@camstack/addon-provider-dreame 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1134 -582
  2. package/dist/addon.mjs +1134 -582
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -37,7 +37,7 @@ let crypto$1 = require("crypto");
37
37
  let events = require("events");
38
38
  let zlib = require("zlib");
39
39
  zlib = __toESM(zlib, 1);
40
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
40
+ //#region ../types/dist/event-category-BLcNejAE.mjs
41
41
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
42
42
  EventCategory["SystemBoot"] = "system.boot";
43
43
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -187,9 +187,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
187
187
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
188
188
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
189
189
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
190
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
191
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
192
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
193
190
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
194
191
  * progress bar the client reconciles via `recordingExport.getExport`. */
195
192
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6868,7 +6865,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6868
6865
  patch: record(string(), unknown())
6869
6866
  }), object({ success: literal(true) });
6870
6867
  object({ deviceId: number() }), unknown().nullable();
6871
- /** Shorthand to define a method schema */
6872
6868
  function method(input, output, options) {
6873
6869
  return {
6874
6870
  input,
@@ -6876,6 +6872,7 @@ function method(input, output, options) {
6876
6872
  kind: options?.kind ?? "query",
6877
6873
  auth: options?.auth ?? "protected",
6878
6874
  ...options?.access !== void 0 ? { access: options.access } : {},
6875
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6879
6876
  timeoutMs: options?.timeoutMs
6880
6877
  };
6881
6878
  }
@@ -8245,6 +8242,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8245
8242
  /** The complete taxonomy dictionary, keyed by kind. */
8246
8243
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8247
8244
  /**
8245
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8246
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8247
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8248
+ * taxonomy surface (timeline, filters, event page).
8249
+ *
8250
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8251
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8252
+ * for the `classes` / `classesExclude` conditions.
8253
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8254
+ * the same class picker, grouped under an Audio header.
8255
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8256
+ * lock / …) for the `sensorKinds` device-event condition.
8257
+ *
8258
+ * Each entry carries `parentKind` so the client can group video subs under
8259
+ * their macro and sensor/control kinds under their category. This surface is
8260
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8261
+ * method, no codegen — so it ships train-free with an addon deploy.
8262
+ */
8263
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8264
+ var NcTaxonomyEntrySchema = object({
8265
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8266
+ kind: string(),
8267
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8268
+ label: string(),
8269
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8270
+ parentKind: string().nullable()
8271
+ });
8272
+ object({
8273
+ videoClasses: array(NcTaxonomyEntrySchema),
8274
+ audioKinds: array(NcTaxonomyEntrySchema),
8275
+ labels: array(NcTaxonomyEntrySchema)
8276
+ });
8277
+ function toEntry(kind, label, parentKind) {
8278
+ return {
8279
+ kind,
8280
+ label,
8281
+ parentKind
8282
+ };
8283
+ }
8284
+ /**
8285
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8286
+ * (macros before their subs), which the client relies on for stable grouping.
8287
+ */
8288
+ function buildNcTaxonomy() {
8289
+ const all = Object.values(EVENT_TAXONOMY);
8290
+ return {
8291
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8292
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8293
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8294
+ };
8295
+ }
8296
+ Object.freeze(buildNcTaxonomy());
8297
+ /**
8248
8298
  * Error types for the safe expression engine. Two distinct classes so callers
8249
8299
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8250
8300
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -12230,6 +12280,22 @@ var CameraMetricsSchema = object({
12230
12280
  ])
12231
12281
  });
12232
12282
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
12283
+ /**
12284
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
12285
+ * within the frame, so the executor can re-cut a leaf child ROI at native
12286
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
12287
+ */
12288
+ var NativeCropRefSchema = object({
12289
+ /** Handle keying the retained native surface (node-pinned to its owner). */
12290
+ handle: FrameHandleSchema,
12291
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
12292
+ cropFrameSpace: object({
12293
+ x: number(),
12294
+ y: number(),
12295
+ w: number(),
12296
+ h: number()
12297
+ })
12298
+ });
12233
12299
  var ModelFormatSchema$1 = _enum([
12234
12300
  "onnx",
12235
12301
  "coreml",
@@ -12505,7 +12571,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
12505
12571
  * Omitted ⇒ the runner's default device (current single-engine
12506
12572
  * behaviour). Selects WHICH device pool of the node runs the call.
12507
12573
  */
12508
- deviceKey: string().optional()
12574
+ deviceKey: string().optional(),
12575
+ /**
12576
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
12577
+ * when the parent crop was resolved from the frame's retained NATIVE
12578
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
12579
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
12580
+ * resolution from that surface — the SAME quality path faces already
12581
+ * had — instead of the downscaled parent tile. `handle` keys the native
12582
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
12583
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
12584
+ * the executor's crop-normalized child ROI back into frame-normalized
12585
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
12586
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
12587
+ * (today's behaviour on the fallback path).
12588
+ */
12589
+ nativeCropRef: NativeCropRefSchema.optional()
12509
12590
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
12510
12591
  engine: PipelineEngineChoiceSchema.optional(),
12511
12592
  steps: array(PipelineStepInputSchema).min(1),
@@ -12754,7 +12835,11 @@ var DetailResultSchema = object({
12754
12835
  bbox: NativeCropBboxSchema.optional(),
12755
12836
  embedding: string().optional(),
12756
12837
  label: string().optional(),
12757
- alignedCropJpeg: string().optional()
12838
+ alignedCropJpeg: string().optional(),
12839
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
12840
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
12841
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
12842
+ nativeFaceShortSidePx: number().optional()
12758
12843
  });
12759
12844
  /**
12760
12845
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -12768,6 +12853,12 @@ var motionCooldownMsField = {
12768
12853
  default: 3e4,
12769
12854
  step: 500
12770
12855
  };
12856
+ var maxSessionHoldMsField = {
12857
+ min: 0,
12858
+ max: 6e5,
12859
+ default: 12e4,
12860
+ step: 5e3
12861
+ };
12771
12862
  var motionFpsField = {
12772
12863
  min: 1,
12773
12864
  max: 30,
@@ -12915,6 +13006,19 @@ var RunnerCameraConfigSchema = object({
12915
13006
  "on-motion"
12916
13007
  ]).default("always-on"),
12917
13008
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
13009
+ /**
13010
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
13011
+ * detection session is active and ≥1 confirmed non-stationary track is
13012
+ * still live, the orchestrator keeps the session open past
13013
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
13014
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
13015
+ * ms since the session opened, after which it closes regardless. `0`
13016
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
13017
+ * runner itself — carried here so it shares the per-camera device-settings
13018
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
13019
+ * resolved `CameraDetectionConfig`.
13020
+ */
13021
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
12918
13022
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
12919
13023
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
12920
13024
  motionStreamId: string(),
@@ -13004,7 +13108,7 @@ var RunnerCameraConfigSchema = object({
13004
13108
  */
13005
13109
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
13006
13110
  });
13007
- 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;
13111
+ 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;
13008
13112
  /**
13009
13113
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
13010
13114
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -16531,94 +16635,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
16531
16635
  bundleUrl: string()
16532
16636
  });
16533
16637
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
16534
- var NotificationRuleConditionsSchema = object({
16535
- deviceIds: array(number()).readonly().optional(),
16536
- classNames: array(string()).readonly().optional(),
16537
- zoneIds: array(string()).readonly().optional(),
16538
- minConfidence: number().optional(),
16539
- source: _enum([
16540
- "pipeline",
16541
- "onboard",
16542
- "any"
16543
- ]).optional(),
16544
- schedule: object({
16545
- days: array(number()).readonly(),
16546
- startHour: number(),
16547
- endHour: number()
16548
- }).optional(),
16549
- cooldownSeconds: number().optional(),
16550
- minDwellSeconds: number().optional(),
16551
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
16552
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
16553
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
16554
- eventTypeTokens: array(string()).readonly().optional(),
16555
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
16556
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
16557
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
16558
- clipDescription: object({
16559
- text: string().min(1),
16560
- minSimilarity: number().min(0).max(1)
16561
- }).optional(),
16562
- /** Match events whose recognized-entity label (face identity name or plate
16563
- * vehicle name, propagated onto `event.data.label`) is one of these values.
16564
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
16565
- * vehicle/person> is seen". */
16566
- labels: array(string()).readonly().optional()
16567
- });
16568
- var NotificationRuleTemplateSchema = object({
16569
- title: string(),
16570
- body: string(),
16571
- imageMode: _enum([
16572
- "crop",
16573
- "annotated",
16574
- "full",
16575
- "none"
16576
- ])
16577
- });
16578
- var NotificationRuleSchema = object({
16579
- id: string(),
16580
- name: string(),
16581
- enabled: boolean(),
16582
- eventTypes: array(string()).readonly(),
16583
- conditions: NotificationRuleConditionsSchema,
16584
- outputs: array(string()).readonly(),
16585
- template: NotificationRuleTemplateSchema.optional(),
16586
- priority: _enum([
16587
- "low",
16588
- "normal",
16589
- "high",
16590
- "critical"
16591
- ])
16592
- });
16593
- var NotificationTestResultSchema = object({
16594
- ruleId: string(),
16595
- eventId: string(),
16596
- timestamp: number(),
16597
- wouldFire: boolean(),
16598
- reason: string().optional()
16599
- });
16600
- var NotificationHistoryEntrySchema = object({
16601
- id: string(),
16602
- ruleId: string(),
16603
- ruleName: string(),
16604
- eventId: string(),
16605
- timestamp: number(),
16606
- outputs: array(string()).readonly(),
16607
- success: boolean(),
16608
- error: string().optional(),
16609
- deviceId: number().optional()
16610
- });
16611
- var NotificationHistoryFilterSchema = object({
16612
- ruleId: string().optional(),
16613
- deviceId: number().optional(),
16614
- from: number().optional(),
16615
- to: number().optional(),
16616
- limit: number().optional()
16617
- });
16618
- 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({
16619
- ruleId: string(),
16620
- lookbackMinutes: number()
16621
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
16622
16638
  /**
16623
16639
  * Alerts capability — collection-based internal alert system.
16624
16640
  *
@@ -16805,89 +16821,6 @@ method(object({
16805
16821
  password: string()
16806
16822
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
16807
16823
  /**
16808
- * `login-method` — collection cap through which auth addons contribute
16809
- * their pre-auth login surfaces to the login page. This is the SINGLE,
16810
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
16811
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
16812
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
16813
- * procedure aggregates them for the unauthenticated login page.
16814
- *
16815
- * A contribution is a discriminated union on `kind`:
16816
- *
16817
- * - `redirect` — a declarative button. The login page renders a generic
16818
- * button that navigates to `startUrl` (an addon-owned HTTP route).
16819
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
16820
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
16821
- * login page needs NO change.
16822
- *
16823
- * - `widget` — a Module-Federation widget the login page mounts (via
16824
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
16825
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
16826
- * mechanism kept for future use; no shipped addon uses it on the login
16827
- * page (the passkey ceremony below runs natively in the shell instead).
16828
- *
16829
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
16830
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
16831
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
16832
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
16833
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
16834
- * fetching any remote code pre-auth. Contribution stays unconditional —
16835
- * enrollment state is never leaked pre-auth; visibility is a shell
16836
- * decision.
16837
- *
16838
- * Every contribution carries a `stage`:
16839
- * - `primary` — shown on the first credentials screen (OIDC /
16840
- * magic-link buttons; a future usernameless passkey).
16841
- * - `second-factor` — shown AFTER the password leg, gated on the
16842
- * returned `factors` (passkey-as-2FA today).
16843
- *
16844
- * `mount: skip` — the cap is read server-side by the core auth router
16845
- * (`registry.getCollection('login-method')`), never mounted as its own
16846
- * tRPC router.
16847
- */
16848
- /** When a login method renders in the two-phase login flow. */
16849
- var LoginStageEnum = _enum(["primary", "second-factor"]);
16850
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
16851
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
16852
- object({
16853
- kind: literal("redirect"),
16854
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
16855
- id: string(),
16856
- /** Operator-facing button label. */
16857
- label: string(),
16858
- /** lucide-react icon name. */
16859
- icon: string().optional(),
16860
- /** Addon-owned HTTP route the button navigates to (GET). */
16861
- startUrl: string(),
16862
- stage: LoginStageEnum
16863
- }),
16864
- object({
16865
- kind: literal("widget"),
16866
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
16867
- id: string(),
16868
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
16869
- addonId: string(),
16870
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
16871
- bundle: string(),
16872
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
16873
- remote: WidgetRemoteSchema,
16874
- stage: LoginStageEnum
16875
- }),
16876
- object({
16877
- kind: literal("passkey"),
16878
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
16879
- id: string(),
16880
- /** Operator-facing button label. */
16881
- label: string(),
16882
- stage: LoginStageEnum,
16883
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
16884
- rpId: string(),
16885
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
16886
- origin: string().nullable()
16887
- })
16888
- ]);
16889
- method(_void(), array(LoginMethodContributionSchema).readonly());
16890
- /**
16891
16824
  * Orchestrator-side destination metadata. The orchestrator computes
16892
16825
  * `id = <addonId>:<subId>` from its provider lookup so consumers
16893
16826
  * (admin UI, restore flow) see one canonical key.
@@ -18248,48 +18181,423 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
18248
18181
  kind: "mutation",
18249
18182
  auth: "admin"
18250
18183
  });
18251
- var LogLevelSchema = _enum([
18252
- "debug",
18253
- "info",
18254
- "warn",
18255
- "error"
18184
+ /**
18185
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18186
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18187
+ * caps stay wire-compatible without a circular cap→cap import.
18188
+ *
18189
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
18190
+ * every transport tier structurally, and failed calls still write usage rows.
18191
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18192
+ */
18193
+ var LlmUsageSchema = object({
18194
+ inputTokens: number(),
18195
+ outputTokens: number()
18196
+ });
18197
+ var LlmErrorCodeSchema = _enum([
18198
+ "timeout",
18199
+ "rate-limited",
18200
+ "auth",
18201
+ "refusal",
18202
+ "bad-request",
18203
+ "unavailable",
18204
+ "no-profile",
18205
+ "budget-exceeded",
18206
+ "adapter-error"
18256
18207
  ]);
