@camstack/addon-notifiers 1.2.4 → 1.2.6

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.
package/dist/addon.js CHANGED
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  let node_zlib = require("node:zlib");
6
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
6
+ //#region ../types/dist/event-category-BLcNejAE.mjs
7
7
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
8
8
  EventCategory["SystemBoot"] = "system.boot";
9
9
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -153,9 +153,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
153
153
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
154
154
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
155
155
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
156
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
157
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
158
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
159
156
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
160
157
  * progress bar the client reconciles via `recordingExport.getExport`. */
161
158
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6820,7 +6817,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6820
6817
  patch: record(string(), unknown())
6821
6818
  }), object({ success: literal(true) });
6822
6819
  object({ deviceId: number() }), unknown().nullable();
6823
- /** Shorthand to define a method schema */
6824
6820
  function method(input, output, options) {
6825
6821
  return {
6826
6822
  input,
@@ -6828,6 +6824,7 @@ function method(input, output, options) {
6828
6824
  kind: options?.kind ?? "query",
6829
6825
  auth: options?.auth ?? "protected",
6830
6826
  ...options?.access !== void 0 ? { access: options.access } : {},
6827
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6831
6828
  timeoutMs: options?.timeoutMs
6832
6829
  };
6833
6830
  }
@@ -8298,6 +8295,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8298
8295
  /** The complete taxonomy dictionary, keyed by kind. */
8299
8296
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8300
8297
  /**
8298
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8299
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8300
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8301
+ * taxonomy surface (timeline, filters, event page).
8302
+ *
8303
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8304
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8305
+ * for the `classes` / `classesExclude` conditions.
8306
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8307
+ * the same class picker, grouped under an Audio header.
8308
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8309
+ * lock / …) for the `sensorKinds` device-event condition.
8310
+ *
8311
+ * Each entry carries `parentKind` so the client can group video subs under
8312
+ * their macro and sensor/control kinds under their category. This surface is
8313
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8314
+ * method, no codegen — so it ships train-free with an addon deploy.
8315
+ */
8316
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8317
+ var NcTaxonomyEntrySchema = object({
8318
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8319
+ kind: string(),
8320
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8321
+ label: string(),
8322
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8323
+ parentKind: string().nullable()
8324
+ });
8325
+ object({
8326
+ videoClasses: array(NcTaxonomyEntrySchema),
8327
+ audioKinds: array(NcTaxonomyEntrySchema),
8328
+ labels: array(NcTaxonomyEntrySchema)
8329
+ });
8330
+ function toEntry(kind, label, parentKind) {
8331
+ return {
8332
+ kind,
8333
+ label,
8334
+ parentKind
8335
+ };
8336
+ }
8337
+ /**
8338
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8339
+ * (macros before their subs), which the client relies on for stable grouping.
8340
+ */
8341
+ function buildNcTaxonomy() {
8342
+ const all = Object.values(EVENT_TAXONOMY);
8343
+ return {
8344
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8345
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8346
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8347
+ };
8348
+ }
8349
+ Object.freeze(buildNcTaxonomy());
8350
+ /**
8301
8351
  * Error types for the safe expression engine. Two distinct classes so callers
8302
8352
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8303
8353
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -11199,6 +11249,22 @@ var CameraMetricsSchema = object({
11199
11249
  ])
11200
11250
  });
11201
11251
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
11252
+ /**
11253
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
11254
+ * within the frame, so the executor can re-cut a leaf child ROI at native
11255
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
11256
+ */
11257
+ var NativeCropRefSchema = object({
11258
+ /** Handle keying the retained native surface (node-pinned to its owner). */
11259
+ handle: FrameHandleSchema,
11260
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
11261
+ cropFrameSpace: object({
11262
+ x: number(),
11263
+ y: number(),
11264
+ w: number(),
11265
+ h: number()
11266
+ })
11267
+ });
11202
11268
  var ModelFormatSchema$1 = _enum([
11203
11269
  "onnx",
11204
11270
  "coreml",
@@ -11474,7 +11540,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
11474
11540
  * Omitted ⇒ the runner's default device (current single-engine
11475
11541
  * behaviour). Selects WHICH device pool of the node runs the call.
11476
11542
  */
11477
- deviceKey: string().optional()
11543
+ deviceKey: string().optional(),
11544
+ /**
11545
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
11546
+ * when the parent crop was resolved from the frame's retained NATIVE
11547
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
11548
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
11549
+ * resolution from that surface — the SAME quality path faces already
11550
+ * had — instead of the downscaled parent tile. `handle` keys the native
11551
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
11552
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
11553
+ * the executor's crop-normalized child ROI back into frame-normalized
11554
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
11555
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
11556
+ * (today's behaviour on the fallback path).
11557
+ */
11558
+ nativeCropRef: NativeCropRefSchema.optional()
11478
11559
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
11479
11560
  engine: PipelineEngineChoiceSchema.optional(),
11480
11561
  steps: array(PipelineStepInputSchema).min(1),
@@ -11690,7 +11771,11 @@ var DetailResultSchema = object({
11690
11771
  bbox: NativeCropBboxSchema.optional(),
11691
11772
  embedding: string().optional(),
11692
11773
  label: string().optional(),
11693
- alignedCropJpeg: string().optional()
11774
+ alignedCropJpeg: string().optional(),
11775
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
11776
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
11777
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
11778
+ nativeFaceShortSidePx: number().optional()
11694
11779
  });
11695
11780
  /**
11696
11781
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -11704,6 +11789,12 @@ var motionCooldownMsField = {
11704
11789
  default: 3e4,
11705
11790
  step: 500
11706
11791
  };
11792
+ var maxSessionHoldMsField = {
11793
+ min: 0,
11794
+ max: 6e5,
11795
+ default: 12e4,
11796
+ step: 5e3
11797
+ };
11707
11798
  var motionFpsField = {
11708
11799
  min: 1,
11709
11800
  max: 30,
@@ -11851,6 +11942,19 @@ var RunnerCameraConfigSchema = object({
11851
11942
  "on-motion"
11852
11943
  ]).default("always-on"),
11853
11944
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
11945
+ /**
11946
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
11947
+ * detection session is active and ≥1 confirmed non-stationary track is
11948
+ * still live, the orchestrator keeps the session open past
11949
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
11950
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
11951
+ * ms since the session opened, after which it closes regardless. `0`
11952
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
11953
+ * runner itself — carried here so it shares the per-camera device-settings
11954
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
11955
+ * resolved `CameraDetectionConfig`.
11956
+ */
11957
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
11854
11958
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
11855
11959
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
11856
11960
  motionStreamId: string(),
@@ -11940,7 +12044,7 @@ var RunnerCameraConfigSchema = object({
11940
12044
  */
11941
12045
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
11942
12046
  });
11943
- 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;
12047
+ 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;
11944
12048
  /**
11945
12049
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
11946
12050
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -13813,94 +13917,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
13813
13917
  bundleUrl: string()
13814
13918
  });
13815
13919
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
13816
- var NotificationRuleConditionsSchema = object({
13817
- deviceIds: array(number()).readonly().optional(),
13818
- classNames: array(string()).readonly().optional(),
13819
- zoneIds: array(string()).readonly().optional(),
13820
- minConfidence: number().optional(),
13821
- source: _enum([
13822
- "pipeline",
13823
- "onboard",
13824
- "any"
13825
- ]).optional(),
13826
- schedule: object({
13827
- days: array(number()).readonly(),
13828
- startHour: number(),
13829
- endHour: number()
13830
- }).optional(),
13831
- cooldownSeconds: number().optional(),
13832
- minDwellSeconds: number().optional(),
13833
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
13834
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
13835
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
13836
- eventTypeTokens: array(string()).readonly().optional(),
13837
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
13838
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
13839
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
13840
- clipDescription: object({
13841
- text: string().min(1),
13842
- minSimilarity: number().min(0).max(1)
13843
- }).optional(),
13844
- /** Match events whose recognized-entity label (face identity name or plate
13845
- * vehicle name, propagated onto `event.data.label`) is one of these values.
13846
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
13847
- * vehicle/person> is seen". */
13848
- labels: array(string()).readonly().optional()
13849
- });
13850
- var NotificationRuleTemplateSchema = object({
13851
- title: string(),
13852
- body: string(),
13853
- imageMode: _enum([
13854
- "crop",
13855
- "annotated",
13856
- "full",
13857
- "none"
13858
- ])
13859
- });
13860
- var NotificationRuleSchema = object({
13861
- id: string(),
13862
- name: string(),
13863
- enabled: boolean(),
13864
- eventTypes: array(string()).readonly(),
13865
- conditions: NotificationRuleConditionsSchema,
13866
- outputs: array(string()).readonly(),
13867
- template: NotificationRuleTemplateSchema.optional(),
13868
- priority: _enum([
13869
- "low",
13870
- "normal",
13871
- "high",
13872
- "critical"
13873
- ])
13874
- });
13875
- var NotificationTestResultSchema = object({
13876
- ruleId: string(),
13877
- eventId: string(),
13878
- timestamp: number(),
13879
- wouldFire: boolean(),
13880
- reason: string().optional()
13881
- });
13882
- var NotificationHistoryEntrySchema = object({
13883
- id: string(),
13884
- ruleId: string(),
13885
- ruleName: string(),
13886
- eventId: string(),
13887
- timestamp: number(),
13888
- outputs: array(string()).readonly(),
13889
- success: boolean(),
13890
- error: string().optional(),
13891
- deviceId: number().optional()
13892
- });
13893
- var NotificationHistoryFilterSchema = object({
13894
- ruleId: string().optional(),
13895
- deviceId: number().optional(),
13896
- from: number().optional(),
13897
- to: number().optional(),
13898
- limit: number().optional()
13899
- });
13900
- 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({
13901
- ruleId: string(),
13902
- lookbackMinutes: number()
13903
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
13904
13920
  /**
13905
13921
  * Alerts capability — collection-based internal alert system.
13906
13922
  *
@@ -14087,89 +14103,6 @@ method(object({
14087
14103
  password: string()
14088
14104
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
14089
14105
  /**
14090
- * `login-method` — collection cap through which auth addons contribute
14091
- * their pre-auth login surfaces to the login page. This is the SINGLE,
14092
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
14093
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
14094
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
14095
- * procedure aggregates them for the unauthenticated login page.
14096
- *
14097
- * A contribution is a discriminated union on `kind`:
14098
- *
14099
- * - `redirect` — a declarative button. The login page renders a generic
14100
- * button that navigates to `startUrl` (an addon-owned HTTP route).
14101
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
14102
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
14103
- * login page needs NO change.
14104
- *
14105
- * - `widget` — a Module-Federation widget the login page mounts (via
14106
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
14107
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
14108
- * mechanism kept for future use; no shipped addon uses it on the login
14109
- * page (the passkey ceremony below runs natively in the shell instead).
14110
- *
14111
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
14112
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
14113
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
14114
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
14115
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
14116
- * fetching any remote code pre-auth. Contribution stays unconditional —
14117
- * enrollment state is never leaked pre-auth; visibility is a shell
14118
- * decision.
14119
- *
14120
- * Every contribution carries a `stage`:
14121
- * - `primary` — shown on the first credentials screen (OIDC /
14122
- * magic-link buttons; a future usernameless passkey).
14123
- * - `second-factor` — shown AFTER the password leg, gated on the
14124
- * returned `factors` (passkey-as-2FA today).
14125
- *
14126
- * `mount: skip` — the cap is read server-side by the core auth router
14127
- * (`registry.getCollection('login-method')`), never mounted as its own
14128
- * tRPC router.
14129
- */
14130
- /** When a login method renders in the two-phase login flow. */
14131
- var LoginStageEnum = _enum(["primary", "second-factor"]);
14132
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
14133
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
14134
- object({
14135
- kind: literal("redirect"),
14136
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
14137
- id: string(),
14138
- /** Operator-facing button label. */
14139
- label: string(),
14140
- /** lucide-react icon name. */
14141
- icon: string().optional(),
14142
- /** Addon-owned HTTP route the button navigates to (GET). */
14143
- startUrl: string(),
14144
- stage: LoginStageEnum
14145
- }),
14146
- object({
14147
- kind: literal("widget"),
14148
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
14149
- id: string(),
14150
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
14151
- addonId: string(),
14152
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
14153
- bundle: string(),
14154
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
14155
- remote: WidgetRemoteSchema,
14156
- stage: LoginStageEnum
14157
- }),
14158
- object({
14159
- kind: literal("passkey"),
14160
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
14161
- id: string(),
14162
- /** Operator-facing button label. */
14163
- label: string(),
14164
- stage: LoginStageEnum,
14165
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
14166
- rpId: string(),
14167
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
14168
- origin: string().nullable()
14169
- })
14170
- ]);
14171
- method(_void(), array(LoginMethodContributionSchema).readonly());
14172
- /**
14173
14106
  * Orchestrator-side destination metadata. The orchestrator computes
14174
14107
  * `id = <addonId>:<subId>` from its provider lookup so consumers
14175
14108
  * (admin UI, restore flow) see one canonical key.
@@ -14526,6 +14459,28 @@ method(ListInputSchema, array(BrokerInfoSchema$1)), method(GetInputSchema, Broke
14526
14459
  }), method(GetStateInputSchema, unknown().nullable()), method(_void(), RegistryStatusSchema);
14527
14460
  DeviceType.Camera;
14528
14461
  /**
14462
+ * Identity — preserves literal types for downstream inference.
14463
+ *
14464
+ * The constraint is `Record<string, unknown>` (not `CustomActionsSpec`) so
14465
+ * TypeScript does not widen each entry's literal `kind`/`auth` fields to
14466
+ * the broader unions declared on `CustomActionSpec`'s default generics.
14467
+ * Shape validity is enforced separately by the `customAction(...)` helper
14468
+ * whose return type is already a `CustomActionSpec<...>`.
14469
+ */
14470
+ function defineCustomActions(spec) {
14471
+ return spec;
14472
+ }
14473
+ function customAction(input, output, options) {
14474
+ return {
14475
+ input,
14476
+ output,
14477
+ kind: options?.kind ?? "query",
14478
+ auth: options?.auth ?? "protected",
14479
+ scope: options?.scope ?? { kind: "system" },
14480
+ ...options?.caller ? { caller: "required" } : {}
14481
+ };
14482
+ }
14483
+ /**
14529
14484
  * `custom-model-registry` — collection cap exposing operator-registered
14530
14485
  * custom detection models. Each provider (today: `addon-model-studio`)
14531
14486
  * contributes a list of `CustomModelDescriptor`s; the hub auto-concatenates
@@ -15513,229 +15468,604 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
15513
15468
  kind: "mutation",
15514
15469
  auth: "admin"
15515
15470
  });
15516
- var LogLevelSchema = _enum([
15517
- "debug",
15518
- "info",
15519
- "warn",
15520
- "error"
15471
+ /**
15472
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15473
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15474
+ * caps stay wire-compatible without a circular cap→cap import.
15475
+ *
15476
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
15477
+ * every transport tier structurally, and failed calls still write usage rows.
15478
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15479
+ */
15480
+ var LlmUsageSchema = object({
15481
+ inputTokens: number(),
15482
+ outputTokens: number()
15483
+ });
15484
+ var LlmErrorCodeSchema = _enum([
15485
+ "timeout",
15486
+ "rate-limited",
15487
+ "auth",
15488
+ "refusal",
15489
+ "bad-request",
15490
+ "unavailable",
15491
+ "no-profile",
15492
+ "budget-exceeded",
15493
+ "adapter-error"
15521
15494
  ]);
