@camstack/addon-provider-hikvision 1.2.6 → 1.2.7

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