@camstack/addon-export-hap 1.2.5 → 1.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7538,16 +7538,23 @@ var StorageLocationDeclarationSchema = object({
7538
7538
  * Which node root the seeded `<id>:default` instance is placed under on a
7539
7539
  * FRESH install:
7540
7540
  * - `'data'` (default) — the node's data dir (`CAMSTACK_DATA` / boot dir),
7541
- * the appData volume. Right for small/durable data (backups, logs, models).
7541
+ * the appData volume. Right for small/durable data (logs, models).
7542
7542
  * - `'media'` — the dedicated media volume (`CAMSTACK_MEDIA_ROOT`) when that
7543
7543
  * env is set, else falls back to the data root. Right for bulky, hot media
7544
7544
  * (recordings, event media) that should stay off the appData disk.
7545
+ * - `'backup'` — the dedicated backup volume (`CAMSTACK_BACKUP_ROOT`, default
7546
+ * `/backups` in the image) so archives live on their own mount rather than
7547
+ * filling the appData disk. Falls back to the data root when unset.
7545
7548
  *
7546
7549
  * Only affects the seeded default's `basePath`; operators can repoint any
7547
7550
  * location afterwards, and a `defaultsTo` slot inherits its parent's root
7548
7551
  * regardless of this field. Absent (the common case) is treated as `'data'`.
7549
7552
  */
7550
- defaultRoot: _enum(["data", "media"]).optional()
7553
+ defaultRoot: _enum([
7554
+ "data",
7555
+ "media",
7556
+ "backup"
7557
+ ]).optional()
7551
7558
  });