18257
- var LogEntrySchema = object({
18258
- timestamp: date(),
18259
- level: LogLevelSchema,
18260
- scope: array(string()),
18208
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18209
+ ok: literal(true),
18210
+ text: string(),
18211
+ model: string(),
18212
+ usage: LlmUsageSchema,
18213
+ truncated: boolean(),
18214
+ latencyMs: number()
18215
+ }), object({
18216
+ ok: literal(false),
18217
+ code: LlmErrorCodeSchema,
18261
18218
  message: string(),
18262
- meta: record(string(), unknown()).optional(),
18263
- tags: record(string(), string()).optional()
18264
- });
18265
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18266
- scope: array(string()).optional(),
18267
- level: LogLevelSchema.optional(),
18268
- since: date().optional(),
18269
- until: date().optional(),
18270
- limit: number().optional(),
18271
- tags: record(string(), string()).optional()
18272
- }), array(LogEntrySchema).readonly());
18273
- var CpuBreakdownSchema = object({
18274
- total: number(),
18275
- user: number(),
18276
- system: number(),
18277
- irq: number(),
18278
- nice: number(),
18279
- loadAvg: tuple([
18280
- number(),
18281
- number(),
18282
- number()
18283
- ]),
18284
- cores: number()
18219
+ retryAfterMs: number().optional()
18220
+ })]);
18221
+ /**
18222
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18223
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18224
+ * notification-output.cap.ts:27-31 precedents).
18225
+ */
18226
+ var LlmImageSchema = object({
18227
+ bytes: _instanceof(Uint8Array),
18228
+ mimeType: string()
18285
18229
  });
