@camstack/addon-import-alexa 0.2.5 → 0.2.6

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