@camstack/addon-provider-reolink 1.2.11 → 1.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +2405 -2156
  2. package/dist/addon.mjs +2405 -2156
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -7732,16 +7732,23 @@ var StorageLocationDeclarationSchema = object({
7732
7732
  * Which node root the seeded `<id>:default` instance is placed under on a
7733
7733
  * FRESH install:
7734
7734
  * - `'data'` (default) — the node's data dir (`CAMSTACK_DATA` / boot dir),
7735
- * the appData volume. Right for small/durable data (backups, logs, models).
7735
+ * the appData volume. Right for small/durable data (logs, models).
7736
7736
  * - `'media'` — the dedicated media volume (`CAMSTACK_MEDIA_ROOT`) when that
7737
7737
  * env is set, else falls back to the data root. Right for bulky, hot media
7738
7738
  * (recordings, event media) that should stay off the appData disk.
7739
+ * - `'backup'` — the dedicated backup volume (`CAMSTACK_BACKUP_ROOT`, default
7740
+ * `/backups` in the image) so archives live on their own mount rather than
7741
+ * filling the appData disk. Falls back to the data root when unset.
7739
7742
  *
7740
7743
  * Only affects the seeded default's `basePath`; operators can repoint any
7741
7744
  * location afterwards, and a `defaultsTo` slot inherits its parent's root
7742
7745
  * regardless of this field. Absent (the common case) is treated as `'data'`.
7743
7746
  */
7744
- defaultRoot: _enum(["data", "media"]).optional()
7747
+ defaultRoot: _enum([
7748
+ "data",
7749
+ "media",
7750
+ "backup"
7751
+ ]).optional()
7745
7752
  });