15522
- var LogEntrySchema = object({
15523
- timestamp: date(),
15524
- level: LogLevelSchema,
15525
- scope: array(string()),
15495
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15496
+ ok: literal(true),
15497
+ text: string(),
15498
+ model: string(),
15499
+ usage: LlmUsageSchema,
15500
+ truncated: boolean(),
15501
+ latencyMs: number()
15502
+ }), object({
15503
+ ok: literal(false),
15504
+ code: LlmErrorCodeSchema,
15526
15505
  message: string(),
15527
- meta: record(string(), unknown()).optional(),
15528
- tags: record(string(), string()).optional()
15529
- });
15530
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15531
- scope: array(string()).optional(),
15532
- level: LogLevelSchema.optional(),
15533
- since: date().optional(),
15534
- until: date().optional(),
15535
- limit: number().optional(),
15536
- tags: record(string(), string()).optional()
15537
- }), array(LogEntrySchema).readonly());
15538
- var CpuBreakdownSchema = object({
15539
- total: number(),
15540
- user: number(),
15541
- system: number(),
15542
- irq: number(),
15543
- nice: number(),
15544
- loadAvg: tuple([
15545
- number(),
15546
- number(),
15547
- number()
15548
- ]),
15549
- cores: number()
15550
- });
15551
- var MemoryInfoSchema = object({
15552
- percent: number(),
15553
- totalBytes: number(),
15554
- usedBytes: number(),
15555
- availableBytes: number(),
15556
- swapUsedBytes: number(),
15557
- swapTotalBytes: number()
15506
+ retryAfterMs: number().optional()
15507
+ })]);
15508
+ /**
15509
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15510
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15511
+ * notification-output.cap.ts:27-31 precedents).
15512
+ */
15513
+ var LlmImageSchema = object({
15514
+ bytes: _instanceof(Uint8Array),
15515
+ mimeType: string()
15558
15516
  });