18286
- var MemoryInfoSchema = object({
18287
- percent: number(),
18288
- totalBytes: number(),
18289
- usedBytes: number(),
18290
- availableBytes: number(),
18291
- swapUsedBytes: number(),
18292
- swapTotalBytes: number()
18230
+ var LlmGenerateBaseInputSchema = object({
18231
+ /** Collection routing (the notification-output posture). */
18232
+ addonId: string().optional(),
18233
+ /** Explicit profile; else the resolution chain (spec §3). */
18234
+ profileId: string().optional(),
18235
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18236
+ consumer: string(),
18237
+ system: string().optional(),
18238
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
18239
+ prompt: string(),
18240
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18241
+ jsonSchema: record(string(), unknown()).optional(),
18242
+ /** Per-call override of the profile default. */
18243
+ maxTokens: number().int().positive().optional(),
18244
+ temperature: number().optional()
18245
+ });
18246
+ /**
18247
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18248
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18249
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18250
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18251
+ * this only through the `llm` cap's methods.
18252
+ *
18253
+ * One running llama-server child per node in v1 (models are RAM-heavy).
18254
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18255
+ * watchdog — operator decision #3).
18256
+ */
18257
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
18258
+ object({
18259
+ kind: literal("catalog"),
18260
+ catalogId: string()
18261
+ }),
18262
+ object({
18263
+ kind: literal("url"),
18264
+ url: string(),
18265
+ sha256: string().optional()
18266
+ }),
18267
+ object({
18268
+ kind: literal("path"),
18269
+ path: string()
18270
+ })
18271
+ ]);
18272
+ var ManagedRuntimeConfigSchema = object({
18273
+ /** WHERE the runtime lives — hub or any agent. */
18274
+ nodeId: string(),
18275
+ /** Closed for v1; 'ollama' is a v2 candidate. */
18276
+ engine: _enum(["llama-cpp"]),
18277
+ model: ManagedModelRefSchema,
18278
+ contextSize: number().int().default(4096),
18279
+ /** 0 = CPU-only. */
18280
+ gpuLayers: number().int().default(0),
18281
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18282
+ threads: number().int().optional(),
18283
+ /** Concurrent slots. */
18284
+ parallel: number().int().default(1),
18285
+ /** Else lazy: first generate boots it. */
18286
+ autoStart: boolean().default(false),
18287
+ /** 0 = never; frees RAM after quiet periods. */
18288
+ idleStopMinutes: number().int().default(30)
18289
+ });
18290
+ var LlmRuntimeStatusSchema = object({
18291
+ /** Status is ALWAYS node-qualified. */
18292
+ nodeId: string(),
18293
+ state: _enum([
18294
+ "stopped",
18295
+ "downloading",
18296
+ "starting",
18297
+ "ready",
18298
+ "crashed",
18299
+ "failed"
18300
+ ]),
18301
+ pid: number().optional(),
18302
+ port: number().optional(),
18303
+ modelPath: string().optional(),
18304
+ modelId: string().optional(),
18305
+ downloadProgress: number().min(0).max(1).optional(),
18306
+ lastError: string().optional(),
18307
+ crashesInWindow: number(),
18308
+ /** Child RSS (sampled best-effort). */
18309
+ memoryBytes: number().optional(),
18310
+ vramBytes: number().optional()
18311
+ });
18312
+ var LlmNodeModelSchema = object({
18313
+ file: string(),
18314
+ sizeBytes: number(),
18315
+ catalogId: string().optional(),
18316
+ installedAt: number().optional()
18317
+ });
18318
+ var LlmRuntimeDiskUsageSchema = object({
18319
+ nodeId: string(),
18320
+ modelsBytes: number(),
18321
+ freeBytes: number().optional()
18322
+ });
18323
+ method(LlmGenerateBaseInputSchema.extend({
18324
+ images: array(LlmImageSchema).optional(),
18325
+ runtime: ManagedRuntimeConfigSchema,
18326
+ /** The managed profile's timeout, threaded by the hub provider. */
18327
+ timeoutMs: number().int().positive().optional()
18328
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18329
+ kind: "mutation",
18330
+ auth: "admin"
18331
+ }), method(object({}), _void(), {
18332
+ kind: "mutation",
18333
+ auth: "admin"
18334
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18335
+ kind: "mutation",
18336
+ auth: "admin"
18337
+ }), method(object({ file: string() }), _void(), {
18338
+ kind: "mutation",
18339
+ auth: "admin"
18340
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18341
+ /**
18342
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18343
+ * methods concat-fan across providers; single-row methods route to ONE
18344
+ * provider by the `addonId` in the call input (the notification-output
18345
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18346
+ * (hub-placed); the cap stays open for future providers.
18347
+ *
18348
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18349
+ * `apiKey` is a password field — providers REDACT it on read and merge on
18350
+ * write; a stored key NEVER round-trips to a client.
18351
+ */
18352
+ var LlmProfileKindSchema = _enum([
18353
+ "openai-compatible",
18354
+ "openai",
18355
+ "anthropic",
18356
+ "google",
18357
+ "managed-local"
18358
+ ]);
18359
+ var LlmProfileSchema = object({
18360
+ id: string(),
18361
+ name: string(),
18362
+ kind: LlmProfileKindSchema,
18363
+ /** Stamped by the provider — keeps the fanned catalog routable. */
18364
+ addonId: string(),
18365
+ enabled: boolean(),
18366
+ /** Vendor model id, or the managed runtime's loaded model. */
18367
+ model: string(),
18368
+ /** Required for openai-compatible; override for cloud kinds. */
18369
+ baseUrl: string().optional(),
18370
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
18371
+ apiKey: string().optional(),
18372
+ supportsVision: boolean(),
18373
+ temperature: number().min(0).max(2).optional(),
18374
+ maxTokens: number().int().positive().optional(),
18375
+ timeoutMs: number().int().positive().default(6e4),
18376
+ extraHeaders: record(string(), string()).optional(),
18377
+ /** kind === 'managed-local' only (spec §4). */
18378
+ runtime: ManagedRuntimeConfigSchema.optional()
18379
+ });
18380
+ /** ConfigUISchema tree passed through untyped on the wire (the
18381
+ * notification-output `ConfigSchemaPassthrough` precedent at
18382
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
18383
+ var ConfigSchemaPassthrough$1 = unknown();
18384
+ var LlmProfileKindDescriptorSchema = object({
18385
+ kind: LlmProfileKindSchema,
18386
+ label: string(),
18387
+ icon: string(),
18388
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
18389
+ addonId: string(),
18390
+ configSchema: ConfigSchemaPassthrough$1
18391
+ });
18392
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
18393
+ var LlmDefaultSchema = object({
18394
+ selector: LlmDefaultSelectorSchema,
18395
+ profileId: string()
18396
+ });
18397
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
18398
+ var LlmUsageRollupSchema = object({
18399
+ day: string(),
18400
+ consumer: string(),
18401
+ profileId: string(),
18402
+ calls: number(),
18403
+ okCalls: number(),
18404
+ errorCalls: number(),
18405
+ inputTokens: number(),
18406
+ outputTokens: number(),
18407
+ avgLatencyMs: number()
18408
+ });
18409
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
18410
+ var ManagedModelCatalogEntrySchema = object({
18411
+ id: string(),
18412
+ label: string(),
18413
+ family: string(),
18414
+ purpose: _enum(["text", "vision"]),
18415
+ url: string(),
18416
+ sha256: string(),
18417
+ sizeBytes: number(),
18418
+ quantization: string(),
18419
+ /** Load-time guidance shown in the picker. */
18420
+ minRamBytes: number(),
18421
+ contextSizeDefault: number().int(),
18422
+ /** Vision models: companion projector file. */
18423
+ mmprojUrl: string().optional()
18424
+ });
18425
+ var LlmRuntimeNodeSchema = object({
18426
+ nodeId: string(),
18427
+ reachable: boolean(),
18428
+ status: LlmRuntimeStatusSchema.optional(),
18429
+ disk: LlmRuntimeDiskUsageSchema.optional(),
18430
+ error: string().optional()
18431
+ });
18432
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
18433
+ var ProfileRefInputSchema = object({
18434
+ addonId: string(),
18435
+ profileId: string()
18436
+ });
18437
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
18438
+ kind: "mutation",
18439
+ auth: "admin"
18440
+ }), method(ProfileRefInputSchema, _void(), {
18441
+ kind: "mutation",
18442
+ auth: "admin"
18443
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
18444
+ kind: "mutation",
18445
+ auth: "admin"
18446
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
18447
+ selector: LlmDefaultSelectorSchema,
18448
+ profileId: string().nullable()
18449
+ }), _void(), {
18450
+ kind: "mutation",
18451
+ auth: "admin"
18452
+ }), method(object({
18453
+ since: number().optional(),
18454
+ until: number().optional(),
18455
+ consumer: string().optional(),
18456
+ profileId: string().optional()
18457
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
18458
+ nodeId: string(),
18459
+ model: ManagedModelRefSchema
18460
+ }), _void(), {
18461
+ kind: "mutation",
18462
+ auth: "admin"
18463
+ }), method(object({
18464
+ nodeId: string(),
18465
+ file: string()
18466
+ }), _void(), {
18467
+ kind: "mutation",
18468
+ auth: "admin"
18469
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
18470
+ kind: "mutation",
18471
+ auth: "admin"
18472
+ }), method(ProfileRefInputSchema, _void(), {
18473
+ kind: "mutation",
18474
+ auth: "admin"
18475
+ });
18476
+ var LogLevelSchema = _enum([
18477
+ "debug",
18478
+ "info",
18479
+ "warn",
18480
+ "error"
18481
+ ]);
18482
+ var LogEntrySchema = object({
18483
+ timestamp: date(),
18484
+ level: LogLevelSchema,
18485
+ scope: array(string()),
18486
+ message: string(),
18487
+ meta: record(string(), unknown()).optional(),
18488
+ tags: record(string(), string()).optional()
18489
+ });
18490
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18491
+ scope: array(string()).optional(),
18492
+ level: LogLevelSchema.optional(),
18493
+ since: date().optional(),
18494
+ until: date().optional(),
18495
+ limit: number().optional(),
18496
+ tags: record(string(), string()).optional()
18497
+ }), array(LogEntrySchema).readonly());
18498
+ /**
18499
+ * `login-method` — collection cap through which auth addons contribute
18500
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
18501
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
18502
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
18503
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
18504
+ * procedure aggregates them for the unauthenticated login page.
18505
+ *
18506
+ * A contribution is a discriminated union on `kind`:
18507
+ *
18508
+ * - `redirect` — a declarative button. The login page renders a generic
18509
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
18510
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
18511
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
18512
+ * login page needs NO change.
18513
+ *
18514
+ * - `widget` — a Module-Federation widget the login page mounts (via
18515
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
18516
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
18517
+ * mechanism kept for future use; no shipped addon uses it on the login
18518
+ * page (the passkey ceremony below runs natively in the shell instead).
18519
+ *
18520
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
18521
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
18522
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
18523
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
18524
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
18525
+ * fetching any remote code pre-auth. Contribution stays unconditional —
18526
+ * enrollment state is never leaked pre-auth; visibility is a shell
18527
+ * decision.
18528
+ *
18529
+ * Every contribution carries a `stage`:
18530
+ * - `primary` — shown on the first credentials screen (OIDC /
18531
+ * magic-link buttons; a future usernameless passkey).
18532
+ * - `second-factor` — shown AFTER the password leg, gated on the
18533
+ * returned `factors` (passkey-as-2FA today).
18534
+ *
18535
+ * `mount: skip` — the cap is read server-side by the core auth router
18536
+ * (`registry.getCollection('login-method')`), never mounted as its own
18537
+ * tRPC router.
18538
+ */
18539
+ /** When a login method renders in the two-phase login flow. */
18540
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
18541
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
18542
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
18543
+ object({
18544
+ kind: literal("redirect"),
18545
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
18546
+ id: string(),
18547
+ /** Operator-facing button label. */
18548
+ label: string(),
18549
+ /** lucide-react icon name. */
18550
+ icon: string().optional(),
18551
+ /** Addon-owned HTTP route the button navigates to (GET). */
18552
+ startUrl: string(),
18553
+ stage: LoginStageEnum
18554
+ }),
18555
+ object({
18556
+ kind: literal("widget"),
18557
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
18558
+ id: string(),
18559
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
18560
+ addonId: string(),
18561
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
18562
+ bundle: string(),
18563
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
18564
+ remote: WidgetRemoteSchema,
18565
+ stage: LoginStageEnum
18566
+ }),
18567
+ object({
18568
+ kind: literal("passkey"),
18569
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
18570
+ id: string(),
18571
+ /** Operator-facing button label. */
18572
+ label: string(),
18573
+ stage: LoginStageEnum,
18574
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
18575
+ rpId: string(),
18576
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
18577
+ origin: string().nullable()
18578
+ })
18579
+ ]);
18580
+ method(_void(), array(LoginMethodContributionSchema).readonly());
18581
+ var CpuBreakdownSchema = object({
18582
+ total: number(),
18583
+ user: number(),
18584
+ system: number(),
18585
+ irq: number(),
18586
+ nice: number(),
18587
+ loadAvg: tuple([
18588
+ number(),
18589
+ number(),
18590
+ number()
18591
+ ]),
18592
+ cores: number()
18593
+ });
18594
+ var MemoryInfoSchema = object({
18595
+ percent: number(),
18596
+ totalBytes: number(),
18597
+ usedBytes: number(),
18598
+ availableBytes: number(),
18599
+ swapUsedBytes: number(),
18600
+ swapTotalBytes: number()
18293
18601
  });
