@camstack/addon-decoder-nodeav 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/index.js +1134 -582
  2. package/dist/index.mjs +1134 -582
  3. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
2
+ //#region ../types/dist/event-category-BLcNejAE.mjs
3
3
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
4
4
  EventCategory["SystemBoot"] = "system.boot";
5
5
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -149,9 +149,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
149
149
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
150
150
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
151
151
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
152
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
153
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
154
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
155
152
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
156
153
  * progress bar the client reconciles via `recordingExport.getExport`. */
157
154
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6816,7 +6813,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6816
6813
  patch: record(string(), unknown())
6817
6814
  }), object({ success: literal(true) });
6818
6815
  object({ deviceId: number() }), unknown().nullable();
6819
- /** Shorthand to define a method schema */
6820
6816
  function method(input, output, options) {
6821
6817
  return {
6822
6818
  input,
@@ -6824,6 +6820,7 @@ function method(input, output, options) {
6824
6820
  kind: options?.kind ?? "query",
6825
6821
  auth: options?.auth ?? "protected",
6826
6822
  ...options?.access !== void 0 ? { access: options.access } : {},
6823
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6827
6824
  timeoutMs: options?.timeoutMs
6828
6825
  };
6829
6826
  }
@@ -8189,6 +8186,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8189
8186
  /** The complete taxonomy dictionary, keyed by kind. */
8190
8187
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8191
8188
  /**
8189
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8190
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8191
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8192
+ * taxonomy surface (timeline, filters, event page).
8193
+ *
8194
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8195
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8196
+ * for the `classes` / `classesExclude` conditions.
8197
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8198
+ * the same class picker, grouped under an Audio header.
8199
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8200
+ * lock / …) for the `sensorKinds` device-event condition.
8201
+ *
8202
+ * Each entry carries `parentKind` so the client can group video subs under
8203
+ * their macro and sensor/control kinds under their category. This surface is
8204
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8205
+ * method, no codegen — so it ships train-free with an addon deploy.
8206
+ */
8207
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8208
+ var NcTaxonomyEntrySchema = object({
8209
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8210
+ kind: string(),
8211
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8212
+ label: string(),
8213
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8214
+ parentKind: string().nullable()
8215
+ });
8216
+ object({
8217
+ videoClasses: array(NcTaxonomyEntrySchema),
8218
+ audioKinds: array(NcTaxonomyEntrySchema),
8219
+ labels: array(NcTaxonomyEntrySchema)
8220
+ });
8221
+ function toEntry(kind, label, parentKind) {
8222
+ return {
8223
+ kind,
8224
+ label,
8225
+ parentKind
8226
+ };
8227
+ }
8228
+ /**
8229
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8230
+ * (macros before their subs), which the client relies on for stable grouping.
8231
+ */
8232
+ function buildNcTaxonomy() {
8233
+ const all = Object.values(EVENT_TAXONOMY);
8234
+ return {
8235
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8236
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8237
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8238
+ };
8239
+ }
8240
+ Object.freeze(buildNcTaxonomy());
8241
+ /**
8192
8242
  * Error types for the safe expression engine. Two distinct classes so callers
8193
8243
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8194
8244
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -10897,6 +10947,22 @@ var CameraMetricsSchema = object({
10897
10947
  ])
10898
10948
  });
10899
10949
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
10950
+ /**
10951
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
10952
+ * within the frame, so the executor can re-cut a leaf child ROI at native
10953
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
10954
+ */
10955
+ var NativeCropRefSchema = object({
10956
+ /** Handle keying the retained native surface (node-pinned to its owner). */
10957
+ handle: FrameHandleSchema,
10958
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
10959
+ cropFrameSpace: object({
10960
+ x: number(),
10961
+ y: number(),
10962
+ w: number(),
10963
+ h: number()
10964
+ })
10965
+ });
10900
10966
  var ModelFormatSchema$1 = _enum([
10901
10967
  "onnx",
10902
10968
  "coreml",
@@ -11172,7 +11238,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
11172
11238
  * Omitted ⇒ the runner's default device (current single-engine
11173
11239
  * behaviour). Selects WHICH device pool of the node runs the call.
11174
11240
  */
11175
- deviceKey: string().optional()
11241
+ deviceKey: string().optional(),
11242
+ /**
11243
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
11244
+ * when the parent crop was resolved from the frame's retained NATIVE
11245
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
11246
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
11247
+ * resolution from that surface — the SAME quality path faces already
11248
+ * had — instead of the downscaled parent tile. `handle` keys the native
11249
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
11250
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
11251
+ * the executor's crop-normalized child ROI back into frame-normalized
11252
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
11253
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
11254
+ * (today's behaviour on the fallback path).
11255
+ */
11256
+ nativeCropRef: NativeCropRefSchema.optional()
11176
11257
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
11177
11258
  engine: PipelineEngineChoiceSchema.optional(),
11178
11259
  steps: array(PipelineStepInputSchema).min(1),
@@ -11388,7 +11469,11 @@ var DetailResultSchema = object({
11388
11469
  bbox: NativeCropBboxSchema.optional(),
11389
11470
  embedding: string().optional(),
11390
11471
  label: string().optional(),
11391
- alignedCropJpeg: string().optional()
11472
+ alignedCropJpeg: string().optional(),
11473
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
11474
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
11475
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
11476
+ nativeFaceShortSidePx: number().optional()
11392
11477
  });
11393
11478
  /**
11394
11479
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -11402,6 +11487,12 @@ var motionCooldownMsField = {
11402
11487
  default: 3e4,
11403
11488
  step: 500
11404
11489
  };
11490
+ var maxSessionHoldMsField = {
11491
+ min: 0,
11492
+ max: 6e5,
11493
+ default: 12e4,
11494
+ step: 5e3
11495
+ };
11405
11496
  var motionFpsField = {
11406
11497
  min: 1,
11407
11498
  max: 30,
@@ -11549,6 +11640,19 @@ var RunnerCameraConfigSchema = object({
11549
11640
  "on-motion"
11550
11641
  ]).default("always-on"),
11551
11642
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
11643
+ /**
11644
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
11645
+ * detection session is active and ≥1 confirmed non-stationary track is
11646
+ * still live, the orchestrator keeps the session open past
11647
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
11648
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
11649
+ * ms since the session opened, after which it closes regardless. `0`
11650
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
11651
+ * runner itself — carried here so it shares the per-camera device-settings
11652
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
11653
+ * resolved `CameraDetectionConfig`.
11654
+ */
11655
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
11552
11656
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
11553
11657
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
11554
11658
  motionStreamId: string(),
@@ -11638,7 +11742,7 @@ var RunnerCameraConfigSchema = object({
11638
11742
  */
11639
11743
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
11640
11744
  });
11641
- 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;
11745
+ 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;
11642
11746
  /**
11643
11747
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
11644
11748
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -13492,94 +13596,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
13492
13596
  bundleUrl: string()
13493
13597
  });
13494
13598
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
13495
- var NotificationRuleConditionsSchema = object({
13496
- deviceIds: array(number()).readonly().optional(),
13497
- classNames: array(string()).readonly().optional(),
13498
- zoneIds: array(string()).readonly().optional(),
13499
- minConfidence: number().optional(),
13500
- source: _enum([
13501
- "pipeline",
13502
- "onboard",
13503
- "any"
13504
- ]).optional(),
13505
- schedule: object({
13506
- days: array(number()).readonly(),
13507
- startHour: number(),
13508
- endHour: number()
13509
- }).optional(),
13510
- cooldownSeconds: number().optional(),
13511
- minDwellSeconds: number().optional(),
13512
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
13513
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
13514
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
13515
- eventTypeTokens: array(string()).readonly().optional(),
13516
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
13517
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
13518
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
13519
- clipDescription: object({
13520
- text: string().min(1),
13521
- minSimilarity: number().min(0).max(1)
13522
- }).optional(),
13523
- /** Match events whose recognized-entity label (face identity name or plate
13524
- * vehicle name, propagated onto `event.data.label`) is one of these values.
13525
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
13526
- * vehicle/person> is seen". */
13527
- labels: array(string()).readonly().optional()
13528
- });
13529
- var NotificationRuleTemplateSchema = object({
13530
- title: string(),
13531
- body: string(),
13532
- imageMode: _enum([
13533
- "crop",
13534
- "annotated",
13535
- "full",
13536
- "none"
13537
- ])
13538
- });
13539
- var NotificationRuleSchema = object({
13540
- id: string(),
13541
- name: string(),
13542
- enabled: boolean(),
13543
- eventTypes: array(string()).readonly(),
13544
- conditions: NotificationRuleConditionsSchema,
13545
- outputs: array(string()).readonly(),
13546
- template: NotificationRuleTemplateSchema.optional(),
13547
- priority: _enum([
13548
- "low",
13549
- "normal",
13550
- "high",
13551
- "critical"
13552
- ])
13553
- });
13554
- var NotificationTestResultSchema = object({
13555
- ruleId: string(),
13556
- eventId: string(),
13557
- timestamp: number(),
13558
- wouldFire: boolean(),
13559
- reason: string().optional()
13560
- });
13561
- var NotificationHistoryEntrySchema = object({
13562
- id: string(),
13563
- ruleId: string(),
13564
- ruleName: string(),
13565
- eventId: string(),
13566
- timestamp: number(),
13567
- outputs: array(string()).readonly(),
13568
- success: boolean(),
13569
- error: string().optional(),
13570
- deviceId: number().optional()
13571
- });
13572
- var NotificationHistoryFilterSchema = object({
13573
- ruleId: string().optional(),
13574
- deviceId: number().optional(),
13575
- from: number().optional(),
13576
- to: number().optional(),
13577
- limit: number().optional()
13578
- });
13579
- 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({
13580
- ruleId: string(),
13581
- lookbackMinutes: number()
13582
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
13583
13599
  /**
13584
13600
  * Alerts capability — collection-based internal alert system.
13585
13601
  *
@@ -13803,89 +13819,6 @@ method(object({
13803
13819
  password: string()
13804
13820
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
13805
13821
  /**
13806
- * `login-method` — collection cap through which auth addons contribute
13807
- * their pre-auth login surfaces to the login page. This is the SINGLE,
13808
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
13809
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
13810
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
13811
- * procedure aggregates them for the unauthenticated login page.
13812
- *
13813
- * A contribution is a discriminated union on `kind`:
13814
- *
13815
- * - `redirect` — a declarative button. The login page renders a generic
13816
- * button that navigates to `startUrl` (an addon-owned HTTP route).
13817
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
13818
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
13819
- * login page needs NO change.
13820
- *
13821
- * - `widget` — a Module-Federation widget the login page mounts (via
13822
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
13823
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
13824
- * mechanism kept for future use; no shipped addon uses it on the login
13825
- * page (the passkey ceremony below runs natively in the shell instead).
13826
- *
13827
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
13828
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
13829
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
13830
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
13831
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
13832
- * fetching any remote code pre-auth. Contribution stays unconditional —
13833
- * enrollment state is never leaked pre-auth; visibility is a shell
13834
- * decision.
13835
- *
13836
- * Every contribution carries a `stage`:
13837
- * - `primary` — shown on the first credentials screen (OIDC /
13838
- * magic-link buttons; a future usernameless passkey).
13839
- * - `second-factor` — shown AFTER the password leg, gated on the
13840
- * returned `factors` (passkey-as-2FA today).
13841
- *
13842
- * `mount: skip` — the cap is read server-side by the core auth router
13843
- * (`registry.getCollection('login-method')`), never mounted as its own
13844
- * tRPC router.
13845
- */
13846
- /** When a login method renders in the two-phase login flow. */
13847
- var LoginStageEnum = _enum(["primary", "second-factor"]);
13848
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
13849
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
13850
- object({
13851
- kind: literal("redirect"),
13852
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
13853
- id: string(),
13854
- /** Operator-facing button label. */
13855
- label: string(),
13856
- /** lucide-react icon name. */
13857
- icon: string().optional(),
13858
- /** Addon-owned HTTP route the button navigates to (GET). */
13859
- startUrl: string(),
13860
- stage: LoginStageEnum
13861
- }),
13862
- object({
13863
- kind: literal("widget"),
13864
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
13865
- id: string(),
13866
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
13867
- addonId: string(),
13868
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
13869
- bundle: string(),
13870
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
13871
- remote: WidgetRemoteSchema,
13872
- stage: LoginStageEnum
13873
- }),
13874
- object({
13875
- kind: literal("passkey"),
13876
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
13877
- id: string(),
13878
- /** Operator-facing button label. */
13879
- label: string(),
13880
- stage: LoginStageEnum,
13881
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
13882
- rpId: string(),
13883
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
13884
- origin: string().nullable()
13885
- })
13886
- ]);
13887
- method(_void(), array(LoginMethodContributionSchema).readonly());
13888
- /**
13889
13822
  * Orchestrator-side destination metadata. The orchestrator computes
13890
13823
  * `id = <addonId>:<subId>` from its provider lookup so consumers
13891
13824
  * (admin UI, restore flow) see one canonical key.
@@ -15322,48 +15255,423 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
15322
15255
  kind: "mutation",
15323
15256
  auth: "admin"
15324
15257
  });
15325
- var LogLevelSchema = _enum([
15326
- "debug",
15327
- "info",
15328
- "warn",
15329
- "error"
15258
+ /**
15259
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15260
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15261
+ * caps stay wire-compatible without a circular cap→cap import.
15262
+ *
15263
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
15264
+ * every transport tier structurally, and failed calls still write usage rows.
15265
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15266
+ */
15267
+ var LlmUsageSchema = object({
15268
+ inputTokens: number(),
15269
+ outputTokens: number()
15270
+ });
15271
+ var LlmErrorCodeSchema = _enum([
15272
+ "timeout",
15273
+ "rate-limited",
15274
+ "auth",
15275
+ "refusal",
15276
+ "bad-request",
15277
+ "unavailable",
15278
+ "no-profile",
15279
+ "budget-exceeded",
15280
+ "adapter-error"
15330
15281
  ]);
