@camstack/addon-pipeline-orchestrator 1.2.10 → 1.2.11

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.
package/dist/index.js CHANGED
@@ -6908,6 +6908,36 @@ function randomGeneration() {
6908
6908
  if (typeof crypto !== "undefined" && crypto.randomUUID) return crypto.randomUUID();
6909
6909
  return Math.random().toString(36).slice(2, 14);
6910
6910
  }
6911
+ /**
6912
+ * Per-call node pinning for `ctx.api` capability calls.
6913
+ *
6914
+ * A capability call normally resolves to its DEFAULT provider — a `singleton`
6915
+ * cap resolves to the hub, a device-scoped cap to the device's owning node. To
6916
+ * query a SPECIFIC node's provider instead (e.g. a remote agent's own
6917
+ * in-process `platform-probe` hardware, which the hub cannot probe), pin the
6918
+ * call to that node.
6919
+ *
6920
+ * The nodeId rides OUT-OF-BAND in the tRPC call context (NOT in the validated
6921
+ * method args), so capability method signatures stay `nodeId`-free — node
6922
+ * targeting is a property of the CALL, not of the method. The transport lifts
6923
+ * it from `op.context` onto the `CapCallInput.nodeId` field (`ipcParentLink`),
6924
+ * and the hub parent's `onUnownedCall` passes it to the `CapRouteResolver`,
6925
+ * which classifies a pinned agent node as `agent-child-forward`
6926
+ * (`$agent-cap-fwd.forward` → the agent's in-process provider).
6927
+ *
6928
+ * Usage at a call site:
6929
+ *
6930
+ * await api.platformProbe.getCapabilities.query(undefined, nodePin(nodeId))
6931
+ */
6932
+ /** tRPC `op.context` key carrying a per-call node pin. */
6933
+ var CAP_NODE_PIN_CONTEXT_KEY = "__camstackNodePin";
6934
+ /**
6935
+ * Build the tRPC request options that pin a single capability call to `nodeId`.
6936
+ * Pass as the second argument to `.query(input, …)` / `.mutate(input, …)`.
6937
+ */
6938
+ function nodePin(nodeId) {
6939
+ return { context: { [CAP_NODE_PIN_CONTEXT_KEY]: nodeId } };
6940
+ }
6911
6941
  var DeviceType = /* @__PURE__ */ function(DeviceType) {
6912
6942
  DeviceType["Camera"] = "camera";
6913
6943
  DeviceType["Hub"] = "hub";
@@ -8011,16 +8041,23 @@ var StorageLocationDeclarationSchema = object({
8011
8041
  * Which node root the seeded `<id>:default` instance is placed under on a
8012
8042
  * FRESH install:
8013
8043
  * - `'data'` (default) — the node's data dir (`CAMSTACK_DATA` / boot dir),
8014
- * the appData volume. Right for small/durable data (backups, logs, models).
8044
+ * the appData volume. Right for small/durable data (logs, models).
8015
8045
  * - `'media'` — the dedicated media volume (`CAMSTACK_MEDIA_ROOT`) when that
8016
8046
  * env is set, else falls back to the data root. Right for bulky, hot media
8017
8047
  * (recordings, event media) that should stay off the appData disk.
8048
+ * - `'backup'` — the dedicated backup volume (`CAMSTACK_BACKUP_ROOT`, default
8049
+ * `/backups` in the image) so archives live on their own mount rather than
8050
+ * filling the appData disk. Falls back to the data root when unset.
8018
8051
  *
8019
8052
  * Only affects the seeded default's `basePath`; operators can repoint any
8020
8053
  * location afterwards, and a `defaultsTo` slot inherits its parent's root
8021
8054
  * regardless of this field. Absent (the common case) is treated as `'data'`.
8022
8055
  */
8023
- defaultRoot: _enum(["data", "media"]).optional()
8056
+ defaultRoot: _enum([
8057
+ "data",
8058
+ "media",
8059
+ "backup"
8060
+ ]).optional()
8024
8061
  });
8025
8062
  var DecoderStatsSchema = object({
8026
8063
  inputFps: number(),
@@ -8145,36 +8182,6 @@ var EncodeProfileSchema = object({
8145
8182
  outputArgs: array(string()).optional()
8146
8183
  });
8147
8184
  /**
8148
- * Per-call node pinning for `ctx.api` capability calls.
8149
- *
8150
- * A capability call normally resolves to its DEFAULT provider — a `singleton`
8151
- * cap resolves to the hub, a device-scoped cap to the device's owning node. To
8152
- * query a SPECIFIC node's provider instead (e.g. a remote agent's own
8153
- * in-process `platform-probe` hardware, which the hub cannot probe), pin the
8154
- * call to that node.
8155
- *
8156
- * The nodeId rides OUT-OF-BAND in the tRPC call context (NOT in the validated
8157
- * method args), so capability method signatures stay `nodeId`-free — node
8158
- * targeting is a property of the CALL, not of the method. The transport lifts
8159
- * it from `op.context` onto the `CapCallInput.nodeId` field (`ipcParentLink`),
8160
- * and the hub parent's `onUnownedCall` passes it to the `CapRouteResolver`,
8161
- * which classifies a pinned agent node as `agent-child-forward`
8162
- * (`$agent-cap-fwd.forward` → the agent's in-process provider).
8163
- *
8164
- * Usage at a call site:
8165
- *
8166
- * await api.platformProbe.getCapabilities.query(undefined, nodePin(nodeId))
8167
- */
8168
- /** tRPC `op.context` key carrying a per-call node pin. */
8169
- var CAP_NODE_PIN_CONTEXT_KEY = "__camstackNodePin";
8170
- /**
8171
- * Build the tRPC request options that pin a single capability call to `nodeId`.
8172
- * Pass as the second argument to `.query(input, …)` / `.mutate(input, …)`.
8173
- */
8174
- function nodePin(nodeId) {
8175
- return { context: { [CAP_NODE_PIN_CONTEXT_KEY]: nodeId } };
8176
- }
8177
- /**
8178
8185
  * DEVICE-POOL backend → model format — the SSOT for the multi-device inference
8179
8186
  * DESCRIPTOR path (Python per-device pools), distinct from {@link BACKEND_TO_FORMAT}
8180
8187
  * above which is the legacy NODE runtime map (where `coreml → onnx` because
@@ -9457,529 +9464,1167 @@ function resolveDeviceProfile(features) {
9457
9464
  return null;
9458
9465
  }
9459
9466
  /**
9460
- * Generic device-level status snapshot. Auto-registered by `BaseDevice`
9461
- * for every device, regardless of provider the kernel needs a uniform
9462
- * cap-keyed slice for the basic device flags every consumer expects to
9463
- * read across processes (the `online` flag in particular). Driver-specific
9464
- * caps (`battery`, `doorbell`, …) carry their domain-specific state on
9465
- * their own slices.
9467
+ * Shared geometry vocabulary for on-frame shape caps — privacy-mask,
9468
+ * motion-zones, and the detection zones/lines editor all speak this one
9469
+ * language so a single drawing-plane editor and the providers stay
9470
+ * decoupled from each cap's storage.
9466
9471
  *
9467
- * Pattern is identical to `battery`: schema-bearing `runtimeState`,
9468
- * empty `methods`, single change event. Reads land at
9469
- * `runtimeState.getCapState('device-status')`; writes at
9470
- * `runtimeState.setCapState('device-status', …)`. Cross-process
9471
- * consumers reach the same data via the `device-state` cap router
9472
- * (`getCapSlice({deviceId, capName: 'device-status'})`).
9472
+ * All coordinates are normalized 0..1 of the camera frame (top-left
9473
+ * origin). Each cap composes the SUBSET of shape kinds it supports and
9474
+ * advertises it via `supportedShapes` in its `getOptions`.
9473
9475
  */
9474
- var DeviceStatusSchema = object({
9475
- /**
9476
- * Device-level liveness. Drivers flip via `markOnline(boolean)` on
9477
- * `BaseDevice`. Provider semantics vary — RTSP aggregates broker
9478
- * stream-health, Reolink reads firmware push events, ONVIF tracks
9479
- * ping responses. This cap intentionally does NOT prescribe which
9480
- * signal drives the flag.
9481
- */
9482
- online: boolean(),
9483
- /** Ms epoch of the last `online` transition. Lets consumers tell
9484
- * apart "just came online" from "still online". */
9485
- lastChangedAt: number()
9476
+ /** A normalized 0..1 point (top-left origin). */
9477
+ var MaskPointSchema = object({
9478
+ x: number(),
9479
+ y: number()
9486
9480
  });
9487
- object({
9488
- deviceId: number(),
9489
- status: DeviceStatusSchema
9481
+ /** Axis-aligned rectangle (normalized 0..1). */
9482
+ var MaskRectShapeSchema = object({
9483
+ kind: literal("rect"),
9484
+ x: number(),
9485
+ y: number(),
9486
+ width: number(),
9487
+ height: number()
9490
9488
  });
9491
- /**
9492
- * Per-device feature/identity probe slice. Holds the runtime-resolved
9493
- * truth about what a device CAN do — which the kernel uses to:
9494
- * 1. Reconcile accessory children (hub-children spawn siren/floodlight/PIR
9495
- * based on what the firmware actually advertises).
9496
- * 2. Compute the public `features: DeviceFeature[]` array surfaced via
9497
- * `device-manager.listAll`.
9498
- * 3. Decide which optional caps (PTZ, intercom, doorbell, battery, …)
9499
- * to register on the device's capability surface.
9500
- *
9501
- * Auto-registered by `BaseDevice` for every device. Drivers populate the
9502
- * slice from `onProbe()` (kernel calls it once after register, before
9503
- * accessory reconciliation). Consumers read via:
9504
- * `runtimeState.getCapState<FeatureProbeStatus>('feature-probe')`
9505
- *
9506
- * `flags` is an open record so each driver carries its own keys without
9507
- * a centralized schema bottleneck — Reolink writes `hasPtz/hasIntercom`,
9508
- * Hikvision writes `hasSupplementalLight/hasAlarmIo`, etc.
9509
- *
9510
- * Replaces the older driver-local `deviceCache.has*` blob: the per-device
9511
- * config is for operator-edited overrides + UI snapshots; runtime probe
9512
- * results belong in runtime-state where the kernel handles persistence,
9513
- * cross-process mirroring, and reactive updates.
9514
- */
9515
- var FeatureProbeStatusSchema = object({
9516
- /**
9517
- * Driver-specific flag bag. Each driver picks its own key names — the
9518
- * cap deliberately does NOT enforce a closed enum here. Reolink keys:
9519
- * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,
9520
- * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:
9521
- * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.
9522
- */
9523
- flags: record(string(), unknown()),
9524
- /**
9525
- * Coarse driver-classification — lets cross-process consumers tell apart
9526
- * cameras / battery-cams / NVRs without re-running the probe. `null`
9527
- * before the first probe completes.
9528
- */
9529
- deviceType: string().nullable(),
9530
- /** Camera/firmware model string. `null` when the firmware doesn't expose it. */
9531
- model: string().nullable(),
9532
- /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */
9533
- channelCount: number().nullable(),
9534
- /**
9535
- * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe
9536
- * completes — drivers' `getAccessoryChildren()` should treat zero as
9537
- * "probe not done yet, return empty" so accessories aren't spawned
9538
- * before the firmware is queried.
9539
- */
9540
- lastProbedAt: number(),
9541
- /**
9542
- * Framework convention: every runtime-state slice carries this for the
9543
- * createRuntimeStateBridge stale-check helper. We keep it in sync with
9544
- * `lastProbedAt` on every write.
9545
- */
9546
- lastFetchedAt: number()
9489
+ /** Free polygon — an ordered list of normalized vertices (≥3). */
9490
+ var MaskPolygonShapeSchema = object({
9491
+ kind: literal("polygon"),
9492
+ points: array(MaskPointSchema)
9547
9493
  });
9548
- object({
9549
- deviceId: number(),
9550
- status: FeatureProbeStatusSchema
9494
+ /** Boolean cell grid — row-major, length === gridWidth*gridHeight. */
9495
+ var MaskGridShapeSchema = object({
9496
+ kind: literal("grid"),
9497
+ gridWidth: number(),
9498
+ gridHeight: number(),
9499
+ cells: array(boolean())
9551
9500
  });
9552
- object({
9553
- /** Carbon dioxide concentration in ppm. */
9554
- co2Ppm: number().min(0).optional(),
9555
- /** Total volatile organic compounds in ppb. */
9556
- vocPpb: number().min(0).optional(),
9557
- /** Particulate matter ≤ 2.5 μm in µg/m³. */
9558
- pm25: number().min(0).optional(),
9559
- /** Particulate matter ≤ 10 μm in µg/m³. */
9560
- pm10: number().min(0).optional(),
9561
- /** Composite AQI value (typically 0..500). */
9562
- aqi: number().optional(),
9563
- /** Ms epoch when the slice was last updated. */
9564
- lastFetchedAt: number(),
9565
- /** Live display unit of the single metric this slice carries (e.g. HA
9566
- * `attributes.unit_of_measurement` → 'ppm' / 'ppb' / 'µg/m³'). Each
9567
- * upstream `sensor.*` entity surfaces ONE device_class, so one unit
9568
- * per slice is unambiguous. */
9569
- unit: string().optional(),
9570
- /** Suggested decimal places for numeric display.
9571
- * Populated live from the upstream source when provided (e.g. HA
9572
- * `attributes.suggested_display_precision`). Falls back to
9573
- * auto-formatting when absent. */
9574
- precision: number().int().min(0).max(10).optional()
9501
+ discriminatedUnion("kind", [
9502
+ MaskRectShapeSchema,
9503
+ MaskPolygonShapeSchema,
9504
+ MaskGridShapeSchema,
9505
+ object({
9506
+ kind: literal("line"),
9507
+ points: array(MaskPointSchema)
9508
+ })
9509
+ ]);
9510
+ /** Every shape-kind discriminant, for `supportedShapes` advertisement. */
9511
+ var MaskShapeKindSchema = _enum([
9512
+ "rect",
9513
+ "polygon",
9514
+ "grid",
9515
+ "line"
9516
+ ]);
9517
+ /** Polygon vertex bounds when a cap supports 'polygon' (e.g. Hikvision {min:4,max:4}). */
9518
+ var MaskPolygonVerticesSchema = object({
9519
+ min: number(),
9520
+ max: number()
9521
+ });
9522
+ /** Grid dimensions when a cap supports 'grid'. */
9523
+ var MaskGridDimsSchema = object({
9524
+ width: number(),
9525
+ height: number()
9575
9526
  });
9576
- DeviceType.Sensor;
9577
9527
  /**
9578
- * Alarm-panel cap. Models HA `alarm_control_panel.*` on
9579
- * `DeviceType.AlarmPanel`. State follows HA's canonical lifecycle
9580
- * across disarmed / armed_(home|away|night|vacation|custom_bypass) /
9581
- * arming / pending / triggered / disarming.
9528
+ * notification-rules the Notification Center rule surface (P1 core).
9582
9529
  *
9583
- * Many panels require a PIN code on arm / disarm — the optional
9584
- * `code` field on the methods passes it through to the upstream
9585
- * service; it's NEVER persisted in the runtime slice or any event
9586
- * payload. The presence of a required code is signalled by
9587
- * `DeviceFeature.AlarmPinRequired` so the UI gates a code-entry
9588
- * field without a slice fetch.
9530
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
9531
+ * (operator decisions D-1/D-2/D-3 are binding):
9589
9532
  *
9590
- * `availableModes` mirrors HA's `supported_features`-derived arm
9591
- * mode list the UI renders only the buttons the panel accepts.
9592
- */
9593
- var AlarmStateSchema = _enum([
9594
- "disarmed",
9595
- "armed_home",
9596
- "armed_away",
9597
- "armed_night",
9598
- "armed_vacation",
9599
- "armed_custom_bypass",
9600
- "arming",
9601
- "disarming",
9602
- "pending",
9603
- "triggered"
9604
- ]);
9605
- var AlarmArmModeSchema = _enum([
9606
- "home",
9607
- "away",
9608
- "night",
9609
- "vacation",
9610
- "custom_bypass"
9611
- ]);
9612
- object({
9613
- /** Current lifecycle state. */
9614
- state: AlarmStateSchema,
9615
- /** Subset of arm modes the panel accepts. UI renders one button per
9616
- * mode in this list. */
9617
- availableModes: array(AlarmArmModeSchema),
9618
- /** Whether the panel requires a PIN on arm / disarm. Mirrors
9619
- * `DeviceFeature.AlarmPinRequired` for slice consumers. */
9620
- requiresCode: boolean(),
9621
- /** Ms epoch when the slice was last updated. */
9622
- lastChangedAt: number()
9623
- });
9624
- DeviceType.AlarmPanel, method(object({
9625
- deviceId: number().int().nonnegative(),
9626
- mode: AlarmArmModeSchema,
9627
- /** Optional PIN code. Required when `requiresCode === true`.
9628
- * Passed through to the upstream service; never persisted. */
9629
- code: string().min(1).optional()
9630
- }), _void(), {
9631
- kind: "mutation",
9632
- auth: "admin"
9633
- }), method(object({
9634
- deviceId: number().int().nonnegative(),
9635
- code: string().min(1).optional()
9636
- }), _void(), {
9637
- kind: "mutation",
9638
- auth: "admin"
9639
- }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
9640
- kind: "mutation",
9641
- auth: "admin"
9642
- });
9643
- object({
9644
- /** Current illuminance in lux (lx). */
9645
- lux: number().min(0),
9646
- /** Ms epoch when the slice was last updated. */
9647
- lastFetchedAt: number(),
9648
- /** Live display unit from the upstream source (e.g. HA
9649
- * `attributes.unit_of_measurement`). The UI prefers this over the
9650
- * role's canonical unit. Absent → fall back to the canonical unit. */
9651
- unit: string().optional(),
9652
- /** Suggested decimal places for numeric display.
9653
- * Populated live from the upstream source when provided (e.g. HA
9654
- * `attributes.suggested_display_precision`). Falls back to
9655
- * auto-formatting when absent. */
9656
- precision: number().int().min(0).max(10).optional()
9657
- });
9658
- DeviceType.Sensor;
9659
- /**
9660
- * Per-class audio metrics aggregated over a sliding window.
9533
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
9534
+ * `notification-center` module), hooked on the durable persistence
9535
+ * moments (object-event insert, TrackCloser.closeExpired) with a
9536
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
9537
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
9538
+ * FIRST persisted detection matching the conditions (per-track dedup,
9539
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
9540
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
9541
+ * - DISPATCH stays behind `notification-output` (rules reference targets
9542
+ * by id; per-backend params are a passthrough blob capped by the
9543
+ * target kind's own caps/degrade engine).
9544
+ *
9545
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
9546
+ * server-injected caller identity — the first `caller: 'required'`
9547
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
9548
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
9549
+ * windows, and the optional label/identity/plate matchers. User rules,
9550
+ * private zones, per-recipient fan-out and the wider condition table are
9551
+ * P2+ (see spec §7).
9552
+ *
9553
+ * All schemas here are the single source of truth — `NcRule` etc. are
9554
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
9555
+ * schema/interface drift is explicitly not repeated).
9661
9556
  */
9662
- var AudioClassSummarySchema = object({
9663
- className: string(),
9664
- /** Number of windows (chunks) where this class was the top hit. */
9665
- hits: number().int().nonnegative(),
9666
- /** Mean score across those hits, clamped to [0,1]. */
9667
- avgScore: number().min(0).max(1),
9668
- /** Peak score in the window. */
9669
- peakScore: number().min(0).max(1)
9670
- });
9671
9557
  /**
9672
- * Per-camera audio metrics snapshotemitted by the analytics frame
9673
- * handler on every `pipeline.audio-inference-result` event and
9674
- * mirrored into the `audio-metrics` device-state slice. Symmetric
9675
- * with `zone-analytics` snapshots for video — every consumer
9676
- * (admin UI panel, automations, alert rules) reads via the
9677
- * canonical `device.state.audioMetrics.value` reactive handle.
9558
+ * D-3: the trigger/urgency of a rule which persistence moment evaluates it.
9559
+ * The value maps 1:1 onto the evaluated record kind:
9560
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
9561
+ * - `track-end` TrackCloser.closeExpired (finalized track record)
9562
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
9563
+ * change of a LINKED device, one row per linked camera)
9564
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
9565
+ * delivery / pick-up)
9678
9566
  *
9679
- * Aggregates are computed over a rolling `windowSec` window
9680
- * (default 60s). Past that window, classes drop out of `byClass`
9681
- * and the level history shifts forward.
9567
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
9568
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
9569
+ * this one field keeps the schema additive a rule still declares exactly
9570
+ * one trigger.
9682
9571
  */
9683
- var AudioMetricsSnapshotSchema = object({
9684
- /** Wall-clock timestamp (ms) of the most recent audio window. */
9685
- ts: number().int(),
9686
- /** Sliding-window length (seconds) used for aggregation. */
9687
- windowSec: number().int().positive(),
9688
- /** Latest level reading from the most recent window. */
9689
- level: object({
9690
- rms: number(),
9691
- dbfs: number()
9692
- }),
9693
- /** Peak dBFS observed across the rolling window. */
9694
- peakDbfs: number(),
9695
- /** Mean dBFS across the rolling window. */
9696
- avgDbfs: number(),
9697
- /** Most recent above-threshold classification, or null on silence. */
9698
- current: object({
9699
- className: string(),
9700
- score: number().min(0).max(1),
9701
- timestamp: number().int()
9702
- }).nullable(),
9703
- /** Per-class summary across the rolling window — keys are
9704
- * `macroClass` strings (e.g. `dog_bark`, `speech`, `glass_break`). */
9705
- byClass: array(AudioClassSummarySchema).readonly()
9572
+ var NcDeliverySchema = _enum([
9573
+ "immediate",
9574
+ "track-end",
9575
+ "device-event",
9576
+ "package-event"
9577
+ ]);
9578
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
9579
+ var NcScheduleSchema = object({
9580
+ windows: array(object({
9581
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
9582
+ days: array(number().int().min(0).max(6)).min(1),
9583
+ startMinute: number().int().min(0).max(1439),
9584
+ endMinute: number().int().min(0).max(1439)
9585
+ })).min(1),
9586
+ /** IANA timezone; default = hub host timezone. */
9587
+ timezone: string().optional(),
9588
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
9589
+ invert: boolean().optional()
9590
+ });
9591
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
9592
+ var NcPlateMatcherSchema = object({
9593
+ values: array(string().min(1)).min(1),
9594
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
9595
+ maxDistance: number().int().min(0).max(3).default(1)
9706
9596
  });
9707
9597
  /**
9708
- * Audio-metrics history payload a series of `AudioMetricsHistoryPoint`
9709
- * samples capped at `maxPoints` (default 1024). When the requested
9710
- * `windowSec / sampleEveryMs` would exceed the cap, the provider
9711
- * subsamples by bucketed averaging and reports the effective sample
9712
- * spacing on `effectiveSampleEveryMs` so the UI can label the x-axis.
9598
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
9599
+ * occupancy edge for a device optionally narrowed to a single admin
9600
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
9601
+ * - `became-occupied` (default) count crossed 0 `count`
9602
+ * - `became-free` count crossed `count` below it
9603
+ * - `>=` / `<=` — count is at/over or at/under `count`
9604
+ * `sustainSeconds` requires the condition hold continuously that long
9605
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
9606
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
9607
+ * the condition never matches. Confirmed edge-state survives addon restarts
9608
+ * (declared SQLite collection, reseeded on boot).
9713
9609
  */
9714
- var AudioMetricsHistorySchema = object({
9715
- points: array(object({
9716
- /** Wall-clock ms when this sample was recorded. */
9717
- ts: number().int(),
9718
- /** Instantaneous dBFS level at sample time. `null` for windows where
9719
- * the source had no level reading (rare; happens at decode startup). */
9720
- dbfs: number().nullable(),
9721
- /** Rolling-window peak dBFS at sample time. Same window the live
9722
- * snapshot reports. */
9723
- peakDbfs: number(),
9724
- /** Rolling-window mean dBFS at sample time. */
9725
- avgDbfs: number(),
9726
- /** Dominant above-threshold class at sample time, or null on silence. */
9727
- topClass: string().nullable(),
9728
- /** Score of the dominant class (`null` whenever `topClass` is null). */
9729
- topScore: number().min(0).max(1).nullable()
9730
- })).readonly(),
9731
- /** Actual ms between adjacent samples after any subsampling. */
9732
- effectiveSampleEveryMs: number().int().positive(),
9733
- /** Wall-clock window covered by `points` (`points[N-1].ts - points[0].ts`),
9734
- * or `0` when there's fewer than 2 samples. */
9735
- windowMsActual: number().int().nonnegative()
9736
- });
9737
- DeviceType.Camera, method(object({ deviceId: number() }), AudioMetricsSnapshotSchema.nullable()), method(object({
9738
- deviceId: number(),
9739
- /** History window in seconds. Default 300 (5 minutes).
9740
- * Provider clamps to its retention cap if larger. */
9741
- windowSec: number().int().positive().optional(),
9742
- /** Target sample interval in ms. Default 1000 (1 sample/second).
9743
- * Provider clamps to natural sample rate if smaller, and
9744
- * bucket-averages when bigger than the requested window
9745
- * would produce more than `maxPoints` samples. */
9746
- sampleEveryMs: number().int().positive().optional()
9747
- }), AudioMetricsHistorySchema);
9748
- object({
9749
- /** Whether the automation is currently enabled. Disabled automations
9750
- * ignore their trigger block — manual `trigger` still works. */
9751
- enabled: boolean(),
9752
- /** Whether the automation is currently executing its action block. */
9753
- isRunning: boolean(),
9754
- /** Ms epoch of the last successful run. 0 when never run. */
9755
- lastTriggeredAt: number(),
9756
- /** Failure description from the last completed run. Null on success
9757
- * or when never run. */
9758
- lastError: string().nullable(),
9759
- /** Ms epoch when the slice was last updated. */
9760
- lastChangedAt: number()
9610
+ var NcOccupancyConditionSchema = object({
9611
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
9612
+ zoneId: string().optional(),
9613
+ /** Object class to count; absent = any class. */
9614
+ className: string().optional(),
9615
+ op: _enum([
9616
+ "became-occupied",
9617
+ "became-free",
9618
+ ">=",
9619
+ "<="
9620
+ ]).default("became-occupied"),
9621
+ count: number().int().min(0).default(1),
9622
+ sustainSeconds: number().int().min(0).max(3600).default(15)
9761
9623
  });
9762
- DeviceType.Automation, method(object({ deviceId: number().int().nonnegative() }), _void(), {
9763
- kind: "mutation",
9764
- auth: "admin"
9765
- }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
9766
- kind: "mutation",
9767
- auth: "admin"
9768
- }), method(object({
9769
- deviceId: number().int().nonnegative(),
9770
- /** When true, fires the action block while bypassing the
9771
- * automation's condition evaluation. Gated by
9772
- * `DeviceFeature.AutomationSkipCondition`. */
9773
- skipCondition: boolean().optional()
9774
- }), _void(), {
9775
- kind: "mutation",
9776
- auth: "admin"
9624
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
9625
+ var NcZoneConditionSchema = object({
9626
+ ids: array(string().min(1)).min(1),
9627
+ /** Quantifier over `ids` at least one / every one visited. */
9628
+ match: _enum(["any", "all"]).default("any")
9777
9629
  });
9778
9630
  /**
9779
- * Battery status snapshot. Emitted by providers whose device is
9780
- * battery-operated (cameras with `DeviceFeature.BatteryOperated`,
9781
- * future sensor/button accessories). Consumers build their own "low
9782
- * battery" alerting on top — the cap deliberately does NOT enforce a
9783
- * threshold.
9631
+ * The P1 condition set a flat AND of groups; absent group = pass;
9632
+ * membership lists are OR within the list (spec §2.3).
9784
9633
  */
9785
- var BatteryStatusSchema = object({
9786
- /** 0..100 inclusive. Firmware-reported. */
9787
- percentage: number().min(0).max(100),
9634
+ var NcConditionsSchema = object({
9635
+ /** Device scope — absent = all devices. */
9636
+ devices: array(number()).optional(),
9637
+ /** Detector class names (any overlap with the record's class set). */
9638
+ classes: array(string().min(1)).optional(),
9639
+ /** Veto classes — any overlap fails the rule. */
9640
+ classesExclude: array(string().min(1)).optional(),
9641
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
9642
+ minConfidence: number().min(0).max(1).optional(),
9643
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
9644
+ zones: NcZoneConditionSchema.optional(),
9645
+ /** Veto zones — any hit fails the rule. */
9646
+ zonesExclude: array(string().min(1)).optional(),
9788
9647
  /**
9789
- * Charging source. `'dc'` covers wall/USB adapters; `'solar'` is
9790
- * Reolink-specific for the Solar Panel 2 accessory (will become
9791
- * common on other battery cams). `'none'` means running on battery
9792
- * alone.
9648
+ * Exact (case-insensitive) match on the record's collapsed `label`
9649
+ * (identity name / plate text / subclass).
9793
9650
  */
9794
- charging: _enum([
9795
- "dc",
9796
- "solar",
9797
- "none"
9798
- ]),
9651
+ labelEquals: array(string().min(1)).optional(),
9799
9652
  /**
9800
- * True when the camera firmware has gone into low-power mode. Battery
9801
- * providers MUST avoid polling during sleep reading the battery
9802
- * wakes the camera up and drains charge.
9653
+ * Identity matcher. P1 boundary: matched against the record's collapsed
9654
+ * `label` (the identity display name propagated by the face pipeline) —
9655
+ * identity-ID matching rides in P2 when identity ids reach the record.
9803
9656
  */
9804
- sleeping: boolean(),
9805
- /** Ms epoch of the last observation. Lets consumers reason about freshness. */
9806
- lastUpdated: number(),
9657
+ identities: array(string().min(1)).optional(),
9658
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
9659
+ plates: NcPlateMatcherSchema.optional(),
9807
9660
  /**
9808
- * True when the source is a BINARY low-battery indicator (HA
9809
- * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
9810
- * charge level `percentage` is then a coarse stand-in (100 = normal,
9811
- * sub-threshold = low). UI MUST render "Normal"/"Low" instead of a
9812
- * misleading exact percentage. Absent/false → genuine 0–100 % reading.
9661
+ * Identity EXCLUDE mirror of {@link identities} with `notIn` semantics.
9662
+ * Same P1 boundary: matched against the record's collapsed `label` (the
9663
+ * identity display name). A record with NO label passes (nothing to
9664
+ * exclude), unlike the include variant which fails on an absent label.
9813
9665
  */
9814
- binary: boolean().optional()
9815
- });
9816
- DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch, method(object({
9817
- deviceId: number(),
9818
- /** Bound on the wait. Sensible range 3000–10000ms. */
9819
- timeoutMs: number().int().min(500).max(3e4).default(8e3)
9820
- }), object({
9821
- awoke: boolean(),
9822
- durationMs: number()
9823
- }), { kind: "mutation" }), object({
9824
- deviceId: number(),
9825
- status: BatteryStatusSchema
9826
- });
9827
- object({
9828
- on: boolean(),
9829
- /** Ms epoch of the last transition. 0 if never observed. */
9830
- lastChangedAt: number()
9831
- });
9832
- DeviceType.Sensor;
9833
- object({
9834
- /** Current level as 0..100 inclusive. Firmware-reported. */
9835
- percentage: number().min(0).max(100),
9836
- /** Ms epoch of the last operator-driven change. Useful for UI freshness. */
9837
- lastChangedAt: number()
9838
- });
9839
- DeviceType.Light, method(object({
9840
- deviceId: number().int().nonnegative(),
9841
- percentage: number().min(0).max(100)
9842
- }), _void(), {
9843
- kind: "mutation",
9844
- auth: "admin"
9845
- }), object({
9846
- deviceId: number(),
9847
- percentage: number().min(0).max(100),
9848
- lastChangedAt: number()
9849
- });
9850
- /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
9851
- var StreamFormatSchema = _enum([
9852
- "webrtc",
9853
- "hls",
9854
- "mjpeg",
9855
- "rtsp"
9856
- ]);
9857
- var RtspRestreamEntrySchema = object({
9858
- brokerId: string(),
9859
- url: string(),
9860
- mutedUrl: string(),
9861
- enabled: boolean(),
9666
+ identitiesExclude: array(string().min(1)).optional(),
9862
9667
  /**
9863
- * Source-stream codec / resolution for the camStream this entry serves
9864
- * (the broker's "high"/"mid"/"low" profile slot for this device).
9865
- * Used by exporter pickers (`pickPreferredRtspEntry`) to resolve
9866
- * `streamPreference: 'auto'` to the slot whose source is closest to
9867
- * the consumer's target Alexa wants ~720p, HomeKit wants ~1080p,
9868
- * and there's no point dialling the 4K slot for an Echo Show. Absent
9869
- * when the source publisher never advertised the field; pickers fall
9870
- * back to first-enabled in that case.
9668
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
9669
+ * TRACK-END only: importance is scored at track close, so it does not exist
9670
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
9671
+ * close the value is threaded via the close-time info (the `Track` clone is
9672
+ * captured before the DB row is updated, so it would otherwise read stale).
9673
+ * Fails when the record carries no importance (never guess quality the
9674
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
9871
9675
  */
9872
- codec: string().optional(),
9873
- resolution: object({
9874
- width: number().int().positive(),
9875
- height: number().int().positive()
9876
- }).optional()
9877
- });
9878
- var BrokerRtspClientSchema = object({
9879
- sessionId: string(),
9880
- remoteAddr: string(),
9881
- /** Client `User-Agent` (e.g. `recorder` for the recorder's RTSP pull), or
9882
- * null/absent when the client sent none. Lets the UI label a consumer by
9883
- * purpose. Optional so a client built against an older schema stays valid. */
9884
- userAgent: string().nullish(),
9885
- playing: boolean(),
9886
- muted: boolean(),
9887
- connectedAt: number(),
9888
- lastRtpAt: number(),
9889
- bytesSent: number()
9890
- });
9891
- var BrokerDecodedClientSchema = object({
9892
- tag: string(),
9893
- subscribedAt: number(),
9894
- maxFps: number(),
9895
- framesDelivered: number(),
9896
- framesDropped: number()
9897
- });
9898
- var BrokerAudioClientSchema = object({
9899
- tag: string(),
9900
- subscribedAt: number(),
9901
- chunksDelivered: number()
9902
- });
9903
- var BrokerConsumerAttributionSchema = object({
9904
- kind: _enum([
9905
- "alexa",
9906
- "homekit",
9907
- "webrtc-browser",
9908
- "webrtc-mobile",
9909
- "webrtc-whep",
9910
- "rtsp-listen",
9911
- "derived-broker",
9912
- "recording",
9913
- "pipeline",
9914
- "snapshot",
9915
- "warmup",
9916
- "unknown"
9917
- ]),
9676
+ minImportance: number().min(0).max(1).optional(),
9918
9677
  /**
9919
- * Free-form label intended to disambiguate consumers OF THE SAME kind
9920
- * on the same broker e.g. user name, device alias. Should NOT repeat
9921
- * the kind / cam / cam-stream / sessionId (those are surfaced by
9922
- * dedicated fields). When empty the widget falls back to `${kind} ·
9923
- * <sessionId tail>`.
9678
+ * Minimum track dwell in SECONDS `(lastSeen firstSeen) / 1000`.
9679
+ * TRACK-END only: an `immediate` / object-event subject has no closed
9680
+ * lifespan, so a dwell condition never matches immediate delivery
9681
+ * (documented choice the object-event record carries no `firstSeen`,
9682
+ * so dwell cannot be computed from what the subject actually carries).
9924
9683
  */
9925
- label: string().optional(),
9684
+ minDwellSeconds: number().min(0).optional(),
9926
9685
  /**
9927
- * Which part of the encoded plane this subscription consumes:
9928
- * - `'audio'` audio packets only
9929
- * - `'video'` video packets only
9930
- * - `'both'` — both video + audio (typical for AnnexB push paths
9931
- * that don't split the source RTP)
9932
- *
9933
- * Missing field means "unknown" — older callers and the legacy
9934
- * paths that haven't been migrated yet.
9686
+ * Detection provenance filter. `any` (default / absent) matches every
9687
+ * source; otherwise the subject's source must equal it. Legacy records
9688
+ * with no stamped source are treated as `pipeline`. The union spans both
9689
+ * record kinds object events carry `pipeline` | `onboard`, synthetic
9690
+ * tracks carry `sensor`.
9935
9691
  */
9936
- media: _enum([
9937
- "audio",
9938
- "video",
9939
- "both"
9692
+ source: _enum([
9693
+ "pipeline",
9694
+ "onboard",
9695
+ "sensor",
9696
+ "any"
9940
9697
  ]).optional(),
9941
9698
  /**
9942
- * Codec the consumer receives AFTER any per-session re-encoding. For
9943
- * a WebRTC session this is the negotiated egress codec (e.g. `H264`,
9944
- * `H265`, `Opus`, `Pcmu`); for an RTSP restreamer it mirrors the
9945
- * source codec. Surfaced in the widget chip so operators see at a
9946
- * glance whether a viewer is on H.264 (Echo) or H.265 (Safari).
9699
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
9700
+ * detector `minConfidence` (that gates the object-detection score; this
9701
+ * gates the recognition/OCR match score). Fails when the subject carries
9702
+ * no label-match confidence (never guess). TRACK-END only: the confidence
9703
+ * lives on the recognition result and reaches the subject at track close.
9704
+ *
9705
+ * What it measures precisely (plumbed at track close — the closer threads
9706
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
9707
+ * `importance`): the BEST recognition match confidence observed for the
9708
+ * label the track carries at close — for a face, the peak cosine similarity
9709
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
9710
+ * for a plate, the peak OCR read score of the best-held plate
9711
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
9712
+ * one track the higher of the two is used. A track that ended with no
9713
+ * confident identity/plate match carries no value, so the condition fails
9714
+ * closed for it (an un-recognized subject).
9947
9715
  */
9948
- targetCodec: string().optional(),
9716
+ minLabelConfidence: number().min(0).max(1).optional(),
9949
9717
  /**
9950
- * Whether the broker is re-encoding for this consumer:
9951
- * - `'passthrough'` bytes flow source→consumer without ffmpeg
9952
- * - `'repacketize'` RTP payload is re-packetized but NOT re-encoded
9953
- * (preserves frames, just rebuilds headers; e.g.
9954
- * the H.265 repacketizer path)
9955
- * - `'transcode'` — a full encode/decode round (ffmpeg, libx264,
9956
- * libav…); the most expensive path
9718
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
9719
+ * e.g. a doorbell `press` / `press_long`) matched case-insensitively
9720
+ * against the token carried on the device-event subject (extracted from the
9721
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
9722
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
9723
+ * eventType, so gate those with {@link sensorKinds} instead.
9957
9724
  */
9958
- transport: _enum([
9959
- "passthrough",
9960
- "repacketize",
9961
- "transcode"
9962
- ]).optional(),
9963
- /** Remote peer IP if the consumer terminates a network socket. */
9964
- remoteAddr: string().optional(),
9725
+ eventTypeTokens: array(string().min(1)).optional(),
9965
9726
  /**
9966
- * Server-read User-Agent of the originating client; enriched by the hub
9967
- * from the tRPC request context (browser sessions).
9727
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
9728
+ * `contact`, `button`, `device-event`) matched against the persisted
9729
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
9968
9730
  */
9969
- userAgent: string().optional(),
9970
- /** Authenticated user id (CamStack OAuth subject) when known. */
9971
- userId: string().optional(),
9972
- /** Higher-level session identifier (Alexa Echo sessionId, HAP session, …). */
9973
- sessionId: string().optional(),
9974
- /** Free-form key/value extras (e.g. clientHints from a WebRTC offer). */
9975
- extra: record(string(), string()).optional()
9976
- }).readonly();
9977
- var BrokerEncodedClientSchema = object({
9978
- /** Stable id assigned on attach; used by `killClient`. */
9979
- id: string(),
9980
- /** Which broker fanout the subscriber rides — annexB encoded packets vs raw RTP. */
9981
- channel: _enum(["annexb", "rtp"]),
9982
- attribution: BrokerConsumerAttributionSchema,
9731
+ sensorKinds: array(string().min(1)).optional(),
9732
+ /**
9733
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
9734
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
9735
+ * when the subject's phase does not match (a subject always carries a phase
9736
+ * on the package-event trigger).
9737
+ */
9738
+ packagePhase: _enum([
9739
+ "delivered",
9740
+ "picked-up",
9741
+ "both"
9742
+ ]).optional(),
9743
+ /**
9744
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
9745
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
9746
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
9747
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
9748
+ */
9749
+ customZones: array(MaskPolygonShapeSchema).optional(),
9750
+ /**
9751
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
9752
+ * (optionally zone/class-scoped) occupancy count crosses the configured
9753
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
9754
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
9755
+ */
9756
+ occupancy: NcOccupancyConditionSchema.optional()
9757
+ });
9758
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
9759
+ var NcRuleTargetSchema = object({
9760
+ /** `notification-output` Target id. */
9761
+ targetId: string().min(1),
9762
+ /**
9763
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
9764
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
9765
+ * degrade engine drops what the backend can't render.
9766
+ */
9767
+ params: record(string(), unknown()).optional()
9768
+ });
9769
+ /**
9770
+ * Media attachment policy (P1 still-image subset).
9771
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
9772
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
9773
+ * matched on identities attaches the subject's `faceCrop`, one matched on
9774
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
9775
+ * (or when the specific crop is missing) degrades to `best`, then
9776
+ * `keyFrame`, then no attachment — never delaying the send. The matched
9777
+ * condition summary is frozen on the outbox row at enqueue (like the rule
9778
+ * name), so the choice never drifts from the record that fired it.
9779
+ * - `keyFrame` — the clean scene frame (no subject box).
9780
+ * - `none` — no attachment.
9781
+ */
9782
+ var NcMediaPolicySchema = object({ attach: _enum([
9783
+ "best",
9784
+ "best-matching",
9785
+ "keyFrame",
9786
+ "none"
9787
+ ]).default("best") });
9788
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
9789
+ var NcThrottleSchema = object({
9790
+ cooldownSec: number().int().min(0).max(86400).default(60),
9791
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
9792
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
9793
+ });
9794
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
9795
+ var NcRuleInputSchema = object({
9796
+ name: string().min(1).max(200),
9797
+ enabled: boolean().default(true),
9798
+ delivery: NcDeliverySchema,
9799
+ conditions: NcConditionsSchema.default({}),
9800
+ schedule: NcScheduleSchema.optional(),
9801
+ targets: array(NcRuleTargetSchema).min(1),
9802
+ media: NcMediaPolicySchema.default({ attach: "best" }),
9803
+ throttle: NcThrottleSchema.default({
9804
+ cooldownSec: 60,
9805
+ scope: "rule-device"
9806
+ }),
9807
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
9808
+ template: object({
9809
+ title: string().max(500).optional(),
9810
+ body: string().max(2e3).optional()
9811
+ }).optional(),
9812
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
9813
+ priority: number().int().min(1).max(5).default(3),
9814
+ /**
9815
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
9816
+ * behaviour, visible to all, read-only in the viewer). Present = personal
9817
+ * rule owned by this userId. Server-stamped; never trusted from a client.
9818
+ */
9819
+ ownerUserId: string().optional()
9820
+ });
9821
+ /**
9822
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
9823
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
9824
+ * NOT a client-authored input field (it lives on the persisted rule, not the
9825
+ * input), so it is added here explicitly to let the store's per-target opt-out
9826
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
9827
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
9828
+ * `updateRule` patch.
9829
+ */
9830
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
9831
+ /** A persisted rule. */
9832
+ var NcRuleSchema = NcRuleInputSchema.extend({
9833
+ id: string(),
9834
+ /** userId of the admin who created the rule (server-stamped caller). */
9835
+ createdBy: string(),
9836
+ createdAt: number(),
9837
+ updatedAt: number(),
9838
+ /**
9839
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
9840
+ * send time. Only a target's OWNER may add/remove its id (server-checked
9841
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
9842
+ */
9843
+ disabledTargetIds: array(string()).default([])
9844
+ });
9845
+ var NcTestResultSchema = object({
9846
+ recordId: string(),
9847
+ recordKind: _enum([
9848
+ "object-event",
9849
+ "track",
9850
+ "device-event",
9851
+ "package-event"
9852
+ ]),
9853
+ deviceId: number(),
9854
+ timestamp: number(),
9855
+ wouldFire: boolean(),
9856
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
9857
+ failedCondition: string().optional(),
9858
+ className: string().optional(),
9859
+ label: string().optional()
9860
+ });
9861
+ var NcConditionDescriptorSchema = object({
9862
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
9863
+ id: string(),
9864
+ group: _enum([
9865
+ "scope",
9866
+ "class",
9867
+ "zones",
9868
+ "quality",
9869
+ "label",
9870
+ "schedule",
9871
+ "device",
9872
+ "package",
9873
+ "occupancy"
9874
+ ]),
9875
+ label: string(),
9876
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
9877
+ valueType: _enum([
9878
+ "deviceIdList",
9879
+ "stringList",
9880
+ "number01",
9881
+ "number",
9882
+ "sourceSelect",
9883
+ "zoneSelection",
9884
+ "zoneIdList",
9885
+ "schedule",
9886
+ "plateMatcher",
9887
+ "packagePhase",
9888
+ "polygonDraw",
9889
+ "occupancy"
9890
+ ]),
9891
+ operator: _enum([
9892
+ "in",
9893
+ "notIn",
9894
+ "anyOf",
9895
+ "allOf",
9896
+ "gte",
9897
+ "fuzzyIn",
9898
+ "withinSchedule"
9899
+ ]),
9900
+ /** Which delivery kinds the condition applies to. */
9901
+ appliesTo: array(NcDeliverySchema),
9902
+ phase: string(),
9903
+ description: string().optional()
9904
+ });
9905
+ /**
9906
+ * The delivery lifecycle status of a history row — a straight read of the
9907
+ * durable outbox row's own status (single source of truth):
9908
+ * - `pending` — enqueued, in-flight or retrying with backoff
9909
+ * - `sent` — delivered (terminal)
9910
+ * - `dead` — dead-lettered after exhausting retries / a permanent
9911
+ * backend rejection / a deleted target (terminal; carries
9912
+ * the failure `error`)
9913
+ *
9914
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
9915
+ * user dimension (quiet hours / snooze) and are additive when they land.
9916
+ */
9917
+ var NcHistoryStatusSchema = _enum([
9918
+ "pending",
9919
+ "sent",
9920
+ "dead"
9921
+ ]);
9922
+ /** The evaluated record kind a history row descends from (one per trigger). */
9923
+ var NcHistoryRecordKindSchema = _enum([
9924
+ "object-event",
9925
+ "track-end",
9926
+ "device-event",
9927
+ "package-event"
9928
+ ]);
9929
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
9930
+ var NcHistorySubjectSchema = object({
9931
+ className: string(),
9932
+ label: string().optional(),
9933
+ confidence: number().optional(),
9934
+ zones: array(string()),
9935
+ timestamp: number()
9936
+ });
9937
+ /**
9938
+ * One delivery-history row. This is a read-only VIEW over the durable
9939
+ * outbox row (single source of truth — the same row the drain loop drives;
9940
+ * NO second write path, so history can never drift from delivery state).
9941
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
9942
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
9943
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
9944
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
9945
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
9946
+ * P1 (admin scope only).
9947
+ */
9948
+ var NcHistoryEntrySchema = object({
9949
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
9950
+ id: string(),
9951
+ ruleId: string(),
9952
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
9953
+ ruleName: string(),
9954
+ /** The rule urgency/trigger that produced this delivery. */
9955
+ delivery: NcDeliverySchema,
9956
+ targetId: string(),
9957
+ deviceId: number(),
9958
+ recordKind: NcHistoryRecordKindSchema,
9959
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
9960
+ recordId: string(),
9961
+ /** Present for track-scoped deliveries (object-event / track-end). */
9962
+ trackId: string().optional(),
9963
+ status: NcHistoryStatusSchema,
9964
+ /** Delivery attempts made so far. */
9965
+ attempts: number().int(),
9966
+ /** Fire time (outbox enqueue). */
9967
+ createdAt: number(),
9968
+ /** Last transition time (terminal for sent / dead). */
9969
+ updatedAt: number(),
9970
+ /** Failure detail — present on a `dead` row. */
9971
+ error: string().optional(),
9972
+ subject: NcHistorySubjectSchema
9973
+ });
9974
+ /**
9975
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
9976
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
9977
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
9978
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
9979
+ */
9980
+ var NcHistoryFilterSchema = object({
9981
+ ruleId: string().optional(),
9982
+ deviceId: number().optional(),
9983
+ status: NcHistoryStatusSchema.optional(),
9984
+ since: number().optional(),
9985
+ until: number().optional(),
9986
+ limit: number().int().min(1).max(500).default(100)
9987
+ });
9988
+ 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 }), {
9989
+ kind: "mutation",
9990
+ auth: "admin",
9991
+ caller: "required"
9992
+ }), method(object({
9993
+ ruleId: string(),
9994
+ patch: NcRulePatchSchema
9995
+ }), object({ rule: NcRuleSchema }), {
9996
+ kind: "mutation",
9997
+ auth: "admin",
9998
+ caller: "required"
9999
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
10000
+ kind: "mutation",
10001
+ auth: "admin"
10002
+ }), method(object({
10003
+ ruleId: string(),
10004
+ enabled: boolean()
10005
+ }), object({ success: literal(true) }), {
10006
+ kind: "mutation",
10007
+ auth: "admin"
10008
+ }), method(object({
10009
+ rule: NcRuleInputSchema,
10010
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
10011
+ }), object({ results: array(NcTestResultSchema) }), {
10012
+ kind: "mutation",
10013
+ auth: "admin"
10014
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
10015
+ /**
10016
+ * TimelapseRule — the STANDALONE scheduled timelapse producer's rule model.
10017
+ *
10018
+ * Spec: `docs/superpowers/specs/2026-07-24-nc-occupancy-timelapse-design.md`
10019
+ * §3.2/§3.3.
10020
+ *
10021
+ * Deliberately NOT a capability definition and NOT an `NcRule`:
10022
+ * - Every `NcDelivery` member is a *persisted-pipeline-record* trigger. A
10023
+ * timelapse fires on a SCHEDULE WINDOW BOUNDARY, evaluates no pipeline
10024
+ * record, and produces a video it assembled itself — so it rides no
10025
+ * delivery-enum member (the enum is frozen) and no cap method. This file is
10026
+ * a plain typed schema; it does NOT go through `npm run codegen`.
10027
+ * - It shares only the delivery leg (`notification-output.send`) and the
10028
+ * persistence/ownership patterns with the Notification Center, reusing
10029
+ * {@link NcScheduleSchema} (weekly windows, midnight-crossing, invertible)
10030
+ * and {@link NcRuleTargetSchema} (target ref + passthrough params).
10031
+ *
10032
+ * Ownership is SERVER-DERIVED. `ownerUserId` / `createdBy` / `createdAt` /
10033
+ * `updatedAt` / `id` / `lastGeneratedAt` live on the PERSISTED rule only —
10034
+ * {@link TimelapseRuleInputSchema} and {@link TimelapseRulePatchSchema} do not
10035
+ * carry them, so a forged client payload can never claim or re-own a rule
10036
+ * (Zod strips unknown keys). The store stamps them from the resolved caller.
10037
+ */
10038
+ /** `{{var}}` templating over camera/rule/time — same vocabulary as `NcRule`. */
10039
+ var TimelapseTemplateSchema = object({
10040
+ title: string().max(500).optional(),
10041
+ body: string().max(2e3).optional()
10042
+ });
10043
+ var NameField = string().min(1).max(200);
10044
+ var DeviceIdsField = array(number()).min(1);
10045
+ var CadenceSecField = number().int().min(2).max(3600);
10046
+ var FramerateField = number().int().min(1).max(60);
10047
+ var TargetsField = array(NcRuleTargetSchema).min(1);
10048
+ var PriorityField = number().int().min(1).max(5);
10049
+ /**
10050
+ * Client-supplied timelapse-rule fields. The server stamps id / createdBy /
10051
+ * createdAt / updatedAt / ownerUserId / lastGeneratedAt — none of them appear
10052
+ * here (see the ownership note above).
10053
+ */
10054
+ var TimelapseRuleInputSchema = object({
10055
+ name: NameField,
10056
+ enabled: boolean().default(true),
10057
+ /** Cameras sampled by this rule — one scratch dir + one artifact per device. */
10058
+ deviceIds: DeviceIdsField,
10059
+ /**
10060
+ * Activation window(s). REQUIRED (unlike `NcRule`, where an absent schedule
10061
+ * means "always active"): a timelapse is defined by its window boundaries —
10062
+ * open clears the scratch, close assembles and delivers.
10063
+ */
10064
+ schedule: NcScheduleSchema,
10065
+ /** Force-snapshot cadence inside the window, seconds (predecessor parity). */
10066
+ cadenceSec: CadenceSecField.default(15),
10067
+ /** Output frames per second of the assembled mp4 (predecessor parity). */
10068
+ framerate: FramerateField.default(10),
10069
+ /** `notification-output` targets the finished video/thumbnail is sent to. */
10070
+ targets: TargetsField,
10071
+ template: TimelapseTemplateSchema.optional(),
10072
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
10073
+ priority: PriorityField.default(3)
10074
+ });
10075
+ object({
10076
+ name: NameField.optional(),
10077
+ enabled: boolean().optional(),
10078
+ deviceIds: DeviceIdsField.optional(),
10079
+ schedule: NcScheduleSchema.optional(),
10080
+ cadenceSec: CadenceSecField.optional(),
10081
+ framerate: FramerateField.optional(),
10082
+ targets: TargetsField.optional(),
10083
+ template: TimelapseTemplateSchema.nullable().optional(),
10084
+ priority: PriorityField.optional()
10085
+ });
10086
+ TimelapseRuleInputSchema.extend({
10087
+ id: string(),
10088
+ /**
10089
+ * Ownership/visibility key. Absent = admin/global rule (visible to all).
10090
+ * Present = personal rule owned by this userId. Server-stamped from the
10091
+ * resolved caller; never trusted from a client payload.
10092
+ */
10093
+ ownerUserId: string().optional(),
10094
+ /**
10095
+ * Epoch-ms of the last successful generation — the 1-hour re-generation
10096
+ * guard's durable state (predecessor parity). Absent = never generated.
10097
+ */
10098
+ lastGeneratedAt: number().optional(),
10099
+ /** userId of the caller who created the rule (server-stamped). */
10100
+ createdBy: string(),
10101
+ createdAt: number(),
10102
+ updatedAt: number()
10103
+ });
10104
+ /**
10105
+ * Generic device-level status snapshot. Auto-registered by `BaseDevice`
10106
+ * for every device, regardless of provider — the kernel needs a uniform
10107
+ * cap-keyed slice for the basic device flags every consumer expects to
10108
+ * read across processes (the `online` flag in particular). Driver-specific
10109
+ * caps (`battery`, `doorbell`, …) carry their domain-specific state on
10110
+ * their own slices.
10111
+ *
10112
+ * Pattern is identical to `battery`: schema-bearing `runtimeState`,
10113
+ * empty `methods`, single change event. Reads land at
10114
+ * `runtimeState.getCapState('device-status')`; writes at
10115
+ * `runtimeState.setCapState('device-status', …)`. Cross-process
10116
+ * consumers reach the same data via the `device-state` cap router
10117
+ * (`getCapSlice({deviceId, capName: 'device-status'})`).
10118
+ */
10119
+ var DeviceStatusSchema = object({
10120
+ /**
10121
+ * Device-level liveness. Drivers flip via `markOnline(boolean)` on
10122
+ * `BaseDevice`. Provider semantics vary — RTSP aggregates broker
10123
+ * stream-health, Reolink reads firmware push events, ONVIF tracks
10124
+ * ping responses. This cap intentionally does NOT prescribe which
10125
+ * signal drives the flag.
10126
+ */
10127
+ online: boolean(),
10128
+ /** Ms epoch of the last `online` transition. Lets consumers tell
10129
+ * apart "just came online" from "still online". */
10130
+ lastChangedAt: number()
10131
+ });
10132
+ object({
10133
+ deviceId: number(),
10134
+ status: DeviceStatusSchema
10135
+ });
10136
+ /**
10137
+ * Per-device feature/identity probe slice. Holds the runtime-resolved
10138
+ * truth about what a device CAN do — which the kernel uses to:
10139
+ * 1. Reconcile accessory children (hub-children spawn siren/floodlight/PIR
10140
+ * based on what the firmware actually advertises).
10141
+ * 2. Compute the public `features: DeviceFeature[]` array surfaced via
10142
+ * `device-manager.listAll`.
10143
+ * 3. Decide which optional caps (PTZ, intercom, doorbell, battery, …)
10144
+ * to register on the device's capability surface.
10145
+ *
10146
+ * Auto-registered by `BaseDevice` for every device. Drivers populate the
10147
+ * slice from `onProbe()` (kernel calls it once after register, before
10148
+ * accessory reconciliation). Consumers read via:
10149
+ * `runtimeState.getCapState<FeatureProbeStatus>('feature-probe')`
10150
+ *
10151
+ * `flags` is an open record so each driver carries its own keys without
10152
+ * a centralized schema bottleneck — Reolink writes `hasPtz/hasIntercom`,
10153
+ * Hikvision writes `hasSupplementalLight/hasAlarmIo`, etc.
10154
+ *
10155
+ * Replaces the older driver-local `deviceCache.has*` blob: the per-device
10156
+ * config is for operator-edited overrides + UI snapshots; runtime probe
10157
+ * results belong in runtime-state where the kernel handles persistence,
10158
+ * cross-process mirroring, and reactive updates.
10159
+ */
10160
+ var FeatureProbeStatusSchema = object({
10161
+ /**
10162
+ * Driver-specific flag bag. Each driver picks its own key names — the
10163
+ * cap deliberately does NOT enforce a closed enum here. Reolink keys:
10164
+ * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,
10165
+ * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:
10166
+ * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.
10167
+ */
10168
+ flags: record(string(), unknown()),
10169
+ /**
10170
+ * Coarse driver-classification — lets cross-process consumers tell apart
10171
+ * cameras / battery-cams / NVRs without re-running the probe. `null`
10172
+ * before the first probe completes.
10173
+ */
10174
+ deviceType: string().nullable(),
10175
+ /** Camera/firmware model string. `null` when the firmware doesn't expose it. */
10176
+ model: string().nullable(),
10177
+ /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */
10178
+ channelCount: number().nullable(),
10179
+ /**
10180
+ * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe
10181
+ * completes — drivers' `getAccessoryChildren()` should treat zero as
10182
+ * "probe not done yet, return empty" so accessories aren't spawned
10183
+ * before the firmware is queried.
10184
+ */
10185
+ lastProbedAt: number(),
10186
+ /**
10187
+ * Framework convention: every runtime-state slice carries this for the
10188
+ * createRuntimeStateBridge stale-check helper. We keep it in sync with
10189
+ * `lastProbedAt` on every write.
10190
+ */
10191
+ lastFetchedAt: number()
10192
+ });
10193
+ object({
10194
+ deviceId: number(),
10195
+ status: FeatureProbeStatusSchema
10196
+ });
10197
+ object({
10198
+ /** Carbon dioxide concentration in ppm. */
10199
+ co2Ppm: number().min(0).optional(),
10200
+ /** Total volatile organic compounds in ppb. */
10201
+ vocPpb: number().min(0).optional(),
10202
+ /** Particulate matter ≤ 2.5 μm in µg/m³. */
10203
+ pm25: number().min(0).optional(),
10204
+ /** Particulate matter ≤ 10 μm in µg/m³. */
10205
+ pm10: number().min(0).optional(),
10206
+ /** Composite AQI value (typically 0..500). */
10207
+ aqi: number().optional(),
10208
+ /** Ms epoch when the slice was last updated. */
10209
+ lastFetchedAt: number(),
10210
+ /** Live display unit of the single metric this slice carries (e.g. HA
10211
+ * `attributes.unit_of_measurement` → 'ppm' / 'ppb' / 'µg/m³'). Each
10212
+ * upstream `sensor.*` entity surfaces ONE device_class, so one unit
10213
+ * per slice is unambiguous. */
10214
+ unit: string().optional(),
10215
+ /** Suggested decimal places for numeric display.
10216
+ * Populated live from the upstream source when provided (e.g. HA
10217
+ * `attributes.suggested_display_precision`). Falls back to
10218
+ * auto-formatting when absent. */
10219
+ precision: number().int().min(0).max(10).optional()
10220
+ });
10221
+ DeviceType.Sensor;
10222
+ /**
10223
+ * Alarm-panel cap. Models HA `alarm_control_panel.*` on
10224
+ * `DeviceType.AlarmPanel`. State follows HA's canonical lifecycle
10225
+ * across disarmed / armed_(home|away|night|vacation|custom_bypass) /
10226
+ * arming / pending / triggered / disarming.
10227
+ *
10228
+ * Many panels require a PIN code on arm / disarm — the optional
10229
+ * `code` field on the methods passes it through to the upstream
10230
+ * service; it's NEVER persisted in the runtime slice or any event
10231
+ * payload. The presence of a required code is signalled by
10232
+ * `DeviceFeature.AlarmPinRequired` so the UI gates a code-entry
10233
+ * field without a slice fetch.
10234
+ *
10235
+ * `availableModes` mirrors HA's `supported_features`-derived arm
10236
+ * mode list — the UI renders only the buttons the panel accepts.
10237
+ */
10238
+ var AlarmStateSchema = _enum([
10239
+ "disarmed",
10240
+ "armed_home",
10241
+ "armed_away",
10242
+ "armed_night",
10243
+ "armed_vacation",
10244
+ "armed_custom_bypass",
10245
+ "arming",
10246
+ "disarming",
10247
+ "pending",
10248
+ "triggered"
10249
+ ]);
10250
+ var AlarmArmModeSchema = _enum([
10251
+ "home",
10252
+ "away",
10253
+ "night",
10254
+ "vacation",
10255
+ "custom_bypass"
10256
+ ]);
10257
+ object({
10258
+ /** Current lifecycle state. */
10259
+ state: AlarmStateSchema,
10260
+ /** Subset of arm modes the panel accepts. UI renders one button per
10261
+ * mode in this list. */
10262
+ availableModes: array(AlarmArmModeSchema),
10263
+ /** Whether the panel requires a PIN on arm / disarm. Mirrors
10264
+ * `DeviceFeature.AlarmPinRequired` for slice consumers. */
10265
+ requiresCode: boolean(),
10266
+ /** Ms epoch when the slice was last updated. */
10267
+ lastChangedAt: number()
10268
+ });
10269
+ DeviceType.AlarmPanel, method(object({
10270
+ deviceId: number().int().nonnegative(),
10271
+ mode: AlarmArmModeSchema,
10272
+ /** Optional PIN code. Required when `requiresCode === true`.
10273
+ * Passed through to the upstream service; never persisted. */
10274
+ code: string().min(1).optional()
10275
+ }), _void(), {
10276
+ kind: "mutation",
10277
+ auth: "admin"
10278
+ }), method(object({
10279
+ deviceId: number().int().nonnegative(),
10280
+ code: string().min(1).optional()
10281
+ }), _void(), {
10282
+ kind: "mutation",
10283
+ auth: "admin"
10284
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
10285
+ kind: "mutation",
10286
+ auth: "admin"
10287
+ });
10288
+ object({
10289
+ /** Current illuminance in lux (lx). */
10290
+ lux: number().min(0),
10291
+ /** Ms epoch when the slice was last updated. */
10292
+ lastFetchedAt: number(),
10293
+ /** Live display unit from the upstream source (e.g. HA
10294
+ * `attributes.unit_of_measurement`). The UI prefers this over the
10295
+ * role's canonical unit. Absent → fall back to the canonical unit. */
10296
+ unit: string().optional(),
10297
+ /** Suggested decimal places for numeric display.
10298
+ * Populated live from the upstream source when provided (e.g. HA
10299
+ * `attributes.suggested_display_precision`). Falls back to
10300
+ * auto-formatting when absent. */
10301
+ precision: number().int().min(0).max(10).optional()
10302
+ });
10303
+ DeviceType.Sensor;
10304
+ /**
10305
+ * Per-class audio metrics aggregated over a sliding window.
10306
+ */
10307
+ var AudioClassSummarySchema = object({
10308
+ className: string(),
10309
+ /** Number of windows (chunks) where this class was the top hit. */
10310
+ hits: number().int().nonnegative(),
10311
+ /** Mean score across those hits, clamped to [0,1]. */
10312
+ avgScore: number().min(0).max(1),
10313
+ /** Peak score in the window. */
10314
+ peakScore: number().min(0).max(1)
10315
+ });
10316
+ /**
10317
+ * Per-camera audio metrics snapshot — emitted by the analytics frame
10318
+ * handler on every `pipeline.audio-inference-result` event and
10319
+ * mirrored into the `audio-metrics` device-state slice. Symmetric
10320
+ * with `zone-analytics` snapshots for video — every consumer
10321
+ * (admin UI panel, automations, alert rules) reads via the
10322
+ * canonical `device.state.audioMetrics.value` reactive handle.
10323
+ *
10324
+ * Aggregates are computed over a rolling `windowSec` window
10325
+ * (default 60s). Past that window, classes drop out of `byClass`
10326
+ * and the level history shifts forward.
10327
+ */
10328
+ var AudioMetricsSnapshotSchema = object({
10329
+ /** Wall-clock timestamp (ms) of the most recent audio window. */
10330
+ ts: number().int(),
10331
+ /** Sliding-window length (seconds) used for aggregation. */
10332
+ windowSec: number().int().positive(),
10333
+ /** Latest level reading from the most recent window. */
10334
+ level: object({
10335
+ rms: number(),
10336
+ dbfs: number()
10337
+ }),
10338
+ /** Peak dBFS observed across the rolling window. */
10339
+ peakDbfs: number(),
10340
+ /** Mean dBFS across the rolling window. */
10341
+ avgDbfs: number(),
10342
+ /** Most recent above-threshold classification, or null on silence. */
10343
+ current: object({
10344
+ className: string(),
10345
+ score: number().min(0).max(1),
10346
+ timestamp: number().int()
10347
+ }).nullable(),
10348
+ /** Per-class summary across the rolling window — keys are
10349
+ * `macroClass` strings (e.g. `dog_bark`, `speech`, `glass_break`). */
10350
+ byClass: array(AudioClassSummarySchema).readonly()
10351
+ });
10352
+ /**
10353
+ * Audio-metrics history payload — a series of `AudioMetricsHistoryPoint`
10354
+ * samples capped at `maxPoints` (default 1024). When the requested
10355
+ * `windowSec / sampleEveryMs` would exceed the cap, the provider
10356
+ * subsamples by bucketed averaging and reports the effective sample
10357
+ * spacing on `effectiveSampleEveryMs` so the UI can label the x-axis.
10358
+ */
10359
+ var AudioMetricsHistorySchema = object({
10360
+ points: array(object({
10361
+ /** Wall-clock ms when this sample was recorded. */
10362
+ ts: number().int(),
10363
+ /** Instantaneous dBFS level at sample time. `null` for windows where
10364
+ * the source had no level reading (rare; happens at decode startup). */
10365
+ dbfs: number().nullable(),
10366
+ /** Rolling-window peak dBFS at sample time. Same window the live
10367
+ * snapshot reports. */
10368
+ peakDbfs: number(),
10369
+ /** Rolling-window mean dBFS at sample time. */
10370
+ avgDbfs: number(),
10371
+ /** Dominant above-threshold class at sample time, or null on silence. */
10372
+ topClass: string().nullable(),
10373
+ /** Score of the dominant class (`null` whenever `topClass` is null). */
10374
+ topScore: number().min(0).max(1).nullable()
10375
+ })).readonly(),
10376
+ /** Actual ms between adjacent samples after any subsampling. */
10377
+ effectiveSampleEveryMs: number().int().positive(),
10378
+ /** Wall-clock window covered by `points` (`points[N-1].ts - points[0].ts`),
10379
+ * or `0` when there's fewer than 2 samples. */
10380
+ windowMsActual: number().int().nonnegative()
10381
+ });
10382
+ DeviceType.Camera, method(object({ deviceId: number() }), AudioMetricsSnapshotSchema.nullable()), method(object({
10383
+ deviceId: number(),
10384
+ /** History window in seconds. Default 300 (5 minutes).
10385
+ * Provider clamps to its retention cap if larger. */
10386
+ windowSec: number().int().positive().optional(),
10387
+ /** Target sample interval in ms. Default 1000 (1 sample/second).
10388
+ * Provider clamps to natural sample rate if smaller, and
10389
+ * bucket-averages when bigger than the requested window
10390
+ * would produce more than `maxPoints` samples. */
10391
+ sampleEveryMs: number().int().positive().optional()
10392
+ }), AudioMetricsHistorySchema);
10393
+ object({
10394
+ /** Whether the automation is currently enabled. Disabled automations
10395
+ * ignore their trigger block — manual `trigger` still works. */
10396
+ enabled: boolean(),
10397
+ /** Whether the automation is currently executing its action block. */
10398
+ isRunning: boolean(),
10399
+ /** Ms epoch of the last successful run. 0 when never run. */
10400
+ lastTriggeredAt: number(),
10401
+ /** Failure description from the last completed run. Null on success
10402
+ * or when never run. */
10403
+ lastError: string().nullable(),
10404
+ /** Ms epoch when the slice was last updated. */
10405
+ lastChangedAt: number()
10406
+ });
10407
+ DeviceType.Automation, method(object({ deviceId: number().int().nonnegative() }), _void(), {
10408
+ kind: "mutation",
10409
+ auth: "admin"
10410
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
10411
+ kind: "mutation",
10412
+ auth: "admin"
10413
+ }), method(object({
10414
+ deviceId: number().int().nonnegative(),
10415
+ /** When true, fires the action block while bypassing the
10416
+ * automation's condition evaluation. Gated by
10417
+ * `DeviceFeature.AutomationSkipCondition`. */
10418
+ skipCondition: boolean().optional()
10419
+ }), _void(), {
10420
+ kind: "mutation",
10421
+ auth: "admin"
10422
+ });
10423
+ /**
10424
+ * Battery status snapshot. Emitted by providers whose device is
10425
+ * battery-operated (cameras with `DeviceFeature.BatteryOperated`,
10426
+ * future sensor/button accessories). Consumers build their own "low
10427
+ * battery" alerting on top — the cap deliberately does NOT enforce a
10428
+ * threshold.
10429
+ */
10430
+ var BatteryStatusSchema = object({
10431
+ /** 0..100 inclusive. Firmware-reported. */
10432
+ percentage: number().min(0).max(100),
10433
+ /**
10434
+ * Charging source. `'dc'` covers wall/USB adapters; `'solar'` is
10435
+ * Reolink-specific for the Solar Panel 2 accessory (will become
10436
+ * common on other battery cams). `'none'` means running on battery
10437
+ * alone.
10438
+ */
10439
+ charging: _enum([
10440
+ "dc",
10441
+ "solar",
10442
+ "none"
10443
+ ]),
10444
+ /**
10445
+ * True when the camera firmware has gone into low-power mode. Battery
10446
+ * providers MUST avoid polling during sleep — reading the battery
10447
+ * wakes the camera up and drains charge.
10448
+ */
10449
+ sleeping: boolean(),
10450
+ /** Ms epoch of the last observation. Lets consumers reason about freshness. */
10451
+ lastUpdated: number(),
10452
+ /**
10453
+ * True when the source is a BINARY low-battery indicator (HA
10454
+ * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
10455
+ * charge level — `percentage` is then a coarse stand-in (100 = normal,
10456
+ * sub-threshold = low). UI MUST render "Normal"/"Low" instead of a
10457
+ * misleading exact percentage. Absent/false → genuine 0–100 % reading.
10458
+ */
10459
+ binary: boolean().optional()
10460
+ });
10461
+ DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch, method(object({
10462
+ deviceId: number(),
10463
+ /** Bound on the wait. Sensible range 3000–10000ms. */
10464
+ timeoutMs: number().int().min(500).max(3e4).default(8e3)
10465
+ }), object({
10466
+ awoke: boolean(),
10467
+ durationMs: number()
10468
+ }), { kind: "mutation" }), object({
10469
+ deviceId: number(),
10470
+ status: BatteryStatusSchema
10471
+ });
10472
+ object({
10473
+ on: boolean(),
10474
+ /** Ms epoch of the last transition. 0 if never observed. */
10475
+ lastChangedAt: number()
10476
+ });
10477
+ DeviceType.Sensor;
10478
+ object({
10479
+ /** Current level as 0..100 inclusive. Firmware-reported. */
10480
+ percentage: number().min(0).max(100),
10481
+ /** Ms epoch of the last operator-driven change. Useful for UI freshness. */
10482
+ lastChangedAt: number()
10483
+ });
10484
+ DeviceType.Light, method(object({
10485
+ deviceId: number().int().nonnegative(),
10486
+ percentage: number().min(0).max(100)
10487
+ }), _void(), {
10488
+ kind: "mutation",
10489
+ auth: "admin"
10490
+ }), object({
10491
+ deviceId: number(),
10492
+ percentage: number().min(0).max(100),
10493
+ lastChangedAt: number()
10494
+ });
10495
+ /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
10496
+ var StreamFormatSchema = _enum([
10497
+ "webrtc",
10498
+ "hls",
10499
+ "mjpeg",
10500
+ "rtsp"
10501
+ ]);
10502
+ var RtspRestreamEntrySchema = object({
10503
+ brokerId: string(),
10504
+ url: string(),
10505
+ mutedUrl: string(),
10506
+ enabled: boolean(),
10507
+ /**
10508
+ * Source-stream codec / resolution for the camStream this entry serves
10509
+ * (the broker's "high"/"mid"/"low" profile slot for this device).
10510
+ * Used by exporter pickers (`pickPreferredRtspEntry`) to resolve
10511
+ * `streamPreference: 'auto'` to the slot whose source is closest to
10512
+ * the consumer's target — Alexa wants ~720p, HomeKit wants ~1080p,
10513
+ * and there's no point dialling the 4K slot for an Echo Show. Absent
10514
+ * when the source publisher never advertised the field; pickers fall
10515
+ * back to first-enabled in that case.
10516
+ */
10517
+ codec: string().optional(),
10518
+ resolution: object({
10519
+ width: number().int().positive(),
10520
+ height: number().int().positive()
10521
+ }).optional()
10522
+ });
10523
+ var BrokerRtspClientSchema = object({
10524
+ sessionId: string(),
10525
+ remoteAddr: string(),
10526
+ /** Client `User-Agent` (e.g. `recorder` for the recorder's RTSP pull), or
10527
+ * null/absent when the client sent none. Lets the UI label a consumer by
10528
+ * purpose. Optional so a client built against an older schema stays valid. */
10529
+ userAgent: string().nullish(),
10530
+ playing: boolean(),
10531
+ muted: boolean(),
10532
+ connectedAt: number(),
10533
+ lastRtpAt: number(),
10534
+ bytesSent: number()
10535
+ });
10536
+ var BrokerDecodedClientSchema = object({
10537
+ tag: string(),
10538
+ subscribedAt: number(),
10539
+ maxFps: number(),
10540
+ framesDelivered: number(),
10541
+ framesDropped: number()
10542
+ });
10543
+ var BrokerAudioClientSchema = object({
10544
+ tag: string(),
10545
+ subscribedAt: number(),
10546
+ chunksDelivered: number()
10547
+ });
10548
+ var BrokerConsumerAttributionSchema = object({
10549
+ kind: _enum([
10550
+ "alexa",
10551
+ "homekit",
10552
+ "webrtc-browser",
10553
+ "webrtc-mobile",
10554
+ "webrtc-whep",
10555
+ "rtsp-listen",
10556
+ "derived-broker",
10557
+ "recording",
10558
+ "pipeline",
10559
+ "snapshot",
10560
+ "warmup",
10561
+ "unknown"
10562
+ ]),
10563
+ /**
10564
+ * Free-form label intended to disambiguate consumers OF THE SAME kind
10565
+ * on the same broker — e.g. user name, device alias. Should NOT repeat
10566
+ * the kind / cam / cam-stream / sessionId (those are surfaced by
10567
+ * dedicated fields). When empty the widget falls back to `${kind} ·
10568
+ * <sessionId tail>`.
10569
+ */
10570
+ label: string().optional(),
10571
+ /**
10572
+ * Which part of the encoded plane this subscription consumes:
10573
+ * - `'audio'` — audio packets only
10574
+ * - `'video'` — video packets only
10575
+ * - `'both'` — both video + audio (typical for AnnexB push paths
10576
+ * that don't split the source RTP)
10577
+ *
10578
+ * Missing field means "unknown" — older callers and the legacy
10579
+ * paths that haven't been migrated yet.
10580
+ */
10581
+ media: _enum([
10582
+ "audio",
10583
+ "video",
10584
+ "both"
10585
+ ]).optional(),
10586
+ /**
10587
+ * Codec the consumer receives AFTER any per-session re-encoding. For
10588
+ * a WebRTC session this is the negotiated egress codec (e.g. `H264`,
10589
+ * `H265`, `Opus`, `Pcmu`); for an RTSP restreamer it mirrors the
10590
+ * source codec. Surfaced in the widget chip so operators see at a
10591
+ * glance whether a viewer is on H.264 (Echo) or H.265 (Safari).
10592
+ */
10593
+ targetCodec: string().optional(),
10594
+ /**
10595
+ * Whether the broker is re-encoding for this consumer:
10596
+ * - `'passthrough'` — bytes flow source→consumer without ffmpeg
10597
+ * - `'repacketize'` — RTP payload is re-packetized but NOT re-encoded
10598
+ * (preserves frames, just rebuilds headers; e.g.
10599
+ * the H.265 repacketizer path)
10600
+ * - `'transcode'` — a full encode/decode round (ffmpeg, libx264,
10601
+ * libav…); the most expensive path
10602
+ */
10603
+ transport: _enum([
10604
+ "passthrough",
10605
+ "repacketize",
10606
+ "transcode"
10607
+ ]).optional(),
10608
+ /** Remote peer IP if the consumer terminates a network socket. */
10609
+ remoteAddr: string().optional(),
10610
+ /**
10611
+ * Server-read User-Agent of the originating client; enriched by the hub
10612
+ * from the tRPC request context (browser sessions).
10613
+ */
10614
+ userAgent: string().optional(),
10615
+ /** Authenticated user id (CamStack OAuth subject) when known. */
10616
+ userId: string().optional(),
10617
+ /** Higher-level session identifier (Alexa Echo sessionId, HAP session, …). */
10618
+ sessionId: string().optional(),
10619
+ /** Free-form key/value extras (e.g. clientHints from a WebRTC offer). */
10620
+ extra: record(string(), string()).optional()
10621
+ }).readonly();
10622
+ var BrokerEncodedClientSchema = object({
10623
+ /** Stable id assigned on attach; used by `killClient`. */
10624
+ id: string(),
10625
+ /** Which broker fanout the subscriber rides — annexB encoded packets vs raw RTP. */
10626
+ channel: _enum(["annexb", "rtp"]),
10627
+ attribution: BrokerConsumerAttributionSchema,
9983
10628
  subscribedAt: number(),
9984
10629
  /** Total packets delivered (annex-B EncodedPackets or RTP byte-buffers). */
9985
10630
  packetsDelivered: number()
@@ -12724,101 +13369,40 @@ method(RunnerCameraConfigSchema, object({ success: literal(true) }), { kind: "mu
12724
13369
  }), object({ details: array(DetailResultSchema) }).nullable(), { kind: "mutation" });
12725
13370
  object({
12726
13371
  detected: boolean(),
12727
- /** Ms epoch of the last detected-true observation. Null if never detected. */
12728
- lastDetectedAt: number().nullable(),
12729
- /**
12730
- * Ms after which `detected` auto-reverts to false if no fresh push
12731
- * arrives. Null means the provider leaves detected state until a
12732
- * native "clear" event.
12733
- */
12734
- autoClearAfterMs: number().nullable()
12735
- });
12736
- object({
12737
- deviceId: number(),
12738
- detected: boolean(),
12739
- timestamp: number(),
12740
- source: MotionSourceEnum,
12741
- regions: array(MotionRegionSchema).readonly().optional()
12742
- });
12743
- DeviceType.Camera, DeviceType.Sensor, method(object({ deviceId: number() }), boolean());
12744
- object({
12745
- enabled: boolean(),
12746
- /** Ms epoch of the last operator-driven change. */
12747
- lastChangedAt: number()
12748
- }).extend({
12749
- /** Ms epoch of the last successful camera fetch (0 = never). */
12750
- lastFetchedAt: number() });
12751
- DeviceType.Light, DeviceType.Siren, DeviceType.Switch, method(object({
12752
- deviceId: number().int().nonnegative(),
12753
- enabled: boolean()
12754
- }), _void(), {
12755
- kind: "mutation",
12756
- auth: "admin"
12757
- }), object({
12758
- deviceId: number(),
12759
- enabled: boolean(),
12760
- lastChangedAt: number()
12761
- });
12762
- /**
12763
- * Shared geometry vocabulary for on-frame shape caps — privacy-mask,
12764
- * motion-zones, and the detection zones/lines editor all speak this one
12765
- * language so a single drawing-plane editor and the providers stay
12766
- * decoupled from each cap's storage.
12767
- *
12768
- * All coordinates are normalized 0..1 of the camera frame (top-left
12769
- * origin). Each cap composes the SUBSET of shape kinds it supports and
12770
- * advertises it via `supportedShapes` in its `getOptions`.
12771
- */
12772
- /** A normalized 0..1 point (top-left origin). */
12773
- var MaskPointSchema = object({
12774
- x: number(),
12775
- y: number()
12776
- });
12777
- /** Axis-aligned rectangle (normalized 0..1). */
12778
- var MaskRectShapeSchema = object({
12779
- kind: literal("rect"),
12780
- x: number(),
12781
- y: number(),
12782
- width: number(),
12783
- height: number()
12784
- });
12785
- /** Free polygon — an ordered list of normalized vertices (≥3). */
12786
- var MaskPolygonShapeSchema = object({
12787
- kind: literal("polygon"),
12788
- points: array(MaskPointSchema)
12789
- });
12790
- /** Boolean cell grid — row-major, length === gridWidth*gridHeight. */
12791
- var MaskGridShapeSchema = object({
12792
- kind: literal("grid"),
12793
- gridWidth: number(),
12794
- gridHeight: number(),
12795
- cells: array(boolean())
12796
- });
12797
- discriminatedUnion("kind", [
12798
- MaskRectShapeSchema,
12799
- MaskPolygonShapeSchema,
12800
- MaskGridShapeSchema,
12801
- object({
12802
- kind: literal("line"),
12803
- points: array(MaskPointSchema)
12804
- })
12805
- ]);
12806
- /** Every shape-kind discriminant, for `supportedShapes` advertisement. */
12807
- var MaskShapeKindSchema = _enum([
12808
- "rect",
12809
- "polygon",
12810
- "grid",
12811
- "line"
12812
- ]);
12813
- /** Polygon vertex bounds when a cap supports 'polygon' (e.g. Hikvision {min:4,max:4}). */
12814
- var MaskPolygonVerticesSchema = object({
12815
- min: number(),
12816
- max: number()
13372
+ /** Ms epoch of the last detected-true observation. Null if never detected. */
13373
+ lastDetectedAt: number().nullable(),
13374
+ /**
13375
+ * Ms after which `detected` auto-reverts to false if no fresh push
13376
+ * arrives. Null means the provider leaves detected state until a
13377
+ * native "clear" event.
13378
+ */
13379
+ autoClearAfterMs: number().nullable()
12817
13380
  });
12818
- /** Grid dimensions when a cap supports 'grid'. */
12819
- var MaskGridDimsSchema = object({
12820
- width: number(),
12821
- height: number()
13381
+ object({
13382
+ deviceId: number(),
13383
+ detected: boolean(),
13384
+ timestamp: number(),
13385
+ source: MotionSourceEnum,
13386
+ regions: array(MotionRegionSchema).readonly().optional()
13387
+ });
13388
+ DeviceType.Camera, DeviceType.Sensor, method(object({ deviceId: number() }), boolean());
13389
+ object({
13390
+ enabled: boolean(),
13391
+ /** Ms epoch of the last operator-driven change. */
13392
+ lastChangedAt: number()
13393
+ }).extend({
13394
+ /** Ms epoch of the last successful camera fetch (0 = never). */
13395
+ lastFetchedAt: number() });
13396
+ DeviceType.Light, DeviceType.Siren, DeviceType.Switch, method(object({
13397
+ deviceId: number().int().nonnegative(),
13398
+ enabled: boolean()
13399
+ }), _void(), {
13400
+ kind: "mutation",
13401
+ auth: "admin"
13402
+ }), object({
13403
+ deviceId: number(),
13404
+ enabled: boolean(),
13405
+ lastChangedAt: number()
12822
13406
  });
12823
13407
  /**
12824
13408
  * Motion-zones share the same MaskShape vocabulary as privacy-mask — the
@@ -14744,6 +15328,55 @@ method(object({
14744
15328
  password: string()
14745
15329
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
14746
15330
  /**
15331
+ * A live terminal session hosted by the provider addon. Output and input do
15332
+ * NOT flow through the capability — they use the addon data plane
15333
+ * (`GET /addon/terminal/<id>/out` SSE, `POST /addon/terminal/<id>/in`) because
15334
+ * terminal output must be ordered and lossless. The event bus is telemetry and
15335
+ * may drop chunks ([D8]), and a dropped chunk desynchronises the vt parser
15336
+ * permanently until a full repaint. The capability owns only lifecycle.
15337
+ */
15338
+ var TerminalSessionInfoSchema = object({
15339
+ /** Opaque session id minted by the provider on `openSession`. */
15340
+ sessionId: string(),
15341
+ /** The pre-declared profile this session runs (never a free-form command). */
15342
+ profileId: string(),
15343
+ /** Human-readable profile label for the UI session list. */
15344
+ label: string(),
15345
+ cols: number().int().positive(),
15346
+ rows: number().int().positive(),
15347
+ /** ms-epoch the session's pty was spawned. */
15348
+ startedAt: number()
15349
+ });
15350
+ /**
15351
+ * A profile the operator may open — a pre-declared, allowlisted program
15352
+ * (`monitor` → `btm`). The capability accepts only these ids; a free-form
15353
+ * command string would be remote code execution as the server's user, so it is
15354
+ * deliberately not part of the contract.
15355
+ */
15356
+ var TerminalProfileInfoSchema = object({
15357
+ profileId: string(),
15358
+ label: string(),
15359
+ description: string().optional()
15360
+ });
15361
+ method(_void(), array(TerminalProfileInfoSchema).readonly(), { auth: "admin" }), method(_void(), array(TerminalSessionInfoSchema).readonly(), { auth: "admin" }), method(object({
15362
+ profileId: string(),
15363
+ cols: number().int().positive(),
15364
+ rows: number().int().positive()
15365
+ }), TerminalSessionInfoSchema, {
15366
+ kind: "mutation",
15367
+ auth: "admin"
15368
+ }), method(object({
15369
+ sessionId: string(),
15370
+ cols: number().int().positive(),
15371
+ rows: number().int().positive()
15372
+ }), _void(), {
15373
+ kind: "mutation",
15374
+ auth: "admin"
15375
+ }), method(object({ sessionId: string() }), _void(), {
15376
+ kind: "mutation",
15377
+ auth: "admin"
15378
+ });
15379
+ /**
14747
15380
  * Orchestrator-side destination metadata. The orchestrator computes
14748
15381
  * `id = <addonId>:<subId>` from its provider lookup so consumers
14749
15382
  * (admin UI, restore flow) see one canonical key.
@@ -14844,11 +15477,53 @@ var LocationStatSchema = object({
14844
15477
  fileCount: number(),
14845
15478
  present: boolean()
14846
15479
  });
15480
+ /**
15481
+ * A backup schedule — the N:M "entry" that binds one cron cadence to a
15482
+ * SET of destination locations. Supersedes the per-location cron on
15483
+ * `BackupDestinationPolicy`: an operator creates a schedule, picks the
15484
+ * `backups` locations it should write to, and the orchestrator fans a
15485
+ * single archive out to all of them when the cron fires.
15486
+ *
15487
+ * `retentionCount` is per-schedule (D-decision 2026-07-28): every
15488
+ * location targeted by this schedule keeps this many archives from
15489
+ * this schedule's runs.
15490
+ *
15491
+ * `dataSources` optionally narrows which top-level state locations
15492
+ * (db, addons, tls, …) are archived; omitted = the orchestrator's
15493
+ * default full set.
15494
+ */
15495
+ var BackupScheduleSchema = object({
15496
+ /** Stable id. Generated by the orchestrator on first upsert if absent. */
15497
+ id: string(),
15498
+ /** Operator-facing display name. */
15499
+ label: string(),
15500
+ /** 5-field POSIX cron. Empty = disabled cadence (kept for editing). */
15501
+ cron: string(),
15502
+ /** Master on/off toggle for the whole schedule. */
15503
+ enabled: boolean(),
15504
+ /** `backups`-location ids this schedule writes to (fan-out set). */
15505
+ locationIds: array(string()).readonly(),
15506
+ /** Archives kept per targeted location for this schedule. */
15507
+ retentionCount: number().int().min(1).max(1e3),
15508
+ /** Optional subset of source locations to include; omitted = all. */
15509
+ dataSources: array(string()).readonly().optional(),
15510
+ /** ms-epoch of last successful run. */
15511
+ lastRunAt: number().optional(),
15512
+ /** ms-epoch of next computed firing (read-only, filled on list). */
15513
+ nextRunAt: number().optional()
15514
+ });
14847
15515
  method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }), method(object({
14848
15516
  /** Subset of registered `backup-destination` addon ids to write to. */
14849
15517
  destinations: array(string()).optional(),
14850
15518
  locations: array(string()).optional(),
14851
- label: string().optional()
15519
+ label: string().optional(),
15520
+ /**
15521
+ * Per-run retention override applied to every targeted
15522
+ * destination. Used by schedule-driven runs (per-entry
15523
+ * retention). Omitted = each destination's own policy
15524
+ * retention (manual runs).
15525
+ */
15526
+ retentionCount: number().int().min(1).max(1e3).optional()
14852
15527
  }).optional(), array(BackupEntrySchema).readonly(), {
14853
15528
  kind: "mutation",
14854
15529
  auth: "admin"
@@ -14897,7 +15572,21 @@ method(_void(), array(BackupDestinationInfoSchema).readonly(), { auth: "admin" }
14897
15572
  ok: boolean(),
14898
15573
  error: string().optional(),
14899
15574
  nextRuns: array(number()).readonly()
14900
- }));
15575
+ })), method(_void(), array(BackupScheduleSchema).readonly(), { auth: "admin" }), method(object({
15576
+ id: string().optional(),
15577
+ label: string(),
15578
+ cron: string(),
15579
+ enabled: boolean(),
15580
+ locationIds: array(string()).readonly(),
15581
+ retentionCount: number().int().min(1).max(1e3),
15582
+ dataSources: array(string()).readonly().optional()
15583
+ }), BackupScheduleSchema, {
15584
+ kind: "mutation",
15585
+ auth: "admin"
15586
+ }), method(object({ id: string() }), _void(), {
15587
+ kind: "mutation",
15588
+ auth: "admin"
15589
+ });
14901
15590
  /**
14902
15591
  * `broker` — unified pub/sub broker registry, system-scoped collection.
14903
15592
  *
@@ -15973,1596 +16662,1108 @@ method(object({
15973
16662
  active: boolean()
15974
16663
  }), _void(), {
15975
16664
  kind: "mutation",
15976
- auth: "admin"
15977
- }), method(object({ capName: string() }), array(string())), method(object({ deviceType: string() }), array(object({
15978
- capName: string(),
15979
- wrappers: array(string())
15980
- }))), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), object({
15981
- settings: SettingsSchemaWithValuesSchema.nullable(),
15982
- live: SettingsSchemaWithValuesSchema.nullable()
15983
- })), method(object({
15984
- deviceId: number().int().nonnegative(),
15985
- action: string().min(1),
15986
- input: unknown()
15987
- }), unknown(), { kind: "mutation" }), method(object({
15988
- deviceId: number(),
15989
- writerCapName: string(),
15990
- writerAddonId: string(),
15991
- key: string(),
15992
- value: unknown()
15993
- }), object({ success: literal(true) }), {
15994
- kind: "mutation",
15995
- auth: "admin"
15996
- }), method(object({
15997
- deviceId: number(),
15998
- changes: array(object({
15999
- writerCapName: string(),
16000
- writerAddonId: string(),
16001
- key: string(),
16002
- value: unknown()
16003
- }))
16004
- }), object({
16005
- success: literal(true),
16006
- failures: array(object({
16007
- writerCapName: string(),
16008
- writerAddonId: string(),
16009
- error: string()
16010
- }))
16011
- }), {
16012
- kind: "mutation",
16013
- auth: "admin"
16014
- }), method(object({ addonId: string() }), array(DiscoveryCandidateSchema), {
16015
- kind: "mutation",
16016
- auth: "admin"
16017
- }), method(object({
16018
- addonId: string(),
16019
- candidate: DiscoveryCandidateSchema,
16020
- /** Owning integration id, stamped onto the new device's meta by the
16021
- * device-manager forwarder so `removeByIntegration` can cascade it.
16022
- * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
16023
- integrationId: string().optional()
16024
- }), DeviceSummarySchema, {
16025
- kind: "mutation",
16026
- auth: "admin"
16027
- }), method(object({
16028
- addonId: string(),
16029
- type: _enum(DeviceType)
16030
- }), unknown().nullable()), method(object({
16031
- addonId: string(),
16032
- type: _enum(DeviceType),
16033
- config: record(string(), unknown()),
16034
- /** Owning integration id, stamped onto the new device's meta by the
16035
- * device-manager forwarder so `removeByIntegration` can cascade it.
16036
- * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
16037
- integrationId: string().optional()
16038
- }), DeviceSummarySchema, {
16039
- kind: "mutation",
16040
- auth: "admin"
16041
- }), method(object({
16042
- addonId: string(),
16043
- type: _enum(DeviceType),
16044
- key: string(),
16045
- value: unknown(),
16046
- formValues: record(string(), unknown()).optional()
16047
- }), FieldProbeResultSchema, {
16048
- kind: "mutation",
16049
- auth: "admin"
16050
- }), method(object({
16051
- addonId: string(),
16052
- integrationId: string()
16053
- }), object({ filters: array(AdoptionFilterSchema) }), { auth: "admin" }), method(ListCandidatesInputSchema.extend({ addonId: string() }), ListCandidatesOutputSchema, { auth: "admin" }), method(object({
16054
- addonId: string(),
16055
- integrationId: string()
16056
- }), AdoptionStatusSchema, {
16057
- kind: "mutation",
16058
- auth: "admin"
16059
- }), method(AdoptInputSchema.extend({ addonId: string() }), AdoptResultSchema, {
16060
- kind: "mutation",
16061
- auth: "admin"
16062
- }), method(ReleaseInputSchema.extend({ addonId: string() }), _void(), {
16063
- kind: "mutation",
16064
- auth: "admin"
16065
- }), method(ResyncInputSchema, ResyncResultSchema, {
16066
- kind: "mutation",
16067
- auth: "admin"
16068
- }), method(object({}), object({ providers: array(object({
16069
- addonId: string(),
16070
- label: string()
16071
- })).readonly() }), { auth: "admin" }), method(object({}), object({ groups: array(object({
16072
- addonId: string(),
16073
- label: string(),
16074
- candidates: array(DiscoveryCandidateSchema).readonly(),
16075
- error: string().nullable()
16076
- })).readonly() }), {
16077
- kind: "mutation",
16078
- auth: "admin"
16079
- }), method(object({
16080
- addonId: string(),
16081
- params: record(string(), unknown()).optional()
16082
- }), object({ candidates: array(DiscoveryCandidateSchema).readonly() }), {
16083
- kind: "mutation",
16084
- auth: "admin"
16085
- }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
16086
- deviceId: number(),
16087
- key: string(),
16088
- value: unknown()
16089
- }), FieldProbeResultSchema, {
16090
- kind: "mutation",
16091
- auth: "admin"
16092
- }), method(object({
16093
- deviceId: number(),
16094
- caps: array(string()).readonly().optional()
16095
- }), record(string(), unknown().nullable()));
16096
- method(object({ deviceId: number() }), record(string(), record(string(), unknown()))), method(object({
16097
- deviceId: number(),
16098
- capName: string()
16099
- }), record(string(), unknown()).nullable()), method(object({}), record(string(), record(string(), record(string(), unknown())))), method(object({
16100
- deviceId: number(),
16101
- capName: string(),
16102
- slice: record(string(), unknown())
16103
- }), _void(), { kind: "mutation" }), object({
16104
- deviceId: number(),
16105
- capName: string(),
16106
- slice: record(string(), unknown())
16107
- });
16108
- /**
16109
- * Embedding output. `embedding` is wire-encoded as `number[]` so the
16110
- * Zod-validated tRPC surface round-trips cleanly; consumers that need a
16111
- * `Float32Array` can wrap it on the way out (in-process, no marshalling
16112
- * is involved). `inferenceMs` mirrors the runtime field used by the
16113
- * post-analysis enrichment-engine.
16114
- */
16115
- var EmbeddingResultSchema = object({
16116
- embedding: array(number()),
16117
- inferenceMs: number()
16118
- });
16119
- var EmbeddingInfoSchema = object({
16120
- modelId: string(),
16121
- embeddingDim: number(),
16122
- ready: boolean()
16123
- });
16124
- method(object({
16125
- crop: _instanceof(Uint8Array),
16126
- width: number(),
16127
- height: number()
16128
- }), EmbeddingResultSchema), method(object({ text: string() }), EmbeddingResultSchema), method(_void(), EmbeddingInfoSchema);
16129
- /**
16130
- * filesystem-browse — per-node capability for browsing the node's local
16131
- * filesystem, sandboxed to operator-configured allowed roots. Used by the
16132
- * admin "Add filesystem location" flow to pick a node + path. `mode:'per-node'`
16133
- * (one provider per node); the hub calls it with `{nodeId}` so the codegen
16134
- * routes to that exact node (default `nodeIdMode:'routing'`).
16135
- */
16136
- var DirEntrySchema = object({
16137
- name: string(),
16138
- path: string()
16139
- });
16140
- var BrowseResultSchema = object({
16141
- path: string(),
16142
- entries: array(DirEntrySchema).readonly(),
16143
- freeBytes: number(),
16144
- totalBytes: number()
16145
- });
16146
- method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({ path: string() }), BrowseResultSchema, { auth: "admin" }), method(object({ path: string() }), object({ path: string() }), {
16665
+ auth: "admin"
16666
+ }), method(object({ capName: string() }), array(string())), method(object({ deviceType: string() }), array(object({
16667
+ capName: string(),
16668
+ wrappers: array(string())
16669
+ }))), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), object({
16670
+ settings: SettingsSchemaWithValuesSchema.nullable(),
16671
+ live: SettingsSchemaWithValuesSchema.nullable()
16672
+ })), method(object({
16673
+ deviceId: number().int().nonnegative(),
16674
+ action: string().min(1),
16675
+ input: unknown()
16676
+ }), unknown(), { kind: "mutation" }), method(object({
16677
+ deviceId: number(),
16678
+ writerCapName: string(),
16679
+ writerAddonId: string(),
16680
+ key: string(),
16681
+ value: unknown()
16682
+ }), object({ success: literal(true) }), {
16147
16683
  kind: "mutation",
16148
16684
  auth: "admin"
16149
- });
16150
- /**
16151
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
16152
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
16153
- * caps stay wire-compatible without a circular cap→cap import.
16154
- *
16155
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
16156
- * every transport tier structurally, and failed calls still write usage rows.
16157
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
16158
- */
16159
- var LlmUsageSchema = object({
16160
- inputTokens: number(),
16161
- outputTokens: number()
16162
- });
16163
- var LlmErrorCodeSchema = _enum([
16164
- "timeout",
16165
- "rate-limited",
16166
- "auth",
16167
- "refusal",
16168
- "bad-request",
16169
- "unavailable",
16170
- "no-profile",
16171
- "budget-exceeded",
16172
- "adapter-error"
16173
- ]);
16174
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
16175
- ok: literal(true),
16176
- text: string(),
16177
- model: string(),
16178
- usage: LlmUsageSchema,
16179
- truncated: boolean(),
16180
- latencyMs: number()
16685
+ }), method(object({
16686
+ deviceId: number(),
16687
+ changes: array(object({
16688
+ writerCapName: string(),
16689
+ writerAddonId: string(),
16690
+ key: string(),
16691
+ value: unknown()
16692
+ }))
16181
16693
  }), object({
16182
- ok: literal(false),
16183
- code: LlmErrorCodeSchema,
16184
- message: string(),
16185
- retryAfterMs: number().optional()
16186
- })]);
16187
- /**
16188
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
16189
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
16190
- * notification-output.cap.ts:27-31 precedents).
16191
- */
16192
- var LlmImageSchema = object({
16193
- bytes: _instanceof(Uint8Array),
16194
- mimeType: string()
16195
- });
16196
- var LlmGenerateBaseInputSchema = object({
16197
- /** Collection routing (the notification-output posture). */
16198
- addonId: string().optional(),
16199
- /** Explicit profile; else the resolution chain (spec §3). */
16200
- profileId: string().optional(),
16201
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
16202
- consumer: string(),
16203
- system: string().optional(),
16204
- /** v1: single-turn. `messages[]` is a v2 additive field. */
16205
- prompt: string(),
16206
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
16207
- jsonSchema: record(string(), unknown()).optional(),
16208
- /** Per-call override of the profile default. */
16209
- maxTokens: number().int().positive().optional(),
16210
- temperature: number().optional()
16211
- });
16212
- /**
16213
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
16214
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
16215
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
16216
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
16217
- * this only through the `llm` cap's methods.
16218
- *
16219
- * One running llama-server child per node in v1 (models are RAM-heavy).
16220
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
16221
- * watchdog — operator decision #3).
16222
- */
16223
- var ManagedModelRefSchema = discriminatedUnion("kind", [
16224
- object({
16225
- kind: literal("catalog"),
16226
- catalogId: string()
16227
- }),
16228
- object({
16229
- kind: literal("url"),
16230
- url: string(),
16231
- sha256: string().optional()
16232
- }),
16233
- object({
16234
- kind: literal("path"),
16235
- path: string()
16236
- })
16237
- ]);
16238
- var ManagedRuntimeConfigSchema = object({
16239
- /** WHERE the runtime lives — hub or any agent. */
16240
- nodeId: string(),
16241
- /** Closed for v1; 'ollama' is a v2 candidate. */
16242
- engine: _enum(["llama-cpp"]),
16243
- model: ManagedModelRefSchema,
16244
- contextSize: number().int().default(4096),
16245
- /** 0 = CPU-only. */
16246
- gpuLayers: number().int().default(0),
16247
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
16248
- threads: number().int().optional(),
16249
- /** Concurrent slots. */
16250
- parallel: number().int().default(1),
16251
- /** Else lazy: first generate boots it. */
16252
- autoStart: boolean().default(false),
16253
- /** 0 = never; frees RAM after quiet periods. */
16254
- idleStopMinutes: number().int().default(30)
16255
- });
16256
- var LlmRuntimeStatusSchema = object({
16257
- /** Status is ALWAYS node-qualified. */
16258
- nodeId: string(),
16259
- state: _enum([
16260
- "stopped",
16261
- "downloading",
16262
- "starting",
16263
- "ready",
16264
- "crashed",
16265
- "failed"
16266
- ]),
16267
- pid: number().optional(),
16268
- port: number().optional(),
16269
- modelPath: string().optional(),
16270
- modelId: string().optional(),
16271
- downloadProgress: number().min(0).max(1).optional(),
16272
- lastError: string().optional(),
16273
- crashesInWindow: number(),
16274
- /** Child RSS (sampled best-effort). */
16275
- memoryBytes: number().optional(),
16276
- vramBytes: number().optional()
16277
- });
16278
- var LlmNodeModelSchema = object({
16279
- file: string(),
16280
- sizeBytes: number(),
16281
- catalogId: string().optional(),
16282
- installedAt: number().optional()
16283
- });
16284
- var LlmRuntimeDiskUsageSchema = object({
16285
- nodeId: string(),
16286
- modelsBytes: number(),
16287
- freeBytes: number().optional()
16288
- });
16289
- method(LlmGenerateBaseInputSchema.extend({
16290
- images: array(LlmImageSchema).optional(),
16291
- runtime: ManagedRuntimeConfigSchema,
16292
- /** The managed profile's timeout, threaded by the hub provider. */
16293
- timeoutMs: number().int().positive().optional()
16294
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
16694
+ success: literal(true),
16695
+ failures: array(object({
16696
+ writerCapName: string(),
16697
+ writerAddonId: string(),
16698
+ error: string()
16699
+ }))
16700
+ }), {
16295
16701
  kind: "mutation",
16296
16702
  auth: "admin"
16297
- }), method(object({}), _void(), {
16703
+ }), method(object({ addonId: string() }), array(DiscoveryCandidateSchema), {
16298
16704
  kind: "mutation",
16299
16705
  auth: "admin"
16300
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
16706
+ }), method(object({
16707
+ addonId: string(),
16708
+ candidate: DiscoveryCandidateSchema,
16709
+ /** Owning integration id, stamped onto the new device's meta by the
16710
+ * device-manager forwarder so `removeByIntegration` can cascade it.
16711
+ * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
16712
+ integrationId: string().optional()
16713
+ }), DeviceSummarySchema, {
16301
16714
  kind: "mutation",
16302
16715
  auth: "admin"
16303
- }), method(object({ file: string() }), _void(), {
16716
+ }), method(object({
16717
+ addonId: string(),
16718
+ type: _enum(DeviceType)
16719
+ }), unknown().nullable()), method(object({
16720
+ addonId: string(),
16721
+ type: _enum(DeviceType),
16722
+ config: record(string(), unknown()),
16723
+ /** Owning integration id, stamped onto the new device's meta by the
16724
+ * device-manager forwarder so `removeByIntegration` can cascade it.
16725
+ * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
16726
+ integrationId: string().optional()
16727
+ }), DeviceSummarySchema, {
16304
16728
  kind: "mutation",
16305
16729
  auth: "admin"
16306
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
16307
- /**
16308
- * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
16309
- * methods concat-fan across providers; single-row methods route to ONE
16310
- * provider by the `addonId` in the call input (the notification-output
16311
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
16312
- * (hub-placed); the cap stays open for future providers.
16313
- *
16314
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
16315
- * `apiKey` is a password field — providers REDACT it on read and merge on
16316
- * write; a stored key NEVER round-trips to a client.
16317
- */
16318
- var LlmProfileKindSchema = _enum([
16319
- "openai-compatible",
16320
- "openai",
16321
- "anthropic",
16322
- "google",
16323
- "managed-local"
16324
- ]);
16325
- var LlmProfileSchema = object({
16326
- id: string(),
16327
- name: string(),
16328
- kind: LlmProfileKindSchema,
16329
- /** Stamped by the provider — keeps the fanned catalog routable. */
16730
+ }), method(object({
16330
16731
  addonId: string(),
16331
- enabled: boolean(),
16332
- /** Vendor model id, or the managed runtime's loaded model. */
16333
- model: string(),
16334
- /** Required for openai-compatible; override for cloud kinds. */
16335
- baseUrl: string().optional(),
16336
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
16337
- apiKey: string().optional(),
16338
- supportsVision: boolean(),
16339
- temperature: number().min(0).max(2).optional(),
16340
- maxTokens: number().int().positive().optional(),
16341
- timeoutMs: number().int().positive().default(6e4),
16342
- extraHeaders: record(string(), string()).optional(),
16343
- /** kind === 'managed-local' only (spec §4). */
16344
- runtime: ManagedRuntimeConfigSchema.optional()
16345
- });
16346
- /** ConfigUISchema tree passed through untyped on the wire (the
16347
- * notification-output `ConfigSchemaPassthrough` precedent at
16348
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
16349
- var ConfigSchemaPassthrough$1 = unknown();
16350
- var LlmProfileKindDescriptorSchema = object({
16351
- kind: LlmProfileKindSchema,
16352
- label: string(),
16353
- icon: string(),
16354
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
16732
+ type: _enum(DeviceType),
16733
+ key: string(),
16734
+ value: unknown(),
16735
+ formValues: record(string(), unknown()).optional()
16736
+ }), FieldProbeResultSchema, {
16737
+ kind: "mutation",
16738
+ auth: "admin"
16739
+ }), method(object({
16355
16740
  addonId: string(),
16356
- configSchema: ConfigSchemaPassthrough$1
16357
- });
16358
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
16359
- var LlmDefaultSchema = object({
16360
- selector: LlmDefaultSelectorSchema,
16361
- profileId: string()
16362
- });
16363
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
16364
- var LlmUsageRollupSchema = object({
16365
- day: string(),
16366
- consumer: string(),
16367
- profileId: string(),
16368
- calls: number(),
16369
- okCalls: number(),
16370
- errorCalls: number(),
16371
- inputTokens: number(),
16372
- outputTokens: number(),
16373
- avgLatencyMs: number()
16374
- });
16375
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
16376
- var ManagedModelCatalogEntrySchema = object({
16377
- id: string(),
16378
- label: string(),
16379
- family: string(),
16380
- purpose: _enum(["text", "vision"]),
16381
- url: string(),
16382
- sha256: string(),
16383
- sizeBytes: number(),
16384
- quantization: string(),
16385
- /** Load-time guidance shown in the picker. */
16386
- minRamBytes: number(),
16387
- contextSizeDefault: number().int(),
16388
- /** Vision models: companion projector file. */
16389
- mmprojUrl: string().optional()
16390
- });
16391
- var LlmRuntimeNodeSchema = object({
16392
- nodeId: string(),
16393
- reachable: boolean(),
16394
- status: LlmRuntimeStatusSchema.optional(),
16395
- disk: LlmRuntimeDiskUsageSchema.optional(),
16396
- error: string().optional()
16397
- });
16398
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16399
- var ProfileRefInputSchema = object({
16741
+ integrationId: string()
16742
+ }), object({ filters: array(AdoptionFilterSchema) }), { auth: "admin" }), method(ListCandidatesInputSchema.extend({ addonId: string() }), ListCandidatesOutputSchema, { auth: "admin" }), method(object({
16400
16743
  addonId: string(),
16401
- profileId: string()
16402
- });
16403
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16744
+ integrationId: string()
16745
+ }), AdoptionStatusSchema, {
16404
16746
  kind: "mutation",
16405
16747
  auth: "admin"
16406
- }), method(ProfileRefInputSchema, _void(), {
16748
+ }), method(AdoptInputSchema.extend({ addonId: string() }), AdoptResultSchema, {
16407
16749
  kind: "mutation",
16408
16750
  auth: "admin"
16409
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16751
+ }), method(ReleaseInputSchema.extend({ addonId: string() }), _void(), {
16410
16752
  kind: "mutation",
16411
16753
  auth: "admin"
16412
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
16413
- selector: LlmDefaultSelectorSchema,
16414
- profileId: string().nullable()
16415
- }), _void(), {
16754
+ }), method(ResyncInputSchema, ResyncResultSchema, {
16416
16755
  kind: "mutation",
16417
16756
  auth: "admin"
16418
- }), method(object({
16419
- since: number().optional(),
16420
- until: number().optional(),
16421
- consumer: string().optional(),
16422
- profileId: string().optional()
16423
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
16424
- nodeId: string(),
16425
- model: ManagedModelRefSchema
16426
- }), _void(), {
16757
+ }), method(object({}), object({ providers: array(object({
16758
+ addonId: string(),
16759
+ label: string()
16760
+ })).readonly() }), { auth: "admin" }), method(object({}), object({ groups: array(object({
16761
+ addonId: string(),
16762
+ label: string(),
16763
+ candidates: array(DiscoveryCandidateSchema).readonly(),
16764
+ error: string().nullable()
16765
+ })).readonly() }), {
16427
16766
  kind: "mutation",
16428
16767
  auth: "admin"
16429
16768
  }), method(object({
16430
- nodeId: string(),
16431
- file: string()
16432
- }), _void(), {
16769
+ addonId: string(),
16770
+ params: record(string(), unknown()).optional()
16771
+ }), object({ candidates: array(DiscoveryCandidateSchema).readonly() }), {
16433
16772
  kind: "mutation",
16434
16773
  auth: "admin"
16435
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16774
+ }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
16775
+ deviceId: number(),
16776
+ key: string(),
16777
+ value: unknown()
16778
+ }), FieldProbeResultSchema, {
16436
16779
  kind: "mutation",
16437
16780
  auth: "admin"
16438
- }), method(ProfileRefInputSchema, _void(), {
16781
+ }), method(object({
16782
+ deviceId: number(),
16783
+ caps: array(string()).readonly().optional()
16784
+ }), record(string(), unknown().nullable()));
16785
+ method(object({ deviceId: number() }), record(string(), record(string(), unknown()))), method(object({
16786
+ deviceId: number(),
16787
+ capName: string()
16788
+ }), record(string(), unknown()).nullable()), method(object({}), record(string(), record(string(), record(string(), unknown())))), method(object({
16789
+ deviceId: number(),
16790
+ capName: string(),
16791
+ slice: record(string(), unknown())
16792
+ }), _void(), { kind: "mutation" }), object({
16793
+ deviceId: number(),
16794
+ capName: string(),
16795
+ slice: record(string(), unknown())
16796
+ });
16797
+ /**
16798
+ * Embedding output. `embedding` is wire-encoded as `number[]` so the
16799
+ * Zod-validated tRPC surface round-trips cleanly; consumers that need a
16800
+ * `Float32Array` can wrap it on the way out (in-process, no marshalling
16801
+ * is involved). `inferenceMs` mirrors the runtime field used by the
16802
+ * post-analysis enrichment-engine.
16803
+ */
16804
+ var EmbeddingResultSchema = object({
16805
+ embedding: array(number()),
16806
+ inferenceMs: number()
16807
+ });
16808
+ var EmbeddingInfoSchema = object({
16809
+ modelId: string(),
16810
+ embeddingDim: number(),
16811
+ ready: boolean()
16812
+ });
16813
+ method(object({
16814
+ crop: _instanceof(Uint8Array),
16815
+ width: number(),
16816
+ height: number()
16817
+ }), EmbeddingResultSchema), method(object({ text: string() }), EmbeddingResultSchema), method(_void(), EmbeddingInfoSchema);
16818
+ /**
16819
+ * filesystem-browse — per-node capability for browsing the node's local
16820
+ * filesystem, sandboxed to operator-configured allowed roots. Used by the
16821
+ * admin "Add filesystem location" flow to pick a node + path. `mode:'per-node'`
16822
+ * (one provider per node); the hub calls it with `{nodeId}` so the codegen
16823
+ * routes to that exact node (default `nodeIdMode:'routing'`).
16824
+ */
16825
+ var DirEntrySchema = object({
16826
+ name: string(),
16827
+ path: string()
16828
+ });
16829
+ var BrowseResultSchema = object({
16830
+ path: string(),
16831
+ entries: array(DirEntrySchema).readonly(),
16832
+ freeBytes: number(),
16833
+ totalBytes: number()
16834
+ });
16835
+ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({ path: string() }), BrowseResultSchema, { auth: "admin" }), method(object({ path: string() }), object({ path: string() }), {
16439
16836
  kind: "mutation",
16440
16837
  auth: "admin"
16441
16838
  });
16442
- var LogLevelSchema = _enum([
16443
- "debug",
16444
- "info",
16445
- "warn",
16446
- "error"
16839
+ /**
16840
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
16841
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
16842
+ * caps stay wire-compatible without a circular cap→cap import.
16843
+ *
16844
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
16845
+ * every transport tier structurally, and failed calls still write usage rows.
16846
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
16847
+ */
16848
+ var LlmUsageSchema = object({
16849
+ inputTokens: number(),
16850
+ outputTokens: number()
16851
+ });
16852
+ var LlmErrorCodeSchema = _enum([
16853
+ "timeout",
16854
+ "rate-limited",
16855
+ "auth",
16856
+ "refusal",
16857
+ "bad-request",
16858
+ "unavailable",
16859
+ "no-profile",
16860
+ "budget-exceeded",
16861
+ "adapter-error"
16447
16862
  ]);
16448
- var LogEntrySchema = object({
16449
- timestamp: date(),
16450
- level: LogLevelSchema,
16451
- scope: array(string()),
16863
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
16864
+ ok: literal(true),
16865
+ text: string(),
16866
+ model: string(),
16867
+ usage: LlmUsageSchema,
16868
+ truncated: boolean(),
16869
+ latencyMs: number()
16870
+ }), object({
16871
+ ok: literal(false),
16872
+ code: LlmErrorCodeSchema,
16452
16873
  message: string(),
16453
- meta: record(string(), unknown()).optional(),
16454
- tags: record(string(), string()).optional()
16455
- });
16456
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
16457
- scope: array(string()).optional(),
16458
- level: LogLevelSchema.optional(),
16459
- since: date().optional(),
16460
- until: date().optional(),
16461
- limit: number().optional(),
16462
- tags: record(string(), string()).optional()
16463
- }), array(LogEntrySchema).readonly());
16874
+ retryAfterMs: number().optional()
16875
+ })]);
16464
16876
  /**
16465
- * `login-method` collection cap through which auth addons contribute
16466
- * their pre-auth login surfaces to the login page. This is the SINGLE,
16467
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
16468
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
16469
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
16470
- * procedure aggregates them for the unauthenticated login page.
16471
- *
16472
- * A contribution is a discriminated union on `kind`:
16473
- *
16474
- * - `redirect` a declarative button. The login page renders a generic
16475
- * button that navigates to `startUrl` (an addon-owned HTTP route).
16476
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
16477
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
16478
- * login page needs NO change.
16479
- *
16480
- * - `widget` — a Module-Federation widget the login page mounts (via
16481
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
16482
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
16483
- * mechanism kept for future use; no shipped addon uses it on the login
16484
- * page (the passkey ceremony below runs natively in the shell instead).
16485
- *
16486
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
16487
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
16488
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
16489
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
16490
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
16491
- * fetching any remote code pre-auth. Contribution stays unconditional
16492
- * enrollment state is never leaked pre-auth; visibility is a shell
16493
- * decision.
16494
- *
16495
- * Every contribution carries a `stage`:
16496
- * - `primary` — shown on the first credentials screen (OIDC /
16497
- * magic-link buttons; a future usernameless passkey).
16498
- * - `second-factor` — shown AFTER the password leg, gated on the
16499
- * returned `factors` (passkey-as-2FA today).
16877
+ * `Uint8Array` is the sanctioned binary convention superjson + the UDS
16878
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
16879
+ * notification-output.cap.ts:27-31 precedents).
16880
+ */
16881
+ var LlmImageSchema = object({
16882
+ bytes: _instanceof(Uint8Array),
16883
+ mimeType: string()
16884
+ });
16885
+ var LlmGenerateBaseInputSchema = object({
16886
+ /** Collection routing (the notification-output posture). */
16887
+ addonId: string().optional(),
16888
+ /** Explicit profile; else the resolution chain (spec §3). */
16889
+ profileId: string().optional(),
16890
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
16891
+ consumer: string(),
16892
+ system: string().optional(),
16893
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
16894
+ prompt: string(),
16895
+ /** Structured output adapter-mapped (response_format / forced tool / responseSchema). */
16896
+ jsonSchema: record(string(), unknown()).optional(),
16897
+ /** Per-call override of the profile default. */
16898
+ maxTokens: number().int().positive().optional(),
16899
+ temperature: number().optional()
16900
+ });
16901
+ /**
16902
+ * `llm-runtime` node-side managed llama.cpp executor (spec §4). Registered
16903
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
16904
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` normal
16905
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
16906
+ * this only through the `llm` cap's methods.
16500
16907
  *
16501
- * `mount: skip` the cap is read server-side by the core auth router
16502
- * (`registry.getCollection('login-method')`), never mounted as its own
16503
- * tRPC router.
16908
+ * One running llama-server child per node in v1 (models are RAM-heavy).
16909
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
16910
+ * watchdog — operator decision #3).
16504
16911
  */
16505
- /** When a login method renders in the two-phase login flow. */
16506
- var LoginStageEnum = _enum(["primary", "second-factor"]);
16507
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
16508
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
16912
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
16509
16913
  object({
16510
- kind: literal("redirect"),
16511
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
16512
- id: string(),
16513
- /** Operator-facing button label. */
16514
- label: string(),
16515
- /** lucide-react icon name. */
16516
- icon: string().optional(),
16517
- /** Addon-owned HTTP route the button navigates to (GET). */
16518
- startUrl: string(),
16519
- stage: LoginStageEnum
16914
+ kind: literal("catalog"),
16915
+ catalogId: string()
16520
16916
  }),
16521
16917
  object({
16522
- kind: literal("widget"),
16523
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
16524
- id: string(),
16525
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
16526
- addonId: string(),
16527
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
16528
- bundle: string(),
16529
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
16530
- remote: WidgetRemoteSchema,
16531
- stage: LoginStageEnum
16918
+ kind: literal("url"),
16919
+ url: string(),
16920
+ sha256: string().optional()
16532
16921
  }),
16533
16922
  object({
16534
- kind: literal("passkey"),
16535
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
16536
- id: string(),
16537
- /** Operator-facing button label. */
16538
- label: string(),
16539
- stage: LoginStageEnum,
16540
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
16541
- rpId: string(),
16542
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
16543
- origin: string().nullable()
16923
+ kind: literal("path"),
16924
+ path: string()
16544
16925
  })
16545
16926
  ]);