7552
7559
  var DecoderStatsSchema = object({
7553
7560
  inputFps: number(),
@@ -8952,92 +8959,730 @@ var AccessoryKind = {
8952
8959
  AccessoryKind.Siren, AccessoryKind.Floodlight, AccessoryKind.Spotlight, AccessoryKind.PirSensor, AccessoryKind.Chime, AccessoryKind.Autotrack, AccessoryKind.Nightvision, AccessoryKind.PrivacyMask;
8953
8960
  DeviceFeature.BatteryOperated;
8954
8961
  /**
8955
- * Generic device-level status snapshot. Auto-registered by `BaseDevice`
8956
- * for every device, regardless of provider the kernel needs a uniform
8957
- * cap-keyed slice for the basic device flags every consumer expects to
8958
- * read across processes (the `online` flag in particular). Driver-specific
8959
- * caps (`battery`, `doorbell`, …) carry their domain-specific state on
8960
- * their own slices.
8962
+ * Shared geometry vocabulary for on-frame shape caps — privacy-mask,
8963
+ * motion-zones, and the detection zones/lines editor all speak this one
8964
+ * language so a single drawing-plane editor and the providers stay
8965
+ * decoupled from each cap's storage.
8961
8966
  *
8962
- * Pattern is identical to `battery`: schema-bearing `runtimeState`,
8963
- * empty `methods`, single change event. Reads land at
8964
- * `runtimeState.getCapState('device-status')`; writes at
8965
- * `runtimeState.setCapState('device-status', …)`. Cross-process
8966
- * consumers reach the same data via the `device-state` cap router
8967
- * (`getCapSlice({deviceId, capName: 'device-status'})`).
8967
+ * All coordinates are normalized 0..1 of the camera frame (top-left
8968
+ * origin). Each cap composes the SUBSET of shape kinds it supports and
8969
+ * advertises it via `supportedShapes` in its `getOptions`.
8968
8970
  */
8969
- var DeviceStatusSchema = object({
8970
- /**
8971
- * Device-level liveness. Drivers flip via `markOnline(boolean)` on
8972
- * `BaseDevice`. Provider semantics vary — RTSP aggregates broker
8973
- * stream-health, Reolink reads firmware push events, ONVIF tracks
8974
- * ping responses. This cap intentionally does NOT prescribe which
8975
- * signal drives the flag.
8976
- */
8977
- online: boolean(),
8978
- /** Ms epoch of the last `online` transition. Lets consumers tell
8979
- * apart "just came online" from "still online". */
8980
- lastChangedAt: number()
8971
+ /** A normalized 0..1 point (top-left origin). */
8972
+ var MaskPointSchema = object({
8973
+ x: number(),
8974
+ y: number()
8981
8975
  });
8982
- object({
8983
- deviceId: number(),
8984
- status: DeviceStatusSchema
8976
+ /** Axis-aligned rectangle (normalized 0..1). */
8977
+ var MaskRectShapeSchema = object({
8978
+ kind: literal("rect"),
8979
+ x: number(),
8980
+ y: number(),
8981
+ width: number(),
8982
+ height: number()
8983
+ });
8984
+ /** Free polygon — an ordered list of normalized vertices (≥3). */
8985
+ var MaskPolygonShapeSchema = object({
8986
+ kind: literal("polygon"),
8987
+ points: array(MaskPointSchema)
8988
+ });
8989
+ /** Boolean cell grid — row-major, length === gridWidth*gridHeight. */
8990
+ var MaskGridShapeSchema = object({
8991
+ kind: literal("grid"),
8992
+ gridWidth: number(),
8993
+ gridHeight: number(),
8994
+ cells: array(boolean())
8995
+ });
8996
+ discriminatedUnion("kind", [
8997
+ MaskRectShapeSchema,
8998
+ MaskPolygonShapeSchema,
8999
+ MaskGridShapeSchema,
9000
+ object({
9001
+ kind: literal("line"),
9002
+ points: array(MaskPointSchema)
9003
+ })
9004
+ ]);
9005
+ /** Every shape-kind discriminant, for `supportedShapes` advertisement. */
9006
+ var MaskShapeKindSchema = _enum([
9007
+ "rect",
9008
+ "polygon",
9009
+ "grid",
9010
+ "line"
9011
+ ]);
9012
+ /** Polygon vertex bounds when a cap supports 'polygon' (e.g. Hikvision {min:4,max:4}). */
9013
+ var MaskPolygonVerticesSchema = object({
9014
+ min: number(),
9015
+ max: number()
9016
+ });
9017
+ /** Grid dimensions when a cap supports 'grid'. */
9018
+ var MaskGridDimsSchema = object({
9019
+ width: number(),
9020
+ height: number()
8985
9021
  });
8986
9022
  /**
8987
- * Per-device feature/identity probe slice. Holds the runtime-resolved
8988
- * truth about what a device CAN do — which the kernel uses to:
8989
- * 1. Reconcile accessory children (hub-children spawn siren/floodlight/PIR
8990
- * based on what the firmware actually advertises).
8991
- * 2. Compute the public `features: DeviceFeature[]` array surfaced via
8992
- * `device-manager.listAll`.
8993
- * 3. Decide which optional caps (PTZ, intercom, doorbell, battery, …)
8994
- * to register on the device's capability surface.
9023
+ * notification-rules the Notification Center rule surface (P1 core).
8995
9024
  *
8996
- * Auto-registered by `BaseDevice` for every device. Drivers populate the
8997
- * slice from `onProbe()` (kernel calls it once after register, before
8998
- * accessory reconciliation). Consumers read via:
8999
- * `runtimeState.getCapState<FeatureProbeStatus>('feature-probe')`
9025
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
9026
+ * (operator decisions D-1/D-2/D-3 are binding):
9000
9027
  *
9001
- * `flags` is an open record so each driver carries its own keys without
9002
- * a centralized schema bottleneck Reolink writes `hasPtz/hasIntercom`,
9003
- * Hikvision writes `hasSupplementalLight/hasAlarmIo`, etc.
9028
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
9029
+ * `notification-center` module), hooked on the durable persistence
9030
+ * moments (object-event insert, TrackCloser.closeExpired) with a
9031
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
9032
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
9033
+ * FIRST persisted detection matching the conditions (per-track dedup,
9034
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
9035
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
9036
+ * - DISPATCH stays behind `notification-output` (rules reference targets
9037
+ * by id; per-backend params are a passthrough blob capped by the
9038
+ * target kind's own caps/degrade engine).
9004
9039
  *
9005
- * Replaces the older driver-local `deviceCache.has*` blob: the per-device
9006
- * config is for operator-edited overrides + UI snapshots; runtime probe
9007
- * results belong in runtime-state where the kernel handles persistence,
9008
- * cross-process mirroring, and reactive updates.
9040
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
9041
+ * server-injected caller identity the first `caller: 'required'`
9042
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
9043
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
9044
+ * windows, and the optional label/identity/plate matchers. User rules,
9045
+ * private zones, per-recipient fan-out and the wider condition table are
9046
+ * P2+ (see spec §7).
9047
+ *
9048
+ * All schemas here are the single source of truth — `NcRule` etc. are
9049
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
9050
+ * schema/interface drift is explicitly not repeated).
9009
9051
  */
9010
- var FeatureProbeStatusSchema = object({
9052
+ /**
9053
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
9054
+ * The value maps 1:1 onto the evaluated record kind:
9055
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
9056
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
9057
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
9058
+ * change of a LINKED device, one row per linked camera)
9059
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
9060
+ * delivery / pick-up)
9061
+ *
9062
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
9063
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
9064
+ * this one field keeps the schema additive — a rule still declares exactly
9065
+ * one trigger.
9066
+ */
9067
+ var NcDeliverySchema = _enum([
9068
+ "immediate",
9069
+ "track-end",
9070
+ "device-event",
9071
+ "package-event"
9072
+ ]);
9073
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
9074
+ var NcScheduleSchema = object({
9075
+ windows: array(object({
9076
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
9077
+ days: array(number().int().min(0).max(6)).min(1),
9078
+ startMinute: number().int().min(0).max(1439),
9079
+ endMinute: number().int().min(0).max(1439)
9080
+ })).min(1),
9081
+ /** IANA timezone; default = hub host timezone. */
9082
+ timezone: string().optional(),
9083
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
9084
+ invert: boolean().optional()
9085
+ });
9086
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
9087
+ var NcPlateMatcherSchema = object({
9088
+ values: array(string().min(1)).min(1),
9089
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
9090
+ maxDistance: number().int().min(0).max(3).default(1)
9091
+ });
9092
+ /**
9093
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
9094
+ * occupancy edge for a device — optionally narrowed to a single admin
9095
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
9096
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
9097
+ * - `became-free` — count crossed ≥ `count` → below it
9098
+ * - `>=` / `<=` — count is at/over or at/under `count`
9099
+ * `sustainSeconds` requires the condition hold continuously that long
9100
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
9101
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
9102
+ * the condition never matches. Confirmed edge-state survives addon restarts
9103
+ * (declared SQLite collection, reseeded on boot).
9104
+ */
9105
+ var NcOccupancyConditionSchema = object({
9106
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
9107
+ zoneId: string().optional(),
9108
+ /** Object class to count; absent = any class. */
9109
+ className: string().optional(),
9110
+ op: _enum([
9111
+ "became-occupied",
9112
+ "became-free",
9113
+ ">=",
9114
+ "<="
9115
+ ]).default("became-occupied"),
9116
+ count: number().int().min(0).default(1),
9117
+ sustainSeconds: number().int().min(0).max(3600).default(15)
9118
+ });
9119
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
9120
+ var NcZoneConditionSchema = object({
9121
+ ids: array(string().min(1)).min(1),
9122
+ /** Quantifier over `ids` — at least one / every one visited. */
9123
+ match: _enum(["any", "all"]).default("any")
9124
+ });
9125
+ /**
9126
+ * The P1 condition set — a flat AND of groups; absent group = pass;
9127
+ * membership lists are OR within the list (spec §2.3).
9128
+ */
9129
+ var NcConditionsSchema = object({
9130
+ /** Device scope — absent = all devices. */
9131
+ devices: array(number()).optional(),
9132
+ /** Detector class names (any overlap with the record's class set). */
9133
+ classes: array(string().min(1)).optional(),
9134
+ /** Veto classes — any overlap fails the rule. */
9135
+ classesExclude: array(string().min(1)).optional(),
9136
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
9137
+ minConfidence: number().min(0).max(1).optional(),
9138
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
9139
+ zones: NcZoneConditionSchema.optional(),
9140
+ /** Veto zones — any hit fails the rule. */
9141
+ zonesExclude: array(string().min(1)).optional(),
9011
9142
  /**
9012
- * Driver-specific flag bag. Each driver picks its own key names — the
9013
- * cap deliberately does NOT enforce a closed enum here. Reolink keys:
9014
- * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,
9015
- * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:
9016
- * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.
9143
+ * Exact (case-insensitive) match on the record's collapsed `label`
9144
+ * (identity name / plate text / subclass).
9017
9145
  */
9018
- flags: record(string(), unknown()),
9146
+ labelEquals: array(string().min(1)).optional(),
9019
9147
  /**
9020
- * Coarse driver-classification lets cross-process consumers tell apart
9021
- * cameras / battery-cams / NVRs without re-running the probe. `null`
9022
- * before the first probe completes.
9148
+ * Identity matcher. P1 boundary: matched against the record's collapsed
9149
+ * `label` (the identity display name propagated by the face pipeline) —
9150
+ * identity-ID matching rides in P2 when identity ids reach the record.
9023
9151
  */
9024
- deviceType: string().nullable(),
9025
- /** Camera/firmware model string. `null` when the firmware doesn't expose it. */
9026
- model: string().nullable(),
9027
- /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */
9028
- channelCount: number().nullable(),
9152
+ identities: array(string().min(1)).optional(),
9153
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
9154
+ plates: NcPlateMatcherSchema.optional(),
9029
9155
  /**
9030
- * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe
9031
- * completes drivers' `getAccessoryChildren()` should treat zero as
9032
- * "probe not done yet, return empty" so accessories aren't spawned
9033
- * before the firmware is queried.
9156
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
9157
+ * Same P1 boundary: matched against the record's collapsed `label` (the
9158
+ * identity display name). A record with NO label passes (nothing to
9159
+ * exclude), unlike the include variant which fails on an absent label.
9034
9160
  */
9035
- lastProbedAt: number(),
9161
+ identitiesExclude: array(string().min(1)).optional(),
9036
9162
  /**
9037
- * Framework convention: every runtime-state slice carries this for the
9038
- * createRuntimeStateBridge stale-check helper. We keep it in sync with
9039
- * `lastProbedAt` on every write.
9040
- */
9163
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
9164
+ * TRACK-END only: importance is scored at track close, so it does not exist
9165
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
9166
+ * close the value is threaded via the close-time info (the `Track` clone is
9167
+ * captured before the DB row is updated, so it would otherwise read stale).
9168
+ * Fails when the record carries no importance (never guess quality — the
9169
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
9170
+ */
9171
+ minImportance: number().min(0).max(1).optional(),
9172
+ /**
9173
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
9174
+ * TRACK-END only: an `immediate` / object-event subject has no closed
9175
+ * lifespan, so a dwell condition never matches immediate delivery
9176
+ * (documented choice — the object-event record carries no `firstSeen`,
9177
+ * so dwell cannot be computed from what the subject actually carries).
9178
+ */
9179
+ minDwellSeconds: number().min(0).optional(),
9180
+ /**
9181
+ * Detection provenance filter. `any` (default / absent) matches every
9182
+ * source; otherwise the subject's source must equal it. Legacy records
9183
+ * with no stamped source are treated as `pipeline`. The union spans both
9184
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
9185
+ * tracks carry `sensor`.
9186
+ */
9187
+ source: _enum([
9188
+ "pipeline",
9189
+ "onboard",
9190
+ "sensor",
9191
+ "any"
9192
+ ]).optional(),
9193
+ /**
9194
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
9195
+ * detector `minConfidence` (that gates the object-detection score; this
9196
+ * gates the recognition/OCR match score). Fails when the subject carries
9197
+ * no label-match confidence (never guess). TRACK-END only: the confidence
9198
+ * lives on the recognition result and reaches the subject at track close.
9199
+ *
9200
+ * What it measures precisely (plumbed at track close — the closer threads
9201
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
9202
+ * `importance`): the BEST recognition match confidence observed for the
9203
+ * label the track carries at close — for a face, the peak cosine similarity
9204
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
9205
+ * for a plate, the peak OCR read score of the best-held plate
9206
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
9207
+ * one track the higher of the two is used. A track that ended with no
9208
+ * confident identity/plate match carries no value, so the condition fails
9209
+ * closed for it (an un-recognized subject).
9210
+ */
9211
+ minLabelConfidence: number().min(0).max(1).optional(),
9212
+ /**
9213
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
9214
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
9215
+ * against the token carried on the device-event subject (extracted from the
9216
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
9217
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
9218
+ * eventType, so gate those with {@link sensorKinds} instead.
9219
+ */
9220
+ eventTypeTokens: array(string().min(1)).optional(),
9221
+ /**
9222
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
9223
+ * `contact`, `button`, `device-event`) — matched against the persisted
9224
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
9225
+ */
9226
+ sensorKinds: array(string().min(1)).optional(),
9227
+ /**
9228
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
9229
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
9230
+ * when the subject's phase does not match (a subject always carries a phase
9231
+ * on the package-event trigger).
9232
+ */
9233
+ packagePhase: _enum([
9234
+ "delivered",
9235
+ "picked-up",
9236
+ "both"
9237
+ ]).optional(),
9238
+ /**
9239
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
9240
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
9241
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
9242
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
9243
+ */
9244
+ customZones: array(MaskPolygonShapeSchema).optional(),
9245
+ /**
9246
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
9247
+ * (optionally zone/class-scoped) occupancy count crosses the configured
9248
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
9249
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
9250
+ */
9251
+ occupancy: NcOccupancyConditionSchema.optional()
9252
+ });
9253
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
9254
+ var NcRuleTargetSchema = object({
9255
+ /** `notification-output` Target id. */
9256
+ targetId: string().min(1),
9257
+ /**
9258
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
9259
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
9260
+ * degrade engine drops what the backend can't render.
9261
+ */
9262
+ params: record(string(), unknown()).optional()
9263
+ });
9264
+ /**
9265
+ * Media attachment policy (P1 still-image subset).
9266
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
9267
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
9268
+ * matched on identities attaches the subject's `faceCrop`, one matched on
9269
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
9270
+ * (or when the specific crop is missing) degrades to `best`, then
9271
+ * `keyFrame`, then no attachment — never delaying the send. The matched
9272
+ * condition summary is frozen on the outbox row at enqueue (like the rule
9273
+ * name), so the choice never drifts from the record that fired it.
9274
+ * - `keyFrame` — the clean scene frame (no subject box).
9275
+ * - `none` — no attachment.
9276
+ */
9277
+ var NcMediaPolicySchema = object({ attach: _enum([
9278
+ "best",
9279
+ "best-matching",
9280
+ "keyFrame",
9281
+ "none"
9282
+ ]).default("best") });
9283
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
9284
+ var NcThrottleSchema = object({
9285
+ cooldownSec: number().int().min(0).max(86400).default(60),
9286
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
9287
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
9288
+ });
9289
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
9290
+ var NcRuleInputSchema = object({
9291
+ name: string().min(1).max(200),
9292
+ enabled: boolean().default(true),
9293
+ delivery: NcDeliverySchema,
9294
+ conditions: NcConditionsSchema.default({}),
9295
+ schedule: NcScheduleSchema.optional(),
9296
+ targets: array(NcRuleTargetSchema).min(1),
9297
+ media: NcMediaPolicySchema.default({ attach: "best" }),
9298
+ throttle: NcThrottleSchema.default({
9299
+ cooldownSec: 60,
9300
+ scope: "rule-device"
9301
+ }),
9302
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
9303
+ template: object({
9304
+ title: string().max(500).optional(),
9305
+ body: string().max(2e3).optional()
9306
+ }).optional(),
9307
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
9308
+ priority: number().int().min(1).max(5).default(3),
9309
+ /**
9310
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
9311
+ * behaviour, visible to all, read-only in the viewer). Present = personal
9312
+ * rule owned by this userId. Server-stamped; never trusted from a client.
9313
+ */
9314
+ ownerUserId: string().optional()
9315
+ });
9316
+ /**
9317
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
9318
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
9319
+ * NOT a client-authored input field (it lives on the persisted rule, not the
9320
+ * input), so it is added here explicitly to let the store's per-target opt-out
9321
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
9322
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
9323
+ * `updateRule` patch.
9324
+ */
9325
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
9326
+ /** A persisted rule. */
9327
+ var NcRuleSchema = NcRuleInputSchema.extend({
9328
+ id: string(),
9329
+ /** userId of the admin who created the rule (server-stamped caller). */
9330
+ createdBy: string(),
9331
+ createdAt: number(),
9332
+ updatedAt: number(),
9333
+ /**
9334
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
9335
+ * send time. Only a target's OWNER may add/remove its id (server-checked
9336
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
9337
+ */
9338
+ disabledTargetIds: array(string()).default([])
9339
+ });
9340
+ var NcTestResultSchema = object({
9341
+ recordId: string(),
9342
+ recordKind: _enum([
9343
+ "object-event",
9344
+ "track",
9345
+ "device-event",
9346
+ "package-event"
9347
+ ]),
9348
+ deviceId: number(),
9349
+ timestamp: number(),
9350
+ wouldFire: boolean(),
9351
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
9352
+ failedCondition: string().optional(),
9353
+ className: string().optional(),
9354
+ label: string().optional()
9355
+ });
9356
+ var NcConditionDescriptorSchema = object({
9357
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
9358
+ id: string(),
9359
+ group: _enum([
9360
+ "scope",
9361
+ "class",
9362
+ "zones",
9363
+ "quality",
9364
+ "label",
9365
+ "schedule",
9366
+ "device",
9367
+ "package",
9368
+ "occupancy"
9369
+ ]),
9370
+ label: string(),
9371
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
9372
+ valueType: _enum([
9373
+ "deviceIdList",
9374
+ "stringList",
9375
+ "number01",
9376
+ "number",
9377
+ "sourceSelect",
9378
+ "zoneSelection",
9379
+ "zoneIdList",
9380
+ "schedule",
9381
+ "plateMatcher",
9382
+ "packagePhase",
9383
+ "polygonDraw",
9384
+ "occupancy"
9385
+ ]),
9386
+ operator: _enum([
9387
+ "in",
9388
+ "notIn",
9389
+ "anyOf",
9390
+ "allOf",
9391
+ "gte",
9392
+ "fuzzyIn",
9393
+ "withinSchedule"
9394
+ ]),
9395
+ /** Which delivery kinds the condition applies to. */
9396
+ appliesTo: array(NcDeliverySchema),
9397
+ phase: string(),
9398
+ description: string().optional()
9399
+ });
9400
+ /**
9401
+ * The delivery lifecycle status of a history row — a straight read of the
9402
+ * durable outbox row's own status (single source of truth):
9403
+ * - `pending` — enqueued, in-flight or retrying with backoff
9404
+ * - `sent` — delivered (terminal)
9405
+ * - `dead` — dead-lettered after exhausting retries / a permanent
9406
+ * backend rejection / a deleted target (terminal; carries
9407
+ * the failure `error`)
9408
+ *
9409
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
9410
+ * user dimension (quiet hours / snooze) and are additive when they land.
9411
+ */
9412
+ var NcHistoryStatusSchema = _enum([
9413
+ "pending",
9414
+ "sent",
9415
+ "dead"
9416
+ ]);
9417
+ /** The evaluated record kind a history row descends from (one per trigger). */
9418
+ var NcHistoryRecordKindSchema = _enum([
9419
+ "object-event",
9420
+ "track-end",
9421
+ "device-event",
9422
+ "package-event"
9423
+ ]);
9424
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
9425
+ var NcHistorySubjectSchema = object({
9426
+ className: string(),
9427
+ label: string().optional(),
9428
+ confidence: number().optional(),
9429
+ zones: array(string()),
9430
+ timestamp: number()
9431
+ });
9432
+ /**
9433
+ * One delivery-history row. This is a read-only VIEW over the durable
9434
+ * outbox row (single source of truth — the same row the drain loop drives;
9435
+ * NO second write path, so history can never drift from delivery state).
9436
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
9437
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
9438
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
9439
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
9440
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
9441
+ * P1 (admin scope only).
9442
+ */
9443
+ var NcHistoryEntrySchema = object({
9444
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
9445
+ id: string(),
9446
+ ruleId: string(),
9447
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
9448
+ ruleName: string(),
9449
+ /** The rule urgency/trigger that produced this delivery. */
9450
+ delivery: NcDeliverySchema,
9451
+ targetId: string(),
9452
+ deviceId: number(),
9453
+ recordKind: NcHistoryRecordKindSchema,
9454
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
9455
+ recordId: string(),
9456
+ /** Present for track-scoped deliveries (object-event / track-end). */
9457
+ trackId: string().optional(),
9458
+ status: NcHistoryStatusSchema,
9459
+ /** Delivery attempts made so far. */
9460
+ attempts: number().int(),
9461
+ /** Fire time (outbox enqueue). */
9462
+ createdAt: number(),
9463
+ /** Last transition time (terminal for sent / dead). */
9464
+ updatedAt: number(),
9465
+ /** Failure detail — present on a `dead` row. */
9466
+ error: string().optional(),
9467
+ subject: NcHistorySubjectSchema
9468
+ });
9469
+ /**
9470
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
9471
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
9472
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
9473
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
9474
+ */
9475
+ var NcHistoryFilterSchema = object({
9476
+ ruleId: string().optional(),
9477
+ deviceId: number().optional(),
9478
+ status: NcHistoryStatusSchema.optional(),
9479
+ since: number().optional(),
9480
+ until: number().optional(),
9481
+ limit: number().int().min(1).max(500).default(100)
9482
+ });
9483
+ method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), method(object({ ruleId: string() }), object({ rule: NcRuleSchema.nullable() }), { auth: "admin" }), method(object({ rule: NcRuleInputSchema }), object({ rule: NcRuleSchema }), {
9484
+ kind: "mutation",
9485
+ auth: "admin",
9486
+ caller: "required"
9487
+ }), method(object({
9488
+ ruleId: string(),
9489
+ patch: NcRulePatchSchema
9490
+ }), object({ rule: NcRuleSchema }), {
9491
+ kind: "mutation",
9492
+ auth: "admin",
9493
+ caller: "required"
9494
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
9495
+ kind: "mutation",
9496
+ auth: "admin"
9497
+ }), method(object({
9498
+ ruleId: string(),
9499
+ enabled: boolean()
9500
+ }), object({ success: literal(true) }), {
9501
+ kind: "mutation",
9502
+ auth: "admin"
9503
+ }), method(object({
9504
+ rule: NcRuleInputSchema,
9505
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
9506
+ }), object({ results: array(NcTestResultSchema) }), {
9507
+ kind: "mutation",
9508
+ auth: "admin"
9509
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
9510
+ /**
9511
+ * TimelapseRule — the STANDALONE scheduled timelapse producer's rule model.
9512
+ *
9513
+ * Spec: `docs/superpowers/specs/2026-07-24-nc-occupancy-timelapse-design.md`
9514
+ * §3.2/§3.3.
9515
+ *
9516
+ * Deliberately NOT a capability definition and NOT an `NcRule`:
9517
+ * - Every `NcDelivery` member is a *persisted-pipeline-record* trigger. A
9518
+ * timelapse fires on a SCHEDULE WINDOW BOUNDARY, evaluates no pipeline
9519
+ * record, and produces a video it assembled itself — so it rides no
9520
+ * delivery-enum member (the enum is frozen) and no cap method. This file is
9521
+ * a plain typed schema; it does NOT go through `npm run codegen`.
9522
+ * - It shares only the delivery leg (`notification-output.send`) and the
9523
+ * persistence/ownership patterns with the Notification Center, reusing
9524
+ * {@link NcScheduleSchema} (weekly windows, midnight-crossing, invertible)
9525
+ * and {@link NcRuleTargetSchema} (target ref + passthrough params).
9526
+ *
9527
+ * Ownership is SERVER-DERIVED. `ownerUserId` / `createdBy` / `createdAt` /
9528
+ * `updatedAt` / `id` / `lastGeneratedAt` live on the PERSISTED rule only —
9529
+ * {@link TimelapseRuleInputSchema} and {@link TimelapseRulePatchSchema} do not
9530
+ * carry them, so a forged client payload can never claim or re-own a rule
9531
+ * (Zod strips unknown keys). The store stamps them from the resolved caller.
9532
+ */
9533
+ /** `{{var}}` templating over camera/rule/time — same vocabulary as `NcRule`. */
9534
+ var TimelapseTemplateSchema = object({
9535
+ title: string().max(500).optional(),
9536
+ body: string().max(2e3).optional()
9537
+ });
9538
+ var NameField = string().min(1).max(200);
9539
+ var DeviceIdsField = array(number()).min(1);
9540
+ var CadenceSecField = number().int().min(2).max(3600);
9541
+ var FramerateField = number().int().min(1).max(60);
9542
+ var TargetsField = array(NcRuleTargetSchema).min(1);
9543
+ var PriorityField = number().int().min(1).max(5);
9544
+ /**
9545
+ * Client-supplied timelapse-rule fields. The server stamps id / createdBy /
9546
+ * createdAt / updatedAt / ownerUserId / lastGeneratedAt — none of them appear
9547
+ * here (see the ownership note above).
9548
+ */
9549
+ var TimelapseRuleInputSchema = object({
9550
+ name: NameField,
9551
+ enabled: boolean().default(true),
9552
+ /** Cameras sampled by this rule — one scratch dir + one artifact per device. */
9553
+ deviceIds: DeviceIdsField,
9554
+ /**
9555
+ * Activation window(s). REQUIRED (unlike `NcRule`, where an absent schedule
9556
+ * means "always active"): a timelapse is defined by its window boundaries —
9557
+ * open clears the scratch, close assembles and delivers.
9558
+ */
9559
+ schedule: NcScheduleSchema,
9560
+ /** Force-snapshot cadence inside the window, seconds (predecessor parity). */
9561
+ cadenceSec: CadenceSecField.default(15),
9562
+ /** Output frames per second of the assembled mp4 (predecessor parity). */
9563
+ framerate: FramerateField.default(10),
9564
+ /** `notification-output` targets the finished video/thumbnail is sent to. */
9565
+ targets: TargetsField,
9566
+ template: TimelapseTemplateSchema.optional(),
9567
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
9568
+ priority: PriorityField.default(3)
9569
+ });
9570
+ object({
9571
+ name: NameField.optional(),
9572
+ enabled: boolean().optional(),
9573
+ deviceIds: DeviceIdsField.optional(),
9574
+ schedule: NcScheduleSchema.optional(),
9575
+ cadenceSec: CadenceSecField.optional(),
9576
+ framerate: FramerateField.optional(),
9577
+ targets: TargetsField.optional(),
9578
+ template: TimelapseTemplateSchema.nullable().optional(),
9579
+ priority: PriorityField.optional()
9580
+ });
9581
+ TimelapseRuleInputSchema.extend({
9582
+ id: string(),
9583
+ /**
9584
+ * Ownership/visibility key. Absent = admin/global rule (visible to all).
9585
+ * Present = personal rule owned by this userId. Server-stamped from the
9586
+ * resolved caller; never trusted from a client payload.
9587
+ */
9588
+ ownerUserId: string().optional(),
9589
+ /**
9590
+ * Epoch-ms of the last successful generation — the 1-hour re-generation
9591
+ * guard's durable state (predecessor parity). Absent = never generated.
9592
+ */
9593
+ lastGeneratedAt: number().optional(),
9594
+ /** userId of the caller who created the rule (server-stamped). */
9595
+ createdBy: string(),
9596
+ createdAt: number(),
9597
+ updatedAt: number()
9598
+ });
9599
+ /**
9600
+ * Generic device-level status snapshot. Auto-registered by `BaseDevice`
9601
+ * for every device, regardless of provider — the kernel needs a uniform
9602
+ * cap-keyed slice for the basic device flags every consumer expects to
9603
+ * read across processes (the `online` flag in particular). Driver-specific
9604
+ * caps (`battery`, `doorbell`, …) carry their domain-specific state on
9605
+ * their own slices.
9606
+ *
9607
+ * Pattern is identical to `battery`: schema-bearing `runtimeState`,
9608
+ * empty `methods`, single change event. Reads land at
9609
+ * `runtimeState.getCapState('device-status')`; writes at
9610
+ * `runtimeState.setCapState('device-status', …)`. Cross-process
9611
+ * consumers reach the same data via the `device-state` cap router
9612
+ * (`getCapSlice({deviceId, capName: 'device-status'})`).
9613
+ */
9614
+ var DeviceStatusSchema = object({
9615
+ /**
9616
+ * Device-level liveness. Drivers flip via `markOnline(boolean)` on
9617
+ * `BaseDevice`. Provider semantics vary — RTSP aggregates broker
9618
+ * stream-health, Reolink reads firmware push events, ONVIF tracks
9619
+ * ping responses. This cap intentionally does NOT prescribe which
9620
+ * signal drives the flag.
9621
+ */
9622
+ online: boolean(),
9623
+ /** Ms epoch of the last `online` transition. Lets consumers tell
9624
+ * apart "just came online" from "still online". */
9625
+ lastChangedAt: number()
9626
+ });
9627
+ object({
9628
+ deviceId: number(),
9629
+ status: DeviceStatusSchema
9630
+ });
9631
+ /**
9632
+ * Per-device feature/identity probe slice. Holds the runtime-resolved
9633
+ * truth about what a device CAN do — which the kernel uses to:
9634
+ * 1. Reconcile accessory children (hub-children spawn siren/floodlight/PIR
9635
+ * based on what the firmware actually advertises).
9636
+ * 2. Compute the public `features: DeviceFeature[]` array surfaced via
9637
+ * `device-manager.listAll`.
9638
+ * 3. Decide which optional caps (PTZ, intercom, doorbell, battery, …)
9639
+ * to register on the device's capability surface.
9640
+ *
9641
+ * Auto-registered by `BaseDevice` for every device. Drivers populate the
9642
+ * slice from `onProbe()` (kernel calls it once after register, before
9643
+ * accessory reconciliation). Consumers read via:
9644
+ * `runtimeState.getCapState<FeatureProbeStatus>('feature-probe')`
9645
+ *
9646
+ * `flags` is an open record so each driver carries its own keys without
9647
+ * a centralized schema bottleneck — Reolink writes `hasPtz/hasIntercom`,
9648
+ * Hikvision writes `hasSupplementalLight/hasAlarmIo`, etc.
9649
+ *
9650
+ * Replaces the older driver-local `deviceCache.has*` blob: the per-device
9651
+ * config is for operator-edited overrides + UI snapshots; runtime probe
9652
+ * results belong in runtime-state where the kernel handles persistence,
9653
+ * cross-process mirroring, and reactive updates.
9654
+ */
9655
+ var FeatureProbeStatusSchema = object({
9656
+ /**
9657
+ * Driver-specific flag bag. Each driver picks its own key names — the
9658
+ * cap deliberately does NOT enforce a closed enum here. Reolink keys:
9659
+ * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,
9660
+ * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:
9661
+ * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.
9662
+ */
9663
+ flags: record(string(), unknown()),
9664
+ /**
9665
+ * Coarse driver-classification — lets cross-process consumers tell apart
9666
+ * cameras / battery-cams / NVRs without re-running the probe. `null`
9667
+ * before the first probe completes.
9668
+ */
9669
+ deviceType: string().nullable(),
9670
+ /** Camera/firmware model string. `null` when the firmware doesn't expose it. */
9671
+ model: string().nullable(),
9672
+ /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */
9673
+ channelCount: number().nullable(),
9674
+ /**
9675
+ * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe
9676
+ * completes — drivers' `getAccessoryChildren()` should treat zero as
9677
+ * "probe not done yet, return empty" so accessories aren't spawned
9678
+ * before the firmware is queried.
9679
+ */
9680
+ lastProbedAt: number(),
9681
+ /**
9682
+ * Framework convention: every runtime-state slice carries this for the
9683
+ * createRuntimeStateBridge stale-check helper. We keep it in sync with
9684
+ * `lastProbedAt` on every write.
9685
+ */
9041
9686
  lastFetchedAt: number()
9042
9687
  });
9043
9688
  object({
@@ -11893,103 +12538,42 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
11893
12538
  parent: DetailParentSchema,
11894
12539
  steps: array(string()).optional()
11895
12540
  }), object({ details: array(DetailResultSchema) }).nullable(), { kind: "mutation" });
11896
- object({
11897
- detected: boolean(),
11898
- /** Ms epoch of the last detected-true observation. Null if never detected. */
11899
- lastDetectedAt: number().nullable(),
11900
- /**
11901
- * Ms after which `detected` auto-reverts to false if no fresh push
11902
- * arrives. Null means the provider leaves detected state until a
11903
- * native "clear" event.
11904
- */
11905
- autoClearAfterMs: number().nullable()
11906
- });
11907
- object({
11908
- deviceId: number(),
11909
- detected: boolean(),
11910
- timestamp: number(),
11911
- source: MotionSourceEnum,
11912
- regions: array(MotionRegionSchema).readonly().optional()
11913
- });
11914
- DeviceType.Camera, DeviceType.Sensor, method(object({ deviceId: number() }), boolean());
11915
- object({
11916
- enabled: boolean(),
11917
- /** Ms epoch of the last operator-driven change. */
11918
- lastChangedAt: number()
11919
- }).extend({
11920
- /** Ms epoch of the last successful camera fetch (0 = never). */
11921
- lastFetchedAt: number() });
11922
- DeviceType.Light, DeviceType.Siren, DeviceType.Switch, method(object({
11923
- deviceId: number().int().nonnegative(),
11924
- enabled: boolean()
11925
- }), _void(), {
11926
- kind: "mutation",
11927
- auth: "admin"
11928
- }), object({
11929
- deviceId: number(),
11930
- enabled: boolean(),
11931
- lastChangedAt: number()
11932
- });
11933
- /**
11934
- * Shared geometry vocabulary for on-frame shape caps — privacy-mask,
11935
- * motion-zones, and the detection zones/lines editor all speak this one
11936
- * language so a single drawing-plane editor and the providers stay
11937
- * decoupled from each cap's storage.
11938
- *
11939
- * All coordinates are normalized 0..1 of the camera frame (top-left
11940
- * origin). Each cap composes the SUBSET of shape kinds it supports and
11941
- * advertises it via `supportedShapes` in its `getOptions`.
11942
- */
11943
- /** A normalized 0..1 point (top-left origin). */
11944
- var MaskPointSchema = object({
11945
- x: number(),
11946
- y: number()
11947
- });
11948
- /** Axis-aligned rectangle (normalized 0..1). */
11949
- var MaskRectShapeSchema = object({
11950
- kind: literal("rect"),
11951
- x: number(),
11952
- y: number(),
11953
- width: number(),
11954
- height: number()
11955
- });
11956
- /** Free polygon — an ordered list of normalized vertices (≥3). */
11957
- var MaskPolygonShapeSchema = object({
11958
- kind: literal("polygon"),
11959
- points: array(MaskPointSchema)
11960
- });
11961
- /** Boolean cell grid — row-major, length === gridWidth*gridHeight. */
11962
- var MaskGridShapeSchema = object({
11963
- kind: literal("grid"),
11964
- gridWidth: number(),
11965
- gridHeight: number(),
11966
- cells: array(boolean())
11967
- });
11968
- discriminatedUnion("kind", [
11969
- MaskRectShapeSchema,
11970
- MaskPolygonShapeSchema,
11971
- MaskGridShapeSchema,
11972
- object({
11973
- kind: literal("line"),
11974
- points: array(MaskPointSchema)
11975
- })
11976
- ]);
11977
- /** Every shape-kind discriminant, for `supportedShapes` advertisement. */
11978
- var MaskShapeKindSchema = _enum([
11979
- "rect",
11980
- "polygon",
11981
- "grid",
11982
- "line"
11983
- ]);
11984
- /** Polygon vertex bounds when a cap supports 'polygon' (e.g. Hikvision {min:4,max:4}). */
11985
- var MaskPolygonVerticesSchema = object({
11986
- min: number(),
11987
- max: number()
12541
+ object({
12542
+ detected: boolean(),
12543
+ /** Ms epoch of the last detected-true observation. Null if never detected. */
12544
+ lastDetectedAt: number().nullable(),
12545
+ /**
12546
+ * Ms after which `detected` auto-reverts to false if no fresh push
12547
+ * arrives. Null means the provider leaves detected state until a
12548
+ * native "clear" event.
12549
+ */
12550
+ autoClearAfterMs: number().nullable()
11988
12551
  });
11989
- /** Grid dimensions when a cap supports 'grid'. */
11990
- var MaskGridDimsSchema = object({
11991
- width: number(),
11992
- height: number()
12552
+ object({
12553
+ deviceId: number(),
12554
+ detected: boolean(),
12555
+ timestamp: number(),
12556
+ source: MotionSourceEnum,
12557
+ regions: array(MotionRegionSchema).readonly().optional()
12558
+ });
12559
+ DeviceType.Camera, DeviceType.Sensor, method(object({ deviceId: number() }), boolean());
12560
+ object({
12561
+ enabled: boolean(),
12562
+ /** Ms epoch of the last operator-driven change. */
12563
+ lastChangedAt: number()
12564
+ }).extend({
12565
+ /** Ms epoch of the last successful camera fetch (0 = never). */
12566
+ lastFetchedAt: number() });
12567
+ DeviceType.Light, DeviceType.Siren, DeviceType.Switch, method(object({
12568
+ deviceId: number().int().nonnegative(),
12569
+ enabled: boolean()
12570
+ }), _void(), {
12571
+ kind: "mutation",
12572
+ auth: "admin"
12573
+ }), object({
12574
+ deviceId: number(),
12575
+ enabled: boolean(),
12576
+ lastChangedAt: number()
11993
12577
  });
11994
12578
  /**
11995
12579
  * Motion-zones share the same MaskShape vocabulary as privacy-mask — the
@@ -13860,6 +14444,55 @@ method(object({
13860
14444
  password: string()
13861
14445
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
13862
14446
  /**
14447
+ * A live terminal session hosted by the provider addon. Output and input do
14448
+ * NOT flow through the capability — they use the addon data plane
14449
+ * (`GET /addon/terminal/<id>/out` SSE, `POST /addon/terminal/<id>/in`) because
14450
+ * terminal output must be ordered and lossless. The event bus is telemetry and
14451
+ * may drop chunks ([D8]), and a dropped chunk desynchronises the vt parser
14452
+ * permanently until a full repaint. The capability owns only lifecycle.
14453
+ */
14454
+ var TerminalSessionInfoSchema = object({
14455
+ /** Opaque session id minted by the provider on `openSession`. */
14456
+ sessionId: string(),
14457
+ /** The pre-declared profile this session runs (never a free-form command). */
14458
+ profileId: string(),
14459
+ /** Human-readable profile label for the UI session list. */
14460
+ label: string(),
14461
+ cols: number().int().positive(),
14462
+ rows: number().int().positive(),
14463
+ /** ms-epoch the session's pty was spawned. */
14464
+ startedAt: number()
14465
+ });
14466
+ /**
14467
+ * A profile the operator may open — a pre-declared, allowlisted program
14468
+ * (`monitor` → `btm`). The capability accepts only these ids; a free-form
14469
+ * command string would be remote code execution as the server's user, so it is
14470
+ * deliberately not part of the contract.
14471
+ */
14472
+ var TerminalProfileInfoSchema = object({
14473
+ profileId: string(),
14474
+ label: string(),
14475
+ description: string().optional()
14476
+ });
14477
+ method(_void(), array(TerminalProfileInfoSchema).readonly(), { auth: "admin" }), method(_void(), array(TerminalSessionInfoSchema).readonly(), { auth: "admin" }), method(object({
14478
+ profileId: string(),
14479
+ cols: number().int().positive(),
14480
+ rows: number().int().positive()
14481
+ }), TerminalSessionInfoSchema, {
14482
+ kind: "mutation",
14483
+ auth: "admin"
14484
+ }), method(object({
14485
+ sessionId: string(),
14486
+ cols: number().int().positive(),
14487
+ rows: number().int().positive()
14488
+ }), _void(), {
14489
+ kind: "mutation",
14490
+ auth: "admin"
14491
+ }), method(object({ sessionId: string() }), _void(), {
14492
+ kind: "mutation",
14493
+ auth: "admin"
14494
+ });
14495
+ /**
13863
14496
  * Orchestrator-side destination metadata. The orchestrator computes
13864
14497
  * `id = <addonId>:<subId>` from its provider lookup so consumers
13865
14498
  * (admin UI, restore flow) see one canonical key.
@@ -13960,11 +14593,53 @@ var LocationStatSchema = object({
13960
14593
  fileCount: number(),
13961
14594
  present: boolean()
13962
14595
  });
14596
+ /**
14597
+ * A backup schedule — the N:M "entry" that binds one cron cadence to a
14598
+ * SET of destination locations. Supersedes the per-location cron on
14599
+ * `BackupDestinationPolicy`: an operator creates a schedule, picks the
14600
+ * `backups` locations it should write to, and the orchestrator fans a
14601
+ * single archive out to all of them when the cron fires.
14602
+ *
14603
+ * `retentionCount` is per-schedule (D-decision 2026-07-28): every
14604
+ * location targeted by this schedule keeps this many archives from
14605
+ * this schedule's runs.
14606
+ *
14607
+ * `dataSources` optionally narrows which top-level state locations
14608
+ * (db, addons, tls, …) are archived; omitted = the orchestrator's
14609
+ * default full set.
14610
+ */
14611
+ var BackupScheduleSchema = object({
14612
+ /** Stable id. Generated by the orchestrator on first upsert if absent. */
14613
+ id: string(),
14614
+ /** Operator-facing display name. */
14615
+ label: string(),
14616
+ /** 5-field POSIX cron. Empty = disabled cadence (kept for editing). */
14617
+ cron: string(),
14618
+ /** Master on/off toggle for the whole schedule. */
14619
+ enabled: boolean(),
14620
+ /** `backups`-location ids this schedule writes to (fan-out set). */
14621
+ locationIds: array(string()).readonly(),
14622
+ /** Archives kept per targeted location for this schedule. */
14623
+ retentionCount: number().int().min(1).max(1e3),
14624
+ /** Optional subset of source locations to include; omitted = all. */
14625
+ dataSources: array(string()).readonly().optional(),
14626
+ /** ms-epoch of last successful run. */
14627
+ lastRunAt: number().optional(),
14628
+ /** ms-epoch of next computed firing (read-only, filled on list). */
14629
+ nextRunAt: number().optional()
14630
+ });
13963
14631
  method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }), method(object({
13964
14632
  /** Subset of registered `backup-destination` addon ids to write to. */
13965
14633
  destinations: array(string()).optional(),
13966
14634
  locations: array(string()).optional(),
13967
- label: string().optional()
14635
+ label: string().optional(),
14636
+ /**
14637
+ * Per-run retention override applied to every targeted
14638
+ * destination. Used by schedule-driven runs (per-entry
14639
+ * retention). Omitted = each destination's own policy
14640
+ * retention (manual runs).
14641
+ */
14642
+ retentionCount: number().int().min(1).max(1e3).optional()
13968
14643
  }).optional(), array(BackupEntrySchema).readonly(), {
13969
14644
  kind: "mutation",
13970
14645
  auth: "admin"
@@ -14013,7 +14688,21 @@ method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }
14013
14688
  ok: boolean(),
14014
14689
  error: string().optional(),
14015
14690
  nextRuns: array(number()).readonly()
14016
- }));
14691
+ })), method(_void(), array(BackupScheduleSchema).readonly(), { auth: "admin" }), method(object({
14692
+ id: string().optional(),
14693
+ label: string(),
14694
+ cron: string(),
14695
+ enabled: boolean(),
14696
+ locationIds: array(string()).readonly(),
14697
+ retentionCount: number().int().min(1).max(1e3),
14698
+ dataSources: array(string()).readonly().optional()
14699
+ }), BackupScheduleSchema, {
14700
+ kind: "mutation",
14701
+ auth: "admin"
14702
+ }), method(object({ id: string() }), _void(), {
14703
+ kind: "mutation",
14704
+ auth: "admin"
14705
+ });
14017
14706
  /**
14018
14707
  * `broker` — unified pub/sub broker registry, system-scoped collection.
14019
14708
  *
@@ -15054,1596 +15743,1108 @@ method(object({
15054
15743
  active: boolean()
15055
15744
  }), _void(), {
15056
15745
  kind: "mutation",
15057
- auth: "admin"
15058
- }), method(object({ capName: string() }), array(string())), method(object({ deviceType: string() }), array(object({
15059
- capName: string(),
15060
- wrappers: array(string())
15061
- }))), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), object({
15062
- settings: SettingsSchemaWithValuesSchema.nullable(),
15063
- live: SettingsSchemaWithValuesSchema.nullable()
15064
- })), method(object({
15065
- deviceId: number().int().nonnegative(),
15066
- action: string().min(1),
15067
- input: unknown()
15068
- }), unknown(), { kind: "mutation" }), method(object({
15069
- deviceId: number(),
15070
- writerCapName: string(),
15071
- writerAddonId: string(),
15072
- key: string(),
15073
- value: unknown()
15074
- }), object({ success: literal(true) }), {
15075
- kind: "mutation",
15076
- auth: "admin"
15077
- }), method(object({
15078
- deviceId: number(),
15079
- changes: array(object({
15080
- writerCapName: string(),
15081
- writerAddonId: string(),
15082
- key: string(),
15083
- value: unknown()
15084
- }))
15085
- }), object({
15086
- success: literal(true),
15087
- failures: array(object({
15088
- writerCapName: string(),
15089
- writerAddonId: string(),
15090
- error: string()
15091
- }))
15092
- }), {
15093
- kind: "mutation",
15094
- auth: "admin"
15095
- }), method(object({ addonId: string() }), array(DiscoveryCandidateSchema), {
15096
- kind: "mutation",
15097
- auth: "admin"
15098
- }), method(object({
15099
- addonId: string(),
15100
- candidate: DiscoveryCandidateSchema,
15101
- /** Owning integration id, stamped onto the new device's meta by the
15102
- * device-manager forwarder so `removeByIntegration` can cascade it.
15103
- * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
15104
- integrationId: string().optional()
15105
- }), DeviceSummarySchema, {
15106
- kind: "mutation",
15107
- auth: "admin"
15108
- }), method(object({
15109
- addonId: string(),
15110
- type: _enum(DeviceType)
15111
- }), unknown().nullable()), method(object({
15112
- addonId: string(),
15113
- type: _enum(DeviceType),
15114
- config: record(string(), unknown()),
15115
- /** Owning integration id, stamped onto the new device's meta by the
15116
- * device-manager forwarder so `removeByIntegration` can cascade it.
15117
- * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
15118
- integrationId: string().optional()
15119
- }), DeviceSummarySchema, {
15120
- kind: "mutation",
15121
- auth: "admin"
15122
- }), method(object({
15123
- addonId: string(),
15124
- type: _enum(DeviceType),
15125
- key: string(),
15126
- value: unknown(),
15127
- formValues: record(string(), unknown()).optional()
15128
- }), FieldProbeResultSchema, {
15129
- kind: "mutation",
15130
- auth: "admin"
15131
- }), method(object({
15132
- addonId: string(),
15133
- integrationId: string()
15134
- }), object({ filters: array(AdoptionFilterSchema) }), { auth: "admin" }), method(ListCandidatesInputSchema.extend({ addonId: string() }), ListCandidatesOutputSchema, { auth: "admin" }), method(object({
15135
- addonId: string(),
15136
- integrationId: string()
15137
- }), AdoptionStatusSchema, {
15138
- kind: "mutation",
15139
- auth: "admin"
15140
- }), method(AdoptInputSchema.extend({ addonId: string() }), AdoptResultSchema, {
15141
- kind: "mutation",
15142
- auth: "admin"
15143
- }), method(ReleaseInputSchema.extend({ addonId: string() }), _void(), {
15144
- kind: "mutation",
15145
- auth: "admin"
15146
- }), method(ResyncInputSchema, ResyncResultSchema, {
15147
- kind: "mutation",
15148
- auth: "admin"
15149
- }), method(object({}), object({ providers: array(object({
15150
- addonId: string(),
15151
- label: string()
15152
- })).readonly() }), { auth: "admin" }), method(object({}), object({ groups: array(object({
15153
- addonId: string(),
15154
- label: string(),
15155
- candidates: array(DiscoveryCandidateSchema).readonly(),
15156
- error: string().nullable()
15157
- })).readonly() }), {
15158
- kind: "mutation",
15159
- auth: "admin"
15160
- }), method(object({
15161
- addonId: string(),
15162
- params: record(string(), unknown()).optional()
15163
- }), object({ candidates: array(DiscoveryCandidateSchema).readonly() }), {
15164
- kind: "mutation",
15165
- auth: "admin"
15166
- }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
15167
- deviceId: number(),
15168
- key: string(),
15169
- value: unknown()
15170
- }), FieldProbeResultSchema, {
15171
- kind: "mutation",
15172
- auth: "admin"
15173
- }), method(object({
15174
- deviceId: number(),
15175
- caps: array(string()).readonly().optional()
15176
- }), record(string(), unknown().nullable()));
15177
- method(object({ deviceId: number() }), record(string(), record(string(), unknown()))), method(object({
15178
- deviceId: number(),
15179
- capName: string()
15180
- }), record(string(), unknown()).nullable()), method(object({}), record(string(), record(string(), record(string(), unknown())))), method(object({
15181
- deviceId: number(),
15182
- capName: string(),
15183
- slice: record(string(), unknown())
15184
- }), _void(), { kind: "mutation" }), object({
15185
- deviceId: number(),
15186
- capName: string(),
15187
- slice: record(string(), unknown())
15188
- });
15189
- /**
15190
- * Embedding output. `embedding` is wire-encoded as `number[]` so the
15191
- * Zod-validated tRPC surface round-trips cleanly; consumers that need a
15192
- * `Float32Array` can wrap it on the way out (in-process, no marshalling
15193
- * is involved). `inferenceMs` mirrors the runtime field used by the
15194
- * post-analysis enrichment-engine.
15195
- */
15196
- var EmbeddingResultSchema = object({
15197
- embedding: array(number()),
15198
- inferenceMs: number()
15199
- });
15200
- var EmbeddingInfoSchema = object({
15201
- modelId: string(),
15202
- embeddingDim: number(),
15203
- ready: boolean()
15204
- });
15205
- method(object({
15206
- crop: _instanceof(Uint8Array),
15207
- width: number(),
15208
- height: number()
15209
- }), EmbeddingResultSchema), method(object({ text: string() }), EmbeddingResultSchema), method(_void(), EmbeddingInfoSchema);
15210
- /**
15211
- * filesystem-browse — per-node capability for browsing the node's local
15212
- * filesystem, sandboxed to operator-configured allowed roots. Used by the
15213
- * admin "Add filesystem location" flow to pick a node + path. `mode:'per-node'`
15214
- * (one provider per node); the hub calls it with `{nodeId}` so the codegen
15215
- * routes to that exact node (default `nodeIdMode:'routing'`).
15216
- */
15217
- var DirEntrySchema = object({
15218
- name: string(),
15219
- path: string()
15220
- });
15221
- var BrowseResultSchema = object({
15222
- path: string(),
15223
- entries: array(DirEntrySchema).readonly(),
15224
- freeBytes: number(),
15225
- totalBytes: number()
15226
- });
15227
- method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({ path: string() }), BrowseResultSchema, { auth: "admin" }), method(object({ path: string() }), object({ path: string() }), {
15746
+ auth: "admin"
15747
+ }), method(object({ capName: string() }), array(string())), method(object({ deviceType: string() }), array(object({
15748
+ capName: string(),
15749
+ wrappers: array(string())
15750
+ }))), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), object({
15751
+ settings: SettingsSchemaWithValuesSchema.nullable(),
15752
+ live: SettingsSchemaWithValuesSchema.nullable()
15753
+ })), method(object({
15754
+ deviceId: number().int().nonnegative(),
15755
+ action: string().min(1),
15756
+ input: unknown()
15757
+ }), unknown(), { kind: "mutation" }), method(object({
15758
+ deviceId: number(),
15759
+ writerCapName: string(),
15760
+ writerAddonId: string(),
15761
+ key: string(),
15762
+ value: unknown()
15763
+ }), object({ success: literal(true) }), {
15228
15764
  kind: "mutation",
15229
15765
  auth: "admin"
15230
- });
15231
- /**
15232
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15233
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15234
- * caps stay wire-compatible without a circular cap→cap import.
15235
- *
15236
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
15237
- * every transport tier structurally, and failed calls still write usage rows.
15238
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15239
- */
15240
- var LlmUsageSchema = object({
15241
- inputTokens: number(),
15242
- outputTokens: number()
15243
- });
15244
- var LlmErrorCodeSchema = _enum([
15245
- "timeout",
15246
- "rate-limited",
15247
- "auth",
15248
- "refusal",
15249
- "bad-request",
15250
- "unavailable",
15251
- "no-profile",
15252
- "budget-exceeded",
15253
- "adapter-error"
15254
- ]);
15255
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15256
- ok: literal(true),
15257
- text: string(),
15258
- model: string(),
15259
- usage: LlmUsageSchema,
15260
- truncated: boolean(),
15261
- latencyMs: number()
15766
+ }), method(object({
15767
+ deviceId: number(),
15768
+ changes: array(object({
15769
+ writerCapName: string(),
15770
+ writerAddonId: string(),
15771
+ key: string(),
15772
+ value: unknown()
15773
+ }))
15262
15774
  }), object({
15263
- ok: literal(false),
15264
- code: LlmErrorCodeSchema,
15265
- message: string(),
15266
- retryAfterMs: number().optional()
15267
- })]);
15268
- /**
15269
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15270
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15271
- * notification-output.cap.ts:27-31 precedents).
15272
- */
15273
- var LlmImageSchema = object({
15274
- bytes: _instanceof(Uint8Array),
15275
- mimeType: string()
15276
- });
15277
- var LlmGenerateBaseInputSchema = object({
15278
- /** Collection routing (the notification-output posture). */
15279
- addonId: string().optional(),
15280
- /** Explicit profile; else the resolution chain (spec §3). */
15281
- profileId: string().optional(),
15282
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15283
- consumer: string(),
15284
- system: string().optional(),
15285
- /** v1: single-turn. `messages[]` is a v2 additive field. */
15286
- prompt: string(),
15287
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15288
- jsonSchema: record(string(), unknown()).optional(),
15289
- /** Per-call override of the profile default. */
15290
- maxTokens: number().int().positive().optional(),
15291
- temperature: number().optional()
15292
- });
15293
- /**
15294
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15295
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15296
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15297
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15298
- * this only through the `llm` cap's methods.
15299
- *
15300
- * One running llama-server child per node in v1 (models are RAM-heavy).
15301
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15302
- * watchdog — operator decision #3).
15303
- */
15304
- var ManagedModelRefSchema = discriminatedUnion("kind", [
15305
- object({
15306
- kind: literal("catalog"),
15307
- catalogId: string()
15308
- }),
15309
- object({
15310
- kind: literal("url"),
15311
- url: string(),
15312
- sha256: string().optional()
15313
- }),
15314
- object({
15315
- kind: literal("path"),
15316
- path: string()
15317
- })
15318
- ]);
15319
- var ManagedRuntimeConfigSchema = object({
15320
- /** WHERE the runtime lives — hub or any agent. */
15321
- nodeId: string(),
15322
- /** Closed for v1; 'ollama' is a v2 candidate. */
15323
- engine: _enum(["llama-cpp"]),
15324
- model: ManagedModelRefSchema,
15325
- contextSize: number().int().default(4096),
15326
- /** 0 = CPU-only. */
15327
- gpuLayers: number().int().default(0),
15328
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15329
- threads: number().int().optional(),
15330
- /** Concurrent slots. */
15331
- parallel: number().int().default(1),
15332
- /** Else lazy: first generate boots it. */
15333
- autoStart: boolean().default(false),
15334
- /** 0 = never; frees RAM after quiet periods. */
15335
- idleStopMinutes: number().int().default(30)
15336
- });
15337
- var LlmRuntimeStatusSchema = object({
15338
- /** Status is ALWAYS node-qualified. */
15339
- nodeId: string(),
15340
- state: _enum([
15341
- "stopped",
15342
- "downloading",
15343
- "starting",
15344
- "ready",
15345
- "crashed",
15346
- "failed"
15347
- ]),
15348
- pid: number().optional(),
15349
- port: number().optional(),
15350
- modelPath: string().optional(),
15351
- modelId: string().optional(),
15352
- downloadProgress: number().min(0).max(1).optional(),
15353
- lastError: string().optional(),
15354
- crashesInWindow: number(),
15355
- /** Child RSS (sampled best-effort). */
15356
- memoryBytes: number().optional(),
15357
- vramBytes: number().optional()
15358
- });
15359
- var LlmNodeModelSchema = object({
15360
- file: string(),
15361
- sizeBytes: number(),
15362
- catalogId: string().optional(),
15363
- installedAt: number().optional()
15364
- });
15365
- var LlmRuntimeDiskUsageSchema = object({
15366
- nodeId: string(),
15367
- modelsBytes: number(),
15368
- freeBytes: number().optional()
15369
- });
15370
- method(LlmGenerateBaseInputSchema.extend({
15371
- images: array(LlmImageSchema).optional(),
15372
- runtime: ManagedRuntimeConfigSchema,
15373
- /** The managed profile's timeout, threaded by the hub provider. */
15374
- timeoutMs: number().int().positive().optional()
15375
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15775
+ success: literal(true),
15776
+ failures: array(object({
15777
+ writerCapName: string(),
15778
+ writerAddonId: string(),
15779
+ error: string()
15780
+ }))
15781
+ }), {
15376
15782
  kind: "mutation",
15377
15783
  auth: "admin"
15378
- }), method(object({}), _void(), {
15784
+ }), method(object({ addonId: string() }), array(DiscoveryCandidateSchema), {
15379
15785
  kind: "mutation",
15380
15786
  auth: "admin"
15381
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15787
+ }), method(object({
15788
+ addonId: string(),
15789
+ candidate: DiscoveryCandidateSchema,
15790
+ /** Owning integration id, stamped onto the new device's meta by the
15791
+ * device-manager forwarder so `removeByIntegration` can cascade it.
15792
+ * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
15793
+ integrationId: string().optional()
15794
+ }), DeviceSummarySchema, {
15382
15795
  kind: "mutation",
15383
15796
  auth: "admin"
15384
- }), method(object({ file: string() }), _void(), {
15797
+ }), method(object({
15798
+ addonId: string(),
15799
+ type: _enum(DeviceType)
15800
+ }), unknown().nullable()), method(object({
15801
+ addonId: string(),
15802
+ type: _enum(DeviceType),
15803
+ config: record(string(), unknown()),
15804
+ /** Owning integration id, stamped onto the new device's meta by the
15805
+ * device-manager forwarder so `removeByIntegration` can cascade it.
15806
+ * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
15807
+ integrationId: string().optional()
15808
+ }), DeviceSummarySchema, {
15385
15809
  kind: "mutation",
15386
15810
  auth: "admin"
15387
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15388
- /**
15389
- * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15390
- * methods concat-fan across providers; single-row methods route to ONE
15391
- * provider by the `addonId` in the call input (the notification-output
15392
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15393
- * (hub-placed); the cap stays open for future providers.
15394
- *
15395
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15396
- * `apiKey` is a password field — providers REDACT it on read and merge on
15397
- * write; a stored key NEVER round-trips to a client.
15398
- */
15399
- var LlmProfileKindSchema = _enum([
15400
- "openai-compatible",
15401
- "openai",
15402
- "anthropic",
15403
- "google",
15404
- "managed-local"
15405
- ]);
15406
- var LlmProfileSchema = object({
15407
- id: string(),
15408
- name: string(),
15409
- kind: LlmProfileKindSchema,
15410
- /** Stamped by the provider — keeps the fanned catalog routable. */
15811
+ }), method(object({
15411
15812
  addonId: string(),
15412
- enabled: boolean(),
15413
- /** Vendor model id, or the managed runtime's loaded model. */
15414
- model: string(),
15415
- /** Required for openai-compatible; override for cloud kinds. */
15416
- baseUrl: string().optional(),
15417
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
15418
- apiKey: string().optional(),
15419
- supportsVision: boolean(),
15420
- temperature: number().min(0).max(2).optional(),
15421
- maxTokens: number().int().positive().optional(),
15422
- timeoutMs: number().int().positive().default(6e4),
15423
- extraHeaders: record(string(), string()).optional(),
15424
- /** kind === 'managed-local' only (spec §4). */
15425
- runtime: ManagedRuntimeConfigSchema.optional()
15426
- });
15427
- /** ConfigUISchema tree passed through untyped on the wire (the
15428
- * notification-output `ConfigSchemaPassthrough` precedent at
15429
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15430
- var ConfigSchemaPassthrough$1 = unknown();
15431
- var LlmProfileKindDescriptorSchema = object({
15432
- kind: LlmProfileKindSchema,
15433
- label: string(),
15434
- icon: string(),
15435
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
15813
+ type: _enum(DeviceType),
15814
+ key: string(),
15815
+ value: unknown(),
15816
+ formValues: record(string(), unknown()).optional()
15817
+ }), FieldProbeResultSchema, {
15818
+ kind: "mutation",
15819
+ auth: "admin"
15820
+ }), method(object({
15436
15821
  addonId: string(),
15437
- configSchema: ConfigSchemaPassthrough$1
15438
- });
15439
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15440
- var LlmDefaultSchema = object({
15441
- selector: LlmDefaultSelectorSchema,
15442
- profileId: string()
15443
- });
15444
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
15445
- var LlmUsageRollupSchema = object({
15446
- day: string(),
15447
- consumer: string(),
15448
- profileId: string(),
15449
- calls: number(),
15450
- okCalls: number(),
15451
- errorCalls: number(),
15452
- inputTokens: number(),
15453
- outputTokens: number(),
15454
- avgLatencyMs: number()
15455
- });
15456
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15457
- var ManagedModelCatalogEntrySchema = object({
15458
- id: string(),
15459
- label: string(),
15460
- family: string(),
15461
- purpose: _enum(["text", "vision"]),
15462
- url: string(),
15463
- sha256: string(),
15464
- sizeBytes: number(),
15465
- quantization: string(),
15466
- /** Load-time guidance shown in the picker. */
15467
- minRamBytes: number(),
15468
- contextSizeDefault: number().int(),
15469
- /** Vision models: companion projector file. */
15470
- mmprojUrl: string().optional()
15471
- });
15472
- var LlmRuntimeNodeSchema = object({
15473
- nodeId: string(),
15474
- reachable: boolean(),
15475
- status: LlmRuntimeStatusSchema.optional(),
15476
- disk: LlmRuntimeDiskUsageSchema.optional(),
15477
- error: string().optional()
15478
- });
15479
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
15480
- var ProfileRefInputSchema = object({
15822
+ integrationId: string()
15823
+ }), object({ filters: array(AdoptionFilterSchema) }), { auth: "admin" }), method(ListCandidatesInputSchema.extend({ addonId: string() }), ListCandidatesOutputSchema, { auth: "admin" }), method(object({
15481
15824
  addonId: string(),
15482
- profileId: string()
15483
- });
15484
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
15825
+ integrationId: string()
15826
+ }), AdoptionStatusSchema, {
15485
15827
  kind: "mutation",
15486
15828
  auth: "admin"
15487
- }), method(ProfileRefInputSchema, _void(), {
15829
+ }), method(AdoptInputSchema.extend({ addonId: string() }), AdoptResultSchema, {
15488
15830
  kind: "mutation",
15489
15831
  auth: "admin"
15490
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
15832
+ }), method(ReleaseInputSchema.extend({ addonId: string() }), _void(), {
15491
15833
  kind: "mutation",
15492
15834
  auth: "admin"
15493
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
15494
- selector: LlmDefaultSelectorSchema,
15495
- profileId: string().nullable()
15496
- }), _void(), {
15835
+ }), method(ResyncInputSchema, ResyncResultSchema, {
15497
15836
  kind: "mutation",
15498
15837
  auth: "admin"
15499
- }), method(object({
15500
- since: number().optional(),
15501
- until: number().optional(),
15502
- consumer: string().optional(),
15503
- profileId: string().optional()
15504
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
15505
- nodeId: string(),
15506
- model: ManagedModelRefSchema
15507
- }), _void(), {
15838
+ }), method(object({}), object({ providers: array(object({
15839
+ addonId: string(),
15840
+ label: string()
15841
+ })).readonly() }), { auth: "admin" }), method(object({}), object({ groups: array(object({
15842
+ addonId: string(),
15843
+ label: string(),
15844
+ candidates: array(DiscoveryCandidateSchema).readonly(),
15845
+ error: string().nullable()
15846
+ })).readonly() }), {
15508
15847
  kind: "mutation",
15509
15848
  auth: "admin"
15510
15849
  }), method(object({
15511
- nodeId: string(),
15512
- file: string()
15513
- }), _void(), {
15850
+ addonId: string(),
15851
+ params: record(string(), unknown()).optional()
15852
+ }), object({ candidates: array(DiscoveryCandidateSchema).readonly() }), {
15514
15853
  kind: "mutation",
15515
15854
  auth: "admin"
15516
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
15855
+ }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
15856
+ deviceId: number(),
15857
+ key: string(),
15858
+ value: unknown()
15859
+ }), FieldProbeResultSchema, {
15517
15860
  kind: "mutation",
15518
15861
  auth: "admin"
15519
- }), method(ProfileRefInputSchema, _void(), {
15862
+ }), method(object({
15863
+ deviceId: number(),
15864
+ caps: array(string()).readonly().optional()
15865
+ }), record(string(), unknown().nullable()));
15866
+ method(object({ deviceId: number() }), record(string(), record(string(), unknown()))), method(object({
15867
+ deviceId: number(),
15868
+ capName: string()
15869
+ }), record(string(), unknown()).nullable()), method(object({}), record(string(), record(string(), record(string(), unknown())))), method(object({
15870
+ deviceId: number(),
15871
+ capName: string(),
15872
+ slice: record(string(), unknown())
15873
+ }), _void(), { kind: "mutation" }), object({
15874
+ deviceId: number(),
15875
+ capName: string(),
15876
+ slice: record(string(), unknown())
15877
+ });
15878
+ /**
15879
+ * Embedding output. `embedding` is wire-encoded as `number[]` so the
15880
+ * Zod-validated tRPC surface round-trips cleanly; consumers that need a
15881
+ * `Float32Array` can wrap it on the way out (in-process, no marshalling
15882
+ * is involved). `inferenceMs` mirrors the runtime field used by the
15883
+ * post-analysis enrichment-engine.
15884
+ */
15885
+ var EmbeddingResultSchema = object({
15886
+ embedding: array(number()),
15887
+ inferenceMs: number()
15888
+ });
15889
+ var EmbeddingInfoSchema = object({
15890
+ modelId: string(),
15891
+ embeddingDim: number(),
15892
+ ready: boolean()
15893
+ });
15894
+ method(object({
15895
+ crop: _instanceof(Uint8Array),
15896
+ width: number(),
15897
+ height: number()
15898
+ }), EmbeddingResultSchema), method(object({ text: string() }), EmbeddingResultSchema), method(_void(), EmbeddingInfoSchema);
15899
+ /**
15900
+ * filesystem-browse — per-node capability for browsing the node's local
15901
+ * filesystem, sandboxed to operator-configured allowed roots. Used by the
15902
+ * admin "Add filesystem location" flow to pick a node + path. `mode:'per-node'`
15903
+ * (one provider per node); the hub calls it with `{nodeId}` so the codegen
15904
+ * routes to that exact node (default `nodeIdMode:'routing'`).
15905
+ */
15906
+ var DirEntrySchema = object({
15907
+ name: string(),
15908
+ path: string()
15909
+ });
15910
+ var BrowseResultSchema = object({
15911
+ path: string(),
15912
+ entries: array(DirEntrySchema).readonly(),
15913
+ freeBytes: number(),
15914
+ totalBytes: number()
15915
+ });
15916
+ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({ path: string() }), BrowseResultSchema, { auth: "admin" }), method(object({ path: string() }), object({ path: string() }), {
15520
15917
  kind: "mutation",
15521
15918
  auth: "admin"
15522
15919
  });
