@camstack/addon-provider-rademacher 0.2.4 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1411 -859
  2. package/dist/addon.mjs +1411 -859
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -983,7 +983,7 @@ var Rademacher = class {
983
983
  }
984
984
  };
985
985
  //#endregion
986
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
986
+ //#region ../types/dist/event-category-BLcNejAE.mjs
987
987
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
988
988
  EventCategory["SystemBoot"] = "system.boot";
989
989
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -1133,9 +1133,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
1133
1133
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
1134
1134
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
1135
1135
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
1136
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
1137
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
1138
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
1139
1136
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
1140
1137
  * progress bar the client reconciles via `recordingExport.getExport`. */
1141
1138
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -7814,7 +7811,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
7814
7811
  patch: record(string(), unknown())
7815
7812
  }), object({ success: literal(true) });
7816
7813
  object({ deviceId: number() }), unknown().nullable();
7817
- /** Shorthand to define a method schema */
7818
7814
  function method(input, output, options) {
7819
7815
  return {
7820
7816
  input,
@@ -7822,6 +7818,7 @@ function method(input, output, options) {
7822
7818
  kind: options?.kind ?? "query",
7823
7819
  auth: options?.auth ?? "protected",
7824
7820
  ...options?.access !== void 0 ? { access: options.access } : {},
7821
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
7825
7822
  timeoutMs: options?.timeoutMs
7826
7823
  };
7827
7824
  }
@@ -9191,6 +9188,59 @@ for (const l of AUDIO_MACRO_LABELS) {
9191
9188
  /** The complete taxonomy dictionary, keyed by kind. */
9192
9189
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
9193
9190
  /**
9191
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
9192
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
9193
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
9194
+ * taxonomy surface (timeline, filters, event page).
9195
+ *
9196
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
9197
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
9198
+ * for the `classes` / `classesExclude` conditions.
9199
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
9200
+ * the same class picker, grouped under an Audio header.
9201
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
9202
+ * lock / …) for the `sensorKinds` device-event condition.
9203
+ *
9204
+ * Each entry carries `parentKind` so the client can group video subs under
9205
+ * their macro and sensor/control kinds under their category. This surface is
9206
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
9207
+ * method, no codegen — so it ships train-free with an addon deploy.
9208
+ */
9209
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
9210
+ var NcTaxonomyEntrySchema = object({
9211
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
9212
+ kind: string(),
9213
+ /** English fallback label (the UI translates via the event-kind i18n key). */
9214
+ label: string(),
9215
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
9216
+ parentKind: string().nullable()
9217
+ });
9218
+ object({
9219
+ videoClasses: array(NcTaxonomyEntrySchema),
9220
+ audioKinds: array(NcTaxonomyEntrySchema),
9221
+ labels: array(NcTaxonomyEntrySchema)
9222
+ });
9223
+ function toEntry(kind, label, parentKind) {
9224
+ return {
9225
+ kind,
9226
+ label,
9227
+ parentKind
9228
+ };
9229
+ }
9230
+ /**
9231
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
9232
+ * (macros before their subs), which the client relies on for stable grouping.
9233
+ */
9234
+ function buildNcTaxonomy() {
9235
+ const all = Object.values(EVENT_TAXONOMY);
9236
+ return {
9237
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
9238
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
9239
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
9240
+ };
9241
+ }
9242
+ Object.freeze(buildNcTaxonomy());
9243
+ /**
9194
9244
  * Error types for the safe expression engine. Two distinct classes so callers
9195
9245
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
9196
9246
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -13176,6 +13226,22 @@ var CameraMetricsSchema = object({
13176
13226
  ])
13177
13227
  });
13178
13228
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
13229
+ /**
13230
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
13231
+ * within the frame, so the executor can re-cut a leaf child ROI at native
13232
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
13233
+ */
13234
+ var NativeCropRefSchema = object({
13235
+ /** Handle keying the retained native surface (node-pinned to its owner). */
13236
+ handle: FrameHandleSchema,
13237
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
13238
+ cropFrameSpace: object({
13239
+ x: number(),
13240
+ y: number(),
13241
+ w: number(),
13242
+ h: number()
13243
+ })
13244
+ });
13179
13245
  var ModelFormatSchema$1 = _enum([
13180
13246
  "onnx",
13181
13247
  "coreml",
@@ -13451,7 +13517,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
13451
13517
  * Omitted ⇒ the runner's default device (current single-engine
13452
13518
  * behaviour). Selects WHICH device pool of the node runs the call.
13453
13519
  */
13454
- deviceKey: string().optional()
13520
+ deviceKey: string().optional(),
13521
+ /**
13522
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
13523
+ * when the parent crop was resolved from the frame's retained NATIVE
13524
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
13525
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
13526
+ * resolution from that surface — the SAME quality path faces already
13527
+ * had — instead of the downscaled parent tile. `handle` keys the native
13528
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
13529
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
13530
+ * the executor's crop-normalized child ROI back into frame-normalized
13531
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
13532
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
13533
+ * (today's behaviour on the fallback path).
13534
+ */
13535
+ nativeCropRef: NativeCropRefSchema.optional()
13455
13536
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
13456
13537
  engine: PipelineEngineChoiceSchema.optional(),
13457
13538
  steps: array(PipelineStepInputSchema).min(1),
@@ -13700,7 +13781,11 @@ var DetailResultSchema = object({
13700
13781
  bbox: NativeCropBboxSchema.optional(),
13701
13782
  embedding: string().optional(),
13702
13783
  label: string().optional(),
13703
- alignedCropJpeg: string().optional()
13784
+ alignedCropJpeg: string().optional(),
13785
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
13786
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
13787
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
13788
+ nativeFaceShortSidePx: number().optional()
13704
13789
  });
13705
13790
  /**
13706
13791
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -13714,6 +13799,12 @@ var motionCooldownMsField = {
13714
13799
  default: 3e4,
13715
13800
  step: 500
13716
13801
  };
13802
+ var maxSessionHoldMsField = {
13803
+ min: 0,
13804
+ max: 6e5,
13805
+ default: 12e4,
13806
+ step: 5e3
13807
+ };
13717
13808
  var motionFpsField = {
13718
13809
  min: 1,
13719
13810
  max: 30,
@@ -13861,6 +13952,19 @@ var RunnerCameraConfigSchema = object({
13861
13952
  "on-motion"
13862
13953
  ]).default("always-on"),
13863
13954
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
13955
+ /**
13956
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
13957
+ * detection session is active and ≥1 confirmed non-stationary track is
13958
+ * still live, the orchestrator keeps the session open past
13959
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
13960
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
13961
+ * ms since the session opened, after which it closes regardless. `0`
13962
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
13963
+ * runner itself — carried here so it shares the per-camera device-settings
13964
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
13965
+ * resolved `CameraDetectionConfig`.
13966
+ */
13967
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
13864
13968
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
13865
13969
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
13866
13970
  motionStreamId: string(),
@@ -13950,7 +14054,7 @@ var RunnerCameraConfigSchema = object({
13950
14054
  */
13951
14055
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
13952
14056
  });
13953
- 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;
14057
+ 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;
13954
14058
  /**
13955
14059
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
13956
14060
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -17477,94 +17581,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
17477
17581
  bundleUrl: string()
17478
17582
  });
17479
17583
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
17480
- var NotificationRuleConditionsSchema = object({
17481
- deviceIds: array(number()).readonly().optional(),
17482
- classNames: array(string()).readonly().optional(),
17483
- zoneIds: array(string()).readonly().optional(),
17484
- minConfidence: number().optional(),
17485
- source: _enum([
17486
- "pipeline",
17487
- "onboard",
17488
- "any"
17489
- ]).optional(),
17490
- schedule: object({
17491
- days: array(number()).readonly(),
17492
- startHour: number(),
17493
- endHour: number()
17494
- }).optional(),
17495
- cooldownSeconds: number().optional(),
17496
- minDwellSeconds: number().optional(),
17497
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
17498
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
17499
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
17500
- eventTypeTokens: array(string()).readonly().optional(),
17501
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
17502
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
17503
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
17504
- clipDescription: object({
17505
- text: string().min(1),
17506
- minSimilarity: number().min(0).max(1)
17507
- }).optional(),
17508
- /** Match events whose recognized-entity label (face identity name or plate
17509
- * vehicle name, propagated onto `event.data.label`) is one of these values.
17510
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
17511
- * vehicle/person> is seen". */
17512
- labels: array(string()).readonly().optional()
17513
- });
17514
- var NotificationRuleTemplateSchema = object({
17515
- title: string(),
17516
- body: string(),
17517
- imageMode: _enum([
17518
- "crop",
17519
- "annotated",
17520
- "full",
17521
- "none"
17522
- ])
17523
- });
17524
- var NotificationRuleSchema = object({
17525
- id: string(),
17526
- name: string(),
17527
- enabled: boolean(),
17528
- eventTypes: array(string()).readonly(),
17529
- conditions: NotificationRuleConditionsSchema,
17530
- outputs: array(string()).readonly(),
17531
- template: NotificationRuleTemplateSchema.optional(),
17532
- priority: _enum([
17533
- "low",
17534
- "normal",
17535
- "high",
17536
- "critical"
17537
- ])
17538
- });
17539
- var NotificationTestResultSchema = object({
17540
- ruleId: string(),
17541
- eventId: string(),
17542
- timestamp: number(),
17543
- wouldFire: boolean(),
17544
- reason: string().optional()
17545
- });
17546
- var NotificationHistoryEntrySchema = object({
17547
- id: string(),
17548
- ruleId: string(),
17549
- ruleName: string(),
17550
- eventId: string(),
17551
- timestamp: number(),
17552
- outputs: array(string()).readonly(),
17553
- success: boolean(),
17554
- error: string().optional(),
17555
- deviceId: number().optional()
17556
- });
17557
- var NotificationHistoryFilterSchema = object({
17558
- ruleId: string().optional(),
17559
- deviceId: number().optional(),
17560
- from: number().optional(),
17561
- to: number().optional(),
17562
- limit: number().optional()
17563
- });
17564
- 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({
17565
- ruleId: string(),
17566
- lookbackMinutes: number()
17567
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
17568
17584
  /**
17569
17585
  * Alerts capability — collection-based internal alert system.
17570
17586
  *
@@ -17751,89 +17767,6 @@ method(object({
17751
17767
  password: string()
17752
17768
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
17753
17769
  /**
17754
- * `login-method` — collection cap through which auth addons contribute
17755
- * their pre-auth login surfaces to the login page. This is the SINGLE,
17756
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
17757
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
17758
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
17759
- * procedure aggregates them for the unauthenticated login page.
17760
- *
17761
- * A contribution is a discriminated union on `kind`:
17762
- *
17763
- * - `redirect` — a declarative button. The login page renders a generic
17764
- * button that navigates to `startUrl` (an addon-owned HTTP route).
17765
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
17766
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
17767
- * login page needs NO change.
17768
- *
17769
- * - `widget` — a Module-Federation widget the login page mounts (via
17770
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
17771
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
17772
- * mechanism kept for future use; no shipped addon uses it on the login
17773
- * page (the passkey ceremony below runs natively in the shell instead).
17774
- *
17775
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
17776
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
17777
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
17778
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
17779
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
17780
- * fetching any remote code pre-auth. Contribution stays unconditional —
17781
- * enrollment state is never leaked pre-auth; visibility is a shell
17782
- * decision.
17783
- *
17784
- * Every contribution carries a `stage`:
17785
- * - `primary` — shown on the first credentials screen (OIDC /
17786
- * magic-link buttons; a future usernameless passkey).
17787
- * - `second-factor` — shown AFTER the password leg, gated on the
17788
- * returned `factors` (passkey-as-2FA today).
17789
- *
17790
- * `mount: skip` — the cap is read server-side by the core auth router
17791
- * (`registry.getCollection('login-method')`), never mounted as its own
17792
- * tRPC router.
17793
- */
17794
- /** When a login method renders in the two-phase login flow. */
17795
- var LoginStageEnum = _enum(["primary", "second-factor"]);
17796
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
17797
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
17798
- object({
17799
- kind: literal("redirect"),
17800
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
17801
- id: string(),
17802
- /** Operator-facing button label. */
17803
- label: string(),
17804
- /** lucide-react icon name. */
17805
- icon: string().optional(),
17806
- /** Addon-owned HTTP route the button navigates to (GET). */
17807
- startUrl: string(),
17808
- stage: LoginStageEnum
17809
- }),
17810
- object({
17811
- kind: literal("widget"),
17812
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
17813
- id: string(),
17814
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
17815
- addonId: string(),
17816
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
17817
- bundle: string(),
17818
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
17819
- remote: WidgetRemoteSchema,
17820
- stage: LoginStageEnum
17821
- }),
17822
- object({
17823
- kind: literal("passkey"),
17824
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
17825
- id: string(),
17826
- /** Operator-facing button label. */
17827
- label: string(),
17828
- stage: LoginStageEnum,
17829
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
17830
- rpId: string(),
17831
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
17832
- origin: string().nullable()
17833
- })
17834
- ]);
17835
- method(_void(), array(LoginMethodContributionSchema).readonly());
17836
- /**
17837
17770
  * Orchestrator-side destination metadata. The orchestrator computes
17838
17771
  * `id = <addonId>:<subId>` from its provider lookup so consumers
17839
17772
  * (admin UI, restore flow) see one canonical key.
@@ -19177,242 +19110,617 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
19177
19110
  kind: "mutation",
19178
19111
  auth: "admin"
19179
19112
  });
19180
- var LogLevelSchema = _enum([
19181
- "debug",
19182
- "info",
19183
- "warn",
19184
- "error"
19113
+ /**
19114
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
19115
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
19116
+ * caps stay wire-compatible without a circular cap→cap import.
19117
+ *
19118
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
19119
+ * every transport tier structurally, and failed calls still write usage rows.
19120
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
19121
+ */
19122
+ var LlmUsageSchema = object({
19123
+ inputTokens: number(),
19124
+ outputTokens: number()
19125
+ });
19126
+ var LlmErrorCodeSchema = _enum([
19127
+ "timeout",
19128
+ "rate-limited",
19129
+ "auth",
19130
+ "refusal",
19131
+ "bad-request",
19132
+ "unavailable",
19133
+ "no-profile",
19134
+ "budget-exceeded",
19135
+ "adapter-error"
19185
19136
  ]);
19186
- var LogEntrySchema = object({
19187
- timestamp: date(),
19188
- level: LogLevelSchema,
19189
- scope: array(string()),
19137
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
19138
+ ok: literal(true),
19139
+ text: string(),
19140
+ model: string(),
19141
+ usage: LlmUsageSchema,
19142
+ truncated: boolean(),
19143
+ latencyMs: number()
19144
+ }), object({
19145
+ ok: literal(false),
19146
+ code: LlmErrorCodeSchema,
19190
19147
  message: string(),
19191
- meta: record(string(), unknown()).optional(),
19192
- tags: record(string(), string()).optional()
19193
- });
19194
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
19195
- scope: array(string()).optional(),
19196
- level: LogLevelSchema.optional(),
19197
- since: date().optional(),
19198
- until: date().optional(),
19199
- limit: number().optional(),
19200
- tags: record(string(), string()).optional()
19201
- }), array(LogEntrySchema).readonly());
19202
- var CpuBreakdownSchema = object({
19203
- total: number(),
19204
- user: number(),
19205
- system: number(),
19206
- irq: number(),
19207
- nice: number(),
19208
- loadAvg: tuple([
19209
- number(),
19210
- number(),
19211
- number()
19212
- ]),
19213
- cores: number()
19148
+ retryAfterMs: number().optional()
19149
+ })]);
19150
+ /**
19151
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
19152
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
19153
+ * notification-output.cap.ts:27-31 precedents).
19154
+ */
19155
+ var LlmImageSchema = object({
19156
+ bytes: _instanceof(Uint8Array),
19157
+ mimeType: string()
19214
19158
  });
