@camstack/addon-provider-petkit 0.2.5 → 0.2.6

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