15523
- var LogLevelSchema = _enum([
15524
- "debug",
15525
- "info",
15526
- "warn",
15527
- "error"
15920
+ /**
15921
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15922
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15923
+ * caps stay wire-compatible without a circular cap→cap import.
15924
+ *
15925
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
15926
+ * every transport tier structurally, and failed calls still write usage rows.
15927
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15928
+ */
15929
+ var LlmUsageSchema = object({
15930
+ inputTokens: number(),
15931
+ outputTokens: number()
15932
+ });
15933
+ var LlmErrorCodeSchema = _enum([
15934
+ "timeout",
15935
+ "rate-limited",
15936
+ "auth",
15937
+ "refusal",
15938
+ "bad-request",
15939
+ "unavailable",
15940
+ "no-profile",
15941
+ "budget-exceeded",
15942
+ "adapter-error"
15528
15943
  ]);
15529
- var LogEntrySchema = object({
15530
- timestamp: date(),
15531
- level: LogLevelSchema,
15532
- scope: array(string()),
15944
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15945
+ ok: literal(true),
15946
+ text: string(),
15947
+ model: string(),
15948
+ usage: LlmUsageSchema,
15949
+ truncated: boolean(),
15950
+ latencyMs: number()
15951
+ }), object({
15952
+ ok: literal(false),
15953
+ code: LlmErrorCodeSchema,
15533
15954
  message: string(),
15534
- meta: record(string(), unknown()).optional(),
15535
- tags: record(string(), string()).optional()
15536
- });
15537
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15538
- scope: array(string()).optional(),
15539
- level: LogLevelSchema.optional(),
15540
- since: date().optional(),
15541
- until: date().optional(),
15542
- limit: number().optional(),
15543
- tags: record(string(), string()).optional()
15544
- }), array(LogEntrySchema).readonly());
15955
+ retryAfterMs: number().optional()
15956
+ })]);
15545
15957
  /**
15546
- * `login-method` collection cap through which auth addons contribute
15547
- * their pre-auth login surfaces to the login page. This is the SINGLE,
15548
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
15549
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
15550
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
15551
- * procedure aggregates them for the unauthenticated login page.
15552
- *
15553
- * A contribution is a discriminated union on `kind`:
15554
- *
15555
- * - `redirect` a declarative button. The login page renders a generic
15556
- * button that navigates to `startUrl` (an addon-owned HTTP route).
15557
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
15558
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
15559
- * login page needs NO change.
15560
- *
15561
- * - `widget` — a Module-Federation widget the login page mounts (via
15562
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
15563
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
15564
- * mechanism kept for future use; no shipped addon uses it on the login
15565
- * page (the passkey ceremony below runs natively in the shell instead).
15566
- *
15567
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
15568
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
15569
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
15570
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
15571
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
15572
- * fetching any remote code pre-auth. Contribution stays unconditional
15573
- * enrollment state is never leaked pre-auth; visibility is a shell
15574
- * decision.
15575
- *
15576
- * Every contribution carries a `stage`:
15577
- * - `primary` — shown on the first credentials screen (OIDC /
15578
- * magic-link buttons; a future usernameless passkey).
15579
- * - `second-factor` — shown AFTER the password leg, gated on the
15580
- * returned `factors` (passkey-as-2FA today).
15958
+ * `Uint8Array` is the sanctioned binary convention superjson + the UDS
15959
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15960
+ * notification-output.cap.ts:27-31 precedents).
15961
+ */
15962
+ var LlmImageSchema = object({
15963
+ bytes: _instanceof(Uint8Array),
15964
+ mimeType: string()
15965
+ });
15966
+ var LlmGenerateBaseInputSchema = object({
15967
+ /** Collection routing (the notification-output posture). */
15968
+ addonId: string().optional(),
15969
+ /** Explicit profile; else the resolution chain (spec §3). */
15970
+ profileId: string().optional(),
15971
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15972
+ consumer: string(),
15973
+ system: string().optional(),
15974
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
15975
+ prompt: string(),
15976
+ /** Structured output adapter-mapped (response_format / forced tool / responseSchema). */
15977
+ jsonSchema: record(string(), unknown()).optional(),
15978
+ /** Per-call override of the profile default. */
15979
+ maxTokens: number().int().positive().optional(),
15980
+ temperature: number().optional()
15981
+ });
15982
+ /**
15983
+ * `llm-runtime` node-side managed llama.cpp executor (spec §4). Registered
15984
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15985
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` normal
15986
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15987
+ * this only through the `llm` cap's methods.
15581
15988
  *
15582
- * `mount: skip` the cap is read server-side by the core auth router
15583
- * (`registry.getCollection('login-method')`), never mounted as its own
15584
- * tRPC router.
15989
+ * One running llama-server child per node in v1 (models are RAM-heavy).
15990
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15991
+ * watchdog — operator decision #3).
15585
15992
  */
