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