@camstack/addon-provider-petkit 0.2.5 → 0.2.6

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