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