@camstack/system 1.2.14 → 1.2.16

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 (57) hide show
  1. package/dist/addon-runner.js +2 -2
  2. package/dist/addon-runner.mjs +2 -2
  3. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  4. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  5. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  6. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  7. package/dist/builtins/alerts/alerts.addon.js +1 -1
  8. package/dist/builtins/alerts/alerts.addon.mjs +1 -1
  9. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +73 -2
  10. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +73 -2
  11. package/dist/builtins/console-logging/index.js +1 -1
  12. package/dist/builtins/console-logging/index.mjs +1 -1
  13. package/dist/builtins/device-manager/device-manager.addon.js +1 -1
  14. package/dist/builtins/device-manager/device-manager.addon.mjs +1 -1
  15. package/dist/builtins/doorbell/virtual-doorbell.addon.js +1 -1
  16. package/dist/builtins/doorbell/virtual-doorbell.addon.mjs +1 -1
  17. package/dist/builtins/hub-forwarder/index.js +1 -1
  18. package/dist/builtins/hub-forwarder/index.mjs +1 -1
  19. package/dist/builtins/local-auth/local-auth.addon.js +1 -1
  20. package/dist/builtins/local-auth/local-auth.addon.mjs +3 -38
  21. package/dist/builtins/local-network/local-network.addon.js +1 -1
  22. package/dist/builtins/local-network/local-network.addon.mjs +1 -1
  23. package/dist/builtins/loki-logging/index.js +1 -1
  24. package/dist/builtins/loki-logging/index.mjs +1 -1
  25. package/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  26. package/dist/builtins/native-metrics/native-metrics.addon.mjs +2 -2
  27. package/dist/builtins/platform-probe/index.js +2 -2
  28. package/dist/builtins/platform-probe/index.mjs +3 -2
  29. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  30. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  31. package/dist/builtins/snapshot/index.js +1 -1
  32. package/dist/builtins/snapshot/index.mjs +1 -1
  33. package/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  34. package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  35. package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +1 -1
  36. package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +1 -1
  37. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  38. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  39. package/dist/builtins/system-backup/system-backup.service.d.ts +14 -1
  40. package/dist/builtins/system-config/system-config.addon.js +1 -1
  41. package/dist/builtins/system-config/system-config.addon.mjs +1 -1
  42. package/dist/builtins/winston-logging/index.js +1 -1
  43. package/dist/builtins/winston-logging/index.mjs +1 -1
  44. package/dist/chunk-CNf5ZN-e.mjs +37 -0
  45. package/dist/{dist-yttC1aUI.js → dist-3AzhkmeY.js} +1325 -1129
  46. package/dist/{dist-eOaraBhT.mjs → dist-BU-QPlE8.mjs} +1325 -1129
  47. package/dist/framework-resolver-hook.mjs +2 -0
  48. package/dist/index.js +224 -32
  49. package/dist/index.mjs +227 -34
  50. package/dist/kernel/addon-installer.d.ts +86 -7
  51. package/dist/kernel/fs-utils.d.ts +18 -5
  52. package/dist/lib-5THG9eKz.mjs +15545 -0
  53. package/dist/lib-CZ3g2WTS.js +15549 -0
  54. package/dist/{manifest-python-deps-bn3qrsxR.mjs → manifest-python-deps-D7-WBIg_.mjs} +1 -1
  55. package/dist/{manifest-python-deps-DSrmih6E.js → manifest-python-deps-DRN3x53E.js} +1 -1
  56. package/dist/{resource-monitor-Le3l0qS2.mjs → resource-monitor-BkP504Vq.mjs} +1 -1
  57. package/package.json +1 -1
