@camstack/addon-admin-ui 1.2.13 → 1.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/dist/assets/AddLocationWizard-BzfZuUFE.js +1 -0
  2. package/dist/assets/{AddonCollectionPage-DYquwbFT.js → AddonCollectionPage-D4dNkjD9.js} +1 -1
  3. package/dist/assets/Addons-KlOfEhx8.js +1 -0
  4. package/dist/assets/{AdminTabs-zSfrI6J9.js → AdminTabs-B6qnIaak.js} +1 -1
  5. package/dist/assets/{AiProfiles-Cx4S2Xkn.js → AiProfiles-DnuLTZqB.js} +1 -1
  6. package/dist/assets/{BrokerForm-1PckGyVt.js → BrokerForm-C99fSuRo.js} +1 -1
  7. package/dist/assets/{Capabilities-DAgsQGgg.js → Capabilities-B8SGK49R.js} +1 -1
  8. package/dist/assets/{CapabilityBadges-DNN-Wcn_.js → CapabilityBadges-BTZKlfM2.js} +1 -1
  9. package/dist/assets/{Cluster-tHXKC3rK.js → Cluster-COcBiWpg.js} +1 -1
  10. package/dist/assets/{ClusterRecordingTab-CSv5S75g.js → ClusterRecordingTab-BPSdzcK3.js} +1 -1
  11. package/dist/assets/{Dashboard-hoLQH06K.js → Dashboard-DCFIPV11.js} +1 -1
  12. package/dist/assets/{Data-BG8m8LaL.js → Data-_pY_q5xu.js} +1 -1
  13. package/dist/assets/{DetectionIntelligence-MFZJV9-v.js → DetectionIntelligence-B6Dj5dVX.js} +1 -1
  14. package/dist/assets/DeviceDetail-N6WvCekZ.js +2 -0
  15. package/dist/assets/{Devices-5G2YiKkY.js → Devices-Dzpvq_f7.js} +1 -1
  16. package/dist/assets/{EmbedPlayerPage-jG_j7yUQ.js → EmbedPlayerPage-CNBEeRdP.js} +1 -1
  17. package/dist/assets/Events-B5T59IPR.js +1 -0
  18. package/dist/assets/{FormBuilder-CiMiy3vQ.js → FormBuilder-CMFZXwvq.js} +1 -1
  19. package/dist/assets/{Identity-pmhb-jIF.js → Identity-BbNZdgPf.js} +1 -1
  20. package/dist/assets/IntegrationDetail-DEPSilP_.js +1 -0
  21. package/dist/assets/{Integrations-CLYqdNHv.js → Integrations-B1Ld1HH1.js} +1 -1
  22. package/dist/assets/{Integrations-83V72pmh.js → Integrations-B3rD6hIo.js} +1 -1
  23. package/dist/assets/{Logs-B0w1rIre.js → Logs-CYpS3BpR.js} +1 -1
  24. package/dist/assets/{MotionZonesSettings-DbtzjXBB.js → MotionZonesSettings-2auRIiQ1.js} +1 -1
  25. package/dist/assets/{MyAccess-nniMr2oJ.js → MyAccess-D3_q9-33.js} +1 -1
  26. package/dist/assets/Network-DIVAg_f5.js +1 -0
  27. package/dist/assets/{NodeAddonsSettingsPanel-CDNzzco1.js → NodeAddonsSettingsPanel-CgGvimGW.js} +1 -1
  28. package/dist/assets/{NodeInferenceDevices-CJmWaPa6.js → NodeInferenceDevices-COSPUL-L.js} +1 -1
  29. package/dist/assets/{Notifications-CjH_7Mrn.js → Notifications-Bv4whDil.js} +1 -1
  30. package/dist/assets/Pipeline-l_vZ2VML.js +1 -0
  31. package/dist/assets/{Plates-Dy8Uqgga.js → Plates-C96Mahmu.js} +1 -1
  32. package/dist/assets/{PrivacyMaskSettings-D7rqLqim.js → PrivacyMaskSettings-C2PIvv63.js} +1 -1
  33. package/dist/assets/{ProviderIcon-B-fRGGgK.js → ProviderIcon-DQ9yuo_L.js} +1 -1
  34. package/dist/assets/{Recordings-BV351EeV.js → Recordings-C2R7zGta.js} +1 -1
  35. package/dist/assets/{ScanNetworkModal-Uw3hg1ai.js → ScanNetworkModal-Cl1Mdjki.js} +1 -1
  36. package/dist/assets/{Settings-CVkG5Y5G.js → Settings-CvCaq_zC.js} +1 -1
  37. package/dist/assets/{Showroom-B-d2WdW_.js → Showroom-BCsIYYwv.js} +1 -1
  38. package/dist/assets/Terminal-BpPIZ0or.js +13 -0
  39. package/dist/assets/Terminal-kHJ-D0s7.css +1 -0
  40. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-D02gABkF.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BALp_9qY.js} +1 -1
  41. package/dist/assets/{build-cluster-graph-vmA5yA4M.js → build-cluster-graph-cp3KQH-1.js} +1 -1
  42. package/dist/assets/circle-check-big-4_1SeqzL.js +1 -0
  43. package/dist/assets/clock-CmbYDH1e.js +1 -0
  44. package/dist/assets/{copy-DGD_D0fl.js → copy-UBfFgSz-.js} +1 -1
  45. package/dist/assets/{debounced-invalidate-OsMHAbLS.js → debounced-invalidate-BsGZbF6v.js} +1 -1
  46. package/dist/assets/dist-CphRM5WA.js +7 -0
  47. package/dist/assets/{dist-DO_uCRhe.js → dist-CvIYYU5j.js} +1 -1
  48. package/dist/assets/{download-DAdvlREf.js → download-BpNiVwyM.js} +1 -1
  49. package/dist/assets/{face-bbox-D-tm4cNu.js → face-bbox-BScALk_z.js} +1 -1
  50. package/dist/assets/{hostInit-DJqsmyYG.js → hostInit-DFZvs0Jw.js} +1 -1
  51. package/dist/assets/index-0YJ-haW4.css +2 -0
  52. package/dist/assets/index-Cl-M8KBA.js +4 -0
  53. package/dist/assets/{key-round-pEZFmYxy.js → key-round-BPb5gRuL.js} +1 -1
  54. package/dist/assets/{mf-entry-bootstrap-0-81564783.js → mf-entry-bootstrap-0-1f1c06da.js} +2 -2
  55. package/dist/assets/{pencil-CQfM-gfd.js → pencil-Bcfk7YmX.js} +1 -1
  56. package/dist/assets/{player-overlays-Z3KIJoY4.js → player-overlays-CpNYQPHP.js} +1 -1
  57. package/dist/assets/plus-z-WZstU2.js +1 -0
  58. package/dist/assets/{radio-xNJ7grGy.js → radio-BH-ZU1HE.js} +1 -1
  59. package/dist/assets/{refresh-cw-D6O4UC61.js → refresh-cw-hhKexEfo.js} +1 -1
  60. package/dist/assets/remoteEntry-C6sBv4xP.js +1 -0
  61. package/dist/assets/{rotate-ccw--NZkK553.js → rotate-ccw-CbpUNSqs.js} +1 -1
  62. package/dist/assets/rotate-cw-CQj7EyBl.js +1 -0
  63. package/dist/assets/search-DqoMv21b.js +1 -0
  64. package/dist/assets/{send-5-cXx4t3.js → send-Cyy_G5i9.js} +1 -1
  65. package/dist/assets/{server-CejZYHBK.js → server-BxRe5xIW.js} +1 -1
  66. package/dist/assets/square-CEBWDX93.js +1 -0
  67. package/dist/assets/{square-check-big-vugmEemF.js → square-check-big-hPLl5NdC.js} +1 -1
  68. package/dist/assets/src-Cv9CvT8c.js +7 -0
  69. package/dist/assets/{src-DmOEfaLx.js → src-DHFCkQHW.js} +10 -10
  70. package/dist/assets/{upload-C59L2Wdl.js → upload-C6Q1-uQx.js} +1 -1
  71. package/dist/assets/{useEventInvalidation-D-pUhceB.js → useEventInvalidation-Bh_CgFlD.js} +1 -1
  72. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-BLiSxcpg.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-C9LrTlPE.js} +2 -2
  73. package/dist/assets/{wifi-Dl3Y5-yO.js → wifi-CL8vr9lV.js} +1 -1
  74. package/dist/assets/{zap-DDoGra5X.js → zap-DZXxY1Hy.js} +1 -1
  75. package/dist/index.html +6 -6
  76. package/dist/server/addon.js +2247 -2079
  77. package/package.json +3 -1
  78. package/dist/assets/AddLocationWizard-DbYmoWjx.js +0 -1
  79. package/dist/assets/Addons-B21MzGyu.js +0 -1
  80. package/dist/assets/DeviceDetail-Cb_hP9AH.js +0 -2
  81. package/dist/assets/Events-DuWWYRlK.js +0 -1
  82. package/dist/assets/IntegrationDetail-BjegrPYt.js +0 -1
  83. package/dist/assets/Network-xntFbRy8.js +0 -1
  84. package/dist/assets/Pipeline-Cn32tJhF.js +0 -1
  85. package/dist/assets/circle-check-big-CbpJhu8J.js +0 -1
  86. package/dist/assets/clock-D8VWqfVX.js +0 -1
  87. package/dist/assets/dist-hhplA-xw.js +0 -7
  88. package/dist/assets/index-DO10ga5L.css +0 -2
  89. package/dist/assets/index-dCklXrvt.js +0 -4
  90. package/dist/assets/plus-CqnkUqMJ.js +0 -1
  91. package/dist/assets/remoteEntry-C2M3CZjx.js +0 -1
  92. package/dist/assets/rotate-cw-CJNm_D4O.js +0 -1
  93. package/dist/assets/search-YJw6yJPL.js +0 -1
  94. package/dist/assets/square-DGtpAb1Z.js +0 -1
  95. package/dist/assets/src-4xaQB5RZ.js +0 -7
