@camstack/addon-provider-amcrest 0.2.5 → 0.2.6

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