15559
- var DiskIoSnapshotSchema = object({
15560
- readBytes: number(),
15561
- writeBytes: number(),
15562
- readOps: number(),
15563
- writeOps: number(),
15564
- timestampMs: number()
15565
- });
15566
- var NetworkIoSnapshotSchema = object({
15567
- rxBytes: number(),
15568
- txBytes: number(),
15569
- rxPackets: number(),
15570
- txPackets: number(),
15571
- rxErrors: number(),
15572
- txErrors: number(),
15573
- timestampMs: number()
15574
- });
15575
- var MetricsGpuInfoSchema = object({
15576
- utilization: number(),
15577
- model: string(),
15578
- memoryUsedBytes: number(),
15579
- memoryTotalBytes: number(),
15580
- temperature: number().nullable()
15581
- });
15582
- var ProcessResourceInfoSchema = object({
15583
- openFds: number(),
15584
- threadCount: number(),
15585
- activeHandles: number(),
15586
- activeRequests: number()
15587
- });
15588
- var PressureAvgsSchema = object({
15589
- avg10: number(),
15590
- avg60: number(),
15591
- avg300: number()
15592
- });
15593
- var PressureInfoSchema = object({
15594
- some: PressureAvgsSchema,
15595
- full: PressureAvgsSchema.nullable()
15517
+ var LlmGenerateBaseInputSchema = object({
15518
+ /** Collection routing (the notification-output posture). */
15519
+ addonId: string().optional(),
15520
+ /** Explicit profile; else the resolution chain (spec §3). */
15521
+ profileId: string().optional(),
15522
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15523
+ consumer: string(),
15524
+ system: string().optional(),
15525
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
15526
+ prompt: string(),
15527
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15528
+ jsonSchema: record(string(), unknown()).optional(),
15529
+ /** Per-call override of the profile default. */
15530
+ maxTokens: number().int().positive().optional(),
15531
+ temperature: number().optional()
15596
15532
  });
15597
- var SystemResourceSnapshotSchema = object({
15598
- cpu: CpuBreakdownSchema,
15599
- memory: MemoryInfoSchema,
15600
- gpu: MetricsGpuInfoSchema.nullable(),
15601
- network: NetworkIoSnapshotSchema,
15602
- disk: DiskIoSnapshotSchema,
15603
- pressure: object({
15604
- cpu: PressureInfoSchema.nullable(),
15605
- memory: PressureInfoSchema.nullable(),
15606
- io: PressureInfoSchema.nullable()
15533
+ /**
15534
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15535
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15536
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15537
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15538
+ * this only through the `llm` cap's methods.
15539
+ *
15540
+ * One running llama-server child per node in v1 (models are RAM-heavy).
15541
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15542
+ * watchdog — operator decision #3).
15543
+ */
15544
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
15545
+ object({
15546
+ kind: literal("catalog"),
15547
+ catalogId: string()
15607
15548
  }),
15608
- process: ProcessResourceInfoSchema,
15609
- cpuTemperature: number().nullable(),
15610
- timestampMs: number()
15611
- });
15612
- var DiskSpaceInfoSchema = object({
15613
- path: string(),
15614
- totalBytes: number(),
15615
- usedBytes: number(),
15616
- availableBytes: number(),
15617
- percent: number()
15618
- });
15619
- var PidResourceStatsSchema = object({
15620
- pid: number(),
15621
- cpu: number(),
15622
- memory: number(),
15623
- /**
15624
- * Private (anonymous) resident bytes — the per-process V8 heap + native
15625
- * allocations NOT shared with other processes (Linux RssAnon). This is the
15626
- * "real" per-runner cost; summing it across runners is meaningful, unlike
15627
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
15628
- * Undefined where /proc is unavailable (e.g. macOS).
15629
- */
15630
- privateBytes: number().optional(),
15631
- /**
15632
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15633
- * code shared copy-on-write across runners. Undefined on macOS.
15634
- */
15635
- sharedBytes: number().optional()
15549
+ object({
15550
+ kind: literal("url"),
15551
+ url: string(),
15552
+ sha256: string().optional()
15553
+ }),
15554
+ object({
15555
+ kind: literal("path"),
15556
+ path: string()
15557
+ })
15558
+ ]);
15559
+ var ManagedRuntimeConfigSchema = object({
15560
+ /** WHERE the runtime lives — hub or any agent. */
15561
+ nodeId: string(),
15562
+ /** Closed for v1; 'ollama' is a v2 candidate. */
15563
+ engine: _enum(["llama-cpp"]),
15564
+ model: ManagedModelRefSchema,
15565
+ contextSize: number().int().default(4096),
15566
+ /** 0 = CPU-only. */
15567
+ gpuLayers: number().int().default(0),
15568
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15569
+ threads: number().int().optional(),
15570
+ /** Concurrent slots. */
15571
+ parallel: number().int().default(1),
15572
+ /** Else lazy: first generate boots it. */
15573
+ autoStart: boolean().default(false),
15574
+ /** 0 = never; frees RAM after quiet periods. */
15575
+ idleStopMinutes: number().int().default(30)
15636
15576
  });
15637
- var AddonInstanceSchema = object({
15638
- addonId: string(),
15577
+ var LlmRuntimeStatusSchema = object({
15578
+ /** Status is ALWAYS node-qualified. */
15639
15579
  nodeId: string(),
15640
- role: _enum(["hub", "worker"]),
15641
- pid: number(),
15642
15580
  state: _enum([
15643
- "starting",
15644
- "running",
15645
- "stopping",
15646
15581
  "stopped",
15647
- "crashed"
15648
- ]),
15649
- uptimeSec: number()
15650
- });
15651
- var NodeProcessSchema = object({
15652
- pid: number(),
15653
- ppid: number(),
15654
- pgid: number(),
15655
- classification: _enum([
15656
- "root",
15657
- "managed",
15658
- "system",
15659
- "ghost"
15582
+ "downloading",
15583
+ "starting",
15584
+ "ready",
15585
+ "crashed",
15586
+ "failed"
15660
15587
  ]),
15661
- /** `$process` addon binding when `managed`, else null. */
15662
- addonId: string().nullable(),
15663
- /** Kernel-reported nodeId when the process is a known agent/worker. */
15664
- nodeId: string().nullable(),
15665
- /** Truncated command line. */
15666
- command: string(),
15667
- cpuPercent: number(),
15668
- memoryRssBytes: number(),
15669
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15670
- uptimeSec: number(),
15671
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15672
- orphaned: boolean()
15673
- });
15674
- var KillProcessInputSchema = object({
15675
- pid: number(),
15676
- /** Force = SIGKILL. Default is SIGTERM. */
15677
- force: boolean().optional()
15678
- });
15679
- var KillProcessResultSchema = object({
15680
- success: boolean(),
15681
- reason: string().optional(),
15682
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15683
- });
15684
- var DumpHeapSnapshotInputSchema = object({
15685
- /** The addon whose runner should dump a heap snapshot. */
15686
- addonId: string() });
15687
- var DumpHeapSnapshotResultSchema = object({
15688
- success: boolean(),
15689
- /** Path of the written .heapsnapshot inside the runner's container/host. */
15690
- path: string().optional(),
15691
- /** Process pid that was signalled. */
15692
15588
  pid: number().optional(),
15693
- reason: string().optional()
15589
+ port: number().optional(),
15590
+ modelPath: string().optional(),
15591
+ modelId: string().optional(),
15592
+ downloadProgress: number().min(0).max(1).optional(),
15593
+ lastError: string().optional(),
15594
+ crashesInWindow: number(),
15595
+ /** Child RSS (sampled best-effort). */
15596
+ memoryBytes: number().optional(),
15597
+ vramBytes: number().optional()
15694
15598
  });
15695
- var SystemMetricsSchema = object({
15696
- cpuPercent: number(),
15697
- memoryPercent: number(),
15698
- memoryUsedMB: number(),
15699
- memoryTotalMB: number(),
15700
- diskPercent: number().optional(),
15701
- temperature: number().optional(),
15702
- gpuPercent: number().optional(),
15703
- gpuMemoryPercent: number().optional()
15599
+ var LlmNodeModelSchema = object({
15600
+ file: string(),
15601
+ sizeBytes: number(),
15602
+ catalogId: string().optional(),
15603
+ installedAt: number().optional()
15704
15604
  });
15705
- method(_void(), SystemResourceSnapshotSchema), method(_void(), SystemResourceSnapshotSchema.nullable()), method(_void(), SystemMetricsSchema), method(object({ dirPath: string() }), DiskSpaceInfoSchema), method(_void(), MetricsGpuInfoSchema.nullable()), method(_void(), number().nullable()), method(object({ pids: array(number()) }), array(PidResourceStatsSchema)), method(_void(), array(AddonInstanceSchema).readonly()), method(object({ addonId: string() }), PidResourceStatsSchema.nullable()), method(_void(), array(NodeProcessSchema).readonly()), method(KillProcessInputSchema, KillProcessResultSchema, {
15605
+ var LlmRuntimeDiskUsageSchema = object({
15606
+ nodeId: string(),
15607
+ modelsBytes: number(),
15608
+ freeBytes: number().optional()
15609
+ });
15610
+ method(LlmGenerateBaseInputSchema.extend({
15611
+ images: array(LlmImageSchema).optional(),
15612
+ runtime: ManagedRuntimeConfigSchema,
15613
+ /** The managed profile's timeout, threaded by the hub provider. */
15614
+ timeoutMs: number().int().positive().optional()
15615
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15706
15616
  kind: "mutation",
15707
15617
  auth: "admin"
15708
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15618
+ }), method(object({}), _void(), {
15709
15619
  kind: "mutation",
15710
15620
  auth: "admin"
15711
- });
15712
- method(object({
15713
- sourceUrl: string(),
15714
- metadata: ModelConvertMetadataSchema,
15715
- targets: array(ConvertTargetSchema).min(1).readonly(),
15716
- calibrationRef: string().optional(),
15717
- sessionId: string().optional()
15718
- }), ConvertResultSchema, {
15621
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15719
15622
  kind: "mutation",
15720
- auth: "admin",
15721
- timeoutMs: 6e5
15722
- });
15723
- method(object({
15724
- nodeId: string(),
15725
- modelId: string(),
15726
- format: _enum(MODEL_FORMATS),
15727
- entry: ModelCatalogEntrySchema
15728
- }), object({
15729
- ok: boolean(),
15730
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
15731
- sha256: string(),
15732
- bytes: number(),
15733
- /** The target node's modelsDir the artifact landed in. */
15734
- path: string()
15735
- }), {
15623
+ auth: "admin"
15624
+ }), method(object({ file: string() }), _void(), {
15736
15625
  kind: "mutation",
15737
15626
  auth: "admin"
15738
- });
15627
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15628
+ /**
15629
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15630
+ * methods concat-fan across providers; single-row methods route to ONE
15631
+ * provider by the `addonId` in the call input (the notification-output
15632
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15633
+ * (hub-placed); the cap stays open for future providers.
15634
+ *
15635
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15636
+ * `apiKey` is a password field — providers REDACT it on read and merge on
15637
+ * write; a stored key NEVER round-trips to a client.
15638
+ */
15639
+ var LlmProfileKindSchema = _enum([
15640
+ "openai-compatible",
15641
+ "openai",
15642
+ "anthropic",
15643
+ "google",
15644
+ "managed-local"
15645
+ ]);
15646
+ var LlmProfileSchema = object({
15647
+ id: string(),
15648
+ name: string(),
15649
+ kind: LlmProfileKindSchema,
15650
+ /** Stamped by the provider — keeps the fanned catalog routable. */
15651
+ addonId: string(),
15652
+ enabled: boolean(),
15653
+ /** Vendor model id, or the managed runtime's loaded model. */
15654
+ model: string(),
15655
+ /** Required for openai-compatible; override for cloud kinds. */
15656
+ baseUrl: string().optional(),
15657
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
15658
+ apiKey: string().optional(),
15659
+ supportsVision: boolean(),
15660
+ temperature: number().min(0).max(2).optional(),
15661
+ maxTokens: number().int().positive().optional(),
15662
+ timeoutMs: number().int().positive().default(6e4),
15663
+ extraHeaders: record(string(), string()).optional(),
15664
+ /** kind === 'managed-local' only (spec §4). */
15665
+ runtime: ManagedRuntimeConfigSchema.optional()
15666
+ });
15667
+ /** ConfigUISchema tree passed through untyped on the wire (the
15668
+ * notification-output `ConfigSchemaPassthrough` precedent at
15669
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15670
+ var ConfigSchemaPassthrough$1 = unknown();
15671
+ var LlmProfileKindDescriptorSchema = object({
15672
+ kind: LlmProfileKindSchema,
15673
+ label: string(),
15674
+ icon: string(),
15675
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
15676
+ addonId: string(),
15677
+ configSchema: ConfigSchemaPassthrough$1
15678
+ });
15679
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15680
+ var LlmDefaultSchema = object({
15681
+ selector: LlmDefaultSelectorSchema,
15682
+ profileId: string()
15683
+ });
15684
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
15685
+ var LlmUsageRollupSchema = object({
15686
+ day: string(),
15687
+ consumer: string(),
15688
+ profileId: string(),
15689
+ calls: number(),
15690
+ okCalls: number(),
15691
+ errorCalls: number(),
15692
+ inputTokens: number(),
15693
+ outputTokens: number(),
15694
+ avgLatencyMs: number()
15695
+ });
15696
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15697
+ var ManagedModelCatalogEntrySchema = object({
15698
+ id: string(),
15699
+ label: string(),
15700
+ family: string(),
15701
+ purpose: _enum(["text", "vision"]),
15702
+ url: string(),
15703
+ sha256: string(),
15704
+ sizeBytes: number(),
15705
+ quantization: string(),
15706
+ /** Load-time guidance shown in the picker. */
15707
+ minRamBytes: number(),
15708
+ contextSizeDefault: number().int(),
15709
+ /** Vision models: companion projector file. */
15710
+ mmprojUrl: string().optional()
15711
+ });
15712
+ var LlmRuntimeNodeSchema = object({
15713
+ nodeId: string(),
15714
+ reachable: boolean(),
15715
+ status: LlmRuntimeStatusSchema.optional(),
15716
+ disk: LlmRuntimeDiskUsageSchema.optional(),
15717
+ error: string().optional()
15718
+ });
15719
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
15720
+ var ProfileRefInputSchema = object({
15721
+ addonId: string(),
15722
+ profileId: string()
15723
+ });
15724
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
15725
+ kind: "mutation",
15726
+ auth: "admin"
15727
+ }), method(ProfileRefInputSchema, _void(), {
15728
+ kind: "mutation",
15729
+ auth: "admin"
15730
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
15731
+ kind: "mutation",
15732
+ auth: "admin"
15733
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
15734
+ selector: LlmDefaultSelectorSchema,
15735
+ profileId: string().nullable()
15736
+ }), _void(), {
15737
+ kind: "mutation",
15738
+ auth: "admin"
15739
+ }), method(object({
15740
+ since: number().optional(),
15741
+ until: number().optional(),
15742
+ consumer: string().optional(),
15743
+ profileId: string().optional()
15744
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
15745
+ nodeId: string(),
15746
+ model: ManagedModelRefSchema
15747
+ }), _void(), {
15748
+ kind: "mutation",
15749
+ auth: "admin"
15750
+ }), method(object({
15751
+ nodeId: string(),
15752
+ file: string()
15753
+ }), _void(), {
15754
+ kind: "mutation",
15755
+ auth: "admin"
15756
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
15757
+ kind: "mutation",
15758
+ auth: "admin"
15759
+ }), method(ProfileRefInputSchema, _void(), {
15760
+ kind: "mutation",
15761
+ auth: "admin"
15762
+ });
15763
+ var LogLevelSchema = _enum([
15764
+ "debug",
15765
+ "info",
15766
+ "warn",
15767
+ "error"
15768
+ ]);
15769
+ var LogEntrySchema = object({
15770
+ timestamp: date(),
15771
+ level: LogLevelSchema,
15772
+ scope: array(string()),
15773
+ message: string(),
15774
+ meta: record(string(), unknown()).optional(),
15775
+ tags: record(string(), string()).optional()
15776
+ });
15777
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15778
+ scope: array(string()).optional(),
15779
+ level: LogLevelSchema.optional(),
15780
+ since: date().optional(),
15781
+ until: date().optional(),
15782
+ limit: number().optional(),
15783
+ tags: record(string(), string()).optional()
15784
+ }), array(LogEntrySchema).readonly());
15785
+ /**
15786
+ * `login-method` — collection cap through which auth addons contribute
15787
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
15788
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
15789
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
15790
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
15791
+ * procedure aggregates them for the unauthenticated login page.
15792
+ *
15793
+ * A contribution is a discriminated union on `kind`:
15794
+ *
15795
+ * - `redirect` — a declarative button. The login page renders a generic
15796
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
15797
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
15798
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
15799
+ * login page needs NO change.
15800
+ *
15801
+ * - `widget` — a Module-Federation widget the login page mounts (via
15802
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
15803
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
15804
+ * mechanism kept for future use; no shipped addon uses it on the login
15805
+ * page (the passkey ceremony below runs natively in the shell instead).
15806
+ *
15807
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
15808
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
15809
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
15810
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
15811
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
15812
+ * fetching any remote code pre-auth. Contribution stays unconditional —
15813
+ * enrollment state is never leaked pre-auth; visibility is a shell
15814
+ * decision.
15815
+ *
15816
+ * Every contribution carries a `stage`:
15817
+ * - `primary` — shown on the first credentials screen (OIDC /
15818
+ * magic-link buttons; a future usernameless passkey).
15819
+ * - `second-factor` — shown AFTER the password leg, gated on the
15820
+ * returned `factors` (passkey-as-2FA today).
15821
+ *
15822
+ * `mount: skip` — the cap is read server-side by the core auth router
15823
+ * (`registry.getCollection('login-method')`), never mounted as its own
15824
+ * tRPC router.
15825
+ */
15826
+ /** When a login method renders in the two-phase login flow. */
15827
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
15828
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
15829
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
15830
+ object({
15831
+ kind: literal("redirect"),
15832
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
15833
+ id: string(),
15834
+ /** Operator-facing button label. */
15835
+ label: string(),
15836
+ /** lucide-react icon name. */
15837
+ icon: string().optional(),
15838
+ /** Addon-owned HTTP route the button navigates to (GET). */
15839
+ startUrl: string(),
15840
+ stage: LoginStageEnum
15841
+ }),
15842
+ object({
15843
+ kind: literal("widget"),
15844
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
15845
+ id: string(),
15846
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
15847
+ addonId: string(),
15848
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
15849
+ bundle: string(),
15850
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
15851
+ remote: WidgetRemoteSchema,
15852
+ stage: LoginStageEnum
15853
+ }),
15854
+ object({
15855
+ kind: literal("passkey"),
15856
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
15857
+ id: string(),
15858
+ /** Operator-facing button label. */
15859
+ label: string(),
15860
+ stage: LoginStageEnum,
15861
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
15862
+ rpId: string(),
15863
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
15864
+ origin: string().nullable()
15865
+ })
15866
+ ]);
15867
+ method(_void(), array(LoginMethodContributionSchema).readonly());
15868
+ var CpuBreakdownSchema = object({
15869
+ total: number(),
15870
+ user: number(),
15871
+ system: number(),
15872
+ irq: number(),
15873
+ nice: number(),
15874
+ loadAvg: tuple([
15875
+ number(),
15876
+ number(),
15877
+ number()
15878
+ ]),
15879
+ cores: number()
15880
+ });
15881
+ var MemoryInfoSchema = object({
15882
+ percent: number(),
15883
+ totalBytes: number(),
15884
+ usedBytes: number(),
15885
+ availableBytes: number(),
15886
+ swapUsedBytes: number(),
15887
+ swapTotalBytes: number()
15888
+ });
15889
+ var DiskIoSnapshotSchema = object({
15890
+ readBytes: number(),
15891
+ writeBytes: number(),
15892
+ readOps: number(),
15893
+ writeOps: number(),
15894
+ timestampMs: number()
15895
+ });
15896
+ var NetworkIoSnapshotSchema = object({
15897
+ rxBytes: number(),
15898
+ txBytes: number(),
15899
+ rxPackets: number(),
15900
+ txPackets: number(),
15901
+ rxErrors: number(),
15902
+ txErrors: number(),
15903
+ timestampMs: number()
15904
+ });
15905
+ var MetricsGpuInfoSchema = object({
15906
+ utilization: number(),
15907
+ model: string(),
15908
+ memoryUsedBytes: number(),
15909
+ memoryTotalBytes: number(),
15910
+ temperature: number().nullable()
15911
+ });
15912
+ var ProcessResourceInfoSchema = object({
15913
+ openFds: number(),
15914
+ threadCount: number(),
15915
+ activeHandles: number(),
15916
+ activeRequests: number()
15917
+ });
15918
+ var PressureAvgsSchema = object({
15919
+ avg10: number(),
15920
+ avg60: number(),
15921
+ avg300: number()
15922
+ });
15923
+ var PressureInfoSchema = object({
15924
+ some: PressureAvgsSchema,
15925
+ full: PressureAvgsSchema.nullable()
15926
+ });
15927
+ var SystemResourceSnapshotSchema = object({
15928
+ cpu: CpuBreakdownSchema,
15929
+ memory: MemoryInfoSchema,
15930
+ gpu: MetricsGpuInfoSchema.nullable(),
15931
+ network: NetworkIoSnapshotSchema,
15932
+ disk: DiskIoSnapshotSchema,
15933
+ pressure: object({
15934
+ cpu: PressureInfoSchema.nullable(),
15935
+ memory: PressureInfoSchema.nullable(),
15936
+ io: PressureInfoSchema.nullable()
15937
+ }),
15938
+ process: ProcessResourceInfoSchema,
15939
+ cpuTemperature: number().nullable(),
15940
+ timestampMs: number()
15941
+ });
15942
+ var DiskSpaceInfoSchema = object({
15943
+ path: string(),
15944
+ totalBytes: number(),
15945
+ usedBytes: number(),
15946
+ availableBytes: number(),
15947
+ percent: number()
15948
+ });
15949
+ var PidResourceStatsSchema = object({
15950
+ pid: number(),
15951
+ cpu: number(),
15952
+ memory: number(),
15953
+ /**
15954
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
15955
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
15956
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
15957
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
15958
+ * Undefined where /proc is unavailable (e.g. macOS).
15959
+ */
15960
+ privateBytes: number().optional(),
15961
+ /**
15962
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15963
+ * code shared copy-on-write across runners. Undefined on macOS.
15964
+ */
15965
+ sharedBytes: number().optional()
15966
+ });
15967
+ var AddonInstanceSchema = object({
15968
+ addonId: string(),
15969
+ nodeId: string(),
15970
+ role: _enum(["hub", "worker"]),
15971
+ pid: number(),
15972
+ state: _enum([
15973
+ "starting",
15974
+ "running",
15975
+ "stopping",
15976
+ "stopped",
15977
+ "crashed"
15978
+ ]),
15979
+ uptimeSec: number()
15980
+ });
15981
+ var NodeProcessSchema = object({
15982
+ pid: number(),
15983
+ ppid: number(),
15984
+ pgid: number(),
15985
+ classification: _enum([
15986
+ "root",
15987
+ "managed",
15988
+ "system",
15989
+ "ghost"
15990
+ ]),
15991
+ /** `$process` addon binding when `managed`, else null. */
15992
+ addonId: string().nullable(),
15993
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
15994
+ nodeId: string().nullable(),
15995
+ /** Truncated command line. */
15996
+ command: string(),
15997
+ cpuPercent: number(),
15998
+ memoryRssBytes: number(),
15999
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
16000
+ uptimeSec: number(),
16001
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
16002
+ orphaned: boolean()
16003
+ });
16004
+ var KillProcessInputSchema = object({
16005
+ pid: number(),
16006
+ /** Force = SIGKILL. Default is SIGTERM. */
16007
+ force: boolean().optional()
16008
+ });
16009
+ var KillProcessResultSchema = object({
16010
+ success: boolean(),
16011
+ reason: string().optional(),
16012
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
16013
+ });
16014
+ var DumpHeapSnapshotInputSchema = object({
16015
+ /** The addon whose runner should dump a heap snapshot. */
16016
+ addonId: string() });
16017
+ var DumpHeapSnapshotResultSchema = object({
16018
+ success: boolean(),
16019
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
16020
+ path: string().optional(),
16021
+ /** Process pid that was signalled. */
16022
+ pid: number().optional(),
16023
+ reason: string().optional()
16024
+ });
16025
+ var SystemMetricsSchema = object({
16026
+ cpuPercent: number(),
16027
+ memoryPercent: number(),
16028
+ memoryUsedMB: number(),
16029
+ memoryTotalMB: number(),
16030
+ diskPercent: number().optional(),
16031
+ temperature: number().optional(),
16032
+ gpuPercent: number().optional(),
16033
+ gpuMemoryPercent: number().optional()
16034
+ });
16035
+ method(_void(), SystemResourceSnapshotSchema), method(_void(), SystemResourceSnapshotSchema.nullable()), method(_void(), SystemMetricsSchema), method(object({ dirPath: string() }), DiskSpaceInfoSchema), method(_void(), MetricsGpuInfoSchema.nullable()), method(_void(), number().nullable()), method(object({ pids: array(number()) }), array(PidResourceStatsSchema)), method(_void(), array(AddonInstanceSchema).readonly()), method(object({ addonId: string() }), PidResourceStatsSchema.nullable()), method(_void(), array(NodeProcessSchema).readonly()), method(KillProcessInputSchema, KillProcessResultSchema, {
16036
+ kind: "mutation",
16037
+ auth: "admin"
16038
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
16039
+ kind: "mutation",
16040
+ auth: "admin"
16041
+ });
16042
+ method(object({
16043
+ sourceUrl: string(),
16044
+ metadata: ModelConvertMetadataSchema,
16045
+ targets: array(ConvertTargetSchema).min(1).readonly(),
16046
+ calibrationRef: string().optional(),
16047
+ sessionId: string().optional()
16048
+ }), ConvertResultSchema, {
16049
+ kind: "mutation",
16050
+ auth: "admin",
16051
+ timeoutMs: 6e5
16052
+ });
16053
+ method(object({
16054
+ nodeId: string(),
16055
+ modelId: string(),
16056
+ format: _enum(MODEL_FORMATS),
16057
+ entry: ModelCatalogEntrySchema
16058
+ }), object({
16059
+ ok: boolean(),
16060
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
16061
+ sha256: string(),
16062
+ bytes: number(),
16063
+ /** The target node's modelsDir the artifact landed in. */
16064
+ path: string()
16065
+ }), {
16066
+ kind: "mutation",
16067
+ auth: "admin"
16068
+ });
15739
16069
  /**
15740
16070
  * `mqtt-broker` — broker-registry cap.
15741
16071
  *
@@ -16007,14 +16337,14 @@ var TargetKindCapsSchema = object({
16007
16337
  * the union is large and not meant for runtime validation here; the exported
16008
16338
  * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
16009
16339
  */
16010
- var ConfigSchemaPassthrough$1 = unknown();
16340
+ var ConfigSchemaPassthrough = unknown();
16011
16341
  var TargetKindSchema = object({
16012
16342
  kind: string(),
16013
16343
  label: string(),
16014
16344
  icon: string(),
16015
16345
  /** Stamped by each provider so the concat-fanned catalog stays routable. */
16016
16346
  addonId: string(),
16017
- configSchema: ConfigSchemaPassthrough$1,
16347
+ configSchema: ConfigSchemaPassthrough,
16018
16348
  supportsDiscovery: boolean(),
16019
16349
  caps: TargetKindCapsSchema
16020
16350
  });
@@ -16081,297 +16411,493 @@ var notificationOutputCapability = {
16081
16411
  }
16082
16412
  };
