@camstack/addon-provider-wyze 0.2.4 → 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 +1411 -859
  2. package/dist/addon.mjs +1411 -859
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -9,7 +9,7 @@ import { spawn } from "node:child_process";
9
9
  //#region \0rolldown/runtime.js
10
10
  var __require$1 = /* @__PURE__ */ createRequire(import.meta.url);
11
11
  //#endregion
12
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
12
+ //#region ../types/dist/event-category-BLcNejAE.mjs
13
13
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
14
14
  EventCategory["SystemBoot"] = "system.boot";
15
15
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -159,9 +159,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
159
159
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
160
160
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
161
161
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
162
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
163
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
164
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
165
162
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
166
163
  * progress bar the client reconciles via `recordingExport.getExport`. */
167
164
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6826,7 +6823,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6826
6823
  patch: record(string(), unknown())
6827
6824
  }), object({ success: literal(true) });
6828
6825
  object({ deviceId: number() }), unknown().nullable();
6829
- /** Shorthand to define a method schema */
6830
6826
  function method(input, output, options) {
6831
6827
  return {
6832
6828
  input,
@@ -6834,6 +6830,7 @@ function method(input, output, options) {
6834
6830
  kind: options?.kind ?? "query",
6835
6831
  auth: options?.auth ?? "protected",
6836
6832
  ...options?.access !== void 0 ? { access: options.access } : {},
6833
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6837
6834
  timeoutMs: options?.timeoutMs
6838
6835
  };
6839
6836
  }
@@ -8203,6 +8200,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8203
8200
  /** The complete taxonomy dictionary, keyed by kind. */
8204
8201
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8205
8202
  /**
8203
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8204
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8205
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8206
+ * taxonomy surface (timeline, filters, event page).
8207
+ *
8208
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8209
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8210
+ * for the `classes` / `classesExclude` conditions.
8211
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8212
+ * the same class picker, grouped under an Audio header.
8213
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8214
+ * lock / …) for the `sensorKinds` device-event condition.
8215
+ *
8216
+ * Each entry carries `parentKind` so the client can group video subs under
8217
+ * their macro and sensor/control kinds under their category. This surface is
8218
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8219
+ * method, no codegen — so it ships train-free with an addon deploy.
8220
+ */
8221
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8222
+ var NcTaxonomyEntrySchema = object({
8223
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8224
+ kind: string(),
8225
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8226
+ label: string(),
8227
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8228
+ parentKind: string().nullable()
8229
+ });
8230
+ object({
8231
+ videoClasses: array(NcTaxonomyEntrySchema),
8232
+ audioKinds: array(NcTaxonomyEntrySchema),
8233
+ labels: array(NcTaxonomyEntrySchema)
8234
+ });
8235
+ function toEntry(kind, label, parentKind) {
8236
+ return {
8237
+ kind,
8238
+ label,
8239
+ parentKind
8240
+ };
8241
+ }
8242
+ /**
8243
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8244
+ * (macros before their subs), which the client relies on for stable grouping.
8245
+ */
8246
+ function buildNcTaxonomy() {
8247
+ const all = Object.values(EVENT_TAXONOMY);
8248
+ return {
8249
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8250
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8251
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8252
+ };
8253
+ }
8254
+ Object.freeze(buildNcTaxonomy());
8255
+ /**
8206
8256
  * Error types for the safe expression engine. Two distinct classes so callers
8207
8257
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8208
8258
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -12188,6 +12238,22 @@ var CameraMetricsSchema = object({
12188
12238
  ])
12189
12239
  });
12190
12240
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
12241
+ /**
12242
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
12243
+ * within the frame, so the executor can re-cut a leaf child ROI at native
12244
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
12245
+ */
12246
+ var NativeCropRefSchema = object({
12247
+ /** Handle keying the retained native surface (node-pinned to its owner). */
12248
+ handle: FrameHandleSchema,
12249
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
12250
+ cropFrameSpace: object({
12251
+ x: number(),
12252
+ y: number(),
12253
+ w: number(),
12254
+ h: number()
12255
+ })
12256
+ });
12191
12257
  var ModelFormatSchema$1 = _enum([
12192
12258
  "onnx",
12193
12259
  "coreml",
@@ -12463,7 +12529,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
12463
12529
  * Omitted ⇒ the runner's default device (current single-engine
12464
12530
  * behaviour). Selects WHICH device pool of the node runs the call.
12465
12531
  */
12466
- deviceKey: string().optional()
12532
+ deviceKey: string().optional(),
12533
+ /**
12534
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
12535
+ * when the parent crop was resolved from the frame's retained NATIVE
12536
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
12537
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
12538
+ * resolution from that surface — the SAME quality path faces already
12539
+ * had — instead of the downscaled parent tile. `handle` keys the native
12540
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
12541
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
12542
+ * the executor's crop-normalized child ROI back into frame-normalized
12543
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
12544
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
12545
+ * (today's behaviour on the fallback path).
12546
+ */
12547
+ nativeCropRef: NativeCropRefSchema.optional()
12467
12548
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
12468
12549
  engine: PipelineEngineChoiceSchema.optional(),
12469
12550
  steps: array(PipelineStepInputSchema).min(1),
@@ -12712,7 +12793,11 @@ var DetailResultSchema = object({
12712
12793
  bbox: NativeCropBboxSchema.optional(),
12713
12794
  embedding: string().optional(),
12714
12795
  label: string().optional(),
12715
- alignedCropJpeg: string().optional()
12796
+ alignedCropJpeg: string().optional(),
12797
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
12798
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
12799
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
12800
+ nativeFaceShortSidePx: number().optional()
12716
12801
  });
12717
12802
  /**
12718
12803
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -12726,6 +12811,12 @@ var motionCooldownMsField = {
12726
12811
  default: 3e4,
12727
12812
  step: 500
12728
12813
  };
12814
+ var maxSessionHoldMsField = {
12815
+ min: 0,
12816
+ max: 6e5,
12817
+ default: 12e4,
12818
+ step: 5e3
12819
+ };
12729
12820
  var motionFpsField = {
12730
12821
  min: 1,
12731
12822
  max: 30,
@@ -12873,6 +12964,19 @@ var RunnerCameraConfigSchema = object({
12873
12964
  "on-motion"
12874
12965
  ]).default("always-on"),
12875
12966
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
12967
+ /**
12968
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
12969
+ * detection session is active and ≥1 confirmed non-stationary track is
12970
+ * still live, the orchestrator keeps the session open past
12971
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
12972
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
12973
+ * ms since the session opened, after which it closes regardless. `0`
12974
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
12975
+ * runner itself — carried here so it shares the per-camera device-settings
12976
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
12977
+ * resolved `CameraDetectionConfig`.
12978
+ */
12979
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
12876
12980
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
12877
12981
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
12878
12982
  motionStreamId: string(),
@@ -12962,7 +13066,7 @@ var RunnerCameraConfigSchema = object({
12962
13066
  */
12963
13067
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
12964
13068
  });
12965
- 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;
13069
+ 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;
12966
13070
  /**
12967
13071
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
12968
13072
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -16489,94 +16593,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
16489
16593
  bundleUrl: string()
16490
16594
  });
16491
16595
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
16492
- var NotificationRuleConditionsSchema = object({
16493
- deviceIds: array(number()).readonly().optional(),
16494
- classNames: array(string()).readonly().optional(),
16495
- zoneIds: array(string()).readonly().optional(),
16496
- minConfidence: number().optional(),
16497
- source: _enum([
16498
- "pipeline",
16499
- "onboard",
16500
- "any"
16501
- ]).optional(),
16502
- schedule: object({
16503
- days: array(number()).readonly(),
16504
- startHour: number(),
16505
- endHour: number()
16506
- }).optional(),
16507
- cooldownSeconds: number().optional(),
16508
- minDwellSeconds: number().optional(),
16509
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
16510
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
16511
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
16512
- eventTypeTokens: array(string()).readonly().optional(),
16513
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
16514
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
16515
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
16516
- clipDescription: object({
16517
- text: string().min(1),
16518
- minSimilarity: number().min(0).max(1)
16519
- }).optional(),
16520
- /** Match events whose recognized-entity label (face identity name or plate
16521
- * vehicle name, propagated onto `event.data.label`) is one of these values.
16522
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
16523
- * vehicle/person> is seen". */
16524
- labels: array(string()).readonly().optional()
16525
- });
16526
- var NotificationRuleTemplateSchema = object({
16527
- title: string(),
16528
- body: string(),
16529
- imageMode: _enum([
16530
- "crop",
16531
- "annotated",
16532
- "full",
16533
- "none"
16534
- ])
16535
- });
16536
- var NotificationRuleSchema = object({
16537
- id: string(),
16538
- name: string(),
16539
- enabled: boolean(),
16540
- eventTypes: array(string()).readonly(),
16541
- conditions: NotificationRuleConditionsSchema,
16542
- outputs: array(string()).readonly(),
16543
- template: NotificationRuleTemplateSchema.optional(),
16544
- priority: _enum([
16545
- "low",
16546
- "normal",
16547
- "high",
16548
- "critical"
16549
- ])
16550
- });
16551
- var NotificationTestResultSchema = object({
16552
- ruleId: string(),
16553
- eventId: string(),
16554
- timestamp: number(),
16555
- wouldFire: boolean(),
16556
- reason: string().optional()
16557
- });
16558
- var NotificationHistoryEntrySchema = object({
16559
- id: string(),
16560
- ruleId: string(),
16561
- ruleName: string(),
16562
- eventId: string(),
16563
- timestamp: number(),
16564
- outputs: array(string()).readonly(),
16565
- success: boolean(),
16566
- error: string().optional(),
16567
- deviceId: number().optional()
16568
- });
16569
- var NotificationHistoryFilterSchema = object({
16570
- ruleId: string().optional(),
16571
- deviceId: number().optional(),
16572
- from: number().optional(),
16573
- to: number().optional(),
16574
- limit: number().optional()
16575
- });
16576
- 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({
16577
- ruleId: string(),
16578
- lookbackMinutes: number()
16579
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
16580
16596
  /**
16581
16597
  * Alerts capability — collection-based internal alert system.
16582
16598
  *
@@ -16763,89 +16779,6 @@ method(object({
16763
16779
  password: string()
16764
16780
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
16765
16781
  /**
16766
- * `login-method` — collection cap through which auth addons contribute
16767
- * their pre-auth login surfaces to the login page. This is the SINGLE,
16768
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
16769
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
16770
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
16771
- * procedure aggregates them for the unauthenticated login page.
16772
- *
16773
- * A contribution is a discriminated union on `kind`:
16774
- *
16775
- * - `redirect` — a declarative button. The login page renders a generic
16776
- * button that navigates to `startUrl` (an addon-owned HTTP route).
16777
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
16778
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
16779
- * login page needs NO change.
16780
- *
16781
- * - `widget` — a Module-Federation widget the login page mounts (via
16782
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
16783
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
16784
- * mechanism kept for future use; no shipped addon uses it on the login
16785
- * page (the passkey ceremony below runs natively in the shell instead).
16786
- *
16787
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
16788
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
16789
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
16790
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
16791
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
16792
- * fetching any remote code pre-auth. Contribution stays unconditional —
16793
- * enrollment state is never leaked pre-auth; visibility is a shell
16794
- * decision.
16795
- *
16796
- * Every contribution carries a `stage`:
16797
- * - `primary` — shown on the first credentials screen (OIDC /
16798
- * magic-link buttons; a future usernameless passkey).
16799
- * - `second-factor` — shown AFTER the password leg, gated on the
16800
- * returned `factors` (passkey-as-2FA today).
16801
- *
16802
- * `mount: skip` — the cap is read server-side by the core auth router
16803
- * (`registry.getCollection('login-method')`), never mounted as its own
16804
- * tRPC router.
16805
- */
16806
- /** When a login method renders in the two-phase login flow. */
16807
- var LoginStageEnum = _enum(["primary", "second-factor"]);
16808
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
16809
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
16810
- object({
16811
- kind: literal("redirect"),
16812
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
16813
- id: string(),
16814
- /** Operator-facing button label. */
16815
- label: string(),
16816
- /** lucide-react icon name. */
16817
- icon: string().optional(),
16818
- /** Addon-owned HTTP route the button navigates to (GET). */
16819
- startUrl: string(),
16820
- stage: LoginStageEnum
16821
- }),
16822
- object({
16823
- kind: literal("widget"),
16824
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
16825
- id: string(),
16826
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
16827
- addonId: string(),
16828
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
16829
- bundle: string(),
16830
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
16831
- remote: WidgetRemoteSchema,
16832
- stage: LoginStageEnum
16833
- }),
16834
- object({
16835
- kind: literal("passkey"),
16836
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
16837
- id: string(),
16838
- /** Operator-facing button label. */
16839
- label: string(),
16840
- stage: LoginStageEnum,
16841
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
16842
- rpId: string(),
16843
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
16844
- origin: string().nullable()
16845
- })
16846
- ]);
16847
- method(_void(), array(LoginMethodContributionSchema).readonly());
16848
- /**
16849
16782
  * Orchestrator-side destination metadata. The orchestrator computes
16850
16783
  * `id = <addonId>:<subId>` from its provider lookup so consumers
16851
16784
  * (admin UI, restore flow) see one canonical key.
@@ -18206,242 +18139,617 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
18206
18139
  kind: "mutation",
18207
18140
  auth: "admin"
18208
18141
  });
18209
- var LogLevelSchema = _enum([
18210
- "debug",
18211
- "info",
18212
- "warn",
18213
- "error"
18142
+ /**
18143
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18144
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18145
+ * caps stay wire-compatible without a circular cap→cap import.
18146
+ *
18147
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
18148
+ * every transport tier structurally, and failed calls still write usage rows.
18149
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18150
+ */
18151
+ var LlmUsageSchema = object({
18152
+ inputTokens: number(),
18153
+ outputTokens: number()
18154
+ });
18155
+ var LlmErrorCodeSchema = _enum([
18156
+ "timeout",
18157
+ "rate-limited",
18158
+ "auth",
18159
+ "refusal",
18160
+ "bad-request",
18161
+ "unavailable",
18162
+ "no-profile",
18163
+ "budget-exceeded",
18164
+ "adapter-error"
18214
18165
  ]);
