@camstack/addon-provider-dreo 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
@@ -36,7 +36,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
36
36
  var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
37
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
38
38
  //#endregion
39
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
39
+ //#region ../types/dist/event-category-BLcNejAE.mjs
40
40
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
41
41
  EventCategory["SystemBoot"] = "system.boot";
42
42
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -186,9 +186,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
186
186
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
187
187
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
188
188
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
189
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
190
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
191
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
192
189
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
193
190
  * progress bar the client reconciles via `recordingExport.getExport`. */
194
191
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6853,7 +6850,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6853
6850
  patch: record(string(), unknown())
6854
6851
  }), object({ success: literal(true) });
6855
6852
  object({ deviceId: number() }), unknown().nullable();
6856
- /** Shorthand to define a method schema */
6857
6853
  function method(input, output, options) {
6858
6854
  return {
6859
6855
  input,
@@ -6861,6 +6857,7 @@ function method(input, output, options) {
6861
6857
  kind: options?.kind ?? "query",
6862
6858
  auth: options?.auth ?? "protected",
6863
6859
  ...options?.access !== void 0 ? { access: options.access } : {},
6860
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6864
6861
  timeoutMs: options?.timeoutMs
6865
6862
  };
6866
6863
  }
@@ -8230,6 +8227,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8230
8227
  /** The complete taxonomy dictionary, keyed by kind. */
8231
8228
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8232
8229
  /**
8230
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8231
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8232
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8233
+ * taxonomy surface (timeline, filters, event page).
8234
+ *
8235
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8236
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8237
+ * for the `classes` / `classesExclude` conditions.
8238
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8239
+ * the same class picker, grouped under an Audio header.
8240
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8241
+ * lock / …) for the `sensorKinds` device-event condition.
8242
+ *
8243
+ * Each entry carries `parentKind` so the client can group video subs under
8244
+ * their macro and sensor/control kinds under their category. This surface is
8245
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8246
+ * method, no codegen — so it ships train-free with an addon deploy.
8247
+ */
8248
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8249
+ var NcTaxonomyEntrySchema = object({
8250
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8251
+ kind: string(),
8252
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8253
+ label: string(),
8254
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8255
+ parentKind: string().nullable()
8256
+ });
8257
+ object({
8258
+ videoClasses: array(NcTaxonomyEntrySchema),
8259
+ audioKinds: array(NcTaxonomyEntrySchema),
8260
+ labels: array(NcTaxonomyEntrySchema)
8261
+ });
8262
+ function toEntry(kind, label, parentKind) {
8263
+ return {
8264
+ kind,
8265
+ label,
8266
+ parentKind
8267
+ };
8268
+ }
8269
+ /**
8270
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8271
+ * (macros before their subs), which the client relies on for stable grouping.
8272
+ */
8273
+ function buildNcTaxonomy() {
8274
+ const all = Object.values(EVENT_TAXONOMY);
8275
+ return {
8276
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8277
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8278
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8279
+ };
8280
+ }
8281
+ Object.freeze(buildNcTaxonomy());
8282
+ /**
8233
8283
  * Error types for the safe expression engine. Two distinct classes so callers
8234
8284
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8235
8285
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -12215,6 +12265,22 @@ var CameraMetricsSchema = object({
12215
12265
  ])
12216
12266
  });
12217
12267
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
12268
+ /**
12269
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
12270
+ * within the frame, so the executor can re-cut a leaf child ROI at native
12271
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
12272
+ */
12273
+ var NativeCropRefSchema = object({
12274
+ /** Handle keying the retained native surface (node-pinned to its owner). */
12275
+ handle: FrameHandleSchema,
12276
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
12277
+ cropFrameSpace: object({
12278
+ x: number(),
12279
+ y: number(),
12280
+ w: number(),
12281
+ h: number()
12282
+ })
12283
+ });
12218
12284
  var ModelFormatSchema$1 = _enum([
12219
12285
  "onnx",
12220
12286
  "coreml",
@@ -12490,7 +12556,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
12490
12556
  * Omitted ⇒ the runner's default device (current single-engine
12491
12557
  * behaviour). Selects WHICH device pool of the node runs the call.
12492
12558
  */
12493
- deviceKey: string().optional()
12559
+ deviceKey: string().optional(),
12560
+ /**
12561
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
12562
+ * when the parent crop was resolved from the frame's retained NATIVE
12563
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
12564
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
12565
+ * resolution from that surface — the SAME quality path faces already
12566
+ * had — instead of the downscaled parent tile. `handle` keys the native
12567
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
12568
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
12569
+ * the executor's crop-normalized child ROI back into frame-normalized
12570
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
12571
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
12572
+ * (today's behaviour on the fallback path).
12573
+ */
12574
+ nativeCropRef: NativeCropRefSchema.optional()
12494
12575
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
12495
12576
  engine: PipelineEngineChoiceSchema.optional(),
12496
12577
  steps: array(PipelineStepInputSchema).min(1),
@@ -12739,7 +12820,11 @@ var DetailResultSchema = object({
12739
12820
  bbox: NativeCropBboxSchema.optional(),
12740
12821
  embedding: string().optional(),
12741
12822
  label: string().optional(),
12742
- alignedCropJpeg: string().optional()
12823
+ alignedCropJpeg: string().optional(),
12824
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
12825
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
12826
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
12827
+ nativeFaceShortSidePx: number().optional()
12743
12828
  });
12744
12829
  /**
12745
12830
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -12753,6 +12838,12 @@ var motionCooldownMsField = {
12753
12838
  default: 3e4,
12754
12839
  step: 500
12755
12840
  };
12841
+ var maxSessionHoldMsField = {
12842
+ min: 0,
12843
+ max: 6e5,
12844
+ default: 12e4,
12845
+ step: 5e3
12846
+ };
12756
12847
  var motionFpsField = {
12757
12848
  min: 1,
12758
12849
  max: 30,
@@ -12900,6 +12991,19 @@ var RunnerCameraConfigSchema = object({
12900
12991
  "on-motion"
12901
12992
  ]).default("always-on"),
12902
12993
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
12994
+ /**
12995
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
12996
+ * detection session is active and ≥1 confirmed non-stationary track is
12997
+ * still live, the orchestrator keeps the session open past
12998
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
12999
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
13000
+ * ms since the session opened, after which it closes regardless. `0`
13001
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
13002
+ * runner itself — carried here so it shares the per-camera device-settings
13003
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
13004
+ * resolved `CameraDetectionConfig`.
13005
+ */
13006
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
12903
13007
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
12904
13008
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
12905
13009
  motionStreamId: string(),
@@ -12989,7 +13093,7 @@ var RunnerCameraConfigSchema = object({
12989
13093
  */
12990
13094
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
12991
13095
  });
12992
- 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;
13096
+ 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;
12993
13097
  /**
12994
13098
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
12995
13099
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -16516,94 +16620,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
16516
16620
  bundleUrl: string()
16517
16621
  });
16518
16622
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
16519
- var NotificationRuleConditionsSchema = object({
16520
- deviceIds: array(number()).readonly().optional(),
16521
- classNames: array(string()).readonly().optional(),
16522
- zoneIds: array(string()).readonly().optional(),
16523
- minConfidence: number().optional(),
16524
- source: _enum([
16525
- "pipeline",
16526
- "onboard",
16527
- "any"
16528
- ]).optional(),
16529
- schedule: object({
16530
- days: array(number()).readonly(),
16531
- startHour: number(),
16532
- endHour: number()
16533
- }).optional(),
16534
- cooldownSeconds: number().optional(),
16535
- minDwellSeconds: number().optional(),
16536
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
16537
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
16538
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
16539
- eventTypeTokens: array(string()).readonly().optional(),
16540
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
16541
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
16542
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
16543
- clipDescription: object({
16544
- text: string().min(1),
16545
- minSimilarity: number().min(0).max(1)
16546
- }).optional(),
16547
- /** Match events whose recognized-entity label (face identity name or plate
16548
- * vehicle name, propagated onto `event.data.label`) is one of these values.
16549
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
16550
- * vehicle/person> is seen". */
16551
- labels: array(string()).readonly().optional()
16552
- });
16553
- var NotificationRuleTemplateSchema = object({
16554
- title: string(),
16555
- body: string(),
16556
- imageMode: _enum([
16557
- "crop",
16558
- "annotated",
16559
- "full",
16560
- "none"
16561
- ])
16562
- });
16563
- var NotificationRuleSchema = object({
16564
- id: string(),
16565
- name: string(),
16566
- enabled: boolean(),
16567
- eventTypes: array(string()).readonly(),
16568
- conditions: NotificationRuleConditionsSchema,
16569
- outputs: array(string()).readonly(),
16570
- template: NotificationRuleTemplateSchema.optional(),
16571
- priority: _enum([
16572
- "low",
16573
- "normal",
16574
- "high",
16575
- "critical"
16576
- ])
16577
- });
16578
- var NotificationTestResultSchema = object({
16579
- ruleId: string(),
16580
- eventId: string(),
16581
- timestamp: number(),
16582
- wouldFire: boolean(),
16583
- reason: string().optional()
16584
- });
16585
- var NotificationHistoryEntrySchema = object({
16586
- id: string(),
16587
- ruleId: string(),
16588
- ruleName: string(),
16589
- eventId: string(),
16590
- timestamp: number(),
16591
- outputs: array(string()).readonly(),
16592
- success: boolean(),
16593
- error: string().optional(),
16594
- deviceId: number().optional()
16595
- });
16596
- var NotificationHistoryFilterSchema = object({
16597
- ruleId: string().optional(),
16598
- deviceId: number().optional(),
16599
- from: number().optional(),
16600
- to: number().optional(),
16601
- limit: number().optional()
16602
- });
16603
- 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({
16604
- ruleId: string(),
16605
- lookbackMinutes: number()
16606
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
16607
16623
  /**
16608
16624
  * Alerts capability — collection-based internal alert system.
16609
16625
  *
@@ -16790,89 +16806,6 @@ method(object({
16790
16806
  password: string()
16791
16807
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
16792
16808
  /**
16793
- * `login-method` — collection cap through which auth addons contribute
16794
- * their pre-auth login surfaces to the login page. This is the SINGLE,
16795
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
16796
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
16797
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
16798
- * procedure aggregates them for the unauthenticated login page.
16799
- *
16800
- * A contribution is a discriminated union on `kind`:
16801
- *
16802
- * - `redirect` — a declarative button. The login page renders a generic
16803
- * button that navigates to `startUrl` (an addon-owned HTTP route).
16804
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
16805
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
16806
- * login page needs NO change.
16807
- *
16808
- * - `widget` — a Module-Federation widget the login page mounts (via
16809
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
16810
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
16811
- * mechanism kept for future use; no shipped addon uses it on the login
16812
- * page (the passkey ceremony below runs natively in the shell instead).
16813
- *
16814
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
16815
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
16816
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
16817
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
16818
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
16819
- * fetching any remote code pre-auth. Contribution stays unconditional —
16820
- * enrollment state is never leaked pre-auth; visibility is a shell
16821
- * decision.
16822
- *
16823
- * Every contribution carries a `stage`:
16824
- * - `primary` — shown on the first credentials screen (OIDC /
16825
- * magic-link buttons; a future usernameless passkey).
16826
- * - `second-factor` — shown AFTER the password leg, gated on the
16827
- * returned `factors` (passkey-as-2FA today).
16828
- *
16829
- * `mount: skip` — the cap is read server-side by the core auth router
16830
- * (`registry.getCollection('login-method')`), never mounted as its own
16831
- * tRPC router.
16832
- */
16833
- /** When a login method renders in the two-phase login flow. */
16834
- var LoginStageEnum = _enum(["primary", "second-factor"]);
16835
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
16836
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
16837
- object({
16838
- kind: literal("redirect"),
16839
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
16840
- id: string(),
16841
- /** Operator-facing button label. */
16842
- label: string(),
16843
- /** lucide-react icon name. */
16844
- icon: string().optional(),
16845
- /** Addon-owned HTTP route the button navigates to (GET). */
16846
- startUrl: string(),
16847
- stage: LoginStageEnum
16848
- }),
16849
- object({
16850
- kind: literal("widget"),
16851
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
16852
- id: string(),
16853
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
16854
- addonId: string(),
16855
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
16856
- bundle: string(),
16857
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
16858
- remote: WidgetRemoteSchema,
16859
- stage: LoginStageEnum
16860
- }),
16861
- object({
16862
- kind: literal("passkey"),
16863
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
16864
- id: string(),
16865
- /** Operator-facing button label. */
16866
- label: string(),
16867
- stage: LoginStageEnum,
16868
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
16869
- rpId: string(),
16870
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
16871
- origin: string().nullable()
16872
- })
16873
- ]);
16874
- method(_void(), array(LoginMethodContributionSchema).readonly());
16875
- /**
16876
16809
  * Orchestrator-side destination metadata. The orchestrator computes
16877
16810
  * `id = <addonId>:<subId>` from its provider lookup so consumers
16878
16811
  * (admin UI, restore flow) see one canonical key.
@@ -18233,242 +18166,617 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
18233
18166
  kind: "mutation",
18234
18167
  auth: "admin"
18235
18168
  });
18236
- var LogLevelSchema = _enum([
18237
- "debug",
18238
- "info",
18239
- "warn",
18240
- "error"
18169
+ /**
18170
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18171
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18172
+ * caps stay wire-compatible without a circular cap→cap import.
18173
+ *
18174
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
18175
+ * every transport tier structurally, and failed calls still write usage rows.
18176
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18177
+ */
18178
+ var LlmUsageSchema = object({
18179
+ inputTokens: number(),
18180
+ outputTokens: number()
18181
+ });
18182
+ var LlmErrorCodeSchema = _enum([
18183
+ "timeout",
18184
+ "rate-limited",
18185
+ "auth",
18186
+ "refusal",
18187
+ "bad-request",
18188
+ "unavailable",
18189
+ "no-profile",
18190
+ "budget-exceeded",
18191
+ "adapter-error"
18241
18192
  ]);
