@camstack/addon-export-hap 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.
@@ -35,7 +35,7 @@ let node_fs_promises = require("node:fs/promises");
35
35
  node_fs_promises = __toESM(node_fs_promises);
36
36
  let node_dgram = require("node:dgram");
37
37
  let node_os = require("node:os");
38
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
38
+ //#region ../types/dist/event-category-BLcNejAE.mjs
39
39
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
40
40
  EventCategory["SystemBoot"] = "system.boot";
41
41
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -185,9 +185,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
185
185
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
186
186
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
187
187
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
188
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
189
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
190
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
191
188
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
192
189
  * progress bar the client reconciles via `recordingExport.getExport`. */
193
190
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6852,7 +6849,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6852
6849
  patch: record(string(), unknown())
6853
6850
  }), object({ success: literal(true) });
6854
6851
  object({ deviceId: number() }), unknown().nullable();
6855
- /** Shorthand to define a method schema */
6856
6852
  function method(input, output, options) {
6857
6853
  return {
6858
6854
  input,
@@ -6860,6 +6856,7 @@ function method(input, output, options) {
6860
6856
  kind: options?.kind ?? "query",
6861
6857
  auth: options?.auth ?? "protected",
6862
6858
  ...options?.access !== void 0 ? { access: options.access } : {},
6859
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6863
6860
  timeoutMs: options?.timeoutMs
6864
6861
  };
6865
6862
  }
@@ -8267,6 +8264,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8267
8264
  /** The complete taxonomy dictionary, keyed by kind. */
8268
8265
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8269
8266
  /**
8267
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8268
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8269
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8270
+ * taxonomy surface (timeline, filters, event page).
8271
+ *
8272
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8273
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8274
+ * for the `classes` / `classesExclude` conditions.
8275
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8276
+ * the same class picker, grouped under an Audio header.
8277
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8278
+ * lock / …) for the `sensorKinds` device-event condition.
8279
+ *
8280
+ * Each entry carries `parentKind` so the client can group video subs under
8281
+ * their macro and sensor/control kinds under their category. This surface is
8282
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8283
+ * method, no codegen — so it ships train-free with an addon deploy.
8284
+ */
8285
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8286
+ var NcTaxonomyEntrySchema = object({
8287
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8288
+ kind: string(),
8289
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8290
+ label: string(),
8291
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8292
+ parentKind: string().nullable()
8293
+ });
8294
+ object({
8295
+ videoClasses: array(NcTaxonomyEntrySchema),
8296
+ audioKinds: array(NcTaxonomyEntrySchema),
8297
+ labels: array(NcTaxonomyEntrySchema)
8298
+ });
8299
+ function toEntry(kind, label, parentKind) {
8300
+ return {
8301
+ kind,
8302
+ label,
8303
+ parentKind
8304
+ };
8305
+ }
8306
+ /**
8307
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8308
+ * (macros before their subs), which the client relies on for stable grouping.
8309
+ */
8310
+ function buildNcTaxonomy() {
8311
+ const all = Object.values(EVENT_TAXONOMY);
8312
+ return {
8313
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8314
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8315
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8316
+ };
8317
+ }
8318
+ Object.freeze(buildNcTaxonomy());
8319
+ /**
8270
8320
  * Error types for the safe expression engine. Two distinct classes so callers
8271
8321
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8272
8322
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -10975,6 +11025,22 @@ var CameraMetricsSchema = object({
10975
11025
  ])
10976
11026
  });
10977
11027
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
11028
+ /**
11029
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
11030
+ * within the frame, so the executor can re-cut a leaf child ROI at native
11031
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
11032
+ */
11033
+ var NativeCropRefSchema = object({
11034
+ /** Handle keying the retained native surface (node-pinned to its owner). */
11035
+ handle: FrameHandleSchema,
11036
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
11037
+ cropFrameSpace: object({
11038
+ x: number(),
11039
+ y: number(),
11040
+ w: number(),
11041
+ h: number()
11042
+ })
11043
+ });
10978
11044
  var ModelFormatSchema$1 = _enum([
10979
11045
  "onnx",
10980
11046
  "coreml",
@@ -11250,7 +11316,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
11250
11316
  * Omitted ⇒ the runner's default device (current single-engine
11251
11317
  * behaviour). Selects WHICH device pool of the node runs the call.
11252
11318
  */
11253
- deviceKey: string().optional()
11319
+ deviceKey: string().optional(),
11320
+ /**
11321
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
11322
+ * when the parent crop was resolved from the frame's retained NATIVE
11323
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
11324
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
11325
+ * resolution from that surface — the SAME quality path faces already
11326
+ * had — instead of the downscaled parent tile. `handle` keys the native
11327
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
11328
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
11329
+ * the executor's crop-normalized child ROI back into frame-normalized
11330
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
11331
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
11332
+ * (today's behaviour on the fallback path).
11333
+ */
11334
+ nativeCropRef: NativeCropRefSchema.optional()
11254
11335
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
11255
11336
  engine: PipelineEngineChoiceSchema.optional(),
11256
11337
  steps: array(PipelineStepInputSchema).min(1),
@@ -11466,7 +11547,11 @@ var DetailResultSchema = object({
11466
11547
  bbox: NativeCropBboxSchema.optional(),
11467
11548
  embedding: string().optional(),
11468
11549
  label: string().optional(),
11469
- alignedCropJpeg: string().optional()
11550
+ alignedCropJpeg: string().optional(),
11551
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
11552
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
11553
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
11554
+ nativeFaceShortSidePx: number().optional()
11470
11555
  });
11471
11556
  /**
11472
11557
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -11480,6 +11565,12 @@ var motionCooldownMsField = {
11480
11565
  default: 3e4,
11481
11566
  step: 500
11482
11567
  };
11568
+ var maxSessionHoldMsField = {
11569
+ min: 0,
11570
+ max: 6e5,
11571
+ default: 12e4,
11572
+ step: 5e3
11573
+ };
11483
11574
  var motionFpsField = {
11484
11575
  min: 1,
11485
11576
  max: 30,
@@ -11627,6 +11718,19 @@ var RunnerCameraConfigSchema = object({
11627
11718
  "on-motion"
11628
11719
  ]).default("always-on"),
11629
11720
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
11721
+ /**
11722
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
11723
+ * detection session is active and ≥1 confirmed non-stationary track is
11724
+ * still live, the orchestrator keeps the session open past
11725
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
11726
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
11727
+ * ms since the session opened, after which it closes regardless. `0`
11728
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
11729
+ * runner itself — carried here so it shares the per-camera device-settings
11730
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
11731
+ * resolved `CameraDetectionConfig`.
11732
+ */
11733
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
11630
11734
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
11631
11735
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
11632
11736
  motionStreamId: string(),
@@ -11716,7 +11820,7 @@ var RunnerCameraConfigSchema = object({
11716
11820
  */
11717
11821
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
11718
11822
  });
11719
- 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;
11823
+ 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;
11720
11824
  /**
11721
11825
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
11722
11826
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -13570,94 +13674,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
13570
13674
  bundleUrl: string()
13571
13675
  });
13572
13676
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
13573
- var NotificationRuleConditionsSchema = object({
13574
- deviceIds: array(number()).readonly().optional(),
13575
- classNames: array(string()).readonly().optional(),
13576
- zoneIds: array(string()).readonly().optional(),
13577
- minConfidence: number().optional(),
13578
- source: _enum([
13579
- "pipeline",
13580
- "onboard",
13581
- "any"
13582
- ]).optional(),
13583
- schedule: object({
13584
- days: array(number()).readonly(),
13585
- startHour: number(),
13586
- endHour: number()
13587
- }).optional(),
13588
- cooldownSeconds: number().optional(),
13589
- minDwellSeconds: number().optional(),
13590
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
13591
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
13592
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
13593
- eventTypeTokens: array(string()).readonly().optional(),
13594
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
13595
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
13596
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
13597
- clipDescription: object({
13598
- text: string().min(1),
13599
- minSimilarity: number().min(0).max(1)
13600
- }).optional(),
13601
- /** Match events whose recognized-entity label (face identity name or plate
13602
- * vehicle name, propagated onto `event.data.label`) is one of these values.
13603
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
13604
- * vehicle/person> is seen". */
13605
- labels: array(string()).readonly().optional()
13606
- });
13607
- var NotificationRuleTemplateSchema = object({
13608
- title: string(),
13609
- body: string(),
13610
- imageMode: _enum([
13611
- "crop",
13612
- "annotated",
13613
- "full",
13614
- "none"
13615
- ])
13616
- });
13617
- var NotificationRuleSchema = object({
13618
- id: string(),
13619
- name: string(),
13620
- enabled: boolean(),
13621
- eventTypes: array(string()).readonly(),
13622
- conditions: NotificationRuleConditionsSchema,
13623
- outputs: array(string()).readonly(),
13624
- template: NotificationRuleTemplateSchema.optional(),
13625
- priority: _enum([
13626
- "low",
13627
- "normal",
13628
- "high",
13629
- "critical"
13630
- ])
13631
- });
13632
- var NotificationTestResultSchema = object({
13633
- ruleId: string(),
13634
- eventId: string(),
13635
- timestamp: number(),
13636
- wouldFire: boolean(),
13637
- reason: string().optional()
13638
- });
13639
- var NotificationHistoryEntrySchema = object({
13640
- id: string(),
13641
- ruleId: string(),
13642
- ruleName: string(),
13643
- eventId: string(),
13644
- timestamp: number(),
13645
- outputs: array(string()).readonly(),
13646
- success: boolean(),
13647
- error: string().optional(),
13648
- deviceId: number().optional()
13649
- });
13650
- var NotificationHistoryFilterSchema = object({
13651
- ruleId: string().optional(),
13652
- deviceId: number().optional(),
13653
- from: number().optional(),
13654
- to: number().optional(),
13655
- limit: number().optional()
13656
- });
13657
- 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({
13658
- ruleId: string(),
13659
- lookbackMinutes: number()
13660
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
13661
13677
  /**
13662
13678
  * Alerts capability — collection-based internal alert system.
13663
13679
  *
@@ -13844,89 +13860,6 @@ method(object({
13844
13860
  password: string()
13845
13861
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
13846
13862
  /**
13847
- * `login-method` — collection cap through which auth addons contribute
13848
- * their pre-auth login surfaces to the login page. This is the SINGLE,
13849
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
13850
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
13851
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
13852
- * procedure aggregates them for the unauthenticated login page.
13853
- *
13854
- * A contribution is a discriminated union on `kind`:
13855
- *
13856
- * - `redirect` — a declarative button. The login page renders a generic
13857
- * button that navigates to `startUrl` (an addon-owned HTTP route).
13858
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
13859
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
13860
- * login page needs NO change.
13861
- *
13862
- * - `widget` — a Module-Federation widget the login page mounts (via
13863
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
13864
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
13865
- * mechanism kept for future use; no shipped addon uses it on the login
13866
- * page (the passkey ceremony below runs natively in the shell instead).
13867
- *
13868
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
13869
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
13870
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
13871
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
13872
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
13873
- * fetching any remote code pre-auth. Contribution stays unconditional —
13874
- * enrollment state is never leaked pre-auth; visibility is a shell
13875
- * decision.
13876
- *
13877
- * Every contribution carries a `stage`:
13878
- * - `primary` — shown on the first credentials screen (OIDC /
13879
- * magic-link buttons; a future usernameless passkey).
13880
- * - `second-factor` — shown AFTER the password leg, gated on the
13881
- * returned `factors` (passkey-as-2FA today).
13882
- *
13883
- * `mount: skip` — the cap is read server-side by the core auth router
13884
- * (`registry.getCollection('login-method')`), never mounted as its own
13885
- * tRPC router.
13886
- */
13887
- /** When a login method renders in the two-phase login flow. */
13888
- var LoginStageEnum = _enum(["primary", "second-factor"]);
13889
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
13890
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
13891
- object({
13892
- kind: literal("redirect"),
13893
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
13894
- id: string(),
13895
- /** Operator-facing button label. */
13896
- label: string(),
13897
- /** lucide-react icon name. */
13898
- icon: string().optional(),
13899
- /** Addon-owned HTTP route the button navigates to (GET). */
13900
- startUrl: string(),
13901
- stage: LoginStageEnum
13902
- }),
13903
- object({
13904
- kind: literal("widget"),
13905
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
13906
- id: string(),
13907
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
13908
- addonId: string(),
13909
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
13910
- bundle: string(),
13911
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
13912
- remote: WidgetRemoteSchema,
13913
- stage: LoginStageEnum
13914
- }),
13915
- object({
13916
- kind: literal("passkey"),
13917
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
13918
- id: string(),
13919
- /** Operator-facing button label. */
13920
- label: string(),
13921
- stage: LoginStageEnum,
13922
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
13923
- rpId: string(),
13924
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
13925
- origin: string().nullable()
13926
- })
13927
- ]);
13928
- method(_void(), array(LoginMethodContributionSchema).readonly());
13929
- /**
13930
13863
  * Orchestrator-side destination metadata. The orchestrator computes
13931
13864
  * `id = <addonId>:<subId>` from its provider lookup so consumers
13932
13865
  * (admin UI, restore flow) see one canonical key.
@@ -15295,48 +15228,423 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
15295
15228
  kind: "mutation",
15296
15229
  auth: "admin"
15297
15230
  });
15298
- var LogLevelSchema = _enum([
15299
- "debug",
15300
- "info",
15301
- "warn",
15302
- "error"
15231
+ /**
15232
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15233
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15234
+ * caps stay wire-compatible without a circular cap→cap import.
15235
+ *
15236
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
15237
+ * every transport tier structurally, and failed calls still write usage rows.
15238
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15239
+ */
15240
+ var LlmUsageSchema = object({
15241
+ inputTokens: number(),
15242
+ outputTokens: number()
15243
+ });
15244
+ var LlmErrorCodeSchema = _enum([
15245
+ "timeout",
15246
+ "rate-limited",
15247
+ "auth",
15248
+ "refusal",
15249
+ "bad-request",
15250
+ "unavailable",
15251
+ "no-profile",
15252
+ "budget-exceeded",
15253
+ "adapter-error"
15303
15254
  ]);