7746
7753
  var DecoderStatsSchema = object({
7747
7754
  inputFps: number(),
@@ -9374,674 +9381,1312 @@ function createRuntimeStateBridge(params) {
9374
9381
  };
9375
9382
  }
9376
9383
  /**
9377
- * Generic device-level status snapshot. Auto-registered by `BaseDevice`
9378
- * for every device, regardless of provider the kernel needs a uniform
9379
- * cap-keyed slice for the basic device flags every consumer expects to
9380
- * read across processes (the `online` flag in particular). Driver-specific
9381
- * caps (`battery`, `doorbell`, …) carry their domain-specific state on
9382
- * their own slices.
9384
+ * Shared geometry vocabulary for on-frame shape caps — privacy-mask,
9385
+ * motion-zones, and the detection zones/lines editor all speak this one
9386
+ * language so a single drawing-plane editor and the providers stay
9387
+ * decoupled from each cap's storage.
9383
9388
  *
9384
- * Pattern is identical to `battery`: schema-bearing `runtimeState`,
9385
- * empty `methods`, single change event. Reads land at
9386
- * `runtimeState.getCapState('device-status')`; writes at
9387
- * `runtimeState.setCapState('device-status', …)`. Cross-process
9388
- * consumers reach the same data via the `device-state` cap router
9389
- * (`getCapSlice({deviceId, capName: 'device-status'})`).
9389
+ * All coordinates are normalized 0..1 of the camera frame (top-left
9390
+ * origin). Each cap composes the SUBSET of shape kinds it supports and
9391
+ * advertises it via `supportedShapes` in its `getOptions`.
9390
9392
  */
9391
- var DeviceStatusSchema = object({
9392
- /**
9393
- * Device-level liveness. Drivers flip via `markOnline(boolean)` on
9394
- * `BaseDevice`. Provider semantics vary — RTSP aggregates broker
9395
- * stream-health, Reolink reads firmware push events, ONVIF tracks
9396
- * ping responses. This cap intentionally does NOT prescribe which
9397
- * signal drives the flag.
9398
- */
9399
- online: boolean(),
9400
- /** Ms epoch of the last `online` transition. Lets consumers tell
9401
- * apart "just came online" from "still online". */
9402
- lastChangedAt: number()
9393
+ /** A normalized 0..1 point (top-left origin). */
9394
+ var MaskPointSchema = object({
9395
+ x: number(),
9396
+ y: number()
9397
+ });
9398
+ /** Axis-aligned rectangle (normalized 0..1). */
9399
+ var MaskRectShapeSchema = object({
9400
+ kind: literal("rect"),
9401
+ x: number(),
9402
+ y: number(),
9403
+ width: number(),
9404
+ height: number()
9405
+ });
9406
+ /** Free polygon — an ordered list of normalized vertices (≥3). */
9407
+ var MaskPolygonShapeSchema = object({
9408
+ kind: literal("polygon"),
9409
+ points: array(MaskPointSchema)
9410
+ });
9411
+ /** Boolean cell grid — row-major, length === gridWidth*gridHeight. */
9412
+ var MaskGridShapeSchema = object({
9413
+ kind: literal("grid"),
9414
+ gridWidth: number(),
9415
+ gridHeight: number(),
9416
+ cells: array(boolean())
9417
+ });
9418
+ discriminatedUnion("kind", [
9419
+ MaskRectShapeSchema,
9420
+ MaskPolygonShapeSchema,
9421
+ MaskGridShapeSchema,
9422
+ object({
9423
+ kind: literal("line"),
9424
+ points: array(MaskPointSchema)
9425
+ })
9426
+ ]);
9427
+ /** Every shape-kind discriminant, for `supportedShapes` advertisement. */
9428
+ var MaskShapeKindSchema = _enum([
9429
+ "rect",
9430
+ "polygon",
9431
+ "grid",
9432
+ "line"
9433
+ ]);
9434
+ /** Polygon vertex bounds when a cap supports 'polygon' (e.g. Hikvision {min:4,max:4}). */
9435
+ var MaskPolygonVerticesSchema = object({
9436
+ min: number(),
9437
+ max: number()
9438
+ });
9439
+ /** Grid dimensions when a cap supports 'grid'. */
9440
+ var MaskGridDimsSchema = object({
9441
+ width: number(),
9442
+ height: number()
9403
9443
  });
9404
- var deviceStatusCapability = {
9405
- name: "device-status",
9406
- scope: "device",
9407
- deviceNative: true,
9408
- mode: "singleton",
9409
- methods: {},
9410
- events: {
9411
- /** Emitted when `online` transitions. Mirrors the semantics of
9412
- * `battery.onStatusChanged`. */
9413
- onStatusChanged: { data: object({
9414
- deviceId: number(),
9415
- status: DeviceStatusSchema
9416
- }) } },
9417
- status: {
9418
- schema: DeviceStatusSchema,
9419
- kind: "push"
9420
- },
9421
- runtimeState: DeviceStatusSchema
9422
- };
9423
9444
  /**
9424
- * Per-device feature/identity probe slice. Holds the runtime-resolved
9425
- * truth about what a device CAN do — which the kernel uses to:
9426
- * 1. Reconcile accessory children (hub-children spawn siren/floodlight/PIR
9427
- * based on what the firmware actually advertises).
9428
- * 2. Compute the public `features: DeviceFeature[]` array surfaced via
9429
- * `device-manager.listAll`.
9430
- * 3. Decide which optional caps (PTZ, intercom, doorbell, battery, …)
9431
- * to register on the device's capability surface.
9445
+ * notification-rules the Notification Center rule surface (P1 core).
9432
9446
  *
9433
- * Auto-registered by `BaseDevice` for every device. Drivers populate the
9434
- * slice from `onProbe()` (kernel calls it once after register, before
9435
- * accessory reconciliation). Consumers read via:
9436
- * `runtimeState.getCapState<FeatureProbeStatus>('feature-probe')`
9447
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
9448
+ * (operator decisions D-1/D-2/D-3 are binding):
9437
9449
  *
9438
- * `flags` is an open record so each driver carries its own keys without
9439
- * a centralized schema bottleneck Reolink writes `hasPtz/hasIntercom`,
9440
- * Hikvision writes `hasSupplementalLight/hasAlarmIo`, etc.
9450
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
9451
+ * `notification-center` module), hooked on the durable persistence
9452
+ * moments (object-event insert, TrackCloser.closeExpired) with a
9453
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
9454
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
9455
+ * FIRST persisted detection matching the conditions (per-track dedup,
9456
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
9457
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
9458
+ * - DISPATCH stays behind `notification-output` (rules reference targets
9459
+ * by id; per-backend params are a passthrough blob capped by the
9460
+ * target kind's own caps/degrade engine).
9441
9461
  *
9442
- * Replaces the older driver-local `deviceCache.has*` blob: the per-device
9443
- * config is for operator-edited overrides + UI snapshots; runtime probe
9444
- * results belong in runtime-state where the kernel handles persistence,
9445
- * cross-process mirroring, and reactive updates.
9462
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
9463
+ * server-injected caller identity the first `caller: 'required'`
9464
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
9465
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
9466
+ * windows, and the optional label/identity/plate matchers. User rules,
9467
+ * private zones, per-recipient fan-out and the wider condition table are
9468
+ * P2+ (see spec §7).
9469
+ *
9470
+ * All schemas here are the single source of truth — `NcRule` etc. are
9471
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
9472
+ * schema/interface drift is explicitly not repeated).
9446
9473
  */
9447
- var FeatureProbeStatusSchema = object({
9474
+ /**
9475
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
9476
+ * The value maps 1:1 onto the evaluated record kind:
9477
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
9478
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
9479
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
9480
+ * change of a LINKED device, one row per linked camera)
9481
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
9482
+ * delivery / pick-up)
9483
+ *
9484
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
9485
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
9486
+ * this one field keeps the schema additive — a rule still declares exactly
9487
+ * one trigger.
9488
+ */
9489
+ var NcDeliverySchema = _enum([
9490
+ "immediate",
9491
+ "track-end",
9492
+ "device-event",
9493
+ "package-event"
9494
+ ]);
9495
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
9496
+ var NcScheduleSchema = object({
9497
+ windows: array(object({
9498
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
9499
+ days: array(number().int().min(0).max(6)).min(1),
9500
+ startMinute: number().int().min(0).max(1439),
9501
+ endMinute: number().int().min(0).max(1439)
9502
+ })).min(1),
9503
+ /** IANA timezone; default = hub host timezone. */
9504
+ timezone: string().optional(),
9505
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
9506
+ invert: boolean().optional()
9507
+ });
9508
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
9509
+ var NcPlateMatcherSchema = object({
9510
+ values: array(string().min(1)).min(1),
9511
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
9512
+ maxDistance: number().int().min(0).max(3).default(1)
9513
+ });
9514
+ /**
9515
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
9516
+ * occupancy edge for a device — optionally narrowed to a single admin
9517
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
9518
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
9519
+ * - `became-free` — count crossed ≥ `count` → below it
9520
+ * - `>=` / `<=` — count is at/over or at/under `count`
9521
+ * `sustainSeconds` requires the condition hold continuously that long
9522
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
9523
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
9524
+ * the condition never matches. Confirmed edge-state survives addon restarts
9525
+ * (declared SQLite collection, reseeded on boot).
9526
+ */
9527
+ var NcOccupancyConditionSchema = object({
9528
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
9529
+ zoneId: string().optional(),
9530
+ /** Object class to count; absent = any class. */
9531
+ className: string().optional(),
9532
+ op: _enum([
9533
+ "became-occupied",
9534
+ "became-free",
9535
+ ">=",
9536
+ "<="
9537
+ ]).default("became-occupied"),
9538
+ count: number().int().min(0).default(1),
9539
+ sustainSeconds: number().int().min(0).max(3600).default(15)
9540
+ });
9541
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
9542
+ var NcZoneConditionSchema = object({
9543
+ ids: array(string().min(1)).min(1),
9544
+ /** Quantifier over `ids` — at least one / every one visited. */
9545
+ match: _enum(["any", "all"]).default("any")
9546
+ });
9547
+ /**
9548
+ * The P1 condition set — a flat AND of groups; absent group = pass;
9549
+ * membership lists are OR within the list (spec §2.3).
9550
+ */
9551
+ var NcConditionsSchema = object({
9552
+ /** Device scope — absent = all devices. */
9553
+ devices: array(number()).optional(),
9554
+ /** Detector class names (any overlap with the record's class set). */
9555
+ classes: array(string().min(1)).optional(),
9556
+ /** Veto classes — any overlap fails the rule. */
9557
+ classesExclude: array(string().min(1)).optional(),
9558
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
9559
+ minConfidence: number().min(0).max(1).optional(),
9560
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
9561
+ zones: NcZoneConditionSchema.optional(),
9562
+ /** Veto zones — any hit fails the rule. */
9563
+ zonesExclude: array(string().min(1)).optional(),
9448
9564
  /**
9449
- * Driver-specific flag bag. Each driver picks its own key names — the
9450
- * cap deliberately does NOT enforce a closed enum here. Reolink keys:
9451
- * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,
9452
- * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:
9453
- * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.
9565
+ * Exact (case-insensitive) match on the record's collapsed `label`
9566
+ * (identity name / plate text / subclass).
9454
9567
  */
9455
- flags: record(string(), unknown()),
9568
+ labelEquals: array(string().min(1)).optional(),
9456
9569
  /**
9457
- * Coarse driver-classification lets cross-process consumers tell apart
9458
- * cameras / battery-cams / NVRs without re-running the probe. `null`
9459
- * before the first probe completes.
9570
+ * Identity matcher. P1 boundary: matched against the record's collapsed
9571
+ * `label` (the identity display name propagated by the face pipeline) —
9572
+ * identity-ID matching rides in P2 when identity ids reach the record.
9460
9573
  */
9461
- deviceType: string().nullable(),
9462
- /** Camera/firmware model string. `null` when the firmware doesn't expose it. */
9463
- model: string().nullable(),
9464
- /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */
9465
- channelCount: number().nullable(),
9574
+ identities: array(string().min(1)).optional(),
9575
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
9576
+ plates: NcPlateMatcherSchema.optional(),
9466
9577
  /**
9467
- * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe
9468
- * completes drivers' `getAccessoryChildren()` should treat zero as
9469
- * "probe not done yet, return empty" so accessories aren't spawned
9470
- * before the firmware is queried.
9578
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
9579
+ * Same P1 boundary: matched against the record's collapsed `label` (the
9580
+ * identity display name). A record with NO label passes (nothing to
9581
+ * exclude), unlike the include variant which fails on an absent label.
9471
9582
  */
9472
- lastProbedAt: number(),
9583
+ identitiesExclude: array(string().min(1)).optional(),
9473
9584
  /**
9474
- * Framework convention: every runtime-state slice carries this for the
9475
- * createRuntimeStateBridge stale-check helper. We keep it in sync with
9476
- * `lastProbedAt` on every write.
9585
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
9586
+ * TRACK-END only: importance is scored at track close, so it does not exist
9587
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
9588
+ * close the value is threaded via the close-time info (the `Track` clone is
9589
+ * captured before the DB row is updated, so it would otherwise read stale).
9590
+ * Fails when the record carries no importance (never guess quality — the
9591
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
9477
9592
  */
9478
- lastFetchedAt: number()
9593
+ minImportance: number().min(0).max(1).optional(),
9594
+ /**
9595
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
9596
+ * TRACK-END only: an `immediate` / object-event subject has no closed
9597
+ * lifespan, so a dwell condition never matches immediate delivery
9598
+ * (documented choice — the object-event record carries no `firstSeen`,
9599
+ * so dwell cannot be computed from what the subject actually carries).
9600
+ */
9601
+ minDwellSeconds: number().min(0).optional(),
9602
+ /**
9603
+ * Detection provenance filter. `any` (default / absent) matches every
9604
+ * source; otherwise the subject's source must equal it. Legacy records
9605
+ * with no stamped source are treated as `pipeline`. The union spans both
9606
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
9607
+ * tracks carry `sensor`.
9608
+ */
9609
+ source: _enum([
9610
+ "pipeline",
9611
+ "onboard",
9612
+ "sensor",
9613
+ "any"
9614
+ ]).optional(),
9615
+ /**
9616
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
9617
+ * detector `minConfidence` (that gates the object-detection score; this
9618
+ * gates the recognition/OCR match score). Fails when the subject carries
9619
+ * no label-match confidence (never guess). TRACK-END only: the confidence
9620
+ * lives on the recognition result and reaches the subject at track close.
9621
+ *
9622
+ * What it measures precisely (plumbed at track close — the closer threads
9623
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
9624
+ * `importance`): the BEST recognition match confidence observed for the
9625
+ * label the track carries at close — for a face, the peak cosine similarity
9626
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
9627
+ * for a plate, the peak OCR read score of the best-held plate
9628
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
9629
+ * one track the higher of the two is used. A track that ended with no
9630
+ * confident identity/plate match carries no value, so the condition fails
9631
+ * closed for it (an un-recognized subject).
9632
+ */
9633
+ minLabelConfidence: number().min(0).max(1).optional(),
9634
+ /**
9635
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
9636
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
9637
+ * against the token carried on the device-event subject (extracted from the
9638
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
9639
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
9640
+ * eventType, so gate those with {@link sensorKinds} instead.
9641
+ */
9642
+ eventTypeTokens: array(string().min(1)).optional(),
9643
+ /**
9644
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
9645
+ * `contact`, `button`, `device-event`) — matched against the persisted
9646
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
9647
+ */
9648
+ sensorKinds: array(string().min(1)).optional(),
9649
+ /**
9650
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
9651
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
9652
+ * when the subject's phase does not match (a subject always carries a phase
9653
+ * on the package-event trigger).
9654
+ */
9655
+ packagePhase: _enum([
9656
+ "delivered",
9657
+ "picked-up",
9658
+ "both"
9659
+ ]).optional(),
9660
+ /**
9661
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
9662
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
9663
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
9664
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
9665
+ */
9666
+ customZones: array(MaskPolygonShapeSchema).optional(),
9667
+ /**
9668
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
9669
+ * (optionally zone/class-scoped) occupancy count crosses the configured
9670
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
9671
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
9672
+ */
9673
+ occupancy: NcOccupancyConditionSchema.optional()
9674
+ });
9675
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
9676
+ var NcRuleTargetSchema = object({
9677
+ /** `notification-output` Target id. */
9678
+ targetId: string().min(1),
9679
+ /**
9680
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
9681
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
9682
+ * degrade engine drops what the backend can't render.
9683
+ */
9684
+ params: record(string(), unknown()).optional()
9479
9685
  });
9480
- var featureProbeCapability = {
9481
- name: "feature-probe",
9482
- scope: "device",
9483
- deviceNative: true,
9484
- mode: "singleton",
9485
- methods: {},
9486
- events: {
9487
- /** Fires whenever a fresh probe completes (kernel-driven `reprobe()`
9488
- * or driver-initiated re-detect after a state change). */
9489
- onProbeChanged: { data: object({
9490
- deviceId: number(),
9491
- status: FeatureProbeStatusSchema
9492
- }) } },
9493
- status: {
9494
- schema: FeatureProbeStatusSchema,
9495
- kind: "push"
9496
- },
9497
- runtimeState: FeatureProbeStatusSchema
9498
- };
9499
9686
  /**
9500
- * Multi-metric air-quality slice. Covers CO₂, total VOCs, particulate
9501
- * matter at PM2.5 / PM10, and a derived AQI index — all optional so
9502
- * a single-metric source populates only what it observes. Mirrors
9503
- * the HA `sensor` device_class set (`co2`, `volatile_organic_compounds`,
9504
- * `pm25`, `pm10`, `aqi`) collapsed into one cap because a typical
9505
- * air-quality node reports several of these together; modelling them
9506
- * as siblings keeps a single timestamp + one slice subscription.
9687
+ * Media attachment policy (P1 still-image subset).
9688
+ * - `best` the best AVAILABLE subject image at dispatch time (D-3).
9689
+ * - `best-matching` the media that explains WHY the rule fired: a rule
9690
+ * matched on identities attaches the subject's `faceCrop`, one matched on
9691
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
9692
+ * (or when the specific crop is missing) degrades to `best`, then
9693
+ * `keyFrame`, then no attachment never delaying the send. The matched
9694
+ * condition summary is frozen on the outbox row at enqueue (like the rule
9695
+ * name), so the choice never drifts from the record that fired it.
9696
+ * - `keyFrame` — the clean scene frame (no subject box).
9697
+ * - `none` — no attachment.
9507
9698
  */
9508
- var AirQualitySensorStatusSchema = object({
9509
- /** Carbon dioxide concentration in ppm. */
9510
- co2Ppm: number().min(0).optional(),
9511
- /** Total volatile organic compounds in ppb. */
9512
- vocPpb: number().min(0).optional(),
9513
- /** Particulate matter ≤ 2.5 μm in µg/m³. */
9514
- pm25: number().min(0).optional(),
9515
- /** Particulate matter ≤ 10 μm in µg/m³. */
9516
- pm10: number().min(0).optional(),
9517
- /** Composite AQI value (typically 0..500). */
9518
- aqi: number().optional(),
9519
- /** Ms epoch when the slice was last updated. */
9520
- lastFetchedAt: number(),
9521
- /** Live display unit of the single metric this slice carries (e.g. HA
9522
- * `attributes.unit_of_measurement` → 'ppm' / 'ppb' / 'µg/m³'). Each
9523
- * upstream `sensor.*` entity surfaces ONE device_class, so one unit
9524
- * per slice is unambiguous. */
9525
- unit: string().optional(),
9526
- /** Suggested decimal places for numeric display.
9527
- * Populated live from the upstream source when provided (e.g. HA
9528
- * `attributes.suggested_display_precision`). Falls back to
9529
- * auto-formatting when absent. */
9530
- precision: number().int().min(0).max(10).optional()
9699
+ var NcMediaPolicySchema = object({ attach: _enum([
9700
+ "best",
9701
+ "best-matching",
9702
+ "keyFrame",
9703
+ "none"
9704
+ ]).default("best") });
9705
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
9706
+ var NcThrottleSchema = object({
9707
+ cooldownSec: number().int().min(0).max(86400).default(60),
9708
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
9709
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
9710
+ });
9711
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
9712
+ var NcRuleInputSchema = object({
9713
+ name: string().min(1).max(200),
9714
+ enabled: boolean().default(true),
9715
+ delivery: NcDeliverySchema,
9716
+ conditions: NcConditionsSchema.default({}),
9717
+ schedule: NcScheduleSchema.optional(),
9718
+ targets: array(NcRuleTargetSchema).min(1),
9719
+ media: NcMediaPolicySchema.default({ attach: "best" }),
9720
+ throttle: NcThrottleSchema.default({
9721
+ cooldownSec: 60,
9722
+ scope: "rule-device"
9723
+ }),
9724
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
9725
+ template: object({
9726
+ title: string().max(500).optional(),
9727
+ body: string().max(2e3).optional()
9728
+ }).optional(),
9729
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
9730
+ priority: number().int().min(1).max(5).default(3),
9731
+ /**
9732
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
9733
+ * behaviour, visible to all, read-only in the viewer). Present = personal
9734
+ * rule owned by this userId. Server-stamped; never trusted from a client.
9735
+ */
9736
+ ownerUserId: string().optional()
9531
9737
  });
9532
- var airQualitySensorCapability = {
9533
- name: "air-quality-sensor",
9534
- scope: "device",
9535
- deviceNative: true,
9536
- mode: "singleton",
9537
- deviceTypes: [DeviceType.Sensor],
9538
- methods: {},
9539
- status: {
9540
- schema: AirQualitySensorStatusSchema,
9541
- kind: "push"
9542
- },
9543
- runtimeState: AirQualitySensorStatusSchema
9544
- };
9545
9738
  /**
9546
- * Alarm-panel cap. Models HA `alarm_control_panel.*` on
9547
- * `DeviceType.AlarmPanel`. State follows HA's canonical lifecycle
9548
- * across disarmed / armed_(home|away|night|vacation|custom_bypass) /
9549
- * arming / pending / triggered / disarming.
9550
- *
9551
- * Many panels require a PIN code on arm / disarm — the optional
9552
- * `code` field on the methods passes it through to the upstream
9553
- * service; it's NEVER persisted in the runtime slice or any event
9554
- * payload. The presence of a required code is signalled by
9555
- * `DeviceFeature.AlarmPinRequired` so the UI gates a code-entry
9556
- * field without a slice fetch.
9557
- *
9558
- * `availableModes` mirrors HA's `supported_features`-derived arm
9559
- * mode list — the UI renders only the buttons the panel accepts.
9739
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
9740
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
9741
+ * NOT a client-authored input field (it lives on the persisted rule, not the
9742
+ * input), so it is added here explicitly to let the store's per-target opt-out
9743
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
9744
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
9745
+ * `updateRule` patch.
9560
9746
  */
9561
- var AlarmStateSchema = _enum([
9562
- "disarmed",
9563
- "armed_home",
9564
- "armed_away",
9565
- "armed_night",
9566
- "armed_vacation",
9567
- "armed_custom_bypass",
9568
- "arming",
9569
- "disarming",
9570
- "pending",
9571
- "triggered"
9572
- ]);
9573
- var AlarmArmModeSchema = _enum([
9574
- "home",
9575
- "away",
9576
- "night",
9577
- "vacation",
9578
- "custom_bypass"
9579
- ]);
9580
- var AlarmPanelStatusSchema = object({
9581
- /** Current lifecycle state. */
9582
- state: AlarmStateSchema,
9583
- /** Subset of arm modes the panel accepts. UI renders one button per
9584
- * mode in this list. */
9585
- availableModes: array(AlarmArmModeSchema),
9586
- /** Whether the panel requires a PIN on arm / disarm. Mirrors
9587
- * `DeviceFeature.AlarmPinRequired` for slice consumers. */
9588
- requiresCode: boolean(),
9589
- /** Ms epoch when the slice was last updated. */
9590
- lastChangedAt: number()
9591
- });
9592
- var alarmPanelCapability = {
9593
- name: "alarm-panel",
9594
- scope: "device",
9595
- deviceNative: true,
9596
- mode: "singleton",
9597
- deviceTypes: [DeviceType.AlarmPanel],
9598
- methods: {
9599
- arm: method(object({
9600
- deviceId: number().int().nonnegative(),
9601
- mode: AlarmArmModeSchema,
9602
- /** Optional PIN code. Required when `requiresCode === true`.
9603
- * Passed through to the upstream service; never persisted. */
9604
- code: string().min(1).optional()
9605
- }), _void(), {
9606
- kind: "mutation",
9607
- auth: "admin"
9608
- }),
9609
- disarm: method(object({
9610
- deviceId: number().int().nonnegative(),
9611
- code: string().min(1).optional()
9612
- }), _void(), {
9613
- kind: "mutation",
9614
- auth: "admin"
9615
- }),
9616
- /**
9617
- * Force the panel into the `triggered` state — used by HA
9618
- * automations to surface external sensor events through the panel
9619
- * (e.g. a Reolink camera intrusion event firing the security
9620
- * system). Provider rejects when the panel hardware doesn't
9621
- * support a software-initiated trigger.
9622
- */
9623
- trigger: method(object({ deviceId: number().int().nonnegative() }), _void(), {
9624
- kind: "mutation",
9625
- auth: "admin"
9626
- })
9627
- },
9628
- status: {
9629
- schema: AlarmPanelStatusSchema,
9630
- kind: "push"
9631
- },
9747
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
9748
+ /** A persisted rule. */
9749
+ var NcRuleSchema = NcRuleInputSchema.extend({
9750
+ id: string(),
9751
+ /** userId of the admin who created the rule (server-stamped caller). */
9752
+ createdBy: string(),
9753
+ createdAt: number(),
9754
+ updatedAt: number(),
9632
9755
  /**
9633
- * Runtime-state slice mirrored by the kernel. UI panel reads the
9634
- * full slice; renders an arm button per `availableModes` entry and
9635
- * a PIN field iff `requiresCode === true`.
9756
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
9757
+ * send time. Only a target's OWNER may add/remove its id (server-checked
9758
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
9636
9759
  */
9637
- runtimeState: AlarmPanelStatusSchema
9638
- };
9639
- /**
9640
- * Ambient illuminance reading in lux. Drives Home Assistant `sensor`
9641
- * entries with `device_class: illuminance`.
9642
- */
9643
- var AmbientLightSensorStatusSchema = object({
9644
- /** Current illuminance in lux (lx). */
9645
- lux: number().min(0),
9646
- /** Ms epoch when the slice was last updated. */
9647
- lastFetchedAt: number(),
9648
- /** Live display unit from the upstream source (e.g. HA
9649
- * `attributes.unit_of_measurement`). The UI prefers this over the
9650
- * role's canonical unit. Absent → fall back to the canonical unit. */
9651
- unit: string().optional(),
9652
- /** Suggested decimal places for numeric display.
9653
- * Populated live from the upstream source when provided (e.g. HA
9654
- * `attributes.suggested_display_precision`). Falls back to
9655
- * auto-formatting when absent. */
9656
- precision: number().int().min(0).max(10).optional()
9760
+ disabledTargetIds: array(string()).default([])
9657
9761
  });
9658
- var ambientLightSensorCapability = {
9659
- name: "ambient-light-sensor",
9660
- scope: "device",
9661
- deviceNative: true,
9662
- mode: "singleton",
9663
- deviceTypes: [DeviceType.Sensor],
9664
- methods: {},
9665
- status: {
9666
- schema: AmbientLightSensorStatusSchema,
9667
- kind: "push"
9668
- },
9669
- runtimeState: AmbientLightSensorStatusSchema
9670
- };
9671
- /**
9672
- * Per-class audio metrics aggregated over a sliding window.
9673
- */
9674
- var AudioClassSummarySchema = object({
9675
- className: string(),
9676
- /** Number of windows (chunks) where this class was the top hit. */
9677
- hits: number().int().nonnegative(),
9678
- /** Mean score across those hits, clamped to [0,1]. */
9679
- avgScore: number().min(0).max(1),
9680
- /** Peak score in the window. */
9681
- peakScore: number().min(0).max(1)
9762
+ var NcTestResultSchema = object({
9763
+ recordId: string(),
9764
+ recordKind: _enum([
9765
+ "object-event",
9766
+ "track",
9767
+ "device-event",
9768
+ "package-event"
9769
+ ]),
9770
+ deviceId: number(),
9771
+ timestamp: number(),
9772
+ wouldFire: boolean(),
9773
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
9774
+ failedCondition: string().optional(),
9775
+ className: string().optional(),
9776
+ label: string().optional()
9777
+ });
9778
+ var NcConditionDescriptorSchema = object({
9779
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
9780
+ id: string(),
9781
+ group: _enum([
9782
+ "scope",
9783
+ "class",
9784
+ "zones",
9785
+ "quality",
9786
+ "label",
9787
+ "schedule",
9788
+ "device",
9789
+ "package",
9790
+ "occupancy"
9791
+ ]),
9792
+ label: string(),
9793
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
9794
+ valueType: _enum([
9795
+ "deviceIdList",
9796
+ "stringList",
9797
+ "number01",
9798
+ "number",
9799
+ "sourceSelect",
9800
+ "zoneSelection",
9801
+ "zoneIdList",
9802
+ "schedule",
9803
+ "plateMatcher",
9804
+ "packagePhase",
9805
+ "polygonDraw",
9806
+ "occupancy"
9807
+ ]),
9808
+ operator: _enum([
9809
+ "in",
9810
+ "notIn",
9811
+ "anyOf",
9812
+ "allOf",
9813
+ "gte",
9814
+ "fuzzyIn",
9815
+ "withinSchedule"
9816
+ ]),
9817
+ /** Which delivery kinds the condition applies to. */
9818
+ appliesTo: array(NcDeliverySchema),
9819
+ phase: string(),
9820
+ description: string().optional()
9682
9821
  });
9683
9822
  /**
9684
- * Per-camera audio metrics snapshotemitted by the analytics frame
9685
- * handler on every `pipeline.audio-inference-result` event and
9686
- * mirrored into the `audio-metrics` device-state slice. Symmetric
9687
- * with `zone-analytics` snapshots for video every consumer
9688
- * (admin UI panel, automations, alert rules) reads via the
9689
- * canonical `device.state.audioMetrics.value` reactive handle.
9823
+ * The delivery lifecycle status of a history row a straight read of the
9824
+ * durable outbox row's own status (single source of truth):
9825
+ * - `pending` enqueued, in-flight or retrying with backoff
9826
+ * - `sent` delivered (terminal)
9827
+ * - `dead` — dead-lettered after exhausting retries / a permanent
9828
+ * backend rejection / a deleted target (terminal; carries
9829
+ * the failure `error`)
9690
9830
  *
9691
- * Aggregates are computed over a rolling `windowSec` window
9692
- * (default 60s). Past that window, classes drop out of `byClass`
9693
- * and the level history shifts forward.
9831
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
9832
+ * user dimension (quiet hours / snooze) and are additive when they land.
9694
9833
  */
9695
- var AudioMetricsSnapshotSchema = object({
9696
- /** Wall-clock timestamp (ms) of the most recent audio window. */
9697
- ts: number().int(),
9698
- /** Sliding-window length (seconds) used for aggregation. */
9699
- windowSec: number().int().positive(),
9700
- /** Latest level reading from the most recent window. */
9701
- level: object({
9702
- rms: number(),
9703
- dbfs: number()
9704
- }),
9705
- /** Peak dBFS observed across the rolling window. */
9706
- peakDbfs: number(),
9707
- /** Mean dBFS across the rolling window. */
9708
- avgDbfs: number(),
9709
- /** Most recent above-threshold classification, or null on silence. */
9710
- current: object({
9711
- className: string(),
9712
- score: number().min(0).max(1),
9713
- timestamp: number().int()
9714
- }).nullable(),
9715
- /** Per-class summary across the rolling window — keys are
9716
- * `macroClass` strings (e.g. `dog_bark`, `speech`, `glass_break`). */
9717
- byClass: array(AudioClassSummarySchema).readonly()
9834
+ var NcHistoryStatusSchema = _enum([
9835
+ "pending",
9836
+ "sent",
9837
+ "dead"
9838
+ ]);
9839
+ /** The evaluated record kind a history row descends from (one per trigger). */
9840
+ var NcHistoryRecordKindSchema = _enum([
9841
+ "object-event",
9842
+ "track-end",
9843
+ "device-event",
9844
+ "package-event"
9845
+ ]);
9846
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
9847
+ var NcHistorySubjectSchema = object({
9848
+ className: string(),
9849
+ label: string().optional(),
9850
+ confidence: number().optional(),
9851
+ zones: array(string()),
9852
+ timestamp: number()
9718
9853
  });
9719
9854
  /**
9720
- * Audio-metrics history payload a series of `AudioMetricsHistoryPoint`
9721
- * samples capped at `maxPoints` (default 1024). When the requested
9722
- * `windowSec / sampleEveryMs` would exceed the cap, the provider
9723
- * subsamples by bucketed averaging and reports the effective sample
9724
- * spacing on `effectiveSampleEveryMs` so the UI can label the x-axis.
9855
+ * One delivery-history row. This is a read-only VIEW over the durable
9856
+ * outbox row (single source of truth the same row the drain loop drives;
9857
+ * NO second write path, so history can never drift from delivery state).
9858
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
9859
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
9860
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
9861
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
9862
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
9863
+ * P1 (admin scope only).
9725
9864
  */
9726
- var AudioMetricsHistorySchema = object({
9727
- points: array(object({
9728
- /** Wall-clock ms when this sample was recorded. */
9729
- ts: number().int(),
9730
- /** Instantaneous dBFS level at sample time. `null` for windows where
9731
- * the source had no level reading (rare; happens at decode startup). */
9732
- dbfs: number().nullable(),
9733
- /** Rolling-window peak dBFS at sample time. Same window the live
9734
- * snapshot reports. */
9735
- peakDbfs: number(),
9736
- /** Rolling-window mean dBFS at sample time. */
9737
- avgDbfs: number(),
9738
- /** Dominant above-threshold class at sample time, or null on silence. */
9739
- topClass: string().nullable(),
9740
- /** Score of the dominant class (`null` whenever `topClass` is null). */
9741
- topScore: number().min(0).max(1).nullable()
9742
- })).readonly(),
9743
- /** Actual ms between adjacent samples after any subsampling. */
9744
- effectiveSampleEveryMs: number().int().positive(),
9745
- /** Wall-clock window covered by `points` (`points[N-1].ts - points[0].ts`),
9746
- * or `0` when there's fewer than 2 samples. */
9747
- windowMsActual: number().int().nonnegative()
9865
+ var NcHistoryEntrySchema = object({
9866
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
9867
+ id: string(),
9868
+ ruleId: string(),
9869
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
9870
+ ruleName: string(),
9871
+ /** The rule urgency/trigger that produced this delivery. */
9872
+ delivery: NcDeliverySchema,
9873
+ targetId: string(),
9874
+ deviceId: number(),
9875
+ recordKind: NcHistoryRecordKindSchema,
9876
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
9877
+ recordId: string(),
9878
+ /** Present for track-scoped deliveries (object-event / track-end). */
9879
+ trackId: string().optional(),
9880
+ status: NcHistoryStatusSchema,
9881
+ /** Delivery attempts made so far. */
9882
+ attempts: number().int(),
9883
+ /** Fire time (outbox enqueue). */
9884
+ createdAt: number(),
9885
+ /** Last transition time (terminal for sent / dead). */
9886
+ updatedAt: number(),
9887
+ /** Failure detail — present on a `dead` row. */
9888
+ error: string().optional(),
9889
+ subject: NcHistorySubjectSchema
9748
9890
  });
9749
9891
  /**
9750
- * Audio Metrics capability sliding-window aggregates over the
9751
- * pipeline audio inference results. Hosted by `addon-pipeline-analytics`
9752
- * (same addon that owns `zone-analytics`); the runtime-state slice
9753
- * gives operators a live read on dB level + dominant classes without
9754
- * a custom event subscription.
9892
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
9893
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
9894
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
9895
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
9755
9896
  */
9756
- var audioMetricsCapability = {
9757
- name: "audio-metrics",
9758
- scope: "device",
9759
- mode: "singleton",
9760
- deviceTypes: [DeviceType.Camera],
9761
- methods: {
9762
- /** Latest snapshot for this device. Null until the analytics
9763
- * pipeline has processed at least one audio window. */
9764
- getCurrentSnapshot: method(object({ deviceId: number() }), AudioMetricsSnapshotSchema.nullable()),
9765
- /**
9766
- * Time-series view of recent audio-metrics samples. The provider
9767
- * keeps an in-memory ring of ~1Hz samples (matching the slice-
9768
- * write rate) capped at `MAX_HISTORY_POINTS_KEPT` (provider-side).
9769
- * `windowSec` selects how far back to read; `sampleEveryMs`
9770
- * downsamples by bucketed averaging when finer than the kept
9771
- * granularity. Empty `points` array on freshly-booted providers
9772
- * with no audio yet — same convention as `getCurrentSnapshot`.
9773
- */
9774
- getHistory: method(object({
9775
- deviceId: number(),
9776
- /** History window in seconds. Default 300 (5 minutes).
9777
- * Provider clamps to its retention cap if larger. */
9778
- windowSec: number().int().positive().optional(),
9779
- /** Target sample interval in ms. Default 1000 (1 sample/second).
9780
- * Provider clamps to natural sample rate if smaller, and
9781
- * bucket-averages when bigger than the requested window
9782
- * would produce more than `maxPoints` samples. */
9783
- sampleEveryMs: number().int().positive().optional()
9784
- }), AudioMetricsHistorySchema)
9785
- },
9786
- /** Reactive runtime-state mirror — live `device.state.audioMetrics.value`. */
9787
- runtimeState: AudioMetricsSnapshotSchema
9788
- };
9897
+ var NcHistoryFilterSchema = object({
9898
+ ruleId: string().optional(),
9899
+ deviceId: number().optional(),
9900
+ status: NcHistoryStatusSchema.optional(),
9901
+ since: number().optional(),
9902
+ until: number().optional(),
9903
+ limit: number().int().min(1).max(500).default(100)
9904
+ });
9905
+ method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), method(object({ ruleId: string() }), object({ rule: NcRuleSchema.nullable() }), { auth: "admin" }), method(object({ rule: NcRuleInputSchema }), object({ rule: NcRuleSchema }), {
9906
+ kind: "mutation",
9907
+ auth: "admin",
9908
+ caller: "required"
9909
+ }), method(object({
9910
+ ruleId: string(),
9911
+ patch: NcRulePatchSchema
9912
+ }), object({ rule: NcRuleSchema }), {
9913
+ kind: "mutation",
9914
+ auth: "admin",
9915
+ caller: "required"
9916
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
9917
+ kind: "mutation",
9918
+ auth: "admin"
9919
+ }), method(object({
9920
+ ruleId: string(),
9921
+ enabled: boolean()
9922
+ }), object({ success: literal(true) }), {
9923
+ kind: "mutation",
9924
+ auth: "admin"
9925
+ }), method(object({
9926
+ rule: NcRuleInputSchema,
9927
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
9928
+ }), object({ results: array(NcTestResultSchema) }), {
9929
+ kind: "mutation",
9930
+ auth: "admin"
9931
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
9789
9932
  /**
9790
- * Automation-control cap. Models HA `automation.*` entities on
9791
- * `DeviceType.Automation`. An automation is a trigger+condition+
9792
- * action rule that can be enabled / disabled and manually fired
9793
- * via the `trigger` method.
9933
+ * TimelapseRule the STANDALONE scheduled timelapse producer's rule model.
9794
9934
  *
9795
- * `trigger` accepts an optional `skipCondition` flag — when true,
9796
- * the automation's action block runs WITHOUT evaluating its
9797
- * condition block. Pair with `DeviceFeature.AutomationSkipCondition`
9798
- * to gate the UI checkbox for the manual-trigger dialog.
9935
+ * Spec: `docs/superpowers/specs/2026-07-24-nc-occupancy-timelapse-design.md`
9936
+ * §3.2/§3.3.
9937
+ *
9938
+ * Deliberately NOT a capability definition and NOT an `NcRule`:
9939
+ * - Every `NcDelivery` member is a *persisted-pipeline-record* trigger. A
9940
+ * timelapse fires on a SCHEDULE WINDOW BOUNDARY, evaluates no pipeline
9941
+ * record, and produces a video it assembled itself — so it rides no
9942
+ * delivery-enum member (the enum is frozen) and no cap method. This file is
9943
+ * a plain typed schema; it does NOT go through `npm run codegen`.
9944
+ * - It shares only the delivery leg (`notification-output.send`) and the
9945
+ * persistence/ownership patterns with the Notification Center, reusing
9946
+ * {@link NcScheduleSchema} (weekly windows, midnight-crossing, invertible)
9947
+ * and {@link NcRuleTargetSchema} (target ref + passthrough params).
9948
+ *
9949
+ * Ownership is SERVER-DERIVED. `ownerUserId` / `createdBy` / `createdAt` /
9950
+ * `updatedAt` / `id` / `lastGeneratedAt` live on the PERSISTED rule only —
9951
+ * {@link TimelapseRuleInputSchema} and {@link TimelapseRulePatchSchema} do not
9952
+ * carry them, so a forged client payload can never claim or re-own a rule
9953
+ * (Zod strips unknown keys). The store stamps them from the resolved caller.
9799
9954
  */
9800
- var AutomationControlStatusSchema = object({
9801
- /** Whether the automation is currently enabled. Disabled automations
9802
- * ignore their trigger block — manual `trigger` still works. */
9803
- enabled: boolean(),
9804
- /** Whether the automation is currently executing its action block. */
9805
- isRunning: boolean(),
9806
- /** Ms epoch of the last successful run. 0 when never run. */
9807
- lastTriggeredAt: number(),
9808
- /** Failure description from the last completed run. Null on success
9809
- * or when never run. */
9810
- lastError: string().nullable(),
9811
- /** Ms epoch when the slice was last updated. */
9812
- lastChangedAt: number()
9813
- });
9814
- var automationControlCapability = {
9815
- name: "automation-control",
9816
- scope: "device",
9817
- deviceNative: true,
9818
- mode: "singleton",
9819
- deviceTypes: [DeviceType.Automation],
9820
- methods: {
9821
- enable: method(object({ deviceId: number().int().nonnegative() }), _void(), {
9822
- kind: "mutation",
9823
- auth: "admin"
9824
- }),
9825
- disable: method(object({ deviceId: number().int().nonnegative() }), _void(), {
9826
- kind: "mutation",
9827
- auth: "admin"
9828
- }),
9829
- trigger: method(object({
9830
- deviceId: number().int().nonnegative(),
9831
- /** When true, fires the action block while bypassing the
9832
- * automation's condition evaluation. Gated by
9833
- * `DeviceFeature.AutomationSkipCondition`. */
9834
- skipCondition: boolean().optional()
9835
- }), _void(), {
9836
- kind: "mutation",
9837
- auth: "admin"
9838
- })
9839
- },
9840
- status: {
9841
- schema: AutomationControlStatusSchema,
9842
- kind: "push"
9843
- },
9844
- /**
9845
- * Runtime-state slice — mirrored by the kernel. UI automation tile
9846
- * reads `enabled` (toggle) + `isRunning` (spinner) + `lastError`
9847
- * (badge) directly.
9848
- */
9849
- runtimeState: AutomationControlStatusSchema
9850
- };
9955
+ /** `{{var}}` templating over camera/rule/time — same vocabulary as `NcRule`. */
9956
+ var TimelapseTemplateSchema = object({
9957
+ title: string().max(500).optional(),
9958
+ body: string().max(2e3).optional()
9959
+ });
9960
+ var NameField = string().min(1).max(200);
9961
+ var DeviceIdsField = array(number()).min(1);
9962
+ var CadenceSecField = number().int().min(2).max(3600);
9963
+ var FramerateField = number().int().min(1).max(60);
9964
+ var TargetsField = array(NcRuleTargetSchema).min(1);
9965
+ var PriorityField = number().int().min(1).max(5);
9851
9966
  /**
9852
- * Battery status snapshot. Emitted by providers whose device is
9853
- * battery-operated (cameras with `DeviceFeature.BatteryOperated`,
9854
- * future sensor/button accessories). Consumers build their own "low
9855
- * battery" alerting on top — the cap deliberately does NOT enforce a
9856
- * threshold.
9967
+ * Client-supplied timelapse-rule fields. The server stamps id / createdBy /
9968
+ * createdAt / updatedAt / ownerUserId / lastGeneratedAt — none of them appear
9969
+ * here (see the ownership note above).
9857
9970
  */
9858
- var BatteryStatusSchema = object({
9859
- /** 0..100 inclusive. Firmware-reported. */
9860
- percentage: number().min(0).max(100),
9971
+ var TimelapseRuleInputSchema = object({
9972
+ name: NameField,
9973
+ enabled: boolean().default(true),
9974
+ /** Cameras sampled by this rule — one scratch dir + one artifact per device. */
9975
+ deviceIds: DeviceIdsField,
9976
+ /**
9977
+ * Activation window(s). REQUIRED (unlike `NcRule`, where an absent schedule
9978
+ * means "always active"): a timelapse is defined by its window boundaries —
9979
+ * open clears the scratch, close assembles and delivers.
9980
+ */
9981
+ schedule: NcScheduleSchema,
9982
+ /** Force-snapshot cadence inside the window, seconds (predecessor parity). */
9983
+ cadenceSec: CadenceSecField.default(15),
9984
+ /** Output frames per second of the assembled mp4 (predecessor parity). */
9985
+ framerate: FramerateField.default(10),
9986
+ /** `notification-output` targets the finished video/thumbnail is sent to. */
9987
+ targets: TargetsField,
9988
+ template: TimelapseTemplateSchema.optional(),
9989
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
9990
+ priority: PriorityField.default(3)
9991
+ });
9992
+ object({
9993
+ name: NameField.optional(),
9994
+ enabled: boolean().optional(),
9995
+ deviceIds: DeviceIdsField.optional(),
9996
+ schedule: NcScheduleSchema.optional(),
9997
+ cadenceSec: CadenceSecField.optional(),
9998
+ framerate: FramerateField.optional(),
9999
+ targets: TargetsField.optional(),
10000
+ template: TimelapseTemplateSchema.nullable().optional(),
10001
+ priority: PriorityField.optional()
10002
+ });
10003
+ TimelapseRuleInputSchema.extend({
10004
+ id: string(),
9861
10005
  /**
9862
- * Charging source. `'dc'` covers wall/USB adapters; `'solar'` is
9863
- * Reolink-specific for the Solar Panel 2 accessory (will become
9864
- * common on other battery cams). `'none'` means running on battery
9865
- * alone.
10006
+ * Ownership/visibility key. Absent = admin/global rule (visible to all).
10007
+ * Present = personal rule owned by this userId. Server-stamped from the
10008
+ * resolved caller; never trusted from a client payload.
9866
10009
  */
9867
- charging: _enum([
9868
- "dc",
9869
- "solar",
9870
- "none"
9871
- ]),
10010
+ ownerUserId: string().optional(),
9872
10011
  /**
9873
- * True when the camera firmware has gone into low-power mode. Battery
9874
- * providers MUST avoid polling during sleep reading the battery
9875
- * wakes the camera up and drains charge.
10012
+ * Epoch-ms of the last successful generation the 1-hour re-generation
10013
+ * guard's durable state (predecessor parity). Absent = never generated.
9876
10014
  */
9877
- sleeping: boolean(),
9878
- /** Ms epoch of the last observation. Lets consumers reason about freshness. */
9879
- lastUpdated: number(),
10015
+ lastGeneratedAt: number().optional(),
10016
+ /** userId of the caller who created the rule (server-stamped). */
10017
+ createdBy: string(),
10018
+ createdAt: number(),
10019
+ updatedAt: number()
10020
+ });
10021
+ /**
10022
+ * Generic device-level status snapshot. Auto-registered by `BaseDevice`
10023
+ * for every device, regardless of provider — the kernel needs a uniform
10024
+ * cap-keyed slice for the basic device flags every consumer expects to
10025
+ * read across processes (the `online` flag in particular). Driver-specific
10026
+ * caps (`battery`, `doorbell`, …) carry their domain-specific state on
10027
+ * their own slices.
10028
+ *
10029
+ * Pattern is identical to `battery`: schema-bearing `runtimeState`,
10030
+ * empty `methods`, single change event. Reads land at
10031
+ * `runtimeState.getCapState('device-status')`; writes at
10032
+ * `runtimeState.setCapState('device-status', …)`. Cross-process
10033
+ * consumers reach the same data via the `device-state` cap router
10034
+ * (`getCapSlice({deviceId, capName: 'device-status'})`).
10035
+ */
10036
+ var DeviceStatusSchema = object({
9880
10037
  /**
9881
- * True when the source is a BINARY low-battery indicator (HA
9882
- * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
9883
- * charge level `percentage` is then a coarse stand-in (100 = normal,
9884
- * sub-threshold = low). UI MUST render "Normal"/"Low" instead of a
9885
- * misleading exact percentage. Absent/false → genuine 0–100 % reading.
10038
+ * Device-level liveness. Drivers flip via `markOnline(boolean)` on
10039
+ * `BaseDevice`. Provider semantics vary RTSP aggregates broker
10040
+ * stream-health, Reolink reads firmware push events, ONVIF tracks
10041
+ * ping responses. This cap intentionally does NOT prescribe which
10042
+ * signal drives the flag.
9886
10043
  */
9887
- binary: boolean().optional()
10044
+ online: boolean(),
10045
+ /** Ms epoch of the last `online` transition. Lets consumers tell
10046
+ * apart "just came online" from "still online". */
10047
+ lastChangedAt: number()
9888
10048
  });
9889
- var batteryCapability = {
9890
- name: "battery",
10049
+ var deviceStatusCapability = {
10050
+ name: "device-status",
9891
10051
  scope: "device",
9892
10052
  deviceNative: true,
9893
10053
  mode: "singleton",
9894
- deviceTypes: [
9895
- DeviceType.Camera,
9896
- DeviceType.Sensor,
9897
- DeviceType.Button,
9898
- DeviceType.Switch
9899
- ],
9900
- methods: {
9901
- /**
9902
- * Explicitly wake the camera from low-power sleep ahead of a
9903
- * streaming session start. Consumers that initiate a stream
9904
- * against a sleeping battery cam (HomeKit Secure Video, Alexa
9905
- * RTCSession, snapshot wrappers) call this with a short timeout
9906
- * before establishing the media pipeline — the broker's own
9907
- * passive wake-on-dial works but adds 5–7 seconds to first-frame,
9908
- * during which the consumer renders a black screen. Pre-waking
9909
- * compresses that gap.
9910
- *
9911
- * Returns `awoke: true` when the firmware acknowledged the wake
9912
- * before `timeoutMs`. Returns `awoke: false` when it timed out OR
9913
- * the cap surface is unavailable (no Baichuan / firmware
9914
- * channel); the caller should still attempt the stream — the
9915
- * passive broker wake remains as fallback.
9916
- */
9917
- wakeForStream: method(object({
9918
- deviceId: number(),
9919
- /** Bound on the wait. Sensible range 3000–10000ms. */
9920
- timeoutMs: number().int().min(500).max(3e4).default(8e3)
9921
- }), object({
9922
- awoke: boolean(),
9923
- durationMs: number()
9924
- }), { kind: "mutation" }) },
10054
+ methods: {},
9925
10055
  events: {
9926
- /**
9927
- * Emitted whenever the cached status changes (firmware push OR
9928
- * poll observes a delta). The DeviceEventPropagator mirrors this
9929
- * event on the parent chain — subscribing to a camera's source
9930
- * receives battery events from child accessories automatically.
9931
- */
10056
+ /** Emitted when `online` transitions. Mirrors the semantics of
10057
+ * `battery.onStatusChanged`. */
9932
10058
  onStatusChanged: { data: object({
9933
10059
  deviceId: number(),
9934
- status: BatteryStatusSchema
10060
+ status: DeviceStatusSchema
9935
10061
  }) } },
9936
10062
  status: {
9937
- schema: BatteryStatusSchema,
9938
- kind: "push",
9939
- empty: {
9940
- percentage: 0,
9941
- charging: "none",
9942
- sleeping: false,
9943
- lastUpdated: 0
9944
- }
10063
+ schema: DeviceStatusSchema,
10064
+ kind: "push"
9945
10065
  },
9946
- /**
9947
- * Runtime-state slice — every provider that registers this cap
9948
- * stores the same shape under `device.runtimeState[battery]`.
9949
- * Cross-provider uniformity: a Reolink Argus, a Frigate sensor
9950
- * proxy, an ONVIF battery cam all read/write the same keys.
9951
- * Consumers (BatteryBadge, snapshot wrapper sleep gate) read once
9952
- * via `device.runtimeState.getCapState('battery')` regardless of
9953
- * the underlying driver.
9954
- */
9955
- runtimeState: BatteryStatusSchema
10066
+ runtimeState: DeviceStatusSchema
9956
10067
  };
9957
10068
  /**
9958
- * Generic boolean sensor last-resort fallback when no domain-
9959
- * specific binary cap fits (Home Assistant `binary_sensor` without a
9960
- * known `device_class`, or a domain we haven't typed yet). Pure
9961
- * pass-through: just the bool + timestamp. Push-driven.
10069
+ * Per-device feature/identity probe slice. Holds the runtime-resolved
10070
+ * truth about what a device CAN do which the kernel uses to:
10071
+ * 1. Reconcile accessory children (hub-children spawn siren/floodlight/PIR
10072
+ * based on what the firmware actually advertises).
10073
+ * 2. Compute the public `features: DeviceFeature[]` array surfaced via
10074
+ * `device-manager.listAll`.
10075
+ * 3. Decide which optional caps (PTZ, intercom, doorbell, battery, …)
10076
+ * to register on the device's capability surface.
9962
10077
  *
9963
- * Prefer the typed alternatives (`contact`, `flood`, `smoke`,
9964
- * `carbon-monoxide`, `gas`, `tamper`, `vibration`, `connectivity`,
9965
- * `motion`) when the semantics match — export adapters render those
9966
- * with the right HomeKit / Alexa display category.
10078
+ * Auto-registered by `BaseDevice` for every device. Drivers populate the
10079
+ * slice from `onProbe()` (kernel calls it once after register, before
10080
+ * accessory reconciliation). Consumers read via:
10081
+ * `runtimeState.getCapState<FeatureProbeStatus>('feature-probe')`
10082
+ *
10083
+ * `flags` is an open record so each driver carries its own keys without
10084
+ * a centralized schema bottleneck — Reolink writes `hasPtz/hasIntercom`,
10085
+ * Hikvision writes `hasSupplementalLight/hasAlarmIo`, etc.
10086
+ *
10087
+ * Replaces the older driver-local `deviceCache.has*` blob: the per-device
10088
+ * config is for operator-edited overrides + UI snapshots; runtime probe
10089
+ * results belong in runtime-state where the kernel handles persistence,
10090
+ * cross-process mirroring, and reactive updates.
9967
10091
  */
9968
- var BinaryStatusSchema = object({
9969
- on: boolean(),
9970
- /** Ms epoch of the last transition. 0 if never observed. */
9971
- lastChangedAt: number()
10092
+ var FeatureProbeStatusSchema = object({
10093
+ /**
10094
+ * Driver-specific flag bag. Each driver picks its own key names — the
10095
+ * cap deliberately does NOT enforce a closed enum here. Reolink keys:
10096
+ * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,
10097
+ * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:
10098
+ * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.
10099
+ */
10100
+ flags: record(string(), unknown()),
10101
+ /**
10102
+ * Coarse driver-classification — lets cross-process consumers tell apart
10103
+ * cameras / battery-cams / NVRs without re-running the probe. `null`
10104
+ * before the first probe completes.
10105
+ */
10106
+ deviceType: string().nullable(),
10107
+ /** Camera/firmware model string. `null` when the firmware doesn't expose it. */
10108
+ model: string().nullable(),
10109
+ /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */
10110
+ channelCount: number().nullable(),
10111
+ /**
10112
+ * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe
10113
+ * completes — drivers' `getAccessoryChildren()` should treat zero as
10114
+ * "probe not done yet, return empty" so accessories aren't spawned
10115
+ * before the firmware is queried.
10116
+ */
10117
+ lastProbedAt: number(),
10118
+ /**
10119
+ * Framework convention: every runtime-state slice carries this for the
10120
+ * createRuntimeStateBridge stale-check helper. We keep it in sync with
10121
+ * `lastProbedAt` on every write.
10122
+ */
10123
+ lastFetchedAt: number()
9972
10124
  });
9973
- var binaryCapability = {
9974
- name: "binary",
10125
+ var featureProbeCapability = {
10126
+ name: "feature-probe",
9975
10127
  scope: "device",
9976
10128
  deviceNative: true,
9977
10129
  mode: "singleton",
9978
- deviceTypes: [DeviceType.Sensor],
9979
10130
  methods: {},
10131
+ events: {
10132
+ /** Fires whenever a fresh probe completes (kernel-driven `reprobe()`
10133
+ * or driver-initiated re-detect after a state change). */
10134
+ onProbeChanged: { data: object({
10135
+ deviceId: number(),
10136
+ status: FeatureProbeStatusSchema
10137
+ }) } },
9980
10138
  status: {
9981
- schema: BinaryStatusSchema,
10139
+ schema: FeatureProbeStatusSchema,
9982
10140
  kind: "push"
9983
10141
  },
9984
- runtimeState: BinaryStatusSchema
10142
+ runtimeState: FeatureProbeStatusSchema
9985
10143
  };
9986
10144
  /**
9987
- * Dimmable-light brightness control. Co-exists with `switch` on the
9988
- * same device the switch toggles on/off, this cap sets the level
9989
- * applied when the light is on. Drivers map their per-vendor dim
9990
- * controls to this single-method surface.
9991
- *
9992
- * The cap is intentionally minimal: a single `setBrightness({deviceId,
9993
- * percentage})` mutation plus the auto-injected `getStatus`. Drivers
9994
- * that expose richer controls (color temperature, scenes, schedules)
9995
- * should surface those via the device's `getSettingsUISchema()`
9996
- * instead of bloating this cap.
10145
+ * Multi-metric air-quality slice. Covers CO₂, total VOCs, particulate
10146
+ * matter at PM2.5 / PM10, and a derived AQI index all optional so
10147
+ * a single-metric source populates only what it observes. Mirrors
10148
+ * the HA `sensor` device_class set (`co2`, `volatile_organic_compounds`,
10149
+ * `pm25`, `pm10`, `aqi`) collapsed into one cap because a typical
10150
+ * air-quality node reports several of these together; modelling them
10151
+ * as siblings keeps a single timestamp + one slice subscription.
9997
10152
  */
9998
- var BrightnessStatusSchema = object({
9999
- /** Current level as 0..100 inclusive. Firmware-reported. */
10000
- percentage: number().min(0).max(100),
10001
- /** Ms epoch of the last operator-driven change. Useful for UI freshness. */
10002
- lastChangedAt: number()
10153
+ var AirQualitySensorStatusSchema = object({
10154
+ /** Carbon dioxide concentration in ppm. */
10155
+ co2Ppm: number().min(0).optional(),
10156
+ /** Total volatile organic compounds in ppb. */
10157
+ vocPpb: number().min(0).optional(),
10158
+ /** Particulate matter ≤ 2.5 μm in µg/m³. */
10159
+ pm25: number().min(0).optional(),
10160
+ /** Particulate matter ≤ 10 μm in µg/m³. */
10161
+ pm10: number().min(0).optional(),
10162
+ /** Composite AQI value (typically 0..500). */
10163
+ aqi: number().optional(),
10164
+ /** Ms epoch when the slice was last updated. */
10165
+ lastFetchedAt: number(),
10166
+ /** Live display unit of the single metric this slice carries (e.g. HA
10167
+ * `attributes.unit_of_measurement` → 'ppm' / 'ppb' / 'µg/m³'). Each
10168
+ * upstream `sensor.*` entity surfaces ONE device_class, so one unit
10169
+ * per slice is unambiguous. */
10170
+ unit: string().optional(),
10171
+ /** Suggested decimal places for numeric display.
10172
+ * Populated live from the upstream source when provided (e.g. HA
10173
+ * `attributes.suggested_display_precision`). Falls back to
10174
+ * auto-formatting when absent. */
10175
+ precision: number().int().min(0).max(10).optional()
10003
10176
  });
10004
- var brightnessCapability = {
10005
- name: "brightness",
10177
+ var airQualitySensorCapability = {
10178
+ name: "air-quality-sensor",
10006
10179
  scope: "device",
10007
10180
  deviceNative: true,
10008
10181
  mode: "singleton",
10009
- deviceTypes: [DeviceType.Light],
10010
- methods: { setBrightness: method(object({
10011
- deviceId: number().int().nonnegative(),
10012
- percentage: number().min(0).max(100)
10013
- }), _void(), {
10014
- kind: "mutation",
10015
- auth: "admin"
10016
- }) },
10017
- events: {
10018
- /**
10019
- * Emitted whenever the brightness changes — operator action OR
10020
- * firmware push. Subscribers (UI sliders, automation engines) react
10021
- * without polling.
10022
- */
10023
- onBrightnessChanged: { data: object({
10024
- deviceId: number(),
10025
- percentage: number().min(0).max(100),
10026
- lastChangedAt: number()
10027
- }) } },
10182
+ deviceTypes: [DeviceType.Sensor],
10183
+ methods: {},
10028
10184
  status: {
10029
- schema: BrightnessStatusSchema,
10030
- kind: "command-driven"
10185
+ schema: AirQualitySensorStatusSchema,
10186
+ kind: "push"
10031
10187
  },
10032
- /**
10033
- * Runtime-state slice — the last applied brightness level, mirrored
10034
- * by the kernel. Read via `device.state.brightness.value` so UI
10035
- * sliders surface the current level without polling the provider.
10036
- */
10037
- runtimeState: BrightnessStatusSchema
10188
+ runtimeState: AirQualitySensorStatusSchema
10038
10189
  };
10039
- /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
10040
- var StreamFormatSchema = _enum([
10041
- "webrtc",
10042
- "hls",
10043
- "mjpeg",
10044
- "rtsp"
10190
+ /**
10191
+ * Alarm-panel cap. Models HA `alarm_control_panel.*` on
10192
+ * `DeviceType.AlarmPanel`. State follows HA's canonical lifecycle
10193
+ * across disarmed / armed_(home|away|night|vacation|custom_bypass) /
10194
+ * arming / pending / triggered / disarming.
10195
+ *
10196
+ * Many panels require a PIN code on arm / disarm — the optional
10197
+ * `code` field on the methods passes it through to the upstream
10198
+ * service; it's NEVER persisted in the runtime slice or any event
10199
+ * payload. The presence of a required code is signalled by
10200
+ * `DeviceFeature.AlarmPinRequired` so the UI gates a code-entry
10201
+ * field without a slice fetch.
10202
+ *
10203
+ * `availableModes` mirrors HA's `supported_features`-derived arm
10204
+ * mode list — the UI renders only the buttons the panel accepts.
10205
+ */
10206
+ var AlarmStateSchema = _enum([
10207
+ "disarmed",
10208
+ "armed_home",
10209
+ "armed_away",
10210
+ "armed_night",
10211
+ "armed_vacation",
10212
+ "armed_custom_bypass",
10213
+ "arming",
10214
+ "disarming",
10215
+ "pending",
10216
+ "triggered"
10217
+ ]);
10218
+ var AlarmArmModeSchema = _enum([
10219
+ "home",
10220
+ "away",
10221
+ "night",
10222
+ "vacation",
10223
+ "custom_bypass"
10224
+ ]);
10225
+ var AlarmPanelStatusSchema = object({
10226
+ /** Current lifecycle state. */
10227
+ state: AlarmStateSchema,
10228
+ /** Subset of arm modes the panel accepts. UI renders one button per
10229
+ * mode in this list. */
10230
+ availableModes: array(AlarmArmModeSchema),
10231
+ /** Whether the panel requires a PIN on arm / disarm. Mirrors
10232
+ * `DeviceFeature.AlarmPinRequired` for slice consumers. */
10233
+ requiresCode: boolean(),
10234
+ /** Ms epoch when the slice was last updated. */
10235
+ lastChangedAt: number()
10236
+ });
10237
+ var alarmPanelCapability = {
10238
+ name: "alarm-panel",
10239
+ scope: "device",
10240
+ deviceNative: true,
10241
+ mode: "singleton",
10242
+ deviceTypes: [DeviceType.AlarmPanel],
10243
+ methods: {
10244
+ arm: method(object({
10245
+ deviceId: number().int().nonnegative(),
10246
+ mode: AlarmArmModeSchema,
10247
+ /** Optional PIN code. Required when `requiresCode === true`.
10248
+ * Passed through to the upstream service; never persisted. */
10249
+ code: string().min(1).optional()
10250
+ }), _void(), {
10251
+ kind: "mutation",
10252
+ auth: "admin"
10253
+ }),
10254
+ disarm: method(object({
10255
+ deviceId: number().int().nonnegative(),
10256
+ code: string().min(1).optional()
10257
+ }), _void(), {
10258
+ kind: "mutation",
10259
+ auth: "admin"
10260
+ }),
10261
+ /**
10262
+ * Force the panel into the `triggered` state — used by HA
10263
+ * automations to surface external sensor events through the panel
10264
+ * (e.g. a Reolink camera intrusion event firing the security
10265
+ * system). Provider rejects when the panel hardware doesn't
10266
+ * support a software-initiated trigger.
10267
+ */
10268
+ trigger: method(object({ deviceId: number().int().nonnegative() }), _void(), {
10269
+ kind: "mutation",
10270
+ auth: "admin"
10271
+ })
10272
+ },
10273
+ status: {
10274
+ schema: AlarmPanelStatusSchema,
10275
+ kind: "push"
10276
+ },
10277
+ /**
10278
+ * Runtime-state slice — mirrored by the kernel. UI panel reads the
10279
+ * full slice; renders an arm button per `availableModes` entry and
10280
+ * a PIN field iff `requiresCode === true`.
10281
+ */
10282
+ runtimeState: AlarmPanelStatusSchema
10283
+ };
10284
+ /**
10285
+ * Ambient illuminance reading in lux. Drives Home Assistant `sensor`
10286
+ * entries with `device_class: illuminance`.
10287
+ */
10288
+ var AmbientLightSensorStatusSchema = object({
10289
+ /** Current illuminance in lux (lx). */
10290
+ lux: number().min(0),
10291
+ /** Ms epoch when the slice was last updated. */
10292
+ lastFetchedAt: number(),
10293
+ /** Live display unit from the upstream source (e.g. HA
10294
+ * `attributes.unit_of_measurement`). The UI prefers this over the
10295
+ * role's canonical unit. Absent → fall back to the canonical unit. */
10296
+ unit: string().optional(),
10297
+ /** Suggested decimal places for numeric display.
10298
+ * Populated live from the upstream source when provided (e.g. HA
10299
+ * `attributes.suggested_display_precision`). Falls back to
10300
+ * auto-formatting when absent. */
10301
+ precision: number().int().min(0).max(10).optional()
10302
+ });
10303
+ var ambientLightSensorCapability = {
10304
+ name: "ambient-light-sensor",
10305
+ scope: "device",
10306
+ deviceNative: true,
10307
+ mode: "singleton",
10308
+ deviceTypes: [DeviceType.Sensor],
10309
+ methods: {},
10310
+ status: {
10311
+ schema: AmbientLightSensorStatusSchema,
10312
+ kind: "push"
10313
+ },
10314
+ runtimeState: AmbientLightSensorStatusSchema
10315
+ };
10316
+ /**
10317
+ * Per-class audio metrics aggregated over a sliding window.
10318
+ */
10319
+ var AudioClassSummarySchema = object({
10320
+ className: string(),
10321
+ /** Number of windows (chunks) where this class was the top hit. */
10322
+ hits: number().int().nonnegative(),
10323
+ /** Mean score across those hits, clamped to [0,1]. */
10324
+ avgScore: number().min(0).max(1),
10325
+ /** Peak score in the window. */
10326
+ peakScore: number().min(0).max(1)
10327
+ });
10328
+ /**
10329
+ * Per-camera audio metrics snapshot — emitted by the analytics frame
10330
+ * handler on every `pipeline.audio-inference-result` event and
10331
+ * mirrored into the `audio-metrics` device-state slice. Symmetric
10332
+ * with `zone-analytics` snapshots for video — every consumer
10333
+ * (admin UI panel, automations, alert rules) reads via the
10334
+ * canonical `device.state.audioMetrics.value` reactive handle.
10335
+ *
10336
+ * Aggregates are computed over a rolling `windowSec` window
10337
+ * (default 60s). Past that window, classes drop out of `byClass`
10338
+ * and the level history shifts forward.
10339
+ */
10340
+ var AudioMetricsSnapshotSchema = object({
10341
+ /** Wall-clock timestamp (ms) of the most recent audio window. */
10342
+ ts: number().int(),
10343
+ /** Sliding-window length (seconds) used for aggregation. */
10344
+ windowSec: number().int().positive(),
10345
+ /** Latest level reading from the most recent window. */
10346
+ level: object({
10347
+ rms: number(),
10348
+ dbfs: number()
10349
+ }),
10350
+ /** Peak dBFS observed across the rolling window. */
10351
+ peakDbfs: number(),
10352
+ /** Mean dBFS across the rolling window. */
10353
+ avgDbfs: number(),
10354
+ /** Most recent above-threshold classification, or null on silence. */
10355
+ current: object({
10356
+ className: string(),
10357
+ score: number().min(0).max(1),
10358
+ timestamp: number().int()
10359
+ }).nullable(),
10360
+ /** Per-class summary across the rolling window — keys are
10361
+ * `macroClass` strings (e.g. `dog_bark`, `speech`, `glass_break`). */
10362
+ byClass: array(AudioClassSummarySchema).readonly()
10363
+ });
10364
+ /**
10365
+ * Audio-metrics history payload — a series of `AudioMetricsHistoryPoint`
10366
+ * samples capped at `maxPoints` (default 1024). When the requested
10367
+ * `windowSec / sampleEveryMs` would exceed the cap, the provider
10368
+ * subsamples by bucketed averaging and reports the effective sample
10369
+ * spacing on `effectiveSampleEveryMs` so the UI can label the x-axis.
10370
+ */
10371
+ var AudioMetricsHistorySchema = object({
10372
+ points: array(object({
10373
+ /** Wall-clock ms when this sample was recorded. */
10374
+ ts: number().int(),
10375
+ /** Instantaneous dBFS level at sample time. `null` for windows where
10376
+ * the source had no level reading (rare; happens at decode startup). */
10377
+ dbfs: number().nullable(),
10378
+ /** Rolling-window peak dBFS at sample time. Same window the live
10379
+ * snapshot reports. */
10380
+ peakDbfs: number(),
10381
+ /** Rolling-window mean dBFS at sample time. */
10382
+ avgDbfs: number(),
10383
+ /** Dominant above-threshold class at sample time, or null on silence. */
10384
+ topClass: string().nullable(),
10385
+ /** Score of the dominant class (`null` whenever `topClass` is null). */
10386
+ topScore: number().min(0).max(1).nullable()
10387
+ })).readonly(),
10388
+ /** Actual ms between adjacent samples after any subsampling. */
10389
+ effectiveSampleEveryMs: number().int().positive(),
10390
+ /** Wall-clock window covered by `points` (`points[N-1].ts - points[0].ts`),
10391
+ * or `0` when there's fewer than 2 samples. */
10392
+ windowMsActual: number().int().nonnegative()
10393
+ });
10394
+ /**
10395
+ * Audio Metrics capability — sliding-window aggregates over the
10396
+ * pipeline audio inference results. Hosted by `addon-pipeline-analytics`
10397
+ * (same addon that owns `zone-analytics`); the runtime-state slice
10398
+ * gives operators a live read on dB level + dominant classes without
10399
+ * a custom event subscription.
10400
+ */
10401
+ var audioMetricsCapability = {
10402
+ name: "audio-metrics",
10403
+ scope: "device",
10404
+ mode: "singleton",
10405
+ deviceTypes: [DeviceType.Camera],
10406
+ methods: {
10407
+ /** Latest snapshot for this device. Null until the analytics
10408
+ * pipeline has processed at least one audio window. */
10409
+ getCurrentSnapshot: method(object({ deviceId: number() }), AudioMetricsSnapshotSchema.nullable()),
10410
+ /**
10411
+ * Time-series view of recent audio-metrics samples. The provider
10412
+ * keeps an in-memory ring of ~1Hz samples (matching the slice-
10413
+ * write rate) capped at `MAX_HISTORY_POINTS_KEPT` (provider-side).
10414
+ * `windowSec` selects how far back to read; `sampleEveryMs`
10415
+ * downsamples by bucketed averaging when finer than the kept
10416
+ * granularity. Empty `points` array on freshly-booted providers
10417
+ * with no audio yet — same convention as `getCurrentSnapshot`.
10418
+ */
10419
+ getHistory: method(object({
10420
+ deviceId: number(),
10421
+ /** History window in seconds. Default 300 (5 minutes).
10422
+ * Provider clamps to its retention cap if larger. */
10423
+ windowSec: number().int().positive().optional(),
10424
+ /** Target sample interval in ms. Default 1000 (1 sample/second).
10425
+ * Provider clamps to natural sample rate if smaller, and
10426
+ * bucket-averages when bigger than the requested window
10427
+ * would produce more than `maxPoints` samples. */
10428
+ sampleEveryMs: number().int().positive().optional()
10429
+ }), AudioMetricsHistorySchema)
10430
+ },
10431
+ /** Reactive runtime-state mirror — live `device.state.audioMetrics.value`. */
10432
+ runtimeState: AudioMetricsSnapshotSchema
10433
+ };
10434
+ /**
10435
+ * Automation-control cap. Models HA `automation.*` entities on
10436
+ * `DeviceType.Automation`. An automation is a trigger+condition+
10437
+ * action rule that can be enabled / disabled and manually fired
10438
+ * via the `trigger` method.
10439
+ *
10440
+ * `trigger` accepts an optional `skipCondition` flag — when true,
10441
+ * the automation's action block runs WITHOUT evaluating its
10442
+ * condition block. Pair with `DeviceFeature.AutomationSkipCondition`
10443
+ * to gate the UI checkbox for the manual-trigger dialog.
10444
+ */
10445
+ var AutomationControlStatusSchema = object({
10446
+ /** Whether the automation is currently enabled. Disabled automations
10447
+ * ignore their trigger block — manual `trigger` still works. */
10448
+ enabled: boolean(),
10449
+ /** Whether the automation is currently executing its action block. */
10450
+ isRunning: boolean(),
10451
+ /** Ms epoch of the last successful run. 0 when never run. */
10452
+ lastTriggeredAt: number(),
10453
+ /** Failure description from the last completed run. Null on success
10454
+ * or when never run. */
10455
+ lastError: string().nullable(),
10456
+ /** Ms epoch when the slice was last updated. */
10457
+ lastChangedAt: number()
10458
+ });
10459
+ var automationControlCapability = {
10460
+ name: "automation-control",
10461
+ scope: "device",
10462
+ deviceNative: true,
10463
+ mode: "singleton",
10464
+ deviceTypes: [DeviceType.Automation],
10465
+ methods: {
10466
+ enable: method(object({ deviceId: number().int().nonnegative() }), _void(), {
10467
+ kind: "mutation",
10468
+ auth: "admin"
10469
+ }),
10470
+ disable: method(object({ deviceId: number().int().nonnegative() }), _void(), {
10471
+ kind: "mutation",
10472
+ auth: "admin"
10473
+ }),
10474
+ trigger: method(object({
10475
+ deviceId: number().int().nonnegative(),
10476
+ /** When true, fires the action block while bypassing the
10477
+ * automation's condition evaluation. Gated by
10478
+ * `DeviceFeature.AutomationSkipCondition`. */
10479
+ skipCondition: boolean().optional()
10480
+ }), _void(), {
10481
+ kind: "mutation",
10482
+ auth: "admin"
10483
+ })
10484
+ },
10485
+ status: {
10486
+ schema: AutomationControlStatusSchema,
10487
+ kind: "push"
10488
+ },
10489
+ /**
10490
+ * Runtime-state slice — mirrored by the kernel. UI automation tile
10491
+ * reads `enabled` (toggle) + `isRunning` (spinner) + `lastError`
10492
+ * (badge) directly.
10493
+ */
10494
+ runtimeState: AutomationControlStatusSchema
10495
+ };
10496
+ /**
10497
+ * Battery status snapshot. Emitted by providers whose device is
10498
+ * battery-operated (cameras with `DeviceFeature.BatteryOperated`,
10499
+ * future sensor/button accessories). Consumers build their own "low
10500
+ * battery" alerting on top — the cap deliberately does NOT enforce a
10501
+ * threshold.
10502
+ */
10503
+ var BatteryStatusSchema = object({
10504
+ /** 0..100 inclusive. Firmware-reported. */
10505
+ percentage: number().min(0).max(100),
10506
+ /**
10507
+ * Charging source. `'dc'` covers wall/USB adapters; `'solar'` is
10508
+ * Reolink-specific for the Solar Panel 2 accessory (will become
10509
+ * common on other battery cams). `'none'` means running on battery
10510
+ * alone.
10511
+ */
10512
+ charging: _enum([
10513
+ "dc",
10514
+ "solar",
10515
+ "none"
10516
+ ]),
10517
+ /**
10518
+ * True when the camera firmware has gone into low-power mode. Battery
10519
+ * providers MUST avoid polling during sleep — reading the battery
10520
+ * wakes the camera up and drains charge.
10521
+ */
10522
+ sleeping: boolean(),
10523
+ /** Ms epoch of the last observation. Lets consumers reason about freshness. */
10524
+ lastUpdated: number(),
10525
+ /**
10526
+ * True when the source is a BINARY low-battery indicator (HA
10527
+ * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
10528
+ * charge level — `percentage` is then a coarse stand-in (100 = normal,
10529
+ * sub-threshold = low). UI MUST render "Normal"/"Low" instead of a
10530
+ * misleading exact percentage. Absent/false → genuine 0–100 % reading.
10531
+ */
10532
+ binary: boolean().optional()
10533
+ });
10534
+ var batteryCapability = {
10535
+ name: "battery",
10536
+ scope: "device",
10537
+ deviceNative: true,
10538
+ mode: "singleton",
10539
+ deviceTypes: [
10540
+ DeviceType.Camera,
10541
+ DeviceType.Sensor,
10542
+ DeviceType.Button,
10543
+ DeviceType.Switch
10544
+ ],
10545
+ methods: {
10546
+ /**
10547
+ * Explicitly wake the camera from low-power sleep ahead of a
10548
+ * streaming session start. Consumers that initiate a stream
10549
+ * against a sleeping battery cam (HomeKit Secure Video, Alexa
10550
+ * RTCSession, snapshot wrappers) call this with a short timeout
10551
+ * before establishing the media pipeline — the broker's own
10552
+ * passive wake-on-dial works but adds 5–7 seconds to first-frame,
10553
+ * during which the consumer renders a black screen. Pre-waking
10554
+ * compresses that gap.
10555
+ *
10556
+ * Returns `awoke: true` when the firmware acknowledged the wake
10557
+ * before `timeoutMs`. Returns `awoke: false` when it timed out OR
10558
+ * the cap surface is unavailable (no Baichuan / firmware
10559
+ * channel); the caller should still attempt the stream — the
10560
+ * passive broker wake remains as fallback.
10561
+ */
10562
+ wakeForStream: method(object({
10563
+ deviceId: number(),
10564
+ /** Bound on the wait. Sensible range 3000–10000ms. */
10565
+ timeoutMs: number().int().min(500).max(3e4).default(8e3)
10566
+ }), object({
10567
+ awoke: boolean(),
10568
+ durationMs: number()
10569
+ }), { kind: "mutation" }) },
10570
+ events: {
10571
+ /**
10572
+ * Emitted whenever the cached status changes (firmware push OR
10573
+ * poll observes a delta). The DeviceEventPropagator mirrors this
10574
+ * event on the parent chain — subscribing to a camera's source
10575
+ * receives battery events from child accessories automatically.
10576
+ */
10577
+ onStatusChanged: { data: object({
10578
+ deviceId: number(),
10579
+ status: BatteryStatusSchema
10580
+ }) } },
10581
+ status: {
10582
+ schema: BatteryStatusSchema,
10583
+ kind: "push",
10584
+ empty: {
10585
+ percentage: 0,
10586
+ charging: "none",
10587
+ sleeping: false,
10588
+ lastUpdated: 0
10589
+ }
10590
+ },
10591
+ /**
10592
+ * Runtime-state slice — every provider that registers this cap
10593
+ * stores the same shape under `device.runtimeState[battery]`.
10594
+ * Cross-provider uniformity: a Reolink Argus, a Frigate sensor
10595
+ * proxy, an ONVIF battery cam all read/write the same keys.
10596
+ * Consumers (BatteryBadge, snapshot wrapper sleep gate) read once
10597
+ * via `device.runtimeState.getCapState('battery')` regardless of
10598
+ * the underlying driver.
10599
+ */
10600
+ runtimeState: BatteryStatusSchema
10601
+ };
10602
+ /**
10603
+ * Generic boolean sensor — last-resort fallback when no domain-
10604
+ * specific binary cap fits (Home Assistant `binary_sensor` without a
10605
+ * known `device_class`, or a domain we haven't typed yet). Pure
10606
+ * pass-through: just the bool + timestamp. Push-driven.
10607
+ *
10608
+ * Prefer the typed alternatives (`contact`, `flood`, `smoke`,
10609
+ * `carbon-monoxide`, `gas`, `tamper`, `vibration`, `connectivity`,
10610
+ * `motion`) when the semantics match — export adapters render those
10611
+ * with the right HomeKit / Alexa display category.
10612
+ */
10613
+ var BinaryStatusSchema = object({
10614
+ on: boolean(),
10615
+ /** Ms epoch of the last transition. 0 if never observed. */
10616
+ lastChangedAt: number()
10617
+ });
10618
+ var binaryCapability = {
10619
+ name: "binary",
10620
+ scope: "device",
10621
+ deviceNative: true,
10622
+ mode: "singleton",
10623
+ deviceTypes: [DeviceType.Sensor],
10624
+ methods: {},
10625
+ status: {
10626
+ schema: BinaryStatusSchema,
10627
+ kind: "push"
10628
+ },
10629
+ runtimeState: BinaryStatusSchema
10630
+ };
10631
+ /**
10632
+ * Dimmable-light brightness control. Co-exists with `switch` on the
10633
+ * same device — the switch toggles on/off, this cap sets the level
10634
+ * applied when the light is on. Drivers map their per-vendor dim
10635
+ * controls to this single-method surface.
10636
+ *
10637
+ * The cap is intentionally minimal: a single `setBrightness({deviceId,
10638
+ * percentage})` mutation plus the auto-injected `getStatus`. Drivers
10639
+ * that expose richer controls (color temperature, scenes, schedules)
10640
+ * should surface those via the device's `getSettingsUISchema()`
10641
+ * instead of bloating this cap.
10642
+ */
10643
+ var BrightnessStatusSchema = object({
10644
+ /** Current level as 0..100 inclusive. Firmware-reported. */
10645
+ percentage: number().min(0).max(100),
10646
+ /** Ms epoch of the last operator-driven change. Useful for UI freshness. */
10647
+ lastChangedAt: number()
10648
+ });
10649
+ var brightnessCapability = {
10650
+ name: "brightness",
10651
+ scope: "device",
10652
+ deviceNative: true,
10653
+ mode: "singleton",
10654
+ deviceTypes: [DeviceType.Light],
10655
+ methods: { setBrightness: method(object({
10656
+ deviceId: number().int().nonnegative(),
10657
+ percentage: number().min(0).max(100)
10658
+ }), _void(), {
10659
+ kind: "mutation",
10660
+ auth: "admin"
10661
+ }) },
10662
+ events: {
10663
+ /**
10664
+ * Emitted whenever the brightness changes — operator action OR
10665
+ * firmware push. Subscribers (UI sliders, automation engines) react
10666
+ * without polling.
10667
+ */
10668
+ onBrightnessChanged: { data: object({
10669
+ deviceId: number(),
10670
+ percentage: number().min(0).max(100),
10671
+ lastChangedAt: number()
10672
+ }) } },
10673
+ status: {
10674
+ schema: BrightnessStatusSchema,
10675
+ kind: "command-driven"
10676
+ },
10677
+ /**
10678
+ * Runtime-state slice — the last applied brightness level, mirrored
10679
+ * by the kernel. Read via `device.state.brightness.value` so UI
10680
+ * sliders surface the current level without polling the provider.
10681
+ */
10682
+ runtimeState: BrightnessStatusSchema
10683
+ };
10684
+ /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
10685
+ var StreamFormatSchema = _enum([
10686
+ "webrtc",
10687
+ "hls",
10688
+ "mjpeg",
10689
+ "rtsp"
10045
10690
  ]);
10046
10691
  var RtspRestreamEntrySchema = object({
10047
10692
  brokerId: string(),
@@ -13487,104 +14132,43 @@ var MotionTriggerStatusSchema = object({
13487
14132
  /**
13488
14133
  * Persistent slice mirrored across restarts. The provider writes here
13489
14134
  * on every successful firmware fetch / setMotionTrigger push; the cap
13490
- * router and admin-ui hero read straight from this snapshot via
13491
- * `device.state.motionTrigger.value` instead of re-issuing a firmware
13492
- * round-trip on every UI mount. `lastFetchedAt` lets the framework
13493
- * helper (`createRuntimeStateBridge`) stale-check before deciding
13494
- * whether to refresh from the camera.
13495
- */
13496
- var MotionTriggerRuntimeStateSchema = MotionTriggerStatusSchema.extend({
13497
- /** Ms epoch of the last successful camera fetch (0 = never). */
13498
- lastFetchedAt: number() });
13499
- var motionTriggerCapability = {
13500
- name: "motion-trigger",
13501
- scope: "device",
13502
- deviceNative: true,
13503
- mode: "singleton",
13504
- deviceTypes: [
13505
- DeviceType.Light,
13506
- DeviceType.Siren,
13507
- DeviceType.Switch
13508
- ],
13509
- methods: { setMotionTrigger: method(object({
13510
- deviceId: number().int().nonnegative(),
13511
- enabled: boolean()
13512
- }), _void(), {
13513
- kind: "mutation",
13514
- auth: "admin"
13515
- }) },
13516
- events: { onMotionTriggerChanged: { data: object({
13517
- deviceId: number(),
13518
- enabled: boolean(),
13519
- lastChangedAt: number()
13520
- }) } },
13521
- status: {
13522
- schema: MotionTriggerStatusSchema,
13523
- kind: "command-driven"
13524
- },
13525
- runtimeState: MotionTriggerRuntimeStateSchema
13526
- };
13527
- /**
13528
- * Shared geometry vocabulary for on-frame shape caps — privacy-mask,
13529
- * motion-zones, and the detection zones/lines editor all speak this one
13530
- * language so a single drawing-plane editor and the providers stay
13531
- * decoupled from each cap's storage.
13532
- *
13533
- * All coordinates are normalized 0..1 of the camera frame (top-left
13534
- * origin). Each cap composes the SUBSET of shape kinds it supports and
13535
- * advertises it via `supportedShapes` in its `getOptions`.
13536
- */
13537
- /** A normalized 0..1 point (top-left origin). */
13538
- var MaskPointSchema = object({
13539
- x: number(),
13540
- y: number()
13541
- });
13542
- /** Axis-aligned rectangle (normalized 0..1). */
13543
- var MaskRectShapeSchema = object({
13544
- kind: literal("rect"),
13545
- x: number(),
13546
- y: number(),
13547
- width: number(),
13548
- height: number()
13549
- });
13550
- /** Free polygon — an ordered list of normalized vertices (≥3). */
13551
- var MaskPolygonShapeSchema = object({
13552
- kind: literal("polygon"),
13553
- points: array(MaskPointSchema)
13554
- });
13555
- /** Boolean cell grid — row-major, length === gridWidth*gridHeight. */
13556
- var MaskGridShapeSchema = object({
13557
- kind: literal("grid"),
13558
- gridWidth: number(),
13559
- gridHeight: number(),
13560
- cells: array(boolean())
13561
- });
13562
- discriminatedUnion("kind", [
13563
- MaskRectShapeSchema,
13564
- MaskPolygonShapeSchema,
13565
- MaskGridShapeSchema,
13566
- object({
13567
- kind: literal("line"),
13568
- points: array(MaskPointSchema)
13569
- })
13570
- ]);
13571
- /** Every shape-kind discriminant, for `supportedShapes` advertisement. */
13572
- var MaskShapeKindSchema = _enum([
13573
- "rect",
13574
- "polygon",
13575
- "grid",
13576
- "line"
13577
- ]);
13578
- /** Polygon vertex bounds when a cap supports 'polygon' (e.g. Hikvision {min:4,max:4}). */
13579
- var MaskPolygonVerticesSchema = object({
13580
- min: number(),
13581
- max: number()
13582
- });
13583
- /** Grid dimensions when a cap supports 'grid'. */
13584
- var MaskGridDimsSchema = object({
13585
- width: number(),
13586
- height: number()
13587
- });
14135
+ * router and admin-ui hero read straight from this snapshot via
14136
+ * `device.state.motionTrigger.value` instead of re-issuing a firmware
14137
+ * round-trip on every UI mount. `lastFetchedAt` lets the framework
14138
+ * helper (`createRuntimeStateBridge`) stale-check before deciding
14139
+ * whether to refresh from the camera.
14140
+ */
14141
+ var MotionTriggerRuntimeStateSchema = MotionTriggerStatusSchema.extend({
14142
+ /** Ms epoch of the last successful camera fetch (0 = never). */
14143
+ lastFetchedAt: number() });
14144
+ var motionTriggerCapability = {
14145
+ name: "motion-trigger",
14146
+ scope: "device",
14147
+ deviceNative: true,
14148
+ mode: "singleton",
14149
+ deviceTypes: [
14150
+ DeviceType.Light,
14151
+ DeviceType.Siren,
14152
+ DeviceType.Switch
14153
+ ],
14154
+ methods: { setMotionTrigger: method(object({
14155
+ deviceId: number().int().nonnegative(),
14156
+ enabled: boolean()
14157
+ }), _void(), {
14158
+ kind: "mutation",
14159
+ auth: "admin"
14160
+ }) },
14161
+ events: { onMotionTriggerChanged: { data: object({
14162
+ deviceId: number(),
14163
+ enabled: boolean(),
14164
+ lastChangedAt: number()
14165
+ }) } },
14166
+ status: {
14167
+ schema: MotionTriggerStatusSchema,
14168
+ kind: "command-driven"
14169
+ },
14170
+ runtimeState: MotionTriggerRuntimeStateSchema
14171
+ };
13588
14172
  /**
13589
14173
  * Motion-zones share the same MaskShape vocabulary as privacy-mask — the
13590
14174
  * on-camera motion-detection mask is a single `grid` region (a row-major
@@ -17022,6 +17606,55 @@ method(object({
17022
17606
  password: string()
17023
17607
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
17024
17608
  /**
17609
+ * A live terminal session hosted by the provider addon. Output and input do
17610
+ * NOT flow through the capability — they use the addon data plane
17611
+ * (`GET /addon/terminal/<id>/out` SSE, `POST /addon/terminal/<id>/in`) because
17612
+ * terminal output must be ordered and lossless. The event bus is telemetry and
17613
+ * may drop chunks ([D8]), and a dropped chunk desynchronises the vt parser
17614
+ * permanently until a full repaint. The capability owns only lifecycle.
17615
+ */
17616
+ var TerminalSessionInfoSchema = object({
17617
+ /** Opaque session id minted by the provider on `openSession`. */
17618
+ sessionId: string(),
17619
+ /** The pre-declared profile this session runs (never a free-form command). */
17620
+ profileId: string(),
17621
+ /** Human-readable profile label for the UI session list. */
17622
+ label: string(),
17623
+ cols: number().int().positive(),
17624
+ rows: number().int().positive(),
17625
+ /** ms-epoch the session's pty was spawned. */
17626
+ startedAt: number()
17627
+ });
17628
+ /**
17629
+ * A profile the operator may open — a pre-declared, allowlisted program
17630
+ * (`monitor` → `btm`). The capability accepts only these ids; a free-form
17631
+ * command string would be remote code execution as the server's user, so it is
17632
+ * deliberately not part of the contract.
17633
+ */
17634
+ var TerminalProfileInfoSchema = object({
17635
+ profileId: string(),
17636
+ label: string(),
17637
+ description: string().optional()
17638
+ });
17639
+ method(_void(), array(TerminalProfileInfoSchema).readonly(), { auth: "admin" }), method(_void(), array(TerminalSessionInfoSchema).readonly(), { auth: "admin" }), method(object({
17640
+ profileId: string(),
17641
+ cols: number().int().positive(),
17642
+ rows: number().int().positive()
17643
+ }), TerminalSessionInfoSchema, {
17644
+ kind: "mutation",
17645
+ auth: "admin"
17646
+ }), method(object({
17647
+ sessionId: string(),
17648
+ cols: number().int().positive(),
17649
+ rows: number().int().positive()
17650
+ }), _void(), {
17651
+ kind: "mutation",
17652
+ auth: "admin"
17653
+ }), method(object({ sessionId: string() }), _void(), {
17654
+ kind: "mutation",
17655
+ auth: "admin"
17656
+ });
17657
+ /**
17025
17658
  * Orchestrator-side destination metadata. The orchestrator computes
17026
17659
  * `id = <addonId>:<subId>` from its provider lookup so consumers
17027
17660
  * (admin UI, restore flow) see one canonical key.
@@ -17122,11 +17755,53 @@ var LocationStatSchema = object({
17122
17755
  fileCount: number(),
17123
17756
  present: boolean()
17124
17757
  });
17758
+ /**
17759
+ * A backup schedule — the N:M "entry" that binds one cron cadence to a
17760
+ * SET of destination locations. Supersedes the per-location cron on
17761
+ * `BackupDestinationPolicy`: an operator creates a schedule, picks the
17762
+ * `backups` locations it should write to, and the orchestrator fans a
17763
+ * single archive out to all of them when the cron fires.
17764
+ *
17765
+ * `retentionCount` is per-schedule (D-decision 2026-07-28): every
17766
+ * location targeted by this schedule keeps this many archives from
17767
+ * this schedule's runs.
17768
+ *
17769
+ * `dataSources` optionally narrows which top-level state locations
17770
+ * (db, addons, tls, …) are archived; omitted = the orchestrator's
17771
+ * default full set.
17772
+ */
17773
+ var BackupScheduleSchema = object({
17774
+ /** Stable id. Generated by the orchestrator on first upsert if absent. */
17775
+ id: string(),
17776
+ /** Operator-facing display name. */
17777
+ label: string(),
17778
+ /** 5-field POSIX cron. Empty = disabled cadence (kept for editing). */
17779
+ cron: string(),
17780
+ /** Master on/off toggle for the whole schedule. */
17781
+ enabled: boolean(),
17782
+ /** `backups`-location ids this schedule writes to (fan-out set). */
17783
+ locationIds: array(string()).readonly(),
17784
+ /** Archives kept per targeted location for this schedule. */
17785
+ retentionCount: number().int().min(1).max(1e3),
17786
+ /** Optional subset of source locations to include; omitted = all. */
17787
+ dataSources: array(string()).readonly().optional(),
17788
+ /** ms-epoch of last successful run. */
17789
+ lastRunAt: number().optional(),
17790
+ /** ms-epoch of next computed firing (read-only, filled on list). */
17791
+ nextRunAt: number().optional()
17792
+ });
17125
17793
  method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }), method(object({
17126
17794
  /** Subset of registered `backup-destination` addon ids to write to. */
17127
17795
  destinations: array(string()).optional(),
17128
17796
  locations: array(string()).optional(),
17129
- label: string().optional()
17797
+ label: string().optional(),
17798
+ /**
17799
+ * Per-run retention override applied to every targeted
17800
+ * destination. Used by schedule-driven runs (per-entry
17801
+ * retention). Omitted = each destination's own policy
17802
+ * retention (manual runs).
17803
+ */
17804
+ retentionCount: number().int().min(1).max(1e3).optional()
17130
17805
  }).optional(), array(BackupEntrySchema).readonly(), {
17131
17806
  kind: "mutation",
17132
17807
  auth: "admin"
@@ -17175,7 +17850,21 @@ method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }
17175
17850
  ok: boolean(),
17176
17851
  error: string().optional(),
17177
17852
  nextRuns: array(number()).readonly()
17178
- }));
17853
+ })), method(_void(), array(BackupScheduleSchema).readonly(), { auth: "admin" }), method(object({
17854
+ id: string().optional(),
17855
+ label: string(),
17856
+ cron: string(),
17857
+ enabled: boolean(),
17858
+ locationIds: array(string()).readonly(),
17859
+ retentionCount: number().int().min(1).max(1e3),
17860
+ dataSources: array(string()).readonly().optional()
17861
+ }), BackupScheduleSchema, {
17862
+ kind: "mutation",
17863
+ auth: "admin"
17864
+ }), method(object({ id: string() }), _void(), {
17865
+ kind: "mutation",
17866
+ auth: "admin"
17867
+ });
17179
17868
  /**
17180
17869
  * `broker` — unified pub/sub broker registry, system-scoped collection.
17181
17870
  *
@@ -18203,1596 +18892,1108 @@ method(object({
18203
18892
  active: boolean()
18204
18893
  }), _void(), {
18205
18894
  kind: "mutation",
18206
- auth: "admin"
18207
- }), method(object({ capName: string() }), array(string())), method(object({ deviceType: string() }), array(object({
18208
- capName: string(),
18209
- wrappers: array(string())
18210
- }))), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), object({
18211
- settings: SettingsSchemaWithValuesSchema.nullable(),
18212
- live: SettingsSchemaWithValuesSchema.nullable()
18213
- })), method(object({
18214
- deviceId: number().int().nonnegative(),
18215
- action: string().min(1),
18216
- input: unknown()
18217
- }), unknown(), { kind: "mutation" }), method(object({
18218
- deviceId: number(),
18219
- writerCapName: string(),
18220
- writerAddonId: string(),
18221
- key: string(),
18222
- value: unknown()
18223
- }), object({ success: literal(true) }), {
18224
- kind: "mutation",
18225
- auth: "admin"
18226
- }), method(object({
18227
- deviceId: number(),
18228
- changes: array(object({
18229
- writerCapName: string(),
18230
- writerAddonId: string(),
18231
- key: string(),
18232
- value: unknown()
18233
- }))
18234
- }), object({
18235
- success: literal(true),
18236
- failures: array(object({
18237
- writerCapName: string(),
18238
- writerAddonId: string(),
18239
- error: string()
18240
- }))
18241
- }), {
18242
- kind: "mutation",
18243
- auth: "admin"
18244
- }), method(object({ addonId: string() }), array(DiscoveryCandidateSchema), {
18245
- kind: "mutation",
18246
- auth: "admin"
18247
- }), method(object({
18248
- addonId: string(),
18249
- candidate: DiscoveryCandidateSchema,
18250
- /** Owning integration id, stamped onto the new device's meta by the
18251
- * device-manager forwarder so `removeByIntegration` can cascade it.
18252
- * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
18253
- integrationId: string().optional()
18254
- }), DeviceSummarySchema, {
18255
- kind: "mutation",
18256
- auth: "admin"
18257
- }), method(object({
18258
- addonId: string(),
18259
- type: _enum(DeviceType)
18260
- }), unknown().nullable()), method(object({
18261
- addonId: string(),
18262
- type: _enum(DeviceType),
18263
- config: record(string(), unknown()),
18264
- /** Owning integration id, stamped onto the new device's meta by the
18265
- * device-manager forwarder so `removeByIntegration` can cascade it.
18266
- * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
18267
- integrationId: string().optional()
18268
- }), DeviceSummarySchema, {
18269
- kind: "mutation",
18270
- auth: "admin"
18271
- }), method(object({
18272
- addonId: string(),
18273
- type: _enum(DeviceType),
18274
- key: string(),
18275
- value: unknown(),
18276
- formValues: record(string(), unknown()).optional()
18277
- }), FieldProbeResultSchema, {
18278
- kind: "mutation",
18279
- auth: "admin"
18280
- }), method(object({
18281
- addonId: string(),
18282
- integrationId: string()
18283
- }), object({ filters: array(AdoptionFilterSchema) }), { auth: "admin" }), method(ListCandidatesInputSchema.extend({ addonId: string() }), ListCandidatesOutputSchema, { auth: "admin" }), method(object({
18284
- addonId: string(),
18285
- integrationId: string()
18286
- }), AdoptionStatusSchema, {
18287
- kind: "mutation",
18288
- auth: "admin"
18289
- }), method(AdoptInputSchema.extend({ addonId: string() }), AdoptResultSchema, {
18290
- kind: "mutation",
18291
- auth: "admin"
18292
- }), method(ReleaseInputSchema.extend({ addonId: string() }), _void(), {
18293
- kind: "mutation",
18294
- auth: "admin"
18295
- }), method(ResyncInputSchema, ResyncResultSchema, {
18296
- kind: "mutation",
18297
- auth: "admin"
18298
- }), method(object({}), object({ providers: array(object({
18299
- addonId: string(),
18300
- label: string()
18301
- })).readonly() }), { auth: "admin" }), method(object({}), object({ groups: array(object({
18302
- addonId: string(),
18303
- label: string(),
18304
- candidates: array(DiscoveryCandidateSchema).readonly(),
18305
- error: string().nullable()
18306
- })).readonly() }), {
18307
- kind: "mutation",
18308
- auth: "admin"
18309
- }), method(object({
18310
- addonId: string(),
18311
- params: record(string(), unknown()).optional()
18312
- }), object({ candidates: array(DiscoveryCandidateSchema).readonly() }), {
18313
- kind: "mutation",
18314
- auth: "admin"
18315
- }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
18316
- deviceId: number(),
18317
- key: string(),
18318
- value: unknown()
18319
- }), FieldProbeResultSchema, {
18320
- kind: "mutation",
18321
- auth: "admin"
18322
- }), method(object({
18323
- deviceId: number(),
18324
- caps: array(string()).readonly().optional()
18325
- }), record(string(), unknown().nullable()));
18326
- method(object({ deviceId: number() }), record(string(), record(string(), unknown()))), method(object({
18327
- deviceId: number(),
18328
- capName: string()
18329
- }), record(string(), unknown()).nullable()), method(object({}), record(string(), record(string(), record(string(), unknown())))), method(object({
18330
- deviceId: number(),
18331
- capName: string(),
18332
- slice: record(string(), unknown())
18333
- }), _void(), { kind: "mutation" }), object({
18334
- deviceId: number(),
18335
- capName: string(),
18336
- slice: record(string(), unknown())
18337
- });
18338
- /**
18339
- * Embedding output. `embedding` is wire-encoded as `number[]` so the
18340
- * Zod-validated tRPC surface round-trips cleanly; consumers that need a
18341
- * `Float32Array` can wrap it on the way out (in-process, no marshalling
18342
- * is involved). `inferenceMs` mirrors the runtime field used by the
18343
- * post-analysis enrichment-engine.
18344
- */
18345
- var EmbeddingResultSchema = object({
18346
- embedding: array(number()),
18347
- inferenceMs: number()
18348
- });
18349
- var EmbeddingInfoSchema = object({
18350
- modelId: string(),
18351
- embeddingDim: number(),
18352
- ready: boolean()
18353
- });
18354
- method(object({
18355
- crop: _instanceof(Uint8Array),
18356
- width: number(),
18357
- height: number()
18358
- }), EmbeddingResultSchema), method(object({ text: string() }), EmbeddingResultSchema), method(_void(), EmbeddingInfoSchema);
18359
- /**
18360
- * filesystem-browse — per-node capability for browsing the node's local
18361
- * filesystem, sandboxed to operator-configured allowed roots. Used by the
18362
- * admin "Add filesystem location" flow to pick a node + path. `mode:'per-node'`
18363
- * (one provider per node); the hub calls it with `{nodeId}` so the codegen
18364
- * routes to that exact node (default `nodeIdMode:'routing'`).
18365
- */
18366
- var DirEntrySchema = object({
18367
- name: string(),
18368
- path: string()
18369
- });
18370
- var BrowseResultSchema = object({
18371
- path: string(),
18372
- entries: array(DirEntrySchema).readonly(),
18373
- freeBytes: number(),
18374
- totalBytes: number()
18375
- });
18376
- method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({ path: string() }), BrowseResultSchema, { auth: "admin" }), method(object({ path: string() }), object({ path: string() }), {
18895
+ auth: "admin"
18896
+ }), method(object({ capName: string() }), array(string())), method(object({ deviceType: string() }), array(object({
18897
+ capName: string(),
18898
+ wrappers: array(string())
18899
+ }))), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), object({
18900
+ settings: SettingsSchemaWithValuesSchema.nullable(),
18901
+ live: SettingsSchemaWithValuesSchema.nullable()
18902
+ })), method(object({
18903
+ deviceId: number().int().nonnegative(),
18904
+ action: string().min(1),
18905
+ input: unknown()
18906
+ }), unknown(), { kind: "mutation" }), method(object({
18907
+ deviceId: number(),
18908
+ writerCapName: string(),
18909
+ writerAddonId: string(),
18910
+ key: string(),
18911
+ value: unknown()
18912
+ }), object({ success: literal(true) }), {
18377
18913
  kind: "mutation",
18378
18914
  auth: "admin"
18379
- });
18380
- /**
18381
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18382
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18383
- * caps stay wire-compatible without a circular cap→cap import.
18384
- *
18385
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
18386
- * every transport tier structurally, and failed calls still write usage rows.
18387
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18388
- */
18389
- var LlmUsageSchema = object({
18390
- inputTokens: number(),
18391
- outputTokens: number()
18392
- });
18393
- var LlmErrorCodeSchema = _enum([
18394
- "timeout",
18395
- "rate-limited",
18396
- "auth",
18397
- "refusal",
18398
- "bad-request",
18399
- "unavailable",
18400
- "no-profile",
18401
- "budget-exceeded",
18402
- "adapter-error"
18403
- ]);
18404
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18405
- ok: literal(true),
18406
- text: string(),
18407
- model: string(),
18408
- usage: LlmUsageSchema,
18409
- truncated: boolean(),
18410
- latencyMs: number()
18915
+ }), method(object({
18916
+ deviceId: number(),
18917
+ changes: array(object({
18918
+ writerCapName: string(),
18919
+ writerAddonId: string(),
18920
+ key: string(),
18921
+ value: unknown()
18922
+ }))
18411
18923
  }), object({
18412
- ok: literal(false),
18413
- code: LlmErrorCodeSchema,
18414
- message: string(),
18415
- retryAfterMs: number().optional()
18416
- })]);
18417
- /**
18418
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18419
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18420
- * notification-output.cap.ts:27-31 precedents).
18421
- */
18422
- var LlmImageSchema = object({
18423
- bytes: _instanceof(Uint8Array),
18424
- mimeType: string()
18425
- });
18426
- var LlmGenerateBaseInputSchema = object({
18427
- /** Collection routing (the notification-output posture). */
18428
- addonId: string().optional(),
18429
- /** Explicit profile; else the resolution chain (spec §3). */
18430
- profileId: string().optional(),
18431
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18432
- consumer: string(),
18433
- system: string().optional(),
18434
- /** v1: single-turn. `messages[]` is a v2 additive field. */
18435
- prompt: string(),
18436
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18437
- jsonSchema: record(string(), unknown()).optional(),
18438
- /** Per-call override of the profile default. */
18439
- maxTokens: number().int().positive().optional(),
18440
- temperature: number().optional()
18441
- });
18442
- /**
18443
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18444
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18445
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18446
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18447
- * this only through the `llm` cap's methods.
18448
- *
18449
- * One running llama-server child per node in v1 (models are RAM-heavy).
18450
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18451
- * watchdog — operator decision #3).
18452
- */
18453
- var ManagedModelRefSchema = discriminatedUnion("kind", [
18454
- object({
18455
- kind: literal("catalog"),
18456
- catalogId: string()
18457
- }),
18458
- object({
18459
- kind: literal("url"),
18460
- url: string(),
18461
- sha256: string().optional()
18462
- }),
18463
- object({
18464
- kind: literal("path"),
18465
- path: string()
18466
- })
18467
- ]);
18468
- var ManagedRuntimeConfigSchema = object({
18469
- /** WHERE the runtime lives — hub or any agent. */
18470
- nodeId: string(),
18471
- /** Closed for v1; 'ollama' is a v2 candidate. */
18472
- engine: _enum(["llama-cpp"]),
18473
- model: ManagedModelRefSchema,
18474
- contextSize: number().int().default(4096),
18475
- /** 0 = CPU-only. */
18476
- gpuLayers: number().int().default(0),
18477
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18478
- threads: number().int().optional(),
18479
- /** Concurrent slots. */
18480
- parallel: number().int().default(1),
18481
- /** Else lazy: first generate boots it. */
18482
- autoStart: boolean().default(false),
18483
- /** 0 = never; frees RAM after quiet periods. */
18484
- idleStopMinutes: number().int().default(30)
18485
- });
18486
- var LlmRuntimeStatusSchema = object({
18487
- /** Status is ALWAYS node-qualified. */
18488
- nodeId: string(),
18489
- state: _enum([
18490
- "stopped",
18491
- "downloading",
18492
- "starting",
18493
- "ready",
18494
- "crashed",
18495
- "failed"
18496
- ]),
18497
- pid: number().optional(),
18498
- port: number().optional(),
18499
- modelPath: string().optional(),
18500
- modelId: string().optional(),
18501
- downloadProgress: number().min(0).max(1).optional(),
18502
- lastError: string().optional(),
18503
- crashesInWindow: number(),
18504
- /** Child RSS (sampled best-effort). */
18505
- memoryBytes: number().optional(),
18506
- vramBytes: number().optional()
18507
- });
18508
- var LlmNodeModelSchema = object({
18509
- file: string(),
18510
- sizeBytes: number(),
18511
- catalogId: string().optional(),
18512
- installedAt: number().optional()
18513
- });
18514
- var LlmRuntimeDiskUsageSchema = object({
18515
- nodeId: string(),
18516
- modelsBytes: number(),
18517
- freeBytes: number().optional()
18518
- });
18519
- method(LlmGenerateBaseInputSchema.extend({
18520
- images: array(LlmImageSchema).optional(),
18521
- runtime: ManagedRuntimeConfigSchema,
18522
- /** The managed profile's timeout, threaded by the hub provider. */
18523
- timeoutMs: number().int().positive().optional()
18524
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18924
+ success: literal(true),
18925
+ failures: array(object({
18926
+ writerCapName: string(),
18927
+ writerAddonId: string(),
18928
+ error: string()
18929
+ }))
18930
+ }), {
18525
18931
  kind: "mutation",
18526
18932
  auth: "admin"
18527
- }), method(object({}), _void(), {
18933
+ }), method(object({ addonId: string() }), array(DiscoveryCandidateSchema), {
18528
18934
  kind: "mutation",
18529
18935
  auth: "admin"
18530
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18936
+ }), method(object({
18937
+ addonId: string(),
18938
+ candidate: DiscoveryCandidateSchema,
18939
+ /** Owning integration id, stamped onto the new device's meta by the
18940
+ * device-manager forwarder so `removeByIntegration` can cascade it.
18941
+ * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
18942
+ integrationId: string().optional()
18943
+ }), DeviceSummarySchema, {
18531
18944
  kind: "mutation",
18532
18945
  auth: "admin"
18533
- }), method(object({ file: string() }), _void(), {
18946
+ }), method(object({
18947
+ addonId: string(),
18948
+ type: _enum(DeviceType)
18949
+ }), unknown().nullable()), method(object({
18950
+ addonId: string(),
18951
+ type: _enum(DeviceType),
18952
+ config: record(string(), unknown()),
18953
+ /** Owning integration id, stamped onto the new device's meta by the
18954
+ * device-manager forwarder so `removeByIntegration` can cascade it.
18955
+ * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
18956
+ integrationId: string().optional()
18957
+ }), DeviceSummarySchema, {
18534
18958
  kind: "mutation",
18535
18959
  auth: "admin"
18536
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18537
- /**
18538
- * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18539
- * methods concat-fan across providers; single-row methods route to ONE
18540
- * provider by the `addonId` in the call input (the notification-output
18541
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18542
- * (hub-placed); the cap stays open for future providers.
18543
- *
18544
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18545
- * `apiKey` is a password field — providers REDACT it on read and merge on
18546
- * write; a stored key NEVER round-trips to a client.
18547
- */
18548
- var LlmProfileKindSchema = _enum([
18549
- "openai-compatible",
18550
- "openai",
18551
- "anthropic",
18552
- "google",
18553
- "managed-local"
18554
- ]);
18555
- var LlmProfileSchema = object({
18556
- id: string(),
18557
- name: string(),
18558
- kind: LlmProfileKindSchema,
18559
- /** Stamped by the provider — keeps the fanned catalog routable. */
18960
+ }), method(object({
18560
18961
  addonId: string(),
18561
- enabled: boolean(),
18562
- /** Vendor model id, or the managed runtime's loaded model. */
18563
- model: string(),
18564
- /** Required for openai-compatible; override for cloud kinds. */
18565
- baseUrl: string().optional(),
18566
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
18567
- apiKey: string().optional(),
18568
- supportsVision: boolean(),
18569
- temperature: number().min(0).max(2).optional(),
18570
- maxTokens: number().int().positive().optional(),
18571
- timeoutMs: number().int().positive().default(6e4),
18572
- extraHeaders: record(string(), string()).optional(),
18573
- /** kind === 'managed-local' only (spec §4). */
18574
- runtime: ManagedRuntimeConfigSchema.optional()
18575
- });
18576
- /** ConfigUISchema tree passed through untyped on the wire (the
18577
- * notification-output `ConfigSchemaPassthrough` precedent at
18578
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
18579
- var ConfigSchemaPassthrough$1 = unknown();
18580
- var LlmProfileKindDescriptorSchema = object({
18581
- kind: LlmProfileKindSchema,
18582
- label: string(),
18583
- icon: string(),
18584
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
18962
+ type: _enum(DeviceType),
18963
+ key: string(),
18964
+ value: unknown(),
18965
+ formValues: record(string(), unknown()).optional()
18966
+ }), FieldProbeResultSchema, {
18967
+ kind: "mutation",
18968
+ auth: "admin"
18969
+ }), method(object({
18585
18970
  addonId: string(),
18586
- configSchema: ConfigSchemaPassthrough$1
18587
- });
18588
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
18589
- var LlmDefaultSchema = object({
18590
- selector: LlmDefaultSelectorSchema,
18591
- profileId: string()
18592
- });
18593
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
18594
- var LlmUsageRollupSchema = object({
18595
- day: string(),
18596
- consumer: string(),
18597
- profileId: string(),
18598
- calls: number(),
18599
- okCalls: number(),
18600
- errorCalls: number(),
18601
- inputTokens: number(),
18602
- outputTokens: number(),
18603
- avgLatencyMs: number()
18604
- });
18605
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
18606
- var ManagedModelCatalogEntrySchema = object({
18607
- id: string(),
18608
- label: string(),
18609
- family: string(),
18610
- purpose: _enum(["text", "vision"]),
18611
- url: string(),
18612
- sha256: string(),
18613
- sizeBytes: number(),
18614
- quantization: string(),
18615
- /** Load-time guidance shown in the picker. */
18616
- minRamBytes: number(),
18617
- contextSizeDefault: number().int(),
18618
- /** Vision models: companion projector file. */
18619
- mmprojUrl: string().optional()
18620
- });
18621
- var LlmRuntimeNodeSchema = object({
18622
- nodeId: string(),
18623
- reachable: boolean(),
18624
- status: LlmRuntimeStatusSchema.optional(),
18625
- disk: LlmRuntimeDiskUsageSchema.optional(),
18626
- error: string().optional()
18627
- });
18628
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
18629
- var ProfileRefInputSchema = object({
18971
+ integrationId: string()
18972
+ }), object({ filters: array(AdoptionFilterSchema) }), { auth: "admin" }), method(ListCandidatesInputSchema.extend({ addonId: string() }), ListCandidatesOutputSchema, { auth: "admin" }), method(object({
18630
18973
  addonId: string(),
18631
- profileId: string()
18632
- });
18633
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
18974
+ integrationId: string()
18975
+ }), AdoptionStatusSchema, {
18634
18976
  kind: "mutation",
18635
18977
  auth: "admin"
18636
- }), method(ProfileRefInputSchema, _void(), {
18978
+ }), method(AdoptInputSchema.extend({ addonId: string() }), AdoptResultSchema, {
18637
18979
  kind: "mutation",
18638
18980
  auth: "admin"
18639
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
18981
+ }), method(ReleaseInputSchema.extend({ addonId: string() }), _void(), {
18640
18982
  kind: "mutation",
18641
18983
  auth: "admin"
18642
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
18643
- selector: LlmDefaultSelectorSchema,
18644
- profileId: string().nullable()
18645
- }), _void(), {
18984
+ }), method(ResyncInputSchema, ResyncResultSchema, {
18646
18985
  kind: "mutation",
18647
18986
  auth: "admin"
18648
- }), method(object({
18649
- since: number().optional(),
18650
- until: number().optional(),
18651
- consumer: string().optional(),
18652
- profileId: string().optional()
18653
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
18654
- nodeId: string(),
18655
- model: ManagedModelRefSchema
18656
- }), _void(), {
18987
+ }), method(object({}), object({ providers: array(object({
18988
+ addonId: string(),
18989
+ label: string()
18990
+ })).readonly() }), { auth: "admin" }), method(object({}), object({ groups: array(object({
18991
+ addonId: string(),
18992
+ label: string(),
18993
+ candidates: array(DiscoveryCandidateSchema).readonly(),
18994
+ error: string().nullable()
18995
+ })).readonly() }), {
18657
18996
  kind: "mutation",
18658
18997
  auth: "admin"
18659
18998
  }), method(object({
18660
- nodeId: string(),
18661
- file: string()
18662
- }), _void(), {
18999
+ addonId: string(),
19000
+ params: record(string(), unknown()).optional()
19001
+ }), object({ candidates: array(DiscoveryCandidateSchema).readonly() }), {
18663
19002
  kind: "mutation",
18664
19003
  auth: "admin"
18665
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
19004
+ }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
19005
+ deviceId: number(),
19006
+ key: string(),
19007
+ value: unknown()
19008
+ }), FieldProbeResultSchema, {
18666
19009
  kind: "mutation",
18667
19010
  auth: "admin"
18668
- }), method(ProfileRefInputSchema, _void(), {
19011
+ }), method(object({
19012
+ deviceId: number(),
19013
+ caps: array(string()).readonly().optional()
19014
+ }), record(string(), unknown().nullable()));
19015
+ method(object({ deviceId: number() }), record(string(), record(string(), unknown()))), method(object({
19016
+ deviceId: number(),
19017
+ capName: string()
19018
+ }), record(string(), unknown()).nullable()), method(object({}), record(string(), record(string(), record(string(), unknown())))), method(object({
19019
+ deviceId: number(),
19020
+ capName: string(),
19021
+ slice: record(string(), unknown())
19022
+ }), _void(), { kind: "mutation" }), object({
19023
+ deviceId: number(),
19024
+ capName: string(),
19025
+ slice: record(string(), unknown())
19026
+ });
19027
+ /**
19028
+ * Embedding output. `embedding` is wire-encoded as `number[]` so the
19029
+ * Zod-validated tRPC surface round-trips cleanly; consumers that need a
19030
+ * `Float32Array` can wrap it on the way out (in-process, no marshalling
19031
+ * is involved). `inferenceMs` mirrors the runtime field used by the
19032
+ * post-analysis enrichment-engine.
19033
+ */
19034
+ var EmbeddingResultSchema = object({
19035
+ embedding: array(number()),
19036
+ inferenceMs: number()
19037
+ });
19038
+ var EmbeddingInfoSchema = object({
19039
+ modelId: string(),
19040
+ embeddingDim: number(),
19041
+ ready: boolean()
19042
+ });
19043
+ method(object({
19044
+ crop: _instanceof(Uint8Array),
19045
+ width: number(),
19046
+ height: number()
19047
+ }), EmbeddingResultSchema), method(object({ text: string() }), EmbeddingResultSchema), method(_void(), EmbeddingInfoSchema);
19048
+ /**
19049
+ * filesystem-browse — per-node capability for browsing the node's local
19050
+ * filesystem, sandboxed to operator-configured allowed roots. Used by the
19051
+ * admin "Add filesystem location" flow to pick a node + path. `mode:'per-node'`
19052
+ * (one provider per node); the hub calls it with `{nodeId}` so the codegen
19053
+ * routes to that exact node (default `nodeIdMode:'routing'`).
19054
+ */
19055
+ var DirEntrySchema = object({
19056
+ name: string(),
19057
+ path: string()
19058
+ });
19059
+ var BrowseResultSchema = object({
19060
+ path: string(),
19061
+ entries: array(DirEntrySchema).readonly(),
19062
+ freeBytes: number(),
19063
+ totalBytes: number()
19064
+ });
19065
+ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({ path: string() }), BrowseResultSchema, { auth: "admin" }), method(object({ path: string() }), object({ path: string() }), {
18669
19066
  kind: "mutation",
18670
19067
  auth: "admin"
18671
19068
  });
18672
- var LogLevelSchema = _enum([
18673
- "debug",
18674
- "info",
18675
- "warn",
18676
- "error"
19069
+ /**
19070
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
19071
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
19072
+ * caps stay wire-compatible without a circular cap→cap import.
19073
+ *
19074
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
19075
+ * every transport tier structurally, and failed calls still write usage rows.
19076
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
19077
+ */
19078
+ var LlmUsageSchema = object({
19079
+ inputTokens: number(),
19080
+ outputTokens: number()
19081
+ });
19082
+ var LlmErrorCodeSchema = _enum([
19083
+ "timeout",
19084
+ "rate-limited",
19085
+ "auth",
19086
+ "refusal",
19087
+ "bad-request",
19088
+ "unavailable",
19089
+ "no-profile",
19090
+ "budget-exceeded",
19091
+ "adapter-error"
18677
19092
  ]);
18678
- var LogEntrySchema = object({
18679
- timestamp: date(),
18680
- level: LogLevelSchema,
18681
- scope: array(string()),
19093
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
19094
+ ok: literal(true),
19095
+ text: string(),
19096
+ model: string(),
19097
+ usage: LlmUsageSchema,
19098
+ truncated: boolean(),
19099
+ latencyMs: number()
19100
+ }), object({
19101
+ ok: literal(false),
19102
+ code: LlmErrorCodeSchema,
18682
19103
  message: string(),
18683
- meta: record(string(), unknown()).optional(),
18684
- tags: record(string(), string()).optional()
18685
- });
18686
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18687
- scope: array(string()).optional(),
18688
- level: LogLevelSchema.optional(),
18689
- since: date().optional(),
18690
- until: date().optional(),
18691
- limit: number().optional(),
18692
- tags: record(string(), string()).optional()
18693
- }), array(LogEntrySchema).readonly());
19104
+ retryAfterMs: number().optional()
19105
+ })]);
18694
19106
  /**
18695
- * `login-method` collection cap through which auth addons contribute
18696
- * their pre-auth login surfaces to the login page. This is the SINGLE,
18697
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
18698
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
18699
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
18700
- * procedure aggregates them for the unauthenticated login page.
18701
- *
18702
- * A contribution is a discriminated union on `kind`:
18703
- *
18704
- * - `redirect` a declarative button. The login page renders a generic
18705
- * button that navigates to `startUrl` (an addon-owned HTTP route).
18706
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
18707
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
18708
- * login page needs NO change.
18709
- *
18710
- * - `widget` — a Module-Federation widget the login page mounts (via
18711
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
18712
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
18713
- * mechanism kept for future use; no shipped addon uses it on the login
18714
- * page (the passkey ceremony below runs natively in the shell instead).
18715
- *
18716
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
18717
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
18718
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
18719
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
18720
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
18721
- * fetching any remote code pre-auth. Contribution stays unconditional
18722
- * enrollment state is never leaked pre-auth; visibility is a shell
18723
- * decision.
18724
- *
18725
- * Every contribution carries a `stage`:
18726
- * - `primary` — shown on the first credentials screen (OIDC /
18727
- * magic-link buttons; a future usernameless passkey).
18728
- * - `second-factor` — shown AFTER the password leg, gated on the
18729
- * returned `factors` (passkey-as-2FA today).
19107
+ * `Uint8Array` is the sanctioned binary convention superjson + the UDS
19108
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
19109
+ * notification-output.cap.ts:27-31 precedents).
19110
+ */
19111
+ var LlmImageSchema = object({
19112
+ bytes: _instanceof(Uint8Array),
19113
+ mimeType: string()
19114
+ });
19115
+ var LlmGenerateBaseInputSchema = object({
19116
+ /** Collection routing (the notification-output posture). */
19117
+ addonId: string().optional(),
19118
+ /** Explicit profile; else the resolution chain (spec §3). */
19119
+ profileId: string().optional(),
19120
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
19121
+ consumer: string(),
19122
+ system: string().optional(),
19123
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
19124
+ prompt: string(),
19125
+ /** Structured output adapter-mapped (response_format / forced tool / responseSchema). */
19126
+ jsonSchema: record(string(), unknown()).optional(),
19127
+ /** Per-call override of the profile default. */
19128
+ maxTokens: number().int().positive().optional(),
19129
+ temperature: number().optional()
19130
+ });
19131
+ /**
19132
+ * `llm-runtime` node-side managed llama.cpp executor (spec §4). Registered
19133
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
19134
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` normal
19135
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
19136
+ * this only through the `llm` cap's methods.
18730
19137
  *
18731
- * `mount: skip` the cap is read server-side by the core auth router
18732
- * (`registry.getCollection('login-method')`), never mounted as its own
18733
- * tRPC router.
19138
+ * One running llama-server child per node in v1 (models are RAM-heavy).
19139
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
19140
+ * watchdog — operator decision #3).
18734
19141
  */
18735
- /** When a login method renders in the two-phase login flow. */
18736
- var LoginStageEnum = _enum(["primary", "second-factor"]);
18737
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
18738
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
19142
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
18739
19143
  object({
18740
- kind: literal("redirect"),
18741
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
18742
- id: string(),
18743
- /** Operator-facing button label. */
18744
- label: string(),
18745
- /** lucide-react icon name. */
18746
- icon: string().optional(),
18747
- /** Addon-owned HTTP route the button navigates to (GET). */
18748
- startUrl: string(),
18749
- stage: LoginStageEnum
19144
+ kind: literal("catalog"),
19145
+ catalogId: string()
18750
19146
  }),
18751
19147
  object({
18752
- kind: literal("widget"),
18753
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
18754
- id: string(),
18755
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
18756
- addonId: string(),
18757
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
18758
- bundle: string(),
18759
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
18760
- remote: WidgetRemoteSchema,
18761
- stage: LoginStageEnum
19148
+ kind: literal("url"),
19149
+ url: string(),
19150
+ sha256: string().optional()
18762
19151
  }),
18763
19152
  object({
18764
- kind: literal("passkey"),
18765
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
18766
- id: string(),
18767
- /** Operator-facing button label. */
18768
- label: string(),
18769
- stage: LoginStageEnum,
18770
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
18771
- rpId: string(),
18772
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
18773
- origin: string().nullable()
19153
+ kind: literal("path"),
19154
+ path: string()
18774
19155
  })
18775
19156
  ]);
18776
- method(_void(), array(LoginMethodContributionSchema).readonly());
18777
- var CpuBreakdownSchema = object({
18778
- total: number(),
18779
- user: number(),
18780
- system: number(),
18781
- irq: number(),
18782
- nice: number(),
18783
- loadAvg: tuple([
18784
- number(),
18785
- number(),
18786
- number()
18787
- ]),
18788
- cores: number()
18789
- });
18790
- var MemoryInfoSchema = object({
18791
- percent: number(),
18792
- totalBytes: number(),
18793
- usedBytes: number(),
18794
- availableBytes: number(),
18795
- swapUsedBytes: number(),
18796
- swapTotalBytes: number()
18797
- });
18798
- var DiskIoSnapshotSchema = object({
18799
- readBytes: number(),
18800
- writeBytes: number(),
18801
- readOps: number(),
18802
- writeOps: number(),
18803
- timestampMs: number()
18804
- });
18805
- var NetworkIoSnapshotSchema = object({
18806
- rxBytes: number(),
18807
- txBytes: number(),
18808
- rxPackets: number(),
18809
- txPackets: number(),
18810
- rxErrors: number(),
18811
- txErrors: number(),
18812
- timestampMs: number()
18813
- });
18814
- var MetricsGpuInfoSchema = object({
18815
- utilization: number(),
18816
- model: string(),
18817
- memoryUsedBytes: number(),
18818
- memoryTotalBytes: number(),
18819
- temperature: number().nullable()
18820
- });
18821
- var ProcessResourceInfoSchema = object({
18822
- openFds: number(),
18823
- threadCount: number(),
18824
- activeHandles: number(),
18825
- activeRequests: number()
18826
- });
18827
- var PressureAvgsSchema = object({
18828
- avg10: number(),
18829
- avg60: number(),
18830
- avg300: number()
18831
- });
18832
- var PressureInfoSchema = object({
18833
- some: PressureAvgsSchema,
18834
- full: PressureAvgsSchema.nullable()
18835
- });
18836
- var SystemResourceSnapshotSchema = object({
18837
- cpu: CpuBreakdownSchema,
18838
- memory: MemoryInfoSchema,
18839
- gpu: MetricsGpuInfoSchema.nullable(),
18840
- network: NetworkIoSnapshotSchema,
18841
- disk: DiskIoSnapshotSchema,
18842
- pressure: object({
18843
- cpu: PressureInfoSchema.nullable(),
18844
- memory: PressureInfoSchema.nullable(),
18845
- io: PressureInfoSchema.nullable()
18846
- }),
18847
- process: ProcessResourceInfoSchema,
18848
- cpuTemperature: number().nullable(),
18849
- timestampMs: number()
18850
- });
18851
- var DiskSpaceInfoSchema = object({
18852
- path: string(),
18853
- totalBytes: number(),
18854
- usedBytes: number(),
18855
- availableBytes: number(),
18856
- percent: number()
18857
- });
18858
- var PidResourceStatsSchema = object({
18859
- pid: number(),
18860
- cpu: number(),
18861
- memory: number(),
18862
- /**
18863
- * Private (anonymous) resident bytes — the per-process V8 heap + native
18864
- * allocations NOT shared with other processes (Linux RssAnon). This is the
18865
- * "real" per-runner cost; summing it across runners is meaningful, unlike
18866
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
18867
- * Undefined where /proc is unavailable (e.g. macOS).
18868
- */
18869
- privateBytes: number().optional(),
18870
- /**
18871
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18872
- * code shared copy-on-write across runners. Undefined on macOS.
18873
- */
18874
- sharedBytes: number().optional()
19157
+ var ManagedRuntimeConfigSchema = object({
19158
+ /** WHERE the runtime lives — hub or any agent. */
19159
+ nodeId: string(),
19160
+ /** Closed for v1; 'ollama' is a v2 candidate. */
19161
+ engine: _enum(["llama-cpp"]),
19162
+ model: ManagedModelRefSchema,
19163
+ contextSize: number().int().default(4096),
19164
+ /** 0 = CPU-only. */
19165
+ gpuLayers: number().int().default(0),
19166
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
19167
+ threads: number().int().optional(),
19168
+ /** Concurrent slots. */
19169
+ parallel: number().int().default(1),
19170
+ /** Else lazy: first generate boots it. */
19171
+ autoStart: boolean().default(false),
19172
+ /** 0 = never; frees RAM after quiet periods. */
19173
+ idleStopMinutes: number().int().default(30)
18875
19174
  });
18876
- var AddonInstanceSchema = object({
18877
- addonId: string(),
19175
+ var LlmRuntimeStatusSchema = object({
19176
+ /** Status is ALWAYS node-qualified. */
18878
19177
  nodeId: string(),
18879
- role: _enum(["hub", "worker"]),
18880
- pid: number(),
18881
19178
  state: _enum([
18882
- "starting",
18883
- "running",
18884
- "stopping",
18885
19179
  "stopped",
18886
- "crashed"
18887
- ]),
18888
- uptimeSec: number()
18889
- });
18890
- var NodeProcessSchema = object({
18891
- pid: number(),
18892
- ppid: number(),
18893
- pgid: number(),
18894
- classification: _enum([
18895
- "root",
18896
- "managed",
18897
- "system",
18898
- "ghost"
19180
+ "downloading",
19181
+ "starting",
19182
+ "ready",
19183
+ "crashed",
19184
+ "failed"
18899
19185
  ]),
18900
- /** `$process` addon binding when `managed`, else null. */
18901
- addonId: string().nullable(),
18902
- /** Kernel-reported nodeId when the process is a known agent/worker. */
18903
- nodeId: string().nullable(),
18904
- /** Truncated command line. */
18905
- command: string(),
18906
- cpuPercent: number(),
18907
- memoryRssBytes: number(),
18908
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18909
- uptimeSec: number(),
18910
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18911
- orphaned: boolean()
18912
- });
18913
- var KillProcessInputSchema = object({
18914
- pid: number(),
18915
- /** Force = SIGKILL. Default is SIGTERM. */
18916
- force: boolean().optional()
18917
- });
18918
- var KillProcessResultSchema = object({
18919
- success: boolean(),
18920
- reason: string().optional(),
18921
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18922
- });
18923
- var DumpHeapSnapshotInputSchema = object({
18924
- /** The addon whose runner should dump a heap snapshot. */
18925
- addonId: string() });
18926
- var DumpHeapSnapshotResultSchema = object({
18927
- success: boolean(),
18928
- /** Path of the written .heapsnapshot inside the runner's container/host. */
18929
- path: string().optional(),
18930
- /** Process pid that was signalled. */
18931
19186
  pid: number().optional(),
18932
- reason: string().optional()
19187
+ port: number().optional(),
19188
+ modelPath: string().optional(),
19189
+ modelId: string().optional(),
19190
+ downloadProgress: number().min(0).max(1).optional(),
19191
+ lastError: string().optional(),
19192
+ crashesInWindow: number(),
19193
+ /** Child RSS (sampled best-effort). */
19194
+ memoryBytes: number().optional(),
19195
+ vramBytes: number().optional()
18933
19196
  });
18934
- var SystemMetricsSchema = object({
18935
- cpuPercent: number(),
18936
- memoryPercent: number(),
18937
- memoryUsedMB: number(),
18938
- memoryTotalMB: number(),
18939
- diskPercent: number().optional(),
18940
- temperature: number().optional(),
18941
- gpuPercent: number().optional(),
18942
- gpuMemoryPercent: number().optional()
19197
+ var LlmNodeModelSchema = object({
19198
+ file: string(),
19199
+ sizeBytes: number(),
19200
+ catalogId: string().optional(),
19201
+ installedAt: number().optional()
18943
19202
  });
18944
- method(_void(), SystemResourceSnapshotSchema), method(_void(), SystemResourceSnapshotSchema.nullable()), method(_void(), SystemMetricsSchema), method(object({ dirPath: string() }), DiskSpaceInfoSchema), method(_void(), MetricsGpuInfoSchema.nullable()), method(_void(), number().nullable()), method(object({ pids: array(number()) }), array(PidResourceStatsSchema)), method(_void(), array(AddonInstanceSchema).readonly()), method(object({ addonId: string() }), PidResourceStatsSchema.nullable()), method(_void(), array(NodeProcessSchema).readonly()), method(KillProcessInputSchema, KillProcessResultSchema, {
19203
+ var LlmRuntimeDiskUsageSchema = object({
19204
+ nodeId: string(),
19205
+ modelsBytes: number(),
19206
+ freeBytes: number().optional()
19207
+ });
19208
+ method(LlmGenerateBaseInputSchema.extend({
19209
+ images: array(LlmImageSchema).optional(),
19210
+ runtime: ManagedRuntimeConfigSchema,
19211
+ /** The managed profile's timeout, threaded by the hub provider. */
19212
+ timeoutMs: number().int().positive().optional()
19213
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18945
19214
  kind: "mutation",
18946
19215
  auth: "admin"
18947
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
19216
+ }), method(object({}), _void(), {
18948
19217
  kind: "mutation",
18949
19218
  auth: "admin"
18950
- });
18951
- method(object({
18952
- sourceUrl: string(),
18953
- metadata: ModelConvertMetadataSchema,
18954
- targets: array(ConvertTargetSchema).min(1).readonly(),
18955
- calibrationRef: string().optional(),
18956
- sessionId: string().optional()
18957
- }), ConvertResultSchema, {
19219
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18958
19220
  kind: "mutation",
18959
- auth: "admin",
18960
- timeoutMs: 6e5
18961
- });
18962
- method(object({
18963
- nodeId: string(),
18964
- modelId: string(),
18965
- format: _enum(MODEL_FORMATS),
18966
- entry: ModelCatalogEntrySchema
18967
- }), object({
18968
- ok: boolean(),
18969
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
18970
- sha256: string(),
18971
- bytes: number(),
18972
- /** The target node's modelsDir the artifact landed in. */
18973
- path: string()
18974
- }), {
19221
+ auth: "admin"
19222
+ }), method(object({ file: string() }), _void(), {
18975
19223
  kind: "mutation",
18976
19224
  auth: "admin"
18977
- });
18978
- /**
18979
- * `mqtt-broker` — broker-registry cap.
18980
- *
18981
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
18982
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
18983
- * and (b) the connection details a consumer addon needs to spin up
18984
- * its OWN `mqtt.js` client.
18985
- *
18986
- * Why: pub/sub routing over the system event-bus loses fidelity
18987
- * (callback shape, QoS guarantees, will/retain semantics) and adds
18988
- * refcount bookkeeping that addons would rather own themselves. The
18989
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
18990
- * features anyway — give it the connection config, get out of the way.
18991
- *
18992
- * Consumer flow:
18993
- * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
18994
- * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
18995
- * client.subscribe('zigbee2mqtt/+')
18996
- *
18997
- * Collection mode: multiple brokers (e.g. one local mosquitto + one
18998
- * cloud bridge). The "embedded" entry (when present) is just another
18999
- * broker in the registry — its lifecycle is owned by the addon that
19000
- * spawned it.
19001
- */
19002
- var BrokerKindSchema = _enum(["external", "embedded"]);
19225
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
19003
19226
  /**
19004
- * Broker live-probe status.
19227
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
19228
+ * methods concat-fan across providers; single-row methods route to ONE
19229
+ * provider by the `addonId` in the call input (the notification-output
19230
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
19231
+ * (hub-placed); the cap stays open for future providers.
19005
19232
  *
19006
- * - `connected` last probe completed a clean CONNACK
19007
- * - `disconnected` — no probe has run yet (cold cache)
19008
- * - `auth-failed` CONNACK refused with auth error (RC 4 / 5)
19009
- * - `unreachable` — TCP connect timed out / refused
19010
- * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
19233
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
19234
+ * `apiKey` is a password field providers REDACT it on read and merge on
19235
+ * write; a stored key NEVER round-trips to a client.
19011
19236
  */
19012
- var BrokerStatusSchema$1 = _enum([
19013
- "connected",
19014
- "disconnected",
19015
- "auth-failed",
19016
- "unreachable",
19017
- "tls-error"
19237
+ var LlmProfileKindSchema = _enum([
19238
+ "openai-compatible",
19239
+ "openai",
19240
+ "anthropic",
19241
+ "google",
19242
+ "managed-local"
19018
19243
  ]);
19019
- var BrokerInfoSchema = object({
19244
+ var LlmProfileSchema = object({
19020
19245
  id: string(),
19021
19246
  name: string(),
19022
- url: string(),
19023
- kind: BrokerKindSchema,
19024
- status: BrokerStatusSchema$1,
19025
- latencyMs: number().nullable(),
19026
- error: string().optional(),
19027
- /** Embedded brokers only: number of MQTT clients currently connected. */
19028
- connectedClients: number().int().nonnegative().optional(),
19029
- /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
19030
- lastCheckedAt: number().optional()
19247
+ kind: LlmProfileKindSchema,
19248
+ /** Stamped by the provider — keeps the fanned catalog routable. */
19249
+ addonId: string(),
19250
+ enabled: boolean(),
19251
+ /** Vendor model id, or the managed runtime's loaded model. */
19252
+ model: string(),
19253
+ /** Required for openai-compatible; override for cloud kinds. */
19254
+ baseUrl: string().optional(),
19255
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
19256
+ apiKey: string().optional(),
19257
+ supportsVision: boolean(),
19258
+ temperature: number().min(0).max(2).optional(),
19259
+ maxTokens: number().int().positive().optional(),
19260
+ timeoutMs: number().int().positive().default(6e4),
19261
+ extraHeaders: record(string(), string()).optional(),
19262
+ /** kind === 'managed-local' only (spec §4). */
19263
+ runtime: ManagedRuntimeConfigSchema.optional()
19031
19264
  });
19032
- /**
19033
- * Connection details — what a consumer needs to call
19034
- * `mqtt.connect(url, options)`. We split URL + credentials so the
19035
- * consumer can pass them as `mqtt.connect(url, { username, password })`
19036
- * instead of stuffing creds into the URL (which leaks them into logs).
19037
- */
19038
- var BrokerConnectionDetailsSchema = object({
19039
- url: string(),
19040
- username: string().optional(),
19041
- password: string().optional(),
19042
- /**
19043
- * Suggested prefix for `clientId`. Each consumer should suffix this
19044
- * with its own discriminator (addon id, instance id) so reconnects
19045
- * don't kick each other off (MQTT spec: clientId must be unique per
19046
- * broker).
19047
- */
19048
- clientIdPrefix: string().optional()
19265
+ /** ConfigUISchema tree passed through untyped on the wire (the
19266
+ * notification-output `ConfigSchemaPassthrough` precedent at
19267
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
19268
+ var ConfigSchemaPassthrough$1 = unknown();
19269
+ var LlmProfileKindDescriptorSchema = object({
19270
+ kind: LlmProfileKindSchema,
19271
+ label: string(),
19272
+ icon: string(),
19273
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
19274
+ addonId: string(),
19275
+ configSchema: ConfigSchemaPassthrough$1
19049
19276
  });
19050
- var AddBrokerInputSchema = object({
19051
- name: string().min(1),
19052
- url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
19053
- username: string().optional(),
19054
- password: string().optional(),
19055
- clientIdPrefix: string().optional()
19277
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
19278
+ var LlmDefaultSchema = object({
19279
+ selector: LlmDefaultSelectorSchema,
19280
+ profileId: string()
19056
19281
  });
19057
- var AddBrokerResultSchema = object({ id: string() });
19058
- var IdInputSchema = object({ id: string() });
19059
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
19060
- ok: literal(true),
19061
- latencyMs: number()
19062
- }), object({
19063
- ok: literal(false),
19064
- error: string()
19065
- })]);
19066
- var StartEmbeddedInputSchema = object({
19067
- port: number().int().min(1).max(65535).default(1883),
19068
- /** Allow anonymous connect (no username/password). Default: false. */
19069
- allowAnonymous: boolean().default(false),
19070
- /** Optional shared username/password for clients. */
19071
- username: string().optional(),
19072
- password: string().optional()
19282
+ /** Server-side rollup row getUsage never dumps raw call rows (spec §6). */
19283
+ var LlmUsageRollupSchema = object({
19284
+ day: string(),
19285
+ consumer: string(),
19286
+ profileId: string(),
19287
+ calls: number(),
19288
+ okCalls: number(),
19289
+ errorCalls: number(),
19290
+ inputTokens: number(),
19291
+ outputTokens: number(),
19292
+ avgLatencyMs: number()
19073
19293
  });
19074
- var StartEmbeddedResultSchema = object({
19294
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
19295
+ var ManagedModelCatalogEntrySchema = object({
19075
19296
  id: string(),
19076
- url: string()
19077
- });
19078
- var StatusSchema = object({
19079
- brokerCount: number(),
19080
- embeddedRunning: boolean()
19081
- });
19082
- method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnectionDetailsSchema), method(AddBrokerInputSchema, AddBrokerResultSchema, { kind: "mutation" }), method(IdInputSchema, _void(), { kind: "mutation" }), method(IdInputSchema, TestResultSchema$1, { kind: "mutation" }), method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, { kind: "mutation" }), method(IdInputSchema, _void(), { kind: "mutation" }), method(_void(), StatusSchema);
19083
- var NetworkEndpointSchema = object({
19297
+ label: string(),
19298
+ family: string(),
19299
+ purpose: _enum(["text", "vision"]),
19084
19300
  url: string(),
19085
- hostname: string(),
19086
- port: number(),
19087
- protocol: _enum(["http", "https"])
19301
+ sha256: string(),
19302
+ sizeBytes: number(),
19303
+ quantization: string(),
19304
+ /** Load-time guidance shown in the picker. */
19305
+ minRamBytes: number(),
19306
+ contextSizeDefault: number().int(),
19307
+ /** Vision models: companion projector file. */
19308
+ mmprojUrl: string().optional()
19088
19309
  });
19089
- var NetworkAccessStatusSchema = object({
19090
- connected: boolean(),
19091
- endpoint: NetworkEndpointSchema.nullable(),
19310
+ var LlmRuntimeNodeSchema = object({
19311
+ nodeId: string(),
19312
+ reachable: boolean(),
19313
+ status: LlmRuntimeStatusSchema.optional(),
19314
+ disk: LlmRuntimeDiskUsageSchema.optional(),
19092
19315
  error: string().optional()
19093
19316
  });
19094
- /**
19095
- * Optional, richer endpoint shape returned by providers that expose
19096
- * MORE than one ingress concurrently (Tailscale Ingress with mixed
19097
- * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
19098
- * the originating provider config (mode + sourcePort) so the
19099
- * orchestrator UI can label rows distinctly. Providers that expose only
19100
- * one endpoint just omit `listEndpoints` from their provider impl.
19101
- */
19102
- var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
19103
- /**
19104
- * Stable id within the provider — typically `<mode>-<sourcePort>` so
19105
- * the orchestrator can dedupe across `listEndpoints` polls.
19106
- */
19107
- id: string(),
19108
- /** Operator-facing label (mirrors `MeshEndpoint.label`). */
19109
- label: string(),
19110
- /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
19111
- mode: string().optional(),
19112
- /** Originating local port the ingress fronts (informational). */
19113
- sourcePort: number().optional()
19317
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
19318
+ var ProfileRefInputSchema = object({
19319
+ addonId: string(),
19320
+ profileId: string()
19321
+ });
19322
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
19323
+ kind: "mutation",
19324
+ auth: "admin"
19325
+ }), method(ProfileRefInputSchema, _void(), {
19326
+ kind: "mutation",
19327
+ auth: "admin"
19328
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
19329
+ kind: "mutation",
19330
+ auth: "admin"
19331
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
19332
+ selector: LlmDefaultSelectorSchema,
19333
+ profileId: string().nullable()
19334
+ }), _void(), {
19335
+ kind: "mutation",
19336
+ auth: "admin"
19337
+ }), method(object({
19338
+ since: number().optional(),
19339
+ until: number().optional(),
19340
+ consumer: string().optional(),
19341
+ profileId: string().optional()
19342
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
19343
+ nodeId: string(),
19344
+ model: ManagedModelRefSchema
19345
+ }), _void(), {
19346
+ kind: "mutation",
19347
+ auth: "admin"
19348
+ }), method(object({
19349
+ nodeId: string(),
19350
+ file: string()
19351
+ }), _void(), {
19352
+ kind: "mutation",
19353
+ auth: "admin"
19354
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
19355
+ kind: "mutation",
19356
+ auth: "admin"
19357
+ }), method(ProfileRefInputSchema, _void(), {
19358
+ kind: "mutation",
19359
+ auth: "admin"
19360
+ });
19361
+ var LogLevelSchema = _enum([
19362
+ "debug",
19363
+ "info",
19364
+ "warn",
19365
+ "error"
19366
+ ]);
19367
+ var LogEntrySchema = object({
19368
+ timestamp: date(),
19369
+ level: LogLevelSchema,
19370
+ scope: array(string()),
19371
+ message: string(),
19372
+ meta: record(string(), unknown()).optional(),
19373
+ tags: record(string(), string()).optional()
19114
19374
  });
19115
- method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
19375
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
19376
+ scope: array(string()).optional(),
19377
+ level: LogLevelSchema.optional(),
19378
+ since: date().optional(),
19379
+ until: date().optional(),
19380
+ limit: number().optional(),
19381
+ tags: record(string(), string()).optional()
19382
+ }), array(LogEntrySchema).readonly());
19116
19383
  /**
19117
- * notification-outputcanonical, capability-gated notification delivery.
19384
+ * `login-method`collection cap through which auth addons contribute
19385
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
19386
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
19387
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
19388
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
19389
+ * procedure aggregates them for the unauthenticated login page.
19118
19390
  *
19119
- * Apprise-derived model (see
19120
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
19121
- * callers emit ONE canonical `Notification`; each provider declares a
19122
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
19123
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
19124
- * message to what the kind supports — callers never special-case a service.
19391
+ * A contribution is a discriminated union on `kind`:
19125
19392
  *
19126
- * DESIGN DECISIONS (locked):
19127
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
19128
- * `setTargetEnabled`), each provider persisting via the `settings-store`
19129
- * cap. Rationale: the admin UI needs one uniform surface across the
19130
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
19131
- * alternative would fork the UI per addon and cannot host the
19132
- * discovery→adopt flow.
19133
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
19134
- * the generated cap-mount auto-`concatCollection`-fans them across every
19135
- * registered provider (notifiers addon + HA addon) so one catalog is
19136
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
19137
- * `addonId` the generated collection router extracts from the call input.
19138
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
19139
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
19140
- * `storage` / `storage-provider` / `recording` caps over the same path. No
19141
- * base64 fallback needed.
19393
+ * - `redirect` a declarative button. The login page renders a generic
19394
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
19395
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
19396
+ * ZERO shell-side JS. A future SSO addon plugs in the same way the
19397
+ * login page needs NO change.
19142
19398
  *
19143
- * TODO (deferred, closed-set change separate decision): add
19144
- * `providerKind: 'notify'` so notification providers surface on the unified
19145
- * admin "Integrations" page.
19146
- */
19147
- /**
19148
- * Zentik-derived typed-media enum — the superset across every kind. Each
19149
- * adapter picks what it supports and the degrade engine filters the rest.
19150
- */
19151
- var AttachmentMediaTypeSchema = _enum([
19152
- "image",
19153
- "video",
19154
- "gif",
19155
- "audio",
19156
- "icon"
19157
- ]);
19158
- /**
19159
- * A single attachment. Exactly one of `url` (remote source, most adapters
19160
- * prefer this) or `bytes` (inline source; required for Pushover-style
19161
- * bytes-only kinds) MUST be present the degrade engine expresses a
19162
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
19399
+ * - `widget` a Module-Federation widget the login page mounts (via
19400
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
19401
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
19402
+ * mechanism kept for future use; no shipped addon uses it on the login
19403
+ * page (the passkey ceremony below runs natively in the shell instead).
19404
+ *
19405
+ * - `passkey` a declarative WebAuthn ceremony the shell renders
19406
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
19407
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
19408
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
19409
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
19410
+ * fetching any remote code pre-auth. Contribution stays unconditional —
19411
+ * enrollment state is never leaked pre-auth; visibility is a shell
19412
+ * decision.
19413
+ *
19414
+ * Every contribution carries a `stage`:
19415
+ * - `primary` — shown on the first credentials screen (OIDC /
19416
+ * magic-link buttons; a future usernameless passkey).
19417
+ * - `second-factor` — shown AFTER the password leg, gated on the
19418
+ * returned `factors` (passkey-as-2FA today).
19419
+ *
19420
+ * `mount: skip` — the cap is read server-side by the core auth router
19421
+ * (`registry.getCollection('login-method')`), never mounted as its own
19422
+ * tRPC router.
19163
19423
  */
19164
- var AttachmentSchema = object({
19165
- mediaType: AttachmentMediaTypeSchema,
19166
- url: string().optional(),
19167
- bytes: _instanceof(Uint8Array).optional(),
19168
- mime: string().optional(),
19169
- name: string().optional()
19170
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
19171
- var NotificationFormatSchema = _enum([
19172
- "text",
19173
- "markdown",
19174
- "html"
19424
+ /** When a login method renders in the two-phase login flow. */
19425
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
19426
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
19427
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
19428
+ object({
19429
+ kind: literal("redirect"),
19430
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
19431
+ id: string(),
19432
+ /** Operator-facing button label. */
19433
+ label: string(),
19434
+ /** lucide-react icon name. */
19435
+ icon: string().optional(),
19436
+ /** Addon-owned HTTP route the button navigates to (GET). */
19437
+ startUrl: string(),
19438
+ stage: LoginStageEnum
19439
+ }),
19440
+ object({
19441
+ kind: literal("widget"),
19442
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
19443
+ id: string(),
19444
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
19445
+ addonId: string(),
19446
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
19447
+ bundle: string(),
19448
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
19449
+ remote: WidgetRemoteSchema,
19450
+ stage: LoginStageEnum
19451
+ }),
19452
+ object({
19453
+ kind: literal("passkey"),
19454
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
19455
+ id: string(),
19456
+ /** Operator-facing button label. */
19457
+ label: string(),
19458
+ stage: LoginStageEnum,
19459
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
19460
+ rpId: string(),
19461
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
19462
+ origin: string().nullable()
19463
+ })
19175
19464
  ]);
19176
- /** A single tap-through action button. */
19177
- var NotificationActionSchema = object({
19178
- id: string(),
19179
- label: string(),
19180
- url: string().optional()
19465
+ method(_void(), array(LoginMethodContributionSchema).readonly());
19466
+ var CpuBreakdownSchema = object({
19467
+ total: number(),
19468
+ user: number(),
19469
+ system: number(),
19470
+ irq: number(),
19471
+ nice: number(),
19472
+ loadAvg: tuple([
19473
+ number(),
19474
+ number(),
19475
+ number()
19476
+ ]),
19477
+ cores: number()
19181
19478
  });
19182
- /**
19183
- * The canonical notification. `body` is the only hard field (Apprise model).
19184
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
19185
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
19186
- * the adapter maps this ordinal onto its native level. `level?` is an
19187
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
19188
- * `priority` for that one target.
19189
- */
19190
- var NotificationSchema = object({
19191
- body: string(),
19192
- title: string().optional(),
19193
- format: NotificationFormatSchema.default("text"),
19194
- priority: number().int().min(1).max(5).default(3),
19195
- level: string().optional(),
19196
- attachments: array(AttachmentSchema).optional(),
19197
- clickUrl: string().optional(),
19198
- actions: array(NotificationActionSchema).optional(),
19199
- sound: string().optional(),
19200
- ttl: number().optional(),
19201
- tag: string().optional(),
19202
- deviceId: number().optional(),
19203
- eventId: string().optional(),
19204
- metadata: record(string(), unknown()).optional()
19479
+ var MemoryInfoSchema = object({
19480
+ percent: number(),
19481
+ totalBytes: number(),
19482
+ usedBytes: number(),
19483
+ availableBytes: number(),
19484
+ swapUsedBytes: number(),
19485
+ swapTotalBytes: number()
19486
+ });
19487
+ var DiskIoSnapshotSchema = object({
19488
+ readBytes: number(),
19489
+ writeBytes: number(),
19490
+ readOps: number(),
19491
+ writeOps: number(),
19492
+ timestampMs: number()
19493
+ });
19494
+ var NetworkIoSnapshotSchema = object({
19495
+ rxBytes: number(),
19496
+ txBytes: number(),
19497
+ rxPackets: number(),
19498
+ txPackets: number(),
19499
+ rxErrors: number(),
19500
+ txErrors: number(),
19501
+ timestampMs: number()
19502
+ });
19503
+ var MetricsGpuInfoSchema = object({
19504
+ utilization: number(),
19505
+ model: string(),
19506
+ memoryUsedBytes: number(),
19507
+ memoryTotalBytes: number(),
19508
+ temperature: number().nullable()
19509
+ });
19510
+ var ProcessResourceInfoSchema = object({
19511
+ openFds: number(),
19512
+ threadCount: number(),
19513
+ activeHandles: number(),
19514
+ activeRequests: number()
19205
19515
  });
19206
- /** One declared native severity/priority level for a kind. */
19207
- var TargetKindLevelSchema = object({
19208
- id: string(),
19209
- label: string(),
19210
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
19211
- ordinal: number().int().min(1).max(5).nullable(),
19212
- flags: object({
19213
- critical: boolean().optional(),
19214
- silent: boolean().optional(),
19215
- noPush: boolean().optional()
19216
- }).optional(),
19217
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
19218
- requires: array(string()).optional(),
19219
- description: string().optional()
19516
+ var PressureAvgsSchema = object({
19517
+ avg10: number(),
19518
+ avg60: number(),
19519
+ avg300: number()
19220
19520
  });
19221
- /** The full capability block consulted before dispatch. */
19222
- var TargetKindCapsSchema = object({
19223
- attachments: object({
19224
- mediaTypes: array(AttachmentMediaTypeSchema),
19225
- mode: _enum([
19226
- "url",
19227
- "bytes",
19228
- "both"
19229
- ]),
19230
- max: number().int().nonnegative(),
19231
- maxBytes: number().int().positive().optional()
19521
+ var PressureInfoSchema = object({
19522
+ some: PressureAvgsSchema,
19523
+ full: PressureAvgsSchema.nullable()
19524
+ });
19525
+ var SystemResourceSnapshotSchema = object({
19526
+ cpu: CpuBreakdownSchema,
19527
+ memory: MemoryInfoSchema,
19528
+ gpu: MetricsGpuInfoSchema.nullable(),
19529
+ network: NetworkIoSnapshotSchema,
19530
+ disk: DiskIoSnapshotSchema,
19531
+ pressure: object({
19532
+ cpu: PressureInfoSchema.nullable(),
19533
+ memory: PressureInfoSchema.nullable(),
19534
+ io: PressureInfoSchema.nullable()
19232
19535
  }),
19233
- /** Max action buttons (0 = none). */
19234
- actions: number().int().nonnegative(),
19235
- levels: array(TargetKindLevelSchema),
19236
- format: array(NotificationFormatSchema),
19237
- clickUrl: boolean(),
19238
- sound: boolean(),
19239
- ttl: boolean(),
19240
- bodyMaxLen: number().int().positive()
19536
+ process: ProcessResourceInfoSchema,
19537
+ cpuTemperature: number().nullable(),
19538
+ timestampMs: number()
19241
19539
  });
19242
- /**
19243
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
19244
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
19245
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
19246
- * the union is large and not meant for runtime validation here; the exported
19247
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
19248
- */
19249
- var ConfigSchemaPassthrough = unknown();
19250
- var TargetKindSchema = object({
19251
- kind: string(),
19252
- label: string(),
19253
- icon: string(),
19254
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
19255
- addonId: string(),
19256
- configSchema: ConfigSchemaPassthrough,
19257
- supportsDiscovery: boolean(),
19258
- caps: TargetKindCapsSchema
19540
+ var DiskSpaceInfoSchema = object({
19541
+ path: string(),
19542
+ totalBytes: number(),
19543
+ usedBytes: number(),
19544
+ availableBytes: number(),
19545
+ percent: number()
19259
19546
  });
19260
- /**
19261
- * A persisted target. `config` holds secrets; providers REDACT secret fields
19262
- * (return a presence marker only) when serving `listTargets` — never
19263
- * round-trip a stored secret to the UI.
19264
- */
19265
- var TargetSchema = object({
19266
- id: string(),
19267
- name: string(),
19268
- kind: string(),
19547
+ var PidResourceStatsSchema = object({
19548
+ pid: number(),
19549
+ cpu: number(),
19550
+ memory: number(),
19551
+ /**
19552
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
19553
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
19554
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
19555
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
19556
+ * Undefined where /proc is unavailable (e.g. macOS).
19557
+ */
19558
+ privateBytes: number().optional(),
19559
+ /**
19560
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
19561
+ * code shared copy-on-write across runners. Undefined on macOS.
19562
+ */
19563
+ sharedBytes: number().optional()
19564
+ });
19565
+ var AddonInstanceSchema = object({
19269
19566
  addonId: string(),
19270
- enabled: boolean(),
19271
- config: record(string(), unknown())
19567
+ nodeId: string(),
19568
+ role: _enum(["hub", "worker"]),
19569
+ pid: number(),
19570
+ state: _enum([
19571
+ "starting",
19572
+ "running",
19573
+ "stopping",
19574
+ "stopped",
19575
+ "crashed"
19576
+ ]),
19577
+ uptimeSec: number()
19272
19578
  });
19273
- /** A discovery-surfaced candidate (config is partial + non-secret). */
19274
- var DiscoveredTargetSchema = object({
19275
- kind: string(),
19276
- suggestedName: string(),
19277
- config: record(string(), unknown())
19579
+ var NodeProcessSchema = object({
19580
+ pid: number(),
19581
+ ppid: number(),
19582
+ pgid: number(),
19583
+ classification: _enum([
19584
+ "root",
19585
+ "managed",
19586
+ "system",
19587
+ "ghost"
19588
+ ]),
19589
+ /** `$process` addon binding when `managed`, else null. */
19590
+ addonId: string().nullable(),
19591
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
19592
+ nodeId: string().nullable(),
19593
+ /** Truncated command line. */
19594
+ command: string(),
19595
+ cpuPercent: number(),
19596
+ memoryRssBytes: number(),
19597
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
19598
+ uptimeSec: number(),
19599
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
19600
+ orphaned: boolean()
19278
19601
  });
19279
- /** The degrade engine's report — what was resolved / dropped / degraded. */
19280
- var RenderedAsSchema = object({
19281
- level: string(),
19282
- format: NotificationFormatSchema,
19283
- attachmentsSent: number().int().nonnegative(),
19284
- actionsSent: number().int().nonnegative(),
19285
- truncated: boolean(),
19286
- dropped: array(string())
19602
+ var KillProcessInputSchema = object({
19603
+ pid: number(),
19604
+ /** Force = SIGKILL. Default is SIGTERM. */
19605
+ force: boolean().optional()
19287
19606
  });
19288
- var SendResultSchema = object({
19607
+ var KillProcessResultSchema = object({
19289
19608
  success: boolean(),
19290
- error: string().optional(),
19291
- renderedAs: RenderedAsSchema.optional()
19609
+ reason: string().optional(),
19610
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
19611
+ });
19612
+ var DumpHeapSnapshotInputSchema = object({
19613
+ /** The addon whose runner should dump a heap snapshot. */
19614
+ addonId: string() });
19615
+ var DumpHeapSnapshotResultSchema = object({
19616
+ success: boolean(),
19617
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
19618
+ path: string().optional(),
19619
+ /** Process pid that was signalled. */
19620
+ pid: number().optional(),
19621
+ reason: string().optional()
19622
+ });
19623
+ var SystemMetricsSchema = object({
19624
+ cpuPercent: number(),
19625
+ memoryPercent: number(),
19626
+ memoryUsedMB: number(),
19627
+ memoryTotalMB: number(),
19628
+ diskPercent: number().optional(),
19629
+ temperature: number().optional(),
19630
+ gpuPercent: number().optional(),
19631
+ gpuMemoryPercent: number().optional()
19632
+ });
19633
+ method(_void(), SystemResourceSnapshotSchema), method(_void(), SystemResourceSnapshotSchema.nullable()), method(_void(), SystemMetricsSchema), method(object({ dirPath: string() }), DiskSpaceInfoSchema), method(_void(), MetricsGpuInfoSchema.nullable()), method(_void(), number().nullable()), method(object({ pids: array(number()) }), array(PidResourceStatsSchema)), method(_void(), array(AddonInstanceSchema).readonly()), method(object({ addonId: string() }), PidResourceStatsSchema.nullable()), method(_void(), array(NodeProcessSchema).readonly()), method(KillProcessInputSchema, KillProcessResultSchema, {
19634
+ kind: "mutation",
19635
+ auth: "admin"
19636
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
19637
+ kind: "mutation",
19638
+ auth: "admin"
19639
+ });
19640
+ method(object({
19641
+ sourceUrl: string(),
19642
+ metadata: ModelConvertMetadataSchema,
19643
+ targets: array(ConvertTargetSchema).min(1).readonly(),
19644
+ calibrationRef: string().optional(),
19645
+ sessionId: string().optional()
19646
+ }), ConvertResultSchema, {
19647
+ kind: "mutation",
19648
+ auth: "admin",
19649
+ timeoutMs: 6e5
19650
+ });
19651
+ method(object({
19652
+ nodeId: string(),
19653
+ modelId: string(),
19654
+ format: _enum(MODEL_FORMATS),
19655
+ entry: ModelCatalogEntrySchema
19656
+ }), object({
19657
+ ok: boolean(),
19658
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
19659
+ sha256: string(),
19660
+ bytes: number(),
19661
+ /** The target node's modelsDir the artifact landed in. */
19662
+ path: string()
19663
+ }), {
19664
+ kind: "mutation",
19665
+ auth: "admin"
19292
19666
  });
19293
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
19294
- var TestResultSchema = SendResultSchema;
19295
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
19296
- kind: string(),
19297
- config: record(string(), unknown()).optional()
19298
- }), array(DiscoveredTargetSchema)), method(object({
19299
- targetId: string(),
19300
- notification: NotificationSchema
19301
- }), SendResultSchema, { kind: "mutation" }), method(object({
19302
- targetId: string(),
19303
- sample: NotificationSchema.optional()
19304
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
19305
- targetId: string(),
19306
- enabled: boolean()
19307
- }), _void(), { kind: "mutation" });
19308
19667
  /**
19309
- * notification-rulesthe Notification Center rule surface (P1 core).
19310
- *
19311
- * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
19312
- * (operator decisions D-1/D-2/D-3 are binding):
19668
+ * `mqtt-broker`broker-registry cap.
19313
19669
  *
19314
- * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
19315
- * `notification-center` module), hooked on the durable persistence
19316
- * moments (object-event insert, TrackCloser.closeExpired) with a
19317
- * persisted outbox + retry — never the lossy telemetry bus (D8).
19318
- * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
19319
- * FIRST persisted detection matching the conditions (per-track dedup,
19320
- * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
19321
- * `delivery: 'track-end'` evaluates the finalized track record at close.
19322
- * - DISPATCH stays behind `notification-output` (rules reference targets
19323
- * by id; per-backend params are a passthrough blob capped by the
19324
- * target kind's own caps/degrade engine).
19670
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
19671
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
19672
+ * and (b) the connection details a consumer addon needs to spin up
19673
+ * its OWN `mqtt.js` client.
19325
19674
  *
19326
- * P1 scope: admin-authored rules only (`createdBy` stamped from the
19327
- * server-injected caller identity the first `caller: 'required'`
19328
- * adopter). The P1 condition subset is: devices, classes(+exclude),
19329
- * minConfidence, admin zones (any/all + exclude), weekly schedule
19330
- * windows, and the optional label/identity/plate matchers. User rules,
19331
- * private zones, per-recipient fan-out and the wider condition table are
19332
- * P2+ (see spec §7).
19675
+ * Why: pub/sub routing over the system event-bus loses fidelity
19676
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
19677
+ * refcount bookkeeping that addons would rather own themselves. The
19678
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
19679
+ * features anyway — give it the connection config, get out of the way.
19333
19680
  *
19334
- * All schemas here are the single source of truth — `NcRule` etc. are
19335
- * `z.infer` exports; no duplicate interfaces (the advanced-notifier
19336
- * schema/interface drift is explicitly not repeated).
19681
+ * Consumer flow:
19682
+ * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
19683
+ * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
19684
+ * client.subscribe('zigbee2mqtt/+')
19685
+ *
19686
+ * Collection mode: multiple brokers (e.g. one local mosquitto + one
19687
+ * cloud bridge). The "embedded" entry (when present) is just another
19688
+ * broker in the registry — its lifecycle is owned by the addon that
19689
+ * spawned it.
19337
19690
  */
19691
+ var BrokerKindSchema = _enum(["external", "embedded"]);
19338
19692
  /**
19339
- * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
19340
- * The value maps 1:1 onto the evaluated record kind:
19341
- * - `immediate` ↔ object-event persist (lowest-latency detection burst)
19342
- * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
19343
- * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
19344
- * change of a LINKED device, one row per linked camera)
19345
- * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
19346
- * delivery / pick-up)
19693
+ * Broker live-probe status.
19347
19694
  *
19348
- * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
19349
- * `package-event` are pure trigger kinds (no urgency dimension). Extending
19350
- * this one field keeps the schema additive a rule still declares exactly
19351
- * one trigger.
19695
+ * - `connected` last probe completed a clean CONNACK
19696
+ * - `disconnected` no probe has run yet (cold cache)
19697
+ * - `auth-failed` CONNACK refused with auth error (RC 4 / 5)
19698
+ * - `unreachable` — TCP connect timed out / refused
19699
+ * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
19352
19700
  */
19353
- var NcDeliverySchema = _enum([
19354
- "immediate",
19355
- "track-end",
19356
- "device-event",
19357
- "package-event"
19701
+ var BrokerStatusSchema$1 = _enum([
19702
+ "connected",
19703
+ "disconnected",
19704
+ "auth-failed",
19705
+ "unreachable",
19706
+ "tls-error"
19358
19707
  ]);
19359
- /** Weekly schedule — OR of windows; absence on the rule = always active. */
19360
- var NcScheduleSchema = object({
19361
- windows: array(object({
19362
- /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
19363
- days: array(number().int().min(0).max(6)).min(1),
19364
- startMinute: number().int().min(0).max(1439),
19365
- endMinute: number().int().min(0).max(1439)
19366
- })).min(1),
19367
- /** IANA timezone; default = hub host timezone. */
19368
- timezone: string().optional(),
19369
- /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
19370
- invert: boolean().optional()
19371
- });
19372
- /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
19373
- var NcPlateMatcherSchema = object({
19374
- values: array(string().min(1)).min(1),
19375
- /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
19376
- maxDistance: number().int().min(0).max(3).default(1)
19377
- });
19378
- /**
19379
- * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
19380
- * occupancy edge for a device — optionally narrowed to a single admin
19381
- * `zoneId` and/or object `className`. `op` selects the edge/threshold:
19382
- * - `became-occupied` (default) — count crossed 0 → ≥ `count`
19383
- * - `became-free` — count crossed ≥ `count` → below it
19384
- * - `>=` / `<=` — count is at/over or at/under `count`
19385
- * `sustainSeconds` requires the condition hold continuously that long
19386
- * before firing (debounces flicker; 0 = fire on the first matching edge).
19387
- * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
19388
- * the condition never matches. Confirmed edge-state survives addon restarts
19389
- * (declared SQLite collection, reseeded on boot).
19390
- */
19391
- var NcOccupancyConditionSchema = object({
19392
- /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
19393
- zoneId: string().optional(),
19394
- /** Object class to count; absent = any class. */
19395
- className: string().optional(),
19396
- op: _enum([
19397
- "became-occupied",
19398
- "became-free",
19399
- ">=",
19400
- "<="
19401
- ]).default("became-occupied"),
19402
- count: number().int().min(0).default(1),
19403
- sustainSeconds: number().int().min(0).max(3600).default(15)
19404
- });
19405
- /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
19406
- var NcZoneConditionSchema = object({
19407
- ids: array(string().min(1)).min(1),
19408
- /** Quantifier over `ids` — at least one / every one visited. */
19409
- match: _enum(["any", "all"]).default("any")
19410
- });
19411
- /**
19412
- * The P1 condition set — a flat AND of groups; absent group = pass;
19413
- * membership lists are OR within the list (spec §2.3).
19414
- */
19415
- var NcConditionsSchema = object({
19416
- /** Device scope — absent = all devices. */
19417
- devices: array(number()).optional(),
19418
- /** Detector class names (any overlap with the record's class set). */
19419
- classes: array(string().min(1)).optional(),
19420
- /** Veto classes — any overlap fails the rule. */
19421
- classesExclude: array(string().min(1)).optional(),
19422
- /** Minimum detection confidence 0–1 (fails when the record has none). */
19423
- minConfidence: number().min(0).max(1).optional(),
19424
- /** Admin zone membership over event `zones` / track `zonesVisited`. */
19425
- zones: NcZoneConditionSchema.optional(),
19426
- /** Veto zones — any hit fails the rule. */
19427
- zonesExclude: array(string().min(1)).optional(),
19428
- /**
19429
- * Exact (case-insensitive) match on the record's collapsed `label`
19430
- * (identity name / plate text / subclass).
19431
- */
19432
- labelEquals: array(string().min(1)).optional(),
19433
- /**
19434
- * Identity matcher. P1 boundary: matched against the record's collapsed
19435
- * `label` (the identity display name propagated by the face pipeline) —
19436
- * identity-ID matching rides in P2 when identity ids reach the record.
19437
- */
19438
- identities: array(string().min(1)).optional(),
19439
- /** Fuzzy plate matcher against the record's `label` (plate text). */
19440
- plates: NcPlateMatcherSchema.optional(),
19441
- /**
19442
- * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
19443
- * Same P1 boundary: matched against the record's collapsed `label` (the
19444
- * identity display name). A record with NO label passes (nothing to
19445
- * exclude), unlike the include variant which fails on an absent label.
19446
- */
19447
- identitiesExclude: array(string().min(1)).optional(),
19448
- /**
19449
- * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
19450
- * TRACK-END only: importance is scored at track close, so it does not exist
19451
- * at immediate / object-event evaluation time (see catalog `appliesTo`). At
19452
- * close the value is threaded via the close-time info (the `Track` clone is
19453
- * captured before the DB row is updated, so it would otherwise read stale).
19454
- * Fails when the record carries no importance (never guess quality — the
19455
- * `minConfidence` precedent). MVP cut: a single scalar threshold.
19456
- */
19457
- minImportance: number().min(0).max(1).optional(),
19458
- /**
19459
- * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
19460
- * TRACK-END only: an `immediate` / object-event subject has no closed
19461
- * lifespan, so a dwell condition never matches immediate delivery
19462
- * (documented choice — the object-event record carries no `firstSeen`,
19463
- * so dwell cannot be computed from what the subject actually carries).
19464
- */
19465
- minDwellSeconds: number().min(0).optional(),
19466
- /**
19467
- * Detection provenance filter. `any` (default / absent) matches every
19468
- * source; otherwise the subject's source must equal it. Legacy records
19469
- * with no stamped source are treated as `pipeline`. The union spans both
19470
- * record kinds — object events carry `pipeline` | `onboard`, synthetic
19471
- * tracks carry `sensor`.
19472
- */
19473
- source: _enum([
19474
- "pipeline",
19475
- "onboard",
19476
- "sensor",
19477
- "any"
19478
- ]).optional(),
19479
- /**
19480
- * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
19481
- * detector `minConfidence` (that gates the object-detection score; this
19482
- * gates the recognition/OCR match score). Fails when the subject carries
19483
- * no label-match confidence (never guess). TRACK-END only: the confidence
19484
- * lives on the recognition result and reaches the subject at track close.
19485
- *
19486
- * What it measures precisely (plumbed at track close — the closer threads
19487
- * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
19488
- * `importance`): the BEST recognition match confidence observed for the
19489
- * label the track carries at close — for a face, the peak cosine similarity
19490
- * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
19491
- * for a plate, the peak OCR read score of the best-held plate
19492
- * (`plateText.confidence`). When BOTH a face and a plate were recognized on
19493
- * one track the higher of the two is used. A track that ended with no
19494
- * confident identity/plate match carries no value, so the condition fails
19495
- * closed for it (an un-recognized subject).
19496
- */
19497
- minLabelConfidence: number().min(0).max(1).optional(),
19498
- /**
19499
- * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
19500
- * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
19501
- * against the token carried on the device-event subject (extracted from the
19502
- * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
19503
- * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
19504
- * eventType, so gate those with {@link sensorKinds} instead.
19505
- */
19506
- eventTypeTokens: array(string().min(1)).optional(),
19507
- /**
19508
- * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
19509
- * `contact`, `button`, `device-event`) — matched against the persisted
19510
- * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
19511
- */
19512
- sensorKinds: array(string().min(1)).optional(),
19513
- /**
19514
- * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
19515
- * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
19516
- * when the subject's phase does not match (a subject always carries a phase
19517
- * on the package-event trigger).
19518
- */
19519
- packagePhase: _enum([
19520
- "delivered",
19521
- "picked-up",
19522
- "both"
19523
- ]).optional(),
19524
- /**
19525
- * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
19526
- * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
19527
- * listed polygon (ZoneEngine membership semantics). Evaluated only when
19528
- * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
19529
- */
19530
- customZones: array(MaskPolygonShapeSchema).optional(),
19531
- /**
19532
- * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
19533
- * (optionally zone/class-scoped) occupancy count crosses the configured
19534
- * threshold and holds for `sustainSeconds`. Fail-closed on missing
19535
- * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
19536
- */
19537
- occupancy: NcOccupancyConditionSchema.optional()
19538
- });
19539
- /** One delivery target: a `notification-output` Target ref + passthrough params. */
19540
- var NcRuleTargetSchema = object({
19541
- /** `notification-output` Target id. */
19542
- targetId: string().min(1),
19543
- /**
19544
- * Per-backend passthrough. Recognized keys are mapped onto the canonical
19545
- * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
19546
- * degrade engine drops what the backend can't render.
19547
- */
19548
- params: record(string(), unknown()).optional()
19708
+ var BrokerInfoSchema = object({
19709
+ id: string(),
19710
+ name: string(),
19711
+ url: string(),
19712
+ kind: BrokerKindSchema,
19713
+ status: BrokerStatusSchema$1,
19714
+ latencyMs: number().nullable(),
19715
+ error: string().optional(),
19716
+ /** Embedded brokers only: number of MQTT clients currently connected. */
19717
+ connectedClients: number().int().nonnegative().optional(),
19718
+ /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
19719
+ lastCheckedAt: number().optional()
19549
19720
  });
19550
19721
  /**
19551
- * Media attachment policy (P1 still-image subset).
19552
- * - `best` the best AVAILABLE subject image at dispatch time (D-3).
19553
- * - `best-matching` the media that explains WHY the rule fired: a rule
19554
- * matched on identities attaches the subject's `faceCrop`, one matched on
19555
- * plates attaches the `plateCrop`; a rule with no identity/plate condition
19556
- * (or when the specific crop is missing) degrades to `best`, then
19557
- * `keyFrame`, then no attachment — never delaying the send. The matched
19558
- * condition summary is frozen on the outbox row at enqueue (like the rule
19559
- * name), so the choice never drifts from the record that fired it.
19560
- * - `keyFrame` — the clean scene frame (no subject box).
19561
- * - `none` — no attachment.
19722
+ * Connection details what a consumer needs to call
19723
+ * `mqtt.connect(url, options)`. We split URL + credentials so the
19724
+ * consumer can pass them as `mqtt.connect(url, { username, password })`
19725
+ * instead of stuffing creds into the URL (which leaks them into logs).
19562
19726
  */
19563
- var NcMediaPolicySchema = object({ attach: _enum([
19564
- "best",
19565
- "best-matching",
19566
- "keyFrame",
19567
- "none"
19568
- ]).default("best") });
19569
- /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
19570
- var NcThrottleSchema = object({
19571
- cooldownSec: number().int().min(0).max(86400).default(60),
19572
- /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
19573
- scope: _enum(["rule", "rule-device"]).default("rule-device")
19574
- });
19575
- /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
19576
- var NcRuleInputSchema = object({
19577
- name: string().min(1).max(200),
19578
- enabled: boolean().default(true),
19579
- delivery: NcDeliverySchema,
19580
- conditions: NcConditionsSchema.default({}),
19581
- schedule: NcScheduleSchema.optional(),
19582
- targets: array(NcRuleTargetSchema).min(1),
19583
- media: NcMediaPolicySchema.default({ attach: "best" }),
19584
- throttle: NcThrottleSchema.default({
19585
- cooldownSec: 60,
19586
- scope: "rule-device"
19587
- }),
19588
- /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
19589
- template: object({
19590
- title: string().max(500).optional(),
19591
- body: string().max(2e3).optional()
19592
- }).optional(),
19593
- /** Canonical notification priority ordinal (1..5); per-target overridable. */
19594
- priority: number().int().min(1).max(5).default(3),
19727
+ var BrokerConnectionDetailsSchema = object({
19728
+ url: string(),
19729
+ username: string().optional(),
19730
+ password: string().optional(),
19595
19731
  /**
19596
- * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
19597
- * behaviour, visible to all, read-only in the viewer). Present = personal
19598
- * rule owned by this userId. Server-stamped; never trusted from a client.
19732
+ * Suggested prefix for `clientId`. Each consumer should suffix this
19733
+ * with its own discriminator (addon id, instance id) so reconnects
19734
+ * don't kick each other off (MQTT spec: clientId must be unique per
19735
+ * broker).
19599
19736
  */
19600
- ownerUserId: string().optional()
19737
+ clientIdPrefix: string().optional()
19738
+ });
19739
+ var AddBrokerInputSchema = object({
19740
+ name: string().min(1),
19741
+ url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
19742
+ username: string().optional(),
19743
+ password: string().optional(),
19744
+ clientIdPrefix: string().optional()
19745
+ });
19746
+ var AddBrokerResultSchema = object({ id: string() });
19747
+ var IdInputSchema = object({ id: string() });
19748
+ var TestResultSchema$1 = discriminatedUnion("ok", [object({
19749
+ ok: literal(true),
19750
+ latencyMs: number()
19751
+ }), object({
19752
+ ok: literal(false),
19753
+ error: string()
19754
+ })]);
19755
+ var StartEmbeddedInputSchema = object({
19756
+ port: number().int().min(1).max(65535).default(1883),
19757
+ /** Allow anonymous connect (no username/password). Default: false. */
19758
+ allowAnonymous: boolean().default(false),
19759
+ /** Optional shared username/password for clients. */
19760
+ username: string().optional(),
19761
+ password: string().optional()
19762
+ });
19763
+ var StartEmbeddedResultSchema = object({
19764
+ id: string(),
19765
+ url: string()
19766
+ });
19767
+ var StatusSchema = object({
19768
+ brokerCount: number(),
19769
+ embeddedRunning: boolean()
19770
+ });
19771
+ method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnectionDetailsSchema), method(AddBrokerInputSchema, AddBrokerResultSchema, { kind: "mutation" }), method(IdInputSchema, _void(), { kind: "mutation" }), method(IdInputSchema, TestResultSchema$1, { kind: "mutation" }), method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, { kind: "mutation" }), method(IdInputSchema, _void(), { kind: "mutation" }), method(_void(), StatusSchema);
19772
+ var NetworkEndpointSchema = object({
19773
+ url: string(),
19774
+ hostname: string(),
19775
+ port: number(),
19776
+ protocol: _enum(["http", "https"])
19777
+ });
19778
+ var NetworkAccessStatusSchema = object({
19779
+ connected: boolean(),
19780
+ endpoint: NetworkEndpointSchema.nullable(),
19781
+ error: string().optional()
19601
19782
  });
19602
19783
  /**
19603
- * Partial patch for `updateRule` any subset of the input fields, plus the
19604
- * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
19605
- * NOT a client-authored input field (it lives on the persisted rule, not the
19606
- * input), so it is added here explicitly to let the store's per-target opt-out
19607
- * toggle round-trip through the shared `update` path. Viewer opt-out mutations
19608
- * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
19609
- * `updateRule` patch.
19784
+ * Optional, richer endpoint shape returned by providers that expose
19785
+ * MORE than one ingress concurrently (Tailscale Ingress with mixed
19786
+ * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
19787
+ * the originating provider config (mode + sourcePort) so the
19788
+ * orchestrator UI can label rows distinctly. Providers that expose only
19789
+ * one endpoint just omit `listEndpoints` from their provider impl.
19610
19790
  */
19611
- var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
19612
- /** A persisted rule. */
19613
- var NcRuleSchema = NcRuleInputSchema.extend({
19614
- id: string(),
19615
- /** userId of the admin who created the rule (server-stamped caller). */
19616
- createdBy: string(),
19617
- createdAt: number(),
19618
- updatedAt: number(),
19791
+ var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
19619
19792
  /**
19620
- * Per-target opt-out set. A targetId here is suppressed for THIS rule at
19621
- * send time. Only a target's OWNER may add/remove its id (server-checked
19622
- * in `nc.setRuleTargetEnabled`). Defaults to empty.
19793
+ * Stable id within the provider typically `<mode>-<sourcePort>` so
19794
+ * the orchestrator can dedupe across `listEndpoints` polls.
19623
19795
  */
19624
- disabledTargetIds: array(string()).default([])
19625
- });
19626
- var NcTestResultSchema = object({
19627
- recordId: string(),
19628
- recordKind: _enum([
19629
- "object-event",
19630
- "track",
19631
- "device-event",
19632
- "package-event"
19633
- ]),
19634
- deviceId: number(),
19635
- timestamp: number(),
19636
- wouldFire: boolean(),
19637
- /** Condition id that failed (first failing group), when `wouldFire` is false. */
19638
- failedCondition: string().optional(),
19639
- className: string().optional(),
19640
- label: string().optional()
19796
+ id: string(),
19797
+ /** Operator-facing label (mirrors `MeshEndpoint.label`). */
19798
+ label: string(),
19799
+ /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
19800
+ mode: string().optional(),
19801
+ /** Originating local port the ingress fronts (informational). */
19802
+ sourcePort: number().optional()
19641
19803
  });
19642
- var NcConditionDescriptorSchema = object({
19643
- /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
19804
+ method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
19805
+ /**
19806
+ * notification-output — canonical, capability-gated notification delivery.
19807
+ *
19808
+ * Apprise-derived model (see
19809
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
19810
+ * callers emit ONE canonical `Notification`; each provider declares a
19811
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
19812
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
19813
+ * message to what the kind supports — callers never special-case a service.
19814
+ *
19815
+ * DESIGN DECISIONS (locked):
19816
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
19817
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
19818
+ * cap. Rationale: the admin UI needs one uniform surface across the
19819
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
19820
+ * alternative would fork the UI per addon and cannot host the
19821
+ * discovery→adopt flow.
19822
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
19823
+ * the generated cap-mount auto-`concatCollection`-fans them across every
19824
+ * registered provider (notifiers addon + HA addon) so one catalog is
19825
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
19826
+ * `addonId` the generated collection router extracts from the call input.
19827
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
19828
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
19829
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
19830
+ * base64 fallback needed.
19831
+ *
19832
+ * TODO (deferred, closed-set change — separate decision): add
19833
+ * `providerKind: 'notify'` so notification providers surface on the unified
19834
+ * admin "Integrations" page.
19835
+ */
19836
+ /**
19837
+ * Zentik-derived typed-media enum — the superset across every kind. Each
19838
+ * adapter picks what it supports and the degrade engine filters the rest.
19839
+ */
19840
+ var AttachmentMediaTypeSchema = _enum([
19841
+ "image",
19842
+ "video",
19843
+ "gif",
19844
+ "audio",
19845
+ "icon"
19846
+ ]);
19847
+ /**
19848
+ * A single attachment. Exactly one of `url` (remote source, most adapters
19849
+ * prefer this) or `bytes` (inline source; required for Pushover-style
19850
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
19851
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
19852
+ */
19853
+ var AttachmentSchema = object({
19854
+ mediaType: AttachmentMediaTypeSchema,
19855
+ url: string().optional(),
19856
+ bytes: _instanceof(Uint8Array).optional(),
19857
+ mime: string().optional(),
19858
+ name: string().optional()
19859
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
19860
+ var NotificationFormatSchema = _enum([
19861
+ "text",
19862
+ "markdown",
19863
+ "html"
19864
+ ]);
19865
+ /** A single tap-through action button. */
19866
+ var NotificationActionSchema = object({
19867
+ id: string(),
19868
+ label: string(),
19869
+ url: string().optional()
19870
+ });
19871
+ /**
19872
+ * The canonical notification. `body` is the only hard field (Apprise model).
19873
+ * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
19874
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
19875
+ * the adapter maps this ordinal onto its native level. `level?` is an
19876
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
19877
+ * `priority` for that one target.
19878
+ */
19879
+ var NotificationSchema = object({
19880
+ body: string(),
19881
+ title: string().optional(),
19882
+ format: NotificationFormatSchema.default("text"),
19883
+ priority: number().int().min(1).max(5).default(3),
19884
+ level: string().optional(),
19885
+ attachments: array(AttachmentSchema).optional(),
19886
+ clickUrl: string().optional(),
19887
+ actions: array(NotificationActionSchema).optional(),
19888
+ sound: string().optional(),
19889
+ ttl: number().optional(),
19890
+ tag: string().optional(),
19891
+ deviceId: number().optional(),
19892
+ eventId: string().optional(),
19893
+ metadata: record(string(), unknown()).optional()
19894
+ });
19895
+ /** One declared native severity/priority level for a kind. */
19896
+ var TargetKindLevelSchema = object({
19644
19897
  id: string(),
19645
- group: _enum([
19646
- "scope",
19647
- "class",
19648
- "zones",
19649
- "quality",
19650
- "label",
19651
- "schedule",
19652
- "device",
19653
- "package",
19654
- "occupancy"
19655
- ]),
19656
19898
  label: string(),
19657
- /** Editor widget the UI renders never hardcode per-condition forms. */
19658
- valueType: _enum([
19659
- "deviceIdList",
19660
- "stringList",
19661
- "number01",
19662
- "number",
19663
- "sourceSelect",
19664
- "zoneSelection",
19665
- "zoneIdList",
19666
- "schedule",
19667
- "plateMatcher",
19668
- "packagePhase",
19669
- "polygonDraw",
19670
- "occupancy"
19671
- ]),
19672
- operator: _enum([
19673
- "in",
19674
- "notIn",
19675
- "anyOf",
19676
- "allOf",
19677
- "gte",
19678
- "fuzzyIn",
19679
- "withinSchedule"
19680
- ]),
19681
- /** Which delivery kinds the condition applies to. */
19682
- appliesTo: array(NcDeliverySchema),
19683
- phase: string(),
19899
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
19900
+ ordinal: number().int().min(1).max(5).nullable(),
19901
+ flags: object({
19902
+ critical: boolean().optional(),
19903
+ silent: boolean().optional(),
19904
+ noPush: boolean().optional()
19905
+ }).optional(),
19906
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
19907
+ requires: array(string()).optional(),
19684
19908
  description: string().optional()
19685
19909
  });
19910
+ /** The full capability block consulted before dispatch. */
19911
+ var TargetKindCapsSchema = object({
19912
+ attachments: object({
19913
+ mediaTypes: array(AttachmentMediaTypeSchema),
19914
+ mode: _enum([
19915
+ "url",
19916
+ "bytes",
19917
+ "both"
19918
+ ]),
19919
+ max: number().int().nonnegative(),
19920
+ maxBytes: number().int().positive().optional()
19921
+ }),
19922
+ /** Max action buttons (0 = none). */
19923
+ actions: number().int().nonnegative(),
19924
+ levels: array(TargetKindLevelSchema),
19925
+ format: array(NotificationFormatSchema),
19926
+ clickUrl: boolean(),
19927
+ sound: boolean(),
19928
+ ttl: boolean(),
19929
+ bodyMaxLen: number().int().positive()
19930
+ });
19686
19931
  /**
19687
- * The delivery lifecycle status of a history row a straight read of the
19688
- * durable outbox row's own status (single source of truth):
19689
- * - `pending` — enqueued, in-flight or retrying with backoff
19690
- * - `sent` — delivered (terminal)
19691
- * - `dead` dead-lettered after exhausting retries / a permanent
19692
- * backend rejection / a deleted target (terminal; carries
19693
- * the failure `error`)
19694
- *
19695
- * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
19696
- * user dimension (quiet hours / snooze) and are additive when they land.
19932
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
19933
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
19934
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
19935
+ * the union is large and not meant for runtime validation here; the exported
19936
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
19697
19937
  */
19698
- var NcHistoryStatusSchema = _enum([
19699
- "pending",
19700
- "sent",
19701
- "dead"
19702
- ]);
19703
- /** The evaluated record kind a history row descends from (one per trigger). */
19704
- var NcHistoryRecordKindSchema = _enum([
19705
- "object-event",
19706
- "track-end",
19707
- "device-event",
19708
- "package-event"
19709
- ]);
19710
- /** Subject summary frozen on the row at fire time (survives rule/record edits). */
19711
- var NcHistorySubjectSchema = object({
19712
- className: string(),
19713
- label: string().optional(),
19714
- confidence: number().optional(),
19715
- zones: array(string()),
19716
- timestamp: number()
19938
+ var ConfigSchemaPassthrough = unknown();
19939
+ var TargetKindSchema = object({
19940
+ kind: string(),
19941
+ label: string(),
19942
+ icon: string(),
19943
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
19944
+ addonId: string(),
19945
+ configSchema: ConfigSchemaPassthrough,
19946
+ supportsDiscovery: boolean(),
19947
+ caps: TargetKindCapsSchema
19717
19948
  });
19718
19949
  /**
19719
- * One delivery-history row. This is a read-only VIEW over the durable
19720
- * outbox row (single source of truth the same row the drain loop drives;
19721
- * NO second write path, so history can never drift from delivery state).
19722
- * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
19723
- * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
19724
- * (fire) / `updatedAt` (last transition), `status` + `error` are the
19725
- * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
19726
- * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
19727
- * P1 (admin scope only).
19950
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
19951
+ * (return a presence marker only) when serving `listTargets` never
19952
+ * round-trip a stored secret to the UI.
19728
19953
  */
19729
- var NcHistoryEntrySchema = object({
19730
- /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
19954
+ var TargetSchema = object({
19731
19955
  id: string(),
19732
- ruleId: string(),
19733
- /** Rule name frozen at fire time (outlives a later rename / delete). */
19734
- ruleName: string(),
19735
- /** The rule urgency/trigger that produced this delivery. */
19736
- delivery: NcDeliverySchema,
19737
- targetId: string(),
19738
- deviceId: number(),
19739
- recordKind: NcHistoryRecordKindSchema,
19740
- /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
19741
- recordId: string(),
19742
- /** Present for track-scoped deliveries (object-event / track-end). */
19743
- trackId: string().optional(),
19744
- status: NcHistoryStatusSchema,
19745
- /** Delivery attempts made so far. */
19746
- attempts: number().int(),
19747
- /** Fire time (outbox enqueue). */
19748
- createdAt: number(),
19749
- /** Last transition time (terminal for sent / dead). */
19750
- updatedAt: number(),
19751
- /** Failure detail — present on a `dead` row. */
19752
- error: string().optional(),
19753
- subject: NcHistorySubjectSchema
19956
+ name: string(),
19957
+ kind: string(),
19958
+ addonId: string(),
19959
+ enabled: boolean(),
19960
+ config: record(string(), unknown())
19754
19961
  });
19755
- /**
19756
- * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
19757
- * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
19758
- * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
19759
- * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
19760
- */
19761
- var NcHistoryFilterSchema = object({
19762
- ruleId: string().optional(),
19763
- deviceId: number().optional(),
19764
- status: NcHistoryStatusSchema.optional(),
19765
- since: number().optional(),
19766
- until: number().optional(),
19767
- limit: number().int().min(1).max(500).default(100)
19962
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
19963
+ var DiscoveredTargetSchema = object({
19964
+ kind: string(),
19965
+ suggestedName: string(),
19966
+ config: record(string(), unknown())
19768
19967
  });
19769
- method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), method(object({ ruleId: string() }), object({ rule: NcRuleSchema.nullable() }), { auth: "admin" }), method(object({ rule: NcRuleInputSchema }), object({ rule: NcRuleSchema }), {
19770
- kind: "mutation",
19771
- auth: "admin",
19772
- caller: "required"
19773
- }), method(object({
19774
- ruleId: string(),
19775
- patch: NcRulePatchSchema
19776
- }), object({ rule: NcRuleSchema }), {
19777
- kind: "mutation",
19778
- auth: "admin",
19779
- caller: "required"
19780
- }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
19781
- kind: "mutation",
19782
- auth: "admin"
19783
- }), method(object({
19784
- ruleId: string(),
19968
+ /** The degrade engine's report what was resolved / dropped / degraded. */
19969
+ var RenderedAsSchema = object({
19970
+ level: string(),
19971
+ format: NotificationFormatSchema,
19972
+ attachmentsSent: number().int().nonnegative(),
19973
+ actionsSent: number().int().nonnegative(),
19974
+ truncated: boolean(),
19975
+ dropped: array(string())
19976
+ });
19977
+ var SendResultSchema = object({
19978
+ success: boolean(),
19979
+ error: string().optional(),
19980
+ renderedAs: RenderedAsSchema.optional()
19981
+ });
19982
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
19983
+ var TestResultSchema = SendResultSchema;
19984
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
19985
+ kind: string(),
19986
+ config: record(string(), unknown()).optional()
19987
+ }), array(DiscoveredTargetSchema)), method(object({
19988
+ targetId: string(),
19989
+ notification: NotificationSchema
19990
+ }), SendResultSchema, { kind: "mutation" }), method(object({
19991
+ targetId: string(),
19992
+ sample: NotificationSchema.optional()
19993
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
19994
+ targetId: string(),
19785
19995
  enabled: boolean()
19786
- }), object({ success: literal(true) }), {
19787
- kind: "mutation",
19788
- auth: "admin"
19789
- }), method(object({
19790
- rule: NcRuleInputSchema,
19791
- lookbackMinutes: number().int().min(1).max(1440).default(60)
19792
- }), object({ results: array(NcTestResultSchema) }), {
19793
- kind: "mutation",
19794
- auth: "admin"
19795
- }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
19996
+ }), _void(), { kind: "mutation" });
19796
19997
  /**
19797
19998
  * Zod schemas for persisted record types.
19798
19999
  *
@@ -25177,6 +25378,12 @@ Object.freeze({
25177
25378
  addonId: null,
25178
25379
  access: "delete"
25179
25380
  },
25381
+ "backup.deleteSchedule": {
25382
+ capName: "backup",
25383
+ capScope: "system",
25384
+ addonId: null,
25385
+ access: "delete"
25386
+ },
25180
25387
  "backup.getEntries": {
25181
25388
  capName: "backup",
25182
25389
  capScope: "system",
@@ -25207,6 +25414,12 @@ Object.freeze({
25207
25414
  addonId: null,
25208
25415
  access: "view"
25209
25416
  },
25417
+ "backup.listSchedules": {
25418
+ capName: "backup",
25419
+ capScope: "system",
25420
+ addonId: null,
25421
+ access: "view"
25422
+ },
25210
25423
  "backup.previewSchedule": {
25211
25424
  capName: "backup",
25212
25425
  capScope: "system",
@@ -25231,6 +25444,12 @@ Object.freeze({
25231
25444
  addonId: null,
25232
25445
  access: "create"
25233
25446
  },
25447
+ "backup.upsertSchedule": {
25448
+ capName: "backup",
25449
+ capScope: "system",
25450
+ addonId: null,
25451
+ access: "create"
25452
+ },
25234
25453
  "battery.wakeForStream": {
25235
25454
  capName: "battery",
25236
25455
  capScope: "device",
@@ -29065,6 +29284,36 @@ Object.freeze({
29065
29284
  addonId: null,
29066
29285
  access: "create"
29067
29286
  },
29287
+ "terminalSession.close": {
29288
+ capName: "terminal-session",
29289
+ capScope: "system",
29290
+ addonId: null,
29291
+ access: "create"
29292
+ },
29293
+ "terminalSession.listProfiles": {
29294
+ capName: "terminal-session",
29295
+ capScope: "system",
29296
+ addonId: null,
29297
+ access: "view"
29298
+ },
29299
+ "terminalSession.listSessions": {
29300
+ capName: "terminal-session",
29301
+ capScope: "system",
29302
+ addonId: null,
29303
+ access: "view"
29304
+ },
29305
+ "terminalSession.openSession": {
29306
+ capName: "terminal-session",
29307
+ capScope: "system",
29308
+ addonId: null,
29309
+ access: "create"
29310
+ },
29311
+ "terminalSession.resize": {
29312
+ capName: "terminal-session",
29313
+ capScope: "system",
29314
+ addonId: null,
29315
+ access: "create"
29316
+ },
29068
29317
  "toast.onToast": {
29069
29318
  capName: "toast",
29070
29319
  capScope: "system",