@camstack/addon-model-studio 1.1.7 → 1.1.9

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.
@@ -6484,6 +6484,36 @@ var ProfileRtspEntrySchema = object({
6484
6484
  codec: string().optional(),
6485
6485
  resolution: CamStreamResolutionSchema.optional()
6486
6486
  });
6487
+ /**
6488
+ * Per-call node pinning for `ctx.api` capability calls.
6489
+ *
6490
+ * A capability call normally resolves to its DEFAULT provider — a `singleton`
6491
+ * cap resolves to the hub, a device-scoped cap to the device's owning node. To
6492
+ * query a SPECIFIC node's provider instead (e.g. a remote agent's own
6493
+ * in-process `platform-probe` hardware, which the hub cannot probe), pin the
6494
+ * call to that node.
6495
+ *
6496
+ * The nodeId rides OUT-OF-BAND in the tRPC call context (NOT in the validated
6497
+ * method args), so capability method signatures stay `nodeId`-free — node
6498
+ * targeting is a property of the CALL, not of the method. The transport lifts
6499
+ * it from `op.context` onto the `CapCallInput.nodeId` field (`ipcParentLink`),
6500
+ * and the hub parent's `onUnownedCall` passes it to the `CapRouteResolver`,
6501
+ * which classifies a pinned agent node as `agent-child-forward`
6502
+ * (`$agent-cap-fwd.forward` → the agent's in-process provider).
6503
+ *
6504
+ * Usage at a call site:
6505
+ *
6506
+ * await api.platformProbe.getCapabilities.query(undefined, nodePin(nodeId))
6507
+ */
6508
+ /** tRPC `op.context` key carrying a per-call node pin. */
6509
+ var CAP_NODE_PIN_CONTEXT_KEY = "__camstackNodePin";
6510
+ /**
6511
+ * Build the tRPC request options that pin a single capability call to `nodeId`.
6512
+ * Pass as the second argument to `.query(input, …)` / `.mutate(input, …)`.
6513
+ */
6514
+ function nodePin(nodeId) {
6515
+ return { context: { [CAP_NODE_PIN_CONTEXT_KEY]: nodeId } };
6516
+ }
6487
6517
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
6488
6518
  DeviceType["Camera"] = "camera";
6489
6519
  DeviceType["Hub"] = "hub";
@@ -7669,36 +7699,6 @@ var EncodeProfileSchema = object({
7669
7699
  */
7670
7700
  outputArgs: array(string()).optional()
7671
7701
  });
