@camstack/addon-ai 0.2.3 → 0.2.5

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 (3) hide show
  1. package/dist/addon.js +1649 -1097
  2. package/dist/addon.mjs +1649 -1097
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -5,7 +5,7 @@ import { createReadStream } from "node:fs";
5
5
  import * as fsp from "node:fs/promises";
6
6
  import { spawn } from "node:child_process";
7
7
  import { createServer } from "node:net";
8
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
8
+ //#region ../types/dist/event-category-BLcNejAE.mjs
9
9
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
10
10
  EventCategory["SystemBoot"] = "system.boot";
11
11
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -155,9 +155,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
155
155
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
156
156
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
157
157
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
158
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
159
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
160
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
161
158
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
162
159
  * progress bar the client reconciles via `recordingExport.getExport`. */
163
160
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6822,7 +6819,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6822
6819
  patch: record(string(), unknown())
6823
6820
  }), object({ success: literal(true) });
6824
6821
  object({ deviceId: number() }), unknown().nullable();
6825
- /** Shorthand to define a method schema */
6826
6822
  function method(input, output, options) {
6827
6823
  return {
6828
6824
  input,
@@ -6830,6 +6826,7 @@ function method(input, output, options) {
6830
6826
  kind: options?.kind ?? "query",
6831
6827
  auth: options?.auth ?? "protected",
6832
6828
  ...options?.access !== void 0 ? { access: options.access } : {},
6829
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6833
6830
  timeoutMs: options?.timeoutMs
6834
6831
  };
6835
6832
  }
@@ -8213,6 +8210,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8213
8210
  /** The complete taxonomy dictionary, keyed by kind. */
8214
8211
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8215
8212
  /**
8213
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8214
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8215
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8216
+ * taxonomy surface (timeline, filters, event page).
8217
+ *
8218
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8219
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8220
+ * for the `classes` / `classesExclude` conditions.
8221
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8222
+ * the same class picker, grouped under an Audio header.
8223
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8224
+ * lock / …) for the `sensorKinds` device-event condition.
8225
+ *
8226
+ * Each entry carries `parentKind` so the client can group video subs under
8227
+ * their macro and sensor/control kinds under their category. This surface is
8228
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8229
+ * method, no codegen — so it ships train-free with an addon deploy.
8230
+ */
8231
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8232
+ var NcTaxonomyEntrySchema = object({
8233
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8234
+ kind: string(),
8235
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8236
+ label: string(),
8237
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8238
+ parentKind: string().nullable()
8239
+ });
8240
+ object({
8241
+ videoClasses: array(NcTaxonomyEntrySchema),
8242
+ audioKinds: array(NcTaxonomyEntrySchema),
8243
+ labels: array(NcTaxonomyEntrySchema)
8244
+ });
8245
+ function toEntry(kind, label, parentKind) {
8246
+ return {
8247
+ kind,
8248
+ label,
8249
+ parentKind
8250
+ };
8251
+ }
8252
+ /**
8253
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8254
+ * (macros before their subs), which the client relies on for stable grouping.
8255
+ */
8256
+ function buildNcTaxonomy() {
8257
+ const all = Object.values(EVENT_TAXONOMY);
8258
+ return {
8259
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8260
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8261
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8262
+ };
8263
+ }
8264
+ Object.freeze(buildNcTaxonomy());
8265
+ /**
8216
8266
  * Error types for the safe expression engine. Two distinct classes so callers
8217
8267
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8218
8268
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -10921,6 +10971,22 @@ var CameraMetricsSchema = object({
10921
10971
  ])
10922
10972
  });
10923
10973
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
10974
+ /**
10975
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
10976
+ * within the frame, so the executor can re-cut a leaf child ROI at native
10977
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
10978
+ */
10979
+ var NativeCropRefSchema = object({
10980
+ /** Handle keying the retained native surface (node-pinned to its owner). */
10981
+ handle: FrameHandleSchema,
10982
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
10983
+ cropFrameSpace: object({
10984
+ x: number(),
10985
+ y: number(),
10986
+ w: number(),
10987
+ h: number()
10988
+ })
10989
+ });
10924
10990
  var ModelFormatSchema$1 = _enum([
10925
10991
  "onnx",
10926
10992
  "coreml",
@@ -11196,7 +11262,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
11196
11262
  * Omitted ⇒ the runner's default device (current single-engine
11197
11263
  * behaviour). Selects WHICH device pool of the node runs the call.
11198
11264
  */
11199
- deviceKey: string().optional()
11265
+ deviceKey: string().optional(),
11266
+ /**
11267
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
11268
+ * when the parent crop was resolved from the frame's retained NATIVE
11269
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
11270
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
11271
+ * resolution from that surface — the SAME quality path faces already
11272
+ * had — instead of the downscaled parent tile. `handle` keys the native
11273
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
11274
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
11275
+ * the executor's crop-normalized child ROI back into frame-normalized
11276
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
11277
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
11278
+ * (today's behaviour on the fallback path).
11279
+ */
11280
+ nativeCropRef: NativeCropRefSchema.optional()
11200
11281
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
11201
11282
  engine: PipelineEngineChoiceSchema.optional(),
11202
11283
  steps: array(PipelineStepInputSchema).min(1),
@@ -11412,7 +11493,11 @@ var DetailResultSchema = object({
11412
11493
  bbox: NativeCropBboxSchema.optional(),
11413
11494
  embedding: string().optional(),
11414
11495
  label: string().optional(),
11415
- alignedCropJpeg: string().optional()
11496
+ alignedCropJpeg: string().optional(),
11497
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
11498
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
11499
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
11500
+ nativeFaceShortSidePx: number().optional()
11416
11501
  });
11417
11502
  /**
11418
11503
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -11426,6 +11511,12 @@ var motionCooldownMsField = {
11426
11511
  default: 3e4,
11427
11512
  step: 500
11428
11513
  };
11514
+ var maxSessionHoldMsField = {
11515
+ min: 0,
11516
+ max: 6e5,
11517
+ default: 12e4,
11518
+ step: 5e3
11519
+ };
11429
11520
  var motionFpsField = {
11430
11521
  min: 1,
11431
11522
  max: 30,
@@ -11573,6 +11664,19 @@ var RunnerCameraConfigSchema = object({
11573
11664
  "on-motion"
11574
11665
  ]).default("always-on"),
11575
11666
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
11667
+ /**
11668
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
11669
+ * detection session is active and ≥1 confirmed non-stationary track is
11670
+ * still live, the orchestrator keeps the session open past
11671
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
11672
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
11673
+ * ms since the session opened, after which it closes regardless. `0`
11674
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
11675
+ * runner itself — carried here so it shares the per-camera device-settings
11676
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
11677
+ * resolved `CameraDetectionConfig`.
11678
+ */
11679
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
11576
11680
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
11577
11681
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
11578
11682
  motionStreamId: string(),
@@ -11662,7 +11766,7 @@ var RunnerCameraConfigSchema = object({
11662
11766
  */
11663
11767
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
11664
11768
  });
11665
- motionFpsField.min, motionFpsField.max, motionFpsField.step, motionFpsField.default, detectionFpsField.min, detectionFpsField.max, detectionFpsField.step, detectionFpsField.default, motionCooldownMsField.min, motionCooldownMsField.max, motionCooldownMsField.step, motionCooldownMsField.default, occupancyRecheckSecField.min, occupancyRecheckSecField.max, occupancyRecheckSecField.step, occupancyRecheckSecField.default, occupancyRecheckFramesField.min, occupancyRecheckFramesField.max, occupancyRecheckFramesField.step, occupancyRecheckFramesField.default;
11769
+ motionFpsField.min, motionFpsField.max, motionFpsField.step, motionFpsField.default, detectionFpsField.min, detectionFpsField.max, detectionFpsField.step, detectionFpsField.default, motionCooldownMsField.min, motionCooldownMsField.max, motionCooldownMsField.step, motionCooldownMsField.default, maxSessionHoldMsField.min, maxSessionHoldMsField.max, maxSessionHoldMsField.step, maxSessionHoldMsField.default, occupancyRecheckSecField.min, occupancyRecheckSecField.max, occupancyRecheckSecField.step, occupancyRecheckSecField.default, occupancyRecheckFramesField.min, occupancyRecheckFramesField.max, occupancyRecheckFramesField.step, occupancyRecheckFramesField.default;
11666
11770
  /**
11667
11771
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
11668
11772
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -13516,94 +13620,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
13516
13620
  bundleUrl: string()
13517
13621
  });
13518
13622
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
13519
- var NotificationRuleConditionsSchema = object({
13520
- deviceIds: array(number()).readonly().optional(),
13521
- classNames: array(string()).readonly().optional(),
13522
- zoneIds: array(string()).readonly().optional(),
13523
- minConfidence: number().optional(),
13524
- source: _enum([
13525
- "pipeline",
13526
- "onboard",
13527
- "any"
13528
- ]).optional(),
13529
- schedule: object({
13530
- days: array(number()).readonly(),
13531
- startHour: number(),
13532
- endHour: number()
13533
- }).optional(),
13534
- cooldownSeconds: number().optional(),
13535
- minDwellSeconds: number().optional(),
13536
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
13537
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
13538
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
13539
- eventTypeTokens: array(string()).readonly().optional(),
13540
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
13541
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
13542
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
13543
- clipDescription: object({
13544
- text: string().min(1),
13545
- minSimilarity: number().min(0).max(1)
13546
- }).optional(),
13547
- /** Match events whose recognized-entity label (face identity name or plate
13548
- * vehicle name, propagated onto `event.data.label`) is one of these values.
13549
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
13550
- * vehicle/person> is seen". */
13551
- labels: array(string()).readonly().optional()
13552
- });
13553
- var NotificationRuleTemplateSchema = object({
13554
- title: string(),
13555
- body: string(),
13556
- imageMode: _enum([
13557
- "crop",
13558
- "annotated",
13559
- "full",
13560
- "none"
13561
- ])
13562
- });
13563
- var NotificationRuleSchema = object({
13564
- id: string(),
13565
- name: string(),
13566
- enabled: boolean(),
13567
- eventTypes: array(string()).readonly(),
13568
- conditions: NotificationRuleConditionsSchema,
13569
- outputs: array(string()).readonly(),
13570
- template: NotificationRuleTemplateSchema.optional(),
13571
- priority: _enum([
13572
- "low",
13573
- "normal",
13574
- "high",
13575
- "critical"
13576
- ])
13577
- });
13578
- var NotificationTestResultSchema = object({
13579
- ruleId: string(),
13580
- eventId: string(),
13581
- timestamp: number(),
13582
- wouldFire: boolean(),
13583
- reason: string().optional()
13584
- });
13585
- var NotificationHistoryEntrySchema = object({
13586
- id: string(),
13587
- ruleId: string(),
13588
- ruleName: string(),
13589
- eventId: string(),
13590
- timestamp: number(),
13591
- outputs: array(string()).readonly(),
13592
- success: boolean(),
13593
- error: string().optional(),
13594
- deviceId: number().optional()
13595
- });
13596
- var NotificationHistoryFilterSchema = object({
13597
- ruleId: string().optional(),
13598
- deviceId: number().optional(),
13599
- from: number().optional(),
13600
- to: number().optional(),
13601
- limit: number().optional()
13602
- });
13603
- method(_void(), object({ rules: array(NotificationRuleSchema).readonly() })), method(object({ rule: NotificationRuleSchema }), object({ success: literal(true) }), { kind: "mutation" }), method(object({ ruleId: string() }), object({ success: literal(true) }), { kind: "mutation" }), method(object({
13604
- ruleId: string(),
13605
- lookbackMinutes: number()
13606
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
13607
13623
  /**
13608
13624
  * Alerts capability — collection-based internal alert system.
13609
13625
  *
@@ -13790,89 +13806,6 @@ method(object({
13790
13806
  password: string()
13791
13807
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
13792
13808
  /**
13793
- * `login-method` — collection cap through which auth addons contribute
13794
- * their pre-auth login surfaces to the login page. This is the SINGLE,
13795
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
13796
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
13797
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
13798
- * procedure aggregates them for the unauthenticated login page.
13799
- *
13800
- * A contribution is a discriminated union on `kind`:
13801
- *
13802
- * - `redirect` — a declarative button. The login page renders a generic
13803
- * button that navigates to `startUrl` (an addon-owned HTTP route).
13804
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
13805
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
13806
- * login page needs NO change.
13807
- *
13808
- * - `widget` — a Module-Federation widget the login page mounts (via
13809
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
13810
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
13811
- * mechanism kept for future use; no shipped addon uses it on the login
13812
- * page (the passkey ceremony below runs natively in the shell instead).
13813
- *
13814
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
13815
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
13816
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
13817
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
13818
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
13819
- * fetching any remote code pre-auth. Contribution stays unconditional —
13820
- * enrollment state is never leaked pre-auth; visibility is a shell
13821
- * decision.
13822
- *
13823
- * Every contribution carries a `stage`:
13824
- * - `primary` — shown on the first credentials screen (OIDC /
13825
- * magic-link buttons; a future usernameless passkey).
13826
- * - `second-factor` — shown AFTER the password leg, gated on the
13827
- * returned `factors` (passkey-as-2FA today).
13828
- *
13829
- * `mount: skip` — the cap is read server-side by the core auth router
13830
- * (`registry.getCollection('login-method')`), never mounted as its own
13831
- * tRPC router.
13832
- */
13833
- /** When a login method renders in the two-phase login flow. */
13834
- var LoginStageEnum = _enum(["primary", "second-factor"]);
13835
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
13836
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
13837
- object({
13838
- kind: literal("redirect"),
13839
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
13840
- id: string(),
13841
- /** Operator-facing button label. */
13842
- label: string(),
13843
- /** lucide-react icon name. */
13844
- icon: string().optional(),
13845
- /** Addon-owned HTTP route the button navigates to (GET). */
13846
- startUrl: string(),
13847
- stage: LoginStageEnum
13848
- }),
13849
- object({
13850
- kind: literal("widget"),
13851
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
13852
- id: string(),
13853
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
13854
- addonId: string(),
13855
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
13856
- bundle: string(),
13857
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
13858
- remote: WidgetRemoteSchema,
13859
- stage: LoginStageEnum
13860
- }),
13861
- object({
13862
- kind: literal("passkey"),
13863
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
13864
- id: string(),
13865
- /** Operator-facing button label. */
13866
- label: string(),
13867
- stage: LoginStageEnum,
13868
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
13869
- rpId: string(),
13870
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
13871
- origin: string().nullable()
13872
- })
13873
- ]);
13874
- method(_void(), array(LoginMethodContributionSchema).readonly());
13875
- /**
13876
13809
  * Orchestrator-side destination metadata. The orchestrator computes
13877
13810
  * `id = <addonId>:<subId>` from its provider lookup so consumers
13878
13811
  * (admin UI, restore flow) see one canonical key.
@@ -15216,896 +15149,1467 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
15216
15149
  kind: "mutation",
15217
15150
  auth: "admin"
15218
15151
  });
15219
- var LogLevelSchema = _enum([
15220
- "debug",
15221
- "info",
15222
- "warn",
15223
- "error"
15152
+ /**
15153
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15154
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15155
+ * caps stay wire-compatible without a circular cap→cap import.
15156
+ *
15157
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
15158
+ * every transport tier structurally, and failed calls still write usage rows.
15159
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15160
+ */
15161
+ var LlmUsageSchema = object({
15162
+ inputTokens: number(),
15163
+ outputTokens: number()
15164
+ });
15165
+ var LlmErrorCodeSchema = _enum([
15166
+ "timeout",
15167
+ "rate-limited",
15168
+ "auth",
15169
+ "refusal",
15170
+ "bad-request",
15171
+ "unavailable",
15172
+ "no-profile",
15173
+ "budget-exceeded",
15174
+ "adapter-error"
15224
15175
  ]);
15225
- var LogEntrySchema = object({
15226
- timestamp: date(),
15227
- level: LogLevelSchema,
15228
- scope: array(string()),
15176
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15177
+ ok: literal(true),
15178
+ text: string(),
15179
+ model: string(),
15180
+ usage: LlmUsageSchema,
15181
+ truncated: boolean(),
15182
+ latencyMs: number()
15183
+ }), object({
15184
+ ok: literal(false),
15185
+ code: LlmErrorCodeSchema,
15229
15186
  message: string(),
15230
- meta: record(string(), unknown()).optional(),
15231
- tags: record(string(), string()).optional()
15187
+ retryAfterMs: number().optional()
15188
+ })]);
15189
+ /**
15190
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15191
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15192
+ * notification-output.cap.ts:27-31 precedents).
15193
+ */
15194
+ var LlmImageSchema = object({
15195
+ bytes: _instanceof(Uint8Array),
15196
+ mimeType: string()
15232
15197
  });
