@camstack/addon-provider-rtsp 1.2.3 → 1.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
@@ -23,7 +23,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  //#endregion
24
24
  let node_net = require("node:net");
25
25
  node_net = __toESM(node_net);
26
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
26
+ //#region ../types/dist/event-category-BLcNejAE.mjs
27
27
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
28
28
  EventCategory["SystemBoot"] = "system.boot";
29
29
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -173,9 +173,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
173
173
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
174
174
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
175
175
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
176
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
177
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
178
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
179
176
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
180
177
  * progress bar the client reconciles via `recordingExport.getExport`. */
181
178
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6854,7 +6851,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6854
6851
  patch: record(string(), unknown())
6855
6852
  }), object({ success: literal(true) });
6856
6853
  object({ deviceId: number() }), unknown().nullable();
6857
- /** Shorthand to define a method schema */
6858
6854
  function method(input, output, options) {
6859
6855
  return {
6860
6856
  input,
@@ -6862,6 +6858,7 @@ function method(input, output, options) {
6862
6858
  kind: options?.kind ?? "query",
6863
6859
  auth: options?.auth ?? "protected",
6864
6860
  ...options?.access !== void 0 ? { access: options.access } : {},
6861
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6865
6862
  timeoutMs: options?.timeoutMs
6866
6863
  };
6867
6864
  }
@@ -8251,6 +8248,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8251
8248
  /** The complete taxonomy dictionary, keyed by kind. */
8252
8249
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8253
8250
  /**
8251
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8252
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8253
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8254
+ * taxonomy surface (timeline, filters, event page).
8255
+ *
8256
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8257
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8258
+ * for the `classes` / `classesExclude` conditions.
8259
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8260
+ * the same class picker, grouped under an Audio header.
8261
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8262
+ * lock / …) for the `sensorKinds` device-event condition.
8263
+ *
8264
+ * Each entry carries `parentKind` so the client can group video subs under
8265
+ * their macro and sensor/control kinds under their category. This surface is
8266
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8267
+ * method, no codegen — so it ships train-free with an addon deploy.
8268
+ */
8269
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8270
+ var NcTaxonomyEntrySchema = object({
8271
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8272
+ kind: string(),
8273
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8274
+ label: string(),
8275
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8276
+ parentKind: string().nullable()
8277
+ });
8278
+ object({
8279
+ videoClasses: array(NcTaxonomyEntrySchema),
8280
+ audioKinds: array(NcTaxonomyEntrySchema),
8281
+ labels: array(NcTaxonomyEntrySchema)
8282
+ });
8283
+ function toEntry(kind, label, parentKind) {
8284
+ return {
8285
+ kind,
8286
+ label,
8287
+ parentKind
8288
+ };
8289
+ }
8290
+ /**
8291
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8292
+ * (macros before their subs), which the client relies on for stable grouping.
8293
+ */
8294
+ function buildNcTaxonomy() {
8295
+ const all = Object.values(EVENT_TAXONOMY);
8296
+ return {
8297
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8298
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8299
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8300
+ };
8301
+ }
8302
+ Object.freeze(buildNcTaxonomy());
8303
+ /**
8254
8304
  * Error types for the safe expression engine. Two distinct classes so callers
8255
8305
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8256
8306
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -12302,6 +12352,22 @@ var CameraMetricsSchema = object({
12302
12352
  ])
12303
12353
  });
12304
12354
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
12355
+ /**
12356
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
12357
+ * within the frame, so the executor can re-cut a leaf child ROI at native
12358
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
12359
+ */
12360
+ var NativeCropRefSchema = object({
12361
+ /** Handle keying the retained native surface (node-pinned to its owner). */
12362
+ handle: FrameHandleSchema,
12363
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
12364
+ cropFrameSpace: object({
12365
+ x: number(),
12366
+ y: number(),
12367
+ w: number(),
12368
+ h: number()
12369
+ })
12370
+ });
12305
12371
  var ModelFormatSchema$1 = _enum([
12306
12372
  "onnx",
12307
12373
  "coreml",
@@ -12577,7 +12643,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
12577
12643
  * Omitted ⇒ the runner's default device (current single-engine
12578
12644
  * behaviour). Selects WHICH device pool of the node runs the call.
12579
12645
  */
12580
- deviceKey: string().optional()
12646
+ deviceKey: string().optional(),
12647
+ /**
12648
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
12649
+ * when the parent crop was resolved from the frame's retained NATIVE
12650
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
12651
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
12652
+ * resolution from that surface — the SAME quality path faces already
12653
+ * had — instead of the downscaled parent tile. `handle` keys the native
12654
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
12655
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
12656
+ * the executor's crop-normalized child ROI back into frame-normalized
12657
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
12658
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
12659
+ * (today's behaviour on the fallback path).
12660
+ */
12661
+ nativeCropRef: NativeCropRefSchema.optional()
12581
12662
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
12582
12663
  engine: PipelineEngineChoiceSchema.optional(),
12583
12664
  steps: array(PipelineStepInputSchema).min(1),
@@ -12826,7 +12907,11 @@ var DetailResultSchema = object({
12826
12907
  bbox: NativeCropBboxSchema.optional(),
12827
12908
  embedding: string().optional(),
12828
12909
  label: string().optional(),
12829
- alignedCropJpeg: string().optional()
12910
+ alignedCropJpeg: string().optional(),
12911
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
12912
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
12913
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
12914
+ nativeFaceShortSidePx: number().optional()
12830
12915
  });
12831
12916
  /**
12832
12917
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -12840,6 +12925,12 @@ var motionCooldownMsField = {
12840
12925
  default: 3e4,
12841
12926
  step: 500
12842
12927
  };
12928
+ var maxSessionHoldMsField = {
12929
+ min: 0,
12930
+ max: 6e5,
12931
+ default: 12e4,
12932
+ step: 5e3
12933
+ };
12843
12934
  var motionFpsField = {
12844
12935
  min: 1,
12845
12936
  max: 30,
@@ -12987,6 +13078,19 @@ var RunnerCameraConfigSchema = object({
12987
13078
  "on-motion"
12988
13079
  ]).default("always-on"),
12989
13080
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
13081
+ /**
13082
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
13083
+ * detection session is active and ≥1 confirmed non-stationary track is
13084
+ * still live, the orchestrator keeps the session open past
13085
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
13086
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
13087
+ * ms since the session opened, after which it closes regardless. `0`
13088
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
13089
+ * runner itself — carried here so it shares the per-camera device-settings
13090
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
13091
+ * resolved `CameraDetectionConfig`.
13092
+ */
13093
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
12990
13094
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
12991
13095
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
12992
13096
  motionStreamId: string(),
@@ -13076,7 +13180,7 @@ var RunnerCameraConfigSchema = object({
13076
13180
  */
13077
13181
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
13078
13182
  });
13079
- 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;
13183
+ 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;
13080
13184
  /**
13081
13185
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
13082
13186
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -16603,94 +16707,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
16603
16707
  bundleUrl: string()
16604
16708
  });
16605
16709
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
16606
- var NotificationRuleConditionsSchema = object({
16607
- deviceIds: array(number()).readonly().optional(),
16608
- classNames: array(string()).readonly().optional(),
16609
- zoneIds: array(string()).readonly().optional(),
16610
- minConfidence: number().optional(),
16611
- source: _enum([
16612
- "pipeline",
16613
- "onboard",
16614
- "any"
16615
- ]).optional(),
16616
- schedule: object({
16617
- days: array(number()).readonly(),
16618
- startHour: number(),
16619
- endHour: number()
16620
- }).optional(),
16621
- cooldownSeconds: number().optional(),
16622
- minDwellSeconds: number().optional(),
16623
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
16624
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
16625
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
16626
- eventTypeTokens: array(string()).readonly().optional(),
16627
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
16628
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
16629
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
16630
- clipDescription: object({
16631
- text: string().min(1),
16632
- minSimilarity: number().min(0).max(1)
16633
- }).optional(),
16634
- /** Match events whose recognized-entity label (face identity name or plate
16635
- * vehicle name, propagated onto `event.data.label`) is one of these values.
16636
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
16637
- * vehicle/person> is seen". */
16638
- labels: array(string()).readonly().optional()
16639
- });
16640
- var NotificationRuleTemplateSchema = object({
16641
- title: string(),
16642
- body: string(),
16643
- imageMode: _enum([
16644
- "crop",
16645
- "annotated",
16646
- "full",
16647
- "none"
16648
- ])
16649
- });
16650
- var NotificationRuleSchema = object({
16651
- id: string(),
16652
- name: string(),
16653
- enabled: boolean(),
16654
- eventTypes: array(string()).readonly(),
16655
- conditions: NotificationRuleConditionsSchema,
16656
- outputs: array(string()).readonly(),
16657
- template: NotificationRuleTemplateSchema.optional(),
16658
- priority: _enum([
16659
- "low",
16660
- "normal",
16661
- "high",
16662
- "critical"
16663
- ])
16664
- });
16665
- var NotificationTestResultSchema = object({
16666
- ruleId: string(),
16667
- eventId: string(),
16668
- timestamp: number(),
16669
- wouldFire: boolean(),
16670
- reason: string().optional()
16671
- });
16672
- var NotificationHistoryEntrySchema = object({
16673
- id: string(),
16674
- ruleId: string(),
16675
- ruleName: string(),
16676
- eventId: string(),
16677
- timestamp: number(),
16678
- outputs: array(string()).readonly(),
16679
- success: boolean(),
16680
- error: string().optional(),
16681
- deviceId: number().optional()
16682
- });
16683
- var NotificationHistoryFilterSchema = object({
16684
- ruleId: string().optional(),
16685
- deviceId: number().optional(),
16686
- from: number().optional(),
16687
- to: number().optional(),
16688
- limit: number().optional()
16689
- });
16690
- 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({
16691
- ruleId: string(),
16692
- lookbackMinutes: number()
16693
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
16694
16710
  /**
16695
16711
  * Alerts capability — collection-based internal alert system.
16696
16712
  *
@@ -16877,89 +16893,6 @@ method(object({
16877
16893
  password: string()
16878
16894
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
16879
16895
  /**
16880
- * `login-method` — collection cap through which auth addons contribute
16881
- * their pre-auth login surfaces to the login page. This is the SINGLE,
16882
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
16883
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
16884
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
16885
- * procedure aggregates them for the unauthenticated login page.
16886
- *
16887
- * A contribution is a discriminated union on `kind`:
16888
- *
16889
- * - `redirect` — a declarative button. The login page renders a generic
16890
- * button that navigates to `startUrl` (an addon-owned HTTP route).
16891
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
16892
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
16893
- * login page needs NO change.
16894
- *
16895
- * - `widget` — a Module-Federation widget the login page mounts (via
16896
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
16897
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
16898
- * mechanism kept for future use; no shipped addon uses it on the login
16899
- * page (the passkey ceremony below runs natively in the shell instead).
16900
- *
16901
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
16902
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
16903
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
16904
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
16905
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
16906
- * fetching any remote code pre-auth. Contribution stays unconditional —
16907
- * enrollment state is never leaked pre-auth; visibility is a shell
16908
- * decision.
16909
- *
16910
- * Every contribution carries a `stage`:
16911
- * - `primary` — shown on the first credentials screen (OIDC /
16912
- * magic-link buttons; a future usernameless passkey).
16913
- * - `second-factor` — shown AFTER the password leg, gated on the
16914
- * returned `factors` (passkey-as-2FA today).
16915
- *
16916
- * `mount: skip` — the cap is read server-side by the core auth router
16917
- * (`registry.getCollection('login-method')`), never mounted as its own
16918
- * tRPC router.
16919
- */
16920
- /** When a login method renders in the two-phase login flow. */
16921
- var LoginStageEnum = _enum(["primary", "second-factor"]);
16922
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
16923
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
16924
- object({
16925
- kind: literal("redirect"),
16926
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
16927
- id: string(),
16928
- /** Operator-facing button label. */
16929
- label: string(),
16930
- /** lucide-react icon name. */
16931
- icon: string().optional(),
16932
- /** Addon-owned HTTP route the button navigates to (GET). */
16933
- startUrl: string(),
16934
- stage: LoginStageEnum
16935
- }),
16936
- object({
16937
- kind: literal("widget"),
16938
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
16939
- id: string(),
16940
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
16941
- addonId: string(),
16942
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
16943
- bundle: string(),
16944
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
16945
- remote: WidgetRemoteSchema,
16946
- stage: LoginStageEnum
16947
- }),
16948
- object({
16949
- kind: literal("passkey"),
16950
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
16951
- id: string(),
16952
- /** Operator-facing button label. */
16953
- label: string(),
16954
- stage: LoginStageEnum,
16955
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
16956
- rpId: string(),
16957
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
16958
- origin: string().nullable()
16959
- })
16960
- ]);
16961
- method(_void(), array(LoginMethodContributionSchema).readonly());
16962
- /**
16963
16896
  * Orchestrator-side destination metadata. The orchestrator computes
16964
16897
  * `id = <addonId>:<subId>` from its provider lookup so consumers
16965
16898
  * (admin UI, restore flow) see one canonical key.
@@ -18303,242 +18236,617 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
18303
18236
  kind: "mutation",
18304
18237
  auth: "admin"
18305
18238
  });
18306
- var LogLevelSchema = _enum([
18307
- "debug",
18308
- "info",
18309
- "warn",
18310
- "error"
18239
+ /**
18240
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18241
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18242
+ * caps stay wire-compatible without a circular cap→cap import.
18243
+ *
18244
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
18245
+ * every transport tier structurally, and failed calls still write usage rows.
18246
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18247
+ */
18248
+ var LlmUsageSchema = object({
18249
+ inputTokens: number(),
18250
+ outputTokens: number()
18251
+ });
18252
+ var LlmErrorCodeSchema = _enum([
18253
+ "timeout",
18254
+ "rate-limited",
18255
+ "auth",
18256
+ "refusal",
18257
+ "bad-request",
18258
+ "unavailable",
18259
+ "no-profile",
18260
+ "budget-exceeded",
18261
+ "adapter-error"
18311
18262
  ]);
