@camstack/addon-model-studio 1.1.6 → 1.1.8

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