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