@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.js CHANGED
@@ -43,7 +43,7 @@ let node_fs_promises = require("node:fs/promises");
43
43
  node_fs_promises = __toESM(node_fs_promises);
44
44
  let node_child_process = require("node:child_process");
45
45
  let node_net = require("node:net");
46
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
46
+ //#region ../types/dist/event-category-BLcNejAE.mjs
47
47
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
48
48
  EventCategory["SystemBoot"] = "system.boot";
49
49
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -193,9 +193,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
193
193
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
194
194
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
195
195
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
196
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
197
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
198
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
199
196
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
200
197
  * progress bar the client reconciles via `recordingExport.getExport`. */
201
198
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6860,7 +6857,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6860
6857
  patch: record(string(), unknown())
6861
6858
  }), object({ success: literal(true) });
6862
6859
  object({ deviceId: number() }), unknown().nullable();
6863
- /** Shorthand to define a method schema */
6864
6860
  function method(input, output, options) {
6865
6861
  return {
6866
6862
  input,
@@ -6868,6 +6864,7 @@ function method(input, output, options) {
6868
6864
  kind: options?.kind ?? "query",
6869
6865
  auth: options?.auth ?? "protected",
6870
6866
  ...options?.access !== void 0 ? { access: options.access } : {},
6867
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6871
6868
  timeoutMs: options?.timeoutMs
6872
6869
  };
6873
6870
  }
@@ -8251,6 +8248,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8251
8248
  /** The complete taxonomy dictionary, keyed by kind. */
8252
8249
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8253
8250
  /**
8251
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8252
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8253
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8254
+ * taxonomy surface (timeline, filters, event page).
8255
+ *
8256
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8257
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8258
+ * for the `classes` / `classesExclude` conditions.
8259
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8260
+ * the same class picker, grouped under an Audio header.
8261
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8262
+ * lock / …) for the `sensorKinds` device-event condition.
8263
+ *
8264
+ * Each entry carries `parentKind` so the client can group video subs under
8265
+ * their macro and sensor/control kinds under their category. This surface is
8266
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8267
+ * method, no codegen — so it ships train-free with an addon deploy.
8268
+ */
8269
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8270
+ var NcTaxonomyEntrySchema = object({
8271
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8272
+ kind: string(),
8273
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8274
+ label: string(),
8275
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8276
+ parentKind: string().nullable()
8277
+ });
8278
+ object({
8279
+ videoClasses: array(NcTaxonomyEntrySchema),
8280
+ audioKinds: array(NcTaxonomyEntrySchema),
8281
+ labels: array(NcTaxonomyEntrySchema)
8282
+ });
8283
+ function toEntry(kind, label, parentKind) {
8284
+ return {
8285
+ kind,
8286
+ label,
8287
+ parentKind
8288
+ };
8289
+ }
8290
+ /**
8291
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8292
+ * (macros before their subs), which the client relies on for stable grouping.
8293
+ */
8294
+ function buildNcTaxonomy() {
8295
+ const all = Object.values(EVENT_TAXONOMY);
8296
+ return {
8297
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8298
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8299
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8300
+ };
8301
+ }
8302
+ Object.freeze(buildNcTaxonomy());
8303
+ /**
8254
8304
  * Error types for the safe expression engine. Two distinct classes so callers
8255
8305
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8256
8306
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -10959,6 +11009,22 @@ var CameraMetricsSchema = object({
10959
11009
  ])
10960
11010
  });
10961
11011
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
11012
+ /**
11013
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
11014
+ * within the frame, so the executor can re-cut a leaf child ROI at native
11015
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
11016
+ */
11017
+ var NativeCropRefSchema = object({
11018
+ /** Handle keying the retained native surface (node-pinned to its owner). */
11019
+ handle: FrameHandleSchema,
11020
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
11021
+ cropFrameSpace: object({
11022
+ x: number(),
11023
+ y: number(),
11024
+ w: number(),
11025
+ h: number()
11026
+ })
11027
+ });
10962
11028
  var ModelFormatSchema$1 = _enum([
10963
11029
  "onnx",
10964
11030
  "coreml",
@@ -11234,7 +11300,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
11234
11300
  * Omitted ⇒ the runner's default device (current single-engine
11235
11301
  * behaviour). Selects WHICH device pool of the node runs the call.
11236
11302
  */
11237
- deviceKey: string().optional()
11303
+ deviceKey: string().optional(),
11304
+ /**
11305
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
11306
+ * when the parent crop was resolved from the frame's retained NATIVE
11307
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
11308
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
11309
+ * resolution from that surface — the SAME quality path faces already
11310
+ * had — instead of the downscaled parent tile. `handle` keys the native
11311
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
11312
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
11313
+ * the executor's crop-normalized child ROI back into frame-normalized
11314
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
11315
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
11316
+ * (today's behaviour on the fallback path).
11317
+ */
11318
+ nativeCropRef: NativeCropRefSchema.optional()
11238
11319
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
11239
11320
  engine: PipelineEngineChoiceSchema.optional(),
11240
11321
  steps: array(PipelineStepInputSchema).min(1),
@@ -11450,7 +11531,11 @@ var DetailResultSchema = object({
11450
11531
  bbox: NativeCropBboxSchema.optional(),
11451
11532
  embedding: string().optional(),
11452
11533
  label: string().optional(),
11453
- alignedCropJpeg: string().optional()
11534
+ alignedCropJpeg: string().optional(),
11535
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
11536
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
11537
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
11538
+ nativeFaceShortSidePx: number().optional()
11454
11539
  });
11455
11540
  /**
11456
11541
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -11464,6 +11549,12 @@ var motionCooldownMsField = {
11464
11549
  default: 3e4,
11465
11550
  step: 500
11466
11551
  };
11552
+ var maxSessionHoldMsField = {
11553
+ min: 0,
11554
+ max: 6e5,
11555
+ default: 12e4,
11556
+ step: 5e3
11557
+ };
11467
11558
  var motionFpsField = {
11468
11559
  min: 1,
11469
11560
  max: 30,
@@ -11611,6 +11702,19 @@ var RunnerCameraConfigSchema = object({
11611
11702
  "on-motion"
11612
11703
  ]).default("always-on"),
11613
11704
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
11705
+ /**
11706
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
11707
+ * detection session is active and ≥1 confirmed non-stationary track is
11708
+ * still live, the orchestrator keeps the session open past
11709
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
11710
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
11711
+ * ms since the session opened, after which it closes regardless. `0`
11712
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
11713
+ * runner itself — carried here so it shares the per-camera device-settings
11714
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
11715
+ * resolved `CameraDetectionConfig`.
11716
+ */
11717
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
11614
11718
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
11615
11719
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
11616
11720
  motionStreamId: string(),
@@ -11700,7 +11804,7 @@ var RunnerCameraConfigSchema = object({
11700
11804
  */
11701
11805
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
11702
11806
  });
11703
- 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;
11807
+ 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;
11704
11808
  /**
11705
11809
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
11706
11810
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -13554,94 +13658,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
13554
13658
  bundleUrl: string()
13555
13659
  });
13556
13660
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
13557
- var NotificationRuleConditionsSchema = object({
13558
- deviceIds: array(number()).readonly().optional(),
13559
- classNames: array(string()).readonly().optional(),
13560
- zoneIds: array(string()).readonly().optional(),
13561
- minConfidence: number().optional(),
13562
- source: _enum([
13563
- "pipeline",
13564
- "onboard",
13565
- "any"
13566
- ]).optional(),
13567
- schedule: object({
13568
- days: array(number()).readonly(),
13569
- startHour: number(),
13570
- endHour: number()
13571
- }).optional(),
13572
- cooldownSeconds: number().optional(),
13573
- minDwellSeconds: number().optional(),
13574
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
13575
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
13576
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
13577
- eventTypeTokens: array(string()).readonly().optional(),
13578
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
13579
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
13580
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
13581
- clipDescription: object({
13582
- text: string().min(1),
13583
- minSimilarity: number().min(0).max(1)
13584
- }).optional(),
13585
- /** Match events whose recognized-entity label (face identity name or plate
13586
- * vehicle name, propagated onto `event.data.label`) is one of these values.
13587
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
13588
- * vehicle/person> is seen". */
13589
- labels: array(string()).readonly().optional()
13590
- });
13591
- var NotificationRuleTemplateSchema = object({
13592
- title: string(),
13593
- body: string(),
13594
- imageMode: _enum([
13595
- "crop",
13596
- "annotated",
13597
- "full",
13598
- "none"
13599
- ])
13600
- });
13601
- var NotificationRuleSchema = object({
13602
- id: string(),
13603
- name: string(),
13604
- enabled: boolean(),
13605
- eventTypes: array(string()).readonly(),
13606
- conditions: NotificationRuleConditionsSchema,
13607
- outputs: array(string()).readonly(),
13608
- template: NotificationRuleTemplateSchema.optional(),
13609
- priority: _enum([
13610
- "low",
13611
- "normal",
13612
- "high",
13613
- "critical"
13614
- ])
13615
- });
13616
- var NotificationTestResultSchema = object({
13617
- ruleId: string(),
13618
- eventId: string(),
13619
- timestamp: number(),
13620
- wouldFire: boolean(),
13621
- reason: string().optional()
13622
- });
13623
- var NotificationHistoryEntrySchema = object({
13624
- id: string(),
13625
- ruleId: string(),
13626
- ruleName: string(),
13627
- eventId: string(),
13628
- timestamp: number(),
13629
- outputs: array(string()).readonly(),
13630
- success: boolean(),
13631
- error: string().optional(),
13632
- deviceId: number().optional()
13633
- });
13634
- var NotificationHistoryFilterSchema = object({
13635
- ruleId: string().optional(),
13636
- deviceId: number().optional(),
13637
- from: number().optional(),
13638
- to: number().optional(),
13639
- limit: number().optional()
13640
- });
13641
- 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({
13642
- ruleId: string(),
13643
- lookbackMinutes: number()
13644
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
13645
13661
  /**
13646
13662
  * Alerts capability — collection-based internal alert system.
13647
13663
  *
@@ -13828,89 +13844,6 @@ method(object({
13828
13844
  password: string()
13829
13845
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
13830
13846
  /**
13831
- * `login-method` — collection cap through which auth addons contribute
13832
- * their pre-auth login surfaces to the login page. This is the SINGLE,
13833
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
13834
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
13835
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
13836
- * procedure aggregates them for the unauthenticated login page.
13837
- *
13838
- * A contribution is a discriminated union on `kind`:
13839
- *
13840
- * - `redirect` — a declarative button. The login page renders a generic
13841
- * button that navigates to `startUrl` (an addon-owned HTTP route).
13842
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
13843
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
13844
- * login page needs NO change.
13845
- *
13846
- * - `widget` — a Module-Federation widget the login page mounts (via
13847
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
13848
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
13849
- * mechanism kept for future use; no shipped addon uses it on the login
13850
- * page (the passkey ceremony below runs natively in the shell instead).
13851
- *
13852
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
13853
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
13854
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
13855
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
13856
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
13857
- * fetching any remote code pre-auth. Contribution stays unconditional —
13858
- * enrollment state is never leaked pre-auth; visibility is a shell
13859
- * decision.
13860
- *
13861
- * Every contribution carries a `stage`:
13862
- * - `primary` — shown on the first credentials screen (OIDC /
13863
- * magic-link buttons; a future usernameless passkey).
13864
- * - `second-factor` — shown AFTER the password leg, gated on the
13865
- * returned `factors` (passkey-as-2FA today).
13866
- *
13867
- * `mount: skip` — the cap is read server-side by the core auth router
13868
- * (`registry.getCollection('login-method')`), never mounted as its own
13869
- * tRPC router.
13870
- */
13871
- /** When a login method renders in the two-phase login flow. */
13872
- var LoginStageEnum = _enum(["primary", "second-factor"]);
13873
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
13874
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
13875
- object({
13876
- kind: literal("redirect"),
13877
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
13878
- id: string(),
13879
- /** Operator-facing button label. */
13880
- label: string(),
13881
- /** lucide-react icon name. */
13882
- icon: string().optional(),
13883
- /** Addon-owned HTTP route the button navigates to (GET). */
13884
- startUrl: string(),
13885
- stage: LoginStageEnum
13886
- }),
13887
- object({
13888
- kind: literal("widget"),
13889
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
13890
- id: string(),
13891
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
13892
- addonId: string(),
13893
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
13894
- bundle: string(),
13895
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
13896
- remote: WidgetRemoteSchema,
13897
- stage: LoginStageEnum
13898
- }),
13899
- object({
13900
- kind: literal("passkey"),
13901
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
13902
- id: string(),
13903
- /** Operator-facing button label. */
13904
- label: string(),
13905
- stage: LoginStageEnum,
13906
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
13907
- rpId: string(),
13908
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
13909
- origin: string().nullable()
13910
- })
13911
- ]);
13912
- method(_void(), array(LoginMethodContributionSchema).readonly());
13913
- /**
13914
13847
  * Orchestrator-side destination metadata. The orchestrator computes
13915
13848
  * `id = <addonId>:<subId>` from its provider lookup so consumers
13916
13849
  * (admin UI, restore flow) see one canonical key.
@@ -15254,896 +15187,1467 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
15254
15187
  kind: "mutation",
15255
15188
  auth: "admin"
15256
15189
  });
15257
- var LogLevelSchema = _enum([
15258
- "debug",
15259
- "info",
15260
- "warn",
15261
- "error"
15190
+ /**
15191
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15192
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15193
+ * caps stay wire-compatible without a circular cap→cap import.
15194
+ *
15195
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
15196
+ * every transport tier structurally, and failed calls still write usage rows.
15197
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15198
+ */
15199
+ var LlmUsageSchema = object({
15200
+ inputTokens: number(),
15201
+ outputTokens: number()
15202
+ });
15203
+ var LlmErrorCodeSchema = _enum([
15204
+ "timeout",
15205
+ "rate-limited",
15206
+ "auth",
15207
+ "refusal",
15208
+ "bad-request",
15209
+ "unavailable",
15210
+ "no-profile",
15211
+ "budget-exceeded",
15212
+ "adapter-error"
15262
15213
  ]);