@@ -5138,280 +5138,825 @@ var AccessoryKind = {
5138
5138
  AccessoryKind.Siren, AccessoryKind.Floodlight, AccessoryKind.Spotlight, AccessoryKind.PirSensor, AccessoryKind.Chime, AccessoryKind.Autotrack, AccessoryKind.Nightvision, AccessoryKind.PrivacyMask;
5139
5139
  DeviceFeature.BatteryOperated;
5140
5140
  /**
5141
- * Generic device-level status snapshot. Auto-registered by `BaseDevice`
5142
- * for every device, regardless of provider the kernel needs a uniform
5143
- * cap-keyed slice for the basic device flags every consumer expects to
5144
- * read across processes (the `online` flag in particular). Driver-specific
5145
- * caps (`battery`, `doorbell`, …) carry their domain-specific state on
5146
- * their own slices.
5141
+ * Shared geometry vocabulary for on-frame shape caps — privacy-mask,
5142
+ * motion-zones, and the detection zones/lines editor all speak this one
5143
+ * language so a single drawing-plane editor and the providers stay
5144
+ * decoupled from each cap's storage.
5147
5145
  *
5148
- * Pattern is identical to `battery`: schema-bearing `runtimeState`,
5149
- * empty `methods`, single change event. Reads land at
5150
- * `runtimeState.getCapState('device-status')`; writes at
5151
- * `runtimeState.setCapState('device-status', …)`. Cross-process
5152
- * consumers reach the same data via the `device-state` cap router
5153
- * (`getCapSlice({deviceId, capName: 'device-status'})`).
5146
+ * All coordinates are normalized 0..1 of the camera frame (top-left
5147
+ * origin). Each cap composes the SUBSET of shape kinds it supports and
5148
+ * advertises it via `supportedShapes` in its `getOptions`.
5154
5149
  */
5155
- var DeviceStatusSchema = z.object({
5156
- /**
5157
- * Device-level liveness. Drivers flip via `markOnline(boolean)` on
5158
- * `BaseDevice`. Provider semantics vary — RTSP aggregates broker
5159
- * stream-health, Reolink reads firmware push events, ONVIF tracks
5160
- * ping responses. This cap intentionally does NOT prescribe which
5161
- * signal drives the flag.
5162
- */
5163
- online: z.boolean(),
5164
- /** Ms epoch of the last `online` transition. Lets consumers tell
5165
- * apart "just came online" from "still online". */
5166
- lastChangedAt: z.number()
5150
+ /** A normalized 0..1 point (top-left origin). */
5151
+ var MaskPointSchema = z.object({
5152
+ x: z.number(),
5153
+ y: z.number()
5154
+ });
5155
+ /** Axis-aligned rectangle (normalized 0..1). */
5156
+ var MaskRectShapeSchema = z.object({
5157
+ kind: z.literal("rect"),
5158
+ x: z.number(),
5159
+ y: z.number(),
5160
+ width: z.number(),
5161
+ height: z.number()
5162
+ });
5163
+ /** Free polygon — an ordered list of normalized vertices (≥3). */
5164
+ var MaskPolygonShapeSchema = z.object({
5165
+ kind: z.literal("polygon"),
5166
+ points: z.array(MaskPointSchema)
5167
+ });
5168
+ /** Boolean cell grid — row-major, length === gridWidth*gridHeight. */
5169
+ var MaskGridShapeSchema = z.object({
5170
+ kind: z.literal("grid"),
5171
+ gridWidth: z.number(),
5172
+ gridHeight: z.number(),
5173
+ cells: z.array(z.boolean())
5174
+ });
5175
+ /** Directed line / tripwire — an ordered list of normalized points (≥2). */
5176
+ var MaskLineShapeSchema = z.object({
5177
+ kind: z.literal("line"),
5178
+ points: z.array(MaskPointSchema)
5179
+ });
5180
+ z.discriminatedUnion("kind", [
5181
+ MaskRectShapeSchema,
5182
+ MaskPolygonShapeSchema,
5183
+ MaskGridShapeSchema,
5184
+ MaskLineShapeSchema
5185
+ ]);
5186
+ /** Every shape-kind discriminant, for `supportedShapes` advertisement. */
5187
+ var MaskShapeKindSchema = z.enum([
5188
+ "rect",
5189
+ "polygon",
5190
+ "grid",
5191
+ "line"
5192
+ ]);
5193
+ /** Polygon vertex bounds when a cap supports 'polygon' (e.g. Hikvision {min:4,max:4}). */
5194
+ var MaskPolygonVerticesSchema = z.object({
5195
+ min: z.number(),
5196
+ max: z.number()
5197
+ });
5198
+ /** Grid dimensions when a cap supports 'grid'. */
5199
+ var MaskGridDimsSchema = z.object({
5200
+ width: z.number(),
5201
+ height: z.number()
5167
5202
  });
5168
- var deviceStatusCapability = {
5169
- name: "device-status",
5170
- scope: "device",
5171
- deviceNative: true,
5172
- mode: "singleton",
5173
- methods: {},
5174
- events: {
5175
- /** Emitted when `online` transitions. Mirrors the semantics of
5176
- * `battery.onStatusChanged`. */
5177
- onStatusChanged: { data: z.object({
5178
- deviceId: z.number(),
5179
- status: DeviceStatusSchema
5180
- }) } },
5181
- status: {
5182
- schema: DeviceStatusSchema,
5183
- kind: "push"
5184
- },
5185
- runtimeState: DeviceStatusSchema
5186
- };
5187
5203
  /**
5188
- * Per-device feature/identity probe slice. Holds the runtime-resolved
5189
- * truth about what a device CAN do — which the kernel uses to:
5190
- * 1. Reconcile accessory children (hub-children spawn siren/floodlight/PIR
5191
- * based on what the firmware actually advertises).
5192
- * 2. Compute the public `features: DeviceFeature[]` array surfaced via
5193
- * `device-manager.listAll`.
5194
- * 3. Decide which optional caps (PTZ, intercom, doorbell, battery, …)
5195
- * to register on the device's capability surface.
5204
+ * notification-rules the Notification Center rule surface (P1 core).
5196
5205
  *
5197
- * Auto-registered by `BaseDevice` for every device. Drivers populate the
5198
- * slice from `onProbe()` (kernel calls it once after register, before
5199
- * accessory reconciliation). Consumers read via:
5200
- * `runtimeState.getCapState<FeatureProbeStatus>('feature-probe')`
5206
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
5207
+ * (operator decisions D-1/D-2/D-3 are binding):
5201
5208
  *
5202
- * `flags` is an open record so each driver carries its own keys without
5203
- * a centralized schema bottleneck Reolink writes `hasPtz/hasIntercom`,
5204
- * Hikvision writes `hasSupplementalLight/hasAlarmIo`, etc.
5209
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
5210
+ * `notification-center` module), hooked on the durable persistence
5211
+ * moments (object-event insert, TrackCloser.closeExpired) with a
5212
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
5213
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
5214
+ * FIRST persisted detection matching the conditions (per-track dedup,
5215
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
5216
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
5217
+ * - DISPATCH stays behind `notification-output` (rules reference targets
5218
+ * by id; per-backend params are a passthrough blob capped by the
5219
+ * target kind's own caps/degrade engine).
5205
5220
  *
5206
- * Replaces the older driver-local `deviceCache.has*` blob: the per-device
5207
- * config is for operator-edited overrides + UI snapshots; runtime probe
5208
- * results belong in runtime-state where the kernel handles persistence,
5209
- * cross-process mirroring, and reactive updates.
5221
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
5222
+ * server-injected caller identity the first `caller: 'required'`
5223
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
5224
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
5225
+ * windows, and the optional label/identity/plate matchers. User rules,
5226
+ * private zones, per-recipient fan-out and the wider condition table are
5227
+ * P2+ (see spec §7).
5228
+ *
5229
+ * All schemas here are the single source of truth — `NcRule` etc. are
5230
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
5231
+ * schema/interface drift is explicitly not repeated).
5210
5232
  */
5211
- var FeatureProbeStatusSchema = z.object({
5233
+ /**
5234
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
5235
+ * The value maps 1:1 onto the evaluated record kind:
5236
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
5237
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
5238
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
5239
+ * change of a LINKED device, one row per linked camera)
5240
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
5241
+ * delivery / pick-up)
5242
+ *
5243
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
5244
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
5245
+ * this one field keeps the schema additive — a rule still declares exactly
5246
+ * one trigger.
5247
+ */
5248
+ var NcDeliverySchema = z.enum([
5249
+ "immediate",
5250
+ "track-end",
5251
+ "device-event",
5252
+ "package-event"
5253
+ ]);
5254
+ /** One weekly activation window. `startMinute > endMinute` crosses midnight. */
5255
+ var NcScheduleWindowSchema = z.object({
5256
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
5257
+ days: z.array(z.number().int().min(0).max(6)).min(1),
5258
+ startMinute: z.number().int().min(0).max(1439),
5259
+ endMinute: z.number().int().min(0).max(1439)
5260
+ });
5261
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
5262
+ var NcScheduleSchema = z.object({
5263
+ windows: z.array(NcScheduleWindowSchema).min(1),
5264
+ /** IANA timezone; default = hub host timezone. */
5265
+ timezone: z.string().optional(),
5266
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
5267
+ invert: z.boolean().optional()
5268
+ });
5269
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
5270
+ var NcPlateMatcherSchema = z.object({
5271
+ values: z.array(z.string().min(1)).min(1),
5272
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
5273
+ maxDistance: z.number().int().min(0).max(3).default(1)
5274
+ });
5275
+ /**
5276
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
5277
+ * occupancy edge for a device — optionally narrowed to a single admin
5278
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
5279
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
5280
+ * - `became-free` — count crossed ≥ `count` → below it
5281
+ * - `>=` / `<=` — count is at/over or at/under `count`
5282
+ * `sustainSeconds` requires the condition hold continuously that long
5283
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
5284
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
5285
+ * the condition never matches. Confirmed edge-state survives addon restarts
5286
+ * (declared SQLite collection, reseeded on boot).
5287
+ */
5288
+ var NcOccupancyConditionSchema = z.object({
5289
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
5290
+ zoneId: z.string().optional(),
5291
+ /** Object class to count; absent = any class. */
5292
+ className: z.string().optional(),
5293
+ op: z.enum([
5294
+ "became-occupied",
5295
+ "became-free",
5296
+ ">=",
5297
+ "<="
5298
+ ]).default("became-occupied"),
5299
+ count: z.number().int().min(0).default(1),
5300
+ sustainSeconds: z.number().int().min(0).max(3600).default(15)
5301
+ });
5302
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
5303
+ var NcZoneConditionSchema = z.object({
5304
+ ids: z.array(z.string().min(1)).min(1),
5305
+ /** Quantifier over `ids` — at least one / every one visited. */
5306
+ match: z.enum(["any", "all"]).default("any")
5307
+ });
5308
+ /**
5309
+ * The P1 condition set — a flat AND of groups; absent group = pass;
5310
+ * membership lists are OR within the list (spec §2.3).
5311
+ */
5312
+ var NcConditionsSchema = z.object({
5313
+ /** Device scope — absent = all devices. */
5314
+ devices: z.array(z.number()).optional(),
5315
+ /** Detector class names (any overlap with the record's class set). */
5316
+ classes: z.array(z.string().min(1)).optional(),
5317
+ /** Veto classes — any overlap fails the rule. */
5318
+ classesExclude: z.array(z.string().min(1)).optional(),
5319
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
5320
+ minConfidence: z.number().min(0).max(1).optional(),
5321
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
5322
+ zones: NcZoneConditionSchema.optional(),
5323
+ /** Veto zones — any hit fails the rule. */
5324
+ zonesExclude: z.array(z.string().min(1)).optional(),
5212
5325
  /**
5213
- * Driver-specific flag bag. Each driver picks its own key names — the
5214
- * cap deliberately does NOT enforce a closed enum here. Reolink keys:
5215
- * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,
5216
- * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:
5217
- * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.
5326
+ * Exact (case-insensitive) match on the record's collapsed `label`
5327
+ * (identity name / plate text / subclass).
5218
5328
  */
5219
- flags: z.record(z.string(), z.unknown()),
5329
+ labelEquals: z.array(z.string().min(1)).optional(),
5220
5330
  /**
5221
- * Coarse driver-classification lets cross-process consumers tell apart
5222
- * cameras / battery-cams / NVRs without re-running the probe. `null`
5223
- * before the first probe completes.
5331
+ * Identity matcher. P1 boundary: matched against the record's collapsed
5332
+ * `label` (the identity display name propagated by the face pipeline) —
5333
+ * identity-ID matching rides in P2 when identity ids reach the record.
5224
5334
  */
5225
- deviceType: z.string().nullable(),
5226
- /** Camera/firmware model string. `null` when the firmware doesn't expose it. */
5227
- model: z.string().nullable(),
5228
- /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */
5229
- channelCount: z.number().nullable(),
5335
+ identities: z.array(z.string().min(1)).optional(),
5336
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
5337
+ plates: NcPlateMatcherSchema.optional(),
5230
5338
  /**
5231
- * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe
5232
- * completes drivers' `getAccessoryChildren()` should treat zero as
5233
- * "probe not done yet, return empty" so accessories aren't spawned
5234
- * before the firmware is queried.
5339
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
5340
+ * Same P1 boundary: matched against the record's collapsed `label` (the
5341
+ * identity display name). A record with NO label passes (nothing to
5342
+ * exclude), unlike the include variant which fails on an absent label.
5235
5343
  */
5236
- lastProbedAt: z.number(),
5344
+ identitiesExclude: z.array(z.string().min(1)).optional(),
5237
5345
  /**
5238
- * Framework convention: every runtime-state slice carries this for the
5239
- * createRuntimeStateBridge stale-check helper. We keep it in sync with
5240
- * `lastProbedAt` on every write.
5346
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
5347
+ * TRACK-END only: importance is scored at track close, so it does not exist
5348
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
5349
+ * close the value is threaded via the close-time info (the `Track` clone is
5350
+ * captured before the DB row is updated, so it would otherwise read stale).
5351
+ * Fails when the record carries no importance (never guess quality — the
5352
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
5241
5353
  */
5242
- lastFetchedAt: z.number()
5354
+ minImportance: z.number().min(0).max(1).optional(),
5355
+ /**
5356
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
5357
+ * TRACK-END only: an `immediate` / object-event subject has no closed
5358
+ * lifespan, so a dwell condition never matches immediate delivery
5359
+ * (documented choice — the object-event record carries no `firstSeen`,
5360
+ * so dwell cannot be computed from what the subject actually carries).
5361
+ */
5362
+ minDwellSeconds: z.number().min(0).optional(),
5363
+ /**
5364
+ * Detection provenance filter. `any` (default / absent) matches every
5365
+ * source; otherwise the subject's source must equal it. Legacy records
5366
+ * with no stamped source are treated as `pipeline`. The union spans both
5367
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
5368
+ * tracks carry `sensor`.
5369
+ */
5370
+ source: z.enum([
5371
+ "pipeline",
5372
+ "onboard",
5373
+ "sensor",
5374
+ "any"
5375
+ ]).optional(),
5376
+ /**
5377
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
5378
+ * detector `minConfidence` (that gates the object-detection score; this
5379
+ * gates the recognition/OCR match score). Fails when the subject carries
5380
+ * no label-match confidence (never guess). TRACK-END only: the confidence
5381
+ * lives on the recognition result and reaches the subject at track close.
5382
+ *
5383
+ * What it measures precisely (plumbed at track close — the closer threads
5384
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
5385
+ * `importance`): the BEST recognition match confidence observed for the
5386
+ * label the track carries at close — for a face, the peak cosine similarity
5387
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
5388
+ * for a plate, the peak OCR read score of the best-held plate
5389
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
5390
+ * one track the higher of the two is used. A track that ended with no
5391
+ * confident identity/plate match carries no value, so the condition fails
5392
+ * closed for it (an un-recognized subject).
5393
+ */
5394
+ minLabelConfidence: z.number().min(0).max(1).optional(),
5395
+ /**
5396
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
5397
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
5398
+ * against the token carried on the device-event subject (extracted from the
5399
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
5400
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
5401
+ * eventType, so gate those with {@link sensorKinds} instead.
5402
+ */
5403
+ eventTypeTokens: z.array(z.string().min(1)).optional(),
5404
+ /**
5405
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
5406
+ * `contact`, `button`, `device-event`) — matched against the persisted
5407
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
5408
+ */
5409
+ sensorKinds: z.array(z.string().min(1)).optional(),
5410
+ /**
5411
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
5412
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
5413
+ * when the subject's phase does not match (a subject always carries a phase
5414
+ * on the package-event trigger).
5415
+ */
5416
+ packagePhase: z.enum([
5417
+ "delivered",
5418
+ "picked-up",
5419
+ "both"
5420
+ ]).optional(),
5421
+ /**
5422
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
5423
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
5424
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
5425
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
5426
+ */
5427
+ customZones: z.array(MaskPolygonShapeSchema).optional(),
5428
+ /**
5429
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
5430
+ * (optionally zone/class-scoped) occupancy count crosses the configured
5431
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
5432
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
5433
+ */
5434
+ occupancy: NcOccupancyConditionSchema.optional()
5435
+ });
5436
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
5437
+ var NcRuleTargetSchema = z.object({
5438
+ /** `notification-output` Target id. */
5439
+ targetId: z.string().min(1),
5440
+ /**
5441
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
5442
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
5443
+ * degrade engine drops what the backend can't render.
5444
+ */
5445
+ params: z.record(z.string(), z.unknown()).optional()
5243
5446
  });
5244
- var featureProbeCapability = {
5245
- name: "feature-probe",
5246
- scope: "device",
5247
- deviceNative: true,
5248
- mode: "singleton",
5249
- methods: {},
5250
- events: {
5251
- /** Fires whenever a fresh probe completes (kernel-driven `reprobe()`
5252
- * or driver-initiated re-detect after a state change). */
5253
- onProbeChanged: { data: z.object({
5254
- deviceId: z.number(),
5255
- status: FeatureProbeStatusSchema
5256
- }) } },
5257
- status: {
5258
- schema: FeatureProbeStatusSchema,
5259
- kind: "push"
5260
- },
5261
- runtimeState: FeatureProbeStatusSchema
5262
- };
5263
5447
  /**
5264
- * Multi-metric air-quality slice. Covers CO₂, total VOCs, particulate
5265
- * matter at PM2.5 / PM10, and a derived AQI index — all optional so
5266
- * a single-metric source populates only what it observes. Mirrors
5267
- * the HA `sensor` device_class set (`co2`, `volatile_organic_compounds`,
5268
- * `pm25`, `pm10`, `aqi`) collapsed into one cap because a typical
5269
- * air-quality node reports several of these together; modelling them
5270
- * as siblings keeps a single timestamp + one slice subscription.
5448
+ * Media attachment policy (P1 still-image subset).
5449
+ * - `best` the best AVAILABLE subject image at dispatch time (D-3).
5450
+ * - `best-matching` the media that explains WHY the rule fired: a rule
5451
+ * matched on identities attaches the subject's `faceCrop`, one matched on
5452
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
5453
+ * (or when the specific crop is missing) degrades to `best`, then
5454
+ * `keyFrame`, then no attachment never delaying the send. The matched
5455
+ * condition summary is frozen on the outbox row at enqueue (like the rule
5456
+ * name), so the choice never drifts from the record that fired it.
5457
+ * - `keyFrame` — the clean scene frame (no subject box).
5458
+ * - `none` — no attachment.
5271
5459
  */
5272
- var AirQualitySensorStatusSchema = z.object({
5273
- /** Carbon dioxide concentration in ppm. */
5274
- co2Ppm: z.number().min(0).optional(),
5275
- /** Total volatile organic compounds in ppb. */
5276
- vocPpb: z.number().min(0).optional(),
5277
- /** Particulate matter ≤ 2.5 μm in µg/m³. */
5278
- pm25: z.number().min(0).optional(),
5279
- /** Particulate matter ≤ 10 μm in µg/m³. */
5280
- pm10: z.number().min(0).optional(),
5281
- /** Composite AQI value (typically 0..500). */
5282
- aqi: z.number().optional(),
5283
- /** Ms epoch when the slice was last updated. */
5284
- lastFetchedAt: z.number(),
5285
- /** Live display unit of the single metric this slice carries (e.g. HA
5286
- * `attributes.unit_of_measurement` → 'ppm' / 'ppb' / 'µg/m³'). Each
5287
- * upstream `sensor.*` entity surfaces ONE device_class, so one unit
5288
- * per slice is unambiguous. */
5289
- unit: z.string().optional(),
5290
- /** Suggested decimal places for numeric display.
5291
- * Populated live from the upstream source when provided (e.g. HA
5292
- * `attributes.suggested_display_precision`). Falls back to
5293
- * auto-formatting when absent. */
5294
- precision: z.number().int().min(0).max(10).optional()
5460
+ var NcMediaPolicySchema = z.object({ attach: z.enum([
5461
+ "best",
5462
+ "best-matching",
5463
+ "keyFrame",
5464
+ "none"
5465
+ ]).default("best") });
5466
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
5467
+ var NcThrottleSchema = z.object({
5468
+ cooldownSec: z.number().int().min(0).max(86400).default(60),
5469
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
5470
+ scope: z.enum(["rule", "rule-device"]).default("rule-device")
5471
+ });
5472
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
5473
+ var NcRuleInputSchema = z.object({
5474
+ name: z.string().min(1).max(200),
5475
+ enabled: z.boolean().default(true),
5476
+ delivery: NcDeliverySchema,
5477
+ conditions: NcConditionsSchema.default({}),
5478
+ schedule: NcScheduleSchema.optional(),
5479
+ targets: z.array(NcRuleTargetSchema).min(1),
5480
+ media: NcMediaPolicySchema.default({ attach: "best" }),
5481
+ throttle: NcThrottleSchema.default({
5482
+ cooldownSec: 60,
5483
+ scope: "rule-device"
5484
+ }),
5485
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
5486
+ template: z.object({
5487
+ title: z.string().max(500).optional(),
5488
+ body: z.string().max(2e3).optional()
5489
+ }).optional(),
5490
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
5491
+ priority: z.number().int().min(1).max(5).default(3),
5492
+ /**
5493
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
5494
+ * behaviour, visible to all, read-only in the viewer). Present = personal
5495
+ * rule owned by this userId. Server-stamped; never trusted from a client.
5496
+ */
5497
+ ownerUserId: z.string().optional()
5295
5498
  });
5296
- var airQualitySensorCapability = {
5297
- name: "air-quality-sensor",
5298
- scope: "device",
5299
- deviceNative: true,
5300
- mode: "singleton",
5301
- deviceTypes: [DeviceType.Sensor],
5302
- methods: {},
5303
- status: {
5304
- schema: AirQualitySensorStatusSchema,
5305
- kind: "push"
5306
- },
5307
- runtimeState: AirQualitySensorStatusSchema
5308
- };
5309
5499
  /**
5310
- * Alarm-panel cap. Models HA `alarm_control_panel.*` on
5311
- * `DeviceType.AlarmPanel`. State follows HA's canonical lifecycle
5312
- * across disarmed / armed_(home|away|night|vacation|custom_bypass) /
5313
- * arming / pending / triggered / disarming.
5314
- *
5315
- * Many panels require a PIN code on arm / disarm — the optional
5316
- * `code` field on the methods passes it through to the upstream
5317
- * service; it's NEVER persisted in the runtime slice or any event
5318
- * payload. The presence of a required code is signalled by
5319
- * `DeviceFeature.AlarmPinRequired` so the UI gates a code-entry
5320
- * field without a slice fetch.
5321
- *
5322
- * `availableModes` mirrors HA's `supported_features`-derived arm
5323
- * mode list — the UI renders only the buttons the panel accepts.
5500
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
5501
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
5502
+ * NOT a client-authored input field (it lives on the persisted rule, not the
5503
+ * input), so it is added here explicitly to let the store's per-target opt-out
5504
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
5505
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
5506
+ * `updateRule` patch.
5324
5507
  */
5325
- var AlarmStateSchema = z.enum([
5326
- "disarmed",
5327
- "armed_home",
5328
- "armed_away",
5329
- "armed_night",
5330
- "armed_vacation",
5331
- "armed_custom_bypass",
5332
- "arming",
5333
- "disarming",
5508
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: z.array(z.string()).optional() });
5509
+ /** A persisted rule. */
5510
+ var NcRuleSchema = NcRuleInputSchema.extend({
5511
+ id: z.string(),
5512
+ /** userId of the admin who created the rule (server-stamped caller). */
5513
+ createdBy: z.string(),
5514
+ createdAt: z.number(),
5515
+ updatedAt: z.number(),
5516
+ /**
5517
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
5518
+ * send time. Only a target's OWNER may add/remove its id (server-checked
5519
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
5520
+ */
5521
+ disabledTargetIds: z.array(z.string()).default([])
5522
+ });
5523
+ var NcTestResultSchema = z.object({
5524
+ recordId: z.string(),
5525
+ recordKind: z.enum([
5526
+ "object-event",
5527
+ "track",
5528
+ "device-event",
5529
+ "package-event"
5530
+ ]),
5531
+ deviceId: z.number(),
5532
+ timestamp: z.number(),
5533
+ wouldFire: z.boolean(),
5534
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
5535
+ failedCondition: z.string().optional(),
5536
+ className: z.string().optional(),
5537
+ label: z.string().optional()
5538
+ });
5539
+ var NcConditionDescriptorSchema = z.object({
5540
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
5541
+ id: z.string(),
5542
+ group: z.enum([
5543
+ "scope",
5544
+ "class",
5545
+ "zones",
5546
+ "quality",
5547
+ "label",
5548
+ "schedule",
5549
+ "device",
5550
+ "package",
5551
+ "occupancy"
5552
+ ]),
5553
+ label: z.string(),
5554
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
5555
+ valueType: z.enum([
5556
+ "deviceIdList",
5557
+ "stringList",
5558
+ "number01",
5559
+ "number",
5560
+ "sourceSelect",
5561
+ "zoneSelection",
5562
+ "zoneIdList",
5563
+ "schedule",
5564
+ "plateMatcher",
5565
+ "packagePhase",
5566
+ "polygonDraw",
5567
+ "occupancy"
5568
+ ]),
5569
+ operator: z.enum([
5570
+ "in",
5571
+ "notIn",
5572
+ "anyOf",
5573
+ "allOf",
5574
+ "gte",
5575
+ "fuzzyIn",
5576
+ "withinSchedule"
5577
+ ]),
5578
+ /** Which delivery kinds the condition applies to. */
5579
+ appliesTo: z.array(NcDeliverySchema),
5580
+ phase: z.string(),
5581
+ description: z.string().optional()
5582
+ });
5583
+ /**
5584
+ * The delivery lifecycle status of a history row — a straight read of the
5585
+ * durable outbox row's own status (single source of truth):
5586
+ * - `pending` — enqueued, in-flight or retrying with backoff
5587
+ * - `sent` — delivered (terminal)
5588
+ * - `dead` — dead-lettered after exhausting retries / a permanent
5589
+ * backend rejection / a deleted target (terminal; carries
5590
+ * the failure `error`)
5591
+ *
5592
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
5593
+ * user dimension (quiet hours / snooze) and are additive when they land.
5594
+ */
5595
+ var NcHistoryStatusSchema = z.enum([
5334
5596
  "pending",
5335
- "triggered"
5597
+ "sent",
5598
+ "dead"
5336
5599
  ]);
5337
- var AlarmArmModeSchema = z.enum([
5338
- "home",
5339
- "away",
5340
- "night",
5341
- "vacation",
5342
- "custom_bypass"
5600
+ /** The evaluated record kind a history row descends from (one per trigger). */
5601
+ var NcHistoryRecordKindSchema = z.enum([
5602
+ "object-event",
5603
+ "track-end",
5604
+ "device-event",
5605
+ "package-event"
5343
5606
  ]);
5344
- var AlarmPanelStatusSchema = z.object({
5345
- /** Current lifecycle state. */
5346
- state: AlarmStateSchema,
5347
- /** Subset of arm modes the panel accepts. UI renders one button per
5348
- * mode in this list. */
5349
- availableModes: z.array(AlarmArmModeSchema),
5350
- /** Whether the panel requires a PIN on arm / disarm. Mirrors
5351
- * `DeviceFeature.AlarmPinRequired` for slice consumers. */
5352
- requiresCode: z.boolean(),
5353
- /** Ms epoch when the slice was last updated. */
5354
- lastChangedAt: z.number()
5607
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
5608
+ var NcHistorySubjectSchema = z.object({
5609
+ className: z.string(),
5610
+ label: z.string().optional(),
5611
+ confidence: z.number().optional(),
5612
+ zones: z.array(z.string()),
5613
+ timestamp: z.number()
5355
5614
  });
5356
- var alarmPanelCapability = {
5357
- name: "alarm-panel",
5358
- scope: "device",
5359
- deviceNative: true,
5615
+ /**
5616
+ * One delivery-history row. This is a read-only VIEW over the durable
5617
+ * outbox row (single source of truth — the same row the drain loop drives;
5618
+ * NO second write path, so history can never drift from delivery state).
5619
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
5620
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
5621
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
5622
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
5623
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
5624
+ * P1 (admin scope only).
5625
+ */
5626
+ var NcHistoryEntrySchema = z.object({
5627
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
5628
+ id: z.string(),
5629
+ ruleId: z.string(),
5630
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
5631
+ ruleName: z.string(),
5632
+ /** The rule urgency/trigger that produced this delivery. */
5633
+ delivery: NcDeliverySchema,
5634
+ targetId: z.string(),
5635
+ deviceId: z.number(),
5636
+ recordKind: NcHistoryRecordKindSchema,
5637
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
5638
+ recordId: z.string(),
5639
+ /** Present for track-scoped deliveries (object-event / track-end). */
5640
+ trackId: z.string().optional(),
5641
+ status: NcHistoryStatusSchema,
5642
+ /** Delivery attempts made so far. */
5643
+ attempts: z.number().int(),
5644
+ /** Fire time (outbox enqueue). */
5645
+ createdAt: z.number(),
5646
+ /** Last transition time (terminal for sent / dead). */
5647
+ updatedAt: z.number(),
5648
+ /** Failure detail — present on a `dead` row. */
5649
+ error: z.string().optional(),
5650
+ subject: NcHistorySubjectSchema
5651
+ });
5652
+ /**
5653
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
5654
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
5655
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
5656
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
5657
+ */
5658
+ var NcHistoryFilterSchema = z.object({
5659
+ ruleId: z.string().optional(),
5660
+ deviceId: z.number().optional(),
5661
+ status: NcHistoryStatusSchema.optional(),
5662
+ since: z.number().optional(),
5663
+ until: z.number().optional(),
5664
+ limit: z.number().int().min(1).max(500).default(100)
5665
+ });
5666
+ var notificationRulesCapability = {
5667
+ name: "notification-rules",
5668
+ scope: "system",
5360
5669
  mode: "singleton",
5361
- deviceTypes: [DeviceType.AlarmPanel],
5362
5670
  methods: {
5363
- arm: method(z.object({
5364
- deviceId: z.number().int().nonnegative(),
5365
- mode: AlarmArmModeSchema,
5366
- /** Optional PIN code. Required when `requiresCode === true`.
5367
- * Passed through to the upstream service; never persisted. */
5368
- code: z.string().min(1).optional()
5369
- }), z.void(), {
5671
+ listRules: method(z.object({}), z.object({ rules: z.array(NcRuleSchema) }), { auth: "admin" }),
5672
+ getRule: method(z.object({ ruleId: z.string() }), z.object({ rule: NcRuleSchema.nullable() }), { auth: "admin" }),
5673
+ createRule: method(z.object({ rule: NcRuleInputSchema }), z.object({ rule: NcRuleSchema }), {
5674
+ kind: "mutation",
5675
+ auth: "admin",
5676
+ caller: "required"
5677
+ }),
5678
+ updateRule: method(z.object({
5679
+ ruleId: z.string(),
5680
+ patch: NcRulePatchSchema
5681
+ }), z.object({ rule: NcRuleSchema }), {
5682
+ kind: "mutation",
5683
+ auth: "admin",
5684
+ caller: "required"
5685
+ }),
5686
+ deleteRule: method(z.object({ ruleId: z.string() }), z.object({ success: z.literal(true) }), {
5370
5687
  kind: "mutation",
5371
5688
  auth: "admin"
5372
5689
  }),
5373
- disarm: method(z.object({
5374
- deviceId: z.number().int().nonnegative(),
5375
- code: z.string().min(1).optional()
5376
- }), z.void(), {
5690
+ setRuleEnabled: method(z.object({
5691
+ ruleId: z.string(),
5692
+ enabled: z.boolean()
5693
+ }), z.object({ success: z.literal(true) }), {
5377
5694
  kind: "mutation",
5378
5695
  auth: "admin"
5379
5696
  }),
5380
5697
  /**
5381
- * Force the panel into the `triggered` state used by HA
5382
- * automations to surface external sensor events through the panel
5383
- * (e.g. a Reolink camera intrusion event firing the security
5384
- * system). Provider rejects when the panel hardware doesn't
5385
- * support a software-initiated trigger.
5698
+ * Dry-run a rule against recently persisted records (object events for
5699
+ * `immediate`, closed tracks for `track-end`). Mutation kind only to
5700
+ * carry the full rule object safely; no side effects.
5386
5701
  */
5387
- trigger: method(z.object({ deviceId: z.number().int().nonnegative() }), z.void(), {
5702
+ testRule: method(z.object({
5703
+ rule: NcRuleInputSchema,
5704
+ lookbackMinutes: z.number().int().min(1).max(1440).default(60)
5705
+ }), z.object({ results: z.array(NcTestResultSchema) }), {
5388
5706
  kind: "mutation",
5389
5707
  auth: "admin"
5390
- })
5391
- },
5392
- status: {
5393
- schema: AlarmPanelStatusSchema,
5394
- kind: "push"
5395
- },
5396
- /**
5397
- * Runtime-state slice mirrored by the kernel. UI panel reads the
5398
- * full slice; renders an arm button per `availableModes` entry and
5399
- * a PIN field iff `requiresCode === true`.
5400
- */
5401
- runtimeState: AlarmPanelStatusSchema
5708
+ }),
5709
+ getConditionCatalog: method(z.object({}), z.object({ catalog: z.array(NcConditionDescriptorSchema) })),
5710
+ /**
5711
+ * Queryable delivery history — a read-only view over the durable outbox
5712
+ * (fired rule, subject summary, target, status, timestamps, error on a
5713
+ * dead row). Newest-first, bounded by `filter.limit`. Retention follows
5714
+ * the outbox's own terminal-row prune horizon (no separate history
5715
+ * horizonsingle collection, single source of truth). Admin-only in
5716
+ * P1 (no user dimension); the P2 viewer History screen adds per-caller
5717
+ * scoping on the same method.
5718
+ */
5719
+ getHistory: method(z.object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), z.object({ entries: z.array(NcHistoryEntrySchema) }), { auth: "admin" })
5720
+ }
5402
5721
  };
5403
5722
  /**
5404
- * Ambient illuminance reading in lux. Drives Home Assistant `sensor`
5405
- * entries with `device_class: illuminance`.
5406
- */
5407
- var AmbientLightSensorStatusSchema = z.object({
5408
- /** Current illuminance in lux (lx). */
5409
- lux: z.number().min(0),
5723
+ * TimelapseRule the STANDALONE scheduled timelapse producer's rule model.
5724
+ *
5725
+ * Spec: `docs/superpowers/specs/2026-07-24-nc-occupancy-timelapse-design.md`
5726
+ * §3.2/§3.3.
5727
+ *
5728
+ * Deliberately NOT a capability definition and NOT an `NcRule`:
5729
+ * - Every `NcDelivery` member is a *persisted-pipeline-record* trigger. A
5730
+ * timelapse fires on a SCHEDULE WINDOW BOUNDARY, evaluates no pipeline
5731
+ * record, and produces a video it assembled itself — so it rides no
5732
+ * delivery-enum member (the enum is frozen) and no cap method. This file is
5733
+ * a plain typed schema; it does NOT go through `npm run codegen`.
5734
+ * - It shares only the delivery leg (`notification-output.send`) and the
5735
+ * persistence/ownership patterns with the Notification Center, reusing
5736
+ * {@link NcScheduleSchema} (weekly windows, midnight-crossing, invertible)
5737
+ * and {@link NcRuleTargetSchema} (target ref + passthrough params).
5738
+ *
5739
+ * Ownership is SERVER-DERIVED. `ownerUserId` / `createdBy` / `createdAt` /
5740
+ * `updatedAt` / `id` / `lastGeneratedAt` live on the PERSISTED rule only —
5741
+ * {@link TimelapseRuleInputSchema} and {@link TimelapseRulePatchSchema} do not
5742
+ * carry them, so a forged client payload can never claim or re-own a rule
5743
+ * (Zod strips unknown keys). The store stamps them from the resolved caller.
5744
+ */
5745
+ /** `{{var}}` templating over camera/rule/time — same vocabulary as `NcRule`. */
5746
+ var TimelapseTemplateSchema = z.object({
5747
+ title: z.string().max(500).optional(),
5748
+ body: z.string().max(2e3).optional()
5749
+ });
5750
+ var NameField = z.string().min(1).max(200);
5751
+ var DeviceIdsField = z.array(z.number()).min(1);
5752
+ var CadenceSecField = z.number().int().min(2).max(3600);
5753
+ var FramerateField = z.number().int().min(1).max(60);
5754
+ var TargetsField = z.array(NcRuleTargetSchema).min(1);
5755
+ var PriorityField = z.number().int().min(1).max(5);
5756
+ /**
5757
+ * Client-supplied timelapse-rule fields. The server stamps id / createdBy /
5758
+ * createdAt / updatedAt / ownerUserId / lastGeneratedAt — none of them appear
5759
+ * here (see the ownership note above).
5760
+ */
5761
+ var TimelapseRuleInputSchema = z.object({
5762
+ name: NameField,
5763
+ enabled: z.boolean().default(true),
5764
+ /** Cameras sampled by this rule — one scratch dir + one artifact per device. */
5765
+ deviceIds: DeviceIdsField,
5766
+ /**
5767
+ * Activation window(s). REQUIRED (unlike `NcRule`, where an absent schedule
5768
+ * means "always active"): a timelapse is defined by its window boundaries —
5769
+ * open clears the scratch, close assembles and delivers.
5770
+ */
5771
+ schedule: NcScheduleSchema,
5772
+ /** Force-snapshot cadence inside the window, seconds (predecessor parity). */
5773
+ cadenceSec: CadenceSecField.default(15),
5774
+ /** Output frames per second of the assembled mp4 (predecessor parity). */
5775
+ framerate: FramerateField.default(10),
5776
+ /** `notification-output` targets the finished video/thumbnail is sent to. */
5777
+ targets: TargetsField,
5778
+ template: TimelapseTemplateSchema.optional(),
5779
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
5780
+ priority: PriorityField.default(3)
5781
+ });
5782
+ z.object({
5783
+ name: NameField.optional(),
5784
+ enabled: z.boolean().optional(),
5785
+ deviceIds: DeviceIdsField.optional(),
5786
+ schedule: NcScheduleSchema.optional(),
5787
+ cadenceSec: CadenceSecField.optional(),
5788
+ framerate: FramerateField.optional(),
5789
+ targets: TargetsField.optional(),
5790
+ template: TimelapseTemplateSchema.nullable().optional(),
5791
+ priority: PriorityField.optional()
5792
+ });
5793
+ TimelapseRuleInputSchema.extend({
5794
+ id: z.string(),
5795
+ /**
5796
+ * Ownership/visibility key. Absent = admin/global rule (visible to all).
5797
+ * Present = personal rule owned by this userId. Server-stamped from the
5798
+ * resolved caller; never trusted from a client payload.
5799
+ */
5800
+ ownerUserId: z.string().optional(),
5801
+ /**
5802
+ * Epoch-ms of the last successful generation — the 1-hour re-generation
5803
+ * guard's durable state (predecessor parity). Absent = never generated.
5804
+ */
5805
+ lastGeneratedAt: z.number().optional(),
5806
+ /** userId of the caller who created the rule (server-stamped). */
5807
+ createdBy: z.string(),
5808
+ createdAt: z.number(),
5809
+ updatedAt: z.number()
5810
+ });
5811
+ /**
5812
+ * Generic device-level status snapshot. Auto-registered by `BaseDevice`
5813
+ * for every device, regardless of provider — the kernel needs a uniform
5814
+ * cap-keyed slice for the basic device flags every consumer expects to
5815
+ * read across processes (the `online` flag in particular). Driver-specific
5816
+ * caps (`battery`, `doorbell`, …) carry their domain-specific state on
5817
+ * their own slices.
5818
+ *
5819
+ * Pattern is identical to `battery`: schema-bearing `runtimeState`,
5820
+ * empty `methods`, single change event. Reads land at
5821
+ * `runtimeState.getCapState('device-status')`; writes at
5822
+ * `runtimeState.setCapState('device-status', …)`. Cross-process
5823
+ * consumers reach the same data via the `device-state` cap router
5824
+ * (`getCapSlice({deviceId, capName: 'device-status'})`).
5825
+ */
5826
+ var DeviceStatusSchema = z.object({
5827
+ /**
5828
+ * Device-level liveness. Drivers flip via `markOnline(boolean)` on
5829
+ * `BaseDevice`. Provider semantics vary — RTSP aggregates broker
5830
+ * stream-health, Reolink reads firmware push events, ONVIF tracks
5831
+ * ping responses. This cap intentionally does NOT prescribe which
5832
+ * signal drives the flag.
5833
+ */
5834
+ online: z.boolean(),
5835
+ /** Ms epoch of the last `online` transition. Lets consumers tell
5836
+ * apart "just came online" from "still online". */
5837
+ lastChangedAt: z.number()
5838
+ });
5839
+ var deviceStatusCapability = {
5840
+ name: "device-status",
5841
+ scope: "device",
5842
+ deviceNative: true,
5843
+ mode: "singleton",
5844
+ methods: {},
5845
+ events: {
5846
+ /** Emitted when `online` transitions. Mirrors the semantics of
5847
+ * `battery.onStatusChanged`. */
5848
+ onStatusChanged: { data: z.object({
5849
+ deviceId: z.number(),
5850
+ status: DeviceStatusSchema
5851
+ }) } },
5852
+ status: {
5853
+ schema: DeviceStatusSchema,
5854
+ kind: "push"
5855
+ },
5856
+ runtimeState: DeviceStatusSchema
5857
+ };
5858
+ /**
5859
+ * Per-device feature/identity probe slice. Holds the runtime-resolved
5860
+ * truth about what a device CAN do — which the kernel uses to:
5861
+ * 1. Reconcile accessory children (hub-children spawn siren/floodlight/PIR
5862
+ * based on what the firmware actually advertises).
5863
+ * 2. Compute the public `features: DeviceFeature[]` array surfaced via
5864
+ * `device-manager.listAll`.
5865
+ * 3. Decide which optional caps (PTZ, intercom, doorbell, battery, …)
5866
+ * to register on the device's capability surface.
5867
+ *
5868
+ * Auto-registered by `BaseDevice` for every device. Drivers populate the
5869
+ * slice from `onProbe()` (kernel calls it once after register, before
5870
+ * accessory reconciliation). Consumers read via:
5871
+ * `runtimeState.getCapState<FeatureProbeStatus>('feature-probe')`
5872
+ *
5873
+ * `flags` is an open record so each driver carries its own keys without
5874
+ * a centralized schema bottleneck — Reolink writes `hasPtz/hasIntercom`,
5875
+ * Hikvision writes `hasSupplementalLight/hasAlarmIo`, etc.
5876
+ *
5877
+ * Replaces the older driver-local `deviceCache.has*` blob: the per-device
5878
+ * config is for operator-edited overrides + UI snapshots; runtime probe
5879
+ * results belong in runtime-state where the kernel handles persistence,
5880
+ * cross-process mirroring, and reactive updates.
5881
+ */
5882
+ var FeatureProbeStatusSchema = z.object({
5883
+ /**
5884
+ * Driver-specific flag bag. Each driver picks its own key names — the
5885
+ * cap deliberately does NOT enforce a closed enum here. Reolink keys:
5886
+ * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,
5887
+ * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:
5888
+ * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.
5889
+ */
5890
+ flags: z.record(z.string(), z.unknown()),
5891
+ /**
5892
+ * Coarse driver-classification — lets cross-process consumers tell apart
5893
+ * cameras / battery-cams / NVRs without re-running the probe. `null`
5894
+ * before the first probe completes.
5895
+ */
5896
+ deviceType: z.string().nullable(),
5897
+ /** Camera/firmware model string. `null` when the firmware doesn't expose it. */
5898
+ model: z.string().nullable(),
5899
+ /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */
5900
+ channelCount: z.number().nullable(),
5901
+ /**
5902
+ * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe
5903
+ * completes — drivers' `getAccessoryChildren()` should treat zero as
5904
+ * "probe not done yet, return empty" so accessories aren't spawned
5905
+ * before the firmware is queried.
5906
+ */
5907
+ lastProbedAt: z.number(),
5908
+ /**
5909
+ * Framework convention: every runtime-state slice carries this for the
5910
+ * createRuntimeStateBridge stale-check helper. We keep it in sync with
5911
+ * `lastProbedAt` on every write.
5912
+ */
5913
+ lastFetchedAt: z.number()
5914
+ });
5915
+ var featureProbeCapability = {
5916
+ name: "feature-probe",
5917
+ scope: "device",
5918
+ deviceNative: true,
5919
+ mode: "singleton",
5920
+ methods: {},
5921
+ events: {
5922
+ /** Fires whenever a fresh probe completes (kernel-driven `reprobe()`
5923
+ * or driver-initiated re-detect after a state change). */
5924
+ onProbeChanged: { data: z.object({
5925
+ deviceId: z.number(),
5926
+ status: FeatureProbeStatusSchema
5927
+ }) } },
5928
+ status: {
5929
+ schema: FeatureProbeStatusSchema,
5930
+ kind: "push"
5931
+ },
5932
+ runtimeState: FeatureProbeStatusSchema
5933
+ };
5934
+ /**
5935
+ * Multi-metric air-quality slice. Covers CO₂, total VOCs, particulate
5936
+ * matter at PM2.5 / PM10, and a derived AQI index — all optional so
5937
+ * a single-metric source populates only what it observes. Mirrors
5938
+ * the HA `sensor` device_class set (`co2`, `volatile_organic_compounds`,
5939
+ * `pm25`, `pm10`, `aqi`) collapsed into one cap because a typical
5940
+ * air-quality node reports several of these together; modelling them
5941
+ * as siblings keeps a single timestamp + one slice subscription.
5942
+ */
5943
+ var AirQualitySensorStatusSchema = z.object({
5944
+ /** Carbon dioxide concentration in ppm. */
5945
+ co2Ppm: z.number().min(0).optional(),
5946
+ /** Total volatile organic compounds in ppb. */
5947
+ vocPpb: z.number().min(0).optional(),
5948
+ /** Particulate matter ≤ 2.5 μm in µg/m³. */
5949
+ pm25: z.number().min(0).optional(),
5950
+ /** Particulate matter ≤ 10 μm in µg/m³. */
5951
+ pm10: z.number().min(0).optional(),
5952
+ /** Composite AQI value (typically 0..500). */
5953
+ aqi: z.number().optional(),
5410
5954
  /** Ms epoch when the slice was last updated. */
5411
5955
  lastFetchedAt: z.number(),
5412
- /** Live display unit from the upstream source (e.g. HA
5413
- * `attributes.unit_of_measurement`). The UI prefers this over the
5414
- * role's canonical unit. Absent fall back to the canonical unit. */
5956
+ /** Live display unit of the single metric this slice carries (e.g. HA
5957
+ * `attributes.unit_of_measurement` 'ppm' / 'ppb' / 'µg/m³'). Each
5958
+ * upstream `sensor.*` entity surfaces ONE device_class, so one unit
5959
+ * per slice is unambiguous. */
5415
5960
  unit: z.string().optional(),
5416
5961
  /** Suggested decimal places for numeric display.
5417
5962
  * Populated live from the upstream source when provided (e.g. HA
@@ -5419,88 +5964,214 @@ var AmbientLightSensorStatusSchema = z.object({
5419
5964
  * auto-formatting when absent. */
5420
5965
  precision: z.number().int().min(0).max(10).optional()
5421
5966
  });
5422
- var ambientLightSensorCapability = {
5423
- name: "ambient-light-sensor",
5967
+ var airQualitySensorCapability = {
5968
+ name: "air-quality-sensor",
5424
5969
  scope: "device",
5425
5970
  deviceNative: true,
5426
5971
  mode: "singleton",
5427
5972
  deviceTypes: [DeviceType.Sensor],
5428
5973
  methods: {},
5429
5974
  status: {
5430
- schema: AmbientLightSensorStatusSchema,
5975
+ schema: AirQualitySensorStatusSchema,
5431
5976
  kind: "push"
5432
5977
  },
5433
- runtimeState: AmbientLightSensorStatusSchema
5978
+ runtimeState: AirQualitySensorStatusSchema
5434
5979
  };
5435
5980
  /**
5436
- * Per-class audio metrics aggregated over a sliding window.
5437
- */
5438
- var AudioClassSummarySchema = z.object({
5439
- className: z.string(),
5440
- /** Number of windows (chunks) where this class was the top hit. */
5441
- hits: z.number().int().nonnegative(),
5442
- /** Mean score across those hits, clamped to [0,1]. */
5443
- avgScore: z.number().min(0).max(1),
5444
- /** Peak score in the window. */
5445
- peakScore: z.number().min(0).max(1)
5446
- });
5447
- /**
5448
- * Per-camera audio metrics snapshot — emitted by the analytics frame
5449
- * handler on every `pipeline.audio-inference-result` event and
5450
- * mirrored into the `audio-metrics` device-state slice. Symmetric
5451
- * with `zone-analytics` snapshots for video — every consumer
5452
- * (admin UI panel, automations, alert rules) reads via the
5453
- * canonical `device.state.audioMetrics.value` reactive handle.
5981
+ * Alarm-panel cap. Models HA `alarm_control_panel.*` on
5982
+ * `DeviceType.AlarmPanel`. State follows HA's canonical lifecycle
5983
+ * across disarmed / armed_(home|away|night|vacation|custom_bypass) /
5984
+ * arming / pending / triggered / disarming.
5454
5985
  *
5455
- * Aggregates are computed over a rolling `windowSec` window
5456
- * (default 60s). Past that window, classes drop out of `byClass`
5457
- * and the level history shifts forward.
5458
- */
5459
- var AudioMetricsSnapshotSchema = z.object({
5460
- /** Wall-clock timestamp (ms) of the most recent audio window. */
5461
- ts: z.number().int(),
5462
- /** Sliding-window length (seconds) used for aggregation. */
5463
- windowSec: z.number().int().positive(),
5464
- /** Latest level reading from the most recent window. */
5465
- level: z.object({
5466
- rms: z.number(),
5467
- dbfs: z.number()
5468
- }),
5469
- /** Peak dBFS observed across the rolling window. */
5470
- peakDbfs: z.number(),
5471
- /** Mean dBFS across the rolling window. */
5472
- avgDbfs: z.number(),
5473
- /** Most recent above-threshold classification, or null on silence. */
5474
- current: z.object({
5475
- className: z.string(),
5476
- score: z.number().min(0).max(1),
5477
- timestamp: z.number().int()
5478
- }).nullable(),
5479
- /** Per-class summary across the rolling window — keys are
5480
- * `macroClass` strings (e.g. `dog_bark`, `speech`, `glass_break`). */
5481
- byClass: z.array(AudioClassSummarySchema).readonly()
5482
- });
5483
- /**
5484
- * One sample on the audio-metrics history time-series. Captures the
5485
- * subset of the live snapshot useful for charting: dB level, peak/avg
5486
- * over the rolling window, and the dominant above-threshold class
5487
- * (when any). Per-class hit breakdown lives on the snapshot but is
5488
- * elided from the history sample to keep the buffer compact —
5489
- * consumers needing class drill-down should pull `getCurrentSnapshot`.
5986
+ * Many panels require a PIN code on arm / disarm — the optional
5987
+ * `code` field on the methods passes it through to the upstream
5988
+ * service; it's NEVER persisted in the runtime slice or any event
5989
+ * payload. The presence of a required code is signalled by
5990
+ * `DeviceFeature.AlarmPinRequired` so the UI gates a code-entry
5991
+ * field without a slice fetch.
5992
+ *
5993
+ * `availableModes` mirrors HA's `supported_features`-derived arm
5994
+ * mode list — the UI renders only the buttons the panel accepts.
5490
5995
  */
5491
- var AudioMetricsHistoryPointSchema = z.object({
5492
- /** Wall-clock ms when this sample was recorded. */
5493
- ts: z.number().int(),
5494
- /** Instantaneous dBFS level at sample time. `null` for windows where
5495
- * the source had no level reading (rare; happens at decode startup). */
5496
- dbfs: z.number().nullable(),
5497
- /** Rolling-window peak dBFS at sample time. Same window the live
5498
- * snapshot reports. */
5499
- peakDbfs: z.number(),
5500
- /** Rolling-window mean dBFS at sample time. */
5501
- avgDbfs: z.number(),
5502
- /** Dominant above-threshold class at sample time, or null on silence. */
5503
- topClass: z.string().nullable(),
5996
+ var AlarmStateSchema = z.enum([
5997
+ "disarmed",
5998
+ "armed_home",
5999
+ "armed_away",
6000
+ "armed_night",
6001
+ "armed_vacation",
6002
+ "armed_custom_bypass",
6003
+ "arming",
6004
+ "disarming",
6005
+ "pending",
6006
+ "triggered"
6007
+ ]);
6008
+ var AlarmArmModeSchema = z.enum([
6009
+ "home",
6010
+ "away",
6011
+ "night",
6012
+ "vacation",
6013
+ "custom_bypass"
6014
+ ]);
6015
+ var AlarmPanelStatusSchema = z.object({
6016
+ /** Current lifecycle state. */
6017
+ state: AlarmStateSchema,
6018
+ /** Subset of arm modes the panel accepts. UI renders one button per
6019
+ * mode in this list. */
6020
+ availableModes: z.array(AlarmArmModeSchema),
6021
+ /** Whether the panel requires a PIN on arm / disarm. Mirrors
6022
+ * `DeviceFeature.AlarmPinRequired` for slice consumers. */
6023
+ requiresCode: z.boolean(),
6024
+ /** Ms epoch when the slice was last updated. */
6025
+ lastChangedAt: z.number()
6026
+ });
6027
+ var alarmPanelCapability = {
6028
+ name: "alarm-panel",
6029
+ scope: "device",
6030
+ deviceNative: true,
6031
+ mode: "singleton",
6032
+ deviceTypes: [DeviceType.AlarmPanel],
6033
+ methods: {
6034
+ arm: method(z.object({
6035
+ deviceId: z.number().int().nonnegative(),
6036
+ mode: AlarmArmModeSchema,
6037
+ /** Optional PIN code. Required when `requiresCode === true`.
6038
+ * Passed through to the upstream service; never persisted. */
6039
+ code: z.string().min(1).optional()
6040
+ }), z.void(), {
6041
+ kind: "mutation",
6042
+ auth: "admin"
6043
+ }),
6044
+ disarm: method(z.object({
6045
+ deviceId: z.number().int().nonnegative(),
6046
+ code: z.string().min(1).optional()
6047
+ }), z.void(), {
6048
+ kind: "mutation",
6049
+ auth: "admin"
6050
+ }),
6051
+ /**
6052
+ * Force the panel into the `triggered` state — used by HA
6053
+ * automations to surface external sensor events through the panel
6054
+ * (e.g. a Reolink camera intrusion event firing the security
6055
+ * system). Provider rejects when the panel hardware doesn't
6056
+ * support a software-initiated trigger.
6057
+ */
6058
+ trigger: method(z.object({ deviceId: z.number().int().nonnegative() }), z.void(), {
6059
+ kind: "mutation",
6060
+ auth: "admin"
6061
+ })
6062
+ },
6063
+ status: {
6064
+ schema: AlarmPanelStatusSchema,
6065
+ kind: "push"
6066
+ },
6067
+ /**
6068
+ * Runtime-state slice — mirrored by the kernel. UI panel reads the
6069
+ * full slice; renders an arm button per `availableModes` entry and
6070
+ * a PIN field iff `requiresCode === true`.
6071
+ */
6072
+ runtimeState: AlarmPanelStatusSchema
6073
+ };
6074
+ /**
6075
+ * Ambient illuminance reading in lux. Drives Home Assistant `sensor`
6076
+ * entries with `device_class: illuminance`.
6077
+ */
6078
+ var AmbientLightSensorStatusSchema = z.object({
6079
+ /** Current illuminance in lux (lx). */
6080
+ lux: z.number().min(0),
6081
+ /** Ms epoch when the slice was last updated. */
6082
+ lastFetchedAt: z.number(),
6083
+ /** Live display unit from the upstream source (e.g. HA
6084
+ * `attributes.unit_of_measurement`). The UI prefers this over the
6085
+ * role's canonical unit. Absent → fall back to the canonical unit. */
6086
+ unit: z.string().optional(),
6087
+ /** Suggested decimal places for numeric display.
6088
+ * Populated live from the upstream source when provided (e.g. HA
6089
+ * `attributes.suggested_display_precision`). Falls back to
6090
+ * auto-formatting when absent. */
6091
+ precision: z.number().int().min(0).max(10).optional()
6092
+ });
6093
+ var ambientLightSensorCapability = {
6094
+ name: "ambient-light-sensor",
6095
+ scope: "device",
6096
+ deviceNative: true,
6097
+ mode: "singleton",
6098
+ deviceTypes: [DeviceType.Sensor],
6099
+ methods: {},
6100
+ status: {
6101
+ schema: AmbientLightSensorStatusSchema,
6102
+ kind: "push"
6103
+ },
6104
+ runtimeState: AmbientLightSensorStatusSchema
6105
+ };
6106
+ /**
6107
+ * Per-class audio metrics aggregated over a sliding window.
6108
+ */
6109
+ var AudioClassSummarySchema = z.object({
6110
+ className: z.string(),
6111
+ /** Number of windows (chunks) where this class was the top hit. */
6112
+ hits: z.number().int().nonnegative(),
6113
+ /** Mean score across those hits, clamped to [0,1]. */
6114
+ avgScore: z.number().min(0).max(1),
6115
+ /** Peak score in the window. */
6116
+ peakScore: z.number().min(0).max(1)
6117
+ });
6118
+ /**
6119
+ * Per-camera audio metrics snapshot — emitted by the analytics frame
6120
+ * handler on every `pipeline.audio-inference-result` event and
6121
+ * mirrored into the `audio-metrics` device-state slice. Symmetric
6122
+ * with `zone-analytics` snapshots for video — every consumer
6123
+ * (admin UI panel, automations, alert rules) reads via the
6124
+ * canonical `device.state.audioMetrics.value` reactive handle.
6125
+ *
6126
+ * Aggregates are computed over a rolling `windowSec` window
6127
+ * (default 60s). Past that window, classes drop out of `byClass`
6128
+ * and the level history shifts forward.
6129
+ */
6130
+ var AudioMetricsSnapshotSchema = z.object({
6131
+ /** Wall-clock timestamp (ms) of the most recent audio window. */
6132
+ ts: z.number().int(),
6133
+ /** Sliding-window length (seconds) used for aggregation. */
6134
+ windowSec: z.number().int().positive(),
6135
+ /** Latest level reading from the most recent window. */
6136
+ level: z.object({
6137
+ rms: z.number(),
6138
+ dbfs: z.number()
6139
+ }),
6140
+ /** Peak dBFS observed across the rolling window. */
6141
+ peakDbfs: z.number(),
6142
+ /** Mean dBFS across the rolling window. */
6143
+ avgDbfs: z.number(),
6144
+ /** Most recent above-threshold classification, or null on silence. */
6145
+ current: z.object({
6146
+ className: z.string(),
6147
+ score: z.number().min(0).max(1),
6148
+ timestamp: z.number().int()
6149
+ }).nullable(),
6150
+ /** Per-class summary across the rolling window — keys are
6151
+ * `macroClass` strings (e.g. `dog_bark`, `speech`, `glass_break`). */
6152
+ byClass: z.array(AudioClassSummarySchema).readonly()
6153
+ });
6154
+ /**
6155
+ * One sample on the audio-metrics history time-series. Captures the
6156
+ * subset of the live snapshot useful for charting: dB level, peak/avg
6157
+ * over the rolling window, and the dominant above-threshold class
6158
+ * (when any). Per-class hit breakdown lives on the snapshot but is
6159
+ * elided from the history sample to keep the buffer compact —
6160
+ * consumers needing class drill-down should pull `getCurrentSnapshot`.
6161
+ */
6162
+ var AudioMetricsHistoryPointSchema = z.object({
6163
+ /** Wall-clock ms when this sample was recorded. */
6164
+ ts: z.number().int(),
6165
+ /** Instantaneous dBFS level at sample time. `null` for windows where
6166
+ * the source had no level reading (rare; happens at decode startup). */
6167
+ dbfs: z.number().nullable(),
6168
+ /** Rolling-window peak dBFS at sample time. Same window the live
6169
+ * snapshot reports. */
6170
+ peakDbfs: z.number(),
6171
+ /** Rolling-window mean dBFS at sample time. */
6172
+ avgDbfs: z.number(),
6173
+ /** Dominant above-threshold class at sample time, or null on silence. */
6174
+ topClass: z.string().nullable(),
5504
6175
  /** Score of the dominant class (`null` whenever `topClass` is null). */
5505
6176
  topScore: z.number().min(0).max(1).nullable()
5506
6177
  });
@@ -9712,69 +10383,6 @@ var motionTriggerCapability = {
9712
10383
  runtimeState: MotionTriggerRuntimeStateSchema
9713
10384
  };
9714
10385
  /**
9715
- * Shared geometry vocabulary for on-frame shape caps — privacy-mask,
9716
- * motion-zones, and the detection zones/lines editor all speak this one
9717
- * language so a single drawing-plane editor and the providers stay
9718
- * decoupled from each cap's storage.
9719
- *
9720
- * All coordinates are normalized 0..1 of the camera frame (top-left
9721
- * origin). Each cap composes the SUBSET of shape kinds it supports and
9722
- * advertises it via `supportedShapes` in its `getOptions`.
9723
- */
9724
- /** A normalized 0..1 point (top-left origin). */
9725
- var MaskPointSchema = z.object({
9726
- x: z.number(),
9727
- y: z.number()
9728
- });
9729
- /** Axis-aligned rectangle (normalized 0..1). */
9730
- var MaskRectShapeSchema = z.object({
9731
- kind: z.literal("rect"),
9732
- x: z.number(),
9733
- y: z.number(),
9734
- width: z.number(),
9735
- height: z.number()
9736
- });
9737
- /** Free polygon — an ordered list of normalized vertices (≥3). */
9738
- var MaskPolygonShapeSchema = z.object({
9739
- kind: z.literal("polygon"),
9740
- points: z.array(MaskPointSchema)
9741
- });
9742
- /** Boolean cell grid — row-major, length === gridWidth*gridHeight. */
9743
- var MaskGridShapeSchema = z.object({
9744
- kind: z.literal("grid"),
9745
- gridWidth: z.number(),
9746
- gridHeight: z.number(),
9747
- cells: z.array(z.boolean())
9748
- });
9749
- /** Directed line / tripwire — an ordered list of normalized points (≥2). */
9750
- var MaskLineShapeSchema = z.object({
9751
- kind: z.literal("line"),
9752
- points: z.array(MaskPointSchema)
9753
- });
9754
- z.discriminatedUnion("kind", [
9755
- MaskRectShapeSchema,
9756
- MaskPolygonShapeSchema,
9757
- MaskGridShapeSchema,
9758
- MaskLineShapeSchema
9759
- ]);
9760
- /** Every shape-kind discriminant, for `supportedShapes` advertisement. */
9761
- var MaskShapeKindSchema = z.enum([
9762
- "rect",
9763
- "polygon",
9764
- "grid",
9765
- "line"
9766
- ]);
9767
- /** Polygon vertex bounds when a cap supports 'polygon' (e.g. Hikvision {min:4,max:4}). */
9768
- var MaskPolygonVerticesSchema = z.object({
9769
- min: z.number(),
9770
- max: z.number()
9771
- });
9772
- /** Grid dimensions when a cap supports 'grid'. */
9773
- var MaskGridDimsSchema = z.object({
9774
- width: z.number(),
9775
- height: z.number()
9776
- });
9777
- /**
9778
10386
  * Motion-zones share the same MaskShape vocabulary as privacy-mask — the
9779
10387
  * on-camera motion-detection mask is a single `grid` region (a row-major
9780
10388
  * boolean cell lattice the camera's onboard VMD evaluates). Composing it as
@@ -12797,21 +13405,97 @@ var authProviderCapability = {
12797
13405
  mount: { kind: "skip" }
12798
13406
  };
12799
13407
  /**
12800
- * Orchestrator-side destination metadata. The orchestrator computes
12801
- * `id = <addonId>:<subId>` from its provider lookup so consumers
12802
- * (admin UI, restore flow) see one canonical key.
12803
- *
12804
- * Phase 4 (admin UI redesign) adds the per-destination policy fields
12805
- * (`enabled`, `retentionCount`, `label`) so the destinations table can
12806
- * render the joined view without a follow-up round-trip. The backend
12807
- * already joins these in `listDestinations` — we now surface them on
12808
- * the wire.
12809
- *
12810
- * `lastSuccessAt` / `lastSuccessSizeBytes` are computed from each
12811
- * location's `manifests.json` (newest archive). Optional — locations
12812
- * with no archives yet leave them undefined.
13408
+ * A live terminal session hosted by the provider addon. Output and input do
13409
+ * NOT flow through the capability they use the addon data plane
13410
+ * (`GET /addon/terminal/<id>/out` SSE, `POST /addon/terminal/<id>/in`) because
13411
+ * terminal output must be ordered and lossless. The event bus is telemetry and
13412
+ * may drop chunks ([D8]), and a dropped chunk desynchronises the vt parser
13413
+ * permanently until a full repaint. The capability owns only lifecycle.
12813
13414
  */
12814
- var BackupDestinationInfoSchema = z.object({
13415
+ var TerminalSessionInfoSchema = z.object({
13416
+ /** Opaque session id minted by the provider on `openSession`. */
13417
+ sessionId: z.string(),
13418
+ /** The pre-declared profile this session runs (never a free-form command). */
13419
+ profileId: z.string(),
13420
+ /** Human-readable profile label for the UI session list. */
13421
+ label: z.string(),
13422
+ cols: z.number().int().positive(),
13423
+ rows: z.number().int().positive(),
13424
+ /** ms-epoch the session's pty was spawned. */
13425
+ startedAt: z.number()
13426
+ });
13427
+ /**
13428
+ * A profile the operator may open — a pre-declared, allowlisted program
13429
+ * (`monitor` → `btm`). The capability accepts only these ids; a free-form
13430
+ * command string would be remote code execution as the server's user, so it is
13431
+ * deliberately not part of the contract.
13432
+ */
13433
+ var TerminalProfileInfoSchema = z.object({
13434
+ profileId: z.string(),
13435
+ label: z.string(),
13436
+ description: z.string().optional()
13437
+ });
13438
+ /**
13439
+ * terminal-session — singleton system capability for interactive TTY sessions.
13440
+ *
13441
+ * Phase 1 (this cap): open/resize/close/list a pty running an allowlisted
13442
+ * profile, streamed to xterm.js over the data plane. Phase 2 (streaming a
13443
+ * session as a camera) is a separate device-provider concern and does not
13444
+ * change this contract.
13445
+ */
13446
+ var terminalSessionCapability = {
13447
+ name: "terminal-session",
13448
+ scope: "system",
13449
+ mode: "singleton",
13450
+ methods: {
13451
+ /** Pre-declared profiles the operator may open. */
13452
+ listProfiles: method(z.void(), z.array(TerminalProfileInfoSchema).readonly(), { auth: "admin" }),
13453
+ /** Live sessions currently hosted by the provider. */
13454
+ listSessions: method(z.void(), z.array(TerminalSessionInfoSchema).readonly(), { auth: "admin" }),
13455
+ /**
13456
+ * Spawn a pty for an allowlisted profile at the given grid size and return
13457
+ * its session id. Output/input then flow over the data plane by that id.
13458
+ */
13459
+ openSession: method(z.object({
13460
+ profileId: z.string(),
13461
+ cols: z.number().int().positive(),
13462
+ rows: z.number().int().positive()
13463
+ }), TerminalSessionInfoSchema, {
13464
+ kind: "mutation",
13465
+ auth: "admin"
13466
+ }),
13467
+ /** Resize a live session's pty (reflows the running program). */
13468
+ resize: method(z.object({
13469
+ sessionId: z.string(),
13470
+ cols: z.number().int().positive(),
13471
+ rows: z.number().int().positive()
13472
+ }), z.void(), {
13473
+ kind: "mutation",
13474
+ auth: "admin"
13475
+ }),
13476
+ /** Terminate a live session and release its pty. */
13477
+ close: method(z.object({ sessionId: z.string() }), z.void(), {
13478
+ kind: "mutation",
13479
+ auth: "admin"
13480
+ })
13481
+ }
13482
+ };
13483
+ /**
13484
+ * Orchestrator-side destination metadata. The orchestrator computes
13485
+ * `id = <addonId>:<subId>` from its provider lookup so consumers
13486
+ * (admin UI, restore flow) see one canonical key.
13487
+ *
13488
+ * Phase 4 (admin UI redesign) adds the per-destination policy fields
13489
+ * (`enabled`, `retentionCount`, `label`) so the destinations table can
13490
+ * render the joined view without a follow-up round-trip. The backend
13491
+ * already joins these in `listDestinations` — we now surface them on
13492
+ * the wire.
13493
+ *
13494
+ * `lastSuccessAt` / `lastSuccessSizeBytes` are computed from each
13495
+ * location's `manifests.json` (newest archive). Optional — locations
13496
+ * with no archives yet leave them undefined.
13497
+ */
13498
+ var BackupDestinationInfoSchema = z.object({
12815
13499
  /**
12816
13500
  * Sub-id within this addon. Convention `default` for single-
12817
13501
  * destination addons; addons that host many (S3 with N buckets)
@@ -15814,780 +16498,261 @@ var mqttBrokerCapability = {
15814
16498
  }
15815
16499
  };
15816
16500
  var NetworkEndpointSchema = z.object({
15817
- url: z.string(),
15818
- hostname: z.string(),
15819
- port: z.number(),
15820
- protocol: z.enum(["http", "https"])
15821
- });
15822
- var NetworkAccessStatusSchema = z.object({
15823
- connected: z.boolean(),
15824
- endpoint: NetworkEndpointSchema.nullable(),
15825
- error: z.string().optional()
15826
- });
15827
- /**
15828
- * Optional, richer endpoint shape returned by providers that expose
15829
- * MORE than one ingress concurrently (Tailscale Ingress with mixed
15830
- * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
15831
- * the originating provider config (mode + sourcePort) so the
15832
- * orchestrator UI can label rows distinctly. Providers that expose only
15833
- * one endpoint just omit `listEndpoints` from their provider impl.
15834
- */
15835
- var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
15836
- /**
15837
- * Stable id within the provider — typically `<mode>-<sourcePort>` so
15838
- * the orchestrator can dedupe across `listEndpoints` polls.
15839
- */
15840
- id: z.string(),
15841
- /** Operator-facing label (mirrors `MeshEndpoint.label`). */
15842
- label: z.string(),
15843
- /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
15844
- mode: z.string().optional(),
15845
- /** Originating local port the ingress fronts (informational). */
15846
- sourcePort: z.number().optional()
15847
- });
15848
- var networkAccessCapability = {
15849
- name: "network-access",
15850
- scope: "system",
15851
- mode: "collection",
15852
- providerKind: "ingress",
15853
- methods: {
15854
- start: method(z.void(), NetworkEndpointSchema, { kind: "mutation" }),
15855
- stop: method(z.void(), z.void(), { kind: "mutation" }),
15856
- getEndpoint: method(z.void(), NetworkEndpointSchema.nullable()),
15857
- getStatus: method(z.void(), NetworkAccessStatusSchema),
15858
- /**
15859
- * Enumerate every active ingress entry. Providers that expose only a
15860
- * single endpoint may omit this method; callers fall back to
15861
- * `getEndpoint()` in that case.
15862
- */
15863
- listEndpoints: method(z.void(), z.array(NetworkEndpointEntrySchema).readonly())
15864
- }
15865
- };
15866
- /**
15867
- * notification-output — canonical, capability-gated notification delivery.
15868
- *
15869
- * Apprise-derived model (see
15870
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
15871
- * callers emit ONE canonical `Notification`; each provider declares a
15872
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
15873
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
15874
- * message to what the kind supports — callers never special-case a service.
15875
- *
15876
- * DESIGN DECISIONS (locked):
15877
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
15878
- * `setTargetEnabled`), each provider persisting via the `settings-store`
15879
- * cap. Rationale: the admin UI needs one uniform surface across the
15880
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
15881
- * alternative would fork the UI per addon and cannot host the
15882
- * discovery→adopt flow.
15883
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
15884
- * the generated cap-mount auto-`concatCollection`-fans them across every
15885
- * registered provider (notifiers addon + HA addon) so one catalog is
15886
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
15887
- * `addonId` the generated collection router extracts from the call input.
15888
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
15889
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
15890
- * `storage` / `storage-provider` / `recording` caps over the same path. No
15891
- * base64 fallback needed.
15892
- *
15893
- * TODO (deferred, closed-set change — separate decision): add
15894
- * `providerKind: 'notify'` so notification providers surface on the unified
15895
- * admin "Integrations" page.
15896
- */
15897
- /**
15898
- * Zentik-derived typed-media enum — the superset across every kind. Each
15899
- * adapter picks what it supports and the degrade engine filters the rest.
15900
- */
15901
- var AttachmentMediaTypeSchema = z.enum([
15902
- "image",
15903
- "video",
15904
- "gif",
15905
- "audio",
15906
- "icon"
15907
- ]);
15908
- /**
15909
- * A single attachment. Exactly one of `url` (remote source, most adapters
15910
- * prefer this) or `bytes` (inline source; required for Pushover-style
15911
- * bytes-only kinds) MUST be present — the degrade engine expresses a
15912
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
15913
- */
15914
- var AttachmentSchema = z.object({
15915
- mediaType: AttachmentMediaTypeSchema,
15916
- url: z.string().optional(),
15917
- bytes: z.instanceof(Uint8Array).optional(),
15918
- mime: z.string().optional(),
15919
- name: z.string().optional()
15920
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
15921
- var NotificationFormatSchema = z.enum([
15922
- "text",
15923
- "markdown",
15924
- "html"
15925
- ]);
15926
- /** A single tap-through action button. */
15927
- var NotificationActionSchema = z.object({
15928
- id: z.string(),
15929
- label: z.string(),
15930
- url: z.string().optional()
15931
- });
15932
- /**
15933
- * The canonical notification. `body` is the only hard field (Apprise model).
15934
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
15935
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
15936
- * the adapter maps this ordinal onto its native level. `level?` is an
15937
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
15938
- * `priority` for that one target.
15939
- */
15940
- var NotificationSchema = z.object({
15941
- body: z.string(),
15942
- title: z.string().optional(),
15943
- format: NotificationFormatSchema.default("text"),
15944
- priority: z.number().int().min(1).max(5).default(3),
15945
- level: z.string().optional(),
15946
- attachments: z.array(AttachmentSchema).optional(),
15947
- clickUrl: z.string().optional(),
15948
- actions: z.array(NotificationActionSchema).optional(),
15949
- sound: z.string().optional(),
15950
- ttl: z.number().optional(),
15951
- tag: z.string().optional(),
15952
- deviceId: z.number().optional(),
15953
- eventId: z.string().optional(),
15954
- metadata: z.record(z.string(), z.unknown()).optional()
15955
- });
15956
- /** One declared native severity/priority level for a kind. */
15957
- var TargetKindLevelSchema = z.object({
15958
- id: z.string(),
15959
- label: z.string(),
15960
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
15961
- ordinal: z.number().int().min(1).max(5).nullable(),
15962
- flags: z.object({
15963
- critical: z.boolean().optional(),
15964
- silent: z.boolean().optional(),
15965
- noPush: z.boolean().optional()
15966
- }).optional(),
15967
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
15968
- requires: z.array(z.string()).optional(),
15969
- description: z.string().optional()
15970
- });
15971
- /** Attachment capabilities for a kind (drives the degrade engine + test panel). */
15972
- var TargetKindAttachmentsCapsSchema = z.object({
15973
- mediaTypes: z.array(AttachmentMediaTypeSchema),
15974
- mode: z.enum([
15975
- "url",
15976
- "bytes",
15977
- "both"
15978
- ]),
15979
- max: z.number().int().nonnegative(),
15980
- maxBytes: z.number().int().positive().optional()
15981
- });
15982
- /** The full capability block consulted before dispatch. */
15983
- var TargetKindCapsSchema = z.object({
15984
- attachments: TargetKindAttachmentsCapsSchema,
15985
- /** Max action buttons (0 = none). */
15986
- actions: z.number().int().nonnegative(),
15987
- levels: z.array(TargetKindLevelSchema),
15988
- format: z.array(NotificationFormatSchema),
15989
- clickUrl: z.boolean(),
15990
- sound: z.boolean(),
15991
- ttl: z.boolean(),
15992
- bodyMaxLen: z.number().int().positive()
15993
- });
15994
- /**
15995
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
15996
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
15997
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
15998
- * the union is large and not meant for runtime validation here; the exported
15999
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
16000
- */
16001
- var ConfigSchemaPassthrough = z.unknown();
16002
- var TargetKindSchema = z.object({
16003
- kind: z.string(),
16004
- label: z.string(),
16005
- icon: z.string(),
16006
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
16007
- addonId: z.string(),
16008
- configSchema: ConfigSchemaPassthrough,
16009
- supportsDiscovery: z.boolean(),
16010
- caps: TargetKindCapsSchema
16011
- });
16012
- /**
16013
- * A persisted target. `config` holds secrets; providers REDACT secret fields
16014
- * (return a presence marker only) when serving `listTargets` — never
16015
- * round-trip a stored secret to the UI.
16016
- */
16017
- var TargetSchema = z.object({
16018
- id: z.string(),
16019
- name: z.string(),
16020
- kind: z.string(),
16021
- addonId: z.string(),
16022
- enabled: z.boolean(),
16023
- config: z.record(z.string(), z.unknown())
16024
- });
16025
- /** A discovery-surfaced candidate (config is partial + non-secret). */
16026
- var DiscoveredTargetSchema = z.object({
16027
- kind: z.string(),
16028
- suggestedName: z.string(),
16029
- config: z.record(z.string(), z.unknown())
16030
- });
16031
- /** The degrade engine's report — what was resolved / dropped / degraded. */
16032
- var RenderedAsSchema = z.object({
16033
- level: z.string(),
16034
- format: NotificationFormatSchema,
16035
- attachmentsSent: z.number().int().nonnegative(),
16036
- actionsSent: z.number().int().nonnegative(),
16037
- truncated: z.boolean(),
16038
- dropped: z.array(z.string())
16039
- });
16040
- var SendResultSchema = z.object({
16041
- success: z.boolean(),
16042
- error: z.string().optional(),
16043
- renderedAs: RenderedAsSchema.optional()
16044
- });
16045
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
16046
- var TestResultSchema = SendResultSchema;
16047
- var notificationOutputCapability = {
16048
- name: "notification-output",
16049
- scope: "system",
16050
- mode: "collection",
16051
- methods: {
16052
- listTargetKinds: method(z.object({}), z.array(TargetKindSchema)),
16053
- listTargets: method(z.object({}), z.array(TargetSchema)),
16054
- discoverTargets: method(z.object({
16055
- kind: z.string(),
16056
- config: z.record(z.string(), z.unknown()).optional()
16057
- }), z.array(DiscoveredTargetSchema)),
16058
- send: method(z.object({
16059
- targetId: z.string(),
16060
- notification: NotificationSchema
16061
- }), SendResultSchema, { kind: "mutation" }),
16062
- testTarget: method(z.object({
16063
- targetId: z.string(),
16064
- sample: NotificationSchema.optional()
16065
- }), TestResultSchema, { kind: "mutation" }),
16066
- upsertTarget: method(z.object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }),
16067
- deleteTarget: method(z.object({ targetId: z.string() }), z.void(), { kind: "mutation" }),
16068
- setTargetEnabled: method(z.object({
16069
- targetId: z.string(),
16070
- enabled: z.boolean()
16071
- }), z.void(), { kind: "mutation" })
16072
- }
16073
- };
16074
- /**
16075
- * notification-rules — the Notification Center rule surface (P1 core).
16076
- *
16077
- * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16078
- * (operator decisions D-1/D-2/D-3 are binding):
16079
- *
16080
- * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16081
- * `notification-center` module), hooked on the durable persistence
16082
- * moments (object-event insert, TrackCloser.closeExpired) with a
16083
- * persisted outbox + retry — never the lossy telemetry bus (D8).
16084
- * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16085
- * FIRST persisted detection matching the conditions (per-track dedup,
16086
- * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16087
- * `delivery: 'track-end'` evaluates the finalized track record at close.
16088
- * - DISPATCH stays behind `notification-output` (rules reference targets
16089
- * by id; per-backend params are a passthrough blob capped by the
16090
- * target kind's own caps/degrade engine).
16091
- *
16092
- * P1 scope: admin-authored rules only (`createdBy` stamped from the
16093
- * server-injected caller identity — the first `caller: 'required'`
16094
- * adopter). The P1 condition subset is: devices, classes(+exclude),
16095
- * minConfidence, admin zones (any/all + exclude), weekly schedule
16096
- * windows, and the optional label/identity/plate matchers. User rules,
16097
- * private zones, per-recipient fan-out and the wider condition table are
16098
- * P2+ (see spec §7).
16099
- *
16100
- * All schemas here are the single source of truth — `NcRule` etc. are
16101
- * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16102
- * schema/interface drift is explicitly not repeated).
16103
- */
16104
- /**
16105
- * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
16106
- * The value maps 1:1 onto the evaluated record kind:
16107
- * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16108
- * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16109
- * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16110
- * change of a LINKED device, one row per linked camera)
16111
- * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16112
- * delivery / pick-up)
16113
- *
16114
- * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16115
- * `package-event` are pure trigger kinds (no urgency dimension). Extending
16116
- * this one field keeps the schema additive — a rule still declares exactly
16117
- * one trigger.
16118
- */
16119
- var NcDeliverySchema = z.enum([
16120
- "immediate",
16121
- "track-end",
16122
- "device-event",
16123
- "package-event"
16124
- ]);
16125
- /** One weekly activation window. `startMinute > endMinute` crosses midnight. */
16126
- var NcScheduleWindowSchema = z.object({
16127
- /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16128
- days: z.array(z.number().int().min(0).max(6)).min(1),
16129
- startMinute: z.number().int().min(0).max(1439),
16130
- endMinute: z.number().int().min(0).max(1439)
16131
- });
16132
- /** Weekly schedule — OR of windows; absence on the rule = always active. */
16133
- var NcScheduleSchema = z.object({
16134
- windows: z.array(NcScheduleWindowSchema).min(1),
16135
- /** IANA timezone; default = hub host timezone. */
16136
- timezone: z.string().optional(),
16137
- /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16138
- invert: z.boolean().optional()
16139
- });
16140
- /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16141
- var NcPlateMatcherSchema = z.object({
16142
- values: z.array(z.string().min(1)).min(1),
16143
- /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16144
- maxDistance: z.number().int().min(0).max(3).default(1)
16145
- });
16146
- /**
16147
- * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16148
- * occupancy edge for a device — optionally narrowed to a single admin
16149
- * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16150
- * - `became-occupied` (default) — count crossed 0 → ≥ `count`
16151
- * - `became-free` — count crossed ≥ `count` → below it
16152
- * - `>=` / `<=` — count is at/over or at/under `count`
16153
- * `sustainSeconds` requires the condition hold continuously that long
16154
- * before firing (debounces flicker; 0 = fire on the first matching edge).
16155
- * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16156
- * the condition never matches. Confirmed edge-state survives addon restarts
16157
- * (declared SQLite collection, reseeded on boot).
16158
- */
16159
- var NcOccupancyConditionSchema = z.object({
16160
- /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16161
- zoneId: z.string().optional(),
16162
- /** Object class to count; absent = any class. */
16163
- className: z.string().optional(),
16164
- op: z.enum([
16165
- "became-occupied",
16166
- "became-free",
16167
- ">=",
16168
- "<="
16169
- ]).default("became-occupied"),
16170
- count: z.number().int().min(0).default(1),
16171
- sustainSeconds: z.number().int().min(0).max(3600).default(15)
16172
- });
16173
- /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16174
- var NcZoneConditionSchema = z.object({
16175
- ids: z.array(z.string().min(1)).min(1),
16176
- /** Quantifier over `ids` — at least one / every one visited. */
16177
- match: z.enum(["any", "all"]).default("any")
16178
- });
16179
- /**
16180
- * The P1 condition set — a flat AND of groups; absent group = pass;
16181
- * membership lists are OR within the list (spec §2.3).
16182
- */
16183
- var NcConditionsSchema = z.object({
16184
- /** Device scope — absent = all devices. */
16185
- devices: z.array(z.number()).optional(),
16186
- /** Detector class names (any overlap with the record's class set). */
16187
- classes: z.array(z.string().min(1)).optional(),
16188
- /** Veto classes — any overlap fails the rule. */
16189
- classesExclude: z.array(z.string().min(1)).optional(),
16190
- /** Minimum detection confidence 0–1 (fails when the record has none). */
16191
- minConfidence: z.number().min(0).max(1).optional(),
16192
- /** Admin zone membership over event `zones` / track `zonesVisited`. */
16193
- zones: NcZoneConditionSchema.optional(),
16194
- /** Veto zones — any hit fails the rule. */
16195
- zonesExclude: z.array(z.string().min(1)).optional(),
16196
- /**
16197
- * Exact (case-insensitive) match on the record's collapsed `label`
16198
- * (identity name / plate text / subclass).
16199
- */
16200
- labelEquals: z.array(z.string().min(1)).optional(),
16201
- /**
16202
- * Identity matcher. P1 boundary: matched against the record's collapsed
16203
- * `label` (the identity display name propagated by the face pipeline) —
16204
- * identity-ID matching rides in P2 when identity ids reach the record.
16205
- */
16206
- identities: z.array(z.string().min(1)).optional(),
16207
- /** Fuzzy plate matcher against the record's `label` (plate text). */
16208
- plates: NcPlateMatcherSchema.optional(),
16209
- /**
16210
- * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16211
- * Same P1 boundary: matched against the record's collapsed `label` (the
16212
- * identity display name). A record with NO label passes (nothing to
16213
- * exclude), unlike the include variant which fails on an absent label.
16214
- */
16215
- identitiesExclude: z.array(z.string().min(1)).optional(),
16216
- /**
16217
- * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16218
- * TRACK-END only: importance is scored at track close, so it does not exist
16219
- * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16220
- * close the value is threaded via the close-time info (the `Track` clone is
16221
- * captured before the DB row is updated, so it would otherwise read stale).
16222
- * Fails when the record carries no importance (never guess quality — the
16223
- * `minConfidence` precedent). MVP cut: a single scalar threshold.
16224
- */
16225
- minImportance: z.number().min(0).max(1).optional(),
16226
- /**
16227
- * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16228
- * TRACK-END only: an `immediate` / object-event subject has no closed
16229
- * lifespan, so a dwell condition never matches immediate delivery
16230
- * (documented choice — the object-event record carries no `firstSeen`,
16231
- * so dwell cannot be computed from what the subject actually carries).
16232
- */
16233
- minDwellSeconds: z.number().min(0).optional(),
16234
- /**
16235
- * Detection provenance filter. `any` (default / absent) matches every
16236
- * source; otherwise the subject's source must equal it. Legacy records
16237
- * with no stamped source are treated as `pipeline`. The union spans both
16238
- * record kinds — object events carry `pipeline` | `onboard`, synthetic
16239
- * tracks carry `sensor`.
16240
- */
16241
- source: z.enum([
16242
- "pipeline",
16243
- "onboard",
16244
- "sensor",
16245
- "any"
16246
- ]).optional(),
16247
- /**
16248
- * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16249
- * detector `minConfidence` (that gates the object-detection score; this
16250
- * gates the recognition/OCR match score). Fails when the subject carries
16251
- * no label-match confidence (never guess). TRACK-END only: the confidence
16252
- * lives on the recognition result and reaches the subject at track close.
16253
- *
16254
- * What it measures precisely (plumbed at track close — the closer threads
16255
- * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16256
- * `importance`): the BEST recognition match confidence observed for the
16257
- * label the track carries at close — for a face, the peak cosine similarity
16258
- * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16259
- * for a plate, the peak OCR read score of the best-held plate
16260
- * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16261
- * one track the higher of the two is used. A track that ended with no
16262
- * confident identity/plate match carries no value, so the condition fails
16263
- * closed for it (an un-recognized subject).
16264
- */
16265
- minLabelConfidence: z.number().min(0).max(1).optional(),
16266
- /**
16267
- * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16268
- * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16269
- * against the token carried on the device-event subject (extracted from the
16270
- * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16271
- * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16272
- * eventType, so gate those with {@link sensorKinds} instead.
16273
- */
16274
- eventTypeTokens: z.array(z.string().min(1)).optional(),
16275
- /**
16276
- * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16277
- * `contact`, `button`, `device-event`) — matched against the persisted
16278
- * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16279
- */
16280
- sensorKinds: z.array(z.string().min(1)).optional(),
16281
- /**
16282
- * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16283
- * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16284
- * when the subject's phase does not match (a subject always carries a phase
16285
- * on the package-event trigger).
16286
- */
16287
- packagePhase: z.enum([
16288
- "delivered",
16289
- "picked-up",
16290
- "both"
16291
- ]).optional(),
16292
- /**
16293
- * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16294
- * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16295
- * listed polygon (ZoneEngine membership semantics). Evaluated only when
16296
- * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16297
- */
16298
- customZones: z.array(MaskPolygonShapeSchema).optional(),
16299
- /**
16300
- * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16301
- * (optionally zone/class-scoped) occupancy count crosses the configured
16302
- * threshold and holds for `sustainSeconds`. Fail-closed on missing
16303
- * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16304
- */
16305
- occupancy: NcOccupancyConditionSchema.optional()
16501
+ url: z.string(),
16502
+ hostname: z.string(),
16503
+ port: z.number(),
16504
+ protocol: z.enum(["http", "https"])
16306
16505
  });
16307
- /** One delivery target: a `notification-output` Target ref + passthrough params. */
16308
- var NcRuleTargetSchema = z.object({
16309
- /** `notification-output` Target id. */
16310
- targetId: z.string().min(1),
16311
- /**
16312
- * Per-backend passthrough. Recognized keys are mapped onto the canonical
16313
- * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16314
- * degrade engine drops what the backend can't render.
16315
- */
16316
- params: z.record(z.string(), z.unknown()).optional()
16506
+ var NetworkAccessStatusSchema = z.object({
16507
+ connected: z.boolean(),
16508
+ endpoint: NetworkEndpointSchema.nullable(),
16509
+ error: z.string().optional()
16317
16510
  });
16318
16511
  /**
16319
- * Media attachment policy (P1 still-image subset).
16320
- * - `best` the best AVAILABLE subject image at dispatch time (D-3).
16321
- * - `best-matching` the media that explains WHY the rule fired: a rule
16322
- * matched on identities attaches the subject's `faceCrop`, one matched on
16323
- * plates attaches the `plateCrop`; a rule with no identity/plate condition
16324
- * (or when the specific crop is missing) degrades to `best`, then
16325
- * `keyFrame`, then no attachment — never delaying the send. The matched
16326
- * condition summary is frozen on the outbox row at enqueue (like the rule
16327
- * name), so the choice never drifts from the record that fired it.
16328
- * - `keyFrame` — the clean scene frame (no subject box).
16329
- * - `none` — no attachment.
16512
+ * Optional, richer endpoint shape returned by providers that expose
16513
+ * MORE than one ingress concurrently (Tailscale Ingress with mixed
16514
+ * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
16515
+ * the originating provider config (mode + sourcePort) so the
16516
+ * orchestrator UI can label rows distinctly. Providers that expose only
16517
+ * one endpoint just omit `listEndpoints` from their provider impl.
16330
16518
  */
16331
- var NcMediaPolicySchema = z.object({ attach: z.enum([
16332
- "best",
16333
- "best-matching",
16334
- "keyFrame",
16335
- "none"
16336
- ]).default("best") });
16337
- /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16338
- var NcThrottleSchema = z.object({
16339
- cooldownSec: z.number().int().min(0).max(86400).default(60),
16340
- /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16341
- scope: z.enum(["rule", "rule-device"]).default("rule-device")
16342
- });
16343
- /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16344
- var NcRuleInputSchema = z.object({
16345
- name: z.string().min(1).max(200),
16346
- enabled: z.boolean().default(true),
16347
- delivery: NcDeliverySchema,
16348
- conditions: NcConditionsSchema.default({}),
16349
- schedule: NcScheduleSchema.optional(),
16350
- targets: z.array(NcRuleTargetSchema).min(1),
16351
- media: NcMediaPolicySchema.default({ attach: "best" }),
16352
- throttle: NcThrottleSchema.default({
16353
- cooldownSec: 60,
16354
- scope: "rule-device"
16355
- }),
16356
- /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16357
- template: z.object({
16358
- title: z.string().max(500).optional(),
16359
- body: z.string().max(2e3).optional()
16360
- }).optional(),
16361
- /** Canonical notification priority ordinal (1..5); per-target overridable. */
16362
- priority: z.number().int().min(1).max(5).default(3),
16519
+ var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
16363
16520
  /**
16364
- * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16365
- * behaviour, visible to all, read-only in the viewer). Present = personal
16366
- * rule owned by this userId. Server-stamped; never trusted from a client.
16521
+ * Stable id within the provider typically `<mode>-<sourcePort>` so
16522
+ * the orchestrator can dedupe across `listEndpoints` polls.
16367
16523
  */
16368
- ownerUserId: z.string().optional()
16524
+ id: z.string(),
16525
+ /** Operator-facing label (mirrors `MeshEndpoint.label`). */
16526
+ label: z.string(),
16527
+ /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
16528
+ mode: z.string().optional(),
16529
+ /** Originating local port the ingress fronts (informational). */
16530
+ sourcePort: z.number().optional()
16369
16531
  });
16532
+ var networkAccessCapability = {
16533
+ name: "network-access",
16534
+ scope: "system",
16535
+ mode: "collection",
16536
+ providerKind: "ingress",
16537
+ methods: {
16538
+ start: method(z.void(), NetworkEndpointSchema, { kind: "mutation" }),
16539
+ stop: method(z.void(), z.void(), { kind: "mutation" }),
16540
+ getEndpoint: method(z.void(), NetworkEndpointSchema.nullable()),
16541
+ getStatus: method(z.void(), NetworkAccessStatusSchema),
16542
+ /**
16543
+ * Enumerate every active ingress entry. Providers that expose only a
16544
+ * single endpoint may omit this method; callers fall back to
16545
+ * `getEndpoint()` in that case.
16546
+ */
16547
+ listEndpoints: method(z.void(), z.array(NetworkEndpointEntrySchema).readonly())
16548
+ }
16549
+ };
16370
16550
  /**
16371
- * Partial patch for `updateRule` any subset of the input fields, plus the
16372
- * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16373
- * NOT a client-authored input field (it lives on the persisted rule, not the
16374
- * input), so it is added here explicitly to let the store's per-target opt-out
16375
- * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16376
- * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16377
- * `updateRule` patch.
16551
+ * notification-outputcanonical, capability-gated notification delivery.
16552
+ *
16553
+ * Apprise-derived model (see
16554
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
16555
+ * callers emit ONE canonical `Notification`; each provider declares a
16556
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
16557
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
16558
+ * message to what the kind supports — callers never special-case a service.
16559
+ *
16560
+ * DESIGN DECISIONS (locked):
16561
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
16562
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
16563
+ * cap. Rationale: the admin UI needs one uniform surface across the
16564
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
16565
+ * alternative would fork the UI per addon and cannot host the
16566
+ * discovery→adopt flow.
16567
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
16568
+ * the generated cap-mount auto-`concatCollection`-fans them across every
16569
+ * registered provider (notifiers addon + HA addon) so one catalog is
16570
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
16571
+ * `addonId` the generated collection router extracts from the call input.
16572
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
16573
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
16574
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
16575
+ * base64 fallback needed.
16576
+ *
16577
+ * TODO (deferred, closed-set change — separate decision): add
16578
+ * `providerKind: 'notify'` so notification providers surface on the unified
16579
+ * admin "Integrations" page.
16378
16580
  */
16379
- var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: z.array(z.string()).optional() });
16380
- /** A persisted rule. */
16381
- var NcRuleSchema = NcRuleInputSchema.extend({
16382
- id: z.string(),
16383
- /** userId of the admin who created the rule (server-stamped caller). */
16384
- createdBy: z.string(),
16385
- createdAt: z.number(),
16386
- updatedAt: z.number(),
16387
- /**
16388
- * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16389
- * send time. Only a target's OWNER may add/remove its id (server-checked
16390
- * in `nc.setRuleTargetEnabled`). Defaults to empty.
16391
- */
16392
- disabledTargetIds: z.array(z.string()).default([])
16393
- });
16394
- var NcTestResultSchema = z.object({
16395
- recordId: z.string(),
16396
- recordKind: z.enum([
16397
- "object-event",
16398
- "track",
16399
- "device-event",
16400
- "package-event"
16401
- ]),
16402
- deviceId: z.number(),
16403
- timestamp: z.number(),
16404
- wouldFire: z.boolean(),
16405
- /** Condition id that failed (first failing group), when `wouldFire` is false. */
16406
- failedCondition: z.string().optional(),
16407
- className: z.string().optional(),
16408
- label: z.string().optional()
16409
- });
16410
- var NcConditionDescriptorSchema = z.object({
16411
- /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16581
+ /**
16582
+ * Zentik-derived typed-media enum — the superset across every kind. Each
16583
+ * adapter picks what it supports and the degrade engine filters the rest.
16584
+ */
16585
+ var AttachmentMediaTypeSchema = z.enum([
16586
+ "image",
16587
+ "video",
16588
+ "gif",
16589
+ "audio",
16590
+ "icon"
16591
+ ]);
16592
+ /**
16593
+ * A single attachment. Exactly one of `url` (remote source, most adapters
16594
+ * prefer this) or `bytes` (inline source; required for Pushover-style
16595
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
16596
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
16597
+ */
16598
+ var AttachmentSchema = z.object({
16599
+ mediaType: AttachmentMediaTypeSchema,
16600
+ url: z.string().optional(),
16601
+ bytes: z.instanceof(Uint8Array).optional(),
16602
+ mime: z.string().optional(),
16603
+ name: z.string().optional()
16604
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
16605
+ var NotificationFormatSchema = z.enum([
16606
+ "text",
16607
+ "markdown",
16608
+ "html"
16609
+ ]);
16610
+ /** A single tap-through action button. */
16611
+ var NotificationActionSchema = z.object({
16412
16612
  id: z.string(),
16413
- group: z.enum([
16414
- "scope",
16415
- "class",
16416
- "zones",
16417
- "quality",
16418
- "label",
16419
- "schedule",
16420
- "device",
16421
- "package",
16422
- "occupancy"
16423
- ]),
16424
16613
  label: z.string(),
16425
- /** Editor widget the UI renders — never hardcode per-condition forms. */
16426
- valueType: z.enum([
16427
- "deviceIdList",
16428
- "stringList",
16429
- "number01",
16430
- "number",
16431
- "sourceSelect",
16432
- "zoneSelection",
16433
- "zoneIdList",
16434
- "schedule",
16435
- "plateMatcher",
16436
- "packagePhase",
16437
- "polygonDraw",
16438
- "occupancy"
16439
- ]),
16440
- operator: z.enum([
16441
- "in",
16442
- "notIn",
16443
- "anyOf",
16444
- "allOf",
16445
- "gte",
16446
- "fuzzyIn",
16447
- "withinSchedule"
16448
- ]),
16449
- /** Which delivery kinds the condition applies to. */
16450
- appliesTo: z.array(NcDeliverySchema),
16451
- phase: z.string(),
16614
+ url: z.string().optional()
16615
+ });
16616
+ /**
16617
+ * The canonical notification. `body` is the only hard field (Apprise model).
16618
+ * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
16619
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
16620
+ * the adapter maps this ordinal onto its native level. `level?` is an
16621
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
16622
+ * `priority` for that one target.
16623
+ */
16624
+ var NotificationSchema = z.object({
16625
+ body: z.string(),
16626
+ title: z.string().optional(),
16627
+ format: NotificationFormatSchema.default("text"),
16628
+ priority: z.number().int().min(1).max(5).default(3),
16629
+ level: z.string().optional(),
16630
+ attachments: z.array(AttachmentSchema).optional(),
16631
+ clickUrl: z.string().optional(),
16632
+ actions: z.array(NotificationActionSchema).optional(),
16633
+ sound: z.string().optional(),
16634
+ ttl: z.number().optional(),
16635
+ tag: z.string().optional(),
16636
+ deviceId: z.number().optional(),
16637
+ eventId: z.string().optional(),
16638
+ metadata: z.record(z.string(), z.unknown()).optional()
16639
+ });
16640
+ /** One declared native severity/priority level for a kind. */
16641
+ var TargetKindLevelSchema = z.object({
16642
+ id: z.string(),
16643
+ label: z.string(),
16644
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
16645
+ ordinal: z.number().int().min(1).max(5).nullable(),
16646
+ flags: z.object({
16647
+ critical: z.boolean().optional(),
16648
+ silent: z.boolean().optional(),
16649
+ noPush: z.boolean().optional()
16650
+ }).optional(),
16651
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
16652
+ requires: z.array(z.string()).optional(),
16452
16653
  description: z.string().optional()
16453
16654
  });
16655
+ /** Attachment capabilities for a kind (drives the degrade engine + test panel). */
16656
+ var TargetKindAttachmentsCapsSchema = z.object({
16657
+ mediaTypes: z.array(AttachmentMediaTypeSchema),
16658
+ mode: z.enum([
16659
+ "url",
16660
+ "bytes",
16661
+ "both"
16662
+ ]),
16663
+ max: z.number().int().nonnegative(),
16664
+ maxBytes: z.number().int().positive().optional()
16665
+ });
16666
+ /** The full capability block consulted before dispatch. */
16667
+ var TargetKindCapsSchema = z.object({
16668
+ attachments: TargetKindAttachmentsCapsSchema,
16669
+ /** Max action buttons (0 = none). */
16670
+ actions: z.number().int().nonnegative(),
16671
+ levels: z.array(TargetKindLevelSchema),
16672
+ format: z.array(NotificationFormatSchema),
16673
+ clickUrl: z.boolean(),
16674
+ sound: z.boolean(),
16675
+ ttl: z.boolean(),
16676
+ bodyMaxLen: z.number().int().positive()
16677
+ });
16454
16678
  /**
16455
- * The delivery lifecycle status of a history row a straight read of the
16456
- * durable outbox row's own status (single source of truth):
16457
- * - `pending` — enqueued, in-flight or retrying with backoff
16458
- * - `sent` — delivered (terminal)
16459
- * - `dead` dead-lettered after exhausting retries / a permanent
16460
- * backend rejection / a deleted target (terminal; carries
16461
- * the failure `error`)
16462
- *
16463
- * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
16464
- * user dimension (quiet hours / snooze) and are additive when they land.
16679
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
16680
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
16681
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
16682
+ * the union is large and not meant for runtime validation here; the exported
16683
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
16465
16684
  */
16466
- var NcHistoryStatusSchema = z.enum([
16467
- "pending",
16468
- "sent",
16469
- "dead"
16470
- ]);
16471
- /** The evaluated record kind a history row descends from (one per trigger). */
16472
- var NcHistoryRecordKindSchema = z.enum([
16473
- "object-event",
16474
- "track-end",
16475
- "device-event",
16476
- "package-event"
16477
- ]);
16478
- /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16479
- var NcHistorySubjectSchema = z.object({
16480
- className: z.string(),
16481
- label: z.string().optional(),
16482
- confidence: z.number().optional(),
16483
- zones: z.array(z.string()),
16484
- timestamp: z.number()
16685
+ var ConfigSchemaPassthrough = z.unknown();
16686
+ var TargetKindSchema = z.object({
16687
+ kind: z.string(),
16688
+ label: z.string(),
16689
+ icon: z.string(),
16690
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
16691
+ addonId: z.string(),
16692
+ configSchema: ConfigSchemaPassthrough,
16693
+ supportsDiscovery: z.boolean(),
16694
+ caps: TargetKindCapsSchema
16485
16695
  });
16486
16696
  /**
16487
- * One delivery-history row. This is a read-only VIEW over the durable
16488
- * outbox row (single source of truth the same row the drain loop drives;
16489
- * NO second write path, so history can never drift from delivery state).
16490
- * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16491
- * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16492
- * (fire) / `updatedAt` (last transition), `status` + `error` are the
16493
- * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16494
- * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16495
- * P1 (admin scope only).
16697
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
16698
+ * (return a presence marker only) when serving `listTargets` never
16699
+ * round-trip a stored secret to the UI.
16496
16700
  */
16497
- var NcHistoryEntrySchema = z.object({
16498
- /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16701
+ var TargetSchema = z.object({
16499
16702
  id: z.string(),
16500
- ruleId: z.string(),
16501
- /** Rule name frozen at fire time (outlives a later rename / delete). */
16502
- ruleName: z.string(),
16503
- /** The rule urgency/trigger that produced this delivery. */
16504
- delivery: NcDeliverySchema,
16505
- targetId: z.string(),
16506
- deviceId: z.number(),
16507
- recordKind: NcHistoryRecordKindSchema,
16508
- /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16509
- recordId: z.string(),
16510
- /** Present for track-scoped deliveries (object-event / track-end). */
16511
- trackId: z.string().optional(),
16512
- status: NcHistoryStatusSchema,
16513
- /** Delivery attempts made so far. */
16514
- attempts: z.number().int(),
16515
- /** Fire time (outbox enqueue). */
16516
- createdAt: z.number(),
16517
- /** Last transition time (terminal for sent / dead). */
16518
- updatedAt: z.number(),
16519
- /** Failure detail — present on a `dead` row. */
16520
- error: z.string().optional(),
16521
- subject: NcHistorySubjectSchema
16703
+ name: z.string(),
16704
+ kind: z.string(),
16705
+ addonId: z.string(),
16706
+ enabled: z.boolean(),
16707
+ config: z.record(z.string(), z.unknown())
16522
16708
  });
16523
- /**
16524
- * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16525
- * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16526
- * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16527
- * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16528
- */
16529
- var NcHistoryFilterSchema = z.object({
16530
- ruleId: z.string().optional(),
16531
- deviceId: z.number().optional(),
16532
- status: NcHistoryStatusSchema.optional(),
16533
- since: z.number().optional(),
16534
- until: z.number().optional(),
16535
- limit: z.number().int().min(1).max(500).default(100)
16709
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
16710
+ var DiscoveredTargetSchema = z.object({
16711
+ kind: z.string(),
16712
+ suggestedName: z.string(),
16713
+ config: z.record(z.string(), z.unknown())
16536
16714
  });
16537
- var notificationRulesCapability = {
16538
- name: "notification-rules",
16715
+ /** The degrade engine's report — what was resolved / dropped / degraded. */
16716
+ var RenderedAsSchema = z.object({
16717
+ level: z.string(),
16718
+ format: NotificationFormatSchema,
16719
+ attachmentsSent: z.number().int().nonnegative(),
16720
+ actionsSent: z.number().int().nonnegative(),
16721
+ truncated: z.boolean(),
16722
+ dropped: z.array(z.string())
16723
+ });
16724
+ var SendResultSchema = z.object({
16725
+ success: z.boolean(),
16726
+ error: z.string().optional(),
16727
+ renderedAs: RenderedAsSchema.optional()
16728
+ });
16729
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
16730
+ var TestResultSchema = SendResultSchema;
16731
+ var notificationOutputCapability = {
16732
+ name: "notification-output",
16539
16733
  scope: "system",
16540
- mode: "singleton",
16734
+ mode: "collection",
16541
16735
  methods: {
16542
- listRules: method(z.object({}), z.object({ rules: z.array(NcRuleSchema) }), { auth: "admin" }),
16543
- getRule: method(z.object({ ruleId: z.string() }), z.object({ rule: NcRuleSchema.nullable() }), { auth: "admin" }),
16544
- createRule: method(z.object({ rule: NcRuleInputSchema }), z.object({ rule: NcRuleSchema }), {
16545
- kind: "mutation",
16546
- auth: "admin",
16547
- caller: "required"
16548
- }),
16549
- updateRule: method(z.object({
16550
- ruleId: z.string(),
16551
- patch: NcRulePatchSchema
16552
- }), z.object({ rule: NcRuleSchema }), {
16553
- kind: "mutation",
16554
- auth: "admin",
16555
- caller: "required"
16556
- }),
16557
- deleteRule: method(z.object({ ruleId: z.string() }), z.object({ success: z.literal(true) }), {
16558
- kind: "mutation",
16559
- auth: "admin"
16560
- }),
16561
- setRuleEnabled: method(z.object({
16562
- ruleId: z.string(),
16736
+ listTargetKinds: method(z.object({}), z.array(TargetKindSchema)),
16737
+ listTargets: method(z.object({}), z.array(TargetSchema)),
16738
+ discoverTargets: method(z.object({
16739
+ kind: z.string(),
16740
+ config: z.record(z.string(), z.unknown()).optional()
16741
+ }), z.array(DiscoveredTargetSchema)),
16742
+ send: method(z.object({
16743
+ targetId: z.string(),
16744
+ notification: NotificationSchema
16745
+ }), SendResultSchema, { kind: "mutation" }),
16746
+ testTarget: method(z.object({
16747
+ targetId: z.string(),
16748
+ sample: NotificationSchema.optional()
16749
+ }), TestResultSchema, { kind: "mutation" }),
16750
+ upsertTarget: method(z.object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }),
16751
+ deleteTarget: method(z.object({ targetId: z.string() }), z.void(), { kind: "mutation" }),
16752
+ setTargetEnabled: method(z.object({
16753
+ targetId: z.string(),
16563
16754
  enabled: z.boolean()
16564
- }), z.object({ success: z.literal(true) }), {
16565
- kind: "mutation",
16566
- auth: "admin"
16567
- }),
16568
- /**
16569
- * Dry-run a rule against recently persisted records (object events for
16570
- * `immediate`, closed tracks for `track-end`). Mutation kind only to
16571
- * carry the full rule object safely; no side effects.
16572
- */
16573
- testRule: method(z.object({
16574
- rule: NcRuleInputSchema,
16575
- lookbackMinutes: z.number().int().min(1).max(1440).default(60)
16576
- }), z.object({ results: z.array(NcTestResultSchema) }), {
16577
- kind: "mutation",
16578
- auth: "admin"
16579
- }),
16580
- getConditionCatalog: method(z.object({}), z.object({ catalog: z.array(NcConditionDescriptorSchema) })),
16581
- /**
16582
- * Queryable delivery history — a read-only view over the durable outbox
16583
- * (fired rule, subject summary, target, status, timestamps, error on a
16584
- * dead row). Newest-first, bounded by `filter.limit`. Retention follows
16585
- * the outbox's own terminal-row prune horizon (no separate history
16586
- * horizon — single collection, single source of truth). Admin-only in
16587
- * P1 (no user dimension); the P2 viewer History screen adds per-caller
16588
- * scoping on the same method.
16589
- */
16590
- getHistory: method(z.object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), z.object({ entries: z.array(NcHistoryEntrySchema) }), { auth: "admin" })
16755
+ }), z.void(), { kind: "mutation" })
16591
16756
  }
16592
16757
  };
16593
16758
  /**
@@ -23156,6 +23321,7 @@ var ALL_CAPABILITY_DEFINITIONS = [
23156
23321
  systemCapability,
23157
23322
  tamperCapability,
23158
23323
  temperatureSensorCapability,
23324
+ terminalSessionCapability,
23159
23325
  toastCapability,
23160
23326
  turnProviderCapability,
23161
23327
  updateCapability,
@@ -27635,6 +27801,36 @@ var METHOD_ACCESS_MAP = Object.freeze({
27635
27801
  addonId: null,
27636
27802
  access: "create"
27637
27803
  },
27804
+ "terminalSession.close": {
27805
+ capName: "terminal-session",
27806
+ capScope: "system",
27807
+ addonId: null,
27808
+ access: "create"
27809
+ },
27810
+ "terminalSession.listProfiles": {
27811
+ capName: "terminal-session",
27812
+ capScope: "system",
27813
+ addonId: null,
27814
+ access: "view"
27815
+ },
27816
+ "terminalSession.listSessions": {
27817
+ capName: "terminal-session",
27818
+ capScope: "system",
27819
+ addonId: null,
27820
+ access: "view"
27821
+ },
27822
+ "terminalSession.openSession": {
27823
+ capName: "terminal-session",
27824
+ capScope: "system",
27825
+ addonId: null,
27826
+ access: "create"
27827
+ },
27828
+ "terminalSession.resize": {
27829
+ capName: "terminal-session",
27830
+ capScope: "system",
27831
+ addonId: null,
27832
+ access: "create"
27833
+ },
27638
27834
  "toast.onToast": {
27639
27835
  capName: "toast",
27640
27836
  capScope: "system",