18242
- var LogEntrySchema = object({
18243
- timestamp: date(),
18244
- level: LogLevelSchema,
18245
- scope: array(string()),
18193
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18194
+ ok: literal(true),
18195
+ text: string(),
18196
+ model: string(),
18197
+ usage: LlmUsageSchema,
18198
+ truncated: boolean(),
18199
+ latencyMs: number()
18200
+ }), object({
18201
+ ok: literal(false),
18202
+ code: LlmErrorCodeSchema,
18246
18203
  message: string(),
18247
- meta: record(string(), unknown()).optional(),
18248
- tags: record(string(), string()).optional()
18249
- });
18250
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18251
- scope: array(string()).optional(),
18252
- level: LogLevelSchema.optional(),
18253
- since: date().optional(),
18254
- until: date().optional(),
18255
- limit: number().optional(),
18256
- tags: record(string(), string()).optional()
18257
- }), array(LogEntrySchema).readonly());
18258
- var CpuBreakdownSchema = object({
18259
- total: number(),
18260
- user: number(),
18261
- system: number(),
18262
- irq: number(),
18263
- nice: number(),
18264
- loadAvg: tuple([
18265
- number(),
18266
- number(),
18267
- number()
18268
- ]),
18269
- cores: number()
18204
+ retryAfterMs: number().optional()
18205
+ })]);
18206
+ /**
18207
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18208
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18209
+ * notification-output.cap.ts:27-31 precedents).
18210
+ */
18211
+ var LlmImageSchema = object({
18212
+ bytes: _instanceof(Uint8Array),
18213
+ mimeType: string()
18270
18214
  });