15331
- var LogEntrySchema = object({
15332
- timestamp: date(),
15333
- level: LogLevelSchema,
15334
- scope: array(string()),
15282
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15283
+ ok: literal(true),
15284
+ text: string(),
15285
+ model: string(),
15286
+ usage: LlmUsageSchema,
15287
+ truncated: boolean(),
15288
+ latencyMs: number()
15289
+ }), object({
15290
+ ok: literal(false),
15291
+ code: LlmErrorCodeSchema,
15335
15292
  message: string(),
15336
- meta: record(string(), unknown()).optional(),
15337
- tags: record(string(), string()).optional()
15338
- });
15339
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15340
- scope: array(string()).optional(),
15341
- level: LogLevelSchema.optional(),
15342
- since: date().optional(),
15343
- until: date().optional(),
15344
- limit: number().optional(),
15345
- tags: record(string(), string()).optional()
15346
- }), array(LogEntrySchema).readonly());
15347
- var CpuBreakdownSchema = object({
15348
- total: number(),
15349
- user: number(),
15350
- system: number(),
15351
- irq: number(),
15352
- nice: number(),
15353
- loadAvg: tuple([
15354
- number(),
15355
- number(),
15356
- number()
15357
- ]),
15358
- cores: number()
15293
+ retryAfterMs: number().optional()
15294
+ })]);
15295
+ /**
15296
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15297
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15298
+ * notification-output.cap.ts:27-31 precedents).
15299
+ */
15300
+ var LlmImageSchema = object({
15301
+ bytes: _instanceof(Uint8Array),
15302
+ mimeType: string()
15359
15303
  });
