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