15304
- var LogEntrySchema = object({
15305
- timestamp: date(),
15306
- level: LogLevelSchema,
15307
- scope: array(string()),
15255
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15256
+ ok: literal(true),
15257
+ text: string(),
15258
+ model: string(),
15259
+ usage: LlmUsageSchema,
15260
+ truncated: boolean(),
15261
+ latencyMs: number()
15262
+ }), object({
15263
+ ok: literal(false),
15264
+ code: LlmErrorCodeSchema,
15308
15265
  message: string(),
15309
- meta: record(string(), unknown()).optional(),
15310
- tags: record(string(), string()).optional()
15311
- });
15312
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15313
- scope: array(string()).optional(),
15314
- level: LogLevelSchema.optional(),
15315
- since: date().optional(),
15316
- until: date().optional(),
15317
- limit: number().optional(),
15318
- tags: record(string(), string()).optional()
15319
- }), array(LogEntrySchema).readonly());
15320
- var CpuBreakdownSchema = object({
15321
- total: number(),
15322
- user: number(),
15323
- system: number(),
15324
- irq: number(),
15325
- nice: number(),
15326
- loadAvg: tuple([
15327
- number(),
15328
- number(),
15329
- number()
15330
- ]),
15331
- cores: number()
15266
+ retryAfterMs: number().optional()
15267
+ })]);
15268
+ /**
15269
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15270
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15271
+ * notification-output.cap.ts:27-31 precedents).
15272
+ */
15273
+ var LlmImageSchema = object({
15274
+ bytes: _instanceof(Uint8Array),
15275
+ mimeType: string()
15332
15276
  });
