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