18271
- var MemoryInfoSchema = object({
18272
- percent: number(),
18273
- totalBytes: number(),
18274
- usedBytes: number(),
18275
- availableBytes: number(),
18276
- swapUsedBytes: number(),
18277
- swapTotalBytes: number()
18215
+ var LlmGenerateBaseInputSchema = object({
18216
+ /** Collection routing (the notification-output posture). */
18217
+ addonId: string().optional(),
18218
+ /** Explicit profile; else the resolution chain (spec §3). */
18219
+ profileId: string().optional(),
18220
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18221
+ consumer: string(),
18222
+ system: string().optional(),
18223
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
18224
+ prompt: string(),
18225
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18226
+ jsonSchema: record(string(), unknown()).optional(),
18227
+ /** Per-call override of the profile default. */
18228
+ maxTokens: number().int().positive().optional(),
18229
+ temperature: number().optional()
18278
18230
  });
18279
- var DiskIoSnapshotSchema = object({
18280
- readBytes: number(),
18281
- writeBytes: number(),
18282
- readOps: number(),
18283
- writeOps: number(),
18284
- timestampMs: number()
18285
- });
18286
- var NetworkIoSnapshotSchema = object({
18287
- rxBytes: number(),
18288
- txBytes: number(),
18289
- rxPackets: number(),
18290
- txPackets: number(),
18291
- rxErrors: number(),
18292
- txErrors: number(),
18293
- timestampMs: number()
18294
- });
18295
- var MetricsGpuInfoSchema = object({
18296
- utilization: number(),
18297
- model: string(),
18298
- memoryUsedBytes: number(),
18299
- memoryTotalBytes: number(),
18300
- temperature: number().nullable()
18301
- });
18302
- var ProcessResourceInfoSchema = object({
18303
- openFds: number(),
18304
- threadCount: number(),
18305
- activeHandles: number(),
18306
- activeRequests: number()
18307
- });
18308
- var PressureAvgsSchema = object({
18309
- avg10: number(),
18310
- avg60: number(),
18311
- avg300: number()
18312
- });
18313
- var PressureInfoSchema = object({
18314
- some: PressureAvgsSchema,
18315
- full: PressureAvgsSchema.nullable()
18316
- });
18317
- var SystemResourceSnapshotSchema = object({
18318
- cpu: CpuBreakdownSchema,
18319
- memory: MemoryInfoSchema,
18320
- gpu: MetricsGpuInfoSchema.nullable(),
18321
- network: NetworkIoSnapshotSchema,
18322
- disk: DiskIoSnapshotSchema,
18323
- pressure: object({
18324
- cpu: PressureInfoSchema.nullable(),
18325
- memory: PressureInfoSchema.nullable(),
18326
- io: PressureInfoSchema.nullable()
18231
+ /**
18232
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18233
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18234
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18235
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18236
+ * this only through the `llm` cap's methods.
18237
+ *
18238
+ * One running llama-server child per node in v1 (models are RAM-heavy).
18239
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18240
+ * watchdog — operator decision #3).
18241
+ */
18242
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
18243
+ object({
18244
+ kind: literal("catalog"),
18245
+ catalogId: string()
18327
18246
  }),
18328
- process: ProcessResourceInfoSchema,
18329
- cpuTemperature: number().nullable(),
18330
- timestampMs: number()
18331
- });
18332
- var DiskSpaceInfoSchema = object({
18333
- path: string(),
18334
- totalBytes: number(),
18335
- usedBytes: number(),
18336
- availableBytes: number(),
18337
- percent: number()
18338
- });
18339
- var PidResourceStatsSchema = object({
18340
- pid: number(),
18341
- cpu: number(),
18342
- memory: number(),
18343
- /**
18344
- * Private (anonymous) resident bytes — the per-process V8 heap + native
18345
- * allocations NOT shared with other processes (Linux RssAnon). This is the
18346
- * "real" per-runner cost; summing it across runners is meaningful, unlike
18347
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
18348
- * Undefined where /proc is unavailable (e.g. macOS).
18349
- */
18350
- privateBytes: number().optional(),
18351
- /**
18352
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18353
- * code shared copy-on-write across runners. Undefined on macOS.
18354
- */
18355
- sharedBytes: number().optional()
18247
+ object({
18248
+ kind: literal("url"),
18249
+ url: string(),
18250
+ sha256: string().optional()
18251
+ }),
18252
+ object({
18253
+ kind: literal("path"),
18254
+ path: string()
18255
+ })
18256
+ ]);
18257
+ var ManagedRuntimeConfigSchema = object({
18258
+ /** WHERE the runtime lives — hub or any agent. */
18259
+ nodeId: string(),
18260
+ /** Closed for v1; 'ollama' is a v2 candidate. */
18261
+ engine: _enum(["llama-cpp"]),
18262
+ model: ManagedModelRefSchema,
18263
+ contextSize: number().int().default(4096),
18264
+ /** 0 = CPU-only. */
18265
+ gpuLayers: number().int().default(0),
18266
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18267
+ threads: number().int().optional(),
18268
+ /** Concurrent slots. */
18269
+ parallel: number().int().default(1),
18270
+ /** Else lazy: first generate boots it. */
18271
+ autoStart: boolean().default(false),
18272
+ /** 0 = never; frees RAM after quiet periods. */
18273
+ idleStopMinutes: number().int().default(30)
18356
18274
  });
18357
- var AddonInstanceSchema = object({
18358
- addonId: string(),
18275
+ var LlmRuntimeStatusSchema = object({
18276
+ /** Status is ALWAYS node-qualified. */
18359
18277
  nodeId: string(),
18360
- role: _enum(["hub", "worker"]),
18361
- pid: number(),
18362
18278
  state: _enum([
18363
- "starting",
18364
- "running",
18365
- "stopping",
18366
18279
  "stopped",
18367
- "crashed"
18368
- ]),
18369
- uptimeSec: number()
18370
- });
18371
- var NodeProcessSchema = object({
18372
- pid: number(),
18373
- ppid: number(),
18374
- pgid: number(),
18375
- classification: _enum([
18376
- "root",
18377
- "managed",
18378
- "system",
18379
- "ghost"
18280
+ "downloading",
18281
+ "starting",
18282
+ "ready",
18283
+ "crashed",
18284
+ "failed"
18380
18285
  ]),
18381
- /** `$process` addon binding when `managed`, else null. */
18382
- addonId: string().nullable(),
18383
- /** Kernel-reported nodeId when the process is a known agent/worker. */
18384
- nodeId: string().nullable(),
18385
- /** Truncated command line. */
18386
- command: string(),
18387
- cpuPercent: number(),
18388
- memoryRssBytes: number(),
18389
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18390
- uptimeSec: number(),
18391
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18392
- orphaned: boolean()
18393
- });
18394
- var KillProcessInputSchema = object({
18395
- pid: number(),
18396
- /** Force = SIGKILL. Default is SIGTERM. */
18397
- force: boolean().optional()
18398
- });
18399
- var KillProcessResultSchema = object({
18400
- success: boolean(),
18401
- reason: string().optional(),
18402
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18403
- });
18404
- var DumpHeapSnapshotInputSchema = object({
18405
- /** The addon whose runner should dump a heap snapshot. */
18406
- addonId: string() });
18407
- var DumpHeapSnapshotResultSchema = object({
18408
- success: boolean(),
18409
- /** Path of the written .heapsnapshot inside the runner's container/host. */
18410
- path: string().optional(),
18411
- /** Process pid that was signalled. */
18412
18286
  pid: number().optional(),
18413
- reason: string().optional()
18287
+ port: number().optional(),
18288
+ modelPath: string().optional(),
18289
+ modelId: string().optional(),
18290
+ downloadProgress: number().min(0).max(1).optional(),
18291
+ lastError: string().optional(),
18292
+ crashesInWindow: number(),
18293
+ /** Child RSS (sampled best-effort). */
18294
+ memoryBytes: number().optional(),
18295
+ vramBytes: number().optional()
18414
18296
  });
18415
- var SystemMetricsSchema = object({
18416
- cpuPercent: number(),
18417
- memoryPercent: number(),
18418
- memoryUsedMB: number(),
18419
- memoryTotalMB: number(),
18420
- diskPercent: number().optional(),
18421
- temperature: number().optional(),
18422
- gpuPercent: number().optional(),
18423
- gpuMemoryPercent: number().optional()
18297
+ var LlmNodeModelSchema = object({
18298
+ file: string(),
18299
+ sizeBytes: number(),
18300
+ catalogId: string().optional(),
18301
+ installedAt: number().optional()
18424
18302
  });
18425
- 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, {
18303
+ var LlmRuntimeDiskUsageSchema = object({
18304
+ nodeId: string(),
18305
+ modelsBytes: number(),
18306
+ freeBytes: number().optional()
18307
+ });
18308
+ method(LlmGenerateBaseInputSchema.extend({
18309
+ images: array(LlmImageSchema).optional(),
18310
+ runtime: ManagedRuntimeConfigSchema,
18311
+ /** The managed profile's timeout, threaded by the hub provider. */
18312
+ timeoutMs: number().int().positive().optional()
18313
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18426
18314
  kind: "mutation",
18427
18315
  auth: "admin"
18428
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
18316
+ }), method(object({}), _void(), {
18429
18317
  kind: "mutation",
18430
18318
  auth: "admin"
18431
- });
18432
- method(object({
18433
- sourceUrl: string(),
18434
- metadata: ModelConvertMetadataSchema,
18435
- targets: array(ConvertTargetSchema).min(1).readonly(),
18436
- calibrationRef: string().optional(),
18437
- sessionId: string().optional()
18438
- }), ConvertResultSchema, {
18319
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18439
18320
  kind: "mutation",
18440
- auth: "admin",
18441
- timeoutMs: 6e5
18442
- });
18443
- method(object({
18444
- nodeId: string(),
18445
- modelId: string(),
18446
- format: _enum(MODEL_FORMATS),
18447
- entry: ModelCatalogEntrySchema
18448
- }), object({
18449
- ok: boolean(),
18450
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
18451
- sha256: string(),
18452
- bytes: number(),
18453
- /** The target node's modelsDir the artifact landed in. */
18454
- path: string()
18455
- }), {
18321
+ auth: "admin"
18322
+ }), method(object({ file: string() }), _void(), {
18456
18323
  kind: "mutation",
18457
18324
  auth: "admin"
18458
- });
18325
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18459
18326
  /**
18460
- * `mqtt-broker` — broker-registry cap.
18461
- *
18462
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
18463
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
18464
- * and (b) the connection details a consumer addon needs to spin up
18465
- * its OWN `mqtt.js` client.
18327
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18328
+ * methods concat-fan across providers; single-row methods route to ONE
18329
+ * provider by the `addonId` in the call input (the notification-output
18330
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18331
+ * (hub-placed); the cap stays open for future providers.
18466
18332
  *
18467
- * Why: pub/sub routing over the system event-bus loses fidelity
18468
- * (callback shape, QoS guarantees, will/retain semantics) and adds
18469
- * refcount bookkeeping that addons would rather own themselves. The
18470
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
18471
- * features anyway — give it the connection config, get out of the way.
18333
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18334
+ * `apiKey` is a password field providers REDACT it on read and merge on
18335
+ * write; a stored key NEVER round-trips to a client.
18336
+ */
18337
+ var LlmProfileKindSchema = _enum([
18338
+ "openai-compatible",
18339
+ "openai",
18340
+ "anthropic",
18341
+ "google",
18342
+ "managed-local"
18343
+ ]);
18344
+ var LlmProfileSchema = object({
18345
+ id: string(),
18346
+ name: string(),
18347
+ kind: LlmProfileKindSchema,
18348
+ /** Stamped by the provider — keeps the fanned catalog routable. */
18349
+ addonId: string(),
18350
+ enabled: boolean(),
18351
+ /** Vendor model id, or the managed runtime's loaded model. */
18352
+ model: string(),
18353
+ /** Required for openai-compatible; override for cloud kinds. */
18354
+ baseUrl: string().optional(),
18355
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
18356
+ apiKey: string().optional(),
18357
+ supportsVision: boolean(),
18358
+ temperature: number().min(0).max(2).optional(),
18359
+ maxTokens: number().int().positive().optional(),
18360
+ timeoutMs: number().int().positive().default(6e4),
18361
+ extraHeaders: record(string(), string()).optional(),
18362
+ /** kind === 'managed-local' only (spec §4). */
18363
+ runtime: ManagedRuntimeConfigSchema.optional()
18364
+ });
18365
+ /** ConfigUISchema tree passed through untyped on the wire (the
18366
+ * notification-output `ConfigSchemaPassthrough` precedent at
18367
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
18368
+ var ConfigSchemaPassthrough$1 = unknown();
18369
+ var LlmProfileKindDescriptorSchema = object({
18370
+ kind: LlmProfileKindSchema,
18371
+ label: string(),
18372
+ icon: string(),
18373
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
18374
+ addonId: string(),
18375
+ configSchema: ConfigSchemaPassthrough$1
18376
+ });
18377
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
18378
+ var LlmDefaultSchema = object({
18379
+ selector: LlmDefaultSelectorSchema,
18380
+ profileId: string()
18381
+ });
18382
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
18383
+ var LlmUsageRollupSchema = object({
18384
+ day: string(),
18385
+ consumer: string(),
18386
+ profileId: string(),
18387
+ calls: number(),
18388
+ okCalls: number(),
18389
+ errorCalls: number(),
18390
+ inputTokens: number(),
18391
+ outputTokens: number(),
18392
+ avgLatencyMs: number()
18393
+ });
18394
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
18395
+ var ManagedModelCatalogEntrySchema = object({
18396
+ id: string(),
18397
+ label: string(),
18398
+ family: string(),
18399
+ purpose: _enum(["text", "vision"]),
18400
+ url: string(),
18401
+ sha256: string(),
18402
+ sizeBytes: number(),
18403
+ quantization: string(),
18404
+ /** Load-time guidance shown in the picker. */
18405
+ minRamBytes: number(),
18406
+ contextSizeDefault: number().int(),
18407
+ /** Vision models: companion projector file. */
18408
+ mmprojUrl: string().optional()
18409
+ });
18410
+ var LlmRuntimeNodeSchema = object({
18411
+ nodeId: string(),
18412
+ reachable: boolean(),
18413
+ status: LlmRuntimeStatusSchema.optional(),
18414
+ disk: LlmRuntimeDiskUsageSchema.optional(),
18415
+ error: string().optional()
18416
+ });
18417
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
18418
+ var ProfileRefInputSchema = object({
18419
+ addonId: string(),
18420
+ profileId: string()
18421
+ });
18422
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
18423
+ kind: "mutation",
18424
+ auth: "admin"
18425
+ }), method(ProfileRefInputSchema, _void(), {
18426
+ kind: "mutation",
18427
+ auth: "admin"
18428
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
18429
+ kind: "mutation",
18430
+ auth: "admin"
18431
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
18432
+ selector: LlmDefaultSelectorSchema,
18433
+ profileId: string().nullable()
18434
+ }), _void(), {
18435
+ kind: "mutation",
18436
+ auth: "admin"
18437
+ }), method(object({
18438
+ since: number().optional(),
18439
+ until: number().optional(),
18440
+ consumer: string().optional(),
18441
+ profileId: string().optional()
18442
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
18443
+ nodeId: string(),
18444
+ model: ManagedModelRefSchema
18445
+ }), _void(), {
18446
+ kind: "mutation",
18447
+ auth: "admin"
18448
+ }), method(object({
18449
+ nodeId: string(),
18450
+ file: string()
18451
+ }), _void(), {
18452
+ kind: "mutation",
18453
+ auth: "admin"
18454
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
18455
+ kind: "mutation",
18456
+ auth: "admin"
18457
+ }), method(ProfileRefInputSchema, _void(), {
18458
+ kind: "mutation",
18459
+ auth: "admin"
18460
+ });
18461
+ var LogLevelSchema = _enum([
18462
+ "debug",
18463
+ "info",
18464
+ "warn",
18465
+ "error"
18466
+ ]);
18467
+ var LogEntrySchema = object({
18468
+ timestamp: date(),
18469
+ level: LogLevelSchema,
18470
+ scope: array(string()),
18471
+ message: string(),
18472
+ meta: record(string(), unknown()).optional(),
18473
+ tags: record(string(), string()).optional()
18474
+ });
18475
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18476
+ scope: array(string()).optional(),
18477
+ level: LogLevelSchema.optional(),
18478
+ since: date().optional(),
18479
+ until: date().optional(),
18480
+ limit: number().optional(),
18481
+ tags: record(string(), string()).optional()
18482
+ }), array(LogEntrySchema).readonly());
18483
+ /**
18484
+ * `login-method` — collection cap through which auth addons contribute
18485
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
18486
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
18487
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
18488
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
18489
+ * procedure aggregates them for the unauthenticated login page.
18490
+ *
18491
+ * A contribution is a discriminated union on `kind`:
18492
+ *
18493
+ * - `redirect` — a declarative button. The login page renders a generic
18494
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
18495
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
18496
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
18497
+ * login page needs NO change.
18498
+ *
18499
+ * - `widget` — a Module-Federation widget the login page mounts (via
18500
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
18501
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
18502
+ * mechanism kept for future use; no shipped addon uses it on the login
18503
+ * page (the passkey ceremony below runs natively in the shell instead).
18504
+ *
18505
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
18506
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
18507
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
18508
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
18509
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
18510
+ * fetching any remote code pre-auth. Contribution stays unconditional —
18511
+ * enrollment state is never leaked pre-auth; visibility is a shell
18512
+ * decision.
18513
+ *
18514
+ * Every contribution carries a `stage`:
18515
+ * - `primary` — shown on the first credentials screen (OIDC /
18516
+ * magic-link buttons; a future usernameless passkey).
18517
+ * - `second-factor` — shown AFTER the password leg, gated on the
18518
+ * returned `factors` (passkey-as-2FA today).
18519
+ *
18520
+ * `mount: skip` — the cap is read server-side by the core auth router
18521
+ * (`registry.getCollection('login-method')`), never mounted as its own
18522
+ * tRPC router.
18523
+ */
18524
+ /** When a login method renders in the two-phase login flow. */
18525
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
18526
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
18527
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
18528
+ object({
18529
+ kind: literal("redirect"),
18530
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
18531
+ id: string(),
18532
+ /** Operator-facing button label. */
18533
+ label: string(),
18534
+ /** lucide-react icon name. */
18535
+ icon: string().optional(),
18536
+ /** Addon-owned HTTP route the button navigates to (GET). */
18537
+ startUrl: string(),
18538
+ stage: LoginStageEnum
18539
+ }),
18540
+ object({
18541
+ kind: literal("widget"),
18542
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
18543
+ id: string(),
18544
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
18545
+ addonId: string(),
18546
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
18547
+ bundle: string(),
18548
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
18549
+ remote: WidgetRemoteSchema,
18550
+ stage: LoginStageEnum
18551
+ }),
18552
+ object({
18553
+ kind: literal("passkey"),
18554
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
18555
+ id: string(),
18556
+ /** Operator-facing button label. */
18557
+ label: string(),
18558
+ stage: LoginStageEnum,
18559
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
18560
+ rpId: string(),
18561
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
18562
+ origin: string().nullable()
18563
+ })
18564
+ ]);
18565
+ method(_void(), array(LoginMethodContributionSchema).readonly());
18566
+ var CpuBreakdownSchema = object({
18567
+ total: number(),
18568
+ user: number(),
18569
+ system: number(),
18570
+ irq: number(),
18571
+ nice: number(),
18572
+ loadAvg: tuple([
18573
+ number(),
18574
+ number(),
18575
+ number()
18576
+ ]),
18577
+ cores: number()
18578
+ });
18579
+ var MemoryInfoSchema = object({
18580
+ percent: number(),
18581
+ totalBytes: number(),
18582
+ usedBytes: number(),
18583
+ availableBytes: number(),
18584
+ swapUsedBytes: number(),
18585
+ swapTotalBytes: number()
18586
+ });
18587
+ var DiskIoSnapshotSchema = object({
18588
+ readBytes: number(),
18589
+ writeBytes: number(),
18590
+ readOps: number(),
18591
+ writeOps: number(),
18592
+ timestampMs: number()
18593
+ });
18594
+ var NetworkIoSnapshotSchema = object({
18595
+ rxBytes: number(),
18596
+ txBytes: number(),
18597
+ rxPackets: number(),
18598
+ txPackets: number(),
18599
+ rxErrors: number(),
18600
+ txErrors: number(),
18601
+ timestampMs: number()
18602
+ });
18603
+ var MetricsGpuInfoSchema = object({
18604
+ utilization: number(),
18605
+ model: string(),
18606
+ memoryUsedBytes: number(),
18607
+ memoryTotalBytes: number(),
18608
+ temperature: number().nullable()
18609
+ });
18610
+ var ProcessResourceInfoSchema = object({
18611
+ openFds: number(),
18612
+ threadCount: number(),
18613
+ activeHandles: number(),
18614
+ activeRequests: number()
18615
+ });
18616
+ var PressureAvgsSchema = object({
18617
+ avg10: number(),
18618
+ avg60: number(),
18619
+ avg300: number()
18620
+ });
18621
+ var PressureInfoSchema = object({
18622
+ some: PressureAvgsSchema,
18623
+ full: PressureAvgsSchema.nullable()
18624
+ });
18625
+ var SystemResourceSnapshotSchema = object({
18626
+ cpu: CpuBreakdownSchema,
18627
+ memory: MemoryInfoSchema,
18628
+ gpu: MetricsGpuInfoSchema.nullable(),
18629
+ network: NetworkIoSnapshotSchema,
18630
+ disk: DiskIoSnapshotSchema,
18631
+ pressure: object({
18632
+ cpu: PressureInfoSchema.nullable(),
18633
+ memory: PressureInfoSchema.nullable(),
18634
+ io: PressureInfoSchema.nullable()
18635
+ }),
18636
+ process: ProcessResourceInfoSchema,
18637
+ cpuTemperature: number().nullable(),
18638
+ timestampMs: number()
18639
+ });
18640
+ var DiskSpaceInfoSchema = object({
18641
+ path: string(),
18642
+ totalBytes: number(),
18643
+ usedBytes: number(),
18644
+ availableBytes: number(),
18645
+ percent: number()
18646
+ });
18647
+ var PidResourceStatsSchema = object({
18648
+ pid: number(),
18649
+ cpu: number(),
18650
+ memory: number(),
18651
+ /**
18652
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
18653
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
18654
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
18655
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
18656
+ * Undefined where /proc is unavailable (e.g. macOS).
18657
+ */
18658
+ privateBytes: number().optional(),
18659
+ /**
18660
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18661
+ * code shared copy-on-write across runners. Undefined on macOS.
18662
+ */
18663
+ sharedBytes: number().optional()
18664
+ });
18665
+ var AddonInstanceSchema = object({
18666
+ addonId: string(),
18667
+ nodeId: string(),
18668
+ role: _enum(["hub", "worker"]),
18669
+ pid: number(),
18670
+ state: _enum([
18671
+ "starting",
18672
+ "running",
18673
+ "stopping",
18674
+ "stopped",
18675
+ "crashed"
18676
+ ]),
18677
+ uptimeSec: number()
18678
+ });
18679
+ var NodeProcessSchema = object({
18680
+ pid: number(),
18681
+ ppid: number(),
18682
+ pgid: number(),
18683
+ classification: _enum([
18684
+ "root",
18685
+ "managed",
18686
+ "system",
18687
+ "ghost"
18688
+ ]),
18689
+ /** `$process` addon binding when `managed`, else null. */
18690
+ addonId: string().nullable(),
18691
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
18692
+ nodeId: string().nullable(),
18693
+ /** Truncated command line. */
18694
+ command: string(),
18695
+ cpuPercent: number(),
18696
+ memoryRssBytes: number(),
18697
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18698
+ uptimeSec: number(),
18699
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18700
+ orphaned: boolean()
18701
+ });
18702
+ var KillProcessInputSchema = object({
18703
+ pid: number(),
18704
+ /** Force = SIGKILL. Default is SIGTERM. */
18705
+ force: boolean().optional()
18706
+ });
18707
+ var KillProcessResultSchema = object({
18708
+ success: boolean(),
18709
+ reason: string().optional(),
18710
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18711
+ });
18712
+ var DumpHeapSnapshotInputSchema = object({
18713
+ /** The addon whose runner should dump a heap snapshot. */
18714
+ addonId: string() });
18715
+ var DumpHeapSnapshotResultSchema = object({
18716
+ success: boolean(),
18717
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
18718
+ path: string().optional(),
18719
+ /** Process pid that was signalled. */
18720
+ pid: number().optional(),
18721
+ reason: string().optional()
18722
+ });
18723
+ var SystemMetricsSchema = object({
18724
+ cpuPercent: number(),
18725
+ memoryPercent: number(),
18726
+ memoryUsedMB: number(),
18727
+ memoryTotalMB: number(),
18728
+ diskPercent: number().optional(),
18729
+ temperature: number().optional(),
18730
+ gpuPercent: number().optional(),
18731
+ gpuMemoryPercent: number().optional()
18732
+ });
18733
+ 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, {
18734
+ kind: "mutation",
18735
+ auth: "admin"
18736
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
18737
+ kind: "mutation",
18738
+ auth: "admin"
18739
+ });
18740
+ method(object({
18741
+ sourceUrl: string(),
18742
+ metadata: ModelConvertMetadataSchema,
18743
+ targets: array(ConvertTargetSchema).min(1).readonly(),
18744
+ calibrationRef: string().optional(),
18745
+ sessionId: string().optional()
18746
+ }), ConvertResultSchema, {
18747
+ kind: "mutation",
18748
+ auth: "admin",
18749
+ timeoutMs: 6e5
18750
+ });
18751
+ method(object({
18752
+ nodeId: string(),
18753
+ modelId: string(),
18754
+ format: _enum(MODEL_FORMATS),
18755
+ entry: ModelCatalogEntrySchema
18756
+ }), object({
18757
+ ok: boolean(),
18758
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
18759
+ sha256: string(),
18760
+ bytes: number(),
18761
+ /** The target node's modelsDir the artifact landed in. */
18762
+ path: string()
18763
+ }), {
18764
+ kind: "mutation",
18765
+ auth: "admin"
18766
+ });
18767
+ /**
18768
+ * `mqtt-broker` — broker-registry cap.
18769
+ *
18770
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
18771
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
18772
+ * and (b) the connection details a consumer addon needs to spin up
18773
+ * its OWN `mqtt.js` client.
18774
+ *
18775
+ * Why: pub/sub routing over the system event-bus loses fidelity
18776
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
18777
+ * refcount bookkeeping that addons would rather own themselves. The
18778
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
18779
+ * features anyway — give it the connection config, get out of the way.
18472
18780
  *
18473
18781
  * Consumer flow:
18474
18782
  * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
@@ -18686,398 +18994,594 @@ var NotificationSchema = object({
18686
18994
  });
18687
18995
  /** One declared native severity/priority level for a kind. */
