@camstack/addon-provider-onvif 1.2.3 → 1.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1134 -582
  2. package/dist/addon.mjs +1134 -582
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -3,7 +3,7 @@ import { createRequire } from "node:module";
3
3
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
4
4
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
5
5
  //#endregion
6
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
6
+ //#region ../types/dist/event-category-BLcNejAE.mjs
7
7
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
8
8
  EventCategory["SystemBoot"] = "system.boot";
9
9
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -153,9 +153,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
153
153
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
154
154
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
155
155
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
156
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
157
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
158
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
159
156
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
160
157
  * progress bar the client reconciles via `recordingExport.getExport`. */
161
158
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6820,7 +6817,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6820
6817
  patch: record(string(), unknown())
6821
6818
  }), object({ success: literal(true) });
6822
6819
  object({ deviceId: number() }), unknown().nullable();
6823
- /** Shorthand to define a method schema */
6824
6820
  function method(input, output, options) {
6825
6821
  return {
6826
6822
  input,
@@ -6828,6 +6824,7 @@ function method(input, output, options) {
6828
6824
  kind: options?.kind ?? "query",
6829
6825
  auth: options?.auth ?? "protected",
6830
6826
  ...options?.access !== void 0 ? { access: options.access } : {},
6827
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6831
6828
  timeoutMs: options?.timeoutMs
6832
6829
  };
6833
6830
  }
@@ -8193,6 +8190,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8193
8190
  /** The complete taxonomy dictionary, keyed by kind. */
8194
8191
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8195
8192
  /**
8193
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8194
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8195
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8196
+ * taxonomy surface (timeline, filters, event page).
8197
+ *
8198
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8199
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8200
+ * for the `classes` / `classesExclude` conditions.
8201
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8202
+ * the same class picker, grouped under an Audio header.
8203
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8204
+ * lock / …) for the `sensorKinds` device-event condition.
8205
+ *
8206
+ * Each entry carries `parentKind` so the client can group video subs under
8207
+ * their macro and sensor/control kinds under their category. This surface is
8208
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8209
+ * method, no codegen — so it ships train-free with an addon deploy.
8210
+ */
8211
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8212
+ var NcTaxonomyEntrySchema = object({
8213
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8214
+ kind: string(),
8215
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8216
+ label: string(),
8217
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8218
+ parentKind: string().nullable()
8219
+ });
8220
+ object({
8221
+ videoClasses: array(NcTaxonomyEntrySchema),
8222
+ audioKinds: array(NcTaxonomyEntrySchema),
8223
+ labels: array(NcTaxonomyEntrySchema)
8224
+ });
8225
+ function toEntry(kind, label, parentKind) {
8226
+ return {
8227
+ kind,
8228
+ label,
8229
+ parentKind
8230
+ };
8231
+ }
8232
+ /**
8233
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8234
+ * (macros before their subs), which the client relies on for stable grouping.
8235
+ */
8236
+ function buildNcTaxonomy() {
8237
+ const all = Object.values(EVENT_TAXONOMY);
8238
+ return {
8239
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8240
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8241
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8242
+ };
8243
+ }
8244
+ Object.freeze(buildNcTaxonomy());
8245
+ /**
8196
8246
  * Error types for the safe expression engine. Two distinct classes so callers
8197
8247
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8198
8248
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -11071,6 +11121,22 @@ var CameraMetricsSchema = object({
11071
11121
  ])
11072
11122
  });
11073
11123
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
11124
+ /**
11125
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
11126
+ * within the frame, so the executor can re-cut a leaf child ROI at native
11127
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
11128
+ */
11129
+ var NativeCropRefSchema = object({
11130
+ /** Handle keying the retained native surface (node-pinned to its owner). */
11131
+ handle: FrameHandleSchema,
11132
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
11133
+ cropFrameSpace: object({
11134
+ x: number(),
11135
+ y: number(),
11136
+ w: number(),
11137
+ h: number()
11138
+ })
11139
+ });
11074
11140
  var ModelFormatSchema$1 = _enum([
11075
11141
  "onnx",
11076
11142
  "coreml",
@@ -11346,7 +11412,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
11346
11412
  * Omitted ⇒ the runner's default device (current single-engine
11347
11413
  * behaviour). Selects WHICH device pool of the node runs the call.
11348
11414
  */
11349
- deviceKey: string().optional()
11415
+ deviceKey: string().optional(),
11416
+ /**
11417
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
11418
+ * when the parent crop was resolved from the frame's retained NATIVE
11419
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
11420
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
11421
+ * resolution from that surface — the SAME quality path faces already
11422
+ * had — instead of the downscaled parent tile. `handle` keys the native
11423
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
11424
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
11425
+ * the executor's crop-normalized child ROI back into frame-normalized
11426
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
11427
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
11428
+ * (today's behaviour on the fallback path).
11429
+ */
11430
+ nativeCropRef: NativeCropRefSchema.optional()
11350
11431
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
11351
11432
  engine: PipelineEngineChoiceSchema.optional(),
11352
11433
  steps: array(PipelineStepInputSchema).min(1),
@@ -11562,7 +11643,11 @@ var DetailResultSchema = object({
11562
11643
  bbox: NativeCropBboxSchema.optional(),
11563
11644
  embedding: string().optional(),
11564
11645
  label: string().optional(),
11565
- alignedCropJpeg: string().optional()
11646
+ alignedCropJpeg: string().optional(),
11647
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
11648
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
11649
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
11650
+ nativeFaceShortSidePx: number().optional()
11566
11651
  });
11567
11652
  /**
11568
11653
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -11576,6 +11661,12 @@ var motionCooldownMsField = {
11576
11661
  default: 3e4,
11577
11662
  step: 500
11578
11663
  };
11664
+ var maxSessionHoldMsField = {
11665
+ min: 0,
11666
+ max: 6e5,
11667
+ default: 12e4,
11668
+ step: 5e3
11669
+ };
11579
11670
  var motionFpsField = {
11580
11671
  min: 1,
11581
11672
  max: 30,
@@ -11723,6 +11814,19 @@ var RunnerCameraConfigSchema = object({
11723
11814
  "on-motion"
11724
11815
  ]).default("always-on"),
11725
11816
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
11817
+ /**
11818
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
11819
+ * detection session is active and ≥1 confirmed non-stationary track is
11820
+ * still live, the orchestrator keeps the session open past
11821
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
11822
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
11823
+ * ms since the session opened, after which it closes regardless. `0`
11824
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
11825
+ * runner itself — carried here so it shares the per-camera device-settings
11826
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
11827
+ * resolved `CameraDetectionConfig`.
11828
+ */
11829
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
11726
11830
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
11727
11831
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
11728
11832
  motionStreamId: string(),
@@ -11812,7 +11916,7 @@ var RunnerCameraConfigSchema = object({
11812
11916
  */
11813
11917
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
11814
11918
  });
11815
- 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;
11919
+ 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;
11816
11920
  /**
11817
11921
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
11818
11922
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -13960,94 +14064,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
13960
14064
  bundleUrl: string()
13961
14065
  });
13962
14066
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
13963
- var NotificationRuleConditionsSchema = object({
13964
- deviceIds: array(number()).readonly().optional(),
13965
- classNames: array(string()).readonly().optional(),
13966
- zoneIds: array(string()).readonly().optional(),
13967
- minConfidence: number().optional(),
13968
- source: _enum([
13969
- "pipeline",
13970
- "onboard",
13971
- "any"
13972
- ]).optional(),
13973
- schedule: object({
13974
- days: array(number()).readonly(),
13975
- startHour: number(),
13976
- endHour: number()
13977
- }).optional(),
13978
- cooldownSeconds: number().optional(),
13979
- minDwellSeconds: number().optional(),
13980
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
13981
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
13982
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
13983
- eventTypeTokens: array(string()).readonly().optional(),
13984
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
13985
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
13986
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
13987
- clipDescription: object({
13988
- text: string().min(1),
13989
- minSimilarity: number().min(0).max(1)
13990
- }).optional(),
13991
- /** Match events whose recognized-entity label (face identity name or plate
13992
- * vehicle name, propagated onto `event.data.label`) is one of these values.
13993
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
13994
- * vehicle/person> is seen". */
13995
- labels: array(string()).readonly().optional()
13996
- });
13997
- var NotificationRuleTemplateSchema = object({
13998
- title: string(),
13999
- body: string(),
14000
- imageMode: _enum([
14001
- "crop",
14002
- "annotated",
14003
- "full",
14004
- "none"
14005
- ])
14006
- });
14007
- var NotificationRuleSchema = object({
14008
- id: string(),
14009
- name: string(),
14010
- enabled: boolean(),
14011
- eventTypes: array(string()).readonly(),
14012
- conditions: NotificationRuleConditionsSchema,
14013
- outputs: array(string()).readonly(),
14014
- template: NotificationRuleTemplateSchema.optional(),
14015
- priority: _enum([
14016
- "low",
14017
- "normal",
14018
- "high",
14019
- "critical"
14020
- ])
14021
- });
14022
- var NotificationTestResultSchema = object({
14023
- ruleId: string(),
14024
- eventId: string(),
14025
- timestamp: number(),
14026
- wouldFire: boolean(),
14027
- reason: string().optional()
14028
- });
14029
- var NotificationHistoryEntrySchema = object({
14030
- id: string(),
14031
- ruleId: string(),
14032
- ruleName: string(),
14033
- eventId: string(),
14034
- timestamp: number(),
14035
- outputs: array(string()).readonly(),
14036
- success: boolean(),
14037
- error: string().optional(),
14038
- deviceId: number().optional()
14039
- });
14040
- var NotificationHistoryFilterSchema = object({
14041
- ruleId: string().optional(),
14042
- deviceId: number().optional(),
14043
- from: number().optional(),
14044
- to: number().optional(),
14045
- limit: number().optional()
14046
- });
14047
- 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({
14048
- ruleId: string(),
14049
- lookbackMinutes: number()
14050
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
14051
14067
  /**
14052
14068
  * Alerts capability — collection-based internal alert system.
14053
14069
  *
@@ -14234,89 +14250,6 @@ method(object({
14234
14250
  password: string()
14235
14251
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
14236
14252
  /**
14237
- * `login-method` — collection cap through which auth addons contribute
14238
- * their pre-auth login surfaces to the login page. This is the SINGLE,
14239
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
14240
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
14241
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
14242
- * procedure aggregates them for the unauthenticated login page.
14243
- *
14244
- * A contribution is a discriminated union on `kind`:
14245
- *
14246
- * - `redirect` — a declarative button. The login page renders a generic
14247
- * button that navigates to `startUrl` (an addon-owned HTTP route).
14248
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
14249
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
14250
- * login page needs NO change.
14251
- *
14252
- * - `widget` — a Module-Federation widget the login page mounts (via
14253
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
14254
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
14255
- * mechanism kept for future use; no shipped addon uses it on the login
14256
- * page (the passkey ceremony below runs natively in the shell instead).
14257
- *
14258
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
14259
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
14260
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
14261
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
14262
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
14263
- * fetching any remote code pre-auth. Contribution stays unconditional —
14264
- * enrollment state is never leaked pre-auth; visibility is a shell
14265
- * decision.
14266
- *
14267
- * Every contribution carries a `stage`:
14268
- * - `primary` — shown on the first credentials screen (OIDC /
14269
- * magic-link buttons; a future usernameless passkey).
14270
- * - `second-factor` — shown AFTER the password leg, gated on the
14271
- * returned `factors` (passkey-as-2FA today).
14272
- *
14273
- * `mount: skip` — the cap is read server-side by the core auth router
14274
- * (`registry.getCollection('login-method')`), never mounted as its own
14275
- * tRPC router.
14276
- */
14277
- /** When a login method renders in the two-phase login flow. */
14278
- var LoginStageEnum = _enum(["primary", "second-factor"]);
14279
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
14280
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
14281
- object({
14282
- kind: literal("redirect"),
14283
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
14284
- id: string(),
14285
- /** Operator-facing button label. */
14286
- label: string(),
14287
- /** lucide-react icon name. */
14288
- icon: string().optional(),
14289
- /** Addon-owned HTTP route the button navigates to (GET). */
14290
- startUrl: string(),
14291
- stage: LoginStageEnum
14292
- }),
14293
- object({
14294
- kind: literal("widget"),
14295
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
14296
- id: string(),
14297
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
14298
- addonId: string(),
14299
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
14300
- bundle: string(),
14301
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
14302
- remote: WidgetRemoteSchema,
14303
- stage: LoginStageEnum
14304
- }),
14305
- object({
14306
- kind: literal("passkey"),
14307
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
14308
- id: string(),
14309
- /** Operator-facing button label. */
14310
- label: string(),
14311
- stage: LoginStageEnum,
14312
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
14313
- rpId: string(),
14314
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
14315
- origin: string().nullable()
14316
- })
14317
- ]);
14318
- method(_void(), array(LoginMethodContributionSchema).readonly());
14319
- /**
14320
14253
  * Orchestrator-side destination metadata. The orchestrator computes
14321
14254
  * `id = <addonId>:<subId>` from its provider lookup so consumers
14322
14255
  * (admin UI, restore flow) see one canonical key.
@@ -15660,48 +15593,423 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
15660
15593
  kind: "mutation",
15661
15594
  auth: "admin"
15662
15595
  });
15663
- var LogLevelSchema = _enum([
15664
- "debug",
15665
- "info",
15666
- "warn",
15667
- "error"
15596
+ /**
15597
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15598
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15599
+ * caps stay wire-compatible without a circular cap→cap import.
15600
+ *
15601
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
15602
+ * every transport tier structurally, and failed calls still write usage rows.
15603
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15604
+ */
15605
+ var LlmUsageSchema = object({
15606
+ inputTokens: number(),
15607
+ outputTokens: number()
15608
+ });
15609
+ var LlmErrorCodeSchema = _enum([
15610
+ "timeout",
15611
+ "rate-limited",
15612
+ "auth",
15613
+ "refusal",
15614
+ "bad-request",
15615
+ "unavailable",
15616
+ "no-profile",
15617
+ "budget-exceeded",
15618
+ "adapter-error"
15668
15619
  ]);