15263
- var LogEntrySchema = object({
15264
- timestamp: date(),
15265
- level: LogLevelSchema,
15266
- scope: array(string()),
15214
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15215
+ ok: literal(true),
15216
+ text: string(),
15217
+ model: string(),
15218
+ usage: LlmUsageSchema,
15219
+ truncated: boolean(),
15220
+ latencyMs: number()
15221
+ }), object({
15222
+ ok: literal(false),
15223
+ code: LlmErrorCodeSchema,
15267
15224
  message: string(),
15268
- meta: record(string(), unknown()).optional(),
15269
- tags: record(string(), string()).optional()
15225
+ retryAfterMs: number().optional()
15226
+ })]);
15227
+ /**
15228
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15229
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15230
+ * notification-output.cap.ts:27-31 precedents).
15231
+ */
15232
+ var LlmImageSchema = object({
15233
+ bytes: _instanceof(Uint8Array),
15234
+ mimeType: string()
15270
15235
  });
15271
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15272
- scope: array(string()).optional(),
15273
- level: LogLevelSchema.optional(),
15274
- since: date().optional(),
15275
- until: date().optional(),
15276
- limit: number().optional(),
15277
- tags: record(string(), string()).optional()
15278
- }), array(LogEntrySchema).readonly());
15279
- var CpuBreakdownSchema = object({
15280
- total: number(),
15281
- user: number(),
15282
- system: number(),
15283
- irq: number(),
15284
- nice: number(),
15285
- loadAvg: tuple([
15286
- number(),
15287
- number(),
15288
- number()
15289
- ]),
15290
- cores: number()
15236
+ var LlmGenerateBaseInputSchema = object({
15237
+ /** Collection routing (the notification-output posture). */
15238
+ addonId: string().optional(),
15239
+ /** Explicit profile; else the resolution chain (spec §3). */
15240
+ profileId: string().optional(),
15241
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15242
+ consumer: string(),
15243
+ system: string().optional(),
15244
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
15245
+ prompt: string(),
15246
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15247
+ jsonSchema: record(string(), unknown()).optional(),
15248
+ /** Per-call override of the profile default. */
15249
+ maxTokens: number().int().positive().optional(),
15250
+ temperature: number().optional()
15291
15251
  });
15292
- var MemoryInfoSchema = object({
15293
- percent: number(),
15294
- totalBytes: number(),
15295
- usedBytes: number(),
15296
- availableBytes: number(),
15297
- swapUsedBytes: number(),
15298
- swapTotalBytes: number()
15299
- });
15300
- var DiskIoSnapshotSchema = object({
15301
- readBytes: number(),
15302
- writeBytes: number(),
15303
- readOps: number(),
15304
- writeOps: number(),
15305
- timestampMs: number()
15306
- });
15307
- var NetworkIoSnapshotSchema = object({
15308
- rxBytes: number(),
15309
- txBytes: number(),
15310
- rxPackets: number(),
15311
- txPackets: number(),
15312
- rxErrors: number(),
15313
- txErrors: number(),
15314
- timestampMs: number()
15315
- });
15316
- var MetricsGpuInfoSchema = object({
15317
- utilization: number(),
15318
- model: string(),
15319
- memoryUsedBytes: number(),
15320
- memoryTotalBytes: number(),
15321
- temperature: number().nullable()
15322
- });
15323
- var ProcessResourceInfoSchema = object({
15324
- openFds: number(),
15325
- threadCount: number(),
15326
- activeHandles: number(),
15327
- activeRequests: number()
15328
- });
15329
- var PressureAvgsSchema = object({
15330
- avg10: number(),
15331
- avg60: number(),
15332
- avg300: number()
15333
- });
15334
- var PressureInfoSchema = object({
15335
- some: PressureAvgsSchema,
15336
- full: PressureAvgsSchema.nullable()
15337
- });
15338
- var SystemResourceSnapshotSchema = object({
15339
- cpu: CpuBreakdownSchema,
15340
- memory: MemoryInfoSchema,
15341
- gpu: MetricsGpuInfoSchema.nullable(),
15342
- network: NetworkIoSnapshotSchema,
15343
- disk: DiskIoSnapshotSchema,
15344
- pressure: object({
15345
- cpu: PressureInfoSchema.nullable(),
15346
- memory: PressureInfoSchema.nullable(),
15347
- io: PressureInfoSchema.nullable()
15252
+ /**
15253
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15254
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15255
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15256
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15257
+ * this only through the `llm` cap's methods.
15258
+ *
15259
+ * One running llama-server child per node in v1 (models are RAM-heavy).
15260
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15261
+ * watchdog — operator decision #3).
15262
+ */
15263
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
15264
+ object({
15265
+ kind: literal("catalog"),
15266
+ catalogId: string()
15348
15267
  }),
15349
- process: ProcessResourceInfoSchema,
15350
- cpuTemperature: number().nullable(),
15351
- timestampMs: number()
15352
- });
15353
- var DiskSpaceInfoSchema = object({
15354
- path: string(),
15355
- totalBytes: number(),
15356
- usedBytes: number(),
15357
- availableBytes: number(),
15358
- percent: number()
15359
- });
15360
- var PidResourceStatsSchema = object({
15361
- pid: number(),
15362
- cpu: number(),
15363
- memory: number(),
15364
- /**
15365
- * Private (anonymous) resident bytes — the per-process V8 heap + native
15366
- * allocations NOT shared with other processes (Linux RssAnon). This is the
15367
- * "real" per-runner cost; summing it across runners is meaningful, unlike
15368
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
15369
- * Undefined where /proc is unavailable (e.g. macOS).
15370
- */
15371
- privateBytes: number().optional(),
15372
- /**
15373
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15374
- * code shared copy-on-write across runners. Undefined on macOS.
15375
- */
15376
- sharedBytes: number().optional()
15268
+ object({
15269
+ kind: literal("url"),
15270
+ url: string(),
15271
+ sha256: string().optional()
15272
+ }),
15273
+ object({
15274
+ kind: literal("path"),
15275
+ path: string()
15276
+ })
15277
+ ]);
15278
+ var ManagedRuntimeConfigSchema = object({
15279
+ /** WHERE the runtime lives — hub or any agent. */
15280
+ nodeId: string(),
15281
+ /** Closed for v1; 'ollama' is a v2 candidate. */
15282
+ engine: _enum(["llama-cpp"]),
15283
+ model: ManagedModelRefSchema,
15284
+ contextSize: number().int().default(4096),
15285
+ /** 0 = CPU-only. */
15286
+ gpuLayers: number().int().default(0),
15287
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15288
+ threads: number().int().optional(),
15289
+ /** Concurrent slots. */
15290
+ parallel: number().int().default(1),
15291
+ /** Else lazy: first generate boots it. */
15292
+ autoStart: boolean().default(false),
15293
+ /** 0 = never; frees RAM after quiet periods. */
15294
+ idleStopMinutes: number().int().default(30)
15377
15295
  });
15378
- var AddonInstanceSchema = object({
15379
- addonId: string(),
15296
+ var LlmRuntimeStatusSchema = object({
15297
+ /** Status is ALWAYS node-qualified. */
15380
15298
  nodeId: string(),
15381
- role: _enum(["hub", "worker"]),
15382
- pid: number(),
15383
15299
  state: _enum([
15384
- "starting",
15385
- "running",
15386
- "stopping",
15387
15300
  "stopped",
15388
- "crashed"
15389
- ]),
15390
- uptimeSec: number()
15391
- });
15392
- var NodeProcessSchema = object({
15393
- pid: number(),
15394
- ppid: number(),
15395
- pgid: number(),
15396
- classification: _enum([
15397
- "root",
15398
- "managed",
15399
- "system",
15400
- "ghost"
15301
+ "downloading",
15302
+ "starting",
15303
+ "ready",
15304
+ "crashed",
15305
+ "failed"
15401
15306
  ]),
15402
- /** `$process` addon binding when `managed`, else null. */
15403
- addonId: string().nullable(),
15404
- /** Kernel-reported nodeId when the process is a known agent/worker. */
15405
- nodeId: string().nullable(),
15406
- /** Truncated command line. */
15407
- command: string(),
15408
- cpuPercent: number(),
15409
- memoryRssBytes: number(),
15410
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15411
- uptimeSec: number(),
15412
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15413
- orphaned: boolean()
15414
- });
15415
- var KillProcessInputSchema = object({
15416
- pid: number(),
15417
- /** Force = SIGKILL. Default is SIGTERM. */
15418
- force: boolean().optional()
15419
- });
15420
- var KillProcessResultSchema = object({
15421
- success: boolean(),
15422
- reason: string().optional(),
15423
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15424
- });
15425
- var DumpHeapSnapshotInputSchema = object({
15426
- /** The addon whose runner should dump a heap snapshot. */
15427
- addonId: string() });
15428
- var DumpHeapSnapshotResultSchema = object({
15429
- success: boolean(),
15430
- /** Path of the written .heapsnapshot inside the runner's container/host. */
15431
- path: string().optional(),
15432
- /** Process pid that was signalled. */
15433
15307
  pid: number().optional(),
15434
- reason: string().optional()
15435
- });
15436
- var SystemMetricsSchema = object({
15437
- cpuPercent: number(),
15438
- memoryPercent: number(),
15439
- memoryUsedMB: number(),
15440
- memoryTotalMB: number(),
15441
- diskPercent: number().optional(),
15442
- temperature: number().optional(),
15443
- gpuPercent: number().optional(),
15444
- gpuMemoryPercent: number().optional()
15445
- });
15446
- 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, {
15447
- kind: "mutation",
15448
- auth: "admin"
15449
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15450
- kind: "mutation",
15451
- auth: "admin"
15308
+ port: number().optional(),
15309
+ modelPath: string().optional(),
15310
+ modelId: string().optional(),
15311
+ downloadProgress: number().min(0).max(1).optional(),
15312
+ lastError: string().optional(),
15313
+ crashesInWindow: number(),
15314
+ /** Child RSS (sampled best-effort). */
15315
+ memoryBytes: number().optional(),
15316
+ vramBytes: number().optional()
15452
15317
  });
15453
- method(object({
15454
- sourceUrl: string(),
15455
- metadata: ModelConvertMetadataSchema,
15456
- targets: array(ConvertTargetSchema).min(1).readonly(),
15457
- calibrationRef: string().optional(),
15458
- sessionId: string().optional()
15459
- }), ConvertResultSchema, {
15460
- kind: "mutation",
15461
- auth: "admin",
15462
- timeoutMs: 6e5
15318
+ var LlmNodeModelSchema = object({
15319
+ file: string(),
15320
+ sizeBytes: number(),
15321
+ catalogId: string().optional(),
15322
+ installedAt: number().optional()
15463
15323
  });
15464
- method(object({
15324
+ var LlmRuntimeDiskUsageSchema = object({
15465
15325
  nodeId: string(),
15466
- modelId: string(),
15467
- format: _enum(MODEL_FORMATS),
15468
- entry: ModelCatalogEntrySchema
15469
- }), object({
15470
- ok: boolean(),
15471
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
15472
- sha256: string(),
15473
- bytes: number(),
15474
- /** The target node's modelsDir the artifact landed in. */
15475
- path: string()
15476
- }), {
15477
- kind: "mutation",
15478
- auth: "admin"
15326
+ modelsBytes: number(),
15327
+ freeBytes: number().optional()
15479
15328
  });
15329
+ var llmRuntimeCapability = {
15330
+ name: "llm-runtime",
15331
+ scope: "system",
15332
+ mode: "singleton",
15333
+ internal: true,
15334
+ methods: {
15335
+ complete: method(LlmGenerateBaseInputSchema.extend({
15336
+ images: array(LlmImageSchema).optional(),
15337
+ runtime: ManagedRuntimeConfigSchema,
15338
+ /** The managed profile's timeout, threaded by the hub provider. */
15339
+ timeoutMs: number().int().positive().optional()
15340
+ }), LlmGenerateResultSchema, { kind: "mutation" }),
15341
+ ensureStarted: method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15342
+ kind: "mutation",
15343
+ auth: "admin"
15344
+ }),
15345
+ stop: method(object({}), _void(), {
15346
+ kind: "mutation",
15347
+ auth: "admin"
15348
+ }),
15349
+ status: method(object({}), LlmRuntimeStatusSchema),
15350
+ installModel: method(object({ model: ManagedModelRefSchema }), _void(), {
15351
+ kind: "mutation",
15352
+ auth: "admin"
15353
+ }),
15354
+ deleteModel: method(object({ file: string() }), _void(), {
15355
+ kind: "mutation",
15356
+ auth: "admin"
15357
+ }),
15358
+ listLocalModels: method(object({}), array(LlmNodeModelSchema)),
15359
+ getDiskUsage: method(object({}), LlmRuntimeDiskUsageSchema)
15360
+ }
15361
+ };
15480
15362
  /**
15481
- * `mqtt-broker` — broker-registry cap.
15482
- *
15483
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15484
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15485
- * and (b) the connection details a consumer addon needs to spin up
15486
- * its OWN `mqtt.js` client.
15487
- *
15488
- * Why: pub/sub routing over the system event-bus loses fidelity
15489
- * (callback shape, QoS guarantees, will/retain semantics) and adds
15490
- * refcount bookkeeping that addons would rather own themselves. The
15491
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
15492
- * features anyway — give it the connection config, get out of the way.
15493
- *
15494
- * Consumer flow:
15495
- * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
15496
- * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
15497
- * client.subscribe('zigbee2mqtt/+')
15498
- *
15499
- * Collection mode: multiple brokers (e.g. one local mosquitto + one
15500
- * cloud bridge). The "embedded" entry (when present) is just another
15501
- * broker in the registry — its lifecycle is owned by the addon that
15502
- * spawned it.
15503
- */
15504
- var BrokerKindSchema = _enum(["external", "embedded"]);
15505
- /**
15506
- * Broker live-probe status.
15363
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15364
+ * methods concat-fan across providers; single-row methods route to ONE
15365
+ * provider by the `addonId` in the call input (the notification-output
15366
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15367
+ * (hub-placed); the cap stays open for future providers.
15507
15368
  *
15508
- * - `connected` last probe completed a clean CONNACK
15509
- * - `disconnected` — no probe has run yet (cold cache)
15510
- * - `auth-failed` CONNACK refused with auth error (RC 4 / 5)
15511
- * - `unreachable` — TCP connect timed out / refused
15512
- * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
15369
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15370
+ * `apiKey` is a password field providers REDACT it on read and merge on
15371
+ * write; a stored key NEVER round-trips to a client.
15513
15372
  */
15514
- var BrokerStatusSchema$1 = _enum([
15515
- "connected",
15516
- "disconnected",
15517
- "auth-failed",
15518
- "unreachable",
15519
- "tls-error"
15373
+ var LlmProfileKindSchema = _enum([
15374
+ "openai-compatible",
15375
+ "openai",
15376
+ "anthropic",
15377
+ "google",
15378
+ "managed-local"
15520
15379
  ]);
15521
- var BrokerInfoSchema = object({
15380
+ var LlmProfileSchema = object({
15522
15381
  id: string(),
15523
15382
  name: string(),
15524
- url: string(),
15525
- kind: BrokerKindSchema,
15526
- status: BrokerStatusSchema$1,
15527
- latencyMs: number().nullable(),
15528
- error: string().optional(),
15529
- /** Embedded brokers only: number of MQTT clients currently connected. */
15530
- connectedClients: number().int().nonnegative().optional(),
15531
- /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
15532
- lastCheckedAt: number().optional()
15383
+ kind: LlmProfileKindSchema,
15384
+ /** Stamped by the provider — keeps the fanned catalog routable. */
15385
+ addonId: string(),
15386
+ enabled: boolean(),
15387
+ /** Vendor model id, or the managed runtime's loaded model. */
15388
+ model: string(),
15389
+ /** Required for openai-compatible; override for cloud kinds. */
15390
+ baseUrl: string().optional(),
15391
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
15392
+ apiKey: string().optional(),
15393
+ supportsVision: boolean(),
15394
+ temperature: number().min(0).max(2).optional(),
15395
+ maxTokens: number().int().positive().optional(),
15396
+ timeoutMs: number().int().positive().default(6e4),
15397
+ extraHeaders: record(string(), string()).optional(),
15398
+ /** kind === 'managed-local' only (spec §4). */
15399
+ runtime: ManagedRuntimeConfigSchema.optional()
15533
15400
  });
15534
- /**
15535
- * Connection details — what a consumer needs to call
15536
- * `mqtt.connect(url, options)`. We split URL + credentials so the
15537
- * consumer can pass them as `mqtt.connect(url, { username, password })`
15538
- * instead of stuffing creds into the URL (which leaks them into logs).
15539
- */
15540
- var BrokerConnectionDetailsSchema = object({
15541
- url: string(),
15542
- username: string().optional(),
15543
- password: string().optional(),
15544
- /**
15545
- * Suggested prefix for `clientId`. Each consumer should suffix this
15546
- * with its own discriminator (addon id, instance id) so reconnects
15547
- * don't kick each other off (MQTT spec: clientId must be unique per
15548
- * broker).
15549
- */
15550
- clientIdPrefix: string().optional()
15401
+ /** ConfigUISchema tree passed through untyped on the wire (the
15402
+ * notification-output `ConfigSchemaPassthrough` precedent at
15403
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15404
+ var ConfigSchemaPassthrough$1 = unknown();
15405
+ var LlmProfileKindDescriptorSchema = object({
15406
+ kind: LlmProfileKindSchema,
15407
+ label: string(),
15408
+ icon: string(),
15409
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
15410
+ addonId: string(),
15411
+ configSchema: ConfigSchemaPassthrough$1
15551
15412
  });
15552
- var AddBrokerInputSchema = object({
15553
- name: string().min(1),
15554
- url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
15555
- username: string().optional(),
15556
- password: string().optional(),
15557
- clientIdPrefix: string().optional()
15413
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15414
+ var LlmDefaultSchema = object({
15415
+ selector: LlmDefaultSelectorSchema,
15416
+ profileId: string()
15558
15417
  });
15559
- var AddBrokerResultSchema = object({ id: string() });
15560
- var IdInputSchema = object({ id: string() });
15561
- var TestResultSchema$1 = discriminatedUnion("ok", [object({
15562
- ok: literal(true),
15563
- latencyMs: number()
15564
- }), object({
15565
- ok: literal(false),
15566
- error: string()
15567
- })]);
15568
- var StartEmbeddedInputSchema = object({
15569
- port: number().int().min(1).max(65535).default(1883),
15570
- /** Allow anonymous connect (no username/password). Default: false. */
15571
- allowAnonymous: boolean().default(false),
15572
- /** Optional shared username/password for clients. */
15573
- username: string().optional(),
15574
- password: string().optional()
15418
+ /** Server-side rollup row getUsage never dumps raw call rows (spec §6). */
15419
+ var LlmUsageRollupSchema = object({
15420
+ day: string(),
15421
+ consumer: string(),
15422
+ profileId: string(),
15423
+ calls: number(),
15424
+ okCalls: number(),
15425
+ errorCalls: number(),
15426
+ inputTokens: number(),
15427
+ outputTokens: number(),
15428
+ avgLatencyMs: number()
15575
15429
  });
15576
- var StartEmbeddedResultSchema = object({
15430
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15431
+ var ManagedModelCatalogEntrySchema = object({
15577
15432
  id: string(),
15578
- url: string()
15579
- });
15580
- var StatusSchema = object({
15581
- brokerCount: number(),
15582
- embeddedRunning: boolean()
15583
- });
15584
- 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);
15585
- var NetworkEndpointSchema = object({
15433
+ label: string(),
15434
+ family: string(),
15435
+ purpose: _enum(["text", "vision"]),
15586
15436
  url: string(),
15587
- hostname: string(),
15588
- port: number(),
15589
- protocol: _enum(["http", "https"])
15437
+ sha256: string(),
15438
+ sizeBytes: number(),
15439
+ quantization: string(),
15440
+ /** Load-time guidance shown in the picker. */
15441
+ minRamBytes: number(),
15442
+ contextSizeDefault: number().int(),
15443
+ /** Vision models: companion projector file. */
15444
+ mmprojUrl: string().optional()
15590
15445
  });
15591
- var NetworkAccessStatusSchema = object({
15592
- connected: boolean(),
15593
- endpoint: NetworkEndpointSchema.nullable(),
15446
+ var LlmRuntimeNodeSchema = object({
15447
+ nodeId: string(),
15448
+ reachable: boolean(),
15449
+ status: LlmRuntimeStatusSchema.optional(),
15450
+ disk: LlmRuntimeDiskUsageSchema.optional(),
15594
15451
  error: string().optional()
15595
15452
  });
15596
- /**
15597
- * Optional, richer endpoint shape returned by providers that expose
15598
- * MORE than one ingress concurrently (Tailscale Ingress with mixed
15599
- * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
15600
- * the originating provider config (mode + sourcePort) so the
15601
- * orchestrator UI can label rows distinctly. Providers that expose only
15602
- * one endpoint just omit `listEndpoints` from their provider impl.
15603
- */
15604
- var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
15605
- /**
15606
- * Stable id within the provider — typically `<mode>-<sourcePort>` so
15607
- * the orchestrator can dedupe across `listEndpoints` polls.
15608
- */
15609
- id: string(),
15610
- /** Operator-facing label (mirrors `MeshEndpoint.label`). */
15611
- label: string(),
15612
- /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
15613
- mode: string().optional(),
15614
- /** Originating local port the ingress fronts (informational). */
15615
- sourcePort: number().optional()
15453
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
15454
+ var ProfileRefInputSchema = object({
15455
+ addonId: string(),
15456
+ profileId: string()
15616
15457
  });
15617
- method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
15618
- /**
15619
- * notification-output — canonical, capability-gated notification delivery.
15620
- *
15621
- * Apprise-derived model (see
15622
- * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
15623
- * callers emit ONE canonical `Notification`; each provider declares a
15624
- * per-kind capability descriptor (`TargetKind`), and the pure degrade
15625
- * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
15626
- * message to what the kind supports — callers never special-case a service.
15627
- *
15628
- * DESIGN DECISIONS (locked):
15629
- * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
15630
- * `setTargetEnabled`), each provider persisting via the `settings-store`
15631
- * cap. Rationale: the admin UI needs one uniform surface across the
15632
- * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
15633
- * alternative would fork the UI per addon and cannot host the
15634
- * discovery→adopt flow.
15635
- * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
15636
- * the generated cap-mount auto-`concatCollection`-fans them across every
15637
- * registered provider (notifiers addon + HA addon) so one catalog is
15638
- * routable. `send` / `testTarget` / CRUD route to ONE provider by the
15639
- * `addonId` the generated collection router extracts from the call input.
15640
- * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
15641
- * transformer) + UDS MsgPack both round-trip typed arrays — already used by
15642
- * `storage` / `storage-provider` / `recording` caps over the same path. No
15643
- * base64 fallback needed.
15644
- *
15645
- * TODO (deferred, closed-set change — separate decision): add
15646
- * `providerKind: 'notify'` so notification providers surface on the unified
15647
- * admin "Integrations" page.
15648
- */
15649
- /**
15650
- * Zentik-derived typed-media enum — the superset across every kind. Each
15651
- * adapter picks what it supports and the degrade engine filters the rest.
15652
- */
15653
- var AttachmentMediaTypeSchema = _enum([
15654
- "image",
15655
- "video",
15656
- "gif",
15657
- "audio",
15658
- "icon"
15458
+ var llmCapability = {
15459
+ name: "llm",
15460
+ scope: "system",
15461
+ mode: "collection",
15462
+ internal: false,
15463
+ providerKind: "ai",
15464
+ /** `nodeId` inputs below are DATA (the hub provider pins itself), never routing. */
15465
+ nodeIdMode: "data",
15466
+ methods: {
15467
+ generate: method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }),
15468
+ generateVision: method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }),
15469
+ listProfileKinds: method(object({}), array(LlmProfileKindDescriptorSchema)),
15470
+ listProfiles: method(object({}), array(LlmProfileSchema)),
15471
+ upsertProfile: method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
15472
+ kind: "mutation",
15473
+ auth: "admin"
15474
+ }),
15475
+ deleteProfile: method(ProfileRefInputSchema, _void(), {
15476
+ kind: "mutation",
15477
+ auth: "admin"
15478
+ }),
15479
+ testProfile: method(ProfileRefInputSchema, LlmGenerateResultSchema, {
15480
+ kind: "mutation",
15481
+ auth: "admin"
15482
+ }),
15483
+ /** Live vendor enumeration (GET /models etc.). */
15484
+ listModels: method(ProfileRefInputSchema, array(string())),
15485
+ getDefaults: method(object({}), array(LlmDefaultSchema)),
15486
+ setDefault: method(object({
15487
+ selector: LlmDefaultSelectorSchema,
15488
+ profileId: string().nullable()
15489
+ }), _void(), {
15490
+ kind: "mutation",
15491
+ auth: "admin"
15492
+ }),
15493
+ getUsage: method(object({
15494
+ since: number().optional(),
15495
+ until: number().optional(),
15496
+ consumer: string().optional(),
15497
+ profileId: string().optional()
15498
+ }), array(LlmUsageRollupSchema)),
15499
+ listModelCatalog: method(object({}), array(ManagedModelCatalogEntrySchema)),
15500
+ listRuntimeNodes: method(object({}), array(LlmRuntimeNodeSchema)),
15501
+ listNodeModels: method(object({ nodeId: string() }), array(LlmNodeModelSchema)),
15502
+ installModel: method(object({
15503
+ nodeId: string(),
15504
+ model: ManagedModelRefSchema
15505
+ }), _void(), {
15506
+ kind: "mutation",
15507
+ auth: "admin"
15508
+ }),
15509
+ deleteModel: method(object({
15510
+ nodeId: string(),
15511
+ file: string()
15512
+ }), _void(), {
15513
+ kind: "mutation",
15514
+ auth: "admin"
15515
+ }),
15516
+ getRuntimeStatus: method(ProfileRefInputSchema, LlmRuntimeStatusSchema),
15517
+ startRuntime: method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
15518
+ kind: "mutation",
15519
+ auth: "admin"
15520
+ }),
15521
+ stopRuntime: method(ProfileRefInputSchema, _void(), {
15522
+ kind: "mutation",
15523
+ auth: "admin"
15524
+ })
15525
+ }
15526
+ };
15527
+ var LogLevelSchema = _enum([
15528
+ "debug",
15529
+ "info",
15530
+ "warn",
15531
+ "error"
15659
15532
  ]);
15533
+ var LogEntrySchema = object({
15534
+ timestamp: date(),
15535
+ level: LogLevelSchema,
15536
+ scope: array(string()),
15537
+ message: string(),
15538
+ meta: record(string(), unknown()).optional(),
15539
+ tags: record(string(), string()).optional()
15540
+ });
15541
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15542
+ scope: array(string()).optional(),
15543
+ level: LogLevelSchema.optional(),
15544
+ since: date().optional(),
15545
+ until: date().optional(),
15546
+ limit: number().optional(),
15547
+ tags: record(string(), string()).optional()
15548
+ }), array(LogEntrySchema).readonly());
15660
15549
  /**
15661
- * A single attachment. Exactly one of `url` (remote source, most adapters
15662
- * prefer this) or `bytes` (inline source; required for Pushover-style
15663
- * bytes-only kinds) MUST be present — the degrade engine expresses a
15664
- * url→bytes fetch as a `needsFetch` directive the adapter executes.
15550
+ * `login-method` collection cap through which auth addons contribute
15551
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
15552
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
15553
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
15554
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
15555
+ * procedure aggregates them for the unauthenticated login page.
15556
+ *
15557
+ * A contribution is a discriminated union on `kind`:
15558
+ *
15559
+ * - `redirect` — a declarative button. The login page renders a generic
15560
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
15561
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
15562
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
15563
+ * login page needs NO change.
15564
+ *
15565
+ * - `widget` — a Module-Federation widget the login page mounts (via
15566
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
15567
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
15568
+ * mechanism kept for future use; no shipped addon uses it on the login
15569
+ * page (the passkey ceremony below runs natively in the shell instead).
15570
+ *
15571
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
15572
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
15573
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
15574
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
15575
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
15576
+ * fetching any remote code pre-auth. Contribution stays unconditional —
15577
+ * enrollment state is never leaked pre-auth; visibility is a shell
15578
+ * decision.
15579
+ *
15580
+ * Every contribution carries a `stage`:
15581
+ * - `primary` — shown on the first credentials screen (OIDC /
15582
+ * magic-link buttons; a future usernameless passkey).
15583
+ * - `second-factor` — shown AFTER the password leg, gated on the
15584
+ * returned `factors` (passkey-as-2FA today).
15585
+ *
15586
+ * `mount: skip` — the cap is read server-side by the core auth router
15587
+ * (`registry.getCollection('login-method')`), never mounted as its own
15588
+ * tRPC router.
15665
15589
  */
15666
- var AttachmentSchema = object({
15667
- mediaType: AttachmentMediaTypeSchema,
15668
- url: string().optional(),
15669
- bytes: _instanceof(Uint8Array).optional(),
15670
- mime: string().optional(),
15671
- name: string().optional()
15672
- }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
15673
- var NotificationFormatSchema = _enum([
15674
- "text",
15675
- "markdown",
15676
- "html"
15590
+ /** When a login method renders in the two-phase login flow. */
15591
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
15592
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
15593
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
15594
+ object({
15595
+ kind: literal("redirect"),
15596
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
15597
+ id: string(),
15598
+ /** Operator-facing button label. */
15599
+ label: string(),
15600
+ /** lucide-react icon name. */
15601
+ icon: string().optional(),
15602
+ /** Addon-owned HTTP route the button navigates to (GET). */
15603
+ startUrl: string(),
15604
+ stage: LoginStageEnum
15605
+ }),
15606
+ object({
15607
+ kind: literal("widget"),
15608
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
15609
+ id: string(),
15610
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
15611
+ addonId: string(),
15612
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
15613
+ bundle: string(),
15614
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
15615
+ remote: WidgetRemoteSchema,
15616
+ stage: LoginStageEnum
15617
+ }),
15618
+ object({
15619
+ kind: literal("passkey"),
15620
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
15621
+ id: string(),
15622
+ /** Operator-facing button label. */
15623
+ label: string(),
15624
+ stage: LoginStageEnum,
15625
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
15626
+ rpId: string(),
15627
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
15628
+ origin: string().nullable()
15629
+ })
15677
15630
  ]);
15678
- /** A single tap-through action button. */
15679
- var NotificationActionSchema = object({
15680
- id: string(),
15681
- label: string(),
15682
- url: string().optional()
15631
+ method(_void(), array(LoginMethodContributionSchema).readonly());
15632
+ var CpuBreakdownSchema = object({
15633
+ total: number(),
15634
+ user: number(),
15635
+ system: number(),
15636
+ irq: number(),
15637
+ nice: number(),
15638
+ loadAvg: tuple([
15639
+ number(),
15640
+ number(),
15641
+ number()
15642
+ ]),
15643
+ cores: number()
15683
15644
  });
15684
- /**
15685
- * The canonical notification. `body` is the only hard field (Apprise model).
15686
- * `priority` is a 5-level ORDINAL (1=lowest … 3=normal(default) … 5=urgent),
15687
- * NOT a fixed severity enum — each kind declares its own `caps.levels` and
15688
- * the adapter maps this ordinal onto its native level. `level?` is an
15689
- * optional kind-native level id (`emergency`, `silent`, …) that overrides
15690
- * `priority` for that one target.
15691
- */
15692
- var NotificationSchema = object({
15693
- body: string(),
15694
- title: string().optional(),
15695
- format: NotificationFormatSchema.default("text"),
15696
- priority: number().int().min(1).max(5).default(3),
15697
- level: string().optional(),
15698
- attachments: array(AttachmentSchema).optional(),
15699
- clickUrl: string().optional(),
15700
- actions: array(NotificationActionSchema).optional(),
15701
- sound: string().optional(),
15702
- ttl: number().optional(),
15703
- tag: string().optional(),
15704
- deviceId: number().optional(),
15705
- eventId: string().optional(),
15706
- metadata: record(string(), unknown()).optional()
15645
+ var MemoryInfoSchema = object({
15646
+ percent: number(),
15647
+ totalBytes: number(),
15648
+ usedBytes: number(),
15649
+ availableBytes: number(),
15650
+ swapUsedBytes: number(),
15651
+ swapTotalBytes: number()
15707
15652
  });
15708
- /** One declared native severity/priority level for a kind. */
15709
- var TargetKindLevelSchema = object({
15710
- id: string(),
15711
- label: string(),
15712
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
15713
- ordinal: number().int().min(1).max(5).nullable(),
15714
- flags: object({
15715
- critical: boolean().optional(),
15716
- silent: boolean().optional(),
15717
- noPush: boolean().optional()
15718
- }).optional(),
15719
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
15720
- requires: array(string()).optional(),
15721
- description: string().optional()
15653
+ var DiskIoSnapshotSchema = object({
15654
+ readBytes: number(),
15655
+ writeBytes: number(),
15656
+ readOps: number(),
15657
+ writeOps: number(),
15658
+ timestampMs: number()
15722
15659
  });
15723
- /** The full capability block consulted before dispatch. */
15724
- var TargetKindCapsSchema = object({
15725
- attachments: object({
15726
- mediaTypes: array(AttachmentMediaTypeSchema),
15727
- mode: _enum([
15728
- "url",
15729
- "bytes",
15730
- "both"
15731
- ]),
15732
- max: number().int().nonnegative(),
15733
- maxBytes: number().int().positive().optional()
15660
+ var NetworkIoSnapshotSchema = object({
15661
+ rxBytes: number(),
15662
+ txBytes: number(),
15663
+ rxPackets: number(),
15664
+ txPackets: number(),
15665
+ rxErrors: number(),
15666
+ txErrors: number(),
15667
+ timestampMs: number()
15668
+ });
15669
+ var MetricsGpuInfoSchema = object({
15670
+ utilization: number(),
15671
+ model: string(),
15672
+ memoryUsedBytes: number(),
15673
+ memoryTotalBytes: number(),
15674
+ temperature: number().nullable()
15675
+ });
15676
+ var ProcessResourceInfoSchema = object({
15677
+ openFds: number(),
15678
+ threadCount: number(),
15679
+ activeHandles: number(),
15680
+ activeRequests: number()
15681
+ });
15682
+ var PressureAvgsSchema = object({
15683
+ avg10: number(),
15684
+ avg60: number(),
15685
+ avg300: number()
15686
+ });
15687
+ var PressureInfoSchema = object({
15688
+ some: PressureAvgsSchema,
15689
+ full: PressureAvgsSchema.nullable()
15690
+ });
15691
+ var SystemResourceSnapshotSchema = object({
15692
+ cpu: CpuBreakdownSchema,
15693
+ memory: MemoryInfoSchema,
15694
+ gpu: MetricsGpuInfoSchema.nullable(),
15695
+ network: NetworkIoSnapshotSchema,
15696
+ disk: DiskIoSnapshotSchema,
15697
+ pressure: object({
15698
+ cpu: PressureInfoSchema.nullable(),
15699
+ memory: PressureInfoSchema.nullable(),
15700
+ io: PressureInfoSchema.nullable()
15734
15701
  }),
15735
- /** Max action buttons (0 = none). */
15736
- actions: number().int().nonnegative(),
15737
- levels: array(TargetKindLevelSchema),
15738
- format: array(NotificationFormatSchema),
15739
- clickUrl: boolean(),
15740
- sound: boolean(),
15741
- ttl: boolean(),
15742
- bodyMaxLen: number().int().positive()
15702
+ process: ProcessResourceInfoSchema,
15703
+ cpuTemperature: number().nullable(),
15704
+ timestampMs: number()
15705
+ });
15706
+ var DiskSpaceInfoSchema = object({
15707
+ path: string(),
15708
+ totalBytes: number(),
15709
+ usedBytes: number(),
15710
+ availableBytes: number(),
15711
+ percent: number()
15712
+ });
15713
+ var PidResourceStatsSchema = object({
15714
+ pid: number(),
15715
+ cpu: number(),
15716
+ memory: number(),
15717
+ /**
15718
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
15719
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
15720
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
15721
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
15722
+ * Undefined where /proc is unavailable (e.g. macOS).
15723
+ */
15724
+ privateBytes: number().optional(),
15725
+ /**
15726
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15727
+ * code shared copy-on-write across runners. Undefined on macOS.
15728
+ */
15729
+ sharedBytes: number().optional()
15730
+ });
15731
+ var AddonInstanceSchema = object({
15732
+ addonId: string(),
15733
+ nodeId: string(),
15734
+ role: _enum(["hub", "worker"]),
15735
+ pid: number(),
15736
+ state: _enum([
15737
+ "starting",
15738
+ "running",
15739
+ "stopping",
15740
+ "stopped",
15741
+ "crashed"
15742
+ ]),
15743
+ uptimeSec: number()
15744
+ });
15745
+ var NodeProcessSchema = object({
15746
+ pid: number(),
15747
+ ppid: number(),
15748
+ pgid: number(),
15749
+ classification: _enum([
15750
+ "root",
15751
+ "managed",
15752
+ "system",
15753
+ "ghost"
15754
+ ]),
15755
+ /** `$process` addon binding when `managed`, else null. */
15756
+ addonId: string().nullable(),
15757
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
15758
+ nodeId: string().nullable(),
15759
+ /** Truncated command line. */
15760
+ command: string(),
15761
+ cpuPercent: number(),
15762
+ memoryRssBytes: number(),
15763
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15764
+ uptimeSec: number(),
15765
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15766
+ orphaned: boolean()
15767
+ });
15768
+ var KillProcessInputSchema = object({
15769
+ pid: number(),
15770
+ /** Force = SIGKILL. Default is SIGTERM. */
15771
+ force: boolean().optional()
15772
+ });
15773
+ var KillProcessResultSchema = object({
15774
+ success: boolean(),
15775
+ reason: string().optional(),
15776
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15777
+ });
15778
+ var DumpHeapSnapshotInputSchema = object({
15779
+ /** The addon whose runner should dump a heap snapshot. */
15780
+ addonId: string() });
15781
+ var DumpHeapSnapshotResultSchema = object({
15782
+ success: boolean(),
15783
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
15784
+ path: string().optional(),
15785
+ /** Process pid that was signalled. */
15786
+ pid: number().optional(),
15787
+ reason: string().optional()
15788
+ });
15789
+ var SystemMetricsSchema = object({
15790
+ cpuPercent: number(),
15791
+ memoryPercent: number(),
15792
+ memoryUsedMB: number(),
15793
+ memoryTotalMB: number(),
15794
+ diskPercent: number().optional(),
15795
+ temperature: number().optional(),
15796
+ gpuPercent: number().optional(),
15797
+ gpuMemoryPercent: number().optional()
15798
+ });
15799
+ 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, {
15800
+ kind: "mutation",
15801
+ auth: "admin"
15802
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15803
+ kind: "mutation",
15804
+ auth: "admin"
15805
+ });
15806
+ method(object({
15807
+ sourceUrl: string(),
15808
+ metadata: ModelConvertMetadataSchema,
15809
+ targets: array(ConvertTargetSchema).min(1).readonly(),
15810
+ calibrationRef: string().optional(),
15811
+ sessionId: string().optional()
15812
+ }), ConvertResultSchema, {
15813
+ kind: "mutation",
15814
+ auth: "admin",
15815
+ timeoutMs: 6e5
15816
+ });
15817
+ method(object({
15818
+ nodeId: string(),
15819
+ modelId: string(),
15820
+ format: _enum(MODEL_FORMATS),
15821
+ entry: ModelCatalogEntrySchema
15822
+ }), object({
15823
+ ok: boolean(),
15824
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
15825
+ sha256: string(),
15826
+ bytes: number(),
15827
+ /** The target node's modelsDir the artifact landed in. */
15828
+ path: string()
15829
+ }), {
15830
+ kind: "mutation",
15831
+ auth: "admin"
15743
15832
  });
15744
15833
  /**
15745
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
15746
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
15747
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
15748
- * the union is large and not meant for runtime validation here; the exported
15749
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
15834
+ * `mqtt-broker` broker-registry cap.
15835
+ *
15836
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15837
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15838
+ * and (b) the connection details a consumer addon needs to spin up
15839
+ * its OWN `mqtt.js` client.
15840
+ *
15841
+ * Why: pub/sub routing over the system event-bus loses fidelity
15842
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
15843
+ * refcount bookkeeping that addons would rather own themselves. The
15844
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
15845
+ * features anyway — give it the connection config, get out of the way.
15846
+ *
15847
+ * Consumer flow:
15848
+ * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
15849
+ * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
15850
+ * client.subscribe('zigbee2mqtt/+')
15851
+ *
15852
+ * Collection mode: multiple brokers (e.g. one local mosquitto + one
15853
+ * cloud bridge). The "embedded" entry (when present) is just another
15854
+ * broker in the registry — its lifecycle is owned by the addon that
15855
+ * spawned it.
15750
15856
  */
15751
- var ConfigSchemaPassthrough$1 = unknown();
15752
- var TargetKindSchema = object({
15753
- kind: string(),
15754
- label: string(),
15755
- icon: string(),
15756
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
15757
- addonId: string(),
15758
- configSchema: ConfigSchemaPassthrough$1,
15759
- supportsDiscovery: boolean(),
15760
- caps: TargetKindCapsSchema
15761
- });
15857
+ var BrokerKindSchema = _enum(["external", "embedded"]);
15762
15858
  /**
15763
- * A persisted target. `config` holds secrets; providers REDACT secret fields
15764
- * (return a presence marker only) when serving `listTargets` — never
15765
- * round-trip a stored secret to the UI.
15859
+ * Broker live-probe status.
15860
+ *
15861
+ * - `connected` last probe completed a clean CONNACK
15862
+ * - `disconnected` — no probe has run yet (cold cache)
15863
+ * - `auth-failed` — CONNACK refused with auth error (RC 4 / 5)
15864
+ * - `unreachable` — TCP connect timed out / refused
15865
+ * - `tls-error` — TLS handshake failed (cert / SNI / cipher)
15766
15866
  */
15767
- var TargetSchema = object({
15867
+ var BrokerStatusSchema$1 = _enum([
15868
+ "connected",
15869
+ "disconnected",
15870
+ "auth-failed",
15871
+ "unreachable",
15872
+ "tls-error"
15873
+ ]);
15874
+ var BrokerInfoSchema = object({
15768
15875
  id: string(),
15769
15876
  name: string(),
15770
- kind: string(),
15771
- addonId: string(),
15772
- enabled: boolean(),
15773
- config: record(string(), unknown())
15774
- });
15775
- /** A discovery-surfaced candidate (config is partial + non-secret). */
15776
- var DiscoveredTargetSchema = object({
15777
- kind: string(),
15778
- suggestedName: string(),
15779
- config: record(string(), unknown())
15780
- });
15781
- /** The degrade engine's report — what was resolved / dropped / degraded. */
15782
- var RenderedAsSchema = object({
15783
- level: string(),
15784
- format: NotificationFormatSchema,
15785
- attachmentsSent: number().int().nonnegative(),
15786
- actionsSent: number().int().nonnegative(),
15787
- truncated: boolean(),
15788
- dropped: array(string())
15789
- });
15790
- var SendResultSchema = object({
15791
- success: boolean(),
15877
+ url: string(),
15878
+ kind: BrokerKindSchema,
15879
+ status: BrokerStatusSchema$1,
15880
+ latencyMs: number().nullable(),
15792
15881
  error: string().optional(),
15793
- renderedAs: RenderedAsSchema.optional()
15882
+ /** Embedded brokers only: number of MQTT clients currently connected. */
15883
+ connectedClients: number().int().nonnegative().optional(),
15884
+ /** Epoch ms of the last live probe (external) or aedes snapshot (embedded). */
15885
+ lastCheckedAt: number().optional()
15794
15886
  });
15795
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
15796
- var TestResultSchema = SendResultSchema;
15797
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
15798
- kind: string(),
15799
- config: record(string(), unknown()).optional()
15800
- }), array(DiscoveredTargetSchema)), method(object({
15801
- targetId: string(),
15802
- notification: NotificationSchema
15803
- }), SendResultSchema, { kind: "mutation" }), method(object({
15804
- targetId: string(),
15805
- sample: NotificationSchema.optional()
15806
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
15807
- targetId: string(),
15808
- enabled: boolean()
15809
- }), _void(), { kind: "mutation" });
15810
15887
  /**
15811
- * Shared LLM generate contracts imported by BOTH `llm.cap.ts` (consumer
15812
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15813
- * caps stay wire-compatible without a circular cap→cap import.
15814
- *
15815
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
15816
- * every transport tier structurally, and failed calls still write usage rows.
15817
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15888
+ * Connection details what a consumer needs to call
15889
+ * `mqtt.connect(url, options)`. We split URL + credentials so the
15890
+ * consumer can pass them as `mqtt.connect(url, { username, password })`
15891
+ * instead of stuffing creds into the URL (which leaks them into logs).
15818
15892
  */
15819
- var LlmUsageSchema = object({
15820
- inputTokens: number(),
15821
- outputTokens: number()
15893
+ var BrokerConnectionDetailsSchema = object({
15894
+ url: string(),
15895
+ username: string().optional(),
15896
+ password: string().optional(),
15897
+ /**
15898
+ * Suggested prefix for `clientId`. Each consumer should suffix this
15899
+ * with its own discriminator (addon id, instance id) so reconnects
15900
+ * don't kick each other off (MQTT spec: clientId must be unique per
15901
+ * broker).
15902
+ */
15903
+ clientIdPrefix: string().optional()
15822
15904
  });
15823
- var LlmErrorCodeSchema = _enum([
15824
- "timeout",
15825
- "rate-limited",
15826
- "auth",
15827
- "refusal",
15828
- "bad-request",
15829
- "unavailable",
15830
- "no-profile",
15831
- "budget-exceeded",
15832
- "adapter-error"
15833
- ]);
15834
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15905
+ var AddBrokerInputSchema = object({
15906
+ name: string().min(1),
15907
+ url: string().regex(/^(mqtt|mqtts|ws|wss):\/\//, "URL must start with mqtt(s):// or ws(s)://"),
15908
+ username: string().optional(),
15909
+ password: string().optional(),
15910
+ clientIdPrefix: string().optional()
15911
+ });
15912
+ var AddBrokerResultSchema = object({ id: string() });
15913
+ var IdInputSchema = object({ id: string() });
15914
+ var TestResultSchema$1 = discriminatedUnion("ok", [object({
15835
15915
  ok: literal(true),
15836
- text: string(),
15837
- model: string(),
15838
- usage: LlmUsageSchema,
15839
- truncated: boolean(),
15840
15916
  latencyMs: number()
15841
- }), object({
15842
- ok: literal(false),
15843
- code: LlmErrorCodeSchema,
15844
- message: string(),
15845
- retryAfterMs: number().optional()
15846
- })]);
15847
- /**
15848
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15849
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15850
- * notification-output.cap.ts:27-31 precedents).
15851
- */
15852
- var LlmImageSchema = object({
15853
- bytes: _instanceof(Uint8Array),
15854
- mimeType: string()
15855
- });
15856
- var LlmGenerateBaseInputSchema = object({
15857
- /** Collection routing (the notification-output posture). */
15858
- addonId: string().optional(),
15859
- /** Explicit profile; else the resolution chain (spec §3). */
15860
- profileId: string().optional(),
15861
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15862
- consumer: string(),
15863
- system: string().optional(),
15864
- /** v1: single-turn. `messages[]` is a v2 additive field. */
15865
- prompt: string(),
15866
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15867
- jsonSchema: record(string(), unknown()).optional(),
15868
- /** Per-call override of the profile default. */
15869
- maxTokens: number().int().positive().optional(),
15870
- temperature: number().optional()
15871
- });
15872
- /**
15873
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15874
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15875
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15876
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15877
- * this only through the `llm` cap's methods.
15878
- *
15879
- * One running llama-server child per node in v1 (models are RAM-heavy).
15880
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15881
- * watchdog — operator decision #3).
15882
- */
15883
- var ManagedModelRefSchema = discriminatedUnion("kind", [
15884
- object({
15885
- kind: literal("catalog"),
15886
- catalogId: string()
15887
- }),
15888
- object({
15889
- kind: literal("url"),
15890
- url: string(),
15891
- sha256: string().optional()
15892
- }),
15893
- object({
15894
- kind: literal("path"),
15895
- path: string()
15896
- })
15897
- ]);
15898
- var ManagedRuntimeConfigSchema = object({
15899
- /** WHERE the runtime lives — hub or any agent. */
15900
- nodeId: string(),
15901
- /** Closed for v1; 'ollama' is a v2 candidate. */
15902
- engine: _enum(["llama-cpp"]),
15903
- model: ManagedModelRefSchema,
15904
- contextSize: number().int().default(4096),
15905
- /** 0 = CPU-only. */
15906
- gpuLayers: number().int().default(0),
15907
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15908
- threads: number().int().optional(),
15909
- /** Concurrent slots. */
15910
- parallel: number().int().default(1),
15911
- /** Else lazy: first generate boots it. */
15912
- autoStart: boolean().default(false),
15913
- /** 0 = never; frees RAM after quiet periods. */
15914
- idleStopMinutes: number().int().default(30)
15917
+ }), object({
15918
+ ok: literal(false),
15919
+ error: string()
15920
+ })]);
15921
+ var StartEmbeddedInputSchema = object({
15922
+ port: number().int().min(1).max(65535).default(1883),
15923
+ /** Allow anonymous connect (no username/password). Default: false. */
15924
+ allowAnonymous: boolean().default(false),
15925
+ /** Optional shared username/password for clients. */
15926
+ username: string().optional(),
15927
+ password: string().optional()
15915
15928
  });
15916
- var LlmRuntimeStatusSchema = object({
15917
- /** Status is ALWAYS node-qualified. */
15918
- nodeId: string(),
15919
- state: _enum([
15920
- "stopped",
15921
- "downloading",
15922
- "starting",
15923
- "ready",
15924
- "crashed",
15925
- "failed"
15926
- ]),
15927
- pid: number().optional(),
15928
- port: number().optional(),
15929
- modelPath: string().optional(),
15930
- modelId: string().optional(),
15931
- downloadProgress: number().min(0).max(1).optional(),
15932
- lastError: string().optional(),
15933
- crashesInWindow: number(),
15934
- /** Child RSS (sampled best-effort). */
15935
- memoryBytes: number().optional(),
15936
- vramBytes: number().optional()
15929
+ var StartEmbeddedResultSchema = object({
15930
+ id: string(),
15931
+ url: string()
15937
15932
  });
15938
- var LlmNodeModelSchema = object({
15939
- file: string(),
15940
- sizeBytes: number(),
15941
- catalogId: string().optional(),
15942
- installedAt: number().optional()
15933
+ var StatusSchema = object({
15934
+ brokerCount: number(),
15935
+ embeddedRunning: boolean()
15943
15936
  });
15944
- var LlmRuntimeDiskUsageSchema = object({
15945
- nodeId: string(),
15946
- modelsBytes: number(),
15947
- freeBytes: number().optional()
15937
+ 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);
15938
+ var NetworkEndpointSchema = object({
15939
+ url: string(),
15940
+ hostname: string(),
15941
+ port: number(),
15942
+ protocol: _enum(["http", "https"])
15943
+ });
15944
+ var NetworkAccessStatusSchema = object({
15945
+ connected: boolean(),
15946
+ endpoint: NetworkEndpointSchema.nullable(),
15947
+ error: string().optional()
15948
15948
  });
15949
- var llmRuntimeCapability = {
15950
- name: "llm-runtime",
15951
- scope: "system",
15952
- mode: "singleton",
15953
- internal: true,
15954
- methods: {
15955
- complete: method(LlmGenerateBaseInputSchema.extend({
15956
- images: array(LlmImageSchema).optional(),
15957
- runtime: ManagedRuntimeConfigSchema,
15958
- /** The managed profile's timeout, threaded by the hub provider. */
15959
- timeoutMs: number().int().positive().optional()
15960
- }), LlmGenerateResultSchema, { kind: "mutation" }),
15961
- ensureStarted: method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15962
- kind: "mutation",
15963
- auth: "admin"
15964
- }),
15965
- stop: method(object({}), _void(), {
15966
- kind: "mutation",
15967
- auth: "admin"
15968
- }),
15969
- status: method(object({}), LlmRuntimeStatusSchema),
15970
- installModel: method(object({ model: ManagedModelRefSchema }), _void(), {
15971
- kind: "mutation",
15972
- auth: "admin"
15973
- }),
15974
- deleteModel: method(object({ file: string() }), _void(), {
15975
- kind: "mutation",
15976
- auth: "admin"
15977
- }),
15978
- listLocalModels: method(object({}), array(LlmNodeModelSchema)),
15979
- getDiskUsage: method(object({}), LlmRuntimeDiskUsageSchema)
15980
- }
15981
- };
15982
15949
  /**
15983
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15984
- * methods concat-fan across providers; single-row methods route to ONE
15985
- * provider by the `addonId` in the call input (the notification-output
15986
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15987
- * (hub-placed); the cap stays open for future providers.
15950
+ * Optional, richer endpoint shape returned by providers that expose
15951
+ * MORE than one ingress concurrently (Tailscale Ingress with mixed
15952
+ * serve+funnel rules, future ngrok multi-tunnel, …). Each entry carries
15953
+ * the originating provider config (mode + sourcePort) so the
15954
+ * orchestrator UI can label rows distinctly. Providers that expose only
15955
+ * one endpoint just omit `listEndpoints` from their provider impl.
15956
+ */
15957
+ var NetworkEndpointEntrySchema = NetworkEndpointSchema.extend({
15958
+ /**
15959
+ * Stable id within the provider — typically `<mode>-<sourcePort>` so
15960
+ * the orchestrator can dedupe across `listEndpoints` polls.
15961
+ */
15962
+ id: string(),
15963
+ /** Operator-facing label (mirrors `MeshEndpoint.label`). */
15964
+ label: string(),
15965
+ /** Optional provider-specific mode tag, used for icon/colour in admin UI. */
15966
+ mode: string().optional(),
15967
+ /** Originating local port the ingress fronts (informational). */
15968
+ sourcePort: number().optional()
15969
+ });
15970
+ method(_void(), NetworkEndpointSchema, { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), method(_void(), NetworkEndpointSchema.nullable()), method(_void(), NetworkAccessStatusSchema), method(_void(), array(NetworkEndpointEntrySchema).readonly());
15971
+ /**
15972
+ * notification-output — canonical, capability-gated notification delivery.
15988
15973
  *
15989
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15990
- * `apiKey` is a password field — providers REDACT it on read and merge on
15991
- * write; a stored key NEVER round-trips to a client.
15974
+ * Apprise-derived model (see
15975
+ * `docs/superpowers/specs/2026-07-03-notification-output-notifier-matrix.md`):
15976
+ * callers emit ONE canonical `Notification`; each provider declares a
15977
+ * per-kind capability descriptor (`TargetKind`), and the pure degrade
15978
+ * engine (`@camstack/types` `prepareNotification`) transcodes / degrades the
15979
+ * message to what the kind supports — callers never special-case a service.
15980
+ *
15981
+ * DESIGN DECISIONS (locked):
15982
+ * - Target CRUD lives on THIS cap (`upsertTarget` / `deleteTarget` /
15983
+ * `setTargetEnabled`), each provider persisting via the `settings-store`
15984
+ * cap. Rationale: the admin UI needs one uniform surface across the
15985
+ * notifiers addon AND the HA addon; the addon-`globalSettingsSchema`-array
15986
+ * alternative would fork the UI per addon and cannot host the
15987
+ * discovery→adopt flow.
15988
+ * - `listTargetKinds` / `listTargets` / `discoverTargets` return arrays →
15989
+ * the generated cap-mount auto-`concatCollection`-fans them across every
15990
+ * registered provider (notifiers addon + HA addon) so one catalog is
15991
+ * routable. `send` / `testTarget` / CRUD route to ONE provider by the
15992
+ * `addonId` the generated collection router extracts from the call input.
15993
+ * - `Attachment.bytes` is `Uint8Array`. Transport-safe: superjson (the tRPC
15994
+ * transformer) + UDS MsgPack both round-trip typed arrays — already used by
15995
+ * `storage` / `storage-provider` / `recording` caps over the same path. No
15996
+ * base64 fallback needed.
15997
+ *
15998
+ * TODO (deferred, closed-set change — separate decision): add
15999
+ * `providerKind: 'notify'` so notification providers surface on the unified
16000
+ * admin "Integrations" page.
15992
16001
  */
15993
- var LlmProfileKindSchema = _enum([
15994
- "openai-compatible",
15995
- "openai",
15996
- "anthropic",
15997
- "google",
15998
- "managed-local"
16002
+ /**
16003
+ * Zentik-derived typed-media enum — the superset across every kind. Each
16004
+ * adapter picks what it supports and the degrade engine filters the rest.
16005
+ */
16006
+ var AttachmentMediaTypeSchema = _enum([
16007
+ "image",
16008
+ "video",
16009
+ "gif",
16010
+ "audio",
16011
+ "icon"
15999
16012
  ]);
16000
- var LlmProfileSchema = object({
16013
+ /**
16014
+ * A single attachment. Exactly one of `url` (remote source, most adapters
16015
+ * prefer this) or `bytes` (inline source; required for Pushover-style
16016
+ * bytes-only kinds) MUST be present — the degrade engine expresses a
16017
+ * url→bytes fetch as a `needsFetch` directive the adapter executes.
16018
+ */
16019
+ var AttachmentSchema = object({
16020
+ mediaType: AttachmentMediaTypeSchema,
16021
+ url: string().optional(),
16022
+ bytes: _instanceof(Uint8Array).optional(),
16023
+ mime: string().optional(),
16024
+ name: string().optional()
16025
+ }).refine((a) => a.url !== void 0 || a.bytes !== void 0, { message: "Attachment requires either `url` or `bytes`" });
16026
+ var NotificationFormatSchema = _enum([
16027
+ "text",
16028
+ "markdown",
16029
+ "html"
16030
+ ]);
16031
+ /** A single tap-through action button. */
16032
+ var NotificationActionSchema = object({
16001
16033
  id: string(),
16002
- name: string(),
16003
- kind: LlmProfileKindSchema,
16004
- /** Stamped by the provider — keeps the fanned catalog routable. */
16005
- addonId: string(),
16006
- enabled: boolean(),
16007
- /** Vendor model id, or the managed runtime's loaded model. */
16008
- model: string(),
16009
- /** Required for openai-compatible; override for cloud kinds. */
16010
- baseUrl: string().optional(),
16011
- /** ConfigUISchema type:'password' never round-trips (spec §5). */
16012
- apiKey: string().optional(),
16013
- supportsVision: boolean(),
16014
- temperature: number().min(0).max(2).optional(),
16015
- maxTokens: number().int().positive().optional(),
16016
- timeoutMs: number().int().positive().default(6e4),
16017
- extraHeaders: record(string(), string()).optional(),
16018
- /** kind === 'managed-local' only (spec §4). */
16019
- runtime: ManagedRuntimeConfigSchema.optional()
16034
+ label: string(),
16035
+ url: string().optional()
16036
+ });
16037
+ /**
16038
+ * The canonical notification. `body` is the only hard field (Apprise model).
16039
+ * `priority` is a 5-level ORDINAL (1=lowest 3=normal(default) 5=urgent),
16040
+ * NOT a fixed severity enum — each kind declares its own `caps.levels` and
16041
+ * the adapter maps this ordinal onto its native level. `level?` is an
16042
+ * optional kind-native level id (`emergency`, `silent`, …) that overrides
16043
+ * `priority` for that one target.
16044
+ */
16045
+ var NotificationSchema = object({
16046
+ body: string(),
16047
+ title: string().optional(),
16048
+ format: NotificationFormatSchema.default("text"),
16049
+ priority: number().int().min(1).max(5).default(3),
16050
+ level: string().optional(),
16051
+ attachments: array(AttachmentSchema).optional(),
16052
+ clickUrl: string().optional(),
16053
+ actions: array(NotificationActionSchema).optional(),
16054
+ sound: string().optional(),
16055
+ ttl: number().optional(),
16056
+ tag: string().optional(),
16057
+ deviceId: number().optional(),
16058
+ eventId: string().optional(),
16059
+ metadata: record(string(), unknown()).optional()
16060
+ });
16061
+ /** One declared native severity/priority level for a kind. */
16062
+ var TargetKindLevelSchema = object({
16063
+ id: string(),
16064
+ label: string(),
16065
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
16066
+ ordinal: number().int().min(1).max(5).nullable(),
16067
+ flags: object({
16068
+ critical: boolean().optional(),
16069
+ silent: boolean().optional(),
16070
+ noPush: boolean().optional()
16071
+ }).optional(),
16072
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
16073
+ requires: array(string()).optional(),
16074
+ description: string().optional()
16075
+ });
16076
+ /** The full capability block consulted before dispatch. */
16077
+ var TargetKindCapsSchema = object({
16078
+ attachments: object({
16079
+ mediaTypes: array(AttachmentMediaTypeSchema),
16080
+ mode: _enum([
16081
+ "url",
16082
+ "bytes",
16083
+ "both"
16084
+ ]),
16085
+ max: number().int().nonnegative(),
16086
+ maxBytes: number().int().positive().optional()
16087
+ }),
16088
+ /** Max action buttons (0 = none). */
16089
+ actions: number().int().nonnegative(),
16090
+ levels: array(TargetKindLevelSchema),
16091
+ format: array(NotificationFormatSchema),
16092
+ clickUrl: boolean(),
16093
+ sound: boolean(),
16094
+ ttl: boolean(),
16095
+ bodyMaxLen: number().int().positive()
16020
16096
  });
16021
- /** ConfigUISchema tree passed through untyped on the wire (the
16022
- * notification-output `ConfigSchemaPassthrough` precedent at
16023
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
16097
+ /**
16098
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
16099
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
16100
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
16101
+ * the union is large and not meant for runtime validation here; the exported
16102
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
16103
+ */
16024
16104
  var ConfigSchemaPassthrough = unknown();
16025
- var LlmProfileKindDescriptorSchema = object({
16026
- kind: LlmProfileKindSchema,
16105
+ var TargetKindSchema = object({
16106
+ kind: string(),
16027
16107
  label: string(),
16028
16108
  icon: string(),
16029
16109
  /** Stamped by each provider so the concat-fanned catalog stays routable. */
16030
16110
  addonId: string(),
16031
- configSchema: ConfigSchemaPassthrough
16111
+ configSchema: ConfigSchemaPassthrough,
16112
+ supportsDiscovery: boolean(),
16113
+ caps: TargetKindCapsSchema
16032
16114
  });
16033
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
16034
- var LlmDefaultSchema = object({
16035
- selector: LlmDefaultSelectorSchema,
16036
- profileId: string()
16115
+ /**
16116
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
16117
+ * (return a presence marker only) when serving `listTargets` — never
16118
+ * round-trip a stored secret to the UI.
16119
+ */
16120
+ var TargetSchema = object({
16121
+ id: string(),
16122
+ name: string(),
16123
+ kind: string(),
16124
+ addonId: string(),
16125
+ enabled: boolean(),
16126
+ config: record(string(), unknown())
16037
16127
  });
16038
- /** Server-side rollup row getUsage never dumps raw call rows (spec §6). */
16039
- var LlmUsageRollupSchema = object({
16040
- day: string(),
16041
- consumer: string(),
16042
- profileId: string(),
16043
- calls: number(),
16044
- okCalls: number(),
16045
- errorCalls: number(),
16046
- inputTokens: number(),
16047
- outputTokens: number(),
16048
- avgLatencyMs: number()
16128
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
16129
+ var DiscoveredTargetSchema = object({
16130
+ kind: string(),
16131
+ suggestedName: string(),
16132
+ config: record(string(), unknown())
16049
16133
  });
16050
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
16051
- var ManagedModelCatalogEntrySchema = object({
16052
- id: string(),
16053
- label: string(),
16054
- family: string(),
16055
- purpose: _enum(["text", "vision"]),
16056
- url: string(),
16057
- sha256: string(),
16058
- sizeBytes: number(),
16059
- quantization: string(),
16060
- /** Load-time guidance shown in the picker. */
16061
- minRamBytes: number(),
16062
- contextSizeDefault: number().int(),
16063
- /** Vision models: companion projector file. */
16064
- mmprojUrl: string().optional()
16134
+ /** The degrade engine's report what was resolved / dropped / degraded. */
16135
+ var RenderedAsSchema = object({
16136
+ level: string(),
16137
+ format: NotificationFormatSchema,
16138
+ attachmentsSent: number().int().nonnegative(),
16139
+ actionsSent: number().int().nonnegative(),
16140
+ truncated: boolean(),
16141
+ dropped: array(string())
16065
16142
  });
16066
- var LlmRuntimeNodeSchema = object({
16067
- nodeId: string(),
16068
- reachable: boolean(),
16069
- status: LlmRuntimeStatusSchema.optional(),
16070
- disk: LlmRuntimeDiskUsageSchema.optional(),
16071
- error: string().optional()
16143
+ var SendResultSchema = object({
16144
+ success: boolean(),
16145
+ error: string().optional(),
16146
+ renderedAs: RenderedAsSchema.optional()
16072
16147
  });
16073
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16074
- var ProfileRefInputSchema = object({
16075
- addonId: string(),
16076
- profileId: string()
16148
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
16149
+ var TestResultSchema = SendResultSchema;
16150
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
16151
+ kind: string(),
16152
+ config: record(string(), unknown()).optional()
16153
+ }), array(DiscoveredTargetSchema)), method(object({
16154
+ targetId: string(),
16155
+ notification: NotificationSchema
16156
+ }), SendResultSchema, { kind: "mutation" }), method(object({
16157
+ targetId: string(),
16158
+ sample: NotificationSchema.optional()
16159
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
16160
+ targetId: string(),
16161
+ enabled: boolean()
16162
+ }), _void(), { kind: "mutation" });
16163
+ /**
16164
+ * notification-rules — the Notification Center rule surface (P1 core).
16165
+ *
16166
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16167
+ * (operator decisions D-1/D-2/D-3 are binding):
16168
+ *
16169
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16170
+ * `notification-center` module), hooked on the durable persistence
16171
+ * moments (object-event insert, TrackCloser.closeExpired) with a
16172
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
16173
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16174
+ * FIRST persisted detection matching the conditions (per-track dedup,
16175
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16176
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
16177
+ * - DISPATCH stays behind `notification-output` (rules reference targets
16178
+ * by id; per-backend params are a passthrough blob capped by the
16179
+ * target kind's own caps/degrade engine).
16180
+ *
16181
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
16182
+ * server-injected caller identity — the first `caller: 'required'`
16183
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
16184
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
16185
+ * windows, and the optional label/identity/plate matchers. User rules,
16186
+ * private zones, per-recipient fan-out and the wider condition table are
16187
+ * P2+ (see spec §7).
16188
+ *
16189
+ * All schemas here are the single source of truth — `NcRule` etc. are
16190
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16191
+ * schema/interface drift is explicitly not repeated).
16192
+ */
16193
+ /**
16194
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
16195
+ * The value maps 1:1 onto the evaluated record kind:
16196
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16197
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16198
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16199
+ * change of a LINKED device, one row per linked camera)
16200
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16201
+ * delivery / pick-up)
16202
+ *
16203
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16204
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
16205
+ * this one field keeps the schema additive — a rule still declares exactly
16206
+ * one trigger.
16207
+ */
16208
+ var NcDeliverySchema = _enum([
16209
+ "immediate",
16210
+ "track-end",
16211
+ "device-event",
16212
+ "package-event"
16213
+ ]);
16214
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
16215
+ var NcScheduleSchema = object({
16216
+ windows: array(object({
16217
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16218
+ days: array(number().int().min(0).max(6)).min(1),
16219
+ startMinute: number().int().min(0).max(1439),
16220
+ endMinute: number().int().min(0).max(1439)
16221
+ })).min(1),
16222
+ /** IANA timezone; default = hub host timezone. */
16223
+ timezone: string().optional(),
16224
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16225
+ invert: boolean().optional()
16077
16226
  });
16078
- var llmCapability = {
16079
- name: "llm",
16080
- scope: "system",
16081
- mode: "collection",
16082
- internal: false,
16083
- providerKind: "ai",
16084
- /** `nodeId` inputs below are DATA (the hub provider pins itself), never routing. */
16085
- nodeIdMode: "data",
16086
- methods: {
16087
- generate: method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }),
16088
- generateVision: method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }),
16089
- listProfileKinds: method(object({}), array(LlmProfileKindDescriptorSchema)),
16090
- listProfiles: method(object({}), array(LlmProfileSchema)),
16091
- upsertProfile: method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16092
- kind: "mutation",
16093
- auth: "admin"
16094
- }),
16095
- deleteProfile: method(ProfileRefInputSchema, _void(), {
16096
- kind: "mutation",
16097
- auth: "admin"
16098
- }),
16099
- testProfile: method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16100
- kind: "mutation",
16101
- auth: "admin"
16102
- }),
16103
- /** Live vendor enumeration (GET /models etc.). */
16104
- listModels: method(ProfileRefInputSchema, array(string())),
16105
- getDefaults: method(object({}), array(LlmDefaultSchema)),
16106
- setDefault: method(object({
16107
- selector: LlmDefaultSelectorSchema,
16108
- profileId: string().nullable()
16109
- }), _void(), {
16110
- kind: "mutation",
16111
- auth: "admin"
16112
- }),
16113
- getUsage: method(object({
16114
- since: number().optional(),
16115
- until: number().optional(),
16116
- consumer: string().optional(),
16117
- profileId: string().optional()
16118
- }), array(LlmUsageRollupSchema)),
16119
- listModelCatalog: method(object({}), array(ManagedModelCatalogEntrySchema)),
16120
- listRuntimeNodes: method(object({}), array(LlmRuntimeNodeSchema)),
16121
- listNodeModels: method(object({ nodeId: string() }), array(LlmNodeModelSchema)),
16122
- installModel: method(object({
16123
- nodeId: string(),
16124
- model: ManagedModelRefSchema
16125
- }), _void(), {
16126
- kind: "mutation",
16127
- auth: "admin"
16128
- }),
16129
- deleteModel: method(object({
16130
- nodeId: string(),
16131
- file: string()
16132
- }), _void(), {
16133
- kind: "mutation",
16134
- auth: "admin"
16135
- }),
16136
- getRuntimeStatus: method(ProfileRefInputSchema, LlmRuntimeStatusSchema),
16137
- startRuntime: method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16138
- kind: "mutation",
16139
- auth: "admin"
16140
- }),
16141
- stopRuntime: method(ProfileRefInputSchema, _void(), {
16142
- kind: "mutation",
16143
- auth: "admin"
16144
- })
16145
- }
16146
- };
16227
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16228
+ var NcPlateMatcherSchema = object({
16229
+ values: array(string().min(1)).min(1),
16230
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16231
+ maxDistance: number().int().min(0).max(3).default(1)
16232
+ });
16233
+ /**
16234
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16235
+ * occupancy edge for a device — optionally narrowed to a single admin
16236
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16237
+ * - `became-occupied` (default) count crossed 0 → ≥ `count`
16238
+ * - `became-free` — count crossed ≥ `count` → below it
16239
+ * - `>=` / `<=` — count is at/over or at/under `count`
16240
+ * `sustainSeconds` requires the condition hold continuously that long
16241
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
16242
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16243
+ * the condition never matches. Confirmed edge-state survives addon restarts
16244
+ * (declared SQLite collection, reseeded on boot).
16245
+ */
16246
+ var NcOccupancyConditionSchema = object({
16247
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16248
+ zoneId: string().optional(),
16249
+ /** Object class to count; absent = any class. */
16250
+ className: string().optional(),
16251
+ op: _enum([
16252
+ "became-occupied",
16253
+ "became-free",
16254
+ ">=",
16255
+ "<="
16256
+ ]).default("became-occupied"),
16257
+ count: number().int().min(0).default(1),
16258
+ sustainSeconds: number().int().min(0).max(3600).default(15)
16259
+ });
16260
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16261
+ var NcZoneConditionSchema = object({
16262
+ ids: array(string().min(1)).min(1),
16263
+ /** Quantifier over `ids` — at least one / every one visited. */
16264
+ match: _enum(["any", "all"]).default("any")
16265
+ });
16266
+ /**
16267
+ * The P1 condition set — a flat AND of groups; absent group = pass;
16268
+ * membership lists are OR within the list (spec §2.3).
16269
+ */
16270
+ var NcConditionsSchema = object({
16271
+ /** Device scope — absent = all devices. */
16272
+ devices: array(number()).optional(),
16273
+ /** Detector class names (any overlap with the record's class set). */
16274
+ classes: array(string().min(1)).optional(),
16275
+ /** Veto classes — any overlap fails the rule. */
16276
+ classesExclude: array(string().min(1)).optional(),
16277
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
16278
+ minConfidence: number().min(0).max(1).optional(),
16279
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
16280
+ zones: NcZoneConditionSchema.optional(),
16281
+ /** Veto zones — any hit fails the rule. */
16282
+ zonesExclude: array(string().min(1)).optional(),
16283
+ /**
16284
+ * Exact (case-insensitive) match on the record's collapsed `label`
16285
+ * (identity name / plate text / subclass).
16286
+ */
16287
+ labelEquals: array(string().min(1)).optional(),
16288
+ /**
16289
+ * Identity matcher. P1 boundary: matched against the record's collapsed
16290
+ * `label` (the identity display name propagated by the face pipeline)
16291
+ * identity-ID matching rides in P2 when identity ids reach the record.
16292
+ */
16293
+ identities: array(string().min(1)).optional(),
16294
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
16295
+ plates: NcPlateMatcherSchema.optional(),
16296
+ /**
16297
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16298
+ * Same P1 boundary: matched against the record's collapsed `label` (the
16299
+ * identity display name). A record with NO label passes (nothing to
16300
+ * exclude), unlike the include variant which fails on an absent label.
16301
+ */
16302
+ identitiesExclude: array(string().min(1)).optional(),
16303
+ /**
16304
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16305
+ * TRACK-END only: importance is scored at track close, so it does not exist
16306
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16307
+ * close the value is threaded via the close-time info (the `Track` clone is
16308
+ * captured before the DB row is updated, so it would otherwise read stale).
16309
+ * Fails when the record carries no importance (never guess quality — the
16310
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
16311
+ */
16312
+ minImportance: number().min(0).max(1).optional(),
16313
+ /**
16314
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16315
+ * TRACK-END only: an `immediate` / object-event subject has no closed
16316
+ * lifespan, so a dwell condition never matches immediate delivery
16317
+ * (documented choice — the object-event record carries no `firstSeen`,
16318
+ * so dwell cannot be computed from what the subject actually carries).
16319
+ */
16320
+ minDwellSeconds: number().min(0).optional(),
16321
+ /**
16322
+ * Detection provenance filter. `any` (default / absent) matches every
16323
+ * source; otherwise the subject's source must equal it. Legacy records
16324
+ * with no stamped source are treated as `pipeline`. The union spans both
16325
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
16326
+ * tracks carry `sensor`.
16327
+ */
16328
+ source: _enum([
16329
+ "pipeline",
16330
+ "onboard",
16331
+ "sensor",
16332
+ "any"
16333
+ ]).optional(),
16334
+ /**
16335
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16336
+ * detector `minConfidence` (that gates the object-detection score; this
16337
+ * gates the recognition/OCR match score). Fails when the subject carries
16338
+ * no label-match confidence (never guess). TRACK-END only: the confidence
16339
+ * lives on the recognition result and reaches the subject at track close.
16340
+ *
16341
+ * What it measures precisely (plumbed at track close — the closer threads
16342
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16343
+ * `importance`): the BEST recognition match confidence observed for the
16344
+ * label the track carries at close — for a face, the peak cosine similarity
16345
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16346
+ * for a plate, the peak OCR read score of the best-held plate
16347
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16348
+ * one track the higher of the two is used. A track that ended with no
16349
+ * confident identity/plate match carries no value, so the condition fails
16350
+ * closed for it (an un-recognized subject).
16351
+ */
16352
+ minLabelConfidence: number().min(0).max(1).optional(),
16353
+ /**
16354
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16355
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16356
+ * against the token carried on the device-event subject (extracted from the
16357
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16358
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16359
+ * eventType, so gate those with {@link sensorKinds} instead.
16360
+ */
16361
+ eventTypeTokens: array(string().min(1)).optional(),
16362
+ /**
16363
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16364
+ * `contact`, `button`, `device-event`) — matched against the persisted
16365
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16366
+ */
16367
+ sensorKinds: array(string().min(1)).optional(),
16368
+ /**
16369
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16370
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16371
+ * when the subject's phase does not match (a subject always carries a phase
16372
+ * on the package-event trigger).
16373
+ */
16374
+ packagePhase: _enum([
16375
+ "delivered",
16376
+ "picked-up",
16377
+ "both"
16378
+ ]).optional(),
16379
+ /**
16380
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16381
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16382
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
16383
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16384
+ */
16385
+ customZones: array(MaskPolygonShapeSchema).optional(),
16386
+ /**
16387
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16388
+ * (optionally zone/class-scoped) occupancy count crosses the configured
16389
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
16390
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16391
+ */
16392
+ occupancy: NcOccupancyConditionSchema.optional()
16393
+ });
16394
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
16395
+ var NcRuleTargetSchema = object({
16396
+ /** `notification-output` Target id. */
16397
+ targetId: string().min(1),
16398
+ /**
16399
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
16400
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16401
+ * degrade engine drops what the backend can't render.
16402
+ */
16403
+ params: record(string(), unknown()).optional()
16404
+ });
16405
+ /**
16406
+ * Media attachment policy (P1 still-image subset).
16407
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
16408
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
16409
+ * matched on identities attaches the subject's `faceCrop`, one matched on
16410
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
16411
+ * (or when the specific crop is missing) degrades to `best`, then
16412
+ * `keyFrame`, then no attachment — never delaying the send. The matched
16413
+ * condition summary is frozen on the outbox row at enqueue (like the rule
16414
+ * name), so the choice never drifts from the record that fired it.
16415
+ * - `keyFrame` — the clean scene frame (no subject box).
16416
+ * - `none` — no attachment.
16417
+ */
16418
+ var NcMediaPolicySchema = object({ attach: _enum([
16419
+ "best",
16420
+ "best-matching",
16421
+ "keyFrame",
16422
+ "none"
16423
+ ]).default("best") });
16424
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16425
+ var NcThrottleSchema = object({
16426
+ cooldownSec: number().int().min(0).max(86400).default(60),
16427
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16428
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
16429
+ });
16430
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16431
+ var NcRuleInputSchema = object({
16432
+ name: string().min(1).max(200),
16433
+ enabled: boolean().default(true),
16434
+ delivery: NcDeliverySchema,
16435
+ conditions: NcConditionsSchema.default({}),
16436
+ schedule: NcScheduleSchema.optional(),
16437
+ targets: array(NcRuleTargetSchema).min(1),
16438
+ media: NcMediaPolicySchema.default({ attach: "best" }),
16439
+ throttle: NcThrottleSchema.default({
16440
+ cooldownSec: 60,
16441
+ scope: "rule-device"
16442
+ }),
16443
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16444
+ template: object({
16445
+ title: string().max(500).optional(),
16446
+ body: string().max(2e3).optional()
16447
+ }).optional(),
16448
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
16449
+ priority: number().int().min(1).max(5).default(3),
16450
+ /**
16451
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16452
+ * behaviour, visible to all, read-only in the viewer). Present = personal
16453
+ * rule owned by this userId. Server-stamped; never trusted from a client.
16454
+ */
16455
+ ownerUserId: string().optional()
16456
+ });
16457
+ /**
16458
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
16459
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16460
+ * NOT a client-authored input field (it lives on the persisted rule, not the
16461
+ * input), so it is added here explicitly to let the store's per-target opt-out
16462
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16463
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16464
+ * `updateRule` patch.
16465
+ */
16466
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
16467
+ /** A persisted rule. */
16468
+ var NcRuleSchema = NcRuleInputSchema.extend({
16469
+ id: string(),
16470
+ /** userId of the admin who created the rule (server-stamped caller). */
16471
+ createdBy: string(),
16472
+ createdAt: number(),
16473
+ updatedAt: number(),
16474
+ /**
16475
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16476
+ * send time. Only a target's OWNER may add/remove its id (server-checked
16477
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
16478
+ */
16479
+ disabledTargetIds: array(string()).default([])
16480
+ });
16481
+ var NcTestResultSchema = object({
16482
+ recordId: string(),
16483
+ recordKind: _enum([
16484
+ "object-event",
16485
+ "track",
16486
+ "device-event",
16487
+ "package-event"
16488
+ ]),
16489
+ deviceId: number(),
16490
+ timestamp: number(),
16491
+ wouldFire: boolean(),
16492
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
16493
+ failedCondition: string().optional(),
16494
+ className: string().optional(),
16495
+ label: string().optional()
16496
+ });
16497
+ var NcConditionDescriptorSchema = object({
16498
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16499
+ id: string(),
16500
+ group: _enum([
16501
+ "scope",
16502
+ "class",
16503
+ "zones",
16504
+ "quality",
16505
+ "label",
16506
+ "schedule",
16507
+ "device",
16508
+ "package",
16509
+ "occupancy"
16510
+ ]),
16511
+ label: string(),
16512
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
16513
+ valueType: _enum([
16514
+ "deviceIdList",
16515
+ "stringList",
16516
+ "number01",
16517
+ "number",
16518
+ "sourceSelect",
16519
+ "zoneSelection",
16520
+ "zoneIdList",
16521
+ "schedule",
16522
+ "plateMatcher",
16523
+ "packagePhase",
16524
+ "polygonDraw",
16525
+ "occupancy"
16526
+ ]),
16527
+ operator: _enum([
16528
+ "in",
16529
+ "notIn",
16530
+ "anyOf",
16531
+ "allOf",
16532
+ "gte",
16533
+ "fuzzyIn",
16534
+ "withinSchedule"
16535
+ ]),
16536
+ /** Which delivery kinds the condition applies to. */
16537
+ appliesTo: array(NcDeliverySchema),
16538
+ phase: string(),
16539
+ description: string().optional()
16540
+ });
16541
+ /**
16542
+ * The delivery lifecycle status of a history row — a straight read of the
16543
+ * durable outbox row's own status (single source of truth):
16544
+ * - `pending` — enqueued, in-flight or retrying with backoff
16545
+ * - `sent` — delivered (terminal)
16546
+ * - `dead` — dead-lettered after exhausting retries / a permanent
16547
+ * backend rejection / a deleted target (terminal; carries
16548
+ * the failure `error`)
16549
+ *
16550
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
16551
+ * user dimension (quiet hours / snooze) and are additive when they land.
16552
+ */
16553
+ var NcHistoryStatusSchema = _enum([
16554
+ "pending",
16555
+ "sent",
16556
+ "dead"
16557
+ ]);
16558
+ /** The evaluated record kind a history row descends from (one per trigger). */
16559
+ var NcHistoryRecordKindSchema = _enum([
16560
+ "object-event",
16561
+ "track-end",
16562
+ "device-event",
16563
+ "package-event"
16564
+ ]);
16565
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16566
+ var NcHistorySubjectSchema = object({
16567
+ className: string(),
16568
+ label: string().optional(),
16569
+ confidence: number().optional(),
16570
+ zones: array(string()),
16571
+ timestamp: number()
16572
+ });
16573
+ /**
16574
+ * One delivery-history row. This is a read-only VIEW over the durable
16575
+ * outbox row (single source of truth — the same row the drain loop drives;
16576
+ * NO second write path, so history can never drift from delivery state).
16577
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16578
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16579
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
16580
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16581
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16582
+ * P1 (admin scope only).
16583
+ */
16584
+ var NcHistoryEntrySchema = object({
16585
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16586
+ id: string(),
16587
+ ruleId: string(),
16588
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
16589
+ ruleName: string(),
16590
+ /** The rule urgency/trigger that produced this delivery. */
16591
+ delivery: NcDeliverySchema,
16592
+ targetId: string(),
16593
+ deviceId: number(),
16594
+ recordKind: NcHistoryRecordKindSchema,
16595
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16596
+ recordId: string(),
16597
+ /** Present for track-scoped deliveries (object-event / track-end). */
16598
+ trackId: string().optional(),
16599
+ status: NcHistoryStatusSchema,
16600
+ /** Delivery attempts made so far. */
16601
+ attempts: number().int(),
16602
+ /** Fire time (outbox enqueue). */
16603
+ createdAt: number(),
16604
+ /** Last transition time (terminal for sent / dead). */
16605
+ updatedAt: number(),
16606
+ /** Failure detail — present on a `dead` row. */
16607
+ error: string().optional(),
16608
+ subject: NcHistorySubjectSchema
16609
+ });
16610
+ /**
16611
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16612
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16613
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16614
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16615
+ */
16616
+ var NcHistoryFilterSchema = object({
16617
+ ruleId: string().optional(),
16618
+ deviceId: number().optional(),
16619
+ status: NcHistoryStatusSchema.optional(),
16620
+ since: number().optional(),
16621
+ until: number().optional(),
16622
+ limit: number().int().min(1).max(500).default(100)
16623
+ });
16624
+ 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 }), {
16625
+ kind: "mutation",
16626
+ auth: "admin",
16627
+ caller: "required"
16628
+ }), method(object({
16629
+ ruleId: string(),
16630
+ patch: NcRulePatchSchema
16631
+ }), object({ rule: NcRuleSchema }), {
16632
+ kind: "mutation",
16633
+ auth: "admin",
16634
+ caller: "required"
16635
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
16636
+ kind: "mutation",
16637
+ auth: "admin"
16638
+ }), method(object({
16639
+ ruleId: string(),
16640
+ enabled: boolean()
16641
+ }), object({ success: literal(true) }), {
16642
+ kind: "mutation",
16643
+ auth: "admin"
16644
+ }), method(object({
16645
+ rule: NcRuleInputSchema,
16646
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
16647
+ }), object({ results: array(NcTestResultSchema) }), {
16648
+ kind: "mutation",
16649
+ auth: "admin"
16650
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
16147
16651
  /**
16148
16652
  * Zod schemas for persisted record types.
16149
16653
  *
@@ -16829,7 +17333,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16829
17333
  }), method(object({
16830
17334
  eventId: string(),
16831
17335
  kind: MediaFileKindEnum.optional()
16832
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
17336
+ }), array(MediaFileSchema).readonly()), method(object({
17337
+ trackId: string(),
17338
+ kinds: array(MediaFileKindEnum).optional()
17339
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
16833
17340
  deviceId: number(),
16834
17341
  timestamp: number(),
16835
17342
  frameWidth: number(),
@@ -16850,76 +17357,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16850
17357
  eventId: string(),
16851
17358
  timestamp: number()
16852
17359
  });
16853
- /**
16854
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
16855
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
16856
- * caps into per-camera event-kind descriptors.
16857
- *
16858
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
16859
- * is NOT duplicated here — every entry is derived from the single
16860
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
16861
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
16862
- * control cap means adding one line here (and a taxonomy entry); the anti-
16863
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
16864
- * eventful cap is missing.
16865
- */
16866
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
16867
- var LEGACY_ICON = {
16868
- motion: "motion",
16869
- audio: "audio",
16870
- person: "person",
16871
- vehicle: "vehicle",
16872
- animal: "animal",
16873
- package: "package",
16874
- door: "door",
16875
- pir: "pir",
16876
- smoke: "smoke",
16877
- water: "water",
16878
- button: "button",
16879
- generic: "generic",
16880
- gas: "smoke",
16881
- vibration: "generic",
16882
- tamper: "generic",
16883
- presence: "person",
16884
- lock: "generic",
16885
- siren: "generic",
16886
- switch: "generic",
16887
- doorbell: "button"
16888
- };
16889
- function legacyIcon(iconId) {
16890
- return LEGACY_ICON[iconId] ?? "generic";
16891
- }
16892
- /**
16893
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
16894
- * The anti-drift guard cross-checks this against the eventful caps declared
16895
- * in `packages/types/src/capabilities/*.cap.ts`.
16896
- */
16897
- var CAP_TO_KIND = {
16898
- contact: "contact",
16899
- motion: "motion-sensor",
16900
- smoke: "smoke",
16901
- flood: "flood",
16902
- gas: "gas",
16903
- "carbon-monoxide": "carbon-monoxide",
16904
- vibration: "vibration",
16905
- tamper: "tamper",
16906
- presence: "presence",
16907
- "enum-sensor": "enum-sensor",
16908
- "event-emitter": "device-event",
16909
- "lock-control": "lock",
16910
- switch: "switch",
16911
- button: "button",
16912
- doorbell: "doorbell"
16913
- };
16914
- function buildDescriptor(capName, kind) {
16915
- const t = EVENT_TAXONOMY[kind];
16916
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
16917
- return {
16918
- ...t,
16919
- icon: legacyIcon(t.iconId)
16920
- };
16921
- }
16922
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
16923
17360
  var CameraPipelineConfigSchema = object({
16924
17361
  engine: PipelineEngineChoiceSchema.optional(),
16925
17362
  steps: array(PipelineStepInputSchema).readonly(),
@@ -17405,6 +17842,76 @@ method(object({
17405
17842
  auth: "admin"
17406
17843
  });
17407
17844
  /**
17845
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
17846
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
17847
+ * caps into per-camera event-kind descriptors.
17848
+ *
17849
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
17850
+ * is NOT duplicated here — every entry is derived from the single
17851
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
17852
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
17853
+ * control cap means adding one line here (and a taxonomy entry); the anti-
17854
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
17855
+ * eventful cap is missing.
17856
+ */
17857
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
17858
+ var LEGACY_ICON = {
17859
+ motion: "motion",
17860
+ audio: "audio",
17861
+ person: "person",
17862
+ vehicle: "vehicle",
17863
+ animal: "animal",
17864
+ package: "package",
17865
+ door: "door",
17866
+ pir: "pir",
17867
+ smoke: "smoke",
17868
+ water: "water",
17869
+ button: "button",
17870
+ generic: "generic",
17871
+ gas: "smoke",
17872
+ vibration: "generic",
17873
+ tamper: "generic",
17874
+ presence: "person",
17875
+ lock: "generic",
17876
+ siren: "generic",
17877
+ switch: "generic",
17878
+ doorbell: "button"
17879
+ };
17880
+ function legacyIcon(iconId) {
17881
+ return LEGACY_ICON[iconId] ?? "generic";
17882
+ }
17883
+ /**
17884
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
17885
+ * The anti-drift guard cross-checks this against the eventful caps declared
17886
+ * in `packages/types/src/capabilities/*.cap.ts`.
17887
+ */
17888
+ var CAP_TO_KIND = {
17889
+ contact: "contact",
17890
+ motion: "motion-sensor",
17891
+ smoke: "smoke",
17892
+ flood: "flood",
17893
+ gas: "gas",
17894
+ "carbon-monoxide": "carbon-monoxide",
17895
+ vibration: "vibration",
17896
+ tamper: "tamper",
17897
+ presence: "presence",
17898
+ "enum-sensor": "enum-sensor",
17899
+ "event-emitter": "device-event",
17900
+ "lock-control": "lock",
17901
+ switch: "switch",
17902
+ button: "button",
17903
+ doorbell: "doorbell"
17904
+ };
17905
+ function buildDescriptor(capName, kind) {
17906
+ const t = EVENT_TAXONOMY[kind];
17907
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
17908
+ return {
17909
+ ...t,
17910
+ icon: legacyIcon(t.iconId)
17911
+ };
17912
+ }
17913
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
17914
+ /**
17408
17915
  * server-management — per-NODE singleton capability for a node's ROOT
17409
17916
  * package lifecycle (runtime-updatable node packages).
17410
17917
  *
@@ -18859,7 +19366,28 @@ var FaceInfoSchema = object({
18859
19366
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
18860
19367
  * track produced no key frame (e.g. native/onboard source) — the UI falls
18861
19368
  * back to the inline `base64` face crop. */
18862
- keyFrameMediaKey: string().optional()
19369
+ keyFrameMediaKey: string().optional(),
19370
+ /** Winning identity-match cosine (0..1) for this face's track, when an
19371
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
19372
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
19373
+ * faces that were never auto-recognized. */
19374
+ bestMatchScore: number().optional(),
19375
+ /** Native-scale face short side (px) at recognition time, when the runner
19376
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
19377
+ * legacy rows / runners that reported no native measure. */
19378
+ nativeFaceShortSidePx: number().optional(),
19379
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
19380
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
19381
+ * but blocked only by the recognition size floor). Mutually exclusive with
19382
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
19383
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
19384
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
19385
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
19386
+ suggestedIdentityId: string().optional(),
19387
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
19388
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
19389
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
19390
+ suggestedMatchScore: number().optional()
18863
19391
  });
18864
19392
  var FaceFilterEnum = _enum([
18865
19393
  "unassigned",
@@ -20902,36 +21430,6 @@ Object.freeze({
20902
21430
  addonId: null,
20903
21431
  access: "view"
20904
21432
  },
20905
- "advancedNotifier.deleteRule": {
20906
- capName: "advanced-notifier",
20907
- capScope: "system",
20908
- addonId: null,
20909
- access: "delete"
20910
- },
20911
- "advancedNotifier.getHistory": {
20912
- capName: "advanced-notifier",
20913
- capScope: "system",
20914
- addonId: null,
20915
- access: "view"
20916
- },
20917
- "advancedNotifier.getRules": {
20918
- capName: "advanced-notifier",
20919
- capScope: "system",
20920
- addonId: null,
20921
- access: "view"
20922
- },
20923
- "advancedNotifier.testRule": {
20924
- capName: "advanced-notifier",
20925
- capScope: "system",
20926
- addonId: null,
20927
- access: "create"
20928
- },
20929
- "advancedNotifier.upsertRule": {
20930
- capName: "advanced-notifier",
20931
- capScope: "system",
20932
- addonId: null,
20933
- access: "create"
20934
- },
20935
21433
  "alarmPanel.arm": {
20936
21434
  capName: "alarm-panel",
20937
21435
  capScope: "device",
@@ -23236,6 +23734,60 @@ Object.freeze({
23236
23734
  addonId: null,
23237
23735
  access: "create"
23238
23736
  },
23737
+ "notificationRules.createRule": {
23738
+ capName: "notification-rules",
23739
+ capScope: "system",
23740
+ addonId: null,
23741
+ access: "create"
23742
+ },
23743
+ "notificationRules.deleteRule": {
23744
+ capName: "notification-rules",
23745
+ capScope: "system",
23746
+ addonId: null,
23747
+ access: "delete"
23748
+ },
23749
+ "notificationRules.getConditionCatalog": {
23750
+ capName: "notification-rules",
23751
+ capScope: "system",
23752
+ addonId: null,
23753
+ access: "view"
23754
+ },
23755
+ "notificationRules.getHistory": {
23756
+ capName: "notification-rules",
23757
+ capScope: "system",
23758
+ addonId: null,
23759
+ access: "view"
23760
+ },
23761
+ "notificationRules.getRule": {
23762
+ capName: "notification-rules",
23763
+ capScope: "system",
23764
+ addonId: null,
23765
+ access: "view"
23766
+ },
23767
+ "notificationRules.listRules": {
23768
+ capName: "notification-rules",
23769
+ capScope: "system",
23770
+ addonId: null,
23771
+ access: "view"
23772
+ },
23773
+ "notificationRules.setRuleEnabled": {
23774
+ capName: "notification-rules",
23775
+ capScope: "system",
23776
+ addonId: null,
23777
+ access: "create"
23778
+ },
23779
+ "notificationRules.testRule": {
23780
+ capName: "notification-rules",
23781
+ capScope: "system",
23782
+ addonId: null,
23783
+ access: "create"
23784
+ },
23785
+ "notificationRules.updateRule": {
23786
+ capName: "notification-rules",
23787
+ capScope: "system",
23788
+ addonId: null,
23789
+ access: "create"
23790
+ },
23239
23791
  "notifier.cancel": {
23240
23792
  capName: "notifier",
23241
23793
  capScope: "device",