15333
- var MemoryInfoSchema = object({
15334
- percent: number(),
15335
- totalBytes: number(),
15336
- usedBytes: number(),
15337
- availableBytes: number(),
15338
- swapUsedBytes: number(),
15339
- swapTotalBytes: number()
15277
+ var LlmGenerateBaseInputSchema = object({
15278
+ /** Collection routing (the notification-output posture). */
15279
+ addonId: string().optional(),
15280
+ /** Explicit profile; else the resolution chain (spec §3). */
15281
+ profileId: string().optional(),
15282
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15283
+ consumer: string(),
15284
+ system: string().optional(),
15285
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
15286
+ prompt: string(),
15287
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15288
+ jsonSchema: record(string(), unknown()).optional(),
15289
+ /** Per-call override of the profile default. */
15290
+ maxTokens: number().int().positive().optional(),
15291
+ temperature: number().optional()
15292
+ });
15293
+ /**
15294
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15295
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15296
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15297
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15298
+ * this only through the `llm` cap's methods.
15299
+ *
15300
+ * One running llama-server child per node in v1 (models are RAM-heavy).
15301
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15302
+ * watchdog — operator decision #3).
15303
+ */
15304
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
15305
+ object({
15306
+ kind: literal("catalog"),
15307
+ catalogId: string()
15308
+ }),
15309
+ object({
15310
+ kind: literal("url"),
15311
+ url: string(),
15312
+ sha256: string().optional()
15313
+ }),
15314
+ object({
15315
+ kind: literal("path"),
15316
+ path: string()
15317
+ })
15318
+ ]);
15319
+ var ManagedRuntimeConfigSchema = object({
15320
+ /** WHERE the runtime lives — hub or any agent. */
15321
+ nodeId: string(),
15322
+ /** Closed for v1; 'ollama' is a v2 candidate. */
15323
+ engine: _enum(["llama-cpp"]),
15324
+ model: ManagedModelRefSchema,
15325
+ contextSize: number().int().default(4096),
15326
+ /** 0 = CPU-only. */
15327
+ gpuLayers: number().int().default(0),
15328
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15329
+ threads: number().int().optional(),
15330
+ /** Concurrent slots. */
15331
+ parallel: number().int().default(1),
15332
+ /** Else lazy: first generate boots it. */
15333
+ autoStart: boolean().default(false),
15334
+ /** 0 = never; frees RAM after quiet periods. */
15335
+ idleStopMinutes: number().int().default(30)
15336
+ });
15337
+ var LlmRuntimeStatusSchema = object({
15338
+ /** Status is ALWAYS node-qualified. */
15339
+ nodeId: string(),
15340
+ state: _enum([
15341
+ "stopped",
15342
+ "downloading",
15343
+ "starting",
15344
+ "ready",
15345
+ "crashed",
15346
+ "failed"
15347
+ ]),
15348
+ pid: number().optional(),
15349
+ port: number().optional(),
15350
+ modelPath: string().optional(),
15351
+ modelId: string().optional(),
15352
+ downloadProgress: number().min(0).max(1).optional(),
15353
+ lastError: string().optional(),
15354
+ crashesInWindow: number(),
15355
+ /** Child RSS (sampled best-effort). */
15356
+ memoryBytes: number().optional(),
15357
+ vramBytes: number().optional()
15358
+ });
15359
+ var LlmNodeModelSchema = object({
15360
+ file: string(),
15361
+ sizeBytes: number(),
15362
+ catalogId: string().optional(),
15363
+ installedAt: number().optional()
15364
+ });
15365
+ var LlmRuntimeDiskUsageSchema = object({
15366
+ nodeId: string(),
15367
+ modelsBytes: number(),
15368
+ freeBytes: number().optional()
15369
+ });
15370
+ method(LlmGenerateBaseInputSchema.extend({
15371
+ images: array(LlmImageSchema).optional(),
15372
+ runtime: ManagedRuntimeConfigSchema,
15373
+ /** The managed profile's timeout, threaded by the hub provider. */
15374
+ timeoutMs: number().int().positive().optional()
15375
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15376
+ kind: "mutation",
15377
+ auth: "admin"
15378
+ }), method(object({}), _void(), {
15379
+ kind: "mutation",
15380
+ auth: "admin"
15381
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15382
+ kind: "mutation",
15383
+ auth: "admin"
15384
+ }), method(object({ file: string() }), _void(), {
15385
+ kind: "mutation",
15386
+ auth: "admin"
15387
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15388
+ /**
15389
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15390
+ * methods concat-fan across providers; single-row methods route to ONE
15391
+ * provider by the `addonId` in the call input (the notification-output
15392
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15393
+ * (hub-placed); the cap stays open for future providers.
15394
+ *
15395
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15396
+ * `apiKey` is a password field — providers REDACT it on read and merge on
15397
+ * write; a stored key NEVER round-trips to a client.
15398
+ */
15399
+ var LlmProfileKindSchema = _enum([
15400
+ "openai-compatible",
15401
+ "openai",
15402
+ "anthropic",
15403
+ "google",
15404
+ "managed-local"
15405
+ ]);
15406
+ var LlmProfileSchema = object({
15407
+ id: string(),
15408
+ name: string(),
15409
+ kind: LlmProfileKindSchema,
15410
+ /** Stamped by the provider — keeps the fanned catalog routable. */
15411
+ addonId: string(),
15412
+ enabled: boolean(),
15413
+ /** Vendor model id, or the managed runtime's loaded model. */
15414
+ model: string(),
15415
+ /** Required for openai-compatible; override for cloud kinds. */
15416
+ baseUrl: string().optional(),
15417
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
15418
+ apiKey: string().optional(),
15419
+ supportsVision: boolean(),
15420
+ temperature: number().min(0).max(2).optional(),
15421
+ maxTokens: number().int().positive().optional(),
15422
+ timeoutMs: number().int().positive().default(6e4),
15423
+ extraHeaders: record(string(), string()).optional(),
15424
+ /** kind === 'managed-local' only (spec §4). */
15425
+ runtime: ManagedRuntimeConfigSchema.optional()
15426
+ });
15427
+ /** ConfigUISchema tree passed through untyped on the wire (the
15428
+ * notification-output `ConfigSchemaPassthrough` precedent at
15429
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15430
+ var ConfigSchemaPassthrough$1 = unknown();
15431
+ var LlmProfileKindDescriptorSchema = object({
15432
+ kind: LlmProfileKindSchema,
15433
+ label: string(),
15434
+ icon: string(),
15435
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
15436
+ addonId: string(),
15437
+ configSchema: ConfigSchemaPassthrough$1
15438
+ });
15439
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15440
+ var LlmDefaultSchema = object({
15441
+ selector: LlmDefaultSelectorSchema,
15442
+ profileId: string()
15443
+ });
15444
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
15445
+ var LlmUsageRollupSchema = object({
15446
+ day: string(),
15447
+ consumer: string(),
15448
+ profileId: string(),
15449
+ calls: number(),
15450
+ okCalls: number(),
15451
+ errorCalls: number(),
15452
+ inputTokens: number(),
15453
+ outputTokens: number(),
15454
+ avgLatencyMs: number()
15455
+ });
15456
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15457
+ var ManagedModelCatalogEntrySchema = object({
15458
+ id: string(),
15459
+ label: string(),
15460
+ family: string(),
15461
+ purpose: _enum(["text", "vision"]),
15462
+ url: string(),
15463
+ sha256: string(),
15464
+ sizeBytes: number(),
15465
+ quantization: string(),
15466
+ /** Load-time guidance shown in the picker. */
15467
+ minRamBytes: number(),
15468
+ contextSizeDefault: number().int(),
15469
+ /** Vision models: companion projector file. */
15470
+ mmprojUrl: string().optional()
15471
+ });
15472
+ var LlmRuntimeNodeSchema = object({
15473
+ nodeId: string(),
15474
+ reachable: boolean(),
15475
+ status: LlmRuntimeStatusSchema.optional(),
15476
+ disk: LlmRuntimeDiskUsageSchema.optional(),
15477
+ error: string().optional()
15478
+ });
15479
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
15480
+ var ProfileRefInputSchema = object({
15481
+ addonId: string(),
15482
+ profileId: string()
15483
+ });
15484
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
15485
+ kind: "mutation",
15486
+ auth: "admin"
15487
+ }), method(ProfileRefInputSchema, _void(), {
15488
+ kind: "mutation",
15489
+ auth: "admin"
15490
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
15491
+ kind: "mutation",
15492
+ auth: "admin"
15493
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
15494
+ selector: LlmDefaultSelectorSchema,
15495
+ profileId: string().nullable()
15496
+ }), _void(), {
15497
+ kind: "mutation",
15498
+ auth: "admin"
15499
+ }), method(object({
15500
+ since: number().optional(),
15501
+ until: number().optional(),
15502
+ consumer: string().optional(),
15503
+ profileId: string().optional()
15504
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
15505
+ nodeId: string(),
15506
+ model: ManagedModelRefSchema
15507
+ }), _void(), {
15508
+ kind: "mutation",
15509
+ auth: "admin"
15510
+ }), method(object({
15511
+ nodeId: string(),
15512
+ file: string()
15513
+ }), _void(), {
15514
+ kind: "mutation",
15515
+ auth: "admin"
15516
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
15517
+ kind: "mutation",
15518
+ auth: "admin"
15519
+ }), method(ProfileRefInputSchema, _void(), {
15520
+ kind: "mutation",
15521
+ auth: "admin"
15522
+ });
15523
+ var LogLevelSchema = _enum([
15524
+ "debug",
15525
+ "info",
15526
+ "warn",
15527
+ "error"
15528
+ ]);
15529
+ var LogEntrySchema = object({
15530
+ timestamp: date(),
15531
+ level: LogLevelSchema,
15532
+ scope: array(string()),
15533
+ message: string(),
15534
+ meta: record(string(), unknown()).optional(),
15535
+ tags: record(string(), string()).optional()
15536
+ });
15537
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15538
+ scope: array(string()).optional(),
15539
+ level: LogLevelSchema.optional(),
15540
+ since: date().optional(),
15541
+ until: date().optional(),
15542
+ limit: number().optional(),
15543
+ tags: record(string(), string()).optional()
15544
+ }), array(LogEntrySchema).readonly());
15545
+ /**
15546
+ * `login-method` — collection cap through which auth addons contribute
15547
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
15548
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
15549
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
15550
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
15551
+ * procedure aggregates them for the unauthenticated login page.
15552
+ *
15553
+ * A contribution is a discriminated union on `kind`:
15554
+ *
15555
+ * - `redirect` — a declarative button. The login page renders a generic
15556
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
15557
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
15558
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
15559
+ * login page needs NO change.
15560
+ *
15561
+ * - `widget` — a Module-Federation widget the login page mounts (via
15562
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
15563
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
15564
+ * mechanism kept for future use; no shipped addon uses it on the login
15565
+ * page (the passkey ceremony below runs natively in the shell instead).
15566
+ *
15567
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
15568
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
15569
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
15570
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
15571
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
15572
+ * fetching any remote code pre-auth. Contribution stays unconditional —
15573
+ * enrollment state is never leaked pre-auth; visibility is a shell
15574
+ * decision.
15575
+ *
15576
+ * Every contribution carries a `stage`:
15577
+ * - `primary` — shown on the first credentials screen (OIDC /
15578
+ * magic-link buttons; a future usernameless passkey).
15579
+ * - `second-factor` — shown AFTER the password leg, gated on the
15580
+ * returned `factors` (passkey-as-2FA today).
15581
+ *
15582
+ * `mount: skip` — the cap is read server-side by the core auth router
15583
+ * (`registry.getCollection('login-method')`), never mounted as its own
15584
+ * tRPC router.
15585
+ */
15586
+ /** When a login method renders in the two-phase login flow. */
15587
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
15588
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
15589
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
15590
+ object({
15591
+ kind: literal("redirect"),
15592
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
15593
+ id: string(),
15594
+ /** Operator-facing button label. */
15595
+ label: string(),
15596
+ /** lucide-react icon name. */
15597
+ icon: string().optional(),
15598
+ /** Addon-owned HTTP route the button navigates to (GET). */
15599
+ startUrl: string(),
15600
+ stage: LoginStageEnum
15601
+ }),
15602
+ object({
15603
+ kind: literal("widget"),
15604
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
15605
+ id: string(),
15606
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
15607
+ addonId: string(),
15608
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
15609
+ bundle: string(),
15610
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
15611
+ remote: WidgetRemoteSchema,
15612
+ stage: LoginStageEnum
15613
+ }),
15614
+ object({
15615
+ kind: literal("passkey"),
15616
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
15617
+ id: string(),
15618
+ /** Operator-facing button label. */
15619
+ label: string(),
15620
+ stage: LoginStageEnum,
15621
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
15622
+ rpId: string(),
15623
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
15624
+ origin: string().nullable()
15625
+ })
15626
+ ]);
15627
+ method(_void(), array(LoginMethodContributionSchema).readonly());
15628
+ var CpuBreakdownSchema = object({
15629
+ total: number(),
15630
+ user: number(),
15631
+ system: number(),
15632
+ irq: number(),
15633
+ nice: number(),
15634
+ loadAvg: tuple([
15635
+ number(),
15636
+ number(),
15637
+ number()
15638
+ ]),
15639
+ cores: number()
15640
+ });
15641
+ var MemoryInfoSchema = object({
15642
+ percent: number(),
15643
+ totalBytes: number(),
15644
+ usedBytes: number(),
15645
+ availableBytes: number(),
15646
+ swapUsedBytes: number(),
15647
+ swapTotalBytes: number()
15340
15648
  });