18688
18996
  var TargetKindLevelSchema = object({
18689
- id: string(),
18690
- label: string(),
18691
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
18692
- ordinal: number().int().min(1).max(5).nullable(),
18693
- flags: object({
18694
- critical: boolean().optional(),
18695
- silent: boolean().optional(),
18696
- noPush: boolean().optional()
18697
- }).optional(),
18698
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
18699
- requires: array(string()).optional(),
18700
- description: string().optional()
18701
- });
18702
- /** The full capability block consulted before dispatch. */
18703
- var TargetKindCapsSchema = object({
18704
- attachments: object({
18705
- mediaTypes: array(AttachmentMediaTypeSchema),
18706
- mode: _enum([
18707
- "url",
18708
- "bytes",
18709
- "both"
18710
- ]),
18711
- max: number().int().nonnegative(),
18712
- maxBytes: number().int().positive().optional()
18713
- }),
18714
- /** Max action buttons (0 = none). */
18715
- actions: number().int().nonnegative(),
18716
- levels: array(TargetKindLevelSchema),
18717
- format: array(NotificationFormatSchema),
18718
- clickUrl: boolean(),
18719
- sound: boolean(),
18720
- ttl: boolean(),
18721
- bodyMaxLen: number().int().positive()
18722
- });
18723
- /**
18724
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
18725
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
18726
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
18727
- * the union is large and not meant for runtime validation here; the exported
18728
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
18729
- */
18730
- var ConfigSchemaPassthrough$1 = unknown();
18731
- var TargetKindSchema = object({
18732
- kind: string(),
18733
- label: string(),
18734
- icon: string(),
18735
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
18736
- addonId: string(),
18737
- configSchema: ConfigSchemaPassthrough$1,
18738
- supportsDiscovery: boolean(),
18739
- caps: TargetKindCapsSchema
18740
- });
18741
- /**
18742
- * A persisted target. `config` holds secrets; providers REDACT secret fields
18743
- * (return a presence marker only) when serving `listTargets` — never
18744
- * round-trip a stored secret to the UI.
18745
- */
18746
- var TargetSchema = object({
18747
- id: string(),
18748
- name: string(),
18749
- kind: string(),
18750
- addonId: string(),
18751
- enabled: boolean(),
18752
- config: record(string(), unknown())
18753
- });
18754
- /** A discovery-surfaced candidate (config is partial + non-secret). */
18755
- var DiscoveredTargetSchema = object({
18756
- kind: string(),
18757
- suggestedName: string(),
18758
- config: record(string(), unknown())
18759
- });
18760
- /** The degrade engine's report — what was resolved / dropped / degraded. */
18761
- var RenderedAsSchema = object({
18762
- level: string(),
18763
- format: NotificationFormatSchema,
18764
- attachmentsSent: number().int().nonnegative(),
18765
- actionsSent: number().int().nonnegative(),
18766
- truncated: boolean(),
18767
- dropped: array(string())
18768
- });
18769
- var SendResultSchema = object({
18770
- success: boolean(),
18771
- error: string().optional(),
18772
- renderedAs: RenderedAsSchema.optional()
18773
- });
18774
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
18775
- var TestResultSchema = SendResultSchema;
18776
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
18777
- kind: string(),
18778
- config: record(string(), unknown()).optional()
18779
- }), array(DiscoveredTargetSchema)), method(object({
18780
- targetId: string(),
18781
- notification: NotificationSchema
18782
- }), SendResultSchema, { kind: "mutation" }), method(object({
18783
- targetId: string(),
18784
- sample: NotificationSchema.optional()
18785
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
18786
- targetId: string(),
18787
- enabled: boolean()
18788
- }), _void(), { kind: "mutation" });
18789
- /**
18790
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18791
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18792
- * caps stay wire-compatible without a circular cap→cap import.
18793
- *
18794
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
18795
- * every transport tier structurally, and failed calls still write usage rows.
18796
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18797
- */
18798
- var LlmUsageSchema = object({
18799
- inputTokens: number(),
18800
- outputTokens: number()
18801
- });
18802
- var LlmErrorCodeSchema = _enum([
18803
- "timeout",
18804
- "rate-limited",
18805
- "auth",
18806
- "refusal",
18807
- "bad-request",
18808
- "unavailable",
18809
- "no-profile",
18810
- "budget-exceeded",
18811
- "adapter-error"
18812
- ]);
18813
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18814
- ok: literal(true),
18815
- text: string(),
18816
- model: string(),
18817
- usage: LlmUsageSchema,
18818
- truncated: boolean(),
18819
- latencyMs: number()
18820
- }), object({
18821
- ok: literal(false),
18822
- code: LlmErrorCodeSchema,
18823
- message: string(),
18824
- retryAfterMs: number().optional()
18825
- })]);
18826
- /**
18827
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18828
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18829
- * notification-output.cap.ts:27-31 precedents).
18830
- */
18831
- var LlmImageSchema = object({
18832
- bytes: _instanceof(Uint8Array),
18833
- mimeType: string()
18834
- });
18835
- var LlmGenerateBaseInputSchema = object({
18836
- /** Collection routing (the notification-output posture). */
18837
- addonId: string().optional(),
18838
- /** Explicit profile; else the resolution chain (spec §3). */
18839
- profileId: string().optional(),
18840
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18841
- consumer: string(),
18842
- system: string().optional(),
18843
- /** v1: single-turn. `messages[]` is a v2 additive field. */
18844
- prompt: string(),
18845
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18846
- jsonSchema: record(string(), unknown()).optional(),
18847
- /** Per-call override of the profile default. */
18848
- maxTokens: number().int().positive().optional(),
18849
- temperature: number().optional()
18850
- });
18851
- /**
18852
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18853
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18854
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18855
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18856
- * this only through the `llm` cap's methods.
18857
- *
18858
- * One running llama-server child per node in v1 (models are RAM-heavy).
18859
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18860
- * watchdog — operator decision #3).
18861
- */
18862
- var ManagedModelRefSchema = discriminatedUnion("kind", [
18863
- object({
18864
- kind: literal("catalog"),
18865
- catalogId: string()
18866
- }),
18867
- object({
18868
- kind: literal("url"),
18869
- url: string(),
18870
- sha256: string().optional()
18871
- }),
18872
- object({
18873
- kind: literal("path"),
18874
- path: string()
18875
- })
18876
- ]);
18877
- var ManagedRuntimeConfigSchema = object({
18878
- /** WHERE the runtime lives — hub or any agent. */
18879
- nodeId: string(),
18880
- /** Closed for v1; 'ollama' is a v2 candidate. */
18881
- engine: _enum(["llama-cpp"]),
18882
- model: ManagedModelRefSchema,
18883
- contextSize: number().int().default(4096),
18884
- /** 0 = CPU-only. */
18885
- gpuLayers: number().int().default(0),
18886
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18887
- threads: number().int().optional(),
18888
- /** Concurrent slots. */
18889
- parallel: number().int().default(1),
18890
- /** Else lazy: first generate boots it. */
18891
- autoStart: boolean().default(false),
18892
- /** 0 = never; frees RAM after quiet periods. */
18893
- idleStopMinutes: number().int().default(30)
18894
- });
18895
- var LlmRuntimeStatusSchema = object({
18896
- /** Status is ALWAYS node-qualified. */
18897
- nodeId: string(),
18898
- state: _enum([
18899
- "stopped",
18900
- "downloading",
18901
- "starting",
18902
- "ready",
18903
- "crashed",
18904
- "failed"
18905
- ]),
18906
- pid: number().optional(),
18907
- port: number().optional(),
18908
- modelPath: string().optional(),
18909
- modelId: string().optional(),
18910
- downloadProgress: number().min(0).max(1).optional(),
18911
- lastError: string().optional(),
18912
- crashesInWindow: number(),
18913
- /** Child RSS (sampled best-effort). */
18914
- memoryBytes: number().optional(),
18915
- vramBytes: number().optional()
18997
+ id: string(),
18998
+ label: string(),
18999
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
19000
+ ordinal: number().int().min(1).max(5).nullable(),
19001
+ flags: object({
19002
+ critical: boolean().optional(),
19003
+ silent: boolean().optional(),
19004
+ noPush: boolean().optional()
19005
+ }).optional(),
19006
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
19007
+ requires: array(string()).optional(),
19008
+ description: string().optional()
18916
19009
  });