18312
- var LogEntrySchema = object({
18313
- timestamp: date(),
18314
- level: LogLevelSchema,
18315
- scope: array(string()),
18263
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18264
+ ok: literal(true),
18265
+ text: string(),
18266
+ model: string(),
18267
+ usage: LlmUsageSchema,
18268
+ truncated: boolean(),
18269
+ latencyMs: number()
18270
+ }), object({
18271
+ ok: literal(false),
18272
+ code: LlmErrorCodeSchema,
18316
18273
  message: string(),
18317
- meta: record(string(), unknown()).optional(),
18318
- tags: record(string(), string()).optional()
18319
- });
18320
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18321
- scope: array(string()).optional(),
18322
- level: LogLevelSchema.optional(),
18323
- since: date().optional(),
18324
- until: date().optional(),
18325
- limit: number().optional(),
18326
- tags: record(string(), string()).optional()
18327
- }), array(LogEntrySchema).readonly());
18328
- var CpuBreakdownSchema = object({
18329
- total: number(),
18330
- user: number(),
18331
- system: number(),
18332
- irq: number(),
18333
- nice: number(),
18334
- loadAvg: tuple([
18335
- number(),
18336
- number(),
18337
- number()
18338
- ]),
18339
- cores: number()
18274
+ retryAfterMs: number().optional()
18275
+ })]);
18276
+ /**
18277
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18278
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18279
+ * notification-output.cap.ts:27-31 precedents).
18280
+ */
18281
+ var LlmImageSchema = object({
18282
+ bytes: _instanceof(Uint8Array),
18283
+ mimeType: string()
18340
18284
  });
