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