@camstack/addon-provider-dreo 0.2.5 → 0.2.6

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