15360
- var MemoryInfoSchema = object({
15361
- percent: number(),
15362
- totalBytes: number(),
15363
- usedBytes: number(),
15364
- availableBytes: number(),
15365
- swapUsedBytes: number(),
15366
- swapTotalBytes: number()
15304
+ var LlmGenerateBaseInputSchema = object({
15305
+ /** Collection routing (the notification-output posture). */
15306
+ addonId: string().optional(),
15307
+ /** Explicit profile; else the resolution chain (spec §3). */
15308
+ profileId: string().optional(),
15309
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15310
+ consumer: string(),
15311
+ system: string().optional(),
15312
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
15313
+ prompt: string(),
15314
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15315
+ jsonSchema: record(string(), unknown()).optional(),
15316
+ /** Per-call override of the profile default. */
15317
+ maxTokens: number().int().positive().optional(),
15318
+ temperature: number().optional()
15319
+ });
15320
+ /**
15321
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15322
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15323
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15324
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15325
+ * this only through the `llm` cap's methods.
15326
+ *
15327
+ * One running llama-server child per node in v1 (models are RAM-heavy).
15328
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15329
+ * watchdog — operator decision #3).
15330
+ */
15331
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
15332
+ object({
15333
+ kind: literal("catalog"),
15334
+ catalogId: string()
15335
+ }),
15336
+ object({
15337
+ kind: literal("url"),
15338
+ url: string(),
15339
+ sha256: string().optional()
15340
+ }),
15341
+ object({
15342
+ kind: literal("path"),
15343
+ path: string()
15344
+ })
15345
+ ]);
15346
+ var ManagedRuntimeConfigSchema = object({
15347
+ /** WHERE the runtime lives — hub or any agent. */
15348
+ nodeId: string(),
15349
+ /** Closed for v1; 'ollama' is a v2 candidate. */
15350
+ engine: _enum(["llama-cpp"]),
15351
+ model: ManagedModelRefSchema,
15352
+ contextSize: number().int().default(4096),
15353
+ /** 0 = CPU-only. */
15354
+ gpuLayers: number().int().default(0),
15355
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15356
+ threads: number().int().optional(),
15357
+ /** Concurrent slots. */
15358
+ parallel: number().int().default(1),
15359
+ /** Else lazy: first generate boots it. */
15360
+ autoStart: boolean().default(false),
15361
+ /** 0 = never; frees RAM after quiet periods. */
15362
+ idleStopMinutes: number().int().default(30)
15363
+ });
15364
+ var LlmRuntimeStatusSchema = object({
15365
+ /** Status is ALWAYS node-qualified. */
15366
+ nodeId: string(),
15367
+ state: _enum([
15368
+ "stopped",
15369
+ "downloading",
15370
+ "starting",
15371
+ "ready",
15372
+ "crashed",
15373
+ "failed"
15374
+ ]),
15375
+ pid: number().optional(),
15376
+ port: number().optional(),
15377
+ modelPath: string().optional(),
15378
+ modelId: string().optional(),
15379
+ downloadProgress: number().min(0).max(1).optional(),
15380
+ lastError: string().optional(),
15381
+ crashesInWindow: number(),
15382
+ /** Child RSS (sampled best-effort). */
15383
+ memoryBytes: number().optional(),
15384
+ vramBytes: number().optional()
15385
+ });
15386
+ var LlmNodeModelSchema = object({
15387
+ file: string(),
15388
+ sizeBytes: number(),
15389
+ catalogId: string().optional(),
15390
+ installedAt: number().optional()
15391
+ });
15392
+ var LlmRuntimeDiskUsageSchema = object({
15393
+ nodeId: string(),
15394
+ modelsBytes: number(),
15395
+ freeBytes: number().optional()
15396
+ });
15397
+ method(LlmGenerateBaseInputSchema.extend({
15398
+ images: array(LlmImageSchema).optional(),
15399
+ runtime: ManagedRuntimeConfigSchema,
15400
+ /** The managed profile's timeout, threaded by the hub provider. */
15401
+ timeoutMs: number().int().positive().optional()
15402
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15403
+ kind: "mutation",
15404
+ auth: "admin"
15405
+ }), method(object({}), _void(), {
15406
+ kind: "mutation",
15407
+ auth: "admin"
15408
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15409
+ kind: "mutation",
15410
+ auth: "admin"
15411
+ }), method(object({ file: string() }), _void(), {
15412
+ kind: "mutation",
15413
+ auth: "admin"
15414
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15415
+ /**
15416
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15417
+ * methods concat-fan across providers; single-row methods route to ONE
15418
+ * provider by the `addonId` in the call input (the notification-output
15419
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15420
+ * (hub-placed); the cap stays open for future providers.
15421
+ *
15422
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15423
+ * `apiKey` is a password field — providers REDACT it on read and merge on
15424
+ * write; a stored key NEVER round-trips to a client.
15425
+ */
15426
+ var LlmProfileKindSchema = _enum([
15427
+ "openai-compatible",
15428
+ "openai",
15429
+ "anthropic",
15430
+ "google",
15431
+ "managed-local"
15432
+ ]);
15433
+ var LlmProfileSchema = object({
15434
+ id: string(),
15435
+ name: string(),
15436
+ kind: LlmProfileKindSchema,
15437
+ /** Stamped by the provider — keeps the fanned catalog routable. */
15438
+ addonId: string(),
15439
+ enabled: boolean(),
15440
+ /** Vendor model id, or the managed runtime's loaded model. */
15441
+ model: string(),
15442
+ /** Required for openai-compatible; override for cloud kinds. */
15443
+ baseUrl: string().optional(),
15444
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
15445
+ apiKey: string().optional(),
15446
+ supportsVision: boolean(),
15447
+ temperature: number().min(0).max(2).optional(),
15448
+ maxTokens: number().int().positive().optional(),
15449
+ timeoutMs: number().int().positive().default(6e4),
15450
+ extraHeaders: record(string(), string()).optional(),
15451
+ /** kind === 'managed-local' only (spec §4). */
15452
+ runtime: ManagedRuntimeConfigSchema.optional()
15453
+ });
15454
+ /** ConfigUISchema tree passed through untyped on the wire (the
15455
+ * notification-output `ConfigSchemaPassthrough` precedent at
15456
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15457
+ var ConfigSchemaPassthrough$1 = unknown();
15458
+ var LlmProfileKindDescriptorSchema = object({
15459
+ kind: LlmProfileKindSchema,
15460
+ label: string(),
15461
+ icon: string(),
15462
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
15463
+ addonId: string(),
15464
+ configSchema: ConfigSchemaPassthrough$1
15465
+ });
15466
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15467
+ var LlmDefaultSchema = object({
15468
+ selector: LlmDefaultSelectorSchema,
15469
+ profileId: string()
15470
+ });
15471
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
15472
+ var LlmUsageRollupSchema = object({
15473
+ day: string(),
15474
+ consumer: string(),
15475
+ profileId: string(),
15476
+ calls: number(),
15477
+ okCalls: number(),
15478
+ errorCalls: number(),
15479
+ inputTokens: number(),
15480
+ outputTokens: number(),
15481
+ avgLatencyMs: number()
15482
+ });
15483
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15484
+ var ManagedModelCatalogEntrySchema = object({
15485
+ id: string(),
15486
+ label: string(),
15487
+ family: string(),
15488
+ purpose: _enum(["text", "vision"]),
15489
+ url: string(),
15490
+ sha256: string(),
15491
+ sizeBytes: number(),
15492
+ quantization: string(),
15493
+ /** Load-time guidance shown in the picker. */
15494
+ minRamBytes: number(),
15495
+ contextSizeDefault: number().int(),
15496
+ /** Vision models: companion projector file. */
15497
+ mmprojUrl: string().optional()
15498
+ });
15499
+ var LlmRuntimeNodeSchema = object({
15500
+ nodeId: string(),
15501
+ reachable: boolean(),
15502
+ status: LlmRuntimeStatusSchema.optional(),
15503
+ disk: LlmRuntimeDiskUsageSchema.optional(),
15504
+ error: string().optional()
15505
+ });
15506
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
15507
+ var ProfileRefInputSchema = object({
15508
+ addonId: string(),
15509
+ profileId: string()
15510
+ });
15511
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
15512
+ kind: "mutation",
15513
+ auth: "admin"
15514
+ }), method(ProfileRefInputSchema, _void(), {
15515
+ kind: "mutation",
15516
+ auth: "admin"
15517
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
15518
+ kind: "mutation",
15519
+ auth: "admin"
15520
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
15521
+ selector: LlmDefaultSelectorSchema,
15522
+ profileId: string().nullable()
15523
+ }), _void(), {
15524
+ kind: "mutation",
15525
+ auth: "admin"
15526
+ }), method(object({
15527
+ since: number().optional(),
15528
+ until: number().optional(),
15529
+ consumer: string().optional(),
15530
+ profileId: string().optional()
15531
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
15532
+ nodeId: string(),
15533
+ model: ManagedModelRefSchema
15534
+ }), _void(), {
15535
+ kind: "mutation",
15536
+ auth: "admin"
15537
+ }), method(object({
15538
+ nodeId: string(),
15539
+ file: string()
15540
+ }), _void(), {
15541
+ kind: "mutation",
15542
+ auth: "admin"
15543
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
15544
+ kind: "mutation",
15545
+ auth: "admin"
15546
+ }), method(ProfileRefInputSchema, _void(), {
15547
+ kind: "mutation",
15548
+ auth: "admin"
15549
+ });
15550
+ var LogLevelSchema = _enum([
15551
+ "debug",
15552
+ "info",
15553
+ "warn",
15554
+ "error"
15555
+ ]);
15556
+ var LogEntrySchema = object({
15557
+ timestamp: date(),
15558
+ level: LogLevelSchema,
15559
+ scope: array(string()),
15560
+ message: string(),
15561
+ meta: record(string(), unknown()).optional(),
15562
+ tags: record(string(), string()).optional()
15563
+ });
15564
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15565
+ scope: array(string()).optional(),
15566
+ level: LogLevelSchema.optional(),
15567
+ since: date().optional(),
15568
+ until: date().optional(),
15569
+ limit: number().optional(),
15570
+ tags: record(string(), string()).optional()
15571
+ }), array(LogEntrySchema).readonly());
15572
+ /**
15573
+ * `login-method` — collection cap through which auth addons contribute
15574
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
15575
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
15576
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
15577
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
15578
+ * procedure aggregates them for the unauthenticated login page.
15579
+ *
15580
+ * A contribution is a discriminated union on `kind`:
15581
+ *
15582
+ * - `redirect` — a declarative button. The login page renders a generic
15583
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
15584
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
15585
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
15586
+ * login page needs NO change.
15587
+ *
15588
+ * - `widget` — a Module-Federation widget the login page mounts (via
15589
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
15590
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
15591
+ * mechanism kept for future use; no shipped addon uses it on the login
15592
+ * page (the passkey ceremony below runs natively in the shell instead).
15593
+ *
15594
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
15595
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
15596
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
15597
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
15598
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
15599
+ * fetching any remote code pre-auth. Contribution stays unconditional —
15600
+ * enrollment state is never leaked pre-auth; visibility is a shell
15601
+ * decision.
15602
+ *
15603
+ * Every contribution carries a `stage`:
15604
+ * - `primary` — shown on the first credentials screen (OIDC /
15605
+ * magic-link buttons; a future usernameless passkey).
15606
+ * - `second-factor` — shown AFTER the password leg, gated on the
15607
+ * returned `factors` (passkey-as-2FA today).
15608
+ *
15609
+ * `mount: skip` — the cap is read server-side by the core auth router
15610
+ * (`registry.getCollection('login-method')`), never mounted as its own
15611
+ * tRPC router.
15612
+ */
15613
+ /** When a login method renders in the two-phase login flow. */
15614
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
15615
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
15616
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
15617
+ object({
15618
+ kind: literal("redirect"),
15619
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
15620
+ id: string(),
15621
+ /** Operator-facing button label. */
15622
+ label: string(),
15623
+ /** lucide-react icon name. */
15624
+ icon: string().optional(),
15625
+ /** Addon-owned HTTP route the button navigates to (GET). */
15626
+ startUrl: string(),
15627
+ stage: LoginStageEnum
15628
+ }),
15629
+ object({
15630
+ kind: literal("widget"),
15631
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
15632
+ id: string(),
15633
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
15634
+ addonId: string(),
15635
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
15636
+ bundle: string(),
15637
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
15638
+ remote: WidgetRemoteSchema,
15639
+ stage: LoginStageEnum
15640
+ }),
15641
+ object({
15642
+ kind: literal("passkey"),
15643
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
15644
+ id: string(),
15645
+ /** Operator-facing button label. */
15646
+ label: string(),
15647
+ stage: LoginStageEnum,
15648
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
15649
+ rpId: string(),
15650
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
15651
+ origin: string().nullable()
15652
+ })
15653
+ ]);
15654
+ method(_void(), array(LoginMethodContributionSchema).readonly());
15655
+ var CpuBreakdownSchema = object({
15656
+ total: number(),
15657
+ user: number(),
15658
+ system: number(),
15659
+ irq: number(),
15660
+ nice: number(),
15661
+ loadAvg: tuple([
15662
+ number(),
15663
+ number(),
15664
+ number()
15665
+ ]),
15666
+ cores: number()
15667
+ });
15668
+ var MemoryInfoSchema = object({
15669
+ percent: number(),
15670
+ totalBytes: number(),
15671
+ usedBytes: number(),
15672
+ availableBytes: number(),
15673
+ swapUsedBytes: number(),
15674
+ swapTotalBytes: number()
15367
15675
  });