16546
- method(_void(), array(LoginMethodContributionSchema).readonly());
16547
- var CpuBreakdownSchema = object({
16548
- total: number(),
16549
- user: number(),
16550
- system: number(),
16551
- irq: number(),
16552
- nice: number(),
16553
- loadAvg: tuple([
16554
- number(),
16555
- number(),
16556
- number()
16557
- ]),
16558
- cores: number()
16559
- });
16560
- var MemoryInfoSchema = object({
16561
- percent: number(),
16562
- totalBytes: number(),
16563
- usedBytes: number(),
16564
- availableBytes: number(),
16565
- swapUsedBytes: number(),
16566
- swapTotalBytes: number()
16567
- });
16568
- var DiskIoSnapshotSchema = object({
16569
- readBytes: number(),
16570
- writeBytes: number(),
16571
- readOps: number(),
16572
- writeOps: number(),
16573
- timestampMs: number()
16574
- });
16575
- var NetworkIoSnapshotSchema = object({
16576
- rxBytes: number(),
16577
- txBytes: number(),
16578
- rxPackets: number(),
16579
- txPackets: number(),
16580
- rxErrors: number(),
16581
- txErrors: number(),
16582
- timestampMs: number()
16583
- });
16584
- var MetricsGpuInfoSchema = object({
16585
- utilization: number(),
16586
- model: string(),
16587
- memoryUsedBytes: number(),
16588
- memoryTotalBytes: number(),
16589
- temperature: number().nullable()
16590
- });
16591
- var ProcessResourceInfoSchema = object({
16592
- openFds: number(),
16593
- threadCount: number(),
16594
- activeHandles: number(),
16595
- activeRequests: number()
16596
- });
16597
- var PressureAvgsSchema = object({
16598
- avg10: number(),
16599
- avg60: number(),
16600
- avg300: number()
16601
- });
16602
- var PressureInfoSchema = object({
16603
- some: PressureAvgsSchema,
16604
- full: PressureAvgsSchema.nullable()
16605
- });
16606
- var SystemResourceSnapshotSchema = object({
16607
- cpu: CpuBreakdownSchema,
16608
- memory: MemoryInfoSchema,
16609
- gpu: MetricsGpuInfoSchema.nullable(),
16610
- network: NetworkIoSnapshotSchema,
16611
- disk: DiskIoSnapshotSchema,
16612
- pressure: object({
16613
- cpu: PressureInfoSchema.nullable(),
16614
- memory: PressureInfoSchema.nullable(),
16615
- io: PressureInfoSchema.nullable()
16616
- }),
16617
- process: ProcessResourceInfoSchema,
16618
- cpuTemperature: number().nullable(),
16619
- timestampMs: number()
16620
- });
16621
- var DiskSpaceInfoSchema = object({
16622
- path: string(),
16623
- totalBytes: number(),
16624
- usedBytes: number(),
16625
- availableBytes: number(),
16626
- percent: number()
16627
- });
16628
- var PidResourceStatsSchema = object({
16629
- pid: number(),
16630
- cpu: number(),
16631
- memory: number(),
16632
- /**
16633
- * Private (anonymous) resident bytes — the per-process V8 heap + native
16634
- * allocations NOT shared with other processes (Linux RssAnon). This is the
16635
- * "real" per-runner cost; summing it across runners is meaningful, unlike
16636
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
16637
- * Undefined where /proc is unavailable (e.g. macOS).
16638
- */
16639
- privateBytes: number().optional(),
16640
- /**
16641
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
16642
- * code shared copy-on-write across runners. Undefined on macOS.
16643
- */
16644
- sharedBytes: number().optional()
16927
+ var ManagedRuntimeConfigSchema = object({
16928
+ /** WHERE the runtime lives — hub or any agent. */
16929
+ nodeId: string(),
16930
+ /** Closed for v1; 'ollama' is a v2 candidate. */
16931
+ engine: _enum(["llama-cpp"]),
16932
+ model: ManagedModelRefSchema,
16933
+ contextSize: number().int().default(4096),
16934
+ /** 0 = CPU-only. */
16935
+ gpuLayers: number().int().default(0),
16936
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
16937
+ threads: number().int().optional(),
16938
+ /** Concurrent slots. */
16939
+ parallel: number().int().default(1),
16940
+ /** Else lazy: first generate boots it. */
16941
+ autoStart: boolean().default(false),
16942
+ /** 0 = never; frees RAM after quiet periods. */
16943
+ idleStopMinutes: number().int().default(30)
16645
16944
  });
16646
- var AddonInstanceSchema = object({
16647
- addonId: string(),
16945
+ var LlmRuntimeStatusSchema = object({
16946
+ /** Status is ALWAYS node-qualified. */
16648
16947
  nodeId: string(),
16649
- role: _enum(["hub", "worker"]),
16650
- pid: number(),
16651
16948
  state: _enum([
16652
- "starting",
16653
- "running",
16654
- "stopping",
16655
16949
  "stopped",
16656
- "crashed"
16657
- ]),
16658
- uptimeSec: number()
16659
- });
16660
- var NodeProcessSchema = object({
16661
- pid: number(),
16662
- ppid: number(),
16663
- pgid: number(),
16664
- classification: _enum([
16665
- "root",
16666
- "managed",
16667
- "system",
16668
- "ghost"
16950
+ "downloading",
16951
+ "starting",
16952
+ "ready",
16953
+ "crashed",
16954
+ "failed"
16669
16955
  ]),
16670
- /** `$process` addon binding when `managed`, else null. */
16671
- addonId: string().nullable(),
16672
- /** Kernel-reported nodeId when the process is a known agent/worker. */
16673
- nodeId: string().nullable(),
16674
- /** Truncated command line. */
16675
- command: string(),
16676
- cpuPercent: number(),
16677
- memoryRssBytes: number(),
16678
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
16679
- uptimeSec: number(),
16680
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
16681
- orphaned: boolean()
16682
- });
16683
- var KillProcessInputSchema = object({
16684
- pid: number(),
16685
- /** Force = SIGKILL. Default is SIGTERM. */
16686
- force: boolean().optional()
16687
- });
16688
- var KillProcessResultSchema = object({
16689
- success: boolean(),
16690
- reason: string().optional(),
16691
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
16692
- });
16693
- var DumpHeapSnapshotInputSchema = object({
16694
- /** The addon whose runner should dump a heap snapshot. */
16695
- addonId: string() });
16696
- var DumpHeapSnapshotResultSchema = object({
16697
- success: boolean(),
16698
- /** Path of the written .heapsnapshot inside the runner's container/host. */
16699
- path: string().optional(),
16700
- /** Process pid that was signalled. */
16701
16956
  pid: number().optional(),
16702
- reason: string().optional()
16957
+ port: number().optional(),
16958
+ modelPath: string().optional(),
16959
+ modelId: string().optional(),
16960
+ downloadProgress: number().min(0).max(1).optional(),
16961
+ lastError: string().optional(),
16962
+ crashesInWindow: number(),
16963
+ /** Child RSS (sampled best-effort). */
16964
+ memoryBytes: number().optional(),
16965
+ vramBytes: number().optional()
16703
16966
  });
16704
- var SystemMetricsSchema = object({
16705
- cpuPercent: number(),
16706
- memoryPercent: number(),
16707
- memoryUsedMB: number(),
16708
- memoryTotalMB: number(),
16709
- diskPercent: number().optional(),
16710
- temperature: number().optional(),
16711
- gpuPercent: number().optional(),
16712
- gpuMemoryPercent: number().optional()
16967
+ var LlmNodeModelSchema = object({
16968
+ file: string(),
16969
+ sizeBytes: number(),
16970
+ catalogId: string().optional(),
16971
+ installedAt: number().optional()
16713
16972
  });
16714
- 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, {
16973
+ var LlmRuntimeDiskUsageSchema = object({
16974
+ nodeId: string(),
16975
+ modelsBytes: number(),
16976
+ freeBytes: number().optional()
16977
+ });
16978
+ method(LlmGenerateBaseInputSchema.extend({
16979
+ images: array(LlmImageSchema).optional(),
16980
+ runtime: ManagedRuntimeConfigSchema,
16981
+ /** The managed profile's timeout, threaded by the hub provider. */
16982
+ timeoutMs: number().int().positive().optional()
16983
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
16715
16984
  kind: "mutation",
16716
16985
  auth: "admin"
16717
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
16986
+ }), method(object({}), _void(), {
16718
16987
  kind: "mutation",
16719
16988
  auth: "admin"
16720
- });
16721
- method(object({
16722
- sourceUrl: string(),
16723
- metadata: ModelConvertMetadataSchema,
16724
- targets: array(ConvertTargetSchema).min(1).readonly(),
16725
- calibrationRef: string().optional(),
16726
- sessionId: string().optional()
16727
- }), ConvertResultSchema, {
16989
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
16728
16990
  kind: "mutation",
16729
- auth: "admin",
16730
- timeoutMs: 6e5
16731
- });
16732
- method(object({
16733
- nodeId: string(),
16734
- modelId: string(),
16735
- format: _enum(MODEL_FORMATS),
16736
- entry: ModelCatalogEntrySchema
16737
- }), object({
16738
- ok: boolean(),
16739
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
16740
- sha256: string(),
16741
- bytes: number(),
16742
- /** The target node's modelsDir the artifact landed in. */
16743
- path: string()
16744
- }), {
16991
+ auth: "admin"
16992
+ }), method(object({ file: string() }), _void(), {
16745
16993
  kind: "mutation",
16746
16994
  auth: "admin"
16747
- });
16748
- /**
16749
- * `mqtt-broker` — broker-registry cap.
16750
- *
16751
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
16752
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
16753
- * and (b) the connection details a consumer addon needs to spin up
16754
- * its OWN `mqtt.js` client.
16755
- *
16756
- * Why: pub/sub routing over the system event-bus loses fidelity
16757
- * (callback shape, QoS guarantees, will/retain semantics) and adds
16758
- * refcount bookkeeping that addons would rather own themselves. The
16759
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
16760
- * features anyway — give it the connection config, get out of the way.
16761
- *
16762
- * Consumer flow:
16763
- * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
16764
- * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
16765
- * client.subscribe('zigbee2mqtt/+')
16766
- *
16767
- * Collection mode: multiple brokers (e.g. one local mosquitto + one
16768
- * cloud bridge). The "embedded" entry (when present) is just another
16769
- * broker in the registry — its lifecycle is owned by the addon that
16770
- * spawned it.
16771
- */
16772
- var BrokerKindSchema = _enum(["external", "embedded"]);
16995
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
16773
16996
  /**
16774
- * Broker live-probe status.
16997
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
16998
+ * methods concat-fan across providers; single-row methods route to ONE
16999
+ * provider by the `addonId` in the call input (the notification-output
17000
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
17001
+ * (hub-placed); the cap stays open for future providers.
16775
17002
  *
16776
- * - `connected` last probe completed a clean CONNACK
16777
- * - `disconnected` — no probe has run yet (cold cache)
16778
- * - `auth-failed` CONNACK refused with auth error (RC 4 / 5)
16779
- * - `unreachable` — TCP connect timed out / refused
16780
- * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
17003
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
17004
+ * `apiKey` is a password field providers REDACT it on read and merge on
17005
+ * write; a stored key NEVER round-trips to a client.
16781
17006
  */
16782
- var BrokerStatusSchema$1 = _enum([
16783
- "connected",
16784
- "disconnected",
16785
- "auth-failed",
16786
- "unreachable",
16787
- "tls-error"
17007
+ var LlmProfileKindSchema = _enum([
17008
+ "openai-compatible",
17009
+ "openai",
17010
+ "anthropic",
17011
+ "google",
17012
+ "managed-local"
16788
17013
  ]);
16789
- var BrokerInfoSchema = object({
17014
+ var LlmProfileSchema = object({
16790
17015
  id: string(),
16791
17016
  name: string(),
16792
- url: string(),
16793
- kind: BrokerKindSchema,
16794
- status: BrokerStatusSchema$1,
16795
- latencyMs: number().nullable(),
16796
- error: string().optional(),
16797
- /** Embedded brokers only: number of MQTT clients currently connected. */
16798
- connectedClients: number().int().nonnegative().optional(),
16799
- /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
16800
- lastCheckedAt: number().optional()
17017
+ kind: LlmProfileKindSchema,
17018
+ /** Stamped by the provider — keeps the fanned catalog routable. */
17019
+ addonId: string(),
17020
+ enabled: boolean(),
17021
+ /** Vendor model id, or the managed runtime's loaded model. */
17022
+ model: string(),
17023
+ /** Required for openai-compatible; override for cloud kinds. */
17024
+ baseUrl: string().optional(),
17025
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
17026
+ apiKey: string().optional(),
17027
+ supportsVision: boolean(),
17028
+ temperature: number().min(0).max(2).optional(),
17029
+ maxTokens: number().int().positive().optional(),
17030
+ timeoutMs: number().int().positive().default(6e4),
17031
+ extraHeaders: record(string(), string()).optional(),
17032
+ /** kind === 'managed-local' only (spec §4). */
17033
+ runtime: ManagedRuntimeConfigSchema.optional()
16801
17034
  });
16802
- /**
16803
- * Connection details — what a consumer needs to call
16804
- * `mqtt.connect(url, options)`. We split URL + credentials so the
16805
- * consumer can pass them as `mqtt.connect(url, { username, password })`
16806
- * instead of stuffing creds into the URL (which leaks them into logs).
16807
- */
16808
- var BrokerConnectionDetailsSchema = object({
16809
- url: string(),
16810
- username: string().optional(),
16811
- password: string().optional(),
16812
- /**
16813
- * Suggested prefix for `clientId`. Each consumer should suffix this
16814
- * with its own discriminator (addon id, instance id) so reconnects
16815
- * don't kick each other off (MQTT spec: clientId must be unique per
16816
- * broker).
16817
- */
16818
- clientIdPrefix: string().optional()
17035
+ /** ConfigUISchema tree passed through untyped on the wire (the
17036
+ * notification-output `ConfigSchemaPassthrough` precedent at
17037
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
17038
+ var ConfigSchemaPassthrough$1 = unknown();
17039
+ var LlmProfileKindDescriptorSchema = object({
17040
+ kind: LlmProfileKindSchema,
17041
+ label: string(),
17042
+ icon: string(),
17043
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
17044
+ addonId: string(),
17045
+ configSchema: ConfigSchemaPassthrough$1
16819
17046
  });
16820
- var AddBrokerInputSchema = object({
16821
- name: string().min(1),
16822
- url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
16823
- username: string().optional(),
16824
- password: string().optional(),
16825
- clientIdPrefix: string().optional()
17047
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
17048
+ var LlmDefaultSchema = object({
17049
+ selector: LlmDefaultSelectorSchema,
17050
+ profileId: string()
16826
17051
  });
16827
- var AddBrokerResultSchema = object({ id: string() });
16828
- var IdInputSchema = object({ id: string() });
16829
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
16830
- ok: literal(true),
16831
- latencyMs: number()
16832
- }), object({
16833
- ok: literal(false),
16834
- error: string()
16835
- })]);
16836
- var StartEmbeddedInputSchema = object({
16837
- port: number().int().min(1).max(65535).default(1883),
16838
- /** Allow anonymous connect (no username/password). Default: false. */
16839
- allowAnonymous: boolean().default(false),
16840
- /** Optional shared username/password for clients. */
16841
- username: string().optional(),
16842
- password: string().optional()
17052
+ /** Server-side rollup row getUsage never dumps raw call rows (spec §6). */
17053
+ var LlmUsageRollupSchema = object({
17054
+ day: string(),
17055
+ consumer: string(),
17056
+ profileId: string(),
17057
+ calls: number(),
17058
+ okCalls: number(),
17059
+ errorCalls: number(),
17060
+ inputTokens: number(),
17061
+ outputTokens: number(),
17062
+ avgLatencyMs: number()
16843
17063
  });
16844
- var StartEmbeddedResultSchema = object({
17064
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
17065
+ var ManagedModelCatalogEntrySchema = object({
16845
17066
  id: string(),
16846
- url: string()
16847
- });
16848
- var StatusSchema = object({
16849
- brokerCount: number(),
16850
- embeddedRunning: boolean()
16851
- });
16852
- 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);
16853
- var NetworkEndpointSchema = object({
17067
+ label: string(),
17068
+ family: string(),
17069
+ purpose: _enum(["text", "vision"]),
16854
17070
  url: string(),
16855
- hostname: string(),
16856
- port: number(),
16857
- protocol: _enum(["http", "https"])
17071
+ sha256: string(),
17072
+ sizeBytes: number(),
17073
+ quantization: string(),
17074
+ /** Load-time guidance shown in the picker. */
17075
+ minRamBytes: number(),
17076
+ contextSizeDefault: number().int(),
17077
+ /** Vision models: companion projector file. */
17078
+ mmprojUrl: string().optional()
16858
17079
  });
16859
- var NetworkAccessStatusSchema = object({
16860
- connected: boolean(),
16861
- endpoint: NetworkEndpointSchema.nullable(),
17080
+ var LlmRuntimeNodeSchema = object({
17081
+ nodeId: string(),
17082
+ reachable: boolean(),
17083
+ status: LlmRuntimeStatusSchema.optional(),
17084
+ disk: LlmRuntimeDiskUsageSchema.optional(),
16862
17085
  error: string().optional()
16863
17086
  });
16864
- /**
16865
- * Optional, richer endpoint shape returned by providers that expose
16866
- * MORE than one ingress concurrently (Tailscale Ingress with mixed
16867
- * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
16868
- * the originating provider config (mode + sourcePort) so the
16869
- * orchestrator UI can label rows distinctly. Providers that expose only
16870
- * one endpoint just omit `listEndpoints` from their provider impl.
16871
- */
16872
- var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
16873
- /**
16874
- * Stable id within the provider — typically `<mode>-<sourcePort>` so
16875
- * the orchestrator can dedupe across `listEndpoints` polls.
16876
- */
16877
- id: string(),
16878
- /** Operator-facing label (mirrors `MeshEndpoint.label`). */
16879
- label: string(),
16880
- /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
16881
- mode: string().optional(),
16882
- /** Originating local port the ingress fronts (informational). */
16883
- sourcePort: number().optional()
17087
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
17088
+ var ProfileRefInputSchema = object({
17089
+ addonId: string(),
17090
+ profileId: string()
17091
+ });
17092
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
17093
+ kind: "mutation",
17094
+ auth: "admin"
17095
+ }), method(ProfileRefInputSchema, _void(), {
17096
+ kind: "mutation",
17097
+ auth: "admin"
17098
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
17099
+ kind: "mutation",
17100
+ auth: "admin"
17101
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
17102
+ selector: LlmDefaultSelectorSchema,
17103
+ profileId: string().nullable()
17104
+ }), _void(), {
17105
+ kind: "mutation",
17106
+ auth: "admin"
17107
+ }), method(object({
17108
+ since: number().optional(),
17109
+ until: number().optional(),
17110
+ consumer: string().optional(),
17111
+ profileId: string().optional()
17112
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
17113
+ nodeId: string(),
17114
+ model: ManagedModelRefSchema
17115
+ }), _void(), {
17116
+ kind: "mutation",
17117
+ auth: "admin"
17118
+ }), method(object({
17119
+ nodeId: string(),
17120
+ file: string()
17121
+ }), _void(), {
17122
+ kind: "mutation",
17123
+ auth: "admin"
17124
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
17125
+ kind: "mutation",
17126
+ auth: "admin"
17127
+ }), method(ProfileRefInputSchema, _void(), {
17128
+ kind: "mutation",
17129
+ auth: "admin"
17130
+ });
17131
+ var LogLevelSchema = _enum([
17132
+ "debug",
17133
+ "info",
17134
+ "warn",
17135
+ "error"
17136
+ ]);
17137
+ var LogEntrySchema = object({
17138
+ timestamp: date(),
17139
+ level: LogLevelSchema,
17140
+ scope: array(string()),
17141
+ message: string(),
17142
+ meta: record(string(), unknown()).optional(),
17143
+ tags: record(string(), string()).optional()
16884
17144
  });
16885
- method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
17145
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
17146
+ scope: array(string()).optional(),
17147
+ level: LogLevelSchema.optional(),
17148
+ since: date().optional(),
17149
+ until: date().optional(),
17150
+ limit: number().optional(),
17151
+ tags: record(string(), string()).optional()
17152
+ }), array(LogEntrySchema).readonly());
16886
17153
  /**
16887
- * notification-outputcanonical, capability-gated notification delivery.
17154
+ * `login-method`collection cap through which auth addons contribute
17155
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
17156
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
17157
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
17158
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
17159
+ * procedure aggregates them for the unauthenticated login page.
16888
17160
  *
16889
- * Apprise-derived model (see
16890
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
16891
- * callers emit ONE canonical `Notification`; each provider declares a
16892
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
16893
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
16894
- * message to what the kind supports — callers never special-case a service.
17161
+ * A contribution is a discriminated union on `kind`:
16895
17162
  *
16896
- * DESIGN DECISIONS (locked):
16897
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
16898
- * `setTargetEnabled`), each provider persisting via the `settings-store`
16899
- * cap. Rationale: the admin UI needs one uniform surface across the
16900
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
16901
- * alternative would fork the UI per addon and cannot host the
16902
- * discovery→adopt flow.
16903
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
16904
- * the generated cap-mount auto-`concatCollection`-fans them across every
16905
- * registered provider (notifiers addon + HA addon) so one catalog is
16906
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
16907
- * `addonId` the generated collection router extracts from the call input.
16908
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
16909
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
16910
- * `storage` / `storage-provider` / `recording` caps over the same path. No
16911
- * base64 fallback needed.
17163
+ * - `redirect` a declarative button. The login page renders a generic
17164
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
17165
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
17166
+ * ZERO shell-side JS. A future SSO addon plugs in the same way the
17167
+ * login page needs NO change.
16912
17168
  *
16913
- * TODO (deferred, closed-set change separate decision): add
16914
- * `providerKind: 'notify'` so notification providers surface on the unified
16915
- * admin "Integrations" page.
16916
- */
16917
- /**
16918
- * Zentik-derived typed-media enum — the superset across every kind. Each
16919
- * adapter picks what it supports and the degrade engine filters the rest.
16920
- */
16921
- var AttachmentMediaTypeSchema = _enum([
16922
- "image",
16923
- "video",
16924
- "gif",
16925
- "audio",
16926
- "icon"
16927
- ]);
16928
- /**
16929
- * A single attachment. Exactly one of `url` (remote source, most adapters
16930
- * prefer this) or `bytes` (inline source; required for Pushover-style
16931
- * bytes-only kinds) MUST be present the degrade engine expresses a
16932
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
17169
+ * - `widget` a Module-Federation widget the login page mounts (via
17170
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
17171
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
17172
+ * mechanism kept for future use; no shipped addon uses it on the login
17173
+ * page (the passkey ceremony below runs natively in the shell instead).
17174
+ *
17175
+ * - `passkey` a declarative WebAuthn ceremony the shell renders
17176
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
17177
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
17178
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
17179
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
17180
+ * fetching any remote code pre-auth. Contribution stays unconditional —
17181
+ * enrollment state is never leaked pre-auth; visibility is a shell
17182
+ * decision.
17183
+ *
17184
+ * Every contribution carries a `stage`:
17185
+ * - `primary` — shown on the first credentials screen (OIDC /
17186
+ * magic-link buttons; a future usernameless passkey).
17187
+ * - `second-factor` — shown AFTER the password leg, gated on the
17188
+ * returned `factors` (passkey-as-2FA today).
17189
+ *
17190
+ * `mount: skip` — the cap is read server-side by the core auth router
17191
+ * (`registry.getCollection('login-method')`), never mounted as its own
17192
+ * tRPC router.
16933
17193
  */
16934
- var AttachmentSchema = object({
16935
- mediaType: AttachmentMediaTypeSchema,
16936
- url: string().optional(),
16937
- bytes: _instanceof(Uint8Array).optional(),
16938
- mime: string().optional(),
16939
- name: string().optional()
16940
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
16941
- var NotificationFormatSchema = _enum([
16942
- "text",
16943
- "markdown",
16944
- "html"
17194
+ /** When a login method renders in the two-phase login flow. */
17195
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
17196
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
17197
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
17198
+ object({
17199
+ kind: literal("redirect"),
17200
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
17201
+ id: string(),
17202
+ /** Operator-facing button label. */
17203
+ label: string(),
17204
+ /** lucide-react icon name. */
17205
+ icon: string().optional(),
17206
+ /** Addon-owned HTTP route the button navigates to (GET). */
17207
+ startUrl: string(),
17208
+ stage: LoginStageEnum
17209
+ }),
17210
+ object({
17211
+ kind: literal("widget"),
17212
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
17213
+ id: string(),
17214
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
17215
+ addonId: string(),
17216
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
17217
+ bundle: string(),
17218
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
17219
+ remote: WidgetRemoteSchema,
17220
+ stage: LoginStageEnum
17221
+ }),
17222
+ object({
17223
+ kind: literal("passkey"),
17224
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
17225
+ id: string(),
17226
+ /** Operator-facing button label. */
17227
+ label: string(),
17228
+ stage: LoginStageEnum,
17229
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
17230
+ rpId: string(),
17231
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
17232
+ origin: string().nullable()
17233
+ })
16945
17234
  ]);
16946
- /** A single tap-through action button. */
16947
- var NotificationActionSchema = object({
16948
- id: string(),
16949
- label: string(),
16950
- url: string().optional()
17235
+ method(_void(), array(LoginMethodContributionSchema).readonly());
17236
+ var CpuBreakdownSchema = object({
17237
+ total: number(),
17238
+ user: number(),
17239
+ system: number(),
17240
+ irq: number(),
17241
+ nice: number(),
17242
+ loadAvg: tuple([
17243
+ number(),
17244
+ number(),
17245
+ number()
17246
+ ]),
17247
+ cores: number()
16951
17248
  });
16952
- /**
16953
- * The canonical notification. `body` is the only hard field (Apprise model).
16954
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
16955
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
16956
- * the adapter maps this ordinal onto its native level. `level?` is an
16957
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
16958
- * `priority` for that one target.
16959
- */
16960
- var NotificationSchema = object({
16961
- body: string(),
16962
- title: string().optional(),
16963
- format: NotificationFormatSchema.default("text"),
16964
- priority: number().int().min(1).max(5).default(3),
16965
- level: string().optional(),
16966
- attachments: array(AttachmentSchema).optional(),
16967
- clickUrl: string().optional(),
16968
- actions: array(NotificationActionSchema).optional(),
16969
- sound: string().optional(),
16970
- ttl: number().optional(),
16971
- tag: string().optional(),
16972
- deviceId: number().optional(),
16973
- eventId: string().optional(),
16974
- metadata: record(string(), unknown()).optional()
17249
+ var MemoryInfoSchema = object({
17250
+ percent: number(),
17251
+ totalBytes: number(),
17252
+ usedBytes: number(),
17253
+ availableBytes: number(),
17254
+ swapUsedBytes: number(),
17255
+ swapTotalBytes: number()
17256
+ });
17257
+ var DiskIoSnapshotSchema = object({
17258
+ readBytes: number(),
17259
+ writeBytes: number(),
17260
+ readOps: number(),
17261
+ writeOps: number(),
17262
+ timestampMs: number()
17263
+ });
17264
+ var NetworkIoSnapshotSchema = object({
17265
+ rxBytes: number(),
17266
+ txBytes: number(),
17267
+ rxPackets: number(),
17268
+ txPackets: number(),
17269
+ rxErrors: number(),
17270
+ txErrors: number(),
17271
+ timestampMs: number()
17272
+ });
17273
+ var MetricsGpuInfoSchema = object({
17274
+ utilization: number(),
17275
+ model: string(),
17276
+ memoryUsedBytes: number(),
17277
+ memoryTotalBytes: number(),
17278
+ temperature: number().nullable()
17279
+ });
17280
+ var ProcessResourceInfoSchema = object({
17281
+ openFds: number(),
17282
+ threadCount: number(),
17283
+ activeHandles: number(),
17284
+ activeRequests: number()
16975
17285
  });
16976
- /** One declared native severity/priority level for a kind. */
16977
- var TargetKindLevelSchema = object({
16978
- id: string(),
16979
- label: string(),
16980
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
16981
- ordinal: number().int().min(1).max(5).nullable(),
16982
- flags: object({
16983
- critical: boolean().optional(),
16984
- silent: boolean().optional(),
16985
- noPush: boolean().optional()
16986
- }).optional(),
16987
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
16988
- requires: array(string()).optional(),
16989
- description: string().optional()
17286
+ var PressureAvgsSchema = object({
17287
+ avg10: number(),
17288
+ avg60: number(),
17289
+ avg300: number()
16990
17290
  });
16991
- /** The full capability block consulted before dispatch. */
16992
- var TargetKindCapsSchema = object({
16993
- attachments: object({
16994
- mediaTypes: array(AttachmentMediaTypeSchema),
16995
- mode: _enum([
16996
- "url",
16997
- "bytes",
16998
- "both"
16999
- ]),
17000
- max: number().int().nonnegative(),
17001
- maxBytes: number().int().positive().optional()
17291
+ var PressureInfoSchema = object({
17292
+ some: PressureAvgsSchema,
17293
+ full: PressureAvgsSchema.nullable()
17294
+ });
17295
+ var SystemResourceSnapshotSchema = object({
17296
+ cpu: CpuBreakdownSchema,
17297
+ memory: MemoryInfoSchema,
17298
+ gpu: MetricsGpuInfoSchema.nullable(),
17299
+ network: NetworkIoSnapshotSchema,
17300
+ disk: DiskIoSnapshotSchema,
17301
+ pressure: object({
17302
+ cpu: PressureInfoSchema.nullable(),
17303
+ memory: PressureInfoSchema.nullable(),
17304
+ io: PressureInfoSchema.nullable()
17002
17305
  }),
17003
- /** Max action buttons (0 = none). */
17004
- actions: number().int().nonnegative(),
17005
- levels: array(TargetKindLevelSchema),
17006
- format: array(NotificationFormatSchema),
17007
- clickUrl: boolean(),
17008
- sound: boolean(),
17009
- ttl: boolean(),
17010
- bodyMaxLen: number().int().positive()
17306
+ process: ProcessResourceInfoSchema,
17307
+ cpuTemperature: number().nullable(),
17308
+ timestampMs: number()
17011
17309
  });
17012
- /**
17013
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
17014
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
17015
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
17016
- * the union is large and not meant for runtime validation here; the exported
17017
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
17018
- */
17019
- var ConfigSchemaPassthrough = unknown();
17020
- var TargetKindSchema = object({
17021
- kind: string(),
17022
- label: string(),
17023
- icon: string(),
17024
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
17025
- addonId: string(),
17026
- configSchema: ConfigSchemaPassthrough,
17027
- supportsDiscovery: boolean(),
17028
- caps: TargetKindCapsSchema
17310
+ var DiskSpaceInfoSchema = object({
17311
+ path: string(),
17312
+ totalBytes: number(),
17313
+ usedBytes: number(),
17314
+ availableBytes: number(),
17315
+ percent: number()
17029
17316
  });
17030
- /**
17031
- * A persisted target. `config` holds secrets; providers REDACT secret fields
17032
- * (return a presence marker only) when serving `listTargets` — never
17033
- * round-trip a stored secret to the UI.
17034
- */
17035
- var TargetSchema = object({
17036
- id: string(),
17037
- name: string(),
17038
- kind: string(),
17317
+ var PidResourceStatsSchema = object({
17318
+ pid: number(),
17319
+ cpu: number(),
17320
+ memory: number(),
17321
+ /**
17322
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
17323
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
17324
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
17325
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
17326
+ * Undefined where /proc is unavailable (e.g. macOS).
17327
+ */
17328
+ privateBytes: number().optional(),
17329
+ /**
17330
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
17331
+ * code shared copy-on-write across runners. Undefined on macOS.
17332
+ */
17333
+ sharedBytes: number().optional()
17334
+ });
17335
+ var AddonInstanceSchema = object({
17039
17336
  addonId: string(),
17040
- enabled: boolean(),
17041
- config: record(string(), unknown())
17337
+ nodeId: string(),
17338
+ role: _enum(["hub", "worker"]),
17339
+ pid: number(),
17340
+ state: _enum([
17341
+ "starting",
17342
+ "running",
17343
+ "stopping",
17344
+ "stopped",
17345
+ "crashed"
17346
+ ]),
17347
+ uptimeSec: number()
17042
17348
  });
17043
- /** A discovery-surfaced candidate (config is partial + non-secret). */
17044
- var DiscoveredTargetSchema = object({
17045
- kind: string(),
17046
- suggestedName: string(),
17047
- config: record(string(), unknown())
17349
+ var NodeProcessSchema = object({
17350
+ pid: number(),
17351
+ ppid: number(),
17352
+ pgid: number(),
17353
+ classification: _enum([
17354
+ "root",
17355
+ "managed",
17356
+ "system",
17357
+ "ghost"
17358
+ ]),
17359
+ /** `$process` addon binding when `managed`, else null. */
17360
+ addonId: string().nullable(),
17361
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
17362
+ nodeId: string().nullable(),
17363
+ /** Truncated command line. */
17364
+ command: string(),
17365
+ cpuPercent: number(),
17366
+ memoryRssBytes: number(),
17367
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
17368
+ uptimeSec: number(),
17369
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
17370
+ orphaned: boolean()
17048
17371
  });
17049
- /** The degrade engine's report — what was resolved / dropped / degraded. */
17050
- var RenderedAsSchema = object({
17051
- level: string(),
17052
- format: NotificationFormatSchema,
17053
- attachmentsSent: number().int().nonnegative(),
17054
- actionsSent: number().int().nonnegative(),
17055
- truncated: boolean(),
17056
- dropped: array(string())
17372
+ var KillProcessInputSchema = object({
17373
+ pid: number(),
17374
+ /** Force = SIGKILL. Default is SIGTERM. */
17375
+ force: boolean().optional()
17057
17376
  });
17058
- var SendResultSchema = object({
17377
+ var KillProcessResultSchema = object({
17059
17378
  success: boolean(),
17060
- error: string().optional(),
17061
- renderedAs: RenderedAsSchema.optional()
17379
+ reason: string().optional(),
17380
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
17381
+ });
17382
+ var DumpHeapSnapshotInputSchema = object({
17383
+ /** The addon whose runner should dump a heap snapshot. */
17384
+ addonId: string() });
17385
+ var DumpHeapSnapshotResultSchema = object({
17386
+ success: boolean(),
17387
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
17388
+ path: string().optional(),
17389
+ /** Process pid that was signalled. */
17390
+ pid: number().optional(),
17391
+ reason: string().optional()
17392
+ });
17393
+ var SystemMetricsSchema = object({
17394
+ cpuPercent: number(),
17395
+ memoryPercent: number(),
17396
+ memoryUsedMB: number(),
17397
+ memoryTotalMB: number(),
17398
+ diskPercent: number().optional(),
17399
+ temperature: number().optional(),
17400
+ gpuPercent: number().optional(),
17401
+ gpuMemoryPercent: number().optional()
17402
+ });
17403
+ 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, {
17404
+ kind: "mutation",
17405
+ auth: "admin"
17406
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
17407
+ kind: "mutation",
17408
+ auth: "admin"
17409
+ });
17410
+ method(object({
17411
+ sourceUrl: string(),
17412
+ metadata: ModelConvertMetadataSchema,
17413
+ targets: array(ConvertTargetSchema).min(1).readonly(),
17414
+ calibrationRef: string().optional(),
17415
+ sessionId: string().optional()
17416
+ }), ConvertResultSchema, {
17417
+ kind: "mutation",
17418
+ auth: "admin",
17419
+ timeoutMs: 6e5
17420
+ });
17421
+ method(object({
17422
+ nodeId: string(),
17423
+ modelId: string(),
17424
+ format: _enum(MODEL_FORMATS),
17425
+ entry: ModelCatalogEntrySchema
17426
+ }), object({
17427
+ ok: boolean(),
17428
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
17429
+ sha256: string(),
17430
+ bytes: number(),
17431
+ /** The target node's modelsDir the artifact landed in. */
17432
+ path: string()
17433
+ }), {
17434
+ kind: "mutation",
17435
+ auth: "admin"
17062
17436
  });
17063
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
17064
- var TestResultSchema = SendResultSchema;
17065
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
17066
- kind: string(),
17067
- config: record(string(), unknown()).optional()
17068
- }), array(DiscoveredTargetSchema)), method(object({
17069
- targetId: string(),
17070
- notification: NotificationSchema
17071
- }), SendResultSchema, { kind: "mutation" }), method(object({
17072
- targetId: string(),
17073
- sample: NotificationSchema.optional()
17074
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
17075
- targetId: string(),
17076
- enabled: boolean()
17077
- }), _void(), { kind: "mutation" });
17078
17437
  /**
17079
- * notification-rulesthe Notification Center rule surface (P1 core).
17080
- *
17081
- * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
17082
- * (operator decisions D-1/D-2/D-3 are binding):
17438
+ * `mqtt-broker`broker-registry cap.
17083
17439
  *
17084
- * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
17085
- * `notification-center` module), hooked on the durable persistence
17086
- * moments (object-event insert, TrackCloser.closeExpired) with a
17087
- * persisted outbox + retry — never the lossy telemetry bus (D8).
17088
- * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
17089
- * FIRST persisted detection matching the conditions (per-track dedup,
17090
- * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
17091
- * `delivery: 'track-end'` evaluates the finalized track record at close.
17092
- * - DISPATCH stays behind `notification-output` (rules reference targets
17093
- * by id; per-backend params are a passthrough blob capped by the
17094
- * target kind's own caps/degrade engine).
17440
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
17441
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
17442
+ * and (b) the connection details a consumer addon needs to spin up
17443
+ * its OWN `mqtt.js` client.
17095
17444
  *
17096
- * P1 scope: admin-authored rules only (`createdBy` stamped from the
17097
- * server-injected caller identity the first `caller: 'required'`
17098
- * adopter). The P1 condition subset is: devices, classes(+exclude),
17099
- * minConfidence, admin zones (any/all + exclude), weekly schedule
17100
- * windows, and the optional label/identity/plate matchers. User rules,
17101
- * private zones, per-recipient fan-out and the wider condition table are
17102
- * P2+ (see spec §7).
17445
+ * Why: pub/sub routing over the system event-bus loses fidelity
17446
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
17447
+ * refcount bookkeeping that addons would rather own themselves. The
17448
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
17449
+ * features anyway — give it the connection config, get out of the way.
17103
17450
  *
17104
- * All schemas here are the single source of truth — `NcRule` etc. are
17105
- * `z.infer` exports; no duplicate interfaces (the advanced-notifier
17106
- * schema/interface drift is explicitly not repeated).
17451
+ * Consumer flow:
17452
+ * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
17453
+ * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
17454
+ * client.subscribe('zigbee2mqtt/+')
17455
+ *
17456
+ * Collection mode: multiple brokers (e.g. one local mosquitto + one
17457
+ * cloud bridge). The "embedded" entry (when present) is just another
17458
+ * broker in the registry — its lifecycle is owned by the addon that
17459
+ * spawned it.
17107
17460
  */
17461
+ var BrokerKindSchema = _enum(["external", "embedded"]);
17108
17462
  /**
17109
- * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
17110
- * The value maps 1:1 onto the evaluated record kind:
17111
- * - `immediate` ↔ object-event persist (lowest-latency detection burst)
17112
- * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
17113
- * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
17114
- * change of a LINKED device, one row per linked camera)
17115
- * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
17116
- * delivery / pick-up)
17463
+ * Broker live-probe status.
17117
17464
  *
17118
- * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
17119
- * `package-event` are pure trigger kinds (no urgency dimension). Extending
17120
- * this one field keeps the schema additive a rule still declares exactly
17121
- * one trigger.
17465
+ * - `connected` last probe completed a clean CONNACK
17466
+ * - `disconnected` no probe has run yet (cold cache)
17467
+ * - `auth-failed` CONNACK refused with auth error (RC 4 / 5)
17468
+ * - `unreachable` — TCP connect timed out / refused
17469
+ * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
17122
17470
  */
17123
- var NcDeliverySchema = _enum([
17124
- "immediate",
17125
- "track-end",
17126
- "device-event",
17127
- "package-event"
17471
+ var BrokerStatusSchema$1 = _enum([
17472
+ "connected",
17473
+ "disconnected",
17474
+ "auth-failed",
17475
+ "unreachable",
17476
+ "tls-error"
17128
17477
  ]);
17129
- /** Weekly schedule — OR of windows; absence on the rule = always active. */
17130
- var NcScheduleSchema = object({
17131
- windows: array(object({
17132
- /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
17133
- days: array(number().int().min(0).max(6)).min(1),
17134
- startMinute: number().int().min(0).max(1439),
17135
- endMinute: number().int().min(0).max(1439)
17136
- })).min(1),
17137
- /** IANA timezone; default = hub host timezone. */
17138
- timezone: string().optional(),
17139
- /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
17140
- invert: boolean().optional()
17141
- });
17142
- /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
17143
- var NcPlateMatcherSchema = object({
17144
- values: array(string().min(1)).min(1),
17145
- /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
17146
- maxDistance: number().int().min(0).max(3).default(1)
17147
- });
17148
- /**
17149
- * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
17150
- * occupancy edge for a device — optionally narrowed to a single admin
17151
- * `zoneId` and/or object `className`. `op` selects the edge/threshold:
17152
- * - `became-occupied` (default) — count crossed 0 → ≥ `count`
17153
- * - `became-free` — count crossed ≥ `count` → below it
17154
- * - `>=` / `<=` — count is at/over or at/under `count`
17155
- * `sustainSeconds` requires the condition hold continuously that long
17156
- * before firing (debounces flicker; 0 = fire on the first matching edge).
17157
- * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
17158
- * the condition never matches. Confirmed edge-state survives addon restarts
17159
- * (declared SQLite collection, reseeded on boot).
17160
- */
17161
- var NcOccupancyConditionSchema = object({
17162
- /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
17163
- zoneId: string().optional(),
17164
- /** Object class to count; absent = any class. */
17165
- className: string().optional(),
17166
- op: _enum([
17167
- "became-occupied",
17168
- "became-free",
17169
- ">=",
17170
- "<="
17171
- ]).default("became-occupied"),
17172
- count: number().int().min(0).default(1),
17173
- sustainSeconds: number().int().min(0).max(3600).default(15)
17174
- });
17175
- /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
17176
- var NcZoneConditionSchema = object({
17177
- ids: array(string().min(1)).min(1),
17178
- /** Quantifier over `ids` — at least one / every one visited. */
17179
- match: _enum(["any", "all"]).default("any")
17180
- });
17181
- /**
17182
- * The P1 condition set — a flat AND of groups; absent group = pass;
17183
- * membership lists are OR within the list (spec §2.3).
17184
- */
17185
- var NcConditionsSchema = object({
17186
- /** Device scope — absent = all devices. */
17187
- devices: array(number()).optional(),
17188
- /** Detector class names (any overlap with the record's class set). */
17189
- classes: array(string().min(1)).optional(),
17190
- /** Veto classes — any overlap fails the rule. */
17191
- classesExclude: array(string().min(1)).optional(),
17192
- /** Minimum detection confidence 0–1 (fails when the record has none). */
17193
- minConfidence: number().min(0).max(1).optional(),
17194
- /** Admin zone membership over event `zones` / track `zonesVisited`. */
17195
- zones: NcZoneConditionSchema.optional(),
17196
- /** Veto zones — any hit fails the rule. */
17197
- zonesExclude: array(string().min(1)).optional(),
17198
- /**
17199
- * Exact (case-insensitive) match on the record's collapsed `label`
17200
- * (identity name / plate text / subclass).
17201
- */
17202
- labelEquals: array(string().min(1)).optional(),
17203
- /**
17204
- * Identity matcher. P1 boundary: matched against the record's collapsed
17205
- * `label` (the identity display name propagated by the face pipeline) —
17206
- * identity-ID matching rides in P2 when identity ids reach the record.
17207
- */
17208
- identities: array(string().min(1)).optional(),
17209
- /** Fuzzy plate matcher against the record's `label` (plate text). */
17210
- plates: NcPlateMatcherSchema.optional(),
17211
- /**
17212
- * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
17213
- * Same P1 boundary: matched against the record's collapsed `label` (the
17214
- * identity display name). A record with NO label passes (nothing to
17215
- * exclude), unlike the include variant which fails on an absent label.
17216
- */
17217
- identitiesExclude: array(string().min(1)).optional(),
17218
- /**
17219
- * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
17220
- * TRACK-END only: importance is scored at track close, so it does not exist
17221
- * at immediate / object-event evaluation time (see catalog `appliesTo`). At
17222
- * close the value is threaded via the close-time info (the `Track` clone is
17223
- * captured before the DB row is updated, so it would otherwise read stale).
17224
- * Fails when the record carries no importance (never guess quality — the
17225
- * `minConfidence` precedent). MVP cut: a single scalar threshold.
17226
- */
17227
- minImportance: number().min(0).max(1).optional(),
17228
- /**
17229
- * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
17230
- * TRACK-END only: an `immediate` / object-event subject has no closed
17231
- * lifespan, so a dwell condition never matches immediate delivery
17232
- * (documented choice — the object-event record carries no `firstSeen`,
17233
- * so dwell cannot be computed from what the subject actually carries).
17234
- */
17235
- minDwellSeconds: number().min(0).optional(),
17236
- /**
17237
- * Detection provenance filter. `any` (default / absent) matches every
17238
- * source; otherwise the subject's source must equal it. Legacy records
17239
- * with no stamped source are treated as `pipeline`. The union spans both
17240
- * record kinds — object events carry `pipeline` | `onboard`, synthetic
17241
- * tracks carry `sensor`.
17242
- */
17243
- source: _enum([
17244
- "pipeline",
17245
- "onboard",
17246
- "sensor",
17247
- "any"
17248
- ]).optional(),
17249
- /**
17250
- * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
17251
- * detector `minConfidence` (that gates the object-detection score; this
17252
- * gates the recognition/OCR match score). Fails when the subject carries
17253
- * no label-match confidence (never guess). TRACK-END only: the confidence
17254
- * lives on the recognition result and reaches the subject at track close.
17255
- *
17256
- * What it measures precisely (plumbed at track close — the closer threads
17257
- * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
17258
- * `importance`): the BEST recognition match confidence observed for the
17259
- * label the track carries at close — for a face, the peak cosine similarity
17260
- * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
17261
- * for a plate, the peak OCR read score of the best-held plate
17262
- * (`plateText.confidence`). When BOTH a face and a plate were recognized on
17263
- * one track the higher of the two is used. A track that ended with no
17264
- * confident identity/plate match carries no value, so the condition fails
17265
- * closed for it (an un-recognized subject).
17266
- */
17267
- minLabelConfidence: number().min(0).max(1).optional(),
17268
- /**
17269
- * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
17270
- * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
17271
- * against the token carried on the device-event subject (extracted from the
17272
- * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
17273
- * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
17274
- * eventType, so gate those with {@link sensorKinds} instead.
17275
- */
17276
- eventTypeTokens: array(string().min(1)).optional(),
17277
- /**
17278
- * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
17279
- * `contact`, `button`, `device-event`) — matched against the persisted
17280
- * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
17281
- */
17282
- sensorKinds: array(string().min(1)).optional(),
17283
- /**
17284
- * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
17285
- * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
17286
- * when the subject's phase does not match (a subject always carries a phase
17287
- * on the package-event trigger).
17288
- */
17289
- packagePhase: _enum([
17290
- "delivered",
17291
- "picked-up",
17292
- "both"
17293
- ]).optional(),
17294
- /**
17295
- * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
17296
- * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
17297
- * listed polygon (ZoneEngine membership semantics). Evaluated only when
17298
- * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
17299
- */
17300
- customZones: array(MaskPolygonShapeSchema).optional(),
17301
- /**
17302
- * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
17303
- * (optionally zone/class-scoped) occupancy count crosses the configured
17304
- * threshold and holds for `sustainSeconds`. Fail-closed on missing
17305
- * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
17306
- */
17307
- occupancy: NcOccupancyConditionSchema.optional()
17308
- });
17309
- /** One delivery target: a `notification-output` Target ref + passthrough params. */
17310
- var NcRuleTargetSchema = object({
17311
- /** `notification-output` Target id. */
17312
- targetId: string().min(1),
17313
- /**
17314
- * Per-backend passthrough. Recognized keys are mapped onto the canonical
17315
- * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
17316
- * degrade engine drops what the backend can't render.
17317
- */
17318
- params: record(string(), unknown()).optional()
17478
+ var BrokerInfoSchema = object({
17479
+ id: string(),
17480
+ name: string(),
17481
+ url: string(),
17482
+ kind: BrokerKindSchema,
17483
+ status: BrokerStatusSchema$1,
17484
+ latencyMs: number().nullable(),
17485
+ error: string().optional(),
17486
+ /** Embedded brokers only: number of MQTT clients currently connected. */
17487
+ connectedClients: number().int().nonnegative().optional(),
17488
+ /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
17489
+ lastCheckedAt: number().optional()
17319
17490
  });
17320
17491
  /**
17321
- * Media attachment policy (P1 still-image subset).
17322
- * - `best` the best AVAILABLE subject image at dispatch time (D-3).
17323
- * - `best-matching` the media that explains WHY the rule fired: a rule
17324
- * matched on identities attaches the subject's `faceCrop`, one matched on
17325
- * plates attaches the `plateCrop`; a rule with no identity/plate condition
17326
- * (or when the specific crop is missing) degrades to `best`, then
17327
- * `keyFrame`, then no attachment — never delaying the send. The matched
17328
- * condition summary is frozen on the outbox row at enqueue (like the rule
17329
- * name), so the choice never drifts from the record that fired it.
17330
- * - `keyFrame` — the clean scene frame (no subject box).
17331
- * - `none` — no attachment.
17492
+ * Connection details what a consumer needs to call
17493
+ * `mqtt.connect(url, options)`. We split URL + credentials so the
17494
+ * consumer can pass them as `mqtt.connect(url, { username, password })`
17495
+ * instead of stuffing creds into the URL (which leaks them into logs).
17332
17496
  */
17333
- var NcMediaPolicySchema = object({ attach: _enum([
17334
- "best",
17335
- "best-matching",
17336
- "keyFrame",
17337
- "none"
17338
- ]).default("best") });
17339
- /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
17340
- var NcThrottleSchema = object({
17341
- cooldownSec: number().int().min(0).max(86400).default(60),
17342
- /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
17343
- scope: _enum(["rule", "rule-device"]).default("rule-device")
17344
- });
17345
- /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
17346
- var NcRuleInputSchema = object({
17347
- name: string().min(1).max(200),
17348
- enabled: boolean().default(true),
17349
- delivery: NcDeliverySchema,
17350
- conditions: NcConditionsSchema.default({}),
17351
- schedule: NcScheduleSchema.optional(),
17352
- targets: array(NcRuleTargetSchema).min(1),
17353
- media: NcMediaPolicySchema.default({ attach: "best" }),
17354
- throttle: NcThrottleSchema.default({
17355
- cooldownSec: 60,
17356
- scope: "rule-device"
17357
- }),
17358
- /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
17359
- template: object({
17360
- title: string().max(500).optional(),
17361
- body: string().max(2e3).optional()
17362
- }).optional(),
17363
- /** Canonical notification priority ordinal (1..5); per-target overridable. */
17364
- priority: number().int().min(1).max(5).default(3),
17497
+ var BrokerConnectionDetailsSchema = object({
17498
+ url: string(),
17499
+ username: string().optional(),
17500
+ password: string().optional(),
17365
17501
  /**
17366
- * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
17367
- * behaviour, visible to all, read-only in the viewer). Present = personal
17368
- * rule owned by this userId. Server-stamped; never trusted from a client.
17502
+ * Suggested prefix for `clientId`. Each consumer should suffix this
17503
+ * with its own discriminator (addon id, instance id) so reconnects
17504
+ * don't kick each other off (MQTT spec: clientId must be unique per
17505
+ * broker).
17369
17506
  */
17370
- ownerUserId: string().optional()
17507
+ clientIdPrefix: string().optional()
17508
+ });
17509
+ var AddBrokerInputSchema = object({
17510
+ name: string().min(1),
17511
+ url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
17512
+ username: string().optional(),
17513
+ password: string().optional(),
17514
+ clientIdPrefix: string().optional()
17515
+ });
17516
+ var AddBrokerResultSchema = object({ id: string() });
17517
+ var IdInputSchema = object({ id: string() });
17518
+ var TestResultSchema$1 = discriminatedUnion("ok", [object({
17519
+ ok: literal(true),
17520
+ latencyMs: number()
17521
+ }), object({
17522
+ ok: literal(false),
17523
+ error: string()
17524
+ })]);
17525
+ var StartEmbeddedInputSchema = object({
17526
+ port: number().int().min(1).max(65535).default(1883),
17527
+ /** Allow anonymous connect (no username/password). Default: false. */
17528
+ allowAnonymous: boolean().default(false),
17529
+ /** Optional shared username/password for clients. */
17530
+ username: string().optional(),
17531
+ password: string().optional()
17532
+ });
17533
+ var StartEmbeddedResultSchema = object({
17534
+ id: string(),
17535
+ url: string()
17536
+ });
17537
+ var StatusSchema = object({
17538
+ brokerCount: number(),
17539
+ embeddedRunning: boolean()
17540
+ });
17541
+ 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);
17542
+ var NetworkEndpointSchema = object({
17543
+ url: string(),
17544
+ hostname: string(),
17545
+ port: number(),
17546
+ protocol: _enum(["http", "https"])
17547
+ });
17548
+ var NetworkAccessStatusSchema = object({
17549
+ connected: boolean(),
17550
+ endpoint: NetworkEndpointSchema.nullable(),
17551
+ error: string().optional()
17371
17552
  });
17372
17553
  /**
17373
- * Partial patch for `updateRule` any subset of the input fields, plus the
17374
- * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
17375
- * NOT a client-authored input field (it lives on the persisted rule, not the
17376
- * input), so it is added here explicitly to let the store's per-target opt-out
17377
- * toggle round-trip through the shared `update` path. Viewer opt-out mutations
17378
- * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
17379
- * `updateRule` patch.
17554
+ * Optional, richer endpoint shape returned by providers that expose
17555
+ * MORE than one ingress concurrently (Tailscale Ingress with mixed
17556
+ * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
17557
+ * the originating provider config (mode + sourcePort) so the
17558
+ * orchestrator UI can label rows distinctly. Providers that expose only
17559
+ * one endpoint just omit `listEndpoints` from their provider impl.
17380
17560
  */
17381
- var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
17382
- /** A persisted rule. */
17383
- var NcRuleSchema = NcRuleInputSchema.extend({
17384
- id: string(),
17385
- /** userId of the admin who created the rule (server-stamped caller). */
17386
- createdBy: string(),
17387
- createdAt: number(),
17388
- updatedAt: number(),
17561
+ var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
17389
17562
  /**
17390
- * Per-target opt-out set. A targetId here is suppressed for THIS rule at
17391
- * send time. Only a target's OWNER may add/remove its id (server-checked
17392
- * in `nc.setRuleTargetEnabled`). Defaults to empty.
17563
+ * Stable id within the provider typically `<mode>-<sourcePort>` so
17564
+ * the orchestrator can dedupe across `listEndpoints` polls.
17393
17565
  */
17394
- disabledTargetIds: array(string()).default([])
17395
- });
17396
- var NcTestResultSchema = object({
17397
- recordId: string(),
17398
- recordKind: _enum([
17399
- "object-event",
17400
- "track",
17401
- "device-event",
17402
- "package-event"
17403
- ]),
17404
- deviceId: number(),
17405
- timestamp: number(),
17406
- wouldFire: boolean(),
17407
- /** Condition id that failed (first failing group), when `wouldFire` is false. */
17408
- failedCondition: string().optional(),
17409
- className: string().optional(),
17410
- label: string().optional()
17566
+ id: string(),
17567
+ /** Operator-facing label (mirrors `MeshEndpoint.label`). */
17568
+ label: string(),
17569
+ /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
17570
+ mode: string().optional(),
17571
+ /** Originating local port the ingress fronts (informational). */
17572
+ sourcePort: number().optional()
17411
17573
  });
17412
- var NcConditionDescriptorSchema = object({
17413
- /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
17574
+ method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
17575
+ /**
17576
+ * notification-output — canonical, capability-gated notification delivery.
17577
+ *
17578
+ * Apprise-derived model (see
17579
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
17580
+ * callers emit ONE canonical `Notification`; each provider declares a
17581
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
17582
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
17583
+ * message to what the kind supports — callers never special-case a service.
17584
+ *
17585
+ * DESIGN DECISIONS (locked):
17586
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
17587
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
17588
+ * cap. Rationale: the admin UI needs one uniform surface across the
17589
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
17590
+ * alternative would fork the UI per addon and cannot host the
17591
+ * discovery→adopt flow.
17592
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
17593
+ * the generated cap-mount auto-`concatCollection`-fans them across every
17594
+ * registered provider (notifiers addon + HA addon) so one catalog is
17595
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
17596
+ * `addonId` the generated collection router extracts from the call input.
17597
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
17598
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
17599
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
17600
+ * base64 fallback needed.
17601
+ *
17602
+ * TODO (deferred, closed-set change — separate decision): add
17603
+ * `providerKind: 'notify'` so notification providers surface on the unified
17604
+ * admin "Integrations" page.
17605
+ */
17606
+ /**
17607
+ * Zentik-derived typed-media enum — the superset across every kind. Each
17608
+ * adapter picks what it supports and the degrade engine filters the rest.
17609
+ */
17610
+ var AttachmentMediaTypeSchema = _enum([
17611
+ "image",
17612
+ "video",
17613
+ "gif",
17614
+ "audio",
17615
+ "icon"
17616
+ ]);
17617
+ /**
17618
+ * A single attachment. Exactly one of `url` (remote source, most adapters
17619
+ * prefer this) or `bytes` (inline source; required for Pushover-style
17620
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
17621
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
17622
+ */
17623
+ var AttachmentSchema = object({
17624
+ mediaType: AttachmentMediaTypeSchema,
17625
+ url: string().optional(),
17626
+ bytes: _instanceof(Uint8Array).optional(),
17627
+ mime: string().optional(),
17628
+ name: string().optional()
17629
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
17630
+ var NotificationFormatSchema = _enum([
17631
+ "text",
17632
+ "markdown",
17633
+ "html"
17634
+ ]);
17635
+ /** A single tap-through action button. */
17636
+ var NotificationActionSchema = object({
17637
+ id: string(),
17638
+ label: string(),
17639
+ url: string().optional()
17640
+ });
17641
+ /**
17642
+ * The canonical notification. `body` is the only hard field (Apprise model).
17643
+ * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
17644
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
17645
+ * the adapter maps this ordinal onto its native level. `level?` is an
17646
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
17647
+ * `priority` for that one target.
17648
+ */
17649
+ var NotificationSchema = object({
17650
+ body: string(),
17651
+ title: string().optional(),
17652
+ format: NotificationFormatSchema.default("text"),
17653
+ priority: number().int().min(1).max(5).default(3),
17654
+ level: string().optional(),
17655
+ attachments: array(AttachmentSchema).optional(),
17656
+ clickUrl: string().optional(),
17657
+ actions: array(NotificationActionSchema).optional(),
17658
+ sound: string().optional(),
17659
+ ttl: number().optional(),
17660
+ tag: string().optional(),
17661
+ deviceId: number().optional(),
17662
+ eventId: string().optional(),
17663
+ metadata: record(string(), unknown()).optional()
17664
+ });
17665
+ /** One declared native severity/priority level for a kind. */
17666
+ var TargetKindLevelSchema = object({
17414
17667
  id: string(),
17415
- group: _enum([
17416
- "scope",
17417
- "class",
17418
- "zones",
17419
- "quality",
17420
- "label",
17421
- "schedule",
17422
- "device",
17423
- "package",
17424
- "occupancy"
17425
- ]),
17426
17668
  label: string(),
17427
- /** Editor widget the UI renders never hardcode per-condition forms. */
17428
- valueType: _enum([
17429
- "deviceIdList",
17430
- "stringList",
17431
- "number01",
17432
- "number",
17433
- "sourceSelect",
17434
- "zoneSelection",
17435
- "zoneIdList",
17436
- "schedule",
17437
- "plateMatcher",
17438
- "packagePhase",
17439
- "polygonDraw",
17440
- "occupancy"
17441
- ]),
17442
- operator: _enum([
17443
- "in",
17444
- "notIn",
17445
- "anyOf",
17446
- "allOf",
17447
- "gte",
17448
- "fuzzyIn",
17449
- "withinSchedule"
17450
- ]),
17451
- /** Which delivery kinds the condition applies to. */
17452
- appliesTo: array(NcDeliverySchema),
17453
- phase: string(),
17669
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
17670
+ ordinal: number().int().min(1).max(5).nullable(),
17671
+ flags: object({
17672
+ critical: boolean().optional(),
17673
+ silent: boolean().optional(),
17674
+ noPush: boolean().optional()
17675
+ }).optional(),
17676
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
17677
+ requires: array(string()).optional(),
17454
17678
  description: string().optional()
17455
17679
  });
17680
+ /** The full capability block consulted before dispatch. */
17681
+ var TargetKindCapsSchema = object({
17682
+ attachments: object({
17683
+ mediaTypes: array(AttachmentMediaTypeSchema),
17684
+ mode: _enum([
17685
+ "url",
17686
+ "bytes",
17687
+ "both"
17688
+ ]),
17689
+ max: number().int().nonnegative(),
17690
+ maxBytes: number().int().positive().optional()
17691
+ }),
17692
+ /** Max action buttons (0 = none). */
17693
+ actions: number().int().nonnegative(),
17694
+ levels: array(TargetKindLevelSchema),
17695
+ format: array(NotificationFormatSchema),
17696
+ clickUrl: boolean(),
17697
+ sound: boolean(),
17698
+ ttl: boolean(),
17699
+ bodyMaxLen: number().int().positive()
17700
+ });
17456
17701
  /**
17457
- * The delivery lifecycle status of a history row a straight read of the
17458
- * durable outbox row's own status (single source of truth):
17459
- * - `pending` — enqueued, in-flight or retrying with backoff
17460
- * - `sent` — delivered (terminal)
17461
- * - `dead` dead-lettered after exhausting retries / a permanent
17462
- * backend rejection / a deleted target (terminal; carries
17463
- * the failure `error`)
17464
- *
17465
- * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
17466
- * user dimension (quiet hours / snooze) and are additive when they land.
17702
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
17703
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
17704
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
17705
+ * the union is large and not meant for runtime validation here; the exported
17706
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
17467
17707
  */
17468
- var NcHistoryStatusSchema = _enum([
17469
- "pending",
17470
- "sent",
17471
- "dead"
17472
- ]);
17473
- /** The evaluated record kind a history row descends from (one per trigger). */
17474
- var NcHistoryRecordKindSchema = _enum([
17475
- "object-event",
17476
- "track-end",
17477
- "device-event",
17478
- "package-event"
17479
- ]);
17480
- /** Subject summary frozen on the row at fire time (survives rule/record edits). */
17481
- var NcHistorySubjectSchema = object({
17482
- className: string(),
17483
- label: string().optional(),
17484
- confidence: number().optional(),
17485
- zones: array(string()),
17486
- timestamp: number()
17708
+ var ConfigSchemaPassthrough = unknown();
17709
+ var TargetKindSchema = object({
17710
+ kind: string(),
17711
+ label: string(),
17712
+ icon: string(),
17713
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
17714
+ addonId: string(),
17715
+ configSchema: ConfigSchemaPassthrough,
17716
+ supportsDiscovery: boolean(),
17717
+ caps: TargetKindCapsSchema
17487
17718
  });
17488
17719
  /**
17489
- * One delivery-history row. This is a read-only VIEW over the durable
17490
- * outbox row (single source of truth the same row the drain loop drives;
17491
- * NO second write path, so history can never drift from delivery state).
17492
- * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
17493
- * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
17494
- * (fire) / `updatedAt` (last transition), `status` + `error` are the
17495
- * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
17496
- * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
17497
- * P1 (admin scope only).
17720
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
17721
+ * (return a presence marker only) when serving `listTargets` never
17722
+ * round-trip a stored secret to the UI.
17498
17723
  */
17499
- var NcHistoryEntrySchema = object({
17500
- /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
17724
+ var TargetSchema = object({
17501
17725
  id: string(),
17502
- ruleId: string(),
17503
- /** Rule name frozen at fire time (outlives a later rename / delete). */
17504
- ruleName: string(),
17505
- /** The rule urgency/trigger that produced this delivery. */
17506
- delivery: NcDeliverySchema,
17507
- targetId: string(),
17508
- deviceId: number(),
17509
- recordKind: NcHistoryRecordKindSchema,
17510
- /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
17511
- recordId: string(),
17512
- /** Present for track-scoped deliveries (object-event / track-end). */
17513
- trackId: string().optional(),
17514
- status: NcHistoryStatusSchema,
17515
- /** Delivery attempts made so far. */
17516
- attempts: number().int(),
17517
- /** Fire time (outbox enqueue). */
17518
- createdAt: number(),
17519
- /** Last transition time (terminal for sent / dead). */
17520
- updatedAt: number(),
17521
- /** Failure detail — present on a `dead` row. */
17522
- error: string().optional(),
17523
- subject: NcHistorySubjectSchema
17726
+ name: string(),
17727
+ kind: string(),
17728
+ addonId: string(),
17729
+ enabled: boolean(),
17730
+ config: record(string(), unknown())
17524
17731
  });
17525
- /**
17526
- * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
17527
- * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
17528
- * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
17529
- * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
17530
- */
17531
- var NcHistoryFilterSchema = object({
17532
- ruleId: string().optional(),
17533
- deviceId: number().optional(),
17534
- status: NcHistoryStatusSchema.optional(),
17535
- since: number().optional(),
17536
- until: number().optional(),
17537
- limit: number().int().min(1).max(500).default(100)
17732
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
17733
+ var DiscoveredTargetSchema = object({
17734
+ kind: string(),
17735
+ suggestedName: string(),
17736
+ config: record(string(), unknown())
17538
17737
  });
17539
- 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 }), {
17540
- kind: "mutation",
17541
- auth: "admin",
17542
- caller: "required"
17543
- }), method(object({
17544
- ruleId: string(),
17545
- patch: NcRulePatchSchema
17546
- }), object({ rule: NcRuleSchema }), {
17547
- kind: "mutation",
17548
- auth: "admin",
17549
- caller: "required"
17550
- }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
17551
- kind: "mutation",
17552
- auth: "admin"
17553
- }), method(object({
17554
- ruleId: string(),
17738
+ /** The degrade engine's report what was resolved / dropped / degraded. */
17739
+ var RenderedAsSchema = object({
17740
+ level: string(),
17741
+ format: NotificationFormatSchema,
17742
+ attachmentsSent: number().int().nonnegative(),
17743
+ actionsSent: number().int().nonnegative(),
17744
+ truncated: boolean(),
17745
+ dropped: array(string())
17746
+ });
17747
+ var SendResultSchema = object({
17748
+ success: boolean(),
17749
+ error: string().optional(),
17750
+ renderedAs: RenderedAsSchema.optional()
17751
+ });
17752
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
17753
+ var TestResultSchema = SendResultSchema;
17754
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
17755
+ kind: string(),
17756
+ config: record(string(), unknown()).optional()
17757
+ }), array(DiscoveredTargetSchema)), method(object({
17758
+ targetId: string(),
17759
+ notification: NotificationSchema
17760
+ }), SendResultSchema, { kind: "mutation" }), method(object({
17761
+ targetId: string(),
17762
+ sample: NotificationSchema.optional()
17763
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
17764
+ targetId: string(),
17555
17765
  enabled: boolean()
17556
- }), object({ success: literal(true) }), {
17557
- kind: "mutation",
17558
- auth: "admin"
17559
- }), method(object({
17560
- rule: NcRuleInputSchema,
17561
- lookbackMinutes: number().int().min(1).max(1440).default(60)
17562
- }), object({ results: array(NcTestResultSchema) }), {
17563
- kind: "mutation",
17564
- auth: "admin"
17565
- }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
17766
+ }), _void(), { kind: "mutation" });
17566
17767
  /**
17567
17768
  * Zod schemas for persisted record types.
17568
17769
  *
@@ -22829,6 +23030,12 @@ Object.freeze({
22829
23030
  addonId: null,
22830
23031
  access: "delete"
22831
23032
  },
23033
+ "backup.deleteSchedule": {
23034
+ capName: "backup",
23035
+ capScope: "system",
23036
+ addonId: null,
23037
+ access: "delete"
23038
+ },
22832
23039
  "backup.getEntries": {
22833
23040
  capName: "backup",
22834
23041
  capScope: "system",
@@ -22859,6 +23066,12 @@ Object.freeze({
22859
23066
  addonId: null,
22860
23067
  access: "view"
22861
23068
  },
23069
+ "backup.listSchedules": {
23070
+ capName: "backup",
23071
+ capScope: "system",
23072
+ addonId: null,
23073
+ access: "view"
23074
+ },
22862
23075
  "backup.previewSchedule": {
22863
23076
  capName: "backup",
22864
23077
  capScope: "system",
@@ -22883,6 +23096,12 @@ Object.freeze({
22883
23096
  addonId: null,
22884
23097
  access: "create"
22885
23098
  },
23099
+ "backup.upsertSchedule": {
23100
+ capName: "backup",
23101
+ capScope: "system",
23102
+ addonId: null,
23103
+ access: "create"
23104
+ },
22886
23105
  "battery.wakeForStream": {
22887
23106
  capName: "battery",
22888
23107
  capScope: "device",
@@ -26717,6 +26936,36 @@ Object.freeze({
26717
26936
  addonId: null,
26718
26937
  access: "create"
26719
26938
  },
26939
+ "terminalSession.close": {
26940
+ capName: "terminal-session",
26941
+ capScope: "system",
26942
+ addonId: null,
26943
+ access: "create"
26944
+ },
26945
+ "terminalSession.listProfiles": {
26946
+ capName: "terminal-session",
26947
+ capScope: "system",
26948
+ addonId: null,
26949
+ access: "view"
26950
+ },
26951
+ "terminalSession.listSessions": {
26952
+ capName: "terminal-session",
26953
+ capScope: "system",
26954
+ addonId: null,
26955
+ access: "view"
26956
+ },
26957
+ "terminalSession.openSession": {
26958
+ capName: "terminal-session",
26959
+ capScope: "system",
26960
+ addonId: null,
26961
+ access: "create"
26962
+ },
26963
+ "terminalSession.resize": {
26964
+ capName: "terminal-session",
26965
+ capScope: "system",
26966
+ addonId: null,
26967
+ access: "create"
26968
+ },
26720
26969
  "toast.onToast": {
26721
26970
  capName: "toast",
26722
26971
  capScope: "system",