18215
- var LogEntrySchema = object({
18216
- timestamp: date(),
18217
- level: LogLevelSchema,
18218
- scope: array(string()),
18166
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18167
+ ok: literal(true),
18168
+ text: string(),
18169
+ model: string(),
18170
+ usage: LlmUsageSchema,
18171
+ truncated: boolean(),
18172
+ latencyMs: number()
18173
+ }), object({
18174
+ ok: literal(false),
18175
+ code: LlmErrorCodeSchema,
18219
18176
  message: string(),
18220
- meta: record(string(), unknown()).optional(),
18221
- tags: record(string(), string()).optional()
18222
- });
18223
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18224
- scope: array(string()).optional(),
18225
- level: LogLevelSchema.optional(),
18226
- since: date().optional(),
18227
- until: date().optional(),
18228
- limit: number().optional(),
18229
- tags: record(string(), string()).optional()
18230
- }), array(LogEntrySchema).readonly());
18231
- var CpuBreakdownSchema = object({
18232
- total: number(),
18233
- user: number(),
18234
- system: number(),
18235
- irq: number(),
18236
- nice: number(),
18237
- loadAvg: tuple([
18238
- number(),
18239
- number(),
18240
- number()
18241
- ]),
18242
- cores: number()
18177
+ retryAfterMs: number().optional()
18178
+ })]);
18179
+ /**
18180
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18181
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18182
+ * notification-output.cap.ts:27-31 precedents).
18183
+ */
18184
+ var LlmImageSchema = object({
18185
+ bytes: _instanceof(Uint8Array),
18186
+ mimeType: string()
18243
18187
  });