@@ -8872,399 +8872,1037 @@ var AccessoryKind = {
8872
8872
  AccessoryKind.Siren, AccessoryKind.Floodlight, AccessoryKind.Spotlight, AccessoryKind.PirSensor, AccessoryKind.Chime, AccessoryKind.Autotrack, AccessoryKind.Nightvision, AccessoryKind.PrivacyMask;
8873
8873
  DeviceFeature.BatteryOperated;
8874
8874
  /**
8875
- * Generic device-level status snapshot. Auto-registered by `BaseDevice`
8876
- * for every device, regardless of provider the kernel needs a uniform
8877
- * cap-keyed slice for the basic device flags every consumer expects to
8878
- * read across processes (the `online` flag in particular). Driver-specific
8879
- * caps (`battery`, `doorbell`, …) carry their domain-specific state on
8880
- * their own slices.
8875
+ * Shared geometry vocabulary for on-frame shape caps — privacy-mask,
8876
+ * motion-zones, and the detection zones/lines editor all speak this one
8877
+ * language so a single drawing-plane editor and the providers stay
8878
+ * decoupled from each cap's storage.
8881
8879
  *
8882
- * Pattern is identical to `battery`: schema-bearing `runtimeState`,
8883
- * empty `methods`, single change event. Reads land at
8884
- * `runtimeState.getCapState('device-status')`; writes at
8885
- * `runtimeState.setCapState('device-status', …)`. Cross-process
8886
- * consumers reach the same data via the `device-state` cap router
8887
- * (`getCapSlice({deviceId, capName: 'device-status'})`).
8880
+ * All coordinates are normalized 0..1 of the camera frame (top-left
8881
+ * origin). Each cap composes the SUBSET of shape kinds it supports and
8882
+ * advertises it via `supportedShapes` in its `getOptions`.
8888
8883
  */
8889
- var DeviceStatusSchema = object({
8890
- /**
8891
- * Device-level liveness. Drivers flip via `markOnline(boolean)` on
8892
- * `BaseDevice`. Provider semantics vary — RTSP aggregates broker
8893
- * stream-health, Reolink reads firmware push events, ONVIF tracks
8894
- * ping responses. This cap intentionally does NOT prescribe which
8895
- * signal drives the flag.
8896
- */
8897
- online: boolean(),
8898
- /** Ms epoch of the last `online` transition. Lets consumers tell
8899
- * apart "just came online" from "still online". */
8900
- lastChangedAt: number()
8884
+ /** A normalized 0..1 point (top-left origin). */
8885
+ var MaskPointSchema = object({
8886
+ x: number(),
8887
+ y: number()
8901
8888
  });
8902
- object({
8903
- deviceId: number(),
8904
- status: DeviceStatusSchema
8889
+ /** Axis-aligned rectangle (normalized 0..1). */
8890
+ var MaskRectShapeSchema = object({
8891
+ kind: literal("rect"),
8892
+ x: number(),
8893
+ y: number(),
8894
+ width: number(),
8895
+ height: number()
8896
+ });
8897
+ /** Free polygon — an ordered list of normalized vertices (≥3). */
8898
+ var MaskPolygonShapeSchema = object({
8899
+ kind: literal("polygon"),
8900
+ points: array(MaskPointSchema)
8901
+ });
8902
+ /** Boolean cell grid — row-major, length === gridWidth*gridHeight. */
8903
+ var MaskGridShapeSchema = object({
8904
+ kind: literal("grid"),
8905
+ gridWidth: number(),
8906
+ gridHeight: number(),
8907
+ cells: array(boolean())
8908
+ });
8909
+ discriminatedUnion("kind", [
8910
+ MaskRectShapeSchema,
8911
+ MaskPolygonShapeSchema,
8912
+ MaskGridShapeSchema,
8913
+ object({
8914
+ kind: literal("line"),
8915
+ points: array(MaskPointSchema)
8916
+ })
8917
+ ]);
8918
+ /** Every shape-kind discriminant, for `supportedShapes` advertisement. */
8919
+ var MaskShapeKindSchema = _enum([
8920
+ "rect",
8921
+ "polygon",
8922
+ "grid",
8923
+ "line"
8924
+ ]);
8925
+ /** Polygon vertex bounds when a cap supports 'polygon' (e.g. Hikvision {min:4,max:4}). */
8926
+ var MaskPolygonVerticesSchema = object({
8927
+ min: number(),
8928
+ max: number()
8929
+ });
8930
+ /** Grid dimensions when a cap supports 'grid'. */
8931
+ var MaskGridDimsSchema = object({
8932
+ width: number(),
8933
+ height: number()
8905
8934
  });
8906
8935
  /**
8907
- * Per-device feature/identity probe slice. Holds the runtime-resolved
8908
- * truth about what a device CAN do — which the kernel uses to:
8909
- * 1. Reconcile accessory children (hub-children spawn siren/floodlight/PIR
8910
- * based on what the firmware actually advertises).
8911
- * 2. Compute the public `features: DeviceFeature[]` array surfaced via
8912
- * `device-manager.listAll`.
8913
- * 3. Decide which optional caps (PTZ, intercom, doorbell, battery, …)
8914
- * to register on the device's capability surface.
8936
+ * notification-rules the Notification Center rule surface (P1 core).
8915
8937
  *
8916
- * Auto-registered by `BaseDevice` for every device. Drivers populate the
8917
- * slice from `onProbe()` (kernel calls it once after register, before
8918
- * accessory reconciliation). Consumers read via:
8919
- * `runtimeState.getCapState<FeatureProbeStatus>('feature-probe')`
8938
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
8939
+ * (operator decisions D-1/D-2/D-3 are binding):
8920
8940
  *
8921
- * `flags` is an open record so each driver carries its own keys without
8922
- * a centralized schema bottleneck Reolink writes `hasPtz/hasIntercom`,
8923
- * Hikvision writes `hasSupplementalLight/hasAlarmIo`, etc.
8941
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
8942
+ * `notification-center` module), hooked on the durable persistence
8943
+ * moments (object-event insert, TrackCloser.closeExpired) with a
8944
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
8945
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
8946
+ * FIRST persisted detection matching the conditions (per-track dedup,
8947
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
8948
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
8949
+ * - DISPATCH stays behind `notification-output` (rules reference targets
8950
+ * by id; per-backend params are a passthrough blob capped by the
8951
+ * target kind's own caps/degrade engine).
8924
8952
  *
8925
- * Replaces the older driver-local `deviceCache.has*` blob: the per-device
8926
- * config is for operator-edited overrides + UI snapshots; runtime probe
8927
- * results belong in runtime-state where the kernel handles persistence,
8928
- * cross-process mirroring, and reactive updates.
8953
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
8954
+ * server-injected caller identity the first `caller: 'required'`
8955
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
8956
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
8957
+ * windows, and the optional label/identity/plate matchers. User rules,
8958
+ * private zones, per-recipient fan-out and the wider condition table are
8959
+ * P2+ (see spec §7).
8960
+ *
8961
+ * All schemas here are the single source of truth — `NcRule` etc. are
8962
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
8963
+ * schema/interface drift is explicitly not repeated).
8929
8964
  */
8930
- var FeatureProbeStatusSchema = object({
8965
+ /**
8966
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
8967
+ * The value maps 1:1 onto the evaluated record kind:
8968
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
8969
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
8970
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
8971
+ * change of a LINKED device, one row per linked camera)
8972
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
8973
+ * delivery / pick-up)
8974
+ *
8975
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
8976
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
8977
+ * this one field keeps the schema additive — a rule still declares exactly
8978
+ * one trigger.
8979
+ */
8980
+ var NcDeliverySchema = _enum([
8981
+ "immediate",
8982
+ "track-end",
8983
+ "device-event",
8984
+ "package-event"
8985
+ ]);
8986
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
8987
+ var NcScheduleSchema = object({
8988
+ windows: array(object({
8989
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
8990
+ days: array(number().int().min(0).max(6)).min(1),
8991
+ startMinute: number().int().min(0).max(1439),
8992
+ endMinute: number().int().min(0).max(1439)
8993
+ })).min(1),
8994
+ /** IANA timezone; default = hub host timezone. */
8995
+ timezone: string().optional(),
8996
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
8997
+ invert: boolean().optional()
8998
+ });
8999
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
9000
+ var NcPlateMatcherSchema = object({
9001
+ values: array(string().min(1)).min(1),
9002
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
9003
+ maxDistance: number().int().min(0).max(3).default(1)
9004
+ });
9005
+ /**
9006
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
9007
+ * occupancy edge for a device — optionally narrowed to a single admin
9008
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
9009
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
9010
+ * - `became-free` — count crossed ≥ `count` → below it
9011
+ * - `>=` / `<=` — count is at/over or at/under `count`
9012
+ * `sustainSeconds` requires the condition hold continuously that long
9013
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
9014
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
9015
+ * the condition never matches. Confirmed edge-state survives addon restarts
9016
+ * (declared SQLite collection, reseeded on boot).
9017
+ */
9018
+ var NcOccupancyConditionSchema = object({
9019
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
9020
+ zoneId: string().optional(),
9021
+ /** Object class to count; absent = any class. */
9022
+ className: string().optional(),
9023
+ op: _enum([
9024
+ "became-occupied",
9025
+ "became-free",
9026
+ ">=",
9027
+ "<="
9028
+ ]).default("became-occupied"),
9029
+ count: number().int().min(0).default(1),
9030
+ sustainSeconds: number().int().min(0).max(3600).default(15)
9031
+ });
9032
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
9033
+ var NcZoneConditionSchema = object({
9034
+ ids: array(string().min(1)).min(1),
9035
+ /** Quantifier over `ids` — at least one / every one visited. */
9036
+ match: _enum(["any", "all"]).default("any")
9037
+ });
9038
+ /**
9039
+ * The P1 condition set — a flat AND of groups; absent group = pass;
9040
+ * membership lists are OR within the list (spec §2.3).
9041
+ */
9042
+ var NcConditionsSchema = object({
9043
+ /** Device scope — absent = all devices. */
9044
+ devices: array(number()).optional(),
9045
+ /** Detector class names (any overlap with the record's class set). */
9046
+ classes: array(string().min(1)).optional(),
9047
+ /** Veto classes — any overlap fails the rule. */
9048
+ classesExclude: array(string().min(1)).optional(),
9049
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
9050
+ minConfidence: number().min(0).max(1).optional(),
9051
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
9052
+ zones: NcZoneConditionSchema.optional(),
9053
+ /** Veto zones — any hit fails the rule. */
9054
+ zonesExclude: array(string().min(1)).optional(),
8931
9055
  /**
8932
- * Driver-specific flag bag. Each driver picks its own key names — the
8933
- * cap deliberately does NOT enforce a closed enum here. Reolink keys:
8934
- * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,
8935
- * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:
8936
- * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.
9056
+ * Exact (case-insensitive) match on the record's collapsed `label`
9057
+ * (identity name / plate text / subclass).
8937
9058
  */
8938
- flags: record(string(), unknown()),
9059
+ labelEquals: array(string().min(1)).optional(),
8939
9060
  /**
8940
- * Coarse driver-classification lets cross-process consumers tell apart
8941
- * cameras / battery-cams / NVRs without re-running the probe. `null`
8942
- * before the first probe completes.
9061
+ * Identity matcher. P1 boundary: matched against the record's collapsed
9062
+ * `label` (the identity display name propagated by the face pipeline) —
9063
+ * identity-ID matching rides in P2 when identity ids reach the record.
8943
9064
  */
8944
- deviceType: string().nullable(),
8945
- /** Camera/firmware model string. `null` when the firmware doesn't expose it. */
8946
- model: string().nullable(),
8947
- /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */
8948
- channelCount: number().nullable(),
9065
+ identities: array(string().min(1)).optional(),
9066
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
9067
+ plates: NcPlateMatcherSchema.optional(),
8949
9068
  /**
8950
- * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe
8951
- * completes drivers' `getAccessoryChildren()` should treat zero as
8952
- * "probe not done yet, return empty" so accessories aren't spawned
8953
- * before the firmware is queried.
9069
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
9070
+ * Same P1 boundary: matched against the record's collapsed `label` (the
9071
+ * identity display name). A record with NO label passes (nothing to
9072
+ * exclude), unlike the include variant which fails on an absent label.
8954
9073
  */
8955
- lastProbedAt: number(),
9074
+ identitiesExclude: array(string().min(1)).optional(),
8956
9075
  /**
8957
- * Framework convention: every runtime-state slice carries this for the
8958
- * createRuntimeStateBridge stale-check helper. We keep it in sync with
8959
- * `lastProbedAt` on every write.
8960
- */
8961
- lastFetchedAt: number()
8962
- });
8963
- object({
8964
- deviceId: number(),
8965
- status: FeatureProbeStatusSchema
9076
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
9077
+ * TRACK-END only: importance is scored at track close, so it does not exist
9078
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
9079
+ * close the value is threaded via the close-time info (the `Track` clone is
9080
+ * captured before the DB row is updated, so it would otherwise read stale).
9081
+ * Fails when the record carries no importance (never guess quality — the
9082
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
9083
+ */
9084
+ minImportance: number().min(0).max(1).optional(),
9085
+ /**
9086
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
9087
+ * TRACK-END only: an `immediate` / object-event subject has no closed
9088
+ * lifespan, so a dwell condition never matches immediate delivery
9089
+ * (documented choice — the object-event record carries no `firstSeen`,
9090
+ * so dwell cannot be computed from what the subject actually carries).
9091
+ */
9092
+ minDwellSeconds: number().min(0).optional(),
9093
+ /**
9094
+ * Detection provenance filter. `any` (default / absent) matches every
9095
+ * source; otherwise the subject's source must equal it. Legacy records
9096
+ * with no stamped source are treated as `pipeline`. The union spans both
9097
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
9098
+ * tracks carry `sensor`.
9099
+ */
9100
+ source: _enum([
9101
+ "pipeline",
9102
+ "onboard",
9103
+ "sensor",
9104
+ "any"
9105
+ ]).optional(),
9106
+ /**
9107
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
9108
+ * detector `minConfidence` (that gates the object-detection score; this
9109
+ * gates the recognition/OCR match score). Fails when the subject carries
9110
+ * no label-match confidence (never guess). TRACK-END only: the confidence
9111
+ * lives on the recognition result and reaches the subject at track close.
9112
+ *
9113
+ * What it measures precisely (plumbed at track close — the closer threads
9114
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
9115
+ * `importance`): the BEST recognition match confidence observed for the
9116
+ * label the track carries at close — for a face, the peak cosine similarity
9117
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
9118
+ * for a plate, the peak OCR read score of the best-held plate
9119
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
9120
+ * one track the higher of the two is used. A track that ended with no
9121
+ * confident identity/plate match carries no value, so the condition fails
9122
+ * closed for it (an un-recognized subject).
9123
+ */
9124
+ minLabelConfidence: number().min(0).max(1).optional(),
9125
+ /**
9126
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
9127
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
9128
+ * against the token carried on the device-event subject (extracted from the
9129
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
9130
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
9131
+ * eventType, so gate those with {@link sensorKinds} instead.
9132
+ */
9133
+ eventTypeTokens: array(string().min(1)).optional(),
9134
+ /**
9135
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
9136
+ * `contact`, `button`, `device-event`) — matched against the persisted
9137
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
9138
+ */
9139
+ sensorKinds: array(string().min(1)).optional(),
9140
+ /**
9141
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
9142
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
9143
+ * when the subject's phase does not match (a subject always carries a phase
9144
+ * on the package-event trigger).
9145
+ */
9146
+ packagePhase: _enum([
9147
+ "delivered",
9148
+ "picked-up",
9149
+ "both"
9150
+ ]).optional(),
9151
+ /**
9152
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
9153
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
9154
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
9155
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
9156
+ */
9157
+ customZones: array(MaskPolygonShapeSchema).optional(),
9158
+ /**
9159
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
9160
+ * (optionally zone/class-scoped) occupancy count crosses the configured
9161
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
9162
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
9163
+ */
9164
+ occupancy: NcOccupancyConditionSchema.optional()
8966
9165
  });
8967
- object({
8968
- /** Carbon dioxide concentration in ppm. */
8969
- co2Ppm: number().min(0).optional(),
8970
- /** Total volatile organic compounds in ppb. */
8971
- vocPpb: number().min(0).optional(),
8972
- /** Particulate matter 2.5 μm in µg/m³. */
8973
- pm25: number().min(0).optional(),
8974
- /** Particulate matter 10 μm in µg/m³. */
8975
- pm10: number().min(0).optional(),
8976
- /** Composite AQI value (typically 0..500). */
8977
- aqi: number().optional(),
8978
- /** Ms epoch when the slice was last updated. */
8979
- lastFetchedAt: number(),
8980
- /** Live display unit of the single metric this slice carries (e.g. HA
8981
- * `attributes.unit_of_measurement` → 'ppm' / 'ppb' / 'µg/m³'). Each
8982
- * upstream `sensor.*` entity surfaces ONE device_class, so one unit
8983
- * per slice is unambiguous. */
8984
- unit: string().optional(),
8985
- /** Suggested decimal places for numeric display.
8986
- * Populated live from the upstream source when provided (e.g. HA
8987
- * `attributes.suggested_display_precision`). Falls back to
8988
- * auto-formatting when absent. */
8989
- precision: number().int().min(0).max(10).optional()
9166
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
9167
+ var NcRuleTargetSchema = object({
9168
+ /** `notification-output` Target id. */
9169
+ targetId: string().min(1),
9170
+ /**
9171
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
9172
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
9173
+ * degrade engine drops what the backend can't render.
9174
+ */
9175
+ params: record(string(), unknown()).optional()
8990
9176
  });
8991
- DeviceType.Sensor;
8992
9177
  /**
8993
- * Alarm-panel cap. Models HA `alarm_control_panel.*` on
8994
- * `DeviceType.AlarmPanel`. State follows HA's canonical lifecycle
8995
- * across disarmed / armed_(home|away|night|vacation|custom_bypass) /
8996
- * arming / pending / triggered / disarming.
8997
- *
8998
- * Many panels require a PIN code on arm / disarm — the optional
8999
- * `code` field on the methods passes it through to the upstream
9000
- * service; it's NEVER persisted in the runtime slice or any event
9001
- * payload. The presence of a required code is signalled by
9002
- * `DeviceFeature.AlarmPinRequired` so the UI gates a code-entry
9003
- * field without a slice fetch.
9004
- *
9005
- * `availableModes` mirrors HA's `supported_features`-derived arm
9006
- * mode list — the UI renders only the buttons the panel accepts.
9178
+ * Media attachment policy (P1 still-image subset).
9179
+ * - `best` the best AVAILABLE subject image at dispatch time (D-3).
9180
+ * - `best-matching` the media that explains WHY the rule fired: a rule
9181
+ * matched on identities attaches the subject's `faceCrop`, one matched on
9182
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
9183
+ * (or when the specific crop is missing) degrades to `best`, then
9184
+ * `keyFrame`, then no attachment never delaying the send. The matched
9185
+ * condition summary is frozen on the outbox row at enqueue (like the rule
9186
+ * name), so the choice never drifts from the record that fired it.
9187
+ * - `keyFrame` the clean scene frame (no subject box).
9188
+ * - `none` no attachment.
9007
9189
  */
9008
- var AlarmStateSchema = _enum([
9009
- "disarmed",
9010
- "armed_home",
9011
- "armed_away",
9012
- "armed_night",
9013
- "armed_vacation",
9014
- "armed_custom_bypass",
9015
- "arming",
9016
- "disarming",
9017
- "pending",
9018
- "triggered"
9019
- ]);
9020
- var AlarmArmModeSchema = _enum([
9021
- "home",
9022
- "away",
9023
- "night",
9024
- "vacation",
9025
- "custom_bypass"
9026
- ]);
9027
- object({
9028
- /** Current lifecycle state. */
9029
- state: AlarmStateSchema,
9030
- /** Subset of arm modes the panel accepts. UI renders one button per
9031
- * mode in this list. */
9032
- availableModes: array(AlarmArmModeSchema),
9033
- /** Whether the panel requires a PIN on arm / disarm. Mirrors
9034
- * `DeviceFeature.AlarmPinRequired` for slice consumers. */
9035
- requiresCode: boolean(),
9036
- /** Ms epoch when the slice was last updated. */
9037
- lastChangedAt: number()
9038
- });
9039
- DeviceType.AlarmPanel, method(object({
9040
- deviceId: number().int().nonnegative(),
9041
- mode: AlarmArmModeSchema,
9042
- /** Optional PIN code. Required when `requiresCode === true`.
9043
- * Passed through to the upstream service; never persisted. */
9044
- code: string().min(1).optional()
9045
- }), _void(), {
9046
- kind: "mutation",
9047
- auth: "admin"
9048
- }), method(object({
9049
- deviceId: number().int().nonnegative(),
9050
- code: string().min(1).optional()
9051
- }), _void(), {
9052
- kind: "mutation",
9053
- auth: "admin"
9054
- }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
9055
- kind: "mutation",
9056
- auth: "admin"
9190
+ var NcMediaPolicySchema = object({ attach: _enum([
9191
+ "best",
9192
+ "best-matching",
9193
+ "keyFrame",
9194
+ "none"
9195
+ ]).default("best") });
9196
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
9197
+ var NcThrottleSchema = object({
9198
+ cooldownSec: number().int().min(0).max(86400).default(60),
9199
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
9200
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
9057
9201
  });
9058
- object({
9059
- /** Current illuminance in lux (lx). */
9060
- lux: number().min(0),
9061
- /** Ms epoch when the slice was last updated. */
9062
- lastFetchedAt: number(),
9063
- /** Live display unit from the upstream source (e.g. HA
9064
- * `attributes.unit_of_measurement`). The UI prefers this over the
9065
- * role's canonical unit. Absent → fall back to the canonical unit. */
9066
- unit: string().optional(),
9067
- /** Suggested decimal places for numeric display.
9068
- * Populated live from the upstream source when provided (e.g. HA
9069
- * `attributes.suggested_display_precision`). Falls back to
9070
- * auto-formatting when absent. */
9071
- precision: number().int().min(0).max(10).optional()
9202
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
9203
+ var NcRuleInputSchema = object({
9204
+ name: string().min(1).max(200),
9205
+ enabled: boolean().default(true),
9206
+ delivery: NcDeliverySchema,
9207
+ conditions: NcConditionsSchema.default({}),
9208
+ schedule: NcScheduleSchema.optional(),
9209
+ targets: array(NcRuleTargetSchema).min(1),
9210
+ media: NcMediaPolicySchema.default({ attach: "best" }),
9211
+ throttle: NcThrottleSchema.default({
9212
+ cooldownSec: 60,
9213
+ scope: "rule-device"
9214
+ }),
9215
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
9216
+ template: object({
9217
+ title: string().max(500).optional(),
9218
+ body: string().max(2e3).optional()
9219
+ }).optional(),
9220
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
9221
+ priority: number().int().min(1).max(5).default(3),
9222
+ /**
9223
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
9224
+ * behaviour, visible to all, read-only in the viewer). Present = personal
9225
+ * rule owned by this userId. Server-stamped; never trusted from a client.
9226
+ */
9227
+ ownerUserId: string().optional()
9072
9228
  });
9073
- DeviceType.Sensor;
9074
9229
  /**
9075
- * Per-class audio metrics aggregated over a sliding window.
9076
- */
9077
- var AudioClassSummarySchema = object({
9078
- className: string(),
9079
- /** Number of windows (chunks) where this class was the top hit. */
9080
- hits: number().int().nonnegative(),
9081
- /** Mean score across those hits, clamped to [0,1]. */
9082
- avgScore: number().min(0).max(1),
9083
- /** Peak score in the window. */
9084
- peakScore: number().min(0).max(1)
9230
+ * Partial patch for `updateRule` any subset of the input fields, plus the
9231
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
9232
+ * NOT a client-authored input field (it lives on the persisted rule, not the
9233
+ * input), so it is added here explicitly to let the store's per-target opt-out
9234
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
9235
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
9236
+ * `updateRule` patch.
9237
+ */
9238
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
9239
+ /** A persisted rule. */
9240
+ var NcRuleSchema = NcRuleInputSchema.extend({
9241
+ id: string(),
9242
+ /** userId of the admin who created the rule (server-stamped caller). */
9243
+ createdBy: string(),
9244
+ createdAt: number(),
9245
+ updatedAt: number(),
9246
+ /**
9247
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
9248
+ * send time. Only a target's OWNER may add/remove its id (server-checked
9249
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
9250
+ */
9251
+ disabledTargetIds: array(string()).default([])
9252
+ });
9253
+ var NcTestResultSchema = object({
9254
+ recordId: string(),
9255
+ recordKind: _enum([
9256
+ "object-event",
9257
+ "track",
9258
+ "device-event",
9259
+ "package-event"
9260
+ ]),
9261
+ deviceId: number(),
9262
+ timestamp: number(),
9263
+ wouldFire: boolean(),
9264
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
9265
+ failedCondition: string().optional(),
9266
+ className: string().optional(),
9267
+ label: string().optional()
9268
+ });
9269
+ var NcConditionDescriptorSchema = object({
9270
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
9271
+ id: string(),
9272
+ group: _enum([
9273
+ "scope",
9274
+ "class",
9275
+ "zones",
9276
+ "quality",
9277
+ "label",
9278
+ "schedule",
9279
+ "device",
9280
+ "package",
9281
+ "occupancy"
9282
+ ]),
9283
+ label: string(),
9284
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
9285
+ valueType: _enum([
9286
+ "deviceIdList",
9287
+ "stringList",
9288
+ "number01",
9289
+ "number",
9290
+ "sourceSelect",
9291
+ "zoneSelection",
9292
+ "zoneIdList",
9293
+ "schedule",
9294
+ "plateMatcher",
9295
+ "packagePhase",
9296
+ "polygonDraw",
9297
+ "occupancy"
9298
+ ]),
9299
+ operator: _enum([
9300
+ "in",
9301
+ "notIn",
9302
+ "anyOf",
9303
+ "allOf",
9304
+ "gte",
9305
+ "fuzzyIn",
9306
+ "withinSchedule"
9307
+ ]),
9308
+ /** Which delivery kinds the condition applies to. */
9309
+ appliesTo: array(NcDeliverySchema),
9310
+ phase: string(),
9311
+ description: string().optional()
9085
9312
  });
9086
9313
  /**
9087
- * Per-camera audio metrics snapshotemitted by the analytics frame
9088
- * handler on every `pipeline.audio-inference-result` event and
9089
- * mirrored into the `audio-metrics` device-state slice. Symmetric
9090
- * with `zone-analytics` snapshots for video every consumer
9091
- * (admin UI panel, automations, alert rules) reads via the
9092
- * canonical `device.state.audioMetrics.value` reactive handle.
9314
+ * The delivery lifecycle status of a history row a straight read of the
9315
+ * durable outbox row's own status (single source of truth):
9316
+ * - `pending` enqueued, in-flight or retrying with backoff
9317
+ * - `sent` delivered (terminal)
9318
+ * - `dead` — dead-lettered after exhausting retries / a permanent
9319
+ * backend rejection / a deleted target (terminal; carries
9320
+ * the failure `error`)
9093
9321
  *
9094
- * Aggregates are computed over a rolling `windowSec` window
9095
- * (default 60s). Past that window, classes drop out of `byClass`
9096
- * and the level history shifts forward.
9322
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
9323
+ * user dimension (quiet hours / snooze) and are additive when they land.
9097
9324
  */
9098
- var AudioMetricsSnapshotSchema = object({
9099
- /** Wall-clock timestamp (ms) of the most recent audio window. */
9100
- ts: number().int(),
9101
- /** Sliding-window length (seconds) used for aggregation. */
9102
- windowSec: number().int().positive(),
9103
- /** Latest level reading from the most recent window. */
9104
- level: object({
9105
- rms: number(),
9106
- dbfs: number()
9107
- }),
9108
- /** Peak dBFS observed across the rolling window. */
9109
- peakDbfs: number(),
9110
- /** Mean dBFS across the rolling window. */
9111
- avgDbfs: number(),
9112
- /** Most recent above-threshold classification, or null on silence. */
9113
- current: object({
9114
- className: string(),
9115
- score: number().min(0).max(1),
9116
- timestamp: number().int()
9117
- }).nullable(),
9118
- /** Per-class summary across the rolling window — keys are
9119
- * `macroClass` strings (e.g. `dog_bark`, `speech`, `glass_break`). */
9120
- byClass: array(AudioClassSummarySchema).readonly()
9325
+ var NcHistoryStatusSchema = _enum([
9326
+ "pending",
9327
+ "sent",
9328
+ "dead"
9329
+ ]);
9330
+ /** The evaluated record kind a history row descends from (one per trigger). */
9331
+ var NcHistoryRecordKindSchema = _enum([
9332
+ "object-event",
9333
+ "track-end",
9334
+ "device-event",
9335
+ "package-event"
9336
+ ]);
9337
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
9338
+ var NcHistorySubjectSchema = object({
9339
+ className: string(),
9340
+ label: string().optional(),
9341
+ confidence: number().optional(),
9342
+ zones: array(string()),
9343
+ timestamp: number()
9121
9344
  });
9122
9345
  /**
9123
- * Audio-metrics history payload a series of `AudioMetricsHistoryPoint`
9124
- * samples capped at `maxPoints` (default 1024). When the requested
9125
- * `windowSec / sampleEveryMs` would exceed the cap, the provider
9126
- * subsamples by bucketed averaging and reports the effective sample
9127
- * spacing on `effectiveSampleEveryMs` so the UI can label the x-axis.
9346
+ * One delivery-history row. This is a read-only VIEW over the durable
9347
+ * outbox row (single source of truth the same row the drain loop drives;
9348
+ * NO second write path, so history can never drift from delivery state).
9349
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
9350
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
9351
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
9352
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
9353
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
9354
+ * P1 (admin scope only).
9128
9355
  */
9129
- var AudioMetricsHistorySchema = object({
9130
- points: array(object({
9131
- /** Wall-clock ms when this sample was recorded. */
9132
- ts: number().int(),
9133
- /** Instantaneous dBFS level at sample time. `null` for windows where
9134
- * the source had no level reading (rare; happens at decode startup). */
9135
- dbfs: number().nullable(),
9136
- /** Rolling-window peak dBFS at sample time. Same window the live
9137
- * snapshot reports. */
9138
- peakDbfs: number(),
9139
- /** Rolling-window mean dBFS at sample time. */
9140
- avgDbfs: number(),
9141
- /** Dominant above-threshold class at sample time, or null on silence. */
9142
- topClass: string().nullable(),
9143
- /** Score of the dominant class (`null` whenever `topClass` is null). */
9144
- topScore: number().min(0).max(1).nullable()
9145
- })).readonly(),
9146
- /** Actual ms between adjacent samples after any subsampling. */
9147
- effectiveSampleEveryMs: number().int().positive(),
9148
- /** Wall-clock window covered by `points` (`points[N-1].ts - points[0].ts`),
9149
- * or `0` when there's fewer than 2 samples. */
9150
- windowMsActual: number().int().nonnegative()
9151
- });
9152
- DeviceType.Camera, method(object({ deviceId: number() }), AudioMetricsSnapshotSchema.nullable()), method(object({
9356
+ var NcHistoryEntrySchema = object({
9357
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
9358
+ id: string(),
9359
+ ruleId: string(),
9360
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
9361
+ ruleName: string(),
9362
+ /** The rule urgency/trigger that produced this delivery. */
9363
+ delivery: NcDeliverySchema,
9364
+ targetId: string(),
9153
9365
  deviceId: number(),
9154
- /** History window in seconds. Default 300 (5 minutes).
9155
- * Provider clamps to its retention cap if larger. */
9156
- windowSec: number().int().positive().optional(),
9157
- /** Target sample interval in ms. Default 1000 (1 sample/second).
9158
- * Provider clamps to natural sample rate if smaller, and
9159
- * bucket-averages when bigger than the requested window
9160
- * would produce more than `maxPoints` samples. */
9161
- sampleEveryMs: number().int().positive().optional()
9162
- }), AudioMetricsHistorySchema);
9163
- object({
9164
- /** Whether the automation is currently enabled. Disabled automations
9165
- * ignore their trigger block — manual `trigger` still works. */
9166
- enabled: boolean(),
9167
- /** Whether the automation is currently executing its action block. */
9168
- isRunning: boolean(),
9169
- /** Ms epoch of the last successful run. 0 when never run. */
9170
- lastTriggeredAt: number(),
9171
- /** Failure description from the last completed run. Null on success
9172
- * or when never run. */
9173
- lastError: string().nullable(),
9174
- /** Ms epoch when the slice was last updated. */
9175
- lastChangedAt: number()
9366
+ recordKind: NcHistoryRecordKindSchema,
9367
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
9368
+ recordId: string(),
9369
+ /** Present for track-scoped deliveries (object-event / track-end). */
9370
+ trackId: string().optional(),
9371
+ status: NcHistoryStatusSchema,
9372
+ /** Delivery attempts made so far. */
9373
+ attempts: number().int(),
9374
+ /** Fire time (outbox enqueue). */
9375
+ createdAt: number(),
9376
+ /** Last transition time (terminal for sent / dead). */
9377
+ updatedAt: number(),
9378
+ /** Failure detail — present on a `dead` row. */
9379
+ error: string().optional(),
9380
+ subject: NcHistorySubjectSchema
9176
9381
  });
9177
- DeviceType.Automation, method(object({ deviceId: number().int().nonnegative() }), _void(), {
9178
- kind: "mutation",
9179
- auth: "admin"
9180
- }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
9382
+ /**
9383
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
9384
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
9385
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
9386
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
9387
+ */
9388
+ var NcHistoryFilterSchema = object({
9389
+ ruleId: string().optional(),
9390
+ deviceId: number().optional(),
9391
+ status: NcHistoryStatusSchema.optional(),
9392
+ since: number().optional(),
9393
+ until: number().optional(),
9394
+ limit: number().int().min(1).max(500).default(100)
9395
+ });
9396
+ 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 }), {
9181
9397
  kind: "mutation",
9182
- auth: "admin"
9398
+ auth: "admin",
9399
+ caller: "required"
9183
9400
  }), method(object({
9184
- deviceId: number().int().nonnegative(),
9185
- /** When true, fires the action block while bypassing the
9186
- * automation's condition evaluation. Gated by
9187
- * `DeviceFeature.AutomationSkipCondition`. */
9188
- skipCondition: boolean().optional()
9189
- }), _void(), {
9401
+ ruleId: string(),
9402
+ patch: NcRulePatchSchema
9403
+ }), object({ rule: NcRuleSchema }), {
9404
+ kind: "mutation",
9405
+ auth: "admin",
9406
+ caller: "required"
9407
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
9190
9408
  kind: "mutation",
9191
9409
  auth: "admin"
9192
- });
9410
+ }), method(object({
9411
+ ruleId: string(),
9412
+ enabled: boolean()
9413
+ }), object({ success: literal(true) }), {
9414
+ kind: "mutation",
9415
+ auth: "admin"
9416
+ }), method(object({
9417
+ rule: NcRuleInputSchema,
9418
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
9419
+ }), object({ results: array(NcTestResultSchema) }), {
9420
+ kind: "mutation",
9421
+ auth: "admin"
9422
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
9193
9423
  /**
9194
- * Battery status snapshot. Emitted by providers whose device is
9195
- * battery-operated (cameras with `DeviceFeature.BatteryOperated`,
9196
- * future sensor/button accessories). Consumers build their own "low
9197
- * battery" alerting on top — the cap deliberately does NOT enforce a
9198
- * threshold.
9424
+ * TimelapseRule the STANDALONE scheduled timelapse producer's rule model.
9425
+ *
9426
+ * Spec: `docs/superpowers/specs/2026-07-24-nc-occupancy-timelapse-design.md`
9427
+ * §3.2/§3.3.
9428
+ *
9429
+ * Deliberately NOT a capability definition and NOT an `NcRule`:
9430
+ * - Every `NcDelivery` member is a *persisted-pipeline-record* trigger. A
9431
+ * timelapse fires on a SCHEDULE WINDOW BOUNDARY, evaluates no pipeline
9432
+ * record, and produces a video it assembled itself — so it rides no
9433
+ * delivery-enum member (the enum is frozen) and no cap method. This file is
9434
+ * a plain typed schema; it does NOT go through `npm run codegen`.
9435
+ * - It shares only the delivery leg (`notification-output.send`) and the
9436
+ * persistence/ownership patterns with the Notification Center, reusing
9437
+ * {@link NcScheduleSchema} (weekly windows, midnight-crossing, invertible)
9438
+ * and {@link NcRuleTargetSchema} (target ref + passthrough params).
9439
+ *
9440
+ * Ownership is SERVER-DERIVED. `ownerUserId` / `createdBy` / `createdAt` /
9441
+ * `updatedAt` / `id` / `lastGeneratedAt` live on the PERSISTED rule only —
9442
+ * {@link TimelapseRuleInputSchema} and {@link TimelapseRulePatchSchema} do not
9443
+ * carry them, so a forged client payload can never claim or re-own a rule
9444
+ * (Zod strips unknown keys). The store stamps them from the resolved caller.
9199
9445
  */
9200
- var BatteryStatusSchema = object({
9201
- /** 0..100 inclusive. Firmware-reported. */
9202
- percentage: number().min(0).max(100),
9446
+ /** `{{var}}` templating over camera/rule/time — same vocabulary as `NcRule`. */
9447
+ var TimelapseTemplateSchema = object({
9448
+ title: string().max(500).optional(),
9449
+ body: string().max(2e3).optional()
9450
+ });
9451
+ var NameField = string().min(1).max(200);
9452
+ var DeviceIdsField = array(number()).min(1);
9453
+ var CadenceSecField = number().int().min(2).max(3600);
9454
+ var FramerateField = number().int().min(1).max(60);
9455
+ var TargetsField = array(NcRuleTargetSchema).min(1);
9456
+ var PriorityField = number().int().min(1).max(5);
9457
+ /**
9458
+ * Client-supplied timelapse-rule fields. The server stamps id / createdBy /
9459
+ * createdAt / updatedAt / ownerUserId / lastGeneratedAt — none of them appear
9460
+ * here (see the ownership note above).
9461
+ */
9462
+ var TimelapseRuleInputSchema = object({
9463
+ name: NameField,
9464
+ enabled: boolean().default(true),
9465
+ /** Cameras sampled by this rule — one scratch dir + one artifact per device. */
9466
+ deviceIds: DeviceIdsField,
9203
9467
  /**
9204
- * Charging source. `'dc'` covers wall/USB adapters; `'solar'` is
9205
- * Reolink-specific for the Solar Panel 2 accessory (will become
9206
- * common on other battery cams). `'none'` means running on battery
9207
- * alone.
9468
+ * Activation window(s). REQUIRED (unlike `NcRule`, where an absent schedule
9469
+ * means "always active"): a timelapse is defined by its window boundaries —
9470
+ * open clears the scratch, close assembles and delivers.
9208
9471
  */
9209
- charging: _enum([
9210
- "dc",
9211
- "solar",
9212
- "none"
9213
- ]),
9472
+ schedule: NcScheduleSchema,
9473
+ /** Force-snapshot cadence inside the window, seconds (predecessor parity). */
9474
+ cadenceSec: CadenceSecField.default(15),
9475
+ /** Output frames per second of the assembled mp4 (predecessor parity). */
9476
+ framerate: FramerateField.default(10),
9477
+ /** `notification-output` targets the finished video/thumbnail is sent to. */
9478
+ targets: TargetsField,
9479
+ template: TimelapseTemplateSchema.optional(),
9480
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
9481
+ priority: PriorityField.default(3)
9482
+ });
9483
+ object({
9484
+ name: NameField.optional(),
9485
+ enabled: boolean().optional(),
9486
+ deviceIds: DeviceIdsField.optional(),
9487
+ schedule: NcScheduleSchema.optional(),
9488
+ cadenceSec: CadenceSecField.optional(),
9489
+ framerate: FramerateField.optional(),
9490
+ targets: TargetsField.optional(),
9491
+ template: TimelapseTemplateSchema.nullable().optional(),
9492
+ priority: PriorityField.optional()
9493
+ });
9494
+ TimelapseRuleInputSchema.extend({
9495
+ id: string(),
9214
9496
  /**
9215
- * True when the camera firmware has gone into low-power mode. Battery
9216
- * providers MUST avoid polling during sleep reading the battery
9217
- * wakes the camera up and drains charge.
9497
+ * Ownership/visibility key. Absent = admin/global rule (visible to all).
9498
+ * Present = personal rule owned by this userId. Server-stamped from the
9499
+ * resolved caller; never trusted from a client payload.
9218
9500
  */
9219
- sleeping: boolean(),
9220
- /** Ms epoch of the last observation. Lets consumers reason about freshness. */
9221
- lastUpdated: number(),
9501
+ ownerUserId: string().optional(),
9222
9502
  /**
9223
- * True when the source is a BINARY low-battery indicator (HA
9224
- * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
9225
- * charge level — `percentage` is then a coarse stand-in (100 = normal,
9226
- * sub-threshold = low). UI MUST render "Normal"/"Low" instead of a
9227
- * misleading exact percentage. Absent/false → genuine 0–100 % reading.
9503
+ * Epoch-ms of the last successful generation the 1-hour re-generation
9504
+ * guard's durable state (predecessor parity). Absent = never generated.
9228
9505
  */
9229
- binary: boolean().optional()
9506
+ lastGeneratedAt: number().optional(),
9507
+ /** userId of the caller who created the rule (server-stamped). */
9508
+ createdBy: string(),
9509
+ createdAt: number(),
9510
+ updatedAt: number()
9230
9511
  });
9231
- DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch, method(object({
9512
+ /**
9513
+ * Generic device-level status snapshot. Auto-registered by `BaseDevice`
9514
+ * for every device, regardless of provider — the kernel needs a uniform
9515
+ * cap-keyed slice for the basic device flags every consumer expects to
9516
+ * read across processes (the `online` flag in particular). Driver-specific
9517
+ * caps (`battery`, `doorbell`, …) carry their domain-specific state on
9518
+ * their own slices.
9519
+ *
9520
+ * Pattern is identical to `battery`: schema-bearing `runtimeState`,
9521
+ * empty `methods`, single change event. Reads land at
9522
+ * `runtimeState.getCapState('device-status')`; writes at
9523
+ * `runtimeState.setCapState('device-status', …)`. Cross-process
9524
+ * consumers reach the same data via the `device-state` cap router
9525
+ * (`getCapSlice({deviceId, capName: 'device-status'})`).
9526
+ */
9527
+ var DeviceStatusSchema = object({
9528
+ /**
9529
+ * Device-level liveness. Drivers flip via `markOnline(boolean)` on
9530
+ * `BaseDevice`. Provider semantics vary — RTSP aggregates broker
9531
+ * stream-health, Reolink reads firmware push events, ONVIF tracks
9532
+ * ping responses. This cap intentionally does NOT prescribe which
9533
+ * signal drives the flag.
9534
+ */
9535
+ online: boolean(),
9536
+ /** Ms epoch of the last `online` transition. Lets consumers tell
9537
+ * apart "just came online" from "still online". */
9538
+ lastChangedAt: number()
9539
+ });
9540
+ object({
9232
9541
  deviceId: number(),
9233
- /** Bound on the wait. Sensible range 3000–10000ms. */
9234
- timeoutMs: number().int().min(500).max(3e4).default(8e3)
9235
- }), object({
9236
- awoke: boolean(),
9237
- durationMs: number()
9238
- }), { kind: "mutation" }), object({
9542
+ status: DeviceStatusSchema
9543
+ });
9544
+ /**
9545
+ * Per-device feature/identity probe slice. Holds the runtime-resolved
9546
+ * truth about what a device CAN do — which the kernel uses to:
9547
+ * 1. Reconcile accessory children (hub-children spawn siren/floodlight/PIR
9548
+ * based on what the firmware actually advertises).
9549
+ * 2. Compute the public `features: DeviceFeature[]` array surfaced via
9550
+ * `device-manager.listAll`.
9551
+ * 3. Decide which optional caps (PTZ, intercom, doorbell, battery, …)
9552
+ * to register on the device's capability surface.
9553
+ *
9554
+ * Auto-registered by `BaseDevice` for every device. Drivers populate the
9555
+ * slice from `onProbe()` (kernel calls it once after register, before
9556
+ * accessory reconciliation). Consumers read via:
9557
+ * `runtimeState.getCapState<FeatureProbeStatus>('feature-probe')`
9558
+ *
9559
+ * `flags` is an open record so each driver carries its own keys without
9560
+ * a centralized schema bottleneck — Reolink writes `hasPtz/hasIntercom`,
9561
+ * Hikvision writes `hasSupplementalLight/hasAlarmIo`, etc.
9562
+ *
9563
+ * Replaces the older driver-local `deviceCache.has*` blob: the per-device
9564
+ * config is for operator-edited overrides + UI snapshots; runtime probe
9565
+ * results belong in runtime-state where the kernel handles persistence,
9566
+ * cross-process mirroring, and reactive updates.
9567
+ */
9568
+ var FeatureProbeStatusSchema = object({
9569
+ /**
9570
+ * Driver-specific flag bag. Each driver picks its own key names — the
9571
+ * cap deliberately does NOT enforce a closed enum here. Reolink keys:
9572
+ * `hasPtz`, `hasIntercom`, `hasDoorbell`, `hasFloodlight`, `hasSiren`,
9573
+ * `hasPirSensor`, `hasAutotrack`, `hasBattery`. Hikvision keys:
9574
+ * `hasSupplementalLight`, `lightHasWhiteLight`, `hasAlarmIo`, `hasPtz`.
9575
+ */
9576
+ flags: record(string(), unknown()),
9577
+ /**
9578
+ * Coarse driver-classification — lets cross-process consumers tell apart
9579
+ * cameras / battery-cams / NVRs without re-running the probe. `null`
9580
+ * before the first probe completes.
9581
+ */
9582
+ deviceType: string().nullable(),
9583
+ /** Camera/firmware model string. `null` when the firmware doesn't expose it. */
9584
+ model: string().nullable(),
9585
+ /** Channel count for NVR/Hub devices; `1` for standalone cameras; `null` pre-probe. */
9586
+ channelCount: number().nullable(),
9587
+ /**
9588
+ * Ms epoch of the last SUCCESSFUL probe. `0` before the first probe
9589
+ * completes — drivers' `getAccessoryChildren()` should treat zero as
9590
+ * "probe not done yet, return empty" so accessories aren't spawned
9591
+ * before the firmware is queried.
9592
+ */
9593
+ lastProbedAt: number(),
9594
+ /**
9595
+ * Framework convention: every runtime-state slice carries this for the
9596
+ * createRuntimeStateBridge stale-check helper. We keep it in sync with
9597
+ * `lastProbedAt` on every write.
9598
+ */
9599
+ lastFetchedAt: number()
9600
+ });
9601
+ object({
9239
9602
  deviceId: number(),
9240
- status: BatteryStatusSchema
9603
+ status: FeatureProbeStatusSchema
9241
9604
  });
9242
9605
  object({
9243
- on: boolean(),
9244
- /** Ms epoch of the last transition. 0 if never observed. */
9245
- lastChangedAt: number()
9606
+ /** Carbon dioxide concentration in ppm. */
9607
+ co2Ppm: number().min(0).optional(),
9608
+ /** Total volatile organic compounds in ppb. */
9609
+ vocPpb: number().min(0).optional(),
9610
+ /** Particulate matter ≤ 2.5 μm in µg/m³. */
9611
+ pm25: number().min(0).optional(),
9612
+ /** Particulate matter ≤ 10 μm in µg/m³. */
9613
+ pm10: number().min(0).optional(),
9614
+ /** Composite AQI value (typically 0..500). */
9615
+ aqi: number().optional(),
9616
+ /** Ms epoch when the slice was last updated. */
9617
+ lastFetchedAt: number(),
9618
+ /** Live display unit of the single metric this slice carries (e.g. HA
9619
+ * `attributes.unit_of_measurement` → 'ppm' / 'ppb' / 'µg/m³'). Each
9620
+ * upstream `sensor.*` entity surfaces ONE device_class, so one unit
9621
+ * per slice is unambiguous. */
9622
+ unit: string().optional(),
9623
+ /** Suggested decimal places for numeric display.
9624
+ * Populated live from the upstream source when provided (e.g. HA
9625
+ * `attributes.suggested_display_precision`). Falls back to
9626
+ * auto-formatting when absent. */
9627
+ precision: number().int().min(0).max(10).optional()
9246
9628
  });
9247
9629
  DeviceType.Sensor;
9630
+ /**
9631
+ * Alarm-panel cap. Models HA `alarm_control_panel.*` on
9632
+ * `DeviceType.AlarmPanel`. State follows HA's canonical lifecycle
9633
+ * across disarmed / armed_(home|away|night|vacation|custom_bypass) /
9634
+ * arming / pending / triggered / disarming.
9635
+ *
9636
+ * Many panels require a PIN code on arm / disarm — the optional
9637
+ * `code` field on the methods passes it through to the upstream
9638
+ * service; it's NEVER persisted in the runtime slice or any event
9639
+ * payload. The presence of a required code is signalled by
9640
+ * `DeviceFeature.AlarmPinRequired` so the UI gates a code-entry
9641
+ * field without a slice fetch.
9642
+ *
9643
+ * `availableModes` mirrors HA's `supported_features`-derived arm
9644
+ * mode list — the UI renders only the buttons the panel accepts.
9645
+ */
9646
+ var AlarmStateSchema = _enum([
9647
+ "disarmed",
9648
+ "armed_home",
9649
+ "armed_away",
9650
+ "armed_night",
9651
+ "armed_vacation",
9652
+ "armed_custom_bypass",
9653
+ "arming",
9654
+ "disarming",
9655
+ "pending",
9656
+ "triggered"
9657
+ ]);
9658
+ var AlarmArmModeSchema = _enum([
9659
+ "home",
9660
+ "away",
9661
+ "night",
9662
+ "vacation",
9663
+ "custom_bypass"
9664
+ ]);
9248
9665
  object({
9249
- /** Current level as 0..100 inclusive. Firmware-reported. */
9250
- percentage: number().min(0).max(100),
9251
- /** Ms epoch of the last operator-driven change. Useful for UI freshness. */
9666
+ /** Current lifecycle state. */
9667
+ state: AlarmStateSchema,
9668
+ /** Subset of arm modes the panel accepts. UI renders one button per
9669
+ * mode in this list. */
9670
+ availableModes: array(AlarmArmModeSchema),
9671
+ /** Whether the panel requires a PIN on arm / disarm. Mirrors
9672
+ * `DeviceFeature.AlarmPinRequired` for slice consumers. */
9673
+ requiresCode: boolean(),
9674
+ /** Ms epoch when the slice was last updated. */
9252
9675
  lastChangedAt: number()
9253
9676
  });
9254
- DeviceType.Light, method(object({
9677
+ DeviceType.AlarmPanel, method(object({
9255
9678
  deviceId: number().int().nonnegative(),
9256
- percentage: number().min(0).max(100)
9679
+ mode: AlarmArmModeSchema,
9680
+ /** Optional PIN code. Required when `requiresCode === true`.
9681
+ * Passed through to the upstream service; never persisted. */
9682
+ code: string().min(1).optional()
9257
9683
  }), _void(), {
9258
9684
  kind: "mutation",
9259
9685
  auth: "admin"
9260
- }), object({
9261
- deviceId: number(),
9262
- percentage: number().min(0).max(100),
9263
- lastChangedAt: number()
9264
- });
9265
- /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
9266
- var StreamFormatSchema = _enum([
9267
- "webrtc",
9686
+ }), method(object({
9687
+ deviceId: number().int().nonnegative(),
9688
+ code: string().min(1).optional()
9689
+ }), _void(), {
9690
+ kind: "mutation",
9691
+ auth: "admin"
9692
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
9693
+ kind: "mutation",
9694
+ auth: "admin"
9695
+ });
9696
+ object({
9697
+ /** Current illuminance in lux (lx). */
9698
+ lux: number().min(0),
9699
+ /** Ms epoch when the slice was last updated. */
9700
+ lastFetchedAt: number(),
9701
+ /** Live display unit from the upstream source (e.g. HA
9702
+ * `attributes.unit_of_measurement`). The UI prefers this over the
9703
+ * role's canonical unit. Absent → fall back to the canonical unit. */
9704
+ unit: string().optional(),
9705
+ /** Suggested decimal places for numeric display.
9706
+ * Populated live from the upstream source when provided (e.g. HA
9707
+ * `attributes.suggested_display_precision`). Falls back to
9708
+ * auto-formatting when absent. */
9709
+ precision: number().int().min(0).max(10).optional()
9710
+ });
9711
+ DeviceType.Sensor;
9712
+ /**
9713
+ * Per-class audio metrics aggregated over a sliding window.
9714
+ */
9715
+ var AudioClassSummarySchema = object({
9716
+ className: string(),
9717
+ /** Number of windows (chunks) where this class was the top hit. */
9718
+ hits: number().int().nonnegative(),
9719
+ /** Mean score across those hits, clamped to [0,1]. */
9720
+ avgScore: number().min(0).max(1),
9721
+ /** Peak score in the window. */
9722
+ peakScore: number().min(0).max(1)
9723
+ });
9724
+ /**
9725
+ * Per-camera audio metrics snapshot — emitted by the analytics frame
9726
+ * handler on every `pipeline.audio-inference-result` event and
9727
+ * mirrored into the `audio-metrics` device-state slice. Symmetric
9728
+ * with `zone-analytics` snapshots for video — every consumer
9729
+ * (admin UI panel, automations, alert rules) reads via the
9730
+ * canonical `device.state.audioMetrics.value` reactive handle.
9731
+ *
9732
+ * Aggregates are computed over a rolling `windowSec` window
9733
+ * (default 60s). Past that window, classes drop out of `byClass`
9734
+ * and the level history shifts forward.
9735
+ */
9736
+ var AudioMetricsSnapshotSchema = object({
9737
+ /** Wall-clock timestamp (ms) of the most recent audio window. */
9738
+ ts: number().int(),
9739
+ /** Sliding-window length (seconds) used for aggregation. */
9740
+ windowSec: number().int().positive(),
9741
+ /** Latest level reading from the most recent window. */
9742
+ level: object({
9743
+ rms: number(),
9744
+ dbfs: number()
9745
+ }),
9746
+ /** Peak dBFS observed across the rolling window. */
9747
+ peakDbfs: number(),
9748
+ /** Mean dBFS across the rolling window. */
9749
+ avgDbfs: number(),
9750
+ /** Most recent above-threshold classification, or null on silence. */
9751
+ current: object({
9752
+ className: string(),
9753
+ score: number().min(0).max(1),
9754
+ timestamp: number().int()
9755
+ }).nullable(),
9756
+ /** Per-class summary across the rolling window — keys are
9757
+ * `macroClass` strings (e.g. `dog_bark`, `speech`, `glass_break`). */
9758
+ byClass: array(AudioClassSummarySchema).readonly()
9759
+ });
9760
+ /**
9761
+ * Audio-metrics history payload — a series of `AudioMetricsHistoryPoint`
9762
+ * samples capped at `maxPoints` (default 1024). When the requested
9763
+ * `windowSec / sampleEveryMs` would exceed the cap, the provider
9764
+ * subsamples by bucketed averaging and reports the effective sample
9765
+ * spacing on `effectiveSampleEveryMs` so the UI can label the x-axis.
9766
+ */
9767
+ var AudioMetricsHistorySchema = object({
9768
+ points: array(object({
9769
+ /** Wall-clock ms when this sample was recorded. */
9770
+ ts: number().int(),
9771
+ /** Instantaneous dBFS level at sample time. `null` for windows where
9772
+ * the source had no level reading (rare; happens at decode startup). */
9773
+ dbfs: number().nullable(),
9774
+ /** Rolling-window peak dBFS at sample time. Same window the live
9775
+ * snapshot reports. */
9776
+ peakDbfs: number(),
9777
+ /** Rolling-window mean dBFS at sample time. */
9778
+ avgDbfs: number(),
9779
+ /** Dominant above-threshold class at sample time, or null on silence. */
9780
+ topClass: string().nullable(),
9781
+ /** Score of the dominant class (`null` whenever `topClass` is null). */
9782
+ topScore: number().min(0).max(1).nullable()
9783
+ })).readonly(),
9784
+ /** Actual ms between adjacent samples after any subsampling. */
9785
+ effectiveSampleEveryMs: number().int().positive(),
9786
+ /** Wall-clock window covered by `points` (`points[N-1].ts - points[0].ts`),
9787
+ * or `0` when there's fewer than 2 samples. */
9788
+ windowMsActual: number().int().nonnegative()
9789
+ });
9790
+ DeviceType.Camera, method(object({ deviceId: number() }), AudioMetricsSnapshotSchema.nullable()), method(object({
9791
+ deviceId: number(),
9792
+ /** History window in seconds. Default 300 (5 minutes).
9793
+ * Provider clamps to its retention cap if larger. */
9794
+ windowSec: number().int().positive().optional(),
9795
+ /** Target sample interval in ms. Default 1000 (1 sample/second).
9796
+ * Provider clamps to natural sample rate if smaller, and
9797
+ * bucket-averages when bigger than the requested window
9798
+ * would produce more than `maxPoints` samples. */
9799
+ sampleEveryMs: number().int().positive().optional()
9800
+ }), AudioMetricsHistorySchema);
9801
+ object({
9802
+ /** Whether the automation is currently enabled. Disabled automations
9803
+ * ignore their trigger block — manual `trigger` still works. */
9804
+ enabled: boolean(),
9805
+ /** Whether the automation is currently executing its action block. */
9806
+ isRunning: boolean(),
9807
+ /** Ms epoch of the last successful run. 0 when never run. */
9808
+ lastTriggeredAt: number(),
9809
+ /** Failure description from the last completed run. Null on success
9810
+ * or when never run. */
9811
+ lastError: string().nullable(),
9812
+ /** Ms epoch when the slice was last updated. */
9813
+ lastChangedAt: number()
9814
+ });
9815
+ DeviceType.Automation, method(object({ deviceId: number().int().nonnegative() }), _void(), {
9816
+ kind: "mutation",
9817
+ auth: "admin"
9818
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
9819
+ kind: "mutation",
9820
+ auth: "admin"
9821
+ }), method(object({
9822
+ deviceId: number().int().nonnegative(),
9823
+ /** When true, fires the action block while bypassing the
9824
+ * automation's condition evaluation. Gated by
9825
+ * `DeviceFeature.AutomationSkipCondition`. */
9826
+ skipCondition: boolean().optional()
9827
+ }), _void(), {
9828
+ kind: "mutation",
9829
+ auth: "admin"
9830
+ });
9831
+ /**
9832
+ * Battery status snapshot. Emitted by providers whose device is
9833
+ * battery-operated (cameras with `DeviceFeature.BatteryOperated`,
9834
+ * future sensor/button accessories). Consumers build their own "low
9835
+ * battery" alerting on top — the cap deliberately does NOT enforce a
9836
+ * threshold.
9837
+ */
9838
+ var BatteryStatusSchema = object({
9839
+ /** 0..100 inclusive. Firmware-reported. */
9840
+ percentage: number().min(0).max(100),
9841
+ /**
9842
+ * Charging source. `'dc'` covers wall/USB adapters; `'solar'` is
9843
+ * Reolink-specific for the Solar Panel 2 accessory (will become
9844
+ * common on other battery cams). `'none'` means running on battery
9845
+ * alone.
9846
+ */
9847
+ charging: _enum([
9848
+ "dc",
9849
+ "solar",
9850
+ "none"
9851
+ ]),
9852
+ /**
9853
+ * True when the camera firmware has gone into low-power mode. Battery
9854
+ * providers MUST avoid polling during sleep — reading the battery
9855
+ * wakes the camera up and drains charge.
9856
+ */
9857
+ sleeping: boolean(),
9858
+ /** Ms epoch of the last observation. Lets consumers reason about freshness. */
9859
+ lastUpdated: number(),
9860
+ /**
9861
+ * True when the source is a BINARY low-battery indicator (HA
9862
+ * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
9863
+ * charge level — `percentage` is then a coarse stand-in (100 = normal,
9864
+ * sub-threshold = low). UI MUST render "Normal"/"Low" instead of a
9865
+ * misleading exact percentage. Absent/false → genuine 0–100 % reading.
9866
+ */
9867
+ binary: boolean().optional()
9868
+ });
9869
+ DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch, method(object({
9870
+ deviceId: number(),
9871
+ /** Bound on the wait. Sensible range 3000–10000ms. */
9872
+ timeoutMs: number().int().min(500).max(3e4).default(8e3)
9873
+ }), object({
9874
+ awoke: boolean(),
9875
+ durationMs: number()
9876
+ }), { kind: "mutation" }), object({
9877
+ deviceId: number(),
9878
+ status: BatteryStatusSchema
9879
+ });
9880
+ object({
9881
+ on: boolean(),
9882
+ /** Ms epoch of the last transition. 0 if never observed. */
9883
+ lastChangedAt: number()
9884
+ });
9885
+ DeviceType.Sensor;
9886
+ object({
9887
+ /** Current level as 0..100 inclusive. Firmware-reported. */
9888
+ percentage: number().min(0).max(100),
9889
+ /** Ms epoch of the last operator-driven change. Useful for UI freshness. */
9890
+ lastChangedAt: number()
9891
+ });
9892
+ DeviceType.Light, method(object({
9893
+ deviceId: number().int().nonnegative(),
9894
+ percentage: number().min(0).max(100)
9895
+ }), _void(), {
9896
+ kind: "mutation",
9897
+ auth: "admin"
9898
+ }), object({
9899
+ deviceId: number(),
9900
+ percentage: number().min(0).max(100),
9901
+ lastChangedAt: number()
9902
+ });
9903
+ /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
9904
+ var StreamFormatSchema = _enum([
9905
+ "webrtc",
9268
9906
  "hls",
9269
9907
  "mjpeg",
9270
9908
  "rtsp"
@@ -11851,84 +12489,23 @@ DeviceType.Light, DeviceType.Siren, DeviceType.Switch, method(object({
11851
12489
  lastChangedAt: number()
11852
12490
  });
11853
12491
  /**
11854
- * Shared geometry vocabulary for on-frame shape caps privacy-mask,
11855
- * motion-zones, and the detection zones/lines editor all speak this one
11856
- * language so a single drawing-plane editor and the providers stay
11857
- * decoupled from each cap's storage.
11858
- *
11859
- * All coordinates are normalized 0..1 of the camera frame (top-left
11860
- * origin). Each cap composes the SUBSET of shape kinds it supports and
11861
- * advertises it via `supportedShapes` in its `getOptions`.
12492
+ * Motion-zones share the same MaskShape vocabulary as privacy-mask — the
12493
+ * on-camera motion-detection mask is a single `grid` region (a row-major
12494
+ * boolean cell lattice the camera's onboard VMD evaluates). Composing it as
12495
+ * a region keeps one drawing-plane model across all geometry caps.
11862
12496
  */
11863
- /** A normalized 0..1 point (top-left origin). */
11864
- var MaskPointSchema = object({
11865
- x: number(),
11866
- y: number()
12497
+ /** A motion-zone region exactly one boolean cell grid today. */
12498
+ var MotionZoneRegionSchema = object({
12499
+ id: number(),
12500
+ enabled: boolean(),
12501
+ shape: MaskGridShapeSchema
11867
12502
  });
11868
- /** Axis-aligned rectangle (normalized 0..1). */
11869
- var MaskRectShapeSchema = object({
11870
- kind: literal("rect"),
11871
- x: number(),
11872
- y: number(),
11873
- width: number(),
11874
- height: number()
11875
- });
11876
- /** Free polygon — an ordered list of normalized vertices (≥3). */
11877
- var MaskPolygonShapeSchema = object({
11878
- kind: literal("polygon"),
11879
- points: array(MaskPointSchema)
11880
- });
11881
- /** Boolean cell grid — row-major, length === gridWidth*gridHeight. */
11882
- var MaskGridShapeSchema = object({
11883
- kind: literal("grid"),
11884
- gridWidth: number(),
11885
- gridHeight: number(),
11886
- cells: array(boolean())
11887
- });
11888
- discriminatedUnion("kind", [
11889
- MaskRectShapeSchema,
11890
- MaskPolygonShapeSchema,
11891
- MaskGridShapeSchema,
11892
- object({
11893
- kind: literal("line"),
11894
- points: array(MaskPointSchema)
11895
- })
11896
- ]);
11897
- /** Every shape-kind discriminant, for `supportedShapes` advertisement. */
11898
- var MaskShapeKindSchema = _enum([
11899
- "rect",
11900
- "polygon",
11901
- "grid",
11902
- "line"
11903
- ]);
11904
- /** Polygon vertex bounds when a cap supports 'polygon' (e.g. Hikvision {min:4,max:4}). */
11905
- var MaskPolygonVerticesSchema = object({
11906
- min: number(),
11907
- max: number()
11908
- });
11909
- /** Grid dimensions when a cap supports 'grid'. */
11910
- var MaskGridDimsSchema = object({
11911
- width: number(),
11912
- height: number()
11913
- });
11914
- /**
11915
- * Motion-zones share the same MaskShape vocabulary as privacy-mask — the
11916
- * on-camera motion-detection mask is a single `grid` region (a row-major
11917
- * boolean cell lattice the camera's onboard VMD evaluates). Composing it as
11918
- * a region keeps one drawing-plane model across all geometry caps.
11919
- */
11920
- /** A motion-zone region — exactly one boolean cell grid today. */
11921
- var MotionZoneRegionSchema = object({
11922
- id: number(),
11923
- enabled: boolean(),
11924
- shape: MaskGridShapeSchema
11925
- });
11926
- object({
11927
- enabled: boolean(),
11928
- sensitivity: number(),
11929
- /** Grid region(s). Today exactly one `grid` shape. */
11930
- regions: array(MotionZoneRegionSchema),
11931
- lastFetchedAt: number()
12503
+ object({
12504
+ enabled: boolean(),
12505
+ sensitivity: number(),
12506
+ /** Grid region(s). Today exactly one `grid` shape. */
12507
+ regions: array(MotionZoneRegionSchema),
12508
+ lastFetchedAt: number()
11932
12509
  });
11933
12510
  /** Per-camera availability — grid dims are fixed per camera model; the UI
11934
12511
  * sizes its editor from `grid`. */
@@ -13780,6 +14357,55 @@ method(object({
13780
14357
  password: string()
13781
14358
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
13782
14359
  /**
14360
+ * A live terminal session hosted by the provider addon. Output and input do
14361
+ * NOT flow through the capability — they use the addon data plane
14362
+ * (`GET /addon/terminal/<id>/out` SSE, `POST /addon/terminal/<id>/in`) because
14363
+ * terminal output must be ordered and lossless. The event bus is telemetry and
14364
+ * may drop chunks ([D8]), and a dropped chunk desynchronises the vt parser
14365
+ * permanently until a full repaint. The capability owns only lifecycle.
14366
+ */
14367
+ var TerminalSessionInfoSchema = object({
14368
+ /** Opaque session id minted by the provider on `openSession`. */
14369
+ sessionId: string(),
14370
+ /** The pre-declared profile this session runs (never a free-form command). */
14371
+ profileId: string(),
14372
+ /** Human-readable profile label for the UI session list. */
14373
+ label: string(),
14374
+ cols: number().int().positive(),
14375
+ rows: number().int().positive(),
14376
+ /** ms-epoch the session's pty was spawned. */
14377
+ startedAt: number()
14378
+ });
14379
+ /**
14380
+ * A profile the operator may open — a pre-declared, allowlisted program
14381
+ * (`monitor` → `btm`). The capability accepts only these ids; a free-form
14382
+ * command string would be remote code execution as the server's user, so it is
14383
+ * deliberately not part of the contract.
14384
+ */
14385
+ var TerminalProfileInfoSchema = object({
14386
+ profileId: string(),
14387
+ label: string(),
14388
+ description: string().optional()
14389
+ });
14390
+ method(_void(), array(TerminalProfileInfoSchema).readonly(), { auth: "admin" }), method(_void(), array(TerminalSessionInfoSchema).readonly(), { auth: "admin" }), method(object({
14391
+ profileId: string(),
14392
+ cols: number().int().positive(),
14393
+ rows: number().int().positive()
14394
+ }), TerminalSessionInfoSchema, {
14395
+ kind: "mutation",
14396
+ auth: "admin"
14397
+ }), method(object({
14398
+ sessionId: string(),
14399
+ cols: number().int().positive(),
14400
+ rows: number().int().positive()
14401
+ }), _void(), {
14402
+ kind: "mutation",
14403
+ auth: "admin"
14404
+ }), method(object({ sessionId: string() }), _void(), {
14405
+ kind: "mutation",
14406
+ auth: "admin"
14407
+ });
14408
+ /**
13783
14409
  * Orchestrator-side destination metadata. The orchestrator computes
13784
14410
  * `id = <addonId>:<subId>` from its provider lookup so consumers
13785
14411
  * (admin UI, restore flow) see one canonical key.
@@ -14736,1809 +15362,1321 @@ var StreamProbeResultSchema = object({
14736
15362
  codec: string().optional(),
14737
15363
  fps: number().optional(),
14738
15364
  bitrateKbps: number().optional()
14739
- });
14740
- var DeviceRegisterPayloadSchema = object({
14741
- addonId: string(),
14742
- stableId: string(),
14743
- /** Pre-allocated numeric id from `allocateDeviceId`. The hub persists
14744
- * it alongside the meta record; callers never invent this value. */
14745
- id: number(),
14746
- type: string(),
14747
- name: string(),
14748
- /** Operator-organisational location label. Optional on register —
14749
- * the hub seeds `null` when omitted. */
14750
- location: string().nullable().optional(),
14751
- /** Soft-disabled flag. Optional on register — the hub seeds `false`. */
14752
- disabled: boolean().optional(),
14753
- parentDeviceId: number().nullable(),
14754
- /** Optional semantic role — see `DeviceRole`. Driver authors pass this
14755
- * at register time when the device is an accessory with a known role. */
14756
- role: string().nullable().optional(),
14757
- /** Snapshot of `device.features` at registration time. Persisted in
14758
- * `DeviceMeta` so the hub can answer `getDevice` for forked-worker
14759
- * devices with the right `DeviceFeature[]` even when the live
14760
- * instance lives on a remote node. Re-published on every register
14761
- * call (workers re-register on init), so probe-driven updates
14762
- * (e.g. PTZ flag flipping after the abilities probe) propagate. */
14763
- features: array(string()).optional(),
14764
- config: record(string(), unknown())
14765
- });
14766
- var DeviceRemovePayloadSchema = object({ deviceId: number() });
14767
- var DevicePersistConfigPayloadSchema = object({
14768
- deviceId: number(),
14769
- data: record(string(), unknown())
14770
- });
14771
- method(object({
14772
- addonId: string(),
14773
- stableId: string()
14774
- }), object({ id: number() }), { kind: "mutation" }), method(DeviceRegisterPayloadSchema, _void(), { kind: "mutation" }), method(DeviceRemovePayloadSchema, _void(), { kind: "mutation" }), method(DevicePersistConfigPayloadSchema, _void(), { kind: "mutation" }), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), DeviceMetaSchema.nullable()), method(object({
14775
- deviceId: number(),
14776
- name: string()
14777
- }), _void(), {
14778
- kind: "mutation",
14779
- auth: "admin"
14780
- }), method(object({
14781
- deviceId: number(),
14782
- location: string().nullable()
14783
- }), _void(), {
14784
- kind: "mutation",
14785
- auth: "admin"
14786
- }), method(object({
14787
- deviceId: number(),
14788
- type: _enum(DeviceType)
14789
- }), _void(), {
14790
- kind: "mutation",
14791
- auth: "admin"
14792
- }), method(object({
14793
- deviceId: number(),
14794
- integrationId: string()
14795
- }), _void(), {
14796
- kind: "mutation",
14797
- auth: "admin"
14798
- }), method(object({
14799
- deviceId: number(),
14800
- linkDeviceId: number().nullable()
14801
- }), _void(), {
14802
- kind: "mutation",
14803
- auth: "admin"
14804
- }), method(object({
14805
- deviceId: number(),
14806
- primaryChildEntityId: string().nullable()
14807
- }), _void(), {
14808
- kind: "mutation",
14809
- auth: "admin"
14810
- }), method(object({
14811
- deviceId: number(),
14812
- childLayout: array(ChildLayoutEntrySchema).readonly()
14813
- }), _void(), {
14814
- kind: "mutation",
14815
- auth: "admin"
14816
- }), method(object({
14817
- deviceId: number(),
14818
- deviceLinks: array(DeviceLinkSchema).readonly()
14819
- }), _void(), {
14820
- kind: "mutation",
14821
- auth: "admin"
14822
- }), method(object({
14823
- deviceId: number(),
14824
- display: DeviceDisplayOverrideSchema.nullable()
14825
- }), _void(), {
14826
- kind: "mutation",
14827
- auth: "admin"
14828
- }), method(object({}), object({ defaults: record(string(), RoleDisplayDefaultSchema) }), { kind: "query" }), method(object({ defaults: record(string(), RoleDisplayDefaultSchema) }), _void(), {
14829
- kind: "mutation",
14830
- auth: "admin"
14831
- }), method(object({
14832
- deviceId: number(),
14833
- includeSynthesizable: boolean().optional()
14834
- }), object({ caps: array(object({
14835
- cap: string(),
14836
- fields: array(object({
14837
- path: string(),
14838
- kind: _enum([
14839
- "string",
14840
- "number",
14841
- "boolean",
14842
- "enum"
14843
- ]),
14844
- enumValues: array(string()).optional(),
14845
- item: boolean().optional()
14846
- })).readonly(),
14847
- itemArray: object({
14848
- path: string(),
14849
- keyField: string()
14850
- }).optional()
14851
- })).readonly() }), { kind: "query" }), method(object({
14852
- deviceId: number(),
14853
- role: string().nullable()
14854
- }), _void(), {
14855
- kind: "mutation",
14856
- auth: "admin"
14857
- }), method(object({
14858
- deviceId: number(),
14859
- name: string().optional(),
14860
- location: string().nullable().optional(),
14861
- type: _enum(DeviceType).optional(),
14862
- integrationId: string().optional(),
14863
- linkDeviceId: number().nullable().optional(),
14864
- role: string().nullable().optional()
14865
- }), _void(), {
14866
- kind: "mutation",
14867
- auth: "admin"
14868
- }), method(object({
14869
- deviceId: number(),
14870
- patch: record(string(), unknown())
14871
- }), _void(), {
14872
- kind: "mutation",
14873
- auth: "admin"
14874
- }), method(_void(), array(string())), method(object({ name: string() }), _void(), {
14875
- kind: "mutation",
14876
- auth: "admin"
14877
- }), method(object({
14878
- name: string(),
14879
- cascade: boolean().optional()
14880
- }), _void(), {
14881
- kind: "mutation",
14882
- auth: "admin"
14883
- }), method(object({
14884
- deviceId: number(),
14885
- disabled: boolean()
14886
- }), _void(), {
14887
- kind: "mutation",
14888
- auth: "admin"
14889
- }), method(object({ addonId: string() }), array(SavedDeviceRowSchema)), method(object({ addonId: string().optional() }), array(DeviceInfoSchema)), method(object({ deviceId: number() }), DeviceInfoSchema.nullable()), method(object({ parentDeviceId: number() }), array(DeviceInfoSchema)), method(object({ deviceId: number() }), object({
14890
- mode: DeviceLinkModeSchema,
14891
- devices: array(LinkedDeviceSchema)
14892
- })), method(object({ deviceId: number() }), array(StreamSourceEntrySchema$1)), method(object({ deviceId: number() }), array(ConfigEntrySchema)), method(object({ deviceId: number() }), ConfigUISchemaOutput), method(object({
14893
- deviceId: number(),
14894
- values: record(string(), unknown())
14895
- }), object({ success: literal(true) }), {
14896
- kind: "mutation",
14897
- auth: "admin"
14898
- }), method(object({ deviceId: number() }), object({ success: literal(true) }), {
14899
- kind: "mutation",
14900
- auth: "admin"
14901
- }), method(object({ deviceId: number() }), object({ success: literal(true) }), {
14902
- kind: "mutation",
14903
- auth: "admin"
14904
- }), method(object({ deviceId: number() }), object({ success: literal(true) }), {
14905
- kind: "mutation",
14906
- auth: "admin"
14907
- }), method(object({ integrationId: string() }), object({ removed: number() }), {
14908
- kind: "mutation",
14909
- auth: "admin"
14910
- }), method(object({ deviceId: number() }), record(string(), string().nullable())), method(object({
14911
- deviceId: number(),
14912
- profileMap: record(string(), string().nullable())
14913
- }), object({ success: literal(true) }), {
14914
- kind: "mutation",
14915
- auth: "admin"
14916
- }), method(object({ deviceId: number() }), array(StreamProbeResultSchema), {
14917
- kind: "mutation",
14918
- auth: "admin"
14919
- }), method(object({ deviceId: number() }), object({
14920
- deviceId: number(),
14921
- entries: array(object({
14922
- capName: string(),
14923
- kind: _enum([
14924
- "native",
14925
- "wrapped",
14926
- "linked"
14927
- ]),
14928
- providerAddonId: string(),
14929
- providerNodeId: string(),
14930
- nativeAddonId: string()
14931
- }))
14932
- })), method(object({}), array(object({
14933
- deviceId: number(),
14934
- entries: array(object({
14935
- capName: string(),
14936
- kind: _enum([
14937
- "native",
14938
- "wrapped",
14939
- "linked"
14940
- ]),
14941
- providerAddonId: string(),
14942
- providerNodeId: string(),
14943
- nativeAddonId: string()
14944
- }))
14945
- }))), method(object({
14946
- deviceId: number(),
14947
- capName: string(),
14948
- wrapperAddonId: string(),
14949
- active: boolean()
14950
- }), _void(), {
14951
- kind: "mutation",
14952
- auth: "admin"
14953
- }), method(object({ capName: string() }), array(string())), method(object({ deviceType: string() }), array(object({
14954
- capName: string(),
14955
- wrappers: array(string())
14956
- }))), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), object({
14957
- settings: SettingsSchemaWithValuesSchema.nullable(),
14958
- live: SettingsSchemaWithValuesSchema.nullable()
14959
- })), method(object({
14960
- deviceId: number().int().nonnegative(),
14961
- action: string().min(1),
14962
- input: unknown()
14963
- }), unknown(), { kind: "mutation" }), method(object({
14964
- deviceId: number(),
14965
- writerCapName: string(),
14966
- writerAddonId: string(),
14967
- key: string(),
14968
- value: unknown()
14969
- }), object({ success: literal(true) }), {
14970
- kind: "mutation",
14971
- auth: "admin"
14972
- }), method(object({
14973
- deviceId: number(),
14974
- changes: array(object({
14975
- writerCapName: string(),
14976
- writerAddonId: string(),
14977
- key: string(),
14978
- value: unknown()
14979
- }))
14980
- }), object({
14981
- success: literal(true),
14982
- failures: array(object({
14983
- writerCapName: string(),
14984
- writerAddonId: string(),
14985
- error: string()
14986
- }))
14987
- }), {
14988
- kind: "mutation",
14989
- auth: "admin"
14990
- }), method(object({ addonId: string() }), array(DiscoveryCandidateSchema), {
14991
- kind: "mutation",
14992
- auth: "admin"
14993
- }), method(object({
14994
- addonId: string(),
14995
- candidate: DiscoveryCandidateSchema,
14996
- /** Owning integration id, stamped onto the new device's meta by the
14997
- * device-manager forwarder so `removeByIntegration` can cascade it.
14998
- * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
14999
- integrationId: string().optional()
15000
- }), DeviceSummarySchema, {
15001
- kind: "mutation",
15002
- auth: "admin"
15003
- }), method(object({
15004
- addonId: string(),
15005
- type: _enum(DeviceType)
15006
- }), unknown().nullable()), method(object({
15007
- addonId: string(),
15008
- type: _enum(DeviceType),
15009
- config: record(string(), unknown()),
15010
- /** Owning integration id, stamped onto the new device's meta by the
15011
- * device-manager forwarder so `removeByIntegration` can cascade it.
15012
- * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
15013
- integrationId: string().optional()
15014
- }), DeviceSummarySchema, {
15015
- kind: "mutation",
15016
- auth: "admin"
15017
- }), method(object({
15018
- addonId: string(),
15019
- type: _enum(DeviceType),
15020
- key: string(),
15021
- value: unknown(),
15022
- formValues: record(string(), unknown()).optional()
15023
- }), FieldProbeResultSchema, {
15024
- kind: "mutation",
15025
- auth: "admin"
15026
- }), method(object({
15027
- addonId: string(),
15028
- integrationId: string()
15029
- }), object({ filters: array(AdoptionFilterSchema) }), { auth: "admin" }), method(ListCandidatesInputSchema.extend({ addonId: string() }), ListCandidatesOutputSchema, { auth: "admin" }), method(object({
15030
- addonId: string(),
15031
- integrationId: string()
15032
- }), AdoptionStatusSchema, {
15033
- kind: "mutation",
15034
- auth: "admin"
15035
- }), method(AdoptInputSchema.extend({ addonId: string() }), AdoptResultSchema, {
15036
- kind: "mutation",
15037
- auth: "admin"
15038
- }), method(ReleaseInputSchema.extend({ addonId: string() }), _void(), {
15039
- kind: "mutation",
15040
- auth: "admin"
15041
- }), method(ResyncInputSchema, ResyncResultSchema, {
15042
- kind: "mutation",
15043
- auth: "admin"
15044
- }), method(object({}), object({ providers: array(object({
15365
+ });
15366
+ var DeviceRegisterPayloadSchema = object({
15045
15367
  addonId: string(),
15046
- label: string()
15047
- })).readonly() }), { auth: "admin" }), method(object({}), object({ groups: array(object({
15368
+ stableId: string(),
15369
+ /** Pre-allocated numeric id from `allocateDeviceId`. The hub persists
15370
+ * it alongside the meta record; callers never invent this value. */
15371
+ id: number(),
15372
+ type: string(),
15373
+ name: string(),
15374
+ /** Operator-organisational location label. Optional on register —
15375
+ * the hub seeds `null` when omitted. */
15376
+ location: string().nullable().optional(),
15377
+ /** Soft-disabled flag. Optional on register — the hub seeds `false`. */
15378
+ disabled: boolean().optional(),
15379
+ parentDeviceId: number().nullable(),
15380
+ /** Optional semantic role — see `DeviceRole`. Driver authors pass this
15381
+ * at register time when the device is an accessory with a known role. */
15382
+ role: string().nullable().optional(),
15383
+ /** Snapshot of `device.features` at registration time. Persisted in
15384
+ * `DeviceMeta` so the hub can answer `getDevice` for forked-worker
15385
+ * devices with the right `DeviceFeature[]` even when the live
15386
+ * instance lives on a remote node. Re-published on every register
15387
+ * call (workers re-register on init), so probe-driven updates
15388
+ * (e.g. PTZ flag flipping after the abilities probe) propagate. */
15389
+ features: array(string()).optional(),
15390
+ config: record(string(), unknown())
15391
+ });
15392
+ var DeviceRemovePayloadSchema = object({ deviceId: number() });
15393
+ var DevicePersistConfigPayloadSchema = object({
15394
+ deviceId: number(),
15395
+ data: record(string(), unknown())
15396
+ });
15397
+ method(object({
15048
15398
  addonId: string(),
15049
- label: string(),
15050
- candidates: array(DiscoveryCandidateSchema).readonly(),
15051
- error: string().nullable()
15052
- })).readonly() }), {
15399
+ stableId: string()
15400
+ }), object({ id: number() }), { kind: "mutation" }), method(DeviceRegisterPayloadSchema, _void(), { kind: "mutation" }), method(DeviceRemovePayloadSchema, _void(), { kind: "mutation" }), method(DevicePersistConfigPayloadSchema, _void(), { kind: "mutation" }), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), record(string(), unknown())), method(object({ deviceId: number() }), DeviceMetaSchema.nullable()), method(object({
15401
+ deviceId: number(),
15402
+ name: string()
15403
+ }), _void(), {
15053
15404
  kind: "mutation",
15054
15405
  auth: "admin"
15055
15406
  }), method(object({
15056
- addonId: string(),
15057
- params: record(string(), unknown()).optional()
15058
- }), object({ candidates: array(DiscoveryCandidateSchema).readonly() }), {
15059
- kind: "mutation",
15060
- auth: "admin"
15061
- }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
15062
15407
  deviceId: number(),
15063
- key: string(),
15064
- value: unknown()
15065
- }), FieldProbeResultSchema, {
15408
+ location: string().nullable()
15409
+ }), _void(), {
15066
15410
  kind: "mutation",
15067
15411
  auth: "admin"
15068
15412
  }), method(object({
15069
15413
  deviceId: number(),
15070
- caps: array(string()).readonly().optional()
15071
- }), record(string(), unknown().nullable()));
15072
- method(object({ deviceId: number() }), record(string(), record(string(), unknown()))), method(object({
15073
- deviceId: number(),
15074
- capName: string()
15075
- }), record(string(), unknown()).nullable()), method(object({}), record(string(), record(string(), record(string(), unknown())))), method(object({
15076
- deviceId: number(),
15077
- capName: string(),
15078
- slice: record(string(), unknown())
15079
- }), _void(), { kind: "mutation" }), object({
15080
- deviceId: number(),
15081
- capName: string(),
15082
- slice: record(string(), unknown())
15083
- });
15084
- /**
15085
- * Embedding output. `embedding` is wire-encoded as `number[]` so the
15086
- * Zod-validated tRPC surface round-trips cleanly; consumers that need a
15087
- * `Float32Array` can wrap it on the way out (in-process, no marshalling
15088
- * is involved). `inferenceMs` mirrors the runtime field used by the
15089
- * post-analysis enrichment-engine.
15090
- */
15091
- var EmbeddingResultSchema = object({
15092
- embedding: array(number()),
15093
- inferenceMs: number()
15094
- });
15095
- var EmbeddingInfoSchema = object({
15096
- modelId: string(),
15097
- embeddingDim: number(),
15098
- ready: boolean()
15099
- });
15100
- method(object({
15101
- crop: _instanceof(Uint8Array),
15102
- width: number(),
15103
- height: number()
15104
- }), EmbeddingResultSchema), method(object({ text: string() }), EmbeddingResultSchema), method(_void(), EmbeddingInfoSchema);
15105
- /**
15106
- * filesystem-browse — per-node capability for browsing the node's local
15107
- * filesystem, sandboxed to operator-configured allowed roots. Used by the
15108
- * admin "Add filesystem location" flow to pick a node + path. `mode:'per-node'`
15109
- * (one provider per node); the hub calls it with `{nodeId}` so the codegen
15110
- * routes to that exact node (default `nodeIdMode:'routing'`).
15111
- */
15112
- var DirEntrySchema = object({
15113
- name: string(),
15114
- path: string()
15115
- });
15116
- var BrowseResultSchema = object({
15117
- path: string(),
15118
- entries: array(DirEntrySchema).readonly(),
15119
- freeBytes: number(),
15120
- totalBytes: number()
15121
- });
15122
- method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({ path: string() }), BrowseResultSchema, { auth: "admin" }), method(object({ path: string() }), object({ path: string() }), {
15414
+ type: _enum(DeviceType)
15415
+ }), _void(), {
15123
15416
  kind: "mutation",
15124
- auth: "admin"
15125
- });
15126
- /**
15127
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15128
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15129
- * caps stay wire-compatible without a circular cap→cap import.
15130
- *
15131
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
15132
- * every transport tier structurally, and failed calls still write usage rows.
15133
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15134
- */
15135
- var LlmUsageSchema = object({
15136
- inputTokens: number(),
15137
- outputTokens: number()
15138
- });
15139
- var LlmErrorCodeSchema = _enum([
15140
- "timeout",
15141
- "rate-limited",
15142
- "auth",
15143
- "refusal",
15144
- "bad-request",
15145
- "unavailable",
15146
- "no-profile",
15147
- "budget-exceeded",
15148
- "adapter-error"
15149
- ]);
15150
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15151
- ok: literal(true),
15152
- text: string(),
15153
- model: string(),
15154
- usage: LlmUsageSchema,
15155
- truncated: boolean(),
15156
- latencyMs: number()
15157
- }), object({
15158
- ok: literal(false),
15159
- code: LlmErrorCodeSchema,
15160
- message: string(),
15161
- retryAfterMs: number().optional()
15162
- })]);
15163
- /**
15164
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15165
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15166
- * notification-output.cap.ts:27-31 precedents).
15167
- */
15168
- var LlmImageSchema = object({
15169
- bytes: _instanceof(Uint8Array),
15170
- mimeType: string()
15171
- });
15172
- var LlmGenerateBaseInputSchema = object({
15173
- /** Collection routing (the notification-output posture). */
15174
- addonId: string().optional(),
15175
- /** Explicit profile; else the resolution chain (spec §3). */
15176
- profileId: string().optional(),
15177
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15178
- consumer: string(),
15179
- system: string().optional(),
15180
- /** v1: single-turn. `messages[]` is a v2 additive field. */
15181
- prompt: string(),
15182
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15183
- jsonSchema: record(string(), unknown()).optional(),
15184
- /** Per-call override of the profile default. */
15185
- maxTokens: number().int().positive().optional(),
15186
- temperature: number().optional()
15187
- });
15188
- /**
15189
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15190
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15191
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15192
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15193
- * this only through the `llm` cap's methods.
15194
- *
15195
- * One running llama-server child per node in v1 (models are RAM-heavy).
15196
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15197
- * watchdog — operator decision #3).
15198
- */
15199
- var ManagedModelRefSchema = discriminatedUnion("kind", [
15200
- object({
15201
- kind: literal("catalog"),
15202
- catalogId: string()
15203
- }),
15204
- object({
15205
- kind: literal("url"),
15206
- url: string(),
15207
- sha256: string().optional()
15208
- }),
15209
- object({
15210
- kind: literal("path"),
15211
- path: string()
15212
- })
15213
- ]);
15214
- var ManagedRuntimeConfigSchema = object({
15215
- /** WHERE the runtime lives — hub or any agent. */
15216
- nodeId: string(),
15217
- /** Closed for v1; 'ollama' is a v2 candidate. */
15218
- engine: _enum(["llama-cpp"]),
15219
- model: ManagedModelRefSchema,
15220
- contextSize: number().int().default(4096),
15221
- /** 0 = CPU-only. */
15222
- gpuLayers: number().int().default(0),
15223
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15224
- threads: number().int().optional(),
15225
- /** Concurrent slots. */
15226
- parallel: number().int().default(1),
15227
- /** Else lazy: first generate boots it. */
15228
- autoStart: boolean().default(false),
15229
- /** 0 = never; frees RAM after quiet periods. */
15230
- idleStopMinutes: number().int().default(30)
15231
- });
15232
- var LlmRuntimeStatusSchema = object({
15233
- /** Status is ALWAYS node-qualified. */
15234
- nodeId: string(),
15235
- state: _enum([
15236
- "stopped",
15237
- "downloading",
15238
- "starting",
15239
- "ready",
15240
- "crashed",
15241
- "failed"
15242
- ]),
15243
- pid: number().optional(),
15244
- port: number().optional(),
15245
- modelPath: string().optional(),
15246
- modelId: string().optional(),
15247
- downloadProgress: number().min(0).max(1).optional(),
15248
- lastError: string().optional(),
15249
- crashesInWindow: number(),
15250
- /** Child RSS (sampled best-effort). */
15251
- memoryBytes: number().optional(),
15252
- vramBytes: number().optional()
15253
- });
15254
- var LlmNodeModelSchema = object({
15255
- file: string(),
15256
- sizeBytes: number(),
15257
- catalogId: string().optional(),
15258
- installedAt: number().optional()
15259
- });
15260
- var LlmRuntimeDiskUsageSchema = object({
15261
- nodeId: string(),
15262
- modelsBytes: number(),
15263
- freeBytes: number().optional()
15264
- });
15265
- method(LlmGenerateBaseInputSchema.extend({
15266
- images: array(LlmImageSchema).optional(),
15267
- runtime: ManagedRuntimeConfigSchema,
15268
- /** The managed profile's timeout, threaded by the hub provider. */
15269
- timeoutMs: number().int().positive().optional()
15270
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15417
+ auth: "admin"
15418
+ }), method(object({
15419
+ deviceId: number(),
15420
+ integrationId: string()
15421
+ }), _void(), {
15271
15422
  kind: "mutation",
15272
15423
  auth: "admin"
15273
- }), method(object({}), _void(), {
15424
+ }), method(object({
15425
+ deviceId: number(),
15426
+ linkDeviceId: number().nullable()
15427
+ }), _void(), {
15274
15428
  kind: "mutation",
15275
15429
  auth: "admin"
15276
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15430
+ }), method(object({
15431
+ deviceId: number(),
15432
+ primaryChildEntityId: string().nullable()
15433
+ }), _void(), {
15277
15434
  kind: "mutation",
15278
15435
  auth: "admin"
15279
- }), method(object({ file: string() }), _void(), {
15436
+ }), method(object({
15437
+ deviceId: number(),
15438
+ childLayout: array(ChildLayoutEntrySchema).readonly()
15439
+ }), _void(), {
15280
15440
  kind: "mutation",
15281
15441
  auth: "admin"
15282
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15283
- /**
15284
- * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15285
- * methods concat-fan across providers; single-row methods route to ONE
15286
- * provider by the `addonId` in the call input (the notification-output
15287
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15288
- * (hub-placed); the cap stays open for future providers.
15289
- *
15290
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15291
- * `apiKey` is a password field — providers REDACT it on read and merge on
15292
- * write; a stored key NEVER round-trips to a client.
15293
- */
15294
- var LlmProfileKindSchema = _enum([
15295
- "openai-compatible",
15296
- "openai",
15297
- "anthropic",
15298
- "google",
15299
- "managed-local"
15300
- ]);
15301
- var LlmProfileSchema = object({
15302
- id: string(),
15442
+ }), method(object({
15443
+ deviceId: number(),
15444
+ deviceLinks: array(DeviceLinkSchema).readonly()
15445
+ }), _void(), {
15446
+ kind: "mutation",
15447
+ auth: "admin"
15448
+ }), method(object({
15449
+ deviceId: number(),
15450
+ display: DeviceDisplayOverrideSchema.nullable()
15451
+ }), _void(), {
15452
+ kind: "mutation",
15453
+ auth: "admin"
15454
+ }), method(object({}), object({ defaults: record(string(), RoleDisplayDefaultSchema) }), { kind: "query" }), method(object({ defaults: record(string(), RoleDisplayDefaultSchema) }), _void(), {
15455
+ kind: "mutation",
15456
+ auth: "admin"
15457
+ }), method(object({
15458
+ deviceId: number(),
15459
+ includeSynthesizable: boolean().optional()
15460
+ }), object({ caps: array(object({
15461
+ cap: string(),
15462
+ fields: array(object({
15463
+ path: string(),
15464
+ kind: _enum([
15465
+ "string",
15466
+ "number",
15467
+ "boolean",
15468
+ "enum"
15469
+ ]),
15470
+ enumValues: array(string()).optional(),
15471
+ item: boolean().optional()
15472
+ })).readonly(),
15473
+ itemArray: object({
15474
+ path: string(),
15475
+ keyField: string()
15476
+ }).optional()
15477
+ })).readonly() }), { kind: "query" }), method(object({
15478
+ deviceId: number(),
15479
+ role: string().nullable()
15480
+ }), _void(), {
15481
+ kind: "mutation",
15482
+ auth: "admin"
15483
+ }), method(object({
15484
+ deviceId: number(),
15485
+ name: string().optional(),
15486
+ location: string().nullable().optional(),
15487
+ type: _enum(DeviceType).optional(),
15488
+ integrationId: string().optional(),
15489
+ linkDeviceId: number().nullable().optional(),
15490
+ role: string().nullable().optional()
15491
+ }), _void(), {
15492
+ kind: "mutation",
15493
+ auth: "admin"
15494
+ }), method(object({
15495
+ deviceId: number(),
15496
+ patch: record(string(), unknown())
15497
+ }), _void(), {
15498
+ kind: "mutation",
15499
+ auth: "admin"
15500
+ }), method(_void(), array(string())), method(object({ name: string() }), _void(), {
15501
+ kind: "mutation",
15502
+ auth: "admin"
15503
+ }), method(object({
15303
15504
  name: string(),
15304
- kind: LlmProfileKindSchema,
15305
- /** Stamped by the provider — keeps the fanned catalog routable. */
15306
- addonId: string(),
15307
- enabled: boolean(),
15308
- /** Vendor model id, or the managed runtime's loaded model. */
15309
- model: string(),
15310
- /** Required for openai-compatible; override for cloud kinds. */
15311
- baseUrl: string().optional(),
15312
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
15313
- apiKey: string().optional(),
15314
- supportsVision: boolean(),
15315
- temperature: number().min(0).max(2).optional(),
15316
- maxTokens: number().int().positive().optional(),
15317
- timeoutMs: number().int().positive().default(6e4),
15318
- extraHeaders: record(string(), string()).optional(),
15319
- /** kind === 'managed-local' only (spec §4). */
15320
- runtime: ManagedRuntimeConfigSchema.optional()
15321
- });
15322
- /** ConfigUISchema tree passed through untyped on the wire (the
15323
- * notification-output `ConfigSchemaPassthrough` precedent at
15324
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15325
- var ConfigSchemaPassthrough$1 = unknown();
15326
- var LlmProfileKindDescriptorSchema = object({
15327
- kind: LlmProfileKindSchema,
15328
- label: string(),
15329
- icon: string(),
15330
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
15331
- addonId: string(),
15332
- configSchema: ConfigSchemaPassthrough$1
15333
- });
15334
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15335
- var LlmDefaultSchema = object({
15336
- selector: LlmDefaultSelectorSchema,
15337
- profileId: string()
15338
- });
15339
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
15340
- var LlmUsageRollupSchema = object({
15341
- day: string(),
15342
- consumer: string(),
15343
- profileId: string(),
15344
- calls: number(),
15345
- okCalls: number(),
15346
- errorCalls: number(),
15347
- inputTokens: number(),
15348
- outputTokens: number(),
15349
- avgLatencyMs: number()
15350
- });
15351
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15352
- var ManagedModelCatalogEntrySchema = object({
15353
- id: string(),
15354
- label: string(),
15355
- family: string(),
15356
- purpose: _enum(["text", "vision"]),
15357
- url: string(),
15358
- sha256: string(),
15359
- sizeBytes: number(),
15360
- quantization: string(),
15361
- /** Load-time guidance shown in the picker. */
15362
- minRamBytes: number(),
15363
- contextSizeDefault: number().int(),
15364
- /** Vision models: companion projector file. */
15365
- mmprojUrl: string().optional()
15366
- });
15367
- var LlmRuntimeNodeSchema = object({
15368
- nodeId: string(),
15369
- reachable: boolean(),
15370
- status: LlmRuntimeStatusSchema.optional(),
15371
- disk: LlmRuntimeDiskUsageSchema.optional(),
15372
- error: string().optional()
15373
- });
15374
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
15375
- var ProfileRefInputSchema = object({
15376
- addonId: string(),
15377
- profileId: string()
15378
- });
15379
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
15505
+ cascade: boolean().optional()
15506
+ }), _void(), {
15507
+ kind: "mutation",
15508
+ auth: "admin"
15509
+ }), method(object({
15510
+ deviceId: number(),
15511
+ disabled: boolean()
15512
+ }), _void(), {
15513
+ kind: "mutation",
15514
+ auth: "admin"
15515
+ }), method(object({ addonId: string() }), array(SavedDeviceRowSchema)), method(object({ addonId: string().optional() }), array(DeviceInfoSchema)), method(object({ deviceId: number() }), DeviceInfoSchema.nullable()), method(object({ parentDeviceId: number() }), array(DeviceInfoSchema)), method(object({ deviceId: number() }), object({
15516
+ mode: DeviceLinkModeSchema,
15517
+ devices: array(LinkedDeviceSchema)
15518
+ })), method(object({ deviceId: number() }), array(StreamSourceEntrySchema$1)), method(object({ deviceId: number() }), array(ConfigEntrySchema)), method(object({ deviceId: number() }), ConfigUISchemaOutput), method(object({
15519
+ deviceId: number(),
15520
+ values: record(string(), unknown())
15521
+ }), object({ success: literal(true) }), {
15522
+ kind: "mutation",
15523
+ auth: "admin"
15524
+ }), method(object({ deviceId: number() }), object({ success: literal(true) }), {
15525
+ kind: "mutation",
15526
+ auth: "admin"
15527
+ }), method(object({ deviceId: number() }), object({ success: literal(true) }), {
15528
+ kind: "mutation",
15529
+ auth: "admin"
15530
+ }), method(object({ deviceId: number() }), object({ success: literal(true) }), {
15531
+ kind: "mutation",
15532
+ auth: "admin"
15533
+ }), method(object({ integrationId: string() }), object({ removed: number() }), {
15534
+ kind: "mutation",
15535
+ auth: "admin"
15536
+ }), method(object({ deviceId: number() }), record(string(), string().nullable())), method(object({
15537
+ deviceId: number(),
15538
+ profileMap: record(string(), string().nullable())
15539
+ }), object({ success: literal(true) }), {
15540
+ kind: "mutation",
15541
+ auth: "admin"
15542
+ }), method(object({ deviceId: number() }), array(StreamProbeResultSchema), {
15543
+ kind: "mutation",
15544
+ auth: "admin"
15545
+ }), method(object({ deviceId: number() }), object({
15546
+ deviceId: number(),
15547
+ entries: array(object({
15548
+ capName: string(),
15549
+ kind: _enum([
15550
+ "native",
15551
+ "wrapped",
15552
+ "linked"
15553
+ ]),
15554
+ providerAddonId: string(),
15555
+ providerNodeId: string(),
15556
+ nativeAddonId: string()
15557
+ }))
15558
+ })), method(object({}), array(object({
15559
+ deviceId: number(),
15560
+ entries: array(object({
15561
+ capName: string(),
15562
+ kind: _enum([
15563
+ "native",
15564
+ "wrapped",
15565
+ "linked"
15566
+ ]),
15567
+ providerAddonId: string(),
15568
+ providerNodeId: string(),
15569
+ nativeAddonId: string()
15570
+ }))
15571
+ }))), method(object({
15572
+ deviceId: number(),
15573
+ capName: string(),
15574
+ wrapperAddonId: string(),
15575
+ active: boolean()
15576
+ }), _void(), {
15577
+ kind: "mutation",
15578
+ auth: "admin"
15579
+ }), method(object({ capName: string() }), array(string())), method(object({ deviceType: string() }), array(object({
15580
+ capName: string(),
15581
+ wrappers: array(string())
15582
+ }))), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), SettingsSchemaWithValuesSchema.nullable()), method(object({ deviceId: number() }), object({
15583
+ settings: SettingsSchemaWithValuesSchema.nullable(),
15584
+ live: SettingsSchemaWithValuesSchema.nullable()
15585
+ })), method(object({
15586
+ deviceId: number().int().nonnegative(),
15587
+ action: string().min(1),
15588
+ input: unknown()
15589
+ }), unknown(), { kind: "mutation" }), method(object({
15590
+ deviceId: number(),
15591
+ writerCapName: string(),
15592
+ writerAddonId: string(),
15593
+ key: string(),
15594
+ value: unknown()
15595
+ }), object({ success: literal(true) }), {
15380
15596
  kind: "mutation",
15381
15597
  auth: "admin"
15382
- }), method(ProfileRefInputSchema, _void(), {
15598
+ }), method(object({
15599
+ deviceId: number(),
15600
+ changes: array(object({
15601
+ writerCapName: string(),
15602
+ writerAddonId: string(),
15603
+ key: string(),
15604
+ value: unknown()
15605
+ }))
15606
+ }), object({
15607
+ success: literal(true),
15608
+ failures: array(object({
15609
+ writerCapName: string(),
15610
+ writerAddonId: string(),
15611
+ error: string()
15612
+ }))
15613
+ }), {
15383
15614
  kind: "mutation",
15384
15615
  auth: "admin"
15385
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
15616
+ }), method(object({ addonId: string() }), array(DiscoveryCandidateSchema), {
15386
15617
  kind: "mutation",
15387
15618
  auth: "admin"
15388
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
15389
- selector: LlmDefaultSelectorSchema,
15390
- profileId: string().nullable()
15391
- }), _void(), {
15619
+ }), method(object({
15620
+ addonId: string(),
15621
+ candidate: DiscoveryCandidateSchema,
15622
+ /** Owning integration id, stamped onto the new device's meta by the
15623
+ * device-manager forwarder so `removeByIntegration` can cascade it.
15624
+ * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
15625
+ integrationId: string().optional()
15626
+ }), DeviceSummarySchema, {
15392
15627
  kind: "mutation",
15393
15628
  auth: "admin"
15394
15629
  }), method(object({
15395
- since: number().optional(),
15396
- until: number().optional(),
15397
- consumer: string().optional(),
15398
- profileId: string().optional()
15399
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
15400
- nodeId: string(),
15401
- model: ManagedModelRefSchema
15402
- }), _void(), {
15630
+ addonId: string(),
15631
+ type: _enum(DeviceType)
15632
+ }), unknown().nullable()), method(object({
15633
+ addonId: string(),
15634
+ type: _enum(DeviceType),
15635
+ config: record(string(), unknown()),
15636
+ /** Owning integration id, stamped onto the new device's meta by the
15637
+ * device-manager forwarder so `removeByIntegration` can cascade it.
15638
+ * Optional for back-compat (omitted = no stamp = pre-existing behavior). */
15639
+ integrationId: string().optional()
15640
+ }), DeviceSummarySchema, {
15403
15641
  kind: "mutation",
15404
15642
  auth: "admin"
15405
15643
  }), method(object({
15406
- nodeId: string(),
15407
- file: string()
15408
- }), _void(), {
15644
+ addonId: string(),
15645
+ type: _enum(DeviceType),
15646
+ key: string(),
15647
+ value: unknown(),
15648
+ formValues: record(string(), unknown()).optional()
15649
+ }), FieldProbeResultSchema, {
15409
15650
  kind: "mutation",
15410
15651
  auth: "admin"
15411
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
15652
+ }), method(object({
15653
+ addonId: string(),
15654
+ integrationId: string()
15655
+ }), object({ filters: array(AdoptionFilterSchema) }), { auth: "admin" }), method(ListCandidatesInputSchema.extend({ addonId: string() }), ListCandidatesOutputSchema, { auth: "admin" }), method(object({
15656
+ addonId: string(),
15657
+ integrationId: string()
15658
+ }), AdoptionStatusSchema, {
15412
15659
  kind: "mutation",
15413
15660
  auth: "admin"
15414
- }), method(ProfileRefInputSchema, _void(), {
15661
+ }), method(AdoptInputSchema.extend({ addonId: string() }), AdoptResultSchema, {
15662
+ kind: "mutation",
15663
+ auth: "admin"
15664
+ }), method(ReleaseInputSchema.extend({ addonId: string() }), _void(), {
15665
+ kind: "mutation",
15666
+ auth: "admin"
15667
+ }), method(ResyncInputSchema, ResyncResultSchema, {
15668
+ kind: "mutation",
15669
+ auth: "admin"
15670
+ }), method(object({}), object({ providers: array(object({
15671
+ addonId: string(),
15672
+ label: string()
15673
+ })).readonly() }), { auth: "admin" }), method(object({}), object({ groups: array(object({
15674
+ addonId: string(),
15675
+ label: string(),
15676
+ candidates: array(DiscoveryCandidateSchema).readonly(),
15677
+ error: string().nullable()
15678
+ })).readonly() }), {
15679
+ kind: "mutation",
15680
+ auth: "admin"
15681
+ }), method(object({
15682
+ addonId: string(),
15683
+ params: record(string(), unknown()).optional()
15684
+ }), object({ candidates: array(DiscoveryCandidateSchema).readonly() }), {
15685
+ kind: "mutation",
15686
+ auth: "admin"
15687
+ }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
15688
+ deviceId: number(),
15689
+ key: string(),
15690
+ value: unknown()
15691
+ }), FieldProbeResultSchema, {
15415
15692
  kind: "mutation",
15416
15693
  auth: "admin"
15694
+ }), method(object({
15695
+ deviceId: number(),
15696
+ caps: array(string()).readonly().optional()
15697
+ }), record(string(), unknown().nullable()));
15698
+ method(object({ deviceId: number() }), record(string(), record(string(), unknown()))), method(object({
15699
+ deviceId: number(),
15700
+ capName: string()
15701
+ }), record(string(), unknown()).nullable()), method(object({}), record(string(), record(string(), record(string(), unknown())))), method(object({
15702
+ deviceId: number(),
15703
+ capName: string(),
15704
+ slice: record(string(), unknown())
15705
+ }), _void(), { kind: "mutation" }), object({
15706
+ deviceId: number(),
15707
+ capName: string(),
15708
+ slice: record(string(), unknown())
15417
15709
  });
15418
- var LogLevelSchema = _enum([
15419
- "debug",
15420
- "info",
15421
- "warn",
15422
- "error"
15423
- ]);
15424
- var LogEntrySchema = object({
15425
- timestamp: date(),
15426
- level: LogLevelSchema,
15427
- scope: array(string()),
15428
- message: string(),
15429
- meta: record(string(), unknown()).optional(),
15430
- tags: record(string(), string()).optional()
15710
+ /**
15711
+ * Embedding output. `embedding` is wire-encoded as `number[]` so the
15712
+ * Zod-validated tRPC surface round-trips cleanly; consumers that need a
15713
+ * `Float32Array` can wrap it on the way out (in-process, no marshalling
15714
+ * is involved). `inferenceMs` mirrors the runtime field used by the
15715
+ * post-analysis enrichment-engine.
15716
+ */
15717
+ var EmbeddingResultSchema = object({
15718
+ embedding: array(number()),
15719
+ inferenceMs: number()
15431
15720
  });
15432
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15433
- scope: array(string()).optional(),
15434
- level: LogLevelSchema.optional(),
15435
- since: date().optional(),
15436
- until: date().optional(),
15437
- limit: number().optional(),
15438
- tags: record(string(), string()).optional()
15439
- }), array(LogEntrySchema).readonly());
15721
+ var EmbeddingInfoSchema = object({
15722
+ modelId: string(),
15723
+ embeddingDim: number(),
15724
+ ready: boolean()
15725
+ });
15726
+ method(object({
15727
+ crop: _instanceof(Uint8Array),
15728
+ width: number(),
15729
+ height: number()
15730
+ }), EmbeddingResultSchema), method(object({ text: string() }), EmbeddingResultSchema), method(_void(), EmbeddingInfoSchema);
15440
15731
  /**
15441
- * `login-method`collection cap through which auth addons contribute
15442
- * their pre-auth login surfaces to the login page. This is the SINGLE,
15443
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
15444
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
15445
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
15446
- * procedure aggregates them for the unauthenticated login page.
15447
- *
15448
- * A contribution is a discriminated union on `kind`:
15449
- *
15450
- * - `redirect` — a declarative button. The login page renders a generic
15451
- * button that navigates to `startUrl` (an addon-owned HTTP route).
15452
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
15453
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
15454
- * login page needs NO change.
15455
- *
15456
- * - `widget` — a Module-Federation widget the login page mounts (via
15457
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
15458
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
15459
- * mechanism kept for future use; no shipped addon uses it on the login
15460
- * page (the passkey ceremony below runs natively in the shell instead).
15461
- *
15462
- * - `passkey` a declarative WebAuthn ceremony the shell renders
15463
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
15464
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
15465
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
15466
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
15467
- * fetching any remote code pre-auth. Contribution stays unconditional —
15468
- * enrollment state is never leaked pre-auth; visibility is a shell
15469
- * decision.
15732
+ * filesystem-browseper-node capability for browsing the node's local
15733
+ * filesystem, sandboxed to operator-configured allowed roots. Used by the
15734
+ * admin "Add filesystem location" flow to pick a node + path. `mode:'per-node'`
15735
+ * (one provider per node); the hub calls it with `{nodeId}` so the codegen
15736
+ * routes to that exact node (default `nodeIdMode:'routing'`).
15737
+ */
15738
+ var DirEntrySchema = object({
15739
+ name: string(),
15740
+ path: string()
15741
+ });
15742
+ var BrowseResultSchema = object({
15743
+ path: string(),
15744
+ entries: array(DirEntrySchema).readonly(),
15745
+ freeBytes: number(),
15746
+ totalBytes: number()
15747
+ });
15748
+ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({ path: string() }), BrowseResultSchema, { auth: "admin" }), method(object({ path: string() }), object({ path: string() }), {
15749
+ kind: "mutation",
15750
+ auth: "admin"
15751
+ });
15752
+ /**
15753
+ * Shared LLM generate contracts imported by BOTH `llm.cap.ts` (consumer
15754
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15755
+ * caps stay wire-compatible without a circular cap→cap import.
15470
15756
  *
15471
- * Every contribution carries a `stage`:
15472
- * - `primary` — shown on the first credentials screen (OIDC /
15473
- * magic-link buttons; a future usernameless passkey).
15474
- * - `second-factor` — shown AFTER the password leg, gated on the
15475
- * returned `factors` (passkey-as-2FA today).
15757
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
15758
+ * every transport tier structurally, and failed calls still write usage rows.
15759
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15760
+ */
15761
+ var LlmUsageSchema = object({
15762
+ inputTokens: number(),
15763
+ outputTokens: number()
15764
+ });
15765
+ var LlmErrorCodeSchema = _enum([
15766
+ "timeout",
15767
+ "rate-limited",
15768
+ "auth",
15769
+ "refusal",
15770
+ "bad-request",
15771
+ "unavailable",
15772
+ "no-profile",
15773
+ "budget-exceeded",
15774
+ "adapter-error"
15775
+ ]);
15776
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15777
+ ok: literal(true),
15778
+ text: string(),
15779
+ model: string(),
15780
+ usage: LlmUsageSchema,
15781
+ truncated: boolean(),
15782
+ latencyMs: number()
15783
+ }), object({
15784
+ ok: literal(false),
15785
+ code: LlmErrorCodeSchema,
15786
+ message: string(),
15787
+ retryAfterMs: number().optional()
15788
+ })]);
15789
+ /**
15790
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15791
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15792
+ * notification-output.cap.ts:27-31 precedents).
15793
+ */
15794
+ var LlmImageSchema = object({
15795
+ bytes: _instanceof(Uint8Array),
15796
+ mimeType: string()
15797
+ });
15798
+ var LlmGenerateBaseInputSchema = object({
15799
+ /** Collection routing (the notification-output posture). */
15800
+ addonId: string().optional(),
15801
+ /** Explicit profile; else the resolution chain (spec §3). */
15802
+ profileId: string().optional(),
15803
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15804
+ consumer: string(),
15805
+ system: string().optional(),
15806
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
15807
+ prompt: string(),
15808
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15809
+ jsonSchema: record(string(), unknown()).optional(),
15810
+ /** Per-call override of the profile default. */
15811
+ maxTokens: number().int().positive().optional(),
15812
+ temperature: number().optional()
15813
+ });
15814
+ /**
15815
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15816
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15817
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15818
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15819
+ * this only through the `llm` cap's methods.
15476
15820
  *
15477
- * `mount: skip` the cap is read server-side by the core auth router
15478
- * (`registry.getCollection('login-method')`), never mounted as its own
15479
- * tRPC router.
15821
+ * One running llama-server child per node in v1 (models are RAM-heavy).
15822
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15823
+ * watchdog — operator decision #3).
15480
15824
  */