15586
- /** When a login method renders in the two-phase login flow. */
15587
- var LoginStageEnum = _enum(["primary", "second-factor"]);
15588
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
15589
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
15993
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
15590
15994
  object({
15591
- kind: literal("redirect"),
15592
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
15593
- id: string(),
15594
- /** Operator-facing button label. */
15595
- label: string(),
15596
- /** lucide-react icon name. */
15597
- icon: string().optional(),
15598
- /** Addon-owned HTTP route the button navigates to (GET). */
15599
- startUrl: string(),
15600
- stage: LoginStageEnum
15995
+ kind: literal("catalog"),
15996
+ catalogId: string()
15601
15997
  }),
15602
15998
  object({
15603
- kind: literal("widget"),
15604
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
15605
- id: string(),
15606
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
15607
- addonId: string(),
15608
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
15609
- bundle: string(),
15610
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
15611
- remote: WidgetRemoteSchema,
15612
- stage: LoginStageEnum
15999
+ kind: literal("url"),
16000
+ url: string(),
16001
+ sha256: string().optional()
15613
16002
  }),
15614
16003
  object({
15615
- kind: literal("passkey"),
15616
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
15617
- id: string(),
15618
- /** Operator-facing button label. */
15619
- label: string(),
15620
- stage: LoginStageEnum,
15621
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
15622
- rpId: string(),
15623
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
15624
- origin: string().nullable()
16004
+ kind: literal("path"),
16005
+ path: string()
15625
16006
  })