18244
- var MemoryInfoSchema = object({
18245
- percent: number(),
18246
- totalBytes: number(),
18247
- usedBytes: number(),
18248
- availableBytes: number(),
18249
- swapUsedBytes: number(),
18250
- swapTotalBytes: number()
18188
+ var LlmGenerateBaseInputSchema = object({
18189
+ /** Collection routing (the notification-output posture). */
18190
+ addonId: string().optional(),
18191
+ /** Explicit profile; else the resolution chain (spec §3). */
18192
+ profileId: string().optional(),
18193
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18194
+ consumer: string(),
18195
+ system: string().optional(),
18196
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
18197
+ prompt: string(),
18198
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18199
+ jsonSchema: record(string(), unknown()).optional(),
18200
+ /** Per-call override of the profile default. */
18201
+ maxTokens: number().int().positive().optional(),
18202
+ temperature: number().optional()
18251
18203
  });
18252
- var DiskIoSnapshotSchema = object({
18253
- readBytes: number(),
18254
- writeBytes: number(),
18255
- readOps: number(),
18256
- writeOps: number(),
18257
- timestampMs: number()
18258
- });
18259
- var NetworkIoSnapshotSchema = object({
18260
- rxBytes: number(),
18261
- txBytes: number(),
18262
- rxPackets: number(),
18263
- txPackets: number(),
18264
- rxErrors: number(),
18265
- txErrors: number(),
18266
- timestampMs: number()
18267
- });
18268
- var MetricsGpuInfoSchema = object({
18269
- utilization: number(),
18270
- model: string(),
18271
- memoryUsedBytes: number(),
18272
- memoryTotalBytes: number(),
18273
- temperature: number().nullable()
18274
- });
18275
- var ProcessResourceInfoSchema = object({
18276
- openFds: number(),
18277
- threadCount: number(),
18278
- activeHandles: number(),
18279
- activeRequests: number()
18280
- });
18281
- var PressureAvgsSchema = object({
18282
- avg10: number(),
18283
- avg60: number(),
18284
- avg300: number()
18285
- });
18286
- var PressureInfoSchema = object({
18287
- some: PressureAvgsSchema,
18288
- full: PressureAvgsSchema.nullable()
18289
- });
18290
- var SystemResourceSnapshotSchema = object({
18291
- cpu: CpuBreakdownSchema,
18292
- memory: MemoryInfoSchema,
18293
- gpu: MetricsGpuInfoSchema.nullable(),
18294
- network: NetworkIoSnapshotSchema,
18295
- disk: DiskIoSnapshotSchema,
18296
- pressure: object({
18297
- cpu: PressureInfoSchema.nullable(),
18298
- memory: PressureInfoSchema.nullable(),
18299
- io: PressureInfoSchema.nullable()
18204
+ /**
18205
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18206
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18207
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18208
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18209
+ * this only through the `llm` cap's methods.
18210
+ *
18211
+ * One running llama-server child per node in v1 (models are RAM-heavy).
18212
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18213
+ * watchdog — operator decision #3).
18214
+ */
18215
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
18216
+ object({
18217
+ kind: literal("catalog"),
18218
+ catalogId: string()
18300
18219
  }),
18301
- process: ProcessResourceInfoSchema,
18302
- cpuTemperature: number().nullable(),
18303
- timestampMs: number()
18304
- });
18305
- var DiskSpaceInfoSchema = object({
18306
- path: string(),
18307
- totalBytes: number(),
18308
- usedBytes: number(),
18309
- availableBytes: number(),
18310
- percent: number()
18311
- });
18312
- var PidResourceStatsSchema = object({
18313
- pid: number(),
18314
- cpu: number(),
18315
- memory: number(),
18316
- /**
18317
- * Private (anonymous) resident bytes — the per-process V8 heap + native
18318
- * allocations NOT shared with other processes (Linux RssAnon). This is the
18319
- * "real" per-runner cost; summing it across runners is meaningful, unlike
18320
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
18321
- * Undefined where /proc is unavailable (e.g. macOS).
18322
- */
18323
- privateBytes: number().optional(),
18324
- /**
18325
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18326
- * code shared copy-on-write across runners. Undefined on macOS.
18327
- */
18328
- sharedBytes: number().optional()
18220
+ object({
18221
+ kind: literal("url"),
18222
+ url: string(),
18223
+ sha256: string().optional()
18224
+ }),
18225
+ object({
18226
+ kind: literal("path"),
18227
+ path: string()
18228
+ })
18229
+ ]);
18230
+ var ManagedRuntimeConfigSchema = object({
18231
+ /** WHERE the runtime lives — hub or any agent. */
18232
+ nodeId: string(),
18233
+ /** Closed for v1; 'ollama' is a v2 candidate. */
18234
+ engine: _enum(["llama-cpp"]),
18235
+ model: ManagedModelRefSchema,
18236
+ contextSize: number().int().default(4096),
18237
+ /** 0 = CPU-only. */
18238
+ gpuLayers: number().int().default(0),
18239
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18240
+ threads: number().int().optional(),
18241
+ /** Concurrent slots. */
18242
+ parallel: number().int().default(1),
18243
+ /** Else lazy: first generate boots it. */
18244
+ autoStart: boolean().default(false),
18245
+ /** 0 = never; frees RAM after quiet periods. */
18246
+ idleStopMinutes: number().int().default(30)
18329
18247
  });
18330
- var AddonInstanceSchema = object({
18331
- addonId: string(),
18248
+ var LlmRuntimeStatusSchema = object({
18249
+ /** Status is ALWAYS node-qualified. */
18332
18250
  nodeId: string(),
18333
- role: _enum(["hub", "worker"]),
18334
- pid: number(),
18335
18251
  state: _enum([
18336
- "starting",
18337
- "running",
18338
- "stopping",
18339
18252
  "stopped",
18340
- "crashed"
18341
- ]),
18342
- uptimeSec: number()
18343
- });
18344
- var NodeProcessSchema = object({
18345
- pid: number(),
18346
- ppid: number(),
18347
- pgid: number(),
18348
- classification: _enum([
18349
- "root",
18350
- "managed",
18351
- "system",
18352
- "ghost"
18253
+ "downloading",
18254
+ "starting",
18255
+ "ready",
18256
+ "crashed",
18257
+ "failed"
18353
18258
  ]),
18354
- /** `$process` addon binding when `managed`, else null. */
18355
- addonId: string().nullable(),
18356
- /** Kernel-reported nodeId when the process is a known agent/worker. */
18357
- nodeId: string().nullable(),
18358
- /** Truncated command line. */
18359
- command: string(),
18360
- cpuPercent: number(),
18361
- memoryRssBytes: number(),
18362
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18363
- uptimeSec: number(),
18364
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18365
- orphaned: boolean()
18366
- });
18367
- var KillProcessInputSchema = object({
18368
- pid: number(),
18369
- /** Force = SIGKILL. Default is SIGTERM. */
18370
- force: boolean().optional()
18371
- });
18372
- var KillProcessResultSchema = object({
18373
- success: boolean(),
18374
- reason: string().optional(),
18375
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18376
- });
18377
- var DumpHeapSnapshotInputSchema = object({
18378
- /** The addon whose runner should dump a heap snapshot. */
18379
- addonId: string() });
18380
- var DumpHeapSnapshotResultSchema = object({
18381
- success: boolean(),
18382
- /** Path of the written .heapsnapshot inside the runner's container/host. */
18383
- path: string().optional(),
18384
- /** Process pid that was signalled. */
18385
18259
  pid: number().optional(),
18386
- reason: string().optional()
18260
+ port: number().optional(),
18261
+ modelPath: string().optional(),
18262
+ modelId: string().optional(),
18263
+ downloadProgress: number().min(0).max(1).optional(),
18264
+ lastError: string().optional(),
18265
+ crashesInWindow: number(),
18266
+ /** Child RSS (sampled best-effort). */
18267
+ memoryBytes: number().optional(),
18268
+ vramBytes: number().optional()
18387
18269
  });
18388
- var SystemMetricsSchema = object({
18389
- cpuPercent: number(),
18390
- memoryPercent: number(),
18391
- memoryUsedMB: number(),
18392
- memoryTotalMB: number(),
18393
- diskPercent: number().optional(),
18394
- temperature: number().optional(),
18395
- gpuPercent: number().optional(),
18396
- gpuMemoryPercent: number().optional()
18270
+ var LlmNodeModelSchema = object({
18271
+ file: string(),
18272
+ sizeBytes: number(),
18273
+ catalogId: string().optional(),
18274
+ installedAt: number().optional()
18397
18275
  });
18398
- 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, {
18276
+ var LlmRuntimeDiskUsageSchema = object({
18277
+ nodeId: string(),
18278
+ modelsBytes: number(),
18279
+ freeBytes: number().optional()
18280
+ });
18281
+ method(LlmGenerateBaseInputSchema.extend({
18282
+ images: array(LlmImageSchema).optional(),
18283
+ runtime: ManagedRuntimeConfigSchema,
18284
+ /** The managed profile's timeout, threaded by the hub provider. */
18285
+ timeoutMs: number().int().positive().optional()
18286
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18399
18287
  kind: "mutation",
18400
18288
  auth: "admin"
18401
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
18289
+ }), method(object({}), _void(), {
18402
18290
  kind: "mutation",
18403
18291
  auth: "admin"
18404
- });
18405
- method(object({
18406
- sourceUrl: string(),
18407
- metadata: ModelConvertMetadataSchema,
18408
- targets: array(ConvertTargetSchema).min(1).readonly(),
18409
- calibrationRef: string().optional(),
18410
- sessionId: string().optional()
18411
- }), ConvertResultSchema, {
18292
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18412
18293
  kind: "mutation",
18413
- auth: "admin",
18414
- timeoutMs: 6e5
18415
- });
18416
- method(object({
18417
- nodeId: string(),
18418
- modelId: string(),
18419
- format: _enum(MODEL_FORMATS),
18420
- entry: ModelCatalogEntrySchema
18421
- }), object({
18422
- ok: boolean(),
18423
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
18424
- sha256: string(),
18425
- bytes: number(),
18426
- /** The target node's modelsDir the artifact landed in. */
18427
- path: string()
18428
- }), {
18294
+ auth: "admin"
18295
+ }), method(object({ file: string() }), _void(), {
18429
18296
  kind: "mutation",
18430
18297
  auth: "admin"
18431
- });
18298
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18432
18299
  /**
18433
- * `mqtt-broker` — broker-registry cap.
18434
- *
18435
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
18436
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
18437
- * and (b) the connection details a consumer addon needs to spin up
18438
- * its OWN `mqtt.js` client.
18300
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18301
+ * methods concat-fan across providers; single-row methods route to ONE
18302
+ * provider by the `addonId` in the call input (the notification-output
18303
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18304
+ * (hub-placed); the cap stays open for future providers.
18439
18305
  *
18440
- * Why: pub/sub routing over the system event-bus loses fidelity
18441
- * (callback shape, QoS guarantees, will/retain semantics) and adds
18442
- * refcount bookkeeping that addons would rather own themselves. The
18443
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
18444
- * features anyway — give it the connection config, get out of the way.
18306
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18307
+ * `apiKey` is a password field providers REDACT it on read and merge on
18308
+ * write; a stored key NEVER round-trips to a client.
18309
+ */
18310
+ var LlmProfileKindSchema = _enum([
18311
+ "openai-compatible",
18312
+ "openai",
18313
+ "anthropic",
18314
+ "google",
18315
+ "managed-local"
18316
+ ]);
18317
+ var LlmProfileSchema = object({
18318
+ id: string(),
18319
+ name: string(),
18320
+ kind: LlmProfileKindSchema,
18321
+ /** Stamped by the provider — keeps the fanned catalog routable. */
18322
+ addonId: string(),
18323
+ enabled: boolean(),
18324
+ /** Vendor model id, or the managed runtime's loaded model. */
18325
+ model: string(),
18326
+ /** Required for openai-compatible; override for cloud kinds. */
18327
+ baseUrl: string().optional(),
18328
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
18329
+ apiKey: string().optional(),
18330
+ supportsVision: boolean(),
18331
+ temperature: number().min(0).max(2).optional(),
18332
+ maxTokens: number().int().positive().optional(),
18333
+ timeoutMs: number().int().positive().default(6e4),
18334
+ extraHeaders: record(string(), string()).optional(),
18335
+ /** kind === 'managed-local' only (spec §4). */
18336
+ runtime: ManagedRuntimeConfigSchema.optional()
18337
+ });
18338
+ /** ConfigUISchema tree passed through untyped on the wire (the
18339
+ * notification-output `ConfigSchemaPassthrough` precedent at
18340
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
18341
+ var ConfigSchemaPassthrough$1 = unknown();
18342
+ var LlmProfileKindDescriptorSchema = object({
18343
+ kind: LlmProfileKindSchema,
18344
+ label: string(),
18345
+ icon: string(),
18346
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
18347
+ addonId: string(),
18348
+ configSchema: ConfigSchemaPassthrough$1
18349
+ });
18350
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
18351
+ var LlmDefaultSchema = object({
18352
+ selector: LlmDefaultSelectorSchema,
18353
+ profileId: string()
18354
+ });
18355
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
18356
+ var LlmUsageRollupSchema = object({
18357
+ day: string(),
18358
+ consumer: string(),
18359
+ profileId: string(),
18360
+ calls: number(),
18361
+ okCalls: number(),
18362
+ errorCalls: number(),
18363
+ inputTokens: number(),
18364
+ outputTokens: number(),
18365
+ avgLatencyMs: number()
18366
+ });
18367
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
18368
+ var ManagedModelCatalogEntrySchema = object({
18369
+ id: string(),
18370
+ label: string(),
18371
+ family: string(),
18372
+ purpose: _enum(["text", "vision"]),
18373
+ url: string(),
18374
+ sha256: string(),
18375
+ sizeBytes: number(),
18376
+ quantization: string(),
18377
+ /** Load-time guidance shown in the picker. */
18378
+ minRamBytes: number(),
18379
+ contextSizeDefault: number().int(),
18380
+ /** Vision models: companion projector file. */
18381
+ mmprojUrl: string().optional()
18382
+ });
18383
+ var LlmRuntimeNodeSchema = object({
18384
+ nodeId: string(),
18385
+ reachable: boolean(),
18386
+ status: LlmRuntimeStatusSchema.optional(),
18387
+ disk: LlmRuntimeDiskUsageSchema.optional(),
18388
+ error: string().optional()
18389
+ });
18390
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
18391
+ var ProfileRefInputSchema = object({
18392
+ addonId: string(),
18393
+ profileId: string()
18394
+ });
18395
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
18396
+ kind: "mutation",
18397
+ auth: "admin"
18398
+ }), method(ProfileRefInputSchema, _void(), {
18399
+ kind: "mutation",
18400
+ auth: "admin"
18401
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
18402
+ kind: "mutation",
18403
+ auth: "admin"
18404
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
18405
+ selector: LlmDefaultSelectorSchema,
18406
+ profileId: string().nullable()
18407
+ }), _void(), {
18408
+ kind: "mutation",
18409
+ auth: "admin"
18410
+ }), method(object({
18411
+ since: number().optional(),
18412
+ until: number().optional(),
18413
+ consumer: string().optional(),
18414
+ profileId: string().optional()
18415
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
18416
+ nodeId: string(),
18417
+ model: ManagedModelRefSchema
18418
+ }), _void(), {
18419
+ kind: "mutation",
18420
+ auth: "admin"
18421
+ }), method(object({
18422
+ nodeId: string(),
18423
+ file: string()
18424
+ }), _void(), {
18425
+ kind: "mutation",
18426
+ auth: "admin"
18427
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
18428
+ kind: "mutation",
18429
+ auth: "admin"
18430
+ }), method(ProfileRefInputSchema, _void(), {
18431
+ kind: "mutation",
18432
+ auth: "admin"
18433
+ });
18434
+ var LogLevelSchema = _enum([
18435
+ "debug",
18436
+ "info",
18437
+ "warn",
18438
+ "error"
18439
+ ]);
18440
+ var LogEntrySchema = object({
18441
+ timestamp: date(),
18442
+ level: LogLevelSchema,
18443
+ scope: array(string()),
18444
+ message: string(),
18445
+ meta: record(string(), unknown()).optional(),
18446
+ tags: record(string(), string()).optional()
18447
+ });
18448
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18449
+ scope: array(string()).optional(),
18450
+ level: LogLevelSchema.optional(),
18451
+ since: date().optional(),
18452
+ until: date().optional(),
18453
+ limit: number().optional(),
18454
+ tags: record(string(), string()).optional()
18455
+ }), array(LogEntrySchema).readonly());
18456
+ /**
18457
+ * `login-method` — collection cap through which auth addons contribute
18458
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
18459
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
18460
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
18461
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
18462
+ * procedure aggregates them for the unauthenticated login page.
18463
+ *
18464
+ * A contribution is a discriminated union on `kind`:
18465
+ *
18466
+ * - `redirect` — a declarative button. The login page renders a generic
18467
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
18468
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
18469
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
18470
+ * login page needs NO change.
18471
+ *
18472
+ * - `widget` — a Module-Federation widget the login page mounts (via
18473
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
18474
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
18475
+ * mechanism kept for future use; no shipped addon uses it on the login
18476
+ * page (the passkey ceremony below runs natively in the shell instead).
18477
+ *
18478
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
18479
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
18480
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
18481
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
18482
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
18483
+ * fetching any remote code pre-auth. Contribution stays unconditional —
18484
+ * enrollment state is never leaked pre-auth; visibility is a shell
18485
+ * decision.
18486
+ *
18487
+ * Every contribution carries a `stage`:
18488
+ * - `primary` — shown on the first credentials screen (OIDC /
18489
+ * magic-link buttons; a future usernameless passkey).
18490
+ * - `second-factor` — shown AFTER the password leg, gated on the
18491
+ * returned `factors` (passkey-as-2FA today).
18492
+ *
18493
+ * `mount: skip` — the cap is read server-side by the core auth router
18494
+ * (`registry.getCollection('login-method')`), never mounted as its own
18495
+ * tRPC router.
18496
+ */
18497
+ /** When a login method renders in the two-phase login flow. */
18498
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
18499
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
18500
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
18501
+ object({
18502
+ kind: literal("redirect"),
18503
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
18504
+ id: string(),
18505
+ /** Operator-facing button label. */
18506
+ label: string(),
18507
+ /** lucide-react icon name. */
18508
+ icon: string().optional(),
18509
+ /** Addon-owned HTTP route the button navigates to (GET). */
18510
+ startUrl: string(),
18511
+ stage: LoginStageEnum
18512
+ }),
18513
+ object({
18514
+ kind: literal("widget"),
18515
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
18516
+ id: string(),
18517
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
18518
+ addonId: string(),
18519
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
18520
+ bundle: string(),
18521
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
18522
+ remote: WidgetRemoteSchema,
18523
+ stage: LoginStageEnum
18524
+ }),
18525
+ object({
18526
+ kind: literal("passkey"),
18527
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
18528
+ id: string(),
18529
+ /** Operator-facing button label. */
18530
+ label: string(),
18531
+ stage: LoginStageEnum,
18532
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
18533
+ rpId: string(),
18534
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
18535
+ origin: string().nullable()
18536
+ })
18537
+ ]);
18538
+ method(_void(), array(LoginMethodContributionSchema).readonly());
18539
+ var CpuBreakdownSchema = object({
18540
+ total: number(),
18541
+ user: number(),
18542
+ system: number(),
18543
+ irq: number(),
18544
+ nice: number(),
18545
+ loadAvg: tuple([
18546
+ number(),
18547
+ number(),
18548
+ number()
18549
+ ]),
18550
+ cores: number()
18551
+ });
18552
+ var MemoryInfoSchema = object({
18553
+ percent: number(),
18554
+ totalBytes: number(),
18555
+ usedBytes: number(),
18556
+ availableBytes: number(),
18557
+ swapUsedBytes: number(),
18558
+ swapTotalBytes: number()
18559
+ });
18560
+ var DiskIoSnapshotSchema = object({
18561
+ readBytes: number(),
18562
+ writeBytes: number(),
18563
+ readOps: number(),
18564
+ writeOps: number(),
18565
+ timestampMs: number()
18566
+ });
18567
+ var NetworkIoSnapshotSchema = object({
18568
+ rxBytes: number(),
18569
+ txBytes: number(),
18570
+ rxPackets: number(),
18571
+ txPackets: number(),
18572
+ rxErrors: number(),
18573
+ txErrors: number(),
18574
+ timestampMs: number()
18575
+ });
18576
+ var MetricsGpuInfoSchema = object({
18577
+ utilization: number(),
18578
+ model: string(),
18579
+ memoryUsedBytes: number(),
18580
+ memoryTotalBytes: number(),
18581
+ temperature: number().nullable()
18582
+ });
18583
+ var ProcessResourceInfoSchema = object({
18584
+ openFds: number(),
18585
+ threadCount: number(),
18586
+ activeHandles: number(),
18587
+ activeRequests: number()
18588
+ });
18589
+ var PressureAvgsSchema = object({
18590
+ avg10: number(),
18591
+ avg60: number(),
18592
+ avg300: number()
18593
+ });
18594
+ var PressureInfoSchema = object({
18595
+ some: PressureAvgsSchema,
18596
+ full: PressureAvgsSchema.nullable()
18597
+ });
18598
+ var SystemResourceSnapshotSchema = object({
18599
+ cpu: CpuBreakdownSchema,
18600
+ memory: MemoryInfoSchema,
18601
+ gpu: MetricsGpuInfoSchema.nullable(),
18602
+ network: NetworkIoSnapshotSchema,
18603
+ disk: DiskIoSnapshotSchema,
18604
+ pressure: object({
18605
+ cpu: PressureInfoSchema.nullable(),
18606
+ memory: PressureInfoSchema.nullable(),
18607
+ io: PressureInfoSchema.nullable()
18608
+ }),
18609
+ process: ProcessResourceInfoSchema,
18610
+ cpuTemperature: number().nullable(),
18611
+ timestampMs: number()
18612
+ });
18613
+ var DiskSpaceInfoSchema = object({
18614
+ path: string(),
18615
+ totalBytes: number(),
18616
+ usedBytes: number(),
18617
+ availableBytes: number(),
18618
+ percent: number()
18619
+ });
18620
+ var PidResourceStatsSchema = object({
18621
+ pid: number(),
18622
+ cpu: number(),
18623
+ memory: number(),
18624
+ /**
18625
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
18626
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
18627
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
18628
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
18629
+ * Undefined where /proc is unavailable (e.g. macOS).
18630
+ */
18631
+ privateBytes: number().optional(),
18632
+ /**
18633
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18634
+ * code shared copy-on-write across runners. Undefined on macOS.
18635
+ */
18636
+ sharedBytes: number().optional()
18637
+ });
18638
+ var AddonInstanceSchema = object({
18639
+ addonId: string(),
18640
+ nodeId: string(),
18641
+ role: _enum(["hub", "worker"]),
18642
+ pid: number(),
18643
+ state: _enum([
18644
+ "starting",
18645
+ "running",
18646
+ "stopping",
18647
+ "stopped",
18648
+ "crashed"
18649
+ ]),
18650
+ uptimeSec: number()
18651
+ });
18652
+ var NodeProcessSchema = object({
18653
+ pid: number(),
18654
+ ppid: number(),
18655
+ pgid: number(),
18656
+ classification: _enum([
18657
+ "root",
18658
+ "managed",
18659
+ "system",
18660
+ "ghost"
18661
+ ]),
18662
+ /** `$process` addon binding when `managed`, else null. */
18663
+ addonId: string().nullable(),
18664
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
18665
+ nodeId: string().nullable(),
18666
+ /** Truncated command line. */
18667
+ command: string(),
18668
+ cpuPercent: number(),
18669
+ memoryRssBytes: number(),
18670
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18671
+ uptimeSec: number(),
18672
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18673
+ orphaned: boolean()
18674
+ });
18675
+ var KillProcessInputSchema = object({
18676
+ pid: number(),
18677
+ /** Force = SIGKILL. Default is SIGTERM. */
18678
+ force: boolean().optional()
18679
+ });
18680
+ var KillProcessResultSchema = object({
18681
+ success: boolean(),
18682
+ reason: string().optional(),
18683
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18684
+ });
18685
+ var DumpHeapSnapshotInputSchema = object({
18686
+ /** The addon whose runner should dump a heap snapshot. */
18687
+ addonId: string() });
18688
+ var DumpHeapSnapshotResultSchema = object({
18689
+ success: boolean(),
18690
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
18691
+ path: string().optional(),
18692
+ /** Process pid that was signalled. */
18693
+ pid: number().optional(),
18694
+ reason: string().optional()
18695
+ });
18696
+ var SystemMetricsSchema = object({
18697
+ cpuPercent: number(),
18698
+ memoryPercent: number(),
18699
+ memoryUsedMB: number(),
18700
+ memoryTotalMB: number(),
18701
+ diskPercent: number().optional(),
18702
+ temperature: number().optional(),
18703
+ gpuPercent: number().optional(),
18704
+ gpuMemoryPercent: number().optional()
18705
+ });
18706
+ 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, {
18707
+ kind: "mutation",
18708
+ auth: "admin"
18709
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
18710
+ kind: "mutation",
18711
+ auth: "admin"
18712
+ });
18713
+ method(object({
18714
+ sourceUrl: string(),
18715
+ metadata: ModelConvertMetadataSchema,
18716
+ targets: array(ConvertTargetSchema).min(1).readonly(),
18717
+ calibrationRef: string().optional(),
18718
+ sessionId: string().optional()
18719
+ }), ConvertResultSchema, {
18720
+ kind: "mutation",
18721
+ auth: "admin",
18722
+ timeoutMs: 6e5
18723
+ });
18724
+ method(object({
18725
+ nodeId: string(),
18726
+ modelId: string(),
18727
+ format: _enum(MODEL_FORMATS),
18728
+ entry: ModelCatalogEntrySchema
18729
+ }), object({
18730
+ ok: boolean(),
18731
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
18732
+ sha256: string(),
18733
+ bytes: number(),
18734
+ /** The target node's modelsDir the artifact landed in. */
18735
+ path: string()
18736
+ }), {
18737
+ kind: "mutation",
18738
+ auth: "admin"
18739
+ });
18740
+ /**
18741
+ * `mqtt-broker` — broker-registry cap.
18742
+ *
18743
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
18744
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
18745
+ * and (b) the connection details a consumer addon needs to spin up
18746
+ * its OWN `mqtt.js` client.
18747
+ *
18748
+ * Why: pub/sub routing over the system event-bus loses fidelity
18749
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
18750
+ * refcount bookkeeping that addons would rather own themselves. The
18751
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
18752
+ * features anyway — give it the connection config, get out of the way.
18445
18753
  *
18446
18754
  * Consumer flow:
18447
18755
  * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
@@ -18659,398 +18967,594 @@ var NotificationSchema = object({
18659
18967
  });
18660
18968
  /** One declared native severity/priority level for a kind. */
