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