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