15669
- var LogEntrySchema = object({
15670
- timestamp: date(),
15671
- level: LogLevelSchema,
15672
- scope: array(string()),
15620
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15621
+ ok: literal(true),
15622
+ text: string(),
15623
+ model: string(),
15624
+ usage: LlmUsageSchema,
15625
+ truncated: boolean(),
15626
+ latencyMs: number()
15627
+ }), object({
15628
+ ok: literal(false),
15629
+ code: LlmErrorCodeSchema,
15673
15630
  message: string(),
15674
- meta: record(string(), unknown()).optional(),
15675
- tags: record(string(), string()).optional()
15676
- });
15677
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15678
- scope: array(string()).optional(),
15679
- level: LogLevelSchema.optional(),
15680
- since: date().optional(),
15681
- until: date().optional(),
15682
- limit: number().optional(),
15683
- tags: record(string(), string()).optional()
15684
- }), array(LogEntrySchema).readonly());
15685
- var CpuBreakdownSchema = object({
15686
- total: number(),
15687
- user: number(),
15688
- system: number(),
15689
- irq: number(),
15690
- nice: number(),
15691
- loadAvg: tuple([
15692
- number(),
15693
- number(),
15694
- number()
15695
- ]),
15696
- cores: number()
15631
+ retryAfterMs: number().optional()
15632
+ })]);
15633
+ /**
15634
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15635
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15636
+ * notification-output.cap.ts:27-31 precedents).
15637
+ */
15638
+ var LlmImageSchema = object({
15639
+ bytes: _instanceof(Uint8Array),
15640
+ mimeType: string()
15697
15641
  });