15233
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15234
- scope: array(string()).optional(),
15235
- level: LogLevelSchema.optional(),
15236
- since: date().optional(),
15237
- until: date().optional(),
15238
- limit: number().optional(),
15239
- tags: record(string(), string()).optional()
15240
- }), array(LogEntrySchema).readonly());
15241
- var CpuBreakdownSchema = object({
15242
- total: number(),
15243
- user: number(),
15244
- system: number(),
15245
- irq: number(),
15246
- nice: number(),
15247
- loadAvg: tuple([
15248
- number(),
15249
- number(),
15250
- number()
15251
- ]),
15252
- cores: number()
15198
+ var LlmGenerateBaseInputSchema = object({
15199
+ /** Collection routing (the notification-output posture). */
15200
+ addonId: string().optional(),
15201
+ /** Explicit profile; else the resolution chain (spec §3). */
15202
+ profileId: string().optional(),
15203
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15204
+ consumer: string(),
15205
+ system: string().optional(),
15206
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
15207
+ prompt: string(),
15208
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15209
+ jsonSchema: record(string(), unknown()).optional(),
15210
+ /** Per-call override of the profile default. */
15211
+ maxTokens: number().int().positive().optional(),
15212
+ temperature: number().optional()
15253
15213
  });
15254
- var MemoryInfoSchema = object({
15255
- percent: number(),
15256
- totalBytes: number(),
15257
- usedBytes: number(),
15258
- availableBytes: number(),
15259
- swapUsedBytes: number(),
15260
- swapTotalBytes: number()
15261
- });
15262
- var DiskIoSnapshotSchema = object({
15263
- readBytes: number(),
15264
- writeBytes: number(),
15265
- readOps: number(),
15266
- writeOps: number(),
15267
- timestampMs: number()
15268
- });
15269
- var NetworkIoSnapshotSchema = object({
15270
- rxBytes: number(),
15271
- txBytes: number(),
15272
- rxPackets: number(),
15273
- txPackets: number(),
15274
- rxErrors: number(),
15275
- txErrors: number(),
15276
- timestampMs: number()
15277
- });
15278
- var MetricsGpuInfoSchema = object({
15279
- utilization: number(),
15280
- model: string(),
15281
- memoryUsedBytes: number(),
15282
- memoryTotalBytes: number(),
15283
- temperature: number().nullable()
15284
- });
15285
- var ProcessResourceInfoSchema = object({
15286
- openFds: number(),
15287
- threadCount: number(),
15288
- activeHandles: number(),
15289
- activeRequests: number()
15290
- });
15291
- var PressureAvgsSchema = object({
15292
- avg10: number(),
15293
- avg60: number(),
15294
- avg300: number()
15295
- });
15296
- var PressureInfoSchema = object({
15297
- some: PressureAvgsSchema,
15298
- full: PressureAvgsSchema.nullable()
15299
- });
15300
- var SystemResourceSnapshotSchema = object({
15301
- cpu: CpuBreakdownSchema,
15302
- memory: MemoryInfoSchema,
15303
- gpu: MetricsGpuInfoSchema.nullable(),
15304
- network: NetworkIoSnapshotSchema,
15305
- disk: DiskIoSnapshotSchema,
15306
- pressure: object({
15307
- cpu: PressureInfoSchema.nullable(),
15308
- memory: PressureInfoSchema.nullable(),
15309
- io: PressureInfoSchema.nullable()
15214
+ /**
15215
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15216
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15217
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15218
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15219
+ * this only through the `llm` cap's methods.
15220
+ *
15221
+ * One running llama-server child per node in v1 (models are RAM-heavy).
15222
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15223
+ * watchdog — operator decision #3).
15224
+ */
15225
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
15226
+ object({
15227
+ kind: literal("catalog"),
15228
+ catalogId: string()
15310
15229
  }),
15311
- process: ProcessResourceInfoSchema,
15312
- cpuTemperature: number().nullable(),
15313
- timestampMs: number()
15314
- });
15315
- var DiskSpaceInfoSchema = object({
15316
- path: string(),
15317
- totalBytes: number(),
15318
- usedBytes: number(),
15319
- availableBytes: number(),
15320
- percent: number()
15321
- });
15322
- var PidResourceStatsSchema = object({
15323
- pid: number(),
15324
- cpu: number(),
15325
- memory: number(),
15326
- /**
15327
- * Private (anonymous) resident bytes — the per-process V8 heap + native
15328
- * allocations NOT shared with other processes (Linux RssAnon). This is the
15329
- * "real" per-runner cost; summing it across runners is meaningful, unlike
15330
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
15331
- * Undefined where /proc is unavailable (e.g. macOS).
15332
- */
15333
- privateBytes: number().optional(),
15334
- /**
15335
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15336
- * code shared copy-on-write across runners. Undefined on macOS.
15337
- */
15338
- sharedBytes: number().optional()
15230
+ object({
15231
+ kind: literal("url"),
15232
+ url: string(),
15233
+ sha256: string().optional()
15234
+ }),
15235
+ object({
15236
+ kind: literal("path"),
15237
+ path: string()
15238
+ })
15239
+ ]);
15240
+ var ManagedRuntimeConfigSchema = object({
15241
+ /** WHERE the runtime lives — hub or any agent. */
15242
+ nodeId: string(),
15243
+ /** Closed for v1; 'ollama' is a v2 candidate. */
15244
+ engine: _enum(["llama-cpp"]),
15245
+ model: ManagedModelRefSchema,
15246
+ contextSize: number().int().default(4096),
15247
+ /** 0 = CPU-only. */
15248
+ gpuLayers: number().int().default(0),
15249
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15250
+ threads: number().int().optional(),
15251
+ /** Concurrent slots. */
15252
+ parallel: number().int().default(1),
15253
+ /** Else lazy: first generate boots it. */
15254
+ autoStart: boolean().default(false),
15255
+ /** 0 = never; frees RAM after quiet periods. */
15256
+ idleStopMinutes: number().int().default(30)
15339
15257
  });
15340
- var AddonInstanceSchema = object({
15341
- addonId: string(),
15258
+ var LlmRuntimeStatusSchema = object({
15259
+ /** Status is ALWAYS node-qualified. */
15342
15260
  nodeId: string(),
15343
- role: _enum(["hub", "worker"]),
15344
- pid: number(),
15345
15261
  state: _enum([
15346
- "starting",
15347
- "running",
15348
- "stopping",
15349
15262
  "stopped",
15350
- "crashed"
15351
- ]),
15352
- uptimeSec: number()
15353
- });
15354
- var NodeProcessSchema = object({
15355
- pid: number(),
15356
- ppid: number(),
15357
- pgid: number(),
15358
- classification: _enum([
15359
- "root",
15360
- "managed",
15361
- "system",
15362
- "ghost"
15263
+ "downloading",
15264
+ "starting",
15265
+ "ready",
15266
+ "crashed",
15267
+ "failed"
15363
15268
  ]),
15364
- /** `$process` addon binding when `managed`, else null. */
15365
- addonId: string().nullable(),
15366
- /** Kernel-reported nodeId when the process is a known agent/worker. */
15367
- nodeId: string().nullable(),
15368
- /** Truncated command line. */
15369
- command: string(),
15370
- cpuPercent: number(),
15371
- memoryRssBytes: number(),
15372
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15373
- uptimeSec: number(),
15374
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15375
- orphaned: boolean()
15376
- });
15377
- var KillProcessInputSchema = object({
15378
- pid: number(),
15379
- /** Force = SIGKILL. Default is SIGTERM. */
15380
- force: boolean().optional()
15381
- });
15382
- var KillProcessResultSchema = object({
15383
- success: boolean(),
15384
- reason: string().optional(),
15385
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15386
- });
15387
- var DumpHeapSnapshotInputSchema = object({
15388
- /** The addon whose runner should dump a heap snapshot. */
15389
- addonId: string() });
15390
- var DumpHeapSnapshotResultSchema = object({
15391
- success: boolean(),
15392
- /** Path of the written .heapsnapshot inside the runner's container/host. */
15393
- path: string().optional(),
15394
- /** Process pid that was signalled. */
15395
15269
  pid: number().optional(),
15396
- reason: string().optional()
15397
- });
15398
- var SystemMetricsSchema = object({
15399
- cpuPercent: number(),
15400
- memoryPercent: number(),
15401
- memoryUsedMB: number(),
15402
- memoryTotalMB: number(),
15403
- diskPercent: number().optional(),
15404
- temperature: number().optional(),
15405
- gpuPercent: number().optional(),
15406
- gpuMemoryPercent: number().optional()
15407
- });
15408
- 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, {
15409
- kind: "mutation",
15410
- auth: "admin"
15411
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15412
- kind: "mutation",
15413
- auth: "admin"
15270
+ port: number().optional(),
15271
+ modelPath: string().optional(),
15272
+ modelId: string().optional(),
15273
+ downloadProgress: number().min(0).max(1).optional(),
15274
+ lastError: string().optional(),
15275
+ crashesInWindow: number(),
15276
+ /** Child RSS (sampled best-effort). */
15277
+ memoryBytes: number().optional(),
15278
+ vramBytes: number().optional()
15414
15279
  });
15415
- method(object({
15416
- sourceUrl: string(),
15417
- metadata: ModelConvertMetadataSchema,
15418
- targets: array(ConvertTargetSchema).min(1).readonly(),
15419
- calibrationRef: string().optional(),
15420
- sessionId: string().optional()
15421
- }), ConvertResultSchema, {
15422
- kind: "mutation",
15423
- auth: "admin",
15424
- timeoutMs: 6e5
15280
+ var LlmNodeModelSchema = object({
15281
+ file: string(),
15282
+ sizeBytes: number(),
15283
+ catalogId: string().optional(),
15284
+ installedAt: number().optional()
15425
15285
  });
15426
- method(object({
15286
+ var LlmRuntimeDiskUsageSchema = object({
15427
15287
  nodeId: string(),
15428
- modelId: string(),
15429
- format: _enum(MODEL_FORMATS),
15430
- entry: ModelCatalogEntrySchema
15431
- }), object({
15432
- ok: boolean(),
15433
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
15434
- sha256: string(),
15435
- bytes: number(),
15436
- /** The target node's modelsDir the artifact landed in. */
15437
- path: string()
15438
- }), {
15439
- kind: "mutation",
15440
- auth: "admin"
15288
+ modelsBytes: number(),
15289
+ freeBytes: number().optional()
15441
15290
  });
15291
+ var llmRuntimeCapability = {
15292
+ name: "llm-runtime",
15293
+ scope: "system",
15294
+ mode: "singleton",
15295
+ internal: true,
15296
+ methods: {
15297
+ complete: method(LlmGenerateBaseInputSchema.extend({
15298
+ images: array(LlmImageSchema).optional(),
15299
+ runtime: ManagedRuntimeConfigSchema,
15300
+ /** The managed profile's timeout, threaded by the hub provider. */
15301
+ timeoutMs: number().int().positive().optional()
15302
+ }), LlmGenerateResultSchema, { kind: "mutation" }),
15303
+ ensureStarted: method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15304
+ kind: "mutation",
15305
+ auth: "admin"
15306
+ }),
15307
+ stop: method(object({}), _void(), {
15308
+ kind: "mutation",
15309
+ auth: "admin"
15310
+ }),
15311
+ status: method(object({}), LlmRuntimeStatusSchema),
15312
+ installModel: method(object({ model: ManagedModelRefSchema }), _void(), {
15313
+ kind: "mutation",
15314
+ auth: "admin"
15315
+ }),
15316
+ deleteModel: method(object({ file: string() }), _void(), {
15317
+ kind: "mutation",
15318
+ auth: "admin"
15319
+ }),
15320
+ listLocalModels: method(object({}), array(LlmNodeModelSchema)),
15321
+ getDiskUsage: method(object({}), LlmRuntimeDiskUsageSchema)
15322
+ }
15323
+ };
15442
15324
  /**
15443
- * `mqtt-broker` — broker-registry cap.
15444
- *
15445
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15446
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15447
- * and (b) the connection details a consumer addon needs to spin up
15448
- * its OWN `mqtt.js` client.
15449
- *
15450
- * Why: pub/sub routing over the system event-bus loses fidelity
15451
- * (callback shape, QoS guarantees, will/retain semantics) and adds
15452
- * refcount bookkeeping that addons would rather own themselves. The
15453
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
15454
- * features anyway — give it the connection config, get out of the way.
15455
- *
15456
- * Consumer flow:
15457
- * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
15458
- * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
15459
- * client.subscribe('zigbee2mqtt/+')
15460
- *
15461
- * Collection mode: multiple brokers (e.g. one local mosquitto + one
15462
- * cloud bridge). The "embedded" entry (when present) is just another
15463
- * broker in the registry — its lifecycle is owned by the addon that
15464
- * spawned it.
15465
- */
15466
- var BrokerKindSchema = _enum(["external", "embedded"]);
15467
- /**
15468
- * Broker live-probe status.
15325
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15326
+ * methods concat-fan across providers; single-row methods route to ONE
15327
+ * provider by the `addonId` in the call input (the notification-output
15328
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15329
+ * (hub-placed); the cap stays open for future providers.
15469
15330
  *
15470
- * - `connected` last probe completed a clean CONNACK
15471
- * - `disconnected` — no probe has run yet (cold cache)
15472
- * - `auth-failed` CONNACK refused with auth error (RC 4 / 5)
15473
- * - `unreachable` — TCP connect timed out / refused
15474
- * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
15331
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15332
+ * `apiKey` is a password field providers REDACT it on read and merge on
15333
+ * write; a stored key NEVER round-trips to a client.
15475
15334
  */
15476
- var BrokerStatusSchema$1 = _enum([
15477
- "connected",
15478
- "disconnected",
15479
- "auth-failed",
15480
- "unreachable",
15481
- "tls-error"
15335
+ var LlmProfileKindSchema = _enum([
15336
+ "openai-compatible",
15337
+ "openai",
15338
+ "anthropic",
15339
+ "google",
15340
+ "managed-local"
15482
15341
  ]);
15483
- var BrokerInfoSchema = object({
15342
+ var LlmProfileSchema = object({
15484
15343
  id: string(),
15485
15344
  name: string(),
15486
- url: string(),
15487
- kind: BrokerKindSchema,
15488
- status: BrokerStatusSchema$1,
15489
- latencyMs: number().nullable(),
15490
- error: string().optional(),
15491
- /** Embedded brokers only: number of MQTT clients currently connected. */
15492
- connectedClients: number().int().nonnegative().optional(),
15493
- /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
15494
- lastCheckedAt: number().optional()
15345
+ kind: LlmProfileKindSchema,
15346
+ /** Stamped by the provider — keeps the fanned catalog routable. */
15347
+ addonId: string(),
15348
+ enabled: boolean(),
15349
+ /** Vendor model id, or the managed runtime's loaded model. */
15350
+ model: string(),
15351
+ /** Required for openai-compatible; override for cloud kinds. */
15352
+ baseUrl: string().optional(),
15353
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
15354
+ apiKey: string().optional(),
15355
+ supportsVision: boolean(),
15356
+ temperature: number().min(0).max(2).optional(),
15357
+ maxTokens: number().int().positive().optional(),
15358
+ timeoutMs: number().int().positive().default(6e4),
15359
+ extraHeaders: record(string(), string()).optional(),
15360
+ /** kind === 'managed-local' only (spec §4). */
15361
+ runtime: ManagedRuntimeConfigSchema.optional()
15495
15362
  });
15496
- /**
15497
- * Connection details — what a consumer needs to call
15498
- * `mqtt.connect(url, options)`. We split URL + credentials so the
15499
- * consumer can pass them as `mqtt.connect(url, { username, password })`
15500
- * instead of stuffing creds into the URL (which leaks them into logs).
15501
- */
15502
- var BrokerConnectionDetailsSchema = object({
15503
- url: string(),
15504
- username: string().optional(),
15505
- password: string().optional(),
15506
- /**
15507
- * Suggested prefix for `clientId`. Each consumer should suffix this
15508
- * with its own discriminator (addon id, instance id) so reconnects
15509
- * don't kick each other off (MQTT spec: clientId must be unique per
15510
- * broker).
15511
- */
15512
- clientIdPrefix: string().optional()
15363
+ /** ConfigUISchema tree passed through untyped on the wire (the
15364
+ * notification-output `ConfigSchemaPassthrough` precedent at
15365
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15366
+ var ConfigSchemaPassthrough$1 = unknown();
15367
+ var LlmProfileKindDescriptorSchema = object({
15368
+ kind: LlmProfileKindSchema,
15369
+ label: string(),
15370
+ icon: string(),
15371
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
15372
+ addonId: string(),
15373
+ configSchema: ConfigSchemaPassthrough$1
15513
15374
  });
15514
- var AddBrokerInputSchema = object({
15515
- name: string().min(1),
15516
- url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
15517
- username: string().optional(),
15518
- password: string().optional(),
15519
- clientIdPrefix: string().optional()
15375
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15376
+ var LlmDefaultSchema = object({
15377
+ selector: LlmDefaultSelectorSchema,
15378
+ profileId: string()
15520
15379
  });
15521
- var AddBrokerResultSchema = object({ id: string() });
15522
- var IdInputSchema = object({ id: string() });
15523
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
15524
- ok: literal(true),
15525
- latencyMs: number()
15526
- }), object({
15527
- ok: literal(false),
15528
- error: string()
15529
- })]);
15530
- var StartEmbeddedInputSchema = object({
15531
- port: number().int().min(1).max(65535).default(1883),
15532
- /** Allow anonymous connect (no username/password). Default: false. */
15533
- allowAnonymous: boolean().default(false),
15534
- /** Optional shared username/password for clients. */
15535
- username: string().optional(),
15536
- password: string().optional()
15380
+ /** Server-side rollup row getUsage never dumps raw call rows (spec §6). */
15381
+ var LlmUsageRollupSchema = object({
15382
+ day: string(),
15383
+ consumer: string(),
15384
+ profileId: string(),
15385
+ calls: number(),
15386
+ okCalls: number(),
15387
+ errorCalls: number(),
15388
+ inputTokens: number(),
15389
+ outputTokens: number(),
15390
+ avgLatencyMs: number()
15537
15391
  });
15538
- var StartEmbeddedResultSchema = object({
15392
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15393
+ var ManagedModelCatalogEntrySchema = object({
15539
15394
  id: string(),
15540
- url: string()
15541
- });
15542
- var StatusSchema = object({
15543
- brokerCount: number(),
15544
- embeddedRunning: boolean()
15545
- });
15546
- 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);
15547
- var NetworkEndpointSchema = object({
15395
+ label: string(),
15396
+ family: string(),
15397
+ purpose: _enum(["text", "vision"]),
15548
15398
  url: string(),
15549
- hostname: string(),
15550
- port: number(),
15551
- protocol: _enum(["http", "https"])
15399
+ sha256: string(),
15400
+ sizeBytes: number(),
15401
+ quantization: string(),
15402
+ /** Load-time guidance shown in the picker. */
15403
+ minRamBytes: number(),
15404
+ contextSizeDefault: number().int(),
15405
+ /** Vision models: companion projector file. */
15406
+ mmprojUrl: string().optional()
15552
15407
  });
15553
- var NetworkAccessStatusSchema = object({
15554
- connected: boolean(),
15555
- endpoint: NetworkEndpointSchema.nullable(),
15408
+ var LlmRuntimeNodeSchema = object({
15409
+ nodeId: string(),
15410
+ reachable: boolean(),
15411
+ status: LlmRuntimeStatusSchema.optional(),
15412
+ disk: LlmRuntimeDiskUsageSchema.optional(),
15556
15413
  error: string().optional()
15557
15414
  });
15558
- /**
15559
- * Optional, richer endpoint shape returned by providers that expose
15560
- * MORE than one ingress concurrently (Tailscale Ingress with mixed
15561
- * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
15562
- * the originating provider config (mode + sourcePort) so the
15563
- * orchestrator UI can label rows distinctly. Providers that expose only
15564
- * one endpoint just omit `listEndpoints` from their provider impl.
15565
- */
15566
- var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
15567
- /**
15568
- * Stable id within the provider — typically `<mode>-<sourcePort>` so
15569
- * the orchestrator can dedupe across `listEndpoints` polls.
15570
- */
15571
- id: string(),
15572
- /** Operator-facing label (mirrors `MeshEndpoint.label`). */
15573
- label: string(),
15574
- /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
15575
- mode: string().optional(),
15576
- /** Originating local port the ingress fronts (informational). */
15577
- sourcePort: number().optional()
15415
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
15416
+ var ProfileRefInputSchema = object({
15417
+ addonId: string(),
15418
+ profileId: string()
15578
15419
  });
15579
- method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
15580
- /**
15581
- * notification-output — canonical, capability-gated notification delivery.
15582
- *
15583
- * Apprise-derived model (see
15584
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
15585
- * callers emit ONE canonical `Notification`; each provider declares a
15586
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
15587
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
15588
- * message to what the kind supports — callers never special-case a service.
15589
- *
15590
- * DESIGN DECISIONS (locked):
15591
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
15592
- * `setTargetEnabled`), each provider persisting via the `settings-store`
15593
- * cap. Rationale: the admin UI needs one uniform surface across the
15594
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
15595
- * alternative would fork the UI per addon and cannot host the
15596
- * discovery→adopt flow.
15597
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
15598
- * the generated cap-mount auto-`concatCollection`-fans them across every
15599
- * registered provider (notifiers addon + HA addon) so one catalog is
15600
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
15601
- * `addonId` the generated collection router extracts from the call input.
15602
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
15603
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
15604
- * `storage` / `storage-provider` / `recording` caps over the same path. No
15605
- * base64 fallback needed.
15606
- *
15607
- * TODO (deferred, closed-set change — separate decision): add
15608
- * `providerKind: 'notify'` so notification providers surface on the unified
15609
- * admin "Integrations" page.
15610
- */
15611
- /**
15612
- * Zentik-derived typed-media enum — the superset across every kind. Each
15613
- * adapter picks what it supports and the degrade engine filters the rest.
15614
- */
15615
- var AttachmentMediaTypeSchema = _enum([
15616
- "image",
15617
- "video",
15618
- "gif",
15619
- "audio",
15620
- "icon"
15420
+ var llmCapability = {
15421
+ name: "llm",
15422
+ scope: "system",
15423
+ mode: "collection",
15424
+ internal: false,
15425
+ providerKind: "ai",
15426
+ /** `nodeId` inputs below are DATA (the hub provider pins itself), never routing. */
15427
+ nodeIdMode: "data",
15428
+ methods: {
15429
+ generate: method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }),
15430
+ generateVision: method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }),
15431
+ listProfileKinds: method(object({}), array(LlmProfileKindDescriptorSchema)),
15432
+ listProfiles: method(object({}), array(LlmProfileSchema)),
15433
+ upsertProfile: method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
15434
+ kind: "mutation",
15435
+ auth: "admin"
15436
+ }),
15437
+ deleteProfile: method(ProfileRefInputSchema, _void(), {
15438
+ kind: "mutation",
15439
+ auth: "admin"
15440
+ }),
15441
+ testProfile: method(ProfileRefInputSchema, LlmGenerateResultSchema, {
15442
+ kind: "mutation",
15443
+ auth: "admin"
15444
+ }),
15445
+ /** Live vendor enumeration (GET /models etc.). */
15446
+ listModels: method(ProfileRefInputSchema, array(string())),
15447
+ getDefaults: method(object({}), array(LlmDefaultSchema)),
15448
+ setDefault: method(object({
15449
+ selector: LlmDefaultSelectorSchema,
15450
+ profileId: string().nullable()
15451
+ }), _void(), {
15452
+ kind: "mutation",
15453
+ auth: "admin"
15454
+ }),
15455
+ getUsage: method(object({
15456
+ since: number().optional(),
15457
+ until: number().optional(),
15458
+ consumer: string().optional(),
15459
+ profileId: string().optional()
15460
+ }), array(LlmUsageRollupSchema)),
15461
+ listModelCatalog: method(object({}), array(ManagedModelCatalogEntrySchema)),
15462
+ listRuntimeNodes: method(object({}), array(LlmRuntimeNodeSchema)),
15463
+ listNodeModels: method(object({ nodeId: string() }), array(LlmNodeModelSchema)),
15464
+ installModel: method(object({
15465
+ nodeId: string(),
15466
+ model: ManagedModelRefSchema
15467
+ }), _void(), {
15468
+ kind: "mutation",
15469
+ auth: "admin"
15470
+ }),
15471
+ deleteModel: method(object({
15472
+ nodeId: string(),
15473
+ file: string()
15474
+ }), _void(), {
15475
+ kind: "mutation",
15476
+ auth: "admin"
15477
+ }),
15478
+ getRuntimeStatus: method(ProfileRefInputSchema, LlmRuntimeStatusSchema),
15479
+ startRuntime: method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
15480
+ kind: "mutation",
15481
+ auth: "admin"
15482
+ }),
15483
+ stopRuntime: method(ProfileRefInputSchema, _void(), {
15484
+ kind: "mutation",
15485
+ auth: "admin"
15486
+ })
15487
+ }
15488
+ };
15489
+ var LogLevelSchema = _enum([
15490
+ "debug",
15491
+ "info",
15492
+ "warn",
15493
+ "error"
15621
15494
  ]);
15495
+ var LogEntrySchema = object({
15496
+ timestamp: date(),
15497
+ level: LogLevelSchema,
15498
+ scope: array(string()),
15499
+ message: string(),
15500
+ meta: record(string(), unknown()).optional(),
15501
+ tags: record(string(), string()).optional()
15502
+ });
15503
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15504
+ scope: array(string()).optional(),
15505
+ level: LogLevelSchema.optional(),
15506
+ since: date().optional(),
15507
+ until: date().optional(),
15508
+ limit: number().optional(),
15509
+ tags: record(string(), string()).optional()
15510
+ }), array(LogEntrySchema).readonly());
15622
15511
  /**
15623
- * A single attachment. Exactly one of `url` (remote source, most adapters
15624
- * prefer this) or `bytes` (inline source; required for Pushover-style
15625
- * bytes-only kinds) MUST be present — the degrade engine expresses a
15626
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
15512
+ * `login-method` collection cap through which auth addons contribute
15513
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
15514
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
15515
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
15516
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
15517
+ * procedure aggregates them for the unauthenticated login page.
15518
+ *
15519
+ * A contribution is a discriminated union on `kind`:
15520
+ *
15521
+ * - `redirect` — a declarative button. The login page renders a generic
15522
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
15523
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
15524
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
15525
+ * login page needs NO change.
15526
+ *
15527
+ * - `widget` — a Module-Federation widget the login page mounts (via
15528
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
15529
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
15530
+ * mechanism kept for future use; no shipped addon uses it on the login
15531
+ * page (the passkey ceremony below runs natively in the shell instead).
15532
+ *
15533
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
15534
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
15535
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
15536
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
15537
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
15538
+ * fetching any remote code pre-auth. Contribution stays unconditional —
15539
+ * enrollment state is never leaked pre-auth; visibility is a shell
15540
+ * decision.
15541
+ *
15542
+ * Every contribution carries a `stage`:
15543
+ * - `primary` — shown on the first credentials screen (OIDC /
15544
+ * magic-link buttons; a future usernameless passkey).
15545
+ * - `second-factor` — shown AFTER the password leg, gated on the
15546
+ * returned `factors` (passkey-as-2FA today).
15547
+ *
15548
+ * `mount: skip` — the cap is read server-side by the core auth router
15549
+ * (`registry.getCollection('login-method')`), never mounted as its own
15550
+ * tRPC router.
15627
15551
  */
15628
- var AttachmentSchema = object({
15629
- mediaType: AttachmentMediaTypeSchema,
15630
- url: string().optional(),
15631
- bytes: _instanceof(Uint8Array).optional(),
15632
- mime: string().optional(),
15633
- name: string().optional()
15634
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
15635
- var NotificationFormatSchema = _enum([
15636
- "text",
15637
- "markdown",
15638
- "html"
15552
+ /** When a login method renders in the two-phase login flow. */
15553
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
15554
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
15555
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
15556
+ object({
15557
+ kind: literal("redirect"),
15558
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
15559
+ id: string(),
15560
+ /** Operator-facing button label. */
15561
+ label: string(),
15562
+ /** lucide-react icon name. */
15563
+ icon: string().optional(),
15564
+ /** Addon-owned HTTP route the button navigates to (GET). */
15565
+ startUrl: string(),
15566
+ stage: LoginStageEnum
15567
+ }),
15568
+ object({
15569
+ kind: literal("widget"),
15570
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
15571
+ id: string(),
15572
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
15573
+ addonId: string(),
15574
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
15575
+ bundle: string(),
15576
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
15577
+ remote: WidgetRemoteSchema,
15578
+ stage: LoginStageEnum
15579
+ }),
15580
+ object({
15581
+ kind: literal("passkey"),
15582
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
15583
+ id: string(),
15584
+ /** Operator-facing button label. */
15585
+ label: string(),
15586
+ stage: LoginStageEnum,
15587
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
15588
+ rpId: string(),
15589
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
15590
+ origin: string().nullable()
15591
+ })
15639
15592
  ]);
15640
- /** A single tap-through action button. */
15641
- var NotificationActionSchema = object({
15642
- id: string(),
15643
- label: string(),
15644
- url: string().optional()
15593
+ method(_void(), array(LoginMethodContributionSchema).readonly());
15594
+ var CpuBreakdownSchema = object({
15595
+ total: number(),
15596
+ user: number(),
15597
+ system: number(),
15598
+ irq: number(),
15599
+ nice: number(),
15600
+ loadAvg: tuple([
15601
+ number(),
15602
+ number(),
15603
+ number()
15604
+ ]),
15605
+ cores: number()
15645
15606
  });
15646
- /**
15647
- * The canonical notification. `body` is the only hard field (Apprise model).
15648
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
15649
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
15650
- * the adapter maps this ordinal onto its native level. `level?` is an
15651
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
15652
- * `priority` for that one target.
15653
- */
15654
- var NotificationSchema = object({
15655
- body: string(),
15656
- title: string().optional(),
15657
- format: NotificationFormatSchema.default("text"),
15658
- priority: number().int().min(1).max(5).default(3),
15659
- level: string().optional(),
15660
- attachments: array(AttachmentSchema).optional(),
15661
- clickUrl: string().optional(),
15662
- actions: array(NotificationActionSchema).optional(),
15663
- sound: string().optional(),
15664
- ttl: number().optional(),
15665
- tag: string().optional(),
15666
- deviceId: number().optional(),
15667
- eventId: string().optional(),
15668
- metadata: record(string(), unknown()).optional()
15607
+ var MemoryInfoSchema = object({
15608
+ percent: number(),
15609
+ totalBytes: number(),
15610
+ usedBytes: number(),
15611
+ availableBytes: number(),
15612
+ swapUsedBytes: number(),
15613
+ swapTotalBytes: number()
15669
15614
  });
15670
- /** One declared native severity/priority level for a kind. */
15671
- var TargetKindLevelSchema = object({
15672
- id: string(),
15673
- label: string(),
15674
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
15675
- ordinal: number().int().min(1).max(5).nullable(),
15676
- flags: object({
15677
- critical: boolean().optional(),
15678
- silent: boolean().optional(),
15679
- noPush: boolean().optional()
15680
- }).optional(),
15681
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
15682
- requires: array(string()).optional(),
15683
- description: string().optional()
15615
+ var DiskIoSnapshotSchema = object({
15616
+ readBytes: number(),
15617
+ writeBytes: number(),
15618
+ readOps: number(),
15619
+ writeOps: number(),
15620
+ timestampMs: number()
15684
15621
  });
15685
- /** The full capability block consulted before dispatch. */
15686
- var TargetKindCapsSchema = object({
15687
- attachments: object({
15688
- mediaTypes: array(AttachmentMediaTypeSchema),
15689
- mode: _enum([
15690
- "url",
15691
- "bytes",
15692
- "both"
15693
- ]),
15694
- max: number().int().nonnegative(),
15695
- maxBytes: number().int().positive().optional()
15622
+ var NetworkIoSnapshotSchema = object({
15623
+ rxBytes: number(),
15624
+ txBytes: number(),
15625
+ rxPackets: number(),
15626
+ txPackets: number(),
15627
+ rxErrors: number(),
15628
+ txErrors: number(),
15629
+ timestampMs: number()
15630
+ });
15631
+ var MetricsGpuInfoSchema = object({
15632
+ utilization: number(),
15633
+ model: string(),
15634
+ memoryUsedBytes: number(),
15635
+ memoryTotalBytes: number(),
15636
+ temperature: number().nullable()
15637
+ });
15638
+ var ProcessResourceInfoSchema = object({
15639
+ openFds: number(),
15640
+ threadCount: number(),
15641
+ activeHandles: number(),
15642
+ activeRequests: number()
15643
+ });
15644
+ var PressureAvgsSchema = object({
15645
+ avg10: number(),
15646
+ avg60: number(),
15647
+ avg300: number()
15648
+ });
15649
+ var PressureInfoSchema = object({
15650
+ some: PressureAvgsSchema,
15651
+ full: PressureAvgsSchema.nullable()
15652
+ });
15653
+ var SystemResourceSnapshotSchema = object({
15654
+ cpu: CpuBreakdownSchema,
15655
+ memory: MemoryInfoSchema,
15656
+ gpu: MetricsGpuInfoSchema.nullable(),
15657
+ network: NetworkIoSnapshotSchema,
15658
+ disk: DiskIoSnapshotSchema,
15659
+ pressure: object({
15660
+ cpu: PressureInfoSchema.nullable(),
15661
+ memory: PressureInfoSchema.nullable(),
15662
+ io: PressureInfoSchema.nullable()
15696
15663
  }),
15697
- /** Max action buttons (0 = none). */
15698
- actions: number().int().nonnegative(),
15699
- levels: array(TargetKindLevelSchema),
15700
- format: array(NotificationFormatSchema),
15701
- clickUrl: boolean(),
15702
- sound: boolean(),
15703
- ttl: boolean(),
15704
- bodyMaxLen: number().int().positive()
15664
+ process: ProcessResourceInfoSchema,
15665
+ cpuTemperature: number().nullable(),
15666
+ timestampMs: number()
15667
+ });
15668
+ var DiskSpaceInfoSchema = object({
15669
+ path: string(),
15670
+ totalBytes: number(),
15671
+ usedBytes: number(),
15672
+ availableBytes: number(),
15673
+ percent: number()
15674
+ });
15675
+ var PidResourceStatsSchema = object({
15676
+ pid: number(),
15677
+ cpu: number(),
15678
+ memory: number(),
15679
+ /**
15680
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
15681
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
15682
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
15683
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
15684
+ * Undefined where /proc is unavailable (e.g. macOS).
15685
+ */
15686
+ privateBytes: number().optional(),
15687
+ /**
15688
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15689
+ * code shared copy-on-write across runners. Undefined on macOS.
15690
+ */
15691
+ sharedBytes: number().optional()
15692
+ });
15693
+ var AddonInstanceSchema = object({
15694
+ addonId: string(),
15695
+ nodeId: string(),
15696
+ role: _enum(["hub", "worker"]),
15697
+ pid: number(),
15698
+ state: _enum([
15699
+ "starting",
15700
+ "running",
15701
+ "stopping",
15702
+ "stopped",
15703
+ "crashed"
15704
+ ]),
15705
+ uptimeSec: number()
15706
+ });
15707
+ var NodeProcessSchema = object({
15708
+ pid: number(),
15709
+ ppid: number(),
15710
+ pgid: number(),
15711
+ classification: _enum([
15712
+ "root",
15713
+ "managed",
15714
+ "system",
15715
+ "ghost"
15716
+ ]),
15717
+ /** `$process` addon binding when `managed`, else null. */
15718
+ addonId: string().nullable(),
15719
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
15720
+ nodeId: string().nullable(),
15721
+ /** Truncated command line. */
15722
+ command: string(),
15723
+ cpuPercent: number(),
15724
+ memoryRssBytes: number(),
15725
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15726
+ uptimeSec: number(),
15727
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15728
+ orphaned: boolean()
15729
+ });
15730
+ var KillProcessInputSchema = object({
15731
+ pid: number(),
15732
+ /** Force = SIGKILL. Default is SIGTERM. */
15733
+ force: boolean().optional()
15734
+ });
15735
+ var KillProcessResultSchema = object({
15736
+ success: boolean(),
15737
+ reason: string().optional(),
15738
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15739
+ });
15740
+ var DumpHeapSnapshotInputSchema = object({
15741
+ /** The addon whose runner should dump a heap snapshot. */
15742
+ addonId: string() });
15743
+ var DumpHeapSnapshotResultSchema = object({
15744
+ success: boolean(),
15745
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
15746
+ path: string().optional(),
15747
+ /** Process pid that was signalled. */
15748
+ pid: number().optional(),
15749
+ reason: string().optional()
15750
+ });
15751
+ var SystemMetricsSchema = object({
15752
+ cpuPercent: number(),
15753
+ memoryPercent: number(),
15754
+ memoryUsedMB: number(),
15755
+ memoryTotalMB: number(),
15756
+ diskPercent: number().optional(),
15757
+ temperature: number().optional(),
15758
+ gpuPercent: number().optional(),
15759
+ gpuMemoryPercent: number().optional()
15760
+ });
15761
+ 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, {
15762
+ kind: "mutation",
15763
+ auth: "admin"
15764
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15765
+ kind: "mutation",
15766
+ auth: "admin"
15767
+ });
15768
+ method(object({
15769
+ sourceUrl: string(),
15770
+ metadata: ModelConvertMetadataSchema,
15771
+ targets: array(ConvertTargetSchema).min(1).readonly(),
15772
+ calibrationRef: string().optional(),
15773
+ sessionId: string().optional()
15774
+ }), ConvertResultSchema, {
15775
+ kind: "mutation",
15776
+ auth: "admin",
15777
+ timeoutMs: 6e5
15778
+ });
15779
+ method(object({
15780
+ nodeId: string(),
15781
+ modelId: string(),
15782
+ format: _enum(MODEL_FORMATS),
15783
+ entry: ModelCatalogEntrySchema
15784
+ }), object({
15785
+ ok: boolean(),
15786
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
15787
+ sha256: string(),
15788
+ bytes: number(),
15789
+ /** The target node's modelsDir the artifact landed in. */
15790
+ path: string()
15791
+ }), {
15792
+ kind: "mutation",
15793
+ auth: "admin"
15705
15794
  });
15706
15795
  /**
15707
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
15708
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
15709
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
15710
- * the union is large and not meant for runtime validation here; the exported
15711
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
15796
+ * `mqtt-broker` broker-registry cap.
15797
+ *
15798
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15799
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15800
+ * and (b) the connection details a consumer addon needs to spin up
15801
+ * its OWN `mqtt.js` client.
15802
+ *
15803
+ * Why: pub/sub routing over the system event-bus loses fidelity
15804
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
15805
+ * refcount bookkeeping that addons would rather own themselves. The
15806
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
15807
+ * features anyway — give it the connection config, get out of the way.
15808
+ *
15809
+ * Consumer flow:
15810
+ * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
15811
+ * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
15812
+ * client.subscribe('zigbee2mqtt/+')
15813
+ *
15814
+ * Collection mode: multiple brokers (e.g. one local mosquitto + one
15815
+ * cloud bridge). The "embedded" entry (when present) is just another
15816
+ * broker in the registry — its lifecycle is owned by the addon that
15817
+ * spawned it.
15712
15818
  */
15713
- var ConfigSchemaPassthrough$1 = unknown();
15714
- var TargetKindSchema = object({
15715
- kind: string(),
15716
- label: string(),
15717
- icon: string(),
15718
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
15719
- addonId: string(),
15720
- configSchema: ConfigSchemaPassthrough$1,
15721
- supportsDiscovery: boolean(),
15722
- caps: TargetKindCapsSchema
15723
- });
15819
+ var BrokerKindSchema = _enum(["external", "embedded"]);
15724
15820
  /**
15725
- * A persisted target. `config` holds secrets; providers REDACT secret fields
15726
- * (return a presence marker only) when serving `listTargets` — never
15727
- * round-trip a stored secret to the UI.
15821
+ * Broker live-probe status.
15822
+ *
15823
+ * - `connected` last probe completed a clean CONNACK
15824
+ * - `disconnected` — no probe has run yet (cold cache)
15825
+ * - `auth-failed` — CONNACK refused with auth error (RC 4 / 5)
15826
+ * - `unreachable` — TCP connect timed out / refused
15827
+ * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
15728
15828
  */
15729
- var TargetSchema = object({
15829
+ var BrokerStatusSchema$1 = _enum([
15830
+ "connected",
15831
+ "disconnected",
15832
+ "auth-failed",
15833
+ "unreachable",
15834
+ "tls-error"
15835
+ ]);
15836
+ var BrokerInfoSchema = object({
15730
15837
  id: string(),
15731
15838
  name: string(),
15732
- kind: string(),
15733
- addonId: string(),
15734
- enabled: boolean(),
15735
- config: record(string(), unknown())
15736
- });
15737
- /** A discovery-surfaced candidate (config is partial + non-secret). */
15738
- var DiscoveredTargetSchema = object({
15739
- kind: string(),
15740
- suggestedName: string(),
15741
- config: record(string(), unknown())
15742
- });
15743
- /** The degrade engine's report — what was resolved / dropped / degraded. */
15744
- var RenderedAsSchema = object({
15745
- level: string(),
15746
- format: NotificationFormatSchema,
15747
- attachmentsSent: number().int().nonnegative(),
15748
- actionsSent: number().int().nonnegative(),
15749
- truncated: boolean(),
15750
- dropped: array(string())
15751
- });
15752
- var SendResultSchema = object({
15753
- success: boolean(),
15839
+ url: string(),
15840
+ kind: BrokerKindSchema,
15841
+ status: BrokerStatusSchema$1,
15842
+ latencyMs: number().nullable(),
15754
15843
  error: string().optional(),
15755
- renderedAs: RenderedAsSchema.optional()
15844
+ /** Embedded brokers only: number of MQTT clients currently connected. */
15845
+ connectedClients: number().int().nonnegative().optional(),
15846
+ /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
15847
+ lastCheckedAt: number().optional()
15756
15848
  });
15757
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
15758
- var TestResultSchema = SendResultSchema;
15759
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
15760
- kind: string(),
15761
- config: record(string(), unknown()).optional()
15762
- }), array(DiscoveredTargetSchema)), method(object({
15763
- targetId: string(),
15764
- notification: NotificationSchema
15765
- }), SendResultSchema, { kind: "mutation" }), method(object({
15766
- targetId: string(),
15767
- sample: NotificationSchema.optional()
15768
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
15769
- targetId: string(),
15770
- enabled: boolean()
15771
- }), _void(), { kind: "mutation" });
15772
15849
  /**
15773
- * Shared LLM generate contracts imported by BOTH `llm.cap.ts` (consumer
15774
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15775
- * caps stay wire-compatible without a circular cap→cap import.
15776
- *
15777
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
15778
- * every transport tier structurally, and failed calls still write usage rows.
15779
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15850
+ * Connection details what a consumer needs to call
15851
+ * `mqtt.connect(url, options)`. We split URL + credentials so the
15852
+ * consumer can pass them as `mqtt.connect(url, { username, password })`
15853
+ * instead of stuffing creds into the URL (which leaks them into logs).
15780
15854
  */
15781
- var LlmUsageSchema = object({
15782
- inputTokens: number(),
15783
- outputTokens: number()
15855
+ var BrokerConnectionDetailsSchema = object({
15856
+ url: string(),
15857
+ username: string().optional(),
15858
+ password: string().optional(),
15859
+ /**
15860
+ * Suggested prefix for `clientId`. Each consumer should suffix this
15861
+ * with its own discriminator (addon id, instance id) so reconnects
15862
+ * don't kick each other off (MQTT spec: clientId must be unique per
15863
+ * broker).
15864
+ */
15865
+ clientIdPrefix: string().optional()
15784
15866
  });
15785
- var LlmErrorCodeSchema = _enum([
15786
- "timeout",
15787
- "rate-limited",
15788
- "auth",
15789
- "refusal",
15790
- "bad-request",
15791
- "unavailable",
15792
- "no-profile",
15793
- "budget-exceeded",
15794
- "adapter-error"
15795
- ]);
15796
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15867
+ var AddBrokerInputSchema = object({
15868
+ name: string().min(1),
15869
+ url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
15870
+ username: string().optional(),
15871
+ password: string().optional(),
15872
+ clientIdPrefix: string().optional()
15873
+ });
15874
+ var AddBrokerResultSchema = object({ id: string() });
15875
+ var IdInputSchema = object({ id: string() });
15876
+ var TestResultSchema$1 = discriminatedUnion("ok", [object({
15797
15877
  ok: literal(true),
15798
- text: string(),
15799
- model: string(),
15800
- usage: LlmUsageSchema,
15801
- truncated: boolean(),
15802
15878
  latencyMs: number()
15803
- }), object({
15804
- ok: literal(false),
15805
- code: LlmErrorCodeSchema,
15806
- message: string(),
15807
- retryAfterMs: number().optional()
15808
- })]);
15809
- /**
15810
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15811
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15812
- * notification-output.cap.ts:27-31 precedents).
15813
- */
15814
- var LlmImageSchema = object({
15815
- bytes: _instanceof(Uint8Array),
15816
- mimeType: string()
15817
- });
15818
- var LlmGenerateBaseInputSchema = object({
15819
- /** Collection routing (the notification-output posture). */
15820
- addonId: string().optional(),
15821
- /** Explicit profile; else the resolution chain (spec §3). */
15822
- profileId: string().optional(),
15823
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15824
- consumer: string(),
15825
- system: string().optional(),
15826
- /** v1: single-turn. `messages[]` is a v2 additive field. */
15827
- prompt: string(),
15828
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15829
- jsonSchema: record(string(), unknown()).optional(),
15830
- /** Per-call override of the profile default. */
15831
- maxTokens: number().int().positive().optional(),
15832
- temperature: number().optional()
15833
- });
15834
- /**
15835
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15836
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15837
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15838
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15839
- * this only through the `llm` cap's methods.
15840
- *
15841
- * One running llama-server child per node in v1 (models are RAM-heavy).
15842
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15843
- * watchdog — operator decision #3).
15844
- */
15845
- var ManagedModelRefSchema = discriminatedUnion("kind", [
15846
- object({
15847
- kind: literal("catalog"),
15848
- catalogId: string()
15849
- }),
15850
- object({
15851
- kind: literal("url"),
15852
- url: string(),
15853
- sha256: string().optional()
15854
- }),
15855
- object({
15856
- kind: literal("path"),
15857
- path: string()
15858
- })
15859
- ]);
15860
- var ManagedRuntimeConfigSchema = object({
15861
- /** WHERE the runtime lives — hub or any agent. */
15862
- nodeId: string(),
15863
- /** Closed for v1; 'ollama' is a v2 candidate. */
15864
- engine: _enum(["llama-cpp"]),
15865
- model: ManagedModelRefSchema,
15866
- contextSize: number().int().default(4096),
15867
- /** 0 = CPU-only. */
15868
- gpuLayers: number().int().default(0),
15869
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15870
- threads: number().int().optional(),
15871
- /** Concurrent slots. */
15872
- parallel: number().int().default(1),
15873
- /** Else lazy: first generate boots it. */
15874
- autoStart: boolean().default(false),
15875
- /** 0 = never; frees RAM after quiet periods. */
15876
- idleStopMinutes: number().int().default(30)
15879
+ }), object({
15880
+ ok: literal(false),
15881
+ error: string()
15882
+ })]);
15883
+ var StartEmbeddedInputSchema = object({
15884
+ port: number().int().min(1).max(65535).default(1883),
15885
+ /** Allow anonymous connect (no username/password). Default: false. */
15886
+ allowAnonymous: boolean().default(false),
15887
+ /** Optional shared username/password for clients. */
15888
+ username: string().optional(),
15889
+ password: string().optional()
15877
15890
  });
15878
- var LlmRuntimeStatusSchema = object({
15879
- /** Status is ALWAYS node-qualified. */
15880
- nodeId: string(),
15881
- state: _enum([
15882
- "stopped",
15883
- "downloading",
15884
- "starting",
15885
- "ready",
15886
- "crashed",
15887
- "failed"
15888
- ]),
15889
- pid: number().optional(),
15890
- port: number().optional(),
15891
- modelPath: string().optional(),
15892
- modelId: string().optional(),
15893
- downloadProgress: number().min(0).max(1).optional(),
15894
- lastError: string().optional(),
15895
- crashesInWindow: number(),
15896
- /** Child RSS (sampled best-effort). */
15897
- memoryBytes: number().optional(),
15898
- vramBytes: number().optional()
15891
+ var StartEmbeddedResultSchema = object({
15892
+ id: string(),
15893
+ url: string()
15899
15894
  });
15900
- var LlmNodeModelSchema = object({
15901
- file: string(),
15902
- sizeBytes: number(),
15903
- catalogId: string().optional(),
15904
- installedAt: number().optional()
15895
+ var StatusSchema = object({
15896
+ brokerCount: number(),
15897
+ embeddedRunning: boolean()
15905
15898
  });
15906
- var LlmRuntimeDiskUsageSchema = object({
15907
- nodeId: string(),
15908
- modelsBytes: number(),
15909
- freeBytes: number().optional()
15899
+ method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnectionDetailsSchema), method(AddBrokerInputSchema, AddBrokerResultSchema, { kind: "mutation" }), method(IdInputSchema, _void(), { kind: "mutation" }), method(IdInputSchema, TestResultSchema$1, { kind: "mutation" }), method(StartEmbeddedInputSchema, StartEmbeddedResultSchema, { kind: "mutation" }), method(IdInputSchema, _void(), { kind: "mutation" }), method(_void(), StatusSchema);
15900
+ var NetworkEndpointSchema = object({
15901
+ url: string(),
15902
+ hostname: string(),
15903
+ port: number(),
15904
+ protocol: _enum(["http", "https"])
15905
+ });
15906
+ var NetworkAccessStatusSchema = object({
15907
+ connected: boolean(),
15908
+ endpoint: NetworkEndpointSchema.nullable(),
15909
+ error: string().optional()
15910
15910
  });
15911
- var llmRuntimeCapability = {
15912
- name: "llm-runtime",
15913
- scope: "system",
15914
- mode: "singleton",
15915
- internal: true,
15916
- methods: {
15917
- complete: method(LlmGenerateBaseInputSchema.extend({
15918
- images: array(LlmImageSchema).optional(),
15919
- runtime: ManagedRuntimeConfigSchema,
15920
- /** The managed profile's timeout, threaded by the hub provider. */
15921
- timeoutMs: number().int().positive().optional()
15922
- }), LlmGenerateResultSchema, { kind: "mutation" }),
15923
- ensureStarted: method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15924
- kind: "mutation",
15925
- auth: "admin"
15926
- }),
15927
- stop: method(object({}), _void(), {
15928
- kind: "mutation",
15929
- auth: "admin"
15930
- }),
15931
- status: method(object({}), LlmRuntimeStatusSchema),
15932
- installModel: method(object({ model: ManagedModelRefSchema }), _void(), {
15933
- kind: "mutation",
15934
- auth: "admin"
15935
- }),
15936
- deleteModel: method(object({ file: string() }), _void(), {
15937
- kind: "mutation",
15938
- auth: "admin"
15939
- }),
15940
- listLocalModels: method(object({}), array(LlmNodeModelSchema)),
15941
- getDiskUsage: method(object({}), LlmRuntimeDiskUsageSchema)
15942
- }
15943
- };
15944
15911
  /**
15945
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15946
- * methods concat-fan across providers; single-row methods route to ONE
15947
- * provider by the `addonId` in the call input (the notification-output
15948
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15949
- * (hub-placed); the cap stays open for future providers.
15912
+ * Optional, richer endpoint shape returned by providers that expose
15913
+ * MORE than one ingress concurrently (Tailscale Ingress with mixed
15914
+ * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
15915
+ * the originating provider config (mode + sourcePort) so the
15916
+ * orchestrator UI can label rows distinctly. Providers that expose only
15917
+ * one endpoint just omit `listEndpoints` from their provider impl.
15918
+ */
15919
+ var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
15920
+ /**
15921
+ * Stable id within the provider — typically `<mode>-<sourcePort>` so
15922
+ * the orchestrator can dedupe across `listEndpoints` polls.
15923
+ */
15924
+ id: string(),
15925
+ /** Operator-facing label (mirrors `MeshEndpoint.label`). */
15926
+ label: string(),
15927
+ /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
15928
+ mode: string().optional(),
15929
+ /** Originating local port the ingress fronts (informational). */
15930
+ sourcePort: number().optional()
15931
+ });
15932
+ method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
15933
+ /**
15934
+ * notification-output — canonical, capability-gated notification delivery.
15950
15935
  *
15951
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15952
- * `apiKey` is a password field — providers REDACT it on read and merge on
15953
- * write; a stored key NEVER round-trips to a client.
15936
+ * Apprise-derived model (see
15937
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
15938
+ * callers emit ONE canonical `Notification`; each provider declares a
15939
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
15940
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
15941
+ * message to what the kind supports — callers never special-case a service.
15942
+ *
15943
+ * DESIGN DECISIONS (locked):
15944
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
15945
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
15946
+ * cap. Rationale: the admin UI needs one uniform surface across the
15947
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
15948
+ * alternative would fork the UI per addon and cannot host the
15949
+ * discovery→adopt flow.
15950
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
15951
+ * the generated cap-mount auto-`concatCollection`-fans them across every
15952
+ * registered provider (notifiers addon + HA addon) so one catalog is
15953
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
15954
+ * `addonId` the generated collection router extracts from the call input.
15955
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
15956
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
15957
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
15958
+ * base64 fallback needed.
15959
+ *
15960
+ * TODO (deferred, closed-set change — separate decision): add
15961
+ * `providerKind: 'notify'` so notification providers surface on the unified
15962
+ * admin "Integrations" page.
15954
15963
  */
15955
- var LlmProfileKindSchema = _enum([
15956
- "openai-compatible",
15957
- "openai",
15958
- "anthropic",
15959
- "google",
15960
- "managed-local"
15964
+ /**
15965
+ * Zentik-derived typed-media enum — the superset across every kind. Each
15966
+ * adapter picks what it supports and the degrade engine filters the rest.
15967
+ */
15968
+ var AttachmentMediaTypeSchema = _enum([
15969
+ "image",
15970
+ "video",
15971
+ "gif",
15972
+ "audio",
15973
+ "icon"
15961
15974
  ]);
15962
- var LlmProfileSchema = object({
15975
+ /**
15976
+ * A single attachment. Exactly one of `url` (remote source, most adapters
15977
+ * prefer this) or `bytes` (inline source; required for Pushover-style
15978
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
15979
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
15980
+ */
15981
+ var AttachmentSchema = object({
15982
+ mediaType: AttachmentMediaTypeSchema,
15983
+ url: string().optional(),
15984
+ bytes: _instanceof(Uint8Array).optional(),
15985
+ mime: string().optional(),
15986
+ name: string().optional()
15987
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
15988
+ var NotificationFormatSchema = _enum([
15989
+ "text",
15990
+ "markdown",
15991
+ "html"
15992
+ ]);
15993
+ /** A single tap-through action button. */
15994
+ var NotificationActionSchema = object({
15963
15995
  id: string(),
15964
- name: string(),
15965
- kind: LlmProfileKindSchema,
15966
- /** Stamped by the provider — keeps the fanned catalog routable. */
15967
- addonId: string(),
15968
- enabled: boolean(),
15969
- /** Vendor model id, or the managed runtime's loaded model. */
15970
- model: string(),
15971
- /** Required for openai-compatible; override for cloud kinds. */
15972
- baseUrl: string().optional(),
15973
- /** ConfigUISchema type:'password' never round-trips (spec §5). */
15974
- apiKey: string().optional(),
15975
- supportsVision: boolean(),
15976
- temperature: number().min(0).max(2).optional(),
15977
- maxTokens: number().int().positive().optional(),
15978
- timeoutMs: number().int().positive().default(6e4),
15979
- extraHeaders: record(string(), string()).optional(),
15980
- /** kind === 'managed-local' only (spec §4). */
15981
- runtime: ManagedRuntimeConfigSchema.optional()
15996
+ label: string(),
15997
+ url: string().optional()
15998
+ });
15999
+ /**
16000
+ * The canonical notification. `body` is the only hard field (Apprise model).
16001
+ * `priority` is a 5-level ORDINAL (1=lowest 3=normal(default) 5=urgent),
16002
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
16003
+ * the adapter maps this ordinal onto its native level. `level?` is an
16004
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
16005
+ * `priority` for that one target.
16006
+ */
16007
+ var NotificationSchema = object({
16008
+ body: string(),
16009
+ title: string().optional(),
16010
+ format: NotificationFormatSchema.default("text"),
16011
+ priority: number().int().min(1).max(5).default(3),
16012
+ level: string().optional(),
16013
+ attachments: array(AttachmentSchema).optional(),
16014
+ clickUrl: string().optional(),
16015
+ actions: array(NotificationActionSchema).optional(),
16016
+ sound: string().optional(),
16017
+ ttl: number().optional(),
16018
+ tag: string().optional(),
16019
+ deviceId: number().optional(),
16020
+ eventId: string().optional(),
16021
+ metadata: record(string(), unknown()).optional()
16022
+ });
16023
+ /** One declared native severity/priority level for a kind. */
16024
+ var TargetKindLevelSchema = object({
16025
+ id: string(),
16026
+ label: string(),
16027
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
16028
+ ordinal: number().int().min(1).max(5).nullable(),
16029
+ flags: object({
16030
+ critical: boolean().optional(),
16031
+ silent: boolean().optional(),
16032
+ noPush: boolean().optional()
16033
+ }).optional(),
16034
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
16035
+ requires: array(string()).optional(),
16036
+ description: string().optional()
16037
+ });
16038
+ /** The full capability block consulted before dispatch. */
16039
+ var TargetKindCapsSchema = object({
16040
+ attachments: object({
16041
+ mediaTypes: array(AttachmentMediaTypeSchema),
16042
+ mode: _enum([
16043
+ "url",
16044
+ "bytes",
16045
+ "both"
16046
+ ]),
16047
+ max: number().int().nonnegative(),
16048
+ maxBytes: number().int().positive().optional()
16049
+ }),
16050
+ /** Max action buttons (0 = none). */
16051
+ actions: number().int().nonnegative(),
16052
+ levels: array(TargetKindLevelSchema),
16053
+ format: array(NotificationFormatSchema),
16054
+ clickUrl: boolean(),
16055
+ sound: boolean(),
16056
+ ttl: boolean(),
16057
+ bodyMaxLen: number().int().positive()
15982
16058
  });
15983
- /** ConfigUISchema tree passed through untyped on the wire (the
15984
- * notification-output `ConfigSchemaPassthrough` precedent at
15985
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
16059
+ /**
16060
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
16061
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
16062
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
16063
+ * the union is large and not meant for runtime validation here; the exported
16064
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
16065
+ */
15986
16066
  var ConfigSchemaPassthrough = unknown();
15987
- var LlmProfileKindDescriptorSchema = object({
15988
- kind: LlmProfileKindSchema,
16067
+ var TargetKindSchema = object({
16068
+ kind: string(),
15989
16069
  label: string(),
15990
16070
  icon: string(),
15991
16071
  /** Stamped by each provider so the concat-fanned catalog stays routable. */
15992
16072
  addonId: string(),
15993
- configSchema: ConfigSchemaPassthrough
16073
+ configSchema: ConfigSchemaPassthrough,
16074
+ supportsDiscovery: boolean(),
16075
+ caps: TargetKindCapsSchema
15994
16076
  });
15995
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15996
- var LlmDefaultSchema = object({
15997
- selector: LlmDefaultSelectorSchema,
15998
- profileId: string()
16077
+ /**
16078
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
16079
+ * (return a presence marker only) when serving `listTargets` — never
16080
+ * round-trip a stored secret to the UI.
16081
+ */
16082
+ var TargetSchema = object({
16083
+ id: string(),
16084
+ name: string(),
16085
+ kind: string(),
16086
+ addonId: string(),
16087
+ enabled: boolean(),
16088
+ config: record(string(), unknown())
15999
16089
  });
16000
- /** Server-side rollup row getUsage never dumps raw call rows (spec §6). */
16001
- var LlmUsageRollupSchema = object({
16002
- day: string(),
16003
- consumer: string(),
16004
- profileId: string(),
16005
- calls: number(),
16006
- okCalls: number(),
16007
- errorCalls: number(),
16008
- inputTokens: number(),
16009
- outputTokens: number(),
16010
- avgLatencyMs: number()
16090
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
16091
+ var DiscoveredTargetSchema = object({
16092
+ kind: string(),
16093
+ suggestedName: string(),
16094
+ config: record(string(), unknown())
16011
16095
  });
16012
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
16013
- var ManagedModelCatalogEntrySchema = object({
16014
- id: string(),
16015
- label: string(),
16016
- family: string(),
16017
- purpose: _enum(["text", "vision"]),
16018
- url: string(),
16019
- sha256: string(),
16020
- sizeBytes: number(),
16021
- quantization: string(),
16022
- /** Load-time guidance shown in the picker. */
16023
- minRamBytes: number(),
16024
- contextSizeDefault: number().int(),
16025
- /** Vision models: companion projector file. */
16026
- mmprojUrl: string().optional()
16096
+ /** The degrade engine's report what was resolved / dropped / degraded. */
16097
+ var RenderedAsSchema = object({
16098
+ level: string(),
16099
+ format: NotificationFormatSchema,
16100
+ attachmentsSent: number().int().nonnegative(),
16101
+ actionsSent: number().int().nonnegative(),
16102
+ truncated: boolean(),
16103
+ dropped: array(string())
16027
16104
  });
16028
- var LlmRuntimeNodeSchema = object({
16029
- nodeId: string(),
16030
- reachable: boolean(),
16031
- status: LlmRuntimeStatusSchema.optional(),
16032
- disk: LlmRuntimeDiskUsageSchema.optional(),
16033
- error: string().optional()
16105
+ var SendResultSchema = object({
16106
+ success: boolean(),
16107
+ error: string().optional(),
16108
+ renderedAs: RenderedAsSchema.optional()
16034
16109
  });
16035
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16036
- var ProfileRefInputSchema = object({
16037
- addonId: string(),
16038
- profileId: string()
16110
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
16111
+ var TestResultSchema = SendResultSchema;
16112
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
16113
+ kind: string(),
16114
+ config: record(string(), unknown()).optional()
16115
+ }), array(DiscoveredTargetSchema)), method(object({
16116
+ targetId: string(),
16117
+ notification: NotificationSchema
16118
+ }), SendResultSchema, { kind: "mutation" }), method(object({
16119
+ targetId: string(),
16120
+ sample: NotificationSchema.optional()
16121
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
16122
+ targetId: string(),
16123
+ enabled: boolean()
16124
+ }), _void(), { kind: "mutation" });
16125
+ /**
16126
+ * notification-rules — the Notification Center rule surface (P1 core).
16127
+ *
16128
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16129
+ * (operator decisions D-1/D-2/D-3 are binding):
16130
+ *
16131
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16132
+ * `notification-center` module), hooked on the durable persistence
16133
+ * moments (object-event insert, TrackCloser.closeExpired) with a
16134
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
16135
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16136
+ * FIRST persisted detection matching the conditions (per-track dedup,
16137
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16138
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
16139
+ * - DISPATCH stays behind `notification-output` (rules reference targets
16140
+ * by id; per-backend params are a passthrough blob capped by the
16141
+ * target kind's own caps/degrade engine).
16142
+ *
16143
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
16144
+ * server-injected caller identity — the first `caller: 'required'`
16145
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
16146
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
16147
+ * windows, and the optional label/identity/plate matchers. User rules,
16148
+ * private zones, per-recipient fan-out and the wider condition table are
16149
+ * P2+ (see spec §7).
16150
+ *
16151
+ * All schemas here are the single source of truth — `NcRule` etc. are
16152
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16153
+ * schema/interface drift is explicitly not repeated).
16154
+ */
16155
+ /**
16156
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
16157
+ * The value maps 1:1 onto the evaluated record kind:
16158
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16159
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16160
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16161
+ * change of a LINKED device, one row per linked camera)
16162
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16163
+ * delivery / pick-up)
16164
+ *
16165
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16166
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
16167
+ * this one field keeps the schema additive — a rule still declares exactly
16168
+ * one trigger.
16169
+ */
16170
+ var NcDeliverySchema = _enum([
16171
+ "immediate",
16172
+ "track-end",
16173
+ "device-event",
16174
+ "package-event"
16175
+ ]);
16176
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
16177
+ var NcScheduleSchema = object({
16178
+ windows: array(object({
16179
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16180
+ days: array(number().int().min(0).max(6)).min(1),
16181
+ startMinute: number().int().min(0).max(1439),
16182
+ endMinute: number().int().min(0).max(1439)
16183
+ })).min(1),
16184
+ /** IANA timezone; default = hub host timezone. */
16185
+ timezone: string().optional(),
16186
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16187
+ invert: boolean().optional()
16039
16188
  });
16040
- var llmCapability = {
16041
- name: "llm",
16042
- scope: "system",
16043
- mode: "collection",
16044
- internal: false,
16045
- providerKind: "ai",
16046
- /** `nodeId` inputs below are DATA (the hub provider pins itself), never routing. */
16047
- nodeIdMode: "data",
16048
- methods: {
16049
- generate: method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }),
16050
- generateVision: method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }),
16051
- listProfileKinds: method(object({}), array(LlmProfileKindDescriptorSchema)),
16052
- listProfiles: method(object({}), array(LlmProfileSchema)),
16053
- upsertProfile: method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16054
- kind: "mutation",
16055
- auth: "admin"
16056
- }),
16057
- deleteProfile: method(ProfileRefInputSchema, _void(), {
16058
- kind: "mutation",
16059
- auth: "admin"
16060
- }),
16061
- testProfile: method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16062
- kind: "mutation",
16063
- auth: "admin"
16064
- }),
16065
- /** Live vendor enumeration (GET /models etc.). */
16066
- listModels: method(ProfileRefInputSchema, array(string())),
16067
- getDefaults: method(object({}), array(LlmDefaultSchema)),
16068
- setDefault: method(object({
16069
- selector: LlmDefaultSelectorSchema,
16070
- profileId: string().nullable()
16071
- }), _void(), {
16072
- kind: "mutation",
16073
- auth: "admin"
16074
- }),
16075
- getUsage: method(object({
16076
- since: number().optional(),
16077
- until: number().optional(),
16078
- consumer: string().optional(),
16079
- profileId: string().optional()
16080
- }), array(LlmUsageRollupSchema)),
16081
- listModelCatalog: method(object({}), array(ManagedModelCatalogEntrySchema)),
16082
- listRuntimeNodes: method(object({}), array(LlmRuntimeNodeSchema)),
16083
- listNodeModels: method(object({ nodeId: string() }), array(LlmNodeModelSchema)),
16084
- installModel: method(object({
16085
- nodeId: string(),
16086
- model: ManagedModelRefSchema
16087
- }), _void(), {
16088
- kind: "mutation",
16089
- auth: "admin"
16090
- }),
16091
- deleteModel: method(object({
16092
- nodeId: string(),
16093
- file: string()
16094
- }), _void(), {
16095
- kind: "mutation",
16096
- auth: "admin"
16097
- }),
16098
- getRuntimeStatus: method(ProfileRefInputSchema, LlmRuntimeStatusSchema),
16099
- startRuntime: method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16100
- kind: "mutation",
16101
- auth: "admin"
16102
- }),
16103
- stopRuntime: method(ProfileRefInputSchema, _void(), {
16104
- kind: "mutation",
16105
- auth: "admin"
16106
- })
16107
- }
16108
- };
16189
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16190
+ var NcPlateMatcherSchema = object({
16191
+ values: array(string().min(1)).min(1),
16192
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16193
+ maxDistance: number().int().min(0).max(3).default(1)
16194
+ });
16195
+ /**
16196
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16197
+ * occupancy edge for a device — optionally narrowed to a single admin
16198
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16199
+ * - `became-occupied` (default) count crossed 0 → ≥ `count`
16200
+ * - `became-free` — count crossed ≥ `count` → below it
16201
+ * - `>=` / `<=` — count is at/over or at/under `count`
16202
+ * `sustainSeconds` requires the condition hold continuously that long
16203
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
16204
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16205
+ * the condition never matches. Confirmed edge-state survives addon restarts
16206
+ * (declared SQLite collection, reseeded on boot).
16207
+ */
16208
+ var NcOccupancyConditionSchema = object({
16209
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16210
+ zoneId: string().optional(),
16211
+ /** Object class to count; absent = any class. */
16212
+ className: string().optional(),
16213
+ op: _enum([
16214
+ "became-occupied",
16215
+ "became-free",
16216
+ ">=",
16217
+ "<="
16218
+ ]).default("became-occupied"),
16219
+ count: number().int().min(0).default(1),
16220
+ sustainSeconds: number().int().min(0).max(3600).default(15)
16221
+ });
16222
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16223
+ var NcZoneConditionSchema = object({
16224
+ ids: array(string().min(1)).min(1),
16225
+ /** Quantifier over `ids` — at least one / every one visited. */
16226
+ match: _enum(["any", "all"]).default("any")
16227
+ });
16228
+ /**
16229
+ * The P1 condition set — a flat AND of groups; absent group = pass;
16230
+ * membership lists are OR within the list (spec §2.3).
16231
+ */
16232
+ var NcConditionsSchema = object({
16233
+ /** Device scope — absent = all devices. */
16234
+ devices: array(number()).optional(),
16235
+ /** Detector class names (any overlap with the record's class set). */
16236
+ classes: array(string().min(1)).optional(),
16237
+ /** Veto classes — any overlap fails the rule. */
16238
+ classesExclude: array(string().min(1)).optional(),
16239
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
16240
+ minConfidence: number().min(0).max(1).optional(),
16241
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
16242
+ zones: NcZoneConditionSchema.optional(),
16243
+ /** Veto zones — any hit fails the rule. */
16244
+ zonesExclude: array(string().min(1)).optional(),
16245
+ /**
16246
+ * Exact (case-insensitive) match on the record's collapsed `label`
16247
+ * (identity name / plate text / subclass).
16248
+ */
16249
+ labelEquals: array(string().min(1)).optional(),
16250
+ /**
16251
+ * Identity matcher. P1 boundary: matched against the record's collapsed
16252
+ * `label` (the identity display name propagated by the face pipeline)
16253
+ * identity-ID matching rides in P2 when identity ids reach the record.
16254
+ */
16255
+ identities: array(string().min(1)).optional(),
16256
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
16257
+ plates: NcPlateMatcherSchema.optional(),
16258
+ /**
16259
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16260
+ * Same P1 boundary: matched against the record's collapsed `label` (the
16261
+ * identity display name). A record with NO label passes (nothing to
16262
+ * exclude), unlike the include variant which fails on an absent label.
16263
+ */
16264
+ identitiesExclude: array(string().min(1)).optional(),
16265
+ /**
16266
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16267
+ * TRACK-END only: importance is scored at track close, so it does not exist
16268
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16269
+ * close the value is threaded via the close-time info (the `Track` clone is
16270
+ * captured before the DB row is updated, so it would otherwise read stale).
16271
+ * Fails when the record carries no importance (never guess quality — the
16272
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
16273
+ */
16274
+ minImportance: number().min(0).max(1).optional(),
16275
+ /**
16276
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16277
+ * TRACK-END only: an `immediate` / object-event subject has no closed
16278
+ * lifespan, so a dwell condition never matches immediate delivery
16279
+ * (documented choice — the object-event record carries no `firstSeen`,
16280
+ * so dwell cannot be computed from what the subject actually carries).
16281
+ */
16282
+ minDwellSeconds: number().min(0).optional(),
16283
+ /**
16284
+ * Detection provenance filter. `any` (default / absent) matches every
16285
+ * source; otherwise the subject's source must equal it. Legacy records
16286
+ * with no stamped source are treated as `pipeline`. The union spans both
16287
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
16288
+ * tracks carry `sensor`.
16289
+ */
16290
+ source: _enum([
16291
+ "pipeline",
16292
+ "onboard",
16293
+ "sensor",
16294
+ "any"
16295
+ ]).optional(),
16296
+ /**
16297
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16298
+ * detector `minConfidence` (that gates the object-detection score; this
16299
+ * gates the recognition/OCR match score). Fails when the subject carries
16300
+ * no label-match confidence (never guess). TRACK-END only: the confidence
16301
+ * lives on the recognition result and reaches the subject at track close.
16302
+ *
16303
+ * What it measures precisely (plumbed at track close — the closer threads
16304
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16305
+ * `importance`): the BEST recognition match confidence observed for the
16306
+ * label the track carries at close — for a face, the peak cosine similarity
16307
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16308
+ * for a plate, the peak OCR read score of the best-held plate
16309
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16310
+ * one track the higher of the two is used. A track that ended with no
16311
+ * confident identity/plate match carries no value, so the condition fails
16312
+ * closed for it (an un-recognized subject).
16313
+ */
16314
+ minLabelConfidence: number().min(0).max(1).optional(),
16315
+ /**
16316
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16317
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16318
+ * against the token carried on the device-event subject (extracted from the
16319
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16320
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16321
+ * eventType, so gate those with {@link sensorKinds} instead.
16322
+ */
16323
+ eventTypeTokens: array(string().min(1)).optional(),
16324
+ /**
16325
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16326
+ * `contact`, `button`, `device-event`) — matched against the persisted
16327
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16328
+ */
16329
+ sensorKinds: array(string().min(1)).optional(),
16330
+ /**
16331
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16332
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16333
+ * when the subject's phase does not match (a subject always carries a phase
16334
+ * on the package-event trigger).
16335
+ */
16336
+ packagePhase: _enum([
16337
+ "delivered",
16338
+ "picked-up",
16339
+ "both"
16340
+ ]).optional(),
16341
+ /**
16342
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16343
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16344
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
16345
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16346
+ */
16347
+ customZones: array(MaskPolygonShapeSchema).optional(),
16348
+ /**
16349
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16350
+ * (optionally zone/class-scoped) occupancy count crosses the configured
16351
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
16352
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16353
+ */
16354
+ occupancy: NcOccupancyConditionSchema.optional()
16355
+ });
16356
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
16357
+ var NcRuleTargetSchema = object({
16358
+ /** `notification-output` Target id. */
16359
+ targetId: string().min(1),
16360
+ /**
16361
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
16362
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16363
+ * degrade engine drops what the backend can't render.
16364
+ */
16365
+ params: record(string(), unknown()).optional()
16366
+ });
16367
+ /**
16368
+ * Media attachment policy (P1 still-image subset).
16369
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
16370
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
16371
+ * matched on identities attaches the subject's `faceCrop`, one matched on
16372
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
16373
+ * (or when the specific crop is missing) degrades to `best`, then
16374
+ * `keyFrame`, then no attachment — never delaying the send. The matched
16375
+ * condition summary is frozen on the outbox row at enqueue (like the rule
16376
+ * name), so the choice never drifts from the record that fired it.
16377
+ * - `keyFrame` — the clean scene frame (no subject box).
16378
+ * - `none` — no attachment.
16379
+ */
16380
+ var NcMediaPolicySchema = object({ attach: _enum([
16381
+ "best",
16382
+ "best-matching",
16383
+ "keyFrame",
16384
+ "none"
16385
+ ]).default("best") });
16386
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16387
+ var NcThrottleSchema = object({
16388
+ cooldownSec: number().int().min(0).max(86400).default(60),
16389
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16390
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
16391
+ });
16392
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16393
+ var NcRuleInputSchema = object({
16394
+ name: string().min(1).max(200),
16395
+ enabled: boolean().default(true),
16396
+ delivery: NcDeliverySchema,
16397
+ conditions: NcConditionsSchema.default({}),
16398
+ schedule: NcScheduleSchema.optional(),
16399
+ targets: array(NcRuleTargetSchema).min(1),
16400
+ media: NcMediaPolicySchema.default({ attach: "best" }),
16401
+ throttle: NcThrottleSchema.default({
16402
+ cooldownSec: 60,
16403
+ scope: "rule-device"
16404
+ }),
16405
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16406
+ template: object({
16407
+ title: string().max(500).optional(),
16408
+ body: string().max(2e3).optional()
16409
+ }).optional(),
16410
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
16411
+ priority: number().int().min(1).max(5).default(3),
16412
+ /**
16413
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16414
+ * behaviour, visible to all, read-only in the viewer). Present = personal
16415
+ * rule owned by this userId. Server-stamped; never trusted from a client.
16416
+ */
16417
+ ownerUserId: string().optional()
16418
+ });
16419
+ /**
16420
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
16421
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16422
+ * NOT a client-authored input field (it lives on the persisted rule, not the
16423
+ * input), so it is added here explicitly to let the store's per-target opt-out
16424
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16425
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16426
+ * `updateRule` patch.
16427
+ */
16428
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
16429
+ /** A persisted rule. */
16430
+ var NcRuleSchema = NcRuleInputSchema.extend({
16431
+ id: string(),
16432
+ /** userId of the admin who created the rule (server-stamped caller). */
16433
+ createdBy: string(),
16434
+ createdAt: number(),
16435
+ updatedAt: number(),
16436
+ /**
16437
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16438
+ * send time. Only a target's OWNER may add/remove its id (server-checked
16439
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
16440
+ */
16441
+ disabledTargetIds: array(string()).default([])
16442
+ });
16443
+ var NcTestResultSchema = object({
16444
+ recordId: string(),
16445
+ recordKind: _enum([
16446
+ "object-event",
16447
+ "track",
16448
+ "device-event",
16449
+ "package-event"
16450
+ ]),
16451
+ deviceId: number(),
16452
+ timestamp: number(),
16453
+ wouldFire: boolean(),
16454
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
16455
+ failedCondition: string().optional(),
16456
+ className: string().optional(),
16457
+ label: string().optional()
16458
+ });
16459
+ var NcConditionDescriptorSchema = object({
16460
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16461
+ id: string(),
16462
+ group: _enum([
16463
+ "scope",
16464
+ "class",
16465
+ "zones",
16466
+ "quality",
16467
+ "label",
16468
+ "schedule",
16469
+ "device",
16470
+ "package",
16471
+ "occupancy"
16472
+ ]),
16473
+ label: string(),
16474
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
16475
+ valueType: _enum([
16476
+ "deviceIdList",
16477
+ "stringList",
16478
+ "number01",
16479
+ "number",
16480
+ "sourceSelect",
16481
+ "zoneSelection",
16482
+ "zoneIdList",
16483
+ "schedule",
16484
+ "plateMatcher",
16485
+ "packagePhase",
16486
+ "polygonDraw",
16487
+ "occupancy"
16488
+ ]),
16489
+ operator: _enum([
16490
+ "in",
16491
+ "notIn",
16492
+ "anyOf",
16493
+ "allOf",
16494
+ "gte",
16495
+ "fuzzyIn",
16496
+ "withinSchedule"
16497
+ ]),
16498
+ /** Which delivery kinds the condition applies to. */
16499
+ appliesTo: array(NcDeliverySchema),
16500
+ phase: string(),
16501
+ description: string().optional()
16502
+ });
16503
+ /**
16504
+ * The delivery lifecycle status of a history row — a straight read of the
16505
+ * durable outbox row's own status (single source of truth):
16506
+ * - `pending` — enqueued, in-flight or retrying with backoff
16507
+ * - `sent` — delivered (terminal)
16508
+ * - `dead` — dead-lettered after exhausting retries / a permanent
16509
+ * backend rejection / a deleted target (terminal; carries
16510
+ * the failure `error`)
16511
+ *
16512
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
16513
+ * user dimension (quiet hours / snooze) and are additive when they land.
16514
+ */
16515
+ var NcHistoryStatusSchema = _enum([
16516
+ "pending",
16517
+ "sent",
16518
+ "dead"
16519
+ ]);
16520
+ /** The evaluated record kind a history row descends from (one per trigger). */
16521
+ var NcHistoryRecordKindSchema = _enum([
16522
+ "object-event",
16523
+ "track-end",
16524
+ "device-event",
16525
+ "package-event"
16526
+ ]);
16527
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16528
+ var NcHistorySubjectSchema = object({
16529
+ className: string(),
16530
+ label: string().optional(),
16531
+ confidence: number().optional(),
16532
+ zones: array(string()),
16533
+ timestamp: number()
16534
+ });
16535
+ /**
16536
+ * One delivery-history row. This is a read-only VIEW over the durable
16537
+ * outbox row (single source of truth — the same row the drain loop drives;
16538
+ * NO second write path, so history can never drift from delivery state).
16539
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16540
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16541
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
16542
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16543
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16544
+ * P1 (admin scope only).
16545
+ */
16546
+ var NcHistoryEntrySchema = object({
16547
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16548
+ id: string(),
16549
+ ruleId: string(),
16550
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
16551
+ ruleName: string(),
16552
+ /** The rule urgency/trigger that produced this delivery. */
16553
+ delivery: NcDeliverySchema,
16554
+ targetId: string(),
16555
+ deviceId: number(),
16556
+ recordKind: NcHistoryRecordKindSchema,
16557
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16558
+ recordId: string(),
16559
+ /** Present for track-scoped deliveries (object-event / track-end). */
16560
+ trackId: string().optional(),
16561
+ status: NcHistoryStatusSchema,
16562
+ /** Delivery attempts made so far. */
16563
+ attempts: number().int(),
16564
+ /** Fire time (outbox enqueue). */
16565
+ createdAt: number(),
16566
+ /** Last transition time (terminal for sent / dead). */
16567
+ updatedAt: number(),
16568
+ /** Failure detail — present on a `dead` row. */
16569
+ error: string().optional(),
16570
+ subject: NcHistorySubjectSchema
16571
+ });
16572
+ /**
16573
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16574
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16575
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16576
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16577
+ */
16578
+ var NcHistoryFilterSchema = object({
16579
+ ruleId: string().optional(),
16580
+ deviceId: number().optional(),
16581
+ status: NcHistoryStatusSchema.optional(),
16582
+ since: number().optional(),
16583
+ until: number().optional(),
16584
+ limit: number().int().min(1).max(500).default(100)
16585
+ });
16586
+ method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), method(object({ ruleId: string() }), object({ rule: NcRuleSchema.nullable() }), { auth: "admin" }), method(object({ rule: NcRuleInputSchema }), object({ rule: NcRuleSchema }), {
16587
+ kind: "mutation",
16588
+ auth: "admin",
16589
+ caller: "required"
16590
+ }), method(object({
16591
+ ruleId: string(),
16592
+ patch: NcRulePatchSchema
16593
+ }), object({ rule: NcRuleSchema }), {
16594
+ kind: "mutation",
16595
+ auth: "admin",
16596
+ caller: "required"
16597
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
16598
+ kind: "mutation",
16599
+ auth: "admin"
16600
+ }), method(object({
16601
+ ruleId: string(),
16602
+ enabled: boolean()
16603
+ }), object({ success: literal(true) }), {
16604
+ kind: "mutation",
16605
+ auth: "admin"
16606
+ }), method(object({
16607
+ rule: NcRuleInputSchema,
16608
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
16609
+ }), object({ results: array(NcTestResultSchema) }), {
16610
+ kind: "mutation",
16611
+ auth: "admin"
16612
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
16109
16613
  /**
16110
16614
  * Zod schemas for persisted record types.
16111
16615
  *
@@ -16791,7 +17295,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16791
17295
  }), method(object({
16792
17296
  eventId: string(),
16793
17297
  kind: MediaFileKindEnum.optional()
16794
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
17298
+ }), array(MediaFileSchema).readonly()), method(object({
17299
+ trackId: string(),
17300
+ kinds: array(MediaFileKindEnum).optional()
17301
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
16795
17302
  deviceId: number(),
16796
17303
  timestamp: number(),
16797
17304
  frameWidth: number(),
@@ -16812,76 +17319,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16812
17319
  eventId: string(),
16813
17320
  timestamp: number()
16814
17321
  });
16815
- /**
16816
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
16817
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
16818
- * caps into per-camera event-kind descriptors.
16819
- *
16820
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
16821
- * is NOT duplicated here — every entry is derived from the single
16822
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
16823
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
16824
- * control cap means adding one line here (and a taxonomy entry); the anti-
16825
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
16826
- * eventful cap is missing.
16827
- */
16828
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
16829
- var LEGACY_ICON = {
16830
- motion: "motion",
16831
- audio: "audio",
16832
- person: "person",
16833
- vehicle: "vehicle",
16834
- animal: "animal",
16835
- package: "package",
16836
- door: "door",
16837
- pir: "pir",
16838
- smoke: "smoke",
16839
- water: "water",
16840
- button: "button",
16841
- generic: "generic",
16842
- gas: "smoke",
16843
- vibration: "generic",
16844
- tamper: "generic",
16845
- presence: "person",
16846
- lock: "generic",
16847
- siren: "generic",
16848
- switch: "generic",
16849
- doorbell: "button"
16850
- };
16851
- function legacyIcon(iconId) {
16852
- return LEGACY_ICON[iconId] ?? "generic";
16853
- }
16854
- /**
16855
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
16856
- * The anti-drift guard cross-checks this against the eventful caps declared
16857
- * in `packages/types/src/capabilities/*.cap.ts`.
16858
- */
16859
- var CAP_TO_KIND = {
16860
- contact: "contact",
16861
- motion: "motion-sensor",
16862
- smoke: "smoke",
16863
- flood: "flood",
16864
- gas: "gas",
16865
- "carbon-monoxide": "carbon-monoxide",
16866
- vibration: "vibration",
16867
- tamper: "tamper",
16868
- presence: "presence",
16869
- "enum-sensor": "enum-sensor",
16870
- "event-emitter": "device-event",
16871
- "lock-control": "lock",
16872
- switch: "switch",
16873
- button: "button",
16874
- doorbell: "doorbell"
16875
- };
16876
- function buildDescriptor(capName, kind) {
16877
- const t = EVENT_TAXONOMY[kind];
16878
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
16879
- return {
16880
- ...t,
16881
- icon: legacyIcon(t.iconId)
16882
- };
16883
- }
16884
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
16885
17322
  var CameraPipelineConfigSchema = object({
16886
17323
  engine: PipelineEngineChoiceSchema.optional(),
16887
17324
  steps: array(PipelineStepInputSchema).readonly(),
@@ -17367,6 +17804,76 @@ method(object({
17367
17804
  auth: "admin"
17368
17805
  });
17369
17806
  /**
17807
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
17808
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
17809
+ * caps into per-camera event-kind descriptors.
17810
+ *
17811
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
17812
+ * is NOT duplicated here — every entry is derived from the single
17813
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
17814
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
17815
+ * control cap means adding one line here (and a taxonomy entry); the anti-
17816
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
17817
+ * eventful cap is missing.
17818
+ */
17819
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
17820
+ var LEGACY_ICON = {
17821
+ motion: "motion",
17822
+ audio: "audio",
17823
+ person: "person",
17824
+ vehicle: "vehicle",
17825
+ animal: "animal",
17826
+ package: "package",
17827
+ door: "door",
17828
+ pir: "pir",
17829
+ smoke: "smoke",
17830
+ water: "water",
17831
+ button: "button",
17832
+ generic: "generic",
17833
+ gas: "smoke",
17834
+ vibration: "generic",
17835
+ tamper: "generic",
17836
+ presence: "person",
17837
+ lock: "generic",
17838
+ siren: "generic",
17839
+ switch: "generic",
17840
+ doorbell: "button"
17841
+ };
17842
+ function legacyIcon(iconId) {
17843
+ return LEGACY_ICON[iconId] ?? "generic";
17844
+ }
17845
+ /**
17846
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
17847
+ * The anti-drift guard cross-checks this against the eventful caps declared
17848
+ * in `packages/types/src/capabilities/*.cap.ts`.
17849
+ */
17850
+ var CAP_TO_KIND = {
17851
+ contact: "contact",
17852
+ motion: "motion-sensor",
17853
+ smoke: "smoke",
17854
+ flood: "flood",
17855
+ gas: "gas",
17856
+ "carbon-monoxide": "carbon-monoxide",
17857
+ vibration: "vibration",
17858
+ tamper: "tamper",
17859
+ presence: "presence",
17860
+ "enum-sensor": "enum-sensor",
17861
+ "event-emitter": "device-event",
17862
+ "lock-control": "lock",
17863
+ switch: "switch",
17864
+ button: "button",
17865
+ doorbell: "doorbell"
17866
+ };
17867
+ function buildDescriptor(capName, kind) {
17868
+ const t = EVENT_TAXONOMY[kind];
17869
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
17870
+ return {
17871
+ ...t,
17872
+ icon: legacyIcon(t.iconId)
17873
+ };
17874
+ }
17875
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
17876
+ /**
17370
17877
  * server-management — per-NODE singleton capability for a node's ROOT
17371
17878
  * package lifecycle (runtime-updatable node packages).
17372
17879
  *
@@ -18821,7 +19328,28 @@ var FaceInfoSchema = object({
18821
19328
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
18822
19329
  * track produced no key frame (e.g. native/onboard source) — the UI falls
18823
19330
  * back to the inline `base64` face crop. */
18824
- keyFrameMediaKey: string().optional()
19331
+ keyFrameMediaKey: string().optional(),
19332
+ /** Winning identity-match cosine (0..1) for this face's track, when an
19333
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
19334
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
19335
+ * faces that were never auto-recognized. */
19336
+ bestMatchScore: number().optional(),
19337
+ /** Native-scale face short side (px) at recognition time, when the runner
19338
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
19339
+ * legacy rows / runners that reported no native measure. */
19340
+ nativeFaceShortSidePx: number().optional(),
19341
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
19342
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
19343
+ * but blocked only by the recognition size floor). Mutually exclusive with
19344
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
19345
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
19346
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
19347
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
19348
+ suggestedIdentityId: string().optional(),
19349
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
19350
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
19351
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
19352
+ suggestedMatchScore: number().optional()
18825
19353
  });
18826
19354
  var FaceFilterEnum = _enum([
18827
19355
  "unassigned",
@@ -20864,36 +21392,6 @@ Object.freeze({
20864
21392
  addonId: null,
20865
21393
  access: "view"
20866
21394
  },
20867
- "advancedNotifier.deleteRule": {
20868
- capName: "advanced-notifier",
20869
- capScope: "system",
20870
- addonId: null,
20871
- access: "delete"
20872
- },
20873
- "advancedNotifier.getHistory": {
20874
- capName: "advanced-notifier",
20875
- capScope: "system",
20876
- addonId: null,
20877
- access: "view"
20878
- },
20879
- "advancedNotifier.getRules": {
20880
- capName: "advanced-notifier",
20881
- capScope: "system",
20882
- addonId: null,
20883
- access: "view"
20884
- },
20885
- "advancedNotifier.testRule": {
20886
- capName: "advanced-notifier",
20887
- capScope: "system",
20888
- addonId: null,
20889
- access: "create"
20890
- },
20891
- "advancedNotifier.upsertRule": {
20892
- capName: "advanced-notifier",
20893
- capScope: "system",
20894
- addonId: null,
20895
- access: "create"
20896
- },
20897
21395
  "alarmPanel.arm": {
20898
21396
  capName: "alarm-panel",
20899
21397
  capScope: "device",
@@ -23198,6 +23696,60 @@ Object.freeze({
23198
23696
  addonId: null,
23199
23697
  access: "create"
23200
23698
  },
23699
+ "notificationRules.createRule": {
23700
+ capName: "notification-rules",
23701
+ capScope: "system",
23702
+ addonId: null,
23703
+ access: "create"
23704
+ },
23705
+ "notificationRules.deleteRule": {
23706
+ capName: "notification-rules",
23707
+ capScope: "system",
23708
+ addonId: null,
23709
+ access: "delete"
23710
+ },
23711
+ "notificationRules.getConditionCatalog": {
23712
+ capName: "notification-rules",
23713
+ capScope: "system",
23714
+ addonId: null,
23715
+ access: "view"
23716
+ },
23717
+ "notificationRules.getHistory": {
23718
+ capName: "notification-rules",
23719
+ capScope: "system",
23720
+ addonId: null,
23721
+ access: "view"
23722
+ },
23723
+ "notificationRules.getRule": {
23724
+ capName: "notification-rules",
23725
+ capScope: "system",
23726
+ addonId: null,
23727
+ access: "view"
23728
+ },
23729
+ "notificationRules.listRules": {
23730
+ capName: "notification-rules",
23731
+ capScope: "system",
23732
+ addonId: null,
23733
+ access: "view"
23734
+ },
23735
+ "notificationRules.setRuleEnabled": {
23736
+ capName: "notification-rules",
23737
+ capScope: "system",
23738
+ addonId: null,
23739
+ access: "create"
23740
+ },
23741
+ "notificationRules.testRule": {
23742
+ capName: "notification-rules",
23743
+ capScope: "system",
23744
+ addonId: null,
23745
+ access: "create"
23746
+ },
23747
+ "notificationRules.updateRule": {
23748
+ capName: "notification-rules",
23749
+ capScope: "system",
23750
+ addonId: null,
23751
+ access: "create"
23752
+ },
23201
23753
  "notifier.cancel": {
23202
23754
  capName: "notifier",
23203
23755
  capScope: "device",