18661
18969
  var TargetKindLevelSchema = object({
18662
- id: string(),
18663
- label: string(),
18664
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
18665
- ordinal: number().int().min(1).max(5).nullable(),
18666
- flags: object({
18667
- critical: boolean().optional(),
18668
- silent: boolean().optional(),
18669
- noPush: boolean().optional()
18670
- }).optional(),
18671
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
18672
- requires: array(string()).optional(),
18673
- description: string().optional()
18674
- });
18675
- /** The full capability block consulted before dispatch. */
18676
- var TargetKindCapsSchema = object({
18677
- attachments: object({
18678
- mediaTypes: array(AttachmentMediaTypeSchema),
18679
- mode: _enum([
18680
- "url",
18681
- "bytes",
18682
- "both"
18683
- ]),
18684
- max: number().int().nonnegative(),
18685
- maxBytes: number().int().positive().optional()
18686
- }),
18687
- /** Max action buttons (0 = none). */
18688
- actions: number().int().nonnegative(),
18689
- levels: array(TargetKindLevelSchema),
18690
- format: array(NotificationFormatSchema),
18691
- clickUrl: boolean(),
18692
- sound: boolean(),
18693
- ttl: boolean(),
18694
- bodyMaxLen: number().int().positive()
18695
- });
18696
- /**
18697
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
18698
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
18699
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
18700
- * the union is large and not meant for runtime validation here; the exported
18701
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
18702
- */
18703
- var ConfigSchemaPassthrough$1 = unknown();
18704
- var TargetKindSchema = object({
18705
- kind: string(),
18706
- label: string(),
18707
- icon: string(),
18708
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
18709
- addonId: string(),
18710
- configSchema: ConfigSchemaPassthrough$1,
18711
- supportsDiscovery: boolean(),
18712
- caps: TargetKindCapsSchema
18713
- });
18714
- /**
18715
- * A persisted target. `config` holds secrets; providers REDACT secret fields
18716
- * (return a presence marker only) when serving `listTargets` — never
18717
- * round-trip a stored secret to the UI.
18718
- */
18719
- var TargetSchema = object({
18720
- id: string(),
18721
- name: string(),
18722
- kind: string(),
18723
- addonId: string(),
18724
- enabled: boolean(),
18725
- config: record(string(), unknown())
18726
- });
18727
- /** A discovery-surfaced candidate (config is partial + non-secret). */
18728
- var DiscoveredTargetSchema = object({
18729
- kind: string(),
18730
- suggestedName: string(),
18731
- config: record(string(), unknown())
18732
- });
18733
- /** The degrade engine's report — what was resolved / dropped / degraded. */
18734
- var RenderedAsSchema = object({
18735
- level: string(),
18736
- format: NotificationFormatSchema,
18737
- attachmentsSent: number().int().nonnegative(),
18738
- actionsSent: number().int().nonnegative(),
18739
- truncated: boolean(),
18740
- dropped: array(string())
18741
- });
18742
- var SendResultSchema = object({
18743
- success: boolean(),
18744
- error: string().optional(),
18745
- renderedAs: RenderedAsSchema.optional()
18746
- });
18747
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
18748
- var TestResultSchema = SendResultSchema;
18749
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
18750
- kind: string(),
18751
- config: record(string(), unknown()).optional()
18752
- }), array(DiscoveredTargetSchema)), method(object({
18753
- targetId: string(),
18754
- notification: NotificationSchema
18755
- }), SendResultSchema, { kind: "mutation" }), method(object({
18756
- targetId: string(),
18757
- sample: NotificationSchema.optional()
18758
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
18759
- targetId: string(),
18760
- enabled: boolean()
18761
- }), _void(), { kind: "mutation" });
18762
- /**
18763
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18764
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18765
- * caps stay wire-compatible without a circular cap→cap import.
18766
- *
18767
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
18768
- * every transport tier structurally, and failed calls still write usage rows.
18769
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18770
- */
18771
- var LlmUsageSchema = object({
18772
- inputTokens: number(),
18773
- outputTokens: number()
18774
- });
18775
- var LlmErrorCodeSchema = _enum([
18776
- "timeout",
18777
- "rate-limited",
18778
- "auth",
18779
- "refusal",
18780
- "bad-request",
18781
- "unavailable",
18782
- "no-profile",
18783
- "budget-exceeded",
18784
- "adapter-error"
18785
- ]);
18786
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18787
- ok: literal(true),
18788
- text: string(),
18789
- model: string(),
18790
- usage: LlmUsageSchema,
18791
- truncated: boolean(),
18792
- latencyMs: number()
18793
- }), object({
18794
- ok: literal(false),
18795
- code: LlmErrorCodeSchema,
18796
- message: string(),
18797
- retryAfterMs: number().optional()
18798
- })]);
18799
- /**
18800
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18801
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18802
- * notification-output.cap.ts:27-31 precedents).
18803
- */
18804
- var LlmImageSchema = object({
18805
- bytes: _instanceof(Uint8Array),
18806
- mimeType: string()
18807
- });
18808
- var LlmGenerateBaseInputSchema = object({
18809
- /** Collection routing (the notification-output posture). */
18810
- addonId: string().optional(),
18811
- /** Explicit profile; else the resolution chain (spec §3). */
18812
- profileId: string().optional(),
18813
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18814
- consumer: string(),
18815
- system: string().optional(),
18816
- /** v1: single-turn. `messages[]` is a v2 additive field. */
18817
- prompt: string(),
18818
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18819
- jsonSchema: record(string(), unknown()).optional(),
18820
- /** Per-call override of the profile default. */
18821
- maxTokens: number().int().positive().optional(),
18822
- temperature: number().optional()
18823
- });
18824
- /**
18825
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18826
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18827
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18828
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18829
- * this only through the `llm` cap's methods.
18830
- *
18831
- * One running llama-server child per node in v1 (models are RAM-heavy).
18832
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18833
- * watchdog — operator decision #3).
18834
- */
18835
- var ManagedModelRefSchema = discriminatedUnion("kind", [
18836
- object({
18837
- kind: literal("catalog"),
18838
- catalogId: string()
18839
- }),
18840
- object({
18841
- kind: literal("url"),
18842
- url: string(),
18843
- sha256: string().optional()
18844
- }),
18845
- object({
18846
- kind: literal("path"),
18847
- path: string()
18848
- })
18849
- ]);
18850
- var ManagedRuntimeConfigSchema = object({
18851
- /** WHERE the runtime lives — hub or any agent. */
18852
- nodeId: string(),
18853
- /** Closed for v1; 'ollama' is a v2 candidate. */
18854
- engine: _enum(["llama-cpp"]),
18855
- model: ManagedModelRefSchema,
18856
- contextSize: number().int().default(4096),
18857
- /** 0 = CPU-only. */
18858
- gpuLayers: number().int().default(0),
18859
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18860
- threads: number().int().optional(),
18861
- /** Concurrent slots. */
18862
- parallel: number().int().default(1),
18863
- /** Else lazy: first generate boots it. */
18864
- autoStart: boolean().default(false),
18865
- /** 0 = never; frees RAM after quiet periods. */
18866
- idleStopMinutes: number().int().default(30)
18867
- });
18868
- var LlmRuntimeStatusSchema = object({
18869
- /** Status is ALWAYS node-qualified. */
18870
- nodeId: string(),
18871
- state: _enum([
18872
- "stopped",
18873
- "downloading",
18874
- "starting",
18875
- "ready",
18876
- "crashed",
18877
- "failed"
18878
- ]),
18879
- pid: number().optional(),
18880
- port: number().optional(),
18881
- modelPath: string().optional(),
18882
- modelId: string().optional(),
18883
- downloadProgress: number().min(0).max(1).optional(),
18884
- lastError: string().optional(),
18885
- crashesInWindow: number(),
18886
- /** Child RSS (sampled best-effort). */
18887
- memoryBytes: number().optional(),
18888
- vramBytes: number().optional()
18970
+ id: string(),
18971
+ label: string(),
18972
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
18973
+ ordinal: number().int().min(1).max(5).nullable(),
18974
+ flags: object({
18975
+ critical: boolean().optional(),
18976
+ silent: boolean().optional(),
18977
+ noPush: boolean().optional()
18978
+ }).optional(),
18979
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
18980
+ requires: array(string()).optional(),
18981
+ description: string().optional()
18889
18982
  });
