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