15481
- /** When a login method renders in the two-phase login flow. */
15482
- var LoginStageEnum = _enum(["primary", "second-factor"]);
15483
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
15484
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
15825
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
15485
15826
  object({
15486
- kind: literal("redirect"),
15487
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
15488
- id: string(),
15489
- /** Operator-facing button label. */
15490
- label: string(),
15491
- /** lucide-react icon name. */
15492
- icon: string().optional(),
15493
- /** Addon-owned HTTP route the button navigates to (GET). */
15494
- startUrl: string(),
15495
- stage: LoginStageEnum
15827
+ kind: literal("catalog"),
15828
+ catalogId: string()
15496
15829
  }),
15497
15830
  object({
15498
- kind: literal("widget"),
15499
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
15500
- id: string(),
15501
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
15502
- addonId: string(),
15503
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
15504
- bundle: string(),
15505
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
15506
- remote: WidgetRemoteSchema,
15507
- stage: LoginStageEnum
15831
+ kind: literal("url"),
15832
+ url: string(),
15833
+ sha256: string().optional()
15508
15834
  }),
15509
15835
  object({
15510
- kind: literal("passkey"),
15511
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
15512
- id: string(),
15513
- /** Operator-facing button label. */
15514
- label: string(),
15515
- stage: LoginStageEnum,
15516
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
15517
- rpId: string(),
15518
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
15519
- origin: string().nullable()
15836
+ kind: literal("path"),
15837
+ path: string()
15520
15838
  })
