@camstack/addon-decoder-nodeav 1.2.5 → 1.2.6

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