18341
- var MemoryInfoSchema = object({
18342
- percent: number(),
18343
- totalBytes: number(),
18344
- usedBytes: number(),
18345
- availableBytes: number(),
18346
- swapUsedBytes: number(),
18347
- swapTotalBytes: number()
18285
+ var LlmGenerateBaseInputSchema = object({
18286
+ /** Collection routing (the notification-output posture). */
18287
+ addonId: string().optional(),
18288
+ /** Explicit profile; else the resolution chain (spec §3). */
18289
+ profileId: string().optional(),
18290
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18291
+ consumer: string(),
18292
+ system: string().optional(),
18293
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
18294
+ prompt: string(),
18295
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18296
+ jsonSchema: record(string(), unknown()).optional(),
18297
+ /** Per-call override of the profile default. */
18298
+ maxTokens: number().int().positive().optional(),
18299
+ temperature: number().optional()
18348
18300
  });
18349
- var DiskIoSnapshotSchema = object({
18350
- readBytes: number(),
18351
- writeBytes: number(),
18352
- readOps: number(),
18353
- writeOps: number(),
18354
- timestampMs: number()
18355
- });
18356
- var NetworkIoSnapshotSchema = object({
18357
- rxBytes: number(),
18358
- txBytes: number(),
18359
- rxPackets: number(),
18360
- txPackets: number(),
18361
- rxErrors: number(),
18362
- txErrors: number(),
18363
- timestampMs: number()
18364
- });
18365
- var MetricsGpuInfoSchema = object({
18366
- utilization: number(),
18367
- model: string(),
18368
- memoryUsedBytes: number(),
18369
- memoryTotalBytes: number(),
18370
- temperature: number().nullable()
18371
- });
18372
- var ProcessResourceInfoSchema = object({
18373
- openFds: number(),
18374
- threadCount: number(),
18375
- activeHandles: number(),
18376
- activeRequests: number()
18377
- });
18378
- var PressureAvgsSchema = object({
18379
- avg10: number(),
18380
- avg60: number(),
18381
- avg300: number()
18382
- });
18383
- var PressureInfoSchema = object({
18384
- some: PressureAvgsSchema,
18385
- full: PressureAvgsSchema.nullable()
18386
- });
18387
- var SystemResourceSnapshotSchema = object({
18388
- cpu: CpuBreakdownSchema,
18389
- memory: MemoryInfoSchema,
18390
- gpu: MetricsGpuInfoSchema.nullable(),
18391
- network: NetworkIoSnapshotSchema,
18392
- disk: DiskIoSnapshotSchema,
18393
- pressure: object({
18394
- cpu: PressureInfoSchema.nullable(),
18395
- memory: PressureInfoSchema.nullable(),
18396
- io: PressureInfoSchema.nullable()
18301
+ /**
18302
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18303
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18304
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18305
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18306
+ * this only through the `llm` cap's methods.
18307
+ *
18308
+ * One running llama-server child per node in v1 (models are RAM-heavy).
18309
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18310
+ * watchdog — operator decision #3).
18311
+ */
18312
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
18313
+ object({
18314
+ kind: literal("catalog"),
18315
+ catalogId: string()
18397
18316
  }),
18398
- process: ProcessResourceInfoSchema,
18399
- cpuTemperature: number().nullable(),
18400
- timestampMs: number()
18401
- });
18402
- var DiskSpaceInfoSchema = object({
18403
- path: string(),
18404
- totalBytes: number(),
18405
- usedBytes: number(),
18406
- availableBytes: number(),
18407
- percent: number()
18408
- });
18409
- var PidResourceStatsSchema = object({
18410
- pid: number(),
18411
- cpu: number(),
18412
- memory: number(),
18413
- /**
18414
- * Private (anonymous) resident bytes — the per-process V8 heap + native
18415
- * allocations NOT shared with other processes (Linux RssAnon). This is the
18416
- * "real" per-runner cost; summing it across runners is meaningful, unlike
18417
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
18418
- * Undefined where /proc is unavailable (e.g. macOS).
18419
- */
18420
- privateBytes: number().optional(),
18421
- /**
18422
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18423
- * code shared copy-on-write across runners. Undefined on macOS.
18424
- */
18425
- sharedBytes: number().optional()
18317
+ object({
18318
+ kind: literal("url"),
18319
+ url: string(),
18320
+ sha256: string().optional()
18321
+ }),
18322
+ object({
18323
+ kind: literal("path"),
18324
+ path: string()
18325
+ })
18326
+ ]);
18327
+ var ManagedRuntimeConfigSchema = object({
18328
+ /** WHERE the runtime lives — hub or any agent. */
18329
+ nodeId: string(),
18330
+ /** Closed for v1; 'ollama' is a v2 candidate. */
18331
+ engine: _enum(["llama-cpp"]),
18332
+ model: ManagedModelRefSchema,
18333
+ contextSize: number().int().default(4096),
18334
+ /** 0 = CPU-only. */
18335
+ gpuLayers: number().int().default(0),
18336
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18337
+ threads: number().int().optional(),
18338
+ /** Concurrent slots. */
18339
+ parallel: number().int().default(1),
18340
+ /** Else lazy: first generate boots it. */
18341
+ autoStart: boolean().default(false),
18342
+ /** 0 = never; frees RAM after quiet periods. */
18343
+ idleStopMinutes: number().int().default(30)
18426
18344
  });
18427
- var AddonInstanceSchema = object({
18428
- addonId: string(),
18345
+ var LlmRuntimeStatusSchema = object({
18346
+ /** Status is ALWAYS node-qualified. */
18429
18347
  nodeId: string(),
18430
- role: _enum(["hub", "worker"]),
18431
- pid: number(),
18432
18348
  state: _enum([
18433
- "starting",
18434
- "running",
18435
- "stopping",
18436
18349
  "stopped",
18437
- "crashed"
18438
- ]),
18439
- uptimeSec: number()
18440
- });
18441
- var NodeProcessSchema = object({
18442
- pid: number(),
18443
- ppid: number(),
18444
- pgid: number(),
18445
- classification: _enum([
18446
- "root",
18447
- "managed",
18448
- "system",
18449
- "ghost"
18350
+ "downloading",
18351
+ "starting",
18352
+ "ready",
18353
+ "crashed",
18354
+ "failed"
18450
18355
  ]),
18451
- /** `$process` addon binding when `managed`, else null. */
18452
- addonId: string().nullable(),
18453
- /** Kernel-reported nodeId when the process is a known agent/worker. */
18454
- nodeId: string().nullable(),
18455
- /** Truncated command line. */
18456
- command: string(),
18457
- cpuPercent: number(),
18458
- memoryRssBytes: number(),
18459
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18460
- uptimeSec: number(),
18461
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18462
- orphaned: boolean()
18463
- });
18464
- var KillProcessInputSchema = object({
18465
- pid: number(),
18466
- /** Force = SIGKILL. Default is SIGTERM. */
18467
- force: boolean().optional()
18468
- });
18469
- var KillProcessResultSchema = object({
18470
- success: boolean(),
18471
- reason: string().optional(),
18472
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18473
- });
18474
- var DumpHeapSnapshotInputSchema = object({
18475
- /** The addon whose runner should dump a heap snapshot. */
18476
- addonId: string() });
18477
- var DumpHeapSnapshotResultSchema = object({
18478
- success: boolean(),
18479
- /** Path of the written .heapsnapshot inside the runner's container/host. */
18480
- path: string().optional(),
18481
- /** Process pid that was signalled. */
18482
18356
  pid: number().optional(),
18483
- reason: string().optional()
18357
+ port: number().optional(),
18358
+ modelPath: string().optional(),
18359
+ modelId: string().optional(),
18360
+ downloadProgress: number().min(0).max(1).optional(),
18361
+ lastError: string().optional(),
18362
+ crashesInWindow: number(),
18363
+ /** Child RSS (sampled best-effort). */
18364
+ memoryBytes: number().optional(),
18365
+ vramBytes: number().optional()
18484
18366
  });
18485
- var SystemMetricsSchema = object({
18486
- cpuPercent: number(),
18487
- memoryPercent: number(),
18488
- memoryUsedMB: number(),
18489
- memoryTotalMB: number(),
18490
- diskPercent: number().optional(),
18491
- temperature: number().optional(),
18492
- gpuPercent: number().optional(),
18493
- gpuMemoryPercent: number().optional()
18367
+ var LlmNodeModelSchema = object({
18368
+ file: string(),
18369
+ sizeBytes: number(),
18370
+ catalogId: string().optional(),
18371
+ installedAt: number().optional()
18494
18372
  });
18495
- 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, {
18373
+ var LlmRuntimeDiskUsageSchema = object({
18374
+ nodeId: string(),
18375
+ modelsBytes: number(),
18376
+ freeBytes: number().optional()
18377
+ });
18378
+ method(LlmGenerateBaseInputSchema.extend({
18379
+ images: array(LlmImageSchema).optional(),
18380
+ runtime: ManagedRuntimeConfigSchema,
18381
+ /** The managed profile's timeout, threaded by the hub provider. */
18382
+ timeoutMs: number().int().positive().optional()
18383
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18496
18384
  kind: "mutation",
18497
18385
  auth: "admin"
18498
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
18386
+ }), method(object({}), _void(), {
18499
18387
  kind: "mutation",
18500
18388
  auth: "admin"
18501
- });
18502
- method(object({
18503
- sourceUrl: string(),
18504
- metadata: ModelConvertMetadataSchema,
18505
- targets: array(ConvertTargetSchema).min(1).readonly(),
18506
- calibrationRef: string().optional(),
18507
- sessionId: string().optional()
18508
- }), ConvertResultSchema, {
18389
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18509
18390
  kind: "mutation",
18510
- auth: "admin",
18511
- timeoutMs: 6e5
18512
- });
18513
- method(object({
18514
- nodeId: string(),
18515
- modelId: string(),
18516
- format: _enum(MODEL_FORMATS),
18517
- entry: ModelCatalogEntrySchema
18518
- }), object({
18519
- ok: boolean(),
18520
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
18521
- sha256: string(),
18522
- bytes: number(),
18523
- /** The target node's modelsDir the artifact landed in. */
18524
- path: string()
18525
- }), {
18391
+ auth: "admin"
18392
+ }), method(object({ file: string() }), _void(), {
18526
18393
  kind: "mutation",
18527
18394
  auth: "admin"
18528
- });
18395
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18529
18396
  /**
18530
- * `mqtt-broker` — broker-registry cap.
18531
- *
18532
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
18533
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
18534
- * and (b) the connection details a consumer addon needs to spin up
18535
- * its OWN `mqtt.js` client.
18397
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18398
+ * methods concat-fan across providers; single-row methods route to ONE
18399
+ * provider by the `addonId` in the call input (the notification-output
18400
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18401
+ * (hub-placed); the cap stays open for future providers.
18536
18402
  *
18537
- * Why: pub/sub routing over the system event-bus loses fidelity
18538
- * (callback shape, QoS guarantees, will/retain semantics) and adds
18539
- * refcount bookkeeping that addons would rather own themselves. The
18540
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
18541
- * features anyway — give it the connection config, get out of the way.
18403
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18404
+ * `apiKey` is a password field providers REDACT it on read and merge on
18405
+ * write; a stored key NEVER round-trips to a client.
18406
+ */
18407
+ var LlmProfileKindSchema = _enum([
18408
+ "openai-compatible",
18409
+ "openai",
18410
+ "anthropic",
18411
+ "google",
18412
+ "managed-local"
18413
+ ]);
18414
+ var LlmProfileSchema = object({
18415
+ id: string(),
18416
+ name: string(),
18417
+ kind: LlmProfileKindSchema,
18418
+ /** Stamped by the provider — keeps the fanned catalog routable. */
18419
+ addonId: string(),
18420
+ enabled: boolean(),
18421
+ /** Vendor model id, or the managed runtime's loaded model. */
18422
+ model: string(),
18423
+ /** Required for openai-compatible; override for cloud kinds. */
18424
+ baseUrl: string().optional(),
18425
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
18426
+ apiKey: string().optional(),
18427
+ supportsVision: boolean(),
18428
+ temperature: number().min(0).max(2).optional(),
18429
+ maxTokens: number().int().positive().optional(),
18430
+ timeoutMs: number().int().positive().default(6e4),
18431
+ extraHeaders: record(string(), string()).optional(),
18432
+ /** kind === 'managed-local' only (spec §4). */
18433
+ runtime: ManagedRuntimeConfigSchema.optional()
18434
+ });
18435
+ /** ConfigUISchema tree passed through untyped on the wire (the
18436
+ * notification-output `ConfigSchemaPassthrough` precedent at
18437
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
18438
+ var ConfigSchemaPassthrough$1 = unknown();
18439
+ var LlmProfileKindDescriptorSchema = object({
18440
+ kind: LlmProfileKindSchema,
18441
+ label: string(),
18442
+ icon: string(),
18443
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
18444
+ addonId: string(),
18445
+ configSchema: ConfigSchemaPassthrough$1
18446
+ });
18447
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
18448
+ var LlmDefaultSchema = object({
18449
+ selector: LlmDefaultSelectorSchema,
18450
+ profileId: string()
18451
+ });
18452
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
18453
+ var LlmUsageRollupSchema = object({
18454
+ day: string(),
18455
+ consumer: string(),
18456
+ profileId: string(),
18457
+ calls: number(),
18458
+ okCalls: number(),
18459
+ errorCalls: number(),
18460
+ inputTokens: number(),
18461
+ outputTokens: number(),
18462
+ avgLatencyMs: number()
18463
+ });
18464
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
18465
+ var ManagedModelCatalogEntrySchema = object({
18466
+ id: string(),
18467
+ label: string(),
18468
+ family: string(),
18469
+ purpose: _enum(["text", "vision"]),
18470
+ url: string(),
18471
+ sha256: string(),
18472
+ sizeBytes: number(),
18473
+ quantization: string(),
18474
+ /** Load-time guidance shown in the picker. */
18475
+ minRamBytes: number(),
18476
+ contextSizeDefault: number().int(),
18477
+ /** Vision models: companion projector file. */
18478
+ mmprojUrl: string().optional()
18479
+ });
18480
+ var LlmRuntimeNodeSchema = object({
18481
+ nodeId: string(),
18482
+ reachable: boolean(),
18483
+ status: LlmRuntimeStatusSchema.optional(),
18484
+ disk: LlmRuntimeDiskUsageSchema.optional(),
18485
+ error: string().optional()
18486
+ });
18487
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
18488
+ var ProfileRefInputSchema = object({
18489
+ addonId: string(),
18490
+ profileId: string()
18491
+ });
18492
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
18493
+ kind: "mutation",
18494
+ auth: "admin"
18495
+ }), method(ProfileRefInputSchema, _void(), {
18496
+ kind: "mutation",
18497
+ auth: "admin"
18498
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
18499
+ kind: "mutation",
18500
+ auth: "admin"
18501
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
18502
+ selector: LlmDefaultSelectorSchema,
18503
+ profileId: string().nullable()
18504
+ }), _void(), {
18505
+ kind: "mutation",
18506
+ auth: "admin"
18507
+ }), method(object({
18508
+ since: number().optional(),
18509
+ until: number().optional(),
18510
+ consumer: string().optional(),
18511
+ profileId: string().optional()
18512
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
18513
+ nodeId: string(),
18514
+ model: ManagedModelRefSchema
18515
+ }), _void(), {
18516
+ kind: "mutation",
18517
+ auth: "admin"
18518
+ }), method(object({
18519
+ nodeId: string(),
18520
+ file: string()
18521
+ }), _void(), {
18522
+ kind: "mutation",
18523
+ auth: "admin"
18524
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
18525
+ kind: "mutation",
18526
+ auth: "admin"
18527
+ }), method(ProfileRefInputSchema, _void(), {
18528
+ kind: "mutation",
18529
+ auth: "admin"
18530
+ });
18531
+ var LogLevelSchema = _enum([
18532
+ "debug",
18533
+ "info",
18534
+ "warn",
18535
+ "error"
18536
+ ]);
18537
+ var LogEntrySchema = object({
18538
+ timestamp: date(),
18539
+ level: LogLevelSchema,
18540
+ scope: array(string()),
18541
+ message: string(),
18542
+ meta: record(string(), unknown()).optional(),
18543
+ tags: record(string(), string()).optional()
18544
+ });
18545
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18546
+ scope: array(string()).optional(),
18547
+ level: LogLevelSchema.optional(),
18548
+ since: date().optional(),
18549
+ until: date().optional(),
18550
+ limit: number().optional(),
18551
+ tags: record(string(), string()).optional()
18552
+ }), array(LogEntrySchema).readonly());
18553
+ /**
18554
+ * `login-method` — collection cap through which auth addons contribute
18555
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
18556
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
18557
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
18558
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
18559
+ * procedure aggregates them for the unauthenticated login page.
18560
+ *
18561
+ * A contribution is a discriminated union on `kind`:
18562
+ *
18563
+ * - `redirect` — a declarative button. The login page renders a generic
18564
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
18565
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
18566
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
18567
+ * login page needs NO change.
18568
+ *
18569
+ * - `widget` — a Module-Federation widget the login page mounts (via
18570
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
18571
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
18572
+ * mechanism kept for future use; no shipped addon uses it on the login
18573
+ * page (the passkey ceremony below runs natively in the shell instead).
18574
+ *
18575
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
18576
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
18577
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
18578
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
18579
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
18580
+ * fetching any remote code pre-auth. Contribution stays unconditional —
18581
+ * enrollment state is never leaked pre-auth; visibility is a shell
18582
+ * decision.
18583
+ *
18584
+ * Every contribution carries a `stage`:
18585
+ * - `primary` — shown on the first credentials screen (OIDC /
18586
+ * magic-link buttons; a future usernameless passkey).
18587
+ * - `second-factor` — shown AFTER the password leg, gated on the
18588
+ * returned `factors` (passkey-as-2FA today).
18589
+ *
18590
+ * `mount: skip` — the cap is read server-side by the core auth router
18591
+ * (`registry.getCollection('login-method')`), never mounted as its own
18592
+ * tRPC router.
18593
+ */
18594
+ /** When a login method renders in the two-phase login flow. */
18595
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
18596
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
18597
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
18598
+ object({
18599
+ kind: literal("redirect"),
18600
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
18601
+ id: string(),
18602
+ /** Operator-facing button label. */
18603
+ label: string(),
18604
+ /** lucide-react icon name. */
18605
+ icon: string().optional(),
18606
+ /** Addon-owned HTTP route the button navigates to (GET). */
18607
+ startUrl: string(),
18608
+ stage: LoginStageEnum
18609
+ }),
18610
+ object({
18611
+ kind: literal("widget"),
18612
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
18613
+ id: string(),
18614
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
18615
+ addonId: string(),
18616
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
18617
+ bundle: string(),
18618
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
18619
+ remote: WidgetRemoteSchema,
18620
+ stage: LoginStageEnum
18621
+ }),
18622
+ object({
18623
+ kind: literal("passkey"),
18624
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
18625
+ id: string(),
18626
+ /** Operator-facing button label. */
18627
+ label: string(),
18628
+ stage: LoginStageEnum,
18629
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
18630
+ rpId: string(),
18631
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
18632
+ origin: string().nullable()
18633
+ })
18634
+ ]);
18635
+ method(_void(), array(LoginMethodContributionSchema).readonly());
18636
+ var CpuBreakdownSchema = object({
18637
+ total: number(),
18638
+ user: number(),
18639
+ system: number(),
18640
+ irq: number(),
18641
+ nice: number(),
18642
+ loadAvg: tuple([
18643
+ number(),
18644
+ number(),
18645
+ number()
18646
+ ]),
18647
+ cores: number()
18648
+ });
18649
+ var MemoryInfoSchema = object({
18650
+ percent: number(),
18651
+ totalBytes: number(),
18652
+ usedBytes: number(),
18653
+ availableBytes: number(),
18654
+ swapUsedBytes: number(),
18655
+ swapTotalBytes: number()
18656
+ });
18657
+ var DiskIoSnapshotSchema = object({
18658
+ readBytes: number(),
18659
+ writeBytes: number(),
18660
+ readOps: number(),
18661
+ writeOps: number(),
18662
+ timestampMs: number()
18663
+ });
18664
+ var NetworkIoSnapshotSchema = object({
18665
+ rxBytes: number(),
18666
+ txBytes: number(),
18667
+ rxPackets: number(),
18668
+ txPackets: number(),
18669
+ rxErrors: number(),
18670
+ txErrors: number(),
18671
+ timestampMs: number()
18672
+ });
18673
+ var MetricsGpuInfoSchema = object({
18674
+ utilization: number(),
18675
+ model: string(),
18676
+ memoryUsedBytes: number(),
18677
+ memoryTotalBytes: number(),
18678
+ temperature: number().nullable()
18679
+ });
18680
+ var ProcessResourceInfoSchema = object({
18681
+ openFds: number(),
18682
+ threadCount: number(),
18683
+ activeHandles: number(),
18684
+ activeRequests: number()
18685
+ });
18686
+ var PressureAvgsSchema = object({
18687
+ avg10: number(),
18688
+ avg60: number(),
18689
+ avg300: number()
18690
+ });
18691
+ var PressureInfoSchema = object({
18692
+ some: PressureAvgsSchema,
18693
+ full: PressureAvgsSchema.nullable()
18694
+ });
18695
+ var SystemResourceSnapshotSchema = object({
18696
+ cpu: CpuBreakdownSchema,
18697
+ memory: MemoryInfoSchema,
18698
+ gpu: MetricsGpuInfoSchema.nullable(),
18699
+ network: NetworkIoSnapshotSchema,
18700
+ disk: DiskIoSnapshotSchema,
18701
+ pressure: object({
18702
+ cpu: PressureInfoSchema.nullable(),
18703
+ memory: PressureInfoSchema.nullable(),
18704
+ io: PressureInfoSchema.nullable()
18705
+ }),
18706
+ process: ProcessResourceInfoSchema,
18707
+ cpuTemperature: number().nullable(),
18708
+ timestampMs: number()
18709
+ });
18710
+ var DiskSpaceInfoSchema = object({
18711
+ path: string(),
18712
+ totalBytes: number(),
18713
+ usedBytes: number(),
18714
+ availableBytes: number(),
18715
+ percent: number()
18716
+ });
18717
+ var PidResourceStatsSchema = object({
18718
+ pid: number(),
18719
+ cpu: number(),
18720
+ memory: number(),
18721
+ /**
18722
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
18723
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
18724
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
18725
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
18726
+ * Undefined where /proc is unavailable (e.g. macOS).
18727
+ */
18728
+ privateBytes: number().optional(),
18729
+ /**
18730
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18731
+ * code shared copy-on-write across runners. Undefined on macOS.
18732
+ */
18733
+ sharedBytes: number().optional()
18734
+ });
18735
+ var AddonInstanceSchema = object({
18736
+ addonId: string(),
18737
+ nodeId: string(),
18738
+ role: _enum(["hub", "worker"]),
18739
+ pid: number(),
18740
+ state: _enum([
18741
+ "starting",
18742
+ "running",
18743
+ "stopping",
18744
+ "stopped",
18745
+ "crashed"
18746
+ ]),
18747
+ uptimeSec: number()
18748
+ });
18749
+ var NodeProcessSchema = object({
18750
+ pid: number(),
18751
+ ppid: number(),
18752
+ pgid: number(),
18753
+ classification: _enum([
18754
+ "root",
18755
+ "managed",
18756
+ "system",
18757
+ "ghost"
18758
+ ]),
18759
+ /** `$process` addon binding when `managed`, else null. */
18760
+ addonId: string().nullable(),
18761
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
18762
+ nodeId: string().nullable(),
18763
+ /** Truncated command line. */
18764
+ command: string(),
18765
+ cpuPercent: number(),
18766
+ memoryRssBytes: number(),
18767
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18768
+ uptimeSec: number(),
18769
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18770
+ orphaned: boolean()
18771
+ });
18772
+ var KillProcessInputSchema = object({
18773
+ pid: number(),
18774
+ /** Force = SIGKILL. Default is SIGTERM. */
18775
+ force: boolean().optional()
18776
+ });
18777
+ var KillProcessResultSchema = object({
18778
+ success: boolean(),
18779
+ reason: string().optional(),
18780
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18781
+ });
18782
+ var DumpHeapSnapshotInputSchema = object({
18783
+ /** The addon whose runner should dump a heap snapshot. */
18784
+ addonId: string() });
18785
+ var DumpHeapSnapshotResultSchema = object({
18786
+ success: boolean(),
18787
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
18788
+ path: string().optional(),
18789
+ /** Process pid that was signalled. */
18790
+ pid: number().optional(),
18791
+ reason: string().optional()
18792
+ });
18793
+ var SystemMetricsSchema = object({
18794
+ cpuPercent: number(),
18795
+ memoryPercent: number(),
18796
+ memoryUsedMB: number(),
18797
+ memoryTotalMB: number(),
18798
+ diskPercent: number().optional(),
18799
+ temperature: number().optional(),
18800
+ gpuPercent: number().optional(),
18801
+ gpuMemoryPercent: number().optional()
18802
+ });
18803
+ 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, {
18804
+ kind: "mutation",
18805
+ auth: "admin"
18806
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
18807
+ kind: "mutation",
18808
+ auth: "admin"
18809
+ });
18810
+ method(object({
18811
+ sourceUrl: string(),
18812
+ metadata: ModelConvertMetadataSchema,
18813
+ targets: array(ConvertTargetSchema).min(1).readonly(),
18814
+ calibrationRef: string().optional(),
18815
+ sessionId: string().optional()
18816
+ }), ConvertResultSchema, {
18817
+ kind: "mutation",
18818
+ auth: "admin",
18819
+ timeoutMs: 6e5
18820
+ });
18821
+ method(object({
18822
+ nodeId: string(),
18823
+ modelId: string(),
18824
+ format: _enum(MODEL_FORMATS),
18825
+ entry: ModelCatalogEntrySchema
18826
+ }), object({
18827
+ ok: boolean(),
18828
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
18829
+ sha256: string(),
18830
+ bytes: number(),
18831
+ /** The target node's modelsDir the artifact landed in. */
18832
+ path: string()
18833
+ }), {
18834
+ kind: "mutation",
18835
+ auth: "admin"
18836
+ });
18837
+ /**
18838
+ * `mqtt-broker` — broker-registry cap.
18839
+ *
18840
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
18841
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
18842
+ * and (b) the connection details a consumer addon needs to spin up
18843
+ * its OWN `mqtt.js` client.
18844
+ *
18845
+ * Why: pub/sub routing over the system event-bus loses fidelity
18846
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
18847
+ * refcount bookkeeping that addons would rather own themselves. The
18848
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
18849
+ * features anyway — give it the connection config, get out of the way.
18542
18850
  *
18543
18851
  * Consumer flow:
18544
18852
  * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
@@ -18756,398 +19064,594 @@ var NotificationSchema = object({
18756
19064
  });
18757
19065
  /** One declared native severity/priority level for a kind. */