16083
16413
  /**
16084
- * Shared LLM generate contracts imported by BOTH `llm.cap.ts` (consumer
16085
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
16086
- * caps stay wire-compatible without a circular cap→cap import.
16414
+ * notification-rules the Notification Center rule surface (P1 core).
16087
16415
  *
16088
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
16089
- * every transport tier structurally, and failed calls still write usage rows.
16090
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
16416
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16417
+ * (operator decisions D-1/D-2/D-3 are binding):
16418
+ *
16419
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16420
+ * `notification-center` module), hooked on the durable persistence
16421
+ * moments (object-event insert, TrackCloser.closeExpired) with a
16422
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
16423
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16424
+ * FIRST persisted detection matching the conditions (per-track dedup,
16425
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16426
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
16427
+ * - DISPATCH stays behind `notification-output` (rules reference targets
16428
+ * by id; per-backend params are a passthrough blob capped by the
16429
+ * target kind's own caps/degrade engine).
16430
+ *
16431
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
16432
+ * server-injected caller identity — the first `caller: 'required'`
16433
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
16434
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
16435
+ * windows, and the optional label/identity/plate matchers. User rules,
16436
+ * private zones, per-recipient fan-out and the wider condition table are
16437
+ * P2+ (see spec §7).
16438
+ *
16439
+ * All schemas here are the single source of truth — `NcRule` etc. are
16440
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16441
+ * schema/interface drift is explicitly not repeated).
16091
16442
  */
