@camstack/addon-provider-rademacher 0.2.5 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +2393 -2144
  2. package/dist/addon.mjs +2393 -2144
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -8516,16 +8516,23 @@ var StorageLocationDeclarationSchema = object({
8516
8516
  * Which node root the seeded `<id>:default` instance is placed under on a
8517
8517
  * FRESH install:
8518
8518
  * - `'data'` (default) — the node's data dir (`CAMSTACK_DATA` / boot dir),
8519
- * the appData volume. Right for small/durable data (backups, logs, models).
8519
+ * the appData volume. Right for small/durable data (logs, models).
8520
8520
  * - `'media'` — the dedicated media volume (`CAMSTACK_MEDIA_ROOT`) when that
8521
8521
  * env is set, else falls back to the data root. Right for bulky, hot media
8522
8522
  * (recordings, event media) that should stay off the appData disk.
8523
+ * - `'backup'` — the dedicated backup volume (`CAMSTACK_BACKUP_ROOT`, default
8524
+ * `/backups` in the image) so archives live on their own mount rather than
8525
+ * filling the appData disk. Falls back to the data root when unset.
8523
8526
  *
8524
8527
  * Only affects the seeded default's `basePath`; operators can repoint any
8525
8528
  * location afterwards, and a `defaultsTo` slot inherits its parent's root
8526
8529
  * regardless of this field. Absent (the common case) is treated as `'data'`.
8527
8530
  */
8528
- defaultRoot: _enum(["data", "media"]).optional()
8531
+ defaultRoot: _enum([
8532
+ "data",
8533
+ "media",
8534
+ "backup"
8535
+ ]).optional()
8529
8536
  });
