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