@camstack/addon-model-studio 1.1.3 → 1.1.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.
@@ -4665,7 +4665,7 @@ var ZodIssueCode = {
4665
4665
  var ZodFirstPartyTypeKind;
4666
4666
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
4667
4667
  //#endregion
4668
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
4668
+ //#region ../types/dist/event-category-BLcNejAE.mjs
4669
4669
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
4670
4670
  EventCategory["SystemBoot"] = "system.boot";
4671
4671
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -4815,9 +4815,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
4815
4815
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
4816
4816
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
4817
4817
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
4818
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
4819
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
4820
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
4821
4818
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
4822
4819
  * progress bar the client reconciles via `recordingExport.getExport`. */
4823
4820
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6826,7 +6823,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6826
6823
  patch: record(string(), unknown())
6827
6824
  }), object({ success: literal(true) });
6828
6825
  object({ deviceId: number() }), unknown().nullable();
6829
- /** Shorthand to define a method schema */
6830
6826
  function method(input, output, options) {
6831
6827
  return {
6832
6828
  input,
@@ -6834,6 +6830,7 @@ function method(input, output, options) {
6834
6830
  kind: options?.kind ?? "query",
6835
6831
  auth: options?.auth ?? "protected",
6836
6832
  ...options?.access !== void 0 ? { access: options.access } : {},
6833
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6837
6834
  timeoutMs: options?.timeoutMs
6838
6835
  };
6839
6836
  }
@@ -8218,6 +8215,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8218
8215
  /** The complete taxonomy dictionary, keyed by kind. */
8219
8216
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8220
8217
  /**
8218
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8219
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8220
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8221
+ * taxonomy surface (timeline, filters, event page).
8222
+ *
8223
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8224
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8225
+ * for the `classes` / `classesExclude` conditions.
8226
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8227
+ * the same class picker, grouped under an Audio header.
8228
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8229
+ * lock / …) for the `sensorKinds` device-event condition.
8230
+ *
8231
+ * Each entry carries `parentKind` so the client can group video subs under
8232
+ * their macro and sensor/control kinds under their category. This surface is
8233
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8234
+ * method, no codegen — so it ships train-free with an addon deploy.
8235
+ */
8236
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8237
+ var NcTaxonomyEntrySchema = object({
8238
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8239
+ kind: string(),
8240
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8241
+ label: string(),
8242
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8243
+ parentKind: string().nullable()
8244
+ });
8245
+ object({
8246
+ videoClasses: array(NcTaxonomyEntrySchema),
8247
+ audioKinds: array(NcTaxonomyEntrySchema),
8248
+ labels: array(NcTaxonomyEntrySchema)
8249
+ });
8250
+ function toEntry(kind, label, parentKind) {
8251
+ return {
8252
+ kind,
8253
+ label,
8254
+ parentKind
8255
+ };
8256
+ }
8257
+ /**
8258
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8259
+ * (macros before their subs), which the client relies on for stable grouping.
8260
+ */
8261
+ function buildNcTaxonomy() {
8262
+ const all = Object.values(EVENT_TAXONOMY);
8263
+ return {
8264
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8265
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8266
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8267
+ };
8268
+ }
8269
+ Object.freeze(buildNcTaxonomy());
8270
+ /**
8221
8271
  * Error types for the safe expression engine. Two distinct classes so callers
8222
8272
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8223
8273
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -10926,6 +10976,22 @@ var CameraMetricsSchema = object({
10926
10976
  ])
10927
10977
  });
10928
10978
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
10979
+ /**
10980
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
10981
+ * within the frame, so the executor can re-cut a leaf child ROI at native
10982
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
10983
+ */
10984
+ var NativeCropRefSchema = object({
10985
+ /** Handle keying the retained native surface (node-pinned to its owner). */
10986
+ handle: FrameHandleSchema,
10987
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
10988
+ cropFrameSpace: object({
10989
+ x: number(),
10990
+ y: number(),
10991
+ w: number(),
10992
+ h: number()
10993
+ })
10994
+ });
10929
10995
  var ModelFormatSchema$1 = _enum([
10930
10996
  "onnx",
10931
10997
  "coreml",
@@ -11201,7 +11267,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
11201
11267
  * Omitted ⇒ the runner's default device (current single-engine
11202
11268
  * behaviour). Selects WHICH device pool of the node runs the call.
11203
11269
  */
11204
- deviceKey: string().optional()
11270
+ deviceKey: string().optional(),
11271
+ /**
11272
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
11273
+ * when the parent crop was resolved from the frame's retained NATIVE
11274
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
11275
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
11276
+ * resolution from that surface — the SAME quality path faces already
11277
+ * had — instead of the downscaled parent tile. `handle` keys the native
11278
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
11279
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
11280
+ * the executor's crop-normalized child ROI back into frame-normalized
11281
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
11282
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
11283
+ * (today's behaviour on the fallback path).
11284
+ */
11285
+ nativeCropRef: NativeCropRefSchema.optional()
11205
11286
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
11206
11287
  engine: PipelineEngineChoiceSchema.optional(),
11207
11288
  steps: array(PipelineStepInputSchema).min(1),
@@ -11417,7 +11498,11 @@ var DetailResultSchema = object({
11417
11498
  bbox: NativeCropBboxSchema.optional(),
11418
11499
  embedding: string().optional(),
11419
11500
  label: string().optional(),
11420
- alignedCropJpeg: string().optional()
11501
+ alignedCropJpeg: string().optional(),
11502
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
11503
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
11504
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
11505
+ nativeFaceShortSidePx: number().optional()
11421
11506
  });
11422
11507
  /**
11423
11508
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -11431,6 +11516,12 @@ var motionCooldownMsField = {
11431
11516
  default: 3e4,
11432
11517
  step: 500
11433
11518
  };
11519
+ var maxSessionHoldMsField = {
11520
+ min: 0,
11521
+ max: 6e5,
11522
+ default: 12e4,
11523
+ step: 5e3
11524
+ };
11434
11525
  var motionFpsField = {
11435
11526
  min: 1,
11436
11527
  max: 30,
@@ -11578,6 +11669,19 @@ var RunnerCameraConfigSchema = object({
11578
11669
  "on-motion"
11579
11670
  ]).default("always-on"),
11580
11671
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
11672
+ /**
11673
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
11674
+ * detection session is active and ≥1 confirmed non-stationary track is
11675
+ * still live, the orchestrator keeps the session open past
11676
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
11677
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
11678
+ * ms since the session opened, after which it closes regardless. `0`
11679
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
11680
+ * runner itself — carried here so it shares the per-camera device-settings
11681
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
11682
+ * resolved `CameraDetectionConfig`.
11683
+ */
11684
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
11581
11685
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
11582
11686
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
11583
11687
  motionStreamId: string(),
@@ -11667,7 +11771,7 @@ var RunnerCameraConfigSchema = object({
11667
11771
  */
11668
11772
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
11669
11773
  });
11670
- 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;
11774
+ 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;
11671
11775
  /**
11672
11776
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
11673
11777
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -13527,94 +13631,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
13527
13631
  bundleUrl: string()
13528
13632
  });
13529
13633
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
13530
- var NotificationRuleConditionsSchema = object({
13531
- deviceIds: array(number()).readonly().optional(),
13532
- classNames: array(string()).readonly().optional(),
13533
- zoneIds: array(string()).readonly().optional(),
13534
- minConfidence: number().optional(),
13535
- source: _enum([
13536
- "pipeline",
13537
- "onboard",
13538
- "any"
13539
- ]).optional(),
13540
- schedule: object({
13541
- days: array(number()).readonly(),
13542
- startHour: number(),
13543
- endHour: number()
13544
- }).optional(),
13545
- cooldownSeconds: number().optional(),
13546
- minDwellSeconds: number().optional(),
13547
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
13548
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
13549
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
13550
- eventTypeTokens: array(string()).readonly().optional(),
13551
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
13552
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
13553
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
13554
- clipDescription: object({
13555
- text: string().min(1),
13556
- minSimilarity: number().min(0).max(1)
13557
- }).optional(),
13558
- /** Match events whose recognized-entity label (face identity name or plate
13559
- * vehicle name, propagated onto `event.data.label`) is one of these values.
13560
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
13561
- * vehicle/person> is seen". */
13562
- labels: array(string()).readonly().optional()
13563
- });
13564
- var NotificationRuleTemplateSchema = object({
13565
- title: string(),
13566
- body: string(),
13567
- imageMode: _enum([
13568
- "crop",
13569
- "annotated",
13570
- "full",
13571
- "none"
13572
- ])
13573
- });
13574
- var NotificationRuleSchema = object({
13575
- id: string(),
13576
- name: string(),
13577
- enabled: boolean(),
13578
- eventTypes: array(string()).readonly(),
13579
- conditions: NotificationRuleConditionsSchema,
13580
- outputs: array(string()).readonly(),
13581
- template: NotificationRuleTemplateSchema.optional(),
13582
- priority: _enum([
13583
- "low",
13584
- "normal",
13585
- "high",
13586
- "critical"
13587
- ])
13588
- });
13589
- var NotificationTestResultSchema = object({
13590
- ruleId: string(),
13591
- eventId: string(),
13592
- timestamp: number(),
13593
- wouldFire: boolean(),
13594
- reason: string().optional()
13595
- });
13596
- var NotificationHistoryEntrySchema = object({
13597
- id: string(),
13598
- ruleId: string(),
13599
- ruleName: string(),
13600
- eventId: string(),
13601
- timestamp: number(),
13602
- outputs: array(string()).readonly(),
13603
- success: boolean(),
13604
- error: string().optional(),
13605
- deviceId: number().optional()
13606
- });
13607
- var NotificationHistoryFilterSchema = object({
13608
- ruleId: string().optional(),
13609
- deviceId: number().optional(),
13610
- from: number().optional(),
13611
- to: number().optional(),
13612
- limit: number().optional()
13613
- });
13614
- 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({
13615
- ruleId: string(),
13616
- lookbackMinutes: number()
13617
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
13618
13634
  /**
13619
13635
  * Alerts capability — collection-based internal alert system.
13620
13636
  *
@@ -13801,89 +13817,6 @@ method(object({
13801
13817
  password: string()
13802
13818
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
13803
13819
  /**
13804
- * `login-method` — collection cap through which auth addons contribute
13805
- * their pre-auth login surfaces to the login page. This is the SINGLE,
13806
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
13807
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
13808
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
13809
- * procedure aggregates them for the unauthenticated login page.
13810
- *
13811
- * A contribution is a discriminated union on `kind`:
13812
- *
13813
- * - `redirect` — a declarative button. The login page renders a generic
13814
- * button that navigates to `startUrl` (an addon-owned HTTP route).
13815
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
13816
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
13817
- * login page needs NO change.
13818
- *
13819
- * - `widget` — a Module-Federation widget the login page mounts (via
13820
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
13821
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
13822
- * mechanism kept for future use; no shipped addon uses it on the login
13823
- * page (the passkey ceremony below runs natively in the shell instead).
13824
- *
13825
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
13826
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
13827
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
13828
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
13829
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
13830
- * fetching any remote code pre-auth. Contribution stays unconditional —
13831
- * enrollment state is never leaked pre-auth; visibility is a shell
13832
- * decision.
13833
- *
13834
- * Every contribution carries a `stage`:
13835
- * - `primary` — shown on the first credentials screen (OIDC /
13836
- * magic-link buttons; a future usernameless passkey).
13837
- * - `second-factor` — shown AFTER the password leg, gated on the
13838
- * returned `factors` (passkey-as-2FA today).
13839
- *
13840
- * `mount: skip` — the cap is read server-side by the core auth router
13841
- * (`registry.getCollection('login-method')`), never mounted as its own
13842
- * tRPC router.
13843
- */
13844
- /** When a login method renders in the two-phase login flow. */
13845
- var LoginStageEnum = _enum(["primary", "second-factor"]);
13846
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
13847
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
13848
- object({
13849
- kind: literal("redirect"),
13850
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
13851
- id: string(),
13852
- /** Operator-facing button label. */
13853
- label: string(),
13854
- /** lucide-react icon name. */
13855
- icon: string().optional(),
13856
- /** Addon-owned HTTP route the button navigates to (GET). */
13857
- startUrl: string(),
13858
- stage: LoginStageEnum
13859
- }),
13860
- object({
13861
- kind: literal("widget"),
13862
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
13863
- id: string(),
13864
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
13865
- addonId: string(),
13866
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
13867
- bundle: string(),
13868
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
13869
- remote: WidgetRemoteSchema,
13870
- stage: LoginStageEnum
13871
- }),
13872
- object({
13873
- kind: literal("passkey"),
13874
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
13875
- id: string(),
13876
- /** Operator-facing button label. */
13877
- label: string(),
13878
- stage: LoginStageEnum,
13879
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
13880
- rpId: string(),
13881
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
13882
- origin: string().nullable()
13883
- })
13884
- ]);
13885
- method(_void(), array(LoginMethodContributionSchema).readonly());
13886
- /**
13887
13820
  * Orchestrator-side destination metadata. The orchestrator computes
13888
13821
  * `id = <addonId>:<subId>` from its provider lookup so consumers
13889
13822
  * (admin UI, restore flow) see one canonical key.
@@ -14257,7 +14190,8 @@ function customAction(input, output, options) {
14257
14190
  output,
14258
14191
  kind: options?.kind ?? "query",
14259
14192
  auth: options?.auth ?? "protected",
14260
- scope: options?.scope ?? { kind: "system" }
14193
+ scope: options?.scope ?? { kind: "system" },
14194
+ ...options?.caller ? { caller: "required" } : {}
14261
14195
  };
14262
14196
  }
14263
14197
  /**
@@ -15254,47 +15188,422 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
15254
15188
  kind: "mutation",
15255
15189
  auth: "admin"
15256
15190
  });
15257
- var LogLevelSchema = _enum([
15258
- "debug",
15259
- "info",
15260
- "warn",
15261
- "error"
15191
+ /**
15192
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15193
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15194
+ * caps stay wire-compatible without a circular cap→cap import.
15195
+ *
15196
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
15197
+ * every transport tier structurally, and failed calls still write usage rows.
15198
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15199
+ */
15200
+ var LlmUsageSchema = object({
15201
+ inputTokens: number(),
15202
+ outputTokens: number()
15203
+ });
15204
+ var LlmErrorCodeSchema = _enum([
15205
+ "timeout",
15206
+ "rate-limited",
15207
+ "auth",
15208
+ "refusal",
15209
+ "bad-request",
15210
+ "unavailable",
15211
+ "no-profile",
15212
+ "budget-exceeded",
15213
+ "adapter-error"
15262
15214
  ]);