15626
16007
  ]);
15627
- method(_void(), array(LoginMethodContributionSchema).readonly());
15628
- var CpuBreakdownSchema = object({
15629
- total: number(),
15630
- user: number(),
15631
- system: number(),
15632
- irq: number(),
15633
- nice: number(),
15634
- loadAvg: tuple([
15635
- number(),
15636
- number(),
15637
- number()
15638
- ]),
15639
- cores: number()
15640
- });
15641
- var MemoryInfoSchema = object({
15642
- percent: number(),
15643
- totalBytes: number(),
15644
- usedBytes: number(),
15645
- availableBytes: number(),
15646
- swapUsedBytes: number(),
15647
- swapTotalBytes: number()
15648
- });
15649
- var DiskIoSnapshotSchema = object({
15650
- readBytes: number(),
15651
- writeBytes: number(),
15652
- readOps: number(),
15653
- writeOps: number(),
15654
- timestampMs: number()
15655
- });
15656
- var NetworkIoSnapshotSchema = object({
15657
- rxBytes: number(),
15658
- txBytes: number(),
15659
- rxPackets: number(),
15660
- txPackets: number(),
15661
- rxErrors: number(),
15662
- txErrors: number(),
15663
- timestampMs: number()
15664
- });
15665
- var MetricsGpuInfoSchema = object({
15666
- utilization: number(),
15667
- model: string(),
15668
- memoryUsedBytes: number(),
15669
- memoryTotalBytes: number(),
15670
- temperature: number().nullable()
15671
- });
15672
- var ProcessResourceInfoSchema = object({
15673
- openFds: number(),
15674
- threadCount: number(),
15675
- activeHandles: number(),
15676
- activeRequests: number()
15677
- });
15678
- var PressureAvgsSchema = object({
15679
- avg10: number(),
15680
- avg60: number(),
15681
- avg300: number()
15682
- });
15683
- var PressureInfoSchema = object({
15684
- some: PressureAvgsSchema,
15685
- full: PressureAvgsSchema.nullable()
15686
- });
15687
- var SystemResourceSnapshotSchema = object({
15688
- cpu: CpuBreakdownSchema,
15689
- memory: MemoryInfoSchema,
15690
- gpu: MetricsGpuInfoSchema.nullable(),
15691
- network: NetworkIoSnapshotSchema,
15692
- disk: DiskIoSnapshotSchema,
15693
- pressure: object({
15694
- cpu: PressureInfoSchema.nullable(),
15695
- memory: PressureInfoSchema.nullable(),
15696
- io: PressureInfoSchema.nullable()
15697
- }),
15698
- process: ProcessResourceInfoSchema,
15699
- cpuTemperature: number().nullable(),
15700
- timestampMs: number()
15701
- });
15702
- var DiskSpaceInfoSchema = object({
15703
- path: string(),
15704
- totalBytes: number(),
15705
- usedBytes: number(),
15706
- availableBytes: number(),
15707
- percent: number()
15708
- });
15709
- var PidResourceStatsSchema = object({
15710
- pid: number(),
15711
- cpu: number(),
15712
- memory: number(),
15713
- /**
15714
- * Private (anonymous) resident bytes — the per-process V8 heap + native
15715
- * allocations NOT shared with other processes (Linux RssAnon). This is the
15716
- * "real" per-runner cost; summing it across runners is meaningful, unlike
15717
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
15718
- * Undefined where /proc is unavailable (e.g. macOS).
15719
- */
15720
- privateBytes: number().optional(),
15721
- /**
15722
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15723
- * code shared copy-on-write across runners. Undefined on macOS.
15724
- */
15725
- sharedBytes: number().optional()
16008
+ var ManagedRuntimeConfigSchema = object({
16009
+ /** WHERE the runtime lives — hub or any agent. */
16010
+ nodeId: string(),
16011
+ /** Closed for v1; 'ollama' is a v2 candidate. */
16012
+ engine: _enum(["llama-cpp"]),
16013
+ model: ManagedModelRefSchema,
16014
+ contextSize: number().int().default(4096),
16015
+ /** 0 = CPU-only. */
16016
+ gpuLayers: number().int().default(0),
16017
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
16018
+ threads: number().int().optional(),
16019
+ /** Concurrent slots. */
16020
+ parallel: number().int().default(1),
16021
+ /** Else lazy: first generate boots it. */
16022
+ autoStart: boolean().default(false),
16023
+ /** 0 = never; frees RAM after quiet periods. */
16024
+ idleStopMinutes: number().int().default(30)
15726
16025
  });
15727
- var AddonInstanceSchema = object({
15728
- addonId: string(),
16026
+ var LlmRuntimeStatusSchema = object({
16027
+ /** Status is ALWAYS node-qualified. */
15729
16028
  nodeId: string(),
15730
- role: _enum(["hub", "worker"]),
15731
- pid: number(),
15732
16029
  state: _enum([
15733
- "starting",
15734
- "running",
15735
- "stopping",
15736
16030
  "stopped",
15737
- "crashed"
15738
- ]),
15739
- uptimeSec: number()
15740
- });
15741
- var NodeProcessSchema = object({
15742
- pid: number(),
15743
- ppid: number(),
15744
- pgid: number(),
15745
- classification: _enum([
15746
- "root",
15747
- "managed",
15748
- "system",
15749
- "ghost"
16031
+ "downloading",
16032
+ "starting",
16033
+ "ready",
16034
+ "crashed",
16035
+ "failed"
15750
16036
  ]),
15751
- /** `$process` addon binding when `managed`, else null. */
15752
- addonId: string().nullable(),
15753
- /** Kernel-reported nodeId when the process is a known agent/worker. */
15754
- nodeId: string().nullable(),
15755
- /** Truncated command line. */
15756
- command: string(),
15757
- cpuPercent: number(),
15758
- memoryRssBytes: number(),
15759
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15760
- uptimeSec: number(),
15761
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15762
- orphaned: boolean()
15763
- });
15764
- var KillProcessInputSchema = object({
15765
- pid: number(),
15766
- /** Force = SIGKILL. Default is SIGTERM. */
15767
- force: boolean().optional()
15768
- });
15769
- var KillProcessResultSchema = object({
15770
- success: boolean(),
15771
- reason: string().optional(),
15772
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15773
- });
15774
- var DumpHeapSnapshotInputSchema = object({
15775
- /** The addon whose runner should dump a heap snapshot. */
15776
- addonId: string() });
15777
- var DumpHeapSnapshotResultSchema = object({
15778
- success: boolean(),
15779
- /** Path of the written .heapsnapshot inside the runner's container/host. */
15780
- path: string().optional(),
15781
- /** Process pid that was signalled. */
15782
16037
  pid: number().optional(),
15783
- reason: string().optional()
16038
+ port: number().optional(),
16039
+ modelPath: string().optional(),
16040
+ modelId: string().optional(),
16041
+ downloadProgress: number().min(0).max(1).optional(),
16042
+ lastError: string().optional(),
16043
+ crashesInWindow: number(),
16044
+ /** Child RSS (sampled best-effort). */
16045
+ memoryBytes: number().optional(),
16046
+ vramBytes: number().optional()
15784
16047
  });
15785
- var SystemMetricsSchema = object({
15786
- cpuPercent: number(),
15787
- memoryPercent: number(),
15788
- memoryUsedMB: number(),
15789
- memoryTotalMB: number(),
15790
- diskPercent: number().optional(),
15791
- temperature: number().optional(),
15792
- gpuPercent: number().optional(),
15793
- gpuMemoryPercent: number().optional()
16048
+ var LlmNodeModelSchema = object({
16049
+ file: string(),
16050
+ sizeBytes: number(),
16051
+ catalogId: string().optional(),
16052
+ installedAt: number().optional()
15794
16053
  });
15795
- method(_void(), SystemResourceSnapshotSchema), method(_void(), SystemResourceSnapshotSchema.nullable()), method(_void(), SystemMetricsSchema), method(object({ dirPath: string() }), DiskSpaceInfoSchema), method(_void(), MetricsGpuInfoSchema.nullable()), method(_void(), number().nullable()), method(object({ pids: array(number()) }), array(PidResourceStatsSchema)), method(_void(), array(AddonInstanceSchema).readonly()), method(object({ addonId: string() }), PidResourceStatsSchema.nullable()), method(_void(), array(NodeProcessSchema).readonly()), method(KillProcessInputSchema, KillProcessResultSchema, {
16054
+ var LlmRuntimeDiskUsageSchema = object({
16055
+ nodeId: string(),
16056
+ modelsBytes: number(),
16057
+ freeBytes: number().optional()
16058
+ });
16059
+ method(LlmGenerateBaseInputSchema.extend({
16060
+ images: array(LlmImageSchema).optional(),
16061
+ runtime: ManagedRuntimeConfigSchema,
16062
+ /** The managed profile's timeout, threaded by the hub provider. */
16063
+ timeoutMs: number().int().positive().optional()
16064
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15796
16065
  kind: "mutation",
15797
16066
  auth: "admin"
15798
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
16067
+ }), method(object({}), _void(), {
15799
16068
  kind: "mutation",
15800
16069
  auth: "admin"
15801
- });
15802
- method(object({
15803
- sourceUrl: string(),
15804
- metadata: ModelConvertMetadataSchema,
15805
- targets: array(ConvertTargetSchema).min(1).readonly(),
15806
- calibrationRef: string().optional(),
15807
- sessionId: string().optional()
15808
- }), ConvertResultSchema, {
16070
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15809
16071
  kind: "mutation",
15810
- auth: "admin",
15811
- timeoutMs: 6e5
15812
- });
15813
- method(object({
15814
- nodeId: string(),
15815
- modelId: string(),
15816
- format: _enum(MODEL_FORMATS),
15817
- entry: ModelCatalogEntrySchema
15818
- }), object({
15819
- ok: boolean(),
15820
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
15821
- sha256: string(),
15822
- bytes: number(),
15823
- /** The target node's modelsDir the artifact landed in. */
15824
- path: string()
15825
- }), {
16072
+ auth: "admin"
16073
+ }), method(object({ file: string() }), _void(), {
15826
16074
  kind: "mutation",
15827
16075
  auth: "admin"
15828
- });
15829
- /**
15830
- * `mqtt-broker` — broker-registry cap.
15831
- *
15832
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15833
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15834
- * and (b) the connection details a consumer addon needs to spin up
15835
- * its OWN `mqtt.js` client.
15836
- *
15837
- * Why: pub/sub routing over the system event-bus loses fidelity
15838
- * (callback shape, QoS guarantees, will/retain semantics) and adds
15839
- * refcount bookkeeping that addons would rather own themselves. The
15840
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
15841
- * features anyway — give it the connection config, get out of the way.
15842
- *
15843
- * Consumer flow:
15844
- * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
15845
- * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
15846
- * client.subscribe('zigbee2mqtt/+')
15847
- *
15848
- * Collection mode: multiple brokers (e.g. one local mosquitto + one
15849
- * cloud bridge). The "embedded" entry (when present) is just another
15850
- * broker in the registry — its lifecycle is owned by the addon that
15851
- * spawned it.
15852
- */
15853
- var BrokerKindSchema = _enum(["external", "embedded"]);
16076
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15854
16077
  /**
15855
- * Broker live-probe status.
16078
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
16079
+ * methods concat-fan across providers; single-row methods route to ONE
16080
+ * provider by the `addonId` in the call input (the notification-output
16081
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
16082
+ * (hub-placed); the cap stays open for future providers.
15856
16083
  *
15857
- * - `connected` last probe completed a clean CONNACK
15858
- * - `disconnected` — no probe has run yet (cold cache)
15859
- * - `auth-failed` CONNACK refused with auth error (RC 4 / 5)
15860
- * - `unreachable` — TCP connect timed out / refused
15861
- * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
16084
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
16085
+ * `apiKey` is a password field providers REDACT it on read and merge on
16086
+ * write; a stored key NEVER round-trips to a client.
15862
16087
  */
15863
- var BrokerStatusSchema$1 = _enum([
15864
- "connected",
15865
- "disconnected",
15866
- "auth-failed",
15867
- "unreachable",
15868
- "tls-error"
16088
+ var LlmProfileKindSchema = _enum([
16089
+ "openai-compatible",
16090
+ "openai",
16091
+ "anthropic",
16092
+ "google",
16093
+ "managed-local"
15869
16094
  ]);
15870
- var BrokerInfoSchema = object({
16095
+ var LlmProfileSchema = object({
15871
16096
  id: string(),
15872
16097
  name: string(),
15873
- url: string(),
15874
- kind: BrokerKindSchema,
15875
- status: BrokerStatusSchema$1,
15876
- latencyMs: number().nullable(),
15877
- error: string().optional(),
15878
- /** Embedded brokers only: number of MQTT clients currently connected. */
15879
- connectedClients: number().int().nonnegative().optional(),
15880
- /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
15881
- lastCheckedAt: number().optional()
16098
+ kind: LlmProfileKindSchema,
16099
+ /** Stamped by the provider — keeps the fanned catalog routable. */
16100
+ addonId: string(),
16101
+ enabled: boolean(),
16102
+ /** Vendor model id, or the managed runtime's loaded model. */
16103
+ model: string(),
16104
+ /** Required for openai-compatible; override for cloud kinds. */
16105
+ baseUrl: string().optional(),
16106
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
16107
+ apiKey: string().optional(),
16108
+ supportsVision: boolean(),
16109
+ temperature: number().min(0).max(2).optional(),
16110
+ maxTokens: number().int().positive().optional(),
16111
+ timeoutMs: number().int().positive().default(6e4),
16112
+ extraHeaders: record(string(), string()).optional(),
16113
+ /** kind === 'managed-local' only (spec §4). */
16114
+ runtime: ManagedRuntimeConfigSchema.optional()
15882
16115
  });
15883
- /**
15884
- * Connection details — what a consumer needs to call
15885
- * `mqtt.connect(url, options)`. We split URL + credentials so the
15886
- * consumer can pass them as `mqtt.connect(url, { username, password })`
15887
- * instead of stuffing creds into the URL (which leaks them into logs).
15888
- */
15889
- var BrokerConnectionDetailsSchema = object({
15890
- url: string(),
15891
- username: string().optional(),
15892
- password: string().optional(),
15893
- /**
15894
- * Suggested prefix for `clientId`. Each consumer should suffix this
15895
- * with its own discriminator (addon id, instance id) so reconnects
15896
- * don't kick each other off (MQTT spec: clientId must be unique per
15897
- * broker).
15898
- */
15899
- clientIdPrefix: string().optional()
16116
+ /** ConfigUISchema tree passed through untyped on the wire (the
16117
+ * notification-output `ConfigSchemaPassthrough` precedent at
16118
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
16119
+ var ConfigSchemaPassthrough$1 = unknown();
16120
+ var LlmProfileKindDescriptorSchema = object({
16121
+ kind: LlmProfileKindSchema,
16122
+ label: string(),
16123
+ icon: string(),
16124
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
16125
+ addonId: string(),
16126
+ configSchema: ConfigSchemaPassthrough$1
15900
16127
  });
15901
- var AddBrokerInputSchema = object({
15902
- name: string().min(1),
15903
- url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
15904
- username: string().optional(),
15905
- password: string().optional(),
15906
- clientIdPrefix: string().optional()
16128
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
16129
+ var LlmDefaultSchema = object({
16130
+ selector: LlmDefaultSelectorSchema,
16131
+ profileId: string()
15907
16132
  });
15908
- var AddBrokerResultSchema = object({ id: string() });
15909
- var IdInputSchema = object({ id: string() });
15910
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
15911
- ok: literal(true),
15912
- latencyMs: number()
15913
- }), object({
15914
- ok: literal(false),
15915
- error: string()
15916
- })]);
15917
- var StartEmbeddedInputSchema = object({
15918
- port: number().int().min(1).max(65535).default(1883),
15919
- /** Allow anonymous connect (no username/password). Default: false. */
15920
- allowAnonymous: boolean().default(false),
15921
- /** Optional shared username/password for clients. */
15922
- username: string().optional(),
15923
- password: string().optional()
16133
+ /** Server-side rollup row getUsage never dumps raw call rows (spec §6). */
16134
+ var LlmUsageRollupSchema = object({
16135
+ day: string(),
16136
+ consumer: string(),
16137
+ profileId: string(),
16138
+ calls: number(),
16139
+ okCalls: number(),
16140
+ errorCalls: number(),
16141
+ inputTokens: number(),
16142
+ outputTokens: number(),
16143
+ avgLatencyMs: number()
15924
16144
  });
15925
- var StartEmbeddedResultSchema = object({
16145
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
16146
+ var ManagedModelCatalogEntrySchema = object({
15926
16147
  id: string(),
15927
- url: string()
15928
- });
15929
- var StatusSchema = object({
15930
- brokerCount: number(),
15931
- embeddedRunning: boolean()
15932
- });
15933
- method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnectionDetailsSchema), method(AddBrokerInputSchema, AddBrokerResultSchema, { kind: "mutation" }), method(IdInputSchema, _void(), { kind: "mutation" }), method(IdInputSchema, TestResultSchema$1, { kind: "mutation" }), method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, { kind: "mutation" }), method(IdInputSchema, _void(), { kind: "mutation" }), method(_void(), StatusSchema);
15934
- var NetworkEndpointSchema = object({
16148
+ label: string(),
16149
+ family: string(),
16150
+ purpose: _enum(["text", "vision"]),
15935
16151
  url: string(),
15936
- hostname: string(),
15937
- port: number(),
15938
- protocol: _enum(["http", "https"])
16152
+ sha256: string(),
16153
+ sizeBytes: number(),
16154
+ quantization: string(),
16155
+ /** Load-time guidance shown in the picker. */
16156
+ minRamBytes: number(),
16157
+ contextSizeDefault: number().int(),
16158
+ /** Vision models: companion projector file. */
16159
+ mmprojUrl: string().optional()
15939
16160
  });
15940
- var NetworkAccessStatusSchema = object({
15941
- connected: boolean(),
15942
- endpoint: NetworkEndpointSchema.nullable(),
16161
+ var LlmRuntimeNodeSchema = object({
16162
+ nodeId: string(),
16163
+ reachable: boolean(),
16164
+ status: LlmRuntimeStatusSchema.optional(),
16165
+ disk: LlmRuntimeDiskUsageSchema.optional(),
15943
16166
  error: string().optional()
15944
16167
  });
15945
- /**
15946
- * Optional, richer endpoint shape returned by providers that expose
15947
- * MORE than one ingress concurrently (Tailscale Ingress with mixed
15948
- * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
15949
- * the originating provider config (mode + sourcePort) so the
15950
- * orchestrator UI can label rows distinctly. Providers that expose only
15951
- * one endpoint just omit `listEndpoints` from their provider impl.
15952
- */
15953
- var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
15954
- /**
15955
- * Stable id within the provider — typically `<mode>-<sourcePort>` so
15956
- * the orchestrator can dedupe across `listEndpoints` polls.
15957
- */
15958
- id: string(),
15959
- /** Operator-facing label (mirrors `MeshEndpoint.label`). */
15960
- label: string(),
15961
- /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
15962
- mode: string().optional(),
15963
- /** Originating local port the ingress fronts (informational). */
15964
- sourcePort: number().optional()
16168
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16169
+ var ProfileRefInputSchema = object({
16170
+ addonId: string(),
16171
+ profileId: string()
16172
+ });
16173
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16174
+ kind: "mutation",
16175
+ auth: "admin"
16176
+ }), method(ProfileRefInputSchema, _void(), {
16177
+ kind: "mutation",
16178
+ auth: "admin"
16179
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16180
+ kind: "mutation",
16181
+ auth: "admin"
16182
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
16183
+ selector: LlmDefaultSelectorSchema,
16184
+ profileId: string().nullable()
16185
+ }), _void(), {
16186
+ kind: "mutation",
16187
+ auth: "admin"
16188
+ }), method(object({
16189
+ since: number().optional(),
16190
+ until: number().optional(),
16191
+ consumer: string().optional(),
16192
+ profileId: string().optional()
16193
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
16194
+ nodeId: string(),
16195
+ model: ManagedModelRefSchema
16196
+ }), _void(), {
16197
+ kind: "mutation",
16198
+ auth: "admin"
16199
+ }), method(object({
16200
+ nodeId: string(),
16201
+ file: string()
16202
+ }), _void(), {
16203
+ kind: "mutation",
16204
+ auth: "admin"
16205
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16206
+ kind: "mutation",
16207
+ auth: "admin"
16208
+ }), method(ProfileRefInputSchema, _void(), {
16209
+ kind: "mutation",
16210
+ auth: "admin"
16211
+ });
16212
+ var LogLevelSchema = _enum([
16213
+ "debug",
16214
+ "info",
16215
+ "warn",
16216
+ "error"
16217
+ ]);
16218
+ var LogEntrySchema = object({
16219
+ timestamp: date(),
16220
+ level: LogLevelSchema,
16221
+ scope: array(string()),
16222
+ message: string(),
16223
+ meta: record(string(), unknown()).optional(),
16224
+ tags: record(string(), string()).optional()
15965
16225
  });
15966
- method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
16226
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
16227
+ scope: array(string()).optional(),
16228
+ level: LogLevelSchema.optional(),
16229
+ since: date().optional(),
16230
+ until: date().optional(),
16231
+ limit: number().optional(),
16232
+ tags: record(string(), string()).optional()
16233
+ }), array(LogEntrySchema).readonly());
15967
16234
  /**
15968
- * notification-outputcanonical, capability-gated notification delivery.
16235
+ * `login-method`collection cap through which auth addons contribute
16236
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
16237
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
16238
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
16239
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
16240
+ * procedure aggregates them for the unauthenticated login page.
15969
16241
  *
15970
- * Apprise-derived model (see
15971
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
15972
- * callers emit ONE canonical `Notification`; each provider declares a
15973
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
15974
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
15975
- * message to what the kind supports — callers never special-case a service.
16242
+ * A contribution is a discriminated union on `kind`:
15976
16243
  *
15977
- * DESIGN DECISIONS (locked):
15978
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
15979
- * `setTargetEnabled`), each provider persisting via the `settings-store`
15980
- * cap. Rationale: the admin UI needs one uniform surface across the
15981
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
15982
- * alternative would fork the UI per addon and cannot host the
15983
- * discovery→adopt flow.
15984
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
15985
- * the generated cap-mount auto-`concatCollection`-fans them across every
15986
- * registered provider (notifiers addon + HA addon) so one catalog is
15987
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
15988
- * `addonId` the generated collection router extracts from the call input.
15989
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
15990
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
15991
- * `storage` / `storage-provider` / `recording` caps over the same path. No
15992
- * base64 fallback needed.
16244
+ * - `redirect` a declarative button. The login page renders a generic
16245
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
16246
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
16247
+ * ZERO shell-side JS. A future SSO addon plugs in the same way the
16248
+ * login page needs NO change.
15993
16249
  *
15994
- * TODO (deferred, closed-set change separate decision): add
15995
- * `providerKind: 'notify'` so notification providers surface on the unified
15996
- * admin "Integrations" page.
15997
- */
15998
- /**
15999
- * Zentik-derived typed-media enum — the superset across every kind. Each
16000
- * adapter picks what it supports and the degrade engine filters the rest.
16001
- */
16002
- var AttachmentMediaTypeSchema = _enum([
16003
- "image",
16004
- "video",
16005
- "gif",
16006
- "audio",
16007
- "icon"
16008
- ]);
16009
- /**
16010
- * A single attachment. Exactly one of `url` (remote source, most adapters
16011
- * prefer this) or `bytes` (inline source; required for Pushover-style
16012
- * bytes-only kinds) MUST be present the degrade engine expresses a
16013
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
16250
+ * - `widget` a Module-Federation widget the login page mounts (via
16251
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
16252
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
16253
+ * mechanism kept for future use; no shipped addon uses it on the login
16254
+ * page (the passkey ceremony below runs natively in the shell instead).
16255
+ *
16256
+ * - `passkey` a declarative WebAuthn ceremony the shell renders
16257
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
16258
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
16259
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
16260
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
16261
+ * fetching any remote code pre-auth. Contribution stays unconditional —
16262
+ * enrollment state is never leaked pre-auth; visibility is a shell
16263
+ * decision.
16264
+ *
16265
+ * Every contribution carries a `stage`:
16266
+ * - `primary` — shown on the first credentials screen (OIDC /
16267
+ * magic-link buttons; a future usernameless passkey).
16268
+ * - `second-factor` — shown AFTER the password leg, gated on the
16269
+ * returned `factors` (passkey-as-2FA today).
16270
+ *
16271
+ * `mount: skip` — the cap is read server-side by the core auth router
16272
+ * (`registry.getCollection('login-method')`), never mounted as its own
16273
+ * tRPC router.
16014
16274
  */
16015
- var AttachmentSchema = object({
16016
- mediaType: AttachmentMediaTypeSchema,
16017
- url: string().optional(),
16018
- bytes: _instanceof(Uint8Array).optional(),
16019
- mime: string().optional(),
16020
- name: string().optional()
16021
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
16022
- var NotificationFormatSchema = _enum([
16023
- "text",
16024
- "markdown",
16025
- "html"
16275
+ /** When a login method renders in the two-phase login flow. */
16276
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
16277
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
16278
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
16279
+ object({
16280
+ kind: literal("redirect"),
16281
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
16282
+ id: string(),
16283
+ /** Operator-facing button label. */
16284
+ label: string(),
16285
+ /** lucide-react icon name. */
16286
+ icon: string().optional(),
16287
+ /** Addon-owned HTTP route the button navigates to (GET). */
16288
+ startUrl: string(),
16289
+ stage: LoginStageEnum
16290
+ }),
16291
+ object({
16292
+ kind: literal("widget"),
16293
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
16294
+ id: string(),
16295
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
16296
+ addonId: string(),
16297
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
16298
+ bundle: string(),
16299
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
16300
+ remote: WidgetRemoteSchema,
16301
+ stage: LoginStageEnum
16302
+ }),
16303
+ object({
16304
+ kind: literal("passkey"),
16305
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
16306
+ id: string(),
16307
+ /** Operator-facing button label. */
16308
+ label: string(),
16309
+ stage: LoginStageEnum,
16310
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
16311
+ rpId: string(),
16312
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
16313
+ origin: string().nullable()
16314
+ })
16026
16315
  ]);
16027
- /** A single tap-through action button. */
16028
- var NotificationActionSchema = object({
16029
- id: string(),
16030
- label: string(),
16031
- url: string().optional()
16316
+ method(_void(), array(LoginMethodContributionSchema).readonly());
16317
+ var CpuBreakdownSchema = object({
16318
+ total: number(),
16319
+ user: number(),
16320
+ system: number(),
16321
+ irq: number(),
16322
+ nice: number(),
16323
+ loadAvg: tuple([
16324
+ number(),
16325
+ number(),
16326
+ number()
16327
+ ]),
16328
+ cores: number()
16032
16329
  });
16033
- /**
16034
- * The canonical notification. `body` is the only hard field (Apprise model).
16035
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
16036
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
16037
- * the adapter maps this ordinal onto its native level. `level?` is an
16038
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
16039
- * `priority` for that one target.
16040
- */
16041
- var NotificationSchema = object({
16042
- body: string(),
16043
- title: string().optional(),
16044
- format: NotificationFormatSchema.default("text"),
16045
- priority: number().int().min(1).max(5).default(3),
16046
- level: string().optional(),
16047
- attachments: array(AttachmentSchema).optional(),
16048
- clickUrl: string().optional(),
16049
- actions: array(NotificationActionSchema).optional(),
16050
- sound: string().optional(),
16051
- ttl: number().optional(),
16052
- tag: string().optional(),
16053
- deviceId: number().optional(),
16054
- eventId: string().optional(),
16055
- metadata: record(string(), unknown()).optional()
16330
+ var MemoryInfoSchema = object({
16331
+ percent: number(),
16332
+ totalBytes: number(),
16333
+ usedBytes: number(),
16334
+ availableBytes: number(),
16335
+ swapUsedBytes: number(),
16336
+ swapTotalBytes: number()
16337
+ });
16338
+ var DiskIoSnapshotSchema = object({
16339
+ readBytes: number(),
16340
+ writeBytes: number(),
16341
+ readOps: number(),
16342
+ writeOps: number(),
16343
+ timestampMs: number()
16344
+ });
16345
+ var NetworkIoSnapshotSchema = object({
16346
+ rxBytes: number(),
16347
+ txBytes: number(),
16348
+ rxPackets: number(),
16349
+ txPackets: number(),
16350
+ rxErrors: number(),
16351
+ txErrors: number(),
16352
+ timestampMs: number()
16353
+ });
16354
+ var MetricsGpuInfoSchema = object({
16355
+ utilization: number(),
16356
+ model: string(),
16357
+ memoryUsedBytes: number(),
16358
+ memoryTotalBytes: number(),
16359
+ temperature: number().nullable()
16360
+ });
16361
+ var ProcessResourceInfoSchema = object({
16362
+ openFds: number(),
16363
+ threadCount: number(),
16364
+ activeHandles: number(),
16365
+ activeRequests: number()
16056
16366
  });
16057
- /** One declared native severity/priority level for a kind. */
16058
- var TargetKindLevelSchema = object({
16059
- id: string(),
16060
- label: string(),
16061
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
16062
- ordinal: number().int().min(1).max(5).nullable(),
16063
- flags: object({
16064
- critical: boolean().optional(),
16065
- silent: boolean().optional(),
16066
- noPush: boolean().optional()
16067
- }).optional(),
16068
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
16069
- requires: array(string()).optional(),
16070
- description: string().optional()
16367
+ var PressureAvgsSchema = object({
16368
+ avg10: number(),
16369
+ avg60: number(),
16370
+ avg300: number()
16071
16371
  });
16072
- /** The full capability block consulted before dispatch. */
16073
- var TargetKindCapsSchema = object({
16074
- attachments: object({
16075
- mediaTypes: array(AttachmentMediaTypeSchema),
16076
- mode: _enum([
16077
- "url",
16078
- "bytes",
16079
- "both"
16080
- ]),
16081
- max: number().int().nonnegative(),
16082
- maxBytes: number().int().positive().optional()
16372
+ var PressureInfoSchema = object({
16373
+ some: PressureAvgsSchema,
16374
+ full: PressureAvgsSchema.nullable()
16375
+ });
16376
+ var SystemResourceSnapshotSchema = object({
16377
+ cpu: CpuBreakdownSchema,
16378
+ memory: MemoryInfoSchema,
16379
+ gpu: MetricsGpuInfoSchema.nullable(),
16380
+ network: NetworkIoSnapshotSchema,
16381
+ disk: DiskIoSnapshotSchema,
16382
+ pressure: object({
16383
+ cpu: PressureInfoSchema.nullable(),
16384
+ memory: PressureInfoSchema.nullable(),
16385
+ io: PressureInfoSchema.nullable()
16083
16386
  }),
16084
- /** Max action buttons (0 = none). */
16085
- actions: number().int().nonnegative(),
16086
- levels: array(TargetKindLevelSchema),
16087
- format: array(NotificationFormatSchema),
16088
- clickUrl: boolean(),
16089
- sound: boolean(),
16090
- ttl: boolean(),
16091
- bodyMaxLen: number().int().positive()
16387
+ process: ProcessResourceInfoSchema,
16388
+ cpuTemperature: number().nullable(),
16389
+ timestampMs: number()
16092
16390
  });
16093
- /**
16094
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
16095
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
16096
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
16097
- * the union is large and not meant for runtime validation here; the exported
16098
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
16099
- */
16100
- var ConfigSchemaPassthrough = unknown();
16101
- var TargetKindSchema = object({
16102
- kind: string(),
16103
- label: string(),
16104
- icon: string(),
16105
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
16106
- addonId: string(),
16107
- configSchema: ConfigSchemaPassthrough,
16108
- supportsDiscovery: boolean(),
16109
- caps: TargetKindCapsSchema
16391
+ var DiskSpaceInfoSchema = object({
16392
+ path: string(),
16393
+ totalBytes: number(),
16394
+ usedBytes: number(),
16395
+ availableBytes: number(),
16396
+ percent: number()
16110
16397
  });
16111
- /**
16112
- * A persisted target. `config` holds secrets; providers REDACT secret fields
16113
- * (return a presence marker only) when serving `listTargets` — never
16114
- * round-trip a stored secret to the UI.
16115
- */
16116
- var TargetSchema = object({
16117
- id: string(),
16118
- name: string(),
16119
- kind: string(),
16398
+ var PidResourceStatsSchema = object({
16399
+ pid: number(),
16400
+ cpu: number(),
16401
+ memory: number(),
16402
+ /**
16403
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
16404
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
16405
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
16406
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
16407
+ * Undefined where /proc is unavailable (e.g. macOS).
16408
+ */
16409
+ privateBytes: number().optional(),
16410
+ /**
16411
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
16412
+ * code shared copy-on-write across runners. Undefined on macOS.
16413
+ */
16414
+ sharedBytes: number().optional()
16415
+ });
16416
+ var AddonInstanceSchema = object({
16120
16417
  addonId: string(),
16121
- enabled: boolean(),
16122
- config: record(string(), unknown())
16418
+ nodeId: string(),
16419
+ role: _enum(["hub", "worker"]),
16420
+ pid: number(),
16421
+ state: _enum([
16422
+ "starting",
16423
+ "running",
16424
+ "stopping",
16425
+ "stopped",
16426
+ "crashed"
16427
+ ]),
16428
+ uptimeSec: number()
16123
16429
  });
16124
- /** A discovery-surfaced candidate (config is partial + non-secret). */
16125
- var DiscoveredTargetSchema = object({
16126
- kind: string(),
16127
- suggestedName: string(),
16128
- config: record(string(), unknown())
16430
+ var NodeProcessSchema = object({
16431
+ pid: number(),
16432
+ ppid: number(),
16433
+ pgid: number(),
16434
+ classification: _enum([
16435
+ "root",
16436
+ "managed",
16437
+ "system",
16438
+ "ghost"
16439
+ ]),
16440
+ /** `$process` addon binding when `managed`, else null. */
16441
+ addonId: string().nullable(),
16442
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
16443
+ nodeId: string().nullable(),
16444
+ /** Truncated command line. */
16445
+ command: string(),
16446
+ cpuPercent: number(),
16447
+ memoryRssBytes: number(),
16448
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
16449
+ uptimeSec: number(),
16450
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
16451
+ orphaned: boolean()
16129
16452
  });
16130
- /** The degrade engine's report — what was resolved / dropped / degraded. */
16131
- var RenderedAsSchema = object({
16132
- level: string(),
16133
- format: NotificationFormatSchema,
16134
- attachmentsSent: number().int().nonnegative(),
16135
- actionsSent: number().int().nonnegative(),
16136
- truncated: boolean(),
16137
- dropped: array(string())
16453
+ var KillProcessInputSchema = object({
16454
+ pid: number(),
16455
+ /** Force = SIGKILL. Default is SIGTERM. */
16456
+ force: boolean().optional()
16138
16457
  });
16139
- var SendResultSchema = object({
16458
+ var KillProcessResultSchema = object({
16140
16459
  success: boolean(),
16141
- error: string().optional(),
16142
- renderedAs: RenderedAsSchema.optional()
16460
+ reason: string().optional(),
16461
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
16462
+ });
16463
+ var DumpHeapSnapshotInputSchema = object({
16464
+ /** The addon whose runner should dump a heap snapshot. */
16465
+ addonId: string() });
16466
+ var DumpHeapSnapshotResultSchema = object({
16467
+ success: boolean(),
16468
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
16469
+ path: string().optional(),
16470
+ /** Process pid that was signalled. */
16471
+ pid: number().optional(),
16472
+ reason: string().optional()
16473
+ });
16474
+ var SystemMetricsSchema = object({
16475
+ cpuPercent: number(),
16476
+ memoryPercent: number(),
16477
+ memoryUsedMB: number(),
16478
+ memoryTotalMB: number(),
16479
+ diskPercent: number().optional(),
16480
+ temperature: number().optional(),
16481
+ gpuPercent: number().optional(),
16482
+ gpuMemoryPercent: number().optional()
16483
+ });
16484
+ method(_void(), SystemResourceSnapshotSchema), method(_void(), SystemResourceSnapshotSchema.nullable()), method(_void(), SystemMetricsSchema), method(object({ dirPath: string() }), DiskSpaceInfoSchema), method(_void(), MetricsGpuInfoSchema.nullable()), method(_void(), number().nullable()), method(object({ pids: array(number()) }), array(PidResourceStatsSchema)), method(_void(), array(AddonInstanceSchema).readonly()), method(object({ addonId: string() }), PidResourceStatsSchema.nullable()), method(_void(), array(NodeProcessSchema).readonly()), method(KillProcessInputSchema, KillProcessResultSchema, {
16485
+ kind: "mutation",
16486
+ auth: "admin"
16487
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
16488
+ kind: "mutation",
16489
+ auth: "admin"
16490
+ });
16491
+ method(object({
16492
+ sourceUrl: string(),
16493
+ metadata: ModelConvertMetadataSchema,
16494
+ targets: array(ConvertTargetSchema).min(1).readonly(),
16495
+ calibrationRef: string().optional(),
16496
+ sessionId: string().optional()
16497
+ }), ConvertResultSchema, {
16498
+ kind: "mutation",
16499
+ auth: "admin",
16500
+ timeoutMs: 6e5
16501
+ });
16502
+ method(object({
16503
+ nodeId: string(),
16504
+ modelId: string(),
16505
+ format: _enum(MODEL_FORMATS),
16506
+ entry: ModelCatalogEntrySchema
16507
+ }), object({
16508
+ ok: boolean(),
16509
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
16510
+ sha256: string(),
16511
+ bytes: number(),
16512
+ /** The target node's modelsDir the artifact landed in. */
16513
+ path: string()
16514
+ }), {
16515
+ kind: "mutation",
16516
+ auth: "admin"
16143
16517
  });
16144
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
16145
- var TestResultSchema = SendResultSchema;
16146
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
16147
- kind: string(),
16148
- config: record(string(), unknown()).optional()
16149
- }), array(DiscoveredTargetSchema)), method(object({
16150
- targetId: string(),
16151
- notification: NotificationSchema
16152
- }), SendResultSchema, { kind: "mutation" }), method(object({
16153
- targetId: string(),
16154
- sample: NotificationSchema.optional()
16155
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
16156
- targetId: string(),
16157
- enabled: boolean()
16158
- }), _void(), { kind: "mutation" });
16159
16518
  /**
16160
- * notification-rulesthe Notification Center rule surface (P1 core).
16161
- *
16162
- * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16163
- * (operator decisions D-1/D-2/D-3 are binding):
16519
+ * `mqtt-broker`broker-registry cap.
16164
16520
  *
16165
- * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16166
- * `notification-center` module), hooked on the durable persistence
16167
- * moments (object-event insert, TrackCloser.closeExpired) with a
16168
- * persisted outbox + retry — never the lossy telemetry bus (D8).
16169
- * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16170
- * FIRST persisted detection matching the conditions (per-track dedup,
16171
- * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16172
- * `delivery: 'track-end'` evaluates the finalized track record at close.
16173
- * - DISPATCH stays behind `notification-output` (rules reference targets
16174
- * by id; per-backend params are a passthrough blob capped by the
16175
- * target kind's own caps/degrade engine).
16521
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
16522
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
16523
+ * and (b) the connection details a consumer addon needs to spin up
16524
+ * its OWN `mqtt.js` client.
16176
16525
  *
16177
- * P1 scope: admin-authored rules only (`createdBy` stamped from the
16178
- * server-injected caller identity the first `caller: 'required'`
16179
- * adopter). The P1 condition subset is: devices, classes(+exclude),
16180
- * minConfidence, admin zones (any/all + exclude), weekly schedule
16181
- * windows, and the optional label/identity/plate matchers. User rules,
16182
- * private zones, per-recipient fan-out and the wider condition table are
16183
- * P2+ (see spec §7).
16526
+ * Why: pub/sub routing over the system event-bus loses fidelity
16527
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
16528
+ * refcount bookkeeping that addons would rather own themselves. The
16529
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
16530
+ * features anyway — give it the connection config, get out of the way.
16184
16531
  *
16185
- * All schemas here are the single source of truth — `NcRule` etc. are
16186
- * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16187
- * schema/interface drift is explicitly not repeated).
16532
+ * Consumer flow:
16533
+ * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
16534
+ * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
16535
+ * client.subscribe('zigbee2mqtt/+')
16536
+ *
16537
+ * Collection mode: multiple brokers (e.g. one local mosquitto + one
16538
+ * cloud bridge). The "embedded" entry (when present) is just another
16539
+ * broker in the registry — its lifecycle is owned by the addon that
16540
+ * spawned it.
16188
16541
  */
16542
+ var BrokerKindSchema = _enum(["external", "embedded"]);
16189
16543
  /**
16190
- * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
16191
- * The value maps 1:1 onto the evaluated record kind:
16192
- * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16193
- * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16194
- * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16195
- * change of a LINKED device, one row per linked camera)
16196
- * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16197
- * delivery / pick-up)
16544
+ * Broker live-probe status.
16198
16545
  *
16199
- * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16200
- * `package-event` are pure trigger kinds (no urgency dimension). Extending
16201
- * this one field keeps the schema additive a rule still declares exactly
16202
- * one trigger.
16546
+ * - `connected` last probe completed a clean CONNACK
16547
+ * - `disconnected` no probe has run yet (cold cache)
16548
+ * - `auth-failed` CONNACK refused with auth error (RC 4 / 5)
16549
+ * - `unreachable` — TCP connect timed out / refused
16550
+ * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
16203
16551
  */
16204
- var NcDeliverySchema = _enum([
16205
- "immediate",
16206
- "track-end",
16207
- "device-event",
16208
- "package-event"
16552
+ var BrokerStatusSchema$1 = _enum([
16553
+ "connected",
16554
+ "disconnected",
16555
+ "auth-failed",
16556
+ "unreachable",
16557
+ "tls-error"
16209
16558
  ]);
16210
- /** Weekly schedule — OR of windows; absence on the rule = always active. */
16211
- var NcScheduleSchema = object({
16212
- windows: array(object({
16213
- /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16214
- days: array(number().int().min(0).max(6)).min(1),
16215
- startMinute: number().int().min(0).max(1439),
16216
- endMinute: number().int().min(0).max(1439)
16217
- })).min(1),
16218
- /** IANA timezone; default = hub host timezone. */
16219
- timezone: string().optional(),
16220
- /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16221
- invert: boolean().optional()
16222
- });
16223
- /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16224
- var NcPlateMatcherSchema = object({
16225
- values: array(string().min(1)).min(1),
16226
- /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16227
- maxDistance: number().int().min(0).max(3).default(1)
16228
- });
16229
- /**
16230
- * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16231
- * occupancy edge for a device — optionally narrowed to a single admin
16232
- * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16233
- * - `became-occupied` (default) — count crossed 0 → ≥ `count`
16234
- * - `became-free` — count crossed ≥ `count` → below it
16235
- * - `>=` / `<=` — count is at/over or at/under `count`
16236
- * `sustainSeconds` requires the condition hold continuously that long
16237
- * before firing (debounces flicker; 0 = fire on the first matching edge).
16238
- * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16239
- * the condition never matches. Confirmed edge-state survives addon restarts
16240
- * (declared SQLite collection, reseeded on boot).
16241
- */
16242
- var NcOccupancyConditionSchema = object({
16243
- /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16244
- zoneId: string().optional(),
16245
- /** Object class to count; absent = any class. */
16246
- className: string().optional(),
16247
- op: _enum([
16248
- "became-occupied",
16249
- "became-free",
16250
- ">=",
16251
- "<="
16252
- ]).default("became-occupied"),
16253
- count: number().int().min(0).default(1),
16254
- sustainSeconds: number().int().min(0).max(3600).default(15)
16255
- });
16256
- /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16257
- var NcZoneConditionSchema = object({
16258
- ids: array(string().min(1)).min(1),
16259
- /** Quantifier over `ids` — at least one / every one visited. */
16260
- match: _enum(["any", "all"]).default("any")
16261
- });
16262
- /**
16263
- * The P1 condition set — a flat AND of groups; absent group = pass;
16264
- * membership lists are OR within the list (spec §2.3).
16265
- */
16266
- var NcConditionsSchema = object({
16267
- /** Device scope — absent = all devices. */
16268
- devices: array(number()).optional(),
16269
- /** Detector class names (any overlap with the record's class set). */
16270
- classes: array(string().min(1)).optional(),
16271
- /** Veto classes — any overlap fails the rule. */
16272
- classesExclude: array(string().min(1)).optional(),
16273
- /** Minimum detection confidence 0–1 (fails when the record has none). */
16274
- minConfidence: number().min(0).max(1).optional(),
16275
- /** Admin zone membership over event `zones` / track `zonesVisited`. */
16276
- zones: NcZoneConditionSchema.optional(),
16277
- /** Veto zones — any hit fails the rule. */
16278
- zonesExclude: array(string().min(1)).optional(),
16279
- /**
16280
- * Exact (case-insensitive) match on the record's collapsed `label`
16281
- * (identity name / plate text / subclass).
16282
- */
16283
- labelEquals: array(string().min(1)).optional(),
16284
- /**
16285
- * Identity matcher. P1 boundary: matched against the record's collapsed
16286
- * `label` (the identity display name propagated by the face pipeline) —
16287
- * identity-ID matching rides in P2 when identity ids reach the record.
16288
- */
16289
- identities: array(string().min(1)).optional(),
16290
- /** Fuzzy plate matcher against the record's `label` (plate text). */
16291
- plates: NcPlateMatcherSchema.optional(),
16292
- /**
16293
- * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16294
- * Same P1 boundary: matched against the record's collapsed `label` (the
16295
- * identity display name). A record with NO label passes (nothing to
16296
- * exclude), unlike the include variant which fails on an absent label.
16297
- */
16298
- identitiesExclude: array(string().min(1)).optional(),
16299
- /**
16300
- * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16301
- * TRACK-END only: importance is scored at track close, so it does not exist
16302
- * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16303
- * close the value is threaded via the close-time info (the `Track` clone is
16304
- * captured before the DB row is updated, so it would otherwise read stale).
16305
- * Fails when the record carries no importance (never guess quality — the
16306
- * `minConfidence` precedent). MVP cut: a single scalar threshold.
16307
- */
16308
- minImportance: number().min(0).max(1).optional(),
16309
- /**
16310
- * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16311
- * TRACK-END only: an `immediate` / object-event subject has no closed
16312
- * lifespan, so a dwell condition never matches immediate delivery
16313
- * (documented choice — the object-event record carries no `firstSeen`,
16314
- * so dwell cannot be computed from what the subject actually carries).
16315
- */
16316
- minDwellSeconds: number().min(0).optional(),
16317
- /**
16318
- * Detection provenance filter. `any` (default / absent) matches every
16319
- * source; otherwise the subject's source must equal it. Legacy records
16320
- * with no stamped source are treated as `pipeline`. The union spans both
16321
- * record kinds — object events carry `pipeline` | `onboard`, synthetic
16322
- * tracks carry `sensor`.
16323
- */
16324
- source: _enum([
16325
- "pipeline",
16326
- "onboard",
16327
- "sensor",
16328
- "any"
16329
- ]).optional(),
16330
- /**
16331
- * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16332
- * detector `minConfidence` (that gates the object-detection score; this
16333
- * gates the recognition/OCR match score). Fails when the subject carries
16334
- * no label-match confidence (never guess). TRACK-END only: the confidence
16335
- * lives on the recognition result and reaches the subject at track close.
16336
- *
16337
- * What it measures precisely (plumbed at track close — the closer threads
16338
- * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16339
- * `importance`): the BEST recognition match confidence observed for the
16340
- * label the track carries at close — for a face, the peak cosine similarity
16341
- * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16342
- * for a plate, the peak OCR read score of the best-held plate
16343
- * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16344
- * one track the higher of the two is used. A track that ended with no
16345
- * confident identity/plate match carries no value, so the condition fails
16346
- * closed for it (an un-recognized subject).
16347
- */
16348
- minLabelConfidence: number().min(0).max(1).optional(),
16349
- /**
16350
- * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16351
- * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16352
- * against the token carried on the device-event subject (extracted from the
16353
- * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16354
- * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16355
- * eventType, so gate those with {@link sensorKinds} instead.
16356
- */
16357
- eventTypeTokens: array(string().min(1)).optional(),
16358
- /**
16359
- * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16360
- * `contact`, `button`, `device-event`) — matched against the persisted
16361
- * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16362
- */
16363
- sensorKinds: array(string().min(1)).optional(),
16364
- /**
16365
- * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16366
- * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16367
- * when the subject's phase does not match (a subject always carries a phase
16368
- * on the package-event trigger).
16369
- */
16370
- packagePhase: _enum([
16371
- "delivered",
16372
- "picked-up",
16373
- "both"
16374
- ]).optional(),
16375
- /**
16376
- * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16377
- * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16378
- * listed polygon (ZoneEngine membership semantics). Evaluated only when
16379
- * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16380
- */
16381
- customZones: array(MaskPolygonShapeSchema).optional(),
16382
- /**
16383
- * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16384
- * (optionally zone/class-scoped) occupancy count crosses the configured
16385
- * threshold and holds for `sustainSeconds`. Fail-closed on missing
16386
- * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16387
- */
16388
- occupancy: NcOccupancyConditionSchema.optional()
16389
- });
16390
- /** One delivery target: a `notification-output` Target ref + passthrough params. */
16391
- var NcRuleTargetSchema = object({
16392
- /** `notification-output` Target id. */
16393
- targetId: string().min(1),
16394
- /**
16395
- * Per-backend passthrough. Recognized keys are mapped onto the canonical
16396
- * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16397
- * degrade engine drops what the backend can't render.
16398
- */
16399
- params: record(string(), unknown()).optional()
16559
+ var BrokerInfoSchema = object({
16560
+ id: string(),
16561
+ name: string(),
16562
+ url: string(),
16563
+ kind: BrokerKindSchema,
16564
+ status: BrokerStatusSchema$1,
16565
+ latencyMs: number().nullable(),
16566
+ error: string().optional(),
16567
+ /** Embedded brokers only: number of MQTT clients currently connected. */
16568
+ connectedClients: number().int().nonnegative().optional(),
16569
+ /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
16570
+ lastCheckedAt: number().optional()
16400
16571
  });
16401
16572
  /**
16402
- * Media attachment policy (P1 still-image subset).
16403
- * - `best` the best AVAILABLE subject image at dispatch time (D-3).
16404
- * - `best-matching` the media that explains WHY the rule fired: a rule
16405
- * matched on identities attaches the subject's `faceCrop`, one matched on
16406
- * plates attaches the `plateCrop`; a rule with no identity/plate condition
16407
- * (or when the specific crop is missing) degrades to `best`, then
16408
- * `keyFrame`, then no attachment — never delaying the send. The matched
16409
- * condition summary is frozen on the outbox row at enqueue (like the rule
16410
- * name), so the choice never drifts from the record that fired it.
16411
- * - `keyFrame` — the clean scene frame (no subject box).
16412
- * - `none` — no attachment.
16573
+ * Connection details what a consumer needs to call
16574
+ * `mqtt.connect(url, options)`. We split URL + credentials so the
16575
+ * consumer can pass them as `mqtt.connect(url, { username, password })`
16576
+ * instead of stuffing creds into the URL (which leaks them into logs).
16413
16577
  */
16414
- var NcMediaPolicySchema = object({ attach: _enum([
16415
- "best",
16416
- "best-matching",
16417
- "keyFrame",
16418
- "none"
16419
- ]).default("best") });
16420
- /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16421
- var NcThrottleSchema = object({
16422
- cooldownSec: number().int().min(0).max(86400).default(60),
16423
- /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16424
- scope: _enum(["rule", "rule-device"]).default("rule-device")
16425
- });
16426
- /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16427
- var NcRuleInputSchema = object({
16428
- name: string().min(1).max(200),
16429
- enabled: boolean().default(true),
16430
- delivery: NcDeliverySchema,
16431
- conditions: NcConditionsSchema.default({}),
16432
- schedule: NcScheduleSchema.optional(),
16433
- targets: array(NcRuleTargetSchema).min(1),
16434
- media: NcMediaPolicySchema.default({ attach: "best" }),
16435
- throttle: NcThrottleSchema.default({
16436
- cooldownSec: 60,
16437
- scope: "rule-device"
16438
- }),
16439
- /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16440
- template: object({
16441
- title: string().max(500).optional(),
16442
- body: string().max(2e3).optional()
16443
- }).optional(),
16444
- /** Canonical notification priority ordinal (1..5); per-target overridable. */
16445
- priority: number().int().min(1).max(5).default(3),
16578
+ var BrokerConnectionDetailsSchema = object({
16579
+ url: string(),
16580
+ username: string().optional(),
16581
+ password: string().optional(),
16446
16582
  /**
16447
- * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16448
- * behaviour, visible to all, read-only in the viewer). Present = personal
16449
- * rule owned by this userId. Server-stamped; never trusted from a client.
16583
+ * Suggested prefix for `clientId`. Each consumer should suffix this
16584
+ * with its own discriminator (addon id, instance id) so reconnects
16585
+ * don't kick each other off (MQTT spec: clientId must be unique per
16586
+ * broker).
16450
16587
  */
16451
- ownerUserId: string().optional()
16588
+ clientIdPrefix: string().optional()
16589
+ });
16590
+ var AddBrokerInputSchema = object({
16591
+ name: string().min(1),
16592
+ url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
16593
+ username: string().optional(),
16594
+ password: string().optional(),
16595
+ clientIdPrefix: string().optional()
16596
+ });
16597
+ var AddBrokerResultSchema = object({ id: string() });
16598
+ var IdInputSchema = object({ id: string() });
16599
+ var TestResultSchema$1 = discriminatedUnion("ok", [object({
16600
+ ok: literal(true),
16601
+ latencyMs: number()
16602
+ }), object({
16603
+ ok: literal(false),
16604
+ error: string()
16605
+ })]);
16606
+ var StartEmbeddedInputSchema = object({
16607
+ port: number().int().min(1).max(65535).default(1883),
16608
+ /** Allow anonymous connect (no username/password). Default: false. */
16609
+ allowAnonymous: boolean().default(false),
16610
+ /** Optional shared username/password for clients. */
16611
+ username: string().optional(),
16612
+ password: string().optional()
16613
+ });
16614
+ var StartEmbeddedResultSchema = object({
16615
+ id: string(),
16616
+ url: string()
16617
+ });
16618
+ var StatusSchema = object({
16619
+ brokerCount: number(),
16620
+ embeddedRunning: boolean()
16621
+ });
16622
+ method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnectionDetailsSchema), method(AddBrokerInputSchema, AddBrokerResultSchema, { kind: "mutation" }), method(IdInputSchema, _void(), { kind: "mutation" }), method(IdInputSchema, TestResultSchema$1, { kind: "mutation" }), method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, { kind: "mutation" }), method(IdInputSchema, _void(), { kind: "mutation" }), method(_void(), StatusSchema);
16623
+ var NetworkEndpointSchema = object({
16624
+ url: string(),
16625
+ hostname: string(),
16626
+ port: number(),
16627
+ protocol: _enum(["http", "https"])
16628
+ });
16629
+ var NetworkAccessStatusSchema = object({
16630
+ connected: boolean(),
16631
+ endpoint: NetworkEndpointSchema.nullable(),
16632
+ error: string().optional()
16452
16633
  });
16453
16634
  /**
16454
- * Partial patch for `updateRule` any subset of the input fields, plus the
16455
- * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16456
- * NOT a client-authored input field (it lives on the persisted rule, not the
16457
- * input), so it is added here explicitly to let the store's per-target opt-out
16458
- * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16459
- * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16460
- * `updateRule` patch.
16635
+ * Optional, richer endpoint shape returned by providers that expose
16636
+ * MORE than one ingress concurrently (Tailscale Ingress with mixed
16637
+ * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
16638
+ * the originating provider config (mode + sourcePort) so the
16639
+ * orchestrator UI can label rows distinctly. Providers that expose only
16640
+ * one endpoint just omit `listEndpoints` from their provider impl.
16461
16641
  */
16462
- var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
16463
- /** A persisted rule. */
16464
- var NcRuleSchema = NcRuleInputSchema.extend({
16465
- id: string(),
16466
- /** userId of the admin who created the rule (server-stamped caller). */
16467
- createdBy: string(),
16468
- createdAt: number(),
16469
- updatedAt: number(),
16642
+ var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
16470
16643
  /**
16471
- * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16472
- * send time. Only a target's OWNER may add/remove its id (server-checked
16473
- * in `nc.setRuleTargetEnabled`). Defaults to empty.
16644
+ * Stable id within the provider typically `<mode>-<sourcePort>` so
16645
+ * the orchestrator can dedupe across `listEndpoints` polls.
16474
16646
  */
16475
- disabledTargetIds: array(string()).default([])
16476
- });
16477
- var NcTestResultSchema = object({
16478
- recordId: string(),
16479
- recordKind: _enum([
16480
- "object-event",
16481
- "track",
16482
- "device-event",
16483
- "package-event"
16484
- ]),
16485
- deviceId: number(),
16486
- timestamp: number(),
16487
- wouldFire: boolean(),
16488
- /** Condition id that failed (first failing group), when `wouldFire` is false. */
16489
- failedCondition: string().optional(),
16490
- className: string().optional(),
16491
- label: string().optional()
16647
+ id: string(),
16648
+ /** Operator-facing label (mirrors `MeshEndpoint.label`). */
16649
+ label: string(),
16650
+ /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
16651
+ mode: string().optional(),
16652
+ /** Originating local port the ingress fronts (informational). */
16653
+ sourcePort: number().optional()
16492
16654
  });
16493
- var NcConditionDescriptorSchema = object({
16494
- /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16655
+ method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
16656
+ /**
16657
+ * notification-output — canonical, capability-gated notification delivery.
16658
+ *
16659
+ * Apprise-derived model (see
16660
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
16661
+ * callers emit ONE canonical `Notification`; each provider declares a
16662
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
16663
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
16664
+ * message to what the kind supports — callers never special-case a service.
16665
+ *
16666
+ * DESIGN DECISIONS (locked):
16667
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
16668
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
16669
+ * cap. Rationale: the admin UI needs one uniform surface across the
16670
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
16671
+ * alternative would fork the UI per addon and cannot host the
16672
+ * discovery→adopt flow.
16673
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
16674
+ * the generated cap-mount auto-`concatCollection`-fans them across every
16675
+ * registered provider (notifiers addon + HA addon) so one catalog is
16676
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
16677
+ * `addonId` the generated collection router extracts from the call input.
16678
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
16679
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
16680
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
16681
+ * base64 fallback needed.
16682
+ *
16683
+ * TODO (deferred, closed-set change — separate decision): add
16684
+ * `providerKind: 'notify'` so notification providers surface on the unified
16685
+ * admin "Integrations" page.
16686
+ */
16687
+ /**
16688
+ * Zentik-derived typed-media enum — the superset across every kind. Each
16689
+ * adapter picks what it supports and the degrade engine filters the rest.
16690
+ */
16691
+ var AttachmentMediaTypeSchema = _enum([
16692
+ "image",
16693
+ "video",
16694
+ "gif",
16695
+ "audio",
16696
+ "icon"
16697
+ ]);
16698
+ /**
16699
+ * A single attachment. Exactly one of `url` (remote source, most adapters
16700
+ * prefer this) or `bytes` (inline source; required for Pushover-style
16701
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
16702
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
16703
+ */
16704
+ var AttachmentSchema = object({
16705
+ mediaType: AttachmentMediaTypeSchema,
16706
+ url: string().optional(),
16707
+ bytes: _instanceof(Uint8Array).optional(),
16708
+ mime: string().optional(),
16709
+ name: string().optional()
16710
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
16711
+ var NotificationFormatSchema = _enum([
16712
+ "text",
16713
+ "markdown",
16714
+ "html"
16715
+ ]);
16716
+ /** A single tap-through action button. */
16717
+ var NotificationActionSchema = object({
16718
+ id: string(),
16719
+ label: string(),
16720
+ url: string().optional()
16721
+ });
16722
+ /**
16723
+ * The canonical notification. `body` is the only hard field (Apprise model).
16724
+ * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
16725
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
16726
+ * the adapter maps this ordinal onto its native level. `level?` is an
16727
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
16728
+ * `priority` for that one target.
16729
+ */
16730
+ var NotificationSchema = object({
16731
+ body: string(),
16732
+ title: string().optional(),
16733
+ format: NotificationFormatSchema.default("text"),
16734
+ priority: number().int().min(1).max(5).default(3),
16735
+ level: string().optional(),
16736
+ attachments: array(AttachmentSchema).optional(),
16737
+ clickUrl: string().optional(),
16738
+ actions: array(NotificationActionSchema).optional(),
16739
+ sound: string().optional(),
16740
+ ttl: number().optional(),
16741
+ tag: string().optional(),
16742
+ deviceId: number().optional(),
16743
+ eventId: string().optional(),
16744
+ metadata: record(string(), unknown()).optional()
16745
+ });
16746
+ /** One declared native severity/priority level for a kind. */
16747
+ var TargetKindLevelSchema = object({
16495
16748
  id: string(),
16496
- group: _enum([
16497
- "scope",
16498
- "class",
16499
- "zones",
16500
- "quality",
16501
- "label",
16502
- "schedule",
16503
- "device",
16504
- "package",
16505
- "occupancy"
16506
- ]),
16507
16749
  label: string(),
16508
- /** Editor widget the UI renders never hardcode per-condition forms. */
16509
- valueType: _enum([
16510
- "deviceIdList",
16511
- "stringList",
16512
- "number01",
16513
- "number",
16514
- "sourceSelect",
16515
- "zoneSelection",
16516
- "zoneIdList",
16517
- "schedule",
16518
- "plateMatcher",
16519
- "packagePhase",
16520
- "polygonDraw",
16521
- "occupancy"
16522
- ]),
16523
- operator: _enum([
16524
- "in",
16525
- "notIn",
16526
- "anyOf",
16527
- "allOf",
16528
- "gte",
16529
- "fuzzyIn",
16530
- "withinSchedule"
16531
- ]),
16532
- /** Which delivery kinds the condition applies to. */
16533
- appliesTo: array(NcDeliverySchema),
16534
- phase: string(),
16750
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
16751
+ ordinal: number().int().min(1).max(5).nullable(),
16752
+ flags: object({
16753
+ critical: boolean().optional(),
16754
+ silent: boolean().optional(),
16755
+ noPush: boolean().optional()
16756
+ }).optional(),
16757
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
16758
+ requires: array(string()).optional(),
16535
16759
  description: string().optional()
16536
16760
  });
16761
+ /** The full capability block consulted before dispatch. */
16762
+ var TargetKindCapsSchema = object({
16763
+ attachments: object({
16764
+ mediaTypes: array(AttachmentMediaTypeSchema),
16765
+ mode: _enum([
16766
+ "url",
16767
+ "bytes",
16768
+ "both"
16769
+ ]),
16770
+ max: number().int().nonnegative(),
16771
+ maxBytes: number().int().positive().optional()
16772
+ }),
16773
+ /** Max action buttons (0 = none). */
16774
+ actions: number().int().nonnegative(),
16775
+ levels: array(TargetKindLevelSchema),
16776
+ format: array(NotificationFormatSchema),
16777
+ clickUrl: boolean(),
16778
+ sound: boolean(),
16779
+ ttl: boolean(),
16780
+ bodyMaxLen: number().int().positive()
16781
+ });
16537
16782
  /**
16538
- * The delivery lifecycle status of a history row a straight read of the
16539
- * durable outbox row's own status (single source of truth):
16540
- * - `pending` — enqueued, in-flight or retrying with backoff
16541
- * - `sent` — delivered (terminal)
16542
- * - `dead` dead-lettered after exhausting retries / a permanent
16543
- * backend rejection / a deleted target (terminal; carries
16544
- * the failure `error`)
16545
- *
16546
- * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
16547
- * user dimension (quiet hours / snooze) and are additive when they land.
16783
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
16784
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
16785
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
16786
+ * the union is large and not meant for runtime validation here; the exported
16787
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
16548
16788
  */
16549
- var NcHistoryStatusSchema = _enum([
16550
- "pending",
16551
- "sent",
16552
- "dead"
16553
- ]);
16554
- /** The evaluated record kind a history row descends from (one per trigger). */
16555
- var NcHistoryRecordKindSchema = _enum([
16556
- "object-event",
16557
- "track-end",
16558
- "device-event",
16559
- "package-event"
16560
- ]);
16561
- /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16562
- var NcHistorySubjectSchema = object({
16563
- className: string(),
16564
- label: string().optional(),
16565
- confidence: number().optional(),
16566
- zones: array(string()),
16567
- timestamp: number()
16789
+ var ConfigSchemaPassthrough = unknown();
16790
+ var TargetKindSchema = object({
16791
+ kind: string(),
16792
+ label: string(),
16793
+ icon: string(),
16794
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
16795
+ addonId: string(),
16796
+ configSchema: ConfigSchemaPassthrough,
16797
+ supportsDiscovery: boolean(),
16798
+ caps: TargetKindCapsSchema
16568
16799
  });
16569
16800
  /**
16570
- * One delivery-history row. This is a read-only VIEW over the durable
16571
- * outbox row (single source of truth the same row the drain loop drives;
16572
- * NO second write path, so history can never drift from delivery state).
16573
- * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16574
- * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16575
- * (fire) / `updatedAt` (last transition), `status` + `error` are the
16576
- * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16577
- * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16578
- * P1 (admin scope only).
16801
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
16802
+ * (return a presence marker only) when serving `listTargets` never
16803
+ * round-trip a stored secret to the UI.
16579
16804
  */
16580
- var NcHistoryEntrySchema = object({
16581
- /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16805
+ var TargetSchema = object({
16582
16806
  id: string(),
16583
- ruleId: string(),
16584
- /** Rule name frozen at fire time (outlives a later rename / delete). */
16585
- ruleName: string(),
16586
- /** The rule urgency/trigger that produced this delivery. */
16587
- delivery: NcDeliverySchema,
16588
- targetId: string(),
16589
- deviceId: number(),
16590
- recordKind: NcHistoryRecordKindSchema,
16591
- /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16592
- recordId: string(),
16593
- /** Present for track-scoped deliveries (object-event / track-end). */
16594
- trackId: string().optional(),
16595
- status: NcHistoryStatusSchema,
16596
- /** Delivery attempts made so far. */
16597
- attempts: number().int(),
16598
- /** Fire time (outbox enqueue). */
16599
- createdAt: number(),
16600
- /** Last transition time (terminal for sent / dead). */
16601
- updatedAt: number(),
16602
- /** Failure detail — present on a `dead` row. */
16603
- error: string().optional(),
16604
- subject: NcHistorySubjectSchema
16807
+ name: string(),
16808
+ kind: string(),
16809
+ addonId: string(),
16810
+ enabled: boolean(),
16811
+ config: record(string(), unknown())
16605
16812
  });
16606
- /**
16607
- * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16608
- * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16609
- * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16610
- * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16611
- */
16612
- var NcHistoryFilterSchema = object({
16613
- ruleId: string().optional(),
16614
- deviceId: number().optional(),
16615
- status: NcHistoryStatusSchema.optional(),
16616
- since: number().optional(),
16617
- until: number().optional(),
16618
- limit: number().int().min(1).max(500).default(100)
16813
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
16814
+ var DiscoveredTargetSchema = object({
16815
+ kind: string(),
16816
+ suggestedName: string(),
16817
+ config: record(string(), unknown())
16619
16818
  });
16620
- method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), method(object({ ruleId: string() }), object({ rule: NcRuleSchema.nullable() }), { auth: "admin" }), method(object({ rule: NcRuleInputSchema }), object({ rule: NcRuleSchema }), {
16621
- kind: "mutation",
16622
- auth: "admin",
16623
- caller: "required"
16624
- }), method(object({
16625
- ruleId: string(),
16626
- patch: NcRulePatchSchema
16627
- }), object({ rule: NcRuleSchema }), {
16628
- kind: "mutation",
16629
- auth: "admin",
16630
- caller: "required"
16631
- }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
16632
- kind: "mutation",
16633
- auth: "admin"
16634
- }), method(object({
16635
- ruleId: string(),
16819
+ /** The degrade engine's report what was resolved / dropped / degraded. */
16820
+ var RenderedAsSchema = object({
16821
+ level: string(),
16822
+ format: NotificationFormatSchema,
16823
+ attachmentsSent: number().int().nonnegative(),
16824
+ actionsSent: number().int().nonnegative(),
16825
+ truncated: boolean(),
16826
+ dropped: array(string())
16827
+ });
16828
+ var SendResultSchema = object({
16829
+ success: boolean(),
16830
+ error: string().optional(),
16831
+ renderedAs: RenderedAsSchema.optional()
16832
+ });
16833
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
16834
+ var TestResultSchema = SendResultSchema;
16835
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
16836
+ kind: string(),
16837
+ config: record(string(), unknown()).optional()
16838
+ }), array(DiscoveredTargetSchema)), method(object({
16839
+ targetId: string(),
16840
+ notification: NotificationSchema
16841
+ }), SendResultSchema, { kind: "mutation" }), method(object({
16842
+ targetId: string(),
16843
+ sample: NotificationSchema.optional()
16844
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
16845
+ targetId: string(),
16636
16846
  enabled: boolean()
16637
- }), object({ success: literal(true) }), {
16638
- kind: "mutation",
16639
- auth: "admin"
16640
- }), method(object({
16641
- rule: NcRuleInputSchema,
16642
- lookbackMinutes: number().int().min(1).max(1440).default(60)
16643
- }), object({ results: array(NcTestResultSchema) }), {
16644
- kind: "mutation",
16645
- auth: "admin"
16646
- }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
16847
+ }), _void(), { kind: "mutation" });
16647
16848
  /**
16648
16849
  * Zod schemas for persisted record types.
16649
16850
  *
@@ -21648,6 +21849,12 @@ Object.freeze({
21648
21849
  addonId: null,
21649
21850
  access: "delete"
21650
21851
  },
21852
+ "backup.deleteSchedule": {
21853
+ capName: "backup",
21854
+ capScope: "system",
21855
+ addonId: null,
21856
+ access: "delete"
21857
+ },
21651
21858
  "backup.getEntries": {
21652
21859
  capName: "backup",
21653
21860
  capScope: "system",
@@ -21678,6 +21885,12 @@ Object.freeze({
21678
21885
  addonId: null,
21679
21886
  access: "view"
21680
21887
  },
21888
+ "backup.listSchedules": {
21889
+ capName: "backup",
21890
+ capScope: "system",
21891
+ addonId: null,
21892
+ access: "view"
21893
+ },
21681
21894
  "backup.previewSchedule": {
21682
21895
  capName: "backup",
21683
21896
  capScope: "system",
@@ -21702,6 +21915,12 @@ Object.freeze({
21702
21915
  addonId: null,
21703
21916
  access: "create"
21704
21917
  },
21918
+ "backup.upsertSchedule": {
21919
+ capName: "backup",
21920
+ capScope: "system",
21921
+ addonId: null,
21922
+ access: "create"
21923
+ },
21705
21924
  "battery.wakeForStream": {
21706
21925
  capName: "battery",
21707
21926
  capScope: "device",
@@ -25536,6 +25755,36 @@ Object.freeze({
25536
25755
  addonId: null,
25537
25756
  access: "create"
25538
25757
  },
25758
+ "terminalSession.close": {
25759
+ capName: "terminal-session",
25760
+ capScope: "system",
25761
+ addonId: null,
25762
+ access: "create"
25763
+ },
25764
+ "terminalSession.listProfiles": {
25765
+ capName: "terminal-session",
25766
+ capScope: "system",
25767
+ addonId: null,
25768
+ access: "view"
25769
+ },
25770
+ "terminalSession.listSessions": {
25771
+ capName: "terminal-session",
25772
+ capScope: "system",
25773
+ addonId: null,
25774
+ access: "view"
25775
+ },
25776
+ "terminalSession.openSession": {
25777
+ capName: "terminal-session",
25778
+ capScope: "system",
25779
+ addonId: null,
25780
+ access: "create"
25781
+ },
25782
+ "terminalSession.resize": {
25783
+ capName: "terminal-session",
25784
+ capScope: "system",
25785
+ addonId: null,
25786
+ access: "create"
25787
+ },
25539
25788
  "toast.onToast": {
25540
25789
  capName: "toast",
25541
25790
  capScope: "system",