18294
18602
  var DiskIoSnapshotSchema = object({
18295
18603
  readBytes: number(),
@@ -18742,14 +19050,14 @@ var TargetKindCapsSchema = object({
18742
19050
  * the union is large and not meant for runtime validation here; the exported
18743
19051
  * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
18744
19052
  */
18745
- var ConfigSchemaPassthrough$1 = unknown();
19053
+ var ConfigSchemaPassthrough = unknown();
18746
19054
  var TargetKindSchema = object({
18747
19055
  kind: string(),
18748
19056
  label: string(),
18749
19057
  icon: string(),
18750
19058
  /** Stamped by each provider so the concat-fanned catalog stays routable. */
18751
19059
  addonId: string(),
18752
- configSchema: ConfigSchemaPassthrough$1,
19060
+ configSchema: ConfigSchemaPassthrough,
18753
19061
  supportsDiscovery: boolean(),
18754
19062
  caps: TargetKindCapsSchema
18755
19063
  });
@@ -18802,297 +19110,493 @@ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSche
18802
19110
  enabled: boolean()
18803
19111
  }), _void(), { kind: "mutation" });
18804
19112
  /**
18805
- * Shared LLM generate contracts imported by BOTH `llm.cap.ts` (consumer
18806
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18807
- * caps stay wire-compatible without a circular cap→cap import.
19113
+ * notification-rules the Notification Center rule surface (P1 core).
18808
19114
  *
18809
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
18810
- * every transport tier structurally, and failed calls still write usage rows.
18811
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18812
- */
18813
- var LlmUsageSchema = object({
18814
- inputTokens: number(),
18815
- outputTokens: number()
18816
- });
18817
- var LlmErrorCodeSchema = _enum([
18818
- "timeout",
18819
- "rate-limited",
18820
- "auth",
18821
- "refusal",
18822
- "bad-request",
18823
- "unavailable",
18824
- "no-profile",
18825
- "budget-exceeded",
18826
- "adapter-error"
18827
- ]);
18828
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18829
- ok: literal(true),
18830
- text: string(),
18831
- model: string(),
18832
- usage: LlmUsageSchema,
18833
- truncated: boolean(),
18834
- latencyMs: number()
18835
- }), object({
18836
- ok: literal(false),
18837
- code: LlmErrorCodeSchema,
18838
- message: string(),
18839
- retryAfterMs: number().optional()
18840
- })]);
19115
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
19116
+ * (operator decisions D-1/D-2/D-3 are binding):
19117
+ *
19118
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
19119
+ * `notification-center` module), hooked on the durable persistence
19120
+ * moments (object-event insert, TrackCloser.closeExpired) with a
19121
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
19122
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
19123
+ * FIRST persisted detection matching the conditions (per-track dedup,
19124
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
19125
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
19126
+ * - DISPATCH stays behind `notification-output` (rules reference targets
19127
+ * by id; per-backend params are a passthrough blob capped by the
19128
+ * target kind's own caps/degrade engine).
19129
+ *
19130
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
19131
+ * server-injected caller identity — the first `caller: 'required'`
19132
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
19133
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
19134
+ * windows, and the optional label/identity/plate matchers. User rules,
19135
+ * private zones, per-recipient fan-out and the wider condition table are
19136
+ * P2+ (see spec §7).
19137
+ *
19138
+ * All schemas here are the single source of truth — `NcRule` etc. are
19139
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
19140
+ * schema/interface drift is explicitly not repeated).
19141
+ */
18841
19142
  /**
18842
- * `Uint8Array` is the sanctioned binary conventionsuperjson + the UDS
18843
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18844
- * notification-output.cap.ts:27-31 precedents).
19143
+ * D-3: the trigger/urgency of a rule which persistence moment evaluates it.
19144
+ * The value maps 1:1 onto the evaluated record kind:
19145
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
19146
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
19147
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
19148
+ * change of a LINKED device, one row per linked camera)
19149
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
19150
+ * delivery / pick-up)
19151
+ *
19152
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
19153
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
19154
+ * this one field keeps the schema additive — a rule still declares exactly
19155
+ * one trigger.
18845
19156
  */
18846
- var LlmImageSchema = object({
18847
- bytes: _instanceof(Uint8Array),
18848
- mimeType: string()
19157
+ var NcDeliverySchema = _enum([
19158
+ "immediate",
19159
+ "track-end",
19160
+ "device-event",
19161
+ "package-event"
19162
+ ]);
19163
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
19164
+ var NcScheduleSchema = object({
19165
+ windows: array(object({
19166
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
19167
+ days: array(number().int().min(0).max(6)).min(1),
19168
+ startMinute: number().int().min(0).max(1439),
19169
+ endMinute: number().int().min(0).max(1439)
19170
+ })).min(1),
19171
+ /** IANA timezone; default = hub host timezone. */
19172
+ timezone: string().optional(),
19173
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
19174
+ invert: boolean().optional()
18849
19175
  });
18850
- var LlmGenerateBaseInputSchema = object({
18851
- /** Collection routing (the notification-output posture). */
18852
- addonId: string().optional(),
18853
- /** Explicit profile; else the resolution chain (spec §3). */
18854
- profileId: string().optional(),
18855
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18856
- consumer: string(),
18857
- system: string().optional(),
18858
- /** v1: single-turn. `messages[]` is a v2 additive field. */
18859
- prompt: string(),
18860
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18861
- jsonSchema: record(string(), unknown()).optional(),
18862
- /** Per-call override of the profile default. */
18863
- maxTokens: number().int().positive().optional(),
18864
- temperature: number().optional()
19176
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
19177
+ var NcPlateMatcherSchema = object({
19178
+ values: array(string().min(1)).min(1),
19179
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
19180
+ maxDistance: number().int().min(0).max(3).default(1)
18865
19181
  });
18866
19182
  /**
18867
- * `llm-runtime` node-side managed llama.cpp executor (spec §4). Registered
18868
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18869
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` normal
18870
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18871
- * this only through the `llm` cap's methods.
18872
- *
18873
- * One running llama-server child per node in v1 (models are RAM-heavy).
18874
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18875
- * watchdog operator decision #3).
19183
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
19184
+ * occupancy edge for a device optionally narrowed to a single admin
19185
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
19186
+ * - `became-occupied` (default) count crossed 0 `count`
19187
+ * - `became-free` — count crossed `count` below it
19188
+ * - `>=` / `<=` — count is at/over or at/under `count`
19189
+ * `sustainSeconds` requires the condition hold continuously that long
19190
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
19191
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
19192
+ * the condition never matches. Confirmed edge-state survives addon restarts
19193
+ * (declared SQLite collection, reseeded on boot).
18876
19194
  */
18877
- var ManagedModelRefSchema = discriminatedUnion("kind", [
18878
- object({
18879
- kind: literal("catalog"),
18880
- catalogId: string()
18881
- }),
18882
- object({
18883
- kind: literal("url"),
18884
- url: string(),
18885
- sha256: string().optional()
18886
- }),
18887
- object({
18888
- kind: literal("path"),
18889
- path: string()
18890
- })
18891
- ]);
18892
- var ManagedRuntimeConfigSchema = object({
18893
- /** WHERE the runtime lives — hub or any agent. */
18894
- nodeId: string(),
18895
- /** Closed for v1; 'ollama' is a v2 candidate. */
18896
- engine: _enum(["llama-cpp"]),
18897
- model: ManagedModelRefSchema,
18898
- contextSize: number().int().default(4096),
18899
- /** 0 = CPU-only. */
18900
- gpuLayers: number().int().default(0),
18901
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18902
- threads: number().int().optional(),
18903
- /** Concurrent slots. */
18904
- parallel: number().int().default(1),
18905
- /** Else lazy: first generate boots it. */
18906
- autoStart: boolean().default(false),
18907
- /** 0 = never; frees RAM after quiet periods. */
18908
- idleStopMinutes: number().int().default(30)
19195
+ var NcOccupancyConditionSchema = object({
19196
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
19197
+ zoneId: string().optional(),
19198
+ /** Object class to count; absent = any class. */
19199
+ className: string().optional(),
19200
+ op: _enum([
19201
+ "became-occupied",
19202
+ "became-free",
19203
+ ">=",
19204
+ "<="
19205
+ ]).default("became-occupied"),
19206
+ count: number().int().min(0).default(1),
19207
+ sustainSeconds: number().int().min(0).max(3600).default(15)
19208
+ });
19209
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
19210
+ var NcZoneConditionSchema = object({
19211
+ ids: array(string().min(1)).min(1),
19212
+ /** Quantifier over `ids` — at least one / every one visited. */
19213
+ match: _enum(["any", "all"]).default("any")
18909
19214
  });
18910
- var LlmRuntimeStatusSchema = object({
18911
- /** Status is ALWAYS node-qualified. */
18912
- nodeId: string(),
18913
- state: _enum([
18914
- "stopped",
18915
- "downloading",
18916
- "starting",
18917
- "ready",
18918
- "crashed",
18919
- "failed"
18920
- ]),
18921
- pid: number().optional(),
18922
- port: number().optional(),
18923
- modelPath: string().optional(),
18924
- modelId: string().optional(),
18925
- downloadProgress: number().min(0).max(1).optional(),
18926
- lastError: string().optional(),
18927
- crashesInWindow: number(),
18928
- /** Child RSS (sampled best-effort). */
18929
- memoryBytes: number().optional(),
18930
- vramBytes: number().optional()
19215
+ /**
19216
+ * The P1 condition set — a flat AND of groups; absent group = pass;
19217
+ * membership lists are OR within the list (spec §2.3).
19218
+ */
19219
+ var NcConditionsSchema = object({
19220
+ /** Device scope — absent = all devices. */
19221
+ devices: array(number()).optional(),
19222
+ /** Detector class names (any overlap with the record's class set). */
19223
+ classes: array(string().min(1)).optional(),
19224
+ /** Veto classes — any overlap fails the rule. */
19225
+ classesExclude: array(string().min(1)).optional(),
19226
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
19227
+ minConfidence: number().min(0).max(1).optional(),
19228
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
19229
+ zones: NcZoneConditionSchema.optional(),
19230
+ /** Veto zones — any hit fails the rule. */
19231
+ zonesExclude: array(string().min(1)).optional(),
19232
+ /**
19233
+ * Exact (case-insensitive) match on the record's collapsed `label`
19234
+ * (identity name / plate text / subclass).
19235
+ */
19236
+ labelEquals: array(string().min(1)).optional(),
19237
+ /**
19238
+ * Identity matcher. P1 boundary: matched against the record's collapsed
19239
+ * `label` (the identity display name propagated by the face pipeline) —
19240
+ * identity-ID matching rides in P2 when identity ids reach the record.
19241
+ */
19242
+ identities: array(string().min(1)).optional(),
19243
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
19244
+ plates: NcPlateMatcherSchema.optional(),
19245
+ /**
19246
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
19247
+ * Same P1 boundary: matched against the record's collapsed `label` (the
19248
+ * identity display name). A record with NO label passes (nothing to
19249
+ * exclude), unlike the include variant which fails on an absent label.
19250
+ */
19251
+ identitiesExclude: array(string().min(1)).optional(),
19252
+ /**
19253
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
19254
+ * TRACK-END only: importance is scored at track close, so it does not exist
19255
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
19256
+ * close the value is threaded via the close-time info (the `Track` clone is
19257
+ * captured before the DB row is updated, so it would otherwise read stale).
19258
+ * Fails when the record carries no importance (never guess quality — the
19259
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
19260
+ */
19261
+ minImportance: number().min(0).max(1).optional(),
19262
+ /**
19263
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
19264
+ * TRACK-END only: an `immediate` / object-event subject has no closed
19265
+ * lifespan, so a dwell condition never matches immediate delivery
19266
+ * (documented choice — the object-event record carries no `firstSeen`,
19267
+ * so dwell cannot be computed from what the subject actually carries).
19268
+ */
19269
+ minDwellSeconds: number().min(0).optional(),
19270
+ /**
19271
+ * Detection provenance filter. `any` (default / absent) matches every
19272
+ * source; otherwise the subject's source must equal it. Legacy records
19273
+ * with no stamped source are treated as `pipeline`. The union spans both
19274
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
19275
+ * tracks carry `sensor`.
19276
+ */
19277
+ source: _enum([
19278
+ "pipeline",
19279
+ "onboard",
19280
+ "sensor",
19281
+ "any"
19282
+ ]).optional(),
19283
+ /**
19284
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
19285
+ * detector `minConfidence` (that gates the object-detection score; this
19286
+ * gates the recognition/OCR match score). Fails when the subject carries
19287
+ * no label-match confidence (never guess). TRACK-END only: the confidence
19288
+ * lives on the recognition result and reaches the subject at track close.
19289
+ *
19290
+ * What it measures precisely (plumbed at track close — the closer threads
19291
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
19292
+ * `importance`): the BEST recognition match confidence observed for the
19293
+ * label the track carries at close — for a face, the peak cosine similarity
19294
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
19295
+ * for a plate, the peak OCR read score of the best-held plate
19296
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
19297
+ * one track the higher of the two is used. A track that ended with no
19298
+ * confident identity/plate match carries no value, so the condition fails
19299
+ * closed for it (an un-recognized subject).
19300
+ */
19301
+ minLabelConfidence: number().min(0).max(1).optional(),
19302
+ /**
19303
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
19304
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
19305
+ * against the token carried on the device-event subject (extracted from the
19306
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
19307
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
19308
+ * eventType, so gate those with {@link sensorKinds} instead.
19309
+ */
19310
+ eventTypeTokens: array(string().min(1)).optional(),
19311
+ /**
19312
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
19313
+ * `contact`, `button`, `device-event`) — matched against the persisted
19314
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
19315
+ */
19316
+ sensorKinds: array(string().min(1)).optional(),
19317
+ /**
19318
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
19319
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
19320
+ * when the subject's phase does not match (a subject always carries a phase
19321
+ * on the package-event trigger).
19322
+ */
19323
+ packagePhase: _enum([
19324
+ "delivered",
19325
+ "picked-up",
19326
+ "both"
19327
+ ]).optional(),
19328
+ /**
19329
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
19330
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
19331
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
19332
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
19333
+ */
19334
+ customZones: array(MaskPolygonShapeSchema).optional(),
19335
+ /**
19336
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
19337
+ * (optionally zone/class-scoped) occupancy count crosses the configured
19338
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
19339
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
19340
+ */
19341
+ occupancy: NcOccupancyConditionSchema.optional()
18931
19342
  });
18932
- var LlmNodeModelSchema = object({
18933
- file: string(),
18934
- sizeBytes: number(),
18935
- catalogId: string().optional(),
18936
- installedAt: number().optional()
19343
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
19344
+ var NcRuleTargetSchema = object({
19345
+ /** `notification-output` Target id. */
19346
+ targetId: string().min(1),
19347
+ /**
19348
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
19349
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
19350
+ * degrade engine drops what the backend can't render.
19351
+ */
19352
+ params: record(string(), unknown()).optional()
18937
19353
  });
18938
- var LlmRuntimeDiskUsageSchema = object({
18939
- nodeId: string(),
18940
- modelsBytes: number(),
18941
- freeBytes: number().optional()
19354
+ /**
19355
+ * Media attachment policy (P1 still-image subset).
19356
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
19357
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
19358
+ * matched on identities attaches the subject's `faceCrop`, one matched on
19359
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
19360
+ * (or when the specific crop is missing) degrades to `best`, then
19361
+ * `keyFrame`, then no attachment — never delaying the send. The matched
19362
+ * condition summary is frozen on the outbox row at enqueue (like the rule
19363
+ * name), so the choice never drifts from the record that fired it.
19364
+ * - `keyFrame` — the clean scene frame (no subject box).
19365
+ * - `none` — no attachment.
19366
+ */
19367
+ var NcMediaPolicySchema = object({ attach: _enum([
19368
+ "best",
19369
+ "best-matching",
19370
+ "keyFrame",
19371
+ "none"
19372
+ ]).default("best") });
19373
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
19374
+ var NcThrottleSchema = object({
19375
+ cooldownSec: number().int().min(0).max(86400).default(60),
19376
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
19377
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
19378
+ });
19379
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
19380
+ var NcRuleInputSchema = object({
19381
+ name: string().min(1).max(200),
19382
+ enabled: boolean().default(true),
19383
+ delivery: NcDeliverySchema,
19384
+ conditions: NcConditionsSchema.default({}),
19385
+ schedule: NcScheduleSchema.optional(),
19386
+ targets: array(NcRuleTargetSchema).min(1),
19387
+ media: NcMediaPolicySchema.default({ attach: "best" }),
19388
+ throttle: NcThrottleSchema.default({
19389
+ cooldownSec: 60,
19390
+ scope: "rule-device"
19391
+ }),
19392
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
19393
+ template: object({
19394
+ title: string().max(500).optional(),
19395
+ body: string().max(2e3).optional()
19396
+ }).optional(),
19397
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
19398
+ priority: number().int().min(1).max(5).default(3),
19399
+ /**
19400
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
19401
+ * behaviour, visible to all, read-only in the viewer). Present = personal
19402
+ * rule owned by this userId. Server-stamped; never trusted from a client.
19403
+ */
19404
+ ownerUserId: string().optional()
18942
19405
  });
18943
- method(LlmGenerateBaseInputSchema.extend({
18944
- images: array(LlmImageSchema).optional(),
18945
- runtime: ManagedRuntimeConfigSchema,
18946
- /** The managed profile's timeout, threaded by the hub provider. */
18947
- timeoutMs: number().int().positive().optional()
18948
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18949
- kind: "mutation",
18950
- auth: "admin"
18951
- }), method(object({}), _void(), {
18952
- kind: "mutation",
18953
- auth: "admin"
18954
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18955
- kind: "mutation",
18956
- auth: "admin"
18957
- }), method(object({ file: string() }), _void(), {
18958
- kind: "mutation",
18959
- auth: "admin"
18960
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18961
19406
  /**
18962
- * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18963
- * methods concat-fan across providers; single-row methods route to ONE
18964
- * provider by the `addonId` in the call input (the notification-output
18965
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18966
- * (hub-placed); the cap stays open for future providers.
18967
- *
18968
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18969
- * `apiKey` is a password field — providers REDACT it on read and merge on
18970
- * write; a stored key NEVER round-trips to a client.
19407
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
19408
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
19409
+ * NOT a client-authored input field (it lives on the persisted rule, not the
19410
+ * input), so it is added here explicitly to let the store's per-target opt-out
19411
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
19412
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
19413
+ * `updateRule` patch.
18971
19414
  */
18972
- var LlmProfileKindSchema = _enum([
18973
- "openai-compatible",
18974
- "openai",
18975
- "anthropic",
18976
- "google",
18977
- "managed-local"
18978
- ]);
18979
- var LlmProfileSchema = object({
19415
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
19416
+ /** A persisted rule. */
19417
+ var NcRuleSchema = NcRuleInputSchema.extend({
18980
19418
  id: string(),
18981
- name: string(),
18982
- kind: LlmProfileKindSchema,
18983
- /** Stamped by the provider — keeps the fanned catalog routable. */
18984
- addonId: string(),
18985
- enabled: boolean(),
18986
- /** Vendor model id, or the managed runtime's loaded model. */
18987
- model: string(),
18988
- /** Required for openai-compatible; override for cloud kinds. */
18989
- baseUrl: string().optional(),
18990
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
18991
- apiKey: string().optional(),
18992
- supportsVision: boolean(),
18993
- temperature: number().min(0).max(2).optional(),
18994
- maxTokens: number().int().positive().optional(),
18995
- timeoutMs: number().int().positive().default(6e4),
18996
- extraHeaders: record(string(), string()).optional(),
18997
- /** kind === 'managed-local' only (spec §4). */
18998
- runtime: ManagedRuntimeConfigSchema.optional()
18999
- });
19000
- /** ConfigUISchema tree passed through untyped on the wire (the
19001
- * notification-output `ConfigSchemaPassthrough` precedent at
19002
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
19003
- var ConfigSchemaPassthrough = unknown();
19004
- var LlmProfileKindDescriptorSchema = object({
19005
- kind: LlmProfileKindSchema,
19006
- label: string(),
19007
- icon: string(),
19008
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
19009
- addonId: string(),
19010
- configSchema: ConfigSchemaPassthrough
19011
- });
19012
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
19013
- var LlmDefaultSchema = object({
19014
- selector: LlmDefaultSelectorSchema,
19015
- profileId: string()
19419
+ /** userId of the admin who created the rule (server-stamped caller). */
19420
+ createdBy: string(),
19421
+ createdAt: number(),
19422
+ updatedAt: number(),
19423
+ /**
19424
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
19425
+ * send time. Only a target's OWNER may add/remove its id (server-checked
19426
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
19427
+ */
19428
+ disabledTargetIds: array(string()).default([])
19016
19429
  });
19017
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
19018
- var LlmUsageRollupSchema = object({
19019
- day: string(),
19020
- consumer: string(),
19021
- profileId: string(),
19022
- calls: number(),
19023
- okCalls: number(),
19024
- errorCalls: number(),
19025
- inputTokens: number(),
19026
- outputTokens: number(),
19027
- avgLatencyMs: number()
19430
+ var NcTestResultSchema = object({
19431
+ recordId: string(),
19432
+ recordKind: _enum([
19433
+ "object-event",
19434
+ "track",
19435
+ "device-event",
19436
+ "package-event"
19437
+ ]),
19438
+ deviceId: number(),
19439
+ timestamp: number(),
19440
+ wouldFire: boolean(),
19441
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
19442
+ failedCondition: string().optional(),
19443
+ className: string().optional(),
19444
+ label: string().optional()
19028
19445
  });
19029
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
19030
- var ManagedModelCatalogEntrySchema = object({
19446
+ var NcConditionDescriptorSchema = object({
19447
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
19031
19448
  id: string(),
19449
+ group: _enum([
19450
+ "scope",
19451
+ "class",
19452
+ "zones",
19453
+ "quality",
19454
+ "label",
19455
+ "schedule",
19456
+ "device",
19457
+ "package",
19458
+ "occupancy"
19459
+ ]),
19032
19460
  label: string(),
19033
- family: string(),
19034
- purpose: _enum(["text", "vision"]),
19035
- url: string(),
19036
- sha256: string(),
19037
- sizeBytes: number(),
19038
- quantization: string(),
19039
- /** Load-time guidance shown in the picker. */
19040
- minRamBytes: number(),
19041
- contextSizeDefault: number().int(),
19042
- /** Vision models: companion projector file. */
19043
- mmprojUrl: string().optional()
19461
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
19462
+ valueType: _enum([
19463
+ "deviceIdList",
19464
+ "stringList",
19465
+ "number01",
19466
+ "number",
19467
+ "sourceSelect",
19468
+ "zoneSelection",
19469
+ "zoneIdList",
19470
+ "schedule",
19471
+ "plateMatcher",
19472
+ "packagePhase",
19473
+ "polygonDraw",
19474
+ "occupancy"
19475
+ ]),
19476
+ operator: _enum([
19477
+ "in",
19478
+ "notIn",
19479
+ "anyOf",
19480
+ "allOf",
19481
+ "gte",
19482
+ "fuzzyIn",
19483
+ "withinSchedule"
19484
+ ]),
19485
+ /** Which delivery kinds the condition applies to. */
19486
+ appliesTo: array(NcDeliverySchema),
19487
+ phase: string(),
19488
+ description: string().optional()
19044
19489
  });
19045
- var LlmRuntimeNodeSchema = object({
19046
- nodeId: string(),
19047
- reachable: boolean(),
19048
- status: LlmRuntimeStatusSchema.optional(),
19049
- disk: LlmRuntimeDiskUsageSchema.optional(),
19050
- error: string().optional()
19490
+ /**
19491
+ * The delivery lifecycle status of a history row — a straight read of the
19492
+ * durable outbox row's own status (single source of truth):
19493
+ * - `pending` — enqueued, in-flight or retrying with backoff
19494
+ * - `sent` — delivered (terminal)
19495
+ * - `dead` — dead-lettered after exhausting retries / a permanent
19496
+ * backend rejection / a deleted target (terminal; carries
19497
+ * the failure `error`)
19498
+ *
19499
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
19500
+ * user dimension (quiet hours / snooze) and are additive when they land.
19501
+ */
19502
+ var NcHistoryStatusSchema = _enum([
19503
+ "pending",
19504
+ "sent",
19505
+ "dead"
19506
+ ]);
19507
+ /** The evaluated record kind a history row descends from (one per trigger). */
19508
+ var NcHistoryRecordKindSchema = _enum([
19509
+ "object-event",
19510
+ "track-end",
19511
+ "device-event",
19512
+ "package-event"
19513
+ ]);
19514
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
19515
+ var NcHistorySubjectSchema = object({
19516
+ className: string(),
19517
+ label: string().optional(),
19518
+ confidence: number().optional(),
19519
+ zones: array(string()),
19520
+ timestamp: number()
19521
+ });
19522
+ /**
19523
+ * One delivery-history row. This is a read-only VIEW over the durable
19524
+ * outbox row (single source of truth — the same row the drain loop drives;
19525
+ * NO second write path, so history can never drift from delivery state).
19526
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
19527
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
19528
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
19529
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
19530
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
19531
+ * P1 (admin scope only).
19532
+ */
19533
+ var NcHistoryEntrySchema = object({
19534
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
19535
+ id: string(),
19536
+ ruleId: string(),
19537
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
19538
+ ruleName: string(),
19539
+ /** The rule urgency/trigger that produced this delivery. */
19540
+ delivery: NcDeliverySchema,
19541
+ targetId: string(),
19542
+ deviceId: number(),
19543
+ recordKind: NcHistoryRecordKindSchema,
19544
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
19545
+ recordId: string(),
19546
+ /** Present for track-scoped deliveries (object-event / track-end). */
19547
+ trackId: string().optional(),
19548
+ status: NcHistoryStatusSchema,
19549
+ /** Delivery attempts made so far. */
19550
+ attempts: number().int(),
19551
+ /** Fire time (outbox enqueue). */
19552
+ createdAt: number(),
19553
+ /** Last transition time (terminal for sent / dead). */
19554
+ updatedAt: number(),
19555
+ /** Failure detail — present on a `dead` row. */
19556
+ error: string().optional(),
19557
+ subject: NcHistorySubjectSchema
19051
19558
  });
19052
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
19053
- var ProfileRefInputSchema = object({
19054
- addonId: string(),
19055
- profileId: string()
19559
+ /**
19560
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
19561
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
19562
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
19563
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
19564
+ */
19565
+ var NcHistoryFilterSchema = object({
19566
+ ruleId: string().optional(),
19567
+ deviceId: number().optional(),
19568
+ status: NcHistoryStatusSchema.optional(),
19569
+ since: number().optional(),
19570
+ until: number().optional(),
19571
+ limit: number().int().min(1).max(500).default(100)
19056
19572
  });
19057
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
19058
- kind: "mutation",
19059
- auth: "admin"
19060
- }), method(ProfileRefInputSchema, _void(), {
19573
+ 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 }), {
19061
19574
  kind: "mutation",
19062
- auth: "admin"
19063
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
19575
+ auth: "admin",
19576
+ caller: "required"
19577
+ }), method(object({
19578
+ ruleId: string(),
19579
+ patch: NcRulePatchSchema
19580
+ }), object({ rule: NcRuleSchema }), {
19064
19581
  kind: "mutation",
19065
- auth: "admin"
19066
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
19067
- selector: LlmDefaultSelectorSchema,
19068
- profileId: string().nullable()
19069
- }), _void(), {
19582
+ auth: "admin",
19583
+ caller: "required"
19584
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
19070
19585
  kind: "mutation",
19071
19586
  auth: "admin"
19072
19587
  }), method(object({
19073
- since: number().optional(),
19074
- until: number().optional(),
19075
- consumer: string().optional(),
19076
- profileId: string().optional()
19077
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
19078
- nodeId: string(),
19079
- model: ManagedModelRefSchema
19080
- }), _void(), {
19588
+ ruleId: string(),
19589
+ enabled: boolean()
19590
+ }), object({ success: literal(true) }), {
19081
19591
  kind: "mutation",
19082
19592
  auth: "admin"
19083
19593
  }), method(object({
19084
- nodeId: string(),
19085
- file: string()
19086
- }), _void(), {
19087
- kind: "mutation",
19088
- auth: "admin"
19089
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
19090
- kind: "mutation",
19091
- auth: "admin"
19092
- }), method(ProfileRefInputSchema, _void(), {
19594
+ rule: NcRuleInputSchema,
19595
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
19596
+ }), object({ results: array(NcTestResultSchema) }), {
19093
19597
  kind: "mutation",
19094
19598
  auth: "admin"
19095
- });
19599
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
19096
19600
  /**
19097
19601
  * Zod schemas for persisted record types.
19098
19602
  *
@@ -19778,7 +20282,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19778
20282
  }), method(object({
19779
20283
  eventId: string(),
19780
20284
  kind: MediaFileKindEnum.optional()
19781
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
20285
+ }), array(MediaFileSchema).readonly()), method(object({
20286
+ trackId: string(),
20287
+ kinds: array(MediaFileKindEnum).optional()
20288
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
19782
20289
  deviceId: number(),
19783
20290
  timestamp: number(),
19784
20291
  frameWidth: number(),
@@ -19799,76 +20306,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19799
20306
  eventId: string(),
19800
20307
  timestamp: number()
19801
20308
  });
19802
- /**
19803
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
19804
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
19805
- * caps into per-camera event-kind descriptors.
19806
- *
19807
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
19808
- * is NOT duplicated here — every entry is derived from the single
19809
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
19810
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
19811
- * control cap means adding one line here (and a taxonomy entry); the anti-
19812
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
19813
- * eventful cap is missing.
19814
- */
19815
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
19816
- var LEGACY_ICON = {
19817
- motion: "motion",
19818
- audio: "audio",
19819
- person: "person",
19820
- vehicle: "vehicle",
19821
- animal: "animal",
19822
- package: "package",
19823
- door: "door",
19824
- pir: "pir",
19825
- smoke: "smoke",
19826
- water: "water",
19827
- button: "button",
19828
- generic: "generic",
19829
- gas: "smoke",
19830
- vibration: "generic",
19831
- tamper: "generic",
19832
- presence: "person",
19833
- lock: "generic",
19834
- siren: "generic",
19835
- switch: "generic",
19836
- doorbell: "button"
19837
- };
19838
- function legacyIcon(iconId) {
19839
- return LEGACY_ICON[iconId] ?? "generic";
19840
- }
19841
- /**
19842
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
19843
- * The anti-drift guard cross-checks this against the eventful caps declared
19844
- * in `packages/types/src/capabilities/*.cap.ts`.
19845
- */
19846
- var CAP_TO_KIND = {
19847
- contact: "contact",
19848
- motion: "motion-sensor",
19849
- smoke: "smoke",
19850
- flood: "flood",
19851
- gas: "gas",
19852
- "carbon-monoxide": "carbon-monoxide",
19853
- vibration: "vibration",
19854
- tamper: "tamper",
19855
- presence: "presence",
19856
- "enum-sensor": "enum-sensor",
19857
- "event-emitter": "device-event",
19858
- "lock-control": "lock",
19859
- switch: "switch",
19860
- button: "button",
19861
- doorbell: "doorbell"
19862
- };
19863
- function buildDescriptor(capName, kind) {
19864
- const t = EVENT_TAXONOMY[kind];
19865
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
19866
- return {
19867
- ...t,
19868
- icon: legacyIcon(t.iconId)
19869
- };
19870
- }
19871
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
19872
20309
  var CameraPipelineConfigSchema = object({
19873
20310
  engine: PipelineEngineChoiceSchema.optional(),
19874
20311
  steps: array(PipelineStepInputSchema).readonly(),
@@ -20354,6 +20791,76 @@ method(object({
20354
20791
  auth: "admin"
20355
20792
  });
20356
20793
  /**
20794
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
20795
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
20796
+ * caps into per-camera event-kind descriptors.
20797
+ *
20798
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
20799
+ * is NOT duplicated here — every entry is derived from the single
20800
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
20801
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
20802
+ * control cap means adding one line here (and a taxonomy entry); the anti-
20803
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
20804
+ * eventful cap is missing.
20805
+ */
20806
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
20807
+ var LEGACY_ICON = {
20808
+ motion: "motion",
20809
+ audio: "audio",
20810
+ person: "person",
20811
+ vehicle: "vehicle",
20812
+ animal: "animal",
20813
+ package: "package",
20814
+ door: "door",
20815
+ pir: "pir",
20816
+ smoke: "smoke",
20817
+ water: "water",
20818
+ button: "button",
20819
+ generic: "generic",
20820
+ gas: "smoke",
20821
+ vibration: "generic",
20822
+ tamper: "generic",
20823
+ presence: "person",
20824
+ lock: "generic",
20825
+ siren: "generic",
20826
+ switch: "generic",
20827
+ doorbell: "button"
20828
+ };
20829
+ function legacyIcon(iconId) {
20830
+ return LEGACY_ICON[iconId] ?? "generic";
20831
+ }
20832
+ /**
20833
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
20834
+ * The anti-drift guard cross-checks this against the eventful caps declared
20835
+ * in `packages/types/src/capabilities/*.cap.ts`.
20836
+ */
20837
+ var CAP_TO_KIND = {
20838
+ contact: "contact",
20839
+ motion: "motion-sensor",
20840
+ smoke: "smoke",
20841
+ flood: "flood",
20842
+ gas: "gas",
20843
+ "carbon-monoxide": "carbon-monoxide",
20844
+ vibration: "vibration",
20845
+ tamper: "tamper",
20846
+ presence: "presence",
20847
+ "enum-sensor": "enum-sensor",
20848
+ "event-emitter": "device-event",
20849
+ "lock-control": "lock",
20850
+ switch: "switch",
20851
+ button: "button",
20852
+ doorbell: "doorbell"
20853
+ };
20854
+ function buildDescriptor(capName, kind) {
20855
+ const t = EVENT_TAXONOMY[kind];
20856
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
20857
+ return {
20858
+ ...t,
20859
+ icon: legacyIcon(t.iconId)
20860
+ };
20861
+ }
20862
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
20863
+ /**
20357
20864
  * server-management — per-NODE singleton capability for a node's ROOT
20358
20865
  * package lifecycle (runtime-updatable node packages).
20359
20866
  *
@@ -21825,7 +22332,28 @@ var FaceInfoSchema = object({
21825
22332
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
21826
22333
  * track produced no key frame (e.g. native/onboard source) — the UI falls
21827
22334
  * back to the inline `base64` face crop. */
21828
- keyFrameMediaKey: string().optional()
22335
+ keyFrameMediaKey: string().optional(),
22336
+ /** Winning identity-match cosine (0..1) for this face's track, when an
22337
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
22338
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
22339
+ * faces that were never auto-recognized. */
22340
+ bestMatchScore: number().optional(),
22341
+ /** Native-scale face short side (px) at recognition time, when the runner
22342
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
22343
+ * legacy rows / runners that reported no native measure. */
22344
+ nativeFaceShortSidePx: number().optional(),
22345
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
22346
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
22347
+ * but blocked only by the recognition size floor). Mutually exclusive with
22348
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
22349
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
22350
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
22351
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
22352
+ suggestedIdentityId: string().optional(),
22353
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
22354
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
22355
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
22356
+ suggestedMatchScore: number().optional()
21829
22357
  });
21830
22358
  var FaceFilterEnum = _enum([
21831
22359
  "unassigned",
@@ -23868,36 +24396,6 @@ Object.freeze({
23868
24396
  addonId: null,
23869
24397
  access: "view"
23870
24398
  },
23871
- "advancedNotifier.deleteRule": {
23872
- capName: "advanced-notifier",
23873
- capScope: "system",
23874
- addonId: null,
23875
- access: "delete"
23876
- },
23877
- "advancedNotifier.getHistory": {
23878
- capName: "advanced-notifier",
23879
- capScope: "system",
23880
- addonId: null,
23881
- access: "view"
23882
- },
23883
- "advancedNotifier.getRules": {
23884
- capName: "advanced-notifier",
23885
- capScope: "system",
23886
- addonId: null,
23887
- access: "view"
23888
- },
23889
- "advancedNotifier.testRule": {
23890
- capName: "advanced-notifier",
23891
- capScope: "system",
23892
- addonId: null,
23893
- access: "create"
23894
- },
23895
- "advancedNotifier.upsertRule": {
23896
- capName: "advanced-notifier",
23897
- capScope: "system",
23898
- addonId: null,
23899
- access: "create"
23900
- },
23901
24399
  "alarmPanel.arm": {
23902
24400
  capName: "alarm-panel",
23903
24401
  capScope: "device",
@@ -26202,6 +26700,60 @@ Object.freeze({
26202
26700
  addonId: null,
26203
26701
  access: "create"
26204
26702
  },
26703
+ "notificationRules.createRule": {
26704
+ capName: "notification-rules",
26705
+ capScope: "system",
26706
+ addonId: null,
26707
+ access: "create"
26708
+ },
26709
+ "notificationRules.deleteRule": {
26710
+ capName: "notification-rules",
26711
+ capScope: "system",
26712
+ addonId: null,
26713
+ access: "delete"
26714
+ },
26715
+ "notificationRules.getConditionCatalog": {
26716
+ capName: "notification-rules",
26717
+ capScope: "system",
26718
+ addonId: null,
26719
+ access: "view"
26720
+ },
26721
+ "notificationRules.getHistory": {
26722
+ capName: "notification-rules",
26723
+ capScope: "system",
26724
+ addonId: null,
26725
+ access: "view"
26726
+ },
26727
+ "notificationRules.getRule": {
26728
+ capName: "notification-rules",
26729
+ capScope: "system",
26730
+ addonId: null,
26731
+ access: "view"
26732
+ },
26733
+ "notificationRules.listRules": {
26734
+ capName: "notification-rules",
26735
+ capScope: "system",
26736
+ addonId: null,
26737
+ access: "view"
26738
+ },
26739
+ "notificationRules.setRuleEnabled": {
26740
+ capName: "notification-rules",
26741
+ capScope: "system",
26742
+ addonId: null,
26743
+ access: "create"
26744
+ },
26745
+ "notificationRules.testRule": {
26746
+ capName: "notification-rules",
26747
+ capScope: "system",
26748
+ addonId: null,
26749
+ access: "create"
26750
+ },
26751
+ "notificationRules.updateRule": {
26752
+ capName: "notification-rules",
26753
+ capScope: "system",
26754
+ addonId: null,
26755
+ access: "create"
26756
+ },
26205
26757
  "notifier.cancel": {
26206
26758
  capName: "notifier",
26207
26759
  capScope: "device",