15698
- var MemoryInfoSchema = object({
15699
- percent: number(),
15700
- totalBytes: number(),
15701
- usedBytes: number(),
15702
- availableBytes: number(),
15703
- swapUsedBytes: number(),
15704
- swapTotalBytes: number()
15642
+ var LlmGenerateBaseInputSchema = object({
15643
+ /** Collection routing (the notification-output posture). */
15644
+ addonId: string().optional(),
15645
+ /** Explicit profile; else the resolution chain (spec §3). */
15646
+ profileId: string().optional(),
15647
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15648
+ consumer: string(),
15649
+ system: string().optional(),
15650
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
15651
+ prompt: string(),
15652
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15653
+ jsonSchema: record(string(), unknown()).optional(),
15654
+ /** Per-call override of the profile default. */
15655
+ maxTokens: number().int().positive().optional(),
15656
+ temperature: number().optional()
15657
+ });
15658
+ /**
15659
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15660
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15661
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15662
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15663
+ * this only through the `llm` cap's methods.
15664
+ *
15665
+ * One running llama-server child per node in v1 (models are RAM-heavy).
15666
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15667
+ * watchdog — operator decision #3).
15668
+ */
15669
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
15670
+ object({
15671
+ kind: literal("catalog"),
15672
+ catalogId: string()
15673
+ }),
15674
+ object({
15675
+ kind: literal("url"),
15676
+ url: string(),
15677
+ sha256: string().optional()
15678
+ }),
15679
+ object({
15680
+ kind: literal("path"),
15681
+ path: string()
15682
+ })
15683
+ ]);
15684
+ var ManagedRuntimeConfigSchema = object({
15685
+ /** WHERE the runtime lives — hub or any agent. */
15686
+ nodeId: string(),
15687
+ /** Closed for v1; 'ollama' is a v2 candidate. */
15688
+ engine: _enum(["llama-cpp"]),
15689
+ model: ManagedModelRefSchema,
15690
+ contextSize: number().int().default(4096),
15691
+ /** 0 = CPU-only. */
15692
+ gpuLayers: number().int().default(0),
15693
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15694
+ threads: number().int().optional(),
15695
+ /** Concurrent slots. */
15696
+ parallel: number().int().default(1),
15697
+ /** Else lazy: first generate boots it. */
15698
+ autoStart: boolean().default(false),
15699
+ /** 0 = never; frees RAM after quiet periods. */
15700
+ idleStopMinutes: number().int().default(30)
15701
+ });
15702
+ var LlmRuntimeStatusSchema = object({
15703
+ /** Status is ALWAYS node-qualified. */
15704
+ nodeId: string(),
15705
+ state: _enum([
15706
+ "stopped",
15707
+ "downloading",
15708
+ "starting",
15709
+ "ready",
15710
+ "crashed",
15711
+ "failed"
15712
+ ]),
15713
+ pid: number().optional(),
15714
+ port: number().optional(),
15715
+ modelPath: string().optional(),
15716
+ modelId: string().optional(),
15717
+ downloadProgress: number().min(0).max(1).optional(),
15718
+ lastError: string().optional(),
15719
+ crashesInWindow: number(),
15720
+ /** Child RSS (sampled best-effort). */
15721
+ memoryBytes: number().optional(),
15722
+ vramBytes: number().optional()
15723
+ });
15724
+ var LlmNodeModelSchema = object({
15725
+ file: string(),
15726
+ sizeBytes: number(),
15727
+ catalogId: string().optional(),
15728
+ installedAt: number().optional()
15729
+ });
15730
+ var LlmRuntimeDiskUsageSchema = object({
15731
+ nodeId: string(),
15732
+ modelsBytes: number(),
15733
+ freeBytes: number().optional()
15734
+ });
15735
+ method(LlmGenerateBaseInputSchema.extend({
15736
+ images: array(LlmImageSchema).optional(),
15737
+ runtime: ManagedRuntimeConfigSchema,
15738
+ /** The managed profile's timeout, threaded by the hub provider. */
15739
+ timeoutMs: number().int().positive().optional()
15740
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15741
+ kind: "mutation",
15742
+ auth: "admin"
15743
+ }), method(object({}), _void(), {
15744
+ kind: "mutation",
15745
+ auth: "admin"
15746
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15747
+ kind: "mutation",
15748
+ auth: "admin"
15749
+ }), method(object({ file: string() }), _void(), {
15750
+ kind: "mutation",
15751
+ auth: "admin"
15752
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15753
+ /**
15754
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15755
+ * methods concat-fan across providers; single-row methods route to ONE
15756
+ * provider by the `addonId` in the call input (the notification-output
15757
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15758
+ * (hub-placed); the cap stays open for future providers.
15759
+ *
15760
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15761
+ * `apiKey` is a password field — providers REDACT it on read and merge on
15762
+ * write; a stored key NEVER round-trips to a client.
15763
+ */
15764
+ var LlmProfileKindSchema = _enum([
15765
+ "openai-compatible",
15766
+ "openai",
15767
+ "anthropic",
15768
+ "google",
15769
+ "managed-local"
15770
+ ]);
15771
+ var LlmProfileSchema = object({
15772
+ id: string(),
15773
+ name: string(),
15774
+ kind: LlmProfileKindSchema,
15775
+ /** Stamped by the provider — keeps the fanned catalog routable. */
15776
+ addonId: string(),
15777
+ enabled: boolean(),
15778
+ /** Vendor model id, or the managed runtime's loaded model. */
15779
+ model: string(),
15780
+ /** Required for openai-compatible; override for cloud kinds. */
15781
+ baseUrl: string().optional(),
15782
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
15783
+ apiKey: string().optional(),
15784
+ supportsVision: boolean(),
15785
+ temperature: number().min(0).max(2).optional(),
15786
+ maxTokens: number().int().positive().optional(),
15787
+ timeoutMs: number().int().positive().default(6e4),
15788
+ extraHeaders: record(string(), string()).optional(),
15789
+ /** kind === 'managed-local' only (spec §4). */
15790
+ runtime: ManagedRuntimeConfigSchema.optional()
15791
+ });
15792
+ /** ConfigUISchema tree passed through untyped on the wire (the
15793
+ * notification-output `ConfigSchemaPassthrough` precedent at
15794
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15795
+ var ConfigSchemaPassthrough$1 = unknown();
15796
+ var LlmProfileKindDescriptorSchema = object({
15797
+ kind: LlmProfileKindSchema,
15798
+ label: string(),
15799
+ icon: string(),
15800
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
15801
+ addonId: string(),
15802
+ configSchema: ConfigSchemaPassthrough$1
15803
+ });
15804
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15805
+ var LlmDefaultSchema = object({
15806
+ selector: LlmDefaultSelectorSchema,
15807
+ profileId: string()
15808
+ });
15809
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
15810
+ var LlmUsageRollupSchema = object({
15811
+ day: string(),
15812
+ consumer: string(),
15813
+ profileId: string(),
15814
+ calls: number(),
15815
+ okCalls: number(),
15816
+ errorCalls: number(),
15817
+ inputTokens: number(),
15818
+ outputTokens: number(),
15819
+ avgLatencyMs: number()
15820
+ });
15821
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15822
+ var ManagedModelCatalogEntrySchema = object({
15823
+ id: string(),
15824
+ label: string(),
15825
+ family: string(),
15826
+ purpose: _enum(["text", "vision"]),
15827
+ url: string(),
15828
+ sha256: string(),
15829
+ sizeBytes: number(),
15830
+ quantization: string(),
15831
+ /** Load-time guidance shown in the picker. */
15832
+ minRamBytes: number(),
15833
+ contextSizeDefault: number().int(),
15834
+ /** Vision models: companion projector file. */
15835
+ mmprojUrl: string().optional()
15836
+ });
15837
+ var LlmRuntimeNodeSchema = object({
15838
+ nodeId: string(),
15839
+ reachable: boolean(),
15840
+ status: LlmRuntimeStatusSchema.optional(),
15841
+ disk: LlmRuntimeDiskUsageSchema.optional(),
15842
+ error: string().optional()
15843
+ });
15844
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
15845
+ var ProfileRefInputSchema = object({
15846
+ addonId: string(),
15847
+ profileId: string()
15848
+ });
15849
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
15850
+ kind: "mutation",
15851
+ auth: "admin"
15852
+ }), method(ProfileRefInputSchema, _void(), {
15853
+ kind: "mutation",
15854
+ auth: "admin"
15855
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
15856
+ kind: "mutation",
15857
+ auth: "admin"
15858
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
15859
+ selector: LlmDefaultSelectorSchema,
15860
+ profileId: string().nullable()
15861
+ }), _void(), {
15862
+ kind: "mutation",
15863
+ auth: "admin"
15864
+ }), method(object({
15865
+ since: number().optional(),
15866
+ until: number().optional(),
15867
+ consumer: string().optional(),
15868
+ profileId: string().optional()
15869
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
15870
+ nodeId: string(),
15871
+ model: ManagedModelRefSchema
15872
+ }), _void(), {
15873
+ kind: "mutation",
15874
+ auth: "admin"
15875
+ }), method(object({
15876
+ nodeId: string(),
15877
+ file: string()
15878
+ }), _void(), {
15879
+ kind: "mutation",
15880
+ auth: "admin"
15881
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
15882
+ kind: "mutation",
15883
+ auth: "admin"
15884
+ }), method(ProfileRefInputSchema, _void(), {
15885
+ kind: "mutation",
15886
+ auth: "admin"
15887
+ });
15888
+ var LogLevelSchema = _enum([
15889
+ "debug",
15890
+ "info",
15891
+ "warn",
15892
+ "error"
15893
+ ]);
15894
+ var LogEntrySchema = object({
15895
+ timestamp: date(),
15896
+ level: LogLevelSchema,
15897
+ scope: array(string()),
15898
+ message: string(),
15899
+ meta: record(string(), unknown()).optional(),
15900
+ tags: record(string(), string()).optional()
15901
+ });
15902
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15903
+ scope: array(string()).optional(),
15904
+ level: LogLevelSchema.optional(),
15905
+ since: date().optional(),
15906
+ until: date().optional(),
15907
+ limit: number().optional(),
15908
+ tags: record(string(), string()).optional()
15909
+ }), array(LogEntrySchema).readonly());
15910
+ /**
15911
+ * `login-method` — collection cap through which auth addons contribute
15912
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
15913
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
15914
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
15915
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
15916
+ * procedure aggregates them for the unauthenticated login page.
15917
+ *
15918
+ * A contribution is a discriminated union on `kind`:
15919
+ *
15920
+ * - `redirect` — a declarative button. The login page renders a generic
15921
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
15922
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
15923
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
15924
+ * login page needs NO change.
15925
+ *
15926
+ * - `widget` — a Module-Federation widget the login page mounts (via
15927
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
15928
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
15929
+ * mechanism kept for future use; no shipped addon uses it on the login
15930
+ * page (the passkey ceremony below runs natively in the shell instead).
15931
+ *
15932
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
15933
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
15934
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
15935
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
15936
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
15937
+ * fetching any remote code pre-auth. Contribution stays unconditional —
15938
+ * enrollment state is never leaked pre-auth; visibility is a shell
15939
+ * decision.
15940
+ *
15941
+ * Every contribution carries a `stage`:
15942
+ * - `primary` — shown on the first credentials screen (OIDC /
15943
+ * magic-link buttons; a future usernameless passkey).
15944
+ * - `second-factor` — shown AFTER the password leg, gated on the
15945
+ * returned `factors` (passkey-as-2FA today).
15946
+ *
15947
+ * `mount: skip` — the cap is read server-side by the core auth router
15948
+ * (`registry.getCollection('login-method')`), never mounted as its own
15949
+ * tRPC router.
15950
+ */
15951
+ /** When a login method renders in the two-phase login flow. */
15952
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
15953
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
15954
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
15955
+ object({
15956
+ kind: literal("redirect"),
15957
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
15958
+ id: string(),
15959
+ /** Operator-facing button label. */
15960
+ label: string(),
15961
+ /** lucide-react icon name. */
15962
+ icon: string().optional(),
15963
+ /** Addon-owned HTTP route the button navigates to (GET). */
15964
+ startUrl: string(),
15965
+ stage: LoginStageEnum
15966
+ }),
15967
+ object({
15968
+ kind: literal("widget"),
15969
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
15970
+ id: string(),
15971
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
15972
+ addonId: string(),
15973
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
15974
+ bundle: string(),
15975
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
15976
+ remote: WidgetRemoteSchema,
15977
+ stage: LoginStageEnum
15978
+ }),
15979
+ object({
15980
+ kind: literal("passkey"),
15981
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
15982
+ id: string(),
15983
+ /** Operator-facing button label. */
15984
+ label: string(),
15985
+ stage: LoginStageEnum,
15986
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
15987
+ rpId: string(),
15988
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
15989
+ origin: string().nullable()
15990
+ })
15991
+ ]);
15992
+ method(_void(), array(LoginMethodContributionSchema).readonly());
15993
+ var CpuBreakdownSchema = object({
15994
+ total: number(),
15995
+ user: number(),
15996
+ system: number(),
15997
+ irq: number(),
15998
+ nice: number(),
15999
+ loadAvg: tuple([
16000
+ number(),
16001
+ number(),
16002
+ number()
16003
+ ]),
16004
+ cores: number()
16005
+ });
16006
+ var MemoryInfoSchema = object({
16007
+ percent: number(),
16008
+ totalBytes: number(),
16009
+ usedBytes: number(),
16010
+ availableBytes: number(),
16011
+ swapUsedBytes: number(),
16012
+ swapTotalBytes: number()
15705
16013
  });