15263
- var LogEntrySchema = object({
15264
- timestamp: date(),
15265
- level: LogLevelSchema,
15266
- scope: array(string()),
15215
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15216
+ ok: literal(true),
15217
+ text: string(),
15218
+ model: string(),
15219
+ usage: LlmUsageSchema,
15220
+ truncated: boolean(),
15221
+ latencyMs: number()
15222
+ }), object({
15223
+ ok: literal(false),
15224
+ code: LlmErrorCodeSchema,
15267
15225
  message: string(),
15268
- meta: record(string(), unknown()).optional(),
15269
- tags: record(string(), string()).optional()
15226
+ retryAfterMs: number().optional()
15227
+ })]);
15228
+ /**
15229
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15230
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15231
+ * notification-output.cap.ts:27-31 precedents).
15232
+ */
15233
+ var LlmImageSchema = object({
15234
+ bytes: _instanceof(Uint8Array),
15235
+ mimeType: string()
15270
15236
  });
15271
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15272
- scope: array(string()).optional(),
15273
- level: LogLevelSchema.optional(),
15274
- since: date().optional(),
15275
- until: date().optional(),
15276
- limit: number().optional(),
15277
- tags: record(string(), string()).optional()
15278
- }), array(LogEntrySchema).readonly());
15279
- var CpuBreakdownSchema = object({
15280
- total: number(),
15281
- user: number(),
15282
- system: number(),
15283
- irq: number(),
15284
- nice: number(),
15285
- loadAvg: tuple([
15286
- number(),
15287
- number(),
15288
- number()
15289
- ]),
15290
- cores: number()
15237
+ var LlmGenerateBaseInputSchema = object({
15238
+ /** Collection routing (the notification-output posture). */
15239
+ addonId: string().optional(),
15240
+ /** Explicit profile; else the resolution chain (spec §3). */
15241
+ profileId: string().optional(),
15242
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15243
+ consumer: string(),
15244
+ system: string().optional(),
15245
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
15246
+ prompt: string(),
15247
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15248
+ jsonSchema: record(string(), unknown()).optional(),
15249
+ /** Per-call override of the profile default. */
15250
+ maxTokens: number().int().positive().optional(),
15251
+ temperature: number().optional()
15291
15252
  });
15292
- var MemoryInfoSchema = object({
15293
- percent: number(),
15294
- totalBytes: number(),
15295
- usedBytes: number(),
15296
- availableBytes: number(),
15297
- swapUsedBytes: number(),
15253
+ /**
15254
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15255
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15256
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15257
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15258
+ * this only through the `llm` cap's methods.
15259
+ *
15260
+ * One running llama-server child per node in v1 (models are RAM-heavy).
15261
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15262
+ * watchdog — operator decision #3).
15263
+ */
15264
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
15265
+ object({
15266
+ kind: literal("catalog"),
15267
+ catalogId: string()
15268
+ }),
15269
+ object({
15270
+ kind: literal("url"),
15271
+ url: string(),
15272
+ sha256: string().optional()
15273
+ }),
15274
+ object({
15275
+ kind: literal("path"),
15276
+ path: string()
15277
+ })
15278
+ ]);
15279
+ var ManagedRuntimeConfigSchema = object({
15280
+ /** WHERE the runtime lives — hub or any agent. */
15281
+ nodeId: string(),
15282
+ /** Closed for v1; 'ollama' is a v2 candidate. */
15283
+ engine: _enum(["llama-cpp"]),
15284
+ model: ManagedModelRefSchema,
15285
+ contextSize: number().int().default(4096),
15286
+ /** 0 = CPU-only. */
15287
+ gpuLayers: number().int().default(0),
15288
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15289
+ threads: number().int().optional(),
15290
+ /** Concurrent slots. */
15291
+ parallel: number().int().default(1),
15292
+ /** Else lazy: first generate boots it. */
15293
+ autoStart: boolean().default(false),
15294
+ /** 0 = never; frees RAM after quiet periods. */
15295
+ idleStopMinutes: number().int().default(30)
15296
+ });
15297
+ var LlmRuntimeStatusSchema = object({
15298
+ /** Status is ALWAYS node-qualified. */
15299
+ nodeId: string(),
15300
+ state: _enum([
15301
+ "stopped",
15302
+ "downloading",
15303
+ "starting",
15304
+ "ready",
15305
+ "crashed",
15306
+ "failed"
15307
+ ]),
15308
+ pid: number().optional(),
15309
+ port: number().optional(),
15310
+ modelPath: string().optional(),
15311
+ modelId: string().optional(),
15312
+ downloadProgress: number().min(0).max(1).optional(),
15313
+ lastError: string().optional(),
15314
+ crashesInWindow: number(),
15315
+ /** Child RSS (sampled best-effort). */
15316
+ memoryBytes: number().optional(),
15317
+ vramBytes: number().optional()
15318
+ });
15319
+ var LlmNodeModelSchema = object({
15320
+ file: string(),
15321
+ sizeBytes: number(),
15322
+ catalogId: string().optional(),
15323
+ installedAt: number().optional()
15324
+ });
15325
+ var LlmRuntimeDiskUsageSchema = object({
15326
+ nodeId: string(),
15327
+ modelsBytes: number(),
15328
+ freeBytes: number().optional()
15329
+ });
15330
+ method(LlmGenerateBaseInputSchema.extend({
15331
+ images: array(LlmImageSchema).optional(),
15332
+ runtime: ManagedRuntimeConfigSchema,
15333
+ /** The managed profile's timeout, threaded by the hub provider. */
15334
+ timeoutMs: number().int().positive().optional()
15335
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15336
+ kind: "mutation",
15337
+ auth: "admin"
15338
+ }), method(object({}), _void(), {
15339
+ kind: "mutation",
15340
+ auth: "admin"
15341
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15342
+ kind: "mutation",
15343
+ auth: "admin"
15344
+ }), method(object({ file: string() }), _void(), {
15345
+ kind: "mutation",
15346
+ auth: "admin"
15347
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15348
+ /**
15349
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15350
+ * methods concat-fan across providers; single-row methods route to ONE
15351
+ * provider by the `addonId` in the call input (the notification-output
15352
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15353
+ * (hub-placed); the cap stays open for future providers.
15354
+ *
15355
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15356
+ * `apiKey` is a password field — providers REDACT it on read and merge on
15357
+ * write; a stored key NEVER round-trips to a client.
15358
+ */
15359
+ var LlmProfileKindSchema = _enum([
15360
+ "openai-compatible",
15361
+ "openai",
15362
+ "anthropic",
15363
+ "google",
15364
+ "managed-local"
15365
+ ]);
15366
+ var LlmProfileSchema = object({
15367
+ id: string(),
15368
+ name: string(),
15369
+ kind: LlmProfileKindSchema,
15370
+ /** Stamped by the provider — keeps the fanned catalog routable. */
15371
+ addonId: string(),
15372
+ enabled: boolean(),
15373
+ /** Vendor model id, or the managed runtime's loaded model. */
15374
+ model: string(),
15375
+ /** Required for openai-compatible; override for cloud kinds. */
15376
+ baseUrl: string().optional(),
15377
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
15378
+ apiKey: string().optional(),
15379
+ supportsVision: boolean(),
15380
+ temperature: number().min(0).max(2).optional(),
15381
+ maxTokens: number().int().positive().optional(),
15382
+ timeoutMs: number().int().positive().default(6e4),
15383
+ extraHeaders: record(string(), string()).optional(),
15384
+ /** kind === 'managed-local' only (spec §4). */
15385
+ runtime: ManagedRuntimeConfigSchema.optional()
15386
+ });
15387
+ /** ConfigUISchema tree passed through untyped on the wire (the
15388
+ * notification-output `ConfigSchemaPassthrough` precedent at
15389
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15390
+ var ConfigSchemaPassthrough$1 = unknown();
15391
+ var LlmProfileKindDescriptorSchema = object({
15392
+ kind: LlmProfileKindSchema,
15393
+ label: string(),
15394
+ icon: string(),
15395
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
15396
+ addonId: string(),
15397
+ configSchema: ConfigSchemaPassthrough$1
15398
+ });
15399
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15400
+ var LlmDefaultSchema = object({
15401
+ selector: LlmDefaultSelectorSchema,
15402
+ profileId: string()
15403
+ });
15404
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
15405
+ var LlmUsageRollupSchema = object({
15406
+ day: string(),
15407
+ consumer: string(),
15408
+ profileId: string(),
15409
+ calls: number(),
15410
+ okCalls: number(),
15411
+ errorCalls: number(),
15412
+ inputTokens: number(),
15413
+ outputTokens: number(),
15414
+ avgLatencyMs: number()
15415
+ });
15416
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15417
+ var ManagedModelCatalogEntrySchema = object({
15418
+ id: string(),
15419
+ label: string(),
15420
+ family: string(),
15421
+ purpose: _enum(["text", "vision"]),
15422
+ url: string(),
15423
+ sha256: string(),
15424
+ sizeBytes: number(),
15425
+ quantization: string(),
15426
+ /** Load-time guidance shown in the picker. */
15427
+ minRamBytes: number(),
15428
+ contextSizeDefault: number().int(),
15429
+ /** Vision models: companion projector file. */
15430
+ mmprojUrl: string().optional()
15431
+ });
15432
+ var LlmRuntimeNodeSchema = object({
15433
+ nodeId: string(),
15434
+ reachable: boolean(),
15435
+ status: LlmRuntimeStatusSchema.optional(),
15436
+ disk: LlmRuntimeDiskUsageSchema.optional(),
15437
+ error: string().optional()
15438
+ });
15439
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
15440
+ var ProfileRefInputSchema = object({
15441
+ addonId: string(),
15442
+ profileId: string()
15443
+ });
15444
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
15445
+ kind: "mutation",
15446
+ auth: "admin"
15447
+ }), method(ProfileRefInputSchema, _void(), {
15448
+ kind: "mutation",
15449
+ auth: "admin"
15450
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
15451
+ kind: "mutation",
15452
+ auth: "admin"
15453
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
15454
+ selector: LlmDefaultSelectorSchema,
15455
+ profileId: string().nullable()
15456
+ }), _void(), {
15457
+ kind: "mutation",
15458
+ auth: "admin"
15459
+ }), method(object({
15460
+ since: number().optional(),
15461
+ until: number().optional(),
15462
+ consumer: string().optional(),
15463
+ profileId: string().optional()
15464
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
15465
+ nodeId: string(),
15466
+ model: ManagedModelRefSchema
15467
+ }), _void(), {
15468
+ kind: "mutation",
15469
+ auth: "admin"
15470
+ }), method(object({
15471
+ nodeId: string(),
15472
+ file: string()
15473
+ }), _void(), {
15474
+ kind: "mutation",
15475
+ auth: "admin"
15476
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
15477
+ kind: "mutation",
15478
+ auth: "admin"
15479
+ }), method(ProfileRefInputSchema, _void(), {
15480
+ kind: "mutation",
15481
+ auth: "admin"
15482
+ });
15483
+ var LogLevelSchema = _enum([
15484
+ "debug",
15485
+ "info",
15486
+ "warn",
15487
+ "error"
15488
+ ]);
15489
+ var LogEntrySchema = object({
15490
+ timestamp: date(),
15491
+ level: LogLevelSchema,
15492
+ scope: array(string()),
15493
+ message: string(),
15494
+ meta: record(string(), unknown()).optional(),
15495
+ tags: record(string(), string()).optional()
15496
+ });
15497
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15498
+ scope: array(string()).optional(),
15499
+ level: LogLevelSchema.optional(),
15500
+ since: date().optional(),
15501
+ until: date().optional(),
15502
+ limit: number().optional(),
15503
+ tags: record(string(), string()).optional()
15504
+ }), array(LogEntrySchema).readonly());
15505
+ /**
15506
+ * `login-method` — collection cap through which auth addons contribute
15507
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
15508
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
15509
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
15510
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
15511
+ * procedure aggregates them for the unauthenticated login page.
15512
+ *
15513
+ * A contribution is a discriminated union on `kind`:
15514
+ *
15515
+ * - `redirect` — a declarative button. The login page renders a generic
15516
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
15517
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
15518
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
15519
+ * login page needs NO change.
15520
+ *
15521
+ * - `widget` — a Module-Federation widget the login page mounts (via
15522
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
15523
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
15524
+ * mechanism kept for future use; no shipped addon uses it on the login
15525
+ * page (the passkey ceremony below runs natively in the shell instead).
15526
+ *
15527
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
15528
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
15529
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
15530
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
15531
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
15532
+ * fetching any remote code pre-auth. Contribution stays unconditional —
15533
+ * enrollment state is never leaked pre-auth; visibility is a shell
15534
+ * decision.
15535
+ *
15536
+ * Every contribution carries a `stage`:
15537
+ * - `primary` — shown on the first credentials screen (OIDC /
15538
+ * magic-link buttons; a future usernameless passkey).
15539
+ * - `second-factor` — shown AFTER the password leg, gated on the
15540
+ * returned `factors` (passkey-as-2FA today).
15541
+ *
15542
+ * `mount: skip` — the cap is read server-side by the core auth router
15543
+ * (`registry.getCollection('login-method')`), never mounted as its own
15544
+ * tRPC router.
15545
+ */
15546
+ /** When a login method renders in the two-phase login flow. */
15547
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
15548
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
15549
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
15550
+ object({
15551
+ kind: literal("redirect"),
15552
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
15553
+ id: string(),
15554
+ /** Operator-facing button label. */
15555
+ label: string(),
15556
+ /** lucide-react icon name. */
15557
+ icon: string().optional(),
15558
+ /** Addon-owned HTTP route the button navigates to (GET). */
15559
+ startUrl: string(),
15560
+ stage: LoginStageEnum
15561
+ }),
15562
+ object({
15563
+ kind: literal("widget"),
15564
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
15565
+ id: string(),
15566
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
15567
+ addonId: string(),
15568
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
15569
+ bundle: string(),
15570
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
15571
+ remote: WidgetRemoteSchema,
15572
+ stage: LoginStageEnum
15573
+ }),
15574
+ object({
15575
+ kind: literal("passkey"),
15576
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
15577
+ id: string(),
15578
+ /** Operator-facing button label. */
15579
+ label: string(),
15580
+ stage: LoginStageEnum,
15581
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
15582
+ rpId: string(),
15583
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
15584
+ origin: string().nullable()
15585
+ })
15586
+ ]);
15587
+ method(_void(), array(LoginMethodContributionSchema).readonly());
15588
+ var CpuBreakdownSchema = object({
15589
+ total: number(),
15590
+ user: number(),
15591
+ system: number(),
15592
+ irq: number(),
15593
+ nice: number(),
15594
+ loadAvg: tuple([
15595
+ number(),
15596
+ number(),
15597
+ number()
15598
+ ]),
15599
+ cores: number()
15600
+ });
15601
+ var MemoryInfoSchema = object({
15602
+ percent: number(),
15603
+ totalBytes: number(),
15604
+ usedBytes: number(),
15605
+ availableBytes: number(),
15606
+ swapUsedBytes: number(),
15298
15607
  swapTotalBytes: number()
15299
15608
  });