18758
19066
  var TargetKindLevelSchema = object({
18759
- id: string(),
18760
- label: string(),
18761
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
18762
- ordinal: number().int().min(1).max(5).nullable(),
18763
- flags: object({
18764
- critical: boolean().optional(),
18765
- silent: boolean().optional(),
18766
- noPush: boolean().optional()
18767
- }).optional(),
18768
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
18769
- requires: array(string()).optional(),
18770
- description: string().optional()
18771
- });
18772
- /** The full capability block consulted before dispatch. */
18773
- var TargetKindCapsSchema = object({
18774
- attachments: object({
18775
- mediaTypes: array(AttachmentMediaTypeSchema),
18776
- mode: _enum([
18777
- "url",
18778
- "bytes",
18779
- "both"
18780
- ]),
18781
- max: number().int().nonnegative(),
18782
- maxBytes: number().int().positive().optional()
18783
- }),
18784
- /** Max action buttons (0 = none). */
18785
- actions: number().int().nonnegative(),
18786
- levels: array(TargetKindLevelSchema),
18787
- format: array(NotificationFormatSchema),
18788
- clickUrl: boolean(),
18789
- sound: boolean(),
18790
- ttl: boolean(),
18791
- bodyMaxLen: number().int().positive()
18792
- });
18793
- /**
18794
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
18795
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
18796
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
18797
- * the union is large and not meant for runtime validation here; the exported
18798
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
18799
- */
18800
- var ConfigSchemaPassthrough$1 = unknown();
18801
- var TargetKindSchema = object({
18802
- kind: string(),
18803
- label: string(),
18804
- icon: string(),
18805
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
18806
- addonId: string(),
18807
- configSchema: ConfigSchemaPassthrough$1,
18808
- supportsDiscovery: boolean(),
18809
- caps: TargetKindCapsSchema
18810
- });
18811
- /**
18812
- * A persisted target. `config` holds secrets; providers REDACT secret fields
18813
- * (return a presence marker only) when serving `listTargets` — never
18814
- * round-trip a stored secret to the UI.
18815
- */
18816
- var TargetSchema = object({
18817
- id: string(),
18818
- name: string(),
18819
- kind: string(),
18820
- addonId: string(),
18821
- enabled: boolean(),
18822
- config: record(string(), unknown())
18823
- });
18824
- /** A discovery-surfaced candidate (config is partial + non-secret). */
18825
- var DiscoveredTargetSchema = object({
18826
- kind: string(),
18827
- suggestedName: string(),
18828
- config: record(string(), unknown())
18829
- });
18830
- /** The degrade engine's report — what was resolved / dropped / degraded. */
18831
- var RenderedAsSchema = object({
18832
- level: string(),
18833
- format: NotificationFormatSchema,
18834
- attachmentsSent: number().int().nonnegative(),
18835
- actionsSent: number().int().nonnegative(),
18836
- truncated: boolean(),
18837
- dropped: array(string())
18838
- });
18839
- var SendResultSchema = object({
18840
- success: boolean(),
18841
- error: string().optional(),
18842
- renderedAs: RenderedAsSchema.optional()
18843
- });
18844
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
18845
- var TestResultSchema = SendResultSchema;
18846
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
18847
- kind: string(),
18848
- config: record(string(), unknown()).optional()
18849
- }), array(DiscoveredTargetSchema)), method(object({
18850
- targetId: string(),
18851
- notification: NotificationSchema
18852
- }), SendResultSchema, { kind: "mutation" }), method(object({
18853
- targetId: string(),
18854
- sample: NotificationSchema.optional()
18855
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
18856
- targetId: string(),
18857
- enabled: boolean()
18858
- }), _void(), { kind: "mutation" });
18859
- /**
18860
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18861
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18862
- * caps stay wire-compatible without a circular cap→cap import.
18863
- *
18864
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
18865
- * every transport tier structurally, and failed calls still write usage rows.
18866
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18867
- */
18868
- var LlmUsageSchema = object({
18869
- inputTokens: number(),
18870
- outputTokens: number()
18871
- });
18872
- var LlmErrorCodeSchema = _enum([
18873
- "timeout",
18874
- "rate-limited",
18875
- "auth",
18876
- "refusal",
18877
- "bad-request",
18878
- "unavailable",
18879
- "no-profile",
18880
- "budget-exceeded",
18881
- "adapter-error"
18882
- ]);
18883
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18884
- ok: literal(true),
18885
- text: string(),
18886
- model: string(),
18887
- usage: LlmUsageSchema,
18888
- truncated: boolean(),
18889
- latencyMs: number()
18890
- }), object({
18891
- ok: literal(false),
18892
- code: LlmErrorCodeSchema,
18893
- message: string(),
18894
- retryAfterMs: number().optional()
18895
- })]);
18896
- /**
18897
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18898
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18899
- * notification-output.cap.ts:27-31 precedents).
18900
- */
18901
- var LlmImageSchema = object({
18902
- bytes: _instanceof(Uint8Array),
18903
- mimeType: string()
18904
- });
18905
- var LlmGenerateBaseInputSchema = object({
18906
- /** Collection routing (the notification-output posture). */
18907
- addonId: string().optional(),
18908
- /** Explicit profile; else the resolution chain (spec §3). */
18909
- profileId: string().optional(),
18910
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18911
- consumer: string(),
18912
- system: string().optional(),
18913
- /** v1: single-turn. `messages[]` is a v2 additive field. */
18914
- prompt: string(),
18915
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18916
- jsonSchema: record(string(), unknown()).optional(),
18917
- /** Per-call override of the profile default. */
18918
- maxTokens: number().int().positive().optional(),
18919
- temperature: number().optional()
18920
- });
18921
- /**
18922
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18923
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18924
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18925
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18926
- * this only through the `llm` cap's methods.
18927
- *
18928
- * One running llama-server child per node in v1 (models are RAM-heavy).
18929
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18930
- * watchdog — operator decision #3).
18931
- */
18932
- var ManagedModelRefSchema = discriminatedUnion("kind", [
18933
- object({
18934
- kind: literal("catalog"),
18935
- catalogId: string()
18936
- }),
18937
- object({
18938
- kind: literal("url"),
18939
- url: string(),
18940
- sha256: string().optional()
18941
- }),
18942
- object({
18943
- kind: literal("path"),
18944
- path: string()
18945
- })
18946
- ]);
18947
- var ManagedRuntimeConfigSchema = object({
18948
- /** WHERE the runtime lives — hub or any agent. */
18949
- nodeId: string(),
18950
- /** Closed for v1; 'ollama' is a v2 candidate. */
18951
- engine: _enum(["llama-cpp"]),
18952
- model: ManagedModelRefSchema,
18953
- contextSize: number().int().default(4096),
18954
- /** 0 = CPU-only. */
18955
- gpuLayers: number().int().default(0),
18956
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18957
- threads: number().int().optional(),
18958
- /** Concurrent slots. */
18959
- parallel: number().int().default(1),
18960
- /** Else lazy: first generate boots it. */
18961
- autoStart: boolean().default(false),
18962
- /** 0 = never; frees RAM after quiet periods. */
18963
- idleStopMinutes: number().int().default(30)
18964
- });
18965
- var LlmRuntimeStatusSchema = object({
18966
- /** Status is ALWAYS node-qualified. */
18967
- nodeId: string(),
18968
- state: _enum([
18969
- "stopped",
18970
- "downloading",
18971
- "starting",
18972
- "ready",
18973
- "crashed",
18974
- "failed"
18975
- ]),
18976
- pid: number().optional(),
18977
- port: number().optional(),
18978
- modelPath: string().optional(),
18979
- modelId: string().optional(),
18980
- downloadProgress: number().min(0).max(1).optional(),
18981
- lastError: string().optional(),
18982
- crashesInWindow: number(),
18983
- /** Child RSS (sampled best-effort). */
18984
- memoryBytes: number().optional(),
18985
- vramBytes: number().optional()
19067
+ id: string(),
19068
+ label: string(),
19069
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
19070
+ ordinal: number().int().min(1).max(5).nullable(),
19071
+ flags: object({
19072
+ critical: boolean().optional(),
19073
+ silent: boolean().optional(),
19074
+ noPush: boolean().optional()
19075
+ }).optional(),
19076
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
19077
+ requires: array(string()).optional(),
19078
+ description: string().optional()
18986
19079
  });