15521
15839
  ]);
15522
- method(_void(), array(LoginMethodContributionSchema).readonly());
15523
- var CpuBreakdownSchema = object({
15524
- total: number(),
15525
- user: number(),
15526
- system: number(),
15527
- irq: number(),
15528
- nice: number(),
15529
- loadAvg: tuple([
15530
- number(),
15531
- number(),
15532
- number()
15533
- ]),
15534
- cores: number()
15535
- });
15536
- var MemoryInfoSchema = object({
15537
- percent: number(),
15538
- totalBytes: number(),
15539
- usedBytes: number(),
15540
- availableBytes: number(),
15541
- swapUsedBytes: number(),
15542
- swapTotalBytes: number()
15543
- });
15544
- var DiskIoSnapshotSchema = object({
15545
- readBytes: number(),
15546
- writeBytes: number(),
15547
- readOps: number(),
15548
- writeOps: number(),
15549
- timestampMs: number()
15550
- });
15551
- var NetworkIoSnapshotSchema = object({
15552
- rxBytes: number(),
15553
- txBytes: number(),
15554
- rxPackets: number(),
15555
- txPackets: number(),
15556
- rxErrors: number(),
15557
- txErrors: number(),
15558
- timestampMs: number()
15559
- });
15560
- var MetricsGpuInfoSchema = object({
15561
- utilization: number(),
15562
- model: string(),
15563
- memoryUsedBytes: number(),
15564
- memoryTotalBytes: number(),
15565
- temperature: number().nullable()
15566
- });
15567
- var ProcessResourceInfoSchema = object({
15568
- openFds: number(),
15569
- threadCount: number(),
15570
- activeHandles: number(),
15571
- activeRequests: number()
15572
- });
15573
- var PressureAvgsSchema = object({
15574
- avg10: number(),
15575
- avg60: number(),
15576
- avg300: number()
15577
- });
15578
- var PressureInfoSchema = object({
15579
- some: PressureAvgsSchema,
15580
- full: PressureAvgsSchema.nullable()
15581
- });
15582
- var SystemResourceSnapshotSchema = object({
15583
- cpu: CpuBreakdownSchema,
15584
- memory: MemoryInfoSchema,
15585
- gpu: MetricsGpuInfoSchema.nullable(),
15586
- network: NetworkIoSnapshotSchema,
15587
- disk: DiskIoSnapshotSchema,
15588
- pressure: object({
15589
- cpu: PressureInfoSchema.nullable(),
15590
- memory: PressureInfoSchema.nullable(),
15591
- io: PressureInfoSchema.nullable()
15592
- }),
15593
- process: ProcessResourceInfoSchema,
15594
- cpuTemperature: number().nullable(),
15595
- timestampMs: number()
15596
- });
15597
- var DiskSpaceInfoSchema = object({
15598
- path: string(),
15599
- totalBytes: number(),
15600
- usedBytes: number(),
15601
- availableBytes: number(),
15602
- percent: number()
15603
- });
15604
- var PidResourceStatsSchema = object({
15605
- pid: number(),
15606
- cpu: number(),
15607
- memory: number(),
15608
- /**
15609
- * Private (anonymous) resident bytes — the per-process V8 heap + native
15610
- * allocations NOT shared with other processes (Linux RssAnon). This is the
15611
- * "real" per-runner cost; summing it across runners is meaningful, unlike
15612
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
15613
- * Undefined where /proc is unavailable (e.g. macOS).
15614
- */
15615
- privateBytes: number().optional(),
15616
- /**
15617
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15618
- * code shared copy-on-write across runners. Undefined on macOS.
15619
- */
15620
- sharedBytes: number().optional()
15840
+ var ManagedRuntimeConfigSchema = object({
15841
+ /** WHERE the runtime lives — hub or any agent. */
15842
+ nodeId: string(),
15843
+ /** Closed for v1; 'ollama' is a v2 candidate. */
15844
+ engine: _enum(["llama-cpp"]),
15845
+ model: ManagedModelRefSchema,
15846
+ contextSize: number().int().default(4096),
15847
+ /** 0 = CPU-only. */
15848
+ gpuLayers: number().int().default(0),
15849
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15850
+ threads: number().int().optional(),
15851
+ /** Concurrent slots. */
15852
+ parallel: number().int().default(1),
15853
+ /** Else lazy: first generate boots it. */
15854
+ autoStart: boolean().default(false),
15855
+ /** 0 = never; frees RAM after quiet periods. */
15856
+ idleStopMinutes: number().int().default(30)
15621
15857
  });
15622
- var AddonInstanceSchema = object({
15623
- addonId: string(),
15858
+ var LlmRuntimeStatusSchema = object({
15859
+ /** Status is ALWAYS node-qualified. */
15624
15860
  nodeId: string(),
15625
- role: _enum(["hub", "worker"]),
15626
- pid: number(),
15627
15861
  state: _enum([
15628
- "starting",
15629
- "running",
15630
- "stopping",
15631
15862
  "stopped",
15632
- "crashed"
15633
- ]),
15634
- uptimeSec: number()
15635
- });
15636
- var NodeProcessSchema = object({
15637
- pid: number(),
15638
- ppid: number(),
15639
- pgid: number(),
15640
- classification: _enum([
15641
- "root",
15642
- "managed",
15643
- "system",
15644
- "ghost"
15645
- ]),
15646
- /** `$process` addon binding when `managed`, else null. */
15647
- addonId: string().nullable(),
15648
- /** Kernel-reported nodeId when the process is a known agent/worker. */
15649
- nodeId: string().nullable(),
15650
- /** Truncated command line. */
15651
- command: string(),
15652
- cpuPercent: number(),
15653
- memoryRssBytes: number(),
15654
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15655
- uptimeSec: number(),
15656
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15657
- orphaned: boolean()
15658
- });
15659
- var KillProcessInputSchema = object({
15660
- pid: number(),
15661
- /** Force = SIGKILL. Default is SIGTERM. */
15662
- force: boolean().optional()
15663
- });
15664
- var KillProcessResultSchema = object({
15665
- success: boolean(),
15666
- reason: string().optional(),
15667
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15668
- });
15669
- var DumpHeapSnapshotInputSchema = object({
15670
- /** The addon whose runner should dump a heap snapshot. */
15671
- addonId: string() });
15672
- var DumpHeapSnapshotResultSchema = object({
15673
- success: boolean(),
15674
- /** Path of the written .heapsnapshot inside the runner's container/host. */
15675
- path: string().optional(),
15676
- /** Process pid that was signalled. */
15863
+ "downloading",
15864
+ "starting",
15865
+ "ready",
15866
+ "crashed",
15867
+ "failed"
15868
+ ]),
15677
15869
  pid: number().optional(),
15678
- reason: string().optional()
15870
+ port: number().optional(),
15871
+ modelPath: string().optional(),
15872
+ modelId: string().optional(),
15873
+ downloadProgress: number().min(0).max(1).optional(),
15874
+ lastError: string().optional(),
15875
+ crashesInWindow: number(),
15876
+ /** Child RSS (sampled best-effort). */
15877
+ memoryBytes: number().optional(),
15878
+ vramBytes: number().optional()
15679
15879
  });
15680
- var SystemMetricsSchema = object({
15681
- cpuPercent: number(),
15682
- memoryPercent: number(),
15683
- memoryUsedMB: number(),
15684
- memoryTotalMB: number(),
15685
- diskPercent: number().optional(),
15686
- temperature: number().optional(),
15687
- gpuPercent: number().optional(),
15688
- gpuMemoryPercent: number().optional()
15880
+ var LlmNodeModelSchema = object({
15881
+ file: string(),
15882
+ sizeBytes: number(),
15883
+ catalogId: string().optional(),
15884
+ installedAt: number().optional()
15689
15885
  });
15690
- 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, {
15886
+ var LlmRuntimeDiskUsageSchema = object({
15887
+ nodeId: string(),
15888
+ modelsBytes: number(),
15889
+ freeBytes: number().optional()
15890
+ });
15891
+ method(LlmGenerateBaseInputSchema.extend({
15892
+ images: array(LlmImageSchema).optional(),
15893
+ runtime: ManagedRuntimeConfigSchema,
15894
+ /** The managed profile's timeout, threaded by the hub provider. */
15895
+ timeoutMs: number().int().positive().optional()
15896
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15691
15897
  kind: "mutation",
15692
15898
  auth: "admin"
15693
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15899
+ }), method(object({}), _void(), {
15694
15900
  kind: "mutation",
15695
15901
  auth: "admin"
15696
- });
15697
- method(object({
15698
- sourceUrl: string(),
15699
- metadata: ModelConvertMetadataSchema,
15700
- targets: array(ConvertTargetSchema).min(1).readonly(),
15701
- calibrationRef: string().optional(),
15702
- sessionId: string().optional()
15703
- }), ConvertResultSchema, {
15902
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15704
15903
  kind: "mutation",
15705
- auth: "admin",
15706
- timeoutMs: 6e5
15707
- });
15708
- method(object({
15709
- nodeId: string(),
15710
- modelId: string(),
15711
- format: _enum(MODEL_FORMATS),
15712
- entry: ModelCatalogEntrySchema
15713
- }), object({
15714
- ok: boolean(),
15715
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
15716
- sha256: string(),
15717
- bytes: number(),
15718
- /** The target node's modelsDir the artifact landed in. */
15719
- path: string()
15720
- }), {
15904
+ auth: "admin"
15905
+ }), method(object({ file: string() }), _void(), {
15721
15906
  kind: "mutation",
15722
15907
  auth: "admin"
15723
- });
15724
- /**
15725
- * `mqtt-broker` — broker-registry cap.
15726
- *
15727
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15728
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15729
- * and (b) the connection details a consumer addon needs to spin up
15730
- * its OWN `mqtt.js` client.
15731
- *
15732
- * Why: pub/sub routing over the system event-bus loses fidelity
15733
- * (callback shape, QoS guarantees, will/retain semantics) and adds
15734
- * refcount bookkeeping that addons would rather own themselves. The
15735
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
15736
- * features anyway — give it the connection config, get out of the way.
15737
- *
15738
- * Consumer flow:
15739
- * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
15740
- * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
15741
- * client.subscribe('zigbee2mqtt/+')
15742
- *
15743
- * Collection mode: multiple brokers (e.g. one local mosquitto + one
15744
- * cloud bridge). The "embedded" entry (when present) is just another
15745
- * broker in the registry — its lifecycle is owned by the addon that
15746
- * spawned it.
15747
- */
15748
- var BrokerKindSchema = _enum(["external", "embedded"]);
15908
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15749
15909
  /**
15750
- * Broker live-probe status.
15910
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15911
+ * methods concat-fan across providers; single-row methods route to ONE
15912
+ * provider by the `addonId` in the call input (the notification-output
15913
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15914
+ * (hub-placed); the cap stays open for future providers.
15751
15915
  *
15752
- * - `connected` last probe completed a clean CONNACK
15753
- * - `disconnected` — no probe has run yet (cold cache)
15754
- * - `auth-failed` CONNACK refused with auth error (RC 4 / 5)
15755
- * - `unreachable` — TCP connect timed out / refused
15756
- * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
15916
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15917
+ * `apiKey` is a password field providers REDACT it on read and merge on
15918
+ * write; a stored key NEVER round-trips to a client.
15757
15919
  */
15758
- var BrokerStatusSchema$1 = _enum([
15759
- "connected",
15760
- "disconnected",
15761
- "auth-failed",
15762
- "unreachable",
15763
- "tls-error"
15920
+ var LlmProfileKindSchema = _enum([
15921
+ "openai-compatible",
15922
+ "openai",
15923
+ "anthropic",
15924
+ "google",
15925
+ "managed-local"
15764
15926
  ]);
15765
- var BrokerInfoSchema = object({
15927
+ var LlmProfileSchema = object({
15766
15928
  id: string(),
15767
15929
  name: string(),
15768
- url: string(),
15769
- kind: BrokerKindSchema,
15770
- status: BrokerStatusSchema$1,
15771
- latencyMs: number().nullable(),
15772
- error: string().optional(),
15773
- /** Embedded brokers only: number of MQTT clients currently connected. */
15774
- connectedClients: number().int().nonnegative().optional(),
15775
- /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
15776
- lastCheckedAt: number().optional()
15930
+ kind: LlmProfileKindSchema,
15931
+ /** Stamped by the provider — keeps the fanned catalog routable. */
15932
+ addonId: string(),
15933
+ enabled: boolean(),
15934
+ /** Vendor model id, or the managed runtime's loaded model. */
15935
+ model: string(),
15936
+ /** Required for openai-compatible; override for cloud kinds. */
15937
+ baseUrl: string().optional(),
15938
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
15939
+ apiKey: string().optional(),
15940
+ supportsVision: boolean(),
15941
+ temperature: number().min(0).max(2).optional(),
15942
+ maxTokens: number().int().positive().optional(),
15943
+ timeoutMs: number().int().positive().default(6e4),
15944
+ extraHeaders: record(string(), string()).optional(),
15945
+ /** kind === 'managed-local' only (spec §4). */
15946
+ runtime: ManagedRuntimeConfigSchema.optional()
15777
15947
  });
15778
- /**
15779
- * Connection details — what a consumer needs to call
15780
- * `mqtt.connect(url, options)`. We split URL + credentials so the
15781
- * consumer can pass them as `mqtt.connect(url, { username, password })`
15782
- * instead of stuffing creds into the URL (which leaks them into logs).
15783
- */
15784
- var BrokerConnectionDetailsSchema = object({
15785
- url: string(),
15786
- username: string().optional(),
15787
- password: string().optional(),
15788
- /**
15789
- * Suggested prefix for `clientId`. Each consumer should suffix this
15790
- * with its own discriminator (addon id, instance id) so reconnects
15791
- * don't kick each other off (MQTT spec: clientId must be unique per
15792
- * broker).
15793
- */
15794
- clientIdPrefix: string().optional()
15948
+ /** ConfigUISchema tree passed through untyped on the wire (the
15949
+ * notification-output `ConfigSchemaPassthrough` precedent at
15950
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15951
+ var ConfigSchemaPassthrough$1 = unknown();
15952
+ var LlmProfileKindDescriptorSchema = object({
15953
+ kind: LlmProfileKindSchema,
15954
+ label: string(),
15955
+ icon: string(),
15956
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
15957
+ addonId: string(),
15958
+ configSchema: ConfigSchemaPassthrough$1
15795
15959
  });
15796
- var AddBrokerInputSchema = object({
15797
- name: string().min(1),
15798
- url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
15799
- username: string().optional(),
15800
- password: string().optional(),
15801
- clientIdPrefix: string().optional()
15960
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15961
+ var LlmDefaultSchema = object({
15962
+ selector: LlmDefaultSelectorSchema,
15963
+ profileId: string()
15802
15964
  });
15803
- var AddBrokerResultSchema = object({ id: string() });
15804
- var IdInputSchema = object({ id: string() });
15805
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
15806
- ok: literal(true),
15807
- latencyMs: number()
15808
- }), object({
15809
- ok: literal(false),
15810
- error: string()
15811
- })]);
15812
- var StartEmbeddedInputSchema = object({
15813
- port: number().int().min(1).max(65535).default(1883),
15814
- /** Allow anonymous connect (no username/password). Default: false. */
15815
- allowAnonymous: boolean().default(false),
15816
- /** Optional shared username/password for clients. */
15817
- username: string().optional(),
15818
- password: string().optional()
15965
+ /** Server-side rollup row getUsage never dumps raw call rows (spec §6). */
15966
+ var LlmUsageRollupSchema = object({
15967
+ day: string(),
15968
+ consumer: string(),
15969
+ profileId: string(),
15970
+ calls: number(),
15971
+ okCalls: number(),
15972
+ errorCalls: number(),
15973
+ inputTokens: number(),
15974
+ outputTokens: number(),
15975
+ avgLatencyMs: number()
15819
15976
  });
15820
- var StartEmbeddedResultSchema = object({
15977
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15978
+ var ManagedModelCatalogEntrySchema = object({
15821
15979
  id: string(),
15822
- url: string()
15823
- });
15824
- var StatusSchema = object({
15825
- brokerCount: number(),
15826
- embeddedRunning: boolean()
15827
- });
15828
- 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);
15829
- var NetworkEndpointSchema = object({
15980
+ label: string(),
15981
+ family: string(),
15982
+ purpose: _enum(["text", "vision"]),
15830
15983
  url: string(),
15831
- hostname: string(),
15832
- port: number(),
15833
- protocol: _enum(["http", "https"])
15984
+ sha256: string(),
15985
+ sizeBytes: number(),
15986
+ quantization: string(),
15987
+ /** Load-time guidance shown in the picker. */
15988
+ minRamBytes: number(),
15989
+ contextSizeDefault: number().int(),
15990
+ /** Vision models: companion projector file. */
15991
+ mmprojUrl: string().optional()
15834
15992
  });
15835
- var NetworkAccessStatusSchema = object({
15836
- connected: boolean(),
15837
- endpoint: NetworkEndpointSchema.nullable(),
15993
+ var LlmRuntimeNodeSchema = object({
15994
+ nodeId: string(),
15995
+ reachable: boolean(),
15996
+ status: LlmRuntimeStatusSchema.optional(),
15997
+ disk: LlmRuntimeDiskUsageSchema.optional(),
15838
15998
  error: string().optional()
15839
15999
  });
15840
- /**
15841
- * Optional, richer endpoint shape returned by providers that expose
15842
- * MORE than one ingress concurrently (Tailscale Ingress with mixed
15843
- * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
15844
- * the originating provider config (mode + sourcePort) so the
15845
- * orchestrator UI can label rows distinctly. Providers that expose only
15846
- * one endpoint just omit `listEndpoints` from their provider impl.
15847
- */
15848
- var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
15849
- /**
15850
- * Stable id within the provider — typically `<mode>-<sourcePort>` so
15851
- * the orchestrator can dedupe across `listEndpoints` polls.
15852
- */
15853
- id: string(),
15854
- /** Operator-facing label (mirrors `MeshEndpoint.label`). */
15855
- label: string(),
15856
- /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
15857
- mode: string().optional(),
15858
- /** Originating local port the ingress fronts (informational). */
15859
- sourcePort: number().optional()
16000
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16001
+ var ProfileRefInputSchema = object({
16002
+ addonId: string(),
16003
+ profileId: string()
16004
+ });
16005
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16006
+ kind: "mutation",
16007
+ auth: "admin"
16008
+ }), method(ProfileRefInputSchema, _void(), {
16009
+ kind: "mutation",
16010
+ auth: "admin"
16011
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16012
+ kind: "mutation",
16013
+ auth: "admin"
16014
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
16015
+ selector: LlmDefaultSelectorSchema,
16016
+ profileId: string().nullable()
16017
+ }), _void(), {
16018
+ kind: "mutation",
16019
+ auth: "admin"
16020
+ }), method(object({
16021
+ since: number().optional(),
16022
+ until: number().optional(),
16023
+ consumer: string().optional(),
16024
+ profileId: string().optional()
16025
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
16026
+ nodeId: string(),
16027
+ model: ManagedModelRefSchema
16028
+ }), _void(), {
16029
+ kind: "mutation",
16030
+ auth: "admin"
16031
+ }), method(object({
16032
+ nodeId: string(),
16033
+ file: string()
16034
+ }), _void(), {
16035
+ kind: "mutation",
16036
+ auth: "admin"
16037
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16038
+ kind: "mutation",
16039
+ auth: "admin"
16040
+ }), method(ProfileRefInputSchema, _void(), {
16041
+ kind: "mutation",
16042
+ auth: "admin"
16043
+ });
16044
+ var LogLevelSchema = _enum([
16045
+ "debug",
16046
+ "info",
16047
+ "warn",
16048
+ "error"
16049
+ ]);
16050
+ var LogEntrySchema = object({
16051
+ timestamp: date(),
16052
+ level: LogLevelSchema,
16053
+ scope: array(string()),
16054
+ message: string(),
16055
+ meta: record(string(), unknown()).optional(),
16056
+ tags: record(string(), string()).optional()
15860
16057
  });
15861
- method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
16058
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
16059
+ scope: array(string()).optional(),
16060
+ level: LogLevelSchema.optional(),
16061
+ since: date().optional(),
16062
+ until: date().optional(),
16063
+ limit: number().optional(),
16064
+ tags: record(string(), string()).optional()
16065
+ }), array(LogEntrySchema).readonly());
15862
16066
  /**
15863
- * notification-outputcanonical, capability-gated notification delivery.
16067
+ * `login-method`collection cap through which auth addons contribute
16068
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
16069
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
16070
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
16071
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
16072
+ * procedure aggregates them for the unauthenticated login page.
15864
16073
  *
15865
- * Apprise-derived model (see
15866
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
15867
- * callers emit ONE canonical `Notification`; each provider declares a
15868
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
15869
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
15870
- * message to what the kind supports — callers never special-case a service.
16074
+ * A contribution is a discriminated union on `kind`:
15871
16075
  *
15872
- * DESIGN DECISIONS (locked):
15873
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
15874
- * `setTargetEnabled`), each provider persisting via the `settings-store`
15875
- * cap. Rationale: the admin UI needs one uniform surface across the
15876
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
15877
- * alternative would fork the UI per addon and cannot host the
15878
- * discovery→adopt flow.
15879
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
15880
- * the generated cap-mount auto-`concatCollection`-fans them across every
15881
- * registered provider (notifiers addon + HA addon) so one catalog is
15882
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
15883
- * `addonId` the generated collection router extracts from the call input.
15884
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
15885
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
15886
- * `storage` / `storage-provider` / `recording` caps over the same path. No
15887
- * base64 fallback needed.
16076
+ * - `redirect` a declarative button. The login page renders a generic
16077
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
16078
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
16079
+ * ZERO shell-side JS. A future SSO addon plugs in the same way the
16080
+ * login page needs NO change.
15888
16081
  *
15889
- * TODO (deferred, closed-set change separate decision): add
15890
- * `providerKind: 'notify'` so notification providers surface on the unified
15891
- * admin "Integrations" page.
15892
- */
15893
- /**
15894
- * Zentik-derived typed-media enum — the superset across every kind. Each
15895
- * adapter picks what it supports and the degrade engine filters the rest.
15896
- */
15897
- var AttachmentMediaTypeSchema = _enum([
15898
- "image",
15899
- "video",
15900
- "gif",
15901
- "audio",
15902
- "icon"
15903
- ]);
15904
- /**
15905
- * A single attachment. Exactly one of `url` (remote source, most adapters
15906
- * prefer this) or `bytes` (inline source; required for Pushover-style
15907
- * bytes-only kinds) MUST be present the degrade engine expresses a
15908
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
16082
+ * - `widget` a Module-Federation widget the login page mounts (via
16083
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
16084
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
16085
+ * mechanism kept for future use; no shipped addon uses it on the login
16086
+ * page (the passkey ceremony below runs natively in the shell instead).
16087
+ *
16088
+ * - `passkey` a declarative WebAuthn ceremony the shell renders
16089
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
16090
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
16091
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
16092
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
16093
+ * fetching any remote code pre-auth. Contribution stays unconditional —
16094
+ * enrollment state is never leaked pre-auth; visibility is a shell
16095
+ * decision.
16096
+ *
16097
+ * Every contribution carries a `stage`:
16098
+ * - `primary` — shown on the first credentials screen (OIDC /
16099
+ * magic-link buttons; a future usernameless passkey).
16100
+ * - `second-factor` — shown AFTER the password leg, gated on the
16101
+ * returned `factors` (passkey-as-2FA today).
16102
+ *
16103
+ * `mount: skip` — the cap is read server-side by the core auth router
16104
+ * (`registry.getCollection('login-method')`), never mounted as its own
16105
+ * tRPC router.
15909
16106
  */
15910
- var AttachmentSchema = object({
15911
- mediaType: AttachmentMediaTypeSchema,
15912
- url: string().optional(),
15913
- bytes: _instanceof(Uint8Array).optional(),
15914
- mime: string().optional(),
15915
- name: string().optional()
15916
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
15917
- var NotificationFormatSchema = _enum([
15918
- "text",
15919
- "markdown",
15920
- "html"
16107
+ /** When a login method renders in the two-phase login flow. */
16108
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
16109
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
16110
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
16111
+ object({
16112
+ kind: literal("redirect"),
16113
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
16114
+ id: string(),
16115
+ /** Operator-facing button label. */
16116
+ label: string(),
16117
+ /** lucide-react icon name. */
16118
+ icon: string().optional(),
16119
+ /** Addon-owned HTTP route the button navigates to (GET). */
16120
+ startUrl: string(),
16121
+ stage: LoginStageEnum
16122
+ }),
16123
+ object({
16124
+ kind: literal("widget"),
16125
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
16126
+ id: string(),
16127
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
16128
+ addonId: string(),
16129
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
16130
+ bundle: string(),
16131
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
16132
+ remote: WidgetRemoteSchema,
16133
+ stage: LoginStageEnum
16134
+ }),
16135
+ object({
16136
+ kind: literal("passkey"),
16137
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
16138
+ id: string(),
16139
+ /** Operator-facing button label. */
16140
+ label: string(),
16141
+ stage: LoginStageEnum,
16142
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
16143
+ rpId: string(),
16144
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
16145
+ origin: string().nullable()
16146
+ })
15921
16147
  ]);
15922
- /** A single tap-through action button. */
15923
- var NotificationActionSchema = object({
15924
- id: string(),
15925
- label: string(),
15926
- url: string().optional()
16148
+ method(_void(), array(LoginMethodContributionSchema).readonly());
16149
+ var CpuBreakdownSchema = object({
16150
+ total: number(),
16151
+ user: number(),
16152
+ system: number(),
16153
+ irq: number(),
16154
+ nice: number(),
16155
+ loadAvg: tuple([
16156
+ number(),
16157
+ number(),
16158
+ number()
16159
+ ]),
16160
+ cores: number()
16161
+ });
16162
+ var MemoryInfoSchema = object({
16163
+ percent: number(),
16164
+ totalBytes: number(),
16165
+ usedBytes: number(),
16166
+ availableBytes: number(),
16167
+ swapUsedBytes: number(),
16168
+ swapTotalBytes: number()
16169
+ });
16170
+ var DiskIoSnapshotSchema = object({
16171
+ readBytes: number(),
16172
+ writeBytes: number(),
16173
+ readOps: number(),
16174
+ writeOps: number(),
16175
+ timestampMs: number()
16176
+ });
16177
+ var NetworkIoSnapshotSchema = object({
16178
+ rxBytes: number(),
16179
+ txBytes: number(),
16180
+ rxPackets: number(),
16181
+ txPackets: number(),
16182
+ rxErrors: number(),
16183
+ txErrors: number(),
16184
+ timestampMs: number()
16185
+ });
16186
+ var MetricsGpuInfoSchema = object({
16187
+ utilization: number(),
16188
+ model: string(),
16189
+ memoryUsedBytes: number(),
16190
+ memoryTotalBytes: number(),
16191
+ temperature: number().nullable()
16192
+ });
16193
+ var ProcessResourceInfoSchema = object({
16194
+ openFds: number(),
16195
+ threadCount: number(),
16196
+ activeHandles: number(),
16197
+ activeRequests: number()
15927
16198
  });
15928
- /**
15929
- * The canonical notification. `body` is the only hard field (Apprise model).
15930
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
15931
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
15932
- * the adapter maps this ordinal onto its native level. `level?` is an
15933
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
15934
- * `priority` for that one target.
15935
- */
15936
- var NotificationSchema = object({
15937
- body: string(),
15938
- title: string().optional(),
15939
- format: NotificationFormatSchema.default("text"),
15940
- priority: number().int().min(1).max(5).default(3),
15941
- level: string().optional(),
15942
- attachments: array(AttachmentSchema).optional(),
15943
- clickUrl: string().optional(),
15944
- actions: array(NotificationActionSchema).optional(),
15945
- sound: string().optional(),
15946
- ttl: number().optional(),
15947
- tag: string().optional(),
15948
- deviceId: number().optional(),
15949
- eventId: string().optional(),
15950
- metadata: record(string(), unknown()).optional()
16199
+ var PressureAvgsSchema = object({
16200
+ avg10: number(),
16201
+ avg60: number(),
16202
+ avg300: number()
15951
16203
  });
15952
- /** One declared native severity/priority level for a kind. */
15953
- var TargetKindLevelSchema = object({
15954
- id: string(),
15955
- label: string(),
15956
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
15957
- ordinal: number().int().min(1).max(5).nullable(),
15958
- flags: object({
15959
- critical: boolean().optional(),
15960
- silent: boolean().optional(),
15961
- noPush: boolean().optional()
15962
- }).optional(),
15963
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
15964
- requires: array(string()).optional(),
15965
- description: string().optional()
16204
+ var PressureInfoSchema = object({
16205
+ some: PressureAvgsSchema,
16206
+ full: PressureAvgsSchema.nullable()
15966
16207
  });
15967
- /** The full capability block consulted before dispatch. */
15968
- var TargetKindCapsSchema = object({
15969
- attachments: object({
15970
- mediaTypes: array(AttachmentMediaTypeSchema),
15971
- mode: _enum([
15972
- "url",
15973
- "bytes",
15974
- "both"
15975
- ]),
15976
- max: number().int().nonnegative(),
15977
- maxBytes: number().int().positive().optional()
16208
+ var SystemResourceSnapshotSchema = object({
16209
+ cpu: CpuBreakdownSchema,
16210
+ memory: MemoryInfoSchema,
16211
+ gpu: MetricsGpuInfoSchema.nullable(),
16212
+ network: NetworkIoSnapshotSchema,
16213
+ disk: DiskIoSnapshotSchema,
16214
+ pressure: object({
16215
+ cpu: PressureInfoSchema.nullable(),
16216
+ memory: PressureInfoSchema.nullable(),
16217
+ io: PressureInfoSchema.nullable()
15978
16218
  }),
15979
- /** Max action buttons (0 = none). */
15980
- actions: number().int().nonnegative(),
15981
- levels: array(TargetKindLevelSchema),
15982
- format: array(NotificationFormatSchema),
15983
- clickUrl: boolean(),
15984
- sound: boolean(),
15985
- ttl: boolean(),
15986
- bodyMaxLen: number().int().positive()
16219
+ process: ProcessResourceInfoSchema,
16220
+ cpuTemperature: number().nullable(),
16221
+ timestampMs: number()
15987
16222
  });
15988
- /**
15989
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
15990
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
15991
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
15992
- * the union is large and not meant for runtime validation here; the exported
15993
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
15994
- */
15995
- var ConfigSchemaPassthrough = unknown();
15996
- var TargetKindSchema = object({
15997
- kind: string(),
15998
- label: string(),
15999
- icon: string(),
16000
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
16001
- addonId: string(),
16002
- configSchema: ConfigSchemaPassthrough,
16003
- supportsDiscovery: boolean(),
16004
- caps: TargetKindCapsSchema
16223
+ var DiskSpaceInfoSchema = object({
16224
+ path: string(),
16225
+ totalBytes: number(),
16226
+ usedBytes: number(),
16227
+ availableBytes: number(),
16228
+ percent: number()
16005
16229
  });
16006
- /**
16007
- * A persisted target. `config` holds secrets; providers REDACT secret fields
16008
- * (return a presence marker only) when serving `listTargets` — never
16009
- * round-trip a stored secret to the UI.
16010
- */
16011
- var TargetSchema = object({
16012
- id: string(),
16013
- name: string(),
16014
- kind: string(),
16230
+ var PidResourceStatsSchema = object({
16231
+ pid: number(),
16232
+ cpu: number(),
16233
+ memory: number(),
16234
+ /**
16235
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
16236
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
16237
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
16238
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
16239
+ * Undefined where /proc is unavailable (e.g. macOS).
16240
+ */
16241
+ privateBytes: number().optional(),
16242
+ /**
16243
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
16244
+ * code shared copy-on-write across runners. Undefined on macOS.
16245
+ */
16246
+ sharedBytes: number().optional()
16247
+ });
16248
+ var AddonInstanceSchema = object({
16015
16249
  addonId: string(),
16016
- enabled: boolean(),
16017
- config: record(string(), unknown())
16250
+ nodeId: string(),
16251
+ role: _enum(["hub", "worker"]),
16252
+ pid: number(),
16253
+ state: _enum([
16254
+ "starting",
16255
+ "running",
16256
+ "stopping",
16257
+ "stopped",
16258
+ "crashed"
16259
+ ]),
16260
+ uptimeSec: number()
16018
16261
  });
16019
- /** A discovery-surfaced candidate (config is partial + non-secret). */
16020
- var DiscoveredTargetSchema = object({
16021
- kind: string(),
16022
- suggestedName: string(),
16023
- config: record(string(), unknown())
16262
+ var NodeProcessSchema = object({
16263
+ pid: number(),
16264
+ ppid: number(),
16265
+ pgid: number(),
16266
+ classification: _enum([
16267
+ "root",
16268
+ "managed",
16269
+ "system",
16270
+ "ghost"
16271
+ ]),
16272
+ /** `$process` addon binding when `managed`, else null. */
16273
+ addonId: string().nullable(),
16274
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
16275
+ nodeId: string().nullable(),
16276
+ /** Truncated command line. */
16277
+ command: string(),
16278
+ cpuPercent: number(),
16279
+ memoryRssBytes: number(),
16280
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
16281
+ uptimeSec: number(),
16282
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
16283
+ orphaned: boolean()
16024
16284
  });
16025
- /** The degrade engine's report — what was resolved / dropped / degraded. */
16026
- var RenderedAsSchema = object({
16027
- level: string(),
16028
- format: NotificationFormatSchema,
16029
- attachmentsSent: number().int().nonnegative(),
16030
- actionsSent: number().int().nonnegative(),
16031
- truncated: boolean(),
16032
- dropped: array(string())
16285
+ var KillProcessInputSchema = object({
16286
+ pid: number(),
16287
+ /** Force = SIGKILL. Default is SIGTERM. */
16288
+ force: boolean().optional()
16033
16289
  });
16034
- var SendResultSchema = object({
16290
+ var KillProcessResultSchema = object({
16035
16291
  success: boolean(),
16036
- error: string().optional(),
16037
- renderedAs: RenderedAsSchema.optional()
16292
+ reason: string().optional(),
16293
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
16294
+ });
16295
+ var DumpHeapSnapshotInputSchema = object({
16296
+ /** The addon whose runner should dump a heap snapshot. */
16297
+ addonId: string() });
16298
+ var DumpHeapSnapshotResultSchema = object({
16299
+ success: boolean(),
16300
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
16301
+ path: string().optional(),
16302
+ /** Process pid that was signalled. */
16303
+ pid: number().optional(),
16304
+ reason: string().optional()
16305
+ });
16306
+ var SystemMetricsSchema = object({
16307
+ cpuPercent: number(),
16308
+ memoryPercent: number(),
16309
+ memoryUsedMB: number(),
16310
+ memoryTotalMB: number(),
16311
+ diskPercent: number().optional(),
16312
+ temperature: number().optional(),
16313
+ gpuPercent: number().optional(),
16314
+ gpuMemoryPercent: number().optional()
16315
+ });
16316
+ 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, {
16317
+ kind: "mutation",
16318
+ auth: "admin"
16319
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
16320
+ kind: "mutation",
16321
+ auth: "admin"
16322
+ });
16323
+ method(object({
16324
+ sourceUrl: string(),
16325
+ metadata: ModelConvertMetadataSchema,
16326
+ targets: array(ConvertTargetSchema).min(1).readonly(),
16327
+ calibrationRef: string().optional(),
16328
+ sessionId: string().optional()
16329
+ }), ConvertResultSchema, {
16330
+ kind: "mutation",
16331
+ auth: "admin",
16332
+ timeoutMs: 6e5
16333
+ });
16334
+ method(object({
16335
+ nodeId: string(),
16336
+ modelId: string(),
16337
+ format: _enum(MODEL_FORMATS),
16338
+ entry: ModelCatalogEntrySchema
16339
+ }), object({
16340
+ ok: boolean(),
16341
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
16342
+ sha256: string(),
16343
+ bytes: number(),
16344
+ /** The target node's modelsDir the artifact landed in. */
16345
+ path: string()
16346
+ }), {
16347
+ kind: "mutation",
16348
+ auth: "admin"
16038
16349
  });
16039
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
16040
- var TestResultSchema = SendResultSchema;
16041
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
16042
- kind: string(),
16043
- config: record(string(), unknown()).optional()
16044
- }), array(DiscoveredTargetSchema)), method(object({
16045
- targetId: string(),
16046
- notification: NotificationSchema
16047
- }), SendResultSchema, { kind: "mutation" }), method(object({
16048
- targetId: string(),
16049
- sample: NotificationSchema.optional()
16050
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
16051
- targetId: string(),
16052
- enabled: boolean()
16053
- }), _void(), { kind: "mutation" });
16054
16350
  /**
16055
- * notification-rulesthe Notification Center rule surface (P1 core).
16351
+ * `mqtt-broker`broker-registry cap.
16056
16352
  *
16057
- * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16058
- * (operator decisions D-1/D-2/D-3 are binding):
16353
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
16354
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
16355
+ * and (b) the connection details a consumer addon needs to spin up
16356
+ * its OWN `mqtt.js` client.
16059
16357
  *
16060
- * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16061
- * `notification-center` module), hooked on the durable persistence
16062
- * moments (object-event insert, TrackCloser.closeExpired) with a
16063
- * persisted outbox + retry never the lossy telemetry bus (D8).
16064
- * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16065
- * FIRST persisted detection matching the conditions (per-track dedup,
16066
- * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16067
- * `delivery: 'track-end'` evaluates the finalized track record at close.
16068
- * - DISPATCH stays behind `notification-output` (rules reference targets
16069
- * by id; per-backend params are a passthrough blob capped by the
16070
- * target kind's own caps/degrade engine).
16358
+ * Why: pub/sub routing over the system event-bus loses fidelity
16359
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
16360
+ * refcount bookkeeping that addons would rather own themselves. The
16361
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
16362
+ * features anyway give it the connection config, get out of the way.
16071
16363
  *
16072
- * P1 scope: admin-authored rules only (`createdBy` stamped from the
16073
- * server-injected caller identity the first `caller: 'required'`
16074
- * adopter). The P1 condition subset is: devices, classes(+exclude),
16075
- * minConfidence, admin zones (any/all + exclude), weekly schedule
16076
- * windows, and the optional label/identity/plate matchers. User rules,
16077
- * private zones, per-recipient fan-out and the wider condition table are
16078
- * P2+ (see spec §7).
16364
+ * Consumer flow:
16365
+ * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
16366
+ * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
16367
+ * client.subscribe('zigbee2mqtt/+')
16079
16368
  *
16080
- * All schemas here are the single source of truth — `NcRule` etc. are
16081
- * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16082
- * schema/interface drift is explicitly not repeated).
16369
+ * Collection mode: multiple brokers (e.g. one local mosquitto + one
16370
+ * cloud bridge). The "embedded" entry (when present) is just another
16371
+ * broker in the registry — its lifecycle is owned by the addon that
16372
+ * spawned it.
16083
16373
  */
16374
+ var BrokerKindSchema = _enum(["external", "embedded"]);
16084
16375
  /**
16085
- * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
16086
- * The value maps 1:1 onto the evaluated record kind:
16087
- * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16088
- * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16089
- * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16090
- * change of a LINKED device, one row per linked camera)
16091
- * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16092
- * delivery / pick-up)
16376
+ * Broker live-probe status.
16093
16377
  *
16094
- * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16095
- * `package-event` are pure trigger kinds (no urgency dimension). Extending
16096
- * this one field keeps the schema additive a rule still declares exactly
16097
- * one trigger.
16378
+ * - `connected` last probe completed a clean CONNACK
16379
+ * - `disconnected` no probe has run yet (cold cache)
16380
+ * - `auth-failed` CONNACK refused with auth error (RC 4 / 5)
16381
+ * - `unreachable` — TCP connect timed out / refused
16382
+ * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
16098
16383
  */
16099
- var NcDeliverySchema = _enum([
16100
- "immediate",
16101
- "track-end",
16102
- "device-event",
16103
- "package-event"
16384
+ var BrokerStatusSchema$1 = _enum([
16385
+ "connected",
16386
+ "disconnected",
16387
+ "auth-failed",
16388
+ "unreachable",
16389
+ "tls-error"
16104
16390
  ]);
16105
- /** Weekly schedule — OR of windows; absence on the rule = always active. */
16106
- var NcScheduleSchema = object({
16107
- windows: array(object({
16108
- /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16109
- days: array(number().int().min(0).max(6)).min(1),
16110
- startMinute: number().int().min(0).max(1439),
16111
- endMinute: number().int().min(0).max(1439)
16112
- })).min(1),
16113
- /** IANA timezone; default = hub host timezone. */
16114
- timezone: string().optional(),
16115
- /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16116
- invert: boolean().optional()
16117
- });
16118
- /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16119
- var NcPlateMatcherSchema = object({
16120
- values: array(string().min(1)).min(1),
16121
- /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16122
- maxDistance: number().int().min(0).max(3).default(1)
16123
- });
16124
- /**
16125
- * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16126
- * occupancy edge for a device — optionally narrowed to a single admin
16127
- * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16128
- * - `became-occupied` (default) — count crossed 0 → ≥ `count`
16129
- * - `became-free` — count crossed ≥ `count` → below it
16130
- * - `>=` / `<=` — count is at/over or at/under `count`
16131
- * `sustainSeconds` requires the condition hold continuously that long
16132
- * before firing (debounces flicker; 0 = fire on the first matching edge).
16133
- * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16134
- * the condition never matches. Confirmed edge-state survives addon restarts
16135
- * (declared SQLite collection, reseeded on boot).
16136
- */
16137
- var NcOccupancyConditionSchema = object({
16138
- /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16139
- zoneId: string().optional(),
16140
- /** Object class to count; absent = any class. */
16141
- className: string().optional(),
16142
- op: _enum([
16143
- "became-occupied",
16144
- "became-free",
16145
- ">=",
16146
- "<="
16147
- ]).default("became-occupied"),
16148
- count: number().int().min(0).default(1),
16149
- sustainSeconds: number().int().min(0).max(3600).default(15)
16150
- });
16151
- /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16152
- var NcZoneConditionSchema = object({
16153
- ids: array(string().min(1)).min(1),
16154
- /** Quantifier over `ids` — at least one / every one visited. */
16155
- match: _enum(["any", "all"]).default("any")
16156
- });
16157
- /**
16158
- * The P1 condition set — a flat AND of groups; absent group = pass;
16159
- * membership lists are OR within the list (spec §2.3).
16160
- */
16161
- var NcConditionsSchema = object({
16162
- /** Device scope — absent = all devices. */
16163
- devices: array(number()).optional(),
16164
- /** Detector class names (any overlap with the record's class set). */
16165
- classes: array(string().min(1)).optional(),
16166
- /** Veto classes — any overlap fails the rule. */
16167
- classesExclude: array(string().min(1)).optional(),
16168
- /** Minimum detection confidence 0–1 (fails when the record has none). */
16169
- minConfidence: number().min(0).max(1).optional(),
16170
- /** Admin zone membership over event `zones` / track `zonesVisited`. */
16171
- zones: NcZoneConditionSchema.optional(),
16172
- /** Veto zones — any hit fails the rule. */
16173
- zonesExclude: array(string().min(1)).optional(),
16174
- /**
16175
- * Exact (case-insensitive) match on the record's collapsed `label`
16176
- * (identity name / plate text / subclass).
16177
- */
16178
- labelEquals: array(string().min(1)).optional(),
16179
- /**
16180
- * Identity matcher. P1 boundary: matched against the record's collapsed
16181
- * `label` (the identity display name propagated by the face pipeline) —
16182
- * identity-ID matching rides in P2 when identity ids reach the record.
16183
- */
16184
- identities: array(string().min(1)).optional(),
16185
- /** Fuzzy plate matcher against the record's `label` (plate text). */
16186
- plates: NcPlateMatcherSchema.optional(),
16187
- /**
16188
- * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16189
- * Same P1 boundary: matched against the record's collapsed `label` (the
16190
- * identity display name). A record with NO label passes (nothing to
16191
- * exclude), unlike the include variant which fails on an absent label.
16192
- */
16193
- identitiesExclude: array(string().min(1)).optional(),
16194
- /**
16195
- * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16196
- * TRACK-END only: importance is scored at track close, so it does not exist
16197
- * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16198
- * close the value is threaded via the close-time info (the `Track` clone is
16199
- * captured before the DB row is updated, so it would otherwise read stale).
16200
- * Fails when the record carries no importance (never guess quality — the
16201
- * `minConfidence` precedent). MVP cut: a single scalar threshold.
16202
- */
16203
- minImportance: number().min(0).max(1).optional(),
16204
- /**
16205
- * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16206
- * TRACK-END only: an `immediate` / object-event subject has no closed
16207
- * lifespan, so a dwell condition never matches immediate delivery
16208
- * (documented choice — the object-event record carries no `firstSeen`,
16209
- * so dwell cannot be computed from what the subject actually carries).
16210
- */
16211
- minDwellSeconds: number().min(0).optional(),
16212
- /**
16213
- * Detection provenance filter. `any` (default / absent) matches every
16214
- * source; otherwise the subject's source must equal it. Legacy records
16215
- * with no stamped source are treated as `pipeline`. The union spans both
16216
- * record kinds — object events carry `pipeline` | `onboard`, synthetic
16217
- * tracks carry `sensor`.
16218
- */
16219
- source: _enum([
16220
- "pipeline",
16221
- "onboard",
16222
- "sensor",
16223
- "any"
16224
- ]).optional(),
16225
- /**
16226
- * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16227
- * detector `minConfidence` (that gates the object-detection score; this
16228
- * gates the recognition/OCR match score). Fails when the subject carries
16229
- * no label-match confidence (never guess). TRACK-END only: the confidence
16230
- * lives on the recognition result and reaches the subject at track close.
16231
- *
16232
- * What it measures precisely (plumbed at track close — the closer threads
16233
- * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16234
- * `importance`): the BEST recognition match confidence observed for the
16235
- * label the track carries at close — for a face, the peak cosine similarity
16236
- * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16237
- * for a plate, the peak OCR read score of the best-held plate
16238
- * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16239
- * one track the higher of the two is used. A track that ended with no
16240
- * confident identity/plate match carries no value, so the condition fails
16241
- * closed for it (an un-recognized subject).
16242
- */
16243
- minLabelConfidence: number().min(0).max(1).optional(),
16244
- /**
16245
- * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16246
- * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16247
- * against the token carried on the device-event subject (extracted from the
16248
- * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16249
- * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16250
- * eventType, so gate those with {@link sensorKinds} instead.
16251
- */
16252
- eventTypeTokens: array(string().min(1)).optional(),
16253
- /**
16254
- * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16255
- * `contact`, `button`, `device-event`) — matched against the persisted
16256
- * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16257
- */
16258
- sensorKinds: array(string().min(1)).optional(),
16259
- /**
16260
- * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16261
- * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16262
- * when the subject's phase does not match (a subject always carries a phase
16263
- * on the package-event trigger).
16264
- */
16265
- packagePhase: _enum([
16266
- "delivered",
16267
- "picked-up",
16268
- "both"
16269
- ]).optional(),
16270
- /**
16271
- * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16272
- * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16273
- * listed polygon (ZoneEngine membership semantics). Evaluated only when
16274
- * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16275
- */
16276
- customZones: array(MaskPolygonShapeSchema).optional(),
16277
- /**
16278
- * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16279
- * (optionally zone/class-scoped) occupancy count crosses the configured
16280
- * threshold and holds for `sustainSeconds`. Fail-closed on missing
16281
- * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16282
- */
16283
- occupancy: NcOccupancyConditionSchema.optional()
16391
+ var BrokerInfoSchema = object({
16392
+ id: string(),
16393
+ name: string(),
16394
+ url: string(),
16395
+ kind: BrokerKindSchema,
16396
+ status: BrokerStatusSchema$1,
16397
+ latencyMs: number().nullable(),
16398
+ error: string().optional(),
16399
+ /** Embedded brokers only: number of MQTT clients currently connected. */
16400
+ connectedClients: number().int().nonnegative().optional(),
16401
+ /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
16402
+ lastCheckedAt: number().optional()
16284
16403
  });
16285
- /** One delivery target: a `notification-output` Target ref + passthrough params. */
16286
- var NcRuleTargetSchema = object({
16287
- /** `notification-output` Target id. */
16288
- targetId: string().min(1),
16404
+ /**
16405
+ * Connection details — what a consumer needs to call
16406
+ * `mqtt.connect(url, options)`. We split URL + credentials so the
16407
+ * consumer can pass them as `mqtt.connect(url, { username, password })`
16408
+ * instead of stuffing creds into the URL (which leaks them into logs).
16409
+ */
16410
+ var BrokerConnectionDetailsSchema = object({
16411
+ url: string(),
16412
+ username: string().optional(),
16413
+ password: string().optional(),
16289
16414
  /**
16290
- * Per-backend passthrough. Recognized keys are mapped onto the canonical
16291
- * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16292
- * degrade engine drops what the backend can't render.
16415
+ * Suggested prefix for `clientId`. Each consumer should suffix this
16416
+ * with its own discriminator (addon id, instance id) so reconnects
16417
+ * don't kick each other off (MQTT spec: clientId must be unique per
16418
+ * broker).
16293
16419
  */
16294
- params: record(string(), unknown()).optional()
16420
+ clientIdPrefix: string().optional()
16421
+ });
16422
+ var AddBrokerInputSchema = object({
16423
+ name: string().min(1),
16424
+ url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
16425
+ username: string().optional(),
16426
+ password: string().optional(),
16427
+ clientIdPrefix: string().optional()
16428
+ });
16429
+ var AddBrokerResultSchema = object({ id: string() });
16430
+ var IdInputSchema = object({ id: string() });
16431
+ var TestResultSchema$1 = discriminatedUnion("ok", [object({
16432
+ ok: literal(true),
16433
+ latencyMs: number()
16434
+ }), object({
16435
+ ok: literal(false),
16436
+ error: string()
16437
+ })]);
16438
+ var StartEmbeddedInputSchema = object({
16439
+ port: number().int().min(1).max(65535).default(1883),
16440
+ /** Allow anonymous connect (no username/password). Default: false. */
16441
+ allowAnonymous: boolean().default(false),
16442
+ /** Optional shared username/password for clients. */
16443
+ username: string().optional(),
16444
+ password: string().optional()
16445
+ });
16446
+ var StartEmbeddedResultSchema = object({
16447
+ id: string(),
16448
+ url: string()
16449
+ });
16450
+ var StatusSchema = object({
16451
+ brokerCount: number(),
16452
+ embeddedRunning: boolean()
16453
+ });
16454
+ 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);
16455
+ var NetworkEndpointSchema = object({
16456
+ url: string(),
16457
+ hostname: string(),
16458
+ port: number(),
16459
+ protocol: _enum(["http", "https"])
16460
+ });
16461
+ var NetworkAccessStatusSchema = object({
16462
+ connected: boolean(),
16463
+ endpoint: NetworkEndpointSchema.nullable(),
16464
+ error: string().optional()
16295
16465
  });
16296
16466
  /**
16297
- * Media attachment policy (P1 still-image subset).
16298
- * - `best` the best AVAILABLE subject image at dispatch time (D-3).
16299
- * - `best-matching` the media that explains WHY the rule fired: a rule
16300
- * matched on identities attaches the subject's `faceCrop`, one matched on
16301
- * plates attaches the `plateCrop`; a rule with no identity/plate condition
16302
- * (or when the specific crop is missing) degrades to `best`, then
16303
- * `keyFrame`, then no attachment — never delaying the send. The matched
16304
- * condition summary is frozen on the outbox row at enqueue (like the rule
16305
- * name), so the choice never drifts from the record that fired it.
16306
- * - `keyFrame` — the clean scene frame (no subject box).
16307
- * - `none` — no attachment.
16467
+ * Optional, richer endpoint shape returned by providers that expose
16468
+ * MORE than one ingress concurrently (Tailscale Ingress with mixed
16469
+ * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
16470
+ * the originating provider config (mode + sourcePort) so the
16471
+ * orchestrator UI can label rows distinctly. Providers that expose only
16472
+ * one endpoint just omit `listEndpoints` from their provider impl.
16308
16473
  */
16309
- var NcMediaPolicySchema = object({ attach: _enum([
16310
- "best",
16311
- "best-matching",
16312
- "keyFrame",
16313
- "none"
16314
- ]).default("best") });
16315
- /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16316
- var NcThrottleSchema = object({
16317
- cooldownSec: number().int().min(0).max(86400).default(60),
16318
- /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16319
- scope: _enum(["rule", "rule-device"]).default("rule-device")
16320
- });
16321
- /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16322
- var NcRuleInputSchema = object({
16323
- name: string().min(1).max(200),
16324
- enabled: boolean().default(true),
16325
- delivery: NcDeliverySchema,
16326
- conditions: NcConditionsSchema.default({}),
16327
- schedule: NcScheduleSchema.optional(),
16328
- targets: array(NcRuleTargetSchema).min(1),
16329
- media: NcMediaPolicySchema.default({ attach: "best" }),
16330
- throttle: NcThrottleSchema.default({
16331
- cooldownSec: 60,
16332
- scope: "rule-device"
16333
- }),
16334
- /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16335
- template: object({
16336
- title: string().max(500).optional(),
16337
- body: string().max(2e3).optional()
16338
- }).optional(),
16339
- /** Canonical notification priority ordinal (1..5); per-target overridable. */
16340
- priority: number().int().min(1).max(5).default(3),
16474
+ var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
16341
16475
  /**
16342
- * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16343
- * behaviour, visible to all, read-only in the viewer). Present = personal
16344
- * rule owned by this userId. Server-stamped; never trusted from a client.
16476
+ * Stable id within the provider typically `<mode>-<sourcePort>` so
16477
+ * the orchestrator can dedupe across `listEndpoints` polls.
16345
16478
  */
16346
- ownerUserId: string().optional()
16479
+ id: string(),
16480
+ /** Operator-facing label (mirrors `MeshEndpoint.label`). */
16481
+ label: string(),
16482
+ /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
16483
+ mode: string().optional(),
16484
+ /** Originating local port the ingress fronts (informational). */
16485
+ sourcePort: number().optional()
16347
16486
  });
16487
+ method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
16348
16488
  /**
16349
- * Partial patch for `updateRule` any subset of the input fields, plus the
16350
- * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16351
- * NOT a client-authored input field (it lives on the persisted rule, not the
16352
- * input), so it is added here explicitly to let the store's per-target opt-out
16353
- * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16354
- * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16355
- * `updateRule` patch.
16489
+ * notification-outputcanonical, capability-gated notification delivery.
16490
+ *
16491
+ * Apprise-derived model (see
16492
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
16493
+ * callers emit ONE canonical `Notification`; each provider declares a
16494
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
16495
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
16496
+ * message to what the kind supports — callers never special-case a service.
16497
+ *
16498
+ * DESIGN DECISIONS (locked):
16499
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
16500
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
16501
+ * cap. Rationale: the admin UI needs one uniform surface across the
16502
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
16503
+ * alternative would fork the UI per addon and cannot host the
16504
+ * discovery→adopt flow.
16505
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
16506
+ * the generated cap-mount auto-`concatCollection`-fans them across every
16507
+ * registered provider (notifiers addon + HA addon) so one catalog is
16508
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
16509
+ * `addonId` the generated collection router extracts from the call input.
16510
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
16511
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
16512
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
16513
+ * base64 fallback needed.
16514
+ *
16515
+ * TODO (deferred, closed-set change — separate decision): add
16516
+ * `providerKind: 'notify'` so notification providers surface on the unified
16517
+ * admin "Integrations" page.
16356
16518
  */
16357
- var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
16358
- /** A persisted rule. */
16359
- var NcRuleSchema = NcRuleInputSchema.extend({
16519
+ /**
16520
+ * Zentik-derived typed-media enum — the superset across every kind. Each
16521
+ * adapter picks what it supports and the degrade engine filters the rest.
16522
+ */
16523
+ var AttachmentMediaTypeSchema = _enum([
16524
+ "image",
16525
+ "video",
16526
+ "gif",
16527
+ "audio",
16528
+ "icon"
16529
+ ]);
16530
+ /**
16531
+ * A single attachment. Exactly one of `url` (remote source, most adapters
16532
+ * prefer this) or `bytes` (inline source; required for Pushover-style
16533
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
16534
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
16535
+ */
16536
+ var AttachmentSchema = object({
16537
+ mediaType: AttachmentMediaTypeSchema,
16538
+ url: string().optional(),
16539
+ bytes: _instanceof(Uint8Array).optional(),
16540
+ mime: string().optional(),
16541
+ name: string().optional()
16542
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
16543
+ var NotificationFormatSchema = _enum([
16544
+ "text",
16545
+ "markdown",
16546
+ "html"
16547
+ ]);
16548
+ /** A single tap-through action button. */
16549
+ var NotificationActionSchema = object({
16360
16550
  id: string(),
16361
- /** userId of the admin who created the rule (server-stamped caller). */
16362
- createdBy: string(),
16363
- createdAt: number(),
16364
- updatedAt: number(),
16365
- /**
16366
- * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16367
- * send time. Only a target's OWNER may add/remove its id (server-checked
16368
- * in `nc.setRuleTargetEnabled`). Defaults to empty.
16369
- */
16370
- disabledTargetIds: array(string()).default([])
16551
+ label: string(),
16552
+ url: string().optional()
16371
16553
  });
16372
- var NcTestResultSchema = object({
16373
- recordId: string(),
16374
- recordKind: _enum([
16375
- "object-event",
16376
- "track",
16377
- "device-event",
16378
- "package-event"
16379
- ]),
16380
- deviceId: number(),
16381
- timestamp: number(),
16382
- wouldFire: boolean(),
16383
- /** Condition id that failed (first failing group), when `wouldFire` is false. */
16384
- failedCondition: string().optional(),
16385
- className: string().optional(),
16386
- label: string().optional()
16554
+ /**
16555
+ * The canonical notification. `body` is the only hard field (Apprise model).
16556
+ * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
16557
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
16558
+ * the adapter maps this ordinal onto its native level. `level?` is an
16559
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
16560
+ * `priority` for that one target.
16561
+ */
16562
+ var NotificationSchema = object({
16563
+ body: string(),
16564
+ title: string().optional(),
16565
+ format: NotificationFormatSchema.default("text"),
16566
+ priority: number().int().min(1).max(5).default(3),
16567
+ level: string().optional(),
16568
+ attachments: array(AttachmentSchema).optional(),
16569
+ clickUrl: string().optional(),
16570
+ actions: array(NotificationActionSchema).optional(),
16571
+ sound: string().optional(),
16572
+ ttl: number().optional(),
16573
+ tag: string().optional(),
16574
+ deviceId: number().optional(),
16575
+ eventId: string().optional(),
16576
+ metadata: record(string(), unknown()).optional()
16387
16577
  });
16388
- var NcConditionDescriptorSchema = object({
16389
- /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16578
+ /** One declared native severity/priority level for a kind. */
16579
+ var TargetKindLevelSchema = object({
16390
16580
  id: string(),
16391
- group: _enum([
16392
- "scope",
16393
- "class",
16394
- "zones",
16395
- "quality",
16396
- "label",
16397
- "schedule",
16398
- "device",
16399
- "package",
16400
- "occupancy"
16401
- ]),
16402
16581
  label: string(),
16403
- /** Editor widget the UI renders never hardcode per-condition forms. */
16404
- valueType: _enum([
16405
- "deviceIdList",
16406
- "stringList",
16407
- "number01",
16408
- "number",
16409
- "sourceSelect",
16410
- "zoneSelection",
16411
- "zoneIdList",
16412
- "schedule",
16413
- "plateMatcher",
16414
- "packagePhase",
16415
- "polygonDraw",
16416
- "occupancy"
16417
- ]),
16418
- operator: _enum([
16419
- "in",
16420
- "notIn",
16421
- "anyOf",
16422
- "allOf",
16423
- "gte",
16424
- "fuzzyIn",
16425
- "withinSchedule"
16426
- ]),
16427
- /** Which delivery kinds the condition applies to. */
16428
- appliesTo: array(NcDeliverySchema),
16429
- phase: string(),
16582
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
16583
+ ordinal: number().int().min(1).max(5).nullable(),
16584
+ flags: object({
16585
+ critical: boolean().optional(),
16586
+ silent: boolean().optional(),
16587
+ noPush: boolean().optional()
16588
+ }).optional(),
16589
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
16590
+ requires: array(string()).optional(),
16430
16591
  description: string().optional()
16431
16592
  });
16593
+ /** The full capability block consulted before dispatch. */
16594
+ var TargetKindCapsSchema = object({
16595
+ attachments: object({
16596
+ mediaTypes: array(AttachmentMediaTypeSchema),
16597
+ mode: _enum([
16598
+ "url",
16599
+ "bytes",
16600
+ "both"
16601
+ ]),
16602
+ max: number().int().nonnegative(),
16603
+ maxBytes: number().int().positive().optional()
16604
+ }),
16605
+ /** Max action buttons (0 = none). */
16606
+ actions: number().int().nonnegative(),
16607
+ levels: array(TargetKindLevelSchema),
16608
+ format: array(NotificationFormatSchema),
16609
+ clickUrl: boolean(),
16610
+ sound: boolean(),
16611
+ ttl: boolean(),
16612
+ bodyMaxLen: number().int().positive()
16613
+ });
16432
16614
  /**
16433
- * The delivery lifecycle status of a history row a straight read of the
16434
- * durable outbox row's own status (single source of truth):
16435
- * - `pending` — enqueued, in-flight or retrying with backoff
16436
- * - `sent` — delivered (terminal)
16437
- * - `dead` dead-lettered after exhausting retries / a permanent
16438
- * backend rejection / a deleted target (terminal; carries
16439
- * the failure `error`)
16440
- *
16441
- * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
16442
- * user dimension (quiet hours / snooze) and are additive when they land.
16615
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
16616
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
16617
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
16618
+ * the union is large and not meant for runtime validation here; the exported
16619
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
16443
16620
  */
16444
- var NcHistoryStatusSchema = _enum([
16445
- "pending",
16446
- "sent",
16447
- "dead"
16448
- ]);
16449
- /** The evaluated record kind a history row descends from (one per trigger). */
16450
- var NcHistoryRecordKindSchema = _enum([
16451
- "object-event",
16452
- "track-end",
16453
- "device-event",
16454
- "package-event"
16455
- ]);
16456
- /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16457
- var NcHistorySubjectSchema = object({
16458
- className: string(),
16459
- label: string().optional(),
16460
- confidence: number().optional(),
16461
- zones: array(string()),
16462
- timestamp: number()
16621
+ var ConfigSchemaPassthrough = unknown();
16622
+ var TargetKindSchema = object({
16623
+ kind: string(),
16624
+ label: string(),
16625
+ icon: string(),
16626
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
16627
+ addonId: string(),
16628
+ configSchema: ConfigSchemaPassthrough,
16629
+ supportsDiscovery: boolean(),
16630
+ caps: TargetKindCapsSchema
16463
16631
  });
16464
16632
  /**
16465
- * One delivery-history row. This is a read-only VIEW over the durable
16466
- * outbox row (single source of truth the same row the drain loop drives;
16467
- * NO second write path, so history can never drift from delivery state).
16468
- * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16469
- * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16470
- * (fire) / `updatedAt` (last transition), `status` + `error` are the
16471
- * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16472
- * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16473
- * P1 (admin scope only).
16633
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
16634
+ * (return a presence marker only) when serving `listTargets` never
16635
+ * round-trip a stored secret to the UI.
16474
16636
  */
16475
- var NcHistoryEntrySchema = object({
16476
- /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16637
+ var TargetSchema = object({
16477
16638
  id: string(),
16478
- ruleId: string(),
16479
- /** Rule name frozen at fire time (outlives a later rename / delete). */
16480
- ruleName: string(),
16481
- /** The rule urgency/trigger that produced this delivery. */
16482
- delivery: NcDeliverySchema,
16483
- targetId: string(),
16484
- deviceId: number(),
16485
- recordKind: NcHistoryRecordKindSchema,
16486
- /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16487
- recordId: string(),
16488
- /** Present for track-scoped deliveries (object-event / track-end). */
16489
- trackId: string().optional(),
16490
- status: NcHistoryStatusSchema,
16491
- /** Delivery attempts made so far. */
16492
- attempts: number().int(),
16493
- /** Fire time (outbox enqueue). */
16494
- createdAt: number(),
16495
- /** Last transition time (terminal for sent / dead). */
16496
- updatedAt: number(),
16497
- /** Failure detail — present on a `dead` row. */
16498
- error: string().optional(),
16499
- subject: NcHistorySubjectSchema
16639
+ name: string(),
16640
+ kind: string(),
16641
+ addonId: string(),
16642
+ enabled: boolean(),
16643
+ config: record(string(), unknown())
16500
16644
  });
16501
- /**
16502
- * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16503
- * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16504
- * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16505
- * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16506
- */
16507
- var NcHistoryFilterSchema = object({
16508
- ruleId: string().optional(),
16509
- deviceId: number().optional(),
16510
- status: NcHistoryStatusSchema.optional(),
16511
- since: number().optional(),
16512
- until: number().optional(),
16513
- limit: number().int().min(1).max(500).default(100)
16645
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
16646
+ var DiscoveredTargetSchema = object({
16647
+ kind: string(),
16648
+ suggestedName: string(),
16649
+ config: record(string(), unknown())
16514
16650
  });
16515
- 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 }), {
16516
- kind: "mutation",
16517
- auth: "admin",
16518
- caller: "required"
16519
- }), method(object({
16520
- ruleId: string(),
16521
- patch: NcRulePatchSchema
16522
- }), object({ rule: NcRuleSchema }), {
16523
- kind: "mutation",
16524
- auth: "admin",
16525
- caller: "required"
16526
- }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
16527
- kind: "mutation",
16528
- auth: "admin"
16529
- }), method(object({
16530
- ruleId: string(),
16651
+ /** The degrade engine's report what was resolved / dropped / degraded. */
16652
+ var RenderedAsSchema = object({
16653
+ level: string(),
16654
+ format: NotificationFormatSchema,
16655
+ attachmentsSent: number().int().nonnegative(),
16656
+ actionsSent: number().int().nonnegative(),
16657
+ truncated: boolean(),
16658
+ dropped: array(string())
16659
+ });
16660
+ var SendResultSchema = object({
16661
+ success: boolean(),
16662
+ error: string().optional(),
16663
+ renderedAs: RenderedAsSchema.optional()
16664
+ });
16665
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
16666
+ var TestResultSchema = SendResultSchema;
16667
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
16668
+ kind: string(),
16669
+ config: record(string(), unknown()).optional()
16670
+ }), array(DiscoveredTargetSchema)), method(object({
16671
+ targetId: string(),
16672
+ notification: NotificationSchema
16673
+ }), SendResultSchema, { kind: "mutation" }), method(object({
16674
+ targetId: string(),
16675
+ sample: NotificationSchema.optional()
16676
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
16677
+ targetId: string(),
16531
16678
  enabled: boolean()
16532
- }), object({ success: literal(true) }), {
16533
- kind: "mutation",
16534
- auth: "admin"
16535
- }), method(object({
16536
- rule: NcRuleInputSchema,
16537
- lookbackMinutes: number().int().min(1).max(1440).default(60)
16538
- }), object({ results: array(NcTestResultSchema) }), {
16539
- kind: "mutation",
16540
- auth: "admin"
16541
- }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
16679
+ }), _void(), { kind: "mutation" });
16542
16680
  /**
16543
16681
  * Zod schemas for persisted record types.
16544
16682
  *
@@ -25431,6 +25569,36 @@ Object.freeze({
25431
25569
  addonId: null,
25432
25570
  access: "create"
25433
25571
  },
25572
+ "terminalSession.close": {
25573
+ capName: "terminal-session",
25574
+ capScope: "system",
25575
+ addonId: null,
25576
+ access: "create"
25577
+ },
25578
+ "terminalSession.listProfiles": {
25579
+ capName: "terminal-session",
25580
+ capScope: "system",
25581
+ addonId: null,
25582
+ access: "view"
25583
+ },
25584
+ "terminalSession.listSessions": {
25585
+ capName: "terminal-session",
25586
+ capScope: "system",
25587
+ addonId: null,
25588
+ access: "view"
25589
+ },
25590
+ "terminalSession.openSession": {
25591
+ capName: "terminal-session",
25592
+ capScope: "system",
25593
+ addonId: null,
25594
+ access: "create"
25595
+ },
25596
+ "terminalSession.resize": {
25597
+ capName: "terminal-session",
25598
+ capScope: "system",
25599
+ addonId: null,
25600
+ access: "create"
25601
+ },
25434
25602
  "toast.onToast": {
25435
25603
  capName: "toast",
25436
25604
  capScope: "system",
@@ -25910,7 +26078,7 @@ var AdminUIAddon = class extends BaseAddon {
25910
26078
  capability: adminUiCapability,
25911
26079
  provider: {
25912
26080
  getStaticDir: async () => ({ staticDir: resolveAdminUiDistDir() }),
25913
- getVersion: async () => ({ version: "1.2.13" })
26081
+ getVersion: async () => ({ version: "1.2.15" })
25914
26082
  }
25915
26083
  }];
25916
26084
  }