15341
15649
  var DiskIoSnapshotSchema = object({
15342
15650
  readBytes: number(),
@@ -15789,14 +16097,14 @@ var TargetKindCapsSchema = object({
15789
16097
  * the union is large and not meant for runtime validation here; the exported
15790
16098
  * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
15791
16099
  */
15792
- var ConfigSchemaPassthrough$1 = unknown();
16100
+ var ConfigSchemaPassthrough = unknown();
15793
16101
  var TargetKindSchema = object({
15794
16102
  kind: string(),
15795
16103
  label: string(),
15796
16104
  icon: string(),
15797
16105
  /** Stamped by each provider so the concat-fanned catalog stays routable. */
15798
16106
  addonId: string(),
15799
- configSchema: ConfigSchemaPassthrough$1,
16107
+ configSchema: ConfigSchemaPassthrough,
15800
16108
  supportsDiscovery: boolean(),
15801
16109
  caps: TargetKindCapsSchema
15802
16110
  });
@@ -15849,297 +16157,493 @@ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSche
15849
16157
  enabled: boolean()
15850
16158
  }), _void(), { kind: "mutation" });
15851
16159
  /**
15852
- * Shared LLM generate contracts imported by BOTH `llm.cap.ts` (consumer
15853
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15854
- * caps stay wire-compatible without a circular cap→cap import.
16160
+ * notification-rules the Notification Center rule surface (P1 core).
15855
16161
  *
15856
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
15857
- * every transport tier structurally, and failed calls still write usage rows.
15858
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15859
- */
15860
- var LlmUsageSchema = object({
15861
- inputTokens: number(),
15862
- outputTokens: number()
15863
- });
15864
- var LlmErrorCodeSchema = _enum([
15865
- "timeout",
15866
- "rate-limited",
15867
- "auth",
15868
- "refusal",
15869
- "bad-request",
15870
- "unavailable",
15871
- "no-profile",
15872
- "budget-exceeded",
15873
- "adapter-error"
15874
- ]);
15875
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15876
- ok: literal(true),
15877
- text: string(),
15878
- model: string(),
15879
- usage: LlmUsageSchema,
15880
- truncated: boolean(),
15881
- latencyMs: number()
15882
- }), object({
15883
- ok: literal(false),
15884
- code: LlmErrorCodeSchema,
15885
- message: string(),
15886
- retryAfterMs: number().optional()
15887
- })]);
16162
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16163
+ * (operator decisions D-1/D-2/D-3 are binding):
16164
+ *
16165
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16166
+ * `notification-center` module), hooked on the durable persistence
16167
+ * moments (object-event insert, TrackCloser.closeExpired) with a
16168
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
16169
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16170
+ * FIRST persisted detection matching the conditions (per-track dedup,
16171
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16172
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
16173
+ * - DISPATCH stays behind `notification-output` (rules reference targets
16174
+ * by id; per-backend params are a passthrough blob capped by the
16175
+ * target kind's own caps/degrade engine).
16176
+ *
16177
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
16178
+ * server-injected caller identity — the first `caller: 'required'`
16179
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
16180
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
16181
+ * windows, and the optional label/identity/plate matchers. User rules,
16182
+ * private zones, per-recipient fan-out and the wider condition table are
16183
+ * P2+ (see spec §7).
16184
+ *
16185
+ * All schemas here are the single source of truth — `NcRule` etc. are
16186
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16187
+ * schema/interface drift is explicitly not repeated).
16188
+ */
15888
16189
  /**
15889
- * `Uint8Array` is the sanctioned binary conventionsuperjson + the UDS
15890
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15891
- * notification-output.cap.ts:27-31 precedents).
16190
+ * D-3: the trigger/urgency of a rule which persistence moment evaluates it.
16191
+ * The value maps 1:1 onto the evaluated record kind:
16192
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16193
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16194
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16195
+ * change of a LINKED device, one row per linked camera)
16196
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16197
+ * delivery / pick-up)
16198
+ *
16199
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16200
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
16201
+ * this one field keeps the schema additive — a rule still declares exactly
16202
+ * one trigger.
15892
16203
  */
15893
- var LlmImageSchema = object({
15894
- bytes: _instanceof(Uint8Array),
15895
- mimeType: string()
16204
+ var NcDeliverySchema = _enum([
16205
+ "immediate",
16206
+ "track-end",
16207
+ "device-event",
16208
+ "package-event"
16209
+ ]);
16210
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
16211
+ var NcScheduleSchema = object({
16212
+ windows: array(object({
16213
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16214
+ days: array(number().int().min(0).max(6)).min(1),
16215
+ startMinute: number().int().min(0).max(1439),
16216
+ endMinute: number().int().min(0).max(1439)
16217
+ })).min(1),
16218
+ /** IANA timezone; default = hub host timezone. */
16219
+ timezone: string().optional(),
16220
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16221
+ invert: boolean().optional()
15896
16222
  });
15897
- var LlmGenerateBaseInputSchema = object({
15898
- /** Collection routing (the notification-output posture). */
15899
- addonId: string().optional(),
15900
- /** Explicit profile; else the resolution chain (spec §3). */
15901
- profileId: string().optional(),
15902
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15903
- consumer: string(),
15904
- system: string().optional(),
15905
- /** v1: single-turn. `messages[]` is a v2 additive field. */
15906
- prompt: string(),
15907
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15908
- jsonSchema: record(string(), unknown()).optional(),
15909
- /** Per-call override of the profile default. */
15910
- maxTokens: number().int().positive().optional(),
15911
- temperature: number().optional()
16223
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16224
+ var NcPlateMatcherSchema = object({
16225
+ values: array(string().min(1)).min(1),
16226
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16227
+ maxDistance: number().int().min(0).max(3).default(1)
15912
16228
  });
15913
16229
  /**
15914
- * `llm-runtime` node-side managed llama.cpp executor (spec §4). Registered
15915
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15916
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` normal
15917
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15918
- * this only through the `llm` cap's methods.
15919
- *
15920
- * One running llama-server child per node in v1 (models are RAM-heavy).
15921
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15922
- * watchdog operator decision #3).
16230
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16231
+ * occupancy edge for a device optionally narrowed to a single admin
16232
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16233
+ * - `became-occupied` (default) count crossed 0 `count`
16234
+ * - `became-free` — count crossed `count` below it
16235
+ * - `>=` / `<=` — count is at/over or at/under `count`
16236
+ * `sustainSeconds` requires the condition hold continuously that long
16237
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
16238
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16239
+ * the condition never matches. Confirmed edge-state survives addon restarts
16240
+ * (declared SQLite collection, reseeded on boot).
15923
16241
  */
15924
- var ManagedModelRefSchema = discriminatedUnion("kind", [
15925
- object({
15926
- kind: literal("catalog"),
15927
- catalogId: string()
15928
- }),
15929
- object({
15930
- kind: literal("url"),
15931
- url: string(),
15932
- sha256: string().optional()
15933
- }),
15934
- object({
15935
- kind: literal("path"),
15936
- path: string()
15937
- })
15938
- ]);
15939
- var ManagedRuntimeConfigSchema = object({
15940
- /** WHERE the runtime lives — hub or any agent. */
15941
- nodeId: string(),
15942
- /** Closed for v1; 'ollama' is a v2 candidate. */
15943
- engine: _enum(["llama-cpp"]),
15944
- model: ManagedModelRefSchema,
15945
- contextSize: number().int().default(4096),
15946
- /** 0 = CPU-only. */
15947
- gpuLayers: number().int().default(0),
15948
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15949
- threads: number().int().optional(),
15950
- /** Concurrent slots. */
15951
- parallel: number().int().default(1),
15952
- /** Else lazy: first generate boots it. */
15953
- autoStart: boolean().default(false),
15954
- /** 0 = never; frees RAM after quiet periods. */
15955
- idleStopMinutes: number().int().default(30)
16242
+ var NcOccupancyConditionSchema = object({
16243
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16244
+ zoneId: string().optional(),
16245
+ /** Object class to count; absent = any class. */
16246
+ className: string().optional(),
16247
+ op: _enum([
16248
+ "became-occupied",
16249
+ "became-free",
16250
+ ">=",
16251
+ "<="
16252
+ ]).default("became-occupied"),
16253
+ count: number().int().min(0).default(1),
16254
+ sustainSeconds: number().int().min(0).max(3600).default(15)
16255
+ });
16256
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16257
+ var NcZoneConditionSchema = object({
16258
+ ids: array(string().min(1)).min(1),
16259
+ /** Quantifier over `ids` — at least one / every one visited. */
16260
+ match: _enum(["any", "all"]).default("any")
15956
16261
  });
15957
- var LlmRuntimeStatusSchema = object({
15958
- /** Status is ALWAYS node-qualified. */
15959
- nodeId: string(),
15960
- state: _enum([
15961
- "stopped",
15962
- "downloading",
15963
- "starting",
15964
- "ready",
15965
- "crashed",
15966
- "failed"
15967
- ]),
15968
- pid: number().optional(),
15969
- port: number().optional(),
15970
- modelPath: string().optional(),
15971
- modelId: string().optional(),
15972
- downloadProgress: number().min(0).max(1).optional(),
15973
- lastError: string().optional(),
15974
- crashesInWindow: number(),
15975
- /** Child RSS (sampled best-effort). */
15976
- memoryBytes: number().optional(),
15977
- vramBytes: number().optional()
16262
+ /**
16263
+ * The P1 condition set — a flat AND of groups; absent group = pass;
16264
+ * membership lists are OR within the list (spec §2.3).
16265
+ */
16266
+ var NcConditionsSchema = object({
16267
+ /** Device scope — absent = all devices. */
16268
+ devices: array(number()).optional(),
16269
+ /** Detector class names (any overlap with the record's class set). */
16270
+ classes: array(string().min(1)).optional(),
16271
+ /** Veto classes — any overlap fails the rule. */
16272
+ classesExclude: array(string().min(1)).optional(),
16273
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
16274
+ minConfidence: number().min(0).max(1).optional(),
16275
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
16276
+ zones: NcZoneConditionSchema.optional(),
16277
+ /** Veto zones — any hit fails the rule. */
16278
+ zonesExclude: array(string().min(1)).optional(),
16279
+ /**
16280
+ * Exact (case-insensitive) match on the record's collapsed `label`
16281
+ * (identity name / plate text / subclass).
16282
+ */
16283
+ labelEquals: array(string().min(1)).optional(),
16284
+ /**
16285
+ * Identity matcher. P1 boundary: matched against the record's collapsed
16286
+ * `label` (the identity display name propagated by the face pipeline) —
16287
+ * identity-ID matching rides in P2 when identity ids reach the record.
16288
+ */
16289
+ identities: array(string().min(1)).optional(),
16290
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
16291
+ plates: NcPlateMatcherSchema.optional(),
16292
+ /**
16293
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16294
+ * Same P1 boundary: matched against the record's collapsed `label` (the
16295
+ * identity display name). A record with NO label passes (nothing to
16296
+ * exclude), unlike the include variant which fails on an absent label.
16297
+ */
16298
+ identitiesExclude: array(string().min(1)).optional(),
16299
+ /**
16300
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16301
+ * TRACK-END only: importance is scored at track close, so it does not exist
16302
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16303
+ * close the value is threaded via the close-time info (the `Track` clone is
16304
+ * captured before the DB row is updated, so it would otherwise read stale).
16305
+ * Fails when the record carries no importance (never guess quality — the
16306
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
16307
+ */
16308
+ minImportance: number().min(0).max(1).optional(),
16309
+ /**
16310
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16311
+ * TRACK-END only: an `immediate` / object-event subject has no closed
16312
+ * lifespan, so a dwell condition never matches immediate delivery
16313
+ * (documented choice — the object-event record carries no `firstSeen`,
16314
+ * so dwell cannot be computed from what the subject actually carries).
16315
+ */
16316
+ minDwellSeconds: number().min(0).optional(),
16317
+ /**
16318
+ * Detection provenance filter. `any` (default / absent) matches every
16319
+ * source; otherwise the subject's source must equal it. Legacy records
16320
+ * with no stamped source are treated as `pipeline`. The union spans both
16321
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
16322
+ * tracks carry `sensor`.
16323
+ */
16324
+ source: _enum([
16325
+ "pipeline",
16326
+ "onboard",
16327
+ "sensor",
16328
+ "any"
16329
+ ]).optional(),
16330
+ /**
16331
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16332
+ * detector `minConfidence` (that gates the object-detection score; this
16333
+ * gates the recognition/OCR match score). Fails when the subject carries
16334
+ * no label-match confidence (never guess). TRACK-END only: the confidence
16335
+ * lives on the recognition result and reaches the subject at track close.
16336
+ *
16337
+ * What it measures precisely (plumbed at track close — the closer threads
16338
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16339
+ * `importance`): the BEST recognition match confidence observed for the
16340
+ * label the track carries at close — for a face, the peak cosine similarity
16341
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16342
+ * for a plate, the peak OCR read score of the best-held plate
16343
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16344
+ * one track the higher of the two is used. A track that ended with no
16345
+ * confident identity/plate match carries no value, so the condition fails
16346
+ * closed for it (an un-recognized subject).
16347
+ */
16348
+ minLabelConfidence: number().min(0).max(1).optional(),
16349
+ /**
16350
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16351
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16352
+ * against the token carried on the device-event subject (extracted from the
16353
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16354
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16355
+ * eventType, so gate those with {@link sensorKinds} instead.
16356
+ */
16357
+ eventTypeTokens: array(string().min(1)).optional(),
16358
+ /**
16359
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16360
+ * `contact`, `button`, `device-event`) — matched against the persisted
16361
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16362
+ */
16363
+ sensorKinds: array(string().min(1)).optional(),
16364
+ /**
16365
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16366
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16367
+ * when the subject's phase does not match (a subject always carries a phase
16368
+ * on the package-event trigger).
16369
+ */
16370
+ packagePhase: _enum([
16371
+ "delivered",
16372
+ "picked-up",
16373
+ "both"
16374
+ ]).optional(),
16375
+ /**
16376
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16377
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16378
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
16379
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16380
+ */
16381
+ customZones: array(MaskPolygonShapeSchema).optional(),
16382
+ /**
16383
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16384
+ * (optionally zone/class-scoped) occupancy count crosses the configured
16385
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
16386
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16387
+ */
16388
+ occupancy: NcOccupancyConditionSchema.optional()
15978
16389
  });
15979
- var LlmNodeModelSchema = object({
15980
- file: string(),
15981
- sizeBytes: number(),
15982
- catalogId: string().optional(),
15983
- installedAt: number().optional()
16390
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
16391
+ var NcRuleTargetSchema = object({
16392
+ /** `notification-output` Target id. */
16393
+ targetId: string().min(1),
16394
+ /**
16395
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
16396
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16397
+ * degrade engine drops what the backend can't render.
16398
+ */
16399
+ params: record(string(), unknown()).optional()
15984
16400
  });
15985
- var LlmRuntimeDiskUsageSchema = object({
15986
- nodeId: string(),
15987
- modelsBytes: number(),
15988
- freeBytes: number().optional()
16401
+ /**
16402
+ * Media attachment policy (P1 still-image subset).
16403
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
16404
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
16405
+ * matched on identities attaches the subject's `faceCrop`, one matched on
16406
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
16407
+ * (or when the specific crop is missing) degrades to `best`, then
16408
+ * `keyFrame`, then no attachment — never delaying the send. The matched
16409
+ * condition summary is frozen on the outbox row at enqueue (like the rule
16410
+ * name), so the choice never drifts from the record that fired it.
16411
+ * - `keyFrame` — the clean scene frame (no subject box).
16412
+ * - `none` — no attachment.
16413
+ */
16414
+ var NcMediaPolicySchema = object({ attach: _enum([
16415
+ "best",
16416
+ "best-matching",
16417
+ "keyFrame",
16418
+ "none"
16419
+ ]).default("best") });
16420
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16421
+ var NcThrottleSchema = object({
16422
+ cooldownSec: number().int().min(0).max(86400).default(60),
16423
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16424
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
16425
+ });
16426
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16427
+ var NcRuleInputSchema = object({
16428
+ name: string().min(1).max(200),
16429
+ enabled: boolean().default(true),
16430
+ delivery: NcDeliverySchema,
16431
+ conditions: NcConditionsSchema.default({}),
16432
+ schedule: NcScheduleSchema.optional(),
16433
+ targets: array(NcRuleTargetSchema).min(1),
16434
+ media: NcMediaPolicySchema.default({ attach: "best" }),
16435
+ throttle: NcThrottleSchema.default({
16436
+ cooldownSec: 60,
16437
+ scope: "rule-device"
16438
+ }),
16439
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16440
+ template: object({
16441
+ title: string().max(500).optional(),
16442
+ body: string().max(2e3).optional()
16443
+ }).optional(),
16444
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
16445
+ priority: number().int().min(1).max(5).default(3),
16446
+ /**
16447
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16448
+ * behaviour, visible to all, read-only in the viewer). Present = personal
16449
+ * rule owned by this userId. Server-stamped; never trusted from a client.
16450
+ */
16451
+ ownerUserId: string().optional()
15989
16452
  });
15990
- method(LlmGenerateBaseInputSchema.extend({
15991
- images: array(LlmImageSchema).optional(),
15992
- runtime: ManagedRuntimeConfigSchema,
15993
- /** The managed profile's timeout, threaded by the hub provider. */
15994
- timeoutMs: number().int().positive().optional()
15995
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15996
- kind: "mutation",
15997
- auth: "admin"
15998
- }), method(object({}), _void(), {
15999
- kind: "mutation",
16000
- auth: "admin"
16001
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
16002
- kind: "mutation",
16003
- auth: "admin"
16004
- }), method(object({ file: string() }), _void(), {
16005
- kind: "mutation",
16006
- auth: "admin"
16007
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
16008
16453
  /**
16009
- * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
16010
- * methods concat-fan across providers; single-row methods route to ONE
16011
- * provider by the `addonId` in the call input (the notification-output
16012
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
16013
- * (hub-placed); the cap stays open for future providers.
16014
- *
16015
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
16016
- * `apiKey` is a password field — providers REDACT it on read and merge on
16017
- * write; a stored key NEVER round-trips to a client.
16454
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
16455
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16456
+ * NOT a client-authored input field (it lives on the persisted rule, not the
16457
+ * input), so it is added here explicitly to let the store's per-target opt-out
16458
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16459
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16460
+ * `updateRule` patch.
16018
16461
  */
16019
- var LlmProfileKindSchema = _enum([
16020
- "openai-compatible",
16021
- "openai",
16022
- "anthropic",
16023
- "google",
16024
- "managed-local"
16025
- ]);
16026
- var LlmProfileSchema = object({
16462
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
16463
+ /** A persisted rule. */
16464
+ var NcRuleSchema = NcRuleInputSchema.extend({
16027
16465
  id: string(),
16028
- name: string(),
16029
- kind: LlmProfileKindSchema,
16030
- /** Stamped by the provider — keeps the fanned catalog routable. */
16031
- addonId: string(),
16032
- enabled: boolean(),
16033
- /** Vendor model id, or the managed runtime's loaded model. */
16034
- model: string(),
16035
- /** Required for openai-compatible; override for cloud kinds. */
16036
- baseUrl: string().optional(),
16037
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
16038
- apiKey: string().optional(),
16039
- supportsVision: boolean(),
16040
- temperature: number().min(0).max(2).optional(),
16041
- maxTokens: number().int().positive().optional(),
16042
- timeoutMs: number().int().positive().default(6e4),
16043
- extraHeaders: record(string(), string()).optional(),
16044
- /** kind === 'managed-local' only (spec §4). */
16045
- runtime: ManagedRuntimeConfigSchema.optional()
16046
- });
16047
- /** ConfigUISchema tree passed through untyped on the wire (the
16048
- * notification-output `ConfigSchemaPassthrough` precedent at
16049
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
16050
- var ConfigSchemaPassthrough = unknown();
16051
- var LlmProfileKindDescriptorSchema = object({
16052
- kind: LlmProfileKindSchema,
16053
- label: string(),
16054
- icon: string(),
16055
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
16056
- addonId: string(),
16057
- configSchema: ConfigSchemaPassthrough
16058
- });
16059
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
16060
- var LlmDefaultSchema = object({
16061
- selector: LlmDefaultSelectorSchema,
16062
- profileId: string()
16466
+ /** userId of the admin who created the rule (server-stamped caller). */
16467
+ createdBy: string(),
16468
+ createdAt: number(),
16469
+ updatedAt: number(),
16470
+ /**
16471
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16472
+ * send time. Only a target's OWNER may add/remove its id (server-checked
16473
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
16474
+ */
16475
+ disabledTargetIds: array(string()).default([])
16063
16476
  });
16064
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
16065
- var LlmUsageRollupSchema = object({
16066
- day: string(),
16067
- consumer: string(),
16068
- profileId: string(),
16069
- calls: number(),
16070
- okCalls: number(),
16071
- errorCalls: number(),
16072
- inputTokens: number(),
16073
- outputTokens: number(),
16074
- avgLatencyMs: number()
16477
+ var NcTestResultSchema = object({
16478
+ recordId: string(),
16479
+ recordKind: _enum([
16480
+ "object-event",
16481
+ "track",
16482
+ "device-event",
16483
+ "package-event"
16484
+ ]),
16485
+ deviceId: number(),
16486
+ timestamp: number(),
16487
+ wouldFire: boolean(),
16488
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
16489
+ failedCondition: string().optional(),
16490
+ className: string().optional(),
16491
+ label: string().optional()
16075
16492
  });
16076
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
16077
- var ManagedModelCatalogEntrySchema = object({
16493
+ var NcConditionDescriptorSchema = object({
16494
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16078
16495
  id: string(),
16496
+ group: _enum([
16497
+ "scope",
16498
+ "class",
16499
+ "zones",
16500
+ "quality",
16501
+ "label",
16502
+ "schedule",
16503
+ "device",
16504
+ "package",
16505
+ "occupancy"
16506
+ ]),
16079
16507
  label: string(),
16080
- family: string(),
16081
- purpose: _enum(["text", "vision"]),
16082
- url: string(),
16083
- sha256: string(),
16084
- sizeBytes: number(),
16085
- quantization: string(),
16086
- /** Load-time guidance shown in the picker. */
16087
- minRamBytes: number(),
16088
- contextSizeDefault: number().int(),
16089
- /** Vision models: companion projector file. */
16090
- mmprojUrl: string().optional()
16508
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
16509
+ valueType: _enum([
16510
+ "deviceIdList",
16511
+ "stringList",
16512
+ "number01",
16513
+ "number",
16514
+ "sourceSelect",
16515
+ "zoneSelection",
16516
+ "zoneIdList",
16517
+ "schedule",
16518
+ "plateMatcher",
16519
+ "packagePhase",
16520
+ "polygonDraw",
16521
+ "occupancy"
16522
+ ]),
16523
+ operator: _enum([
16524
+ "in",
16525
+ "notIn",
16526
+ "anyOf",
16527
+ "allOf",
16528
+ "gte",
16529
+ "fuzzyIn",
16530
+ "withinSchedule"
16531
+ ]),
16532
+ /** Which delivery kinds the condition applies to. */
16533
+ appliesTo: array(NcDeliverySchema),
16534
+ phase: string(),
16535
+ description: string().optional()
16091
16536
  });
16092
- var LlmRuntimeNodeSchema = object({
16093
- nodeId: string(),
16094
- reachable: boolean(),
16095
- status: LlmRuntimeStatusSchema.optional(),
16096
- disk: LlmRuntimeDiskUsageSchema.optional(),
16097
- error: string().optional()
16537
+ /**
16538
+ * The delivery lifecycle status of a history row — a straight read of the
16539
+ * durable outbox row's own status (single source of truth):
16540
+ * - `pending` — enqueued, in-flight or retrying with backoff
16541
+ * - `sent` — delivered (terminal)
16542
+ * - `dead` — dead-lettered after exhausting retries / a permanent
16543
+ * backend rejection / a deleted target (terminal; carries
16544
+ * the failure `error`)
16545
+ *
16546
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
16547
+ * user dimension (quiet hours / snooze) and are additive when they land.
16548
+ */
16549
+ var NcHistoryStatusSchema = _enum([
16550
+ "pending",
16551
+ "sent",
16552
+ "dead"
16553
+ ]);
16554
+ /** The evaluated record kind a history row descends from (one per trigger). */
16555
+ var NcHistoryRecordKindSchema = _enum([
16556
+ "object-event",
16557
+ "track-end",
16558
+ "device-event",
16559
+ "package-event"
16560
+ ]);
16561
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16562
+ var NcHistorySubjectSchema = object({
16563
+ className: string(),
16564
+ label: string().optional(),
16565
+ confidence: number().optional(),
16566
+ zones: array(string()),
16567
+ timestamp: number()
16568
+ });
16569
+ /**
16570
+ * One delivery-history row. This is a read-only VIEW over the durable
16571
+ * outbox row (single source of truth — the same row the drain loop drives;
16572
+ * NO second write path, so history can never drift from delivery state).
16573
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16574
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16575
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
16576
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16577
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16578
+ * P1 (admin scope only).
16579
+ */
16580
+ var NcHistoryEntrySchema = object({
16581
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16582
+ id: string(),
16583
+ ruleId: string(),
16584
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
16585
+ ruleName: string(),
16586
+ /** The rule urgency/trigger that produced this delivery. */
16587
+ delivery: NcDeliverySchema,
16588
+ targetId: string(),
16589
+ deviceId: number(),
16590
+ recordKind: NcHistoryRecordKindSchema,
16591
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16592
+ recordId: string(),
16593
+ /** Present for track-scoped deliveries (object-event / track-end). */
16594
+ trackId: string().optional(),
16595
+ status: NcHistoryStatusSchema,
16596
+ /** Delivery attempts made so far. */
16597
+ attempts: number().int(),
16598
+ /** Fire time (outbox enqueue). */
16599
+ createdAt: number(),
16600
+ /** Last transition time (terminal for sent / dead). */
16601
+ updatedAt: number(),
16602
+ /** Failure detail — present on a `dead` row. */
16603
+ error: string().optional(),
16604
+ subject: NcHistorySubjectSchema
16098
16605
  });
16099
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16100
- var ProfileRefInputSchema = object({
16101
- addonId: string(),
16102
- profileId: string()
16606
+ /**
16607
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16608
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16609
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16610
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16611
+ */
16612
+ var NcHistoryFilterSchema = object({
16613
+ ruleId: string().optional(),
16614
+ deviceId: number().optional(),
16615
+ status: NcHistoryStatusSchema.optional(),
16616
+ since: number().optional(),
16617
+ until: number().optional(),
16618
+ limit: number().int().min(1).max(500).default(100)
16103
16619
  });
16104
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16105
- kind: "mutation",
16106
- auth: "admin"
16107
- }), method(ProfileRefInputSchema, _void(), {
16620
+ 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 }), {
16108
16621
  kind: "mutation",
16109
- auth: "admin"
16110
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16622
+ auth: "admin",
16623
+ caller: "required"
16624
+ }), method(object({
16625
+ ruleId: string(),
16626
+ patch: NcRulePatchSchema
16627
+ }), object({ rule: NcRuleSchema }), {
16111
16628
  kind: "mutation",
16112
- auth: "admin"
16113
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
16114
- selector: LlmDefaultSelectorSchema,
16115
- profileId: string().nullable()
16116
- }), _void(), {
16629
+ auth: "admin",
16630
+ caller: "required"
16631
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
16117
16632
  kind: "mutation",
16118
16633
  auth: "admin"
16119
16634
  }), method(object({
16120
- since: number().optional(),
16121
- until: number().optional(),
16122
- consumer: string().optional(),
16123
- profileId: string().optional()
16124
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
16125
- nodeId: string(),
16126
- model: ManagedModelRefSchema
16127
- }), _void(), {
16635
+ ruleId: string(),
16636
+ enabled: boolean()
16637
+ }), object({ success: literal(true) }), {
16128
16638
  kind: "mutation",
16129
16639
  auth: "admin"
16130
16640
  }), method(object({
16131
- nodeId: string(),
16132
- file: string()
16133
- }), _void(), {
16134
- kind: "mutation",
16135
- auth: "admin"
16136
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16137
- kind: "mutation",
16138
- auth: "admin"
16139
- }), method(ProfileRefInputSchema, _void(), {
16641
+ rule: NcRuleInputSchema,
16642
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
16643
+ }), object({ results: array(NcTestResultSchema) }), {
16140
16644
  kind: "mutation",
16141
16645
  auth: "admin"
16142
- });
16646
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
16143
16647
  /**
16144
16648
  * Zod schemas for persisted record types.
16145
16649
  *
@@ -16825,7 +17329,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16825
17329
  }), method(object({
16826
17330
  eventId: string(),
16827
17331
  kind: MediaFileKindEnum.optional()
16828
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
17332
+ }), array(MediaFileSchema).readonly()), method(object({
17333
+ trackId: string(),
17334
+ kinds: array(MediaFileKindEnum).optional()
17335
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
16829
17336
  deviceId: number(),
16830
17337
  timestamp: number(),
16831
17338
  frameWidth: number(),
@@ -16846,76 +17353,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16846
17353
  eventId: string(),
16847
17354
  timestamp: number()
16848
17355
  });
16849
- /**
16850
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
16851
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
16852
- * caps into per-camera event-kind descriptors.
16853
- *
16854
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
16855
- * is NOT duplicated here — every entry is derived from the single
16856
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
16857
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
16858
- * control cap means adding one line here (and a taxonomy entry); the anti-
16859
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
16860
- * eventful cap is missing.
16861
- */
16862
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
16863
- var LEGACY_ICON = {
16864
- motion: "motion",
16865
- audio: "audio",
16866
- person: "person",
16867
- vehicle: "vehicle",
16868
- animal: "animal",
16869
- package: "package",
16870
- door: "door",
16871
- pir: "pir",
16872
- smoke: "smoke",
16873
- water: "water",
16874
- button: "button",
16875
- generic: "generic",
16876
- gas: "smoke",
16877
- vibration: "generic",
16878
- tamper: "generic",
16879
- presence: "person",
16880
- lock: "generic",
16881
- siren: "generic",
16882
- switch: "generic",
16883
- doorbell: "button"
16884
- };
16885
- function legacyIcon(iconId) {
16886
- return LEGACY_ICON[iconId] ?? "generic";
16887
- }
16888
- /**
16889
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
16890
- * The anti-drift guard cross-checks this against the eventful caps declared
16891
- * in `packages/types/src/capabilities/*.cap.ts`.
16892
- */
16893
- var CAP_TO_KIND = {
16894
- contact: "contact",
16895
- motion: "motion-sensor",
16896
- smoke: "smoke",
16897
- flood: "flood",
16898
- gas: "gas",
16899
- "carbon-monoxide": "carbon-monoxide",
16900
- vibration: "vibration",
16901
- tamper: "tamper",
16902
- presence: "presence",
16903
- "enum-sensor": "enum-sensor",
16904
- "event-emitter": "device-event",
16905
- "lock-control": "lock",
16906
- switch: "switch",
16907
- button: "button",
16908
- doorbell: "doorbell"
16909
- };
16910
- function buildDescriptor(capName, kind) {
16911
- const t = EVENT_TAXONOMY[kind];
16912
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
16913
- return {
16914
- ...t,
16915
- icon: legacyIcon(t.iconId)
16916
- };
16917
- }
16918
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
16919
17356
  var CameraPipelineConfigSchema = object({
16920
17357
  engine: PipelineEngineChoiceSchema.optional(),
16921
17358
  steps: array(PipelineStepInputSchema).readonly(),
@@ -17401,6 +17838,76 @@ method(object({
17401
17838
  auth: "admin"
17402
17839
  });
17403
17840
  /**
17841
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
17842
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
17843
+ * caps into per-camera event-kind descriptors.
17844
+ *
17845
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
17846
+ * is NOT duplicated here — every entry is derived from the single
17847
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
17848
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
17849
+ * control cap means adding one line here (and a taxonomy entry); the anti-
17850
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
17851
+ * eventful cap is missing.
17852
+ */
17853
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
17854
+ var LEGACY_ICON = {
17855
+ motion: "motion",
17856
+ audio: "audio",
17857
+ person: "person",
17858
+ vehicle: "vehicle",
17859
+ animal: "animal",
17860
+ package: "package",
17861
+ door: "door",
17862
+ pir: "pir",
17863
+ smoke: "smoke",
17864
+ water: "water",
17865
+ button: "button",
17866
+ generic: "generic",
17867
+ gas: "smoke",
17868
+ vibration: "generic",
17869
+ tamper: "generic",
17870
+ presence: "person",
17871
+ lock: "generic",
17872
+ siren: "generic",
17873
+ switch: "generic",
17874
+ doorbell: "button"
17875
+ };
17876
+ function legacyIcon(iconId) {
17877
+ return LEGACY_ICON[iconId] ?? "generic";
17878
+ }
17879
+ /**
17880
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
17881
+ * The anti-drift guard cross-checks this against the eventful caps declared
17882
+ * in `packages/types/src/capabilities/*.cap.ts`.
17883
+ */
17884
+ var CAP_TO_KIND = {
17885
+ contact: "contact",
17886
+ motion: "motion-sensor",
17887
+ smoke: "smoke",
17888
+ flood: "flood",
17889
+ gas: "gas",
17890
+ "carbon-monoxide": "carbon-monoxide",
17891
+ vibration: "vibration",
17892
+ tamper: "tamper",
17893
+ presence: "presence",
17894
+ "enum-sensor": "enum-sensor",
17895
+ "event-emitter": "device-event",
17896
+ "lock-control": "lock",
17897
+ switch: "switch",
17898
+ button: "button",
17899
+ doorbell: "doorbell"
17900
+ };
17901
+ function buildDescriptor(capName, kind) {
17902
+ const t = EVENT_TAXONOMY[kind];
17903
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
17904
+ return {
17905
+ ...t,
17906
+ icon: legacyIcon(t.iconId)
17907
+ };
17908
+ }
17909
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
17910
+ /**
17404
17911
  * server-management — per-NODE singleton capability for a node's ROOT
17405
17912
  * package lifecycle (runtime-updatable node packages).
17406
17913
  *
@@ -18855,7 +19362,28 @@ var FaceInfoSchema = object({
18855
19362
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
18856
19363
  * track produced no key frame (e.g. native/onboard source) — the UI falls
18857
19364
  * back to the inline `base64` face crop. */
18858
- keyFrameMediaKey: string().optional()
19365
+ keyFrameMediaKey: string().optional(),
19366
+ /** Winning identity-match cosine (0..1) for this face's track, when an
19367
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
19368
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
19369
+ * faces that were never auto-recognized. */
19370
+ bestMatchScore: number().optional(),
19371
+ /** Native-scale face short side (px) at recognition time, when the runner
19372
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
19373
+ * legacy rows / runners that reported no native measure. */
19374
+ nativeFaceShortSidePx: number().optional(),
19375
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
19376
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
19377
+ * but blocked only by the recognition size floor). Mutually exclusive with
19378
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
19379
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
19380
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
19381
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
19382
+ suggestedIdentityId: string().optional(),
19383
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
19384
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
19385
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
19386
+ suggestedMatchScore: number().optional()
18859
19387
  });
18860
19388
  var FaceFilterEnum = _enum([
18861
19389
  "unassigned",
@@ -20898,36 +21426,6 @@ Object.freeze({
20898
21426
  addonId: null,
20899
21427
  access: "view"
20900
21428
  },
20901
- "advancedNotifier.deleteRule": {
20902
- capName: "advanced-notifier",
20903
- capScope: "system",
20904
- addonId: null,
20905
- access: "delete"
20906
- },
20907
- "advancedNotifier.getHistory": {
20908
- capName: "advanced-notifier",
20909
- capScope: "system",
20910
- addonId: null,
20911
- access: "view"
20912
- },
20913
- "advancedNotifier.getRules": {
20914
- capName: "advanced-notifier",
20915
- capScope: "system",
20916
- addonId: null,
20917
- access: "view"
20918
- },
20919
- "advancedNotifier.testRule": {
20920
- capName: "advanced-notifier",
20921
- capScope: "system",
20922
- addonId: null,
20923
- access: "create"
20924
- },
20925
- "advancedNotifier.upsertRule": {
20926
- capName: "advanced-notifier",
20927
- capScope: "system",
20928
- addonId: null,
20929
- access: "create"
20930
- },
20931
21429
  "alarmPanel.arm": {
20932
21430
  capName: "alarm-panel",
20933
21431
  capScope: "device",
@@ -23232,6 +23730,60 @@ Object.freeze({
23232
23730
  addonId: null,
23233
23731
  access: "create"
23234
23732
  },
23733
+ "notificationRules.createRule": {
23734
+ capName: "notification-rules",
23735
+ capScope: "system",
23736
+ addonId: null,
23737
+ access: "create"
23738
+ },
23739
+ "notificationRules.deleteRule": {
23740
+ capName: "notification-rules",
23741
+ capScope: "system",
23742
+ addonId: null,
23743
+ access: "delete"
23744
+ },
23745
+ "notificationRules.getConditionCatalog": {
23746
+ capName: "notification-rules",
23747
+ capScope: "system",
23748
+ addonId: null,
23749
+ access: "view"
23750
+ },
23751
+ "notificationRules.getHistory": {
23752
+ capName: "notification-rules",
23753
+ capScope: "system",
23754
+ addonId: null,
23755
+ access: "view"
23756
+ },
23757
+ "notificationRules.getRule": {
23758
+ capName: "notification-rules",
23759
+ capScope: "system",
23760
+ addonId: null,
23761
+ access: "view"
23762
+ },
23763
+ "notificationRules.listRules": {
23764
+ capName: "notification-rules",
23765
+ capScope: "system",
23766
+ addonId: null,
23767
+ access: "view"
23768
+ },
23769
+ "notificationRules.setRuleEnabled": {
23770
+ capName: "notification-rules",
23771
+ capScope: "system",
23772
+ addonId: null,
23773
+ access: "create"
23774
+ },
23775
+ "notificationRules.testRule": {
23776
+ capName: "notification-rules",
23777
+ capScope: "system",
23778
+ addonId: null,
23779
+ access: "create"
23780
+ },
23781
+ "notificationRules.updateRule": {
23782
+ capName: "notification-rules",
23783
+ capScope: "system",
23784
+ addonId: null,
23785
+ access: "create"
23786
+ },
23235
23787
  "notifier.cancel": {
23236
23788
  capName: "notifier",
23237
23789
  capScope: "device",