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