15300
15609
  var DiskIoSnapshotSchema = object({
@@ -15754,14 +16063,14 @@ var TargetKindCapsSchema = object({
15754
16063
  * the union is large and not meant for runtime validation here; the exported
15755
16064
  * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
15756
16065
  */
15757
- var ConfigSchemaPassthrough$1 = unknown();
16066
+ var ConfigSchemaPassthrough = unknown();
15758
16067
  var TargetKindSchema = object({
15759
16068
  kind: string(),
15760
16069
  label: string(),
15761
16070
  icon: string(),
15762
16071
  /** Stamped by each provider so the concat-fanned catalog stays routable. */
15763
16072
  addonId: string(),
15764
- configSchema: ConfigSchemaPassthrough$1,
16073
+ configSchema: ConfigSchemaPassthrough,
15765
16074
  supportsDiscovery: boolean(),
15766
16075
  caps: TargetKindCapsSchema
15767
16076
  });
@@ -15809,302 +16118,498 @@ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSche
15809
16118
  }), SendResultSchema, { kind: "mutation" }), method(object({
15810
16119
  targetId: string(),
15811
16120
  sample: NotificationSchema.optional()
15812
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
15813
- targetId: string(),
15814
- enabled: boolean()
15815
- }), _void(), { kind: "mutation" });
15816
- /**
15817
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15818
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15819
- * caps stay wire-compatible without a circular cap→cap import.
15820
- *
15821
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
15822
- * every transport tier structurally, and failed calls still write usage rows.
15823
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15824
- */
15825
- var LlmUsageSchema = object({
15826
- inputTokens: number(),
15827
- outputTokens: number()
15828
- });
15829
- var LlmErrorCodeSchema = _enum([
15830
- "timeout",
15831
- "rate-limited",
15832
- "auth",
15833
- "refusal",
15834
- "bad-request",
15835
- "unavailable",
15836
- "no-profile",
15837
- "budget-exceeded",
15838
- "adapter-error"
15839
- ]);
15840
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15841
- ok: literal(true),
15842
- text: string(),
15843
- model: string(),
15844
- usage: LlmUsageSchema,
15845
- truncated: boolean(),
15846
- latencyMs: number()
15847
- }), object({
15848
- ok: literal(false),
15849
- code: LlmErrorCodeSchema,
15850
- message: string(),
15851
- retryAfterMs: number().optional()
15852
- })]);
15853
- /**
15854
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15855
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15856
- * notification-output.cap.ts:27-31 precedents).
15857
- */
15858
- var LlmImageSchema = object({
15859
- bytes: _instanceof(Uint8Array),
15860
- mimeType: string()
15861
- });
15862
- var LlmGenerateBaseInputSchema = object({
15863
- /** Collection routing (the notification-output posture). */
15864
- addonId: string().optional(),
15865
- /** Explicit profile; else the resolution chain (spec §3). */
15866
- profileId: string().optional(),
15867
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15868
- consumer: string(),
15869
- system: string().optional(),
15870
- /** v1: single-turn. `messages[]` is a v2 additive field. */
15871
- prompt: string(),
15872
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15873
- jsonSchema: record(string(), unknown()).optional(),
15874
- /** Per-call override of the profile default. */
15875
- maxTokens: number().int().positive().optional(),
15876
- temperature: number().optional()
15877
- });
16121
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
16122
+ targetId: string(),
16123
+ enabled: boolean()
16124
+ }), _void(), { kind: "mutation" });
15878
16125
  /**
15879
- * `llm-runtime`node-side managed llama.cpp executor (spec §4). Registered
15880
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15881
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15882
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15883
- * this only through the `llm` cap's methods.
16126
+ * notification-rulesthe Notification Center rule surface (P1 core).
15884
16127
  *
15885
- * One running llama-server child per node in v1 (models are RAM-heavy).
15886
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15887
- * watchdog — operator decision #3).
16128
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16129
+ * (operator decisions D-1/D-2/D-3 are binding):
16130
+ *
16131
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16132
+ * `notification-center` module), hooked on the durable persistence
16133
+ * moments (object-event insert, TrackCloser.closeExpired) with a
16134
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
16135
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16136
+ * FIRST persisted detection matching the conditions (per-track dedup,
16137
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16138
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
16139
+ * - DISPATCH stays behind `notification-output` (rules reference targets
16140
+ * by id; per-backend params are a passthrough blob capped by the
16141
+ * target kind's own caps/degrade engine).
16142
+ *
16143
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
16144
+ * server-injected caller identity — the first `caller: 'required'`
16145
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
16146
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
16147
+ * windows, and the optional label/identity/plate matchers. User rules,
16148
+ * private zones, per-recipient fan-out and the wider condition table are
16149
+ * P2+ (see spec §7).
16150
+ *
16151
+ * All schemas here are the single source of truth — `NcRule` etc. are
16152
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16153
+ * schema/interface drift is explicitly not repeated).
15888
16154
  */
