@camstack/addon-decoder-ffmpeg 1.2.5 → 1.2.6

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