16092
- var LlmUsageSchema = object({
16093
- inputTokens: number(),
16094
- outputTokens: number()
16095
- });
16096
- var LlmErrorCodeSchema = _enum([
16097
- "timeout",
16098
- "rate-limited",
16099
- "auth",
16100
- "refusal",
16101
- "bad-request",
16102
- "unavailable",
16103
- "no-profile",
16104
- "budget-exceeded",
16105
- "adapter-error"
16443
+ /**
16444
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
16445
+ * The value maps 1:1 onto the evaluated record kind:
16446
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16447
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16448
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16449
+ * change of a LINKED device, one row per linked camera)
16450
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16451
+ * delivery / pick-up)
16452
+ *
16453
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16454
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
16455
+ * this one field keeps the schema additive — a rule still declares exactly
16456
+ * one trigger.
16457
+ */
16458
+ var NcDeliverySchema = _enum([
16459
+ "immediate",
16460
+ "track-end",
16461
+ "device-event",
16462
+ "package-event"
16106
16463
  ]);
16107
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
16108
- ok: literal(true),
16109
- text: string(),
16110
- model: string(),
16111
- usage: LlmUsageSchema,
16112
- truncated: boolean(),
16113
- latencyMs: number()
16114
- }), object({
16115
- ok: literal(false),
16116
- code: LlmErrorCodeSchema,
16117
- message: string(),
16118
- retryAfterMs: number().optional()
16119
- })]);
16464
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
16465
+ var NcScheduleSchema = object({
16466
+ windows: array(object({
16467
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16468
+ days: array(number().int().min(0).max(6)).min(1),
16469
+ startMinute: number().int().min(0).max(1439),
16470
+ endMinute: number().int().min(0).max(1439)
16471
+ })).min(1),
16472
+ /** IANA timezone; default = hub host timezone. */
16473
+ timezone: string().optional(),
16474
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16475
+ invert: boolean().optional()
16476
+ });
16477
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16478
+ var NcPlateMatcherSchema = object({
16479
+ values: array(string().min(1)).min(1),
16480
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16481
+ maxDistance: number().int().min(0).max(3).default(1)
16482
+ });
16120
16483
  /**
16121
- * `Uint8Array` is the sanctioned binary convention superjson + the UDS
16122
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
16123
- * notification-output.cap.ts:27-31 precedents).
16484
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16485
+ * occupancy edge for a device — optionally narrowed to a single admin
16486
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16487
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
16488
+ * - `became-free` — count crossed ≥ `count` → below it
16489
+ * - `>=` / `<=` — count is at/over or at/under `count`
16490
+ * `sustainSeconds` requires the condition hold continuously that long
16491
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
16492
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16493
+ * the condition never matches. Confirmed edge-state survives addon restarts
16494
+ * (declared SQLite collection, reseeded on boot).
16124
16495
  */