8530
8537
  var DecoderStatsSchema = object({
8531
8538
  inputFps: number(),
@@ -10119,669 +10126,1307 @@ function shallowEqual(a, b) {
10119
10126
  return true;
10120
10127
  }
10121
10128
  /**
10122
- * Generic device-level status snapshot. Auto-registered by `BaseDevice`
10123
- * for every device, regardless of provider the kernel needs a uniform
10124
- * cap-keyed slice for the basic device flags every consumer expects to
10125
- * read across processes (the `online` flag in particular). Driver-specific
10126
- * caps (`battery`, `doorbell`, …) carry their domain-specific state on
10127
- * their own slices.
10129
+ * Shared geometry vocabulary for on-frame shape caps — privacy-mask,
10130
+ * motion-zones, and the detection zones/lines editor all speak this one
10131
+ * language so a single drawing-plane editor and the providers stay
10132
+ * decoupled from each cap's storage.
10128
10133
  *
10129
- * Pattern is identical to `battery`: schema-bearing `runtimeState`,
10130
- * empty `methods`, single change event. Reads land at
10131
- * `runtimeState.getCapState('device-status')`; writes at
10132
- * `runtimeState.setCapState('device-status', …)`. Cross-process
10133
- * consumers reach the same data via the `device-state` cap router
10134
- * (`getCapSlice({deviceId, capName: 'device-status'})`).
10134
+ * All coordinates are normalized 0..1 of the camera frame (top-left
10135
+ * origin). Each cap composes the SUBSET of shape kinds it supports and
10136
+ * advertises it via `supportedShapes` in its `getOptions`.
10135
10137
  */
10136
- var DeviceStatusSchema = object({
10137
- /**
10138
- * Device-level liveness. Drivers flip via `markOnline(boolean)` on
10139
- * `BaseDevice`. Provider semantics vary — RTSP aggregates broker
10140
- * stream-health, Reolink reads firmware push events, ONVIF tracks
10141
- * ping responses. This cap intentionally does NOT prescribe which
10142
- * signal drives the flag.
10143
- */
10144
- online: boolean(),
10145
- /** Ms epoch of the last `online` transition. Lets consumers tell
10146
- * apart "just came online" from "still online". */
10147
- lastChangedAt: number()
10138
+ /** A normalized 0..1 point (top-left origin). */
10139
+ var MaskPointSchema = object({
10140
+ x: number(),
10141
+ y: number()
10142
+ });
10143
+ /** Axis-aligned rectangle (normalized 0..1). */
10144
+ var MaskRectShapeSchema = object({
10145
+ kind: literal("rect"),
10146
+ x: number(),
10147
+ y: number(),
10148
+ width: number(),
10149
+ height: number()
10150
+ });
10151
+ /** Free polygon — an ordered list of normalized vertices (≥3). */
10152
+ var MaskPolygonShapeSchema = object({
10153
+ kind: literal("polygon"),
10154
+ points: array(MaskPointSchema)
10155
+ });
10156
+ /** Boolean cell grid — row-major, length === gridWidth*gridHeight. */
10157
+ var MaskGridShapeSchema = object({
10158
+ kind: literal("grid"),
10159
+ gridWidth: number(),
10160
+ gridHeight: number(),
10161
+ cells: array(boolean())
10162
+ });
10163
+ discriminatedUnion("kind", [
10164
+ MaskRectShapeSchema,
10165
+ MaskPolygonShapeSchema,
10166
+ MaskGridShapeSchema,
10167
+ object({
10168
+ kind: literal("line"),
10169
+ points: array(MaskPointSchema)
10170
+ })
10171
+ ]);
10172
+ /** Every shape-kind discriminant, for `supportedShapes` advertisement. */
10173
+ var MaskShapeKindSchema = _enum([
10174
+ "rect",
10175
+ "polygon",
10176
+ "grid",
10177
+ "line"
10178
+ ]);
10179
+ /** Polygon vertex bounds when a cap supports 'polygon' (e.g. Hikvision {min:4,max:4}). */
10180
+ var MaskPolygonVerticesSchema = object({
10181
+ min: number(),
10182
+ max: number()
10183
+ });
10184
+ /** Grid dimensions when a cap supports 'grid'. */
10185
+ var MaskGridDimsSchema = object({
10186
+ width: number(),
10187
+ height: number()
10148
10188
  });
10149
- var deviceStatusCapability = {
10150
- name: "device-status",
10151
- scope: "device",
10152
- deviceNative: true,
10153
- mode: "singleton",
10154
- methods: {},
10155
- events: {
10156
- /** Emitted when `online` transitions. Mirrors the semantics of
10157
- * `battery.onStatusChanged`. */
10158
- onStatusChanged: { data: object({
10159
- deviceId: number(),
10160
- status: DeviceStatusSchema
10161
- }) } },
10162
- status: {
10163
- schema: DeviceStatusSchema,
10164
- kind: "push"
10165
- },
10166
- runtimeState: DeviceStatusSchema
10167
- };
10168
10189
  /**
10169
- * Per-device feature/identity probe slice. Holds the runtime-resolved
10170
- * truth about what a device CAN do — which the kernel uses to:
10171
- * 1. Reconcile accessory children (hub-children spawn siren/floodlight/PIR
10172
- * based on what the firmware actually advertises).
10173
- * 2. Compute the public `features: DeviceFeature[]` array surfaced via
10174
- * `device-manager.listAll`.
10175
- * 3. Decide which optional caps (PTZ, intercom, doorbell, battery, …)
10176
- * to register on the device's capability surface.
10190
+ * notification-rules the Notification Center rule surface (P1 core).
10177
10191
  *
10178
- * Auto-registered by `BaseDevice` for every device. Drivers populate the
10179
- * slice from `onProbe()` (kernel calls it once after register, before
10180
- * accessory reconciliation). Consumers read via:
10181
- * `runtimeState.getCapState<FeatureProbeStatus>('feature-probe')`
10192
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
10193
+ * (operator decisions D-1/D-2/D-3 are binding):
10182
10194
  *
10183
- * `flags` is an open record so each driver carries its own keys without
10184
- * a centralized schema bottleneck Reolink writes `hasPtz/hasIntercom`,
10185
- * Hikvision writes `hasSupplementalLight/hasAlarmIo`, etc.
10195
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
10196
+ * `notification-center` module), hooked on the durable persistence
10197
+ * moments (object-event insert, TrackCloser.closeExpired) with a
10198
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
10199
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
10200
+ * FIRST persisted detection matching the conditions (per-track dedup,
10201
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
10202
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
10203
+ * - DISPATCH stays behind `notification-output` (rules reference targets
10204
+ * by id; per-backend params are a passthrough blob capped by the
10205
+ * target kind's own caps/degrade engine).
10186
10206
  *
10187
- * Replaces the older driver-local `deviceCache.has*` blob: the per-device
10188
- * config is for operator-edited overrides + UI snapshots; runtime probe
10189
- * results belong in runtime-state where the kernel handles persistence,
10190
- * cross-process mirroring, and reactive updates.
10207
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
10208
+ * server-injected caller identity the first `caller: 'required'`
10209
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
10210
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
10211
+ * windows, and the optional label/identity/plate matchers. User rules,
10212
+ * private zones, per-recipient fan-out and the wider condition table are
10213
+ * P2+ (see spec §7).
10214
+ *
10215
+ * All schemas here are the single source of truth — `NcRule` etc. are
10216
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
10217
+ * schema/interface drift is explicitly not repeated).
10191
10218
  */
10192
- var FeatureProbeStatusSchema = object({
10219
+ /**
10220
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
10221
+ * The value maps 1:1 onto the evaluated record kind:
10222
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
10223
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
10224
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
10225
+ * change of a LINKED device, one row per linked camera)
10226
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
10227
+ * delivery / pick-up)
10228
+ *
10229
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
10230
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
10231
+ * this one field keeps the schema additive — a rule still declares exactly
10232
+ * one trigger.
10233
+ */
10234
+ var NcDeliverySchema = _enum([
10235
+ "immediate",
10236
+ "track-end",
10237
+ "device-event",
10238
+ "package-event"
10239
+ ]);
10240
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
10241
+ var NcScheduleSchema = object({
10242
+ windows: array(object({
10243
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
10244
+ days: array(number().int().min(0).max(6)).min(1),
10245
+ startMinute: number().int().min(0).max(1439),
10246
+ endMinute: number().int().min(0).max(1439)
10247
+ })).min(1),
10248
+ /** IANA timezone; default = hub host timezone. */
10249
+ timezone: string().optional(),
10250
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
10251
+ invert: boolean().optional()
10252
+ });
10253
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
10254
+ var NcPlateMatcherSchema = object({
10255
+ values: array(string().min(1)).min(1),
10256
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
10257
+ maxDistance: number().int().min(0).max(3).default(1)
10258
+ });
10259
+ /**
10260
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
10261
+ * occupancy edge for a device — optionally narrowed to a single admin
10262
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
10263
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
10264
+ * - `became-free` — count crossed ≥ `count` → below it
10265
+ * - `>=` / `<=` — count is at/over or at/under `count`
10266
+ * `sustainSeconds` requires the condition hold continuously that long
10267
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
10268
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
10269
+ * the condition never matches. Confirmed edge-state survives addon restarts
10270
+ * (declared SQLite collection, reseeded on boot).
10271
+ */
10272
+ var NcOccupancyConditionSchema = object({
10273
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
10274
+ zoneId: string().optional(),
10275
+ /** Object class to count; absent = any class. */
10276
+ className: string().optional(),
10277
+ op: _enum([
10278
+ "became-occupied",
10279
+ "became-free",
10280
+ ">=",
10281
+ "<="
10282
+ ]).default("became-occupied"),
10283
+ count: number().int().min(0).default(1),
10284
+ sustainSeconds: number().int().min(0).max(3600).default(15)
10285
+ });
10286
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
10287
+ var NcZoneConditionSchema = object({
10288
+ ids: array(string().min(1)).min(1),
10289
+ /** Quantifier over `ids` — at least one / every one visited. */
10290
+ match: _enum(["any", "all"]).default("any")
10291
+ });
10292
+ /**
10293
+ * The P1 condition set — a flat AND of groups; absent group = pass;
10294
+ * membership lists are OR within the list (spec §2.3).
10295
+ */
10296
+ var NcConditionsSchema = object({
10297
+ /** Device scope — absent = all devices. */
10298
+ devices: array(number()).optional(),
10299
+ /** Detector class names (any overlap with the record's class set). */
10300
+ classes: array(string().min(1)).optional(),
10301
+ /** Veto classes — any overlap fails the rule. */
10302
+ classesExclude: array(string().min(1)).optional(),
10303
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
10304
+ minConfidence: number().min(0).max(1).optional(),
10305
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
10306
+ zones: NcZoneConditionSchema.optional(),
10307
+ /** Veto zones — any hit fails the rule. */
10308
+ zonesExclude: array(string().min(1)).optional(),
10193
10309
  /**
10194
- * Driver-specific flag bag. Each driver picks its own key names — the
10195
- * cap deliberately does NOT enforce a closed enum here. Reolink keys:
10196
- * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,
10197
- * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:
10198
- * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.
10310
+ * Exact (case-insensitive) match on the record's collapsed `label`
10311
+ * (identity name / plate text / subclass).
10199
10312
  */
10200
- flags: record(string(), unknown()),
10313
+ labelEquals: array(string().min(1)).optional(),
10201
10314
  /**
10202
- * Coarse driver-classification lets cross-process consumers tell apart
10203
- * cameras / battery-cams / NVRs without re-running the probe. `null`
10204
- * before the first probe completes.
10315
+ * Identity matcher. P1 boundary: matched against the record's collapsed
10316
+ * `label` (the identity display name propagated by the face pipeline) —
10317
+ * identity-ID matching rides in P2 when identity ids reach the record.
10205
10318
  */
10206
- deviceType: string().nullable(),
10207
- /** Camera/firmware model string. `null` when the firmware doesn't expose it. */
10208
- model: string().nullable(),
10209
- /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */
10210
- channelCount: number().nullable(),
10319
+ identities: array(string().min(1)).optional(),
10320
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
10321
+ plates: NcPlateMatcherSchema.optional(),
10211
10322
  /**
10212
- * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe
10213
- * completes drivers' `getAccessoryChildren()` should treat zero as
10214
- * "probe not done yet, return empty" so accessories aren't spawned
10215
- * before the firmware is queried.
10323
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
10324
+ * Same P1 boundary: matched against the record's collapsed `label` (the
10325
+ * identity display name). A record with NO label passes (nothing to
10326
+ * exclude), unlike the include variant which fails on an absent label.
10216
10327
  */
10217
- lastProbedAt: number(),
10328
+ identitiesExclude: array(string().min(1)).optional(),
10218
10329
  /**
10219
- * Framework convention: every runtime-state slice carries this for the
10220
- * createRuntimeStateBridge stale-check helper. We keep it in sync with
10221
- * `lastProbedAt` on every write.
10330
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
10331
+ * TRACK-END only: importance is scored at track close, so it does not exist
10332
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
10333
+ * close the value is threaded via the close-time info (the `Track` clone is
10334
+ * captured before the DB row is updated, so it would otherwise read stale).
10335
+ * Fails when the record carries no importance (never guess quality — the
10336
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
10222
10337
  */
10223
- lastFetchedAt: number()
10338
+ minImportance: number().min(0).max(1).optional(),
10339
+ /**
10340
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
10341
+ * TRACK-END only: an `immediate` / object-event subject has no closed
10342
+ * lifespan, so a dwell condition never matches immediate delivery
10343
+ * (documented choice — the object-event record carries no `firstSeen`,
10344
+ * so dwell cannot be computed from what the subject actually carries).
10345
+ */
10346
+ minDwellSeconds: number().min(0).optional(),
10347
+ /**
10348
+ * Detection provenance filter. `any` (default / absent) matches every
10349
+ * source; otherwise the subject's source must equal it. Legacy records
10350
+ * with no stamped source are treated as `pipeline`. The union spans both
10351
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
10352
+ * tracks carry `sensor`.
10353
+ */
10354
+ source: _enum([
10355
+ "pipeline",
10356
+ "onboard",
10357
+ "sensor",
10358
+ "any"
10359
+ ]).optional(),
10360
+ /**
10361
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
10362
+ * detector `minConfidence` (that gates the object-detection score; this
10363
+ * gates the recognition/OCR match score). Fails when the subject carries
10364
+ * no label-match confidence (never guess). TRACK-END only: the confidence
10365
+ * lives on the recognition result and reaches the subject at track close.
10366
+ *
10367
+ * What it measures precisely (plumbed at track close — the closer threads
10368
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
10369
+ * `importance`): the BEST recognition match confidence observed for the
10370
+ * label the track carries at close — for a face, the peak cosine similarity
10371
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
10372
+ * for a plate, the peak OCR read score of the best-held plate
10373
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
10374
+ * one track the higher of the two is used. A track that ended with no
10375
+ * confident identity/plate match carries no value, so the condition fails
10376
+ * closed for it (an un-recognized subject).
10377
+ */
10378
+ minLabelConfidence: number().min(0).max(1).optional(),
10379
+ /**
10380
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
10381
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
10382
+ * against the token carried on the device-event subject (extracted from the
10383
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
10384
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
10385
+ * eventType, so gate those with {@link sensorKinds} instead.
10386
+ */
10387
+ eventTypeTokens: array(string().min(1)).optional(),
10388
+ /**
10389
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
10390
+ * `contact`, `button`, `device-event`) — matched against the persisted
10391
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
10392
+ */
10393
+ sensorKinds: array(string().min(1)).optional(),
10394
+ /**
10395
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
10396
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
10397
+ * when the subject's phase does not match (a subject always carries a phase
10398
+ * on the package-event trigger).
10399
+ */
10400
+ packagePhase: _enum([
10401
+ "delivered",
10402
+ "picked-up",
10403
+ "both"
10404
+ ]).optional(),
10405
+ /**
10406
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
10407
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
10408
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
10409
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
10410
+ */
10411
+ customZones: array(MaskPolygonShapeSchema).optional(),
10412
+ /**
10413
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
10414
+ * (optionally zone/class-scoped) occupancy count crosses the configured
10415
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
10416
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
10417
+ */
10418
+ occupancy: NcOccupancyConditionSchema.optional()
10419
+ });
10420
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
10421
+ var NcRuleTargetSchema = object({
10422
+ /** `notification-output` Target id. */
10423
+ targetId: string().min(1),
10424
+ /**
10425
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
10426
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
10427
+ * degrade engine drops what the backend can't render.
10428
+ */
10429
+ params: record(string(), unknown()).optional()
10224
10430
  });
10225
- var featureProbeCapability = {
10226
- name: "feature-probe",
10227
- scope: "device",
10228
- deviceNative: true,
10229
- mode: "singleton",
10230
- methods: {},
10231
- events: {
10232
- /** Fires whenever a fresh probe completes (kernel-driven `reprobe()`
10233
- * or driver-initiated re-detect after a state change). */
10234
- onProbeChanged: { data: object({
10235
- deviceId: number(),
10236
- status: FeatureProbeStatusSchema
10237
- }) } },
10238
- status: {
10239
- schema: FeatureProbeStatusSchema,
10240
- kind: "push"
10241
- },
10242
- runtimeState: FeatureProbeStatusSchema
10243
- };
10244
10431
  /**
10245
- * Multi-metric air-quality slice. Covers CO₂, total VOCs, particulate
10246
- * matter at PM2.5 / PM10, and a derived AQI index — all optional so
10247
- * a single-metric source populates only what it observes. Mirrors
10248
- * the HA `sensor` device_class set (`co2`, `volatile_organic_compounds`,
10249
- * `pm25`, `pm10`, `aqi`) collapsed into one cap because a typical
10250
- * air-quality node reports several of these together; modelling them
10251
- * as siblings keeps a single timestamp + one slice subscription.
10432
+ * Media attachment policy (P1 still-image subset).
10433
+ * - `best` the best AVAILABLE subject image at dispatch time (D-3).
10434
+ * - `best-matching` the media that explains WHY the rule fired: a rule
10435
+ * matched on identities attaches the subject's `faceCrop`, one matched on
10436
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
10437
+ * (or when the specific crop is missing) degrades to `best`, then
10438
+ * `keyFrame`, then no attachment never delaying the send. The matched
10439
+ * condition summary is frozen on the outbox row at enqueue (like the rule
10440
+ * name), so the choice never drifts from the record that fired it.
10441
+ * - `keyFrame` — the clean scene frame (no subject box).
10442
+ * - `none` — no attachment.
10252
10443
  */
10253
- var AirQualitySensorStatusSchema = object({
10254
- /** Carbon dioxide concentration in ppm. */
10255
- co2Ppm: number().min(0).optional(),
10256
- /** Total volatile organic compounds in ppb. */
10257
- vocPpb: number().min(0).optional(),
10258
- /** Particulate matter ≤ 2.5 μm in µg/m³. */
10259
- pm25: number().min(0).optional(),
10260
- /** Particulate matter ≤ 10 μm in µg/m³. */
10261
- pm10: number().min(0).optional(),
10262
- /** Composite AQI value (typically 0..500). */
10263
- aqi: number().optional(),
10264
- /** Ms epoch when the slice was last updated. */
10265
- lastFetchedAt: number(),
10266
- /** Live display unit of the single metric this slice carries (e.g. HA
10267
- * `attributes.unit_of_measurement` → 'ppm' / 'ppb' / 'µg/m³'). Each
10268
- * upstream `sensor.*` entity surfaces ONE device_class, so one unit
10269
- * per slice is unambiguous. */
10270
- unit: string().optional(),
10271
- /** Suggested decimal places for numeric display.
10272
- * Populated live from the upstream source when provided (e.g. HA
10273
- * `attributes.suggested_display_precision`). Falls back to
10274
- * auto-formatting when absent. */
10275
- precision: number().int().min(0).max(10).optional()
10444
+ var NcMediaPolicySchema = object({ attach: _enum([
10445
+ "best",
10446
+ "best-matching",
10447
+ "keyFrame",
10448
+ "none"
10449
+ ]).default("best") });
10450
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
10451
+ var NcThrottleSchema = object({
10452
+ cooldownSec: number().int().min(0).max(86400).default(60),
10453
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
10454
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
10455
+ });
10456
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
10457
+ var NcRuleInputSchema = object({
10458
+ name: string().min(1).max(200),
10459
+ enabled: boolean().default(true),
10460
+ delivery: NcDeliverySchema,
10461
+ conditions: NcConditionsSchema.default({}),
10462
+ schedule: NcScheduleSchema.optional(),
10463
+ targets: array(NcRuleTargetSchema).min(1),
10464
+ media: NcMediaPolicySchema.default({ attach: "best" }),
10465
+ throttle: NcThrottleSchema.default({
10466
+ cooldownSec: 60,
10467
+ scope: "rule-device"
10468
+ }),
10469
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
10470
+ template: object({
10471
+ title: string().max(500).optional(),
10472
+ body: string().max(2e3).optional()
10473
+ }).optional(),
10474
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
10475
+ priority: number().int().min(1).max(5).default(3),
10476
+ /**
10477
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
10478
+ * behaviour, visible to all, read-only in the viewer). Present = personal
10479
+ * rule owned by this userId. Server-stamped; never trusted from a client.
10480
+ */
10481
+ ownerUserId: string().optional()
10276
10482
  });
10277
- var airQualitySensorCapability = {
10278
- name: "air-quality-sensor",
10279
- scope: "device",
10280
- deviceNative: true,
10281
- mode: "singleton",
10282
- deviceTypes: [DeviceType.Sensor],
10283
- methods: {},
10284
- status: {
10285
- schema: AirQualitySensorStatusSchema,
10286
- kind: "push"
10287
- },
10288
- runtimeState: AirQualitySensorStatusSchema
10289
- };
10290
10483
  /**
10291
- * Alarm-panel cap. Models HA `alarm_control_panel.*` on
10292
- * `DeviceType.AlarmPanel`. State follows HA's canonical lifecycle
10293
- * across disarmed / armed_(home|away|night|vacation|custom_bypass) /
10294
- * arming / pending / triggered / disarming.
10295
- *
10296
- * Many panels require a PIN code on arm / disarm — the optional
10297
- * `code` field on the methods passes it through to the upstream
10298
- * service; it's NEVER persisted in the runtime slice or any event
10299
- * payload. The presence of a required code is signalled by
10300
- * `DeviceFeature.AlarmPinRequired` so the UI gates a code-entry
10301
- * field without a slice fetch.
10302
- *
10303
- * `availableModes` mirrors HA's `supported_features`-derived arm
10304
- * mode list — the UI renders only the buttons the panel accepts.
10484
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
10485
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
10486
+ * NOT a client-authored input field (it lives on the persisted rule, not the
10487
+ * input), so it is added here explicitly to let the store's per-target opt-out
10488
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
10489
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
10490
+ * `updateRule` patch.
10305
10491
  */
10306
- var AlarmStateSchema = _enum([
10307
- "disarmed",
10308
- "armed_home",
10309
- "armed_away",
10310
- "armed_night",
10311
- "armed_vacation",
10312
- "armed_custom_bypass",
10313
- "arming",
10314
- "disarming",
10315
- "pending",
10316
- "triggered"
10317
- ]);
10318
- var AlarmArmModeSchema = _enum([
10319
- "home",
10320
- "away",
10321
- "night",
10322
- "vacation",
10323
- "custom_bypass"
10324
- ]);
10325
- var AlarmPanelStatusSchema = object({
10326
- /** Current lifecycle state. */
10327
- state: AlarmStateSchema,
10328
- /** Subset of arm modes the panel accepts. UI renders one button per
10329
- * mode in this list. */
10330
- availableModes: array(AlarmArmModeSchema),
10331
- /** Whether the panel requires a PIN on arm / disarm. Mirrors
10332
- * `DeviceFeature.AlarmPinRequired` for slice consumers. */
10333
- requiresCode: boolean(),
10334
- /** Ms epoch when the slice was last updated. */
10335
- lastChangedAt: number()
10336
- });
10337
- var alarmPanelCapability = {
10338
- name: "alarm-panel",
10339
- scope: "device",
10340
- deviceNative: true,
10341
- mode: "singleton",
10342
- deviceTypes: [DeviceType.AlarmPanel],
10343
- methods: {
10344
- arm: method(object({
10345
- deviceId: number().int().nonnegative(),
10346
- mode: AlarmArmModeSchema,
10347
- /** Optional PIN code. Required when `requiresCode === true`.
10348
- * Passed through to the upstream service; never persisted. */
10349
- code: string().min(1).optional()
10350
- }), _void(), {
10351
- kind: "mutation",
10352
- auth: "admin"
10353
- }),
10354
- disarm: method(object({
10355
- deviceId: number().int().nonnegative(),
10356
- code: string().min(1).optional()
10357
- }), _void(), {
10358
- kind: "mutation",
10359
- auth: "admin"
10360
- }),
10361
- /**
10362
- * Force the panel into the `triggered` state — used by HA
10363
- * automations to surface external sensor events through the panel
10364
- * (e.g. a Reolink camera intrusion event firing the security
10365
- * system). Provider rejects when the panel hardware doesn't
10366
- * support a software-initiated trigger.
10367
- */
10368
- trigger: method(object({ deviceId: number().int().nonnegative() }), _void(), {
10369
- kind: "mutation",
10370
- auth: "admin"
10371
- })
10372
- },
10373
- status: {
10374
- schema: AlarmPanelStatusSchema,
10375
- kind: "push"
10376
- },
10492
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
10493
+ /** A persisted rule. */
10494
+ var NcRuleSchema = NcRuleInputSchema.extend({
10495
+ id: string(),
10496
+ /** userId of the admin who created the rule (server-stamped caller). */
10497
+ createdBy: string(),
10498
+ createdAt: number(),
10499
+ updatedAt: number(),
10377
10500
  /**
10378
- * Runtime-state slice mirrored by the kernel. UI panel reads the
10379
- * full slice; renders an arm button per `availableModes` entry and
10380
- * a PIN field iff `requiresCode === true`.
10501
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
10502
+ * send time. Only a target's OWNER may add/remove its id (server-checked
10503
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
10381
10504
  */
10382
- runtimeState: AlarmPanelStatusSchema
10383
- };
10384
- /**
10385
- * Ambient illuminance reading in lux. Drives Home Assistant `sensor`
10386
- * entries with `device_class: illuminance`.
10387
- */
10388
- var AmbientLightSensorStatusSchema = object({
10389
- /** Current illuminance in lux (lx). */
10390
- lux: number().min(0),
10391
- /** Ms epoch when the slice was last updated. */
10392
- lastFetchedAt: number(),
10393
- /** Live display unit from the upstream source (e.g. HA
10394
- * `attributes.unit_of_measurement`). The UI prefers this over the
10395
- * role's canonical unit. Absent → fall back to the canonical unit. */
10396
- unit: string().optional(),
10397
- /** Suggested decimal places for numeric display.
10398
- * Populated live from the upstream source when provided (e.g. HA
10399
- * `attributes.suggested_display_precision`). Falls back to
10400
- * auto-formatting when absent. */
10401
- precision: number().int().min(0).max(10).optional()
10505
+ disabledTargetIds: array(string()).default([])
10402
10506
  });
10403
- var ambientLightSensorCapability = {
10404
- name: "ambient-light-sensor",
10405
- scope: "device",
10406
- deviceNative: true,
10407
- mode: "singleton",
10408
- deviceTypes: [DeviceType.Sensor],
10409
- methods: {},
10410
- status: {
10411
- schema: AmbientLightSensorStatusSchema,
10412
- kind: "push"
10413
- },
10414
- runtimeState: AmbientLightSensorStatusSchema
10415
- };
10416
- /**
10417
- * Per-class audio metrics aggregated over a sliding window.
10418
- */
10419
- var AudioClassSummarySchema = object({
10420
- className: string(),
10421
- /** Number of windows (chunks) where this class was the top hit. */
10422
- hits: number().int().nonnegative(),
10423
- /** Mean score across those hits, clamped to [0,1]. */
10424
- avgScore: number().min(0).max(1),
10425
- /** Peak score in the window. */
10426
- peakScore: number().min(0).max(1)
10507
+ var NcTestResultSchema = object({
10508
+ recordId: string(),
10509
+ recordKind: _enum([
10510
+ "object-event",
10511
+ "track",
10512
+ "device-event",
10513
+ "package-event"
10514
+ ]),
10515
+ deviceId: number(),
10516
+ timestamp: number(),
10517
+ wouldFire: boolean(),
10518
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
10519
+ failedCondition: string().optional(),
10520
+ className: string().optional(),
10521
+ label: string().optional()
10522
+ });
10523
+ var NcConditionDescriptorSchema = object({
10524
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
10525
+ id: string(),
10526
+ group: _enum([
10527
+ "scope",
10528
+ "class",
10529
+ "zones",
10530
+ "quality",
10531
+ "label",
10532
+ "schedule",
10533
+ "device",
10534
+ "package",
10535
+ "occupancy"
10536
+ ]),
10537
+ label: string(),
10538
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
10539
+ valueType: _enum([
10540
+ "deviceIdList",
10541
+ "stringList",
10542
+ "number01",
10543
+ "number",
10544
+ "sourceSelect",
10545
+ "zoneSelection",
10546
+ "zoneIdList",
10547
+ "schedule",
10548
+ "plateMatcher",
10549
+ "packagePhase",
10550
+ "polygonDraw",
10551
+ "occupancy"
10552
+ ]),
10553
+ operator: _enum([
10554
+ "in",
10555
+ "notIn",
10556
+ "anyOf",
10557
+ "allOf",
10558
+ "gte",
10559
+ "fuzzyIn",
10560
+ "withinSchedule"
10561
+ ]),
10562
+ /** Which delivery kinds the condition applies to. */
10563
+ appliesTo: array(NcDeliverySchema),
10564
+ phase: string(),
10565
+ description: string().optional()
10427
10566
  });
10428
10567
  /**
10429
- * Per-camera audio metrics snapshotemitted by the analytics frame
10430
- * handler on every `pipeline.audio-inference-result` event and
10431
- * mirrored into the `audio-metrics` device-state slice. Symmetric
10432
- * with `zone-analytics` snapshots for video every consumer
10433
- * (admin UI panel, automations, alert rules) reads via the
10434
- * canonical `device.state.audioMetrics.value` reactive handle.
10568
+ * The delivery lifecycle status of a history row a straight read of the
10569
+ * durable outbox row's own status (single source of truth):
10570
+ * - `pending` enqueued, in-flight or retrying with backoff
10571
+ * - `sent` delivered (terminal)
10572
+ * - `dead` — dead-lettered after exhausting retries / a permanent
10573
+ * backend rejection / a deleted target (terminal; carries
10574
+ * the failure `error`)
10435
10575
  *
10436
- * Aggregates are computed over a rolling `windowSec` window
10437
- * (default 60s). Past that window, classes drop out of `byClass`
10438
- * and the level history shifts forward.
10576
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
10577
+ * user dimension (quiet hours / snooze) and are additive when they land.
10439
10578
  */
10440
- var AudioMetricsSnapshotSchema = object({
10441
- /** Wall-clock timestamp (ms) of the most recent audio window. */
10442
- ts: number().int(),
10443
- /** Sliding-window length (seconds) used for aggregation. */
10444
- windowSec: number().int().positive(),
10445
- /** Latest level reading from the most recent window. */
10446
- level: object({
10447
- rms: number(),
10448
- dbfs: number()
10449
- }),
10450
- /** Peak dBFS observed across the rolling window. */
10451
- peakDbfs: number(),
10452
- /** Mean dBFS across the rolling window. */
10453
- avgDbfs: number(),
10454
- /** Most recent above-threshold classification, or null on silence. */
10455
- current: object({
10456
- className: string(),
10457
- score: number().min(0).max(1),
10458
- timestamp: number().int()
10459
- }).nullable(),
10460
- /** Per-class summary across the rolling window — keys are
10461
- * `macroClass` strings (e.g. `dog_bark`, `speech`, `glass_break`). */
10462
- byClass: array(AudioClassSummarySchema).readonly()
10579
+ var NcHistoryStatusSchema = _enum([
10580
+ "pending",
10581
+ "sent",
10582
+ "dead"
10583
+ ]);
10584
+ /** The evaluated record kind a history row descends from (one per trigger). */
10585
+ var NcHistoryRecordKindSchema = _enum([
10586
+ "object-event",
10587
+ "track-end",
10588
+ "device-event",
10589
+ "package-event"
10590
+ ]);
10591
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
10592
+ var NcHistorySubjectSchema = object({
10593
+ className: string(),
10594
+ label: string().optional(),
10595
+ confidence: number().optional(),
10596
+ zones: array(string()),
10597
+ timestamp: number()
10463
10598
  });
10464
10599
  /**
10465
- * Audio-metrics history payload a series of `AudioMetricsHistoryPoint`
10466
- * samples capped at `maxPoints` (default 1024). When the requested
10467
- * `windowSec / sampleEveryMs` would exceed the cap, the provider
10468
- * subsamples by bucketed averaging and reports the effective sample
10469
- * spacing on `effectiveSampleEveryMs` so the UI can label the x-axis.
10600
+ * One delivery-history row. This is a read-only VIEW over the durable
10601
+ * outbox row (single source of truth the same row the drain loop drives;
10602
+ * NO second write path, so history can never drift from delivery state).
10603
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
10604
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
10605
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
10606
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
10607
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
10608
+ * P1 (admin scope only).
10470
10609
  */
10471
- var AudioMetricsHistorySchema = object({
10472
- points: array(object({
10473
- /** Wall-clock ms when this sample was recorded. */
10474
- ts: number().int(),
10475
- /** Instantaneous dBFS level at sample time. `null` for windows where
10476
- * the source had no level reading (rare; happens at decode startup). */
10477
- dbfs: number().nullable(),
10478
- /** Rolling-window peak dBFS at sample time. Same window the live
10479
- * snapshot reports. */
10480
- peakDbfs: number(),
10481
- /** Rolling-window mean dBFS at sample time. */
10482
- avgDbfs: number(),
10483
- /** Dominant above-threshold class at sample time, or null on silence. */
10484
- topClass: string().nullable(),
10485
- /** Score of the dominant class (`null` whenever `topClass` is null). */
10486
- topScore: number().min(0).max(1).nullable()
10487
- })).readonly(),
10488
- /** Actual ms between adjacent samples after any subsampling. */
10489
- effectiveSampleEveryMs: number().int().positive(),
10490
- /** Wall-clock window covered by `points` (`points[N-1].ts - points[0].ts`),
10491
- * or `0` when there's fewer than 2 samples. */
10492
- windowMsActual: number().int().nonnegative()
10610
+ var NcHistoryEntrySchema = object({
10611
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
10612
+ id: string(),
10613
+ ruleId: string(),
10614
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
10615
+ ruleName: string(),
10616
+ /** The rule urgency/trigger that produced this delivery. */
10617
+ delivery: NcDeliverySchema,
10618
+ targetId: string(),
10619
+ deviceId: number(),
10620
+ recordKind: NcHistoryRecordKindSchema,
10621
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
10622
+ recordId: string(),
10623
+ /** Present for track-scoped deliveries (object-event / track-end). */
10624
+ trackId: string().optional(),
10625
+ status: NcHistoryStatusSchema,
10626
+ /** Delivery attempts made so far. */
10627
+ attempts: number().int(),
10628
+ /** Fire time (outbox enqueue). */
10629
+ createdAt: number(),
10630
+ /** Last transition time (terminal for sent / dead). */
10631
+ updatedAt: number(),
10632
+ /** Failure detail — present on a `dead` row. */
10633
+ error: string().optional(),
10634
+ subject: NcHistorySubjectSchema
10493
10635
  });
10494
10636
  /**
10495
- * Audio Metrics capability sliding-window aggregates over the
10496
- * pipeline audio inference results. Hosted by `addon-pipeline-analytics`
10497
- * (same addon that owns `zone-analytics`); the runtime-state slice
10498
- * gives operators a live read on dB level + dominant classes without
10499
- * a custom event subscription.
10637
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
10638
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
10639
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
10640
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
10500
10641
  */
10501
- var audioMetricsCapability = {
10502
- name: "audio-metrics",
10503
- scope: "device",
10504
- mode: "singleton",
10505
- deviceTypes: [DeviceType.Camera],
10506
- methods: {
10507
- /** Latest snapshot for this device. Null until the analytics
10508
- * pipeline has processed at least one audio window. */
10509
- getCurrentSnapshot: method(object({ deviceId: number() }), AudioMetricsSnapshotSchema.nullable()),
10510
- /**
10511
- * Time-series view of recent audio-metrics samples. The provider
10512
- * keeps an in-memory ring of ~1Hz samples (matching the slice-
10513
- * write rate) capped at `MAX_HISTORY_POINTS_KEPT` (provider-side).
10514
- * `windowSec` selects how far back to read; `sampleEveryMs`
10515
- * downsamples by bucketed averaging when finer than the kept
10516
- * granularity. Empty `points` array on freshly-booted providers
10517
- * with no audio yet — same convention as `getCurrentSnapshot`.
10518
- */
10519
- getHistory: method(object({
10520
- deviceId: number(),
10521
- /** History window in seconds. Default 300 (5 minutes).
10522
- * Provider clamps to its retention cap if larger. */
10523
- windowSec: number().int().positive().optional(),
10524
- /** Target sample interval in ms. Default 1000 (1 sample/second).
10525
- * Provider clamps to natural sample rate if smaller, and
10526
- * bucket-averages when bigger than the requested window
10527
- * would produce more than `maxPoints` samples. */
10528
- sampleEveryMs: number().int().positive().optional()
10529
- }), AudioMetricsHistorySchema)
10530
- },
10531
- /** Reactive runtime-state mirror — live `device.state.audioMetrics.value`. */
10532
- runtimeState: AudioMetricsSnapshotSchema
10533
- };
10642
+ var NcHistoryFilterSchema = object({
10643
+ ruleId: string().optional(),
10644
+ deviceId: number().optional(),
10645
+ status: NcHistoryStatusSchema.optional(),
10646
+ since: number().optional(),
10647
+ until: number().optional(),
10648
+ limit: number().int().min(1).max(500).default(100)
10649
+ });
10650
+ method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), method(object({ ruleId: string() }), object({ rule: NcRuleSchema.nullable() }), { auth: "admin" }), method(object({ rule: NcRuleInputSchema }), object({ rule: NcRuleSchema }), {
10651
+ kind: "mutation",
10652
+ auth: "admin",
10653
+ caller: "required"
10654
+ }), method(object({
10655
+ ruleId: string(),
10656
+ patch: NcRulePatchSchema
10657
+ }), object({ rule: NcRuleSchema }), {
10658
+ kind: "mutation",
10659
+ auth: "admin",
10660
+ caller: "required"
10661
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
10662
+ kind: "mutation",
10663
+ auth: "admin"
10664
+ }), method(object({
10665
+ ruleId: string(),
10666
+ enabled: boolean()
10667
+ }), object({ success: literal(true) }), {
10668
+ kind: "mutation",
10669
+ auth: "admin"
10670
+ }), method(object({
10671
+ rule: NcRuleInputSchema,
10672
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
10673
+ }), object({ results: array(NcTestResultSchema) }), {
10674
+ kind: "mutation",
10675
+ auth: "admin"
10676
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
10534
10677
  /**
10535
- * Automation-control cap. Models HA `automation.*` entities on
10536
- * `DeviceType.Automation`. An automation is a trigger+condition+
10537
- * action rule that can be enabled / disabled and manually fired
10538
- * via the `trigger` method.
10678
+ * TimelapseRule the STANDALONE scheduled timelapse producer's rule model.
10679
+ *
10680
+ * Spec: `docs/superpowers/specs/2026-07-24-nc-occupancy-timelapse-design.md`
10681
+ * §3.2/§3.3.
10682
+ *
10683
+ * Deliberately NOT a capability definition and NOT an `NcRule`:
10684
+ * - Every `NcDelivery` member is a *persisted-pipeline-record* trigger. A
10685
+ * timelapse fires on a SCHEDULE WINDOW BOUNDARY, evaluates no pipeline
10686
+ * record, and produces a video it assembled itself — so it rides no
10687
+ * delivery-enum member (the enum is frozen) and no cap method. This file is
10688
+ * a plain typed schema; it does NOT go through `npm run codegen`.
10689
+ * - It shares only the delivery leg (`notification-output.send`) and the
10690
+ * persistence/ownership patterns with the Notification Center, reusing
10691
+ * {@link NcScheduleSchema} (weekly windows, midnight-crossing, invertible)
10692
+ * and {@link NcRuleTargetSchema} (target ref + passthrough params).
10693
+ *
10694
+ * Ownership is SERVER-DERIVED. `ownerUserId` / `createdBy` / `createdAt` /
10695
+ * `updatedAt` / `id` / `lastGeneratedAt` live on the PERSISTED rule only —
10696
+ * {@link TimelapseRuleInputSchema} and {@link TimelapseRulePatchSchema} do not
10697
+ * carry them, so a forged client payload can never claim or re-own a rule
10698
+ * (Zod strips unknown keys). The store stamps them from the resolved caller.
10699
+ */
10700
+ /** `{{var}}` templating over camera/rule/time — same vocabulary as `NcRule`. */
10701
+ var TimelapseTemplateSchema = object({
10702
+ title: string().max(500).optional(),
10703
+ body: string().max(2e3).optional()
10704
+ });
10705
+ var NameField = string().min(1).max(200);
10706
+ var DeviceIdsField = array(number()).min(1);
10707
+ var CadenceSecField = number().int().min(2).max(3600);
10708
+ var FramerateField = number().int().min(1).max(60);
10709
+ var TargetsField = array(NcRuleTargetSchema).min(1);
10710
+ var PriorityField = number().int().min(1).max(5);
10711
+ /**
10712
+ * Client-supplied timelapse-rule fields. The server stamps id / createdBy /
10713
+ * createdAt / updatedAt / ownerUserId / lastGeneratedAt — none of them appear
10714
+ * here (see the ownership note above).
10715
+ */
10716
+ var TimelapseRuleInputSchema = object({
10717
+ name: NameField,
10718
+ enabled: boolean().default(true),
10719
+ /** Cameras sampled by this rule — one scratch dir + one artifact per device. */
10720
+ deviceIds: DeviceIdsField,
10721
+ /**
10722
+ * Activation window(s). REQUIRED (unlike `NcRule`, where an absent schedule
10723
+ * means "always active"): a timelapse is defined by its window boundaries —
10724
+ * open clears the scratch, close assembles and delivers.
10725
+ */
10726
+ schedule: NcScheduleSchema,
10727
+ /** Force-snapshot cadence inside the window, seconds (predecessor parity). */
10728
+ cadenceSec: CadenceSecField.default(15),
10729
+ /** Output frames per second of the assembled mp4 (predecessor parity). */
10730
+ framerate: FramerateField.default(10),
10731
+ /** `notification-output` targets the finished video/thumbnail is sent to. */
10732
+ targets: TargetsField,
10733
+ template: TimelapseTemplateSchema.optional(),
10734
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
10735
+ priority: PriorityField.default(3)
10736
+ });
10737
+ object({
10738
+ name: NameField.optional(),
10739
+ enabled: boolean().optional(),
10740
+ deviceIds: DeviceIdsField.optional(),
10741
+ schedule: NcScheduleSchema.optional(),
10742
+ cadenceSec: CadenceSecField.optional(),
10743
+ framerate: FramerateField.optional(),
10744
+ targets: TargetsField.optional(),
10745
+ template: TimelapseTemplateSchema.nullable().optional(),
10746
+ priority: PriorityField.optional()
10747
+ });
10748
+ TimelapseRuleInputSchema.extend({
10749
+ id: string(),
10750
+ /**
10751
+ * Ownership/visibility key. Absent = admin/global rule (visible to all).
10752
+ * Present = personal rule owned by this userId. Server-stamped from the
10753
+ * resolved caller; never trusted from a client payload.
10754
+ */
10755
+ ownerUserId: string().optional(),
10756
+ /**
10757
+ * Epoch-ms of the last successful generation — the 1-hour re-generation
10758
+ * guard's durable state (predecessor parity). Absent = never generated.
10759
+ */
10760
+ lastGeneratedAt: number().optional(),
10761
+ /** userId of the caller who created the rule (server-stamped). */
10762
+ createdBy: string(),
10763
+ createdAt: number(),
10764
+ updatedAt: number()
10765
+ });
10766
+ /**
10767
+ * Generic device-level status snapshot. Auto-registered by `BaseDevice`
10768
+ * for every device, regardless of provider — the kernel needs a uniform
10769
+ * cap-keyed slice for the basic device flags every consumer expects to
10770
+ * read across processes (the `online` flag in particular). Driver-specific
10771
+ * caps (`battery`, `doorbell`, …) carry their domain-specific state on
10772
+ * their own slices.
10539
10773
  *
10540
- * `trigger` accepts an optional `skipCondition` flag — when true,
10541
- * the automation's action block runs WITHOUT evaluating its
10542
- * condition block. Pair with `DeviceFeature.AutomationSkipCondition`
10543
- * to gate the UI checkbox for the manual-trigger dialog.
10774
+ * Pattern is identical to `battery`: schema-bearing `runtimeState`,
10775
+ * empty `methods`, single change event. Reads land at
10776
+ * `runtimeState.getCapState('device-status')`; writes at
10777
+ * `runtimeState.setCapState('device-status', …)`. Cross-process
10778
+ * consumers reach the same data via the `device-state` cap router
10779
+ * (`getCapSlice({deviceId, capName: 'device-status'})`).
10544
10780
  */
10545
- var AutomationControlStatusSchema = object({
10546
- /** Whether the automation is currently enabled. Disabled automations
10547
- * ignore their trigger block manual `trigger` still works. */
10548
- enabled: boolean(),
10549
- /** Whether the automation is currently executing its action block. */
10550
- isRunning: boolean(),
10551
- /** Ms epoch of the last successful run. 0 when never run. */
10552
- lastTriggeredAt: number(),
10553
- /** Failure description from the last completed run. Null on success
10554
- * or when never run. */
10555
- lastError: string().nullable(),
10556
- /** Ms epoch when the slice was last updated. */
10781
+ var DeviceStatusSchema = object({
10782
+ /**
10783
+ * Device-level liveness. Drivers flip via `markOnline(boolean)` on
10784
+ * `BaseDevice`. Provider semantics vary — RTSP aggregates broker
10785
+ * stream-health, Reolink reads firmware push events, ONVIF tracks
10786
+ * ping responses. This cap intentionally does NOT prescribe which
10787
+ * signal drives the flag.
10788
+ */
10789
+ online: boolean(),
10790
+ /** Ms epoch of the last `online` transition. Lets consumers tell
10791
+ * apart "just came online" from "still online". */
10557
10792
  lastChangedAt: number()
10558
10793
  });
10559
- var automationControlCapability = {
10560
- name: "automation-control",
10794
+ var deviceStatusCapability = {
10795
+ name: "device-status",
10561
10796
  scope: "device",
10562
10797
  deviceNative: true,
10563
10798
  mode: "singleton",
10564
- deviceTypes: [DeviceType.Automation],
10565
- methods: {
10566
- enable: method(object({ deviceId: number().int().nonnegative() }), _void(), {
10567
- kind: "mutation",
10568
- auth: "admin"
10569
- }),
10570
- disable: method(object({ deviceId: number().int().nonnegative() }), _void(), {
10571
- kind: "mutation",
10572
- auth: "admin"
10573
- }),
10574
- trigger: method(object({
10575
- deviceId: number().int().nonnegative(),
10576
- /** When true, fires the action block while bypassing the
10577
- * automation's condition evaluation. Gated by
10578
- * `DeviceFeature.AutomationSkipCondition`. */
10579
- skipCondition: boolean().optional()
10580
- }), _void(), {
10581
- kind: "mutation",
10582
- auth: "admin"
10583
- })
10584
- },
10799
+ methods: {},
10800
+ events: {
10801
+ /** Emitted when `online` transitions. Mirrors the semantics of
10802
+ * `battery.onStatusChanged`. */
10803
+ onStatusChanged: { data: object({
10804
+ deviceId: number(),
10805
+ status: DeviceStatusSchema
10806
+ }) } },
10585
10807
  status: {
10586
- schema: AutomationControlStatusSchema,
10808
+ schema: DeviceStatusSchema,
10587
10809
  kind: "push"
10588
10810
  },
10589
- /**
10590
- * Runtime-state slice — mirrored by the kernel. UI automation tile
10591
- * reads `enabled` (toggle) + `isRunning` (spinner) + `lastError`
10592
- * (badge) directly.
10593
- */
10594
- runtimeState: AutomationControlStatusSchema
10811
+ runtimeState: DeviceStatusSchema
10595
10812
  };
10596
10813
  /**
10597
- * Battery status snapshot. Emitted by providers whose device is
10598
- * battery-operated (cameras with `DeviceFeature.BatteryOperated`,
10599
- * future sensor/button accessories). Consumers build their own "low
10600
- * battery" alerting on top the cap deliberately does NOT enforce a
10601
- * threshold.
10814
+ * Per-device feature/identity probe slice. Holds the runtime-resolved
10815
+ * truth about what a device CAN do — which the kernel uses to:
10816
+ * 1. Reconcile accessory children (hub-children spawn siren/floodlight/PIR
10817
+ * based on what the firmware actually advertises).
10818
+ * 2. Compute the public `features: DeviceFeature[]` array surfaced via
10819
+ * `device-manager.listAll`.
10820
+ * 3. Decide which optional caps (PTZ, intercom, doorbell, battery, …)
10821
+ * to register on the device's capability surface.
10822
+ *
10823
+ * Auto-registered by `BaseDevice` for every device. Drivers populate the
10824
+ * slice from `onProbe()` (kernel calls it once after register, before
10825
+ * accessory reconciliation). Consumers read via:
10826
+ * `runtimeState.getCapState<FeatureProbeStatus>('feature-probe')`
10827
+ *
10828
+ * `flags` is an open record so each driver carries its own keys without
10829
+ * a centralized schema bottleneck — Reolink writes `hasPtz/hasIntercom`,
10830
+ * Hikvision writes `hasSupplementalLight/hasAlarmIo`, etc.
10831
+ *
10832
+ * Replaces the older driver-local `deviceCache.has*` blob: the per-device
10833
+ * config is for operator-edited overrides + UI snapshots; runtime probe
10834
+ * results belong in runtime-state where the kernel handles persistence,
10835
+ * cross-process mirroring, and reactive updates.
10602
10836
  */
10603
- var BatteryStatusSchema = object({
10604
- /** 0..100 inclusive. Firmware-reported. */
10605
- percentage: number().min(0).max(100),
10837
+ var FeatureProbeStatusSchema = object({
10606
10838
  /**
10607
- * Charging source. `'dc'` covers wall/USB adapters; `'solar'` is
10608
- * Reolink-specific for the Solar Panel 2 accessory (will become
10609
- * common on other battery cams). `'none'` means running on battery
10610
- * alone.
10839
+ * Driver-specific flag bag. Each driver picks its own key names — the
10840
+ * cap deliberately does NOT enforce a closed enum here. Reolink keys:
10841
+ * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,
10842
+ * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:
10843
+ * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.
10611
10844
  */
10612
- charging: _enum([
10613
- "dc",
10614
- "solar",
10615
- "none"
10616
- ]),
10845
+ flags: record(string(), unknown()),
10617
10846
  /**
10618
- * True when the camera firmware has gone into low-power mode. Battery
10619
- * providers MUST avoid polling during sleep reading the battery
10620
- * wakes the camera up and drains charge.
10847
+ * Coarse driver-classification lets cross-process consumers tell apart
10848
+ * cameras / battery-cams / NVRs without re-running the probe. `null`
10849
+ * before the first probe completes.
10621
10850
  */
10622
- sleeping: boolean(),
10623
- /** Ms epoch of the last observation. Lets consumers reason about freshness. */
10624
- lastUpdated: number(),
10851
+ deviceType: string().nullable(),
10852
+ /** Camera/firmware model string. `null` when the firmware doesn't expose it. */
10853
+ model: string().nullable(),
10854
+ /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */
10855
+ channelCount: number().nullable(),
10625
10856
  /**
10626
- * True when the source is a BINARY low-battery indicator (HA
10627
- * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
10628
- * charge level `percentage` is then a coarse stand-in (100 = normal,
10629
- * sub-threshold = low). UI MUST render "Normal"/"Low" instead of a
10630
- * misleading exact percentage. Absent/false → genuine 0–100 % reading.
10857
+ * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe
10858
+ * completes drivers' `getAccessoryChildren()` should treat zero as
10859
+ * "probe not done yet, return empty" so accessories aren't spawned
10860
+ * before the firmware is queried.
10631
10861
  */
10632
- binary: boolean().optional()
10862
+ lastProbedAt: number(),
10863
+ /**
10864
+ * Framework convention: every runtime-state slice carries this for the
10865
+ * createRuntimeStateBridge stale-check helper. We keep it in sync with
10866
+ * `lastProbedAt` on every write.
10867
+ */
10868
+ lastFetchedAt: number()
10633
10869
  });
10634
- var batteryCapability = {
10635
- name: "battery",
10870
+ var featureProbeCapability = {
10871
+ name: "feature-probe",
10636
10872
  scope: "device",
10637
10873
  deviceNative: true,
10638
10874
  mode: "singleton",
10639
- deviceTypes: [
10640
- DeviceType.Camera,
10641
- DeviceType.Sensor,
10642
- DeviceType.Button,
10643
- DeviceType.Switch
10644
- ],
10645
- methods: {
10646
- /**
10647
- * Explicitly wake the camera from low-power sleep ahead of a
10648
- * streaming session start. Consumers that initiate a stream
10649
- * against a sleeping battery cam (HomeKit Secure Video, Alexa
10650
- * RTCSession, snapshot wrappers) call this with a short timeout
10651
- * before establishing the media pipeline — the broker's own
10652
- * passive wake-on-dial works but adds 5–7 seconds to first-frame,
10653
- * during which the consumer renders a black screen. Pre-waking
10654
- * compresses that gap.
10655
- *
10656
- * Returns `awoke: true` when the firmware acknowledged the wake
10657
- * before `timeoutMs`. Returns `awoke: false` when it timed out OR
10658
- * the cap surface is unavailable (no Baichuan / firmware
10659
- * channel); the caller should still attempt the stream — the
10660
- * passive broker wake remains as fallback.
10661
- */
10662
- wakeForStream: method(object({
10663
- deviceId: number(),
10664
- /** Bound on the wait. Sensible range 3000–10000ms. */
10665
- timeoutMs: number().int().min(500).max(3e4).default(8e3)
10666
- }), object({
10667
- awoke: boolean(),
10668
- durationMs: number()
10669
- }), { kind: "mutation" }) },
10875
+ methods: {},
10670
10876
  events: {
10671
- /**
10672
- * Emitted whenever the cached status changes (firmware push OR
10673
- * poll observes a delta). The DeviceEventPropagator mirrors this
10674
- * event on the parent chain — subscribing to a camera's source
10675
- * receives battery events from child accessories automatically.
10676
- */
10677
- onStatusChanged: { data: object({
10877
+ /** Fires whenever a fresh probe completes (kernel-driven `reprobe()`
10878
+ * or driver-initiated re-detect after a state change). */
10879
+ onProbeChanged: { data: object({
10678
10880
  deviceId: number(),
10679
- status: BatteryStatusSchema
10881
+ status: FeatureProbeStatusSchema
10680
10882
  }) } },
10681
10883
  status: {
10682
- schema: BatteryStatusSchema,
10683
- kind: "push",
10684
- empty: {
10685
- percentage: 0,
10686
- charging: "none",
10687
- sleeping: false,
10688
- lastUpdated: 0
10689
- }
10884
+ schema: FeatureProbeStatusSchema,
10885
+ kind: "push"
10690
10886
  },
10691
- /**
10692
- * Runtime-state slice — every provider that registers this cap
10693
- * stores the same shape under `device.runtimeState[battery]`.
10694
- * Cross-provider uniformity: a Reolink Argus, a Frigate sensor
10695
- * proxy, an ONVIF battery cam all read/write the same keys.
10696
- * Consumers (BatteryBadge, snapshot wrapper sleep gate) read once
10697
- * via `device.runtimeState.getCapState('battery')` regardless of
10698
- * the underlying driver.
10699
- */
10700
- runtimeState: BatteryStatusSchema
10887
+ runtimeState: FeatureProbeStatusSchema
10701
10888
  };
10702
10889
  /**
10703
- * Generic boolean sensor last-resort fallback when no domain-
10704
- * specific binary cap fits (Home Assistant `binary_sensor` without a
10705
- * known `device_class`, or a domain we haven't typed yet). Pure
10706
- * pass-through: just the bool + timestamp. Push-driven.
10707
- *
10708
- * Prefer the typed alternatives (`contact`, `flood`, `smoke`,
10709
- * `carbon-monoxide`, `gas`, `tamper`, `vibration`, `connectivity`,
10710
- * `motion`) when the semantics match — export adapters render those
10711
- * with the right HomeKit / Alexa display category.
10890
+ * Multi-metric air-quality slice. Covers CO₂, total VOCs, particulate
10891
+ * matter at PM2.5 / PM10, and a derived AQI index — all optional so
10892
+ * a single-metric source populates only what it observes. Mirrors
10893
+ * the HA `sensor` device_class set (`co2`, `volatile_organic_compounds`,
10894
+ * `pm25`, `pm10`, `aqi`) collapsed into one cap because a typical
10895
+ * air-quality node reports several of these together; modelling them
10896
+ * as siblings keeps a single timestamp + one slice subscription.
10712
10897
  */
10713
- var BinaryStatusSchema = object({
10714
- on: boolean(),
10715
- /** Ms epoch of the last transition. 0 if never observed. */
10716
- lastChangedAt: number()
10898
+ var AirQualitySensorStatusSchema = object({
10899
+ /** Carbon dioxide concentration in ppm. */
10900
+ co2Ppm: number().min(0).optional(),
10901
+ /** Total volatile organic compounds in ppb. */
10902
+ vocPpb: number().min(0).optional(),
10903
+ /** Particulate matter ≤ 2.5 μm in µg/m³. */
10904
+ pm25: number().min(0).optional(),
10905
+ /** Particulate matter ≤ 10 μm in µg/m³. */
10906
+ pm10: number().min(0).optional(),
10907
+ /** Composite AQI value (typically 0..500). */
10908
+ aqi: number().optional(),
10909
+ /** Ms epoch when the slice was last updated. */
10910
+ lastFetchedAt: number(),
10911
+ /** Live display unit of the single metric this slice carries (e.g. HA
10912
+ * `attributes.unit_of_measurement` → 'ppm' / 'ppb' / 'µg/m³'). Each
10913
+ * upstream `sensor.*` entity surfaces ONE device_class, so one unit
10914
+ * per slice is unambiguous. */
10915
+ unit: string().optional(),
10916
+ /** Suggested decimal places for numeric display.
10917
+ * Populated live from the upstream source when provided (e.g. HA
10918
+ * `attributes.suggested_display_precision`). Falls back to
10919
+ * auto-formatting when absent. */
10920
+ precision: number().int().min(0).max(10).optional()
10717
10921
  });
10718
- var binaryCapability = {
10719
- name: "binary",
10922
+ var airQualitySensorCapability = {
10923
+ name: "air-quality-sensor",
10720
10924
  scope: "device",
10721
10925
  deviceNative: true,
10722
10926
  mode: "singleton",
10723
10927
  deviceTypes: [DeviceType.Sensor],
10724
10928
  methods: {},
10725
10929
  status: {
10726
- schema: BinaryStatusSchema,
10930
+ schema: AirQualitySensorStatusSchema,
10727
10931
  kind: "push"
10728
10932
  },
10729
- runtimeState: BinaryStatusSchema
10933
+ runtimeState: AirQualitySensorStatusSchema
10730
10934
  };
10731
10935
  /**
10732
- * Dimmable-light brightness control. Co-exists with `switch` on the
10733
- * same device the switch toggles on/off, this cap sets the level
10734
- * applied when the light is on. Drivers map their per-vendor dim
10735
- * controls to this single-method surface.
10936
+ * Alarm-panel cap. Models HA `alarm_control_panel.*` on
10937
+ * `DeviceType.AlarmPanel`. State follows HA's canonical lifecycle
10938
+ * across disarmed / armed_(home|away|night|vacation|custom_bypass) /
10939
+ * arming / pending / triggered / disarming.
10736
10940
  *
10737
- * The cap is intentionally minimal: a single `setBrightness({deviceId,
10738
- * percentage})` mutation plus the auto-injected `getStatus`. Drivers
10739
- * that expose richer controls (color temperature, scenes, schedules)
10740
- * should surface those via the device's `getSettingsUISchema()`
10741
- * instead of bloating this cap.
10941
+ * Many panels require a PIN code on arm / disarm — the optional
10942
+ * `code` field on the methods passes it through to the upstream
10943
+ * service; it's NEVER persisted in the runtime slice or any event
10944
+ * payload. The presence of a required code is signalled by
10945
+ * `DeviceFeature.AlarmPinRequired` so the UI gates a code-entry
10946
+ * field without a slice fetch.
10947
+ *
10948
+ * `availableModes` mirrors HA's `supported_features`-derived arm
10949
+ * mode list — the UI renders only the buttons the panel accepts.
10742
10950
  */
10743
- var BrightnessStatusSchema = object({
10744
- /** Current level as 0..100 inclusive. Firmware-reported. */
10745
- percentage: number().min(0).max(100),
10746
- /** Ms epoch of the last operator-driven change. Useful for UI freshness. */
10951
+ var AlarmStateSchema = _enum([
10952
+ "disarmed",
10953
+ "armed_home",
10954
+ "armed_away",
10955
+ "armed_night",
10956
+ "armed_vacation",
10957
+ "armed_custom_bypass",
10958
+ "arming",
10959
+ "disarming",
10960
+ "pending",
10961
+ "triggered"
10962
+ ]);
10963
+ var AlarmArmModeSchema = _enum([
10964
+ "home",
10965
+ "away",
10966
+ "night",
10967
+ "vacation",
10968
+ "custom_bypass"
10969
+ ]);
10970
+ var AlarmPanelStatusSchema = object({
10971
+ /** Current lifecycle state. */
10972
+ state: AlarmStateSchema,
10973
+ /** Subset of arm modes the panel accepts. UI renders one button per
10974
+ * mode in this list. */
10975
+ availableModes: array(AlarmArmModeSchema),
10976
+ /** Whether the panel requires a PIN on arm / disarm. Mirrors
10977
+ * `DeviceFeature.AlarmPinRequired` for slice consumers. */
10978
+ requiresCode: boolean(),
10979
+ /** Ms epoch when the slice was last updated. */
10747
10980
  lastChangedAt: number()
10748
10981
  });
10749
- var brightnessCapability = {
10750
- name: "brightness",
10982
+ var alarmPanelCapability = {
10983
+ name: "alarm-panel",
10751
10984
  scope: "device",
10752
10985
  deviceNative: true,
10753
10986
  mode: "singleton",
10754
- deviceTypes: [DeviceType.Light],
10755
- methods: { setBrightness: method(object({
10756
- deviceId: number().int().nonnegative(),
10757
- percentage: number().min(0).max(100)
10758
- }), _void(), {
10759
- kind: "mutation",
10760
- auth: "admin"
10761
- }) },
10762
- events: {
10763
- /**
10764
- * Emitted whenever the brightness changes — operator action OR
10765
- * firmware push. Subscribers (UI sliders, automation engines) react
10766
- * without polling.
10767
- */
10768
- onBrightnessChanged: { data: object({
10769
- deviceId: number(),
10770
- percentage: number().min(0).max(100),
10771
- lastChangedAt: number()
10772
- }) } },
10773
- status: {
10774
- schema: BrightnessStatusSchema,
10775
- kind: "command-driven"
10776
- },
10777
- /**
10778
- * Runtime-state slice the last applied brightness level, mirrored
10779
- * by the kernel. Read via `device.state.brightness.value` so UI
10780
- * sliders surface the current level without polling the provider.
10781
- */
10782
- runtimeState: BrightnessStatusSchema
10783
- };
10784
- /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
10987
+ deviceTypes: [DeviceType.AlarmPanel],
10988
+ methods: {
10989
+ arm: method(object({
10990
+ deviceId: number().int().nonnegative(),
10991
+ mode: AlarmArmModeSchema,
10992
+ /** Optional PIN code. Required when `requiresCode === true`.
10993
+ * Passed through to the upstream service; never persisted. */
10994
+ code: string().min(1).optional()
10995
+ }), _void(), {
10996
+ kind: "mutation",
10997
+ auth: "admin"
10998
+ }),
10999
+ disarm: method(object({
11000
+ deviceId: number().int().nonnegative(),
11001
+ code: string().min(1).optional()
11002
+ }), _void(), {
11003
+ kind: "mutation",
11004
+ auth: "admin"
11005
+ }),
11006
+ /**
11007
+ * Force the panel into the `triggered` state — used by HA
11008
+ * automations to surface external sensor events through the panel
11009
+ * (e.g. a Reolink camera intrusion event firing the security
11010
+ * system). Provider rejects when the panel hardware doesn't
11011
+ * support a software-initiated trigger.
11012
+ */
11013
+ trigger: method(object({ deviceId: number().int().nonnegative() }), _void(), {
11014
+ kind: "mutation",
11015
+ auth: "admin"
11016
+ })
11017
+ },
11018
+ status: {
11019
+ schema: AlarmPanelStatusSchema,
11020
+ kind: "push"
11021
+ },
11022
+ /**
11023
+ * Runtime-state slice — mirrored by the kernel. UI panel reads the
11024
+ * full slice; renders an arm button per `availableModes` entry and
11025
+ * a PIN field iff `requiresCode === true`.
11026
+ */
11027
+ runtimeState: AlarmPanelStatusSchema
11028
+ };
11029
+ /**
11030
+ * Ambient illuminance reading in lux. Drives Home Assistant `sensor`
11031
+ * entries with `device_class: illuminance`.
11032
+ */
11033
+ var AmbientLightSensorStatusSchema = object({
11034
+ /** Current illuminance in lux (lx). */
11035
+ lux: number().min(0),
11036
+ /** Ms epoch when the slice was last updated. */
11037
+ lastFetchedAt: number(),
11038
+ /** Live display unit from the upstream source (e.g. HA
11039
+ * `attributes.unit_of_measurement`). The UI prefers this over the
11040
+ * role's canonical unit. Absent → fall back to the canonical unit. */
11041
+ unit: string().optional(),
11042
+ /** Suggested decimal places for numeric display.
11043
+ * Populated live from the upstream source when provided (e.g. HA
11044
+ * `attributes.suggested_display_precision`). Falls back to
11045
+ * auto-formatting when absent. */
11046
+ precision: number().int().min(0).max(10).optional()
11047
+ });
11048
+ var ambientLightSensorCapability = {
11049
+ name: "ambient-light-sensor",
11050
+ scope: "device",
11051
+ deviceNative: true,
11052
+ mode: "singleton",
11053
+ deviceTypes: [DeviceType.Sensor],
11054
+ methods: {},
11055
+ status: {
11056
+ schema: AmbientLightSensorStatusSchema,
11057
+ kind: "push"
11058
+ },
11059
+ runtimeState: AmbientLightSensorStatusSchema
11060
+ };
11061
+ /**
11062
+ * Per-class audio metrics aggregated over a sliding window.
11063
+ */
11064
+ var AudioClassSummarySchema = object({
11065
+ className: string(),
11066
+ /** Number of windows (chunks) where this class was the top hit. */
11067
+ hits: number().int().nonnegative(),
11068
+ /** Mean score across those hits, clamped to [0,1]. */
11069
+ avgScore: number().min(0).max(1),
11070
+ /** Peak score in the window. */
11071
+ peakScore: number().min(0).max(1)
11072
+ });
11073
+ /**
11074
+ * Per-camera audio metrics snapshot — emitted by the analytics frame
11075
+ * handler on every `pipeline.audio-inference-result` event and
11076
+ * mirrored into the `audio-metrics` device-state slice. Symmetric
11077
+ * with `zone-analytics` snapshots for video — every consumer
11078
+ * (admin UI panel, automations, alert rules) reads via the
11079
+ * canonical `device.state.audioMetrics.value` reactive handle.
11080
+ *
11081
+ * Aggregates are computed over a rolling `windowSec` window
11082
+ * (default 60s). Past that window, classes drop out of `byClass`
11083
+ * and the level history shifts forward.
11084
+ */
11085
+ var AudioMetricsSnapshotSchema = object({
11086
+ /** Wall-clock timestamp (ms) of the most recent audio window. */
11087
+ ts: number().int(),
11088
+ /** Sliding-window length (seconds) used for aggregation. */
11089
+ windowSec: number().int().positive(),
11090
+ /** Latest level reading from the most recent window. */
11091
+ level: object({
11092
+ rms: number(),
11093
+ dbfs: number()
11094
+ }),
11095
+ /** Peak dBFS observed across the rolling window. */
11096
+ peakDbfs: number(),
11097
+ /** Mean dBFS across the rolling window. */
11098
+ avgDbfs: number(),
11099
+ /** Most recent above-threshold classification, or null on silence. */
11100
+ current: object({
11101
+ className: string(),
11102
+ score: number().min(0).max(1),
11103
+ timestamp: number().int()
11104
+ }).nullable(),
11105
+ /** Per-class summary across the rolling window — keys are
11106
+ * `macroClass` strings (e.g. `dog_bark`, `speech`, `glass_break`). */
11107
+ byClass: array(AudioClassSummarySchema).readonly()
11108
+ });
11109
+ /**
11110
+ * Audio-metrics history payload — a series of `AudioMetricsHistoryPoint`
11111
+ * samples capped at `maxPoints` (default 1024). When the requested
11112
+ * `windowSec / sampleEveryMs` would exceed the cap, the provider
11113
+ * subsamples by bucketed averaging and reports the effective sample
11114
+ * spacing on `effectiveSampleEveryMs` so the UI can label the x-axis.
11115
+ */
11116
+ var AudioMetricsHistorySchema = object({
11117
+ points: array(object({
11118
+ /** Wall-clock ms when this sample was recorded. */
11119
+ ts: number().int(),
11120
+ /** Instantaneous dBFS level at sample time. `null` for windows where
11121
+ * the source had no level reading (rare; happens at decode startup). */
11122
+ dbfs: number().nullable(),
11123
+ /** Rolling-window peak dBFS at sample time. Same window the live
11124
+ * snapshot reports. */
11125
+ peakDbfs: number(),
11126
+ /** Rolling-window mean dBFS at sample time. */
11127
+ avgDbfs: number(),
11128
+ /** Dominant above-threshold class at sample time, or null on silence. */
11129
+ topClass: string().nullable(),
11130
+ /** Score of the dominant class (`null` whenever `topClass` is null). */
11131
+ topScore: number().min(0).max(1).nullable()
11132
+ })).readonly(),
11133
+ /** Actual ms between adjacent samples after any subsampling. */
11134
+ effectiveSampleEveryMs: number().int().positive(),
11135
+ /** Wall-clock window covered by `points` (`points[N-1].ts - points[0].ts`),
11136
+ * or `0` when there's fewer than 2 samples. */
11137
+ windowMsActual: number().int().nonnegative()
11138
+ });
11139
+ /**
11140
+ * Audio Metrics capability — sliding-window aggregates over the
11141
+ * pipeline audio inference results. Hosted by `addon-pipeline-analytics`
11142
+ * (same addon that owns `zone-analytics`); the runtime-state slice
11143
+ * gives operators a live read on dB level + dominant classes without
11144
+ * a custom event subscription.
11145
+ */
11146
+ var audioMetricsCapability = {
11147
+ name: "audio-metrics",
11148
+ scope: "device",
11149
+ mode: "singleton",
11150
+ deviceTypes: [DeviceType.Camera],
11151
+ methods: {
11152
+ /** Latest snapshot for this device. Null until the analytics
11153
+ * pipeline has processed at least one audio window. */
11154
+ getCurrentSnapshot: method(object({ deviceId: number() }), AudioMetricsSnapshotSchema.nullable()),
11155
+ /**
11156
+ * Time-series view of recent audio-metrics samples. The provider
11157
+ * keeps an in-memory ring of ~1Hz samples (matching the slice-
11158
+ * write rate) capped at `MAX_HISTORY_POINTS_KEPT` (provider-side).
11159
+ * `windowSec` selects how far back to read; `sampleEveryMs`
11160
+ * downsamples by bucketed averaging when finer than the kept
11161
+ * granularity. Empty `points` array on freshly-booted providers
11162
+ * with no audio yet — same convention as `getCurrentSnapshot`.
11163
+ */
11164
+ getHistory: method(object({
11165
+ deviceId: number(),
11166
+ /** History window in seconds. Default 300 (5 minutes).
11167
+ * Provider clamps to its retention cap if larger. */
11168
+ windowSec: number().int().positive().optional(),
11169
+ /** Target sample interval in ms. Default 1000 (1 sample/second).
11170
+ * Provider clamps to natural sample rate if smaller, and
11171
+ * bucket-averages when bigger than the requested window
11172
+ * would produce more than `maxPoints` samples. */
11173
+ sampleEveryMs: number().int().positive().optional()
11174
+ }), AudioMetricsHistorySchema)
11175
+ },
11176
+ /** Reactive runtime-state mirror — live `device.state.audioMetrics.value`. */
11177
+ runtimeState: AudioMetricsSnapshotSchema
11178
+ };
11179
+ /**
11180
+ * Automation-control cap. Models HA `automation.*` entities on
11181
+ * `DeviceType.Automation`. An automation is a trigger+condition+
11182
+ * action rule that can be enabled / disabled and manually fired
11183
+ * via the `trigger` method.
11184
+ *
11185
+ * `trigger` accepts an optional `skipCondition` flag — when true,
11186
+ * the automation's action block runs WITHOUT evaluating its
11187
+ * condition block. Pair with `DeviceFeature.AutomationSkipCondition`
11188
+ * to gate the UI checkbox for the manual-trigger dialog.
11189
+ */
11190
+ var AutomationControlStatusSchema = object({
11191
+ /** Whether the automation is currently enabled. Disabled automations
11192
+ * ignore their trigger block — manual `trigger` still works. */
11193
+ enabled: boolean(),
11194
+ /** Whether the automation is currently executing its action block. */
11195
+ isRunning: boolean(),
11196
+ /** Ms epoch of the last successful run. 0 when never run. */
11197
+ lastTriggeredAt: number(),
11198
+ /** Failure description from the last completed run. Null on success
11199
+ * or when never run. */
11200
+ lastError: string().nullable(),
11201
+ /** Ms epoch when the slice was last updated. */
11202
+ lastChangedAt: number()
11203
+ });
11204
+ var automationControlCapability = {
11205
+ name: "automation-control",
11206
+ scope: "device",
11207
+ deviceNative: true,
11208
+ mode: "singleton",
11209
+ deviceTypes: [DeviceType.Automation],
11210
+ methods: {
11211
+ enable: method(object({ deviceId: number().int().nonnegative() }), _void(), {
11212
+ kind: "mutation",
11213
+ auth: "admin"
11214
+ }),
11215
+ disable: method(object({ deviceId: number().int().nonnegative() }), _void(), {
11216
+ kind: "mutation",
11217
+ auth: "admin"
11218
+ }),
11219
+ trigger: method(object({
11220
+ deviceId: number().int().nonnegative(),
11221
+ /** When true, fires the action block while bypassing the
11222
+ * automation's condition evaluation. Gated by
11223
+ * `DeviceFeature.AutomationSkipCondition`. */
11224
+ skipCondition: boolean().optional()
11225
+ }), _void(), {
11226
+ kind: "mutation",
11227
+ auth: "admin"
11228
+ })
11229
+ },
11230
+ status: {
11231
+ schema: AutomationControlStatusSchema,
11232
+ kind: "push"
11233
+ },
11234
+ /**
11235
+ * Runtime-state slice — mirrored by the kernel. UI automation tile
11236
+ * reads `enabled` (toggle) + `isRunning` (spinner) + `lastError`
11237
+ * (badge) directly.
11238
+ */
11239
+ runtimeState: AutomationControlStatusSchema
11240
+ };
11241
+ /**
11242
+ * Battery status snapshot. Emitted by providers whose device is
11243
+ * battery-operated (cameras with `DeviceFeature.BatteryOperated`,
11244
+ * future sensor/button accessories). Consumers build their own "low
11245
+ * battery" alerting on top — the cap deliberately does NOT enforce a
11246
+ * threshold.
11247
+ */
11248
+ var BatteryStatusSchema = object({
11249
+ /** 0..100 inclusive. Firmware-reported. */
11250
+ percentage: number().min(0).max(100),
11251
+ /**
11252
+ * Charging source. `'dc'` covers wall/USB adapters; `'solar'` is
11253
+ * Reolink-specific for the Solar Panel 2 accessory (will become
11254
+ * common on other battery cams). `'none'` means running on battery
11255
+ * alone.
11256
+ */
11257
+ charging: _enum([
11258
+ "dc",
11259
+ "solar",
11260
+ "none"
11261
+ ]),
11262
+ /**
11263
+ * True when the camera firmware has gone into low-power mode. Battery
11264
+ * providers MUST avoid polling during sleep — reading the battery
11265
+ * wakes the camera up and drains charge.
11266
+ */
11267
+ sleeping: boolean(),
11268
+ /** Ms epoch of the last observation. Lets consumers reason about freshness. */
11269
+ lastUpdated: number(),
11270
+ /**
11271
+ * True when the source is a BINARY low-battery indicator (HA
11272
+ * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
11273
+ * charge level — `percentage` is then a coarse stand-in (100 = normal,
11274
+ * sub-threshold = low). UI MUST render "Normal"/"Low" instead of a
11275
+ * misleading exact percentage. Absent/false → genuine 0–100 % reading.
11276
+ */
11277
+ binary: boolean().optional()
11278
+ });
11279
+ var batteryCapability = {
11280
+ name: "battery",
11281
+ scope: "device",
11282
+ deviceNative: true,
11283
+ mode: "singleton",
11284
+ deviceTypes: [
11285
+ DeviceType.Camera,
11286
+ DeviceType.Sensor,
11287
+ DeviceType.Button,
11288
+ DeviceType.Switch
11289
+ ],
11290
+ methods: {
11291
+ /**
11292
+ * Explicitly wake the camera from low-power sleep ahead of a
11293
+ * streaming session start. Consumers that initiate a stream
11294
+ * against a sleeping battery cam (HomeKit Secure Video, Alexa
11295
+ * RTCSession, snapshot wrappers) call this with a short timeout
11296
+ * before establishing the media pipeline — the broker's own
11297
+ * passive wake-on-dial works but adds 5–7 seconds to first-frame,
11298
+ * during which the consumer renders a black screen. Pre-waking
11299
+ * compresses that gap.
11300
+ *
11301
+ * Returns `awoke: true` when the firmware acknowledged the wake
11302
+ * before `timeoutMs`. Returns `awoke: false` when it timed out OR
11303
+ * the cap surface is unavailable (no Baichuan / firmware
11304
+ * channel); the caller should still attempt the stream — the
11305
+ * passive broker wake remains as fallback.
11306
+ */
11307
+ wakeForStream: method(object({
11308
+ deviceId: number(),
11309
+ /** Bound on the wait. Sensible range 3000–10000ms. */
11310
+ timeoutMs: number().int().min(500).max(3e4).default(8e3)
11311
+ }), object({
11312
+ awoke: boolean(),
11313
+ durationMs: number()
11314
+ }), { kind: "mutation" }) },
11315
+ events: {
11316
+ /**
11317
+ * Emitted whenever the cached status changes (firmware push OR
11318
+ * poll observes a delta). The DeviceEventPropagator mirrors this
11319
+ * event on the parent chain — subscribing to a camera's source
11320
+ * receives battery events from child accessories automatically.
11321
+ */
11322
+ onStatusChanged: { data: object({
11323
+ deviceId: number(),
11324
+ status: BatteryStatusSchema
11325
+ }) } },
11326
+ status: {
11327
+ schema: BatteryStatusSchema,
11328
+ kind: "push",
11329
+ empty: {
11330
+ percentage: 0,
11331
+ charging: "none",
11332
+ sleeping: false,
11333
+ lastUpdated: 0
11334
+ }
11335
+ },
11336
+ /**
11337
+ * Runtime-state slice — every provider that registers this cap
11338
+ * stores the same shape under `device.runtimeState[battery]`.
11339
+ * Cross-provider uniformity: a Reolink Argus, a Frigate sensor
11340
+ * proxy, an ONVIF battery cam all read/write the same keys.
11341
+ * Consumers (BatteryBadge, snapshot wrapper sleep gate) read once
11342
+ * via `device.runtimeState.getCapState('battery')` regardless of
11343
+ * the underlying driver.
11344
+ */
11345
+ runtimeState: BatteryStatusSchema
11346
+ };
11347
+ /**
11348
+ * Generic boolean sensor — last-resort fallback when no domain-
11349
+ * specific binary cap fits (Home Assistant `binary_sensor` without a
11350
+ * known `device_class`, or a domain we haven't typed yet). Pure
11351
+ * pass-through: just the bool + timestamp. Push-driven.
11352
+ *
11353
+ * Prefer the typed alternatives (`contact`, `flood`, `smoke`,
11354
+ * `carbon-monoxide`, `gas`, `tamper`, `vibration`, `connectivity`,
11355
+ * `motion`) when the semantics match — export adapters render those
11356
+ * with the right HomeKit / Alexa display category.
11357
+ */
11358
+ var BinaryStatusSchema = object({
11359
+ on: boolean(),
11360
+ /** Ms epoch of the last transition. 0 if never observed. */
11361
+ lastChangedAt: number()
11362
+ });
11363
+ var binaryCapability = {
11364
+ name: "binary",
11365
+ scope: "device",
11366
+ deviceNative: true,
11367
+ mode: "singleton",
11368
+ deviceTypes: [DeviceType.Sensor],
11369
+ methods: {},
11370
+ status: {
11371
+ schema: BinaryStatusSchema,
11372
+ kind: "push"
11373
+ },
11374
+ runtimeState: BinaryStatusSchema
11375
+ };
11376
+ /**
11377
+ * Dimmable-light brightness control. Co-exists with `switch` on the
11378
+ * same device — the switch toggles on/off, this cap sets the level
11379
+ * applied when the light is on. Drivers map their per-vendor dim
11380
+ * controls to this single-method surface.
11381
+ *
11382
+ * The cap is intentionally minimal: a single `setBrightness({deviceId,
11383
+ * percentage})` mutation plus the auto-injected `getStatus`. Drivers
11384
+ * that expose richer controls (color temperature, scenes, schedules)
11385
+ * should surface those via the device's `getSettingsUISchema()`
11386
+ * instead of bloating this cap.
11387
+ */
11388
+ var BrightnessStatusSchema = object({
11389
+ /** Current level as 0..100 inclusive. Firmware-reported. */
11390
+ percentage: number().min(0).max(100),
11391
+ /** Ms epoch of the last operator-driven change. Useful for UI freshness. */
11392
+ lastChangedAt: number()
11393
+ });
11394
+ var brightnessCapability = {
11395
+ name: "brightness",
11396
+ scope: "device",
11397
+ deviceNative: true,
11398
+ mode: "singleton",
11399
+ deviceTypes: [DeviceType.Light],
11400
+ methods: { setBrightness: method(object({
11401
+ deviceId: number().int().nonnegative(),
11402
+ percentage: number().min(0).max(100)
11403
+ }), _void(), {
11404
+ kind: "mutation",
11405
+ auth: "admin"
11406
+ }) },
11407
+ events: {
11408
+ /**
11409
+ * Emitted whenever the brightness changes — operator action OR
11410
+ * firmware push. Subscribers (UI sliders, automation engines) react
11411
+ * without polling.
11412
+ */
11413
+ onBrightnessChanged: { data: object({
11414
+ deviceId: number(),
11415
+ percentage: number().min(0).max(100),
11416
+ lastChangedAt: number()
11417
+ }) } },
11418
+ status: {
11419
+ schema: BrightnessStatusSchema,
11420
+ kind: "command-driven"
11421
+ },
11422
+ /**
11423
+ * Runtime-state slice — the last applied brightness level, mirrored
11424
+ * by the kernel. Read via `device.state.brightness.value` so UI
11425
+ * sliders surface the current level without polling the provider.
11426
+ */
11427
+ runtimeState: BrightnessStatusSchema
11428
+ };
11429
+ /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
10785
11430
  var StreamFormatSchema = _enum([
10786
11431
  "webrtc",
10787
11432
  "hls",
@@ -14232,104 +14877,43 @@ var MotionTriggerStatusSchema = object({
14232
14877
  /**
14233
14878
  * Persistent slice mirrored across restarts. The provider writes here
14234
14879
  * on every successful firmware fetch / setMotionTrigger push; the cap
14235
- * router and admin-ui hero read straight from this snapshot via
14236
- * `device.state.motionTrigger.value` instead of re-issuing a firmware
14237
- * round-trip on every UI mount. `lastFetchedAt` lets the framework
14238
- * helper (`createRuntimeStateBridge`) stale-check before deciding
14239
- * whether to refresh from the camera.
14240
- */
14241
- var MotionTriggerRuntimeStateSchema = MotionTriggerStatusSchema.extend({
14242
- /** Ms epoch of the last successful camera fetch (0 = never). */
14243
- lastFetchedAt: number() });
14244
- var motionTriggerCapability = {
14245
- name: "motion-trigger",
14246
- scope: "device",
14247
- deviceNative: true,
14248
- mode: "singleton",
14249
- deviceTypes: [
14250
- DeviceType.Light,
14251
- DeviceType.Siren,
14252
- DeviceType.Switch
14253
- ],
14254
- methods: { setMotionTrigger: method(object({
14255
- deviceId: number().int().nonnegative(),
14256
- enabled: boolean()
14257
- }), _void(), {
14258
- kind: "mutation",
14259
- auth: "admin"
14260
- }) },
14261
- events: { onMotionTriggerChanged: { data: object({
14262
- deviceId: number(),
14263
- enabled: boolean(),
14264
- lastChangedAt: number()
14265
- }) } },
14266
- status: {
14267
- schema: MotionTriggerStatusSchema,
14268
- kind: "command-driven"
14269
- },
14270
- runtimeState: MotionTriggerRuntimeStateSchema
14271
- };
14272
- /**
14273
- * Shared geometry vocabulary for on-frame shape caps — privacy-mask,
14274
- * motion-zones, and the detection zones/lines editor all speak this one
14275
- * language so a single drawing-plane editor and the providers stay
14276
- * decoupled from each cap's storage.
14277
- *
14278
- * All coordinates are normalized 0..1 of the camera frame (top-left
14279
- * origin). Each cap composes the SUBSET of shape kinds it supports and
14280
- * advertises it via `supportedShapes` in its `getOptions`.
14281
- */
14282
- /** A normalized 0..1 point (top-left origin). */
14283
- var MaskPointSchema = object({
14284
- x: number(),
14285
- y: number()
14286
- });
14287
- /** Axis-aligned rectangle (normalized 0..1). */
14288
- var MaskRectShapeSchema = object({
14289
- kind: literal("rect"),
14290
- x: number(),
14291
- y: number(),
14292
- width: number(),
14293
- height: number()
14294
- });
14295
- /** Free polygon — an ordered list of normalized vertices (≥3). */
14296
- var MaskPolygonShapeSchema = object({
14297
- kind: literal("polygon"),
14298
- points: array(MaskPointSchema)
14299
- });
14300
- /** Boolean cell grid — row-major, length === gridWidth*gridHeight. */
14301
- var MaskGridShapeSchema = object({
14302
- kind: literal("grid"),
14303
- gridWidth: number(),
14304
- gridHeight: number(),
14305
- cells: array(boolean())
14306
- });
14307
- discriminatedUnion("kind", [
14308
- MaskRectShapeSchema,
14309
- MaskPolygonShapeSchema,
14310
- MaskGridShapeSchema,
14311
- object({
14312
- kind: literal("line"),
14313
- points: array(MaskPointSchema)
14314
- })
14315
- ]);
14316
- /** Every shape-kind discriminant, for `supportedShapes` advertisement. */
14317
- var MaskShapeKindSchema = _enum([
14318
- "rect",
14319
- "polygon",
14320
- "grid",
14321
- "line"
14322
- ]);
14323
- /** Polygon vertex bounds when a cap supports 'polygon' (e.g. Hikvision {min:4,max:4}). */
14324
- var MaskPolygonVerticesSchema = object({
14325
- min: number(),
14326
- max: number()
14327
- });
14328
- /** Grid dimensions when a cap supports 'grid'. */
14329
- var MaskGridDimsSchema = object({
14330
- width: number(),
14331
- height: number()
14332
- });
14880
+ * router and admin-ui hero read straight from this snapshot via
14881
+ * `device.state.motionTrigger.value` instead of re-issuing a firmware
14882
+ * round-trip on every UI mount. `lastFetchedAt` lets the framework
14883
+ * helper (`createRuntimeStateBridge`) stale-check before deciding
14884
+ * whether to refresh from the camera.
14885
+ */
14886
+ var MotionTriggerRuntimeStateSchema = MotionTriggerStatusSchema.extend({
14887
+ /** Ms epoch of the last successful camera fetch (0 = never). */
14888
+ lastFetchedAt: number() });
14889
+ var motionTriggerCapability = {
14890
+ name: "motion-trigger",
14891
+ scope: "device",
14892
+ deviceNative: true,
14893
+ mode: "singleton",
14894
+ deviceTypes: [
14895
+ DeviceType.Light,
14896
+ DeviceType.Siren,
14897
+ DeviceType.Switch
14898
+ ],
14899
+ methods: { setMotionTrigger: method(object({
14900
+ deviceId: number().int().nonnegative(),
14901
+ enabled: boolean()
14902
+ }), _void(), {
14903
+ kind: "mutation",
14904
+ auth: "admin"
14905
+ }) },
14906
+ events: { onMotionTriggerChanged: { data: object({
14907
+ deviceId: number(),
14908
+ enabled: boolean(),
14909
+ lastChangedAt: number()
14910
+ }) } },
14911
+ status: {
14912
+ schema: MotionTriggerStatusSchema,
14913
+ kind: "command-driven"
14914
+ },
14915
+ runtimeState: MotionTriggerRuntimeStateSchema
14916
+ };
14333
14917
  /**
14334
14918
  * Motion-zones share the same MaskShape vocabulary as privacy-mask — the
14335
14919
  * on-camera motion-detection mask is a single `grid` region (a row-major
@@ -17767,6 +18351,55 @@ method(object({
17767
18351
  password: string()
17768
18352
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
17769
18353
  /**
18354
+ * A live terminal session hosted by the provider addon. Output and input do
18355
+ * NOT flow through the capability — they use the addon data plane
18356
+ * (`GET /addon/terminal/<id>/out` SSE, `POST /addon/terminal/<id>/in`) because
18357
+ * terminal output must be ordered and lossless. The event bus is telemetry and
18358
+ * may drop chunks ([D8]), and a dropped chunk desynchronises the vt parser
18359
+ * permanently until a full repaint. The capability owns only lifecycle.
18360
+ */
18361
+ var TerminalSessionInfoSchema = object({
18362
+ /** Opaque session id minted by the provider on `openSession`. */
18363
+ sessionId: string(),
18364
+ /** The pre-declared profile this session runs (never a free-form command). */
18365
+ profileId: string(),
18366
+ /** Human-readable profile label for the UI session list. */
18367
+ label: string(),
18368
+ cols: number().int().positive(),
18369
+ rows: number().int().positive(),
18370
+ /** ms-epoch the session's pty was spawned. */
18371
+ startedAt: number()
18372
+ });
18373
+ /**
18374
+ * A profile the operator may open — a pre-declared, allowlisted program
18375
+ * (`monitor` → `btm`). The capability accepts only these ids; a free-form
18376
+ * command string would be remote code execution as the server's user, so it is
18377
+ * deliberately not part of the contract.
18378
+ */
18379
+ var TerminalProfileInfoSchema = object({
18380
+ profileId: string(),
18381
+ label: string(),
18382
+ description: string().optional()
18383
+ });
18384
+ method(_void(), array(TerminalProfileInfoSchema).readonly(), { auth: "admin" }), method(_void(), array(TerminalSessionInfoSchema).readonly(), { auth: "admin" }), method(object({
18385
+ profileId: string(),
18386
+ cols: number().int().positive(),
18387
+ rows: number().int().positive()
18388
+ }), TerminalSessionInfoSchema, {
18389
+ kind: "mutation",
18390
+ auth: "admin"
18391
+ }), method(object({
18392
+ sessionId: string(),
18393
+ cols: number().int().positive(),
18394
+ rows: number().int().positive()
18395
+ }), _void(), {
18396
+ kind: "mutation",
18397
+ auth: "admin"
18398
+ }), method(object({ sessionId: string() }), _void(), {
18399
+ kind: "mutation",
18400
+ auth: "admin"
18401
+ });
18402
+ /**
17770
18403
  * Orchestrator-side destination metadata. The orchestrator computes
17771
18404
  * `id = <addonId>:<subId>` from its provider lookup so consumers
17772
18405
  * (admin UI, restore flow) see one canonical key.
@@ -17867,11 +18500,53 @@ var LocationStatSchema = object({
17867
18500
  fileCount: number(),
17868
18501
  present: boolean()
17869
18502
  });
18503
+ /**
18504
+ * A backup schedule — the N:M "entry" that binds one cron cadence to a
18505
+ * SET of destination locations. Supersedes the per-location cron on
18506
+ * `BackupDestinationPolicy`: an operator creates a schedule, picks the
18507
+ * `backups` locations it should write to, and the orchestrator fans a
18508
+ * single archive out to all of them when the cron fires.
18509
+ *
18510
+ * `retentionCount` is per-schedule (D-decision 2026-07-28): every
18511
+ * location targeted by this schedule keeps this many archives from
18512
+ * this schedule's runs.
18513
+ *
18514
+ * `dataSources` optionally narrows which top-level state locations
18515
+ * (db, addons, tls, …) are archived; omitted = the orchestrator's
18516
+ * default full set.
18517
+ */
18518
+ var BackupScheduleSchema = object({
18519
+ /** Stable id. Generated by the orchestrator on first upsert if absent. */
18520
+ id: string(),
18521
+ /** Operator-facing display name. */
18522
+ label: string(),
18523
+ /** 5-field POSIX cron. Empty = disabled cadence (kept for editing). */
18524
+ cron: string(),
18525
+ /** Master on/off toggle for the whole schedule. */
18526
+ enabled: boolean(),
18527
+ /** `backups`-location ids this schedule writes to (fan-out set). */
18528
+ locationIds: array(string()).readonly(),
18529
+ /** Archives kept per targeted location for this schedule. */
18530
+ retentionCount: number().int().min(1).max(1e3),
18531
+ /** Optional subset of source locations to include; omitted = all. */
18532
+ dataSources: array(string()).readonly().optional(),
18533
+ /** ms-epoch of last successful run. */
18534
+ lastRunAt: number().optional(),
18535
+ /** ms-epoch of next computed firing (read-only, filled on list). */
18536
+ nextRunAt: number().optional()
18537
+ });
17870
18538
  method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }), method(object({
17871
18539
  /** Subset of registered `backup-destination` addon ids to write to. */
17872
18540
  destinations: array(string()).optional(),
17873
18541
  locations: array(string()).optional(),
17874
- label: string().optional()
18542
+ label: string().optional(),
18543
+ /**
18544
+ * Per-run retention override applied to every targeted
18545
+ * destination. Used by schedule-driven runs (per-entry
18546
+ * retention). Omitted = each destination's own policy
18547
+ * retention (manual runs).
18548
+ */
18549
+ retentionCount: number().int().min(1).max(1e3).optional()
17875
18550
  }).optional(), array(BackupEntrySchema).readonly(), {
17876
18551
  kind: "mutation",
17877
18552
  auth: "admin"
@@ -17920,7 +18595,21 @@ method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }
17920
18595
  ok: boolean(),
17921
18596
  error: string().optional(),
17922
18597
  nextRuns: array(number()).readonly()
17923
- }));
18598
+ })), method(_void(), array(BackupScheduleSchema).readonly(), { auth: "admin" }), method(object({
18599
+ id: string().optional(),
18600
+ label: string(),
18601
+ cron: string(),
18602
+ enabled: boolean(),
18603
+ locationIds: array(string()).readonly(),
18604
+ retentionCount: number().int().min(1).max(1e3),
18605
+ dataSources: array(string()).readonly().optional()
18606
+ }), BackupScheduleSchema, {
18607
+ kind: "mutation",
18608
+ auth: "admin"
18609
+ }), method(object({ id: string() }), _void(), {
18610
+ kind: "mutation",
18611
+ auth: "admin"
18612
+ });
17924
18613
  /**
17925
18614
  * `broker` — unified pub/sub broker registry, system-scoped collection.
17926
18615
  *
@@ -18936,1596 +19625,1108 @@ method(object({
18936
19625
  active: boolean()
18937
19626
  }), _void(), {
18938
19627
  kind: "mutation",
18939
- auth: "admin"
18940
- }), method(object({ capName: string() }), array(string())), method(object({ deviceType: string() }), array(object({
18941
- capName: string(),
18942
- wrappers: array(string())
18943
- }))), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), object({
18944
- settings: SettingsSchemaWithValuesSchema.nullable(),
18945
- live: SettingsSchemaWithValuesSchema.nullable()
18946
- })), method(object({
18947
- deviceId: number().int().nonnegative(),
18948
- action: string().min(1),
18949
- input: unknown()
18950
- }), unknown(), { kind: "mutation" }), method(object({
18951
- deviceId: number(),
18952
- writerCapName: string(),
18953
- writerAddonId: string(),
18954
- key: string(),
18955
- value: unknown()
18956
- }), object({ success: literal(true) }), {
18957
- kind: "mutation",
18958
- auth: "admin"
18959
- }), method(object({
18960
- deviceId: number(),
18961
- changes: array(object({
18962
- writerCapName: string(),
18963
- writerAddonId: string(),
18964
- key: string(),
18965
- value: unknown()
18966
- }))
18967
- }), object({
18968
- success: literal(true),
18969
- failures: array(object({
18970
- writerCapName: string(),
18971
- writerAddonId: string(),
18972
- error: string()
18973
- }))
18974
- }), {
18975
- kind: "mutation",
18976
- auth: "admin"
18977
- }), method(object({ addonId: string() }), array(DiscoveryCandidateSchema), {
18978
- kind: "mutation",
18979
- auth: "admin"
18980
- }), method(object({
18981
- addonId: string(),
18982
- candidate: DiscoveryCandidateSchema,
18983
- /** Owning integration id, stamped onto the new device's meta by the
18984
- * device-manager forwarder so `removeByIntegration` can cascade it.
18985
- * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
18986
- integrationId: string().optional()
18987
- }), DeviceSummarySchema, {
18988
- kind: "mutation",
18989
- auth: "admin"
18990
- }), method(object({
18991
- addonId: string(),
18992
- type: _enum(DeviceType)
18993
- }), unknown().nullable()), method(object({
18994
- addonId: string(),
18995
- type: _enum(DeviceType),
18996
- config: record(string(), unknown()),
18997
- /** Owning integration id, stamped onto the new device's meta by the
18998
- * device-manager forwarder so `removeByIntegration` can cascade it.
18999
- * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
19000
- integrationId: string().optional()
19001
- }), DeviceSummarySchema, {
19002
- kind: "mutation",
19003
- auth: "admin"
19004
- }), method(object({
19005
- addonId: string(),
19006
- type: _enum(DeviceType),
19007
- key: string(),
19008
- value: unknown(),
19009
- formValues: record(string(), unknown()).optional()
19010
- }), FieldProbeResultSchema, {
19011
- kind: "mutation",
19012
- auth: "admin"
19013
- }), method(object({
19014
- addonId: string(),
19015
- integrationId: string()
19016
- }), object({ filters: array(AdoptionFilterSchema) }), { auth: "admin" }), method(ListCandidatesInputSchema.extend({ addonId: string() }), ListCandidatesOutputSchema, { auth: "admin" }), method(object({
19017
- addonId: string(),
19018
- integrationId: string()
19019
- }), AdoptionStatusSchema, {
19020
- kind: "mutation",
19021
- auth: "admin"
19022
- }), method(AdoptInputSchema.extend({ addonId: string() }), AdoptResultSchema, {
19023
- kind: "mutation",
19024
- auth: "admin"
19025
- }), method(ReleaseInputSchema.extend({ addonId: string() }), _void(), {
19026
- kind: "mutation",
19027
- auth: "admin"
19028
- }), method(ResyncInputSchema, ResyncResultSchema, {
19029
- kind: "mutation",
19030
- auth: "admin"
19031
- }), method(object({}), object({ providers: array(object({
19032
- addonId: string(),
19033
- label: string()
19034
- })).readonly() }), { auth: "admin" }), method(object({}), object({ groups: array(object({
19035
- addonId: string(),
19036
- label: string(),
19037
- candidates: array(DiscoveryCandidateSchema).readonly(),
19038
- error: string().nullable()
19039
- })).readonly() }), {
19040
- kind: "mutation",
19041
- auth: "admin"
19042
- }), method(object({
19043
- addonId: string(),
19044
- params: record(string(), unknown()).optional()
19045
- }), object({ candidates: array(DiscoveryCandidateSchema).readonly() }), {
19046
- kind: "mutation",
19047
- auth: "admin"
19048
- }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
19049
- deviceId: number(),
19050
- key: string(),
19051
- value: unknown()
19052
- }), FieldProbeResultSchema, {
19053
- kind: "mutation",
19054
- auth: "admin"
19055
- }), method(object({
19056
- deviceId: number(),
19057
- caps: array(string()).readonly().optional()
19058
- }), record(string(), unknown().nullable()));
19059
- method(object({ deviceId: number() }), record(string(), record(string(), unknown()))), method(object({
19060
- deviceId: number(),
19061
- capName: string()
19062
- }), record(string(), unknown()).nullable()), method(object({}), record(string(), record(string(), record(string(), unknown())))), method(object({
19063
- deviceId: number(),
19064
- capName: string(),
19065
- slice: record(string(), unknown())
19066
- }), _void(), { kind: "mutation" }), object({
19067
- deviceId: number(),
19068
- capName: string(),
19069
- slice: record(string(), unknown())
19070
- });
19071
- /**
19072
- * Embedding output. `embedding` is wire-encoded as `number[]` so the
19073
- * Zod-validated tRPC surface round-trips cleanly; consumers that need a
19074
- * `Float32Array` can wrap it on the way out (in-process, no marshalling
19075
- * is involved). `inferenceMs` mirrors the runtime field used by the
19076
- * post-analysis enrichment-engine.
19077
- */
19078
- var EmbeddingResultSchema = object({
19079
- embedding: array(number()),
19080
- inferenceMs: number()
19081
- });
19082
- var EmbeddingInfoSchema = object({
19083
- modelId: string(),
19084
- embeddingDim: number(),
19085
- ready: boolean()
19086
- });
19087
- method(object({
19088
- crop: _instanceof(Uint8Array),
19089
- width: number(),
19090
- height: number()
19091
- }), EmbeddingResultSchema), method(object({ text: string() }), EmbeddingResultSchema), method(_void(), EmbeddingInfoSchema);
19092
- /**
19093
- * filesystem-browse — per-node capability for browsing the node's local
19094
- * filesystem, sandboxed to operator-configured allowed roots. Used by the
19095
- * admin "Add filesystem location" flow to pick a node + path. `mode:'per-node'`
19096
- * (one provider per node); the hub calls it with `{nodeId}` so the codegen
19097
- * routes to that exact node (default `nodeIdMode:'routing'`).
19098
- */
19099
- var DirEntrySchema = object({
19100
- name: string(),
19101
- path: string()
19102
- });
19103
- var BrowseResultSchema = object({
19104
- path: string(),
19105
- entries: array(DirEntrySchema).readonly(),
19106
- freeBytes: number(),
19107
- totalBytes: number()
19108
- });
19109
- method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({ path: string() }), BrowseResultSchema, { auth: "admin" }), method(object({ path: string() }), object({ path: string() }), {
19628
+ auth: "admin"
19629
+ }), method(object({ capName: string() }), array(string())), method(object({ deviceType: string() }), array(object({
19630
+ capName: string(),
19631
+ wrappers: array(string())
19632
+ }))), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), object({
19633
+ settings: SettingsSchemaWithValuesSchema.nullable(),
19634
+ live: SettingsSchemaWithValuesSchema.nullable()
19635
+ })), method(object({
19636
+ deviceId: number().int().nonnegative(),
19637
+ action: string().min(1),
19638
+ input: unknown()
19639
+ }), unknown(), { kind: "mutation" }), method(object({
19640
+ deviceId: number(),
19641
+ writerCapName: string(),
19642
+ writerAddonId: string(),
19643
+ key: string(),
19644
+ value: unknown()
19645
+ }), object({ success: literal(true) }), {
19110
19646
  kind: "mutation",
19111
19647
  auth: "admin"
19112
- });
19113
- /**
19114
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
19115
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
19116
- * caps stay wire-compatible without a circular cap→cap import.
19117
- *
19118
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
19119
- * every transport tier structurally, and failed calls still write usage rows.
19120
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
19121
- */
19122
- var LlmUsageSchema = object({
19123
- inputTokens: number(),
19124
- outputTokens: number()
19125
- });
19126
- var LlmErrorCodeSchema = _enum([
19127
- "timeout",
19128
- "rate-limited",
19129
- "auth",
19130
- "refusal",
19131
- "bad-request",
19132
- "unavailable",
19133
- "no-profile",
19134
- "budget-exceeded",
19135
- "adapter-error"
19136
- ]);
19137
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
19138
- ok: literal(true),
19139
- text: string(),
19140
- model: string(),
19141
- usage: LlmUsageSchema,
19142
- truncated: boolean(),
19143
- latencyMs: number()
19648
+ }), method(object({
19649
+ deviceId: number(),
19650
+ changes: array(object({
19651
+ writerCapName: string(),
19652
+ writerAddonId: string(),
19653
+ key: string(),
19654
+ value: unknown()
19655
+ }))
19144
19656
  }), object({
19145
- ok: literal(false),
19146
- code: LlmErrorCodeSchema,
19147
- message: string(),
19148
- retryAfterMs: number().optional()
19149
- })]);
19150
- /**
19151
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
19152
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
19153
- * notification-output.cap.ts:27-31 precedents).
19154
- */
19155
- var LlmImageSchema = object({
19156
- bytes: _instanceof(Uint8Array),
19157
- mimeType: string()
19158
- });
19159
- var LlmGenerateBaseInputSchema = object({
19160
- /** Collection routing (the notification-output posture). */
19161
- addonId: string().optional(),
19162
- /** Explicit profile; else the resolution chain (spec §3). */
19163
- profileId: string().optional(),
19164
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
19165
- consumer: string(),
19166
- system: string().optional(),
19167
- /** v1: single-turn. `messages[]` is a v2 additive field. */
19168
- prompt: string(),
19169
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
19170
- jsonSchema: record(string(), unknown()).optional(),
19171
- /** Per-call override of the profile default. */
19172
- maxTokens: number().int().positive().optional(),
19173
- temperature: number().optional()
19174
- });
19175
- /**
19176
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
19177
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
19178
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
19179
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
19180
- * this only through the `llm` cap's methods.
19181
- *
19182
- * One running llama-server child per node in v1 (models are RAM-heavy).
19183
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
19184
- * watchdog — operator decision #3).
19185
- */
19186
- var ManagedModelRefSchema = discriminatedUnion("kind", [
19187
- object({
19188
- kind: literal("catalog"),
19189
- catalogId: string()
19190
- }),
19191
- object({
19192
- kind: literal("url"),
19193
- url: string(),
19194
- sha256: string().optional()
19195
- }),
19196
- object({
19197
- kind: literal("path"),
19198
- path: string()
19199
- })
19200
- ]);
19201
- var ManagedRuntimeConfigSchema = object({
19202
- /** WHERE the runtime lives — hub or any agent. */
19203
- nodeId: string(),
19204
- /** Closed for v1; 'ollama' is a v2 candidate. */
19205
- engine: _enum(["llama-cpp"]),
19206
- model: ManagedModelRefSchema,
19207
- contextSize: number().int().default(4096),
19208
- /** 0 = CPU-only. */
19209
- gpuLayers: number().int().default(0),
19210
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
19211
- threads: number().int().optional(),
19212
- /** Concurrent slots. */
19213
- parallel: number().int().default(1),
19214
- /** Else lazy: first generate boots it. */
19215
- autoStart: boolean().default(false),
19216
- /** 0 = never; frees RAM after quiet periods. */
19217
- idleStopMinutes: number().int().default(30)
19218
- });
19219
- var LlmRuntimeStatusSchema = object({
19220
- /** Status is ALWAYS node-qualified. */
19221
- nodeId: string(),
19222
- state: _enum([
19223
- "stopped",
19224
- "downloading",
19225
- "starting",
19226
- "ready",
19227
- "crashed",
19228
- "failed"
19229
- ]),
19230
- pid: number().optional(),
19231
- port: number().optional(),
19232
- modelPath: string().optional(),
19233
- modelId: string().optional(),
19234
- downloadProgress: number().min(0).max(1).optional(),
19235
- lastError: string().optional(),
19236
- crashesInWindow: number(),
19237
- /** Child RSS (sampled best-effort). */
19238
- memoryBytes: number().optional(),
19239
- vramBytes: number().optional()
19240
- });
19241
- var LlmNodeModelSchema = object({
19242
- file: string(),
19243
- sizeBytes: number(),
19244
- catalogId: string().optional(),
19245
- installedAt: number().optional()
19246
- });
19247
- var LlmRuntimeDiskUsageSchema = object({
19248
- nodeId: string(),
19249
- modelsBytes: number(),
19250
- freeBytes: number().optional()
19251
- });
19252
- method(LlmGenerateBaseInputSchema.extend({
19253
- images: array(LlmImageSchema).optional(),
19254
- runtime: ManagedRuntimeConfigSchema,
19255
- /** The managed profile's timeout, threaded by the hub provider. */
19256
- timeoutMs: number().int().positive().optional()
19257
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
19657
+ success: literal(true),
19658
+ failures: array(object({
19659
+ writerCapName: string(),
19660
+ writerAddonId: string(),
19661
+ error: string()
19662
+ }))
19663
+ }), {
19258
19664
  kind: "mutation",
19259
19665
  auth: "admin"
19260
- }), method(object({}), _void(), {
19666
+ }), method(object({ addonId: string() }), array(DiscoveryCandidateSchema), {
19261
19667
  kind: "mutation",
19262
19668
  auth: "admin"
19263
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
19669
+ }), method(object({
19670
+ addonId: string(),
19671
+ candidate: DiscoveryCandidateSchema,
19672
+ /** Owning integration id, stamped onto the new device's meta by the
19673
+ * device-manager forwarder so `removeByIntegration` can cascade it.
19674
+ * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
19675
+ integrationId: string().optional()
19676
+ }), DeviceSummarySchema, {
19264
19677
  kind: "mutation",
19265
19678
  auth: "admin"
19266
- }), method(object({ file: string() }), _void(), {
19679
+ }), method(object({
19680
+ addonId: string(),
19681
+ type: _enum(DeviceType)
19682
+ }), unknown().nullable()), method(object({
19683
+ addonId: string(),
19684
+ type: _enum(DeviceType),
19685
+ config: record(string(), unknown()),
19686
+ /** Owning integration id, stamped onto the new device's meta by the
19687
+ * device-manager forwarder so `removeByIntegration` can cascade it.
19688
+ * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
19689
+ integrationId: string().optional()
19690
+ }), DeviceSummarySchema, {
19267
19691
  kind: "mutation",
19268
19692
  auth: "admin"
19269
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
19270
- /**
19271
- * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
19272
- * methods concat-fan across providers; single-row methods route to ONE
19273
- * provider by the `addonId` in the call input (the notification-output
19274
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
19275
- * (hub-placed); the cap stays open for future providers.
19276
- *
19277
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
19278
- * `apiKey` is a password field — providers REDACT it on read and merge on
19279
- * write; a stored key NEVER round-trips to a client.
19280
- */
19281
- var LlmProfileKindSchema = _enum([
19282
- "openai-compatible",
19283
- "openai",
19284
- "anthropic",
19285
- "google",
19286
- "managed-local"
19287
- ]);
19288
- var LlmProfileSchema = object({
19289
- id: string(),
19290
- name: string(),
19291
- kind: LlmProfileKindSchema,
19292
- /** Stamped by the provider — keeps the fanned catalog routable. */
19693
+ }), method(object({
19293
19694
  addonId: string(),
19294
- enabled: boolean(),
19295
- /** Vendor model id, or the managed runtime's loaded model. */
19296
- model: string(),
19297
- /** Required for openai-compatible; override for cloud kinds. */
19298
- baseUrl: string().optional(),
19299
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
19300
- apiKey: string().optional(),
19301
- supportsVision: boolean(),
19302
- temperature: number().min(0).max(2).optional(),
19303
- maxTokens: number().int().positive().optional(),
19304
- timeoutMs: number().int().positive().default(6e4),
19305
- extraHeaders: record(string(), string()).optional(),
19306
- /** kind === 'managed-local' only (spec §4). */
19307
- runtime: ManagedRuntimeConfigSchema.optional()
19308
- });
19309
- /** ConfigUISchema tree passed through untyped on the wire (the
19310
- * notification-output `ConfigSchemaPassthrough` precedent at
19311
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
19312
- var ConfigSchemaPassthrough$1 = unknown();
19313
- var LlmProfileKindDescriptorSchema = object({
19314
- kind: LlmProfileKindSchema,
19315
- label: string(),
19316
- icon: string(),
19317
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
19695
+ type: _enum(DeviceType),
19696
+ key: string(),
19697
+ value: unknown(),
19698
+ formValues: record(string(), unknown()).optional()
19699
+ }), FieldProbeResultSchema, {
19700
+ kind: "mutation",
19701
+ auth: "admin"
19702
+ }), method(object({
19318
19703
  addonId: string(),
19319
- configSchema: ConfigSchemaPassthrough$1
19320
- });
19321
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
19322
- var LlmDefaultSchema = object({
19323
- selector: LlmDefaultSelectorSchema,
19324
- profileId: string()
19325
- });
19326
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
19327
- var LlmUsageRollupSchema = object({
19328
- day: string(),
19329
- consumer: string(),
19330
- profileId: string(),
19331
- calls: number(),
19332
- okCalls: number(),
19333
- errorCalls: number(),
19334
- inputTokens: number(),
19335
- outputTokens: number(),
19336
- avgLatencyMs: number()
19337
- });
19338
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
19339
- var ManagedModelCatalogEntrySchema = object({
19340
- id: string(),
19341
- label: string(),
19342
- family: string(),
19343
- purpose: _enum(["text", "vision"]),
19344
- url: string(),
19345
- sha256: string(),
19346
- sizeBytes: number(),
19347
- quantization: string(),
19348
- /** Load-time guidance shown in the picker. */
19349
- minRamBytes: number(),
19350
- contextSizeDefault: number().int(),
19351
- /** Vision models: companion projector file. */
19352
- mmprojUrl: string().optional()
19353
- });
19354
- var LlmRuntimeNodeSchema = object({
19355
- nodeId: string(),
19356
- reachable: boolean(),
19357
- status: LlmRuntimeStatusSchema.optional(),
19358
- disk: LlmRuntimeDiskUsageSchema.optional(),
19359
- error: string().optional()
19360
- });
19361
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
19362
- var ProfileRefInputSchema = object({
19704
+ integrationId: string()
19705
+ }), object({ filters: array(AdoptionFilterSchema) }), { auth: "admin" }), method(ListCandidatesInputSchema.extend({ addonId: string() }), ListCandidatesOutputSchema, { auth: "admin" }), method(object({
19363
19706
  addonId: string(),
19364
- profileId: string()
19365
- });
19366
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
19707
+ integrationId: string()
19708
+ }), AdoptionStatusSchema, {
19367
19709
  kind: "mutation",
19368
19710
  auth: "admin"
19369
- }), method(ProfileRefInputSchema, _void(), {
19711
+ }), method(AdoptInputSchema.extend({ addonId: string() }), AdoptResultSchema, {
19370
19712
  kind: "mutation",
19371
19713
  auth: "admin"
19372
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
19714
+ }), method(ReleaseInputSchema.extend({ addonId: string() }), _void(), {
19373
19715
  kind: "mutation",
19374
19716
  auth: "admin"
19375
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
19376
- selector: LlmDefaultSelectorSchema,
19377
- profileId: string().nullable()
19378
- }), _void(), {
19717
+ }), method(ResyncInputSchema, ResyncResultSchema, {
19379
19718
  kind: "mutation",
19380
19719
  auth: "admin"
19381
- }), method(object({
19382
- since: number().optional(),
19383
- until: number().optional(),
19384
- consumer: string().optional(),
19385
- profileId: string().optional()
19386
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
19387
- nodeId: string(),
19388
- model: ManagedModelRefSchema
19389
- }), _void(), {
19720
+ }), method(object({}), object({ providers: array(object({
19721
+ addonId: string(),
19722
+ label: string()
19723
+ })).readonly() }), { auth: "admin" }), method(object({}), object({ groups: array(object({
19724
+ addonId: string(),
19725
+ label: string(),
19726
+ candidates: array(DiscoveryCandidateSchema).readonly(),
19727
+ error: string().nullable()
19728
+ })).readonly() }), {
19390
19729
  kind: "mutation",
19391
19730
  auth: "admin"
19392
19731
  }), method(object({
19393
- nodeId: string(),
19394
- file: string()
19395
- }), _void(), {
19732
+ addonId: string(),
19733
+ params: record(string(), unknown()).optional()
19734
+ }), object({ candidates: array(DiscoveryCandidateSchema).readonly() }), {
19396
19735
  kind: "mutation",
19397
19736
  auth: "admin"
19398
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
19737
+ }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
19738
+ deviceId: number(),
19739
+ key: string(),
19740
+ value: unknown()
19741
+ }), FieldProbeResultSchema, {
19399
19742
  kind: "mutation",
19400
19743
  auth: "admin"
19401
- }), method(ProfileRefInputSchema, _void(), {
19744
+ }), method(object({
19745
+ deviceId: number(),
19746
+ caps: array(string()).readonly().optional()
19747
+ }), record(string(), unknown().nullable()));
19748
+ method(object({ deviceId: number() }), record(string(), record(string(), unknown()))), method(object({
19749
+ deviceId: number(),
19750
+ capName: string()
19751
+ }), record(string(), unknown()).nullable()), method(object({}), record(string(), record(string(), record(string(), unknown())))), method(object({
19752
+ deviceId: number(),
19753
+ capName: string(),
19754
+ slice: record(string(), unknown())
19755
+ }), _void(), { kind: "mutation" }), object({
19756
+ deviceId: number(),
19757
+ capName: string(),
19758
+ slice: record(string(), unknown())
19759
+ });
19760
+ /**
19761
+ * Embedding output. `embedding` is wire-encoded as `number[]` so the
19762
+ * Zod-validated tRPC surface round-trips cleanly; consumers that need a
19763
+ * `Float32Array` can wrap it on the way out (in-process, no marshalling
19764
+ * is involved). `inferenceMs` mirrors the runtime field used by the
19765
+ * post-analysis enrichment-engine.
19766
+ */
19767
+ var EmbeddingResultSchema = object({
19768
+ embedding: array(number()),
19769
+ inferenceMs: number()
19770
+ });
19771
+ var EmbeddingInfoSchema = object({
19772
+ modelId: string(),
19773
+ embeddingDim: number(),
19774
+ ready: boolean()
19775
+ });
19776
+ method(object({
19777
+ crop: _instanceof(Uint8Array),
19778
+ width: number(),
19779
+ height: number()
19780
+ }), EmbeddingResultSchema), method(object({ text: string() }), EmbeddingResultSchema), method(_void(), EmbeddingInfoSchema);
19781
+ /**
19782
+ * filesystem-browse — per-node capability for browsing the node's local
19783
+ * filesystem, sandboxed to operator-configured allowed roots. Used by the
19784
+ * admin "Add filesystem location" flow to pick a node + path. `mode:'per-node'`
19785
+ * (one provider per node); the hub calls it with `{nodeId}` so the codegen
19786
+ * routes to that exact node (default `nodeIdMode:'routing'`).
19787
+ */
19788
+ var DirEntrySchema = object({
19789
+ name: string(),
19790
+ path: string()
19791
+ });
19792
+ var BrowseResultSchema = object({
19793
+ path: string(),
19794
+ entries: array(DirEntrySchema).readonly(),
19795
+ freeBytes: number(),
19796
+ totalBytes: number()
19797
+ });
19798
+ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({ path: string() }), BrowseResultSchema, { auth: "admin" }), method(object({ path: string() }), object({ path: string() }), {
19402
19799
  kind: "mutation",
19403
19800
  auth: "admin"
19404
19801
  });
19405
- var LogLevelSchema = _enum([
19406
- "debug",
19407
- "info",
19408
- "warn",
19409
- "error"
19802
+ /**
19803
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
19804
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
19805
+ * caps stay wire-compatible without a circular cap→cap import.
19806
+ *
19807
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
19808
+ * every transport tier structurally, and failed calls still write usage rows.
19809
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
19810
+ */
19811
+ var LlmUsageSchema = object({
19812
+ inputTokens: number(),
19813
+ outputTokens: number()
19814
+ });
19815
+ var LlmErrorCodeSchema = _enum([
19816
+ "timeout",
19817
+ "rate-limited",
19818
+ "auth",
19819
+ "refusal",
19820
+ "bad-request",
19821
+ "unavailable",
19822
+ "no-profile",
19823
+ "budget-exceeded",
19824
+ "adapter-error"
19410
19825
  ]);
19411
- var LogEntrySchema = object({
19412
- timestamp: date(),
19413
- level: LogLevelSchema,
19414
- scope: array(string()),
19826
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
19827
+ ok: literal(true),
19828
+ text: string(),
19829
+ model: string(),
19830
+ usage: LlmUsageSchema,
19831
+ truncated: boolean(),
19832
+ latencyMs: number()
19833
+ }), object({
19834
+ ok: literal(false),
19835
+ code: LlmErrorCodeSchema,
19415
19836
  message: string(),
19416
- meta: record(string(), unknown()).optional(),
19417
- tags: record(string(), string()).optional()
19418
- });
19419
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
19420
- scope: array(string()).optional(),
19421
- level: LogLevelSchema.optional(),
19422
- since: date().optional(),
19423
- until: date().optional(),
19424
- limit: number().optional(),
19425
- tags: record(string(), string()).optional()
19426
- }), array(LogEntrySchema).readonly());
19837
+ retryAfterMs: number().optional()
19838
+ })]);
19427
19839
  /**
19428
- * `login-method` collection cap through which auth addons contribute
19429
- * their pre-auth login surfaces to the login page. This is the SINGLE,
19430
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
19431
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
19432
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
19433
- * procedure aggregates them for the unauthenticated login page.
19434
- *
19435
- * A contribution is a discriminated union on `kind`:
19436
- *
19437
- * - `redirect` a declarative button. The login page renders a generic
19438
- * button that navigates to `startUrl` (an addon-owned HTTP route).
19439
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
19440
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
19441
- * login page needs NO change.
19442
- *
19443
- * - `widget` — a Module-Federation widget the login page mounts (via
19444
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
19445
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
19446
- * mechanism kept for future use; no shipped addon uses it on the login
19447
- * page (the passkey ceremony below runs natively in the shell instead).
19448
- *
19449
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
19450
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
19451
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
19452
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
19453
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
19454
- * fetching any remote code pre-auth. Contribution stays unconditional
19455
- * enrollment state is never leaked pre-auth; visibility is a shell
19456
- * decision.
19457
- *
19458
- * Every contribution carries a `stage`:
19459
- * - `primary` — shown on the first credentials screen (OIDC /
19460
- * magic-link buttons; a future usernameless passkey).
19461
- * - `second-factor` — shown AFTER the password leg, gated on the
19462
- * returned `factors` (passkey-as-2FA today).
19840
+ * `Uint8Array` is the sanctioned binary convention superjson + the UDS
19841
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
19842
+ * notification-output.cap.ts:27-31 precedents).
19843
+ */
19844
+ var LlmImageSchema = object({
19845
+ bytes: _instanceof(Uint8Array),
19846
+ mimeType: string()
19847
+ });
19848
+ var LlmGenerateBaseInputSchema = object({
19849
+ /** Collection routing (the notification-output posture). */
19850
+ addonId: string().optional(),
19851
+ /** Explicit profile; else the resolution chain (spec §3). */
19852
+ profileId: string().optional(),
19853
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
19854
+ consumer: string(),
19855
+ system: string().optional(),
19856
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
19857
+ prompt: string(),
19858
+ /** Structured output adapter-mapped (response_format / forced tool / responseSchema). */
19859
+ jsonSchema: record(string(), unknown()).optional(),
19860
+ /** Per-call override of the profile default. */
19861
+ maxTokens: number().int().positive().optional(),
19862
+ temperature: number().optional()
19863
+ });
19864
+ /**
19865
+ * `llm-runtime` node-side managed llama.cpp executor (spec §4). Registered
19866
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
19867
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` normal
19868
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
19869
+ * this only through the `llm` cap's methods.
19463
19870
  *
19464
- * `mount: skip` the cap is read server-side by the core auth router
19465
- * (`registry.getCollection('login-method')`), never mounted as its own
19466
- * tRPC router.
19871
+ * One running llama-server child per node in v1 (models are RAM-heavy).
19872
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
19873
+ * watchdog — operator decision #3).
19467
19874
  */
19468
- /** When a login method renders in the two-phase login flow. */
19469
- var LoginStageEnum = _enum(["primary", "second-factor"]);
19470
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
19471
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
19875
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
19472
19876
  object({
19473
- kind: literal("redirect"),
19474
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
19475
- id: string(),
19476
- /** Operator-facing button label. */
19477
- label: string(),
19478
- /** lucide-react icon name. */
19479
- icon: string().optional(),
19480
- /** Addon-owned HTTP route the button navigates to (GET). */
19481
- startUrl: string(),
19482
- stage: LoginStageEnum
19877
+ kind: literal("catalog"),
19878
+ catalogId: string()
19483
19879
  }),
19484
19880
  object({
19485
- kind: literal("widget"),
19486
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
19487
- id: string(),
19488
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
19489
- addonId: string(),
19490
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
19491
- bundle: string(),
19492
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
19493
- remote: WidgetRemoteSchema,
19494
- stage: LoginStageEnum
19881
+ kind: literal("url"),
19882
+ url: string(),
19883
+ sha256: string().optional()
19495
19884
  }),
19496
19885
  object({
19497
- kind: literal("passkey"),
19498
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
19499
- id: string(),
19500
- /** Operator-facing button label. */
19501
- label: string(),
19502
- stage: LoginStageEnum,
19503
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
19504
- rpId: string(),
19505
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
19506
- origin: string().nullable()
19886
+ kind: literal("path"),
19887
+ path: string()
19507
19888
  })
19508
19889
  ]);
19509
- method(_void(), array(LoginMethodContributionSchema).readonly());
19510
- var CpuBreakdownSchema = object({
19511
- total: number(),
19512
- user: number(),
19513
- system: number(),
19514
- irq: number(),
19515
- nice: number(),
19516
- loadAvg: tuple([
19517
- number(),
19518
- number(),
19519
- number()
19520
- ]),
19521
- cores: number()
19522
- });
19523
- var MemoryInfoSchema = object({
19524
- percent: number(),
19525
- totalBytes: number(),
19526
- usedBytes: number(),
19527
- availableBytes: number(),
19528
- swapUsedBytes: number(),
19529
- swapTotalBytes: number()
19530
- });
19531
- var DiskIoSnapshotSchema = object({
19532
- readBytes: number(),
19533
- writeBytes: number(),
19534
- readOps: number(),
19535
- writeOps: number(),
19536
- timestampMs: number()
19537
- });
19538
- var NetworkIoSnapshotSchema = object({
19539
- rxBytes: number(),
19540
- txBytes: number(),
19541
- rxPackets: number(),
19542
- txPackets: number(),
19543
- rxErrors: number(),
19544
- txErrors: number(),
19545
- timestampMs: number()
19546
- });
19547
- var MetricsGpuInfoSchema = object({
19548
- utilization: number(),
19549
- model: string(),
19550
- memoryUsedBytes: number(),
19551
- memoryTotalBytes: number(),
19552
- temperature: number().nullable()
19553
- });
19554
- var ProcessResourceInfoSchema = object({
19555
- openFds: number(),
19556
- threadCount: number(),
19557
- activeHandles: number(),
19558
- activeRequests: number()
19559
- });
19560
- var PressureAvgsSchema = object({
19561
- avg10: number(),
19562
- avg60: number(),
19563
- avg300: number()
19564
- });
19565
- var PressureInfoSchema = object({
19566
- some: PressureAvgsSchema,
19567
- full: PressureAvgsSchema.nullable()
19568
- });
19569
- var SystemResourceSnapshotSchema = object({
19570
- cpu: CpuBreakdownSchema,
19571
- memory: MemoryInfoSchema,
19572
- gpu: MetricsGpuInfoSchema.nullable(),
19573
- network: NetworkIoSnapshotSchema,
19574
- disk: DiskIoSnapshotSchema,
19575
- pressure: object({
19576
- cpu: PressureInfoSchema.nullable(),
19577
- memory: PressureInfoSchema.nullable(),
19578
- io: PressureInfoSchema.nullable()
19579
- }),
19580
- process: ProcessResourceInfoSchema,
19581
- cpuTemperature: number().nullable(),
19582
- timestampMs: number()
19583
- });
19584
- var DiskSpaceInfoSchema = object({
19585
- path: string(),
19586
- totalBytes: number(),
19587
- usedBytes: number(),
19588
- availableBytes: number(),
19589
- percent: number()
19590
- });
19591
- var PidResourceStatsSchema = object({
19592
- pid: number(),
19593
- cpu: number(),
19594
- memory: number(),
19595
- /**
19596
- * Private (anonymous) resident bytes — the per-process V8 heap + native
19597
- * allocations NOT shared with other processes (Linux RssAnon). This is the
19598
- * "real" per-runner cost; summing it across runners is meaningful, unlike
19599
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
19600
- * Undefined where /proc is unavailable (e.g. macOS).
19601
- */
19602
- privateBytes: number().optional(),
19603
- /**
19604
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
19605
- * code shared copy-on-write across runners. Undefined on macOS.
19606
- */
19607
- sharedBytes: number().optional()
19890
+ var ManagedRuntimeConfigSchema = object({
19891
+ /** WHERE the runtime lives — hub or any agent. */
19892
+ nodeId: string(),
19893
+ /** Closed for v1; 'ollama' is a v2 candidate. */
19894
+ engine: _enum(["llama-cpp"]),
19895
+ model: ManagedModelRefSchema,
19896
+ contextSize: number().int().default(4096),
19897
+ /** 0 = CPU-only. */
19898
+ gpuLayers: number().int().default(0),
19899
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
19900
+ threads: number().int().optional(),
19901
+ /** Concurrent slots. */
19902
+ parallel: number().int().default(1),
19903
+ /** Else lazy: first generate boots it. */
19904
+ autoStart: boolean().default(false),
19905
+ /** 0 = never; frees RAM after quiet periods. */
19906
+ idleStopMinutes: number().int().default(30)
19608
19907
  });
19609
- var AddonInstanceSchema = object({
19610
- addonId: string(),
19908
+ var LlmRuntimeStatusSchema = object({
19909
+ /** Status is ALWAYS node-qualified. */
19611
19910
  nodeId: string(),
19612
- role: _enum(["hub", "worker"]),
19613
- pid: number(),
19614
19911
  state: _enum([
19615
- "starting",
19616
- "running",
19617
- "stopping",
19618
19912
  "stopped",
19619
- "crashed"
19620
- ]),
19621
- uptimeSec: number()
19622
- });
19623
- var NodeProcessSchema = object({
19624
- pid: number(),
19625
- ppid: number(),
19626
- pgid: number(),
19627
- classification: _enum([
19628
- "root",
19629
- "managed",
19630
- "system",
19631
- "ghost"
19913
+ "downloading",
19914
+ "starting",
19915
+ "ready",
19916
+ "crashed",
19917
+ "failed"
19632
19918
  ]),
19633
- /** `$process` addon binding when `managed`, else null. */
19634
- addonId: string().nullable(),
19635
- /** Kernel-reported nodeId when the process is a known agent/worker. */
19636
- nodeId: string().nullable(),
19637
- /** Truncated command line. */
19638
- command: string(),
19639
- cpuPercent: number(),
19640
- memoryRssBytes: number(),
19641
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
19642
- uptimeSec: number(),
19643
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
19644
- orphaned: boolean()
19645
- });
19646
- var KillProcessInputSchema = object({
19647
- pid: number(),
19648
- /** Force = SIGKILL. Default is SIGTERM. */
19649
- force: boolean().optional()
19650
- });
19651
- var KillProcessResultSchema = object({
19652
- success: boolean(),
19653
- reason: string().optional(),
19654
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
19655
- });
19656
- var DumpHeapSnapshotInputSchema = object({
19657
- /** The addon whose runner should dump a heap snapshot. */
19658
- addonId: string() });
19659
- var DumpHeapSnapshotResultSchema = object({
19660
- success: boolean(),
19661
- /** Path of the written .heapsnapshot inside the runner's container/host. */
19662
- path: string().optional(),
19663
- /** Process pid that was signalled. */
19664
19919
  pid: number().optional(),
19665
- reason: string().optional()
19920
+ port: number().optional(),
19921
+ modelPath: string().optional(),
19922
+ modelId: string().optional(),
19923
+ downloadProgress: number().min(0).max(1).optional(),
19924
+ lastError: string().optional(),
19925
+ crashesInWindow: number(),
19926
+ /** Child RSS (sampled best-effort). */
19927
+ memoryBytes: number().optional(),
19928
+ vramBytes: number().optional()
19666
19929
  });
19667
- var SystemMetricsSchema = object({
19668
- cpuPercent: number(),
19669
- memoryPercent: number(),
19670
- memoryUsedMB: number(),
19671
- memoryTotalMB: number(),
19672
- diskPercent: number().optional(),
19673
- temperature: number().optional(),
19674
- gpuPercent: number().optional(),
19675
- gpuMemoryPercent: number().optional()
19930
+ var LlmNodeModelSchema = object({
19931
+ file: string(),
19932
+ sizeBytes: number(),
19933
+ catalogId: string().optional(),
19934
+ installedAt: number().optional()
19676
19935
  });
19677
- method(_void(), SystemResourceSnapshotSchema), method(_void(), SystemResourceSnapshotSchema.nullable()), method(_void(), SystemMetricsSchema), method(object({ dirPath: string() }), DiskSpaceInfoSchema), method(_void(), MetricsGpuInfoSchema.nullable()), method(_void(), number().nullable()), method(object({ pids: array(number()) }), array(PidResourceStatsSchema)), method(_void(), array(AddonInstanceSchema).readonly()), method(object({ addonId: string() }), PidResourceStatsSchema.nullable()), method(_void(), array(NodeProcessSchema).readonly()), method(KillProcessInputSchema, KillProcessResultSchema, {
19936
+ var LlmRuntimeDiskUsageSchema = object({
19937
+ nodeId: string(),
19938
+ modelsBytes: number(),
19939
+ freeBytes: number().optional()
19940
+ });
19941
+ method(LlmGenerateBaseInputSchema.extend({
19942
+ images: array(LlmImageSchema).optional(),
19943
+ runtime: ManagedRuntimeConfigSchema,
19944
+ /** The managed profile's timeout, threaded by the hub provider. */
19945
+ timeoutMs: number().int().positive().optional()
19946
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
19678
19947
  kind: "mutation",
19679
19948
  auth: "admin"
19680
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
19949
+ }), method(object({}), _void(), {
19681
19950
  kind: "mutation",
19682
19951
  auth: "admin"
19683
- });
19684
- method(object({
19685
- sourceUrl: string(),
19686
- metadata: ModelConvertMetadataSchema,
19687
- targets: array(ConvertTargetSchema).min(1).readonly(),
19688
- calibrationRef: string().optional(),
19689
- sessionId: string().optional()
19690
- }), ConvertResultSchema, {
19952
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
19691
19953
  kind: "mutation",
19692
- auth: "admin",
19693
- timeoutMs: 6e5
19694
- });
19695
- method(object({
19696
- nodeId: string(),
19697
- modelId: string(),
19698
- format: _enum(MODEL_FORMATS),
19699
- entry: ModelCatalogEntrySchema
19700
- }), object({
19701
- ok: boolean(),
19702
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
19703
- sha256: string(),
19704
- bytes: number(),
19705
- /** The target node's modelsDir the artifact landed in. */
19706
- path: string()
19707
- }), {
19954
+ auth: "admin"
19955
+ }), method(object({ file: string() }), _void(), {
19708
19956
  kind: "mutation",
19709
19957
  auth: "admin"
19710
- });
19711
- /**
19712
- * `mqtt-broker` — broker-registry cap.
19713
- *
19714
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
19715
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
19716
- * and (b) the connection details a consumer addon needs to spin up
19717
- * its OWN `mqtt.js` client.
19718
- *
19719
- * Why: pub/sub routing over the system event-bus loses fidelity
19720
- * (callback shape, QoS guarantees, will/retain semantics) and adds
19721
- * refcount bookkeeping that addons would rather own themselves. The
19722
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
19723
- * features anyway — give it the connection config, get out of the way.
19724
- *
19725
- * Consumer flow:
19726
- * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
19727
- * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
19728
- * client.subscribe('zigbee2mqtt/+')
19729
- *
19730
- * Collection mode: multiple brokers (e.g. one local mosquitto + one
19731
- * cloud bridge). The "embedded" entry (when present) is just another
19732
- * broker in the registry — its lifecycle is owned by the addon that
19733
- * spawned it.
19734
- */
19735
- var BrokerKindSchema = _enum(["external", "embedded"]);
19958
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
19736
19959
  /**
19737
- * Broker live-probe status.
19960
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
19961
+ * methods concat-fan across providers; single-row methods route to ONE
19962
+ * provider by the `addonId` in the call input (the notification-output
19963
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
19964
+ * (hub-placed); the cap stays open for future providers.
19738
19965
  *
19739
- * - `connected` last probe completed a clean CONNACK
19740
- * - `disconnected` — no probe has run yet (cold cache)
19741
- * - `auth-failed` CONNACK refused with auth error (RC 4 / 5)
19742
- * - `unreachable` — TCP connect timed out / refused
19743
- * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
19966
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
19967
+ * `apiKey` is a password field providers REDACT it on read and merge on
19968
+ * write; a stored key NEVER round-trips to a client.
19744
19969
  */
19745
- var BrokerStatusSchema$1 = _enum([
19746
- "connected",
19747
- "disconnected",
19748
- "auth-failed",
19749
- "unreachable",
19750
- "tls-error"
19970
+ var LlmProfileKindSchema = _enum([
19971
+ "openai-compatible",
19972
+ "openai",
19973
+ "anthropic",
19974
+ "google",
19975
+ "managed-local"
19751
19976
  ]);
19752
- var BrokerInfoSchema = object({
19977
+ var LlmProfileSchema = object({
19753
19978
  id: string(),
19754
19979
  name: string(),
19755
- url: string(),
19756
- kind: BrokerKindSchema,
19757
- status: BrokerStatusSchema$1,
19758
- latencyMs: number().nullable(),
19759
- error: string().optional(),
19760
- /** Embedded brokers only: number of MQTT clients currently connected. */
19761
- connectedClients: number().int().nonnegative().optional(),
19762
- /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
19763
- lastCheckedAt: number().optional()
19980
+ kind: LlmProfileKindSchema,
19981
+ /** Stamped by the provider — keeps the fanned catalog routable. */
19982
+ addonId: string(),
19983
+ enabled: boolean(),
19984
+ /** Vendor model id, or the managed runtime's loaded model. */
19985
+ model: string(),
19986
+ /** Required for openai-compatible; override for cloud kinds. */
19987
+ baseUrl: string().optional(),
19988
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
19989
+ apiKey: string().optional(),
19990
+ supportsVision: boolean(),
19991
+ temperature: number().min(0).max(2).optional(),
19992
+ maxTokens: number().int().positive().optional(),
19993
+ timeoutMs: number().int().positive().default(6e4),
19994
+ extraHeaders: record(string(), string()).optional(),
19995
+ /** kind === 'managed-local' only (spec §4). */
19996
+ runtime: ManagedRuntimeConfigSchema.optional()
19764
19997
  });
19765
- /**
19766
- * Connection details — what a consumer needs to call
19767
- * `mqtt.connect(url, options)`. We split URL + credentials so the
19768
- * consumer can pass them as `mqtt.connect(url, { username, password })`
19769
- * instead of stuffing creds into the URL (which leaks them into logs).
19770
- */
19771
- var BrokerConnectionDetailsSchema = object({
19772
- url: string(),
19773
- username: string().optional(),
19774
- password: string().optional(),
19775
- /**
19776
- * Suggested prefix for `clientId`. Each consumer should suffix this
19777
- * with its own discriminator (addon id, instance id) so reconnects
19778
- * don't kick each other off (MQTT spec: clientId must be unique per
19779
- * broker).
19780
- */
19781
- clientIdPrefix: string().optional()
19998
+ /** ConfigUISchema tree passed through untyped on the wire (the
19999
+ * notification-output `ConfigSchemaPassthrough` precedent at
20000
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
20001
+ var ConfigSchemaPassthrough$1 = unknown();
20002
+ var LlmProfileKindDescriptorSchema = object({
20003
+ kind: LlmProfileKindSchema,
20004
+ label: string(),
20005
+ icon: string(),
20006
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
20007
+ addonId: string(),
20008
+ configSchema: ConfigSchemaPassthrough$1
19782
20009
  });
19783
- var AddBrokerInputSchema = object({
19784
- name: string().min(1),
19785
- url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
19786
- username: string().optional(),
19787
- password: string().optional(),
19788
- clientIdPrefix: string().optional()
20010
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
20011
+ var LlmDefaultSchema = object({
20012
+ selector: LlmDefaultSelectorSchema,
20013
+ profileId: string()
19789
20014
  });
19790
- var AddBrokerResultSchema = object({ id: string() });
19791
- var IdInputSchema = object({ id: string() });
19792
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
19793
- ok: literal(true),
19794
- latencyMs: number()
19795
- }), object({
19796
- ok: literal(false),
19797
- error: string()
19798
- })]);
19799
- var StartEmbeddedInputSchema = object({
19800
- port: number().int().min(1).max(65535).default(1883),
19801
- /** Allow anonymous connect (no username/password). Default: false. */
19802
- allowAnonymous: boolean().default(false),
19803
- /** Optional shared username/password for clients. */
19804
- username: string().optional(),
19805
- password: string().optional()
20015
+ /** Server-side rollup row getUsage never dumps raw call rows (spec §6). */
20016
+ var LlmUsageRollupSchema = object({
20017
+ day: string(),
20018
+ consumer: string(),
20019
+ profileId: string(),
20020
+ calls: number(),
20021
+ okCalls: number(),
20022
+ errorCalls: number(),
20023
+ inputTokens: number(),
20024
+ outputTokens: number(),
20025
+ avgLatencyMs: number()
19806
20026
  });
19807
- var StartEmbeddedResultSchema = object({
20027
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
20028
+ var ManagedModelCatalogEntrySchema = object({
19808
20029
  id: string(),
19809
- url: string()
19810
- });
19811
- var StatusSchema = object({
19812
- brokerCount: number(),
19813
- embeddedRunning: boolean()
19814
- });
19815
- 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);
19816
- var NetworkEndpointSchema = object({
20030
+ label: string(),
20031
+ family: string(),
20032
+ purpose: _enum(["text", "vision"]),
19817
20033
  url: string(),
19818
- hostname: string(),
19819
- port: number(),
19820
- protocol: _enum(["http", "https"])
20034
+ sha256: string(),
20035
+ sizeBytes: number(),
20036
+ quantization: string(),
20037
+ /** Load-time guidance shown in the picker. */
20038
+ minRamBytes: number(),
20039
+ contextSizeDefault: number().int(),
20040
+ /** Vision models: companion projector file. */
20041
+ mmprojUrl: string().optional()
19821
20042
  });
19822
- var NetworkAccessStatusSchema = object({
19823
- connected: boolean(),
19824
- endpoint: NetworkEndpointSchema.nullable(),
20043
+ var LlmRuntimeNodeSchema = object({
20044
+ nodeId: string(),
20045
+ reachable: boolean(),
20046
+ status: LlmRuntimeStatusSchema.optional(),
20047
+ disk: LlmRuntimeDiskUsageSchema.optional(),
19825
20048
  error: string().optional()
19826
20049
  });
19827
- /**
19828
- * Optional, richer endpoint shape returned by providers that expose
19829
- * MORE than one ingress concurrently (Tailscale Ingress with mixed
19830
- * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
19831
- * the originating provider config (mode + sourcePort) so the
19832
- * orchestrator UI can label rows distinctly. Providers that expose only
19833
- * one endpoint just omit `listEndpoints` from their provider impl.
19834
- */
19835
- var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
19836
- /**
19837
- * Stable id within the provider — typically `<mode>-<sourcePort>` so
19838
- * the orchestrator can dedupe across `listEndpoints` polls.
19839
- */
19840
- id: string(),
19841
- /** Operator-facing label (mirrors `MeshEndpoint.label`). */
19842
- label: string(),
19843
- /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
19844
- mode: string().optional(),
19845
- /** Originating local port the ingress fronts (informational). */
19846
- sourcePort: number().optional()
20050
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
20051
+ var ProfileRefInputSchema = object({
20052
+ addonId: string(),
20053
+ profileId: string()
20054
+ });
20055
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
20056
+ kind: "mutation",
20057
+ auth: "admin"
20058
+ }), method(ProfileRefInputSchema, _void(), {
20059
+ kind: "mutation",
20060
+ auth: "admin"
20061
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
20062
+ kind: "mutation",
20063
+ auth: "admin"
20064
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
20065
+ selector: LlmDefaultSelectorSchema,
20066
+ profileId: string().nullable()
20067
+ }), _void(), {
20068
+ kind: "mutation",
20069
+ auth: "admin"
20070
+ }), method(object({
20071
+ since: number().optional(),
20072
+ until: number().optional(),
20073
+ consumer: string().optional(),
20074
+ profileId: string().optional()
20075
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
20076
+ nodeId: string(),
20077
+ model: ManagedModelRefSchema
20078
+ }), _void(), {
20079
+ kind: "mutation",
20080
+ auth: "admin"
20081
+ }), method(object({
20082
+ nodeId: string(),
20083
+ file: string()
20084
+ }), _void(), {
20085
+ kind: "mutation",
20086
+ auth: "admin"
20087
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
20088
+ kind: "mutation",
20089
+ auth: "admin"
20090
+ }), method(ProfileRefInputSchema, _void(), {
20091
+ kind: "mutation",
20092
+ auth: "admin"
20093
+ });
20094
+ var LogLevelSchema = _enum([
20095
+ "debug",
20096
+ "info",
20097
+ "warn",
20098
+ "error"
20099
+ ]);
20100
+ var LogEntrySchema = object({
20101
+ timestamp: date(),
20102
+ level: LogLevelSchema,
20103
+ scope: array(string()),
20104
+ message: string(),
20105
+ meta: record(string(), unknown()).optional(),
20106
+ tags: record(string(), string()).optional()
19847
20107
  });
19848
- method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
20108
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
20109
+ scope: array(string()).optional(),
20110
+ level: LogLevelSchema.optional(),
20111
+ since: date().optional(),
20112
+ until: date().optional(),
20113
+ limit: number().optional(),
20114
+ tags: record(string(), string()).optional()
20115
+ }), array(LogEntrySchema).readonly());
19849
20116
  /**
19850
- * notification-outputcanonical, capability-gated notification delivery.
20117
+ * `login-method`collection cap through which auth addons contribute
20118
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
20119
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
20120
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
20121
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
20122
+ * procedure aggregates them for the unauthenticated login page.
19851
20123
  *
19852
- * Apprise-derived model (see
19853
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
19854
- * callers emit ONE canonical `Notification`; each provider declares a
19855
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
19856
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
19857
- * message to what the kind supports — callers never special-case a service.
20124
+ * A contribution is a discriminated union on `kind`:
19858
20125
  *
19859
- * DESIGN DECISIONS (locked):
19860
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
19861
- * `setTargetEnabled`), each provider persisting via the `settings-store`
19862
- * cap. Rationale: the admin UI needs one uniform surface across the
19863
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
19864
- * alternative would fork the UI per addon and cannot host the
19865
- * discovery→adopt flow.
19866
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
19867
- * the generated cap-mount auto-`concatCollection`-fans them across every
19868
- * registered provider (notifiers addon + HA addon) so one catalog is
19869
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
19870
- * `addonId` the generated collection router extracts from the call input.
19871
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
19872
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
19873
- * `storage` / `storage-provider` / `recording` caps over the same path. No
19874
- * base64 fallback needed.
20126
+ * - `redirect` a declarative button. The login page renders a generic
20127
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
20128
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
20129
+ * ZERO shell-side JS. A future SSO addon plugs in the same way the
20130
+ * login page needs NO change.
19875
20131
  *
19876
- * TODO (deferred, closed-set change separate decision): add
19877
- * `providerKind: 'notify'` so notification providers surface on the unified
19878
- * admin "Integrations" page.
19879
- */
19880
- /**
19881
- * Zentik-derived typed-media enum — the superset across every kind. Each
19882
- * adapter picks what it supports and the degrade engine filters the rest.
19883
- */
19884
- var AttachmentMediaTypeSchema = _enum([
19885
- "image",
19886
- "video",
19887
- "gif",
19888
- "audio",
19889
- "icon"
19890
- ]);
19891
- /**
19892
- * A single attachment. Exactly one of `url` (remote source, most adapters
19893
- * prefer this) or `bytes` (inline source; required for Pushover-style
19894
- * bytes-only kinds) MUST be present the degrade engine expresses a
19895
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
20132
+ * - `widget` a Module-Federation widget the login page mounts (via
20133
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
20134
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
20135
+ * mechanism kept for future use; no shipped addon uses it on the login
20136
+ * page (the passkey ceremony below runs natively in the shell instead).
20137
+ *
20138
+ * - `passkey` a declarative WebAuthn ceremony the shell renders
20139
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
20140
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
20141
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
20142
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
20143
+ * fetching any remote code pre-auth. Contribution stays unconditional —
20144
+ * enrollment state is never leaked pre-auth; visibility is a shell
20145
+ * decision.
20146
+ *
20147
+ * Every contribution carries a `stage`:
20148
+ * - `primary` — shown on the first credentials screen (OIDC /
20149
+ * magic-link buttons; a future usernameless passkey).
20150
+ * - `second-factor` — shown AFTER the password leg, gated on the
20151
+ * returned `factors` (passkey-as-2FA today).
20152
+ *
20153
+ * `mount: skip` — the cap is read server-side by the core auth router
20154
+ * (`registry.getCollection('login-method')`), never mounted as its own
20155
+ * tRPC router.
19896
20156
  */
19897
- var AttachmentSchema = object({
19898
- mediaType: AttachmentMediaTypeSchema,
19899
- url: string().optional(),
19900
- bytes: _instanceof(Uint8Array).optional(),
19901
- mime: string().optional(),
19902
- name: string().optional()
19903
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
19904
- var NotificationFormatSchema = _enum([
19905
- "text",
19906
- "markdown",
19907
- "html"
20157
+ /** When a login method renders in the two-phase login flow. */
20158
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
20159
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
20160
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
20161
+ object({
20162
+ kind: literal("redirect"),
20163
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
20164
+ id: string(),
20165
+ /** Operator-facing button label. */
20166
+ label: string(),
20167
+ /** lucide-react icon name. */
20168
+ icon: string().optional(),
20169
+ /** Addon-owned HTTP route the button navigates to (GET). */
20170
+ startUrl: string(),
20171
+ stage: LoginStageEnum
20172
+ }),
20173
+ object({
20174
+ kind: literal("widget"),
20175
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
20176
+ id: string(),
20177
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
20178
+ addonId: string(),
20179
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
20180
+ bundle: string(),
20181
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
20182
+ remote: WidgetRemoteSchema,
20183
+ stage: LoginStageEnum
20184
+ }),
20185
+ object({
20186
+ kind: literal("passkey"),
20187
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
20188
+ id: string(),
20189
+ /** Operator-facing button label. */
20190
+ label: string(),
20191
+ stage: LoginStageEnum,
20192
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
20193
+ rpId: string(),
20194
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
20195
+ origin: string().nullable()
20196
+ })
19908
20197
  ]);
19909
- /** A single tap-through action button. */
19910
- var NotificationActionSchema = object({
19911
- id: string(),
19912
- label: string(),
19913
- url: string().optional()
20198
+ method(_void(), array(LoginMethodContributionSchema).readonly());
20199
+ var CpuBreakdownSchema = object({
20200
+ total: number(),
20201
+ user: number(),
20202
+ system: number(),
20203
+ irq: number(),
20204
+ nice: number(),
20205
+ loadAvg: tuple([
20206
+ number(),
20207
+ number(),
20208
+ number()
20209
+ ]),
20210
+ cores: number()
19914
20211
  });
19915
- /**
19916
- * The canonical notification. `body` is the only hard field (Apprise model).
19917
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
19918
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
19919
- * the adapter maps this ordinal onto its native level. `level?` is an
19920
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
19921
- * `priority` for that one target.
19922
- */
19923
- var NotificationSchema = object({
19924
- body: string(),
19925
- title: string().optional(),
19926
- format: NotificationFormatSchema.default("text"),
19927
- priority: number().int().min(1).max(5).default(3),
19928
- level: string().optional(),
19929
- attachments: array(AttachmentSchema).optional(),
19930
- clickUrl: string().optional(),
19931
- actions: array(NotificationActionSchema).optional(),
19932
- sound: string().optional(),
19933
- ttl: number().optional(),
19934
- tag: string().optional(),
19935
- deviceId: number().optional(),
19936
- eventId: string().optional(),
19937
- metadata: record(string(), unknown()).optional()
20212
+ var MemoryInfoSchema = object({
20213
+ percent: number(),
20214
+ totalBytes: number(),
20215
+ usedBytes: number(),
20216
+ availableBytes: number(),
20217
+ swapUsedBytes: number(),
20218
+ swapTotalBytes: number()
20219
+ });
20220
+ var DiskIoSnapshotSchema = object({
20221
+ readBytes: number(),
20222
+ writeBytes: number(),
20223
+ readOps: number(),
20224
+ writeOps: number(),
20225
+ timestampMs: number()
20226
+ });
20227
+ var NetworkIoSnapshotSchema = object({
20228
+ rxBytes: number(),
20229
+ txBytes: number(),
20230
+ rxPackets: number(),
20231
+ txPackets: number(),
20232
+ rxErrors: number(),
20233
+ txErrors: number(),
20234
+ timestampMs: number()
20235
+ });
20236
+ var MetricsGpuInfoSchema = object({
20237
+ utilization: number(),
20238
+ model: string(),
20239
+ memoryUsedBytes: number(),
20240
+ memoryTotalBytes: number(),
20241
+ temperature: number().nullable()
20242
+ });
20243
+ var ProcessResourceInfoSchema = object({
20244
+ openFds: number(),
20245
+ threadCount: number(),
20246
+ activeHandles: number(),
20247
+ activeRequests: number()
19938
20248
  });
19939
- /** One declared native severity/priority level for a kind. */
19940
- var TargetKindLevelSchema = object({
19941
- id: string(),
19942
- label: string(),
19943
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
19944
- ordinal: number().int().min(1).max(5).nullable(),
19945
- flags: object({
19946
- critical: boolean().optional(),
19947
- silent: boolean().optional(),
19948
- noPush: boolean().optional()
19949
- }).optional(),
19950
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
19951
- requires: array(string()).optional(),
19952
- description: string().optional()
20249
+ var PressureAvgsSchema = object({
20250
+ avg10: number(),
20251
+ avg60: number(),
20252
+ avg300: number()
19953
20253
  });
19954
- /** The full capability block consulted before dispatch. */
19955
- var TargetKindCapsSchema = object({
19956
- attachments: object({
19957
- mediaTypes: array(AttachmentMediaTypeSchema),
19958
- mode: _enum([
19959
- "url",
19960
- "bytes",
19961
- "both"
19962
- ]),
19963
- max: number().int().nonnegative(),
19964
- maxBytes: number().int().positive().optional()
20254
+ var PressureInfoSchema = object({
20255
+ some: PressureAvgsSchema,
20256
+ full: PressureAvgsSchema.nullable()
20257
+ });
20258
+ var SystemResourceSnapshotSchema = object({
20259
+ cpu: CpuBreakdownSchema,
20260
+ memory: MemoryInfoSchema,
20261
+ gpu: MetricsGpuInfoSchema.nullable(),
20262
+ network: NetworkIoSnapshotSchema,
20263
+ disk: DiskIoSnapshotSchema,
20264
+ pressure: object({
20265
+ cpu: PressureInfoSchema.nullable(),
20266
+ memory: PressureInfoSchema.nullable(),
20267
+ io: PressureInfoSchema.nullable()
19965
20268
  }),
19966
- /** Max action buttons (0 = none). */
19967
- actions: number().int().nonnegative(),
19968
- levels: array(TargetKindLevelSchema),
19969
- format: array(NotificationFormatSchema),
19970
- clickUrl: boolean(),
19971
- sound: boolean(),
19972
- ttl: boolean(),
19973
- bodyMaxLen: number().int().positive()
20269
+ process: ProcessResourceInfoSchema,
20270
+ cpuTemperature: number().nullable(),
20271
+ timestampMs: number()
19974
20272
  });
19975
- /**
19976
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
19977
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
19978
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
19979
- * the union is large and not meant for runtime validation here; the exported
19980
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
19981
- */
19982
- var ConfigSchemaPassthrough = unknown();
19983
- var TargetKindSchema = object({
19984
- kind: string(),
19985
- label: string(),
19986
- icon: string(),
19987
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
19988
- addonId: string(),
19989
- configSchema: ConfigSchemaPassthrough,
19990
- supportsDiscovery: boolean(),
19991
- caps: TargetKindCapsSchema
20273
+ var DiskSpaceInfoSchema = object({
20274
+ path: string(),
20275
+ totalBytes: number(),
20276
+ usedBytes: number(),
20277
+ availableBytes: number(),
20278
+ percent: number()
19992
20279
  });
19993
- /**
19994
- * A persisted target. `config` holds secrets; providers REDACT secret fields
19995
- * (return a presence marker only) when serving `listTargets` — never
19996
- * round-trip a stored secret to the UI.
19997
- */
19998
- var TargetSchema = object({
19999
- id: string(),
20000
- name: string(),
20001
- kind: string(),
20280
+ var PidResourceStatsSchema = object({
20281
+ pid: number(),
20282
+ cpu: number(),
20283
+ memory: number(),
20284
+ /**
20285
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
20286
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
20287
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
20288
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
20289
+ * Undefined where /proc is unavailable (e.g. macOS).
20290
+ */
20291
+ privateBytes: number().optional(),
20292
+ /**
20293
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
20294
+ * code shared copy-on-write across runners. Undefined on macOS.
20295
+ */
20296
+ sharedBytes: number().optional()
20297
+ });
20298
+ var AddonInstanceSchema = object({
20002
20299
  addonId: string(),
20003
- enabled: boolean(),
20004
- config: record(string(), unknown())
20300
+ nodeId: string(),
20301
+ role: _enum(["hub", "worker"]),
20302
+ pid: number(),
20303
+ state: _enum([
20304
+ "starting",
20305
+ "running",
20306
+ "stopping",
20307
+ "stopped",
20308
+ "crashed"
20309
+ ]),
20310
+ uptimeSec: number()
20005
20311
  });
20006
- /** A discovery-surfaced candidate (config is partial + non-secret). */
20007
- var DiscoveredTargetSchema = object({
20008
- kind: string(),
20009
- suggestedName: string(),
20010
- config: record(string(), unknown())
20312
+ var NodeProcessSchema = object({
20313
+ pid: number(),
20314
+ ppid: number(),
20315
+ pgid: number(),
20316
+ classification: _enum([
20317
+ "root",
20318
+ "managed",
20319
+ "system",
20320
+ "ghost"
20321
+ ]),
20322
+ /** `$process` addon binding when `managed`, else null. */
20323
+ addonId: string().nullable(),
20324
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
20325
+ nodeId: string().nullable(),
20326
+ /** Truncated command line. */
20327
+ command: string(),
20328
+ cpuPercent: number(),
20329
+ memoryRssBytes: number(),
20330
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
20331
+ uptimeSec: number(),
20332
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
20333
+ orphaned: boolean()
20011
20334
  });
20012
- /** The degrade engine's report — what was resolved / dropped / degraded. */
20013
- var RenderedAsSchema = object({
20014
- level: string(),
20015
- format: NotificationFormatSchema,
20016
- attachmentsSent: number().int().nonnegative(),
20017
- actionsSent: number().int().nonnegative(),
20018
- truncated: boolean(),
20019
- dropped: array(string())
20335
+ var KillProcessInputSchema = object({
20336
+ pid: number(),
20337
+ /** Force = SIGKILL. Default is SIGTERM. */
20338
+ force: boolean().optional()
20020
20339
  });
20021
- var SendResultSchema = object({
20340
+ var KillProcessResultSchema = object({
20022
20341
  success: boolean(),
20023
- error: string().optional(),
20024
- renderedAs: RenderedAsSchema.optional()
20342
+ reason: string().optional(),
20343
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
20344
+ });
20345
+ var DumpHeapSnapshotInputSchema = object({
20346
+ /** The addon whose runner should dump a heap snapshot. */
20347
+ addonId: string() });
20348
+ var DumpHeapSnapshotResultSchema = object({
20349
+ success: boolean(),
20350
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
20351
+ path: string().optional(),
20352
+ /** Process pid that was signalled. */
20353
+ pid: number().optional(),
20354
+ reason: string().optional()
20355
+ });
20356
+ var SystemMetricsSchema = object({
20357
+ cpuPercent: number(),
20358
+ memoryPercent: number(),
20359
+ memoryUsedMB: number(),
20360
+ memoryTotalMB: number(),
20361
+ diskPercent: number().optional(),
20362
+ temperature: number().optional(),
20363
+ gpuPercent: number().optional(),
20364
+ gpuMemoryPercent: number().optional()
20365
+ });
20366
+ method(_void(), SystemResourceSnapshotSchema), method(_void(), SystemResourceSnapshotSchema.nullable()), method(_void(), SystemMetricsSchema), method(object({ dirPath: string() }), DiskSpaceInfoSchema), method(_void(), MetricsGpuInfoSchema.nullable()), method(_void(), number().nullable()), method(object({ pids: array(number()) }), array(PidResourceStatsSchema)), method(_void(), array(AddonInstanceSchema).readonly()), method(object({ addonId: string() }), PidResourceStatsSchema.nullable()), method(_void(), array(NodeProcessSchema).readonly()), method(KillProcessInputSchema, KillProcessResultSchema, {
20367
+ kind: "mutation",
20368
+ auth: "admin"
20369
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
20370
+ kind: "mutation",
20371
+ auth: "admin"
20372
+ });
20373
+ method(object({
20374
+ sourceUrl: string(),
20375
+ metadata: ModelConvertMetadataSchema,
20376
+ targets: array(ConvertTargetSchema).min(1).readonly(),
20377
+ calibrationRef: string().optional(),
20378
+ sessionId: string().optional()
20379
+ }), ConvertResultSchema, {
20380
+ kind: "mutation",
20381
+ auth: "admin",
20382
+ timeoutMs: 6e5
20383
+ });
20384
+ method(object({
20385
+ nodeId: string(),
20386
+ modelId: string(),
20387
+ format: _enum(MODEL_FORMATS),
20388
+ entry: ModelCatalogEntrySchema
20389
+ }), object({
20390
+ ok: boolean(),
20391
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
20392
+ sha256: string(),
20393
+ bytes: number(),
20394
+ /** The target node's modelsDir the artifact landed in. */
20395
+ path: string()
20396
+ }), {
20397
+ kind: "mutation",
20398
+ auth: "admin"
20025
20399
  });
20026
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
20027
- var TestResultSchema = SendResultSchema;
20028
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
20029
- kind: string(),
20030
- config: record(string(), unknown()).optional()
20031
- }), array(DiscoveredTargetSchema)), method(object({
20032
- targetId: string(),
20033
- notification: NotificationSchema
20034
- }), SendResultSchema, { kind: "mutation" }), method(object({
20035
- targetId: string(),
20036
- sample: NotificationSchema.optional()
20037
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
20038
- targetId: string(),
20039
- enabled: boolean()
20040
- }), _void(), { kind: "mutation" });
20041
20400
  /**
20042
- * notification-rulesthe Notification Center rule surface (P1 core).
20043
- *
20044
- * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
20045
- * (operator decisions D-1/D-2/D-3 are binding):
20401
+ * `mqtt-broker`broker-registry cap.
20046
20402
  *
20047
- * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
20048
- * `notification-center` module), hooked on the durable persistence
20049
- * moments (object-event insert, TrackCloser.closeExpired) with a
20050
- * persisted outbox + retry — never the lossy telemetry bus (D8).
20051
- * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
20052
- * FIRST persisted detection matching the conditions (per-track dedup,
20053
- * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
20054
- * `delivery: 'track-end'` evaluates the finalized track record at close.
20055
- * - DISPATCH stays behind `notification-output` (rules reference targets
20056
- * by id; per-backend params are a passthrough blob capped by the
20057
- * target kind's own caps/degrade engine).
20403
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
20404
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
20405
+ * and (b) the connection details a consumer addon needs to spin up
20406
+ * its OWN `mqtt.js` client.
20058
20407
  *
20059
- * P1 scope: admin-authored rules only (`createdBy` stamped from the
20060
- * server-injected caller identity the first `caller: 'required'`
20061
- * adopter). The P1 condition subset is: devices, classes(+exclude),
20062
- * minConfidence, admin zones (any/all + exclude), weekly schedule
20063
- * windows, and the optional label/identity/plate matchers. User rules,
20064
- * private zones, per-recipient fan-out and the wider condition table are
20065
- * P2+ (see spec §7).
20408
+ * Why: pub/sub routing over the system event-bus loses fidelity
20409
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
20410
+ * refcount bookkeeping that addons would rather own themselves. The
20411
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
20412
+ * features anyway — give it the connection config, get out of the way.
20066
20413
  *
20067
- * All schemas here are the single source of truth — `NcRule` etc. are
20068
- * `z.infer` exports; no duplicate interfaces (the advanced-notifier
20069
- * schema/interface drift is explicitly not repeated).
20414
+ * Consumer flow:
20415
+ * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
20416
+ * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
20417
+ * client.subscribe('zigbee2mqtt/+')
20418
+ *
20419
+ * Collection mode: multiple brokers (e.g. one local mosquitto + one
20420
+ * cloud bridge). The "embedded" entry (when present) is just another
20421
+ * broker in the registry — its lifecycle is owned by the addon that
20422
+ * spawned it.
20070
20423
  */
20424
+ var BrokerKindSchema = _enum(["external", "embedded"]);
20071
20425
  /**
20072
- * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
20073
- * The value maps 1:1 onto the evaluated record kind:
20074
- * - `immediate` ↔ object-event persist (lowest-latency detection burst)
20075
- * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
20076
- * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
20077
- * change of a LINKED device, one row per linked camera)
20078
- * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
20079
- * delivery / pick-up)
20426
+ * Broker live-probe status.
20080
20427
  *
20081
- * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
20082
- * `package-event` are pure trigger kinds (no urgency dimension). Extending
20083
- * this one field keeps the schema additive a rule still declares exactly
20084
- * one trigger.
20428
+ * - `connected` last probe completed a clean CONNACK
20429
+ * - `disconnected` no probe has run yet (cold cache)
20430
+ * - `auth-failed` CONNACK refused with auth error (RC 4 / 5)
20431
+ * - `unreachable` — TCP connect timed out / refused
20432
+ * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
20085
20433
  */
20086
- var NcDeliverySchema = _enum([
20087
- "immediate",
20088
- "track-end",
20089
- "device-event",
20090
- "package-event"
20434
+ var BrokerStatusSchema$1 = _enum([
20435
+ "connected",
20436
+ "disconnected",
20437
+ "auth-failed",
20438
+ "unreachable",
20439
+ "tls-error"
20091
20440
  ]);
20092
- /** Weekly schedule — OR of windows; absence on the rule = always active. */
20093
- var NcScheduleSchema = object({
20094
- windows: array(object({
20095
- /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
20096
- days: array(number().int().min(0).max(6)).min(1),
20097
- startMinute: number().int().min(0).max(1439),
20098
- endMinute: number().int().min(0).max(1439)
20099
- })).min(1),
20100
- /** IANA timezone; default = hub host timezone. */
20101
- timezone: string().optional(),
20102
- /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
20103
- invert: boolean().optional()
20104
- });
20105
- /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
20106
- var NcPlateMatcherSchema = object({
20107
- values: array(string().min(1)).min(1),
20108
- /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
20109
- maxDistance: number().int().min(0).max(3).default(1)
20110
- });
20111
- /**
20112
- * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
20113
- * occupancy edge for a device — optionally narrowed to a single admin
20114
- * `zoneId` and/or object `className`. `op` selects the edge/threshold:
20115
- * - `became-occupied` (default) — count crossed 0 → ≥ `count`
20116
- * - `became-free` — count crossed ≥ `count` → below it
20117
- * - `>=` / `<=` — count is at/over or at/under `count`
20118
- * `sustainSeconds` requires the condition hold continuously that long
20119
- * before firing (debounces flicker; 0 = fire on the first matching edge).
20120
- * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
20121
- * the condition never matches. Confirmed edge-state survives addon restarts
20122
- * (declared SQLite collection, reseeded on boot).
20123
- */
20124
- var NcOccupancyConditionSchema = object({
20125
- /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
20126
- zoneId: string().optional(),
20127
- /** Object class to count; absent = any class. */
20128
- className: string().optional(),
20129
- op: _enum([
20130
- "became-occupied",
20131
- "became-free",
20132
- ">=",
20133
- "<="
20134
- ]).default("became-occupied"),
20135
- count: number().int().min(0).default(1),
20136
- sustainSeconds: number().int().min(0).max(3600).default(15)
20137
- });
20138
- /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
20139
- var NcZoneConditionSchema = object({
20140
- ids: array(string().min(1)).min(1),
20141
- /** Quantifier over `ids` — at least one / every one visited. */
20142
- match: _enum(["any", "all"]).default("any")
20143
- });
20144
- /**
20145
- * The P1 condition set — a flat AND of groups; absent group = pass;
20146
- * membership lists are OR within the list (spec §2.3).
20147
- */
20148
- var NcConditionsSchema = object({
20149
- /** Device scope — absent = all devices. */
20150
- devices: array(number()).optional(),
20151
- /** Detector class names (any overlap with the record's class set). */
20152
- classes: array(string().min(1)).optional(),
20153
- /** Veto classes — any overlap fails the rule. */
20154
- classesExclude: array(string().min(1)).optional(),
20155
- /** Minimum detection confidence 0–1 (fails when the record has none). */
20156
- minConfidence: number().min(0).max(1).optional(),
20157
- /** Admin zone membership over event `zones` / track `zonesVisited`. */
20158
- zones: NcZoneConditionSchema.optional(),
20159
- /** Veto zones — any hit fails the rule. */
20160
- zonesExclude: array(string().min(1)).optional(),
20161
- /**
20162
- * Exact (case-insensitive) match on the record's collapsed `label`
20163
- * (identity name / plate text / subclass).
20164
- */
20165
- labelEquals: array(string().min(1)).optional(),
20166
- /**
20167
- * Identity matcher. P1 boundary: matched against the record's collapsed
20168
- * `label` (the identity display name propagated by the face pipeline) —
20169
- * identity-ID matching rides in P2 when identity ids reach the record.
20170
- */
20171
- identities: array(string().min(1)).optional(),
20172
- /** Fuzzy plate matcher against the record's `label` (plate text). */
20173
- plates: NcPlateMatcherSchema.optional(),
20174
- /**
20175
- * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
20176
- * Same P1 boundary: matched against the record's collapsed `label` (the
20177
- * identity display name). A record with NO label passes (nothing to
20178
- * exclude), unlike the include variant which fails on an absent label.
20179
- */
20180
- identitiesExclude: array(string().min(1)).optional(),
20181
- /**
20182
- * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
20183
- * TRACK-END only: importance is scored at track close, so it does not exist
20184
- * at immediate / object-event evaluation time (see catalog `appliesTo`). At
20185
- * close the value is threaded via the close-time info (the `Track` clone is
20186
- * captured before the DB row is updated, so it would otherwise read stale).
20187
- * Fails when the record carries no importance (never guess quality — the
20188
- * `minConfidence` precedent). MVP cut: a single scalar threshold.
20189
- */
20190
- minImportance: number().min(0).max(1).optional(),
20191
- /**
20192
- * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
20193
- * TRACK-END only: an `immediate` / object-event subject has no closed
20194
- * lifespan, so a dwell condition never matches immediate delivery
20195
- * (documented choice — the object-event record carries no `firstSeen`,
20196
- * so dwell cannot be computed from what the subject actually carries).
20197
- */
20198
- minDwellSeconds: number().min(0).optional(),
20199
- /**
20200
- * Detection provenance filter. `any` (default / absent) matches every
20201
- * source; otherwise the subject's source must equal it. Legacy records
20202
- * with no stamped source are treated as `pipeline`. The union spans both
20203
- * record kinds — object events carry `pipeline` | `onboard`, synthetic
20204
- * tracks carry `sensor`.
20205
- */
20206
- source: _enum([
20207
- "pipeline",
20208
- "onboard",
20209
- "sensor",
20210
- "any"
20211
- ]).optional(),
20212
- /**
20213
- * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
20214
- * detector `minConfidence` (that gates the object-detection score; this
20215
- * gates the recognition/OCR match score). Fails when the subject carries
20216
- * no label-match confidence (never guess). TRACK-END only: the confidence
20217
- * lives on the recognition result and reaches the subject at track close.
20218
- *
20219
- * What it measures precisely (plumbed at track close — the closer threads
20220
- * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
20221
- * `importance`): the BEST recognition match confidence observed for the
20222
- * label the track carries at close — for a face, the peak cosine similarity
20223
- * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
20224
- * for a plate, the peak OCR read score of the best-held plate
20225
- * (`plateText.confidence`). When BOTH a face and a plate were recognized on
20226
- * one track the higher of the two is used. A track that ended with no
20227
- * confident identity/plate match carries no value, so the condition fails
20228
- * closed for it (an un-recognized subject).
20229
- */
20230
- minLabelConfidence: number().min(0).max(1).optional(),
20231
- /**
20232
- * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
20233
- * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
20234
- * against the token carried on the device-event subject (extracted from the
20235
- * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
20236
- * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
20237
- * eventType, so gate those with {@link sensorKinds} instead.
20238
- */
20239
- eventTypeTokens: array(string().min(1)).optional(),
20240
- /**
20241
- * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
20242
- * `contact`, `button`, `device-event`) — matched against the persisted
20243
- * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
20244
- */
20245
- sensorKinds: array(string().min(1)).optional(),
20246
- /**
20247
- * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
20248
- * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
20249
- * when the subject's phase does not match (a subject always carries a phase
20250
- * on the package-event trigger).
20251
- */
20252
- packagePhase: _enum([
20253
- "delivered",
20254
- "picked-up",
20255
- "both"
20256
- ]).optional(),
20257
- /**
20258
- * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
20259
- * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
20260
- * listed polygon (ZoneEngine membership semantics). Evaluated only when
20261
- * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
20262
- */
20263
- customZones: array(MaskPolygonShapeSchema).optional(),
20264
- /**
20265
- * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
20266
- * (optionally zone/class-scoped) occupancy count crosses the configured
20267
- * threshold and holds for `sustainSeconds`. Fail-closed on missing
20268
- * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
20269
- */
20270
- occupancy: NcOccupancyConditionSchema.optional()
20271
- });
20272
- /** One delivery target: a `notification-output` Target ref + passthrough params. */
20273
- var NcRuleTargetSchema = object({
20274
- /** `notification-output` Target id. */
20275
- targetId: string().min(1),
20276
- /**
20277
- * Per-backend passthrough. Recognized keys are mapped onto the canonical
20278
- * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
20279
- * degrade engine drops what the backend can't render.
20280
- */
20281
- params: record(string(), unknown()).optional()
20441
+ var BrokerInfoSchema = object({
20442
+ id: string(),
20443
+ name: string(),
20444
+ url: string(),
20445
+ kind: BrokerKindSchema,
20446
+ status: BrokerStatusSchema$1,
20447
+ latencyMs: number().nullable(),
20448
+ error: string().optional(),
20449
+ /** Embedded brokers only: number of MQTT clients currently connected. */
20450
+ connectedClients: number().int().nonnegative().optional(),
20451
+ /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
20452
+ lastCheckedAt: number().optional()
20282
20453
  });
20283
20454
  /**
20284
- * Media attachment policy (P1 still-image subset).
20285
- * - `best` the best AVAILABLE subject image at dispatch time (D-3).
20286
- * - `best-matching` the media that explains WHY the rule fired: a rule
20287
- * matched on identities attaches the subject's `faceCrop`, one matched on
20288
- * plates attaches the `plateCrop`; a rule with no identity/plate condition
20289
- * (or when the specific crop is missing) degrades to `best`, then
20290
- * `keyFrame`, then no attachment — never delaying the send. The matched
20291
- * condition summary is frozen on the outbox row at enqueue (like the rule
20292
- * name), so the choice never drifts from the record that fired it.
20293
- * - `keyFrame` — the clean scene frame (no subject box).
20294
- * - `none` — no attachment.
20455
+ * Connection details what a consumer needs to call
20456
+ * `mqtt.connect(url, options)`. We split URL + credentials so the
20457
+ * consumer can pass them as `mqtt.connect(url, { username, password })`
20458
+ * instead of stuffing creds into the URL (which leaks them into logs).
20295
20459
  */
20296
- var NcMediaPolicySchema = object({ attach: _enum([
20297
- "best",
20298
- "best-matching",
20299
- "keyFrame",
20300
- "none"
20301
- ]).default("best") });
20302
- /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
20303
- var NcThrottleSchema = object({
20304
- cooldownSec: number().int().min(0).max(86400).default(60),
20305
- /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
20306
- scope: _enum(["rule", "rule-device"]).default("rule-device")
20307
- });
20308
- /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
20309
- var NcRuleInputSchema = object({
20310
- name: string().min(1).max(200),
20311
- enabled: boolean().default(true),
20312
- delivery: NcDeliverySchema,
20313
- conditions: NcConditionsSchema.default({}),
20314
- schedule: NcScheduleSchema.optional(),
20315
- targets: array(NcRuleTargetSchema).min(1),
20316
- media: NcMediaPolicySchema.default({ attach: "best" }),
20317
- throttle: NcThrottleSchema.default({
20318
- cooldownSec: 60,
20319
- scope: "rule-device"
20320
- }),
20321
- /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
20322
- template: object({
20323
- title: string().max(500).optional(),
20324
- body: string().max(2e3).optional()
20325
- }).optional(),
20326
- /** Canonical notification priority ordinal (1..5); per-target overridable. */
20327
- priority: number().int().min(1).max(5).default(3),
20460
+ var BrokerConnectionDetailsSchema = object({
20461
+ url: string(),
20462
+ username: string().optional(),
20463
+ password: string().optional(),
20328
20464
  /**
20329
- * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
20330
- * behaviour, visible to all, read-only in the viewer). Present = personal
20331
- * rule owned by this userId. Server-stamped; never trusted from a client.
20465
+ * Suggested prefix for `clientId`. Each consumer should suffix this
20466
+ * with its own discriminator (addon id, instance id) so reconnects
20467
+ * don't kick each other off (MQTT spec: clientId must be unique per
20468
+ * broker).
20332
20469
  */
20333
- ownerUserId: string().optional()
20470
+ clientIdPrefix: string().optional()
20471
+ });
20472
+ var AddBrokerInputSchema = object({
20473
+ name: string().min(1),
20474
+ url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
20475
+ username: string().optional(),
20476
+ password: string().optional(),
20477
+ clientIdPrefix: string().optional()
20478
+ });
20479
+ var AddBrokerResultSchema = object({ id: string() });
20480
+ var IdInputSchema = object({ id: string() });
20481
+ var TestResultSchema$1 = discriminatedUnion("ok", [object({
20482
+ ok: literal(true),
20483
+ latencyMs: number()
20484
+ }), object({
20485
+ ok: literal(false),
20486
+ error: string()
20487
+ })]);
20488
+ var StartEmbeddedInputSchema = object({
20489
+ port: number().int().min(1).max(65535).default(1883),
20490
+ /** Allow anonymous connect (no username/password). Default: false. */
20491
+ allowAnonymous: boolean().default(false),
20492
+ /** Optional shared username/password for clients. */
20493
+ username: string().optional(),
20494
+ password: string().optional()
20495
+ });
20496
+ var StartEmbeddedResultSchema = object({
20497
+ id: string(),
20498
+ url: string()
20499
+ });
20500
+ var StatusSchema = object({
20501
+ brokerCount: number(),
20502
+ embeddedRunning: boolean()
20503
+ });
20504
+ 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);
20505
+ var NetworkEndpointSchema = object({
20506
+ url: string(),
20507
+ hostname: string(),
20508
+ port: number(),
20509
+ protocol: _enum(["http", "https"])
20510
+ });
20511
+ var NetworkAccessStatusSchema = object({
20512
+ connected: boolean(),
20513
+ endpoint: NetworkEndpointSchema.nullable(),
20514
+ error: string().optional()
20334
20515
  });
20335
20516
  /**
20336
- * Partial patch for `updateRule` any subset of the input fields, plus the
20337
- * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
20338
- * NOT a client-authored input field (it lives on the persisted rule, not the
20339
- * input), so it is added here explicitly to let the store's per-target opt-out
20340
- * toggle round-trip through the shared `update` path. Viewer opt-out mutations
20341
- * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
20342
- * `updateRule` patch.
20517
+ * Optional, richer endpoint shape returned by providers that expose
20518
+ * MORE than one ingress concurrently (Tailscale Ingress with mixed
20519
+ * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
20520
+ * the originating provider config (mode + sourcePort) so the
20521
+ * orchestrator UI can label rows distinctly. Providers that expose only
20522
+ * one endpoint just omit `listEndpoints` from their provider impl.
20343
20523
  */
20344
- var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
20345
- /** A persisted rule. */
20346
- var NcRuleSchema = NcRuleInputSchema.extend({
20347
- id: string(),
20348
- /** userId of the admin who created the rule (server-stamped caller). */
20349
- createdBy: string(),
20350
- createdAt: number(),
20351
- updatedAt: number(),
20524
+ var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
20352
20525
  /**
20353
- * Per-target opt-out set. A targetId here is suppressed for THIS rule at
20354
- * send time. Only a target's OWNER may add/remove its id (server-checked
20355
- * in `nc.setRuleTargetEnabled`). Defaults to empty.
20526
+ * Stable id within the provider typically `<mode>-<sourcePort>` so
20527
+ * the orchestrator can dedupe across `listEndpoints` polls.
20356
20528
  */
20357
- disabledTargetIds: array(string()).default([])
20358
- });
20359
- var NcTestResultSchema = object({
20360
- recordId: string(),
20361
- recordKind: _enum([
20362
- "object-event",
20363
- "track",
20364
- "device-event",
20365
- "package-event"
20366
- ]),
20367
- deviceId: number(),
20368
- timestamp: number(),
20369
- wouldFire: boolean(),
20370
- /** Condition id that failed (first failing group), when `wouldFire` is false. */
20371
- failedCondition: string().optional(),
20372
- className: string().optional(),
20373
- label: string().optional()
20529
+ id: string(),
20530
+ /** Operator-facing label (mirrors `MeshEndpoint.label`). */
20531
+ label: string(),
20532
+ /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
20533
+ mode: string().optional(),
20534
+ /** Originating local port the ingress fronts (informational). */
20535
+ sourcePort: number().optional()
20374
20536
  });
20375
- var NcConditionDescriptorSchema = object({
20376
- /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
20537
+ method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
20538
+ /**
20539
+ * notification-output — canonical, capability-gated notification delivery.
20540
+ *
20541
+ * Apprise-derived model (see
20542
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
20543
+ * callers emit ONE canonical `Notification`; each provider declares a
20544
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
20545
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
20546
+ * message to what the kind supports — callers never special-case a service.
20547
+ *
20548
+ * DESIGN DECISIONS (locked):
20549
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
20550
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
20551
+ * cap. Rationale: the admin UI needs one uniform surface across the
20552
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
20553
+ * alternative would fork the UI per addon and cannot host the
20554
+ * discovery→adopt flow.
20555
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
20556
+ * the generated cap-mount auto-`concatCollection`-fans them across every
20557
+ * registered provider (notifiers addon + HA addon) so one catalog is
20558
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
20559
+ * `addonId` the generated collection router extracts from the call input.
20560
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
20561
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
20562
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
20563
+ * base64 fallback needed.
20564
+ *
20565
+ * TODO (deferred, closed-set change — separate decision): add
20566
+ * `providerKind: 'notify'` so notification providers surface on the unified
20567
+ * admin "Integrations" page.
20568
+ */
20569
+ /**
20570
+ * Zentik-derived typed-media enum — the superset across every kind. Each
20571
+ * adapter picks what it supports and the degrade engine filters the rest.
20572
+ */
20573
+ var AttachmentMediaTypeSchema = _enum([
20574
+ "image",
20575
+ "video",
20576
+ "gif",
20577
+ "audio",
20578
+ "icon"
20579
+ ]);
20580
+ /**
20581
+ * A single attachment. Exactly one of `url` (remote source, most adapters
20582
+ * prefer this) or `bytes` (inline source; required for Pushover-style
20583
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
20584
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
20585
+ */
20586
+ var AttachmentSchema = object({
20587
+ mediaType: AttachmentMediaTypeSchema,
20588
+ url: string().optional(),
20589
+ bytes: _instanceof(Uint8Array).optional(),
20590
+ mime: string().optional(),
20591
+ name: string().optional()
20592
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
20593
+ var NotificationFormatSchema = _enum([
20594
+ "text",
20595
+ "markdown",
20596
+ "html"
20597
+ ]);
20598
+ /** A single tap-through action button. */
20599
+ var NotificationActionSchema = object({
20600
+ id: string(),
20601
+ label: string(),
20602
+ url: string().optional()
20603
+ });
20604
+ /**
20605
+ * The canonical notification. `body` is the only hard field (Apprise model).
20606
+ * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
20607
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
20608
+ * the adapter maps this ordinal onto its native level. `level?` is an
20609
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
20610
+ * `priority` for that one target.
20611
+ */
20612
+ var NotificationSchema = object({
20613
+ body: string(),
20614
+ title: string().optional(),
20615
+ format: NotificationFormatSchema.default("text"),
20616
+ priority: number().int().min(1).max(5).default(3),
20617
+ level: string().optional(),
20618
+ attachments: array(AttachmentSchema).optional(),
20619
+ clickUrl: string().optional(),
20620
+ actions: array(NotificationActionSchema).optional(),
20621
+ sound: string().optional(),
20622
+ ttl: number().optional(),
20623
+ tag: string().optional(),
20624
+ deviceId: number().optional(),
20625
+ eventId: string().optional(),
20626
+ metadata: record(string(), unknown()).optional()
20627
+ });
20628
+ /** One declared native severity/priority level for a kind. */
20629
+ var TargetKindLevelSchema = object({
20377
20630
  id: string(),
20378
- group: _enum([
20379
- "scope",
20380
- "class",
20381
- "zones",
20382
- "quality",
20383
- "label",
20384
- "schedule",
20385
- "device",
20386
- "package",
20387
- "occupancy"
20388
- ]),
20389
20631
  label: string(),
20390
- /** Editor widget the UI renders never hardcode per-condition forms. */
20391
- valueType: _enum([
20392
- "deviceIdList",
20393
- "stringList",
20394
- "number01",
20395
- "number",
20396
- "sourceSelect",
20397
- "zoneSelection",
20398
- "zoneIdList",
20399
- "schedule",
20400
- "plateMatcher",
20401
- "packagePhase",
20402
- "polygonDraw",
20403
- "occupancy"
20404
- ]),
20405
- operator: _enum([
20406
- "in",
20407
- "notIn",
20408
- "anyOf",
20409
- "allOf",
20410
- "gte",
20411
- "fuzzyIn",
20412
- "withinSchedule"
20413
- ]),
20414
- /** Which delivery kinds the condition applies to. */
20415
- appliesTo: array(NcDeliverySchema),
20416
- phase: string(),
20632
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
20633
+ ordinal: number().int().min(1).max(5).nullable(),
20634
+ flags: object({
20635
+ critical: boolean().optional(),
20636
+ silent: boolean().optional(),
20637
+ noPush: boolean().optional()
20638
+ }).optional(),
20639
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
20640
+ requires: array(string()).optional(),
20417
20641
  description: string().optional()
20418
20642
  });
20643
+ /** The full capability block consulted before dispatch. */
20644
+ var TargetKindCapsSchema = object({
20645
+ attachments: object({
20646
+ mediaTypes: array(AttachmentMediaTypeSchema),
20647
+ mode: _enum([
20648
+ "url",
20649
+ "bytes",
20650
+ "both"
20651
+ ]),
20652
+ max: number().int().nonnegative(),
20653
+ maxBytes: number().int().positive().optional()
20654
+ }),
20655
+ /** Max action buttons (0 = none). */
20656
+ actions: number().int().nonnegative(),
20657
+ levels: array(TargetKindLevelSchema),
20658
+ format: array(NotificationFormatSchema),
20659
+ clickUrl: boolean(),
20660
+ sound: boolean(),
20661
+ ttl: boolean(),
20662
+ bodyMaxLen: number().int().positive()
20663
+ });
20419
20664
  /**
20420
- * The delivery lifecycle status of a history row a straight read of the
20421
- * durable outbox row's own status (single source of truth):
20422
- * - `pending` — enqueued, in-flight or retrying with backoff
20423
- * - `sent` — delivered (terminal)
20424
- * - `dead` dead-lettered after exhausting retries / a permanent
20425
- * backend rejection / a deleted target (terminal; carries
20426
- * the failure `error`)
20427
- *
20428
- * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
20429
- * user dimension (quiet hours / snooze) and are additive when they land.
20665
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
20666
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
20667
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
20668
+ * the union is large and not meant for runtime validation here; the exported
20669
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
20430
20670
  */
20431
- var NcHistoryStatusSchema = _enum([
20432
- "pending",
20433
- "sent",
20434
- "dead"
20435
- ]);
20436
- /** The evaluated record kind a history row descends from (one per trigger). */
20437
- var NcHistoryRecordKindSchema = _enum([
20438
- "object-event",
20439
- "track-end",
20440
- "device-event",
20441
- "package-event"
20442
- ]);
20443
- /** Subject summary frozen on the row at fire time (survives rule/record edits). */
20444
- var NcHistorySubjectSchema = object({
20445
- className: string(),
20446
- label: string().optional(),
20447
- confidence: number().optional(),
20448
- zones: array(string()),
20449
- timestamp: number()
20671
+ var ConfigSchemaPassthrough = unknown();
20672
+ var TargetKindSchema = object({
20673
+ kind: string(),
20674
+ label: string(),
20675
+ icon: string(),
20676
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
20677
+ addonId: string(),
20678
+ configSchema: ConfigSchemaPassthrough,
20679
+ supportsDiscovery: boolean(),
20680
+ caps: TargetKindCapsSchema
20450
20681
  });
20451
20682
  /**
20452
- * One delivery-history row. This is a read-only VIEW over the durable
20453
- * outbox row (single source of truth the same row the drain loop drives;
20454
- * NO second write path, so history can never drift from delivery state).
20455
- * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
20456
- * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
20457
- * (fire) / `updatedAt` (last transition), `status` + `error` are the
20458
- * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
20459
- * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
20460
- * P1 (admin scope only).
20683
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
20684
+ * (return a presence marker only) when serving `listTargets` never
20685
+ * round-trip a stored secret to the UI.
20461
20686
  */
20462
- var NcHistoryEntrySchema = object({
20463
- /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
20687
+ var TargetSchema = object({
20464
20688
  id: string(),
20465
- ruleId: string(),
20466
- /** Rule name frozen at fire time (outlives a later rename / delete). */
20467
- ruleName: string(),
20468
- /** The rule urgency/trigger that produced this delivery. */
20469
- delivery: NcDeliverySchema,
20470
- targetId: string(),
20471
- deviceId: number(),
20472
- recordKind: NcHistoryRecordKindSchema,
20473
- /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
20474
- recordId: string(),
20475
- /** Present for track-scoped deliveries (object-event / track-end). */
20476
- trackId: string().optional(),
20477
- status: NcHistoryStatusSchema,
20478
- /** Delivery attempts made so far. */
20479
- attempts: number().int(),
20480
- /** Fire time (outbox enqueue). */
20481
- createdAt: number(),
20482
- /** Last transition time (terminal for sent / dead). */
20483
- updatedAt: number(),
20484
- /** Failure detail — present on a `dead` row. */
20485
- error: string().optional(),
20486
- subject: NcHistorySubjectSchema
20689
+ name: string(),
20690
+ kind: string(),
20691
+ addonId: string(),
20692
+ enabled: boolean(),
20693
+ config: record(string(), unknown())
20487
20694
  });
20488
- /**
20489
- * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
20490
- * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
20491
- * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
20492
- * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
20493
- */
20494
- var NcHistoryFilterSchema = object({
20495
- ruleId: string().optional(),
20496
- deviceId: number().optional(),
20497
- status: NcHistoryStatusSchema.optional(),
20498
- since: number().optional(),
20499
- until: number().optional(),
20500
- limit: number().int().min(1).max(500).default(100)
20695
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
20696
+ var DiscoveredTargetSchema = object({
20697
+ kind: string(),
20698
+ suggestedName: string(),
20699
+ config: record(string(), unknown())
20501
20700
  });
20502
- method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), method(object({ ruleId: string() }), object({ rule: NcRuleSchema.nullable() }), { auth: "admin" }), method(object({ rule: NcRuleInputSchema }), object({ rule: NcRuleSchema }), {
20503
- kind: "mutation",
20504
- auth: "admin",
20505
- caller: "required"
20506
- }), method(object({
20507
- ruleId: string(),
20508
- patch: NcRulePatchSchema
20509
- }), object({ rule: NcRuleSchema }), {
20510
- kind: "mutation",
20511
- auth: "admin",
20512
- caller: "required"
20513
- }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
20514
- kind: "mutation",
20515
- auth: "admin"
20516
- }), method(object({
20517
- ruleId: string(),
20701
+ /** The degrade engine's report what was resolved / dropped / degraded. */
20702
+ var RenderedAsSchema = object({
20703
+ level: string(),
20704
+ format: NotificationFormatSchema,
20705
+ attachmentsSent: number().int().nonnegative(),
20706
+ actionsSent: number().int().nonnegative(),
20707
+ truncated: boolean(),
20708
+ dropped: array(string())
20709
+ });
20710
+ var SendResultSchema = object({
20711
+ success: boolean(),
20712
+ error: string().optional(),
20713
+ renderedAs: RenderedAsSchema.optional()
20714
+ });
20715
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
20716
+ var TestResultSchema = SendResultSchema;
20717
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
20718
+ kind: string(),
20719
+ config: record(string(), unknown()).optional()
20720
+ }), array(DiscoveredTargetSchema)), method(object({
20721
+ targetId: string(),
20722
+ notification: NotificationSchema
20723
+ }), SendResultSchema, { kind: "mutation" }), method(object({
20724
+ targetId: string(),
20725
+ sample: NotificationSchema.optional()
20726
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
20727
+ targetId: string(),
20518
20728
  enabled: boolean()
20519
- }), object({ success: literal(true) }), {
20520
- kind: "mutation",
20521
- auth: "admin"
20522
- }), method(object({
20523
- rule: NcRuleInputSchema,
20524
- lookbackMinutes: number().int().min(1).max(1440).default(60)
20525
- }), object({ results: array(NcTestResultSchema) }), {
20526
- kind: "mutation",
20527
- auth: "admin"
20528
- }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
20729
+ }), _void(), { kind: "mutation" });
20529
20730
  /**
20530
20731
  * Zod schemas for persisted record types.
20531
20732
  *
@@ -25530,6 +25731,12 @@ Object.freeze({
25530
25731
  addonId: null,
25531
25732
  access: "delete"
25532
25733
  },
25734
+ "backup.deleteSchedule": {
25735
+ capName: "backup",
25736
+ capScope: "system",
25737
+ addonId: null,
25738
+ access: "delete"
25739
+ },
25533
25740
  "backup.getEntries": {
25534
25741
  capName: "backup",
25535
25742
  capScope: "system",
@@ -25560,6 +25767,12 @@ Object.freeze({
25560
25767
  addonId: null,
25561
25768
  access: "view"
25562
25769
  },
25770
+ "backup.listSchedules": {
25771
+ capName: "backup",
25772
+ capScope: "system",
25773
+ addonId: null,
25774
+ access: "view"
25775
+ },
25563
25776
  "backup.previewSchedule": {
25564
25777
  capName: "backup",
25565
25778
  capScope: "system",
@@ -25584,6 +25797,12 @@ Object.freeze({
25584
25797
  addonId: null,
25585
25798
  access: "create"
25586
25799
  },
25800
+ "backup.upsertSchedule": {
25801
+ capName: "backup",
25802
+ capScope: "system",
25803
+ addonId: null,
25804
+ access: "create"
25805
+ },
25587
25806
  "battery.wakeForStream": {
25588
25807
  capName: "battery",
25589
25808
  capScope: "device",
@@ -29418,6 +29637,36 @@ Object.freeze({
29418
29637
  addonId: null,
29419
29638
  access: "create"
29420
29639
  },
29640
+ "terminalSession.close": {
29641
+ capName: "terminal-session",
29642
+ capScope: "system",
29643
+ addonId: null,
29644
+ access: "create"
29645
+ },
29646
+ "terminalSession.listProfiles": {
29647
+ capName: "terminal-session",
29648
+ capScope: "system",
29649
+ addonId: null,
29650
+ access: "view"
29651
+ },
29652
+ "terminalSession.listSessions": {
29653
+ capName: "terminal-session",
29654
+ capScope: "system",
29655
+ addonId: null,
29656
+ access: "view"
29657
+ },
29658
+ "terminalSession.openSession": {
29659
+ capName: "terminal-session",
29660
+ capScope: "system",
29661
+ addonId: null,
29662
+ access: "create"
29663
+ },
29664
+ "terminalSession.resize": {
29665
+ capName: "terminal-session",
29666
+ capScope: "system",
29667
+ addonId: null,
29668
+ access: "create"
29669
+ },
29421
29670
  "toast.onToast": {
29422
29671
  capName: "toast",
29423
29672
  capScope: "system",