7672
- /**
7673
- * Per-call node pinning for `ctx.api` capability calls.
7674
- *
7675
- * A capability call normally resolves to its DEFAULT provider — a `singleton`
7676
- * cap resolves to the hub, a device-scoped cap to the device's owning node. To
7677
- * query a SPECIFIC node's provider instead (e.g. a remote agent's own
7678
- * in-process `platform-probe` hardware, which the hub cannot probe), pin the
7679
- * call to that node.
7680
- *
7681
- * The nodeId rides OUT-OF-BAND in the tRPC call context (NOT in the validated
7682
- * method args), so capability method signatures stay `nodeId`-free — node
7683
- * targeting is a property of the CALL, not of the method. The transport lifts
7684
- * it from `op.context` onto the `CapCallInput.nodeId` field (`ipcParentLink`),
7685
- * and the hub parent's `onUnownedCall` passes it to the `CapRouteResolver`,
7686
- * which classifies a pinned agent node as `agent-child-forward`
7687
- * (`$agent-cap-fwd.forward` → the agent's in-process provider).
7688
- *
7689
- * Usage at a call site:
7690
- *
7691
- * await api.platformProbe.getCapabilities.query(undefined, nodePin(nodeId))
7692
- */
7693
- /** tRPC `op.context` key carrying a per-call node pin. */
7694
- var CAP_NODE_PIN_CONTEXT_KEY = "__camstackNodePin";
7695
- /**
7696
- * Build the tRPC request options that pin a single capability call to `nodeId`.
7697
- * Pass as the second argument to `.query(input, …)` / `.mutate(input, …)`.
7698
- */
7699
- function nodePin(nodeId) {
7700
- return { context: { [CAP_NODE_PIN_CONTEXT_KEY]: nodeId } };
7701
- }
7702
7702
  var COCO_TO_MACRO = {
7703
7703
  mapping: {
7704
7704
  person: "person",
@@ -8926,530 +8926,1168 @@ var AccessoryKind = {
8926
8926
  AccessoryKind.Siren, AccessoryKind.Floodlight, AccessoryKind.Spotlight, AccessoryKind.PirSensor, AccessoryKind.Chime, AccessoryKind.Autotrack, AccessoryKind.Nightvision, AccessoryKind.PrivacyMask;
8927
8927
  DeviceFeature.BatteryOperated;
8928
8928
  /**
8929
- * Generic device-level status snapshot. Auto-registered by `BaseDevice`
8930
- * for every device, regardless of provider the kernel needs a uniform
8931
- * cap-keyed slice for the basic device flags every consumer expects to
8932
- * read across processes (the `online` flag in particular). Driver-specific
8933
- * caps (`battery`, `doorbell`, …) carry their domain-specific state on
8934
- * their own slices.
8929
+ * Shared geometry vocabulary for on-frame shape caps — privacy-mask,
8930
+ * motion-zones, and the detection zones/lines editor all speak this one
8931
+ * language so a single drawing-plane editor and the providers stay
8932
+ * decoupled from each cap's storage.
8935
8933
  *
8936
- * Pattern is identical to `battery`: schema-bearing `runtimeState`,
8937
- * empty `methods`, single change event. Reads land at
8938
- * `runtimeState.getCapState('device-status')`; writes at
8939
- * `runtimeState.setCapState('device-status', …)`. Cross-process
8940
- * consumers reach the same data via the `device-state` cap router
8941
- * (`getCapSlice({deviceId, capName: 'device-status'})`).
8934
+ * All coordinates are normalized 0..1 of the camera frame (top-left
8935
+ * origin). Each cap composes the SUBSET of shape kinds it supports and
8936
+ * advertises it via `supportedShapes` in its `getOptions`.
8942
8937
  */
8943
- var DeviceStatusSchema = object({
8944
- /**
8945
- * Device-level liveness. Drivers flip via `markOnline(boolean)` on
8946
- * `BaseDevice`. Provider semantics vary — RTSP aggregates broker
8947
- * stream-health, Reolink reads firmware push events, ONVIF tracks
8948
- * ping responses. This cap intentionally does NOT prescribe which
8949
- * signal drives the flag.
8950
- */
8951
- online: boolean(),
8952
- /** Ms epoch of the last `online` transition. Lets consumers tell
8953
- * apart "just came online" from "still online". */
8954
- lastChangedAt: number()
8938
+ /** A normalized 0..1 point (top-left origin). */
8939
+ var MaskPointSchema = object({
8940
+ x: number(),
8941
+ y: number()
8955
8942
  });
8956
- object({
8957
- deviceId: number(),
8958
- status: DeviceStatusSchema
8943
+ /** Axis-aligned rectangle (normalized 0..1). */
8944
+ var MaskRectShapeSchema = object({
8945
+ kind: literal("rect"),
8946
+ x: number(),
8947
+ y: number(),
8948
+ width: number(),
8949
+ height: number()
8959
8950
  });
8960
- /**
8961
- * Per-device feature/identity probe slice. Holds the runtime-resolved
8962
- * truth about what a device CAN do — which the kernel uses to:
8963
- * 1. Reconcile accessory children (hub-children spawn siren/floodlight/PIR
8964
- * based on what the firmware actually advertises).
8965
- * 2. Compute the public `features: DeviceFeature[]` array surfaced via
8966
- * `device-manager.listAll`.
8967
- * 3. Decide which optional caps (PTZ, intercom, doorbell, battery, …)
8968
- * to register on the device's capability surface.
8969
- *
8970
- * Auto-registered by `BaseDevice` for every device. Drivers populate the
8971
- * slice from `onProbe()` (kernel calls it once after register, before
8972
- * accessory reconciliation). Consumers read via:
8973
- * `runtimeState.getCapState<FeatureProbeStatus>('feature-probe')`
8974
- *
8975
- * `flags` is an open record so each driver carries its own keys without
8976
- * a centralized schema bottleneck — Reolink writes `hasPtz/hasIntercom`,
8977
- * Hikvision writes `hasSupplementalLight/hasAlarmIo`, etc.
8978
- *
8979
- * Replaces the older driver-local `deviceCache.has*` blob: the per-device
8980
- * config is for operator-edited overrides + UI snapshots; runtime probe
8981
- * results belong in runtime-state where the kernel handles persistence,
8982
- * cross-process mirroring, and reactive updates.
8983
- */
8984
- var FeatureProbeStatusSchema = object({
8985
- /**
8986
- * Driver-specific flag bag. Each driver picks its own key names — the
8987
- * cap deliberately does NOT enforce a closed enum here. Reolink keys:
8988
- * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,
8989
- * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:
8990
- * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.
8991
- */
8992
- flags: record(string(), unknown()),
8993
- /**
8994
- * Coarse driver-classification — lets cross-process consumers tell apart
8995
- * cameras / battery-cams / NVRs without re-running the probe. `null`
8996
- * before the first probe completes.
8997
- */
8998
- deviceType: string().nullable(),
8999
- /** Camera/firmware model string. `null` when the firmware doesn't expose it. */
9000
- model: string().nullable(),
9001
- /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */
9002
- channelCount: number().nullable(),
9003
- /**
9004
- * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe
9005
- * completes — drivers' `getAccessoryChildren()` should treat zero as
9006
- * "probe not done yet, return empty" so accessories aren't spawned
9007
- * before the firmware is queried.
9008
- */
9009
- lastProbedAt: number(),
9010
- /**
9011
- * Framework convention: every runtime-state slice carries this for the
9012
- * createRuntimeStateBridge stale-check helper. We keep it in sync with
9013
- * `lastProbedAt` on every write.
9014
- */
9015
- lastFetchedAt: number()
8951
+ /** Free polygon — an ordered list of normalized vertices (≥3). */
8952
+ var MaskPolygonShapeSchema = object({
8953
+ kind: literal("polygon"),
8954
+ points: array(MaskPointSchema)
9016
8955
  });
9017
- object({
9018
- deviceId: number(),
9019
- status: FeatureProbeStatusSchema
8956
+ /** Boolean cell grid — row-major, length === gridWidth*gridHeight. */
8957
+ var MaskGridShapeSchema = object({
8958
+ kind: literal("grid"),
8959
+ gridWidth: number(),
8960
+ gridHeight: number(),
8961
+ cells: array(boolean())
9020
8962
  });
9021
- object({
9022
- /** Carbon dioxide concentration in ppm. */
9023
- co2Ppm: number().min(0).optional(),
9024
- /** Total volatile organic compounds in ppb. */
9025
- vocPpb: number().min(0).optional(),
9026
- /** Particulate matter ≤ 2.5 μm in µg/m³. */
9027
- pm25: number().min(0).optional(),
9028
- /** Particulate matter ≤ 10 μm in µg/m³. */
9029
- pm10: number().min(0).optional(),
9030
- /** Composite AQI value (typically 0..500). */
9031
- aqi: number().optional(),
9032
- /** Ms epoch when the slice was last updated. */
9033
- lastFetchedAt: number(),
9034
- /** Live display unit of the single metric this slice carries (e.g. HA
9035
- * `attributes.unit_of_measurement` → 'ppm' / 'ppb' / 'µg/m³'). Each
9036
- * upstream `sensor.*` entity surfaces ONE device_class, so one unit
9037
- * per slice is unambiguous. */
9038
- unit: string().optional(),
9039
- /** Suggested decimal places for numeric display.
9040
- * Populated live from the upstream source when provided (e.g. HA
9041
- * `attributes.suggested_display_precision`). Falls back to
9042
- * auto-formatting when absent. */
9043
- precision: number().int().min(0).max(10).optional()
8963
+ discriminatedUnion("kind", [
8964
+ MaskRectShapeSchema,
8965
+ MaskPolygonShapeSchema,
8966
+ MaskGridShapeSchema,
8967
+ object({
8968
+ kind: literal("line"),
8969
+ points: array(MaskPointSchema)
8970
+ })
8971
+ ]);
8972
+ /** Every shape-kind discriminant, for `supportedShapes` advertisement. */
8973
+ var MaskShapeKindSchema = _enum([
8974
+ "rect",
8975
+ "polygon",
8976
+ "grid",
8977
+ "line"
8978
+ ]);
8979
+ /** Polygon vertex bounds when a cap supports 'polygon' (e.g. Hikvision {min:4,max:4}). */
8980
+ var MaskPolygonVerticesSchema = object({
8981
+ min: number(),
8982
+ max: number()
8983
+ });
8984
+ /** Grid dimensions when a cap supports 'grid'. */
8985
+ var MaskGridDimsSchema = object({
8986
+ width: number(),
8987
+ height: number()
9044
8988
  });
9045
- DeviceType.Sensor;
9046
8989
  /**
9047
- * Alarm-panel cap. Models HA `alarm_control_panel.*` on
9048
- * `DeviceType.AlarmPanel`. State follows HA's canonical lifecycle
9049
- * across disarmed / armed_(home|away|night|vacation|custom_bypass) /
9050
- * arming / pending / triggered / disarming.
8990
+ * notification-rules the Notification Center rule surface (P1 core).
9051
8991
  *
9052
- * Many panels require a PIN code on arm / disarm — the optional
9053
- * `code` field on the methods passes it through to the upstream
9054
- * service; it's NEVER persisted in the runtime slice or any event
9055
- * payload. The presence of a required code is signalled by
9056
- * `DeviceFeature.AlarmPinRequired` so the UI gates a code-entry
9057
- * field without a slice fetch.
8992
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
8993
+ * (operator decisions D-1/D-2/D-3 are binding):
9058
8994
  *
9059
- * `availableModes` mirrors HA's `supported_features`-derived arm
9060
- * mode list the UI renders only the buttons the panel accepts.
9061
- */
9062
- var AlarmStateSchema = _enum([
9063
- "disarmed",
9064
- "armed_home",
9065
- "armed_away",
9066
- "armed_night",
9067
- "armed_vacation",
9068
- "armed_custom_bypass",
9069
- "arming",
9070
- "disarming",
9071
- "pending",
9072
- "triggered"
9073
- ]);
9074
- var AlarmArmModeSchema = _enum([
9075
- "home",
9076
- "away",
9077
- "night",
9078
- "vacation",
9079
- "custom_bypass"
9080
- ]);
9081
- object({
9082
- /** Current lifecycle state. */
9083
- state: AlarmStateSchema,
9084
- /** Subset of arm modes the panel accepts. UI renders one button per
9085
- * mode in this list. */
9086
- availableModes: array(AlarmArmModeSchema),
9087
- /** Whether the panel requires a PIN on arm / disarm. Mirrors
9088
- * `DeviceFeature.AlarmPinRequired` for slice consumers. */
9089
- requiresCode: boolean(),
9090
- /** Ms epoch when the slice was last updated. */
9091
- lastChangedAt: number()
9092
- });
9093
- DeviceType.AlarmPanel, method(object({
9094
- deviceId: number().int().nonnegative(),
9095
- mode: AlarmArmModeSchema,
9096
- /** Optional PIN code. Required when `requiresCode === true`.
9097
- * Passed through to the upstream service; never persisted. */
9098
- code: string().min(1).optional()
9099
- }), _void(), {
9100
- kind: "mutation",
9101
- auth: "admin"
9102
- }), method(object({
9103
- deviceId: number().int().nonnegative(),
9104
- code: string().min(1).optional()
9105
- }), _void(), {
9106
- kind: "mutation",
9107
- auth: "admin"
9108
- }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
9109
- kind: "mutation",
9110
- auth: "admin"
9111
- });
9112
- object({
9113
- /** Current illuminance in lux (lx). */
9114
- lux: number().min(0),
9115
- /** Ms epoch when the slice was last updated. */
9116
- lastFetchedAt: number(),
9117
- /** Live display unit from the upstream source (e.g. HA
9118
- * `attributes.unit_of_measurement`). The UI prefers this over the
9119
- * role's canonical unit. Absent → fall back to the canonical unit. */
9120
- unit: string().optional(),
9121
- /** Suggested decimal places for numeric display.
9122
- * Populated live from the upstream source when provided (e.g. HA
9123
- * `attributes.suggested_display_precision`). Falls back to
9124
- * auto-formatting when absent. */
9125
- precision: number().int().min(0).max(10).optional()
9126
- });
9127
- DeviceType.Sensor;
9128
- /**
9129
- * Per-class audio metrics aggregated over a sliding window.
8995
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
8996
+ * `notification-center` module), hooked on the durable persistence
8997
+ * moments (object-event insert, TrackCloser.closeExpired) with a
8998
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
8999
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
9000
+ * FIRST persisted detection matching the conditions (per-track dedup,
9001
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
9002
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
9003
+ * - DISPATCH stays behind `notification-output` (rules reference targets
9004
+ * by id; per-backend params are a passthrough blob capped by the
9005
+ * target kind's own caps/degrade engine).
9006
+ *
9007
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
9008
+ * server-injected caller identity — the first `caller: 'required'`
9009
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
9010
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
9011
+ * windows, and the optional label/identity/plate matchers. User rules,
9012
+ * private zones, per-recipient fan-out and the wider condition table are
9013
+ * P2+ (see spec §7).
9014
+ *
9015
+ * All schemas here are the single source of truth — `NcRule` etc. are
9016
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
9017
+ * schema/interface drift is explicitly not repeated).
9130
9018
  */
9131
- var AudioClassSummarySchema = object({
9132
- className: string(),
9133
- /** Number of windows (chunks) where this class was the top hit. */
9134
- hits: number().int().nonnegative(),
9135
- /** Mean score across those hits, clamped to [0,1]. */
9136
- avgScore: number().min(0).max(1),
9137
- /** Peak score in the window. */
9138
- peakScore: number().min(0).max(1)
9139
- });
9140
9019
  /**
9141
- * Per-camera audio metrics snapshotemitted by the analytics frame
9142
- * handler on every `pipeline.audio-inference-result` event and
9143
- * mirrored into the `audio-metrics` device-state slice. Symmetric
9144
- * with `zone-analytics` snapshots for video — every consumer
9145
- * (admin UI panel, automations, alert rules) reads via the
9146
- * canonical `device.state.audioMetrics.value` reactive handle.
9020
+ * D-3: the trigger/urgency of a rule which persistence moment evaluates it.
9021
+ * The value maps 1:1 onto the evaluated record kind:
9022
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
9023
+ * - `track-end` TrackCloser.closeExpired (finalized track record)
9024
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
9025
+ * change of a LINKED device, one row per linked camera)
9026
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
9027
+ * delivery / pick-up)
9147
9028
  *
9148
- * Aggregates are computed over a rolling `windowSec` window
9149
- * (default 60s). Past that window, classes drop out of `byClass`
9150
- * and the level history shifts forward.
9029
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
9030
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
9031
+ * this one field keeps the schema additive a rule still declares exactly
9032
+ * one trigger.
9151
9033
  */
9152
- var AudioMetricsSnapshotSchema = object({
9153
- /** Wall-clock timestamp (ms) of the most recent audio window. */
9154
- ts: number().int(),
9155
- /** Sliding-window length (seconds) used for aggregation. */
9156
- windowSec: number().int().positive(),
9157
- /** Latest level reading from the most recent window. */
9158
- level: object({
9159
- rms: number(),
9160
- dbfs: number()
9161
- }),
9162
- /** Peak dBFS observed across the rolling window. */
9163
- peakDbfs: number(),
9164
- /** Mean dBFS across the rolling window. */
9165
- avgDbfs: number(),
9166
- /** Most recent above-threshold classification, or null on silence. */
9167
- current: object({
9168
- className: string(),
9169
- score: number().min(0).max(1),
9170
- timestamp: number().int()
9171
- }).nullable(),
9172
- /** Per-class summary across the rolling window — keys are
9173
- * `macroClass` strings (e.g. `dog_bark`, `speech`, `glass_break`). */
9174
- byClass: array(AudioClassSummarySchema).readonly()
9034
+ var NcDeliverySchema = _enum([
9035
+ "immediate",
9036
+ "track-end",
9037
+ "device-event",
9038
+ "package-event"
9039
+ ]);
9040
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
9041
+ var NcScheduleSchema = object({
9042
+ windows: array(object({
9043
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
9044
+ days: array(number().int().min(0).max(6)).min(1),
9045
+ startMinute: number().int().min(0).max(1439),
9046
+ endMinute: number().int().min(0).max(1439)
9047
+ })).min(1),
9048
+ /** IANA timezone; default = hub host timezone. */
9049
+ timezone: string().optional(),
9050
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
9051
+ invert: boolean().optional()
9052
+ });
9053
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
9054
+ var NcPlateMatcherSchema = object({
9055
+ values: array(string().min(1)).min(1),
9056
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
9057
+ maxDistance: number().int().min(0).max(3).default(1)
9175
9058
  });
9176
9059
  /**
9177
- * Audio-metrics history payload a series of `AudioMetricsHistoryPoint`
9178
- * samples capped at `maxPoints` (default 1024). When the requested
9179
- * `windowSec / sampleEveryMs` would exceed the cap, the provider
9180
- * subsamples by bucketed averaging and reports the effective sample
9181
- * spacing on `effectiveSampleEveryMs` so the UI can label the x-axis.
9060
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
9061
+ * occupancy edge for a device optionally narrowed to a single admin
9062
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
9063
+ * - `became-occupied` (default) count crossed 0 `count`
9064
+ * - `became-free` count crossed `count` below it
9065
+ * - `>=` / `<=` — count is at/over or at/under `count`
9066
+ * `sustainSeconds` requires the condition hold continuously that long
9067
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
9068
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
9069
+ * the condition never matches. Confirmed edge-state survives addon restarts
9070
+ * (declared SQLite collection, reseeded on boot).
9182
9071
  */
9183
- var AudioMetricsHistorySchema = object({
9184
- points: array(object({
9185
- /** Wall-clock ms when this sample was recorded. */
9186
- ts: number().int(),
9187
- /** Instantaneous dBFS level at sample time. `null` for windows where
9188
- * the source had no level reading (rare; happens at decode startup). */
9189
- dbfs: number().nullable(),
9190
- /** Rolling-window peak dBFS at sample time. Same window the live
9191
- * snapshot reports. */
9192
- peakDbfs: number(),
9193
- /** Rolling-window mean dBFS at sample time. */
9194
- avgDbfs: number(),
9195
- /** Dominant above-threshold class at sample time, or null on silence. */
9196
- topClass: string().nullable(),
9197
- /** Score of the dominant class (`null` whenever `topClass` is null). */
9198
- topScore: number().min(0).max(1).nullable()
9199
- })).readonly(),
9200
- /** Actual ms between adjacent samples after any subsampling. */
9201
- effectiveSampleEveryMs: number().int().positive(),
9202
- /** Wall-clock window covered by `points` (`points[N-1].ts - points[0].ts`),
9203
- * or `0` when there's fewer than 2 samples. */
9204
- windowMsActual: number().int().nonnegative()
9205
- });
9206
- DeviceType.Camera, method(object({ deviceId: number() }), AudioMetricsSnapshotSchema.nullable()), method(object({
9207
- deviceId: number(),
9208
- /** History window in seconds. Default 300 (5 minutes).
9209
- * Provider clamps to its retention cap if larger. */
9210
- windowSec: number().int().positive().optional(),
9211
- /** Target sample interval in ms. Default 1000 (1 sample/second).
9212
- * Provider clamps to natural sample rate if smaller, and
9213
- * bucket-averages when bigger than the requested window
9214
- * would produce more than `maxPoints` samples. */
9215
- sampleEveryMs: number().int().positive().optional()
9216
- }), AudioMetricsHistorySchema);
9217
- object({
9218
- /** Whether the automation is currently enabled. Disabled automations
9219
- * ignore their trigger block — manual `trigger` still works. */
9220
- enabled: boolean(),
9221
- /** Whether the automation is currently executing its action block. */
9222
- isRunning: boolean(),
9223
- /** Ms epoch of the last successful run. 0 when never run. */
9224
- lastTriggeredAt: number(),
9225
- /** Failure description from the last completed run. Null on success
9226
- * or when never run. */
9227
- lastError: string().nullable(),
9228
- /** Ms epoch when the slice was last updated. */
9229
- lastChangedAt: number()
9072
+ var NcOccupancyConditionSchema = object({
9073
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
9074
+ zoneId: string().optional(),
9075
+ /** Object class to count; absent = any class. */
9076
+ className: string().optional(),
9077
+ op: _enum([
9078
+ "became-occupied",
9079
+ "became-free",
9080
+ ">=",
9081
+ "<="
9082
+ ]).default("became-occupied"),
9083
+ count: number().int().min(0).default(1),
9084
+ sustainSeconds: number().int().min(0).max(3600).default(15)
9230
9085
  });
9231
- DeviceType.Automation, method(object({ deviceId: number().int().nonnegative() }), _void(), {
9232
- kind: "mutation",
9233
- auth: "admin"
9234
- }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
9235
- kind: "mutation",
9236
- auth: "admin"
9237
- }), method(object({
9238
- deviceId: number().int().nonnegative(),
9239
- /** When true, fires the action block while bypassing the
9240
- * automation's condition evaluation. Gated by
9241
- * `DeviceFeature.AutomationSkipCondition`. */
9242
- skipCondition: boolean().optional()
9243
- }), _void(), {
9244
- kind: "mutation",
9245
- auth: "admin"
9086
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
9087
+ var NcZoneConditionSchema = object({
9088
+ ids: array(string().min(1)).min(1),
9089
+ /** Quantifier over `ids` at least one / every one visited. */
9090
+ match: _enum(["any", "all"]).default("any")
9246
9091
  });
9247
9092
  /**
9248
- * Battery status snapshot. Emitted by providers whose device is
9249
- * battery-operated (cameras with `DeviceFeature.BatteryOperated`,
9250
- * future sensor/button accessories). Consumers build their own "low
9251
- * battery" alerting on top — the cap deliberately does NOT enforce a
9252
- * threshold.
9093
+ * The P1 condition set a flat AND of groups; absent group = pass;
9094
+ * membership lists are OR within the list (spec §2.3).
9253
9095
  */
9254
- var BatteryStatusSchema = object({
9255
- /** 0..100 inclusive. Firmware-reported. */
9256
- percentage: number().min(0).max(100),
9096
+ var NcConditionsSchema = object({
9097
+ /** Device scope — absent = all devices. */
9098
+ devices: array(number()).optional(),
9099
+ /** Detector class names (any overlap with the record's class set). */
9100
+ classes: array(string().min(1)).optional(),
9101
+ /** Veto classes — any overlap fails the rule. */
9102
+ classesExclude: array(string().min(1)).optional(),
9103
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
9104
+ minConfidence: number().min(0).max(1).optional(),
9105
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
9106
+ zones: NcZoneConditionSchema.optional(),
9107
+ /** Veto zones — any hit fails the rule. */
9108
+ zonesExclude: array(string().min(1)).optional(),
9257
9109
  /**
9258
- * Charging source. `'dc'` covers wall/USB adapters; `'solar'` is
9259
- * Reolink-specific for the Solar Panel 2 accessory (will become
9260
- * common on other battery cams). `'none'` means running on battery
9261
- * alone.
9110
+ * Exact (case-insensitive) match on the record's collapsed `label`
9111
+ * (identity name / plate text / subclass).
9262
9112
  */
9263
- charging: _enum([
9264
- "dc",
9265
- "solar",
9266
- "none"
9267
- ]),
9113
+ labelEquals: array(string().min(1)).optional(),
9268
9114
  /**
9269
- * True when the camera firmware has gone into low-power mode. Battery
9270
- * providers MUST avoid polling during sleep reading the battery
9271
- * wakes the camera up and drains charge.
9115
+ * Identity matcher. P1 boundary: matched against the record's collapsed
9116
+ * `label` (the identity display name propagated by the face pipeline) —
9117
+ * identity-ID matching rides in P2 when identity ids reach the record.
9272
9118
  */
9273
- sleeping: boolean(),
9274
- /** Ms epoch of the last observation. Lets consumers reason about freshness. */
9275
- lastUpdated: number(),
9119
+ identities: array(string().min(1)).optional(),
9120
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
9121
+ plates: NcPlateMatcherSchema.optional(),
9276
9122
  /**
9277
- * True when the source is a BINARY low-battery indicator (HA
9278
- * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
9279
- * charge level `percentage` is then a coarse stand-in (100 = normal,
9280
- * sub-threshold = low). UI MUST render "Normal"/"Low" instead of a
9281
- * misleading exact percentage. Absent/false → genuine 0–100 % reading.
9123
+ * Identity EXCLUDE mirror of {@link identities} with `notIn` semantics.
9124
+ * Same P1 boundary: matched against the record's collapsed `label` (the
9125
+ * identity display name). A record with NO label passes (nothing to
9126
+ * exclude), unlike the include variant which fails on an absent label.
9282
9127
  */
9283
- binary: boolean().optional()
9284
- });
9285
- DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch, method(object({
9286
- deviceId: number(),
9287
- /** Bound on the wait. Sensible range 3000–10000ms. */
9288
- timeoutMs: number().int().min(500).max(3e4).default(8e3)
9289
- }), object({
9290
- awoke: boolean(),
9291
- durationMs: number()
9292
- }), { kind: "mutation" }), object({
9293
- deviceId: number(),
9294
- status: BatteryStatusSchema
9295
- });
9296
- object({
9297
- on: boolean(),
9298
- /** Ms epoch of the last transition. 0 if never observed. */
9299
- lastChangedAt: number()
9300
- });
9301
- DeviceType.Sensor;
9302
- object({
9303
- /** Current level as 0..100 inclusive. Firmware-reported. */
9304
- percentage: number().min(0).max(100),
9305
- /** Ms epoch of the last operator-driven change. Useful for UI freshness. */
9306
- lastChangedAt: number()
9307
- });
9308
- DeviceType.Light, method(object({
9309
- deviceId: number().int().nonnegative(),
9310
- percentage: number().min(0).max(100)
9311
- }), _void(), {
9312
- kind: "mutation",
9313
- auth: "admin"
9314
- }), object({
9315
- deviceId: number(),
9316
- percentage: number().min(0).max(100),
9317
- lastChangedAt: number()
9318
- });
9319
- /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
9320
- var StreamFormatSchema = _enum([
9321
- "webrtc",
9322
- "hls",
9323
- "mjpeg",
9324
- "rtsp"
9325
- ]);
9326
- var RtspRestreamEntrySchema = object({
9327
- brokerId: string(),
9328
- url: string(),
9329
- mutedUrl: string(),
9330
- enabled: boolean(),
9128
+ identitiesExclude: array(string().min(1)).optional(),
9331
9129
  /**
9332
- * Source-stream codec / resolution for the camStream this entry serves
9333
- * (the broker's "high"/"mid"/"low" profile slot for this device).
9334
- * Used by exporter pickers (`pickPreferredRtspEntry`) to resolve
9335
- * `streamPreference: 'auto'` to the slot whose source is closest to
9336
- * the consumer's target Alexa wants ~720p, HomeKit wants ~1080p,
9337
- * and there's no point dialling the 4K slot for an Echo Show. Absent
9338
- * when the source publisher never advertised the field; pickers fall
9339
- * back to first-enabled in that case.
9130
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
9131
+ * TRACK-END only: importance is scored at track close, so it does not exist
9132
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
9133
+ * close the value is threaded via the close-time info (the `Track` clone is
9134
+ * captured before the DB row is updated, so it would otherwise read stale).
9135
+ * Fails when the record carries no importance (never guess quality the
9136
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
9340
9137
  */
9341
- codec: string().optional(),
9342
- resolution: object({
9343
- width: number().int().positive(),
9344
- height: number().int().positive()
9345
- }).optional()
9346
- });
9347
- var BrokerRtspClientSchema = object({
9348
- sessionId: string(),
9349
- remoteAddr: string(),
9350
- /** Client `User-Agent` (e.g. `recorder` for the recorder's RTSP pull), or
9351
- * null/absent when the client sent none. Lets the UI label a consumer by
9352
- * purpose. Optional so a client built against an older schema stays valid. */
9353
- userAgent: string().nullish(),
9354
- playing: boolean(),
9355
- muted: boolean(),
9356
- connectedAt: number(),
9357
- lastRtpAt: number(),
9358
- bytesSent: number()
9359
- });
9360
- var BrokerDecodedClientSchema = object({
9361
- tag: string(),
9362
- subscribedAt: number(),
9363
- maxFps: number(),
9364
- framesDelivered: number(),
9365
- framesDropped: number()
9366
- });
9367
- var BrokerAudioClientSchema = object({
9368
- tag: string(),
9369
- subscribedAt: number(),
9370
- chunksDelivered: number()
9371
- });
9372
- var BrokerConsumerAttributionSchema = object({
9373
- kind: _enum([
9374
- "alexa",
9375
- "homekit",
9376
- "webrtc-browser",
9377
- "webrtc-mobile",
9378
- "webrtc-whep",
9379
- "rtsp-listen",
9380
- "derived-broker",
9381
- "recording",
9382
- "pipeline",
9383
- "snapshot",
9384
- "warmup",
9385
- "unknown"
9386
- ]),
9138
+ minImportance: number().min(0).max(1).optional(),
9387
9139
  /**
9388
- * Free-form label intended to disambiguate consumers OF THE SAME kind
9389
- * on the same broker e.g. user name, device alias. Should NOT repeat
9390
- * the kind / cam / cam-stream / sessionId (those are surfaced by
9391
- * dedicated fields). When empty the widget falls back to `${kind} ·
9392
- * <sessionId tail>`.
9140
+ * Minimum track dwell in SECONDS `(lastSeen firstSeen) / 1000`.
9141
+ * TRACK-END only: an `immediate` / object-event subject has no closed
9142
+ * lifespan, so a dwell condition never matches immediate delivery
9143
+ * (documented choice the object-event record carries no `firstSeen`,
9144
+ * so dwell cannot be computed from what the subject actually carries).
9393
9145
  */
9394
- label: string().optional(),
9146
+ minDwellSeconds: number().min(0).optional(),
9395
9147
  /**
9396
- * Which part of the encoded plane this subscription consumes:
9397
- * - `'audio'` audio packets only
9398
- * - `'video'` video packets only
9399
- * - `'both'` — both video + audio (typical for AnnexB push paths
9400
- * that don't split the source RTP)
9401
- *
9402
- * Missing field means "unknown" — older callers and the legacy
9403
- * paths that haven't been migrated yet.
9148
+ * Detection provenance filter. `any` (default / absent) matches every
9149
+ * source; otherwise the subject's source must equal it. Legacy records
9150
+ * with no stamped source are treated as `pipeline`. The union spans both
9151
+ * record kinds object events carry `pipeline` | `onboard`, synthetic
9152
+ * tracks carry `sensor`.
9404
9153
  */
9405
- media: _enum([
9406
- "audio",
9407
- "video",
9408
- "both"
9154
+ source: _enum([
9155
+ "pipeline",
9156
+ "onboard",
9157
+ "sensor",
9158
+ "any"
9409
9159
  ]).optional(),
9410
9160
  /**
9411
- * Codec the consumer receives AFTER any per-session re-encoding. For
9412
- * a WebRTC session this is the negotiated egress codec (e.g. `H264`,
9413
- * `H265`, `Opus`, `Pcmu`); for an RTSP restreamer it mirrors the
9414
- * source codec. Surfaced in the widget chip so operators see at a
9415
- * glance whether a viewer is on H.264 (Echo) or H.265 (Safari).
9161
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
9162
+ * detector `minConfidence` (that gates the object-detection score; this
9163
+ * gates the recognition/OCR match score). Fails when the subject carries
9164
+ * no label-match confidence (never guess). TRACK-END only: the confidence
9165
+ * lives on the recognition result and reaches the subject at track close.
9166
+ *
9167
+ * What it measures precisely (plumbed at track close — the closer threads
9168
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
9169
+ * `importance`): the BEST recognition match confidence observed for the
9170
+ * label the track carries at close — for a face, the peak cosine similarity
9171
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
9172
+ * for a plate, the peak OCR read score of the best-held plate
9173
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
9174
+ * one track the higher of the two is used. A track that ended with no
9175
+ * confident identity/plate match carries no value, so the condition fails
9176
+ * closed for it (an un-recognized subject).
9416
9177
  */
9417
- targetCodec: string().optional(),
9178
+ minLabelConfidence: number().min(0).max(1).optional(),
9418
9179
  /**
9419
- * Whether the broker is re-encoding for this consumer:
9420
- * - `'passthrough'` bytes flow source→consumer without ffmpeg
9421
- * - `'repacketize'` RTP payload is re-packetized but NOT re-encoded
9422
- * (preserves frames, just rebuilds headers; e.g.
9423
- * the H.265 repacketizer path)
9424
- * - `'transcode'` — a full encode/decode round (ffmpeg, libx264,
9425
- * libav…); the most expensive path
9180
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
9181
+ * e.g. a doorbell `press` / `press_long`) matched case-insensitively
9182
+ * against the token carried on the device-event subject (extracted from the
9183
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
9184
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
9185
+ * eventType, so gate those with {@link sensorKinds} instead.
9426
9186
  */
9427
- transport: _enum([
9428
- "passthrough",
9429
- "repacketize",
9430
- "transcode"
9431
- ]).optional(),
9432
- /** Remote peer IP if the consumer terminates a network socket. */
9433
- remoteAddr: string().optional(),
9187
+ eventTypeTokens: array(string().min(1)).optional(),
9434
9188
  /**
9435
- * Server-read User-Agent of the originating client; enriched by the hub
9436
- * from the tRPC request context (browser sessions).
9189
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
9190
+ * `contact`, `button`, `device-event`) matched against the persisted
9191
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
9437
9192
  */
9438
- userAgent: string().optional(),
9439
- /** Authenticated user id (CamStack OAuth subject) when known. */
9440
- userId: string().optional(),
9441
- /** Higher-level session identifier (Alexa Echo sessionId, HAP session, …). */
9442
- sessionId: string().optional(),
9443
- /** Free-form key/value extras (e.g. clientHints from a WebRTC offer). */
9444
- extra: record(string(), string()).optional()
9445
- }).readonly();
9446
- var BrokerEncodedClientSchema = object({
9447
- /** Stable id assigned on attach; used by `killClient`. */
9448
- id: string(),
9449
- /** Which broker fanout the subscriber rides — annexB encoded packets vs raw RTP. */
9450
- channel: _enum(["annexb", "rtp"]),
9451
- attribution: BrokerConsumerAttributionSchema,
9452
- subscribedAt: number(),
9193
+ sensorKinds: array(string().min(1)).optional(),
9194
+ /**
9195
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
9196
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
9197
+ * when the subject's phase does not match (a subject always carries a phase
9198
+ * on the package-event trigger).
9199
+ */
9200
+ packagePhase: _enum([
9201
+ "delivered",
9202
+ "picked-up",
9203
+ "both"
9204
+ ]).optional(),
9205
+ /**
9206
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
9207
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
9208
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
9209
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
9210
+ */
9211
+ customZones: array(MaskPolygonShapeSchema).optional(),
9212
+ /**
9213
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
9214
+ * (optionally zone/class-scoped) occupancy count crosses the configured
9215
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
9216
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
9217
+ */
9218
+ occupancy: NcOccupancyConditionSchema.optional()
9219
+ });
9220
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
9221
+ var NcRuleTargetSchema = object({
9222
+ /** `notification-output` Target id. */
9223
+ targetId: string().min(1),
9224
+ /**
9225
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
9226
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
9227
+ * degrade engine drops what the backend can't render.
9228
+ */
9229
+ params: record(string(), unknown()).optional()
9230
+ });
9231
+ /**
9232
+ * Media attachment policy (P1 still-image subset).
9233
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
9234
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
9235
+ * matched on identities attaches the subject's `faceCrop`, one matched on
9236
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
9237
+ * (or when the specific crop is missing) degrades to `best`, then
9238
+ * `keyFrame`, then no attachment — never delaying the send. The matched
9239
+ * condition summary is frozen on the outbox row at enqueue (like the rule
9240
+ * name), so the choice never drifts from the record that fired it.
9241
+ * - `keyFrame` — the clean scene frame (no subject box).
9242
+ * - `none` — no attachment.
9243
+ */
9244
+ var NcMediaPolicySchema = object({ attach: _enum([
9245
+ "best",
9246
+ "best-matching",
9247
+ "keyFrame",
9248
+ "none"
9249
+ ]).default("best") });
9250
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
9251
+ var NcThrottleSchema = object({
9252
+ cooldownSec: number().int().min(0).max(86400).default(60),
9253
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
9254
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
9255
+ });
9256
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
9257
+ var NcRuleInputSchema = object({
9258
+ name: string().min(1).max(200),
9259
+ enabled: boolean().default(true),
9260
+ delivery: NcDeliverySchema,
9261
+ conditions: NcConditionsSchema.default({}),
9262
+ schedule: NcScheduleSchema.optional(),
9263
+ targets: array(NcRuleTargetSchema).min(1),
9264
+ media: NcMediaPolicySchema.default({ attach: "best" }),
9265
+ throttle: NcThrottleSchema.default({
9266
+ cooldownSec: 60,
9267
+ scope: "rule-device"
9268
+ }),
9269
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
9270
+ template: object({
9271
+ title: string().max(500).optional(),
9272
+ body: string().max(2e3).optional()
9273
+ }).optional(),
9274
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
9275
+ priority: number().int().min(1).max(5).default(3),
9276
+ /**
9277
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
9278
+ * behaviour, visible to all, read-only in the viewer). Present = personal
9279
+ * rule owned by this userId. Server-stamped; never trusted from a client.
9280
+ */
9281
+ ownerUserId: string().optional()
9282
+ });
9283
+ /**
9284
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
9285
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
9286
+ * NOT a client-authored input field (it lives on the persisted rule, not the
9287
+ * input), so it is added here explicitly to let the store's per-target opt-out
9288
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
9289
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
9290
+ * `updateRule` patch.
9291
+ */
9292
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
9293
+ /** A persisted rule. */
9294
+ var NcRuleSchema = NcRuleInputSchema.extend({
9295
+ id: string(),
9296
+ /** userId of the admin who created the rule (server-stamped caller). */
9297
+ createdBy: string(),
9298
+ createdAt: number(),
9299
+ updatedAt: number(),
9300
+ /**
9301
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
9302
+ * send time. Only a target's OWNER may add/remove its id (server-checked
9303
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
9304
+ */
9305
+ disabledTargetIds: array(string()).default([])
9306
+ });
9307
+ var NcTestResultSchema = object({
9308
+ recordId: string(),
9309
+ recordKind: _enum([
9310
+ "object-event",
9311
+ "track",
9312
+ "device-event",
9313
+ "package-event"
9314
+ ]),
9315
+ deviceId: number(),
9316
+ timestamp: number(),
9317
+ wouldFire: boolean(),
9318
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
9319
+ failedCondition: string().optional(),
9320
+ className: string().optional(),
9321
+ label: string().optional()
9322
+ });
9323
+ var NcConditionDescriptorSchema = object({
9324
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
9325
+ id: string(),
9326
+ group: _enum([
9327
+ "scope",
9328
+ "class",
9329
+ "zones",
9330
+ "quality",
9331
+ "label",
9332
+ "schedule",
9333
+ "device",
9334
+ "package",
9335
+ "occupancy"
9336
+ ]),
9337
+ label: string(),
9338
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
9339
+ valueType: _enum([
9340
+ "deviceIdList",
9341
+ "stringList",
9342
+ "number01",
9343
+ "number",
9344
+ "sourceSelect",
9345
+ "zoneSelection",
9346
+ "zoneIdList",
9347
+ "schedule",
9348
+ "plateMatcher",
9349
+ "packagePhase",
9350
+ "polygonDraw",
9351
+ "occupancy"
9352
+ ]),
9353
+ operator: _enum([
9354
+ "in",
9355
+ "notIn",
9356
+ "anyOf",
9357
+ "allOf",
9358
+ "gte",
9359
+ "fuzzyIn",
9360
+ "withinSchedule"
9361
+ ]),
9362
+ /** Which delivery kinds the condition applies to. */
9363
+ appliesTo: array(NcDeliverySchema),
9364
+ phase: string(),
9365
+ description: string().optional()
9366
+ });
9367
+ /**
9368
+ * The delivery lifecycle status of a history row — a straight read of the
9369
+ * durable outbox row's own status (single source of truth):
9370
+ * - `pending` — enqueued, in-flight or retrying with backoff
9371
+ * - `sent` — delivered (terminal)
9372
+ * - `dead` — dead-lettered after exhausting retries / a permanent
9373
+ * backend rejection / a deleted target (terminal; carries
9374
+ * the failure `error`)
9375
+ *
9376
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
9377
+ * user dimension (quiet hours / snooze) and are additive when they land.
9378
+ */
9379
+ var NcHistoryStatusSchema = _enum([
9380
+ "pending",
9381
+ "sent",
9382
+ "dead"
9383
+ ]);
9384
+ /** The evaluated record kind a history row descends from (one per trigger). */
9385
+ var NcHistoryRecordKindSchema = _enum([
9386
+ "object-event",
9387
+ "track-end",
9388
+ "device-event",
9389
+ "package-event"
9390
+ ]);
9391
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
9392
+ var NcHistorySubjectSchema = object({
9393
+ className: string(),
9394
+ label: string().optional(),
9395
+ confidence: number().optional(),
9396
+ zones: array(string()),
9397
+ timestamp: number()
9398
+ });
9399
+ /**
9400
+ * One delivery-history row. This is a read-only VIEW over the durable
9401
+ * outbox row (single source of truth — the same row the drain loop drives;
9402
+ * NO second write path, so history can never drift from delivery state).
9403
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
9404
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
9405
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
9406
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
9407
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
9408
+ * P1 (admin scope only).
9409
+ */
9410
+ var NcHistoryEntrySchema = object({
9411
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
9412
+ id: string(),
9413
+ ruleId: string(),
9414
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
9415
+ ruleName: string(),
9416
+ /** The rule urgency/trigger that produced this delivery. */
9417
+ delivery: NcDeliverySchema,
9418
+ targetId: string(),
9419
+ deviceId: number(),
9420
+ recordKind: NcHistoryRecordKindSchema,
9421
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
9422
+ recordId: string(),
9423
+ /** Present for track-scoped deliveries (object-event / track-end). */
9424
+ trackId: string().optional(),
9425
+ status: NcHistoryStatusSchema,
9426
+ /** Delivery attempts made so far. */
9427
+ attempts: number().int(),
9428
+ /** Fire time (outbox enqueue). */
9429
+ createdAt: number(),
9430
+ /** Last transition time (terminal for sent / dead). */
9431
+ updatedAt: number(),
9432
+ /** Failure detail — present on a `dead` row. */
9433
+ error: string().optional(),
9434
+ subject: NcHistorySubjectSchema
9435
+ });
9436
+ /**
9437
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
9438
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
9439
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
9440
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
9441
+ */
9442
+ var NcHistoryFilterSchema = object({
9443
+ ruleId: string().optional(),
9444
+ deviceId: number().optional(),
9445
+ status: NcHistoryStatusSchema.optional(),
9446
+ since: number().optional(),
9447
+ until: number().optional(),
9448
+ limit: number().int().min(1).max(500).default(100)
9449
+ });
9450
+ 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 }), {
9451
+ kind: "mutation",
9452
+ auth: "admin",
9453
+ caller: "required"
9454
+ }), method(object({
9455
+ ruleId: string(),
9456
+ patch: NcRulePatchSchema
9457
+ }), object({ rule: NcRuleSchema }), {
9458
+ kind: "mutation",
9459
+ auth: "admin",
9460
+ caller: "required"
9461
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
9462
+ kind: "mutation",
9463
+ auth: "admin"
9464
+ }), method(object({
9465
+ ruleId: string(),
9466
+ enabled: boolean()
9467
+ }), object({ success: literal(true) }), {
9468
+ kind: "mutation",
9469
+ auth: "admin"
9470
+ }), method(object({
9471
+ rule: NcRuleInputSchema,
9472
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
9473
+ }), object({ results: array(NcTestResultSchema) }), {
9474
+ kind: "mutation",
9475
+ auth: "admin"
9476
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
9477
+ /**
9478
+ * TimelapseRule — the STANDALONE scheduled timelapse producer's rule model.
9479
+ *
9480
+ * Spec: `docs/superpowers/specs/2026-07-24-nc-occupancy-timelapse-design.md`
9481
+ * §3.2/§3.3.
9482
+ *
9483
+ * Deliberately NOT a capability definition and NOT an `NcRule`:
9484
+ * - Every `NcDelivery` member is a *persisted-pipeline-record* trigger. A
9485
+ * timelapse fires on a SCHEDULE WINDOW BOUNDARY, evaluates no pipeline
9486
+ * record, and produces a video it assembled itself — so it rides no
9487
+ * delivery-enum member (the enum is frozen) and no cap method. This file is
9488
+ * a plain typed schema; it does NOT go through `npm run codegen`.
9489
+ * - It shares only the delivery leg (`notification-output.send`) and the
9490
+ * persistence/ownership patterns with the Notification Center, reusing
9491
+ * {@link NcScheduleSchema} (weekly windows, midnight-crossing, invertible)
9492
+ * and {@link NcRuleTargetSchema} (target ref + passthrough params).
9493
+ *
9494
+ * Ownership is SERVER-DERIVED. `ownerUserId` / `createdBy` / `createdAt` /
9495
+ * `updatedAt` / `id` / `lastGeneratedAt` live on the PERSISTED rule only —
9496
+ * {@link TimelapseRuleInputSchema} and {@link TimelapseRulePatchSchema} do not
9497
+ * carry them, so a forged client payload can never claim or re-own a rule
9498
+ * (Zod strips unknown keys). The store stamps them from the resolved caller.
9499
+ */
9500
+ /** `{{var}}` templating over camera/rule/time — same vocabulary as `NcRule`. */
9501
+ var TimelapseTemplateSchema = object({
9502
+ title: string().max(500).optional(),
9503
+ body: string().max(2e3).optional()
9504
+ });
9505
+ var NameField = string().min(1).max(200);
9506
+ var DeviceIdsField = array(number()).min(1);
9507
+ var CadenceSecField = number().int().min(2).max(3600);
9508
+ var FramerateField = number().int().min(1).max(60);
9509
+ var TargetsField = array(NcRuleTargetSchema).min(1);
9510
+ var PriorityField = number().int().min(1).max(5);
9511
+ /**
9512
+ * Client-supplied timelapse-rule fields. The server stamps id / createdBy /
9513
+ * createdAt / updatedAt / ownerUserId / lastGeneratedAt — none of them appear
9514
+ * here (see the ownership note above).
9515
+ */
9516
+ var TimelapseRuleInputSchema = object({
9517
+ name: NameField,
9518
+ enabled: boolean().default(true),
9519
+ /** Cameras sampled by this rule — one scratch dir + one artifact per device. */
9520
+ deviceIds: DeviceIdsField,
9521
+ /**
9522
+ * Activation window(s). REQUIRED (unlike `NcRule`, where an absent schedule
9523
+ * means "always active"): a timelapse is defined by its window boundaries —
9524
+ * open clears the scratch, close assembles and delivers.
9525
+ */
9526
+ schedule: NcScheduleSchema,
9527
+ /** Force-snapshot cadence inside the window, seconds (predecessor parity). */
9528
+ cadenceSec: CadenceSecField.default(15),
9529
+ /** Output frames per second of the assembled mp4 (predecessor parity). */
9530
+ framerate: FramerateField.default(10),
9531
+ /** `notification-output` targets the finished video/thumbnail is sent to. */
9532
+ targets: TargetsField,
9533
+ template: TimelapseTemplateSchema.optional(),
9534
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
9535
+ priority: PriorityField.default(3)
9536
+ });
9537
+ object({
9538
+ name: NameField.optional(),
9539
+ enabled: boolean().optional(),
9540
+ deviceIds: DeviceIdsField.optional(),
9541
+ schedule: NcScheduleSchema.optional(),
9542
+ cadenceSec: CadenceSecField.optional(),
9543
+ framerate: FramerateField.optional(),
9544
+ targets: TargetsField.optional(),
9545
+ template: TimelapseTemplateSchema.nullable().optional(),
9546
+ priority: PriorityField.optional()
9547
+ });
9548
+ TimelapseRuleInputSchema.extend({
9549
+ id: string(),
9550
+ /**
9551
+ * Ownership/visibility key. Absent = admin/global rule (visible to all).
9552
+ * Present = personal rule owned by this userId. Server-stamped from the
9553
+ * resolved caller; never trusted from a client payload.
9554
+ */
9555
+ ownerUserId: string().optional(),
9556
+ /**
9557
+ * Epoch-ms of the last successful generation — the 1-hour re-generation
9558
+ * guard's durable state (predecessor parity). Absent = never generated.
9559
+ */
9560
+ lastGeneratedAt: number().optional(),
9561
+ /** userId of the caller who created the rule (server-stamped). */
9562
+ createdBy: string(),
9563
+ createdAt: number(),
9564
+ updatedAt: number()
9565
+ });
9566
+ /**
9567
+ * Generic device-level status snapshot. Auto-registered by `BaseDevice`
9568
+ * for every device, regardless of provider — the kernel needs a uniform
9569
+ * cap-keyed slice for the basic device flags every consumer expects to
9570
+ * read across processes (the `online` flag in particular). Driver-specific
9571
+ * caps (`battery`, `doorbell`, …) carry their domain-specific state on
9572
+ * their own slices.
9573
+ *
9574
+ * Pattern is identical to `battery`: schema-bearing `runtimeState`,
9575
+ * empty `methods`, single change event. Reads land at
9576
+ * `runtimeState.getCapState('device-status')`; writes at
9577
+ * `runtimeState.setCapState('device-status', …)`. Cross-process
9578
+ * consumers reach the same data via the `device-state` cap router
9579
+ * (`getCapSlice({deviceId, capName: 'device-status'})`).
9580
+ */
9581
+ var DeviceStatusSchema = object({
9582
+ /**
9583
+ * Device-level liveness. Drivers flip via `markOnline(boolean)` on
9584
+ * `BaseDevice`. Provider semantics vary — RTSP aggregates broker
9585
+ * stream-health, Reolink reads firmware push events, ONVIF tracks
9586
+ * ping responses. This cap intentionally does NOT prescribe which
9587
+ * signal drives the flag.
9588
+ */
9589
+ online: boolean(),
9590
+ /** Ms epoch of the last `online` transition. Lets consumers tell
9591
+ * apart "just came online" from "still online". */
9592
+ lastChangedAt: number()
9593
+ });
9594
+ object({
9595
+ deviceId: number(),
9596
+ status: DeviceStatusSchema
9597
+ });
9598
+ /**
9599
+ * Per-device feature/identity probe slice. Holds the runtime-resolved
9600
+ * truth about what a device CAN do — which the kernel uses to:
9601
+ * 1. Reconcile accessory children (hub-children spawn siren/floodlight/PIR
9602
+ * based on what the firmware actually advertises).
9603
+ * 2. Compute the public `features: DeviceFeature[]` array surfaced via
9604
+ * `device-manager.listAll`.
9605
+ * 3. Decide which optional caps (PTZ, intercom, doorbell, battery, …)
9606
+ * to register on the device's capability surface.
9607
+ *
9608
+ * Auto-registered by `BaseDevice` for every device. Drivers populate the
9609
+ * slice from `onProbe()` (kernel calls it once after register, before
9610
+ * accessory reconciliation). Consumers read via:
9611
+ * `runtimeState.getCapState<FeatureProbeStatus>('feature-probe')`
9612
+ *
9613
+ * `flags` is an open record so each driver carries its own keys without
9614
+ * a centralized schema bottleneck — Reolink writes `hasPtz/hasIntercom`,
9615
+ * Hikvision writes `hasSupplementalLight/hasAlarmIo`, etc.
9616
+ *
9617
+ * Replaces the older driver-local `deviceCache.has*` blob: the per-device
9618
+ * config is for operator-edited overrides + UI snapshots; runtime probe
9619
+ * results belong in runtime-state where the kernel handles persistence,
9620
+ * cross-process mirroring, and reactive updates.
9621
+ */
9622
+ var FeatureProbeStatusSchema = object({
9623
+ /**
9624
+ * Driver-specific flag bag. Each driver picks its own key names — the
9625
+ * cap deliberately does NOT enforce a closed enum here. Reolink keys:
9626
+ * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,
9627
+ * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:
9628
+ * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.
9629
+ */
9630
+ flags: record(string(), unknown()),
9631
+ /**
9632
+ * Coarse driver-classification — lets cross-process consumers tell apart
9633
+ * cameras / battery-cams / NVRs without re-running the probe. `null`
9634
+ * before the first probe completes.
9635
+ */
9636
+ deviceType: string().nullable(),
9637
+ /** Camera/firmware model string. `null` when the firmware doesn't expose it. */
9638
+ model: string().nullable(),
9639
+ /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */
9640
+ channelCount: number().nullable(),
9641
+ /**
9642
+ * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe
9643
+ * completes — drivers' `getAccessoryChildren()` should treat zero as
9644
+ * "probe not done yet, return empty" so accessories aren't spawned
9645
+ * before the firmware is queried.
9646
+ */
9647
+ lastProbedAt: number(),
9648
+ /**
9649
+ * Framework convention: every runtime-state slice carries this for the
9650
+ * createRuntimeStateBridge stale-check helper. We keep it in sync with
9651
+ * `lastProbedAt` on every write.
9652
+ */
9653
+ lastFetchedAt: number()
9654
+ });
9655
+ object({
9656
+ deviceId: number(),
9657
+ status: FeatureProbeStatusSchema
9658
+ });
9659
+ object({
9660
+ /** Carbon dioxide concentration in ppm. */
9661
+ co2Ppm: number().min(0).optional(),
9662
+ /** Total volatile organic compounds in ppb. */
9663
+ vocPpb: number().min(0).optional(),
9664
+ /** Particulate matter ≤ 2.5 μm in µg/m³. */
9665
+ pm25: number().min(0).optional(),
9666
+ /** Particulate matter ≤ 10 μm in µg/m³. */
9667
+ pm10: number().min(0).optional(),
9668
+ /** Composite AQI value (typically 0..500). */
9669
+ aqi: number().optional(),
9670
+ /** Ms epoch when the slice was last updated. */
9671
+ lastFetchedAt: number(),
9672
+ /** Live display unit of the single metric this slice carries (e.g. HA
9673
+ * `attributes.unit_of_measurement` → 'ppm' / 'ppb' / 'µg/m³'). Each
9674
+ * upstream `sensor.*` entity surfaces ONE device_class, so one unit
9675
+ * per slice is unambiguous. */
9676
+ unit: string().optional(),
9677
+ /** Suggested decimal places for numeric display.
9678
+ * Populated live from the upstream source when provided (e.g. HA
9679
+ * `attributes.suggested_display_precision`). Falls back to
9680
+ * auto-formatting when absent. */
9681
+ precision: number().int().min(0).max(10).optional()
9682
+ });
9683
+ DeviceType.Sensor;
9684
+ /**
9685
+ * Alarm-panel cap. Models HA `alarm_control_panel.*` on
9686
+ * `DeviceType.AlarmPanel`. State follows HA's canonical lifecycle
9687
+ * across disarmed / armed_(home|away|night|vacation|custom_bypass) /
9688
+ * arming / pending / triggered / disarming.
9689
+ *
9690
+ * Many panels require a PIN code on arm / disarm — the optional
9691
+ * `code` field on the methods passes it through to the upstream
9692
+ * service; it's NEVER persisted in the runtime slice or any event
9693
+ * payload. The presence of a required code is signalled by
9694
+ * `DeviceFeature.AlarmPinRequired` so the UI gates a code-entry
9695
+ * field without a slice fetch.
9696
+ *
9697
+ * `availableModes` mirrors HA's `supported_features`-derived arm
9698
+ * mode list — the UI renders only the buttons the panel accepts.
9699
+ */
9700
+ var AlarmStateSchema = _enum([
9701
+ "disarmed",
9702
+ "armed_home",
9703
+ "armed_away",
9704
+ "armed_night",
9705
+ "armed_vacation",
9706
+ "armed_custom_bypass",
9707
+ "arming",
9708
+ "disarming",
9709
+ "pending",
9710
+ "triggered"
9711
+ ]);
9712
+ var AlarmArmModeSchema = _enum([
9713
+ "home",
9714
+ "away",
9715
+ "night",
9716
+ "vacation",
9717
+ "custom_bypass"
9718
+ ]);
9719
+ object({
9720
+ /** Current lifecycle state. */
9721
+ state: AlarmStateSchema,
9722
+ /** Subset of arm modes the panel accepts. UI renders one button per
9723
+ * mode in this list. */
9724
+ availableModes: array(AlarmArmModeSchema),
9725
+ /** Whether the panel requires a PIN on arm / disarm. Mirrors
9726
+ * `DeviceFeature.AlarmPinRequired` for slice consumers. */
9727
+ requiresCode: boolean(),
9728
+ /** Ms epoch when the slice was last updated. */
9729
+ lastChangedAt: number()
9730
+ });
9731
+ DeviceType.AlarmPanel, method(object({
9732
+ deviceId: number().int().nonnegative(),
9733
+ mode: AlarmArmModeSchema,
9734
+ /** Optional PIN code. Required when `requiresCode === true`.
9735
+ * Passed through to the upstream service; never persisted. */
9736
+ code: string().min(1).optional()
9737
+ }), _void(), {
9738
+ kind: "mutation",
9739
+ auth: "admin"
9740
+ }), method(object({
9741
+ deviceId: number().int().nonnegative(),
9742
+ code: string().min(1).optional()
9743
+ }), _void(), {
9744
+ kind: "mutation",
9745
+ auth: "admin"
9746
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
9747
+ kind: "mutation",
9748
+ auth: "admin"
9749
+ });
9750
+ object({
9751
+ /** Current illuminance in lux (lx). */
9752
+ lux: number().min(0),
9753
+ /** Ms epoch when the slice was last updated. */
9754
+ lastFetchedAt: number(),
9755
+ /** Live display unit from the upstream source (e.g. HA
9756
+ * `attributes.unit_of_measurement`). The UI prefers this over the
9757
+ * role's canonical unit. Absent → fall back to the canonical unit. */
9758
+ unit: string().optional(),
9759
+ /** Suggested decimal places for numeric display.
9760
+ * Populated live from the upstream source when provided (e.g. HA
9761
+ * `attributes.suggested_display_precision`). Falls back to
9762
+ * auto-formatting when absent. */
9763
+ precision: number().int().min(0).max(10).optional()
9764
+ });
9765
+ DeviceType.Sensor;
9766
+ /**
9767
+ * Per-class audio metrics aggregated over a sliding window.
9768
+ */
9769
+ var AudioClassSummarySchema = object({
9770
+ className: string(),
9771
+ /** Number of windows (chunks) where this class was the top hit. */
9772
+ hits: number().int().nonnegative(),
9773
+ /** Mean score across those hits, clamped to [0,1]. */
9774
+ avgScore: number().min(0).max(1),
9775
+ /** Peak score in the window. */
9776
+ peakScore: number().min(0).max(1)
9777
+ });
9778
+ /**
9779
+ * Per-camera audio metrics snapshot — emitted by the analytics frame
9780
+ * handler on every `pipeline.audio-inference-result` event and
9781
+ * mirrored into the `audio-metrics` device-state slice. Symmetric
9782
+ * with `zone-analytics` snapshots for video — every consumer
9783
+ * (admin UI panel, automations, alert rules) reads via the
9784
+ * canonical `device.state.audioMetrics.value` reactive handle.
9785
+ *
9786
+ * Aggregates are computed over a rolling `windowSec` window
9787
+ * (default 60s). Past that window, classes drop out of `byClass`
9788
+ * and the level history shifts forward.
9789
+ */
9790
+ var AudioMetricsSnapshotSchema = object({
9791
+ /** Wall-clock timestamp (ms) of the most recent audio window. */
9792
+ ts: number().int(),
9793
+ /** Sliding-window length (seconds) used for aggregation. */
9794
+ windowSec: number().int().positive(),
9795
+ /** Latest level reading from the most recent window. */
9796
+ level: object({
9797
+ rms: number(),
9798
+ dbfs: number()
9799
+ }),
9800
+ /** Peak dBFS observed across the rolling window. */
9801
+ peakDbfs: number(),
9802
+ /** Mean dBFS across the rolling window. */
9803
+ avgDbfs: number(),
9804
+ /** Most recent above-threshold classification, or null on silence. */
9805
+ current: object({
9806
+ className: string(),
9807
+ score: number().min(0).max(1),
9808
+ timestamp: number().int()
9809
+ }).nullable(),
9810
+ /** Per-class summary across the rolling window — keys are
9811
+ * `macroClass` strings (e.g. `dog_bark`, `speech`, `glass_break`). */
9812
+ byClass: array(AudioClassSummarySchema).readonly()
9813
+ });
9814
+ /**
9815
+ * Audio-metrics history payload — a series of `AudioMetricsHistoryPoint`
9816
+ * samples capped at `maxPoints` (default 1024). When the requested
9817
+ * `windowSec / sampleEveryMs` would exceed the cap, the provider
9818
+ * subsamples by bucketed averaging and reports the effective sample
9819
+ * spacing on `effectiveSampleEveryMs` so the UI can label the x-axis.
9820
+ */
9821
+ var AudioMetricsHistorySchema = object({
9822
+ points: array(object({
9823
+ /** Wall-clock ms when this sample was recorded. */
9824
+ ts: number().int(),
9825
+ /** Instantaneous dBFS level at sample time. `null` for windows where
9826
+ * the source had no level reading (rare; happens at decode startup). */
9827
+ dbfs: number().nullable(),
9828
+ /** Rolling-window peak dBFS at sample time. Same window the live
9829
+ * snapshot reports. */
9830
+ peakDbfs: number(),
9831
+ /** Rolling-window mean dBFS at sample time. */
9832
+ avgDbfs: number(),
9833
+ /** Dominant above-threshold class at sample time, or null on silence. */
9834
+ topClass: string().nullable(),
9835
+ /** Score of the dominant class (`null` whenever `topClass` is null). */
9836
+ topScore: number().min(0).max(1).nullable()
9837
+ })).readonly(),
9838
+ /** Actual ms between adjacent samples after any subsampling. */
9839
+ effectiveSampleEveryMs: number().int().positive(),
9840
+ /** Wall-clock window covered by `points` (`points[N-1].ts - points[0].ts`),
9841
+ * or `0` when there's fewer than 2 samples. */
9842
+ windowMsActual: number().int().nonnegative()
9843
+ });
9844
+ DeviceType.Camera, method(object({ deviceId: number() }), AudioMetricsSnapshotSchema.nullable()), method(object({
9845
+ deviceId: number(),
9846
+ /** History window in seconds. Default 300 (5 minutes).
9847
+ * Provider clamps to its retention cap if larger. */
9848
+ windowSec: number().int().positive().optional(),
9849
+ /** Target sample interval in ms. Default 1000 (1 sample/second).
9850
+ * Provider clamps to natural sample rate if smaller, and
9851
+ * bucket-averages when bigger than the requested window
9852
+ * would produce more than `maxPoints` samples. */
9853
+ sampleEveryMs: number().int().positive().optional()
9854
+ }), AudioMetricsHistorySchema);
9855
+ object({
9856
+ /** Whether the automation is currently enabled. Disabled automations
9857
+ * ignore their trigger block — manual `trigger` still works. */
9858
+ enabled: boolean(),
9859
+ /** Whether the automation is currently executing its action block. */
9860
+ isRunning: boolean(),
9861
+ /** Ms epoch of the last successful run. 0 when never run. */
9862
+ lastTriggeredAt: number(),
9863
+ /** Failure description from the last completed run. Null on success
9864
+ * or when never run. */
9865
+ lastError: string().nullable(),
9866
+ /** Ms epoch when the slice was last updated. */
9867
+ lastChangedAt: number()
9868
+ });
9869
+ DeviceType.Automation, method(object({ deviceId: number().int().nonnegative() }), _void(), {
9870
+ kind: "mutation",
9871
+ auth: "admin"
9872
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
9873
+ kind: "mutation",
9874
+ auth: "admin"
9875
+ }), method(object({
9876
+ deviceId: number().int().nonnegative(),
9877
+ /** When true, fires the action block while bypassing the
9878
+ * automation's condition evaluation. Gated by
9879
+ * `DeviceFeature.AutomationSkipCondition`. */
9880
+ skipCondition: boolean().optional()
9881
+ }), _void(), {
9882
+ kind: "mutation",
9883
+ auth: "admin"
9884
+ });
9885
+ /**
9886
+ * Battery status snapshot. Emitted by providers whose device is
9887
+ * battery-operated (cameras with `DeviceFeature.BatteryOperated`,
9888
+ * future sensor/button accessories). Consumers build their own "low
9889
+ * battery" alerting on top — the cap deliberately does NOT enforce a
9890
+ * threshold.
9891
+ */
9892
+ var BatteryStatusSchema = object({
9893
+ /** 0..100 inclusive. Firmware-reported. */
9894
+ percentage: number().min(0).max(100),
9895
+ /**
9896
+ * Charging source. `'dc'` covers wall/USB adapters; `'solar'` is
9897
+ * Reolink-specific for the Solar Panel 2 accessory (will become
9898
+ * common on other battery cams). `'none'` means running on battery
9899
+ * alone.
9900
+ */
9901
+ charging: _enum([
9902
+ "dc",
9903
+ "solar",
9904
+ "none"
9905
+ ]),
9906
+ /**
9907
+ * True when the camera firmware has gone into low-power mode. Battery
9908
+ * providers MUST avoid polling during sleep — reading the battery
9909
+ * wakes the camera up and drains charge.
9910
+ */
9911
+ sleeping: boolean(),
9912
+ /** Ms epoch of the last observation. Lets consumers reason about freshness. */
9913
+ lastUpdated: number(),
9914
+ /**
9915
+ * True when the source is a BINARY low-battery indicator (HA
9916
+ * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
9917
+ * charge level — `percentage` is then a coarse stand-in (100 = normal,
9918
+ * sub-threshold = low). UI MUST render "Normal"/"Low" instead of a
9919
+ * misleading exact percentage. Absent/false → genuine 0–100 % reading.
9920
+ */
9921
+ binary: boolean().optional()
9922
+ });
9923
+ DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch, method(object({
9924
+ deviceId: number(),
9925
+ /** Bound on the wait. Sensible range 3000–10000ms. */
9926
+ timeoutMs: number().int().min(500).max(3e4).default(8e3)
9927
+ }), object({
9928
+ awoke: boolean(),
9929
+ durationMs: number()
9930
+ }), { kind: "mutation" }), object({
9931
+ deviceId: number(),
9932
+ status: BatteryStatusSchema
9933
+ });
9934
+ object({
9935
+ on: boolean(),
9936
+ /** Ms epoch of the last transition. 0 if never observed. */
9937
+ lastChangedAt: number()
9938
+ });
9939
+ DeviceType.Sensor;
9940
+ object({
9941
+ /** Current level as 0..100 inclusive. Firmware-reported. */
9942
+ percentage: number().min(0).max(100),
9943
+ /** Ms epoch of the last operator-driven change. Useful for UI freshness. */
9944
+ lastChangedAt: number()
9945
+ });
9946
+ DeviceType.Light, method(object({
9947
+ deviceId: number().int().nonnegative(),
9948
+ percentage: number().min(0).max(100)
9949
+ }), _void(), {
9950
+ kind: "mutation",
9951
+ auth: "admin"
9952
+ }), object({
9953
+ deviceId: number(),
9954
+ percentage: number().min(0).max(100),
9955
+ lastChangedAt: number()
9956
+ });
9957
+ /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
9958
+ var StreamFormatSchema = _enum([
9959
+ "webrtc",
9960
+ "hls",
9961
+ "mjpeg",
9962
+ "rtsp"
9963
+ ]);
9964
+ var RtspRestreamEntrySchema = object({
9965
+ brokerId: string(),
9966
+ url: string(),
9967
+ mutedUrl: string(),
9968
+ enabled: boolean(),
9969
+ /**
9970
+ * Source-stream codec / resolution for the camStream this entry serves
9971
+ * (the broker's "high"/"mid"/"low" profile slot for this device).
9972
+ * Used by exporter pickers (`pickPreferredRtspEntry`) to resolve
9973
+ * `streamPreference: 'auto'` to the slot whose source is closest to
9974
+ * the consumer's target — Alexa wants ~720p, HomeKit wants ~1080p,
9975
+ * and there's no point dialling the 4K slot for an Echo Show. Absent
9976
+ * when the source publisher never advertised the field; pickers fall
9977
+ * back to first-enabled in that case.
9978
+ */
9979
+ codec: string().optional(),
9980
+ resolution: object({
9981
+ width: number().int().positive(),
9982
+ height: number().int().positive()
9983
+ }).optional()
9984
+ });
9985
+ var BrokerRtspClientSchema = object({
9986
+ sessionId: string(),
9987
+ remoteAddr: string(),
9988
+ /** Client `User-Agent` (e.g. `recorder` for the recorder's RTSP pull), or
9989
+ * null/absent when the client sent none. Lets the UI label a consumer by
9990
+ * purpose. Optional so a client built against an older schema stays valid. */
9991
+ userAgent: string().nullish(),
9992
+ playing: boolean(),
9993
+ muted: boolean(),
9994
+ connectedAt: number(),
9995
+ lastRtpAt: number(),
9996
+ bytesSent: number()
9997
+ });
9998
+ var BrokerDecodedClientSchema = object({
9999
+ tag: string(),
10000
+ subscribedAt: number(),
10001
+ maxFps: number(),
10002
+ framesDelivered: number(),
10003
+ framesDropped: number()
10004
+ });
10005
+ var BrokerAudioClientSchema = object({
10006
+ tag: string(),
10007
+ subscribedAt: number(),
10008
+ chunksDelivered: number()
10009
+ });
10010
+ var BrokerConsumerAttributionSchema = object({
10011
+ kind: _enum([
10012
+ "alexa",
10013
+ "homekit",
10014
+ "webrtc-browser",
10015
+ "webrtc-mobile",
10016
+ "webrtc-whep",
10017
+ "rtsp-listen",
10018
+ "derived-broker",
10019
+ "recording",
10020
+ "pipeline",
10021
+ "snapshot",
10022
+ "warmup",
10023
+ "unknown"
10024
+ ]),
10025
+ /**
10026
+ * Free-form label intended to disambiguate consumers OF THE SAME kind
10027
+ * on the same broker — e.g. user name, device alias. Should NOT repeat
10028
+ * the kind / cam / cam-stream / sessionId (those are surfaced by
10029
+ * dedicated fields). When empty the widget falls back to `${kind} ·
10030
+ * <sessionId tail>`.
10031
+ */
10032
+ label: string().optional(),
10033
+ /**
10034
+ * Which part of the encoded plane this subscription consumes:
10035
+ * - `'audio'` — audio packets only
10036
+ * - `'video'` — video packets only
10037
+ * - `'both'` — both video + audio (typical for AnnexB push paths
10038
+ * that don't split the source RTP)
10039
+ *
10040
+ * Missing field means "unknown" — older callers and the legacy
10041
+ * paths that haven't been migrated yet.
10042
+ */
10043
+ media: _enum([
10044
+ "audio",
10045
+ "video",
10046
+ "both"
10047
+ ]).optional(),
10048
+ /**
10049
+ * Codec the consumer receives AFTER any per-session re-encoding. For
10050
+ * a WebRTC session this is the negotiated egress codec (e.g. `H264`,
10051
+ * `H265`, `Opus`, `Pcmu`); for an RTSP restreamer it mirrors the
10052
+ * source codec. Surfaced in the widget chip so operators see at a
10053
+ * glance whether a viewer is on H.264 (Echo) or H.265 (Safari).
10054
+ */
10055
+ targetCodec: string().optional(),
10056
+ /**
10057
+ * Whether the broker is re-encoding for this consumer:
10058
+ * - `'passthrough'` — bytes flow source→consumer without ffmpeg
10059
+ * - `'repacketize'` — RTP payload is re-packetized but NOT re-encoded
10060
+ * (preserves frames, just rebuilds headers; e.g.
10061
+ * the H.265 repacketizer path)
10062
+ * - `'transcode'` — a full encode/decode round (ffmpeg, libx264,
10063
+ * libav…); the most expensive path
10064
+ */
10065
+ transport: _enum([
10066
+ "passthrough",
10067
+ "repacketize",
10068
+ "transcode"
10069
+ ]).optional(),
10070
+ /** Remote peer IP if the consumer terminates a network socket. */
10071
+ remoteAddr: string().optional(),
10072
+ /**
10073
+ * Server-read User-Agent of the originating client; enriched by the hub
10074
+ * from the tRPC request context (browser sessions).
10075
+ */
10076
+ userAgent: string().optional(),
10077
+ /** Authenticated user id (CamStack OAuth subject) when known. */
10078
+ userId: string().optional(),
10079
+ /** Higher-level session identifier (Alexa Echo sessionId, HAP session, …). */
10080
+ sessionId: string().optional(),
10081
+ /** Free-form key/value extras (e.g. clientHints from a WebRTC offer). */
10082
+ extra: record(string(), string()).optional()
10083
+ }).readonly();
10084
+ var BrokerEncodedClientSchema = object({
10085
+ /** Stable id assigned on attach; used by `killClient`. */
10086
+ id: string(),
10087
+ /** Which broker fanout the subscriber rides — annexB encoded packets vs raw RTP. */
10088
+ channel: _enum(["annexb", "rtp"]),
10089
+ attribution: BrokerConsumerAttributionSchema,
10090
+ subscribedAt: number(),
9453
10091
  /** Total packets delivered (annex-B EncodedPackets or RTP byte-buffers). */
9454
10092
  packetsDelivered: number()
9455
10093
  });
@@ -11870,100 +12508,39 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
11870
12508
  object({
11871
12509
  detected: boolean(),
11872
12510
  /** Ms epoch of the last detected-true observation. Null if never detected. */
11873
- lastDetectedAt: number().nullable(),
11874
- /**
11875
- * Ms after which `detected` auto-reverts to false if no fresh push
11876
- * arrives. Null means the provider leaves detected state until a
11877
- * native "clear" event.
11878
- */
11879
- autoClearAfterMs: number().nullable()
11880
- });
11881
- object({
11882
- deviceId: number(),
11883
- detected: boolean(),
11884
- timestamp: number(),
11885
- source: MotionSourceEnum,
11886
- regions: array(MotionRegionSchema).readonly().optional()
11887
- });
11888
- DeviceType.Camera, DeviceType.Sensor, method(object({ deviceId: number() }), boolean());
11889
- object({
11890
- enabled: boolean(),
11891
- /** Ms epoch of the last operator-driven change. */
11892
- lastChangedAt: number()
11893
- }).extend({
11894
- /** Ms epoch of the last successful camera fetch (0 = never). */
11895
- lastFetchedAt: number() });
11896
- DeviceType.Light, DeviceType.Siren, DeviceType.Switch, method(object({
11897
- deviceId: number().int().nonnegative(),
11898
- enabled: boolean()
11899
- }), _void(), {
11900
- kind: "mutation",
11901
- auth: "admin"
11902
- }), object({
11903
- deviceId: number(),
11904
- enabled: boolean(),
11905
- lastChangedAt: number()
11906
- });
11907
- /**
11908
- * Shared geometry vocabulary for on-frame shape caps — privacy-mask,
11909
- * motion-zones, and the detection zones/lines editor all speak this one
11910
- * language so a single drawing-plane editor and the providers stay
11911
- * decoupled from each cap's storage.
11912
- *
11913
- * All coordinates are normalized 0..1 of the camera frame (top-left
11914
- * origin). Each cap composes the SUBSET of shape kinds it supports and
11915
- * advertises it via `supportedShapes` in its `getOptions`.
11916
- */
11917
- /** A normalized 0..1 point (top-left origin). */
11918
- var MaskPointSchema = object({
11919
- x: number(),
11920
- y: number()
11921
- });
11922
- /** Axis-aligned rectangle (normalized 0..1). */
11923
- var MaskRectShapeSchema = object({
11924
- kind: literal("rect"),
11925
- x: number(),
11926
- y: number(),
11927
- width: number(),
11928
- height: number()
11929
- });
11930
- /** Free polygon — an ordered list of normalized vertices (≥3). */
11931
- var MaskPolygonShapeSchema = object({
11932
- kind: literal("polygon"),
11933
- points: array(MaskPointSchema)
11934
- });
11935
- /** Boolean cell grid — row-major, length === gridWidth*gridHeight. */
11936
- var MaskGridShapeSchema = object({
11937
- kind: literal("grid"),
11938
- gridWidth: number(),
11939
- gridHeight: number(),
11940
- cells: array(boolean())
12511
+ lastDetectedAt: number().nullable(),
12512
+ /**
12513
+ * Ms after which `detected` auto-reverts to false if no fresh push
12514
+ * arrives. Null means the provider leaves detected state until a
12515
+ * native "clear" event.
12516
+ */
12517
+ autoClearAfterMs: number().nullable()
11941
12518
  });
11942
- discriminatedUnion("kind", [
11943
- MaskRectShapeSchema,
11944
- MaskPolygonShapeSchema,
11945
- MaskGridShapeSchema,
11946
- object({
11947
- kind: literal("line"),
11948
- points: array(MaskPointSchema)
11949
- })
11950
- ]);
11951
- /** Every shape-kind discriminant, for `supportedShapes` advertisement. */
11952
- var MaskShapeKindSchema = _enum([
11953
- "rect",
11954
- "polygon",
11955
- "grid",
11956
- "line"
11957
- ]);
11958
- /** Polygon vertex bounds when a cap supports 'polygon' (e.g. Hikvision {min:4,max:4}). */
11959
- var MaskPolygonVerticesSchema = object({
11960
- min: number(),
11961
- max: number()
12519
+ object({
12520
+ deviceId: number(),
12521
+ detected: boolean(),
12522
+ timestamp: number(),
12523
+ source: MotionSourceEnum,
12524
+ regions: array(MotionRegionSchema).readonly().optional()
11962
12525
  });
11963
- /** Grid dimensions when a cap supports 'grid'. */
11964
- var MaskGridDimsSchema = object({
11965
- width: number(),
11966
- height: number()
12526
+ DeviceType.Camera, DeviceType.Sensor, method(object({ deviceId: number() }), boolean());
12527
+ object({
12528
+ enabled: boolean(),
12529
+ /** Ms epoch of the last operator-driven change. */
12530
+ lastChangedAt: number()
12531
+ }).extend({
12532
+ /** Ms epoch of the last successful camera fetch (0 = never). */
12533
+ lastFetchedAt: number() });
12534
+ DeviceType.Light, DeviceType.Siren, DeviceType.Switch, method(object({
12535
+ deviceId: number().int().nonnegative(),
12536
+ enabled: boolean()
12537
+ }), _void(), {
12538
+ kind: "mutation",
12539
+ auth: "admin"
12540
+ }), object({
12541
+ deviceId: number(),
12542
+ enabled: boolean(),
12543
+ lastChangedAt: number()
11967
12544
  });
11968
12545
  /**
11969
12546
  * Motion-zones share the same MaskShape vocabulary as privacy-mask — the
@@ -13840,6 +14417,55 @@ method(object({
13840
14417
  password: string()
13841
14418
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
13842
14419
  /**
14420
+ * A live terminal session hosted by the provider addon. Output and input do
14421
+ * NOT flow through the capability — they use the addon data plane
14422
+ * (`GET /addon/terminal/<id>/out` SSE, `POST /addon/terminal/<id>/in`) because
14423
+ * terminal output must be ordered and lossless. The event bus is telemetry and
14424
+ * may drop chunks ([D8]), and a dropped chunk desynchronises the vt parser
14425
+ * permanently until a full repaint. The capability owns only lifecycle.
14426
+ */
14427
+ var TerminalSessionInfoSchema = object({
14428
+ /** Opaque session id minted by the provider on `openSession`. */
14429
+ sessionId: string(),
14430
+ /** The pre-declared profile this session runs (never a free-form command). */
14431
+ profileId: string(),
14432
+ /** Human-readable profile label for the UI session list. */
14433
+ label: string(),
14434
+ cols: number().int().positive(),
14435
+ rows: number().int().positive(),
14436
+ /** ms-epoch the session's pty was spawned. */
14437
+ startedAt: number()
14438
+ });
14439
+ /**
14440
+ * A profile the operator may open — a pre-declared, allowlisted program
14441
+ * (`monitor` → `btm`). The capability accepts only these ids; a free-form
14442
+ * command string would be remote code execution as the server's user, so it is
14443
+ * deliberately not part of the contract.
14444
+ */
14445
+ var TerminalProfileInfoSchema = object({
14446
+ profileId: string(),
14447
+ label: string(),
14448
+ description: string().optional()
14449
+ });
14450
+ method(_void(), array(TerminalProfileInfoSchema).readonly(), { auth: "admin" }), method(_void(), array(TerminalSessionInfoSchema).readonly(), { auth: "admin" }), method(object({
14451
+ profileId: string(),
14452
+ cols: number().int().positive(),
14453
+ rows: number().int().positive()
14454
+ }), TerminalSessionInfoSchema, {
14455
+ kind: "mutation",
14456
+ auth: "admin"
14457
+ }), method(object({
14458
+ sessionId: string(),
14459
+ cols: number().int().positive(),
14460
+ rows: number().int().positive()
14461
+ }), _void(), {
14462
+ kind: "mutation",
14463
+ auth: "admin"
14464
+ }), method(object({ sessionId: string() }), _void(), {
14465
+ kind: "mutation",
14466
+ auth: "admin"
14467
+ });
14468
+ /**
13843
14469
  * Orchestrator-side destination metadata. The orchestrator computes
13844
14470
  * `id = <addonId>:<subId>` from its provider lookup so consumers
13845
14471
  * (admin UI, restore flow) see one canonical key.
@@ -15030,1609 +15656,1121 @@ method(object({
15030
15656
  providerNodeId: string(),
15031
15657
  nativeAddonId: string()
15032
15658
  }))
15033
- }))), method(object({
15034
- deviceId: number(),
15035
- capName: string(),
15036
- wrapperAddonId: string(),
15037
- active: boolean()
15038
- }), _void(), {
15039
- kind: "mutation",
15040
- auth: "admin"
15041
- }), method(object({ capName: string() }), array(string())), method(object({ deviceType: string() }), array(object({
15042
- capName: string(),
15043
- wrappers: array(string())
15044
- }))), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), object({
15045
- settings: SettingsSchemaWithValuesSchema.nullable(),
15046
- live: SettingsSchemaWithValuesSchema.nullable()
15047
- })), method(object({
15048
- deviceId: number().int().nonnegative(),
15049
- action: string().min(1),
15050
- input: unknown()
15051
- }), unknown(), { kind: "mutation" }), method(object({
15052
- deviceId: number(),
15053
- writerCapName: string(),
15054
- writerAddonId: string(),
15055
- key: string(),
15056
- value: unknown()
15057
- }), object({ success: literal(true) }), {
15058
- kind: "mutation",
15059
- auth: "admin"
15060
- }), method(object({
15061
- deviceId: number(),
15062
- changes: array(object({
15063
- writerCapName: string(),
15064
- writerAddonId: string(),
15065
- key: string(),
15066
- value: unknown()
15067
- }))
15068
- }), object({
15069
- success: literal(true),
15070
- failures: array(object({
15071
- writerCapName: string(),
15072
- writerAddonId: string(),
15073
- error: string()
15074
- }))
15075
- }), {
15076
- kind: "mutation",
15077
- auth: "admin"
15078
- }), method(object({ addonId: string() }), array(DiscoveryCandidateSchema), {
15079
- kind: "mutation",
15080
- auth: "admin"
15081
- }), method(object({
15082
- addonId: string(),
15083
- candidate: DiscoveryCandidateSchema,
15084
- /** Owning integration id, stamped onto the new device's meta by the
15085
- * device-manager forwarder so `removeByIntegration` can cascade it.
15086
- * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
15087
- integrationId: string().optional()
15088
- }), DeviceSummarySchema, {
15089
- kind: "mutation",
15090
- auth: "admin"
15091
- }), method(object({
15092
- addonId: string(),
15093
- type: _enum(DeviceType)
15094
- }), unknown().nullable()), method(object({
15095
- addonId: string(),
15096
- type: _enum(DeviceType),
15097
- config: record(string(), unknown()),
15098
- /** Owning integration id, stamped onto the new device's meta by the
15099
- * device-manager forwarder so `removeByIntegration` can cascade it.
15100
- * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
15101
- integrationId: string().optional()
15102
- }), DeviceSummarySchema, {
15103
- kind: "mutation",
15104
- auth: "admin"
15105
- }), method(object({
15106
- addonId: string(),
15107
- type: _enum(DeviceType),
15108
- key: string(),
15109
- value: unknown(),
15110
- formValues: record(string(), unknown()).optional()
15111
- }), FieldProbeResultSchema, {
15112
- kind: "mutation",
15113
- auth: "admin"
15114
- }), method(object({
15115
- addonId: string(),
15116
- integrationId: string()
15117
- }), object({ filters: array(AdoptionFilterSchema) }), { auth: "admin" }), method(ListCandidatesInputSchema.extend({ addonId: string() }), ListCandidatesOutputSchema, { auth: "admin" }), method(object({
15118
- addonId: string(),
15119
- integrationId: string()
15120
- }), AdoptionStatusSchema, {
15121
- kind: "mutation",
15122
- auth: "admin"
15123
- }), method(AdoptInputSchema.extend({ addonId: string() }), AdoptResultSchema, {
15124
- kind: "mutation",
15125
- auth: "admin"
15126
- }), method(ReleaseInputSchema.extend({ addonId: string() }), _void(), {
15127
- kind: "mutation",
15128
- auth: "admin"
15129
- }), method(ResyncInputSchema, ResyncResultSchema, {
15130
- kind: "mutation",
15131
- auth: "admin"
15132
- }), method(object({}), object({ providers: array(object({
15133
- addonId: string(),
15134
- label: string()
15135
- })).readonly() }), { auth: "admin" }), method(object({}), object({ groups: array(object({
15136
- addonId: string(),
15137
- label: string(),
15138
- candidates: array(DiscoveryCandidateSchema).readonly(),
15139
- error: string().nullable()
15140
- })).readonly() }), {
15141
- kind: "mutation",
15142
- auth: "admin"
15143
- }), method(object({
15144
- addonId: string(),
15145
- params: record(string(), unknown()).optional()
15146
- }), object({ candidates: array(DiscoveryCandidateSchema).readonly() }), {
15147
- kind: "mutation",
15148
- auth: "admin"
15149
- }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
15150
- deviceId: number(),
15151
- key: string(),
15152
- value: unknown()
15153
- }), FieldProbeResultSchema, {
15154
- kind: "mutation",
15155
- auth: "admin"
15156
- }), method(object({
15157
- deviceId: number(),
15158
- caps: array(string()).readonly().optional()
15159
- }), record(string(), unknown().nullable()));
15160
- method(object({ deviceId: number() }), record(string(), record(string(), unknown()))), method(object({
15161
- deviceId: number(),
15162
- capName: string()
15163
- }), record(string(), unknown()).nullable()), method(object({}), record(string(), record(string(), record(string(), unknown())))), method(object({
15164
- deviceId: number(),
15165
- capName: string(),
15166
- slice: record(string(), unknown())
15167
- }), _void(), { kind: "mutation" }), object({
15168
- deviceId: number(),
15169
- capName: string(),
15170
- slice: record(string(), unknown())
15171
- });
15172
- /**
15173
- * Embedding output. `embedding` is wire-encoded as `number[]` so the
15174
- * Zod-validated tRPC surface round-trips cleanly; consumers that need a
15175
- * `Float32Array` can wrap it on the way out (in-process, no marshalling
15176
- * is involved). `inferenceMs` mirrors the runtime field used by the
15177
- * post-analysis enrichment-engine.
15178
- */
15179
- var EmbeddingResultSchema = object({
15180
- embedding: array(number()),
15181
- inferenceMs: number()
15182
- });
15183
- var EmbeddingInfoSchema = object({
15184
- modelId: string(),
15185
- embeddingDim: number(),
15186
- ready: boolean()
15187
- });
15188
- method(object({
15189
- crop: _instanceof(Uint8Array),
15190
- width: number(),
15191
- height: number()
15192
- }), EmbeddingResultSchema), method(object({ text: string() }), EmbeddingResultSchema), method(_void(), EmbeddingInfoSchema);
15193
- /**
15194
- * filesystem-browse — per-node capability for browsing the node's local
15195
- * filesystem, sandboxed to operator-configured allowed roots. Used by the
15196
- * admin "Add filesystem location" flow to pick a node + path. `mode:'per-node'`
15197
- * (one provider per node); the hub calls it with `{nodeId}` so the codegen
15198
- * routes to that exact node (default `nodeIdMode:'routing'`).
15199
- */
15200
- var DirEntrySchema = object({
15201
- name: string(),
15202
- path: string()
15203
- });
15204
- var BrowseResultSchema = object({
15205
- path: string(),
15206
- entries: array(DirEntrySchema).readonly(),
15207
- freeBytes: number(),
15208
- totalBytes: number()
15209
- });
15210
- method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({ path: string() }), BrowseResultSchema, { auth: "admin" }), method(object({ path: string() }), object({ path: string() }), {
15659
+ }))), method(object({
15660
+ deviceId: number(),
15661
+ capName: string(),
15662
+ wrapperAddonId: string(),
15663
+ active: boolean()
15664
+ }), _void(), {
15211
15665
  kind: "mutation",
15212
15666
  auth: "admin"
15213
- });
15214
- /**
15215
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15216
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15217
- * caps stay wire-compatible without a circular cap→cap import.
15218
- *
15219
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
15220
- * every transport tier structurally, and failed calls still write usage rows.
15221
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15222
- */
15223
- var LlmUsageSchema = object({
15224
- inputTokens: number(),
15225
- outputTokens: number()
15226
- });
15227
- var LlmErrorCodeSchema = _enum([
15228
- "timeout",
15229
- "rate-limited",
15230
- "auth",
15231
- "refusal",
15232
- "bad-request",
15233
- "unavailable",
15234
- "no-profile",
15235
- "budget-exceeded",
15236
- "adapter-error"
15237
- ]);
15238
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15239
- ok: literal(true),
15240
- text: string(),
15241
- model: string(),
15242
- usage: LlmUsageSchema,
15243
- truncated: boolean(),
15244
- latencyMs: number()
15245
- }), object({
15246
- ok: literal(false),
15247
- code: LlmErrorCodeSchema,
15248
- message: string(),
15249
- retryAfterMs: number().optional()
15250
- })]);
15251
- /**
15252
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15253
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15254
- * notification-output.cap.ts:27-31 precedents).
15255
- */
15256
- var LlmImageSchema = object({
15257
- bytes: _instanceof(Uint8Array),
15258
- mimeType: string()
15259
- });
15260
- var LlmGenerateBaseInputSchema = object({
15261
- /** Collection routing (the notification-output posture). */
15262
- addonId: string().optional(),
15263
- /** Explicit profile; else the resolution chain (spec §3). */
15264
- profileId: string().optional(),
15265
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15266
- consumer: string(),
15267
- system: string().optional(),
15268
- /** v1: single-turn. `messages[]` is a v2 additive field. */
15269
- prompt: string(),
15270
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15271
- jsonSchema: record(string(), unknown()).optional(),
15272
- /** Per-call override of the profile default. */
15273
- maxTokens: number().int().positive().optional(),
15274
- temperature: number().optional()
15275
- });
15276
- /**
15277
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15278
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15279
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15280
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15281
- * this only through the `llm` cap's methods.
15282
- *
15283
- * One running llama-server child per node in v1 (models are RAM-heavy).
15284
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15285
- * watchdog — operator decision #3).
15286
- */
15287
- var ManagedModelRefSchema = discriminatedUnion("kind", [
15288
- object({
15289
- kind: literal("catalog"),
15290
- catalogId: string()
15291
- }),
15292
- object({
15293
- kind: literal("url"),
15294
- url: string(),
15295
- sha256: string().optional()
15296
- }),
15297
- object({
15298
- kind: literal("path"),
15299
- path: string()
15300
- })
15301
- ]);
15302
- var ManagedRuntimeConfigSchema = object({
15303
- /** WHERE the runtime lives — hub or any agent. */
15304
- nodeId: string(),
15305
- /** Closed for v1; 'ollama' is a v2 candidate. */
15306
- engine: _enum(["llama-cpp"]),
15307
- model: ManagedModelRefSchema,
15308
- contextSize: number().int().default(4096),
15309
- /** 0 = CPU-only. */
15310
- gpuLayers: number().int().default(0),
15311
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15312
- threads: number().int().optional(),
15313
- /** Concurrent slots. */
15314
- parallel: number().int().default(1),
15315
- /** Else lazy: first generate boots it. */
15316
- autoStart: boolean().default(false),
15317
- /** 0 = never; frees RAM after quiet periods. */
15318
- idleStopMinutes: number().int().default(30)
15319
- });
15320
- var LlmRuntimeStatusSchema = object({
15321
- /** Status is ALWAYS node-qualified. */
15322
- nodeId: string(),
15323
- state: _enum([
15324
- "stopped",
15325
- "downloading",
15326
- "starting",
15327
- "ready",
15328
- "crashed",
15329
- "failed"
15330
- ]),
15331
- pid: number().optional(),
15332
- port: number().optional(),
15333
- modelPath: string().optional(),
15334
- modelId: string().optional(),
15335
- downloadProgress: number().min(0).max(1).optional(),
15336
- lastError: string().optional(),
15337
- crashesInWindow: number(),
15338
- /** Child RSS (sampled best-effort). */
15339
- memoryBytes: number().optional(),
15340
- vramBytes: number().optional()
15341
- });
15342
- var LlmNodeModelSchema = object({
15343
- file: string(),
15344
- sizeBytes: number(),
15345
- catalogId: string().optional(),
15346
- installedAt: number().optional()
15347
- });
15348
- var LlmRuntimeDiskUsageSchema = object({
15349
- nodeId: string(),
15350
- modelsBytes: number(),
15351
- freeBytes: number().optional()
15352
- });
15353
- method(LlmGenerateBaseInputSchema.extend({
15354
- images: array(LlmImageSchema).optional(),
15355
- runtime: ManagedRuntimeConfigSchema,
15356
- /** The managed profile's timeout, threaded by the hub provider. */
15357
- timeoutMs: number().int().positive().optional()
15358
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15667
+ }), method(object({ capName: string() }), array(string())), method(object({ deviceType: string() }), array(object({
15668
+ capName: string(),
15669
+ wrappers: array(string())
15670
+ }))), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), object({
15671
+ settings: SettingsSchemaWithValuesSchema.nullable(),
15672
+ live: SettingsSchemaWithValuesSchema.nullable()
15673
+ })), method(object({
15674
+ deviceId: number().int().nonnegative(),
15675
+ action: string().min(1),
15676
+ input: unknown()
15677
+ }), unknown(), { kind: "mutation" }), method(object({
15678
+ deviceId: number(),
15679
+ writerCapName: string(),
15680
+ writerAddonId: string(),
15681
+ key: string(),
15682
+ value: unknown()
15683
+ }), object({ success: literal(true) }), {
15359
15684
  kind: "mutation",
15360
15685
  auth: "admin"
15361
- }), method(object({}), _void(), {
15686
+ }), method(object({
15687
+ deviceId: number(),
15688
+ changes: array(object({
15689
+ writerCapName: string(),
15690
+ writerAddonId: string(),
15691
+ key: string(),
15692
+ value: unknown()
15693
+ }))
15694
+ }), object({
15695
+ success: literal(true),
15696
+ failures: array(object({
15697
+ writerCapName: string(),
15698
+ writerAddonId: string(),
15699
+ error: string()
15700
+ }))
15701
+ }), {
15362
15702
  kind: "mutation",
15363
15703
  auth: "admin"
15364
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15704
+ }), method(object({ addonId: string() }), array(DiscoveryCandidateSchema), {
15365
15705
  kind: "mutation",
15366
15706
  auth: "admin"
15367
- }), method(object({ file: string() }), _void(), {
15707
+ }), method(object({
15708
+ addonId: string(),
15709
+ candidate: DiscoveryCandidateSchema,
15710
+ /** Owning integration id, stamped onto the new device's meta by the
15711
+ * device-manager forwarder so `removeByIntegration` can cascade it.
15712
+ * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
15713
+ integrationId: string().optional()
15714
+ }), DeviceSummarySchema, {
15368
15715
  kind: "mutation",
15369
15716
  auth: "admin"
15370
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15371
- /**
15372
- * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15373
- * methods concat-fan across providers; single-row methods route to ONE
15374
- * provider by the `addonId` in the call input (the notification-output
15375
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15376
- * (hub-placed); the cap stays open for future providers.
15377
- *
15378
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15379
- * `apiKey` is a password field — providers REDACT it on read and merge on
15380
- * write; a stored key NEVER round-trips to a client.
15381
- */
15382
- var LlmProfileKindSchema = _enum([
15383
- "openai-compatible",
15384
- "openai",
15385
- "anthropic",
15386
- "google",
15387
- "managed-local"
15388
- ]);
15389
- var LlmProfileSchema = object({
15390
- id: string(),
15391
- name: string(),
15392
- kind: LlmProfileKindSchema,
15393
- /** Stamped by the provider — keeps the fanned catalog routable. */
15717
+ }), method(object({
15394
15718
  addonId: string(),
15395
- enabled: boolean(),
15396
- /** Vendor model id, or the managed runtime's loaded model. */
15397
- model: string(),
15398
- /** Required for openai-compatible; override for cloud kinds. */
15399
- baseUrl: string().optional(),
15400
- /** ConfigUISchema type:'password' never round-trips (spec §5). */
15401
- apiKey: string().optional(),
15402
- supportsVision: boolean(),
15403
- temperature: number().min(0).max(2).optional(),
15404
- maxTokens: number().int().positive().optional(),
15405
- timeoutMs: number().int().positive().default(6e4),
15406
- extraHeaders: record(string(), string()).optional(),
15407
- /** kind === 'managed-local' only (spec §4). */
15408
- runtime: ManagedRuntimeConfigSchema.optional()
15409
- });
15410
- /** ConfigUISchema tree passed through untyped on the wire (the
15411
- * notification-output `ConfigSchemaPassthrough` precedent at
15412
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15413
- var ConfigSchemaPassthrough$1 = unknown();
15414
- var LlmProfileKindDescriptorSchema = object({
15415
- kind: LlmProfileKindSchema,
15416
- label: string(),
15417
- icon: string(),
15418
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
15719
+ type: _enum(DeviceType)
15720
+ }), unknown().nullable()), method(object({
15721
+ addonId: string(),
15722
+ type: _enum(DeviceType),
15723
+ config: record(string(), unknown()),
15724
+ /** Owning integration id, stamped onto the new device's meta by the
15725
+ * device-manager forwarder so `removeByIntegration` can cascade it.
15726
+ * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
15727
+ integrationId: string().optional()
15728
+ }), DeviceSummarySchema, {
15729
+ kind: "mutation",
15730
+ auth: "admin"
15731
+ }), method(object({
15419
15732
  addonId: string(),
15420
- configSchema: ConfigSchemaPassthrough$1
15421
- });
15422
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15423
- var LlmDefaultSchema = object({
15424
- selector: LlmDefaultSelectorSchema,
15425
- profileId: string()
15426
- });
15427
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
15428
- var LlmUsageRollupSchema = object({
15429
- day: string(),
15430
- consumer: string(),
15431
- profileId: string(),
15432
- calls: number(),
15433
- okCalls: number(),
15434
- errorCalls: number(),
15435
- inputTokens: number(),
15436
- outputTokens: number(),
15437
- avgLatencyMs: number()
15438
- });
15439
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15440
- var ManagedModelCatalogEntrySchema = object({
15441
- id: string(),
15442
- label: string(),
15443
- family: string(),
15444
- purpose: _enum(["text", "vision"]),
15445
- url: string(),
15446
- sha256: string(),
15447
- sizeBytes: number(),
15448
- quantization: string(),
15449
- /** Load-time guidance shown in the picker. */
15450
- minRamBytes: number(),
15451
- contextSizeDefault: number().int(),
15452
- /** Vision models: companion projector file. */
15453
- mmprojUrl: string().optional()
15454
- });
15455
- var LlmRuntimeNodeSchema = object({
15456
- nodeId: string(),
15457
- reachable: boolean(),
15458
- status: LlmRuntimeStatusSchema.optional(),
15459
- disk: LlmRuntimeDiskUsageSchema.optional(),
15460
- error: string().optional()
15461
- });
15462
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
15463
- var ProfileRefInputSchema = object({
15733
+ type: _enum(DeviceType),
15734
+ key: string(),
15735
+ value: unknown(),
15736
+ formValues: record(string(), unknown()).optional()
15737
+ }), FieldProbeResultSchema, {
15738
+ kind: "mutation",
15739
+ auth: "admin"
15740
+ }), method(object({
15464
15741
  addonId: string(),
15465
- profileId: string()
15466
- });
15467
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
15742
+ integrationId: string()
15743
+ }), object({ filters: array(AdoptionFilterSchema) }), { auth: "admin" }), method(ListCandidatesInputSchema.extend({ addonId: string() }), ListCandidatesOutputSchema, { auth: "admin" }), method(object({
15744
+ addonId: string(),
15745
+ integrationId: string()
15746
+ }), AdoptionStatusSchema, {
15468
15747
  kind: "mutation",
15469
15748
  auth: "admin"
15470
- }), method(ProfileRefInputSchema, _void(), {
15749
+ }), method(AdoptInputSchema.extend({ addonId: string() }), AdoptResultSchema, {
15471
15750
  kind: "mutation",
15472
15751
  auth: "admin"
15473
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
15752
+ }), method(ReleaseInputSchema.extend({ addonId: string() }), _void(), {
15474
15753
  kind: "mutation",
15475
15754
  auth: "admin"
15476
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
15477
- selector: LlmDefaultSelectorSchema,
15478
- profileId: string().nullable()
15479
- }), _void(), {
15755
+ }), method(ResyncInputSchema, ResyncResultSchema, {
15480
15756
  kind: "mutation",
15481
15757
  auth: "admin"
15482
- }), method(object({
15483
- since: number().optional(),
15484
- until: number().optional(),
15485
- consumer: string().optional(),
15486
- profileId: string().optional()
15487
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
15488
- nodeId: string(),
15489
- model: ManagedModelRefSchema
15490
- }), _void(), {
15758
+ }), method(object({}), object({ providers: array(object({
15759
+ addonId: string(),
15760
+ label: string()
15761
+ })).readonly() }), { auth: "admin" }), method(object({}), object({ groups: array(object({
15762
+ addonId: string(),
15763
+ label: string(),
15764
+ candidates: array(DiscoveryCandidateSchema).readonly(),
15765
+ error: string().nullable()
15766
+ })).readonly() }), {
15491
15767
  kind: "mutation",
15492
15768
  auth: "admin"
15493
15769
  }), method(object({
15494
- nodeId: string(),
15495
- file: string()
15496
- }), _void(), {
15770
+ addonId: string(),
15771
+ params: record(string(), unknown()).optional()
15772
+ }), object({ candidates: array(DiscoveryCandidateSchema).readonly() }), {
15497
15773
  kind: "mutation",
15498
15774
  auth: "admin"
15499
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
15775
+ }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
15776
+ deviceId: number(),
15777
+ key: string(),
15778
+ value: unknown()
15779
+ }), FieldProbeResultSchema, {
15500
15780
  kind: "mutation",
15501
15781
  auth: "admin"
15502
- }), method(ProfileRefInputSchema, _void(), {
15782
+ }), method(object({
15783
+ deviceId: number(),
15784
+ caps: array(string()).readonly().optional()
15785
+ }), record(string(), unknown().nullable()));
15786
+ method(object({ deviceId: number() }), record(string(), record(string(), unknown()))), method(object({
15787
+ deviceId: number(),
15788
+ capName: string()
15789
+ }), record(string(), unknown()).nullable()), method(object({}), record(string(), record(string(), record(string(), unknown())))), method(object({
15790
+ deviceId: number(),
15791
+ capName: string(),
15792
+ slice: record(string(), unknown())
15793
+ }), _void(), { kind: "mutation" }), object({
15794
+ deviceId: number(),
15795
+ capName: string(),
15796
+ slice: record(string(), unknown())
15797
+ });
15798
+ /**
15799
+ * Embedding output. `embedding` is wire-encoded as `number[]` so the
15800
+ * Zod-validated tRPC surface round-trips cleanly; consumers that need a
15801
+ * `Float32Array` can wrap it on the way out (in-process, no marshalling
15802
+ * is involved). `inferenceMs` mirrors the runtime field used by the
15803
+ * post-analysis enrichment-engine.
15804
+ */
15805
+ var EmbeddingResultSchema = object({
15806
+ embedding: array(number()),
15807
+ inferenceMs: number()
15808
+ });
15809
+ var EmbeddingInfoSchema = object({
15810
+ modelId: string(),
15811
+ embeddingDim: number(),
15812
+ ready: boolean()
15813
+ });
15814
+ method(object({
15815
+ crop: _instanceof(Uint8Array),
15816
+ width: number(),
15817
+ height: number()
15818
+ }), EmbeddingResultSchema), method(object({ text: string() }), EmbeddingResultSchema), method(_void(), EmbeddingInfoSchema);
15819
+ /**
15820
+ * filesystem-browse — per-node capability for browsing the node's local
15821
+ * filesystem, sandboxed to operator-configured allowed roots. Used by the
15822
+ * admin "Add filesystem location" flow to pick a node + path. `mode:'per-node'`
15823
+ * (one provider per node); the hub calls it with `{nodeId}` so the codegen
15824
+ * routes to that exact node (default `nodeIdMode:'routing'`).
15825
+ */
15826
+ var DirEntrySchema = object({
15827
+ name: string(),
15828
+ path: string()
15829
+ });
15830
+ var BrowseResultSchema = object({
15831
+ path: string(),
15832
+ entries: array(DirEntrySchema).readonly(),
15833
+ freeBytes: number(),
15834
+ totalBytes: number()
15835
+ });
15836
+ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({ path: string() }), BrowseResultSchema, { auth: "admin" }), method(object({ path: string() }), object({ path: string() }), {
15503
15837
  kind: "mutation",
15504
15838
  auth: "admin"
15505
15839
  });
15506
- var LogLevelSchema = _enum([
15507
- "debug",
15508
- "info",
15509
- "warn",
15510
- "error"
15840
+ /**
15841
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15842
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15843
+ * caps stay wire-compatible without a circular cap→cap import.
15844
+ *
15845
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
15846
+ * every transport tier structurally, and failed calls still write usage rows.
15847
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15848
+ */
15849
+ var LlmUsageSchema = object({
15850
+ inputTokens: number(),
15851
+ outputTokens: number()
15852
+ });
15853
+ var LlmErrorCodeSchema = _enum([
15854
+ "timeout",
15855
+ "rate-limited",
15856
+ "auth",
15857
+ "refusal",
15858
+ "bad-request",
15859
+ "unavailable",
15860
+ "no-profile",
15861
+ "budget-exceeded",
15862
+ "adapter-error"
15511
15863
  ]);
15512
- var LogEntrySchema = object({
15513
- timestamp: date(),
15514
- level: LogLevelSchema,
15515
- scope: array(string()),
15864
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15865
+ ok: literal(true),
15866
+ text: string(),
15867
+ model: string(),
15868
+ usage: LlmUsageSchema,
15869
+ truncated: boolean(),
15870
+ latencyMs: number()
15871
+ }), object({
15872
+ ok: literal(false),
15873
+ code: LlmErrorCodeSchema,
15516
15874
  message: string(),
15517
- meta: record(string(), unknown()).optional(),
15518
- tags: record(string(), string()).optional()
15519
- });
15520
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15521
- scope: array(string()).optional(),
15522
- level: LogLevelSchema.optional(),
15523
- since: date().optional(),
15524
- until: date().optional(),
15525
- limit: number().optional(),
15526
- tags: record(string(), string()).optional()
15527
- }), array(LogEntrySchema).readonly());
15875
+ retryAfterMs: number().optional()
15876
+ })]);
15528
15877
  /**
15529
- * `login-method` collection cap through which auth addons contribute
15530
- * their pre-auth login surfaces to the login page. This is the SINGLE,
15531
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
15532
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
15533
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
15534
- * procedure aggregates them for the unauthenticated login page.
15535
- *
15536
- * A contribution is a discriminated union on `kind`:
15537
- *
15538
- * - `redirect` a declarative button. The login page renders a generic
15539
- * button that navigates to `startUrl` (an addon-owned HTTP route).
15540
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
15541
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
15542
- * login page needs NO change.
15543
- *
15544
- * - `widget` — a Module-Federation widget the login page mounts (via
15545
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
15546
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
15547
- * mechanism kept for future use; no shipped addon uses it on the login
15548
- * page (the passkey ceremony below runs natively in the shell instead).
15549
- *
15550
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
15551
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
15552
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
15553
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
15554
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
15555
- * fetching any remote code pre-auth. Contribution stays unconditional
15556
- * enrollment state is never leaked pre-auth; visibility is a shell
15557
- * decision.
15558
- *
15559
- * Every contribution carries a `stage`:
15560
- * - `primary` — shown on the first credentials screen (OIDC /
15561
- * magic-link buttons; a future usernameless passkey).
15562
- * - `second-factor` — shown AFTER the password leg, gated on the
15563
- * returned `factors` (passkey-as-2FA today).
15878
+ * `Uint8Array` is the sanctioned binary convention superjson + the UDS
15879
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15880
+ * notification-output.cap.ts:27-31 precedents).
15881
+ */
15882
+ var LlmImageSchema = object({
15883
+ bytes: _instanceof(Uint8Array),
15884
+ mimeType: string()
15885
+ });
15886
+ var LlmGenerateBaseInputSchema = object({
15887
+ /** Collection routing (the notification-output posture). */
15888
+ addonId: string().optional(),
15889
+ /** Explicit profile; else the resolution chain (spec §3). */
15890
+ profileId: string().optional(),
15891
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15892
+ consumer: string(),
15893
+ system: string().optional(),
15894
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
15895
+ prompt: string(),
15896
+ /** Structured output adapter-mapped (response_format / forced tool / responseSchema). */
15897
+ jsonSchema: record(string(), unknown()).optional(),
15898
+ /** Per-call override of the profile default. */
15899
+ maxTokens: number().int().positive().optional(),
15900
+ temperature: number().optional()
15901
+ });
15902
+ /**
15903
+ * `llm-runtime` node-side managed llama.cpp executor (spec §4). Registered
15904
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15905
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` normal
15906
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15907
+ * this only through the `llm` cap's methods.
15564
15908
  *
15565
- * `mount: skip` the cap is read server-side by the core auth router
15566
- * (`registry.getCollection('login-method')`), never mounted as its own
15567
- * tRPC router.
15909
+ * One running llama-server child per node in v1 (models are RAM-heavy).
15910
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15911
+ * watchdog — operator decision #3).
15568
15912
  */
15569
- /** When a login method renders in the two-phase login flow. */
15570
- var LoginStageEnum = _enum(["primary", "second-factor"]);
15571
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
15572
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
15913
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
15573
15914
  object({
15574
- kind: literal("redirect"),
15575
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
15576
- id: string(),
15577
- /** Operator-facing button label. */
15578
- label: string(),
15579
- /** lucide-react icon name. */
15580
- icon: string().optional(),
15581
- /** Addon-owned HTTP route the button navigates to (GET). */
15582
- startUrl: string(),
15583
- stage: LoginStageEnum
15915
+ kind: literal("catalog"),
15916
+ catalogId: string()
15584
15917
  }),
15585
15918
  object({
15586
- kind: literal("widget"),
15587
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
15588
- id: string(),
15589
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
15590
- addonId: string(),
15591
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
15592
- bundle: string(),
15593
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
15594
- remote: WidgetRemoteSchema,
15595
- stage: LoginStageEnum
15919
+ kind: literal("url"),
15920
+ url: string(),
15921
+ sha256: string().optional()
15596
15922
  }),
15597
15923
  object({
15598
- kind: literal("passkey"),
15599
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
15600
- id: string(),
15601
- /** Operator-facing button label. */
15602
- label: string(),
15603
- stage: LoginStageEnum,
15604
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
15605
- rpId: string(),
15606
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
15607
- origin: string().nullable()
15924
+ kind: literal("path"),
15925
+ path: string()
15608
15926
  })
15609
15927
  ]);
15610
- method(_void(), array(LoginMethodContributionSchema).readonly());
15611
- var CpuBreakdownSchema = object({
15612
- total: number(),
15613
- user: number(),
15614
- system: number(),
15615
- irq: number(),
15616
- nice: number(),
15617
- loadAvg: tuple([
15618
- number(),
15619
- number(),
15620
- number()
15621
- ]),
15622
- cores: number()
15623
- });
15624
- var MemoryInfoSchema = object({
15625
- percent: number(),
15626
- totalBytes: number(),
15627
- usedBytes: number(),
15628
- availableBytes: number(),
15629
- swapUsedBytes: number(),
15630
- swapTotalBytes: number()
15631
- });
15632
- var DiskIoSnapshotSchema = object({
15633
- readBytes: number(),
15634
- writeBytes: number(),
15635
- readOps: number(),
15636
- writeOps: number(),
15637
- timestampMs: number()
15638
- });
15639
- var NetworkIoSnapshotSchema = object({
15640
- rxBytes: number(),
15641
- txBytes: number(),
15642
- rxPackets: number(),
15643
- txPackets: number(),
15644
- rxErrors: number(),
15645
- txErrors: number(),
15646
- timestampMs: number()
15647
- });
15648
- var MetricsGpuInfoSchema = object({
15649
- utilization: number(),
15650
- model: string(),
15651
- memoryUsedBytes: number(),
15652
- memoryTotalBytes: number(),
15653
- temperature: number().nullable()
15654
- });
15655
- var ProcessResourceInfoSchema = object({
15656
- openFds: number(),
15657
- threadCount: number(),
15658
- activeHandles: number(),
15659
- activeRequests: number()
15660
- });
15661
- var PressureAvgsSchema = object({
15662
- avg10: number(),
15663
- avg60: number(),
15664
- avg300: number()
15665
- });
15666
- var PressureInfoSchema = object({
15667
- some: PressureAvgsSchema,
15668
- full: PressureAvgsSchema.nullable()
15669
- });
15670
- var SystemResourceSnapshotSchema = object({
15671
- cpu: CpuBreakdownSchema,
15672
- memory: MemoryInfoSchema,
15673
- gpu: MetricsGpuInfoSchema.nullable(),
15674
- network: NetworkIoSnapshotSchema,
15675
- disk: DiskIoSnapshotSchema,
15676
- pressure: object({
15677
- cpu: PressureInfoSchema.nullable(),
15678
- memory: PressureInfoSchema.nullable(),
15679
- io: PressureInfoSchema.nullable()
15680
- }),
15681
- process: ProcessResourceInfoSchema,
15682
- cpuTemperature: number().nullable(),
15683
- timestampMs: number()
15684
- });
15685
- var DiskSpaceInfoSchema = object({
15686
- path: string(),
15687
- totalBytes: number(),
15688
- usedBytes: number(),
15689
- availableBytes: number(),
15690
- percent: number()
15691
- });
15692
- var PidResourceStatsSchema = object({
15693
- pid: number(),
15694
- cpu: number(),
15695
- memory: number(),
15696
- /**
15697
- * Private (anonymous) resident bytes — the per-process V8 heap + native
15698
- * allocations NOT shared with other processes (Linux RssAnon). This is the
15699
- * "real" per-runner cost; summing it across runners is meaningful, unlike
15700
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
15701
- * Undefined where /proc is unavailable (e.g. macOS).
15702
- */
15703
- privateBytes: number().optional(),
15704
- /**
15705
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15706
- * code shared copy-on-write across runners. Undefined on macOS.
15707
- */
15708
- sharedBytes: number().optional()
15928
+ var ManagedRuntimeConfigSchema = object({
15929
+ /** WHERE the runtime lives — hub or any agent. */
15930
+ nodeId: string(),
15931
+ /** Closed for v1; 'ollama' is a v2 candidate. */
15932
+ engine: _enum(["llama-cpp"]),
15933
+ model: ManagedModelRefSchema,
15934
+ contextSize: number().int().default(4096),
15935
+ /** 0 = CPU-only. */
15936
+ gpuLayers: number().int().default(0),
15937
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15938
+ threads: number().int().optional(),
15939
+ /** Concurrent slots. */
15940
+ parallel: number().int().default(1),
15941
+ /** Else lazy: first generate boots it. */
15942
+ autoStart: boolean().default(false),
15943
+ /** 0 = never; frees RAM after quiet periods. */
15944
+ idleStopMinutes: number().int().default(30)
15709
15945
  });
15710
- var AddonInstanceSchema = object({
15711
- addonId: string(),
15946
+ var LlmRuntimeStatusSchema = object({
15947
+ /** Status is ALWAYS node-qualified. */
15712
15948
  nodeId: string(),
15713
- role: _enum(["hub", "worker"]),
15714
- pid: number(),
15715
15949
  state: _enum([
15716
- "starting",
15717
- "running",
15718
- "stopping",
15719
15950
  "stopped",
15720
- "crashed"
15721
- ]),
15722
- uptimeSec: number()
15723
- });
15724
- var NodeProcessSchema = object({
15725
- pid: number(),
15726
- ppid: number(),
15727
- pgid: number(),
15728
- classification: _enum([
15729
- "root",
15730
- "managed",
15731
- "system",
15732
- "ghost"
15951
+ "downloading",
15952
+ "starting",
15953
+ "ready",
15954
+ "crashed",
15955
+ "failed"
15733
15956
  ]),
15734
- /** `$process` addon binding when `managed`, else null. */
15735
- addonId: string().nullable(),
15736
- /** Kernel-reported nodeId when the process is a known agent/worker. */
15737
- nodeId: string().nullable(),
15738
- /** Truncated command line. */
15739
- command: string(),
15740
- cpuPercent: number(),
15741
- memoryRssBytes: number(),
15742
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15743
- uptimeSec: number(),
15744
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15745
- orphaned: boolean()
15746
- });
15747
- var KillProcessInputSchema = object({
15748
- pid: number(),
15749
- /** Force = SIGKILL. Default is SIGTERM. */
15750
- force: boolean().optional()
15751
- });
15752
- var KillProcessResultSchema = object({
15753
- success: boolean(),
15754
- reason: string().optional(),
15755
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15756
- });
15757
- var DumpHeapSnapshotInputSchema = object({
15758
- /** The addon whose runner should dump a heap snapshot. */
15759
- addonId: string() });
15760
- var DumpHeapSnapshotResultSchema = object({
15761
- success: boolean(),
15762
- /** Path of the written .heapsnapshot inside the runner's container/host. */
15763
- path: string().optional(),
15764
- /** Process pid that was signalled. */
15765
15957
  pid: number().optional(),
15766
- reason: string().optional()
15958
+ port: number().optional(),
15959
+ modelPath: string().optional(),
15960
+ modelId: string().optional(),
15961
+ downloadProgress: number().min(0).max(1).optional(),
15962
+ lastError: string().optional(),
15963
+ crashesInWindow: number(),
15964
+ /** Child RSS (sampled best-effort). */
15965
+ memoryBytes: number().optional(),
15966
+ vramBytes: number().optional()
15967
+ });
15968
+ var LlmNodeModelSchema = object({
15969
+ file: string(),
15970
+ sizeBytes: number(),
15971
+ catalogId: string().optional(),
15972
+ installedAt: number().optional()
15767
15973
  });
15768
- var SystemMetricsSchema = object({
15769
- cpuPercent: number(),
15770
- memoryPercent: number(),
15771
- memoryUsedMB: number(),
15772
- memoryTotalMB: number(),
15773
- diskPercent: number().optional(),
15774
- temperature: number().optional(),
15775
- gpuPercent: number().optional(),
15776
- gpuMemoryPercent: number().optional()
15974
+ var LlmRuntimeDiskUsageSchema = object({
15975
+ nodeId: string(),
15976
+ modelsBytes: number(),
15977
+ freeBytes: number().optional()
15777
15978
  });
15778
- 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, {
15979
+ method(LlmGenerateBaseInputSchema.extend({
15980
+ images: array(LlmImageSchema).optional(),
15981
+ runtime: ManagedRuntimeConfigSchema,
15982
+ /** The managed profile's timeout, threaded by the hub provider. */
15983
+ timeoutMs: number().int().positive().optional()
15984
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15779
15985
  kind: "mutation",
15780
15986
  auth: "admin"
15781
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15987
+ }), method(object({}), _void(), {
15782
15988
  kind: "mutation",
15783
15989
  auth: "admin"
15784
- });
15785
- var modelConvertCapability = {
15786
- name: "model-convert",
15787
- scope: "system",
15788
- mode: "singleton",
15789
- internal: true,
15790
- methods: { convert: method(object({
15791
- sourceUrl: string(),
15792
- metadata: ModelConvertMetadataSchema,
15793
- targets: array(ConvertTargetSchema).min(1).readonly(),
15794
- calibrationRef: string().optional(),
15795
- sessionId: string().optional()
15796
- }), ConvertResultSchema, {
15797
- kind: "mutation",
15798
- auth: "admin",
15799
- timeoutMs: 6e5
15800
- }) }
15801
- };
15802
- method(object({
15803
- nodeId: string(),
15804
- modelId: string(),
15805
- format: _enum(MODEL_FORMATS),
15806
- entry: ModelCatalogEntrySchema
15807
- }), object({
15808
- ok: boolean(),
15809
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
15810
- sha256: string(),
15811
- bytes: number(),
15812
- /** The target node's modelsDir the artifact landed in. */
15813
- path: string()
15814
- }), {
15990
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15815
15991
  kind: "mutation",
15816
15992
  auth: "admin"
15817
- });
15818
- /**
15819
- * `mqtt-broker` — broker-registry cap.
15820
- *
15821
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15822
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15823
- * and (b) the connection details a consumer addon needs to spin up
15824
- * its OWN `mqtt.js` client.
15825
- *
15826
- * Why: pub/sub routing over the system event-bus loses fidelity
15827
- * (callback shape, QoS guarantees, will/retain semantics) and adds
15828
- * refcount bookkeeping that addons would rather own themselves. The
15829
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
15830
- * features anyway — give it the connection config, get out of the way.
15831
- *
15832
- * Consumer flow:
15833
- * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
15834
- * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
15835
- * client.subscribe('zigbee2mqtt/+')
15836
- *
15837
- * Collection mode: multiple brokers (e.g. one local mosquitto + one
15838
- * cloud bridge). The "embedded" entry (when present) is just another
15839
- * broker in the registry — its lifecycle is owned by the addon that
15840
- * spawned it.
15841
- */
15842
- var BrokerKindSchema = _enum(["external", "embedded"]);
15993
+ }), method(object({ file: string() }), _void(), {
15994
+ kind: "mutation",
15995
+ auth: "admin"
15996
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15843
15997
  /**
15844
- * Broker live-probe status.
15998
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15999
+ * methods concat-fan across providers; single-row methods route to ONE
16000
+ * provider by the `addonId` in the call input (the notification-output
16001
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
16002
+ * (hub-placed); the cap stays open for future providers.
15845
16003
  *
15846
- * - `connected` last probe completed a clean CONNACK
15847
- * - `disconnected` — no probe has run yet (cold cache)
15848
- * - `auth-failed` CONNACK refused with auth error (RC 4 / 5)
15849
- * - `unreachable` — TCP connect timed out / refused
15850
- * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
16004
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
16005
+ * `apiKey` is a password field providers REDACT it on read and merge on
16006
+ * write; a stored key NEVER round-trips to a client.
15851
16007
  */
15852
- var BrokerStatusSchema$1 = _enum([
15853
- "connected",
15854
- "disconnected",
15855
- "auth-failed",
15856
- "unreachable",
15857
- "tls-error"
16008
+ var LlmProfileKindSchema = _enum([
16009
+ "openai-compatible",
16010
+ "openai",
16011
+ "anthropic",
16012
+ "google",
16013
+ "managed-local"
15858
16014
  ]);
15859
- var BrokerInfoSchema = object({
16015
+ var LlmProfileSchema = object({
15860
16016
  id: string(),
15861
16017
  name: string(),
15862
- url: string(),
15863
- kind: BrokerKindSchema,
15864
- status: BrokerStatusSchema$1,
15865
- latencyMs: number().nullable(),
15866
- error: string().optional(),
15867
- /** Embedded brokers only: number of MQTT clients currently connected. */
15868
- connectedClients: number().int().nonnegative().optional(),
15869
- /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
15870
- lastCheckedAt: number().optional()
16018
+ kind: LlmProfileKindSchema,
16019
+ /** Stamped by the provider — keeps the fanned catalog routable. */
16020
+ addonId: string(),
16021
+ enabled: boolean(),
16022
+ /** Vendor model id, or the managed runtime's loaded model. */
16023
+ model: string(),
16024
+ /** Required for openai-compatible; override for cloud kinds. */
16025
+ baseUrl: string().optional(),
16026
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
16027
+ apiKey: string().optional(),
16028
+ supportsVision: boolean(),
16029
+ temperature: number().min(0).max(2).optional(),
16030
+ maxTokens: number().int().positive().optional(),
16031
+ timeoutMs: number().int().positive().default(6e4),
16032
+ extraHeaders: record(string(), string()).optional(),
16033
+ /** kind === 'managed-local' only (spec §4). */
16034
+ runtime: ManagedRuntimeConfigSchema.optional()
15871
16035
  });
15872
- /**
15873
- * Connection details — what a consumer needs to call
15874
- * `mqtt.connect(url, options)`. We split URL + credentials so the
15875
- * consumer can pass them as `mqtt.connect(url, { username, password })`
15876
- * instead of stuffing creds into the URL (which leaks them into logs).
15877
- */
15878
- var BrokerConnectionDetailsSchema = object({
15879
- url: string(),
15880
- username: string().optional(),
15881
- password: string().optional(),
15882
- /**
15883
- * Suggested prefix for `clientId`. Each consumer should suffix this
15884
- * with its own discriminator (addon id, instance id) so reconnects
15885
- * don't kick each other off (MQTT spec: clientId must be unique per
15886
- * broker).
15887
- */
15888
- clientIdPrefix: string().optional()
16036
+ /** ConfigUISchema tree passed through untyped on the wire (the
16037
+ * notification-output `ConfigSchemaPassthrough` precedent at
16038
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
16039
+ var ConfigSchemaPassthrough$1 = unknown();
16040
+ var LlmProfileKindDescriptorSchema = object({
16041
+ kind: LlmProfileKindSchema,
16042
+ label: string(),
16043
+ icon: string(),
16044
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
16045
+ addonId: string(),
16046
+ configSchema: ConfigSchemaPassthrough$1
15889
16047
  });
15890
- var AddBrokerInputSchema = object({
15891
- name: string().min(1),
15892
- url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
15893
- username: string().optional(),
15894
- password: string().optional(),
15895
- clientIdPrefix: string().optional()
16048
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
16049
+ var LlmDefaultSchema = object({
16050
+ selector: LlmDefaultSelectorSchema,
16051
+ profileId: string()
15896
16052
  });
15897
- var AddBrokerResultSchema = object({ id: string() });
15898
- var IdInputSchema = object({ id: string() });
15899
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
15900
- ok: literal(true),
15901
- latencyMs: number()
15902
- }), object({
15903
- ok: literal(false),
15904
- error: string()
15905
- })]);
15906
- var StartEmbeddedInputSchema = object({
15907
- port: number().int().min(1).max(65535).default(1883),
15908
- /** Allow anonymous connect (no username/password). Default: false. */
15909
- allowAnonymous: boolean().default(false),
15910
- /** Optional shared username/password for clients. */
15911
- username: string().optional(),
15912
- password: string().optional()
16053
+ /** Server-side rollup row getUsage never dumps raw call rows (spec §6). */
16054
+ var LlmUsageRollupSchema = object({
16055
+ day: string(),
16056
+ consumer: string(),
16057
+ profileId: string(),
16058
+ calls: number(),
16059
+ okCalls: number(),
16060
+ errorCalls: number(),
16061
+ inputTokens: number(),
16062
+ outputTokens: number(),
16063
+ avgLatencyMs: number()
15913
16064
  });
15914
- var StartEmbeddedResultSchema = object({
16065
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
16066
+ var ManagedModelCatalogEntrySchema = object({
15915
16067
  id: string(),
15916
- url: string()
15917
- });
15918
- var StatusSchema = object({
15919
- brokerCount: number(),
15920
- embeddedRunning: boolean()
15921
- });
15922
- 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);
15923
- var NetworkEndpointSchema = object({
16068
+ label: string(),
16069
+ family: string(),
16070
+ purpose: _enum(["text", "vision"]),
15924
16071
  url: string(),
15925
- hostname: string(),
15926
- port: number(),
15927
- protocol: _enum(["http", "https"])
16072
+ sha256: string(),
16073
+ sizeBytes: number(),
16074
+ quantization: string(),
16075
+ /** Load-time guidance shown in the picker. */
16076
+ minRamBytes: number(),
16077
+ contextSizeDefault: number().int(),
16078
+ /** Vision models: companion projector file. */
16079
+ mmprojUrl: string().optional()
15928
16080
  });
15929
- var NetworkAccessStatusSchema = object({
15930
- connected: boolean(),
15931
- endpoint: NetworkEndpointSchema.nullable(),
16081
+ var LlmRuntimeNodeSchema = object({
16082
+ nodeId: string(),
16083
+ reachable: boolean(),
16084
+ status: LlmRuntimeStatusSchema.optional(),
16085
+ disk: LlmRuntimeDiskUsageSchema.optional(),
15932
16086
  error: string().optional()
15933
16087
  });
15934
- /**
15935
- * Optional, richer endpoint shape returned by providers that expose
15936
- * MORE than one ingress concurrently (Tailscale Ingress with mixed
15937
- * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
15938
- * the originating provider config (mode + sourcePort) so the
15939
- * orchestrator UI can label rows distinctly. Providers that expose only
15940
- * one endpoint just omit `listEndpoints` from their provider impl.
15941
- */
15942
- var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
15943
- /**
15944
- * Stable id within the provider — typically `<mode>-<sourcePort>` so
15945
- * the orchestrator can dedupe across `listEndpoints` polls.
15946
- */
15947
- id: string(),
15948
- /** Operator-facing label (mirrors `MeshEndpoint.label`). */
15949
- label: string(),
15950
- /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
15951
- mode: string().optional(),
15952
- /** Originating local port the ingress fronts (informational). */
15953
- sourcePort: number().optional()
16088
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16089
+ var ProfileRefInputSchema = object({
16090
+ addonId: string(),
16091
+ profileId: string()
16092
+ });
16093
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16094
+ kind: "mutation",
16095
+ auth: "admin"
16096
+ }), method(ProfileRefInputSchema, _void(), {
16097
+ kind: "mutation",
16098
+ auth: "admin"
16099
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16100
+ kind: "mutation",
16101
+ auth: "admin"
16102
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
16103
+ selector: LlmDefaultSelectorSchema,
16104
+ profileId: string().nullable()
16105
+ }), _void(), {
16106
+ kind: "mutation",
16107
+ auth: "admin"
16108
+ }), method(object({
16109
+ since: number().optional(),
16110
+ until: number().optional(),
16111
+ consumer: string().optional(),
16112
+ profileId: string().optional()
16113
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
16114
+ nodeId: string(),
16115
+ model: ManagedModelRefSchema
16116
+ }), _void(), {
16117
+ kind: "mutation",
16118
+ auth: "admin"
16119
+ }), method(object({
16120
+ nodeId: string(),
16121
+ file: string()
16122
+ }), _void(), {
16123
+ kind: "mutation",
16124
+ auth: "admin"
16125
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16126
+ kind: "mutation",
16127
+ auth: "admin"
16128
+ }), method(ProfileRefInputSchema, _void(), {
16129
+ kind: "mutation",
16130
+ auth: "admin"
16131
+ });
16132
+ var LogLevelSchema = _enum([
16133
+ "debug",
16134
+ "info",
16135
+ "warn",
16136
+ "error"
16137
+ ]);
16138
+ var LogEntrySchema = object({
16139
+ timestamp: date(),
16140
+ level: LogLevelSchema,
16141
+ scope: array(string()),
16142
+ message: string(),
16143
+ meta: record(string(), unknown()).optional(),
16144
+ tags: record(string(), string()).optional()
15954
16145
  });
15955
- method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
16146
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
16147
+ scope: array(string()).optional(),
16148
+ level: LogLevelSchema.optional(),
16149
+ since: date().optional(),
16150
+ until: date().optional(),
16151
+ limit: number().optional(),
16152
+ tags: record(string(), string()).optional()
16153
+ }), array(LogEntrySchema).readonly());
15956
16154
  /**
15957
- * notification-outputcanonical, capability-gated notification delivery.
16155
+ * `login-method`collection cap through which auth addons contribute
16156
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
16157
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
16158
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
16159
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
16160
+ * procedure aggregates them for the unauthenticated login page.
15958
16161
  *
15959
- * Apprise-derived model (see
15960
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
15961
- * callers emit ONE canonical `Notification`; each provider declares a
15962
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
15963
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
15964
- * message to what the kind supports — callers never special-case a service.
16162
+ * A contribution is a discriminated union on `kind`:
15965
16163
  *
15966
- * DESIGN DECISIONS (locked):
15967
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
15968
- * `setTargetEnabled`), each provider persisting via the `settings-store`
15969
- * cap. Rationale: the admin UI needs one uniform surface across the
15970
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
15971
- * alternative would fork the UI per addon and cannot host the
15972
- * discovery→adopt flow.
15973
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
15974
- * the generated cap-mount auto-`concatCollection`-fans them across every
15975
- * registered provider (notifiers addon + HA addon) so one catalog is
15976
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
15977
- * `addonId` the generated collection router extracts from the call input.
15978
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
15979
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
15980
- * `storage` / `storage-provider` / `recording` caps over the same path. No
15981
- * base64 fallback needed.
16164
+ * - `redirect` a declarative button. The login page renders a generic
16165
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
16166
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
16167
+ * ZERO shell-side JS. A future SSO addon plugs in the same way the
16168
+ * login page needs NO change.
15982
16169
  *
15983
- * TODO (deferred, closed-set change separate decision): add
15984
- * `providerKind: 'notify'` so notification providers surface on the unified
15985
- * admin "Integrations" page.
15986
- */
15987
- /**
15988
- * Zentik-derived typed-media enum — the superset across every kind. Each
15989
- * adapter picks what it supports and the degrade engine filters the rest.
15990
- */
15991
- var AttachmentMediaTypeSchema = _enum([
15992
- "image",
15993
- "video",
15994
- "gif",
15995
- "audio",
15996
- "icon"
15997
- ]);
15998
- /**
15999
- * A single attachment. Exactly one of `url` (remote source, most adapters
16000
- * prefer this) or `bytes` (inline source; required for Pushover-style
16001
- * bytes-only kinds) MUST be present the degrade engine expresses a
16002
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
16170
+ * - `widget` a Module-Federation widget the login page mounts (via
16171
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
16172
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
16173
+ * mechanism kept for future use; no shipped addon uses it on the login
16174
+ * page (the passkey ceremony below runs natively in the shell instead).
16175
+ *
16176
+ * - `passkey` a declarative WebAuthn ceremony the shell renders
16177
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
16178
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
16179
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
16180
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
16181
+ * fetching any remote code pre-auth. Contribution stays unconditional —
16182
+ * enrollment state is never leaked pre-auth; visibility is a shell
16183
+ * decision.
16184
+ *
16185
+ * Every contribution carries a `stage`:
16186
+ * - `primary` — shown on the first credentials screen (OIDC /
16187
+ * magic-link buttons; a future usernameless passkey).
16188
+ * - `second-factor` — shown AFTER the password leg, gated on the
16189
+ * returned `factors` (passkey-as-2FA today).
16190
+ *
16191
+ * `mount: skip` — the cap is read server-side by the core auth router
16192
+ * (`registry.getCollection('login-method')`), never mounted as its own
16193
+ * tRPC router.
16003
16194
  */
16004
- var AttachmentSchema = object({
16005
- mediaType: AttachmentMediaTypeSchema,
16006
- url: string().optional(),
16007
- bytes: _instanceof(Uint8Array).optional(),
16008
- mime: string().optional(),
16009
- name: string().optional()
16010
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
16011
- var NotificationFormatSchema = _enum([
16012
- "text",
16013
- "markdown",
16014
- "html"
16195
+ /** When a login method renders in the two-phase login flow. */
16196
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
16197
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
16198
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
16199
+ object({
16200
+ kind: literal("redirect"),
16201
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
16202
+ id: string(),
16203
+ /** Operator-facing button label. */
16204
+ label: string(),
16205
+ /** lucide-react icon name. */
16206
+ icon: string().optional(),
16207
+ /** Addon-owned HTTP route the button navigates to (GET). */
16208
+ startUrl: string(),
16209
+ stage: LoginStageEnum
16210
+ }),
16211
+ object({
16212
+ kind: literal("widget"),
16213
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
16214
+ id: string(),
16215
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
16216
+ addonId: string(),
16217
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
16218
+ bundle: string(),
16219
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
16220
+ remote: WidgetRemoteSchema,
16221
+ stage: LoginStageEnum
16222
+ }),
16223
+ object({
16224
+ kind: literal("passkey"),
16225
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
16226
+ id: string(),
16227
+ /** Operator-facing button label. */
16228
+ label: string(),
16229
+ stage: LoginStageEnum,
16230
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
16231
+ rpId: string(),
16232
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
16233
+ origin: string().nullable()
16234
+ })
16015
16235
  ]);
16016
- /** A single tap-through action button. */
16017
- var NotificationActionSchema = object({
16018
- id: string(),
16019
- label: string(),
16020
- url: string().optional()
16236
+ method(_void(), array(LoginMethodContributionSchema).readonly());
16237
+ var CpuBreakdownSchema = object({
16238
+ total: number(),
16239
+ user: number(),
16240
+ system: number(),
16241
+ irq: number(),
16242
+ nice: number(),
16243
+ loadAvg: tuple([
16244
+ number(),
16245
+ number(),
16246
+ number()
16247
+ ]),
16248
+ cores: number()
16021
16249
  });
16022
- /**
16023
- * The canonical notification. `body` is the only hard field (Apprise model).
16024
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
16025
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
16026
- * the adapter maps this ordinal onto its native level. `level?` is an
16027
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
16028
- * `priority` for that one target.
16029
- */
16030
- var NotificationSchema = object({
16031
- body: string(),
16032
- title: string().optional(),
16033
- format: NotificationFormatSchema.default("text"),
16034
- priority: number().int().min(1).max(5).default(3),
16035
- level: string().optional(),
16036
- attachments: array(AttachmentSchema).optional(),
16037
- clickUrl: string().optional(),
16038
- actions: array(NotificationActionSchema).optional(),
16039
- sound: string().optional(),
16040
- ttl: number().optional(),
16041
- tag: string().optional(),
16042
- deviceId: number().optional(),
16043
- eventId: string().optional(),
16044
- metadata: record(string(), unknown()).optional()
16250
+ var MemoryInfoSchema = object({
16251
+ percent: number(),
16252
+ totalBytes: number(),
16253
+ usedBytes: number(),
16254
+ availableBytes: number(),
16255
+ swapUsedBytes: number(),
16256
+ swapTotalBytes: number()
16257
+ });
16258
+ var DiskIoSnapshotSchema = object({
16259
+ readBytes: number(),
16260
+ writeBytes: number(),
16261
+ readOps: number(),
16262
+ writeOps: number(),
16263
+ timestampMs: number()
16264
+ });
16265
+ var NetworkIoSnapshotSchema = object({
16266
+ rxBytes: number(),
16267
+ txBytes: number(),
16268
+ rxPackets: number(),
16269
+ txPackets: number(),
16270
+ rxErrors: number(),
16271
+ txErrors: number(),
16272
+ timestampMs: number()
16045
16273
  });
16046
- /** One declared native severity/priority level for a kind. */
16047
- var TargetKindLevelSchema = object({
16048
- id: string(),
16049
- label: string(),
16050
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
16051
- ordinal: number().int().min(1).max(5).nullable(),
16052
- flags: object({
16053
- critical: boolean().optional(),
16054
- silent: boolean().optional(),
16055
- noPush: boolean().optional()
16056
- }).optional(),
16057
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
16058
- requires: array(string()).optional(),
16059
- description: string().optional()
16274
+ var MetricsGpuInfoSchema = object({
16275
+ utilization: number(),
16276
+ model: string(),
16277
+ memoryUsedBytes: number(),
16278
+ memoryTotalBytes: number(),
16279
+ temperature: number().nullable()
16060
16280
  });
16061
- /** The full capability block consulted before dispatch. */
16062
- var TargetKindCapsSchema = object({
16063
- attachments: object({
16064
- mediaTypes: array(AttachmentMediaTypeSchema),
16065
- mode: _enum([
16066
- "url",
16067
- "bytes",
16068
- "both"
16069
- ]),
16070
- max: number().int().nonnegative(),
16071
- maxBytes: number().int().positive().optional()
16281
+ var ProcessResourceInfoSchema = object({
16282
+ openFds: number(),
16283
+ threadCount: number(),
16284
+ activeHandles: number(),
16285
+ activeRequests: number()
16286
+ });
16287
+ var PressureAvgsSchema = object({
16288
+ avg10: number(),
16289
+ avg60: number(),
16290
+ avg300: number()
16291
+ });
16292
+ var PressureInfoSchema = object({
16293
+ some: PressureAvgsSchema,
16294
+ full: PressureAvgsSchema.nullable()
16295
+ });
16296
+ var SystemResourceSnapshotSchema = object({
16297
+ cpu: CpuBreakdownSchema,
16298
+ memory: MemoryInfoSchema,
16299
+ gpu: MetricsGpuInfoSchema.nullable(),
16300
+ network: NetworkIoSnapshotSchema,
16301
+ disk: DiskIoSnapshotSchema,
16302
+ pressure: object({
16303
+ cpu: PressureInfoSchema.nullable(),
16304
+ memory: PressureInfoSchema.nullable(),
16305
+ io: PressureInfoSchema.nullable()
16072
16306
  }),
16073
- /** Max action buttons (0 = none). */
16074
- actions: number().int().nonnegative(),
16075
- levels: array(TargetKindLevelSchema),
16076
- format: array(NotificationFormatSchema),
16077
- clickUrl: boolean(),
16078
- sound: boolean(),
16079
- ttl: boolean(),
16080
- bodyMaxLen: number().int().positive()
16307
+ process: ProcessResourceInfoSchema,
16308
+ cpuTemperature: number().nullable(),
16309
+ timestampMs: number()
16081
16310
  });
16082
- /**
16083
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
16084
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
16085
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
16086
- * the union is large and not meant for runtime validation here; the exported
16087
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
16088
- */
16089
- var ConfigSchemaPassthrough = unknown();
16090
- var TargetKindSchema = object({
16091
- kind: string(),
16092
- label: string(),
16093
- icon: string(),
16094
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
16095
- addonId: string(),
16096
- configSchema: ConfigSchemaPassthrough,
16097
- supportsDiscovery: boolean(),
16098
- caps: TargetKindCapsSchema
16311
+ var DiskSpaceInfoSchema = object({
16312
+ path: string(),
16313
+ totalBytes: number(),
16314
+ usedBytes: number(),
16315
+ availableBytes: number(),
16316
+ percent: number()
16099
16317
  });
16100
- /**
16101
- * A persisted target. `config` holds secrets; providers REDACT secret fields
16102
- * (return a presence marker only) when serving `listTargets` — never
16103
- * round-trip a stored secret to the UI.
16104
- */
16105
- var TargetSchema = object({
16106
- id: string(),
16107
- name: string(),
16108
- kind: string(),
16318
+ var PidResourceStatsSchema = object({
16319
+ pid: number(),
16320
+ cpu: number(),
16321
+ memory: number(),
16322
+ /**
16323
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
16324
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
16325
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
16326
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
16327
+ * Undefined where /proc is unavailable (e.g. macOS).
16328
+ */
16329
+ privateBytes: number().optional(),
16330
+ /**
16331
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
16332
+ * code shared copy-on-write across runners. Undefined on macOS.
16333
+ */
16334
+ sharedBytes: number().optional()
16335
+ });
16336
+ var AddonInstanceSchema = object({
16109
16337
  addonId: string(),
16110
- enabled: boolean(),
16111
- config: record(string(), unknown())
16338
+ nodeId: string(),
16339
+ role: _enum(["hub", "worker"]),
16340
+ pid: number(),
16341
+ state: _enum([
16342
+ "starting",
16343
+ "running",
16344
+ "stopping",
16345
+ "stopped",
16346
+ "crashed"
16347
+ ]),
16348
+ uptimeSec: number()
16112
16349
  });
16113
- /** A discovery-surfaced candidate (config is partial + non-secret). */
16114
- var DiscoveredTargetSchema = object({
16115
- kind: string(),
16116
- suggestedName: string(),
16117
- config: record(string(), unknown())
16350
+ var NodeProcessSchema = object({
16351
+ pid: number(),
16352
+ ppid: number(),
16353
+ pgid: number(),
16354
+ classification: _enum([
16355
+ "root",
16356
+ "managed",
16357
+ "system",
16358
+ "ghost"
16359
+ ]),
16360
+ /** `$process` addon binding when `managed`, else null. */
16361
+ addonId: string().nullable(),
16362
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
16363
+ nodeId: string().nullable(),
16364
+ /** Truncated command line. */
16365
+ command: string(),
16366
+ cpuPercent: number(),
16367
+ memoryRssBytes: number(),
16368
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
16369
+ uptimeSec: number(),
16370
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
16371
+ orphaned: boolean()
16118
16372
  });
16119
- /** The degrade engine's report — what was resolved / dropped / degraded. */
16120
- var RenderedAsSchema = object({
16121
- level: string(),
16122
- format: NotificationFormatSchema,
16123
- attachmentsSent: number().int().nonnegative(),
16124
- actionsSent: number().int().nonnegative(),
16125
- truncated: boolean(),
16126
- dropped: array(string())
16373
+ var KillProcessInputSchema = object({
16374
+ pid: number(),
16375
+ /** Force = SIGKILL. Default is SIGTERM. */
16376
+ force: boolean().optional()
16127
16377
  });
16128
- var SendResultSchema = object({
16378
+ var KillProcessResultSchema = object({
16129
16379
  success: boolean(),
16130
- error: string().optional(),
16131
- renderedAs: RenderedAsSchema.optional()
16380
+ reason: string().optional(),
16381
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
16382
+ });
16383
+ var DumpHeapSnapshotInputSchema = object({
16384
+ /** The addon whose runner should dump a heap snapshot. */
16385
+ addonId: string() });
16386
+ var DumpHeapSnapshotResultSchema = object({
16387
+ success: boolean(),
16388
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
16389
+ path: string().optional(),
16390
+ /** Process pid that was signalled. */
16391
+ pid: number().optional(),
16392
+ reason: string().optional()
16393
+ });
16394
+ var SystemMetricsSchema = object({
16395
+ cpuPercent: number(),
16396
+ memoryPercent: number(),
16397
+ memoryUsedMB: number(),
16398
+ memoryTotalMB: number(),
16399
+ diskPercent: number().optional(),
16400
+ temperature: number().optional(),
16401
+ gpuPercent: number().optional(),
16402
+ gpuMemoryPercent: number().optional()
16403
+ });
16404
+ 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, {
16405
+ kind: "mutation",
16406
+ auth: "admin"
16407
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
16408
+ kind: "mutation",
16409
+ auth: "admin"
16410
+ });
16411
+ var modelConvertCapability = {
16412
+ name: "model-convert",
16413
+ scope: "system",
16414
+ mode: "singleton",
16415
+ internal: true,
16416
+ methods: { convert: method(object({
16417
+ sourceUrl: string(),
16418
+ metadata: ModelConvertMetadataSchema,
16419
+ targets: array(ConvertTargetSchema).min(1).readonly(),
16420
+ calibrationRef: string().optional(),
16421
+ sessionId: string().optional()
16422
+ }), ConvertResultSchema, {
16423
+ kind: "mutation",
16424
+ auth: "admin",
16425
+ timeoutMs: 6e5
16426
+ }) }
16427
+ };
16428
+ method(object({
16429
+ nodeId: string(),
16430
+ modelId: string(),
16431
+ format: _enum(MODEL_FORMATS),
16432
+ entry: ModelCatalogEntrySchema
16433
+ }), object({
16434
+ ok: boolean(),
16435
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
16436
+ sha256: string(),
16437
+ bytes: number(),
16438
+ /** The target node's modelsDir the artifact landed in. */
16439
+ path: string()
16440
+ }), {
16441
+ kind: "mutation",
16442
+ auth: "admin"
16132
16443
  });
16133
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
16134
- var TestResultSchema = SendResultSchema;
16135
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
16136
- kind: string(),
16137
- config: record(string(), unknown()).optional()
16138
- }), array(DiscoveredTargetSchema)), method(object({
16139
- targetId: string(),
16140
- notification: NotificationSchema
16141
- }), SendResultSchema, { kind: "mutation" }), method(object({
16142
- targetId: string(),
16143
- sample: NotificationSchema.optional()
16144
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
16145
- targetId: string(),
16146
- enabled: boolean()
16147
- }), _void(), { kind: "mutation" });
16148
16444
  /**
16149
- * notification-rulesthe Notification Center rule surface (P1 core).
16445
+ * `mqtt-broker`broker-registry cap.
16150
16446
  *
16151
- * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16152
- * (operator decisions D-1/D-2/D-3 are binding):
16447
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
16448
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
16449
+ * and (b) the connection details a consumer addon needs to spin up
16450
+ * its OWN `mqtt.js` client.
16153
16451
  *
16154
- * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16155
- * `notification-center` module), hooked on the durable persistence
16156
- * moments (object-event insert, TrackCloser.closeExpired) with a
16157
- * persisted outbox + retry never the lossy telemetry bus (D8).
16158
- * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16159
- * FIRST persisted detection matching the conditions (per-track dedup,
16160
- * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16161
- * `delivery: 'track-end'` evaluates the finalized track record at close.
16162
- * - DISPATCH stays behind `notification-output` (rules reference targets
16163
- * by id; per-backend params are a passthrough blob capped by the
16164
- * target kind's own caps/degrade engine).
16452
+ * Why: pub/sub routing over the system event-bus loses fidelity
16453
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
16454
+ * refcount bookkeeping that addons would rather own themselves. The
16455
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
16456
+ * features anyway give it the connection config, get out of the way.
16165
16457
  *
16166
- * P1 scope: admin-authored rules only (`createdBy` stamped from the
16167
- * server-injected caller identity the first `caller: 'required'`
16168
- * adopter). The P1 condition subset is: devices, classes(+exclude),
16169
- * minConfidence, admin zones (any/all + exclude), weekly schedule
16170
- * windows, and the optional label/identity/plate matchers. User rules,
16171
- * private zones, per-recipient fan-out and the wider condition table are
16172
- * P2+ (see spec §7).
16458
+ * Consumer flow:
16459
+ * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
16460
+ * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
16461
+ * client.subscribe('zigbee2mqtt/+')
16173
16462
  *
16174
- * All schemas here are the single source of truth — `NcRule` etc. are
16175
- * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16176
- * schema/interface drift is explicitly not repeated).
16463
+ * Collection mode: multiple brokers (e.g. one local mosquitto + one
16464
+ * cloud bridge). The "embedded" entry (when present) is just another
16465
+ * broker in the registry — its lifecycle is owned by the addon that
16466
+ * spawned it.
16177
16467
  */
16468
+ var BrokerKindSchema = _enum(["external", "embedded"]);
16178
16469
  /**
16179
- * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
16180
- * The value maps 1:1 onto the evaluated record kind:
16181
- * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16182
- * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16183
- * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16184
- * change of a LINKED device, one row per linked camera)
16185
- * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16186
- * delivery / pick-up)
16470
+ * Broker live-probe status.
16187
16471
  *
16188
- * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16189
- * `package-event` are pure trigger kinds (no urgency dimension). Extending
16190
- * this one field keeps the schema additive a rule still declares exactly
16191
- * one trigger.
16472
+ * - `connected` last probe completed a clean CONNACK
16473
+ * - `disconnected` no probe has run yet (cold cache)
16474
+ * - `auth-failed` CONNACK refused with auth error (RC 4 / 5)
16475
+ * - `unreachable` — TCP connect timed out / refused
16476
+ * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
16192
16477
  */
16193
- var NcDeliverySchema = _enum([
16194
- "immediate",
16195
- "track-end",
16196
- "device-event",
16197
- "package-event"
16478
+ var BrokerStatusSchema$1 = _enum([
16479
+ "connected",
16480
+ "disconnected",
16481
+ "auth-failed",
16482
+ "unreachable",
16483
+ "tls-error"
16198
16484
  ]);
16199
- /** Weekly schedule — OR of windows; absence on the rule = always active. */
16200
- var NcScheduleSchema = object({
16201
- windows: array(object({
16202
- /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16203
- days: array(number().int().min(0).max(6)).min(1),
16204
- startMinute: number().int().min(0).max(1439),
16205
- endMinute: number().int().min(0).max(1439)
16206
- })).min(1),
16207
- /** IANA timezone; default = hub host timezone. */
16208
- timezone: string().optional(),
16209
- /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16210
- invert: boolean().optional()
16211
- });
16212
- /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16213
- var NcPlateMatcherSchema = object({
16214
- values: array(string().min(1)).min(1),
16215
- /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16216
- maxDistance: number().int().min(0).max(3).default(1)
16217
- });
16218
- /**
16219
- * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16220
- * occupancy edge for a device — optionally narrowed to a single admin
16221
- * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16222
- * - `became-occupied` (default) — count crossed 0 → ≥ `count`
16223
- * - `became-free` — count crossed ≥ `count` → below it
16224
- * - `>=` / `<=` — count is at/over or at/under `count`
16225
- * `sustainSeconds` requires the condition hold continuously that long
16226
- * before firing (debounces flicker; 0 = fire on the first matching edge).
16227
- * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16228
- * the condition never matches. Confirmed edge-state survives addon restarts
16229
- * (declared SQLite collection, reseeded on boot).
16230
- */
16231
- var NcOccupancyConditionSchema = object({
16232
- /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16233
- zoneId: string().optional(),
16234
- /** Object class to count; absent = any class. */
16235
- className: string().optional(),
16236
- op: _enum([
16237
- "became-occupied",
16238
- "became-free",
16239
- ">=",
16240
- "<="
16241
- ]).default("became-occupied"),
16242
- count: number().int().min(0).default(1),
16243
- sustainSeconds: number().int().min(0).max(3600).default(15)
16244
- });
16245
- /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16246
- var NcZoneConditionSchema = object({
16247
- ids: array(string().min(1)).min(1),
16248
- /** Quantifier over `ids` — at least one / every one visited. */
16249
- match: _enum(["any", "all"]).default("any")
16250
- });
16251
- /**
16252
- * The P1 condition set — a flat AND of groups; absent group = pass;
16253
- * membership lists are OR within the list (spec §2.3).
16254
- */
16255
- var NcConditionsSchema = object({
16256
- /** Device scope — absent = all devices. */
16257
- devices: array(number()).optional(),
16258
- /** Detector class names (any overlap with the record's class set). */
16259
- classes: array(string().min(1)).optional(),
16260
- /** Veto classes — any overlap fails the rule. */
16261
- classesExclude: array(string().min(1)).optional(),
16262
- /** Minimum detection confidence 0–1 (fails when the record has none). */
16263
- minConfidence: number().min(0).max(1).optional(),
16264
- /** Admin zone membership over event `zones` / track `zonesVisited`. */
16265
- zones: NcZoneConditionSchema.optional(),
16266
- /** Veto zones — any hit fails the rule. */
16267
- zonesExclude: array(string().min(1)).optional(),
16268
- /**
16269
- * Exact (case-insensitive) match on the record's collapsed `label`
16270
- * (identity name / plate text / subclass).
16271
- */
16272
- labelEquals: array(string().min(1)).optional(),
16273
- /**
16274
- * Identity matcher. P1 boundary: matched against the record's collapsed
16275
- * `label` (the identity display name propagated by the face pipeline) —
16276
- * identity-ID matching rides in P2 when identity ids reach the record.
16277
- */
16278
- identities: array(string().min(1)).optional(),
16279
- /** Fuzzy plate matcher against the record's `label` (plate text). */
16280
- plates: NcPlateMatcherSchema.optional(),
16281
- /**
16282
- * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16283
- * Same P1 boundary: matched against the record's collapsed `label` (the
16284
- * identity display name). A record with NO label passes (nothing to
16285
- * exclude), unlike the include variant which fails on an absent label.
16286
- */
16287
- identitiesExclude: array(string().min(1)).optional(),
16288
- /**
16289
- * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16290
- * TRACK-END only: importance is scored at track close, so it does not exist
16291
- * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16292
- * close the value is threaded via the close-time info (the `Track` clone is
16293
- * captured before the DB row is updated, so it would otherwise read stale).
16294
- * Fails when the record carries no importance (never guess quality — the
16295
- * `minConfidence` precedent). MVP cut: a single scalar threshold.
16296
- */
16297
- minImportance: number().min(0).max(1).optional(),
16298
- /**
16299
- * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16300
- * TRACK-END only: an `immediate` / object-event subject has no closed
16301
- * lifespan, so a dwell condition never matches immediate delivery
16302
- * (documented choice — the object-event record carries no `firstSeen`,
16303
- * so dwell cannot be computed from what the subject actually carries).
16304
- */
16305
- minDwellSeconds: number().min(0).optional(),
16306
- /**
16307
- * Detection provenance filter. `any` (default / absent) matches every
16308
- * source; otherwise the subject's source must equal it. Legacy records
16309
- * with no stamped source are treated as `pipeline`. The union spans both
16310
- * record kinds — object events carry `pipeline` | `onboard`, synthetic
16311
- * tracks carry `sensor`.
16312
- */
16313
- source: _enum([
16314
- "pipeline",
16315
- "onboard",
16316
- "sensor",
16317
- "any"
16318
- ]).optional(),
16319
- /**
16320
- * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16321
- * detector `minConfidence` (that gates the object-detection score; this
16322
- * gates the recognition/OCR match score). Fails when the subject carries
16323
- * no label-match confidence (never guess). TRACK-END only: the confidence
16324
- * lives on the recognition result and reaches the subject at track close.
16325
- *
16326
- * What it measures precisely (plumbed at track close — the closer threads
16327
- * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16328
- * `importance`): the BEST recognition match confidence observed for the
16329
- * label the track carries at close — for a face, the peak cosine similarity
16330
- * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16331
- * for a plate, the peak OCR read score of the best-held plate
16332
- * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16333
- * one track the higher of the two is used. A track that ended with no
16334
- * confident identity/plate match carries no value, so the condition fails
16335
- * closed for it (an un-recognized subject).
16336
- */
16337
- minLabelConfidence: number().min(0).max(1).optional(),
16338
- /**
16339
- * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16340
- * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16341
- * against the token carried on the device-event subject (extracted from the
16342
- * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16343
- * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16344
- * eventType, so gate those with {@link sensorKinds} instead.
16345
- */
16346
- eventTypeTokens: array(string().min(1)).optional(),
16347
- /**
16348
- * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16349
- * `contact`, `button`, `device-event`) — matched against the persisted
16350
- * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16351
- */
16352
- sensorKinds: array(string().min(1)).optional(),
16353
- /**
16354
- * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16355
- * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16356
- * when the subject's phase does not match (a subject always carries a phase
16357
- * on the package-event trigger).
16358
- */
16359
- packagePhase: _enum([
16360
- "delivered",
16361
- "picked-up",
16362
- "both"
16363
- ]).optional(),
16364
- /**
16365
- * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16366
- * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16367
- * listed polygon (ZoneEngine membership semantics). Evaluated only when
16368
- * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16369
- */
16370
- customZones: array(MaskPolygonShapeSchema).optional(),
16371
- /**
16372
- * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16373
- * (optionally zone/class-scoped) occupancy count crosses the configured
16374
- * threshold and holds for `sustainSeconds`. Fail-closed on missing
16375
- * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16376
- */
16377
- occupancy: NcOccupancyConditionSchema.optional()
16485
+ var BrokerInfoSchema = object({
16486
+ id: string(),
16487
+ name: string(),
16488
+ url: string(),
16489
+ kind: BrokerKindSchema,
16490
+ status: BrokerStatusSchema$1,
16491
+ latencyMs: number().nullable(),
16492
+ error: string().optional(),
16493
+ /** Embedded brokers only: number of MQTT clients currently connected. */
16494
+ connectedClients: number().int().nonnegative().optional(),
16495
+ /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
16496
+ lastCheckedAt: number().optional()
16378
16497
  });
16379
- /** One delivery target: a `notification-output` Target ref + passthrough params. */
16380
- var NcRuleTargetSchema = object({
16381
- /** `notification-output` Target id. */
16382
- targetId: string().min(1),
16498
+ /**
16499
+ * Connection details — what a consumer needs to call
16500
+ * `mqtt.connect(url, options)`. We split URL + credentials so the
16501
+ * consumer can pass them as `mqtt.connect(url, { username, password })`
16502
+ * instead of stuffing creds into the URL (which leaks them into logs).
16503
+ */
16504
+ var BrokerConnectionDetailsSchema = object({
16505
+ url: string(),
16506
+ username: string().optional(),
16507
+ password: string().optional(),
16383
16508
  /**
16384
- * Per-backend passthrough. Recognized keys are mapped onto the canonical
16385
- * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16386
- * degrade engine drops what the backend can't render.
16509
+ * Suggested prefix for `clientId`. Each consumer should suffix this
16510
+ * with its own discriminator (addon id, instance id) so reconnects
16511
+ * don't kick each other off (MQTT spec: clientId must be unique per
16512
+ * broker).
16387
16513
  */
16388
- params: record(string(), unknown()).optional()
16514
+ clientIdPrefix: string().optional()
16515
+ });
16516
+ var AddBrokerInputSchema = object({
16517
+ name: string().min(1),
16518
+ url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
16519
+ username: string().optional(),
16520
+ password: string().optional(),
16521
+ clientIdPrefix: string().optional()
16522
+ });
16523
+ var AddBrokerResultSchema = object({ id: string() });
16524
+ var IdInputSchema = object({ id: string() });
16525
+ var TestResultSchema$1 = discriminatedUnion("ok", [object({
16526
+ ok: literal(true),
16527
+ latencyMs: number()
16528
+ }), object({
16529
+ ok: literal(false),
16530
+ error: string()
16531
+ })]);
16532
+ var StartEmbeddedInputSchema = object({
16533
+ port: number().int().min(1).max(65535).default(1883),
16534
+ /** Allow anonymous connect (no username/password). Default: false. */
16535
+ allowAnonymous: boolean().default(false),
16536
+ /** Optional shared username/password for clients. */
16537
+ username: string().optional(),
16538
+ password: string().optional()
16539
+ });
16540
+ var StartEmbeddedResultSchema = object({
16541
+ id: string(),
16542
+ url: string()
16543
+ });
16544
+ var StatusSchema = object({
16545
+ brokerCount: number(),
16546
+ embeddedRunning: boolean()
16547
+ });
16548
+ 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);
16549
+ var NetworkEndpointSchema = object({
16550
+ url: string(),
16551
+ hostname: string(),
16552
+ port: number(),
16553
+ protocol: _enum(["http", "https"])
16554
+ });
16555
+ var NetworkAccessStatusSchema = object({
16556
+ connected: boolean(),
16557
+ endpoint: NetworkEndpointSchema.nullable(),
16558
+ error: string().optional()
16389
16559
  });
16390
16560
  /**
16391
- * Media attachment policy (P1 still-image subset).
16392
- * - `best` the best AVAILABLE subject image at dispatch time (D-3).
16393
- * - `best-matching` the media that explains WHY the rule fired: a rule
16394
- * matched on identities attaches the subject's `faceCrop`, one matched on
16395
- * plates attaches the `plateCrop`; a rule with no identity/plate condition
16396
- * (or when the specific crop is missing) degrades to `best`, then
16397
- * `keyFrame`, then no attachment — never delaying the send. The matched
16398
- * condition summary is frozen on the outbox row at enqueue (like the rule
16399
- * name), so the choice never drifts from the record that fired it.
16400
- * - `keyFrame` — the clean scene frame (no subject box).
16401
- * - `none` — no attachment.
16561
+ * Optional, richer endpoint shape returned by providers that expose
16562
+ * MORE than one ingress concurrently (Tailscale Ingress with mixed
16563
+ * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
16564
+ * the originating provider config (mode + sourcePort) so the
16565
+ * orchestrator UI can label rows distinctly. Providers that expose only
16566
+ * one endpoint just omit `listEndpoints` from their provider impl.
16402
16567
  */
16403
- var NcMediaPolicySchema = object({ attach: _enum([
16404
- "best",
16405
- "best-matching",
16406
- "keyFrame",
16407
- "none"
16408
- ]).default("best") });
16409
- /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16410
- var NcThrottleSchema = object({
16411
- cooldownSec: number().int().min(0).max(86400).default(60),
16412
- /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16413
- scope: _enum(["rule", "rule-device"]).default("rule-device")
16414
- });
16415
- /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16416
- var NcRuleInputSchema = object({
16417
- name: string().min(1).max(200),
16418
- enabled: boolean().default(true),
16419
- delivery: NcDeliverySchema,
16420
- conditions: NcConditionsSchema.default({}),
16421
- schedule: NcScheduleSchema.optional(),
16422
- targets: array(NcRuleTargetSchema).min(1),
16423
- media: NcMediaPolicySchema.default({ attach: "best" }),
16424
- throttle: NcThrottleSchema.default({
16425
- cooldownSec: 60,
16426
- scope: "rule-device"
16427
- }),
16428
- /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16429
- template: object({
16430
- title: string().max(500).optional(),
16431
- body: string().max(2e3).optional()
16432
- }).optional(),
16433
- /** Canonical notification priority ordinal (1..5); per-target overridable. */
16434
- priority: number().int().min(1).max(5).default(3),
16568
+ var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
16435
16569
  /**
16436
- * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16437
- * behaviour, visible to all, read-only in the viewer). Present = personal
16438
- * rule owned by this userId. Server-stamped; never trusted from a client.
16570
+ * Stable id within the provider typically `<mode>-<sourcePort>` so
16571
+ * the orchestrator can dedupe across `listEndpoints` polls.
16439
16572
  */
16440
- ownerUserId: string().optional()
16573
+ id: string(),
16574
+ /** Operator-facing label (mirrors `MeshEndpoint.label`). */
16575
+ label: string(),
16576
+ /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
16577
+ mode: string().optional(),
16578
+ /** Originating local port the ingress fronts (informational). */
16579
+ sourcePort: number().optional()
16441
16580
  });
16581
+ method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
16442
16582
  /**
16443
- * Partial patch for `updateRule` any subset of the input fields, plus the
16444
- * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16445
- * NOT a client-authored input field (it lives on the persisted rule, not the
16446
- * input), so it is added here explicitly to let the store's per-target opt-out
16447
- * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16448
- * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16449
- * `updateRule` patch.
16583
+ * notification-outputcanonical, capability-gated notification delivery.
16584
+ *
16585
+ * Apprise-derived model (see
16586
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
16587
+ * callers emit ONE canonical `Notification`; each provider declares a
16588
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
16589
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
16590
+ * message to what the kind supports — callers never special-case a service.
16591
+ *
16592
+ * DESIGN DECISIONS (locked):
16593
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
16594
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
16595
+ * cap. Rationale: the admin UI needs one uniform surface across the
16596
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
16597
+ * alternative would fork the UI per addon and cannot host the
16598
+ * discovery→adopt flow.
16599
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
16600
+ * the generated cap-mount auto-`concatCollection`-fans them across every
16601
+ * registered provider (notifiers addon + HA addon) so one catalog is
16602
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
16603
+ * `addonId` the generated collection router extracts from the call input.
16604
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
16605
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
16606
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
16607
+ * base64 fallback needed.
16608
+ *
16609
+ * TODO (deferred, closed-set change — separate decision): add
16610
+ * `providerKind: 'notify'` so notification providers surface on the unified
16611
+ * admin "Integrations" page.
16450
16612
  */
16451
- var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
16452
- /** A persisted rule. */
16453
- var NcRuleSchema = NcRuleInputSchema.extend({
16613
+ /**
16614
+ * Zentik-derived typed-media enum — the superset across every kind. Each
16615
+ * adapter picks what it supports and the degrade engine filters the rest.
16616
+ */
16617
+ var AttachmentMediaTypeSchema = _enum([
16618
+ "image",
16619
+ "video",
16620
+ "gif",
16621
+ "audio",
16622
+ "icon"
16623
+ ]);
16624
+ /**
16625
+ * A single attachment. Exactly one of `url` (remote source, most adapters
16626
+ * prefer this) or `bytes` (inline source; required for Pushover-style
16627
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
16628
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
16629
+ */
16630
+ var AttachmentSchema = object({
16631
+ mediaType: AttachmentMediaTypeSchema,
16632
+ url: string().optional(),
16633
+ bytes: _instanceof(Uint8Array).optional(),
16634
+ mime: string().optional(),
16635
+ name: string().optional()
16636
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
16637
+ var NotificationFormatSchema = _enum([
16638
+ "text",
16639
+ "markdown",
16640
+ "html"
16641
+ ]);
16642
+ /** A single tap-through action button. */
16643
+ var NotificationActionSchema = object({
16454
16644
  id: string(),
16455
- /** userId of the admin who created the rule (server-stamped caller). */
16456
- createdBy: string(),
16457
- createdAt: number(),
16458
- updatedAt: number(),
16459
- /**
16460
- * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16461
- * send time. Only a target's OWNER may add/remove its id (server-checked
16462
- * in `nc.setRuleTargetEnabled`). Defaults to empty.
16463
- */
16464
- disabledTargetIds: array(string()).default([])
16645
+ label: string(),
16646
+ url: string().optional()
16465
16647
  });
16466
- var NcTestResultSchema = object({
16467
- recordId: string(),
16468
- recordKind: _enum([
16469
- "object-event",
16470
- "track",
16471
- "device-event",
16472
- "package-event"
16473
- ]),
16474
- deviceId: number(),
16475
- timestamp: number(),
16476
- wouldFire: boolean(),
16477
- /** Condition id that failed (first failing group), when `wouldFire` is false. */
16478
- failedCondition: string().optional(),
16479
- className: string().optional(),
16480
- label: string().optional()
16648
+ /**
16649
+ * The canonical notification. `body` is the only hard field (Apprise model).
16650
+ * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
16651
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
16652
+ * the adapter maps this ordinal onto its native level. `level?` is an
16653
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
16654
+ * `priority` for that one target.
16655
+ */
16656
+ var NotificationSchema = object({
16657
+ body: string(),
16658
+ title: string().optional(),
16659
+ format: NotificationFormatSchema.default("text"),
16660
+ priority: number().int().min(1).max(5).default(3),
16661
+ level: string().optional(),
16662
+ attachments: array(AttachmentSchema).optional(),
16663
+ clickUrl: string().optional(),
16664
+ actions: array(NotificationActionSchema).optional(),
16665
+ sound: string().optional(),
16666
+ ttl: number().optional(),
16667
+ tag: string().optional(),
16668
+ deviceId: number().optional(),
16669
+ eventId: string().optional(),
16670
+ metadata: record(string(), unknown()).optional()
16481
16671
  });
16482
- var NcConditionDescriptorSchema = object({
16483
- /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16672
+ /** One declared native severity/priority level for a kind. */
16673
+ var TargetKindLevelSchema = object({
16484
16674
  id: string(),
16485
- group: _enum([
16486
- "scope",
16487
- "class",
16488
- "zones",
16489
- "quality",
16490
- "label",
16491
- "schedule",
16492
- "device",
16493
- "package",
16494
- "occupancy"
16495
- ]),
16496
16675
  label: string(),
16497
- /** Editor widget the UI renders never hardcode per-condition forms. */
16498
- valueType: _enum([
16499
- "deviceIdList",
16500
- "stringList",
16501
- "number01",
16502
- "number",
16503
- "sourceSelect",
16504
- "zoneSelection",
16505
- "zoneIdList",
16506
- "schedule",
16507
- "plateMatcher",
16508
- "packagePhase",
16509
- "polygonDraw",
16510
- "occupancy"
16511
- ]),
16512
- operator: _enum([
16513
- "in",
16514
- "notIn",
16515
- "anyOf",
16516
- "allOf",
16517
- "gte",
16518
- "fuzzyIn",
16519
- "withinSchedule"
16520
- ]),
16521
- /** Which delivery kinds the condition applies to. */
16522
- appliesTo: array(NcDeliverySchema),
16523
- phase: string(),
16676
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
16677
+ ordinal: number().int().min(1).max(5).nullable(),
16678
+ flags: object({
16679
+ critical: boolean().optional(),
16680
+ silent: boolean().optional(),
16681
+ noPush: boolean().optional()
16682
+ }).optional(),
16683
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
16684
+ requires: array(string()).optional(),
16524
16685
  description: string().optional()
16525
16686
  });
16687
+ /** The full capability block consulted before dispatch. */
16688
+ var TargetKindCapsSchema = object({
16689
+ attachments: object({
16690
+ mediaTypes: array(AttachmentMediaTypeSchema),
16691
+ mode: _enum([
16692
+ "url",
16693
+ "bytes",
16694
+ "both"
16695
+ ]),
16696
+ max: number().int().nonnegative(),
16697
+ maxBytes: number().int().positive().optional()
16698
+ }),
16699
+ /** Max action buttons (0 = none). */
16700
+ actions: number().int().nonnegative(),
16701
+ levels: array(TargetKindLevelSchema),
16702
+ format: array(NotificationFormatSchema),
16703
+ clickUrl: boolean(),
16704
+ sound: boolean(),
16705
+ ttl: boolean(),
16706
+ bodyMaxLen: number().int().positive()
16707
+ });
16526
16708
  /**
16527
- * The delivery lifecycle status of a history row a straight read of the
16528
- * durable outbox row's own status (single source of truth):
16529
- * - `pending` — enqueued, in-flight or retrying with backoff
16530
- * - `sent` — delivered (terminal)
16531
- * - `dead` dead-lettered after exhausting retries / a permanent
16532
- * backend rejection / a deleted target (terminal; carries
16533
- * the failure `error`)
16534
- *
16535
- * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
16536
- * user dimension (quiet hours / snooze) and are additive when they land.
16709
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
16710
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
16711
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
16712
+ * the union is large and not meant for runtime validation here; the exported
16713
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
16537
16714
  */
16538
- var NcHistoryStatusSchema = _enum([
16539
- "pending",
16540
- "sent",
16541
- "dead"
16542
- ]);
16543
- /** The evaluated record kind a history row descends from (one per trigger). */
16544
- var NcHistoryRecordKindSchema = _enum([
16545
- "object-event",
16546
- "track-end",
16547
- "device-event",
16548
- "package-event"
16549
- ]);
16550
- /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16551
- var NcHistorySubjectSchema = object({
16552
- className: string(),
16553
- label: string().optional(),
16554
- confidence: number().optional(),
16555
- zones: array(string()),
16556
- timestamp: number()
16715
+ var ConfigSchemaPassthrough = unknown();
16716
+ var TargetKindSchema = object({
16717
+ kind: string(),
16718
+ label: string(),
16719
+ icon: string(),
16720
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
16721
+ addonId: string(),
16722
+ configSchema: ConfigSchemaPassthrough,
16723
+ supportsDiscovery: boolean(),
16724
+ caps: TargetKindCapsSchema
16557
16725
  });
16558
16726
  /**
16559
- * One delivery-history row. This is a read-only VIEW over the durable
16560
- * outbox row (single source of truth the same row the drain loop drives;
16561
- * NO second write path, so history can never drift from delivery state).
16562
- * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16563
- * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16564
- * (fire) / `updatedAt` (last transition), `status` + `error` are the
16565
- * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16566
- * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16567
- * P1 (admin scope only).
16727
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
16728
+ * (return a presence marker only) when serving `listTargets` never
16729
+ * round-trip a stored secret to the UI.
16568
16730
  */
16569
- var NcHistoryEntrySchema = object({
16570
- /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16731
+ var TargetSchema = object({
16571
16732
  id: string(),
16572
- ruleId: string(),
16573
- /** Rule name frozen at fire time (outlives a later rename / delete). */
16574
- ruleName: string(),
16575
- /** The rule urgency/trigger that produced this delivery. */
16576
- delivery: NcDeliverySchema,
16577
- targetId: string(),
16578
- deviceId: number(),
16579
- recordKind: NcHistoryRecordKindSchema,
16580
- /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16581
- recordId: string(),
16582
- /** Present for track-scoped deliveries (object-event / track-end). */
16583
- trackId: string().optional(),
16584
- status: NcHistoryStatusSchema,
16585
- /** Delivery attempts made so far. */
16586
- attempts: number().int(),
16587
- /** Fire time (outbox enqueue). */
16588
- createdAt: number(),
16589
- /** Last transition time (terminal for sent / dead). */
16590
- updatedAt: number(),
16591
- /** Failure detail — present on a `dead` row. */
16592
- error: string().optional(),
16593
- subject: NcHistorySubjectSchema
16733
+ name: string(),
16734
+ kind: string(),
16735
+ addonId: string(),
16736
+ enabled: boolean(),
16737
+ config: record(string(), unknown())
16594
16738
  });
16595
- /**
16596
- * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16597
- * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16598
- * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16599
- * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16600
- */
16601
- var NcHistoryFilterSchema = object({
16602
- ruleId: string().optional(),
16603
- deviceId: number().optional(),
16604
- status: NcHistoryStatusSchema.optional(),
16605
- since: number().optional(),
16606
- until: number().optional(),
16607
- limit: number().int().min(1).max(500).default(100)
16739
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
16740
+ var DiscoveredTargetSchema = object({
16741
+ kind: string(),
16742
+ suggestedName: string(),
16743
+ config: record(string(), unknown())
16608
16744
  });
16609
- 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 }), {
16610
- kind: "mutation",
16611
- auth: "admin",
16612
- caller: "required"
16613
- }), method(object({
16614
- ruleId: string(),
16615
- patch: NcRulePatchSchema
16616
- }), object({ rule: NcRuleSchema }), {
16617
- kind: "mutation",
16618
- auth: "admin",
16619
- caller: "required"
16620
- }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
16621
- kind: "mutation",
16622
- auth: "admin"
16623
- }), method(object({
16624
- ruleId: string(),
16745
+ /** The degrade engine's report what was resolved / dropped / degraded. */
16746
+ var RenderedAsSchema = object({
16747
+ level: string(),
16748
+ format: NotificationFormatSchema,
16749
+ attachmentsSent: number().int().nonnegative(),
16750
+ actionsSent: number().int().nonnegative(),
16751
+ truncated: boolean(),
16752
+ dropped: array(string())
16753
+ });
16754
+ var SendResultSchema = object({
16755
+ success: boolean(),
16756
+ error: string().optional(),
16757
+ renderedAs: RenderedAsSchema.optional()
16758
+ });
16759
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
16760
+ var TestResultSchema = SendResultSchema;
16761
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
16762
+ kind: string(),
16763
+ config: record(string(), unknown()).optional()
16764
+ }), array(DiscoveredTargetSchema)), method(object({
16765
+ targetId: string(),
16766
+ notification: NotificationSchema
16767
+ }), SendResultSchema, { kind: "mutation" }), method(object({
16768
+ targetId: string(),
16769
+ sample: NotificationSchema.optional()
16770
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
16771
+ targetId: string(),
16625
16772
  enabled: boolean()
16626
- }), object({ success: literal(true) }), {
16627
- kind: "mutation",
16628
- auth: "admin"
16629
- }), method(object({
16630
- rule: NcRuleInputSchema,
16631
- lookbackMinutes: number().int().min(1).max(1440).default(60)
16632
- }), object({ results: array(NcTestResultSchema) }), {
16633
- kind: "mutation",
16634
- auth: "admin"
16635
- }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
16773
+ }), _void(), { kind: "mutation" });
16636
16774
  /**
16637
16775
  * Zod schemas for persisted record types.
16638
16776
  *
@@ -25525,6 +25663,36 @@ Object.freeze({
25525
25663
  addonId: null,
25526
25664
  access: "create"
25527
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
+ },
25528
25696
  "toast.onToast": {
25529
25697
  capName: "toast",
25530
25698
  capScope: "system",