16125
- var LlmImageSchema = object({
16126
- bytes: _instanceof(Uint8Array),
16127
- mimeType: string()
16496
+ var NcOccupancyConditionSchema = object({
16497
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16498
+ zoneId: string().optional(),
16499
+ /** Object class to count; absent = any class. */
16500
+ className: string().optional(),
16501
+ op: _enum([
16502
+ "became-occupied",
16503
+ "became-free",
16504
+ ">=",
16505
+ "<="
16506
+ ]).default("became-occupied"),
16507
+ count: number().int().min(0).default(1),
16508
+ sustainSeconds: number().int().min(0).max(3600).default(15)
16509
+ });
16510
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16511
+ var NcZoneConditionSchema = object({
16512
+ ids: array(string().min(1)).min(1),
16513
+ /** Quantifier over `ids` — at least one / every one visited. */
16514
+ match: _enum(["any", "all"]).default("any")
16128
16515
  });
16129
- var LlmGenerateBaseInputSchema = object({
16130
- /** Collection routing (the notification-output posture). */
16131
- addonId: string().optional(),
16132
- /** Explicit profile; else the resolution chain (spec §3). */
16133
- profileId: string().optional(),
16134
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', */
16135
- consumer: string(),
16136
- system: string().optional(),
16137
- /** v1: single-turn. `messages[]` is a v2 additive field. */
16138
- prompt: string(),
16139
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
16140
- jsonSchema: record(string(), unknown()).optional(),
16141
- /** Per-call override of the profile default. */
16142
- maxTokens: number().int().positive().optional(),
16143
- temperature: number().optional()
16516
+ /**
16517
+ * The P1 condition set a flat AND of groups; absent group = pass;
16518
+ * membership lists are OR within the list (spec §2.3).
16519
+ */
16520
+ var NcConditionsSchema = object({
16521
+ /** Device scope absent = all devices. */
16522
+ devices: array(number()).optional(),
16523
+ /** Detector class names (any overlap with the record's class set). */
16524
+ classes: array(string().min(1)).optional(),
16525
+ /** Veto classes — any overlap fails the rule. */
16526
+ classesExclude: array(string().min(1)).optional(),
16527
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
16528
+ minConfidence: number().min(0).max(1).optional(),
16529
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
16530
+ zones: NcZoneConditionSchema.optional(),
16531
+ /** Veto zones — any hit fails the rule. */
16532
+ zonesExclude: array(string().min(1)).optional(),
16533
+ /**
16534
+ * Exact (case-insensitive) match on the record's collapsed `label`
16535
+ * (identity name / plate text / subclass).
16536
+ */
16537
+ labelEquals: array(string().min(1)).optional(),
16538
+ /**
16539
+ * Identity matcher. P1 boundary: matched against the record's collapsed
16540
+ * `label` (the identity display name propagated by the face pipeline) —
16541
+ * identity-ID matching rides in P2 when identity ids reach the record.
16542
+ */
16543
+ identities: array(string().min(1)).optional(),
16544
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
16545
+ plates: NcPlateMatcherSchema.optional(),
16546
+ /**
16547
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16548
+ * Same P1 boundary: matched against the record's collapsed `label` (the
16549
+ * identity display name). A record with NO label passes (nothing to
16550
+ * exclude), unlike the include variant which fails on an absent label.
16551
+ */
16552
+ identitiesExclude: array(string().min(1)).optional(),
16553
+ /**
16554
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16555
+ * TRACK-END only: importance is scored at track close, so it does not exist
16556
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16557
+ * close the value is threaded via the close-time info (the `Track` clone is
16558
+ * captured before the DB row is updated, so it would otherwise read stale).
16559
+ * Fails when the record carries no importance (never guess quality — the
16560
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
16561
+ */
16562
+ minImportance: number().min(0).max(1).optional(),
16563
+ /**
16564
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16565
+ * TRACK-END only: an `immediate` / object-event subject has no closed
16566
+ * lifespan, so a dwell condition never matches immediate delivery
16567
+ * (documented choice — the object-event record carries no `firstSeen`,
16568
+ * so dwell cannot be computed from what the subject actually carries).
16569
+ */
16570
+ minDwellSeconds: number().min(0).optional(),
16571
+ /**
16572
+ * Detection provenance filter. `any` (default / absent) matches every
16573
+ * source; otherwise the subject's source must equal it. Legacy records
16574
+ * with no stamped source are treated as `pipeline`. The union spans both
16575
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
16576
+ * tracks carry `sensor`.
16577
+ */
16578
+ source: _enum([
16579
+ "pipeline",
16580
+ "onboard",
16581
+ "sensor",
16582
+ "any"
16583
+ ]).optional(),
16584
+ /**
16585
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16586
+ * detector `minConfidence` (that gates the object-detection score; this
16587
+ * gates the recognition/OCR match score). Fails when the subject carries
16588
+ * no label-match confidence (never guess). TRACK-END only: the confidence
16589
+ * lives on the recognition result and reaches the subject at track close.
16590
+ *
16591
+ * What it measures precisely (plumbed at track close — the closer threads
16592
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16593
+ * `importance`): the BEST recognition match confidence observed for the
16594
+ * label the track carries at close — for a face, the peak cosine similarity
16595
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16596
+ * for a plate, the peak OCR read score of the best-held plate
16597
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16598
+ * one track the higher of the two is used. A track that ended with no
16599
+ * confident identity/plate match carries no value, so the condition fails
16600
+ * closed for it (an un-recognized subject).
16601
+ */
16602
+ minLabelConfidence: number().min(0).max(1).optional(),
16603
+ /**
16604
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16605
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16606
+ * against the token carried on the device-event subject (extracted from the
16607
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16608
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16609
+ * eventType, so gate those with {@link sensorKinds} instead.
16610
+ */
16611
+ eventTypeTokens: array(string().min(1)).optional(),
16612
+ /**
16613
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16614
+ * `contact`, `button`, `device-event`) — matched against the persisted
16615
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16616
+ */
16617
+ sensorKinds: array(string().min(1)).optional(),
16618
+ /**
16619
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16620
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16621
+ * when the subject's phase does not match (a subject always carries a phase
16622
+ * on the package-event trigger).
16623
+ */
16624
+ packagePhase: _enum([
16625
+ "delivered",
16626
+ "picked-up",
16627
+ "both"
16628
+ ]).optional(),
16629
+ /**
16630
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16631
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16632
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
16633
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16634
+ */
16635
+ customZones: array(MaskPolygonShapeSchema).optional(),
16636
+ /**
16637
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16638
+ * (optionally zone/class-scoped) occupancy count crosses the configured
16639
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
16640
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16641
+ */
16642
+ occupancy: NcOccupancyConditionSchema.optional()
16643
+ });
16644
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
16645
+ var NcRuleTargetSchema = object({
16646
+ /** `notification-output` Target id. */
16647
+ targetId: string().min(1),
16648
+ /**
16649
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
16650
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16651
+ * degrade engine drops what the backend can't render.
16652
+ */
16653
+ params: record(string(), unknown()).optional()
16144
16654
  });
16145
16655
  /**
16146
- * `llm-runtime` node-side managed llama.cpp executor (spec §4). Registered
16147
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
16148
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` normal
16149
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
16150
- * this only through the `llm` cap's methods.
16151
- *
16152
- * One running llama-server child per node in v1 (models are RAM-heavy).
16153
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
16154
- * watchdog operator decision #3).
16656
+ * Media attachment policy (P1 still-image subset).
16657
+ * - `best` the best AVAILABLE subject image at dispatch time (D-3).
16658
+ * - `best-matching` the media that explains WHY the rule fired: a rule
16659
+ * matched on identities attaches the subject's `faceCrop`, one matched on
16660
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
16661
+ * (or when the specific crop is missing) degrades to `best`, then
16662
+ * `keyFrame`, then no attachment never delaying the send. The matched
16663
+ * condition summary is frozen on the outbox row at enqueue (like the rule
16664
+ * name), so the choice never drifts from the record that fired it.
16665
+ * - `keyFrame` — the clean scene frame (no subject box).
16666
+ * - `none` — no attachment.
16155
16667
  */
16156
- var ManagedModelRefSchema = discriminatedUnion("kind", [
16157
- object({
16158
- kind: literal("catalog"),
16159
- catalogId: string()
16160
- }),
16161
- object({
16162
- kind: literal("url"),
16163
- url: string(),
16164
- sha256: string().optional()
16668
+ var NcMediaPolicySchema = object({ attach: _enum([
16669
+ "best",
16670
+ "best-matching",
16671
+ "keyFrame",
16672
+ "none"
16673
+ ]).default("best") });
16674
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16675
+ var NcThrottleSchema = object({
16676
+ cooldownSec: number().int().min(0).max(86400).default(60),
16677
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16678
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
16679
+ });
16680
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16681
+ var NcRuleInputSchema = object({
16682
+ name: string().min(1).max(200),
16683
+ enabled: boolean().default(true),
16684
+ delivery: NcDeliverySchema,
16685
+ conditions: NcConditionsSchema.default({}),
16686
+ schedule: NcScheduleSchema.optional(),
16687
+ targets: array(NcRuleTargetSchema).min(1),
16688
+ media: NcMediaPolicySchema.default({ attach: "best" }),
16689
+ throttle: NcThrottleSchema.default({
16690
+ cooldownSec: 60,
16691
+ scope: "rule-device"
16165
16692
  }),
16166
- object({
16167
- kind: literal("path"),
16168
- path: string()
16169
- })
16170
- ]);
16171
- var ManagedRuntimeConfigSchema = object({
16172
- /** WHERE the runtime lives — hub or any agent. */
16173
- nodeId: string(),
16174
- /** Closed for v1; 'ollama' is a v2 candidate. */
16175
- engine: _enum(["llama-cpp"]),
16176
- model: ManagedModelRefSchema,
16177
- contextSize: number().int().default(4096),
16178
- /** 0 = CPU-only. */
16179
- gpuLayers: number().int().default(0),
16180
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
16181
- threads: number().int().optional(),
16182
- /** Concurrent slots. */
16183
- parallel: number().int().default(1),
16184
- /** Else lazy: first generate boots it. */
16185
- autoStart: boolean().default(false),
16186
- /** 0 = never; frees RAM after quiet periods. */
16187
- idleStopMinutes: number().int().default(30)
16693
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16694
+ template: object({
16695
+ title: string().max(500).optional(),
16696
+ body: string().max(2e3).optional()
16697
+ }).optional(),
16698
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
16699
+ priority: number().int().min(1).max(5).default(3),
16700
+ /**
16701
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16702
+ * behaviour, visible to all, read-only in the viewer). Present = personal
16703
+ * rule owned by this userId. Server-stamped; never trusted from a client.
16704
+ */
16705
+ ownerUserId: string().optional()
16188
16706
  });
16189
- var LlmRuntimeStatusSchema = object({
16190
- /** Status is ALWAYS node-qualified. */
16191
- nodeId: string(),
16192
- state: _enum([
16193
- "stopped",
16194
- "downloading",
16195
- "starting",
16196
- "ready",
16197
- "crashed",
16198
- "failed"
16707
+ /**
16708
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
16709
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16710
+ * NOT a client-authored input field (it lives on the persisted rule, not the
16711
+ * input), so it is added here explicitly to let the store's per-target opt-out
16712
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16713
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16714
+ * `updateRule` patch.
16715
+ */
16716
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
16717
+ /** A persisted rule. */
16718
+ var NcRuleSchema = NcRuleInputSchema.extend({
16719
+ id: string(),
16720
+ /** userId of the admin who created the rule (server-stamped caller). */
16721
+ createdBy: string(),
16722
+ createdAt: number(),
16723
+ updatedAt: number(),
16724
+ /**
16725
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16726
+ * send time. Only a target's OWNER may add/remove its id (server-checked
16727
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
16728
+ */
16729
+ disabledTargetIds: array(string()).default([])
16730
+ });
16731
+ var NcTestResultSchema = object({
16732
+ recordId: string(),
16733
+ recordKind: _enum([
16734
+ "object-event",
16735
+ "track",
16736
+ "device-event",
16737
+ "package-event"
16199
16738
  ]),
16200
- pid: number().optional(),
16201
- port: number().optional(),
16202
- modelPath: string().optional(),
16203
- modelId: string().optional(),
16204
- downloadProgress: number().min(0).max(1).optional(),
16205
- lastError: string().optional(),
16206
- crashesInWindow: number(),
16207
- /** Child RSS (sampled best-effort). */
16208
- memoryBytes: number().optional(),
16209
- vramBytes: number().optional()
16210
- });
16211
- var LlmNodeModelSchema = object({
16212
- file: string(),
16213
- sizeBytes: number(),
16214
- catalogId: string().optional(),
16215
- installedAt: number().optional()
16739
+ deviceId: number(),
16740
+ timestamp: number(),
16741
+ wouldFire: boolean(),
16742
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
16743
+ failedCondition: string().optional(),
16744
+ className: string().optional(),
16745
+ label: string().optional()
16216
16746
  });
16217
- var LlmRuntimeDiskUsageSchema = object({
16218
- nodeId: string(),
16219
- modelsBytes: number(),
16220
- freeBytes: number().optional()
16747
+ var NcConditionDescriptorSchema = object({
16748
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16749
+ id: string(),
16750
+ group: _enum([
16751
+ "scope",
16752
+ "class",
16753
+ "zones",
16754
+ "quality",
16755
+ "label",
16756
+ "schedule",
16757
+ "device",
16758
+ "package",
16759
+ "occupancy"
16760
+ ]),
16761
+ label: string(),
16762
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
16763
+ valueType: _enum([
16764
+ "deviceIdList",
16765
+ "stringList",
16766
+ "number01",
16767
+ "number",
16768
+ "sourceSelect",
16769
+ "zoneSelection",
16770
+ "zoneIdList",
16771
+ "schedule",
16772
+ "plateMatcher",
16773
+ "packagePhase",
16774
+ "polygonDraw",
16775
+ "occupancy"
16776
+ ]),
16777
+ operator: _enum([
16778
+ "in",
16779
+ "notIn",
16780
+ "anyOf",
16781
+ "allOf",
16782
+ "gte",
16783
+ "fuzzyIn",
16784
+ "withinSchedule"
16785
+ ]),
16786
+ /** Which delivery kinds the condition applies to. */
16787
+ appliesTo: array(NcDeliverySchema),
16788
+ phase: string(),
16789
+ description: string().optional()
16221
16790
  });
16222
- method(LlmGenerateBaseInputSchema.extend({
16223
- images: array(LlmImageSchema).optional(),
16224
- runtime: ManagedRuntimeConfigSchema,
16225
- /** The managed profile's timeout, threaded by the hub provider. */
16226
- timeoutMs: number().int().positive().optional()
16227
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
16228
- kind: "mutation",
16229
- auth: "admin"
16230
- }), method(object({}), _void(), {
16231
- kind: "mutation",
16232
- auth: "admin"
16233
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
16234
- kind: "mutation",
16235
- auth: "admin"
16236
- }), method(object({ file: string() }), _void(), {
16237
- kind: "mutation",
16238
- auth: "admin"
16239
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
16240
16791
  /**
16241
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
16242
- * methods concat-fan across providers; single-row methods route to ONE
16243
- * provider by the `addonId` in the call input (the notification-output
16244
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
16245
- * (hub-placed); the cap stays open for future providers.
16792
+ * The delivery lifecycle status of a history row — a straight read of the
16793
+ * durable outbox row's own status (single source of truth):
16794
+ * - `pending` enqueued, in-flight or retrying with backoff
16795
+ * - `sent` — delivered (terminal)
16796
+ * - `dead` — dead-lettered after exhausting retries / a permanent
16797
+ * backend rejection / a deleted target (terminal; carries
16798
+ * the failure `error`)
16246
16799
  *
16247
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
16248
- * `apiKey` is a password field providers REDACT it on read and merge on
16249
- * write; a stored key NEVER round-trips to a client.
16800
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states those ride the P2
16801
+ * user dimension (quiet hours / snooze) and are additive when they land.
16250
16802
  */
16251
- var LlmProfileKindSchema = _enum([
16252
- "openai-compatible",
16253
- "openai",
16254
- "anthropic",
16255
- "google",
16256
- "managed-local"
16803
+ var NcHistoryStatusSchema = _enum([
16804
+ "pending",
16805
+ "sent",
16806
+ "dead"
16257
16807
  ]);
16258
- var LlmProfileSchema = object({
16259
- id: string(),
16260
- name: string(),
16261
- kind: LlmProfileKindSchema,
16262
- /** Stamped by the provider — keeps the fanned catalog routable. */
16263
- addonId: string(),
16264
- enabled: boolean(),
16265
- /** Vendor model id, or the managed runtime's loaded model. */
16266
- model: string(),
16267
- /** Required for openai-compatible; override for cloud kinds. */
16268
- baseUrl: string().optional(),
16269
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
16270
- apiKey: string().optional(),
16271
- supportsVision: boolean(),
16272
- temperature: number().min(0).max(2).optional(),
16273
- maxTokens: number().int().positive().optional(),
16274
- timeoutMs: number().int().positive().default(6e4),
16275
- extraHeaders: record(string(), string()).optional(),
16276
- /** kind === 'managed-local' only (spec §4). */
16277
- runtime: ManagedRuntimeConfigSchema.optional()
16278
- });
16279
- /** ConfigUISchema tree passed through untyped on the wire (the
16280
- * notification-output `ConfigSchemaPassthrough` precedent at
16281
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
16282
- var ConfigSchemaPassthrough = unknown();
16283
- var LlmProfileKindDescriptorSchema = object({
16284
- kind: LlmProfileKindSchema,
16285
- label: string(),
16286
- icon: string(),
16287
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
16288
- addonId: string(),
16289
- configSchema: ConfigSchemaPassthrough
16290
- });
16291
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
16292
- var LlmDefaultSchema = object({
16293
- selector: LlmDefaultSelectorSchema,
16294
- profileId: string()
16295
- });
16296
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
16297
- var LlmUsageRollupSchema = object({
16298
- day: string(),
16299
- consumer: string(),
16300
- profileId: string(),
16301
- calls: number(),
16302
- okCalls: number(),
16303
- errorCalls: number(),
16304
- inputTokens: number(),
16305
- outputTokens: number(),
16306
- avgLatencyMs: number()
16808
+ /** The evaluated record kind a history row descends from (one per trigger). */
16809
+ var NcHistoryRecordKindSchema = _enum([
16810
+ "object-event",
16811
+ "track-end",
16812
+ "device-event",
16813
+ "package-event"
16814
+ ]);
16815
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16816
+ var NcHistorySubjectSchema = object({
16817
+ className: string(),
16818
+ label: string().optional(),
16819
+ confidence: number().optional(),
16820
+ zones: array(string()),
16821
+ timestamp: number()
16307
16822
  });
16308
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
16309
- var ManagedModelCatalogEntrySchema = object({
16823
+ /**
16824
+ * One delivery-history row. This is a read-only VIEW over the durable
16825
+ * outbox row (single source of truth — the same row the drain loop drives;
16826
+ * NO second write path, so history can never drift from delivery state).
16827
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16828
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16829
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
16830
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16831
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16832
+ * P1 (admin scope only).
16833
+ */
16834
+ var NcHistoryEntrySchema = object({
16835
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16310
16836
  id: string(),
16311
- label: string(),
16312
- family: string(),
16313
- purpose: _enum(["text", "vision"]),
16314
- url: string(),
16315
- sha256: string(),
16316
- sizeBytes: number(),
16317
- quantization: string(),
16318
- /** Load-time guidance shown in the picker. */
16319
- minRamBytes: number(),
16320
- contextSizeDefault: number().int(),
16321
- /** Vision models: companion projector file. */
16322
- mmprojUrl: string().optional()
16323
- });
16324
- var LlmRuntimeNodeSchema = object({
16325
- nodeId: string(),
16326
- reachable: boolean(),
16327
- status: LlmRuntimeStatusSchema.optional(),
16328
- disk: LlmRuntimeDiskUsageSchema.optional(),
16329
- error: string().optional()
16330
- });
16331
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16332
- var ProfileRefInputSchema = object({
16333
- addonId: string(),
16334
- profileId: string()
16837
+ ruleId: string(),
16838
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
16839
+ ruleName: string(),
16840
+ /** The rule urgency/trigger that produced this delivery. */
16841
+ delivery: NcDeliverySchema,
16842
+ targetId: string(),
16843
+ deviceId: number(),
16844
+ recordKind: NcHistoryRecordKindSchema,
16845
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16846
+ recordId: string(),
16847
+ /** Present for track-scoped deliveries (object-event / track-end). */
16848
+ trackId: string().optional(),
16849
+ status: NcHistoryStatusSchema,
16850
+ /** Delivery attempts made so far. */
16851
+ attempts: number().int(),
16852
+ /** Fire time (outbox enqueue). */
16853
+ createdAt: number(),
16854
+ /** Last transition time (terminal for sent / dead). */
16855
+ updatedAt: number(),
16856
+ /** Failure detail — present on a `dead` row. */
16857
+ error: string().optional(),
16858
+ subject: NcHistorySubjectSchema
16335
16859
  });
16336
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16337
- kind: "mutation",
16338
- auth: "admin"
16339
- }), method(ProfileRefInputSchema, _void(), {
16340
- kind: "mutation",
16341
- auth: "admin"
16342
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16343
- kind: "mutation",
16344
- auth: "admin"
16345
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
16346
- selector: LlmDefaultSelectorSchema,
16347
- profileId: string().nullable()
16348
- }), _void(), {
16349
- kind: "mutation",
16350
- auth: "admin"
16351
- }), method(object({
16860
+ /**
16861
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16862
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16863
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16864
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16865
+ */
16866
+ var NcHistoryFilterSchema = object({
16867
+ ruleId: string().optional(),
16868
+ deviceId: number().optional(),
16869
+ status: NcHistoryStatusSchema.optional(),
16352
16870
  since: number().optional(),
16353
- until: number().optional(),
16354
- consumer: string().optional(),
16355
- profileId: string().optional()
16356
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
16357
- nodeId: string(),
16358
- model: ManagedModelRefSchema
16359
- }), _void(), {
16871
+ until: number().optional(),
16872
+ limit: number().int().min(1).max(500).default(100)
16873
+ });
16874
+ 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 }), {
16360
16875
  kind: "mutation",
16361
- auth: "admin"
16876
+ auth: "admin",
16877
+ caller: "required"
16362
16878
  }), method(object({
16363
- nodeId: string(),
16364
- file: string()
16365
- }), _void(), {
16879
+ ruleId: string(),
16880
+ patch: NcRulePatchSchema
16881
+ }), object({ rule: NcRuleSchema }), {
16882
+ kind: "mutation",
16883
+ auth: "admin",
16884
+ caller: "required"
16885
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
16366
16886
  kind: "mutation",
16367
16887
  auth: "admin"
16368
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16888
+ }), method(object({
16889
+ ruleId: string(),
16890
+ enabled: boolean()
16891
+ }), object({ success: literal(true) }), {
16369
16892
  kind: "mutation",
16370
16893
  auth: "admin"
16371
- }), method(ProfileRefInputSchema, _void(), {
16894
+ }), method(object({
16895
+ rule: NcRuleInputSchema,
16896
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
16897
+ }), object({ results: array(NcTestResultSchema) }), {
16372
16898
  kind: "mutation",
16373
16899
  auth: "admin"
16374
- });
16900
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
16375
16901
  /**
16376
16902
  * Zod schemas for persisted record types.
16377
16903
  *
@@ -17057,7 +17583,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
17057
17583
  }), method(object({
17058
17584
  eventId: string(),
17059
17585
  kind: MediaFileKindEnum.optional()
17060
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
17586
+ }), array(MediaFileSchema).readonly()), method(object({
17587
+ trackId: string(),
17588
+ kinds: array(MediaFileKindEnum).optional()
17589
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
17061
17590
  deviceId: number(),
17062
17591
  timestamp: number(),
17063
17592
  frameWidth: number(),
@@ -17078,76 +17607,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
17078
17607
  eventId: string(),
17079
17608
  timestamp: number()
17080
17609
  });
17081
- /**
17082
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
17083
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
17084
- * caps into per-camera event-kind descriptors.
17085
- *
17086
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
17087
- * is NOT duplicated here — every entry is derived from the single
17088
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
17089
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
17090
- * control cap means adding one line here (and a taxonomy entry); the anti-
17091
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
17092
- * eventful cap is missing.
17093
- */
17094
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
17095
- var LEGACY_ICON = {
17096
- motion: "motion",
17097
- audio: "audio",
17098
- person: "person",
17099
- vehicle: "vehicle",
17100
- animal: "animal",
17101
- package: "package",
17102
- door: "door",
17103
- pir: "pir",
17104
- smoke: "smoke",
17105
- water: "water",
17106
- button: "button",
17107
- generic: "generic",
17108
- gas: "smoke",
17109
- vibration: "generic",
17110
- tamper: "generic",
17111
- presence: "person",
17112
- lock: "generic",
17113
- siren: "generic",
17114
- switch: "generic",
17115
- doorbell: "button"
17116
- };
17117
- function legacyIcon(iconId) {
17118
- return LEGACY_ICON[iconId] ?? "generic";
17119
- }
17120
- /**
17121
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
17122
- * The anti-drift guard cross-checks this against the eventful caps declared
17123
- * in `packages/types/src/capabilities/*.cap.ts`.
17124
- */
17125
- var CAP_TO_KIND = {
17126
- contact: "contact",
17127
- motion: "motion-sensor",
17128
- smoke: "smoke",
17129
- flood: "flood",
17130
- gas: "gas",
17131
- "carbon-monoxide": "carbon-monoxide",
17132
- vibration: "vibration",
17133
- tamper: "tamper",
17134
- presence: "presence",
17135
- "enum-sensor": "enum-sensor",
17136
- "event-emitter": "device-event",
17137
- "lock-control": "lock",
17138
- switch: "switch",
17139
- button: "button",
17140
- doorbell: "doorbell"
17141
- };
17142
- function buildDescriptor(capName, kind) {
17143
- const t = EVENT_TAXONOMY[kind];
17144
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
17145
- return {
17146
- ...t,
17147
- icon: legacyIcon(t.iconId)
17148
- };
17149
- }
17150
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
17151
17610
  var CameraPipelineConfigSchema = object({
17152
17611
  engine: PipelineEngineChoiceSchema.optional(),
17153
17612
  steps: array(PipelineStepInputSchema).readonly(),
@@ -17633,6 +18092,76 @@ method(object({
17633
18092
  auth: "admin"
17634
18093
  });
17635
18094
  /**
18095
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
18096
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
18097
+ * caps into per-camera event-kind descriptors.
18098
+ *
18099
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
18100
+ * is NOT duplicated here — every entry is derived from the single
18101
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
18102
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
18103
+ * control cap means adding one line here (and a taxonomy entry); the anti-
18104
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
18105
+ * eventful cap is missing.
18106
+ */
18107
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
18108
+ var LEGACY_ICON = {
18109
+ motion: "motion",
18110
+ audio: "audio",
18111
+ person: "person",
18112
+ vehicle: "vehicle",
18113
+ animal: "animal",
18114
+ package: "package",
18115
+ door: "door",
18116
+ pir: "pir",
18117
+ smoke: "smoke",
18118
+ water: "water",
18119
+ button: "button",
18120
+ generic: "generic",
18121
+ gas: "smoke",
18122
+ vibration: "generic",
18123
+ tamper: "generic",
18124
+ presence: "person",
18125
+ lock: "generic",
18126
+ siren: "generic",
18127
+ switch: "generic",
18128
+ doorbell: "button"
18129
+ };
18130
+ function legacyIcon(iconId) {
18131
+ return LEGACY_ICON[iconId] ?? "generic";
18132
+ }
18133
+ /**
18134
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
18135
+ * The anti-drift guard cross-checks this against the eventful caps declared
18136
+ * in `packages/types/src/capabilities/*.cap.ts`.
18137
+ */
18138
+ var CAP_TO_KIND = {
18139
+ contact: "contact",
18140
+ motion: "motion-sensor",
18141
+ smoke: "smoke",
18142
+ flood: "flood",
18143
+ gas: "gas",
18144
+ "carbon-monoxide": "carbon-monoxide",
18145
+ vibration: "vibration",
18146
+ tamper: "tamper",
18147
+ presence: "presence",
18148
+ "enum-sensor": "enum-sensor",
18149
+ "event-emitter": "device-event",
18150
+ "lock-control": "lock",
18151
+ switch: "switch",
18152
+ button: "button",
18153
+ doorbell: "doorbell"
18154
+ };
18155
+ function buildDescriptor(capName, kind) {
18156
+ const t = EVENT_TAXONOMY[kind];
18157
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
18158
+ return {
18159
+ ...t,
18160
+ icon: legacyIcon(t.iconId)
18161
+ };
18162
+ }
18163
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
18164
+ /**
17636
18165
  * server-management — per-NODE singleton capability for a node's ROOT
17637
18166
  * package lifecycle (runtime-updatable node packages).
17638
18167
  *
@@ -19087,7 +19616,28 @@ var FaceInfoSchema = object({
19087
19616
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
19088
19617
  * track produced no key frame (e.g. native/onboard source) — the UI falls
19089
19618
  * back to the inline `base64` face crop. */
19090
- keyFrameMediaKey: string().optional()
19619
+ keyFrameMediaKey: string().optional(),
19620
+ /** Winning identity-match cosine (0..1) for this face's track, when an
19621
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
19622
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
19623
+ * faces that were never auto-recognized. */
19624
+ bestMatchScore: number().optional(),
19625
+ /** Native-scale face short side (px) at recognition time, when the runner
19626
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
19627
+ * legacy rows / runners that reported no native measure. */
19628
+ nativeFaceShortSidePx: number().optional(),
19629
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
19630
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
19631
+ * but blocked only by the recognition size floor). Mutually exclusive with
19632
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
19633
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
19634
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
19635
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
19636
+ suggestedIdentityId: string().optional(),
19637
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
19638
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
19639
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
19640
+ suggestedMatchScore: number().optional()
19091
19641
  });
19092
19642
  var FaceFilterEnum = _enum([
19093
19643
  "unassigned",
@@ -21130,36 +21680,6 @@ Object.freeze({
21130
21680
  addonId: null,
21131
21681
  access: "view"
21132
21682
  },
21133
- "advancedNotifier.deleteRule": {
21134
- capName: "advanced-notifier",
21135
- capScope: "system",
21136
- addonId: null,
21137
- access: "delete"
21138
- },
21139
- "advancedNotifier.getHistory": {
21140
- capName: "advanced-notifier",
21141
- capScope: "system",
21142
- addonId: null,
21143
- access: "view"
21144
- },
21145
- "advancedNotifier.getRules": {
21146
- capName: "advanced-notifier",
21147
- capScope: "system",
21148
- addonId: null,
21149
- access: "view"
21150
- },
21151
- "advancedNotifier.testRule": {
21152
- capName: "advanced-notifier",
21153
- capScope: "system",
21154
- addonId: null,
21155
- access: "create"
21156
- },
21157
- "advancedNotifier.upsertRule": {
21158
- capName: "advanced-notifier",
21159
- capScope: "system",
21160
- addonId: null,
21161
- access: "create"
21162
- },
21163
21683
  "alarmPanel.arm": {
21164
21684
  capName: "alarm-panel",
21165
21685
  capScope: "device",
@@ -23464,6 +23984,60 @@ Object.freeze({
23464
23984
  addonId: null,
23465
23985
  access: "create"
23466
23986
  },
23987
+ "notificationRules.createRule": {
23988
+ capName: "notification-rules",
23989
+ capScope: "system",
23990
+ addonId: null,
23991
+ access: "create"
23992
+ },
23993
+ "notificationRules.deleteRule": {
23994
+ capName: "notification-rules",
23995
+ capScope: "system",
23996
+ addonId: null,
23997
+ access: "delete"
23998
+ },
23999
+ "notificationRules.getConditionCatalog": {
24000
+ capName: "notification-rules",
24001
+ capScope: "system",
24002
+ addonId: null,
24003
+ access: "view"
24004
+ },
24005
+ "notificationRules.getHistory": {
24006
+ capName: "notification-rules",
24007
+ capScope: "system",
24008
+ addonId: null,
24009
+ access: "view"
24010
+ },
24011
+ "notificationRules.getRule": {
24012
+ capName: "notification-rules",
24013
+ capScope: "system",
24014
+ addonId: null,
24015
+ access: "view"
24016
+ },
24017
+ "notificationRules.listRules": {
24018
+ capName: "notification-rules",
24019
+ capScope: "system",
24020
+ addonId: null,
24021
+ access: "view"
24022
+ },
24023
+ "notificationRules.setRuleEnabled": {
24024
+ capName: "notification-rules",
24025
+ capScope: "system",
24026
+ addonId: null,
24027
+ access: "create"
24028
+ },
24029
+ "notificationRules.testRule": {
24030
+ capName: "notification-rules",
24031
+ capScope: "system",
24032
+ addonId: null,
24033
+ access: "create"
24034
+ },
24035
+ "notificationRules.updateRule": {
24036
+ capName: "notification-rules",
24037
+ capScope: "system",
24038
+ addonId: null,
24039
+ access: "create"
24040
+ },
23467
24041
  "notifier.cancel": {
23468
24042
  capName: "notifier",
23469
24043
  capScope: "device",
@@ -25814,6 +26388,152 @@ function createIconRouteProvider() {
25814
26388
  return buildAddonRouteProvider(NOTIFIERS_ROUTE_ID, Object.keys(NOTIFIER_ICONS).map(iconRoute));
25815
26389
  }
25816
26390
  //#endregion
26391
+ //#region src/nc-target-actions.ts
26392
+ /**
26393
+ * nc-target-actions — the `notifiers` target-bridge action catalog.
26394
+ *
26395
+ * The Notification Center viewer NEVER adds a cap method: every target
26396
+ * read/write rides the generic `addons.custom` bridge (`{ addonId, action,
26397
+ * input }`) with a per-action `nc.*` name, and THIS module enforces the
26398
+ * per-action auth + ownership server-side (spec C1/C2). The addon id is
26399
+ * `'notifiers'`.
26400
+ *
26401
+ * Ownership model (spec §2 / §5 — server-derived, never client-trusted):
26402
+ * - A PERSONAL target carries its owner INSIDE the open `config.ownerUserId`
26403
+ * blob (train-free, additive — no `notification-output` schema change). This
26404
+ * matches the A6 rule-bridge's target-ownership check verbatim
26405
+ * (`target.config['ownerUserId']`).
26406
+ * - `ownerUserId` absent = a legacy admin/global target (owned by no viewer
26407
+ * user); the viewer never sees or mutates those through this bridge.
26408
+ * - `nc.listMyTargets` returns ONLY the caller's own targets.
26409
+ * - `nc.upsertMyTarget` STAMPS `config.ownerUserId` from the caller (stripping
26410
+ * any client-supplied value) and, on edit, requires the existing row to be
26411
+ * caller-owned. A client-suggested id that collides with a FOREIGN target is
26412
+ * minted fresh so a viewer can never edit or clobber another user's row.
26413
+ * - `nc.deleteMyTarget` / `nc.setMyTargetEnabled` / `nc.testMyTarget` operate
26414
+ * ONLY on caller-owned targets.
26415
+ *
26416
+ * FAIL-CLOSED: an absent forwarded caller (UDS version-skew can still deliver
26417
+ * `undefined`) is rejected before any ownership decision — never treated as
26418
+ * admin/global.
26419
+ *
26420
+ * Secret redaction (on read) + secret merge (on write) is the underlying
26421
+ * `notification-output` provider's concern (`provider.ts` / `secrets.ts`): this
26422
+ * bridge wraps that provider, so `nc.listMyTargets` returns already-redacted
26423
+ * rows and `nc.upsertMyTarget` inherits the stored-secret merge (the viewer's
26424
+ * blank-seed round-trip). `config.ownerUserId` is NOT a password field, so it
26425
+ * survives redaction and remains the ownership key on read.
26426
+ */
26427
+ /**
26428
+ * The action catalog — the tRPC contract Group B (the viewer client) consumes
26429
+ * against `addonId: 'notifiers'`. Every entry that depends on the caller
26430
+ * identity is declared `caller: 'required'` so the dispatcher forwards the
26431
+ * server-derived `{ userId, isAdmin }` as the handler's second argument.
26432
+ */
26433
+ var ncTargetActions = defineCustomActions({
26434
+ "nc.listMyTargets": customAction(object({}), object({ targets: array(TargetSchema) }), { caller: "required" }),
26435
+ "nc.listTargetKinds": customAction(object({}), object({ kinds: array(TargetKindSchema) })),
26436
+ "nc.upsertMyTarget": customAction(object({ target: TargetSchema }), object({ target: TargetSchema }), {
26437
+ kind: "mutation",
26438
+ caller: "required"
26439
+ }),
26440
+ "nc.deleteMyTarget": customAction(object({ targetId: string() }), object({ success: literal(true) }), {
26441
+ kind: "mutation",
26442
+ caller: "required"
26443
+ }),
26444
+ "nc.setMyTargetEnabled": customAction(object({
26445
+ targetId: string(),
26446
+ enabled: boolean()
26447
+ }), object({ success: literal(true) }), {
26448
+ kind: "mutation",
26449
+ caller: "required"
26450
+ }),
26451
+ "nc.testMyTarget": customAction(object({ targetId: string() }), object({
26452
+ success: boolean(),
26453
+ error: string().optional()
26454
+ }), {
26455
+ kind: "mutation",
26456
+ caller: "required"
26457
+ })
26458
+ });
26459
+ /** The open-blob ownership key — matches the A6 rule-bridge check verbatim. */
26460
+ var OWNER_KEY = "ownerUserId";
26461
+ var ownerOf = (target) => target.config[OWNER_KEY];
26462
+ /** Fail-closed caller resolution — an absent forwarded caller is NEVER admin. */
26463
+ function requireCaller(caller) {
26464
+ if (!caller || typeof caller.userId !== "string" || caller.userId.length === 0) throw new Error("forbidden: authenticated caller required");
26465
+ return caller;
26466
+ }
26467
+ /** Mint a fresh, collision-resistant target id (kind-prefixed for readability). */
26468
+ function mintTargetId(kind) {
26469
+ const rand = Math.random().toString(36).slice(2, 10);
26470
+ return `${kind}-${Date.now()}-${rand}`;
26471
+ }
26472
+ function makeNcTargetHandlers(deps) {
26473
+ /** A caller-owned target — must exist AND carry the caller's ownerUserId. */
26474
+ const assertOwns = async (targetId, userId) => {
26475
+ const target = (await deps.provider.listTargets({})).find((t) => t.id === targetId);
26476
+ if (!target || ownerOf(target) !== userId) throw new Error(`forbidden: target not owned: ${targetId}`);
26477
+ return target;
26478
+ };
26479
+ return {
26480
+ "nc.listMyTargets": async (_input, caller) => {
26481
+ const c = requireCaller(caller);
26482
+ return { targets: (await deps.provider.listTargets({})).filter((t) => ownerOf(t) === c.userId) };
26483
+ },
26484
+ "nc.listTargetKinds": async () => ({ kinds: await deps.provider.listTargetKinds({}) }),
26485
+ "nc.upsertMyTarget": async (input, caller) => {
26486
+ const c = requireCaller(caller);
26487
+ const all = await deps.provider.listTargets({});
26488
+ const suggestedId = input.target.id;
26489
+ const existing = suggestedId.length > 0 ? all.find((t) => t.id === suggestedId) : void 0;
26490
+ const id = existing !== void 0 ? ownerOf(existing) === c.userId ? suggestedId : mintTargetId(input.target.kind) : suggestedId.length > 0 ? suggestedId : mintTargetId(input.target.kind);
26491
+ const stamped = {
26492
+ ...input.target,
26493
+ id,
26494
+ config: {
26495
+ ...input.target.config,
26496
+ [OWNER_KEY]: c.userId
26497
+ }
26498
+ };
26499
+ const saved = await deps.provider.upsertTarget({ target: stamped });
26500
+ deps.logger.info("nc target upserted", { meta: {
26501
+ targetId: saved.id,
26502
+ owner: c.userId
26503
+ } });
26504
+ return { target: saved };
26505
+ },
26506
+ "nc.deleteMyTarget": async (input, caller) => {
26507
+ const c = requireCaller(caller);
26508
+ await assertOwns(input.targetId, c.userId);
26509
+ await deps.provider.deleteTarget({ targetId: input.targetId });
26510
+ deps.logger.info("nc target deleted", { meta: {
26511
+ targetId: input.targetId,
26512
+ owner: c.userId
26513
+ } });
26514
+ return { success: true };
26515
+ },
26516
+ "nc.setMyTargetEnabled": async (input, caller) => {
26517
+ const c = requireCaller(caller);
26518
+ await assertOwns(input.targetId, c.userId);
26519
+ await deps.provider.setTargetEnabled({
26520
+ targetId: input.targetId,
26521
+ enabled: input.enabled
26522
+ });
26523
+ return { success: true };
26524
+ },
26525
+ "nc.testMyTarget": async (input, caller) => {
26526
+ const c = requireCaller(caller);
26527
+ await assertOwns(input.targetId, c.userId);
26528
+ const res = await deps.provider.testTarget({ targetId: input.targetId });
26529
+ return {
26530
+ success: res.success,
26531
+ ...res.error !== void 0 ? { error: res.error } : {}
26532
+ };
26533
+ }
26534
+ };
26535
+ }
26536
+ //#endregion
25817
26537
  //#region src/adapters/discord.ts
25818
26538
  /** Discord message `content` hard limit. */
25819
26539
  var CONTENT_MAX_LEN = 2e3;
@@ -28538,14 +29258,22 @@ var NotifiersAddon = class extends BaseAddon {
28538
29258
  iconUrlFor
28539
29259
  });
28540
29260
  const iconRouteProvider = createIconRouteProvider();
29261
+ const ncHandlers = makeNcTargetHandlers({
29262
+ provider,
29263
+ logger: this.ctx.logger.child("nc-target-actions")
29264
+ });
28541
29265
  this.ctx.logger.info("NotifiersAddon initialized", { meta: { adapterCount: ADAPTERS.length } });
28542
- return [{
28543
- capability: notificationOutputCapability,
28544
- provider
28545
- }, {
28546
- capability: addonRoutesCapability,
28547
- provider: iconRouteProvider
28548
- }];
29266
+ return {
29267
+ providers: [{
29268
+ capability: notificationOutputCapability,
29269
+ provider
29270
+ }, {
29271
+ capability: addonRoutesCapability,
29272
+ provider: iconRouteProvider
29273
+ }],
29274
+ customActions: ncTargetActions,
29275
+ actionHandlers: ncHandlers
29276
+ };
28549
29277
  }
28550
29278
  async onShutdown() {
28551
29279
  this.ctx.logger.info("NotifiersAddon shut down");
@@ -28565,7 +29293,9 @@ exports.createMemorySettingsStorePort = createMemorySettingsStorePort;
28565
29293
  exports.createNotificationOutputProvider = createNotificationOutputProvider;
28566
29294
  exports.fetchAttachmentBytes = fetchAttachmentBytes;
28567
29295
  exports.fetchWithTimeout = fetchWithTimeout;
29296
+ exports.makeNcTargetHandlers = makeNcTargetHandlers;
28568
29297
  exports.mergeSecrets = mergeSecrets;
29298
+ exports.ncTargetActions = ncTargetActions;
28569
29299
  exports.passwordFieldKeys = passwordFieldKeys;
28570
29300
  exports.redactForRead = redactForRead;
28571
29301
  exports.sendHttpPlan = sendHttpPlan;