18890
- var LlmNodeModelSchema = object({
18891
- file: string(),
18892
- sizeBytes: number(),
18893
- catalogId: string().optional(),
18894
- installedAt: number().optional()
18983
+ /** The full capability block consulted before dispatch. */
18984
+ var TargetKindCapsSchema = object({
18985
+ attachments: object({
18986
+ mediaTypes: array(AttachmentMediaTypeSchema),
18987
+ mode: _enum([
18988
+ "url",
18989
+ "bytes",
18990
+ "both"
18991
+ ]),
18992
+ max: number().int().nonnegative(),
18993
+ maxBytes: number().int().positive().optional()
18994
+ }),
18995
+ /** Max action buttons (0 = none). */
18996
+ actions: number().int().nonnegative(),
18997
+ levels: array(TargetKindLevelSchema),
18998
+ format: array(NotificationFormatSchema),
18999
+ clickUrl: boolean(),
19000
+ sound: boolean(),
19001
+ ttl: boolean(),
19002
+ bodyMaxLen: number().int().positive()
18895
19003
  });
18896
- var LlmRuntimeDiskUsageSchema = object({
18897
- nodeId: string(),
18898
- modelsBytes: number(),
18899
- freeBytes: number().optional()
19004
+ /**
19005
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
19006
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
19007
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
19008
+ * the union is large and not meant for runtime validation here; the exported
19009
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
19010
+ */
19011
+ var ConfigSchemaPassthrough = unknown();
19012
+ var TargetKindSchema = object({
19013
+ kind: string(),
19014
+ label: string(),
19015
+ icon: string(),
19016
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
19017
+ addonId: string(),
19018
+ configSchema: ConfigSchemaPassthrough,
19019
+ supportsDiscovery: boolean(),
19020
+ caps: TargetKindCapsSchema
18900
19021
  });
18901
- method(LlmGenerateBaseInputSchema.extend({
18902
- images: array(LlmImageSchema).optional(),
18903
- runtime: ManagedRuntimeConfigSchema,
18904
- /** The managed profile's timeout, threaded by the hub provider. */
18905
- timeoutMs: number().int().positive().optional()
18906
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18907
- kind: "mutation",
18908
- auth: "admin"
18909
- }), method(object({}), _void(), {
18910
- kind: "mutation",
18911
- auth: "admin"
18912
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18913
- kind: "mutation",
18914
- auth: "admin"
18915
- }), method(object({ file: string() }), _void(), {
18916
- kind: "mutation",
18917
- auth: "admin"
18918
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18919
19022
  /**
18920
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18921
- * methods concat-fan across providers; single-row methods route to ONE
18922
- * provider by the `addonId` in the call input (the notification-output
18923
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18924
- * (hub-placed); the cap stays open for future providers.
18925
- *
18926
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18927
- * `apiKey` is a password field — providers REDACT it on read and merge on
18928
- * write; a stored key NEVER round-trips to a client.
19023
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
19024
+ * (return a presence marker only) when serving `listTargets` — never
19025
+ * round-trip a stored secret to the UI.
18929
19026
  */
18930
- var LlmProfileKindSchema = _enum([
18931
- "openai-compatible",
18932
- "openai",
18933
- "anthropic",
18934
- "google",
18935
- "managed-local"
18936
- ]);
18937
- var LlmProfileSchema = object({
19027
+ var TargetSchema = object({
18938
19028
  id: string(),
18939
19029
  name: string(),
18940
- kind: LlmProfileKindSchema,
18941
- /** Stamped by the provider — keeps the fanned catalog routable. */
19030
+ kind: string(),
18942
19031
  addonId: string(),
18943
19032
  enabled: boolean(),
18944
- /** Vendor model id, or the managed runtime's loaded model. */
18945
- model: string(),
18946
- /** Required for openai-compatible; override for cloud kinds. */
18947
- baseUrl: string().optional(),
18948
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
18949
- apiKey: string().optional(),
18950
- supportsVision: boolean(),
18951
- temperature: number().min(0).max(2).optional(),
18952
- maxTokens: number().int().positive().optional(),
18953
- timeoutMs: number().int().positive().default(6e4),
18954
- extraHeaders: record(string(), string()).optional(),
18955
- /** kind === 'managed-local' only (spec §4). */
18956
- runtime: ManagedRuntimeConfigSchema.optional()
19033
+ config: record(string(), unknown())
18957
19034
  });
18958
- /** ConfigUISchema tree passed through untyped on the wire (the
18959
- * notification-output `ConfigSchemaPassthrough` precedent at
18960
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
18961
- var ConfigSchemaPassthrough = unknown();
18962
- var LlmProfileKindDescriptorSchema = object({
18963
- kind: LlmProfileKindSchema,
18964
- label: string(),
18965
- icon: string(),
18966
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
18967
- addonId: string(),
18968
- configSchema: ConfigSchemaPassthrough
19035
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
19036
+ var DiscoveredTargetSchema = object({
19037
+ kind: string(),
19038
+ suggestedName: string(),
19039
+ config: record(string(), unknown())
18969
19040
  });
18970
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
18971
- var LlmDefaultSchema = object({
18972
- selector: LlmDefaultSelectorSchema,
18973
- profileId: string()
19041
+ /** The degrade engine's report what was resolved / dropped / degraded. */
19042
+ var RenderedAsSchema = object({
19043
+ level: string(),
19044
+ format: NotificationFormatSchema,
19045
+ attachmentsSent: number().int().nonnegative(),
19046
+ actionsSent: number().int().nonnegative(),
19047
+ truncated: boolean(),
19048
+ dropped: array(string())
18974
19049
  });
18975
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
18976
- var LlmUsageRollupSchema = object({
18977
- day: string(),
18978
- consumer: string(),
18979
- profileId: string(),
18980
- calls: number(),
18981
- okCalls: number(),
18982
- errorCalls: number(),
18983
- inputTokens: number(),
18984
- outputTokens: number(),
18985
- avgLatencyMs: number()
19050
+ var SendResultSchema = object({
19051
+ success: boolean(),
19052
+ error: string().optional(),
19053
+ renderedAs: RenderedAsSchema.optional()
18986
19054
  });
18987
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
18988
- var ManagedModelCatalogEntrySchema = object({
19055
+ /** Same shape as SendResult kept as a distinct name for the test panel. */
19056
+ var TestResultSchema = SendResultSchema;
19057
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
19058
+ kind: string(),
19059
+ config: record(string(), unknown()).optional()
19060
+ }), array(DiscoveredTargetSchema)), method(object({
19061
+ targetId: string(),
19062
+ notification: NotificationSchema
19063
+ }), SendResultSchema, { kind: "mutation" }), method(object({
19064
+ targetId: string(),
19065
+ sample: NotificationSchema.optional()
19066
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
19067
+ targetId: string(),
19068
+ enabled: boolean()
19069
+ }), _void(), { kind: "mutation" });
19070
+ /**
19071
+ * notification-rules — the Notification Center rule surface (P1 core).
19072
+ *
19073
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
19074
+ * (operator decisions D-1/D-2/D-3 are binding):
19075
+ *
19076
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
19077
+ * `notification-center` module), hooked on the durable persistence
19078
+ * moments (object-event insert, TrackCloser.closeExpired) with a
19079
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
19080
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
19081
+ * FIRST persisted detection matching the conditions (per-track dedup,
19082
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
19083
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
19084
+ * - DISPATCH stays behind `notification-output` (rules reference targets
19085
+ * by id; per-backend params are a passthrough blob capped by the
19086
+ * target kind's own caps/degrade engine).
19087
+ *
19088
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
19089
+ * server-injected caller identity — the first `caller: 'required'`
19090
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
19091
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
19092
+ * windows, and the optional label/identity/plate matchers. User rules,
19093
+ * private zones, per-recipient fan-out and the wider condition table are
19094
+ * P2+ (see spec §7).
19095
+ *
19096
+ * All schemas here are the single source of truth — `NcRule` etc. are
19097
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
19098
+ * schema/interface drift is explicitly not repeated).
19099
+ */
19100
+ /**
19101
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
19102
+ * The value maps 1:1 onto the evaluated record kind:
19103
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
19104
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
19105
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
19106
+ * change of a LINKED device, one row per linked camera)
19107
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
19108
+ * delivery / pick-up)
19109
+ *
19110
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
19111
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
19112
+ * this one field keeps the schema additive — a rule still declares exactly
19113
+ * one trigger.
19114
+ */
19115
+ var NcDeliverySchema = _enum([
19116
+ "immediate",
19117
+ "track-end",
19118
+ "device-event",
19119
+ "package-event"
19120
+ ]);
19121
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
19122
+ var NcScheduleSchema = object({
19123
+ windows: array(object({
19124
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
19125
+ days: array(number().int().min(0).max(6)).min(1),
19126
+ startMinute: number().int().min(0).max(1439),
19127
+ endMinute: number().int().min(0).max(1439)
19128
+ })).min(1),
19129
+ /** IANA timezone; default = hub host timezone. */
19130
+ timezone: string().optional(),
19131
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
19132
+ invert: boolean().optional()
19133
+ });
19134
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
19135
+ var NcPlateMatcherSchema = object({
19136
+ values: array(string().min(1)).min(1),
19137
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
19138
+ maxDistance: number().int().min(0).max(3).default(1)
19139
+ });
19140
+ /**
19141
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
19142
+ * occupancy edge for a device — optionally narrowed to a single admin
19143
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
19144
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
19145
+ * - `became-free` — count crossed ≥ `count` → below it
19146
+ * - `>=` / `<=` — count is at/over or at/under `count`
19147
+ * `sustainSeconds` requires the condition hold continuously that long
19148
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
19149
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
19150
+ * the condition never matches. Confirmed edge-state survives addon restarts
19151
+ * (declared SQLite collection, reseeded on boot).
19152
+ */
19153
+ var NcOccupancyConditionSchema = object({
19154
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
19155
+ zoneId: string().optional(),
19156
+ /** Object class to count; absent = any class. */
19157
+ className: string().optional(),
19158
+ op: _enum([
19159
+ "became-occupied",
19160
+ "became-free",
19161
+ ">=",
19162
+ "<="
19163
+ ]).default("became-occupied"),
19164
+ count: number().int().min(0).default(1),
19165
+ sustainSeconds: number().int().min(0).max(3600).default(15)
19166
+ });
19167
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
19168
+ var NcZoneConditionSchema = object({
19169
+ ids: array(string().min(1)).min(1),
19170
+ /** Quantifier over `ids` — at least one / every one visited. */
19171
+ match: _enum(["any", "all"]).default("any")
19172
+ });
19173
+ /**
19174
+ * The P1 condition set — a flat AND of groups; absent group = pass;
19175
+ * membership lists are OR within the list (spec §2.3).
19176
+ */
19177
+ var NcConditionsSchema = object({
19178
+ /** Device scope — absent = all devices. */
19179
+ devices: array(number()).optional(),
19180
+ /** Detector class names (any overlap with the record's class set). */
19181
+ classes: array(string().min(1)).optional(),
19182
+ /** Veto classes — any overlap fails the rule. */
19183
+ classesExclude: array(string().min(1)).optional(),
19184
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
19185
+ minConfidence: number().min(0).max(1).optional(),
19186
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
19187
+ zones: NcZoneConditionSchema.optional(),
19188
+ /** Veto zones — any hit fails the rule. */
19189
+ zonesExclude: array(string().min(1)).optional(),
19190
+ /**
19191
+ * Exact (case-insensitive) match on the record's collapsed `label`
19192
+ * (identity name / plate text / subclass).
19193
+ */
19194
+ labelEquals: array(string().min(1)).optional(),
19195
+ /**
19196
+ * Identity matcher. P1 boundary: matched against the record's collapsed
19197
+ * `label` (the identity display name propagated by the face pipeline) —
19198
+ * identity-ID matching rides in P2 when identity ids reach the record.
19199
+ */
19200
+ identities: array(string().min(1)).optional(),
19201
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
19202
+ plates: NcPlateMatcherSchema.optional(),
19203
+ /**
19204
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
19205
+ * Same P1 boundary: matched against the record's collapsed `label` (the
19206
+ * identity display name). A record with NO label passes (nothing to
19207
+ * exclude), unlike the include variant which fails on an absent label.
19208
+ */
19209
+ identitiesExclude: array(string().min(1)).optional(),
19210
+ /**
19211
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
19212
+ * TRACK-END only: importance is scored at track close, so it does not exist
19213
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
19214
+ * close the value is threaded via the close-time info (the `Track` clone is
19215
+ * captured before the DB row is updated, so it would otherwise read stale).
19216
+ * Fails when the record carries no importance (never guess quality — the
19217
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
19218
+ */
19219
+ minImportance: number().min(0).max(1).optional(),
19220
+ /**
19221
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
19222
+ * TRACK-END only: an `immediate` / object-event subject has no closed
19223
+ * lifespan, so a dwell condition never matches immediate delivery
19224
+ * (documented choice — the object-event record carries no `firstSeen`,
19225
+ * so dwell cannot be computed from what the subject actually carries).
19226
+ */
19227
+ minDwellSeconds: number().min(0).optional(),
19228
+ /**
19229
+ * Detection provenance filter. `any` (default / absent) matches every
19230
+ * source; otherwise the subject's source must equal it. Legacy records
19231
+ * with no stamped source are treated as `pipeline`. The union spans both
19232
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
19233
+ * tracks carry `sensor`.
19234
+ */
19235
+ source: _enum([
19236
+ "pipeline",
19237
+ "onboard",
19238
+ "sensor",
19239
+ "any"
19240
+ ]).optional(),
19241
+ /**
19242
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
19243
+ * detector `minConfidence` (that gates the object-detection score; this
19244
+ * gates the recognition/OCR match score). Fails when the subject carries
19245
+ * no label-match confidence (never guess). TRACK-END only: the confidence
19246
+ * lives on the recognition result and reaches the subject at track close.
19247
+ *
19248
+ * What it measures precisely (plumbed at track close — the closer threads
19249
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
19250
+ * `importance`): the BEST recognition match confidence observed for the
19251
+ * label the track carries at close — for a face, the peak cosine similarity
19252
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
19253
+ * for a plate, the peak OCR read score of the best-held plate
19254
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
19255
+ * one track the higher of the two is used. A track that ended with no
19256
+ * confident identity/plate match carries no value, so the condition fails
19257
+ * closed for it (an un-recognized subject).
19258
+ */
19259
+ minLabelConfidence: number().min(0).max(1).optional(),
19260
+ /**
19261
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
19262
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
19263
+ * against the token carried on the device-event subject (extracted from the
19264
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
19265
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
19266
+ * eventType, so gate those with {@link sensorKinds} instead.
19267
+ */
19268
+ eventTypeTokens: array(string().min(1)).optional(),
19269
+ /**
19270
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
19271
+ * `contact`, `button`, `device-event`) — matched against the persisted
19272
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
19273
+ */
19274
+ sensorKinds: array(string().min(1)).optional(),
19275
+ /**
19276
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
19277
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
19278
+ * when the subject's phase does not match (a subject always carries a phase
19279
+ * on the package-event trigger).
19280
+ */
19281
+ packagePhase: _enum([
19282
+ "delivered",
19283
+ "picked-up",
19284
+ "both"
19285
+ ]).optional(),
19286
+ /**
19287
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
19288
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
19289
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
19290
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
19291
+ */
19292
+ customZones: array(MaskPolygonShapeSchema).optional(),
19293
+ /**
19294
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
19295
+ * (optionally zone/class-scoped) occupancy count crosses the configured
19296
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
19297
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
19298
+ */
19299
+ occupancy: NcOccupancyConditionSchema.optional()
19300
+ });
19301
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
19302
+ var NcRuleTargetSchema = object({
19303
+ /** `notification-output` Target id. */
19304
+ targetId: string().min(1),
19305
+ /**
19306
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
19307
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
19308
+ * degrade engine drops what the backend can't render.
19309
+ */
19310
+ params: record(string(), unknown()).optional()
19311
+ });
19312
+ /**
19313
+ * Media attachment policy (P1 still-image subset).
19314
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
19315
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
19316
+ * matched on identities attaches the subject's `faceCrop`, one matched on
19317
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
19318
+ * (or when the specific crop is missing) degrades to `best`, then
19319
+ * `keyFrame`, then no attachment — never delaying the send. The matched
19320
+ * condition summary is frozen on the outbox row at enqueue (like the rule
19321
+ * name), so the choice never drifts from the record that fired it.
19322
+ * - `keyFrame` — the clean scene frame (no subject box).
19323
+ * - `none` — no attachment.
19324
+ */
19325
+ var NcMediaPolicySchema = object({ attach: _enum([
19326
+ "best",
19327
+ "best-matching",
19328
+ "keyFrame",
19329
+ "none"
19330
+ ]).default("best") });
19331
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
19332
+ var NcThrottleSchema = object({
19333
+ cooldownSec: number().int().min(0).max(86400).default(60),
19334
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
19335
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
19336
+ });
19337
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
19338
+ var NcRuleInputSchema = object({
19339
+ name: string().min(1).max(200),
19340
+ enabled: boolean().default(true),
19341
+ delivery: NcDeliverySchema,
19342
+ conditions: NcConditionsSchema.default({}),
19343
+ schedule: NcScheduleSchema.optional(),
19344
+ targets: array(NcRuleTargetSchema).min(1),
19345
+ media: NcMediaPolicySchema.default({ attach: "best" }),
19346
+ throttle: NcThrottleSchema.default({
19347
+ cooldownSec: 60,
19348
+ scope: "rule-device"
19349
+ }),
19350
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
19351
+ template: object({
19352
+ title: string().max(500).optional(),
19353
+ body: string().max(2e3).optional()
19354
+ }).optional(),
19355
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
19356
+ priority: number().int().min(1).max(5).default(3),
19357
+ /**
19358
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
19359
+ * behaviour, visible to all, read-only in the viewer). Present = personal
19360
+ * rule owned by this userId. Server-stamped; never trusted from a client.
19361
+ */
19362
+ ownerUserId: string().optional()
19363
+ });
19364
+ /**
19365
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
19366
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
19367
+ * NOT a client-authored input field (it lives on the persisted rule, not the
19368
+ * input), so it is added here explicitly to let the store's per-target opt-out
19369
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
19370
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
19371
+ * `updateRule` patch.
19372
+ */
19373
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
19374
+ /** A persisted rule. */
19375
+ var NcRuleSchema = NcRuleInputSchema.extend({
19376
+ id: string(),
19377
+ /** userId of the admin who created the rule (server-stamped caller). */
19378
+ createdBy: string(),
19379
+ createdAt: number(),
19380
+ updatedAt: number(),
19381
+ /**
19382
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
19383
+ * send time. Only a target's OWNER may add/remove its id (server-checked
19384
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
19385
+ */
19386
+ disabledTargetIds: array(string()).default([])
19387
+ });
19388
+ var NcTestResultSchema = object({
19389
+ recordId: string(),
19390
+ recordKind: _enum([
19391
+ "object-event",
19392
+ "track",
19393
+ "device-event",
19394
+ "package-event"
19395
+ ]),
19396
+ deviceId: number(),
19397
+ timestamp: number(),
19398
+ wouldFire: boolean(),
19399
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
19400
+ failedCondition: string().optional(),
19401
+ className: string().optional(),
19402
+ label: string().optional()
19403
+ });
19404
+ var NcConditionDescriptorSchema = object({
19405
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
18989
19406
  id: string(),
19407
+ group: _enum([
19408
+ "scope",
19409
+ "class",
19410
+ "zones",
19411
+ "quality",
19412
+ "label",
19413
+ "schedule",
19414
+ "device",
19415
+ "package",
19416
+ "occupancy"
19417
+ ]),
18990
19418
  label: string(),
18991
- family: string(),
18992
- purpose: _enum(["text", "vision"]),
18993
- url: string(),
18994
- sha256: string(),
18995
- sizeBytes: number(),
18996
- quantization: string(),
18997
- /** Load-time guidance shown in the picker. */
18998
- minRamBytes: number(),
18999
- contextSizeDefault: number().int(),
19000
- /** Vision models: companion projector file. */
19001
- mmprojUrl: string().optional()
19419
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
19420
+ valueType: _enum([
19421
+ "deviceIdList",
19422
+ "stringList",
19423
+ "number01",
19424
+ "number",
19425
+ "sourceSelect",
19426
+ "zoneSelection",
19427
+ "zoneIdList",
19428
+ "schedule",
19429
+ "plateMatcher",
19430
+ "packagePhase",
19431
+ "polygonDraw",
19432
+ "occupancy"
19433
+ ]),
19434
+ operator: _enum([
19435
+ "in",
19436
+ "notIn",
19437
+ "anyOf",
19438
+ "allOf",
19439
+ "gte",
19440
+ "fuzzyIn",
19441
+ "withinSchedule"
19442
+ ]),
19443
+ /** Which delivery kinds the condition applies to. */
19444
+ appliesTo: array(NcDeliverySchema),
19445
+ phase: string(),
19446
+ description: string().optional()
19002
19447
  });
19003
- var LlmRuntimeNodeSchema = object({
19004
- nodeId: string(),
19005
- reachable: boolean(),
19006
- status: LlmRuntimeStatusSchema.optional(),
19007
- disk: LlmRuntimeDiskUsageSchema.optional(),
19008
- error: string().optional()
19448
+ /**
19449
+ * The delivery lifecycle status of a history row — a straight read of the
19450
+ * durable outbox row's own status (single source of truth):
19451
+ * - `pending` — enqueued, in-flight or retrying with backoff
19452
+ * - `sent` — delivered (terminal)
19453
+ * - `dead` — dead-lettered after exhausting retries / a permanent
19454
+ * backend rejection / a deleted target (terminal; carries
19455
+ * the failure `error`)
19456
+ *
19457
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
19458
+ * user dimension (quiet hours / snooze) and are additive when they land.
19459
+ */
19460
+ var NcHistoryStatusSchema = _enum([
19461
+ "pending",
19462
+ "sent",
19463
+ "dead"
19464
+ ]);
19465
+ /** The evaluated record kind a history row descends from (one per trigger). */
19466
+ var NcHistoryRecordKindSchema = _enum([
19467
+ "object-event",
19468
+ "track-end",
19469
+ "device-event",
19470
+ "package-event"
19471
+ ]);
19472
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
19473
+ var NcHistorySubjectSchema = object({
19474
+ className: string(),
19475
+ label: string().optional(),
19476
+ confidence: number().optional(),
19477
+ zones: array(string()),
19478
+ timestamp: number()
19479
+ });
19480
+ /**
19481
+ * One delivery-history row. This is a read-only VIEW over the durable
19482
+ * outbox row (single source of truth — the same row the drain loop drives;
19483
+ * NO second write path, so history can never drift from delivery state).
19484
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
19485
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
19486
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
19487
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
19488
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
19489
+ * P1 (admin scope only).
19490
+ */
19491
+ var NcHistoryEntrySchema = object({
19492
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
19493
+ id: string(),
19494
+ ruleId: string(),
19495
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
19496
+ ruleName: string(),
19497
+ /** The rule urgency/trigger that produced this delivery. */
19498
+ delivery: NcDeliverySchema,
19499
+ targetId: string(),
19500
+ deviceId: number(),
19501
+ recordKind: NcHistoryRecordKindSchema,
19502
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
19503
+ recordId: string(),
19504
+ /** Present for track-scoped deliveries (object-event / track-end). */
19505
+ trackId: string().optional(),
19506
+ status: NcHistoryStatusSchema,
19507
+ /** Delivery attempts made so far. */
19508
+ attempts: number().int(),
19509
+ /** Fire time (outbox enqueue). */
19510
+ createdAt: number(),
19511
+ /** Last transition time (terminal for sent / dead). */
19512
+ updatedAt: number(),
19513
+ /** Failure detail — present on a `dead` row. */
19514
+ error: string().optional(),
19515
+ subject: NcHistorySubjectSchema
19009
19516
  });
19010
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
19011
- var ProfileRefInputSchema = object({
19012
- addonId: string(),
19013
- profileId: string()
19517
+ /**
19518
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
19519
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
19520
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
19521
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
19522
+ */
19523
+ var NcHistoryFilterSchema = object({
19524
+ ruleId: string().optional(),
19525
+ deviceId: number().optional(),
19526
+ status: NcHistoryStatusSchema.optional(),
19527
+ since: number().optional(),
19528
+ until: number().optional(),
19529
+ limit: number().int().min(1).max(500).default(100)
19014
19530
  });
19015
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
19016
- kind: "mutation",
19017
- auth: "admin"
19018
- }), method(ProfileRefInputSchema, _void(), {
19531
+ 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 }), {
19019
19532
  kind: "mutation",
19020
- auth: "admin"
19021
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
19533
+ auth: "admin",
19534
+ caller: "required"
19535
+ }), method(object({
19536
+ ruleId: string(),
19537
+ patch: NcRulePatchSchema
19538
+ }), object({ rule: NcRuleSchema }), {
19022
19539
  kind: "mutation",
19023
- auth: "admin"
19024
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
19025
- selector: LlmDefaultSelectorSchema,
19026
- profileId: string().nullable()
19027
- }), _void(), {
19540
+ auth: "admin",
19541
+ caller: "required"
19542
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
19028
19543
  kind: "mutation",
19029
19544
  auth: "admin"
19030
19545
  }), method(object({
19031
- since: number().optional(),
19032
- until: number().optional(),
19033
- consumer: string().optional(),
19034
- profileId: string().optional()
19035
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
19036
- nodeId: string(),
19037
- model: ManagedModelRefSchema
19038
- }), _void(), {
19546
+ ruleId: string(),
19547
+ enabled: boolean()
19548
+ }), object({ success: literal(true) }), {
19039
19549
  kind: "mutation",
19040
19550
  auth: "admin"
19041
19551
  }), method(object({
19042
- nodeId: string(),
19043
- file: string()
19044
- }), _void(), {
19045
- kind: "mutation",
19046
- auth: "admin"
19047
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
19048
- kind: "mutation",
19049
- auth: "admin"
19050
- }), method(ProfileRefInputSchema, _void(), {
19552
+ rule: NcRuleInputSchema,
19553
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
19554
+ }), object({ results: array(NcTestResultSchema) }), {
19051
19555
  kind: "mutation",
19052
19556
  auth: "admin"
19053
- });
19557
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
19054
19558
  /**
19055
19559
  * Zod schemas for persisted record types.
19056
19560
  *
@@ -19736,7 +20240,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19736
20240
  }), method(object({
19737
20241
  eventId: string(),
19738
20242
  kind: MediaFileKindEnum.optional()
19739
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
20243
+ }), array(MediaFileSchema).readonly()), method(object({
20244
+ trackId: string(),
20245
+ kinds: array(MediaFileKindEnum).optional()
20246
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
19740
20247
  deviceId: number(),
19741
20248
  timestamp: number(),
19742
20249
  frameWidth: number(),
@@ -19757,76 +20264,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19757
20264
  eventId: string(),
19758
20265
  timestamp: number()
19759
20266
  });
19760
- /**
19761
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
19762
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
19763
- * caps into per-camera event-kind descriptors.
19764
- *
19765
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
19766
- * is NOT duplicated here — every entry is derived from the single
19767
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
19768
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
19769
- * control cap means adding one line here (and a taxonomy entry); the anti-
19770
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
19771
- * eventful cap is missing.
19772
- */
19773
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
19774
- var LEGACY_ICON = {
19775
- motion: "motion",
19776
- audio: "audio",
19777
- person: "person",
19778
- vehicle: "vehicle",
19779
- animal: "animal",
19780
- package: "package",
19781
- door: "door",
19782
- pir: "pir",
19783
- smoke: "smoke",
19784
- water: "water",
19785
- button: "button",
19786
- generic: "generic",
19787
- gas: "smoke",
19788
- vibration: "generic",
19789
- tamper: "generic",
19790
- presence: "person",
19791
- lock: "generic",
19792
- siren: "generic",
19793
- switch: "generic",
19794
- doorbell: "button"
19795
- };
19796
- function legacyIcon(iconId) {
19797
- return LEGACY_ICON[iconId] ?? "generic";
19798
- }
19799
- /**
19800
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
19801
- * The anti-drift guard cross-checks this against the eventful caps declared
19802
- * in `packages/types/src/capabilities/*.cap.ts`.
19803
- */
19804
- var CAP_TO_KIND = {
19805
- contact: "contact",
19806
- motion: "motion-sensor",
19807
- smoke: "smoke",
19808
- flood: "flood",
19809
- gas: "gas",
19810
- "carbon-monoxide": "carbon-monoxide",
19811
- vibration: "vibration",
19812
- tamper: "tamper",
19813
- presence: "presence",
19814
- "enum-sensor": "enum-sensor",
19815
- "event-emitter": "device-event",
19816
- "lock-control": "lock",
19817
- switch: "switch",
19818
- button: "button",
19819
- doorbell: "doorbell"
19820
- };
19821
- function buildDescriptor(capName, kind) {
19822
- const t = EVENT_TAXONOMY[kind];
19823
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
19824
- return {
19825
- ...t,
19826
- icon: legacyIcon(t.iconId)
19827
- };
19828
- }
19829
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
19830
20267
  var CameraPipelineConfigSchema = object({
19831
20268
  engine: PipelineEngineChoiceSchema.optional(),
19832
20269
  steps: array(PipelineStepInputSchema).readonly(),
@@ -20312,6 +20749,76 @@ method(object({
20312
20749
  auth: "admin"
20313
20750
  });
20314
20751
  /**
20752
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
20753
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
20754
+ * caps into per-camera event-kind descriptors.
20755
+ *
20756
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
20757
+ * is NOT duplicated here — every entry is derived from the single
20758
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
20759
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
20760
+ * control cap means adding one line here (and a taxonomy entry); the anti-
20761
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
20762
+ * eventful cap is missing.
20763
+ */
20764
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
20765
+ var LEGACY_ICON = {
20766
+ motion: "motion",
20767
+ audio: "audio",
20768
+ person: "person",
20769
+ vehicle: "vehicle",
20770
+ animal: "animal",
20771
+ package: "package",
20772
+ door: "door",
20773
+ pir: "pir",
20774
+ smoke: "smoke",
20775
+ water: "water",
20776
+ button: "button",
20777
+ generic: "generic",
20778
+ gas: "smoke",
20779
+ vibration: "generic",
20780
+ tamper: "generic",
20781
+ presence: "person",
20782
+ lock: "generic",
20783
+ siren: "generic",
20784
+ switch: "generic",
20785
+ doorbell: "button"
20786
+ };
20787
+ function legacyIcon(iconId) {
20788
+ return LEGACY_ICON[iconId] ?? "generic";
20789
+ }
20790
+ /**
20791
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
20792
+ * The anti-drift guard cross-checks this against the eventful caps declared
20793
+ * in `packages/types/src/capabilities/*.cap.ts`.
20794
+ */
20795
+ var CAP_TO_KIND = {
20796
+ contact: "contact",
20797
+ motion: "motion-sensor",
20798
+ smoke: "smoke",
20799
+ flood: "flood",
20800
+ gas: "gas",
20801
+ "carbon-monoxide": "carbon-monoxide",
20802
+ vibration: "vibration",
20803
+ tamper: "tamper",
20804
+ presence: "presence",
20805
+ "enum-sensor": "enum-sensor",
20806
+ "event-emitter": "device-event",
20807
+ "lock-control": "lock",
20808
+ switch: "switch",
20809
+ button: "button",
20810
+ doorbell: "doorbell"
20811
+ };
20812
+ function buildDescriptor(capName, kind) {
20813
+ const t = EVENT_TAXONOMY[kind];
20814
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
20815
+ return {
20816
+ ...t,
20817
+ icon: legacyIcon(t.iconId)
20818
+ };
20819
+ }
20820
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
20821
+ /**
20315
20822
  * server-management — per-NODE singleton capability for a node's ROOT
20316
20823
  * package lifecycle (runtime-updatable node packages).
20317
20824
  *
@@ -21817,7 +22324,28 @@ var FaceInfoSchema = object({
21817
22324
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
21818
22325
  * track produced no key frame (e.g. native/onboard source) — the UI falls
21819
22326
  * back to the inline `base64` face crop. */
21820
- keyFrameMediaKey: string().optional()
22327
+ keyFrameMediaKey: string().optional(),
22328
+ /** Winning identity-match cosine (0..1) for this face's track, when an
22329
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
22330
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
22331
+ * faces that were never auto-recognized. */
22332
+ bestMatchScore: number().optional(),
22333
+ /** Native-scale face short side (px) at recognition time, when the runner
22334
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
22335
+ * legacy rows / runners that reported no native measure. */
22336
+ nativeFaceShortSidePx: number().optional(),
22337
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
22338
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
22339
+ * but blocked only by the recognition size floor). Mutually exclusive with
22340
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
22341
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
22342
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
22343
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
22344
+ suggestedIdentityId: string().optional(),
22345
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
22346
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
22347
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
22348
+ suggestedMatchScore: number().optional()
21821
22349
  });
21822
22350
  var FaceFilterEnum = _enum([
21823
22351
  "unassigned",
@@ -23924,36 +24452,6 @@ Object.freeze({
23924
24452
  addonId: null,
23925
24453
  access: "view"
23926
24454
  },
23927
- "advancedNotifier.deleteRule": {
23928
- capName: "advanced-notifier",
23929
- capScope: "system",
23930
- addonId: null,
23931
- access: "delete"
23932
- },
23933
- "advancedNotifier.getHistory": {
23934
- capName: "advanced-notifier",
23935
- capScope: "system",
23936
- addonId: null,
23937
- access: "view"
23938
- },
23939
- "advancedNotifier.getRules": {
23940
- capName: "advanced-notifier",
23941
- capScope: "system",
23942
- addonId: null,
23943
- access: "view"
23944
- },
23945
- "advancedNotifier.testRule": {
23946
- capName: "advanced-notifier",
23947
- capScope: "system",
23948
- addonId: null,
23949
- access: "create"
23950
- },
23951
- "advancedNotifier.upsertRule": {
23952
- capName: "advanced-notifier",
23953
- capScope: "system",
23954
- addonId: null,
23955
- access: "create"
23956
- },
23957
24455
  "alarmPanel.arm": {
23958
24456
  capName: "alarm-panel",
23959
24457
  capScope: "device",
@@ -26258,6 +26756,60 @@ Object.freeze({
26258
26756
  addonId: null,
26259
26757
  access: "create"
26260
26758
  },
26759
+ "notificationRules.createRule": {
26760
+ capName: "notification-rules",
26761
+ capScope: "system",
26762
+ addonId: null,
26763
+ access: "create"
26764
+ },
26765
+ "notificationRules.deleteRule": {
26766
+ capName: "notification-rules",
26767
+ capScope: "system",
26768
+ addonId: null,
26769
+ access: "delete"
26770
+ },
26771
+ "notificationRules.getConditionCatalog": {
26772
+ capName: "notification-rules",
26773
+ capScope: "system",
26774
+ addonId: null,
26775
+ access: "view"
26776
+ },
26777
+ "notificationRules.getHistory": {
26778
+ capName: "notification-rules",
26779
+ capScope: "system",
26780
+ addonId: null,
26781
+ access: "view"
26782
+ },
26783
+ "notificationRules.getRule": {
26784
+ capName: "notification-rules",
26785
+ capScope: "system",
26786
+ addonId: null,
26787
+ access: "view"
26788
+ },
26789
+ "notificationRules.listRules": {
26790
+ capName: "notification-rules",
26791
+ capScope: "system",
26792
+ addonId: null,
26793
+ access: "view"
26794
+ },
26795
+ "notificationRules.setRuleEnabled": {
26796
+ capName: "notification-rules",
26797
+ capScope: "system",
26798
+ addonId: null,
26799
+ access: "create"
26800
+ },
26801
+ "notificationRules.testRule": {
26802
+ capName: "notification-rules",
26803
+ capScope: "system",
26804
+ addonId: null,
26805
+ access: "create"
26806
+ },
26807
+ "notificationRules.updateRule": {
26808
+ capName: "notification-rules",
26809
+ capScope: "system",
26810
+ addonId: null,
26811
+ access: "create"
26812
+ },
26261
26813
  "notifier.cancel": {
26262
26814
  capName: "notifier",
26263
26815
  capScope: "device",