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