@camstack/addon-provider-onvif 1.2.4 → 1.2.5

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