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