19215
- var MemoryInfoSchema = object({
19216
- percent: number(),
19217
- totalBytes: number(),
19218
- usedBytes: number(),
19219
- availableBytes: number(),
19220
- swapUsedBytes: number(),
19221
- swapTotalBytes: number()
19159
+ var LlmGenerateBaseInputSchema = object({
19160
+ /** Collection routing (the notification-output posture). */
19161
+ addonId: string().optional(),
19162
+ /** Explicit profile; else the resolution chain (spec §3). */
19163
+ profileId: string().optional(),
19164
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
19165
+ consumer: string(),
19166
+ system: string().optional(),
19167
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
19168
+ prompt: string(),
19169
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
19170
+ jsonSchema: record(string(), unknown()).optional(),
19171
+ /** Per-call override of the profile default. */
19172
+ maxTokens: number().int().positive().optional(),
19173
+ temperature: number().optional()
19222
19174
  });
19223
- var DiskIoSnapshotSchema = object({
19224
- readBytes: number(),
19225
- writeBytes: number(),
19226
- readOps: number(),
19227
- writeOps: number(),
19228
- timestampMs: number()
19229
- });
19230
- var NetworkIoSnapshotSchema = object({
19231
- rxBytes: number(),
19232
- txBytes: number(),
19233
- rxPackets: number(),
19234
- txPackets: number(),
19235
- rxErrors: number(),
19236
- txErrors: number(),
19237
- timestampMs: number()
19238
- });
19239
- var MetricsGpuInfoSchema = object({
19240
- utilization: number(),
19241
- model: string(),
19242
- memoryUsedBytes: number(),
19243
- memoryTotalBytes: number(),
19244
- temperature: number().nullable()
19245
- });
19246
- var ProcessResourceInfoSchema = object({
19247
- openFds: number(),
19248
- threadCount: number(),
19249
- activeHandles: number(),
19250
- activeRequests: number()
19251
- });
19252
- var PressureAvgsSchema = object({
19253
- avg10: number(),
19254
- avg60: number(),
19255
- avg300: number()
19256
- });
19257
- var PressureInfoSchema = object({
19258
- some: PressureAvgsSchema,
19259
- full: PressureAvgsSchema.nullable()
19260
- });
19261
- var SystemResourceSnapshotSchema = object({
19262
- cpu: CpuBreakdownSchema,
19263
- memory: MemoryInfoSchema,
19264
- gpu: MetricsGpuInfoSchema.nullable(),
19265
- network: NetworkIoSnapshotSchema,
19266
- disk: DiskIoSnapshotSchema,
19267
- pressure: object({
19268
- cpu: PressureInfoSchema.nullable(),
19269
- memory: PressureInfoSchema.nullable(),
19270
- io: PressureInfoSchema.nullable()
19175
+ /**
19176
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
19177
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
19178
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
19179
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
19180
+ * this only through the `llm` cap's methods.
19181
+ *
19182
+ * One running llama-server child per node in v1 (models are RAM-heavy).
19183
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
19184
+ * watchdog — operator decision #3).
19185
+ */
19186
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
19187
+ object({
19188
+ kind: literal("catalog"),
19189
+ catalogId: string()
19271
19190
  }),
19272
- process: ProcessResourceInfoSchema,
19273
- cpuTemperature: number().nullable(),
19274
- timestampMs: number()
19275
- });
19276
- var DiskSpaceInfoSchema = object({
19277
- path: string(),
19278
- totalBytes: number(),
19279
- usedBytes: number(),
19280
- availableBytes: number(),
19281
- percent: number()
19282
- });
19283
- var PidResourceStatsSchema = object({
19284
- pid: number(),
19285
- cpu: number(),
19286
- memory: number(),
19287
- /**
19288
- * Private (anonymous) resident bytes — the per-process V8 heap + native
19289
- * allocations NOT shared with other processes (Linux RssAnon). This is the
19290
- * "real" per-runner cost; summing it across runners is meaningful, unlike
19291
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
19292
- * Undefined where /proc is unavailable (e.g. macOS).
19293
- */
19294
- privateBytes: number().optional(),
19295
- /**
19296
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
19297
- * code shared copy-on-write across runners. Undefined on macOS.
19298
- */
19299
- sharedBytes: number().optional()
19191
+ object({
19192
+ kind: literal("url"),
19193
+ url: string(),
19194
+ sha256: string().optional()
19195
+ }),
19196
+ object({
19197
+ kind: literal("path"),
19198
+ path: string()
19199
+ })
19200
+ ]);
19201
+ var ManagedRuntimeConfigSchema = object({
19202
+ /** WHERE the runtime lives — hub or any agent. */
19203
+ nodeId: string(),
19204
+ /** Closed for v1; 'ollama' is a v2 candidate. */
19205
+ engine: _enum(["llama-cpp"]),
19206
+ model: ManagedModelRefSchema,
19207
+ contextSize: number().int().default(4096),
19208
+ /** 0 = CPU-only. */
19209
+ gpuLayers: number().int().default(0),
19210
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
19211
+ threads: number().int().optional(),
19212
+ /** Concurrent slots. */
19213
+ parallel: number().int().default(1),
19214
+ /** Else lazy: first generate boots it. */
19215
+ autoStart: boolean().default(false),
19216
+ /** 0 = never; frees RAM after quiet periods. */
19217
+ idleStopMinutes: number().int().default(30)
19300
19218
  });
19301
- var AddonInstanceSchema = object({
19302
- addonId: string(),
19219
+ var LlmRuntimeStatusSchema = object({
19220
+ /** Status is ALWAYS node-qualified. */
19303
19221
  nodeId: string(),
19304
- role: _enum(["hub", "worker"]),
19305
- pid: number(),
19306
19222
  state: _enum([
19307
- "starting",
19308
- "running",
19309
- "stopping",
19310
19223
  "stopped",
19311
- "crashed"
19312
- ]),
19313
- uptimeSec: number()
19314
- });
19315
- var NodeProcessSchema = object({
19316
- pid: number(),
19317
- ppid: number(),
19318
- pgid: number(),
19319
- classification: _enum([
19320
- "root",
19321
- "managed",
19322
- "system",
19323
- "ghost"
19224
+ "downloading",
19225
+ "starting",
19226
+ "ready",
19227
+ "crashed",
19228
+ "failed"
19324
19229
  ]),
19325
- /** `$process` addon binding when `managed`, else null. */
19326
- addonId: string().nullable(),
19327
- /** Kernel-reported nodeId when the process is a known agent/worker. */
19328
- nodeId: string().nullable(),
19329
- /** Truncated command line. */
19330
- command: string(),
19331
- cpuPercent: number(),
19332
- memoryRssBytes: number(),
19333
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
19334
- uptimeSec: number(),
19335
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
19336
- orphaned: boolean()
19337
- });
19338
- var KillProcessInputSchema = object({
19339
- pid: number(),
19340
- /** Force = SIGKILL. Default is SIGTERM. */
19341
- force: boolean().optional()
19342
- });
19343
- var KillProcessResultSchema = object({
19344
- success: boolean(),
19345
- reason: string().optional(),
19346
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
19347
- });
19348
- var DumpHeapSnapshotInputSchema = object({
19349
- /** The addon whose runner should dump a heap snapshot. */
19350
- addonId: string() });
19351
- var DumpHeapSnapshotResultSchema = object({
19352
- success: boolean(),
19353
- /** Path of the written .heapsnapshot inside the runner's container/host. */
19354
- path: string().optional(),
19355
- /** Process pid that was signalled. */
19356
19230
  pid: number().optional(),
19357
- reason: string().optional()
19231
+ port: number().optional(),
19232
+ modelPath: string().optional(),
19233
+ modelId: string().optional(),
19234
+ downloadProgress: number().min(0).max(1).optional(),
19235
+ lastError: string().optional(),
19236
+ crashesInWindow: number(),
19237
+ /** Child RSS (sampled best-effort). */
19238
+ memoryBytes: number().optional(),
19239
+ vramBytes: number().optional()
19358
19240
  });
19359
- var SystemMetricsSchema = object({
19360
- cpuPercent: number(),
19361
- memoryPercent: number(),
19362
- memoryUsedMB: number(),
19363
- memoryTotalMB: number(),
19364
- diskPercent: number().optional(),
19365
- temperature: number().optional(),
19366
- gpuPercent: number().optional(),
19367
- gpuMemoryPercent: number().optional()
19241
+ var LlmNodeModelSchema = object({
19242
+ file: string(),
19243
+ sizeBytes: number(),
19244
+ catalogId: string().optional(),
19245
+ installedAt: number().optional()
19368
19246
  });
19369
- 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, {
19247
+ var LlmRuntimeDiskUsageSchema = object({
19248
+ nodeId: string(),
19249
+ modelsBytes: number(),
19250
+ freeBytes: number().optional()
19251
+ });
19252
+ method(LlmGenerateBaseInputSchema.extend({
19253
+ images: array(LlmImageSchema).optional(),
19254
+ runtime: ManagedRuntimeConfigSchema,
19255
+ /** The managed profile's timeout, threaded by the hub provider. */
19256
+ timeoutMs: number().int().positive().optional()
19257
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
19370
19258
  kind: "mutation",
19371
19259
  auth: "admin"
19372
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
19260
+ }), method(object({}), _void(), {
19373
19261
  kind: "mutation",
19374
19262
  auth: "admin"
19375
- });
19376
- method(object({
19377
- sourceUrl: string(),
19378
- metadata: ModelConvertMetadataSchema,
19379
- targets: array(ConvertTargetSchema).min(1).readonly(),
19380
- calibrationRef: string().optional(),
19381
- sessionId: string().optional()
19382
- }), ConvertResultSchema, {
19263
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
19383
19264
  kind: "mutation",
19384
- auth: "admin",
19385
- timeoutMs: 6e5
19386
- });
19387
- method(object({
19388
- nodeId: string(),
19389
- modelId: string(),
19390
- format: _enum(MODEL_FORMATS),
19391
- entry: ModelCatalogEntrySchema
19392
- }), object({
19393
- ok: boolean(),
19394
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
19395
- sha256: string(),
19396
- bytes: number(),
19397
- /** The target node's modelsDir the artifact landed in. */
19398
- path: string()
19399
- }), {
19265
+ auth: "admin"
19266
+ }), method(object({ file: string() }), _void(), {
19400
19267
  kind: "mutation",
19401
19268
  auth: "admin"
19402
- });
19269
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
19403
19270
  /**
19404
- * `mqtt-broker` — broker-registry cap.
19405
- *
19406
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
19407
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
19408
- * and (b) the connection details a consumer addon needs to spin up
19409
- * its OWN `mqtt.js` client.
19271
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
19272
+ * methods concat-fan across providers; single-row methods route to ONE
19273
+ * provider by the `addonId` in the call input (the notification-output
19274
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
19275
+ * (hub-placed); the cap stays open for future providers.
19410
19276
  *
19411
- * Why: pub/sub routing over the system event-bus loses fidelity
19412
- * (callback shape, QoS guarantees, will/retain semantics) and adds
19413
- * refcount bookkeeping that addons would rather own themselves. The
19414
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
19415
- * features anyway — give it the connection config, get out of the way.
19277
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
19278
+ * `apiKey` is a password field providers REDACT it on read and merge on
19279
+ * write; a stored key NEVER round-trips to a client.
19280
+ */
19281
+ var LlmProfileKindSchema = _enum([
19282
+ "openai-compatible",
19283
+ "openai",
19284
+ "anthropic",
19285
+ "google",
19286
+ "managed-local"
19287
+ ]);
19288
+ var LlmProfileSchema = object({
19289
+ id: string(),
19290
+ name: string(),
19291
+ kind: LlmProfileKindSchema,
19292
+ /** Stamped by the provider — keeps the fanned catalog routable. */
19293
+ addonId: string(),
19294
+ enabled: boolean(),
19295
+ /** Vendor model id, or the managed runtime's loaded model. */
19296
+ model: string(),
19297
+ /** Required for openai-compatible; override for cloud kinds. */
19298
+ baseUrl: string().optional(),
19299
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
19300
+ apiKey: string().optional(),
19301
+ supportsVision: boolean(),
19302
+ temperature: number().min(0).max(2).optional(),
19303
+ maxTokens: number().int().positive().optional(),
19304
+ timeoutMs: number().int().positive().default(6e4),
19305
+ extraHeaders: record(string(), string()).optional(),
19306
+ /** kind === 'managed-local' only (spec §4). */
19307
+ runtime: ManagedRuntimeConfigSchema.optional()
19308
+ });
19309
+ /** ConfigUISchema tree passed through untyped on the wire (the
19310
+ * notification-output `ConfigSchemaPassthrough` precedent at
19311
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
19312
+ var ConfigSchemaPassthrough$1 = unknown();
19313
+ var LlmProfileKindDescriptorSchema = object({
19314
+ kind: LlmProfileKindSchema,
19315
+ label: string(),
19316
+ icon: string(),
19317
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
19318
+ addonId: string(),
19319
+ configSchema: ConfigSchemaPassthrough$1
19320
+ });
19321
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
19322
+ var LlmDefaultSchema = object({
19323
+ selector: LlmDefaultSelectorSchema,
19324
+ profileId: string()
19325
+ });
19326
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
19327
+ var LlmUsageRollupSchema = object({
19328
+ day: string(),
19329
+ consumer: string(),
19330
+ profileId: string(),
19331
+ calls: number(),
19332
+ okCalls: number(),
19333
+ errorCalls: number(),
19334
+ inputTokens: number(),
19335
+ outputTokens: number(),
19336
+ avgLatencyMs: number()
19337
+ });
19338
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
19339
+ var ManagedModelCatalogEntrySchema = object({
19340
+ id: string(),
19341
+ label: string(),
19342
+ family: string(),
19343
+ purpose: _enum(["text", "vision"]),
19344
+ url: string(),
19345
+ sha256: string(),
19346
+ sizeBytes: number(),
19347
+ quantization: string(),
19348
+ /** Load-time guidance shown in the picker. */
19349
+ minRamBytes: number(),
19350
+ contextSizeDefault: number().int(),
19351
+ /** Vision models: companion projector file. */
19352
+ mmprojUrl: string().optional()
19353
+ });
19354
+ var LlmRuntimeNodeSchema = object({
19355
+ nodeId: string(),
19356
+ reachable: boolean(),
19357
+ status: LlmRuntimeStatusSchema.optional(),
19358
+ disk: LlmRuntimeDiskUsageSchema.optional(),
19359
+ error: string().optional()
19360
+ });
19361
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
19362
+ var ProfileRefInputSchema = object({
19363
+ addonId: string(),
19364
+ profileId: string()
19365
+ });
19366
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
19367
+ kind: "mutation",
19368
+ auth: "admin"
19369
+ }), method(ProfileRefInputSchema, _void(), {
19370
+ kind: "mutation",
19371
+ auth: "admin"
19372
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
19373
+ kind: "mutation",
19374
+ auth: "admin"
19375
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
19376
+ selector: LlmDefaultSelectorSchema,
19377
+ profileId: string().nullable()
19378
+ }), _void(), {
19379
+ kind: "mutation",
19380
+ auth: "admin"
19381
+ }), method(object({
19382
+ since: number().optional(),
19383
+ until: number().optional(),
19384
+ consumer: string().optional(),
19385
+ profileId: string().optional()
19386
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
19387
+ nodeId: string(),
19388
+ model: ManagedModelRefSchema
19389
+ }), _void(), {
19390
+ kind: "mutation",
19391
+ auth: "admin"
19392
+ }), method(object({
19393
+ nodeId: string(),
19394
+ file: string()
19395
+ }), _void(), {
19396
+ kind: "mutation",
19397
+ auth: "admin"
19398
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
19399
+ kind: "mutation",
19400
+ auth: "admin"
19401
+ }), method(ProfileRefInputSchema, _void(), {
19402
+ kind: "mutation",
19403
+ auth: "admin"
19404
+ });
19405
+ var LogLevelSchema = _enum([
19406
+ "debug",
19407
+ "info",
19408
+ "warn",
19409
+ "error"
19410
+ ]);
19411
+ var LogEntrySchema = object({
19412
+ timestamp: date(),
19413
+ level: LogLevelSchema,
19414
+ scope: array(string()),
19415
+ message: string(),
19416
+ meta: record(string(), unknown()).optional(),
19417
+ tags: record(string(), string()).optional()
19418
+ });
19419
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
19420
+ scope: array(string()).optional(),
19421
+ level: LogLevelSchema.optional(),
19422
+ since: date().optional(),
19423
+ until: date().optional(),
19424
+ limit: number().optional(),
19425
+ tags: record(string(), string()).optional()
19426
+ }), array(LogEntrySchema).readonly());
19427
+ /**
19428
+ * `login-method` — collection cap through which auth addons contribute
19429
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
19430
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
19431
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
19432
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
19433
+ * procedure aggregates them for the unauthenticated login page.
19434
+ *
19435
+ * A contribution is a discriminated union on `kind`:
19436
+ *
19437
+ * - `redirect` — a declarative button. The login page renders a generic
19438
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
19439
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
19440
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
19441
+ * login page needs NO change.
19442
+ *
19443
+ * - `widget` — a Module-Federation widget the login page mounts (via
19444
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
19445
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
19446
+ * mechanism kept for future use; no shipped addon uses it on the login
19447
+ * page (the passkey ceremony below runs natively in the shell instead).
19448
+ *
19449
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
19450
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
19451
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
19452
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
19453
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
19454
+ * fetching any remote code pre-auth. Contribution stays unconditional —
19455
+ * enrollment state is never leaked pre-auth; visibility is a shell
19456
+ * decision.
19457
+ *
19458
+ * Every contribution carries a `stage`:
19459
+ * - `primary` — shown on the first credentials screen (OIDC /
19460
+ * magic-link buttons; a future usernameless passkey).
19461
+ * - `second-factor` — shown AFTER the password leg, gated on the
19462
+ * returned `factors` (passkey-as-2FA today).
19463
+ *
19464
+ * `mount: skip` — the cap is read server-side by the core auth router
19465
+ * (`registry.getCollection('login-method')`), never mounted as its own
19466
+ * tRPC router.
19467
+ */
19468
+ /** When a login method renders in the two-phase login flow. */
19469
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
19470
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
19471
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
19472
+ object({
19473
+ kind: literal("redirect"),
19474
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
19475
+ id: string(),
19476
+ /** Operator-facing button label. */
19477
+ label: string(),
19478
+ /** lucide-react icon name. */
19479
+ icon: string().optional(),
19480
+ /** Addon-owned HTTP route the button navigates to (GET). */
19481
+ startUrl: string(),
19482
+ stage: LoginStageEnum
19483
+ }),
19484
+ object({
19485
+ kind: literal("widget"),
19486
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
19487
+ id: string(),
19488
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
19489
+ addonId: string(),
19490
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
19491
+ bundle: string(),
19492
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
19493
+ remote: WidgetRemoteSchema,
19494
+ stage: LoginStageEnum
19495
+ }),
19496
+ object({
19497
+ kind: literal("passkey"),
19498
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
19499
+ id: string(),
19500
+ /** Operator-facing button label. */
19501
+ label: string(),
19502
+ stage: LoginStageEnum,
19503
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
19504
+ rpId: string(),
19505
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
19506
+ origin: string().nullable()
19507
+ })
19508
+ ]);
19509
+ method(_void(), array(LoginMethodContributionSchema).readonly());
19510
+ var CpuBreakdownSchema = object({
19511
+ total: number(),
19512
+ user: number(),
19513
+ system: number(),
19514
+ irq: number(),
19515
+ nice: number(),
19516
+ loadAvg: tuple([
19517
+ number(),
19518
+ number(),
19519
+ number()
19520
+ ]),
19521
+ cores: number()
19522
+ });
19523
+ var MemoryInfoSchema = object({
19524
+ percent: number(),
19525
+ totalBytes: number(),
19526
+ usedBytes: number(),
19527
+ availableBytes: number(),
19528
+ swapUsedBytes: number(),
19529
+ swapTotalBytes: number()
19530
+ });
19531
+ var DiskIoSnapshotSchema = object({
19532
+ readBytes: number(),
19533
+ writeBytes: number(),
19534
+ readOps: number(),
19535
+ writeOps: number(),
19536
+ timestampMs: number()
19537
+ });
19538
+ var NetworkIoSnapshotSchema = object({
19539
+ rxBytes: number(),
19540
+ txBytes: number(),
19541
+ rxPackets: number(),
19542
+ txPackets: number(),
19543
+ rxErrors: number(),
19544
+ txErrors: number(),
19545
+ timestampMs: number()
19546
+ });
19547
+ var MetricsGpuInfoSchema = object({
19548
+ utilization: number(),
19549
+ model: string(),
19550
+ memoryUsedBytes: number(),
19551
+ memoryTotalBytes: number(),
19552
+ temperature: number().nullable()
19553
+ });
19554
+ var ProcessResourceInfoSchema = object({
19555
+ openFds: number(),
19556
+ threadCount: number(),
19557
+ activeHandles: number(),
19558
+ activeRequests: number()
19559
+ });
19560
+ var PressureAvgsSchema = object({
19561
+ avg10: number(),
19562
+ avg60: number(),
19563
+ avg300: number()
19564
+ });
19565
+ var PressureInfoSchema = object({
19566
+ some: PressureAvgsSchema,
19567
+ full: PressureAvgsSchema.nullable()
19568
+ });
19569
+ var SystemResourceSnapshotSchema = object({
19570
+ cpu: CpuBreakdownSchema,
19571
+ memory: MemoryInfoSchema,
19572
+ gpu: MetricsGpuInfoSchema.nullable(),
19573
+ network: NetworkIoSnapshotSchema,
19574
+ disk: DiskIoSnapshotSchema,
19575
+ pressure: object({
19576
+ cpu: PressureInfoSchema.nullable(),
19577
+ memory: PressureInfoSchema.nullable(),
19578
+ io: PressureInfoSchema.nullable()
19579
+ }),
19580
+ process: ProcessResourceInfoSchema,
19581
+ cpuTemperature: number().nullable(),
19582
+ timestampMs: number()
19583
+ });
19584
+ var DiskSpaceInfoSchema = object({
19585
+ path: string(),
19586
+ totalBytes: number(),
19587
+ usedBytes: number(),
19588
+ availableBytes: number(),
19589
+ percent: number()
19590
+ });
19591
+ var PidResourceStatsSchema = object({
19592
+ pid: number(),
19593
+ cpu: number(),
19594
+ memory: number(),
19595
+ /**
19596
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
19597
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
19598
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
19599
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
19600
+ * Undefined where /proc is unavailable (e.g. macOS).
19601
+ */
19602
+ privateBytes: number().optional(),
19603
+ /**
19604
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
19605
+ * code shared copy-on-write across runners. Undefined on macOS.
19606
+ */
19607
+ sharedBytes: number().optional()
19608
+ });
19609
+ var AddonInstanceSchema = object({
19610
+ addonId: string(),
19611
+ nodeId: string(),
19612
+ role: _enum(["hub", "worker"]),
19613
+ pid: number(),
19614
+ state: _enum([
19615
+ "starting",
19616
+ "running",
19617
+ "stopping",
19618
+ "stopped",
19619
+ "crashed"
19620
+ ]),
19621
+ uptimeSec: number()
19622
+ });
19623
+ var NodeProcessSchema = object({
19624
+ pid: number(),
19625
+ ppid: number(),
19626
+ pgid: number(),
19627
+ classification: _enum([
19628
+ "root",
19629
+ "managed",
19630
+ "system",
19631
+ "ghost"
19632
+ ]),
19633
+ /** `$process` addon binding when `managed`, else null. */
19634
+ addonId: string().nullable(),
19635
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
19636
+ nodeId: string().nullable(),
19637
+ /** Truncated command line. */
19638
+ command: string(),
19639
+ cpuPercent: number(),
19640
+ memoryRssBytes: number(),
19641
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
19642
+ uptimeSec: number(),
19643
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
19644
+ orphaned: boolean()
19645
+ });
19646
+ var KillProcessInputSchema = object({
19647
+ pid: number(),
19648
+ /** Force = SIGKILL. Default is SIGTERM. */
19649
+ force: boolean().optional()
19650
+ });
19651
+ var KillProcessResultSchema = object({
19652
+ success: boolean(),
19653
+ reason: string().optional(),
19654
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
19655
+ });
19656
+ var DumpHeapSnapshotInputSchema = object({
19657
+ /** The addon whose runner should dump a heap snapshot. */
19658
+ addonId: string() });
19659
+ var DumpHeapSnapshotResultSchema = object({
19660
+ success: boolean(),
19661
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
19662
+ path: string().optional(),
19663
+ /** Process pid that was signalled. */
19664
+ pid: number().optional(),
19665
+ reason: string().optional()
19666
+ });
19667
+ var SystemMetricsSchema = object({
19668
+ cpuPercent: number(),
19669
+ memoryPercent: number(),
19670
+ memoryUsedMB: number(),
19671
+ memoryTotalMB: number(),
19672
+ diskPercent: number().optional(),
19673
+ temperature: number().optional(),
19674
+ gpuPercent: number().optional(),
19675
+ gpuMemoryPercent: number().optional()
19676
+ });
19677
+ 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, {
19678
+ kind: "mutation",
19679
+ auth: "admin"
19680
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
19681
+ kind: "mutation",
19682
+ auth: "admin"
19683
+ });
19684
+ method(object({
19685
+ sourceUrl: string(),
19686
+ metadata: ModelConvertMetadataSchema,
19687
+ targets: array(ConvertTargetSchema).min(1).readonly(),
19688
+ calibrationRef: string().optional(),
19689
+ sessionId: string().optional()
19690
+ }), ConvertResultSchema, {
19691
+ kind: "mutation",
19692
+ auth: "admin",
19693
+ timeoutMs: 6e5
19694
+ });
19695
+ method(object({
19696
+ nodeId: string(),
19697
+ modelId: string(),
19698
+ format: _enum(MODEL_FORMATS),
19699
+ entry: ModelCatalogEntrySchema
19700
+ }), object({
19701
+ ok: boolean(),
19702
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
19703
+ sha256: string(),
19704
+ bytes: number(),
19705
+ /** The target node's modelsDir the artifact landed in. */
19706
+ path: string()
19707
+ }), {
19708
+ kind: "mutation",
19709
+ auth: "admin"
19710
+ });
19711
+ /**
19712
+ * `mqtt-broker` — broker-registry cap.
19713
+ *
19714
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
19715
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
19716
+ * and (b) the connection details a consumer addon needs to spin up
19717
+ * its OWN `mqtt.js` client.
19718
+ *
19719
+ * Why: pub/sub routing over the system event-bus loses fidelity
19720
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
19721
+ * refcount bookkeeping that addons would rather own themselves. The
19722
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
19723
+ * features anyway — give it the connection config, get out of the way.
19416
19724
  *
19417
19725
  * Consumer flow:
19418
19726
  * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
@@ -19630,398 +19938,594 @@ var NotificationSchema = object({
19630
19938
  });
19631
19939
  /** One declared native severity/priority level for a kind. */
