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