18917
- var LlmNodeModelSchema = object({
18918
- file: string(),
18919
- sizeBytes: number(),
18920
- catalogId: string().optional(),
18921
- installedAt: number().optional()
19010
+ /** The full capability block consulted before dispatch. */
19011
+ var TargetKindCapsSchema = object({
19012
+ attachments: object({
19013
+ mediaTypes: array(AttachmentMediaTypeSchema),
19014
+ mode: _enum([
19015
+ "url",
19016
+ "bytes",
19017
+ "both"
19018
+ ]),
19019
+ max: number().int().nonnegative(),
19020
+ maxBytes: number().int().positive().optional()
19021
+ }),
19022
+ /** Max action buttons (0 = none). */
19023
+ actions: number().int().nonnegative(),
19024
+ levels: array(TargetKindLevelSchema),
19025
+ format: array(NotificationFormatSchema),
19026
+ clickUrl: boolean(),
19027
+ sound: boolean(),
19028
+ ttl: boolean(),
19029
+ bodyMaxLen: number().int().positive()
18922
19030
  });
18923
- var LlmRuntimeDiskUsageSchema = object({
18924
- nodeId: string(),
18925
- modelsBytes: number(),
18926
- freeBytes: number().optional()
19031
+ /**
19032
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
19033
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
19034
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
19035
+ * the union is large and not meant for runtime validation here; the exported
19036
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
19037
+ */
19038
+ var ConfigSchemaPassthrough = unknown();
19039
+ var TargetKindSchema = object({
19040
+ kind: string(),
19041
+ label: string(),
19042
+ icon: string(),
19043
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
19044
+ addonId: string(),
19045
+ configSchema: ConfigSchemaPassthrough,
19046
+ supportsDiscovery: boolean(),
19047
+ caps: TargetKindCapsSchema
18927
19048
  });
18928
- method(LlmGenerateBaseInputSchema.extend({
18929
- images: array(LlmImageSchema).optional(),
18930
- runtime: ManagedRuntimeConfigSchema,
18931
- /** The managed profile's timeout, threaded by the hub provider. */
18932
- timeoutMs: number().int().positive().optional()
18933
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18934
- kind: "mutation",
18935
- auth: "admin"
18936
- }), method(object({}), _void(), {
18937
- kind: "mutation",
18938
- auth: "admin"
18939
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18940
- kind: "mutation",
18941
- auth: "admin"
18942
- }), method(object({ file: string() }), _void(), {
18943
- kind: "mutation",
18944
- auth: "admin"
18945
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18946
19049
  /**
18947
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18948
- * methods concat-fan across providers; single-row methods route to ONE
18949
- * provider by the `addonId` in the call input (the notification-output
18950
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18951
- * (hub-placed); the cap stays open for future providers.
18952
- *
18953
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18954
- * `apiKey` is a password field — providers REDACT it on read and merge on
18955
- * write; a stored key NEVER round-trips to a client.
19050
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
19051
+ * (return a presence marker only) when serving `listTargets` — never
19052
+ * round-trip a stored secret to the UI.
18956
19053
  */
18957
- var LlmProfileKindSchema = _enum([
18958
- "openai-compatible",
18959
- "openai",
18960
- "anthropic",
18961
- "google",
18962
- "managed-local"
18963
- ]);
18964
- var LlmProfileSchema = object({
19054
+ var TargetSchema = object({
18965
19055
  id: string(),
18966
19056
  name: string(),
18967
- kind: LlmProfileKindSchema,
18968
- /** Stamped by the provider — keeps the fanned catalog routable. */
19057
+ kind: string(),
18969
19058
  addonId: string(),
18970
19059
  enabled: boolean(),
18971
- /** Vendor model id, or the managed runtime's loaded model. */
18972
- model: string(),
18973
- /** Required for openai-compatible; override for cloud kinds. */
18974
- baseUrl: string().optional(),
18975
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
18976
- apiKey: string().optional(),
18977
- supportsVision: boolean(),
18978
- temperature: number().min(0).max(2).optional(),
18979
- maxTokens: number().int().positive().optional(),
18980
- timeoutMs: number().int().positive().default(6e4),
18981
- extraHeaders: record(string(), string()).optional(),
18982
- /** kind === 'managed-local' only (spec §4). */
18983
- runtime: ManagedRuntimeConfigSchema.optional()
19060
+ config: record(string(), unknown())
18984
19061
  });
18985
- /** ConfigUISchema tree passed through untyped on the wire (the
18986
- * notification-output `ConfigSchemaPassthrough` precedent at
18987
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
18988
- var ConfigSchemaPassthrough = unknown();
18989
- var LlmProfileKindDescriptorSchema = object({
18990
- kind: LlmProfileKindSchema,
18991
- label: string(),
18992
- icon: string(),
18993
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
18994
- addonId: string(),
18995
- configSchema: ConfigSchemaPassthrough
19062
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
19063
+ var DiscoveredTargetSchema = object({
19064
+ kind: string(),
19065
+ suggestedName: string(),
19066
+ config: record(string(), unknown())
18996
19067
  });
18997
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
18998
- var LlmDefaultSchema = object({
18999
- selector: LlmDefaultSelectorSchema,
19000
- profileId: string()
19068
+ /** The degrade engine's report what was resolved / dropped / degraded. */
19069
+ var RenderedAsSchema = object({
19070
+ level: string(),
19071
+ format: NotificationFormatSchema,
19072
+ attachmentsSent: number().int().nonnegative(),
19073
+ actionsSent: number().int().nonnegative(),
19074
+ truncated: boolean(),
19075
+ dropped: array(string())
19001
19076
  });
19002
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
19003
- var LlmUsageRollupSchema = object({
19004
- day: string(),
19005
- consumer: string(),
19006
- profileId: string(),
19007
- calls: number(),
19008
- okCalls: number(),
19009
- errorCalls: number(),
19010
- inputTokens: number(),
19011
- outputTokens: number(),
19012
- avgLatencyMs: number()
19077
+ var SendResultSchema = object({
19078
+ success: boolean(),
19079
+ error: string().optional(),
19080
+ renderedAs: RenderedAsSchema.optional()
19013
19081
  });
19014
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
19015
- var ManagedModelCatalogEntrySchema = object({
19082
+ /** Same shape as SendResult kept as a distinct name for the test panel. */
19083
+ var TestResultSchema = SendResultSchema;
19084
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
19085
+ kind: string(),
19086
+ config: record(string(), unknown()).optional()
19087
+ }), array(DiscoveredTargetSchema)), method(object({
19088
+ targetId: string(),
19089
+ notification: NotificationSchema
19090
+ }), SendResultSchema, { kind: "mutation" }), method(object({
19091
+ targetId: string(),
19092
+ sample: NotificationSchema.optional()
19093
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
19094
+ targetId: string(),
19095
+ enabled: boolean()
19096
+ }), _void(), { kind: "mutation" });
19097
+ /**
19098
+ * notification-rules — the Notification Center rule surface (P1 core).
19099
+ *
19100
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
19101
+ * (operator decisions D-1/D-2/D-3 are binding):
19102
+ *
19103
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
19104
+ * `notification-center` module), hooked on the durable persistence
19105
+ * moments (object-event insert, TrackCloser.closeExpired) with a
19106
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
19107
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
19108
+ * FIRST persisted detection matching the conditions (per-track dedup,
19109
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
19110
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
19111
+ * - DISPATCH stays behind `notification-output` (rules reference targets
19112
+ * by id; per-backend params are a passthrough blob capped by the
19113
+ * target kind's own caps/degrade engine).
19114
+ *
19115
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
19116
+ * server-injected caller identity — the first `caller: 'required'`
19117
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
19118
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
19119
+ * windows, and the optional label/identity/plate matchers. User rules,
19120
+ * private zones, per-recipient fan-out and the wider condition table are
19121
+ * P2+ (see spec §7).
19122
+ *
19123
+ * All schemas here are the single source of truth — `NcRule` etc. are
19124
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
19125
+ * schema/interface drift is explicitly not repeated).
19126
+ */
19127
+ /**
19128
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
19129
+ * The value maps 1:1 onto the evaluated record kind:
19130
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
19131
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
19132
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
19133
+ * change of a LINKED device, one row per linked camera)
19134
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
19135
+ * delivery / pick-up)
19136
+ *
19137
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
19138
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
19139
+ * this one field keeps the schema additive — a rule still declares exactly
19140
+ * one trigger.
19141
+ */
19142
+ var NcDeliverySchema = _enum([
19143
+ "immediate",
19144
+ "track-end",
19145
+ "device-event",
19146
+ "package-event"
19147
+ ]);
19148
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
19149
+ var NcScheduleSchema = object({
19150
+ windows: array(object({
19151
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
19152
+ days: array(number().int().min(0).max(6)).min(1),
19153
+ startMinute: number().int().min(0).max(1439),
19154
+ endMinute: number().int().min(0).max(1439)
19155
+ })).min(1),
19156
+ /** IANA timezone; default = hub host timezone. */
19157
+ timezone: string().optional(),
19158
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
19159
+ invert: boolean().optional()
19160
+ });
19161
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
19162
+ var NcPlateMatcherSchema = object({
19163
+ values: array(string().min(1)).min(1),
19164
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
19165
+ maxDistance: number().int().min(0).max(3).default(1)
19166
+ });
19167
+ /**
19168
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
19169
+ * occupancy edge for a device — optionally narrowed to a single admin
19170
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
19171
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
19172
+ * - `became-free` — count crossed ≥ `count` → below it
19173
+ * - `>=` / `<=` — count is at/over or at/under `count`
19174
+ * `sustainSeconds` requires the condition hold continuously that long
19175
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
19176
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
19177
+ * the condition never matches. Confirmed edge-state survives addon restarts
19178
+ * (declared SQLite collection, reseeded on boot).
19179
+ */
19180
+ var NcOccupancyConditionSchema = object({
19181
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
19182
+ zoneId: string().optional(),
19183
+ /** Object class to count; absent = any class. */
19184
+ className: string().optional(),
19185
+ op: _enum([
19186
+ "became-occupied",
19187
+ "became-free",
19188
+ ">=",
19189
+ "<="
19190
+ ]).default("became-occupied"),
19191
+ count: number().int().min(0).default(1),
19192
+ sustainSeconds: number().int().min(0).max(3600).default(15)
19193
+ });
19194
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
19195
+ var NcZoneConditionSchema = object({
19196
+ ids: array(string().min(1)).min(1),
19197
+ /** Quantifier over `ids` — at least one / every one visited. */
19198
+ match: _enum(["any", "all"]).default("any")
19199
+ });
19200
+ /**
19201
+ * The P1 condition set — a flat AND of groups; absent group = pass;
19202
+ * membership lists are OR within the list (spec §2.3).
19203
+ */
19204
+ var NcConditionsSchema = object({
19205
+ /** Device scope — absent = all devices. */
19206
+ devices: array(number()).optional(),
19207
+ /** Detector class names (any overlap with the record's class set). */
19208
+ classes: array(string().min(1)).optional(),
19209
+ /** Veto classes — any overlap fails the rule. */
19210
+ classesExclude: array(string().min(1)).optional(),
19211
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
19212
+ minConfidence: number().min(0).max(1).optional(),
19213
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
19214
+ zones: NcZoneConditionSchema.optional(),
19215
+ /** Veto zones — any hit fails the rule. */
19216
+ zonesExclude: array(string().min(1)).optional(),
19217
+ /**
19218
+ * Exact (case-insensitive) match on the record's collapsed `label`
19219
+ * (identity name / plate text / subclass).
19220
+ */
19221
+ labelEquals: array(string().min(1)).optional(),
19222
+ /**
19223
+ * Identity matcher. P1 boundary: matched against the record's collapsed
19224
+ * `label` (the identity display name propagated by the face pipeline) —
19225
+ * identity-ID matching rides in P2 when identity ids reach the record.
19226
+ */
19227
+ identities: array(string().min(1)).optional(),
19228
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
19229
+ plates: NcPlateMatcherSchema.optional(),
19230
+ /**
19231
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
19232
+ * Same P1 boundary: matched against the record's collapsed `label` (the
19233
+ * identity display name). A record with NO label passes (nothing to
19234
+ * exclude), unlike the include variant which fails on an absent label.
19235
+ */
19236
+ identitiesExclude: array(string().min(1)).optional(),
19237
+ /**
19238
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
19239
+ * TRACK-END only: importance is scored at track close, so it does not exist
19240
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
19241
+ * close the value is threaded via the close-time info (the `Track` clone is
19242
+ * captured before the DB row is updated, so it would otherwise read stale).
19243
+ * Fails when the record carries no importance (never guess quality — the
19244
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
19245
+ */
19246
+ minImportance: number().min(0).max(1).optional(),
19247
+ /**
19248
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
19249
+ * TRACK-END only: an `immediate` / object-event subject has no closed
19250
+ * lifespan, so a dwell condition never matches immediate delivery
19251
+ * (documented choice — the object-event record carries no `firstSeen`,
19252
+ * so dwell cannot be computed from what the subject actually carries).
19253
+ */
19254
+ minDwellSeconds: number().min(0).optional(),
19255
+ /**
19256
+ * Detection provenance filter. `any` (default / absent) matches every
19257
+ * source; otherwise the subject's source must equal it. Legacy records
19258
+ * with no stamped source are treated as `pipeline`. The union spans both
19259
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
19260
+ * tracks carry `sensor`.
19261
+ */
19262
+ source: _enum([
19263
+ "pipeline",
19264
+ "onboard",
19265
+ "sensor",
19266
+ "any"
19267
+ ]).optional(),
19268
+ /**
19269
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
19270
+ * detector `minConfidence` (that gates the object-detection score; this
19271
+ * gates the recognition/OCR match score). Fails when the subject carries
19272
+ * no label-match confidence (never guess). TRACK-END only: the confidence
19273
+ * lives on the recognition result and reaches the subject at track close.
19274
+ *
19275
+ * What it measures precisely (plumbed at track close — the closer threads
19276
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
19277
+ * `importance`): the BEST recognition match confidence observed for the
19278
+ * label the track carries at close — for a face, the peak cosine similarity
19279
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
19280
+ * for a plate, the peak OCR read score of the best-held plate
19281
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
19282
+ * one track the higher of the two is used. A track that ended with no
19283
+ * confident identity/plate match carries no value, so the condition fails
19284
+ * closed for it (an un-recognized subject).
19285
+ */
19286
+ minLabelConfidence: number().min(0).max(1).optional(),
19287
+ /**
19288
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
19289
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
19290
+ * against the token carried on the device-event subject (extracted from the
19291
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
19292
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
19293
+ * eventType, so gate those with {@link sensorKinds} instead.
19294
+ */
19295
+ eventTypeTokens: array(string().min(1)).optional(),
19296
+ /**
19297
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
19298
+ * `contact`, `button`, `device-event`) — matched against the persisted
19299
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
19300
+ */
19301
+ sensorKinds: array(string().min(1)).optional(),
19302
+ /**
19303
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
19304
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
19305
+ * when the subject's phase does not match (a subject always carries a phase
19306
+ * on the package-event trigger).
19307
+ */
19308
+ packagePhase: _enum([
19309
+ "delivered",
19310
+ "picked-up",
19311
+ "both"
19312
+ ]).optional(),
19313
+ /**
19314
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
19315
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
19316
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
19317
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
19318
+ */
19319
+ customZones: array(MaskPolygonShapeSchema).optional(),
19320
+ /**
19321
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
19322
+ * (optionally zone/class-scoped) occupancy count crosses the configured
19323
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
19324
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
19325
+ */
19326
+ occupancy: NcOccupancyConditionSchema.optional()
19327
+ });
19328
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
19329
+ var NcRuleTargetSchema = object({
19330
+ /** `notification-output` Target id. */
19331
+ targetId: string().min(1),
19332
+ /**
19333
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
19334
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
19335
+ * degrade engine drops what the backend can't render.
19336
+ */
19337
+ params: record(string(), unknown()).optional()
19338
+ });
19339
+ /**
19340
+ * Media attachment policy (P1 still-image subset).
19341
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
19342
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
19343
+ * matched on identities attaches the subject's `faceCrop`, one matched on
19344
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
19345
+ * (or when the specific crop is missing) degrades to `best`, then
19346
+ * `keyFrame`, then no attachment — never delaying the send. The matched
19347
+ * condition summary is frozen on the outbox row at enqueue (like the rule
19348
+ * name), so the choice never drifts from the record that fired it.
19349
+ * - `keyFrame` — the clean scene frame (no subject box).
19350
+ * - `none` — no attachment.
19351
+ */
19352
+ var NcMediaPolicySchema = object({ attach: _enum([
19353
+ "best",
19354
+ "best-matching",
19355
+ "keyFrame",
19356
+ "none"
19357
+ ]).default("best") });
19358
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
19359
+ var NcThrottleSchema = object({
19360
+ cooldownSec: number().int().min(0).max(86400).default(60),
19361
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
19362
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
19363
+ });
19364
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
19365
+ var NcRuleInputSchema = object({
19366
+ name: string().min(1).max(200),
19367
+ enabled: boolean().default(true),
19368
+ delivery: NcDeliverySchema,
19369
+ conditions: NcConditionsSchema.default({}),
19370
+ schedule: NcScheduleSchema.optional(),
19371
+ targets: array(NcRuleTargetSchema).min(1),
19372
+ media: NcMediaPolicySchema.default({ attach: "best" }),
19373
+ throttle: NcThrottleSchema.default({
19374
+ cooldownSec: 60,
19375
+ scope: "rule-device"
19376
+ }),
19377
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
19378
+ template: object({
19379
+ title: string().max(500).optional(),
19380
+ body: string().max(2e3).optional()
19381
+ }).optional(),
19382
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
19383
+ priority: number().int().min(1).max(5).default(3),
19384
+ /**
19385
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
19386
+ * behaviour, visible to all, read-only in the viewer). Present = personal
19387
+ * rule owned by this userId. Server-stamped; never trusted from a client.
19388
+ */
19389
+ ownerUserId: string().optional()
19390
+ });
19391
+ /**
19392
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
19393
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
19394
+ * NOT a client-authored input field (it lives on the persisted rule, not the
19395
+ * input), so it is added here explicitly to let the store's per-target opt-out
19396
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
19397
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
19398
+ * `updateRule` patch.
19399
+ */
19400
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
19401
+ /** A persisted rule. */
19402
+ var NcRuleSchema = NcRuleInputSchema.extend({
19403
+ id: string(),
19404
+ /** userId of the admin who created the rule (server-stamped caller). */
19405
+ createdBy: string(),
19406
+ createdAt: number(),
19407
+ updatedAt: number(),
19408
+ /**
19409
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
19410
+ * send time. Only a target's OWNER may add/remove its id (server-checked
19411
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
19412
+ */
19413
+ disabledTargetIds: array(string()).default([])
19414
+ });
19415
+ var NcTestResultSchema = object({
19416
+ recordId: string(),
19417
+ recordKind: _enum([
19418
+ "object-event",
19419
+ "track",
19420
+ "device-event",
19421
+ "package-event"
19422
+ ]),
19423
+ deviceId: number(),
19424
+ timestamp: number(),
19425
+ wouldFire: boolean(),
19426
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
19427
+ failedCondition: string().optional(),
19428
+ className: string().optional(),
19429
+ label: string().optional()
19430
+ });
19431
+ var NcConditionDescriptorSchema = object({
19432
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
19016
19433
  id: string(),
19434
+ group: _enum([
19435
+ "scope",
19436
+ "class",
19437
+ "zones",
19438
+ "quality",
19439
+ "label",
19440
+ "schedule",
19441
+ "device",
19442
+ "package",
19443
+ "occupancy"
19444
+ ]),
19017
19445
  label: string(),
19018
- family: string(),
19019
- purpose: _enum(["text", "vision"]),
19020
- url: string(),
19021
- sha256: string(),
19022
- sizeBytes: number(),
19023
- quantization: string(),
19024
- /** Load-time guidance shown in the picker. */
19025
- minRamBytes: number(),
19026
- contextSizeDefault: number().int(),
19027
- /** Vision models: companion projector file. */
19028
- mmprojUrl: string().optional()
19446
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
19447
+ valueType: _enum([
19448
+ "deviceIdList",
19449
+ "stringList",
19450
+ "number01",
19451
+ "number",
19452
+ "sourceSelect",
19453
+ "zoneSelection",
19454
+ "zoneIdList",
19455
+ "schedule",
19456
+ "plateMatcher",
19457
+ "packagePhase",
19458
+ "polygonDraw",
19459
+ "occupancy"
19460
+ ]),
19461
+ operator: _enum([
19462
+ "in",
19463
+ "notIn",
19464
+ "anyOf",
19465
+ "allOf",
19466
+ "gte",
19467
+ "fuzzyIn",
19468
+ "withinSchedule"
19469
+ ]),
19470
+ /** Which delivery kinds the condition applies to. */
19471
+ appliesTo: array(NcDeliverySchema),
19472
+ phase: string(),
19473
+ description: string().optional()
19029
19474
  });
19030
- var LlmRuntimeNodeSchema = object({
19031
- nodeId: string(),
19032
- reachable: boolean(),
19033
- status: LlmRuntimeStatusSchema.optional(),
19034
- disk: LlmRuntimeDiskUsageSchema.optional(),
19035
- error: string().optional()
19475
+ /**
19476
+ * The delivery lifecycle status of a history row — a straight read of the
19477
+ * durable outbox row's own status (single source of truth):
19478
+ * - `pending` — enqueued, in-flight or retrying with backoff
19479
+ * - `sent` — delivered (terminal)
19480
+ * - `dead` — dead-lettered after exhausting retries / a permanent
19481
+ * backend rejection / a deleted target (terminal; carries
19482
+ * the failure `error`)
19483
+ *
19484
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
19485
+ * user dimension (quiet hours / snooze) and are additive when they land.
19486
+ */
19487
+ var NcHistoryStatusSchema = _enum([
19488
+ "pending",
19489
+ "sent",
19490
+ "dead"
19491
+ ]);
19492
+ /** The evaluated record kind a history row descends from (one per trigger). */
19493
+ var NcHistoryRecordKindSchema = _enum([
19494
+ "object-event",
19495
+ "track-end",
19496
+ "device-event",
19497
+ "package-event"
19498
+ ]);
19499
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
19500
+ var NcHistorySubjectSchema = object({
19501
+ className: string(),
19502
+ label: string().optional(),
19503
+ confidence: number().optional(),
19504
+ zones: array(string()),
19505
+ timestamp: number()
19506
+ });
19507
+ /**
19508
+ * One delivery-history row. This is a read-only VIEW over the durable
19509
+ * outbox row (single source of truth — the same row the drain loop drives;
19510
+ * NO second write path, so history can never drift from delivery state).
19511
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
19512
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
19513
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
19514
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
19515
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
19516
+ * P1 (admin scope only).
19517
+ */
19518
+ var NcHistoryEntrySchema = object({
19519
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
19520
+ id: string(),
19521
+ ruleId: string(),
19522
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
19523
+ ruleName: string(),
19524
+ /** The rule urgency/trigger that produced this delivery. */
19525
+ delivery: NcDeliverySchema,
19526
+ targetId: string(),
19527
+ deviceId: number(),
19528
+ recordKind: NcHistoryRecordKindSchema,
19529
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
19530
+ recordId: string(),
19531
+ /** Present for track-scoped deliveries (object-event / track-end). */
19532
+ trackId: string().optional(),
19533
+ status: NcHistoryStatusSchema,
19534
+ /** Delivery attempts made so far. */
19535
+ attempts: number().int(),
19536
+ /** Fire time (outbox enqueue). */
19537
+ createdAt: number(),
19538
+ /** Last transition time (terminal for sent / dead). */
19539
+ updatedAt: number(),
19540
+ /** Failure detail — present on a `dead` row. */
19541
+ error: string().optional(),
19542
+ subject: NcHistorySubjectSchema
19036
19543
  });
19037
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
19038
- var ProfileRefInputSchema = object({
19039
- addonId: string(),
19040
- profileId: string()
19544
+ /**
19545
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
19546
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
19547
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
19548
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
19549
+ */
19550
+ var NcHistoryFilterSchema = object({
19551
+ ruleId: string().optional(),
19552
+ deviceId: number().optional(),
19553
+ status: NcHistoryStatusSchema.optional(),
19554
+ since: number().optional(),
19555
+ until: number().optional(),
19556
+ limit: number().int().min(1).max(500).default(100)
19041
19557
  });
19042
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
19043
- kind: "mutation",
19044
- auth: "admin"
19045
- }), method(ProfileRefInputSchema, _void(), {
19558
+ 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 }), {
19046
19559
  kind: "mutation",
19047
- auth: "admin"
19048
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
19560
+ auth: "admin",
19561
+ caller: "required"
19562
+ }), method(object({
19563
+ ruleId: string(),
19564
+ patch: NcRulePatchSchema
19565
+ }), object({ rule: NcRuleSchema }), {
19049
19566
  kind: "mutation",
19050
- auth: "admin"
19051
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
19052
- selector: LlmDefaultSelectorSchema,
19053
- profileId: string().nullable()
19054
- }), _void(), {
19567
+ auth: "admin",
19568
+ caller: "required"
19569
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
19055
19570
  kind: "mutation",
19056
19571
  auth: "admin"
19057
19572
  }), method(object({
19058
- since: number().optional(),
19059
- until: number().optional(),
19060
- consumer: string().optional(),
19061
- profileId: string().optional()
19062
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
19063
- nodeId: string(),
19064
- model: ManagedModelRefSchema
19065
- }), _void(), {
19573
+ ruleId: string(),
19574
+ enabled: boolean()
19575
+ }), object({ success: literal(true) }), {
19066
19576
  kind: "mutation",
19067
19577
  auth: "admin"
19068
19578
  }), method(object({
19069
- nodeId: string(),
19070
- file: string()
19071
- }), _void(), {
19072
- kind: "mutation",
19073
- auth: "admin"
19074
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
19075
- kind: "mutation",
19076
- auth: "admin"
19077
- }), method(ProfileRefInputSchema, _void(), {
19579
+ rule: NcRuleInputSchema,
19580
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
19581
+ }), object({ results: array(NcTestResultSchema) }), {
19078
19582
  kind: "mutation",
19079
19583
  auth: "admin"
19080
- });
19584
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
19081
19585
  /**
19082
19586
  * Zod schemas for persisted record types.
19083
19587
  *
@@ -19763,7 +20267,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19763
20267
  }), method(object({
19764
20268
  eventId: string(),
19765
20269
  kind: MediaFileKindEnum.optional()
19766
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
20270
+ }), array(MediaFileSchema).readonly()), method(object({
20271
+ trackId: string(),
20272
+ kinds: array(MediaFileKindEnum).optional()
20273
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
19767
20274
  deviceId: number(),
19768
20275
  timestamp: number(),
19769
20276
  frameWidth: number(),
@@ -19784,76 +20291,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19784
20291
  eventId: string(),
19785
20292
  timestamp: number()
19786
20293
  });
19787
- /**
19788
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
19789
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
19790
- * caps into per-camera event-kind descriptors.
19791
- *
19792
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
19793
- * is NOT duplicated here — every entry is derived from the single
19794
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
19795
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
19796
- * control cap means adding one line here (and a taxonomy entry); the anti-
19797
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
19798
- * eventful cap is missing.
19799
- */
19800
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
19801
- var LEGACY_ICON = {
19802
- motion: "motion",
19803
- audio: "audio",
19804
- person: "person",
19805
- vehicle: "vehicle",
19806
- animal: "animal",
19807
- package: "package",
19808
- door: "door",
19809
- pir: "pir",
19810
- smoke: "smoke",
19811
- water: "water",
19812
- button: "button",
19813
- generic: "generic",
19814
- gas: "smoke",
19815
- vibration: "generic",
19816
- tamper: "generic",
19817
- presence: "person",
19818
- lock: "generic",
19819
- siren: "generic",
19820
- switch: "generic",
19821
- doorbell: "button"
19822
- };
19823
- function legacyIcon(iconId) {
19824
- return LEGACY_ICON[iconId] ?? "generic";
19825
- }
19826
- /**
19827
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
19828
- * The anti-drift guard cross-checks this against the eventful caps declared
19829
- * in `packages/types/src/capabilities/*.cap.ts`.
19830
- */
19831
- var CAP_TO_KIND = {
19832
- contact: "contact",
19833
- motion: "motion-sensor",
19834
- smoke: "smoke",
19835
- flood: "flood",
19836
- gas: "gas",
19837
- "carbon-monoxide": "carbon-monoxide",
19838
- vibration: "vibration",
19839
- tamper: "tamper",
19840
- presence: "presence",
19841
- "enum-sensor": "enum-sensor",
19842
- "event-emitter": "device-event",
19843
- "lock-control": "lock",
19844
- switch: "switch",
19845
- button: "button",
19846
- doorbell: "doorbell"
19847
- };
19848
- function buildDescriptor(capName, kind) {
19849
- const t = EVENT_TAXONOMY[kind];
19850
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
19851
- return {
19852
- ...t,
19853
- icon: legacyIcon(t.iconId)
19854
- };
19855
- }
19856
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
19857
20294
  var CameraPipelineConfigSchema = object({
19858
20295
  engine: PipelineEngineChoiceSchema.optional(),
19859
20296
  steps: array(PipelineStepInputSchema).readonly(),
@@ -20339,6 +20776,76 @@ method(object({
20339
20776
  auth: "admin"
20340
20777
  });
20341
20778
  /**
20779
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
20780
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
20781
+ * caps into per-camera event-kind descriptors.
20782
+ *
20783
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
20784
+ * is NOT duplicated here — every entry is derived from the single
20785
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
20786
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
20787
+ * control cap means adding one line here (and a taxonomy entry); the anti-
20788
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
20789
+ * eventful cap is missing.
20790
+ */
20791
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
20792
+ var LEGACY_ICON = {
20793
+ motion: "motion",
20794
+ audio: "audio",
20795
+ person: "person",
20796
+ vehicle: "vehicle",
20797
+ animal: "animal",
20798
+ package: "package",
20799
+ door: "door",
20800
+ pir: "pir",
20801
+ smoke: "smoke",
20802
+ water: "water",
20803
+ button: "button",
20804
+ generic: "generic",
20805
+ gas: "smoke",
20806
+ vibration: "generic",
20807
+ tamper: "generic",
20808
+ presence: "person",
20809
+ lock: "generic",
20810
+ siren: "generic",
20811
+ switch: "generic",
20812
+ doorbell: "button"
20813
+ };
20814
+ function legacyIcon(iconId) {
20815
+ return LEGACY_ICON[iconId] ?? "generic";
20816
+ }
20817
+ /**
20818
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
20819
+ * The anti-drift guard cross-checks this against the eventful caps declared
20820
+ * in `packages/types/src/capabilities/*.cap.ts`.
20821
+ */
20822
+ var CAP_TO_KIND = {
20823
+ contact: "contact",
20824
+ motion: "motion-sensor",
20825
+ smoke: "smoke",
20826
+ flood: "flood",
20827
+ gas: "gas",
20828
+ "carbon-monoxide": "carbon-monoxide",
20829
+ vibration: "vibration",
20830
+ tamper: "tamper",
20831
+ presence: "presence",
20832
+ "enum-sensor": "enum-sensor",
20833
+ "event-emitter": "device-event",
20834
+ "lock-control": "lock",
20835
+ switch: "switch",
20836
+ button: "button",
20837
+ doorbell: "doorbell"
20838
+ };
20839
+ function buildDescriptor(capName, kind) {
20840
+ const t = EVENT_TAXONOMY[kind];
20841
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
20842
+ return {
20843
+ ...t,
20844
+ icon: legacyIcon(t.iconId)
20845
+ };
20846
+ }
20847
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
20848
+ /**
20342
20849
  * server-management — per-NODE singleton capability for a node's ROOT
20343
20850
  * package lifecycle (runtime-updatable node packages).
20344
20851
  *
@@ -21793,7 +22300,28 @@ var FaceInfoSchema = object({
21793
22300
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
21794
22301
  * track produced no key frame (e.g. native/onboard source) — the UI falls
21795
22302
  * back to the inline `base64` face crop. */
21796
- keyFrameMediaKey: string().optional()
22303
+ keyFrameMediaKey: string().optional(),
22304
+ /** Winning identity-match cosine (0..1) for this face's track, when an
22305
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
22306
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
22307
+ * faces that were never auto-recognized. */
22308
+ bestMatchScore: number().optional(),
22309
+ /** Native-scale face short side (px) at recognition time, when the runner
22310
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
22311
+ * legacy rows / runners that reported no native measure. */
22312
+ nativeFaceShortSidePx: number().optional(),
22313
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
22314
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
22315
+ * but blocked only by the recognition size floor). Mutually exclusive with
22316
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
22317
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
22318
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
22319
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
22320
+ suggestedIdentityId: string().optional(),
22321
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
22322
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
22323
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
22324
+ suggestedMatchScore: number().optional()
21797
22325
  });
21798
22326
  var FaceFilterEnum = _enum([
21799
22327
  "unassigned",
@@ -23836,36 +24364,6 @@ Object.freeze({
23836
24364
  addonId: null,
23837
24365
  access: "view"
23838
24366
  },
23839
- "advancedNotifier.deleteRule": {
23840
- capName: "advanced-notifier",
23841
- capScope: "system",
23842
- addonId: null,
23843
- access: "delete"
23844
- },
23845
- "advancedNotifier.getHistory": {
23846
- capName: "advanced-notifier",
23847
- capScope: "system",
23848
- addonId: null,
23849
- access: "view"
23850
- },
23851
- "advancedNotifier.getRules": {
23852
- capName: "advanced-notifier",
23853
- capScope: "system",
23854
- addonId: null,
23855
- access: "view"
23856
- },
23857
- "advancedNotifier.testRule": {
23858
- capName: "advanced-notifier",
23859
- capScope: "system",
23860
- addonId: null,
23861
- access: "create"
23862
- },
23863
- "advancedNotifier.upsertRule": {
23864
- capName: "advanced-notifier",
23865
- capScope: "system",
23866
- addonId: null,
23867
- access: "create"
23868
- },
23869
24367
  "alarmPanel.arm": {
23870
24368
  capName: "alarm-panel",
23871
24369
  capScope: "device",
@@ -26170,6 +26668,60 @@ Object.freeze({
26170
26668
  addonId: null,
26171
26669
  access: "create"
26172
26670
  },
26671
+ "notificationRules.createRule": {
26672
+ capName: "notification-rules",
26673
+ capScope: "system",
26674
+ addonId: null,
26675
+ access: "create"
26676
+ },
26677
+ "notificationRules.deleteRule": {
26678
+ capName: "notification-rules",
26679
+ capScope: "system",
26680
+ addonId: null,
26681
+ access: "delete"
26682
+ },
26683
+ "notificationRules.getConditionCatalog": {
26684
+ capName: "notification-rules",
26685
+ capScope: "system",
26686
+ addonId: null,
26687
+ access: "view"
26688
+ },
26689
+ "notificationRules.getHistory": {
26690
+ capName: "notification-rules",
26691
+ capScope: "system",
26692
+ addonId: null,
26693
+ access: "view"
26694
+ },
26695
+ "notificationRules.getRule": {
26696
+ capName: "notification-rules",
26697
+ capScope: "system",
26698
+ addonId: null,
26699
+ access: "view"
26700
+ },
26701
+ "notificationRules.listRules": {
26702
+ capName: "notification-rules",
26703
+ capScope: "system",
26704
+ addonId: null,
26705
+ access: "view"
26706
+ },
26707
+ "notificationRules.setRuleEnabled": {
26708
+ capName: "notification-rules",
26709
+ capScope: "system",
26710
+ addonId: null,
26711
+ access: "create"
26712
+ },
26713
+ "notificationRules.testRule": {
26714
+ capName: "notification-rules",
26715
+ capScope: "system",
26716
+ addonId: null,
26717
+ access: "create"
26718
+ },
26719
+ "notificationRules.updateRule": {
26720
+ capName: "notification-rules",
26721
+ capScope: "system",
26722
+ addonId: null,
26723
+ access: "create"
26724
+ },
26173
26725
  "notifier.cancel": {
26174
26726
  capName: "notifier",
26175
26727
  capScope: "device",