19632
19940
  var TargetKindLevelSchema = object({
19633
- id: string(),
19634
- label: string(),
19635
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
19636
- ordinal: number().int().min(1).max(5).nullable(),
19637
- flags: object({
19638
- critical: boolean().optional(),
19639
- silent: boolean().optional(),
19640
- noPush: boolean().optional()
19641
- }).optional(),
19642
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
19643
- requires: array(string()).optional(),
19644
- description: string().optional()
19645
- });
19646
- /** The full capability block consulted before dispatch. */
19647
- var TargetKindCapsSchema = object({
19648
- attachments: object({
19649
- mediaTypes: array(AttachmentMediaTypeSchema),
19650
- mode: _enum([
19651
- "url",
19652
- "bytes",
19653
- "both"
19654
- ]),
19655
- max: number().int().nonnegative(),
19656
- maxBytes: number().int().positive().optional()
19657
- }),
19658
- /** Max action buttons (0 = none). */
19659
- actions: number().int().nonnegative(),
19660
- levels: array(TargetKindLevelSchema),
19661
- format: array(NotificationFormatSchema),
19662
- clickUrl: boolean(),
19663
- sound: boolean(),
19664
- ttl: boolean(),
19665
- bodyMaxLen: number().int().positive()
19666
- });
19667
- /**
19668
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
19669
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
19670
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
19671
- * the union is large and not meant for runtime validation here; the exported
19672
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
19673
- */
19674
- var ConfigSchemaPassthrough$1 = unknown();
19675
- var TargetKindSchema = object({
19676
- kind: string(),
19677
- label: string(),
19678
- icon: string(),
19679
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
19680
- addonId: string(),
19681
- configSchema: ConfigSchemaPassthrough$1,
19682
- supportsDiscovery: boolean(),
19683
- caps: TargetKindCapsSchema
19684
- });
19685
- /**
19686
- * A persisted target. `config` holds secrets; providers REDACT secret fields
19687
- * (return a presence marker only) when serving `listTargets` — never
19688
- * round-trip a stored secret to the UI.
19689
- */
19690
- var TargetSchema = object({
19691
- id: string(),
19692
- name: string(),
19693
- kind: string(),
19694
- addonId: string(),
19695
- enabled: boolean(),
19696
- config: record(string(), unknown())
19697
- });
19698
- /** A discovery-surfaced candidate (config is partial + non-secret). */
19699
- var DiscoveredTargetSchema = object({
19700
- kind: string(),
19701
- suggestedName: string(),
19702
- config: record(string(), unknown())
19703
- });
19704
- /** The degrade engine's report — what was resolved / dropped / degraded. */
19705
- var RenderedAsSchema = object({
19706
- level: string(),
19707
- format: NotificationFormatSchema,
19708
- attachmentsSent: number().int().nonnegative(),
19709
- actionsSent: number().int().nonnegative(),
19710
- truncated: boolean(),
19711
- dropped: array(string())
19712
- });
19713
- var SendResultSchema = object({
19714
- success: boolean(),
19715
- error: string().optional(),
19716
- renderedAs: RenderedAsSchema.optional()
19717
- });
19718
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
19719
- var TestResultSchema = SendResultSchema;
19720
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
19721
- kind: string(),
19722
- config: record(string(), unknown()).optional()
19723
- }), array(DiscoveredTargetSchema)), method(object({
19724
- targetId: string(),
19725
- notification: NotificationSchema
19726
- }), SendResultSchema, { kind: "mutation" }), method(object({
19727
- targetId: string(),
19728
- sample: NotificationSchema.optional()
19729
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
19730
- targetId: string(),
19731
- enabled: boolean()
19732
- }), _void(), { kind: "mutation" });
19733
- /**
19734
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
19735
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
19736
- * caps stay wire-compatible without a circular cap→cap import.
19737
- *
19738
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
19739
- * every transport tier structurally, and failed calls still write usage rows.
19740
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
19741
- */
19742
- var LlmUsageSchema = object({
19743
- inputTokens: number(),
19744
- outputTokens: number()
19745
- });
19746
- var LlmErrorCodeSchema = _enum([
19747
- "timeout",
19748
- "rate-limited",
19749
- "auth",
19750
- "refusal",
19751
- "bad-request",
19752
- "unavailable",
19753
- "no-profile",
19754
- "budget-exceeded",
19755
- "adapter-error"
19756
- ]);
19757
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
19758
- ok: literal(true),
19759
- text: string(),
19760
- model: string(),
19761
- usage: LlmUsageSchema,
19762
- truncated: boolean(),
19763
- latencyMs: number()
19764
- }), object({
19765
- ok: literal(false),
19766
- code: LlmErrorCodeSchema,
19767
- message: string(),
19768
- retryAfterMs: number().optional()
19769
- })]);
19770
- /**
19771
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
19772
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
19773
- * notification-output.cap.ts:27-31 precedents).
19774
- */
19775
- var LlmImageSchema = object({
19776
- bytes: _instanceof(Uint8Array),
19777
- mimeType: string()
19778
- });
19779
- var LlmGenerateBaseInputSchema = object({
19780
- /** Collection routing (the notification-output posture). */
19781
- addonId: string().optional(),
19782
- /** Explicit profile; else the resolution chain (spec §3). */
19783
- profileId: string().optional(),
19784
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
19785
- consumer: string(),
19786
- system: string().optional(),
19787
- /** v1: single-turn. `messages[]` is a v2 additive field. */
19788
- prompt: string(),
19789
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
19790
- jsonSchema: record(string(), unknown()).optional(),
19791
- /** Per-call override of the profile default. */
19792
- maxTokens: number().int().positive().optional(),
19793
- temperature: number().optional()
19794
- });
19795
- /**
19796
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
19797
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
19798
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
19799
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
19800
- * this only through the `llm` cap's methods.
19801
- *
19802
- * One running llama-server child per node in v1 (models are RAM-heavy).
19803
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
19804
- * watchdog — operator decision #3).
19805
- */
19806
- var ManagedModelRefSchema = discriminatedUnion("kind", [
19807
- object({
19808
- kind: literal("catalog"),
19809
- catalogId: string()
19810
- }),
19811
- object({
19812
- kind: literal("url"),
19813
- url: string(),
19814
- sha256: string().optional()
19815
- }),
19816
- object({
19817
- kind: literal("path"),
19818
- path: string()
19819
- })
19820
- ]);
19821
- var ManagedRuntimeConfigSchema = object({
19822
- /** WHERE the runtime lives — hub or any agent. */
19823
- nodeId: string(),
19824
- /** Closed for v1; 'ollama' is a v2 candidate. */
19825
- engine: _enum(["llama-cpp"]),
19826
- model: ManagedModelRefSchema,
19827
- contextSize: number().int().default(4096),
19828
- /** 0 = CPU-only. */
19829
- gpuLayers: number().int().default(0),
19830
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
19831
- threads: number().int().optional(),
19832
- /** Concurrent slots. */
19833
- parallel: number().int().default(1),
19834
- /** Else lazy: first generate boots it. */
19835
- autoStart: boolean().default(false),
19836
- /** 0 = never; frees RAM after quiet periods. */
19837
- idleStopMinutes: number().int().default(30)
19838
- });
19839
- var LlmRuntimeStatusSchema = object({
19840
- /** Status is ALWAYS node-qualified. */
19841
- nodeId: string(),
19842
- state: _enum([
19843
- "stopped",
19844
- "downloading",
19845
- "starting",
19846
- "ready",
19847
- "crashed",
19848
- "failed"
19849
- ]),
19850
- pid: number().optional(),
19851
- port: number().optional(),
19852
- modelPath: string().optional(),
19853
- modelId: string().optional(),
19854
- downloadProgress: number().min(0).max(1).optional(),
19855
- lastError: string().optional(),
19856
- crashesInWindow: number(),
19857
- /** Child RSS (sampled best-effort). */
19858
- memoryBytes: number().optional(),
19859
- vramBytes: number().optional()
19941
+ id: string(),
19942
+ label: string(),
19943
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
19944
+ ordinal: number().int().min(1).max(5).nullable(),
19945
+ flags: object({
19946
+ critical: boolean().optional(),
19947
+ silent: boolean().optional(),
19948
+ noPush: boolean().optional()
19949
+ }).optional(),
19950
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
19951
+ requires: array(string()).optional(),
19952
+ description: string().optional()
19860
19953
  });