15368
15676
  var DiskIoSnapshotSchema = object({
15369
15677
  readBytes: number(),
@@ -15816,14 +16124,14 @@ var TargetKindCapsSchema = object({
15816
16124
  * the union is large and not meant for runtime validation here; the exported
15817
16125
  * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
15818
16126
  */
15819
- var ConfigSchemaPassthrough$1 = unknown();
16127
+ var ConfigSchemaPassthrough = unknown();
15820
16128
  var TargetKindSchema = object({
15821
16129
  kind: string(),
15822
16130
  label: string(),
15823
16131
  icon: string(),
15824
16132
  /** Stamped by each provider so the concat-fanned catalog stays routable. */
15825
16133
  addonId: string(),
15826
- configSchema: ConfigSchemaPassthrough$1,
16134
+ configSchema: ConfigSchemaPassthrough,
15827
16135
  supportsDiscovery: boolean(),
15828
16136
  caps: TargetKindCapsSchema
15829
16137
  });
@@ -15876,297 +16184,493 @@ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSche
15876
16184
  enabled: boolean()
15877
16185
  }), _void(), { kind: "mutation" });
15878
16186
  /**
15879
- * Shared LLM generate contracts imported by BOTH `llm.cap.ts` (consumer
15880
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15881
- * caps stay wire-compatible without a circular cap→cap import.
16187
+ * notification-rules the Notification Center rule surface (P1 core).
15882
16188
  *
15883
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
15884
- * every transport tier structurally, and failed calls still write usage rows.
15885
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15886
- */
15887
- var LlmUsageSchema = object({
15888
- inputTokens: number(),
15889
- outputTokens: number()
15890
- });
15891
- var LlmErrorCodeSchema = _enum([
15892
- "timeout",
15893
- "rate-limited",
15894
- "auth",
15895
- "refusal",
15896
- "bad-request",
15897
- "unavailable",
15898
- "no-profile",
15899
- "budget-exceeded",
15900
- "adapter-error"
15901
- ]);
15902
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15903
- ok: literal(true),
15904
- text: string(),
15905
- model: string(),
15906
- usage: LlmUsageSchema,
15907
- truncated: boolean(),
15908
- latencyMs: number()
15909
- }), object({
15910
- ok: literal(false),
15911
- code: LlmErrorCodeSchema,
15912
- message: string(),
15913
- retryAfterMs: number().optional()
15914
- })]);
16189
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16190
+ * (operator decisions D-1/D-2/D-3 are binding):
16191
+ *
16192
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16193
+ * `notification-center` module), hooked on the durable persistence
16194
+ * moments (object-event insert, TrackCloser.closeExpired) with a
16195
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
16196
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16197
+ * FIRST persisted detection matching the conditions (per-track dedup,
16198
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16199
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
16200
+ * - DISPATCH stays behind `notification-output` (rules reference targets
16201
+ * by id; per-backend params are a passthrough blob capped by the
16202
+ * target kind's own caps/degrade engine).
16203
+ *
16204
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
16205
+ * server-injected caller identity — the first `caller: 'required'`
16206
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
16207
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
16208
+ * windows, and the optional label/identity/plate matchers. User rules,
16209
+ * private zones, per-recipient fan-out and the wider condition table are
16210
+ * P2+ (see spec §7).
16211
+ *
16212
+ * All schemas here are the single source of truth — `NcRule` etc. are
16213
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16214
+ * schema/interface drift is explicitly not repeated).
16215
+ */
15915
16216
  /**
15916
- * `Uint8Array` is the sanctioned binary conventionsuperjson + the UDS
15917
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15918
- * notification-output.cap.ts:27-31 precedents).
16217
+ * D-3: the trigger/urgency of a rule which persistence moment evaluates it.
16218
+ * The value maps 1:1 onto the evaluated record kind:
16219
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16220
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16221
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16222
+ * change of a LINKED device, one row per linked camera)
16223
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16224
+ * delivery / pick-up)
16225
+ *
16226
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16227
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
16228
+ * this one field keeps the schema additive — a rule still declares exactly
16229
+ * one trigger.
15919
16230
  */
15920
- var LlmImageSchema = object({
15921
- bytes: _instanceof(Uint8Array),
15922
- mimeType: string()
16231
+ var NcDeliverySchema = _enum([
16232
+ "immediate",
16233
+ "track-end",
16234
+ "device-event",
16235
+ "package-event"
16236
+ ]);
16237
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
16238
+ var NcScheduleSchema = object({
16239
+ windows: array(object({
16240
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16241
+ days: array(number().int().min(0).max(6)).min(1),
16242
+ startMinute: number().int().min(0).max(1439),
16243
+ endMinute: number().int().min(0).max(1439)
16244
+ })).min(1),
16245
+ /** IANA timezone; default = hub host timezone. */
16246
+ timezone: string().optional(),
16247
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16248
+ invert: boolean().optional()
15923
16249
  });
15924
- var LlmGenerateBaseInputSchema = object({
15925
- /** Collection routing (the notification-output posture). */
15926
- addonId: string().optional(),
15927
- /** Explicit profile; else the resolution chain (spec §3). */
15928
- profileId: string().optional(),
15929
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15930
- consumer: string(),
15931
- system: string().optional(),
15932
- /** v1: single-turn. `messages[]` is a v2 additive field. */
15933
- prompt: string(),
15934
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15935
- jsonSchema: record(string(), unknown()).optional(),
15936
- /** Per-call override of the profile default. */
15937
- maxTokens: number().int().positive().optional(),
15938
- temperature: number().optional()
16250
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16251
+ var NcPlateMatcherSchema = object({
16252
+ values: array(string().min(1)).min(1),
16253
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16254
+ maxDistance: number().int().min(0).max(3).default(1)
15939
16255
  });
15940
16256
  /**
15941
- * `llm-runtime` node-side managed llama.cpp executor (spec §4). Registered
15942
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15943
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` normal
15944
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15945
- * this only through the `llm` cap's methods.
15946
- *
15947
- * One running llama-server child per node in v1 (models are RAM-heavy).
15948
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15949
- * watchdog operator decision #3).
16257
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16258
+ * occupancy edge for a device optionally narrowed to a single admin
16259
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16260
+ * - `became-occupied` (default) count crossed 0 `count`
16261
+ * - `became-free` — count crossed `count` below it
16262
+ * - `>=` / `<=` — count is at/over or at/under `count`
16263
+ * `sustainSeconds` requires the condition hold continuously that long
16264
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
16265
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16266
+ * the condition never matches. Confirmed edge-state survives addon restarts
16267
+ * (declared SQLite collection, reseeded on boot).
15950
16268
  */
15951
- var ManagedModelRefSchema = discriminatedUnion("kind", [
15952
- object({
15953
- kind: literal("catalog"),
15954
- catalogId: string()
15955
- }),
15956
- object({
15957
- kind: literal("url"),
15958
- url: string(),
15959
- sha256: string().optional()
15960
- }),
15961
- object({
15962
- kind: literal("path"),
15963
- path: string()
15964
- })
15965
- ]);
15966
- var ManagedRuntimeConfigSchema = object({
15967
- /** WHERE the runtime lives — hub or any agent. */
15968
- nodeId: string(),
15969
- /** Closed for v1; 'ollama' is a v2 candidate. */
15970
- engine: _enum(["llama-cpp"]),
15971
- model: ManagedModelRefSchema,
15972
- contextSize: number().int().default(4096),
15973
- /** 0 = CPU-only. */
15974
- gpuLayers: number().int().default(0),
15975
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15976
- threads: number().int().optional(),
15977
- /** Concurrent slots. */
15978
- parallel: number().int().default(1),
15979
- /** Else lazy: first generate boots it. */
15980
- autoStart: boolean().default(false),
15981
- /** 0 = never; frees RAM after quiet periods. */
15982
- idleStopMinutes: number().int().default(30)
16269
+ var NcOccupancyConditionSchema = object({
16270
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16271
+ zoneId: string().optional(),
16272
+ /** Object class to count; absent = any class. */
16273
+ className: string().optional(),
16274
+ op: _enum([
16275
+ "became-occupied",
16276
+ "became-free",
16277
+ ">=",
16278
+ "<="
16279
+ ]).default("became-occupied"),
16280
+ count: number().int().min(0).default(1),
16281
+ sustainSeconds: number().int().min(0).max(3600).default(15)
16282
+ });
16283
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16284
+ var NcZoneConditionSchema = object({
16285
+ ids: array(string().min(1)).min(1),
16286
+ /** Quantifier over `ids` — at least one / every one visited. */
16287
+ match: _enum(["any", "all"]).default("any")
15983
16288
  });
15984
- var LlmRuntimeStatusSchema = object({
15985
- /** Status is ALWAYS node-qualified. */
15986
- nodeId: string(),
15987
- state: _enum([
15988
- "stopped",
15989
- "downloading",
15990
- "starting",
15991
- "ready",
15992
- "crashed",
15993
- "failed"
15994
- ]),
15995
- pid: number().optional(),
15996
- port: number().optional(),
15997
- modelPath: string().optional(),
15998
- modelId: string().optional(),
15999
- downloadProgress: number().min(0).max(1).optional(),
16000
- lastError: string().optional(),
16001
- crashesInWindow: number(),
16002
- /** Child RSS (sampled best-effort). */
16003
- memoryBytes: number().optional(),
16004
- vramBytes: number().optional()
16289
+ /**
16290
+ * The P1 condition set — a flat AND of groups; absent group = pass;
16291
+ * membership lists are OR within the list (spec §2.3).
16292
+ */
16293
+ var NcConditionsSchema = object({
16294
+ /** Device scope — absent = all devices. */
16295
+ devices: array(number()).optional(),
16296
+ /** Detector class names (any overlap with the record's class set). */
16297
+ classes: array(string().min(1)).optional(),
16298
+ /** Veto classes — any overlap fails the rule. */
16299
+ classesExclude: array(string().min(1)).optional(),
16300
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
16301
+ minConfidence: number().min(0).max(1).optional(),
16302
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
16303
+ zones: NcZoneConditionSchema.optional(),
16304
+ /** Veto zones — any hit fails the rule. */
16305
+ zonesExclude: array(string().min(1)).optional(),
16306
+ /**
16307
+ * Exact (case-insensitive) match on the record's collapsed `label`
16308
+ * (identity name / plate text / subclass).
16309
+ */
16310
+ labelEquals: array(string().min(1)).optional(),
16311
+ /**
16312
+ * Identity matcher. P1 boundary: matched against the record's collapsed
16313
+ * `label` (the identity display name propagated by the face pipeline) —
16314
+ * identity-ID matching rides in P2 when identity ids reach the record.
16315
+ */
16316
+ identities: array(string().min(1)).optional(),
16317
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
16318
+ plates: NcPlateMatcherSchema.optional(),
16319
+ /**
16320
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16321
+ * Same P1 boundary: matched against the record's collapsed `label` (the
16322
+ * identity display name). A record with NO label passes (nothing to
16323
+ * exclude), unlike the include variant which fails on an absent label.
16324
+ */
16325
+ identitiesExclude: array(string().min(1)).optional(),
16326
+ /**
16327
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16328
+ * TRACK-END only: importance is scored at track close, so it does not exist
16329
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16330
+ * close the value is threaded via the close-time info (the `Track` clone is
16331
+ * captured before the DB row is updated, so it would otherwise read stale).
16332
+ * Fails when the record carries no importance (never guess quality — the
16333
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
16334
+ */
16335
+ minImportance: number().min(0).max(1).optional(),
16336
+ /**
16337
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16338
+ * TRACK-END only: an `immediate` / object-event subject has no closed
16339
+ * lifespan, so a dwell condition never matches immediate delivery
16340
+ * (documented choice — the object-event record carries no `firstSeen`,
16341
+ * so dwell cannot be computed from what the subject actually carries).
16342
+ */
16343
+ minDwellSeconds: number().min(0).optional(),
16344
+ /**
16345
+ * Detection provenance filter. `any` (default / absent) matches every
16346
+ * source; otherwise the subject's source must equal it. Legacy records
16347
+ * with no stamped source are treated as `pipeline`. The union spans both
16348
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
16349
+ * tracks carry `sensor`.
16350
+ */
16351
+ source: _enum([
16352
+ "pipeline",
16353
+ "onboard",
16354
+ "sensor",
16355
+ "any"
16356
+ ]).optional(),
16357
+ /**
16358
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16359
+ * detector `minConfidence` (that gates the object-detection score; this
16360
+ * gates the recognition/OCR match score). Fails when the subject carries
16361
+ * no label-match confidence (never guess). TRACK-END only: the confidence
16362
+ * lives on the recognition result and reaches the subject at track close.
16363
+ *
16364
+ * What it measures precisely (plumbed at track close — the closer threads
16365
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16366
+ * `importance`): the BEST recognition match confidence observed for the
16367
+ * label the track carries at close — for a face, the peak cosine similarity
16368
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16369
+ * for a plate, the peak OCR read score of the best-held plate
16370
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16371
+ * one track the higher of the two is used. A track that ended with no
16372
+ * confident identity/plate match carries no value, so the condition fails
16373
+ * closed for it (an un-recognized subject).
16374
+ */
16375
+ minLabelConfidence: number().min(0).max(1).optional(),
16376
+ /**
16377
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16378
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16379
+ * against the token carried on the device-event subject (extracted from the
16380
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16381
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16382
+ * eventType, so gate those with {@link sensorKinds} instead.
16383
+ */
16384
+ eventTypeTokens: array(string().min(1)).optional(),
16385
+ /**
16386
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16387
+ * `contact`, `button`, `device-event`) — matched against the persisted
16388
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16389
+ */
16390
+ sensorKinds: array(string().min(1)).optional(),
16391
+ /**
16392
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16393
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16394
+ * when the subject's phase does not match (a subject always carries a phase
16395
+ * on the package-event trigger).
16396
+ */
16397
+ packagePhase: _enum([
16398
+ "delivered",
16399
+ "picked-up",
16400
+ "both"
16401
+ ]).optional(),
16402
+ /**
16403
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16404
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16405
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
16406
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16407
+ */
16408
+ customZones: array(MaskPolygonShapeSchema).optional(),
16409
+ /**
16410
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16411
+ * (optionally zone/class-scoped) occupancy count crosses the configured
16412
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
16413
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16414
+ */
16415
+ occupancy: NcOccupancyConditionSchema.optional()
16005
16416
  });
16006
- var LlmNodeModelSchema = object({
16007
- file: string(),
16008
- sizeBytes: number(),
16009
- catalogId: string().optional(),
16010
- installedAt: number().optional()
16417
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
16418
+ var NcRuleTargetSchema = object({
16419
+ /** `notification-output` Target id. */
16420
+ targetId: string().min(1),
16421
+ /**
16422
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
16423
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16424
+ * degrade engine drops what the backend can't render.
16425
+ */
16426
+ params: record(string(), unknown()).optional()
16011
16427
  });
16012
- var LlmRuntimeDiskUsageSchema = object({
16013
- nodeId: string(),
16014
- modelsBytes: number(),
16015
- freeBytes: number().optional()
16428
+ /**
16429
+ * Media attachment policy (P1 still-image subset).
16430
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
16431
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
16432
+ * matched on identities attaches the subject's `faceCrop`, one matched on
16433
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
16434
+ * (or when the specific crop is missing) degrades to `best`, then
16435
+ * `keyFrame`, then no attachment — never delaying the send. The matched
16436
+ * condition summary is frozen on the outbox row at enqueue (like the rule
16437
+ * name), so the choice never drifts from the record that fired it.
16438
+ * - `keyFrame` — the clean scene frame (no subject box).
16439
+ * - `none` — no attachment.
16440
+ */
16441
+ var NcMediaPolicySchema = object({ attach: _enum([
16442
+ "best",
16443
+ "best-matching",
16444
+ "keyFrame",
16445
+ "none"
16446
+ ]).default("best") });
16447
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16448
+ var NcThrottleSchema = object({
16449
+ cooldownSec: number().int().min(0).max(86400).default(60),
16450
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16451
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
16452
+ });
16453
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16454
+ var NcRuleInputSchema = object({
16455
+ name: string().min(1).max(200),
16456
+ enabled: boolean().default(true),
16457
+ delivery: NcDeliverySchema,
16458
+ conditions: NcConditionsSchema.default({}),
16459
+ schedule: NcScheduleSchema.optional(),
16460
+ targets: array(NcRuleTargetSchema).min(1),
16461
+ media: NcMediaPolicySchema.default({ attach: "best" }),
16462
+ throttle: NcThrottleSchema.default({
16463
+ cooldownSec: 60,
16464
+ scope: "rule-device"
16465
+ }),
16466
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16467
+ template: object({
16468
+ title: string().max(500).optional(),
16469
+ body: string().max(2e3).optional()
16470
+ }).optional(),
16471
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
16472
+ priority: number().int().min(1).max(5).default(3),
16473
+ /**
16474
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16475
+ * behaviour, visible to all, read-only in the viewer). Present = personal
16476
+ * rule owned by this userId. Server-stamped; never trusted from a client.
16477
+ */
16478
+ ownerUserId: string().optional()
16016
16479
  });
16017
- method(LlmGenerateBaseInputSchema.extend({
16018
- images: array(LlmImageSchema).optional(),
16019
- runtime: ManagedRuntimeConfigSchema,
16020
- /** The managed profile's timeout, threaded by the hub provider. */
16021
- timeoutMs: number().int().positive().optional()
16022
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
16023
- kind: "mutation",
16024
- auth: "admin"
16025
- }), method(object({}), _void(), {
16026
- kind: "mutation",
16027
- auth: "admin"
16028
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
16029
- kind: "mutation",
16030
- auth: "admin"
16031
- }), method(object({ file: string() }), _void(), {
16032
- kind: "mutation",
16033
- auth: "admin"
16034
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
16035
16480
  /**
16036
- * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
16037
- * methods concat-fan across providers; single-row methods route to ONE
16038
- * provider by the `addonId` in the call input (the notification-output
16039
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
16040
- * (hub-placed); the cap stays open for future providers.
16041
- *
16042
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
16043
- * `apiKey` is a password field — providers REDACT it on read and merge on
16044
- * write; a stored key NEVER round-trips to a client.
16481
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
16482
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16483
+ * NOT a client-authored input field (it lives on the persisted rule, not the
16484
+ * input), so it is added here explicitly to let the store's per-target opt-out
16485
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16486
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16487
+ * `updateRule` patch.
16045
16488
  */
16046
- var LlmProfileKindSchema = _enum([
16047
- "openai-compatible",
16048
- "openai",
16049
- "anthropic",
16050
- "google",
16051
- "managed-local"
16052
- ]);
16053
- var LlmProfileSchema = object({
16489
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
16490
+ /** A persisted rule. */
16491
+ var NcRuleSchema = NcRuleInputSchema.extend({
16054
16492
  id: string(),
16055
- name: string(),
16056
- kind: LlmProfileKindSchema,
16057
- /** Stamped by the provider — keeps the fanned catalog routable. */
16058
- addonId: string(),
16059
- enabled: boolean(),
16060
- /** Vendor model id, or the managed runtime's loaded model. */
16061
- model: string(),
16062
- /** Required for openai-compatible; override for cloud kinds. */
16063
- baseUrl: string().optional(),
16064
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
16065
- apiKey: string().optional(),
16066
- supportsVision: boolean(),
16067
- temperature: number().min(0).max(2).optional(),
16068
- maxTokens: number().int().positive().optional(),
16069
- timeoutMs: number().int().positive().default(6e4),
16070
- extraHeaders: record(string(), string()).optional(),
16071
- /** kind === 'managed-local' only (spec §4). */
16072
- runtime: ManagedRuntimeConfigSchema.optional()
16073
- });
16074
- /** ConfigUISchema tree passed through untyped on the wire (the
16075
- * notification-output `ConfigSchemaPassthrough` precedent at
16076
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
16077
- var ConfigSchemaPassthrough = unknown();
16078
- var LlmProfileKindDescriptorSchema = object({
16079
- kind: LlmProfileKindSchema,
16080
- label: string(),
16081
- icon: string(),
16082
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
16083
- addonId: string(),
16084
- configSchema: ConfigSchemaPassthrough
16085
- });
16086
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
16087
- var LlmDefaultSchema = object({
16088
- selector: LlmDefaultSelectorSchema,
16089
- profileId: string()
16493
+ /** userId of the admin who created the rule (server-stamped caller). */
16494
+ createdBy: string(),
16495
+ createdAt: number(),
16496
+ updatedAt: number(),
16497
+ /**
16498
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16499
+ * send time. Only a target's OWNER may add/remove its id (server-checked
16500
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
16501
+ */
16502
+ disabledTargetIds: array(string()).default([])
16090
16503
  });
16091
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
16092
- var LlmUsageRollupSchema = object({
16093
- day: string(),
16094
- consumer: string(),
16095
- profileId: string(),
16096
- calls: number(),
16097
- okCalls: number(),
16098
- errorCalls: number(),
16099
- inputTokens: number(),
16100
- outputTokens: number(),
16101
- avgLatencyMs: number()
16504
+ var NcTestResultSchema = object({
16505
+ recordId: string(),
16506
+ recordKind: _enum([
16507
+ "object-event",
16508
+ "track",
16509
+ "device-event",
16510
+ "package-event"
16511
+ ]),
16512
+ deviceId: number(),
16513
+ timestamp: number(),
16514
+ wouldFire: boolean(),
16515
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
16516
+ failedCondition: string().optional(),
16517
+ className: string().optional(),
16518
+ label: string().optional()
16102
16519
  });
16103
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
16104
- var ManagedModelCatalogEntrySchema = object({
16520
+ var NcConditionDescriptorSchema = object({
16521
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16105
16522
  id: string(),
16523
+ group: _enum([
16524
+ "scope",
16525
+ "class",
16526
+ "zones",
16527
+ "quality",
16528
+ "label",
16529
+ "schedule",
16530
+ "device",
16531
+ "package",
16532
+ "occupancy"
16533
+ ]),
16106
16534
  label: string(),
16107
- family: string(),
16108
- purpose: _enum(["text", "vision"]),
16109
- url: string(),
16110
- sha256: string(),
16111
- sizeBytes: number(),
16112
- quantization: string(),
16113
- /** Load-time guidance shown in the picker. */
16114
- minRamBytes: number(),
16115
- contextSizeDefault: number().int(),
16116
- /** Vision models: companion projector file. */
16117
- mmprojUrl: string().optional()
16535
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
16536
+ valueType: _enum([
16537
+ "deviceIdList",
16538
+ "stringList",
16539
+ "number01",
16540
+ "number",
16541
+ "sourceSelect",
16542
+ "zoneSelection",
16543
+ "zoneIdList",
16544
+ "schedule",
16545
+ "plateMatcher",
16546
+ "packagePhase",
16547
+ "polygonDraw",
16548
+ "occupancy"
16549
+ ]),
16550
+ operator: _enum([
16551
+ "in",
16552
+ "notIn",
16553
+ "anyOf",
16554
+ "allOf",
16555
+ "gte",
16556
+ "fuzzyIn",
16557
+ "withinSchedule"
16558
+ ]),
16559
+ /** Which delivery kinds the condition applies to. */
16560
+ appliesTo: array(NcDeliverySchema),
16561
+ phase: string(),
16562
+ description: string().optional()
16118
16563
  });
16119
- var LlmRuntimeNodeSchema = object({
16120
- nodeId: string(),
16121
- reachable: boolean(),
16122
- status: LlmRuntimeStatusSchema.optional(),
16123
- disk: LlmRuntimeDiskUsageSchema.optional(),
16124
- error: string().optional()
16564
+ /**
16565
+ * The delivery lifecycle status of a history row — a straight read of the
16566
+ * durable outbox row's own status (single source of truth):
16567
+ * - `pending` — enqueued, in-flight or retrying with backoff
16568
+ * - `sent` — delivered (terminal)
16569
+ * - `dead` — dead-lettered after exhausting retries / a permanent
16570
+ * backend rejection / a deleted target (terminal; carries
16571
+ * the failure `error`)
16572
+ *
16573
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
16574
+ * user dimension (quiet hours / snooze) and are additive when they land.
16575
+ */
16576
+ var NcHistoryStatusSchema = _enum([
16577
+ "pending",
16578
+ "sent",
16579
+ "dead"
16580
+ ]);
16581
+ /** The evaluated record kind a history row descends from (one per trigger). */
16582
+ var NcHistoryRecordKindSchema = _enum([
16583
+ "object-event",
16584
+ "track-end",
16585
+ "device-event",
16586
+ "package-event"
16587
+ ]);
16588
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16589
+ var NcHistorySubjectSchema = object({
16590
+ className: string(),
16591
+ label: string().optional(),
16592
+ confidence: number().optional(),
16593
+ zones: array(string()),
16594
+ timestamp: number()
16595
+ });
16596
+ /**
16597
+ * One delivery-history row. This is a read-only VIEW over the durable
16598
+ * outbox row (single source of truth — the same row the drain loop drives;
16599
+ * NO second write path, so history can never drift from delivery state).
16600
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16601
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16602
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
16603
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16604
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16605
+ * P1 (admin scope only).
16606
+ */
16607
+ var NcHistoryEntrySchema = object({
16608
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16609
+ id: string(),
16610
+ ruleId: string(),
16611
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
16612
+ ruleName: string(),
16613
+ /** The rule urgency/trigger that produced this delivery. */
16614
+ delivery: NcDeliverySchema,
16615
+ targetId: string(),
16616
+ deviceId: number(),
16617
+ recordKind: NcHistoryRecordKindSchema,
16618
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16619
+ recordId: string(),
16620
+ /** Present for track-scoped deliveries (object-event / track-end). */
16621
+ trackId: string().optional(),
16622
+ status: NcHistoryStatusSchema,
16623
+ /** Delivery attempts made so far. */
16624
+ attempts: number().int(),
16625
+ /** Fire time (outbox enqueue). */
16626
+ createdAt: number(),
16627
+ /** Last transition time (terminal for sent / dead). */
16628
+ updatedAt: number(),
16629
+ /** Failure detail — present on a `dead` row. */
16630
+ error: string().optional(),
16631
+ subject: NcHistorySubjectSchema
16125
16632
  });
16126
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16127
- var ProfileRefInputSchema = object({
16128
- addonId: string(),
16129
- profileId: string()
16633
+ /**
16634
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16635
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16636
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16637
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16638
+ */
16639
+ var NcHistoryFilterSchema = object({
16640
+ ruleId: string().optional(),
16641
+ deviceId: number().optional(),
16642
+ status: NcHistoryStatusSchema.optional(),
16643
+ since: number().optional(),
16644
+ until: number().optional(),
16645
+ limit: number().int().min(1).max(500).default(100)
16130
16646
  });
16131
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16132
- kind: "mutation",
16133
- auth: "admin"
16134
- }), method(ProfileRefInputSchema, _void(), {
16647
+ 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 }), {
16135
16648
  kind: "mutation",
16136
- auth: "admin"
16137
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16649
+ auth: "admin",
16650
+ caller: "required"
16651
+ }), method(object({
16652
+ ruleId: string(),
16653
+ patch: NcRulePatchSchema
16654
+ }), object({ rule: NcRuleSchema }), {
16138
16655
  kind: "mutation",
16139
- auth: "admin"
16140
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
16141
- selector: LlmDefaultSelectorSchema,
16142
- profileId: string().nullable()
16143
- }), _void(), {
16656
+ auth: "admin",
16657
+ caller: "required"
16658
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
16144
16659
  kind: "mutation",
16145
16660
  auth: "admin"
16146
16661
  }), method(object({
16147
- since: number().optional(),
16148
- until: number().optional(),
16149
- consumer: string().optional(),
16150
- profileId: string().optional()
16151
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
16152
- nodeId: string(),
16153
- model: ManagedModelRefSchema
16154
- }), _void(), {
16662
+ ruleId: string(),
16663
+ enabled: boolean()
16664
+ }), object({ success: literal(true) }), {
16155
16665
  kind: "mutation",
16156
16666
  auth: "admin"
16157
16667
  }), method(object({
16158
- nodeId: string(),
16159
- file: string()
16160
- }), _void(), {
16161
- kind: "mutation",
16162
- auth: "admin"
16163
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16164
- kind: "mutation",
16165
- auth: "admin"
16166
- }), method(ProfileRefInputSchema, _void(), {
16668
+ rule: NcRuleInputSchema,
16669
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
16670
+ }), object({ results: array(NcTestResultSchema) }), {
16167
16671
  kind: "mutation",
16168
16672
  auth: "admin"
16169
- });
16673
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
16170
16674
  /**
16171
16675
  * Zod schemas for persisted record types.
16172
16676
  *
@@ -16852,7 +17356,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16852
17356
  }), method(object({
16853
17357
  eventId: string(),
16854
17358
  kind: MediaFileKindEnum.optional()
16855
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
17359
+ }), array(MediaFileSchema).readonly()), method(object({
17360
+ trackId: string(),
17361
+ kinds: array(MediaFileKindEnum).optional()
17362
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
16856
17363
  deviceId: number(),
16857
17364
  timestamp: number(),
16858
17365
  frameWidth: number(),
@@ -16873,76 +17380,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16873
17380
  eventId: string(),
16874
17381
  timestamp: number()
16875
17382
  });
16876
- /**
16877
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
16878
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
16879
- * caps into per-camera event-kind descriptors.
16880
- *
16881
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
16882
- * is NOT duplicated here — every entry is derived from the single
16883
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
16884
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
16885
- * control cap means adding one line here (and a taxonomy entry); the anti-
16886
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
16887
- * eventful cap is missing.
16888
- */
16889
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
16890
- var LEGACY_ICON = {
16891
- motion: "motion",
16892
- audio: "audio",
16893
- person: "person",
16894
- vehicle: "vehicle",
16895
- animal: "animal",
16896
- package: "package",
16897
- door: "door",
16898
- pir: "pir",
16899
- smoke: "smoke",
16900
- water: "water",
16901
- button: "button",
16902
- generic: "generic",
16903
- gas: "smoke",
16904
- vibration: "generic",
16905
- tamper: "generic",
16906
- presence: "person",
16907
- lock: "generic",
16908
- siren: "generic",
16909
- switch: "generic",
16910
- doorbell: "button"
16911
- };
16912
- function legacyIcon(iconId) {
16913
- return LEGACY_ICON[iconId] ?? "generic";
16914
- }
16915
- /**
16916
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
16917
- * The anti-drift guard cross-checks this against the eventful caps declared
16918
- * in `packages/types/src/capabilities/*.cap.ts`.
16919
- */
16920
- var CAP_TO_KIND = {
16921
- contact: "contact",
16922
- motion: "motion-sensor",
16923
- smoke: "smoke",
16924
- flood: "flood",
16925
- gas: "gas",
16926
- "carbon-monoxide": "carbon-monoxide",
16927
- vibration: "vibration",
16928
- tamper: "tamper",
16929
- presence: "presence",
16930
- "enum-sensor": "enum-sensor",
16931
- "event-emitter": "device-event",
16932
- "lock-control": "lock",
16933
- switch: "switch",
16934
- button: "button",
16935
- doorbell: "doorbell"
16936
- };
16937
- function buildDescriptor(capName, kind) {
16938
- const t = EVENT_TAXONOMY[kind];
16939
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
16940
- return {
16941
- ...t,
16942
- icon: legacyIcon(t.iconId)
16943
- };
16944
- }
16945
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
16946
17383
  var CameraPipelineConfigSchema = object({
16947
17384
  engine: PipelineEngineChoiceSchema.optional(),
16948
17385
  steps: array(PipelineStepInputSchema).readonly(),
@@ -17428,6 +17865,76 @@ method(object({
17428
17865
  auth: "admin"
17429
17866
  });
17430
17867
  /**
17868
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
17869
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
17870
+ * caps into per-camera event-kind descriptors.
17871
+ *
17872
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
17873
+ * is NOT duplicated here — every entry is derived from the single
17874
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
17875
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
17876
+ * control cap means adding one line here (and a taxonomy entry); the anti-
17877
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
17878
+ * eventful cap is missing.
17879
+ */
17880
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
17881
+ var LEGACY_ICON = {
17882
+ motion: "motion",
17883
+ audio: "audio",
17884
+ person: "person",
17885
+ vehicle: "vehicle",
17886
+ animal: "animal",
17887
+ package: "package",
17888
+ door: "door",
17889
+ pir: "pir",
17890
+ smoke: "smoke",
17891
+ water: "water",
17892
+ button: "button",
17893
+ generic: "generic",
17894
+ gas: "smoke",
17895
+ vibration: "generic",
17896
+ tamper: "generic",
17897
+ presence: "person",
17898
+ lock: "generic",
17899
+ siren: "generic",
17900
+ switch: "generic",
17901
+ doorbell: "button"
17902
+ };
17903
+ function legacyIcon(iconId) {
17904
+ return LEGACY_ICON[iconId] ?? "generic";
17905
+ }
17906
+ /**
17907
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
17908
+ * The anti-drift guard cross-checks this against the eventful caps declared
17909
+ * in `packages/types/src/capabilities/*.cap.ts`.
17910
+ */
17911
+ var CAP_TO_KIND = {
17912
+ contact: "contact",
17913
+ motion: "motion-sensor",
17914
+ smoke: "smoke",
17915
+ flood: "flood",
17916
+ gas: "gas",
17917
+ "carbon-monoxide": "carbon-monoxide",
17918
+ vibration: "vibration",
17919
+ tamper: "tamper",
17920
+ presence: "presence",
17921
+ "enum-sensor": "enum-sensor",
17922
+ "event-emitter": "device-event",
17923
+ "lock-control": "lock",
17924
+ switch: "switch",
17925
+ button: "button",
17926
+ doorbell: "doorbell"
17927
+ };
17928
+ function buildDescriptor(capName, kind) {
17929
+ const t = EVENT_TAXONOMY[kind];
17930
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
17931
+ return {
17932
+ ...t,
17933
+ icon: legacyIcon(t.iconId)
17934
+ };
17935
+ }
17936
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
17937
+ /**
17431
17938
  * server-management — per-NODE singleton capability for a node's ROOT
17432
17939
  * package lifecycle (runtime-updatable node packages).
17433
17940
  *
@@ -18882,7 +19389,28 @@ var FaceInfoSchema = object({
18882
19389
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
18883
19390
  * track produced no key frame (e.g. native/onboard source) — the UI falls
18884
19391
  * back to the inline `base64` face crop. */
18885
- keyFrameMediaKey: string().optional()
19392
+ keyFrameMediaKey: string().optional(),
19393
+ /** Winning identity-match cosine (0..1) for this face's track, when an
19394
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
19395
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
19396
+ * faces that were never auto-recognized. */
19397
+ bestMatchScore: number().optional(),
19398
+ /** Native-scale face short side (px) at recognition time, when the runner
19399
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
19400
+ * legacy rows / runners that reported no native measure. */
19401
+ nativeFaceShortSidePx: number().optional(),
19402
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
19403
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
19404
+ * but blocked only by the recognition size floor). Mutually exclusive with
19405
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
19406
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
19407
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
19408
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
19409
+ suggestedIdentityId: string().optional(),
19410
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
19411
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
19412
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
19413
+ suggestedMatchScore: number().optional()
18886
19414
  });
18887
19415
  var FaceFilterEnum = _enum([
18888
19416
  "unassigned",
@@ -20925,36 +21453,6 @@ Object.freeze({
20925
21453
  addonId: null,
20926
21454
  access: "view"
20927
21455
  },
20928
- "advancedNotifier.deleteRule": {
20929
- capName: "advanced-notifier",
20930
- capScope: "system",
20931
- addonId: null,
20932
- access: "delete"
20933
- },
20934
- "advancedNotifier.getHistory": {
20935
- capName: "advanced-notifier",
20936
- capScope: "system",
20937
- addonId: null,
20938
- access: "view"
20939
- },
20940
- "advancedNotifier.getRules": {
20941
- capName: "advanced-notifier",
20942
- capScope: "system",
20943
- addonId: null,
20944
- access: "view"
20945
- },
20946
- "advancedNotifier.testRule": {
20947
- capName: "advanced-notifier",
20948
- capScope: "system",
20949
- addonId: null,
20950
- access: "create"
20951
- },
20952
- "advancedNotifier.upsertRule": {
20953
- capName: "advanced-notifier",
20954
- capScope: "system",
20955
- addonId: null,
20956
- access: "create"
20957
- },
20958
21456
  "alarmPanel.arm": {
20959
21457
  capName: "alarm-panel",
20960
21458
  capScope: "device",
@@ -23259,6 +23757,60 @@ Object.freeze({
23259
23757
  addonId: null,
23260
23758
  access: "create"
23261
23759
  },
23760
+ "notificationRules.createRule": {
23761
+ capName: "notification-rules",
23762
+ capScope: "system",
23763
+ addonId: null,
23764
+ access: "create"
23765
+ },
23766
+ "notificationRules.deleteRule": {
23767
+ capName: "notification-rules",
23768
+ capScope: "system",
23769
+ addonId: null,
23770
+ access: "delete"
23771
+ },
23772
+ "notificationRules.getConditionCatalog": {
23773
+ capName: "notification-rules",
23774
+ capScope: "system",
23775
+ addonId: null,
23776
+ access: "view"
23777
+ },
23778
+ "notificationRules.getHistory": {
23779
+ capName: "notification-rules",
23780
+ capScope: "system",
23781
+ addonId: null,
23782
+ access: "view"
23783
+ },
23784
+ "notificationRules.getRule": {
23785
+ capName: "notification-rules",
23786
+ capScope: "system",
23787
+ addonId: null,
23788
+ access: "view"
23789
+ },
23790
+ "notificationRules.listRules": {
23791
+ capName: "notification-rules",
23792
+ capScope: "system",
23793
+ addonId: null,
23794
+ access: "view"
23795
+ },
23796
+ "notificationRules.setRuleEnabled": {
23797
+ capName: "notification-rules",
23798
+ capScope: "system",
23799
+ addonId: null,
23800
+ access: "create"
23801
+ },
23802
+ "notificationRules.testRule": {
23803
+ capName: "notification-rules",
23804
+ capScope: "system",
23805
+ addonId: null,
23806
+ access: "create"
23807
+ },
23808
+ "notificationRules.updateRule": {
23809
+ capName: "notification-rules",
23810
+ capScope: "system",
23811
+ addonId: null,
23812
+ access: "create"
23813
+ },
23262
23814
  "notifier.cancel": {
23263
23815
  capName: "notifier",
23264
23816
  capScope: "device",