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