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