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