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