15706
16014
  var DiskIoSnapshotSchema = object({
15707
16015
  readBytes: number(),
@@ -16154,14 +16462,14 @@ var TargetKindCapsSchema = object({
16154
16462
  * the union is large and not meant for runtime validation here; the exported
16155
16463
  * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
16156
16464
  */
16157
- var ConfigSchemaPassthrough$1 = unknown();
16465
+ var ConfigSchemaPassthrough = unknown();
16158
16466
  var TargetKindSchema = object({
16159
16467
  kind: string(),
16160
16468
  label: string(),
16161
16469
  icon: string(),
16162
16470
  /** Stamped by each provider so the concat-fanned catalog stays routable. */
16163
16471
  addonId: string(),
16164
- configSchema: ConfigSchemaPassthrough$1,
16472
+ configSchema: ConfigSchemaPassthrough,
16165
16473
  supportsDiscovery: boolean(),
16166
16474
  caps: TargetKindCapsSchema
16167
16475
  });
@@ -16214,297 +16522,493 @@ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSche
16214
16522
  enabled: boolean()
16215
16523
  }), _void(), { kind: "mutation" });
16216
16524
  /**
16217
- * Shared LLM generate contracts imported by BOTH `llm.cap.ts` (consumer
16218
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
16219
- * caps stay wire-compatible without a circular cap→cap import.
16525
+ * notification-rules the Notification Center rule surface (P1 core).
16220
16526
  *
16221
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
16222
- * every transport tier structurally, and failed calls still write usage rows.
16223
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
16224
- */
16225
- var LlmUsageSchema = object({
16226
- inputTokens: number(),
16227
- outputTokens: number()
16228
- });
16229
- var LlmErrorCodeSchema = _enum([
16230
- "timeout",
16231
- "rate-limited",
16232
- "auth",
16233
- "refusal",
16234
- "bad-request",
16235
- "unavailable",
16236
- "no-profile",
16237
- "budget-exceeded",
16238
- "adapter-error"
16239
- ]);
16240
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
16241
- ok: literal(true),
16242
- text: string(),
16243
- model: string(),
16244
- usage: LlmUsageSchema,
16245
- truncated: boolean(),
16246
- latencyMs: number()
16247
- }), object({
16248
- ok: literal(false),
16249
- code: LlmErrorCodeSchema,
16250
- message: string(),
16251
- retryAfterMs: number().optional()
16252
- })]);
16527
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16528
+ * (operator decisions D-1/D-2/D-3 are binding):
16529
+ *
16530
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16531
+ * `notification-center` module), hooked on the durable persistence
16532
+ * moments (object-event insert, TrackCloser.closeExpired) with a
16533
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
16534
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16535
+ * FIRST persisted detection matching the conditions (per-track dedup,
16536
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16537
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
16538
+ * - DISPATCH stays behind `notification-output` (rules reference targets
16539
+ * by id; per-backend params are a passthrough blob capped by the
16540
+ * target kind's own caps/degrade engine).
16541
+ *
16542
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
16543
+ * server-injected caller identity — the first `caller: 'required'`
16544
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
16545
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
16546
+ * windows, and the optional label/identity/plate matchers. User rules,
16547
+ * private zones, per-recipient fan-out and the wider condition table are
16548
+ * P2+ (see spec §7).
16549
+ *
16550
+ * All schemas here are the single source of truth — `NcRule` etc. are
16551
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16552
+ * schema/interface drift is explicitly not repeated).
16553
+ */
16253
16554
  /**
16254
- * `Uint8Array` is the sanctioned binary conventionsuperjson + the UDS
16255
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
16256
- * notification-output.cap.ts:27-31 precedents).
16555
+ * D-3: the trigger/urgency of a rule which persistence moment evaluates it.
16556
+ * The value maps 1:1 onto the evaluated record kind:
16557
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16558
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16559
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16560
+ * change of a LINKED device, one row per linked camera)
16561
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16562
+ * delivery / pick-up)
16563
+ *
16564
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16565
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
16566
+ * this one field keeps the schema additive — a rule still declares exactly
16567
+ * one trigger.
16257
16568
  */
16258
- var LlmImageSchema = object({
16259
- bytes: _instanceof(Uint8Array),
16260
- mimeType: string()
16569
+ var NcDeliverySchema = _enum([
16570
+ "immediate",
16571
+ "track-end",
16572
+ "device-event",
16573
+ "package-event"
16574
+ ]);
16575
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
16576
+ var NcScheduleSchema = object({
16577
+ windows: array(object({
16578
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16579
+ days: array(number().int().min(0).max(6)).min(1),
16580
+ startMinute: number().int().min(0).max(1439),
16581
+ endMinute: number().int().min(0).max(1439)
16582
+ })).min(1),
16583
+ /** IANA timezone; default = hub host timezone. */
16584
+ timezone: string().optional(),
16585
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16586
+ invert: boolean().optional()
16261
16587
  });
16262
- var LlmGenerateBaseInputSchema = object({
16263
- /** Collection routing (the notification-output posture). */
16264
- addonId: string().optional(),
16265
- /** Explicit profile; else the resolution chain (spec §3). */
16266
- profileId: string().optional(),
16267
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
16268
- consumer: string(),
16269
- system: string().optional(),
16270
- /** v1: single-turn. `messages[]` is a v2 additive field. */
16271
- prompt: string(),
16272
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
16273
- jsonSchema: record(string(), unknown()).optional(),
16274
- /** Per-call override of the profile default. */
16275
- maxTokens: number().int().positive().optional(),
16276
- temperature: number().optional()
16588
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16589
+ var NcPlateMatcherSchema = object({
16590
+ values: array(string().min(1)).min(1),
16591
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16592
+ maxDistance: number().int().min(0).max(3).default(1)
16277
16593
  });
16278
16594
  /**
16279
- * `llm-runtime` node-side managed llama.cpp executor (spec §4). Registered
16280
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
16281
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` normal
16282
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
16283
- * this only through the `llm` cap's methods.
16284
- *
16285
- * One running llama-server child per node in v1 (models are RAM-heavy).
16286
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
16287
- * watchdog operator decision #3).
16595
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16596
+ * occupancy edge for a device optionally narrowed to a single admin
16597
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16598
+ * - `became-occupied` (default) count crossed 0 `count`
16599
+ * - `became-free` — count crossed `count` below it
16600
+ * - `>=` / `<=` — count is at/over or at/under `count`
16601
+ * `sustainSeconds` requires the condition hold continuously that long
16602
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
16603
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16604
+ * the condition never matches. Confirmed edge-state survives addon restarts
16605
+ * (declared SQLite collection, reseeded on boot).
16288
16606
  */
16289
- var ManagedModelRefSchema = discriminatedUnion("kind", [
16290
- object({
16291
- kind: literal("catalog"),
16292
- catalogId: string()
16293
- }),
16294
- object({
16295
- kind: literal("url"),
16296
- url: string(),
16297
- sha256: string().optional()
16298
- }),
16299
- object({
16300
- kind: literal("path"),
16301
- path: string()
16302
- })
16303
- ]);
16304
- var ManagedRuntimeConfigSchema = object({
16305
- /** WHERE the runtime lives — hub or any agent. */
16306
- nodeId: string(),
16307
- /** Closed for v1; 'ollama' is a v2 candidate. */
16308
- engine: _enum(["llama-cpp"]),
16309
- model: ManagedModelRefSchema,
16310
- contextSize: number().int().default(4096),
16311
- /** 0 = CPU-only. */
16312
- gpuLayers: number().int().default(0),
16313
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
16314
- threads: number().int().optional(),
16315
- /** Concurrent slots. */
16316
- parallel: number().int().default(1),
16317
- /** Else lazy: first generate boots it. */
16318
- autoStart: boolean().default(false),
16319
- /** 0 = never; frees RAM after quiet periods. */
16320
- idleStopMinutes: number().int().default(30)
16607
+ var NcOccupancyConditionSchema = object({
16608
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16609
+ zoneId: string().optional(),
16610
+ /** Object class to count; absent = any class. */
16611
+ className: string().optional(),
16612
+ op: _enum([
16613
+ "became-occupied",
16614
+ "became-free",
16615
+ ">=",
16616
+ "<="
16617
+ ]).default("became-occupied"),
16618
+ count: number().int().min(0).default(1),
16619
+ sustainSeconds: number().int().min(0).max(3600).default(15)
16620
+ });
16621
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16622
+ var NcZoneConditionSchema = object({
16623
+ ids: array(string().min(1)).min(1),
16624
+ /** Quantifier over `ids` — at least one / every one visited. */
16625
+ match: _enum(["any", "all"]).default("any")
16321
16626
  });
16322
- var LlmRuntimeStatusSchema = object({
16323
- /** Status is ALWAYS node-qualified. */
16324
- nodeId: string(),
16325
- state: _enum([
16326
- "stopped",
16327
- "downloading",
16328
- "starting",
16329
- "ready",
16330
- "crashed",
16331
- "failed"
16332
- ]),
16333
- pid: number().optional(),
16334
- port: number().optional(),
16335
- modelPath: string().optional(),
16336
- modelId: string().optional(),
16337
- downloadProgress: number().min(0).max(1).optional(),
16338
- lastError: string().optional(),
16339
- crashesInWindow: number(),
16340
- /** Child RSS (sampled best-effort). */
16341
- memoryBytes: number().optional(),
16342
- vramBytes: number().optional()
16627
+ /**
16628
+ * The P1 condition set — a flat AND of groups; absent group = pass;
16629
+ * membership lists are OR within the list (spec §2.3).
16630
+ */
16631
+ var NcConditionsSchema = object({
16632
+ /** Device scope — absent = all devices. */
16633
+ devices: array(number()).optional(),
16634
+ /** Detector class names (any overlap with the record's class set). */
16635
+ classes: array(string().min(1)).optional(),
16636
+ /** Veto classes — any overlap fails the rule. */
16637
+ classesExclude: array(string().min(1)).optional(),
16638
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
16639
+ minConfidence: number().min(0).max(1).optional(),
16640
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
16641
+ zones: NcZoneConditionSchema.optional(),
16642
+ /** Veto zones — any hit fails the rule. */
16643
+ zonesExclude: array(string().min(1)).optional(),
16644
+ /**
16645
+ * Exact (case-insensitive) match on the record's collapsed `label`
16646
+ * (identity name / plate text / subclass).
16647
+ */
16648
+ labelEquals: array(string().min(1)).optional(),
16649
+ /**
16650
+ * Identity matcher. P1 boundary: matched against the record's collapsed
16651
+ * `label` (the identity display name propagated by the face pipeline) —
16652
+ * identity-ID matching rides in P2 when identity ids reach the record.
16653
+ */
16654
+ identities: array(string().min(1)).optional(),
16655
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
16656
+ plates: NcPlateMatcherSchema.optional(),
16657
+ /**
16658
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16659
+ * Same P1 boundary: matched against the record's collapsed `label` (the
16660
+ * identity display name). A record with NO label passes (nothing to
16661
+ * exclude), unlike the include variant which fails on an absent label.
16662
+ */
16663
+ identitiesExclude: array(string().min(1)).optional(),
16664
+ /**
16665
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16666
+ * TRACK-END only: importance is scored at track close, so it does not exist
16667
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16668
+ * close the value is threaded via the close-time info (the `Track` clone is
16669
+ * captured before the DB row is updated, so it would otherwise read stale).
16670
+ * Fails when the record carries no importance (never guess quality — the
16671
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
16672
+ */
16673
+ minImportance: number().min(0).max(1).optional(),
16674
+ /**
16675
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16676
+ * TRACK-END only: an `immediate` / object-event subject has no closed
16677
+ * lifespan, so a dwell condition never matches immediate delivery
16678
+ * (documented choice — the object-event record carries no `firstSeen`,
16679
+ * so dwell cannot be computed from what the subject actually carries).
16680
+ */
16681
+ minDwellSeconds: number().min(0).optional(),
16682
+ /**
16683
+ * Detection provenance filter. `any` (default / absent) matches every
16684
+ * source; otherwise the subject's source must equal it. Legacy records
16685
+ * with no stamped source are treated as `pipeline`. The union spans both
16686
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
16687
+ * tracks carry `sensor`.
16688
+ */
16689
+ source: _enum([
16690
+ "pipeline",
16691
+ "onboard",
16692
+ "sensor",
16693
+ "any"
16694
+ ]).optional(),
16695
+ /**
16696
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16697
+ * detector `minConfidence` (that gates the object-detection score; this
16698
+ * gates the recognition/OCR match score). Fails when the subject carries
16699
+ * no label-match confidence (never guess). TRACK-END only: the confidence
16700
+ * lives on the recognition result and reaches the subject at track close.
16701
+ *
16702
+ * What it measures precisely (plumbed at track close — the closer threads
16703
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16704
+ * `importance`): the BEST recognition match confidence observed for the
16705
+ * label the track carries at close — for a face, the peak cosine similarity
16706
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16707
+ * for a plate, the peak OCR read score of the best-held plate
16708
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16709
+ * one track the higher of the two is used. A track that ended with no
16710
+ * confident identity/plate match carries no value, so the condition fails
16711
+ * closed for it (an un-recognized subject).
16712
+ */
16713
+ minLabelConfidence: number().min(0).max(1).optional(),
16714
+ /**
16715
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16716
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16717
+ * against the token carried on the device-event subject (extracted from the
16718
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16719
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16720
+ * eventType, so gate those with {@link sensorKinds} instead.
16721
+ */
16722
+ eventTypeTokens: array(string().min(1)).optional(),
16723
+ /**
16724
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16725
+ * `contact`, `button`, `device-event`) — matched against the persisted
16726
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16727
+ */
16728
+ sensorKinds: array(string().min(1)).optional(),
16729
+ /**
16730
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16731
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16732
+ * when the subject's phase does not match (a subject always carries a phase
16733
+ * on the package-event trigger).
16734
+ */
16735
+ packagePhase: _enum([
16736
+ "delivered",
16737
+ "picked-up",
16738
+ "both"
16739
+ ]).optional(),
16740
+ /**
16741
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16742
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16743
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
16744
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16745
+ */
16746
+ customZones: array(MaskPolygonShapeSchema).optional(),
16747
+ /**
16748
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16749
+ * (optionally zone/class-scoped) occupancy count crosses the configured
16750
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
16751
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16752
+ */
16753
+ occupancy: NcOccupancyConditionSchema.optional()
16343
16754
  });
16344
- var LlmNodeModelSchema = object({
16345
- file: string(),
16346
- sizeBytes: number(),
16347
- catalogId: string().optional(),
16348
- installedAt: number().optional()
16755
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
16756
+ var NcRuleTargetSchema = object({
16757
+ /** `notification-output` Target id. */
16758
+ targetId: string().min(1),
16759
+ /**
16760
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
16761
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16762
+ * degrade engine drops what the backend can't render.
16763
+ */
16764
+ params: record(string(), unknown()).optional()
16349
16765
  });
16350
- var LlmRuntimeDiskUsageSchema = object({
16351
- nodeId: string(),
16352
- modelsBytes: number(),
16353
- freeBytes: number().optional()
16766
+ /**
16767
+ * Media attachment policy (P1 still-image subset).
16768
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
16769
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
16770
+ * matched on identities attaches the subject's `faceCrop`, one matched on
16771
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
16772
+ * (or when the specific crop is missing) degrades to `best`, then
16773
+ * `keyFrame`, then no attachment — never delaying the send. The matched
16774
+ * condition summary is frozen on the outbox row at enqueue (like the rule
16775
+ * name), so the choice never drifts from the record that fired it.
16776
+ * - `keyFrame` — the clean scene frame (no subject box).
16777
+ * - `none` — no attachment.
16778
+ */
16779
+ var NcMediaPolicySchema = object({ attach: _enum([
16780
+ "best",
16781
+ "best-matching",
16782
+ "keyFrame",
16783
+ "none"
16784
+ ]).default("best") });
16785
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16786
+ var NcThrottleSchema = object({
16787
+ cooldownSec: number().int().min(0).max(86400).default(60),
16788
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16789
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
16790
+ });
16791
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16792
+ var NcRuleInputSchema = object({
16793
+ name: string().min(1).max(200),
16794
+ enabled: boolean().default(true),
16795
+ delivery: NcDeliverySchema,
16796
+ conditions: NcConditionsSchema.default({}),
16797
+ schedule: NcScheduleSchema.optional(),
16798
+ targets: array(NcRuleTargetSchema).min(1),
16799
+ media: NcMediaPolicySchema.default({ attach: "best" }),
16800
+ throttle: NcThrottleSchema.default({
16801
+ cooldownSec: 60,
16802
+ scope: "rule-device"
16803
+ }),
16804
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16805
+ template: object({
16806
+ title: string().max(500).optional(),
16807
+ body: string().max(2e3).optional()
16808
+ }).optional(),
16809
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
16810
+ priority: number().int().min(1).max(5).default(3),
16811
+ /**
16812
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16813
+ * behaviour, visible to all, read-only in the viewer). Present = personal
16814
+ * rule owned by this userId. Server-stamped; never trusted from a client.
16815
+ */
16816
+ ownerUserId: string().optional()
16354
16817
  });
16355
- method(LlmGenerateBaseInputSchema.extend({
16356
- images: array(LlmImageSchema).optional(),
16357
- runtime: ManagedRuntimeConfigSchema,
16358
- /** The managed profile's timeout, threaded by the hub provider. */
16359
- timeoutMs: number().int().positive().optional()
16360
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
16361
- kind: "mutation",
16362
- auth: "admin"
16363
- }), method(object({}), _void(), {
16364
- kind: "mutation",
16365
- auth: "admin"
16366
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
16367
- kind: "mutation",
16368
- auth: "admin"
16369
- }), method(object({ file: string() }), _void(), {
16370
- kind: "mutation",
16371
- auth: "admin"
16372
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
16373
16818
  /**
16374
- * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
16375
- * methods concat-fan across providers; single-row methods route to ONE
16376
- * provider by the `addonId` in the call input (the notification-output
16377
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
16378
- * (hub-placed); the cap stays open for future providers.
16379
- *
16380
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
16381
- * `apiKey` is a password field — providers REDACT it on read and merge on
16382
- * write; a stored key NEVER round-trips to a client.
16819
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
16820
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16821
+ * NOT a client-authored input field (it lives on the persisted rule, not the
16822
+ * input), so it is added here explicitly to let the store's per-target opt-out
16823
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16824
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16825
+ * `updateRule` patch.
16383
16826
  */
16384
- var LlmProfileKindSchema = _enum([
16385
- "openai-compatible",
16386
- "openai",
16387
- "anthropic",
16388
- "google",
16389
- "managed-local"
16390
- ]);
16391
- var LlmProfileSchema = object({
16827
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
16828
+ /** A persisted rule. */
16829
+ var NcRuleSchema = NcRuleInputSchema.extend({
16392
16830
  id: string(),
16393
- name: string(),
16394
- kind: LlmProfileKindSchema,
16395
- /** Stamped by the provider — keeps the fanned catalog routable. */
16396
- addonId: string(),
16397
- enabled: boolean(),
16398
- /** Vendor model id, or the managed runtime's loaded model. */
16399
- model: string(),
16400
- /** Required for openai-compatible; override for cloud kinds. */
16401
- baseUrl: string().optional(),
16402
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
16403
- apiKey: string().optional(),
16404
- supportsVision: boolean(),
16405
- temperature: number().min(0).max(2).optional(),
16406
- maxTokens: number().int().positive().optional(),
16407
- timeoutMs: number().int().positive().default(6e4),
16408
- extraHeaders: record(string(), string()).optional(),
16409
- /** kind === 'managed-local' only (spec §4). */
16410
- runtime: ManagedRuntimeConfigSchema.optional()
16411
- });
16412
- /** ConfigUISchema tree passed through untyped on the wire (the
16413
- * notification-output `ConfigSchemaPassthrough` precedent at
16414
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
16415
- var ConfigSchemaPassthrough = unknown();
16416
- var LlmProfileKindDescriptorSchema = object({
16417
- kind: LlmProfileKindSchema,
16418
- label: string(),
16419
- icon: string(),
16420
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
16421
- addonId: string(),
16422
- configSchema: ConfigSchemaPassthrough
16423
- });
16424
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
16425
- var LlmDefaultSchema = object({
16426
- selector: LlmDefaultSelectorSchema,
16427
- profileId: string()
16831
+ /** userId of the admin who created the rule (server-stamped caller). */
16832
+ createdBy: string(),
16833
+ createdAt: number(),
16834
+ updatedAt: number(),
16835
+ /**
16836
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16837
+ * send time. Only a target's OWNER may add/remove its id (server-checked
16838
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
16839
+ */
16840
+ disabledTargetIds: array(string()).default([])
16428
16841
  });
16429
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
16430
- var LlmUsageRollupSchema = object({
16431
- day: string(),
16432
- consumer: string(),
16433
- profileId: string(),
16434
- calls: number(),
16435
- okCalls: number(),
16436
- errorCalls: number(),
16437
- inputTokens: number(),
16438
- outputTokens: number(),
16439
- avgLatencyMs: number()
16842
+ var NcTestResultSchema = object({
16843
+ recordId: string(),
16844
+ recordKind: _enum([
16845
+ "object-event",
16846
+ "track",
16847
+ "device-event",
16848
+ "package-event"
16849
+ ]),
16850
+ deviceId: number(),
16851
+ timestamp: number(),
16852
+ wouldFire: boolean(),
16853
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
16854
+ failedCondition: string().optional(),
16855
+ className: string().optional(),
16856
+ label: string().optional()
16440
16857
  });
16441
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
16442
- var ManagedModelCatalogEntrySchema = object({
16858
+ var NcConditionDescriptorSchema = object({
16859
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16443
16860
  id: string(),
16861
+ group: _enum([
16862
+ "scope",
16863
+ "class",
16864
+ "zones",
16865
+ "quality",
16866
+ "label",
16867
+ "schedule",
16868
+ "device",
16869
+ "package",
16870
+ "occupancy"
16871
+ ]),
16444
16872
  label: string(),
16445
- family: string(),
16446
- purpose: _enum(["text", "vision"]),
16447
- url: string(),
16448
- sha256: string(),
16449
- sizeBytes: number(),
16450
- quantization: string(),
16451
- /** Load-time guidance shown in the picker. */
16452
- minRamBytes: number(),
16453
- contextSizeDefault: number().int(),
16454
- /** Vision models: companion projector file. */
16455
- mmprojUrl: string().optional()
16873
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
16874
+ valueType: _enum([
16875
+ "deviceIdList",
16876
+ "stringList",
16877
+ "number01",
16878
+ "number",
16879
+ "sourceSelect",
16880
+ "zoneSelection",
16881
+ "zoneIdList",
16882
+ "schedule",
16883
+ "plateMatcher",
16884
+ "packagePhase",
16885
+ "polygonDraw",
16886
+ "occupancy"
16887
+ ]),
16888
+ operator: _enum([
16889
+ "in",
16890
+ "notIn",
16891
+ "anyOf",
16892
+ "allOf",
16893
+ "gte",
16894
+ "fuzzyIn",
16895
+ "withinSchedule"
16896
+ ]),
16897
+ /** Which delivery kinds the condition applies to. */
16898
+ appliesTo: array(NcDeliverySchema),
16899
+ phase: string(),
16900
+ description: string().optional()
16456
16901
  });
16457
- var LlmRuntimeNodeSchema = object({
16458
- nodeId: string(),
16459
- reachable: boolean(),
16460
- status: LlmRuntimeStatusSchema.optional(),
16461
- disk: LlmRuntimeDiskUsageSchema.optional(),
16462
- error: string().optional()
16902
+ /**
16903
+ * The delivery lifecycle status of a history row — a straight read of the
16904
+ * durable outbox row's own status (single source of truth):
16905
+ * - `pending` — enqueued, in-flight or retrying with backoff
16906
+ * - `sent` — delivered (terminal)
16907
+ * - `dead` — dead-lettered after exhausting retries / a permanent
16908
+ * backend rejection / a deleted target (terminal; carries
16909
+ * the failure `error`)
16910
+ *
16911
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
16912
+ * user dimension (quiet hours / snooze) and are additive when they land.
16913
+ */
16914
+ var NcHistoryStatusSchema = _enum([
16915
+ "pending",
16916
+ "sent",
16917
+ "dead"
16918
+ ]);
16919
+ /** The evaluated record kind a history row descends from (one per trigger). */
16920
+ var NcHistoryRecordKindSchema = _enum([
16921
+ "object-event",
16922
+ "track-end",
16923
+ "device-event",
16924
+ "package-event"
16925
+ ]);
16926
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16927
+ var NcHistorySubjectSchema = object({
16928
+ className: string(),
16929
+ label: string().optional(),
16930
+ confidence: number().optional(),
16931
+ zones: array(string()),
16932
+ timestamp: number()
16933
+ });
16934
+ /**
16935
+ * One delivery-history row. This is a read-only VIEW over the durable
16936
+ * outbox row (single source of truth — the same row the drain loop drives;
16937
+ * NO second write path, so history can never drift from delivery state).
16938
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16939
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16940
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
16941
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16942
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16943
+ * P1 (admin scope only).
16944
+ */
16945
+ var NcHistoryEntrySchema = object({
16946
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16947
+ id: string(),
16948
+ ruleId: string(),
16949
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
16950
+ ruleName: string(),
16951
+ /** The rule urgency/trigger that produced this delivery. */
16952
+ delivery: NcDeliverySchema,
16953
+ targetId: string(),
16954
+ deviceId: number(),
16955
+ recordKind: NcHistoryRecordKindSchema,
16956
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16957
+ recordId: string(),
16958
+ /** Present for track-scoped deliveries (object-event / track-end). */
16959
+ trackId: string().optional(),
16960
+ status: NcHistoryStatusSchema,
16961
+ /** Delivery attempts made so far. */
16962
+ attempts: number().int(),
16963
+ /** Fire time (outbox enqueue). */
16964
+ createdAt: number(),
16965
+ /** Last transition time (terminal for sent / dead). */
16966
+ updatedAt: number(),
16967
+ /** Failure detail — present on a `dead` row. */
16968
+ error: string().optional(),
16969
+ subject: NcHistorySubjectSchema
16463
16970
  });
16464
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16465
- var ProfileRefInputSchema = object({
16466
- addonId: string(),
16467
- profileId: string()
16971
+ /**
16972
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16973
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16974
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16975
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16976
+ */
16977
+ var NcHistoryFilterSchema = object({
16978
+ ruleId: string().optional(),
16979
+ deviceId: number().optional(),
16980
+ status: NcHistoryStatusSchema.optional(),
16981
+ since: number().optional(),
16982
+ until: number().optional(),
16983
+ limit: number().int().min(1).max(500).default(100)
16468
16984
  });
16469
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16470
- kind: "mutation",
16471
- auth: "admin"
16472
- }), method(ProfileRefInputSchema, _void(), {
16985
+ 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 }), {
16473
16986
  kind: "mutation",
16474
- auth: "admin"
16475
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16987
+ auth: "admin",
16988
+ caller: "required"
16989
+ }), method(object({
16990
+ ruleId: string(),
16991
+ patch: NcRulePatchSchema
16992
+ }), object({ rule: NcRuleSchema }), {
16476
16993
  kind: "mutation",
16477
- auth: "admin"
16478
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
16479
- selector: LlmDefaultSelectorSchema,
16480
- profileId: string().nullable()
16481
- }), _void(), {
16994
+ auth: "admin",
16995
+ caller: "required"
16996
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
16482
16997
  kind: "mutation",
16483
16998
  auth: "admin"
16484
16999
  }), method(object({
16485
- since: number().optional(),
16486
- until: number().optional(),
16487
- consumer: string().optional(),
16488
- profileId: string().optional()
16489
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
16490
- nodeId: string(),
16491
- model: ManagedModelRefSchema
16492
- }), _void(), {
17000
+ ruleId: string(),
17001
+ enabled: boolean()
17002
+ }), object({ success: literal(true) }), {
16493
17003
  kind: "mutation",
16494
17004
  auth: "admin"
16495
17005
  }), method(object({
16496
- nodeId: string(),
16497
- file: string()
16498
- }), _void(), {
16499
- kind: "mutation",
16500
- auth: "admin"
16501
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16502
- kind: "mutation",
16503
- auth: "admin"
16504
- }), method(ProfileRefInputSchema, _void(), {
17006
+ rule: NcRuleInputSchema,
17007
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
17008
+ }), object({ results: array(NcTestResultSchema) }), {
16505
17009
  kind: "mutation",
16506
17010
  auth: "admin"
16507
- });
17011
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
16508
17012
  /**
16509
17013
  * Zod schemas for persisted record types.
16510
17014
  *
@@ -17190,7 +17694,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
17190
17694
  }), method(object({
17191
17695
  eventId: string(),
17192
17696
  kind: MediaFileKindEnum.optional()
17193
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
17697
+ }), array(MediaFileSchema).readonly()), method(object({
17698
+ trackId: string(),
17699
+ kinds: array(MediaFileKindEnum).optional()
17700
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
17194
17701
  deviceId: number(),
17195
17702
  timestamp: number(),
17196
17703
  frameWidth: number(),
@@ -17211,76 +17718,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
17211
17718
  eventId: string(),
17212
17719
  timestamp: number()
17213
17720
  });
17214
- /**
17215
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
17216
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
17217
- * caps into per-camera event-kind descriptors.
17218
- *
17219
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
17220
- * is NOT duplicated here — every entry is derived from the single
17221
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
17222
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
17223
- * control cap means adding one line here (and a taxonomy entry); the anti-
17224
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
17225
- * eventful cap is missing.
17226
- */
17227
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
17228
- var LEGACY_ICON = {
17229
- motion: "motion",
17230
- audio: "audio",
17231
- person: "person",
17232
- vehicle: "vehicle",
17233
- animal: "animal",
17234
- package: "package",
17235
- door: "door",
17236
- pir: "pir",
17237
- smoke: "smoke",
17238
- water: "water",
17239
- button: "button",
17240
- generic: "generic",
17241
- gas: "smoke",
17242
- vibration: "generic",
17243
- tamper: "generic",
17244
- presence: "person",
17245
- lock: "generic",
17246
- siren: "generic",
17247
- switch: "generic",
17248
- doorbell: "button"
17249
- };
17250
- function legacyIcon(iconId) {
17251
- return LEGACY_ICON[iconId] ?? "generic";
17252
- }
17253
- /**
17254
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
17255
- * The anti-drift guard cross-checks this against the eventful caps declared
17256
- * in `packages/types/src/capabilities/*.cap.ts`.
17257
- */
17258
- var CAP_TO_KIND = {
17259
- contact: "contact",
17260
- motion: "motion-sensor",
17261
- smoke: "smoke",
17262
- flood: "flood",
17263
- gas: "gas",
17264
- "carbon-monoxide": "carbon-monoxide",
17265
- vibration: "vibration",
17266
- tamper: "tamper",
17267
- presence: "presence",
17268
- "enum-sensor": "enum-sensor",
17269
- "event-emitter": "device-event",
17270
- "lock-control": "lock",
17271
- switch: "switch",
17272
- button: "button",
17273
- doorbell: "doorbell"
17274
- };
17275
- function buildDescriptor(capName, kind) {
17276
- const t = EVENT_TAXONOMY[kind];
17277
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
17278
- return {
17279
- ...t,
17280
- icon: legacyIcon(t.iconId)
17281
- };
17282
- }
17283
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
17284
17721
  var CameraPipelineConfigSchema = object({
17285
17722
  engine: PipelineEngineChoiceSchema.optional(),
17286
17723
  steps: array(PipelineStepInputSchema).readonly(),
@@ -17766,6 +18203,76 @@ method(object({
17766
18203
  auth: "admin"
17767
18204
  });
17768
18205
  /**
18206
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
18207
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
18208
+ * caps into per-camera event-kind descriptors.
18209
+ *
18210
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
18211
+ * is NOT duplicated here — every entry is derived from the single
18212
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
18213
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
18214
+ * control cap means adding one line here (and a taxonomy entry); the anti-
18215
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
18216
+ * eventful cap is missing.
18217
+ */
18218
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
18219
+ var LEGACY_ICON = {
18220
+ motion: "motion",
18221
+ audio: "audio",
18222
+ person: "person",
18223
+ vehicle: "vehicle",
18224
+ animal: "animal",
18225
+ package: "package",
18226
+ door: "door",
18227
+ pir: "pir",
18228
+ smoke: "smoke",
18229
+ water: "water",
18230
+ button: "button",
18231
+ generic: "generic",
18232
+ gas: "smoke",
18233
+ vibration: "generic",
18234
+ tamper: "generic",
18235
+ presence: "person",
18236
+ lock: "generic",
18237
+ siren: "generic",
18238
+ switch: "generic",
18239
+ doorbell: "button"
18240
+ };
18241
+ function legacyIcon(iconId) {
18242
+ return LEGACY_ICON[iconId] ?? "generic";
18243
+ }
18244
+ /**
18245
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
18246
+ * The anti-drift guard cross-checks this against the eventful caps declared
18247
+ * in `packages/types/src/capabilities/*.cap.ts`.
18248
+ */
18249
+ var CAP_TO_KIND = {
18250
+ contact: "contact",
18251
+ motion: "motion-sensor",
18252
+ smoke: "smoke",
18253
+ flood: "flood",
18254
+ gas: "gas",
18255
+ "carbon-monoxide": "carbon-monoxide",
18256
+ vibration: "vibration",
18257
+ tamper: "tamper",
18258
+ presence: "presence",
18259
+ "enum-sensor": "enum-sensor",
18260
+ "event-emitter": "device-event",
18261
+ "lock-control": "lock",
18262
+ switch: "switch",
18263
+ button: "button",
18264
+ doorbell: "doorbell"
18265
+ };
18266
+ function buildDescriptor(capName, kind) {
18267
+ const t = EVENT_TAXONOMY[kind];
18268
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
18269
+ return {
18270
+ ...t,
18271
+ icon: legacyIcon(t.iconId)
18272
+ };
18273
+ }
18274
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
18275
+ /**
17769
18276
  * server-management — per-NODE singleton capability for a node's ROOT
17770
18277
  * package lifecycle (runtime-updatable node packages).
17771
18278
  *
@@ -19271,7 +19778,28 @@ var FaceInfoSchema = object({
19271
19778
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
19272
19779
  * track produced no key frame (e.g. native/onboard source) — the UI falls
19273
19780
  * back to the inline `base64` face crop. */
19274
- keyFrameMediaKey: string().optional()
19781
+ keyFrameMediaKey: string().optional(),
19782
+ /** Winning identity-match cosine (0..1) for this face's track, when an
19783
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
19784
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
19785
+ * faces that were never auto-recognized. */
19786
+ bestMatchScore: number().optional(),
19787
+ /** Native-scale face short side (px) at recognition time, when the runner
19788
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
19789
+ * legacy rows / runners that reported no native measure. */
19790
+ nativeFaceShortSidePx: number().optional(),
19791
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
19792
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
19793
+ * but blocked only by the recognition size floor). Mutually exclusive with
19794
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
19795
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
19796
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
19797
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
19798
+ suggestedIdentityId: string().optional(),
19799
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
19800
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
19801
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
19802
+ suggestedMatchScore: number().optional()
19275
19803
  });
19276
19804
  var FaceFilterEnum = _enum([
19277
19805
  "unassigned",
@@ -21356,36 +21884,6 @@ Object.freeze({
21356
21884
  addonId: null,
21357
21885
  access: "view"
21358
21886
  },
21359
- "advancedNotifier.deleteRule": {
21360
- capName: "advanced-notifier",
21361
- capScope: "system",
21362
- addonId: null,
21363
- access: "delete"
21364
- },
21365
- "advancedNotifier.getHistory": {
21366
- capName: "advanced-notifier",
21367
- capScope: "system",
21368
- addonId: null,
21369
- access: "view"
21370
- },
21371
- "advancedNotifier.getRules": {
21372
- capName: "advanced-notifier",
21373
- capScope: "system",
21374
- addonId: null,
21375
- access: "view"
21376
- },
21377
- "advancedNotifier.testRule": {
21378
- capName: "advanced-notifier",
21379
- capScope: "system",
21380
- addonId: null,
21381
- access: "create"
21382
- },
21383
- "advancedNotifier.upsertRule": {
21384
- capName: "advanced-notifier",
21385
- capScope: "system",
21386
- addonId: null,
21387
- access: "create"
21388
- },
21389
21887
  "alarmPanel.arm": {
21390
21888
  capName: "alarm-panel",
21391
21889
  capScope: "device",
@@ -23690,6 +24188,60 @@ Object.freeze({
23690
24188
  addonId: null,
23691
24189
  access: "create"
23692
24190
  },
24191
+ "notificationRules.createRule": {
24192
+ capName: "notification-rules",
24193
+ capScope: "system",
24194
+ addonId: null,
24195
+ access: "create"
24196
+ },
24197
+ "notificationRules.deleteRule": {
24198
+ capName: "notification-rules",
24199
+ capScope: "system",
24200
+ addonId: null,
24201
+ access: "delete"
24202
+ },
24203
+ "notificationRules.getConditionCatalog": {
24204
+ capName: "notification-rules",
24205
+ capScope: "system",
24206
+ addonId: null,
24207
+ access: "view"
24208
+ },
24209
+ "notificationRules.getHistory": {
24210
+ capName: "notification-rules",
24211
+ capScope: "system",
24212
+ addonId: null,
24213
+ access: "view"
24214
+ },
24215
+ "notificationRules.getRule": {
24216
+ capName: "notification-rules",
24217
+ capScope: "system",
24218
+ addonId: null,
24219
+ access: "view"
24220
+ },
24221
+ "notificationRules.listRules": {
24222
+ capName: "notification-rules",
24223
+ capScope: "system",
24224
+ addonId: null,
24225
+ access: "view"
24226
+ },
24227
+ "notificationRules.setRuleEnabled": {
24228
+ capName: "notification-rules",
24229
+ capScope: "system",
24230
+ addonId: null,
24231
+ access: "create"
24232
+ },
24233
+ "notificationRules.testRule": {
24234
+ capName: "notification-rules",
24235
+ capScope: "system",
24236
+ addonId: null,
24237
+ access: "create"
24238
+ },
24239
+ "notificationRules.updateRule": {
24240
+ capName: "notification-rules",
24241
+ capScope: "system",
24242
+ addonId: null,
24243
+ access: "create"
24244
+ },
23693
24245
  "notifier.cancel": {
23694
24246
  capName: "notifier",
23695
24247
  capScope: "device",