15889
- var ManagedModelRefSchema = discriminatedUnion("kind", [
15890
- object({
15891
- kind: literal("catalog"),
15892
- catalogId: string()
15893
- }),
15894
- object({
15895
- kind: literal("url"),
15896
- url: string(),
15897
- sha256: string().optional()
15898
- }),
15899
- object({
15900
- kind: literal("path"),
15901
- path: string()
15902
- })
16155
+ /**
16156
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
16157
+ * The value maps 1:1 onto the evaluated record kind:
16158
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16159
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16160
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16161
+ * change of a LINKED device, one row per linked camera)
16162
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16163
+ * delivery / pick-up)
16164
+ *
16165
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16166
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
16167
+ * this one field keeps the schema additive — a rule still declares exactly
16168
+ * one trigger.
16169
+ */
16170
+ var NcDeliverySchema = _enum([
16171
+ "immediate",
16172
+ "track-end",
16173
+ "device-event",
16174
+ "package-event"
15903
16175
  ]);
15904
- var ManagedRuntimeConfigSchema = object({
15905
- /** WHERE the runtime lives — hub or any agent. */
15906
- nodeId: string(),
15907
- /** Closed for v1; 'ollama' is a v2 candidate. */
15908
- engine: _enum(["llama-cpp"]),
15909
- model: ManagedModelRefSchema,
15910
- contextSize: number().int().default(4096),
15911
- /** 0 = CPU-only. */
15912
- gpuLayers: number().int().default(0),
15913
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15914
- threads: number().int().optional(),
15915
- /** Concurrent slots. */
15916
- parallel: number().int().default(1),
15917
- /** Else lazy: first generate boots it. */
15918
- autoStart: boolean().default(false),
15919
- /** 0 = never; frees RAM after quiet periods. */
15920
- idleStopMinutes: number().int().default(30)
15921
- });
15922
- var LlmRuntimeStatusSchema = object({
15923
- /** Status is ALWAYS node-qualified. */
15924
- nodeId: string(),
15925
- state: _enum([
15926
- "stopped",
15927
- "downloading",
15928
- "starting",
15929
- "ready",
15930
- "crashed",
15931
- "failed"
15932
- ]),
15933
- pid: number().optional(),
15934
- port: number().optional(),
15935
- modelPath: string().optional(),
15936
- modelId: string().optional(),
15937
- downloadProgress: number().min(0).max(1).optional(),
15938
- lastError: string().optional(),
15939
- crashesInWindow: number(),
15940
- /** Child RSS (sampled best-effort). */
15941
- memoryBytes: number().optional(),
15942
- vramBytes: number().optional()
16176
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
16177
+ var NcScheduleSchema = object({
16178
+ windows: array(object({
16179
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16180
+ days: array(number().int().min(0).max(6)).min(1),
16181
+ startMinute: number().int().min(0).max(1439),
16182
+ endMinute: number().int().min(0).max(1439)
16183
+ })).min(1),
16184
+ /** IANA timezone; default = hub host timezone. */
16185
+ timezone: string().optional(),
16186
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16187
+ invert: boolean().optional()
15943
16188
  });
15944
- var LlmNodeModelSchema = object({
15945
- file: string(),
15946
- sizeBytes: number(),
15947
- catalogId: string().optional(),
15948
- installedAt: number().optional()
16189
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16190
+ var NcPlateMatcherSchema = object({
16191
+ values: array(string().min(1)).min(1),
16192
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16193
+ maxDistance: number().int().min(0).max(3).default(1)
15949
16194
  });
15950
- var LlmRuntimeDiskUsageSchema = object({
15951
- nodeId: string(),
15952
- modelsBytes: number(),
15953
- freeBytes: number().optional()
16195
+ /**
16196
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16197
+ * occupancy edge for a device — optionally narrowed to a single admin
16198
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16199
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
16200
+ * - `became-free` — count crossed ≥ `count` → below it
16201
+ * - `>=` / `<=` — count is at/over or at/under `count`
16202
+ * `sustainSeconds` requires the condition hold continuously that long
16203
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
16204
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16205
+ * the condition never matches. Confirmed edge-state survives addon restarts
16206
+ * (declared SQLite collection, reseeded on boot).
16207
+ */
16208
+ var NcOccupancyConditionSchema = object({
16209
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16210
+ zoneId: string().optional(),
16211
+ /** Object class to count; absent = any class. */
16212
+ className: string().optional(),
16213
+ op: _enum([
16214
+ "became-occupied",
16215
+ "became-free",
16216
+ ">=",
16217
+ "<="
16218
+ ]).default("became-occupied"),
16219
+ count: number().int().min(0).default(1),
16220
+ sustainSeconds: number().int().min(0).max(3600).default(15)
16221
+ });
16222
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16223
+ var NcZoneConditionSchema = object({
16224
+ ids: array(string().min(1)).min(1),
16225
+ /** Quantifier over `ids` — at least one / every one visited. */
16226
+ match: _enum(["any", "all"]).default("any")
15954
16227
  });
15955
- method(LlmGenerateBaseInputSchema.extend({
15956
- images: array(LlmImageSchema).optional(),
15957
- runtime: ManagedRuntimeConfigSchema,
15958
- /** The managed profile's timeout, threaded by the hub provider. */
15959
- timeoutMs: number().int().positive().optional()
15960
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15961
- kind: "mutation",
15962
- auth: "admin"
15963
- }), method(object({}), _void(), {
15964
- kind: "mutation",
15965
- auth: "admin"
15966
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15967
- kind: "mutation",
15968
- auth: "admin"
15969
- }), method(object({ file: string() }), _void(), {
15970
- kind: "mutation",
15971
- auth: "admin"
15972
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15973
16228
  /**
15974
- * `llm`consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15975
- * methods concat-fan across providers; single-row methods route to ONE
15976
- * provider by the `addonId` in the call input (the notification-output
15977
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15978
- * (hub-placed); the cap stays open for future providers.
15979
- *
15980
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15981
- * `apiKey` is a password field — providers REDACT it on read and merge on
15982
- * write; a stored key NEVER round-trips to a client.
16229
+ * The P1 condition set a flat AND of groups; absent group = pass;
16230
+ * membership lists are OR within the list (spec §2.3).
15983
16231
  */
15984
- var LlmProfileKindSchema = _enum([
15985
- "openai-compatible",
15986
- "openai",
15987
- "anthropic",
15988
- "google",
15989
- "managed-local"
15990
- ]);
15991
- var LlmProfileSchema = object({
15992
- id: string(),
15993
- name: string(),
15994
- kind: LlmProfileKindSchema,
15995
- /** Stamped by the provider keeps the fanned catalog routable. */
15996
- addonId: string(),
15997
- enabled: boolean(),
15998
- /** Vendor model id, or the managed runtime's loaded model. */
15999
- model: string(),
16000
- /** Required for openai-compatible; override for cloud kinds. */
16001
- baseUrl: string().optional(),
16002
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
16003
- apiKey: string().optional(),
16004
- supportsVision: boolean(),
16005
- temperature: number().min(0).max(2).optional(),
16006
- maxTokens: number().int().positive().optional(),
16007
- timeoutMs: number().int().positive().default(6e4),
16008
- extraHeaders: record(string(), string()).optional(),
16009
- /** kind === 'managed-local' only (spec §4). */
16010
- runtime: ManagedRuntimeConfigSchema.optional()
16232
+ var NcConditionsSchema = object({
16233
+ /** Device scope — absent = all devices. */
16234
+ devices: array(number()).optional(),
16235
+ /** Detector class names (any overlap with the record's class set). */
16236
+ classes: array(string().min(1)).optional(),
16237
+ /** Veto classes — any overlap fails the rule. */
16238
+ classesExclude: array(string().min(1)).optional(),
16239
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
16240
+ minConfidence: number().min(0).max(1).optional(),
16241
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
16242
+ zones: NcZoneConditionSchema.optional(),
16243
+ /** Veto zones any hit fails the rule. */
16244
+ zonesExclude: array(string().min(1)).optional(),
16245
+ /**
16246
+ * Exact (case-insensitive) match on the record's collapsed `label`
16247
+ * (identity name / plate text / subclass).
16248
+ */
16249
+ labelEquals: array(string().min(1)).optional(),
16250
+ /**
16251
+ * Identity matcher. P1 boundary: matched against the record's collapsed
16252
+ * `label` (the identity display name propagated by the face pipeline)
16253
+ * identity-ID matching rides in P2 when identity ids reach the record.
16254
+ */
16255
+ identities: array(string().min(1)).optional(),
16256
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
16257
+ plates: NcPlateMatcherSchema.optional(),
16258
+ /**
16259
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16260
+ * Same P1 boundary: matched against the record's collapsed `label` (the
16261
+ * identity display name). A record with NO label passes (nothing to
16262
+ * exclude), unlike the include variant which fails on an absent label.
16263
+ */
16264
+ identitiesExclude: array(string().min(1)).optional(),
16265
+ /**
16266
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16267
+ * TRACK-END only: importance is scored at track close, so it does not exist
16268
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16269
+ * close the value is threaded via the close-time info (the `Track` clone is
16270
+ * captured before the DB row is updated, so it would otherwise read stale).
16271
+ * Fails when the record carries no importance (never guess quality — the
16272
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
16273
+ */
16274
+ minImportance: number().min(0).max(1).optional(),
16275
+ /**
16276
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16277
+ * TRACK-END only: an `immediate` / object-event subject has no closed
16278
+ * lifespan, so a dwell condition never matches immediate delivery
16279
+ * (documented choice — the object-event record carries no `firstSeen`,
16280
+ * so dwell cannot be computed from what the subject actually carries).
16281
+ */
16282
+ minDwellSeconds: number().min(0).optional(),
16283
+ /**
16284
+ * Detection provenance filter. `any` (default / absent) matches every
16285
+ * source; otherwise the subject's source must equal it. Legacy records
16286
+ * with no stamped source are treated as `pipeline`. The union spans both
16287
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
16288
+ * tracks carry `sensor`.
16289
+ */
16290
+ source: _enum([
16291
+ "pipeline",
16292
+ "onboard",
16293
+ "sensor",
16294
+ "any"
16295
+ ]).optional(),
16296
+ /**
16297
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16298
+ * detector `minConfidence` (that gates the object-detection score; this
16299
+ * gates the recognition/OCR match score). Fails when the subject carries
16300
+ * no label-match confidence (never guess). TRACK-END only: the confidence
16301
+ * lives on the recognition result and reaches the subject at track close.
16302
+ *
16303
+ * What it measures precisely (plumbed at track close — the closer threads
16304
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16305
+ * `importance`): the BEST recognition match confidence observed for the
16306
+ * label the track carries at close — for a face, the peak cosine similarity
16307
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16308
+ * for a plate, the peak OCR read score of the best-held plate
16309
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16310
+ * one track the higher of the two is used. A track that ended with no
16311
+ * confident identity/plate match carries no value, so the condition fails
16312
+ * closed for it (an un-recognized subject).
16313
+ */
16314
+ minLabelConfidence: number().min(0).max(1).optional(),
16315
+ /**
16316
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16317
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16318
+ * against the token carried on the device-event subject (extracted from the
16319
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16320
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16321
+ * eventType, so gate those with {@link sensorKinds} instead.
16322
+ */
16323
+ eventTypeTokens: array(string().min(1)).optional(),
16324
+ /**
16325
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16326
+ * `contact`, `button`, `device-event`) — matched against the persisted
16327
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16328
+ */
16329
+ sensorKinds: array(string().min(1)).optional(),
16330
+ /**
16331
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16332
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16333
+ * when the subject's phase does not match (a subject always carries a phase
16334
+ * on the package-event trigger).
16335
+ */
16336
+ packagePhase: _enum([
16337
+ "delivered",
16338
+ "picked-up",
16339
+ "both"
16340
+ ]).optional(),
16341
+ /**
16342
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16343
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16344
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
16345
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16346
+ */
16347
+ customZones: array(MaskPolygonShapeSchema).optional(),
16348
+ /**
16349
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16350
+ * (optionally zone/class-scoped) occupancy count crosses the configured
16351
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
16352
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16353
+ */
16354
+ occupancy: NcOccupancyConditionSchema.optional()
16011
16355
  });
16012
- /** ConfigUISchema tree passed through untyped on the wire (the
16013
- * notification-output `ConfigSchemaPassthrough` precedent at
16014
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
16015
- var ConfigSchemaPassthrough = unknown();
16016
- var LlmProfileKindDescriptorSchema = object({
16017
- kind: LlmProfileKindSchema,
16018
- label: string(),
16019
- icon: string(),
16020
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
16021
- addonId: string(),
16022
- configSchema: ConfigSchemaPassthrough
16356
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
16357
+ var NcRuleTargetSchema = object({
16358
+ /** `notification-output` Target id. */
16359
+ targetId: string().min(1),
16360
+ /**
16361
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
16362
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16363
+ * degrade engine drops what the backend can't render.
16364
+ */
16365
+ params: record(string(), unknown()).optional()
16023
16366
  });
16024
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
16025
- var LlmDefaultSchema = object({
16026
- selector: LlmDefaultSelectorSchema,
16027
- profileId: string()
16367
+ /**
16368
+ * Media attachment policy (P1 still-image subset).
16369
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
16370
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
16371
+ * matched on identities attaches the subject's `faceCrop`, one matched on
16372
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
16373
+ * (or when the specific crop is missing) degrades to `best`, then
16374
+ * `keyFrame`, then no attachment — never delaying the send. The matched
16375
+ * condition summary is frozen on the outbox row at enqueue (like the rule
16376
+ * name), so the choice never drifts from the record that fired it.
16377
+ * - `keyFrame` — the clean scene frame (no subject box).
16378
+ * - `none` — no attachment.
16379
+ */
16380
+ var NcMediaPolicySchema = object({ attach: _enum([
16381
+ "best",
16382
+ "best-matching",
16383
+ "keyFrame",
16384
+ "none"
16385
+ ]).default("best") });
16386
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16387
+ var NcThrottleSchema = object({
16388
+ cooldownSec: number().int().min(0).max(86400).default(60),
16389
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16390
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
16391
+ });
16392
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16393
+ var NcRuleInputSchema = object({
16394
+ name: string().min(1).max(200),
16395
+ enabled: boolean().default(true),
16396
+ delivery: NcDeliverySchema,
16397
+ conditions: NcConditionsSchema.default({}),
16398
+ schedule: NcScheduleSchema.optional(),
16399
+ targets: array(NcRuleTargetSchema).min(1),
16400
+ media: NcMediaPolicySchema.default({ attach: "best" }),
16401
+ throttle: NcThrottleSchema.default({
16402
+ cooldownSec: 60,
16403
+ scope: "rule-device"
16404
+ }),
16405
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16406
+ template: object({
16407
+ title: string().max(500).optional(),
16408
+ body: string().max(2e3).optional()
16409
+ }).optional(),
16410
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
16411
+ priority: number().int().min(1).max(5).default(3),
16412
+ /**
16413
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16414
+ * behaviour, visible to all, read-only in the viewer). Present = personal
16415
+ * rule owned by this userId. Server-stamped; never trusted from a client.
16416
+ */
16417
+ ownerUserId: string().optional()
16028
16418
  });
16029
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
16030
- var LlmUsageRollupSchema = object({
16031
- day: string(),
16032
- consumer: string(),
16033
- profileId: string(),
16034
- calls: number(),
16035
- okCalls: number(),
16036
- errorCalls: number(),
16037
- inputTokens: number(),
16038
- outputTokens: number(),
16039
- avgLatencyMs: number()
16419
+ /**
16420
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
16421
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16422
+ * NOT a client-authored input field (it lives on the persisted rule, not the
16423
+ * input), so it is added here explicitly to let the store's per-target opt-out
16424
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16425
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16426
+ * `updateRule` patch.
16427
+ */
16428
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
16429
+ /** A persisted rule. */
16430
+ var NcRuleSchema = NcRuleInputSchema.extend({
16431
+ id: string(),
16432
+ /** userId of the admin who created the rule (server-stamped caller). */
16433
+ createdBy: string(),
16434
+ createdAt: number(),
16435
+ updatedAt: number(),
16436
+ /**
16437
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16438
+ * send time. Only a target's OWNER may add/remove its id (server-checked
16439
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
16440
+ */
16441
+ disabledTargetIds: array(string()).default([])
16442
+ });
16443
+ var NcTestResultSchema = object({
16444
+ recordId: string(),
16445
+ recordKind: _enum([
16446
+ "object-event",
16447
+ "track",
16448
+ "device-event",
16449
+ "package-event"
16450
+ ]),
16451
+ deviceId: number(),
16452
+ timestamp: number(),
16453
+ wouldFire: boolean(),
16454
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
16455
+ failedCondition: string().optional(),
16456
+ className: string().optional(),
16457
+ label: string().optional()
16040
16458
  });
16041
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
16042
- var ManagedModelCatalogEntrySchema = object({
16459
+ var NcConditionDescriptorSchema = object({
16460
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16043
16461
  id: string(),
16462
+ group: _enum([
16463
+ "scope",
16464
+ "class",
16465
+ "zones",
16466
+ "quality",
16467
+ "label",
16468
+ "schedule",
16469
+ "device",
16470
+ "package",
16471
+ "occupancy"
16472
+ ]),
16044
16473
  label: string(),
16045
- family: string(),
16046
- purpose: _enum(["text", "vision"]),
16047
- url: string(),
16048
- sha256: string(),
16049
- sizeBytes: number(),
16050
- quantization: string(),
16051
- /** Load-time guidance shown in the picker. */
16052
- minRamBytes: number(),
16053
- contextSizeDefault: number().int(),
16054
- /** Vision models: companion projector file. */
16055
- mmprojUrl: string().optional()
16474
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
16475
+ valueType: _enum([
16476
+ "deviceIdList",
16477
+ "stringList",
16478
+ "number01",
16479
+ "number",
16480
+ "sourceSelect",
16481
+ "zoneSelection",
16482
+ "zoneIdList",
16483
+ "schedule",
16484
+ "plateMatcher",
16485
+ "packagePhase",
16486
+ "polygonDraw",
16487
+ "occupancy"
16488
+ ]),
16489
+ operator: _enum([
16490
+ "in",
16491
+ "notIn",
16492
+ "anyOf",
16493
+ "allOf",
16494
+ "gte",
16495
+ "fuzzyIn",
16496
+ "withinSchedule"
16497
+ ]),
16498
+ /** Which delivery kinds the condition applies to. */
16499
+ appliesTo: array(NcDeliverySchema),
16500
+ phase: string(),
16501
+ description: string().optional()
16056
16502
  });
16057
- var LlmRuntimeNodeSchema = object({
16058
- nodeId: string(),
16059
- reachable: boolean(),
16060
- status: LlmRuntimeStatusSchema.optional(),
16061
- disk: LlmRuntimeDiskUsageSchema.optional(),
16062
- error: string().optional()
16503
+ /**
16504
+ * The delivery lifecycle status of a history row — a straight read of the
16505
+ * durable outbox row's own status (single source of truth):
16506
+ * - `pending` — enqueued, in-flight or retrying with backoff
16507
+ * - `sent` — delivered (terminal)
16508
+ * - `dead` — dead-lettered after exhausting retries / a permanent
16509
+ * backend rejection / a deleted target (terminal; carries
16510
+ * the failure `error`)
16511
+ *
16512
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
16513
+ * user dimension (quiet hours / snooze) and are additive when they land.
16514
+ */
16515
+ var NcHistoryStatusSchema = _enum([
16516
+ "pending",
16517
+ "sent",
16518
+ "dead"
16519
+ ]);
16520
+ /** The evaluated record kind a history row descends from (one per trigger). */
16521
+ var NcHistoryRecordKindSchema = _enum([
16522
+ "object-event",
16523
+ "track-end",
16524
+ "device-event",
16525
+ "package-event"
16526
+ ]);
16527
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16528
+ var NcHistorySubjectSchema = object({
16529
+ className: string(),
16530
+ label: string().optional(),
16531
+ confidence: number().optional(),
16532
+ zones: array(string()),
16533
+ timestamp: number()
16534
+ });
16535
+ /**
16536
+ * One delivery-history row. This is a read-only VIEW over the durable
16537
+ * outbox row (single source of truth — the same row the drain loop drives;
16538
+ * NO second write path, so history can never drift from delivery state).
16539
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16540
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16541
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
16542
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16543
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16544
+ * P1 (admin scope only).
16545
+ */
16546
+ var NcHistoryEntrySchema = object({
16547
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16548
+ id: string(),
16549
+ ruleId: string(),
16550
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
16551
+ ruleName: string(),
16552
+ /** The rule urgency/trigger that produced this delivery. */
16553
+ delivery: NcDeliverySchema,
16554
+ targetId: string(),
16555
+ deviceId: number(),
16556
+ recordKind: NcHistoryRecordKindSchema,
16557
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16558
+ recordId: string(),
16559
+ /** Present for track-scoped deliveries (object-event / track-end). */
16560
+ trackId: string().optional(),
16561
+ status: NcHistoryStatusSchema,
16562
+ /** Delivery attempts made so far. */
16563
+ attempts: number().int(),
16564
+ /** Fire time (outbox enqueue). */
16565
+ createdAt: number(),
16566
+ /** Last transition time (terminal for sent / dead). */
16567
+ updatedAt: number(),
16568
+ /** Failure detail — present on a `dead` row. */
16569
+ error: string().optional(),
16570
+ subject: NcHistorySubjectSchema
16063
16571
  });
16064
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16065
- var ProfileRefInputSchema = object({
16066
- addonId: string(),
16067
- profileId: string()
16572
+ /**
16573
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16574
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16575
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16576
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16577
+ */
16578
+ var NcHistoryFilterSchema = object({
16579
+ ruleId: string().optional(),
16580
+ deviceId: number().optional(),
16581
+ status: NcHistoryStatusSchema.optional(),
16582
+ since: number().optional(),
16583
+ until: number().optional(),
16584
+ limit: number().int().min(1).max(500).default(100)
16068
16585
  });
16069
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16070
- kind: "mutation",
16071
- auth: "admin"
16072
- }), method(ProfileRefInputSchema, _void(), {
16586
+ 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 }), {
16073
16587
  kind: "mutation",
16074
- auth: "admin"
16075
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16588
+ auth: "admin",
16589
+ caller: "required"
16590
+ }), method(object({
16591
+ ruleId: string(),
16592
+ patch: NcRulePatchSchema
16593
+ }), object({ rule: NcRuleSchema }), {
16076
16594
  kind: "mutation",
16077
- auth: "admin"
16078
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
16079
- selector: LlmDefaultSelectorSchema,
16080
- profileId: string().nullable()
16081
- }), _void(), {
16595
+ auth: "admin",
16596
+ caller: "required"
16597
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
16082
16598
  kind: "mutation",
16083
16599
  auth: "admin"
16084
16600
  }), method(object({
16085
- since: number().optional(),
16086
- until: number().optional(),
16087
- consumer: string().optional(),
16088
- profileId: string().optional()
16089
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
16090
- nodeId: string(),
16091
- model: ManagedModelRefSchema
16092
- }), _void(), {
16601
+ ruleId: string(),
16602
+ enabled: boolean()
16603
+ }), object({ success: literal(true) }), {
16093
16604
  kind: "mutation",
16094
16605
  auth: "admin"
16095
16606
  }), method(object({
16096
- nodeId: string(),
16097
- file: string()
16098
- }), _void(), {
16099
- kind: "mutation",
16100
- auth: "admin"
16101
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16102
- kind: "mutation",
16103
- auth: "admin"
16104
- }), method(ProfileRefInputSchema, _void(), {
16607
+ rule: NcRuleInputSchema,
16608
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
16609
+ }), object({ results: array(NcTestResultSchema) }), {
16105
16610
  kind: "mutation",
16106
16611
  auth: "admin"
16107
- });
16612
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
16108
16613
  /**
16109
16614
  * Zod schemas for persisted record types.
16110
16615
  *
@@ -16790,7 +17295,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16790
17295
  }), method(object({
16791
17296
  eventId: string(),
16792
17297
  kind: MediaFileKindEnum.optional()
16793
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
17298
+ }), array(MediaFileSchema).readonly()), method(object({
17299
+ trackId: string(),
17300
+ kinds: array(MediaFileKindEnum).optional()
17301
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
16794
17302
  deviceId: number(),
16795
17303
  timestamp: number(),
16796
17304
  frameWidth: number(),
@@ -16811,76 +17319,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16811
17319
  eventId: string(),
16812
17320
  timestamp: number()
16813
17321
  });
16814
- /**
16815
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
16816
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
16817
- * caps into per-camera event-kind descriptors.
16818
- *
16819
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
16820
- * is NOT duplicated here — every entry is derived from the single
16821
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
16822
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
16823
- * control cap means adding one line here (and a taxonomy entry); the anti-
16824
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
16825
- * eventful cap is missing.
16826
- */
16827
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
16828
- var LEGACY_ICON = {
16829
- motion: "motion",
16830
- audio: "audio",
16831
- person: "person",
16832
- vehicle: "vehicle",
16833
- animal: "animal",
16834
- package: "package",
16835
- door: "door",
16836
- pir: "pir",
16837
- smoke: "smoke",
16838
- water: "water",
16839
- button: "button",
16840
- generic: "generic",
16841
- gas: "smoke",
16842
- vibration: "generic",
16843
- tamper: "generic",
16844
- presence: "person",
16845
- lock: "generic",
16846
- siren: "generic",
16847
- switch: "generic",
16848
- doorbell: "button"
16849
- };
16850
- function legacyIcon(iconId) {
16851
- return LEGACY_ICON[iconId] ?? "generic";
16852
- }
16853
- /**
16854
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
16855
- * The anti-drift guard cross-checks this against the eventful caps declared
16856
- * in `packages/types/src/capabilities/*.cap.ts`.
16857
- */
16858
- var CAP_TO_KIND = {
16859
- contact: "contact",
16860
- motion: "motion-sensor",
16861
- smoke: "smoke",
16862
- flood: "flood",
16863
- gas: "gas",
16864
- "carbon-monoxide": "carbon-monoxide",
16865
- vibration: "vibration",
16866
- tamper: "tamper",
16867
- presence: "presence",
16868
- "enum-sensor": "enum-sensor",
16869
- "event-emitter": "device-event",
16870
- "lock-control": "lock",
16871
- switch: "switch",
16872
- button: "button",
16873
- doorbell: "doorbell"
16874
- };
16875
- function buildDescriptor(capName, kind) {
16876
- const t = EVENT_TAXONOMY[kind];
16877
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
16878
- return {
16879
- ...t,
16880
- icon: legacyIcon(t.iconId)
16881
- };
16882
- }
16883
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
16884
17322
  var CameraPipelineConfigSchema = object({
16885
17323
  engine: PipelineEngineChoiceSchema.optional(),
16886
17324
  steps: array(PipelineStepInputSchema).readonly(),
@@ -17366,6 +17804,76 @@ method(object({
17366
17804
  auth: "admin"
17367
17805
  });
17368
17806
  /**
17807
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
17808
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
17809
+ * caps into per-camera event-kind descriptors.
17810
+ *
17811
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
17812
+ * is NOT duplicated here — every entry is derived from the single
17813
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
17814
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
17815
+ * control cap means adding one line here (and a taxonomy entry); the anti-
17816
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
17817
+ * eventful cap is missing.
17818
+ */
17819
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
17820
+ var LEGACY_ICON = {
17821
+ motion: "motion",
17822
+ audio: "audio",
17823
+ person: "person",
17824
+ vehicle: "vehicle",
17825
+ animal: "animal",
17826
+ package: "package",
17827
+ door: "door",
17828
+ pir: "pir",
17829
+ smoke: "smoke",
17830
+ water: "water",
17831
+ button: "button",
17832
+ generic: "generic",
17833
+ gas: "smoke",
17834
+ vibration: "generic",
17835
+ tamper: "generic",
17836
+ presence: "person",
17837
+ lock: "generic",
17838
+ siren: "generic",
17839
+ switch: "generic",
17840
+ doorbell: "button"
17841
+ };
17842
+ function legacyIcon(iconId) {
17843
+ return LEGACY_ICON[iconId] ?? "generic";
17844
+ }
17845
+ /**
17846
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
17847
+ * The anti-drift guard cross-checks this against the eventful caps declared
17848
+ * in `packages/types/src/capabilities/*.cap.ts`.
17849
+ */
17850
+ var CAP_TO_KIND = {
17851
+ contact: "contact",
17852
+ motion: "motion-sensor",
17853
+ smoke: "smoke",
17854
+ flood: "flood",
17855
+ gas: "gas",
17856
+ "carbon-monoxide": "carbon-monoxide",
17857
+ vibration: "vibration",
17858
+ tamper: "tamper",
17859
+ presence: "presence",
17860
+ "enum-sensor": "enum-sensor",
17861
+ "event-emitter": "device-event",
17862
+ "lock-control": "lock",
17863
+ switch: "switch",
17864
+ button: "button",
17865
+ doorbell: "doorbell"
17866
+ };
17867
+ function buildDescriptor(capName, kind) {
17868
+ const t = EVENT_TAXONOMY[kind];
17869
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
17870
+ return {
17871
+ ...t,
17872
+ icon: legacyIcon(t.iconId)
17873
+ };
17874
+ }
17875
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
17876
+ /**
17369
17877
  * server-management — per-NODE singleton capability for a node's ROOT
17370
17878
  * package lifecycle (runtime-updatable node packages).
17371
17879
  *
@@ -18820,7 +19328,28 @@ var FaceInfoSchema = object({
18820
19328
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
18821
19329
  * track produced no key frame (e.g. native/onboard source) — the UI falls
18822
19330
  * back to the inline `base64` face crop. */
18823
- keyFrameMediaKey: string().optional()
19331
+ keyFrameMediaKey: string().optional(),
19332
+ /** Winning identity-match cosine (0..1) for this face's track, when an
19333
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
19334
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
19335
+ * faces that were never auto-recognized. */
19336
+ bestMatchScore: number().optional(),
19337
+ /** Native-scale face short side (px) at recognition time, when the runner
19338
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
19339
+ * legacy rows / runners that reported no native measure. */
19340
+ nativeFaceShortSidePx: number().optional(),
19341
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
19342
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
19343
+ * but blocked only by the recognition size floor). Mutually exclusive with
19344
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
19345
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
19346
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
19347
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
19348
+ suggestedIdentityId: string().optional(),
19349
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
19350
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
19351
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
19352
+ suggestedMatchScore: number().optional()
18824
19353
  });
18825
19354
  var FaceFilterEnum = _enum([
18826
19355
  "unassigned",
@@ -20863,36 +21392,6 @@ Object.freeze({
20863
21392
  addonId: null,
20864
21393
  access: "view"
20865
21394
  },
20866
- "advancedNotifier.deleteRule": {
20867
- capName: "advanced-notifier",
20868
- capScope: "system",
20869
- addonId: null,
20870
- access: "delete"
20871
- },
20872
- "advancedNotifier.getHistory": {
20873
- capName: "advanced-notifier",
20874
- capScope: "system",
20875
- addonId: null,
20876
- access: "view"
20877
- },
20878
- "advancedNotifier.getRules": {
20879
- capName: "advanced-notifier",
20880
- capScope: "system",
20881
- addonId: null,
20882
- access: "view"
20883
- },
20884
- "advancedNotifier.testRule": {
20885
- capName: "advanced-notifier",
20886
- capScope: "system",
20887
- addonId: null,
20888
- access: "create"
20889
- },
20890
- "advancedNotifier.upsertRule": {
20891
- capName: "advanced-notifier",
20892
- capScope: "system",
20893
- addonId: null,
20894
- access: "create"
20895
- },
20896
21395
  "alarmPanel.arm": {
20897
21396
  capName: "alarm-panel",
20898
21397
  capScope: "device",
@@ -23197,6 +23696,60 @@ Object.freeze({
23197
23696
  addonId: null,
23198
23697
  access: "create"
23199
23698
  },
23699
+ "notificationRules.createRule": {
23700
+ capName: "notification-rules",
23701
+ capScope: "system",
23702
+ addonId: null,
23703
+ access: "create"
23704
+ },
23705
+ "notificationRules.deleteRule": {
23706
+ capName: "notification-rules",
23707
+ capScope: "system",
23708
+ addonId: null,
23709
+ access: "delete"
23710
+ },
23711
+ "notificationRules.getConditionCatalog": {
23712
+ capName: "notification-rules",
23713
+ capScope: "system",
23714
+ addonId: null,
23715
+ access: "view"
23716
+ },
23717
+ "notificationRules.getHistory": {
23718
+ capName: "notification-rules",
23719
+ capScope: "system",
23720
+ addonId: null,
23721
+ access: "view"
23722
+ },
23723
+ "notificationRules.getRule": {
23724
+ capName: "notification-rules",
23725
+ capScope: "system",
23726
+ addonId: null,
23727
+ access: "view"
23728
+ },
23729
+ "notificationRules.listRules": {
23730
+ capName: "notification-rules",
23731
+ capScope: "system",
23732
+ addonId: null,
23733
+ access: "view"
23734
+ },
23735
+ "notificationRules.setRuleEnabled": {
23736
+ capName: "notification-rules",
23737
+ capScope: "system",
23738
+ addonId: null,
23739
+ access: "create"
23740
+ },
23741
+ "notificationRules.testRule": {
23742
+ capName: "notification-rules",
23743
+ capScope: "system",
23744
+ addonId: null,
23745
+ access: "create"
23746
+ },
23747
+ "notificationRules.updateRule": {
23748
+ capName: "notification-rules",
23749
+ capScope: "system",
23750
+ addonId: null,
23751
+ access: "create"
23752
+ },
23200
23753
  "notifier.cancel": {
23201
23754
  capName: "notifier",
23202
23755
  capScope: "device",