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