18987
- var LlmNodeModelSchema = object({
18988
- file: string(),
18989
- sizeBytes: number(),
18990
- catalogId: string().optional(),
18991
- installedAt: number().optional()
19080
+ /** The full capability block consulted before dispatch. */
19081
+ var TargetKindCapsSchema = object({
19082
+ attachments: object({
19083
+ mediaTypes: array(AttachmentMediaTypeSchema),
19084
+ mode: _enum([
19085
+ "url",
19086
+ "bytes",
19087
+ "both"
19088
+ ]),
19089
+ max: number().int().nonnegative(),
19090
+ maxBytes: number().int().positive().optional()
19091
+ }),
19092
+ /** Max action buttons (0 = none). */
19093
+ actions: number().int().nonnegative(),
19094
+ levels: array(TargetKindLevelSchema),
19095
+ format: array(NotificationFormatSchema),
19096
+ clickUrl: boolean(),
19097
+ sound: boolean(),
19098
+ ttl: boolean(),
19099
+ bodyMaxLen: number().int().positive()
18992
19100
  });
18993
- var LlmRuntimeDiskUsageSchema = object({
18994
- nodeId: string(),
18995
- modelsBytes: number(),
18996
- freeBytes: number().optional()
19101
+ /**
19102
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
19103
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
19104
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
19105
+ * the union is large and not meant for runtime validation here; the exported
19106
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
19107
+ */
19108
+ var ConfigSchemaPassthrough = unknown();
19109
+ var TargetKindSchema = object({
19110
+ kind: string(),
19111
+ label: string(),
19112
+ icon: string(),
19113
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
19114
+ addonId: string(),
19115
+ configSchema: ConfigSchemaPassthrough,
19116
+ supportsDiscovery: boolean(),
19117
+ caps: TargetKindCapsSchema
18997
19118
  });
18998
- method(LlmGenerateBaseInputSchema.extend({
18999
- images: array(LlmImageSchema).optional(),
19000
- runtime: ManagedRuntimeConfigSchema,
19001
- /** The managed profile's timeout, threaded by the hub provider. */
19002
- timeoutMs: number().int().positive().optional()
19003
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
19004
- kind: "mutation",
19005
- auth: "admin"
19006
- }), method(object({}), _void(), {
19007
- kind: "mutation",
19008
- auth: "admin"
19009
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
19010
- kind: "mutation",
19011
- auth: "admin"
19012
- }), method(object({ file: string() }), _void(), {
19013
- kind: "mutation",
19014
- auth: "admin"
19015
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
19016
19119
  /**
19017
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
19018
- * methods concat-fan across providers; single-row methods route to ONE
19019
- * provider by the `addonId` in the call input (the notification-output
19020
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
19021
- * (hub-placed); the cap stays open for future providers.
19022
- *
19023
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
19024
- * `apiKey` is a password field — providers REDACT it on read and merge on
19025
- * write; a stored key NEVER round-trips to a client.
19120
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
19121
+ * (return a presence marker only) when serving `listTargets` — never
19122
+ * round-trip a stored secret to the UI.
19026
19123
  */
19027
- var LlmProfileKindSchema = _enum([
19028
- "openai-compatible",
19029
- "openai",
19030
- "anthropic",
19031
- "google",
19032
- "managed-local"
19033
- ]);
19034
- var LlmProfileSchema = object({
19124
+ var TargetSchema = object({
19035
19125
  id: string(),
19036
19126
  name: string(),
19037
- kind: LlmProfileKindSchema,
19038
- /** Stamped by the provider — keeps the fanned catalog routable. */
19127
+ kind: string(),
19039
19128
  addonId: string(),
19040
19129
  enabled: boolean(),
19041
- /** Vendor model id, or the managed runtime's loaded model. */
19042
- model: string(),
19043
- /** Required for openai-compatible; override for cloud kinds. */
19044
- baseUrl: string().optional(),
19045
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
19046
- apiKey: string().optional(),
19047
- supportsVision: boolean(),
19048
- temperature: number().min(0).max(2).optional(),
19049
- maxTokens: number().int().positive().optional(),
19050
- timeoutMs: number().int().positive().default(6e4),
19051
- extraHeaders: record(string(), string()).optional(),
19052
- /** kind === 'managed-local' only (spec §4). */
19053
- runtime: ManagedRuntimeConfigSchema.optional()
19130
+ config: record(string(), unknown())
19054
19131
  });
19055
- /** ConfigUISchema tree passed through untyped on the wire (the
19056
- * notification-output `ConfigSchemaPassthrough` precedent at
19057
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
19058
- var ConfigSchemaPassthrough = unknown();
19059
- var LlmProfileKindDescriptorSchema = object({
19060
- kind: LlmProfileKindSchema,
19061
- label: string(),
19062
- icon: string(),
19063
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
19064
- addonId: string(),
19065
- configSchema: ConfigSchemaPassthrough
19132
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
19133
+ var DiscoveredTargetSchema = object({
19134
+ kind: string(),
19135
+ suggestedName: string(),
19136
+ config: record(string(), unknown())
19066
19137
  });
19067
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
19068
- var LlmDefaultSchema = object({
19069
- selector: LlmDefaultSelectorSchema,
19070
- profileId: string()
19138
+ /** The degrade engine's report what was resolved / dropped / degraded. */
19139
+ var RenderedAsSchema = object({
19140
+ level: string(),
19141
+ format: NotificationFormatSchema,
19142
+ attachmentsSent: number().int().nonnegative(),
19143
+ actionsSent: number().int().nonnegative(),
19144
+ truncated: boolean(),
19145
+ dropped: array(string())
19071
19146
  });
19072
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
19073
- var LlmUsageRollupSchema = object({
19074
- day: string(),
19075
- consumer: string(),
19076
- profileId: string(),
19077
- calls: number(),
19078
- okCalls: number(),
19079
- errorCalls: number(),
19080
- inputTokens: number(),
19081
- outputTokens: number(),
19082
- avgLatencyMs: number()
19147
+ var SendResultSchema = object({
19148
+ success: boolean(),
19149
+ error: string().optional(),
19150
+ renderedAs: RenderedAsSchema.optional()
19083
19151
  });
19084
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
19085
- var ManagedModelCatalogEntrySchema = object({
19152
+ /** Same shape as SendResult kept as a distinct name for the test panel. */
19153
+ var TestResultSchema = SendResultSchema;
19154
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
19155
+ kind: string(),
19156
+ config: record(string(), unknown()).optional()
19157
+ }), array(DiscoveredTargetSchema)), method(object({
19158
+ targetId: string(),
19159
+ notification: NotificationSchema
19160
+ }), SendResultSchema, { kind: "mutation" }), method(object({
19161
+ targetId: string(),
19162
+ sample: NotificationSchema.optional()
19163
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
19164
+ targetId: string(),
19165
+ enabled: boolean()
19166
+ }), _void(), { kind: "mutation" });
19167
+ /**
19168
+ * notification-rules — the Notification Center rule surface (P1 core).
19169
+ *
19170
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
19171
+ * (operator decisions D-1/D-2/D-3 are binding):
19172
+ *
19173
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
19174
+ * `notification-center` module), hooked on the durable persistence
19175
+ * moments (object-event insert, TrackCloser.closeExpired) with a
19176
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
19177
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
19178
+ * FIRST persisted detection matching the conditions (per-track dedup,
19179
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
19180
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
19181
+ * - DISPATCH stays behind `notification-output` (rules reference targets
19182
+ * by id; per-backend params are a passthrough blob capped by the
19183
+ * target kind's own caps/degrade engine).
19184
+ *
19185
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
19186
+ * server-injected caller identity — the first `caller: 'required'`
19187
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
19188
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
19189
+ * windows, and the optional label/identity/plate matchers. User rules,
19190
+ * private zones, per-recipient fan-out and the wider condition table are
19191
+ * P2+ (see spec §7).
19192
+ *
19193
+ * All schemas here are the single source of truth — `NcRule` etc. are
19194
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
19195
+ * schema/interface drift is explicitly not repeated).
19196
+ */
19197
+ /**
19198
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
19199
+ * The value maps 1:1 onto the evaluated record kind:
19200
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
19201
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
19202
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
19203
+ * change of a LINKED device, one row per linked camera)
19204
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
19205
+ * delivery / pick-up)
19206
+ *
19207
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
19208
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
19209
+ * this one field keeps the schema additive — a rule still declares exactly
19210
+ * one trigger.
19211
+ */
19212
+ var NcDeliverySchema = _enum([
19213
+ "immediate",
19214
+ "track-end",
19215
+ "device-event",
19216
+ "package-event"
19217
+ ]);
19218
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
19219
+ var NcScheduleSchema = object({
19220
+ windows: array(object({
19221
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
19222
+ days: array(number().int().min(0).max(6)).min(1),
19223
+ startMinute: number().int().min(0).max(1439),
19224
+ endMinute: number().int().min(0).max(1439)
19225
+ })).min(1),
19226
+ /** IANA timezone; default = hub host timezone. */
19227
+ timezone: string().optional(),
19228
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
19229
+ invert: boolean().optional()
19230
+ });
19231
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
19232
+ var NcPlateMatcherSchema = object({
19233
+ values: array(string().min(1)).min(1),
19234
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
19235
+ maxDistance: number().int().min(0).max(3).default(1)
19236
+ });
19237
+ /**
19238
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
19239
+ * occupancy edge for a device — optionally narrowed to a single admin
19240
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
19241
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
19242
+ * - `became-free` — count crossed ≥ `count` → below it
19243
+ * - `>=` / `<=` — count is at/over or at/under `count`
19244
+ * `sustainSeconds` requires the condition hold continuously that long
19245
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
19246
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
19247
+ * the condition never matches. Confirmed edge-state survives addon restarts
19248
+ * (declared SQLite collection, reseeded on boot).
19249
+ */
19250
+ var NcOccupancyConditionSchema = object({
19251
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
19252
+ zoneId: string().optional(),
19253
+ /** Object class to count; absent = any class. */
19254
+ className: string().optional(),
19255
+ op: _enum([
19256
+ "became-occupied",
19257
+ "became-free",
19258
+ ">=",
19259
+ "<="
19260
+ ]).default("became-occupied"),
19261
+ count: number().int().min(0).default(1),
19262
+ sustainSeconds: number().int().min(0).max(3600).default(15)
19263
+ });
19264
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
19265
+ var NcZoneConditionSchema = object({
19266
+ ids: array(string().min(1)).min(1),
19267
+ /** Quantifier over `ids` — at least one / every one visited. */
19268
+ match: _enum(["any", "all"]).default("any")
19269
+ });
19270
+ /**
19271
+ * The P1 condition set — a flat AND of groups; absent group = pass;
19272
+ * membership lists are OR within the list (spec §2.3).
19273
+ */
19274
+ var NcConditionsSchema = object({
19275
+ /** Device scope — absent = all devices. */
19276
+ devices: array(number()).optional(),
19277
+ /** Detector class names (any overlap with the record's class set). */
19278
+ classes: array(string().min(1)).optional(),
19279
+ /** Veto classes — any overlap fails the rule. */
19280
+ classesExclude: array(string().min(1)).optional(),
19281
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
19282
+ minConfidence: number().min(0).max(1).optional(),
19283
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
19284
+ zones: NcZoneConditionSchema.optional(),
19285
+ /** Veto zones — any hit fails the rule. */
19286
+ zonesExclude: array(string().min(1)).optional(),
19287
+ /**
19288
+ * Exact (case-insensitive) match on the record's collapsed `label`
19289
+ * (identity name / plate text / subclass).
19290
+ */
19291
+ labelEquals: array(string().min(1)).optional(),
19292
+ /**
19293
+ * Identity matcher. P1 boundary: matched against the record's collapsed
19294
+ * `label` (the identity display name propagated by the face pipeline) —
19295
+ * identity-ID matching rides in P2 when identity ids reach the record.
19296
+ */
19297
+ identities: array(string().min(1)).optional(),
19298
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
19299
+ plates: NcPlateMatcherSchema.optional(),
19300
+ /**
19301
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
19302
+ * Same P1 boundary: matched against the record's collapsed `label` (the
19303
+ * identity display name). A record with NO label passes (nothing to
19304
+ * exclude), unlike the include variant which fails on an absent label.
19305
+ */
19306
+ identitiesExclude: array(string().min(1)).optional(),
19307
+ /**
19308
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
19309
+ * TRACK-END only: importance is scored at track close, so it does not exist
19310
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
19311
+ * close the value is threaded via the close-time info (the `Track` clone is
19312
+ * captured before the DB row is updated, so it would otherwise read stale).
19313
+ * Fails when the record carries no importance (never guess quality — the
19314
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
19315
+ */
19316
+ minImportance: number().min(0).max(1).optional(),
19317
+ /**
19318
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
19319
+ * TRACK-END only: an `immediate` / object-event subject has no closed
19320
+ * lifespan, so a dwell condition never matches immediate delivery
19321
+ * (documented choice — the object-event record carries no `firstSeen`,
19322
+ * so dwell cannot be computed from what the subject actually carries).
19323
+ */
19324
+ minDwellSeconds: number().min(0).optional(),
19325
+ /**
19326
+ * Detection provenance filter. `any` (default / absent) matches every
19327
+ * source; otherwise the subject's source must equal it. Legacy records
19328
+ * with no stamped source are treated as `pipeline`. The union spans both
19329
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
19330
+ * tracks carry `sensor`.
19331
+ */
19332
+ source: _enum([
19333
+ "pipeline",
19334
+ "onboard",
19335
+ "sensor",
19336
+ "any"
19337
+ ]).optional(),
19338
+ /**
19339
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
19340
+ * detector `minConfidence` (that gates the object-detection score; this
19341
+ * gates the recognition/OCR match score). Fails when the subject carries
19342
+ * no label-match confidence (never guess). TRACK-END only: the confidence
19343
+ * lives on the recognition result and reaches the subject at track close.
19344
+ *
19345
+ * What it measures precisely (plumbed at track close — the closer threads
19346
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
19347
+ * `importance`): the BEST recognition match confidence observed for the
19348
+ * label the track carries at close — for a face, the peak cosine similarity
19349
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
19350
+ * for a plate, the peak OCR read score of the best-held plate
19351
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
19352
+ * one track the higher of the two is used. A track that ended with no
19353
+ * confident identity/plate match carries no value, so the condition fails
19354
+ * closed for it (an un-recognized subject).
19355
+ */
19356
+ minLabelConfidence: number().min(0).max(1).optional(),
19357
+ /**
19358
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
19359
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
19360
+ * against the token carried on the device-event subject (extracted from the
19361
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
19362
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
19363
+ * eventType, so gate those with {@link sensorKinds} instead.
19364
+ */
19365
+ eventTypeTokens: array(string().min(1)).optional(),
19366
+ /**
19367
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
19368
+ * `contact`, `button`, `device-event`) — matched against the persisted
19369
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
19370
+ */
19371
+ sensorKinds: array(string().min(1)).optional(),
19372
+ /**
19373
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
19374
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
19375
+ * when the subject's phase does not match (a subject always carries a phase
19376
+ * on the package-event trigger).
19377
+ */
19378
+ packagePhase: _enum([
19379
+ "delivered",
19380
+ "picked-up",
19381
+ "both"
19382
+ ]).optional(),
19383
+ /**
19384
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
19385
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
19386
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
19387
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
19388
+ */
19389
+ customZones: array(MaskPolygonShapeSchema).optional(),
19390
+ /**
19391
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
19392
+ * (optionally zone/class-scoped) occupancy count crosses the configured
19393
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
19394
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
19395
+ */
19396
+ occupancy: NcOccupancyConditionSchema.optional()
19397
+ });
19398
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
19399
+ var NcRuleTargetSchema = object({
19400
+ /** `notification-output` Target id. */
19401
+ targetId: string().min(1),
19402
+ /**
19403
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
19404
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
19405
+ * degrade engine drops what the backend can't render.
19406
+ */
19407
+ params: record(string(), unknown()).optional()
19408
+ });
19409
+ /**
19410
+ * Media attachment policy (P1 still-image subset).
19411
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
19412
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
19413
+ * matched on identities attaches the subject's `faceCrop`, one matched on
19414
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
19415
+ * (or when the specific crop is missing) degrades to `best`, then
19416
+ * `keyFrame`, then no attachment — never delaying the send. The matched
19417
+ * condition summary is frozen on the outbox row at enqueue (like the rule
19418
+ * name), so the choice never drifts from the record that fired it.
19419
+ * - `keyFrame` — the clean scene frame (no subject box).
19420
+ * - `none` — no attachment.
19421
+ */
19422
+ var NcMediaPolicySchema = object({ attach: _enum([
19423
+ "best",
19424
+ "best-matching",
19425
+ "keyFrame",
19426
+ "none"
19427
+ ]).default("best") });
19428
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
19429
+ var NcThrottleSchema = object({
19430
+ cooldownSec: number().int().min(0).max(86400).default(60),
19431
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
19432
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
19433
+ });
19434
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
19435
+ var NcRuleInputSchema = object({
19436
+ name: string().min(1).max(200),
19437
+ enabled: boolean().default(true),
19438
+ delivery: NcDeliverySchema,
19439
+ conditions: NcConditionsSchema.default({}),
19440
+ schedule: NcScheduleSchema.optional(),
19441
+ targets: array(NcRuleTargetSchema).min(1),
19442
+ media: NcMediaPolicySchema.default({ attach: "best" }),
19443
+ throttle: NcThrottleSchema.default({
19444
+ cooldownSec: 60,
19445
+ scope: "rule-device"
19446
+ }),
19447
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
19448
+ template: object({
19449
+ title: string().max(500).optional(),
19450
+ body: string().max(2e3).optional()
19451
+ }).optional(),
19452
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
19453
+ priority: number().int().min(1).max(5).default(3),
19454
+ /**
19455
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
19456
+ * behaviour, visible to all, read-only in the viewer). Present = personal
19457
+ * rule owned by this userId. Server-stamped; never trusted from a client.
19458
+ */
19459
+ ownerUserId: string().optional()
19460
+ });
19461
+ /**
19462
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
19463
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
19464
+ * NOT a client-authored input field (it lives on the persisted rule, not the
19465
+ * input), so it is added here explicitly to let the store's per-target opt-out
19466
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
19467
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
19468
+ * `updateRule` patch.
19469
+ */
19470
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
19471
+ /** A persisted rule. */
19472
+ var NcRuleSchema = NcRuleInputSchema.extend({
19473
+ id: string(),
19474
+ /** userId of the admin who created the rule (server-stamped caller). */
19475
+ createdBy: string(),
19476
+ createdAt: number(),
19477
+ updatedAt: number(),
19478
+ /**
19479
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
19480
+ * send time. Only a target's OWNER may add/remove its id (server-checked
19481
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
19482
+ */
19483
+ disabledTargetIds: array(string()).default([])
19484
+ });
19485
+ var NcTestResultSchema = object({
19486
+ recordId: string(),
19487
+ recordKind: _enum([
19488
+ "object-event",
19489
+ "track",
19490
+ "device-event",
19491
+ "package-event"
19492
+ ]),
19493
+ deviceId: number(),
19494
+ timestamp: number(),
19495
+ wouldFire: boolean(),
19496
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
19497
+ failedCondition: string().optional(),
19498
+ className: string().optional(),
19499
+ label: string().optional()
19500
+ });
19501
+ var NcConditionDescriptorSchema = object({
19502
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
19086
19503
  id: string(),
19504
+ group: _enum([
19505
+ "scope",
19506
+ "class",
19507
+ "zones",
19508
+ "quality",
19509
+ "label",
19510
+ "schedule",
19511
+ "device",
19512
+ "package",
19513
+ "occupancy"
19514
+ ]),
19087
19515
  label: string(),
19088
- family: string(),
19089
- purpose: _enum(["text", "vision"]),
19090
- url: string(),
19091
- sha256: string(),
19092
- sizeBytes: number(),
19093
- quantization: string(),
19094
- /** Load-time guidance shown in the picker. */
19095
- minRamBytes: number(),
19096
- contextSizeDefault: number().int(),
19097
- /** Vision models: companion projector file. */
19098
- mmprojUrl: string().optional()
19516
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
19517
+ valueType: _enum([
19518
+ "deviceIdList",
19519
+ "stringList",
19520
+ "number01",
19521
+ "number",
19522
+ "sourceSelect",
19523
+ "zoneSelection",
19524
+ "zoneIdList",
19525
+ "schedule",
19526
+ "plateMatcher",
19527
+ "packagePhase",
19528
+ "polygonDraw",
19529
+ "occupancy"
19530
+ ]),
19531
+ operator: _enum([
19532
+ "in",
19533
+ "notIn",
19534
+ "anyOf",
19535
+ "allOf",
19536
+ "gte",
19537
+ "fuzzyIn",
19538
+ "withinSchedule"
19539
+ ]),
19540
+ /** Which delivery kinds the condition applies to. */
19541
+ appliesTo: array(NcDeliverySchema),
19542
+ phase: string(),
19543
+ description: string().optional()
19099
19544
  });
19100
- var LlmRuntimeNodeSchema = object({
19101
- nodeId: string(),
19102
- reachable: boolean(),
19103
- status: LlmRuntimeStatusSchema.optional(),
19104
- disk: LlmRuntimeDiskUsageSchema.optional(),
19105
- error: string().optional()
19545
+ /**
19546
+ * The delivery lifecycle status of a history row — a straight read of the
19547
+ * durable outbox row's own status (single source of truth):
19548
+ * - `pending` — enqueued, in-flight or retrying with backoff
19549
+ * - `sent` — delivered (terminal)
19550
+ * - `dead` — dead-lettered after exhausting retries / a permanent
19551
+ * backend rejection / a deleted target (terminal; carries
19552
+ * the failure `error`)
19553
+ *
19554
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
19555
+ * user dimension (quiet hours / snooze) and are additive when they land.
19556
+ */
19557
+ var NcHistoryStatusSchema = _enum([
19558
+ "pending",
19559
+ "sent",
19560
+ "dead"
19561
+ ]);
19562
+ /** The evaluated record kind a history row descends from (one per trigger). */
19563
+ var NcHistoryRecordKindSchema = _enum([
19564
+ "object-event",
19565
+ "track-end",
19566
+ "device-event",
19567
+ "package-event"
19568
+ ]);
19569
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
19570
+ var NcHistorySubjectSchema = object({
19571
+ className: string(),
19572
+ label: string().optional(),
19573
+ confidence: number().optional(),
19574
+ zones: array(string()),
19575
+ timestamp: number()
19576
+ });
19577
+ /**
19578
+ * One delivery-history row. This is a read-only VIEW over the durable
19579
+ * outbox row (single source of truth — the same row the drain loop drives;
19580
+ * NO second write path, so history can never drift from delivery state).
19581
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
19582
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
19583
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
19584
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
19585
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
19586
+ * P1 (admin scope only).
19587
+ */
19588
+ var NcHistoryEntrySchema = object({
19589
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
19590
+ id: string(),
19591
+ ruleId: string(),
19592
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
19593
+ ruleName: string(),
19594
+ /** The rule urgency/trigger that produced this delivery. */
19595
+ delivery: NcDeliverySchema,
19596
+ targetId: string(),
19597
+ deviceId: number(),
19598
+ recordKind: NcHistoryRecordKindSchema,
19599
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
19600
+ recordId: string(),
19601
+ /** Present for track-scoped deliveries (object-event / track-end). */
19602
+ trackId: string().optional(),
19603
+ status: NcHistoryStatusSchema,
19604
+ /** Delivery attempts made so far. */
19605
+ attempts: number().int(),
19606
+ /** Fire time (outbox enqueue). */
19607
+ createdAt: number(),
19608
+ /** Last transition time (terminal for sent / dead). */
19609
+ updatedAt: number(),
19610
+ /** Failure detail — present on a `dead` row. */
19611
+ error: string().optional(),
19612
+ subject: NcHistorySubjectSchema
19106
19613
  });
19107
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
19108
- var ProfileRefInputSchema = object({
19109
- addonId: string(),
19110
- profileId: string()
19614
+ /**
19615
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
19616
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
19617
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
19618
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
19619
+ */
19620
+ var NcHistoryFilterSchema = object({
19621
+ ruleId: string().optional(),
19622
+ deviceId: number().optional(),
19623
+ status: NcHistoryStatusSchema.optional(),
19624
+ since: number().optional(),
19625
+ until: number().optional(),
19626
+ limit: number().int().min(1).max(500).default(100)
19111
19627
  });
19112
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
19113
- kind: "mutation",
19114
- auth: "admin"
19115
- }), method(ProfileRefInputSchema, _void(), {
19628
+ 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 }), {
19116
19629
  kind: "mutation",
19117
- auth: "admin"
19118
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
19630
+ auth: "admin",
19631
+ caller: "required"
19632
+ }), method(object({
19633
+ ruleId: string(),
19634
+ patch: NcRulePatchSchema
19635
+ }), object({ rule: NcRuleSchema }), {
19119
19636
  kind: "mutation",
19120
- auth: "admin"
19121
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
19122
- selector: LlmDefaultSelectorSchema,
19123
- profileId: string().nullable()
19124
- }), _void(), {
19637
+ auth: "admin",
19638
+ caller: "required"
19639
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
19125
19640
  kind: "mutation",
19126
19641
  auth: "admin"
19127
19642
  }), method(object({
19128
- since: number().optional(),
19129
- until: number().optional(),
19130
- consumer: string().optional(),
19131
- profileId: string().optional()
19132
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
19133
- nodeId: string(),
19134
- model: ManagedModelRefSchema
19135
- }), _void(), {
19643
+ ruleId: string(),
19644
+ enabled: boolean()
19645
+ }), object({ success: literal(true) }), {
19136
19646
  kind: "mutation",
19137
19647
  auth: "admin"
19138
19648
  }), method(object({
19139
- nodeId: string(),
19140
- file: string()
19141
- }), _void(), {
19142
- kind: "mutation",
19143
- auth: "admin"
19144
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
19145
- kind: "mutation",
19146
- auth: "admin"
19147
- }), method(ProfileRefInputSchema, _void(), {
19649
+ rule: NcRuleInputSchema,
19650
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
19651
+ }), object({ results: array(NcTestResultSchema) }), {
19148
19652
  kind: "mutation",
19149
19653
  auth: "admin"
19150
- });
19654
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
19151
19655
  /**
19152
19656
  * Zod schemas for persisted record types.
19153
19657
  *
@@ -19833,7 +20337,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19833
20337
  }), method(object({
19834
20338
  eventId: string(),
19835
20339
  kind: MediaFileKindEnum.optional()
19836
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
20340
+ }), array(MediaFileSchema).readonly()), method(object({
20341
+ trackId: string(),
20342
+ kinds: array(MediaFileKindEnum).optional()
20343
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
19837
20344
  deviceId: number(),
19838
20345
  timestamp: number(),
19839
20346
  frameWidth: number(),
@@ -19854,76 +20361,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19854
20361
  eventId: string(),
19855
20362
  timestamp: number()
19856
20363
  });
19857
- /**
19858
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
19859
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
19860
- * caps into per-camera event-kind descriptors.
19861
- *
19862
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
19863
- * is NOT duplicated here — every entry is derived from the single
19864
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
19865
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
19866
- * control cap means adding one line here (and a taxonomy entry); the anti-
19867
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
19868
- * eventful cap is missing.
19869
- */
19870
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
19871
- var LEGACY_ICON = {
19872
- motion: "motion",
19873
- audio: "audio",
19874
- person: "person",
19875
- vehicle: "vehicle",
19876
- animal: "animal",
19877
- package: "package",
19878
- door: "door",
19879
- pir: "pir",
19880
- smoke: "smoke",
19881
- water: "water",
19882
- button: "button",
19883
- generic: "generic",
19884
- gas: "smoke",
19885
- vibration: "generic",
19886
- tamper: "generic",
19887
- presence: "person",
19888
- lock: "generic",
19889
- siren: "generic",
19890
- switch: "generic",
19891
- doorbell: "button"
19892
- };
19893
- function legacyIcon(iconId) {
19894
- return LEGACY_ICON[iconId] ?? "generic";
19895
- }
19896
- /**
19897
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
19898
- * The anti-drift guard cross-checks this against the eventful caps declared
19899
- * in `packages/types/src/capabilities/*.cap.ts`.
19900
- */
19901
- var CAP_TO_KIND = {
19902
- contact: "contact",
19903
- motion: "motion-sensor",
19904
- smoke: "smoke",
19905
- flood: "flood",
19906
- gas: "gas",
19907
- "carbon-monoxide": "carbon-monoxide",
19908
- vibration: "vibration",
19909
- tamper: "tamper",
19910
- presence: "presence",
19911
- "enum-sensor": "enum-sensor",
19912
- "event-emitter": "device-event",
19913
- "lock-control": "lock",
19914
- switch: "switch",
19915
- button: "button",
19916
- doorbell: "doorbell"
19917
- };
19918
- function buildDescriptor(capName, kind) {
19919
- const t = EVENT_TAXONOMY[kind];
19920
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
19921
- return {
19922
- ...t,
19923
- icon: legacyIcon(t.iconId)
19924
- };
19925
- }
19926
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
19927
20364
  var CameraPipelineConfigSchema = object({
19928
20365
  engine: PipelineEngineChoiceSchema.optional(),
19929
20366
  steps: array(PipelineStepInputSchema).readonly(),
@@ -20409,6 +20846,76 @@ method(object({
20409
20846
  auth: "admin"
20410
20847
  });
20411
20848
  /**
20849
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
20850
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
20851
+ * caps into per-camera event-kind descriptors.
20852
+ *
20853
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
20854
+ * is NOT duplicated here — every entry is derived from the single
20855
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
20856
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
20857
+ * control cap means adding one line here (and a taxonomy entry); the anti-
20858
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
20859
+ * eventful cap is missing.
20860
+ */
20861
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
20862
+ var LEGACY_ICON = {
20863
+ motion: "motion",
20864
+ audio: "audio",
20865
+ person: "person",
20866
+ vehicle: "vehicle",
20867
+ animal: "animal",
20868
+ package: "package",
20869
+ door: "door",
20870
+ pir: "pir",
20871
+ smoke: "smoke",
20872
+ water: "water",
20873
+ button: "button",
20874
+ generic: "generic",
20875
+ gas: "smoke",
20876
+ vibration: "generic",
20877
+ tamper: "generic",
20878
+ presence: "person",
20879
+ lock: "generic",
20880
+ siren: "generic",
20881
+ switch: "generic",
20882
+ doorbell: "button"
20883
+ };
20884
+ function legacyIcon(iconId) {
20885
+ return LEGACY_ICON[iconId] ?? "generic";
20886
+ }
20887
+ /**
20888
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
20889
+ * The anti-drift guard cross-checks this against the eventful caps declared
20890
+ * in `packages/types/src/capabilities/*.cap.ts`.
20891
+ */
20892
+ var CAP_TO_KIND = {
20893
+ contact: "contact",
20894
+ motion: "motion-sensor",
20895
+ smoke: "smoke",
20896
+ flood: "flood",
20897
+ gas: "gas",
20898
+ "carbon-monoxide": "carbon-monoxide",
20899
+ vibration: "vibration",
20900
+ tamper: "tamper",
20901
+ presence: "presence",
20902
+ "enum-sensor": "enum-sensor",
20903
+ "event-emitter": "device-event",
20904
+ "lock-control": "lock",
20905
+ switch: "switch",
20906
+ button: "button",
20907
+ doorbell: "doorbell"
20908
+ };
20909
+ function buildDescriptor(capName, kind) {
20910
+ const t = EVENT_TAXONOMY[kind];
20911
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
20912
+ return {
20913
+ ...t,
20914
+ icon: legacyIcon(t.iconId)
20915
+ };
20916
+ }
20917
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
20918
+ /**
20412
20919
  * server-management — per-NODE singleton capability for a node's ROOT
20413
20920
  * package lifecycle (runtime-updatable node packages).
20414
20921
  *
@@ -21914,7 +22421,28 @@ var FaceInfoSchema = object({
21914
22421
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
21915
22422
  * track produced no key frame (e.g. native/onboard source) — the UI falls
21916
22423
  * back to the inline `base64` face crop. */
21917
- keyFrameMediaKey: string().optional()
22424
+ keyFrameMediaKey: string().optional(),
22425
+ /** Winning identity-match cosine (0..1) for this face's track, when an
22426
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
22427
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
22428
+ * faces that were never auto-recognized. */
22429
+ bestMatchScore: number().optional(),
22430
+ /** Native-scale face short side (px) at recognition time, when the runner
22431
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
22432
+ * legacy rows / runners that reported no native measure. */
22433
+ nativeFaceShortSidePx: number().optional(),
22434
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
22435
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
22436
+ * but blocked only by the recognition size floor). Mutually exclusive with
22437
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
22438
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
22439
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
22440
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
22441
+ suggestedIdentityId: string().optional(),
22442
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
22443
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
22444
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
22445
+ suggestedMatchScore: number().optional()
21918
22446
  });
21919
22447
  var FaceFilterEnum = _enum([
21920
22448
  "unassigned",
@@ -23970,36 +24498,6 @@ Object.freeze({
23970
24498
  addonId: null,
23971
24499
  access: "view"
23972
24500
  },
23973
- "advancedNotifier.deleteRule": {
23974
- capName: "advanced-notifier",
23975
- capScope: "system",
23976
- addonId: null,
23977
- access: "delete"
23978
- },
23979
- "advancedNotifier.getHistory": {
23980
- capName: "advanced-notifier",
23981
- capScope: "system",
23982
- addonId: null,
23983
- access: "view"
23984
- },
23985
- "advancedNotifier.getRules": {
23986
- capName: "advanced-notifier",
23987
- capScope: "system",
23988
- addonId: null,
23989
- access: "view"
23990
- },
23991
- "advancedNotifier.testRule": {
23992
- capName: "advanced-notifier",
23993
- capScope: "system",
23994
- addonId: null,
23995
- access: "create"
23996
- },
23997
- "advancedNotifier.upsertRule": {
23998
- capName: "advanced-notifier",
23999
- capScope: "system",
24000
- addonId: null,
24001
- access: "create"
24002
- },
24003
24501
  "alarmPanel.arm": {
24004
24502
  capName: "alarm-panel",
24005
24503
  capScope: "device",
@@ -26304,6 +26802,60 @@ Object.freeze({
26304
26802
  addonId: null,
26305
26803
  access: "create"
26306
26804
  },
26805
+ "notificationRules.createRule": {
26806
+ capName: "notification-rules",
26807
+ capScope: "system",
26808
+ addonId: null,
26809
+ access: "create"
26810
+ },
26811
+ "notificationRules.deleteRule": {
26812
+ capName: "notification-rules",
26813
+ capScope: "system",
26814
+ addonId: null,
26815
+ access: "delete"
26816
+ },
26817
+ "notificationRules.getConditionCatalog": {
26818
+ capName: "notification-rules",
26819
+ capScope: "system",
26820
+ addonId: null,
26821
+ access: "view"
26822
+ },
26823
+ "notificationRules.getHistory": {
26824
+ capName: "notification-rules",
26825
+ capScope: "system",
26826
+ addonId: null,
26827
+ access: "view"
26828
+ },
26829
+ "notificationRules.getRule": {
26830
+ capName: "notification-rules",
26831
+ capScope: "system",
26832
+ addonId: null,
26833
+ access: "view"
26834
+ },
26835
+ "notificationRules.listRules": {
26836
+ capName: "notification-rules",
26837
+ capScope: "system",
26838
+ addonId: null,
26839
+ access: "view"
26840
+ },
26841
+ "notificationRules.setRuleEnabled": {
26842
+ capName: "notification-rules",
26843
+ capScope: "system",
26844
+ addonId: null,
26845
+ access: "create"
26846
+ },
26847
+ "notificationRules.testRule": {
26848
+ capName: "notification-rules",
26849
+ capScope: "system",
26850
+ addonId: null,
26851
+ access: "create"
26852
+ },
26853
+ "notificationRules.updateRule": {
26854
+ capName: "notification-rules",
26855
+ capScope: "system",
26856
+ addonId: null,
26857
+ access: "create"
26858
+ },
26307
26859
  "notifier.cancel": {
26308
26860
  capName: "notifier",
26309
26861
  capScope: "device",