@camstack/addon-provider-homematic 1.2.5 → 1.2.6

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