19861
- var LlmNodeModelSchema = object({
19862
- file: string(),
19863
- sizeBytes: number(),
19864
- catalogId: string().optional(),
19865
- installedAt: number().optional()
19954
+ /** The full capability block consulted before dispatch. */
19955
+ var TargetKindCapsSchema = object({
19956
+ attachments: object({
19957
+ mediaTypes: array(AttachmentMediaTypeSchema),
19958
+ mode: _enum([
19959
+ "url",
19960
+ "bytes",
19961
+ "both"
19962
+ ]),
19963
+ max: number().int().nonnegative(),
19964
+ maxBytes: number().int().positive().optional()
19965
+ }),
19966
+ /** Max action buttons (0 = none). */
19967
+ actions: number().int().nonnegative(),
19968
+ levels: array(TargetKindLevelSchema),
19969
+ format: array(NotificationFormatSchema),
19970
+ clickUrl: boolean(),
19971
+ sound: boolean(),
19972
+ ttl: boolean(),
19973
+ bodyMaxLen: number().int().positive()
19866
19974
  });
19867
- var LlmRuntimeDiskUsageSchema = object({
19868
- nodeId: string(),
19869
- modelsBytes: number(),
19870
- freeBytes: number().optional()
19975
+ /**
19976
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
19977
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
19978
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
19979
+ * the union is large and not meant for runtime validation here; the exported
19980
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
19981
+ */
19982
+ var ConfigSchemaPassthrough = unknown();
19983
+ var TargetKindSchema = object({
19984
+ kind: string(),
19985
+ label: string(),
19986
+ icon: string(),
19987
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
19988
+ addonId: string(),
19989
+ configSchema: ConfigSchemaPassthrough,
19990
+ supportsDiscovery: boolean(),
19991
+ caps: TargetKindCapsSchema
19871
19992
  });
19872
- method(LlmGenerateBaseInputSchema.extend({
19873
- images: array(LlmImageSchema).optional(),
19874
- runtime: ManagedRuntimeConfigSchema,
19875
- /** The managed profile's timeout, threaded by the hub provider. */
19876
- timeoutMs: number().int().positive().optional()
19877
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
19878
- kind: "mutation",
19879
- auth: "admin"
19880
- }), method(object({}), _void(), {
19881
- kind: "mutation",
19882
- auth: "admin"
19883
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
19884
- kind: "mutation",
19885
- auth: "admin"
19886
- }), method(object({ file: string() }), _void(), {
19887
- kind: "mutation",
19888
- auth: "admin"
19889
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
19890
19993
  /**
19891
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
19892
- * methods concat-fan across providers; single-row methods route to ONE
19893
- * provider by the `addonId` in the call input (the notification-output
19894
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
19895
- * (hub-placed); the cap stays open for future providers.
19896
- *
19897
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
19898
- * `apiKey` is a password field — providers REDACT it on read and merge on
19899
- * write; a stored key NEVER round-trips to a client.
19994
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
19995
+ * (return a presence marker only) when serving `listTargets` — never
19996
+ * round-trip a stored secret to the UI.
19900
19997
  */
19901
- var LlmProfileKindSchema = _enum([
19902
- "openai-compatible",
19903
- "openai",
19904
- "anthropic",
19905
- "google",
19906
- "managed-local"
19907
- ]);
19908
- var LlmProfileSchema = object({
19998
+ var TargetSchema = object({
19909
19999
  id: string(),
19910
20000
  name: string(),
19911
- kind: LlmProfileKindSchema,
19912
- /** Stamped by the provider — keeps the fanned catalog routable. */
20001
+ kind: string(),
19913
20002
  addonId: string(),
19914
20003
  enabled: boolean(),
19915
- /** Vendor model id, or the managed runtime's loaded model. */
19916
- model: string(),
19917
- /** Required for openai-compatible; override for cloud kinds. */
19918
- baseUrl: string().optional(),
19919
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
19920
- apiKey: string().optional(),
19921
- supportsVision: boolean(),
19922
- temperature: number().min(0).max(2).optional(),
19923
- maxTokens: number().int().positive().optional(),
19924
- timeoutMs: number().int().positive().default(6e4),
19925
- extraHeaders: record(string(), string()).optional(),
19926
- /** kind === 'managed-local' only (spec §4). */
19927
- runtime: ManagedRuntimeConfigSchema.optional()
20004
+ config: record(string(), unknown())
19928
20005
  });
19929
- /** ConfigUISchema tree passed through untyped on the wire (the
19930
- * notification-output `ConfigSchemaPassthrough` precedent at
19931
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
19932
- var ConfigSchemaPassthrough = unknown();
19933
- var LlmProfileKindDescriptorSchema = object({
19934
- kind: LlmProfileKindSchema,
19935
- label: string(),
19936
- icon: string(),
19937
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
19938
- addonId: string(),
19939
- configSchema: ConfigSchemaPassthrough
20006
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
20007
+ var DiscoveredTargetSchema = object({
20008
+ kind: string(),
20009
+ suggestedName: string(),
20010
+ config: record(string(), unknown())
19940
20011
  });
19941
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
19942
- var LlmDefaultSchema = object({
19943
- selector: LlmDefaultSelectorSchema,
19944
- profileId: string()
20012
+ /** The degrade engine's report what was resolved / dropped / degraded. */
20013
+ var RenderedAsSchema = object({
20014
+ level: string(),
20015
+ format: NotificationFormatSchema,
20016
+ attachmentsSent: number().int().nonnegative(),
20017
+ actionsSent: number().int().nonnegative(),
20018
+ truncated: boolean(),
20019
+ dropped: array(string())
19945
20020
  });
19946
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
19947
- var LlmUsageRollupSchema = object({
19948
- day: string(),
19949
- consumer: string(),
19950
- profileId: string(),
19951
- calls: number(),
19952
- okCalls: number(),
19953
- errorCalls: number(),
19954
- inputTokens: number(),
19955
- outputTokens: number(),
19956
- avgLatencyMs: number()
20021
+ var SendResultSchema = object({
20022
+ success: boolean(),
20023
+ error: string().optional(),
20024
+ renderedAs: RenderedAsSchema.optional()
19957
20025
  });
19958
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
19959
- var ManagedModelCatalogEntrySchema = object({
20026
+ /** Same shape as SendResult kept as a distinct name for the test panel. */
20027
+ var TestResultSchema = SendResultSchema;
20028
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
20029
+ kind: string(),
20030
+ config: record(string(), unknown()).optional()
20031
+ }), array(DiscoveredTargetSchema)), method(object({
20032
+ targetId: string(),
20033
+ notification: NotificationSchema
20034
+ }), SendResultSchema, { kind: "mutation" }), method(object({
20035
+ targetId: string(),
20036
+ sample: NotificationSchema.optional()
20037
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
20038
+ targetId: string(),
20039
+ enabled: boolean()
20040
+ }), _void(), { kind: "mutation" });
20041
+ /**
20042
+ * notification-rules — the Notification Center rule surface (P1 core).
20043
+ *
20044
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
20045
+ * (operator decisions D-1/D-2/D-3 are binding):
20046
+ *
20047
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
20048
+ * `notification-center` module), hooked on the durable persistence
20049
+ * moments (object-event insert, TrackCloser.closeExpired) with a
20050
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
20051
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
20052
+ * FIRST persisted detection matching the conditions (per-track dedup,
20053
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
20054
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
20055
+ * - DISPATCH stays behind `notification-output` (rules reference targets
20056
+ * by id; per-backend params are a passthrough blob capped by the
20057
+ * target kind's own caps/degrade engine).
20058
+ *
20059
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
20060
+ * server-injected caller identity — the first `caller: 'required'`
20061
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
20062
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
20063
+ * windows, and the optional label/identity/plate matchers. User rules,
20064
+ * private zones, per-recipient fan-out and the wider condition table are
20065
+ * P2+ (see spec §7).
20066
+ *
20067
+ * All schemas here are the single source of truth — `NcRule` etc. are
20068
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
20069
+ * schema/interface drift is explicitly not repeated).
20070
+ */
20071
+ /**
20072
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
20073
+ * The value maps 1:1 onto the evaluated record kind:
20074
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
20075
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
20076
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
20077
+ * change of a LINKED device, one row per linked camera)
20078
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
20079
+ * delivery / pick-up)
20080
+ *
20081
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
20082
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
20083
+ * this one field keeps the schema additive — a rule still declares exactly
20084
+ * one trigger.
20085
+ */
20086
+ var NcDeliverySchema = _enum([
20087
+ "immediate",
20088
+ "track-end",
20089
+ "device-event",
20090
+ "package-event"
20091
+ ]);
20092
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
20093
+ var NcScheduleSchema = object({
20094
+ windows: array(object({
20095
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
20096
+ days: array(number().int().min(0).max(6)).min(1),
20097
+ startMinute: number().int().min(0).max(1439),
20098
+ endMinute: number().int().min(0).max(1439)
20099
+ })).min(1),
20100
+ /** IANA timezone; default = hub host timezone. */
20101
+ timezone: string().optional(),
20102
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
20103
+ invert: boolean().optional()
20104
+ });
20105
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
20106
+ var NcPlateMatcherSchema = object({
20107
+ values: array(string().min(1)).min(1),
20108
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
20109
+ maxDistance: number().int().min(0).max(3).default(1)
20110
+ });
20111
+ /**
20112
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
20113
+ * occupancy edge for a device — optionally narrowed to a single admin
20114
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
20115
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
20116
+ * - `became-free` — count crossed ≥ `count` → below it
20117
+ * - `>=` / `<=` — count is at/over or at/under `count`
20118
+ * `sustainSeconds` requires the condition hold continuously that long
20119
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
20120
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
20121
+ * the condition never matches. Confirmed edge-state survives addon restarts
20122
+ * (declared SQLite collection, reseeded on boot).
20123
+ */
20124
+ var NcOccupancyConditionSchema = object({
20125
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
20126
+ zoneId: string().optional(),
20127
+ /** Object class to count; absent = any class. */
20128
+ className: string().optional(),
20129
+ op: _enum([
20130
+ "became-occupied",
20131
+ "became-free",
20132
+ ">=",
20133
+ "<="
20134
+ ]).default("became-occupied"),
20135
+ count: number().int().min(0).default(1),
20136
+ sustainSeconds: number().int().min(0).max(3600).default(15)
20137
+ });
20138
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
20139
+ var NcZoneConditionSchema = object({
20140
+ ids: array(string().min(1)).min(1),
20141
+ /** Quantifier over `ids` — at least one / every one visited. */
20142
+ match: _enum(["any", "all"]).default("any")
20143
+ });
20144
+ /**
20145
+ * The P1 condition set — a flat AND of groups; absent group = pass;
20146
+ * membership lists are OR within the list (spec §2.3).
20147
+ */
20148
+ var NcConditionsSchema = object({
20149
+ /** Device scope — absent = all devices. */
20150
+ devices: array(number()).optional(),
20151
+ /** Detector class names (any overlap with the record's class set). */
20152
+ classes: array(string().min(1)).optional(),
20153
+ /** Veto classes — any overlap fails the rule. */
20154
+ classesExclude: array(string().min(1)).optional(),
20155
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
20156
+ minConfidence: number().min(0).max(1).optional(),
20157
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
20158
+ zones: NcZoneConditionSchema.optional(),
20159
+ /** Veto zones — any hit fails the rule. */
20160
+ zonesExclude: array(string().min(1)).optional(),
20161
+ /**
20162
+ * Exact (case-insensitive) match on the record's collapsed `label`
20163
+ * (identity name / plate text / subclass).
20164
+ */
20165
+ labelEquals: array(string().min(1)).optional(),
20166
+ /**
20167
+ * Identity matcher. P1 boundary: matched against the record's collapsed
20168
+ * `label` (the identity display name propagated by the face pipeline) —
20169
+ * identity-ID matching rides in P2 when identity ids reach the record.
20170
+ */
20171
+ identities: array(string().min(1)).optional(),
20172
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
20173
+ plates: NcPlateMatcherSchema.optional(),
20174
+ /**
20175
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
20176
+ * Same P1 boundary: matched against the record's collapsed `label` (the
20177
+ * identity display name). A record with NO label passes (nothing to
20178
+ * exclude), unlike the include variant which fails on an absent label.
20179
+ */
20180
+ identitiesExclude: array(string().min(1)).optional(),
20181
+ /**
20182
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
20183
+ * TRACK-END only: importance is scored at track close, so it does not exist
20184
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
20185
+ * close the value is threaded via the close-time info (the `Track` clone is
20186
+ * captured before the DB row is updated, so it would otherwise read stale).
20187
+ * Fails when the record carries no importance (never guess quality — the
20188
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
20189
+ */
20190
+ minImportance: number().min(0).max(1).optional(),
20191
+ /**
20192
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
20193
+ * TRACK-END only: an `immediate` / object-event subject has no closed
20194
+ * lifespan, so a dwell condition never matches immediate delivery
20195
+ * (documented choice — the object-event record carries no `firstSeen`,
20196
+ * so dwell cannot be computed from what the subject actually carries).
20197
+ */
20198
+ minDwellSeconds: number().min(0).optional(),
20199
+ /**
20200
+ * Detection provenance filter. `any` (default / absent) matches every
20201
+ * source; otherwise the subject's source must equal it. Legacy records
20202
+ * with no stamped source are treated as `pipeline`. The union spans both
20203
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
20204
+ * tracks carry `sensor`.
20205
+ */
20206
+ source: _enum([
20207
+ "pipeline",
20208
+ "onboard",
20209
+ "sensor",
20210
+ "any"
20211
+ ]).optional(),
20212
+ /**
20213
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
20214
+ * detector `minConfidence` (that gates the object-detection score; this
20215
+ * gates the recognition/OCR match score). Fails when the subject carries
20216
+ * no label-match confidence (never guess). TRACK-END only: the confidence
20217
+ * lives on the recognition result and reaches the subject at track close.
20218
+ *
20219
+ * What it measures precisely (plumbed at track close — the closer threads
20220
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
20221
+ * `importance`): the BEST recognition match confidence observed for the
20222
+ * label the track carries at close — for a face, the peak cosine similarity
20223
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
20224
+ * for a plate, the peak OCR read score of the best-held plate
20225
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
20226
+ * one track the higher of the two is used. A track that ended with no
20227
+ * confident identity/plate match carries no value, so the condition fails
20228
+ * closed for it (an un-recognized subject).
20229
+ */
20230
+ minLabelConfidence: number().min(0).max(1).optional(),
20231
+ /**
20232
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
20233
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
20234
+ * against the token carried on the device-event subject (extracted from the
20235
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
20236
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
20237
+ * eventType, so gate those with {@link sensorKinds} instead.
20238
+ */
20239
+ eventTypeTokens: array(string().min(1)).optional(),
20240
+ /**
20241
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
20242
+ * `contact`, `button`, `device-event`) — matched against the persisted
20243
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
20244
+ */
20245
+ sensorKinds: array(string().min(1)).optional(),
20246
+ /**
20247
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
20248
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
20249
+ * when the subject's phase does not match (a subject always carries a phase
20250
+ * on the package-event trigger).
20251
+ */
20252
+ packagePhase: _enum([
20253
+ "delivered",
20254
+ "picked-up",
20255
+ "both"
20256
+ ]).optional(),
20257
+ /**
20258
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
20259
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
20260
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
20261
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
20262
+ */
20263
+ customZones: array(MaskPolygonShapeSchema).optional(),
20264
+ /**
20265
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
20266
+ * (optionally zone/class-scoped) occupancy count crosses the configured
20267
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
20268
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
20269
+ */
20270
+ occupancy: NcOccupancyConditionSchema.optional()
20271
+ });
20272
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
20273
+ var NcRuleTargetSchema = object({
20274
+ /** `notification-output` Target id. */
20275
+ targetId: string().min(1),
20276
+ /**
20277
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
20278
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
20279
+ * degrade engine drops what the backend can't render.
20280
+ */
20281
+ params: record(string(), unknown()).optional()
20282
+ });
20283
+ /**
20284
+ * Media attachment policy (P1 still-image subset).
20285
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
20286
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
20287
+ * matched on identities attaches the subject's `faceCrop`, one matched on
20288
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
20289
+ * (or when the specific crop is missing) degrades to `best`, then
20290
+ * `keyFrame`, then no attachment — never delaying the send. The matched
20291
+ * condition summary is frozen on the outbox row at enqueue (like the rule
20292
+ * name), so the choice never drifts from the record that fired it.
20293
+ * - `keyFrame` — the clean scene frame (no subject box).
20294
+ * - `none` — no attachment.
20295
+ */
20296
+ var NcMediaPolicySchema = object({ attach: _enum([
20297
+ "best",
20298
+ "best-matching",
20299
+ "keyFrame",
20300
+ "none"
20301
+ ]).default("best") });
20302
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
20303
+ var NcThrottleSchema = object({
20304
+ cooldownSec: number().int().min(0).max(86400).default(60),
20305
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
20306
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
20307
+ });
20308
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
20309
+ var NcRuleInputSchema = object({
20310
+ name: string().min(1).max(200),
20311
+ enabled: boolean().default(true),
20312
+ delivery: NcDeliverySchema,
20313
+ conditions: NcConditionsSchema.default({}),
20314
+ schedule: NcScheduleSchema.optional(),
20315
+ targets: array(NcRuleTargetSchema).min(1),
20316
+ media: NcMediaPolicySchema.default({ attach: "best" }),
20317
+ throttle: NcThrottleSchema.default({
20318
+ cooldownSec: 60,
20319
+ scope: "rule-device"
20320
+ }),
20321
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
20322
+ template: object({
20323
+ title: string().max(500).optional(),
20324
+ body: string().max(2e3).optional()
20325
+ }).optional(),
20326
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
20327
+ priority: number().int().min(1).max(5).default(3),
20328
+ /**
20329
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
20330
+ * behaviour, visible to all, read-only in the viewer). Present = personal
20331
+ * rule owned by this userId. Server-stamped; never trusted from a client.
20332
+ */
20333
+ ownerUserId: string().optional()
20334
+ });
20335
+ /**
20336
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
20337
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
20338
+ * NOT a client-authored input field (it lives on the persisted rule, not the
20339
+ * input), so it is added here explicitly to let the store's per-target opt-out
20340
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
20341
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
20342
+ * `updateRule` patch.
20343
+ */
20344
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
20345
+ /** A persisted rule. */
20346
+ var NcRuleSchema = NcRuleInputSchema.extend({
20347
+ id: string(),
20348
+ /** userId of the admin who created the rule (server-stamped caller). */
20349
+ createdBy: string(),
20350
+ createdAt: number(),
20351
+ updatedAt: number(),
20352
+ /**
20353
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
20354
+ * send time. Only a target's OWNER may add/remove its id (server-checked
20355
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
20356
+ */
20357
+ disabledTargetIds: array(string()).default([])
20358
+ });
20359
+ var NcTestResultSchema = object({
20360
+ recordId: string(),
20361
+ recordKind: _enum([
20362
+ "object-event",
20363
+ "track",
20364
+ "device-event",
20365
+ "package-event"
20366
+ ]),
20367
+ deviceId: number(),
20368
+ timestamp: number(),
20369
+ wouldFire: boolean(),
20370
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
20371
+ failedCondition: string().optional(),
20372
+ className: string().optional(),
20373
+ label: string().optional()
20374
+ });
20375
+ var NcConditionDescriptorSchema = object({
20376
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
19960
20377
  id: string(),
20378
+ group: _enum([
20379
+ "scope",
20380
+ "class",
20381
+ "zones",
20382
+ "quality",
20383
+ "label",
20384
+ "schedule",
20385
+ "device",
20386
+ "package",
20387
+ "occupancy"
20388
+ ]),
19961
20389
  label: string(),
19962
- family: string(),
19963
- purpose: _enum(["text", "vision"]),
19964
- url: string(),
19965
- sha256: string(),
19966
- sizeBytes: number(),
19967
- quantization: string(),
19968
- /** Load-time guidance shown in the picker. */
19969
- minRamBytes: number(),
19970
- contextSizeDefault: number().int(),
19971
- /** Vision models: companion projector file. */
19972
- mmprojUrl: string().optional()
20390
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
20391
+ valueType: _enum([
20392
+ "deviceIdList",
20393
+ "stringList",
20394
+ "number01",
20395
+ "number",
20396
+ "sourceSelect",
20397
+ "zoneSelection",
20398
+ "zoneIdList",
20399
+ "schedule",
20400
+ "plateMatcher",
20401
+ "packagePhase",
20402
+ "polygonDraw",
20403
+ "occupancy"
20404
+ ]),
20405
+ operator: _enum([
20406
+ "in",
20407
+ "notIn",
20408
+ "anyOf",
20409
+ "allOf",
20410
+ "gte",
20411
+ "fuzzyIn",
20412
+ "withinSchedule"
20413
+ ]),
20414
+ /** Which delivery kinds the condition applies to. */
20415
+ appliesTo: array(NcDeliverySchema),
20416
+ phase: string(),
20417
+ description: string().optional()
19973
20418
  });
19974
- var LlmRuntimeNodeSchema = object({
19975
- nodeId: string(),
19976
- reachable: boolean(),
19977
- status: LlmRuntimeStatusSchema.optional(),
19978
- disk: LlmRuntimeDiskUsageSchema.optional(),
19979
- error: string().optional()
20419
+ /**
20420
+ * The delivery lifecycle status of a history row — a straight read of the
20421
+ * durable outbox row's own status (single source of truth):
20422
+ * - `pending` — enqueued, in-flight or retrying with backoff
20423
+ * - `sent` — delivered (terminal)
20424
+ * - `dead` — dead-lettered after exhausting retries / a permanent
20425
+ * backend rejection / a deleted target (terminal; carries
20426
+ * the failure `error`)
20427
+ *
20428
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
20429
+ * user dimension (quiet hours / snooze) and are additive when they land.
20430
+ */
20431
+ var NcHistoryStatusSchema = _enum([
20432
+ "pending",
20433
+ "sent",
20434
+ "dead"
20435
+ ]);
20436
+ /** The evaluated record kind a history row descends from (one per trigger). */
20437
+ var NcHistoryRecordKindSchema = _enum([
20438
+ "object-event",
20439
+ "track-end",
20440
+ "device-event",
20441
+ "package-event"
20442
+ ]);
20443
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
20444
+ var NcHistorySubjectSchema = object({
20445
+ className: string(),
20446
+ label: string().optional(),
20447
+ confidence: number().optional(),
20448
+ zones: array(string()),
20449
+ timestamp: number()
20450
+ });
20451
+ /**
20452
+ * One delivery-history row. This is a read-only VIEW over the durable
20453
+ * outbox row (single source of truth — the same row the drain loop drives;
20454
+ * NO second write path, so history can never drift from delivery state).
20455
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
20456
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
20457
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
20458
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
20459
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
20460
+ * P1 (admin scope only).
20461
+ */
20462
+ var NcHistoryEntrySchema = object({
20463
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
20464
+ id: string(),
20465
+ ruleId: string(),
20466
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
20467
+ ruleName: string(),
20468
+ /** The rule urgency/trigger that produced this delivery. */
20469
+ delivery: NcDeliverySchema,
20470
+ targetId: string(),
20471
+ deviceId: number(),
20472
+ recordKind: NcHistoryRecordKindSchema,
20473
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
20474
+ recordId: string(),
20475
+ /** Present for track-scoped deliveries (object-event / track-end). */
20476
+ trackId: string().optional(),
20477
+ status: NcHistoryStatusSchema,
20478
+ /** Delivery attempts made so far. */
20479
+ attempts: number().int(),
20480
+ /** Fire time (outbox enqueue). */
20481
+ createdAt: number(),
20482
+ /** Last transition time (terminal for sent / dead). */
20483
+ updatedAt: number(),
20484
+ /** Failure detail — present on a `dead` row. */
20485
+ error: string().optional(),
20486
+ subject: NcHistorySubjectSchema
19980
20487
  });
19981
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
19982
- var ProfileRefInputSchema = object({
19983
- addonId: string(),
19984
- profileId: string()
20488
+ /**
20489
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
20490
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
20491
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
20492
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
20493
+ */
20494
+ var NcHistoryFilterSchema = object({
20495
+ ruleId: string().optional(),
20496
+ deviceId: number().optional(),
20497
+ status: NcHistoryStatusSchema.optional(),
20498
+ since: number().optional(),
20499
+ until: number().optional(),
20500
+ limit: number().int().min(1).max(500).default(100)
19985
20501
  });
19986
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
19987
- kind: "mutation",
19988
- auth: "admin"
19989
- }), method(ProfileRefInputSchema, _void(), {
20502
+ 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 }), {
19990
20503
  kind: "mutation",
19991
- auth: "admin"
19992
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
20504
+ auth: "admin",
20505
+ caller: "required"
20506
+ }), method(object({
20507
+ ruleId: string(),
20508
+ patch: NcRulePatchSchema
20509
+ }), object({ rule: NcRuleSchema }), {
19993
20510
  kind: "mutation",
19994
- auth: "admin"
19995
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
19996
- selector: LlmDefaultSelectorSchema,
19997
- profileId: string().nullable()
19998
- }), _void(), {
20511
+ auth: "admin",
20512
+ caller: "required"
20513
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
19999
20514
  kind: "mutation",
20000
20515
  auth: "admin"
20001
20516
  }), method(object({
20002
- since: number().optional(),
20003
- until: number().optional(),
20004
- consumer: string().optional(),
20005
- profileId: string().optional()
20006
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
20007
- nodeId: string(),
20008
- model: ManagedModelRefSchema
20009
- }), _void(), {
20517
+ ruleId: string(),
20518
+ enabled: boolean()
20519
+ }), object({ success: literal(true) }), {
20010
20520
  kind: "mutation",
20011
20521
  auth: "admin"
20012
20522
  }), method(object({
20013
- nodeId: string(),
20014
- file: string()
20015
- }), _void(), {
20016
- kind: "mutation",
20017
- auth: "admin"
20018
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
20019
- kind: "mutation",
20020
- auth: "admin"
20021
- }), method(ProfileRefInputSchema, _void(), {
20523
+ rule: NcRuleInputSchema,
20524
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
20525
+ }), object({ results: array(NcTestResultSchema) }), {
20022
20526
  kind: "mutation",
20023
20527
  auth: "admin"
20024
- });
20528
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
20025
20529
  /**
20026
20530
  * Zod schemas for persisted record types.
20027
20531
  *
@@ -20707,7 +21211,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
20707
21211
  }), method(object({
20708
21212
  eventId: string(),
20709
21213
  kind: MediaFileKindEnum.optional()
20710
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
21214
+ }), array(MediaFileSchema).readonly()), method(object({
21215
+ trackId: string(),
21216
+ kinds: array(MediaFileKindEnum).optional()
21217
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
20711
21218
  deviceId: number(),
20712
21219
  timestamp: number(),
20713
21220
  frameWidth: number(),
@@ -20728,76 +21235,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
20728
21235
  eventId: string(),
20729
21236
  timestamp: number()
20730
21237
  });
20731
- /**
20732
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
20733
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
20734
- * caps into per-camera event-kind descriptors.
20735
- *
20736
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
20737
- * is NOT duplicated here — every entry is derived from the single
20738
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
20739
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
20740
- * control cap means adding one line here (and a taxonomy entry); the anti-
20741
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
20742
- * eventful cap is missing.
20743
- */
20744
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
20745
- var LEGACY_ICON = {
20746
- motion: "motion",
20747
- audio: "audio",
20748
- person: "person",
20749
- vehicle: "vehicle",
20750
- animal: "animal",
20751
- package: "package",
20752
- door: "door",
20753
- pir: "pir",
20754
- smoke: "smoke",
20755
- water: "water",
20756
- button: "button",
20757
- generic: "generic",
20758
- gas: "smoke",
20759
- vibration: "generic",
20760
- tamper: "generic",
20761
- presence: "person",
20762
- lock: "generic",
20763
- siren: "generic",
20764
- switch: "generic",
20765
- doorbell: "button"
20766
- };
20767
- function legacyIcon(iconId) {
20768
- return LEGACY_ICON[iconId] ?? "generic";
20769
- }
20770
- /**
20771
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
20772
- * The anti-drift guard cross-checks this against the eventful caps declared
20773
- * in `packages/types/src/capabilities/*.cap.ts`.
20774
- */
20775
- var CAP_TO_KIND = {
20776
- contact: "contact",
20777
- motion: "motion-sensor",
20778
- smoke: "smoke",
20779
- flood: "flood",
20780
- gas: "gas",
20781
- "carbon-monoxide": "carbon-monoxide",
20782
- vibration: "vibration",
20783
- tamper: "tamper",
20784
- presence: "presence",
20785
- "enum-sensor": "enum-sensor",
20786
- "event-emitter": "device-event",
20787
- "lock-control": "lock",
20788
- switch: "switch",
20789
- button: "button",
20790
- doorbell: "doorbell"
20791
- };
20792
- function buildDescriptor(capName, kind) {
20793
- const t = EVENT_TAXONOMY[kind];
20794
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
20795
- return {
20796
- ...t,
20797
- icon: legacyIcon(t.iconId)
20798
- };
20799
- }
20800
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
20801
21238
  var CameraPipelineConfigSchema = object({
20802
21239
  engine: PipelineEngineChoiceSchema.optional(),
20803
21240
  steps: array(PipelineStepInputSchema).readonly(),
@@ -21283,6 +21720,76 @@ method(object({
21283
21720
  auth: "admin"
21284
21721
  });
21285
21722
  /**
21723
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
21724
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
21725
+ * caps into per-camera event-kind descriptors.
21726
+ *
21727
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
21728
+ * is NOT duplicated here — every entry is derived from the single
21729
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
21730
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
21731
+ * control cap means adding one line here (and a taxonomy entry); the anti-
21732
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
21733
+ * eventful cap is missing.
21734
+ */
21735
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
21736
+ var LEGACY_ICON = {
21737
+ motion: "motion",
21738
+ audio: "audio",
21739
+ person: "person",
21740
+ vehicle: "vehicle",
21741
+ animal: "animal",
21742
+ package: "package",
21743
+ door: "door",
21744
+ pir: "pir",
21745
+ smoke: "smoke",
21746
+ water: "water",
21747
+ button: "button",
21748
+ generic: "generic",
21749
+ gas: "smoke",
21750
+ vibration: "generic",
21751
+ tamper: "generic",
21752
+ presence: "person",
21753
+ lock: "generic",
21754
+ siren: "generic",
21755
+ switch: "generic",
21756
+ doorbell: "button"
21757
+ };
21758
+ function legacyIcon(iconId) {
21759
+ return LEGACY_ICON[iconId] ?? "generic";
21760
+ }
21761
+ /**
21762
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
21763
+ * The anti-drift guard cross-checks this against the eventful caps declared
21764
+ * in `packages/types/src/capabilities/*.cap.ts`.
21765
+ */
21766
+ var CAP_TO_KIND = {
21767
+ contact: "contact",
21768
+ motion: "motion-sensor",
21769
+ smoke: "smoke",
21770
+ flood: "flood",
21771
+ gas: "gas",
21772
+ "carbon-monoxide": "carbon-monoxide",
21773
+ vibration: "vibration",
21774
+ tamper: "tamper",
21775
+ presence: "presence",
21776
+ "enum-sensor": "enum-sensor",
21777
+ "event-emitter": "device-event",
21778
+ "lock-control": "lock",
21779
+ switch: "switch",
21780
+ button: "button",
21781
+ doorbell: "doorbell"
21782
+ };
21783
+ function buildDescriptor(capName, kind) {
21784
+ const t = EVENT_TAXONOMY[kind];
21785
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
21786
+ return {
21787
+ ...t,
21788
+ icon: legacyIcon(t.iconId)
21789
+ };
21790
+ }
21791
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
21792
+ /**
21286
21793
  * server-management — per-NODE singleton capability for a node's ROOT
21287
21794
  * package lifecycle (runtime-updatable node packages).
21288
21795
  *
@@ -22737,7 +23244,28 @@ var FaceInfoSchema = object({
22737
23244
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
22738
23245
  * track produced no key frame (e.g. native/onboard source) — the UI falls
22739
23246
  * back to the inline `base64` face crop. */
22740
- keyFrameMediaKey: string().optional()
23247
+ keyFrameMediaKey: string().optional(),
23248
+ /** Winning identity-match cosine (0..1) for this face's track, when an
23249
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
23250
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
23251
+ * faces that were never auto-recognized. */
23252
+ bestMatchScore: number().optional(),
23253
+ /** Native-scale face short side (px) at recognition time, when the runner
23254
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
23255
+ * legacy rows / runners that reported no native measure. */
23256
+ nativeFaceShortSidePx: number().optional(),
23257
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
23258
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
23259
+ * but blocked only by the recognition size floor). Mutually exclusive with
23260
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
23261
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
23262
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
23263
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
23264
+ suggestedIdentityId: string().optional(),
23265
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
23266
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
23267
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
23268
+ suggestedMatchScore: number().optional()
22741
23269
  });
22742
23270
  var FaceFilterEnum = _enum([
22743
23271
  "unassigned",
@@ -24780,36 +25308,6 @@ Object.freeze({
24780
25308
  addonId: null,
24781
25309
  access: "view"
24782
25310
  },
24783
- "advancedNotifier.deleteRule": {
24784
- capName: "advanced-notifier",
24785
- capScope: "system",
24786
- addonId: null,
24787
- access: "delete"
24788
- },
24789
- "advancedNotifier.getHistory": {
24790
- capName: "advanced-notifier",
24791
- capScope: "system",
24792
- addonId: null,
24793
- access: "view"
24794
- },
24795
- "advancedNotifier.getRules": {
24796
- capName: "advanced-notifier",
24797
- capScope: "system",
24798
- addonId: null,
24799
- access: "view"
24800
- },
24801
- "advancedNotifier.testRule": {
24802
- capName: "advanced-notifier",
24803
- capScope: "system",
24804
- addonId: null,
24805
- access: "create"
24806
- },
24807
- "advancedNotifier.upsertRule": {
24808
- capName: "advanced-notifier",
24809
- capScope: "system",
24810
- addonId: null,
24811
- access: "create"
24812
- },
24813
25311
  "alarmPanel.arm": {
24814
25312
  capName: "alarm-panel",
24815
25313
  capScope: "device",
@@ -27114,6 +27612,60 @@ Object.freeze({
27114
27612
  addonId: null,
27115
27613
  access: "create"
27116
27614
  },
27615
+ "notificationRules.createRule": {
27616
+ capName: "notification-rules",
27617
+ capScope: "system",
27618
+ addonId: null,
27619
+ access: "create"
27620
+ },
27621
+ "notificationRules.deleteRule": {
27622
+ capName: "notification-rules",
27623
+ capScope: "system",
27624
+ addonId: null,
27625
+ access: "delete"
27626
+ },
27627
+ "notificationRules.getConditionCatalog": {
27628
+ capName: "notification-rules",
27629
+ capScope: "system",
27630
+ addonId: null,
27631
+ access: "view"
27632
+ },
27633
+ "notificationRules.getHistory": {
27634
+ capName: "notification-rules",
27635
+ capScope: "system",
27636
+ addonId: null,
27637
+ access: "view"
27638
+ },
27639
+ "notificationRules.getRule": {
27640
+ capName: "notification-rules",
27641
+ capScope: "system",
27642
+ addonId: null,
27643
+ access: "view"
27644
+ },
27645
+ "notificationRules.listRules": {
27646
+ capName: "notification-rules",
27647
+ capScope: "system",
27648
+ addonId: null,
27649
+ access: "view"
27650
+ },
27651
+ "notificationRules.setRuleEnabled": {
27652
+ capName: "notification-rules",
27653
+ capScope: "system",
27654
+ addonId: null,
27655
+ access: "create"
27656
+ },
27657
+ "notificationRules.testRule": {
27658
+ capName: "notification-rules",
27659
+ capScope: "system",
27660
+ addonId: null,
27661
+ access: "create"
27662
+ },
27663
+ "notificationRules.updateRule": {
27664
+ capName: "notification-rules",
27665
+ capScope: "system",
27666
+ addonId: null,
27667
+ access: "create"
27668
+ },
27117
27669
  "notifier.cancel": {
27118
27670
  capName: "notifier",
27119
27671
  capScope: "device",