@camstack/addon-provider-amcrest 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1411 -859
  2. package/dist/addon.mjs +1411 -859
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -4,7 +4,7 @@ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).expor
4
4
  //#endregion
5
5
  let node_crypto = require("node:crypto");
6
6
  let node_os = require("node:os");
7
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
7
+ //#region ../types/dist/event-category-BLcNejAE.mjs
8
8
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
9
9
  EventCategory["SystemBoot"] = "system.boot";
10
10
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -154,9 +154,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
154
154
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
155
155
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
156
156
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
157
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
158
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
159
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
160
157
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
161
158
  * progress bar the client reconciles via `recordingExport.getExport`. */
162
159
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6821,7 +6818,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6821
6818
  patch: record(string(), unknown())
6822
6819
  }), object({ success: literal(true) });
6823
6820
  object({ deviceId: number() }), unknown().nullable();
6824
- /** Shorthand to define a method schema */
6825
6821
  function method(input, output, options) {
6826
6822
  return {
6827
6823
  input,
@@ -6829,6 +6825,7 @@ function method(input, output, options) {
6829
6825
  kind: options?.kind ?? "query",
6830
6826
  auth: options?.auth ?? "protected",
6831
6827
  ...options?.access !== void 0 ? { access: options.access } : {},
6828
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6832
6829
  timeoutMs: options?.timeoutMs
6833
6830
  };
6834
6831
  }
@@ -8186,6 +8183,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8186
8183
  /** The complete taxonomy dictionary, keyed by kind. */
8187
8184
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8188
8185
  /**
8186
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8187
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8188
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8189
+ * taxonomy surface (timeline, filters, event page).
8190
+ *
8191
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8192
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8193
+ * for the `classes` / `classesExclude` conditions.
8194
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8195
+ * the same class picker, grouped under an Audio header.
8196
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8197
+ * lock / …) for the `sensorKinds` device-event condition.
8198
+ *
8199
+ * Each entry carries `parentKind` so the client can group video subs under
8200
+ * their macro and sensor/control kinds under their category. This surface is
8201
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8202
+ * method, no codegen — so it ships train-free with an addon deploy.
8203
+ */
8204
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8205
+ var NcTaxonomyEntrySchema = object({
8206
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8207
+ kind: string(),
8208
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8209
+ label: string(),
8210
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8211
+ parentKind: string().nullable()
8212
+ });
8213
+ object({
8214
+ videoClasses: array(NcTaxonomyEntrySchema),
8215
+ audioKinds: array(NcTaxonomyEntrySchema),
8216
+ labels: array(NcTaxonomyEntrySchema)
8217
+ });
8218
+ function toEntry(kind, label, parentKind) {
8219
+ return {
8220
+ kind,
8221
+ label,
8222
+ parentKind
8223
+ };
8224
+ }
8225
+ /**
8226
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8227
+ * (macros before their subs), which the client relies on for stable grouping.
8228
+ */
8229
+ function buildNcTaxonomy() {
8230
+ const all = Object.values(EVENT_TAXONOMY);
8231
+ return {
8232
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8233
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8234
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8235
+ };
8236
+ }
8237
+ Object.freeze(buildNcTaxonomy());
8238
+ /**
8189
8239
  * Error types for the safe expression engine. Two distinct classes so callers
8190
8240
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8191
8241
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -12261,6 +12311,22 @@ var CameraMetricsSchema = object({
12261
12311
  ])
12262
12312
  });
12263
12313
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
12314
+ /**
12315
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
12316
+ * within the frame, so the executor can re-cut a leaf child ROI at native
12317
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
12318
+ */
12319
+ var NativeCropRefSchema = object({
12320
+ /** Handle keying the retained native surface (node-pinned to its owner). */
12321
+ handle: FrameHandleSchema,
12322
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
12323
+ cropFrameSpace: object({
12324
+ x: number(),
12325
+ y: number(),
12326
+ w: number(),
12327
+ h: number()
12328
+ })
12329
+ });
12264
12330
  var ModelFormatSchema$1 = _enum([
12265
12331
  "onnx",
12266
12332
  "coreml",
@@ -12536,7 +12602,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
12536
12602
  * Omitted ⇒ the runner's default device (current single-engine
12537
12603
  * behaviour). Selects WHICH device pool of the node runs the call.
12538
12604
  */
12539
- deviceKey: string().optional()
12605
+ deviceKey: string().optional(),
12606
+ /**
12607
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
12608
+ * when the parent crop was resolved from the frame's retained NATIVE
12609
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
12610
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
12611
+ * resolution from that surface — the SAME quality path faces already
12612
+ * had — instead of the downscaled parent tile. `handle` keys the native
12613
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
12614
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
12615
+ * the executor's crop-normalized child ROI back into frame-normalized
12616
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
12617
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
12618
+ * (today's behaviour on the fallback path).
12619
+ */
12620
+ nativeCropRef: NativeCropRefSchema.optional()
12540
12621
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
12541
12622
  engine: PipelineEngineChoiceSchema.optional(),
12542
12623
  steps: array(PipelineStepInputSchema).min(1),
@@ -12785,7 +12866,11 @@ var DetailResultSchema = object({
12785
12866
  bbox: NativeCropBboxSchema.optional(),
12786
12867
  embedding: string().optional(),
12787
12868
  label: string().optional(),
12788
- alignedCropJpeg: string().optional()
12869
+ alignedCropJpeg: string().optional(),
12870
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
12871
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
12872
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
12873
+ nativeFaceShortSidePx: number().optional()
12789
12874
  });
12790
12875
  /**
12791
12876
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -12799,6 +12884,12 @@ var motionCooldownMsField = {
12799
12884
  default: 3e4,
12800
12885
  step: 500
12801
12886
  };
12887
+ var maxSessionHoldMsField = {
12888
+ min: 0,
12889
+ max: 6e5,
12890
+ default: 12e4,
12891
+ step: 5e3
12892
+ };
12802
12893
  var motionFpsField = {
12803
12894
  min: 1,
12804
12895
  max: 30,
@@ -12946,6 +13037,19 @@ var RunnerCameraConfigSchema = object({
12946
13037
  "on-motion"
12947
13038
  ]).default("always-on"),
12948
13039
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
13040
+ /**
13041
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
13042
+ * detection session is active and ≥1 confirmed non-stationary track is
13043
+ * still live, the orchestrator keeps the session open past
13044
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
13045
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
13046
+ * ms since the session opened, after which it closes regardless. `0`
13047
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
13048
+ * runner itself — carried here so it shares the per-camera device-settings
13049
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
13050
+ * resolved `CameraDetectionConfig`.
13051
+ */
13052
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
12949
13053
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
12950
13054
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
12951
13055
  motionStreamId: string(),
@@ -13035,7 +13139,7 @@ var RunnerCameraConfigSchema = object({
13035
13139
  */
13036
13140
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
13037
13141
  });
13038
- 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;
13142
+ 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;
13039
13143
  /**
13040
13144
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
13041
13145
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -16562,94 +16666,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
16562
16666
  bundleUrl: string()
16563
16667
  });
16564
16668
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
16565
- var NotificationRuleConditionsSchema = object({
16566
- deviceIds: array(number()).readonly().optional(),
16567
- classNames: array(string()).readonly().optional(),
16568
- zoneIds: array(string()).readonly().optional(),
16569
- minConfidence: number().optional(),
16570
- source: _enum([
16571
- "pipeline",
16572
- "onboard",
16573
- "any"
16574
- ]).optional(),
16575
- schedule: object({
16576
- days: array(number()).readonly(),
16577
- startHour: number(),
16578
- endHour: number()
16579
- }).optional(),
16580
- cooldownSeconds: number().optional(),
16581
- minDwellSeconds: number().optional(),
16582
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
16583
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
16584
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
16585
- eventTypeTokens: array(string()).readonly().optional(),
16586
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
16587
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
16588
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
16589
- clipDescription: object({
16590
- text: string().min(1),
16591
- minSimilarity: number().min(0).max(1)
16592
- }).optional(),
16593
- /** Match events whose recognized-entity label (face identity name or plate
16594
- * vehicle name, propagated onto `event.data.label`) is one of these values.
16595
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
16596
- * vehicle/person> is seen". */
16597
- labels: array(string()).readonly().optional()
16598
- });
16599
- var NotificationRuleTemplateSchema = object({
16600
- title: string(),
16601
- body: string(),
16602
- imageMode: _enum([
16603
- "crop",
16604
- "annotated",
16605
- "full",
16606
- "none"
16607
- ])
16608
- });
16609
- var NotificationRuleSchema = object({
16610
- id: string(),
16611
- name: string(),
16612
- enabled: boolean(),
16613
- eventTypes: array(string()).readonly(),
16614
- conditions: NotificationRuleConditionsSchema,
16615
- outputs: array(string()).readonly(),
16616
- template: NotificationRuleTemplateSchema.optional(),
16617
- priority: _enum([
16618
- "low",
16619
- "normal",
16620
- "high",
16621
- "critical"
16622
- ])
16623
- });
16624
- var NotificationTestResultSchema = object({
16625
- ruleId: string(),
16626
- eventId: string(),
16627
- timestamp: number(),
16628
- wouldFire: boolean(),
16629
- reason: string().optional()
16630
- });
16631
- var NotificationHistoryEntrySchema = object({
16632
- id: string(),
16633
- ruleId: string(),
16634
- ruleName: string(),
16635
- eventId: string(),
16636
- timestamp: number(),
16637
- outputs: array(string()).readonly(),
16638
- success: boolean(),
16639
- error: string().optional(),
16640
- deviceId: number().optional()
16641
- });
16642
- var NotificationHistoryFilterSchema = object({
16643
- ruleId: string().optional(),
16644
- deviceId: number().optional(),
16645
- from: number().optional(),
16646
- to: number().optional(),
16647
- limit: number().optional()
16648
- });
16649
- 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({
16650
- ruleId: string(),
16651
- lookbackMinutes: number()
16652
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
16653
16669
  /**
16654
16670
  * Alerts capability — collection-based internal alert system.
16655
16671
  *
@@ -16836,89 +16852,6 @@ method(object({
16836
16852
  password: string()
16837
16853
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
16838
16854
  /**
16839
- * `login-method` — collection cap through which auth addons contribute
16840
- * their pre-auth login surfaces to the login page. This is the SINGLE,
16841
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
16842
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
16843
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
16844
- * procedure aggregates them for the unauthenticated login page.
16845
- *
16846
- * A contribution is a discriminated union on `kind`:
16847
- *
16848
- * - `redirect` — a declarative button. The login page renders a generic
16849
- * button that navigates to `startUrl` (an addon-owned HTTP route).
16850
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
16851
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
16852
- * login page needs NO change.
16853
- *
16854
- * - `widget` — a Module-Federation widget the login page mounts (via
16855
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
16856
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
16857
- * mechanism kept for future use; no shipped addon uses it on the login
16858
- * page (the passkey ceremony below runs natively in the shell instead).
16859
- *
16860
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
16861
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
16862
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
16863
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
16864
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
16865
- * fetching any remote code pre-auth. Contribution stays unconditional —
16866
- * enrollment state is never leaked pre-auth; visibility is a shell
16867
- * decision.
16868
- *
16869
- * Every contribution carries a `stage`:
16870
- * - `primary` — shown on the first credentials screen (OIDC /
16871
- * magic-link buttons; a future usernameless passkey).
16872
- * - `second-factor` — shown AFTER the password leg, gated on the
16873
- * returned `factors` (passkey-as-2FA today).
16874
- *
16875
- * `mount: skip` — the cap is read server-side by the core auth router
16876
- * (`registry.getCollection('login-method')`), never mounted as its own
16877
- * tRPC router.
16878
- */
16879
- /** When a login method renders in the two-phase login flow. */
16880
- var LoginStageEnum = _enum(["primary", "second-factor"]);
16881
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
16882
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
16883
- object({
16884
- kind: literal("redirect"),
16885
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
16886
- id: string(),
16887
- /** Operator-facing button label. */
16888
- label: string(),
16889
- /** lucide-react icon name. */
16890
- icon: string().optional(),
16891
- /** Addon-owned HTTP route the button navigates to (GET). */
16892
- startUrl: string(),
16893
- stage: LoginStageEnum
16894
- }),
16895
- object({
16896
- kind: literal("widget"),
16897
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
16898
- id: string(),
16899
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
16900
- addonId: string(),
16901
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
16902
- bundle: string(),
16903
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
16904
- remote: WidgetRemoteSchema,
16905
- stage: LoginStageEnum
16906
- }),
16907
- object({
16908
- kind: literal("passkey"),
16909
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
16910
- id: string(),
16911
- /** Operator-facing button label. */
16912
- label: string(),
16913
- stage: LoginStageEnum,
16914
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
16915
- rpId: string(),
16916
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
16917
- origin: string().nullable()
16918
- })
16919
- ]);
16920
- method(_void(), array(LoginMethodContributionSchema).readonly());
16921
- /**
16922
16855
  * Orchestrator-side destination metadata. The orchestrator computes
16923
16856
  * `id = <addonId>:<subId>` from its provider lookup so consumers
16924
16857
  * (admin UI, restore flow) see one canonical key.
@@ -18262,242 +18195,617 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
18262
18195
  kind: "mutation",
18263
18196
  auth: "admin"
18264
18197
  });
18265
- var LogLevelSchema = _enum([
18266
- "debug",
18267
- "info",
18268
- "warn",
18269
- "error"
18198
+ /**
18199
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18200
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18201
+ * caps stay wire-compatible without a circular cap→cap import.
18202
+ *
18203
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
18204
+ * every transport tier structurally, and failed calls still write usage rows.
18205
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18206
+ */
18207
+ var LlmUsageSchema = object({
18208
+ inputTokens: number(),
18209
+ outputTokens: number()
18210
+ });
18211
+ var LlmErrorCodeSchema = _enum([
18212
+ "timeout",
18213
+ "rate-limited",
18214
+ "auth",
18215
+ "refusal",
18216
+ "bad-request",
18217
+ "unavailable",
18218
+ "no-profile",
18219
+ "budget-exceeded",
18220
+ "adapter-error"
18270
18221
  ]);
18271
- var LogEntrySchema = object({
18272
- timestamp: date(),
18273
- level: LogLevelSchema,
18274
- scope: array(string()),
18222
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18223
+ ok: literal(true),
18224
+ text: string(),
18225
+ model: string(),
18226
+ usage: LlmUsageSchema,
18227
+ truncated: boolean(),
18228
+ latencyMs: number()
18229
+ }), object({
18230
+ ok: literal(false),
18231
+ code: LlmErrorCodeSchema,
18275
18232
  message: string(),
18276
- meta: record(string(), unknown()).optional(),
18277
- tags: record(string(), string()).optional()
18278
- });
18279
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18280
- scope: array(string()).optional(),
18281
- level: LogLevelSchema.optional(),
18282
- since: date().optional(),
18283
- until: date().optional(),
18284
- limit: number().optional(),
18285
- tags: record(string(), string()).optional()
18286
- }), array(LogEntrySchema).readonly());
18287
- var CpuBreakdownSchema = object({
18288
- total: number(),
18289
- user: number(),
18290
- system: number(),
18291
- irq: number(),
18292
- nice: number(),
18293
- loadAvg: tuple([
18294
- number(),
18295
- number(),
18296
- number()
18297
- ]),
18298
- cores: number()
18233
+ retryAfterMs: number().optional()
18234
+ })]);
18235
+ /**
18236
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18237
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18238
+ * notification-output.cap.ts:27-31 precedents).
18239
+ */
18240
+ var LlmImageSchema = object({
18241
+ bytes: _instanceof(Uint8Array),
18242
+ mimeType: string()
18299
18243
  });
18300
- var MemoryInfoSchema = object({
18301
- percent: number(),
18302
- totalBytes: number(),
18303
- usedBytes: number(),
18304
- availableBytes: number(),
18305
- swapUsedBytes: number(),
18306
- swapTotalBytes: number()
18244
+ var LlmGenerateBaseInputSchema = object({
18245
+ /** Collection routing (the notification-output posture). */
18246
+ addonId: string().optional(),
18247
+ /** Explicit profile; else the resolution chain (spec §3). */
18248
+ profileId: string().optional(),
18249
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18250
+ consumer: string(),
18251
+ system: string().optional(),
18252
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
18253
+ prompt: string(),
18254
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18255
+ jsonSchema: record(string(), unknown()).optional(),
18256
+ /** Per-call override of the profile default. */
18257
+ maxTokens: number().int().positive().optional(),
18258
+ temperature: number().optional()
18307
18259
  });
18308
- var DiskIoSnapshotSchema = object({
18309
- readBytes: number(),
18310
- writeBytes: number(),
18311
- readOps: number(),
18312
- writeOps: number(),
18313
- timestampMs: number()
18314
- });
18315
- var NetworkIoSnapshotSchema = object({
18316
- rxBytes: number(),
18317
- txBytes: number(),
18318
- rxPackets: number(),
18319
- txPackets: number(),
18320
- rxErrors: number(),
18321
- txErrors: number(),
18322
- timestampMs: number()
18323
- });
18324
- var MetricsGpuInfoSchema = object({
18325
- utilization: number(),
18326
- model: string(),
18327
- memoryUsedBytes: number(),
18328
- memoryTotalBytes: number(),
18329
- temperature: number().nullable()
18330
- });
18331
- var ProcessResourceInfoSchema = object({
18332
- openFds: number(),
18333
- threadCount: number(),
18334
- activeHandles: number(),
18335
- activeRequests: number()
18336
- });
18337
- var PressureAvgsSchema = object({
18338
- avg10: number(),
18339
- avg60: number(),
18340
- avg300: number()
18341
- });
18342
- var PressureInfoSchema = object({
18343
- some: PressureAvgsSchema,
18344
- full: PressureAvgsSchema.nullable()
18345
- });
18346
- var SystemResourceSnapshotSchema = object({
18347
- cpu: CpuBreakdownSchema,
18348
- memory: MemoryInfoSchema,
18349
- gpu: MetricsGpuInfoSchema.nullable(),
18350
- network: NetworkIoSnapshotSchema,
18351
- disk: DiskIoSnapshotSchema,
18352
- pressure: object({
18353
- cpu: PressureInfoSchema.nullable(),
18354
- memory: PressureInfoSchema.nullable(),
18355
- io: PressureInfoSchema.nullable()
18260
+ /**
18261
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18262
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18263
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18264
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18265
+ * this only through the `llm` cap's methods.
18266
+ *
18267
+ * One running llama-server child per node in v1 (models are RAM-heavy).
18268
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18269
+ * watchdog — operator decision #3).
18270
+ */
18271
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
18272
+ object({
18273
+ kind: literal("catalog"),
18274
+ catalogId: string()
18356
18275
  }),
18357
- process: ProcessResourceInfoSchema,
18358
- cpuTemperature: number().nullable(),
18359
- timestampMs: number()
18360
- });
18361
- var DiskSpaceInfoSchema = object({
18362
- path: string(),
18363
- totalBytes: number(),
18364
- usedBytes: number(),
18365
- availableBytes: number(),
18366
- percent: number()
18367
- });
18368
- var PidResourceStatsSchema = object({
18369
- pid: number(),
18370
- cpu: number(),
18371
- memory: number(),
18372
- /**
18373
- * Private (anonymous) resident bytes — the per-process V8 heap + native
18374
- * allocations NOT shared with other processes (Linux RssAnon). This is the
18375
- * "real" per-runner cost; summing it across runners is meaningful, unlike
18376
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
18377
- * Undefined where /proc is unavailable (e.g. macOS).
18378
- */
18379
- privateBytes: number().optional(),
18380
- /**
18381
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18382
- * code shared copy-on-write across runners. Undefined on macOS.
18383
- */
18384
- sharedBytes: number().optional()
18276
+ object({
18277
+ kind: literal("url"),
18278
+ url: string(),
18279
+ sha256: string().optional()
18280
+ }),
18281
+ object({
18282
+ kind: literal("path"),
18283
+ path: string()
18284
+ })
18285
+ ]);
18286
+ var ManagedRuntimeConfigSchema = object({
18287
+ /** WHERE the runtime lives — hub or any agent. */
18288
+ nodeId: string(),
18289
+ /** Closed for v1; 'ollama' is a v2 candidate. */
18290
+ engine: _enum(["llama-cpp"]),
18291
+ model: ManagedModelRefSchema,
18292
+ contextSize: number().int().default(4096),
18293
+ /** 0 = CPU-only. */
18294
+ gpuLayers: number().int().default(0),
18295
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18296
+ threads: number().int().optional(),
18297
+ /** Concurrent slots. */
18298
+ parallel: number().int().default(1),
18299
+ /** Else lazy: first generate boots it. */
18300
+ autoStart: boolean().default(false),
18301
+ /** 0 = never; frees RAM after quiet periods. */
18302
+ idleStopMinutes: number().int().default(30)
18385
18303
  });
18386
- var AddonInstanceSchema = object({
18387
- addonId: string(),
18304
+ var LlmRuntimeStatusSchema = object({
18305
+ /** Status is ALWAYS node-qualified. */
18388
18306
  nodeId: string(),
18389
- role: _enum(["hub", "worker"]),
18390
- pid: number(),
18391
18307
  state: _enum([
18392
- "starting",
18393
- "running",
18394
- "stopping",
18395
18308
  "stopped",
18396
- "crashed"
18397
- ]),
18398
- uptimeSec: number()
18399
- });
18400
- var NodeProcessSchema = object({
18401
- pid: number(),
18402
- ppid: number(),
18403
- pgid: number(),
18404
- classification: _enum([
18405
- "root",
18406
- "managed",
18407
- "system",
18408
- "ghost"
18309
+ "downloading",
18310
+ "starting",
18311
+ "ready",
18312
+ "crashed",
18313
+ "failed"
18409
18314
  ]),
18410
- /** `$process` addon binding when `managed`, else null. */
18411
- addonId: string().nullable(),
18412
- /** Kernel-reported nodeId when the process is a known agent/worker. */
18413
- nodeId: string().nullable(),
18414
- /** Truncated command line. */
18415
- command: string(),
18416
- cpuPercent: number(),
18417
- memoryRssBytes: number(),
18418
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18419
- uptimeSec: number(),
18420
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18421
- orphaned: boolean()
18422
- });
18423
- var KillProcessInputSchema = object({
18424
- pid: number(),
18425
- /** Force = SIGKILL. Default is SIGTERM. */
18426
- force: boolean().optional()
18427
- });
18428
- var KillProcessResultSchema = object({
18429
- success: boolean(),
18430
- reason: string().optional(),
18431
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18432
- });
18433
- var DumpHeapSnapshotInputSchema = object({
18434
- /** The addon whose runner should dump a heap snapshot. */
18435
- addonId: string() });
18436
- var DumpHeapSnapshotResultSchema = object({
18437
- success: boolean(),
18438
- /** Path of the written .heapsnapshot inside the runner's container/host. */
18439
- path: string().optional(),
18440
- /** Process pid that was signalled. */
18441
18315
  pid: number().optional(),
18442
- reason: string().optional()
18316
+ port: number().optional(),
18317
+ modelPath: string().optional(),
18318
+ modelId: string().optional(),
18319
+ downloadProgress: number().min(0).max(1).optional(),
18320
+ lastError: string().optional(),
18321
+ crashesInWindow: number(),
18322
+ /** Child RSS (sampled best-effort). */
18323
+ memoryBytes: number().optional(),
18324
+ vramBytes: number().optional()
18443
18325
  });
18444
- var SystemMetricsSchema = object({
18445
- cpuPercent: number(),
18446
- memoryPercent: number(),
18447
- memoryUsedMB: number(),
18448
- memoryTotalMB: number(),
18449
- diskPercent: number().optional(),
18450
- temperature: number().optional(),
18451
- gpuPercent: number().optional(),
18452
- gpuMemoryPercent: number().optional()
18326
+ var LlmNodeModelSchema = object({
18327
+ file: string(),
18328
+ sizeBytes: number(),
18329
+ catalogId: string().optional(),
18330
+ installedAt: number().optional()
18453
18331
  });
18454
- 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, {
18332
+ var LlmRuntimeDiskUsageSchema = object({
18333
+ nodeId: string(),
18334
+ modelsBytes: number(),
18335
+ freeBytes: number().optional()
18336
+ });
18337
+ method(LlmGenerateBaseInputSchema.extend({
18338
+ images: array(LlmImageSchema).optional(),
18339
+ runtime: ManagedRuntimeConfigSchema,
18340
+ /** The managed profile's timeout, threaded by the hub provider. */
18341
+ timeoutMs: number().int().positive().optional()
18342
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18455
18343
  kind: "mutation",
18456
18344
  auth: "admin"
18457
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
18345
+ }), method(object({}), _void(), {
18458
18346
  kind: "mutation",
18459
18347
  auth: "admin"
18460
- });
18461
- method(object({
18462
- sourceUrl: string(),
18463
- metadata: ModelConvertMetadataSchema,
18464
- targets: array(ConvertTargetSchema).min(1).readonly(),
18465
- calibrationRef: string().optional(),
18466
- sessionId: string().optional()
18467
- }), ConvertResultSchema, {
18348
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18468
18349
  kind: "mutation",
18469
- auth: "admin",
18470
- timeoutMs: 6e5
18471
- });
18472
- method(object({
18473
- nodeId: string(),
18474
- modelId: string(),
18475
- format: _enum(MODEL_FORMATS),
18476
- entry: ModelCatalogEntrySchema
18477
- }), object({
18478
- ok: boolean(),
18479
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
18480
- sha256: string(),
18481
- bytes: number(),
18482
- /** The target node's modelsDir the artifact landed in. */
18483
- path: string()
18484
- }), {
18350
+ auth: "admin"
18351
+ }), method(object({ file: string() }), _void(), {
18485
18352
  kind: "mutation",
18486
18353
  auth: "admin"
18487
- });
18354
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18488
18355
  /**
18489
- * `mqtt-broker` — broker-registry cap.
18490
- *
18491
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
18492
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
18493
- * and (b) the connection details a consumer addon needs to spin up
18494
- * its OWN `mqtt.js` client.
18356
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18357
+ * methods concat-fan across providers; single-row methods route to ONE
18358
+ * provider by the `addonId` in the call input (the notification-output
18359
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18360
+ * (hub-placed); the cap stays open for future providers.
18495
18361
  *
18496
- * Why: pub/sub routing over the system event-bus loses fidelity
18497
- * (callback shape, QoS guarantees, will/retain semantics) and adds
18498
- * refcount bookkeeping that addons would rather own themselves. The
18499
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
18500
- * features anyway — give it the connection config, get out of the way.
18362
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18363
+ * `apiKey` is a password field providers REDACT it on read and merge on
18364
+ * write; a stored key NEVER round-trips to a client.
18365
+ */
18366
+ var LlmProfileKindSchema = _enum([
18367
+ "openai-compatible",
18368
+ "openai",
18369
+ "anthropic",
18370
+ "google",
18371
+ "managed-local"
18372
+ ]);
18373
+ var LlmProfileSchema = object({
18374
+ id: string(),
18375
+ name: string(),
18376
+ kind: LlmProfileKindSchema,
18377
+ /** Stamped by the provider — keeps the fanned catalog routable. */
18378
+ addonId: string(),
18379
+ enabled: boolean(),
18380
+ /** Vendor model id, or the managed runtime's loaded model. */
18381
+ model: string(),
18382
+ /** Required for openai-compatible; override for cloud kinds. */
18383
+ baseUrl: string().optional(),
18384
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
18385
+ apiKey: string().optional(),
18386
+ supportsVision: boolean(),
18387
+ temperature: number().min(0).max(2).optional(),
18388
+ maxTokens: number().int().positive().optional(),
18389
+ timeoutMs: number().int().positive().default(6e4),
18390
+ extraHeaders: record(string(), string()).optional(),
18391
+ /** kind === 'managed-local' only (spec §4). */
18392
+ runtime: ManagedRuntimeConfigSchema.optional()
18393
+ });
18394
+ /** ConfigUISchema tree passed through untyped on the wire (the
18395
+ * notification-output `ConfigSchemaPassthrough` precedent at
18396
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
18397
+ var ConfigSchemaPassthrough$1 = unknown();
18398
+ var LlmProfileKindDescriptorSchema = object({
18399
+ kind: LlmProfileKindSchema,
18400
+ label: string(),
18401
+ icon: string(),
18402
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
18403
+ addonId: string(),
18404
+ configSchema: ConfigSchemaPassthrough$1
18405
+ });
18406
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
18407
+ var LlmDefaultSchema = object({
18408
+ selector: LlmDefaultSelectorSchema,
18409
+ profileId: string()
18410
+ });
18411
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
18412
+ var LlmUsageRollupSchema = object({
18413
+ day: string(),
18414
+ consumer: string(),
18415
+ profileId: string(),
18416
+ calls: number(),
18417
+ okCalls: number(),
18418
+ errorCalls: number(),
18419
+ inputTokens: number(),
18420
+ outputTokens: number(),
18421
+ avgLatencyMs: number()
18422
+ });
18423
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
18424
+ var ManagedModelCatalogEntrySchema = object({
18425
+ id: string(),
18426
+ label: string(),
18427
+ family: string(),
18428
+ purpose: _enum(["text", "vision"]),
18429
+ url: string(),
18430
+ sha256: string(),
18431
+ sizeBytes: number(),
18432
+ quantization: string(),
18433
+ /** Load-time guidance shown in the picker. */
18434
+ minRamBytes: number(),
18435
+ contextSizeDefault: number().int(),
18436
+ /** Vision models: companion projector file. */
18437
+ mmprojUrl: string().optional()
18438
+ });
18439
+ var LlmRuntimeNodeSchema = object({
18440
+ nodeId: string(),
18441
+ reachable: boolean(),
18442
+ status: LlmRuntimeStatusSchema.optional(),
18443
+ disk: LlmRuntimeDiskUsageSchema.optional(),
18444
+ error: string().optional()
18445
+ });
18446
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
18447
+ var ProfileRefInputSchema = object({
18448
+ addonId: string(),
18449
+ profileId: string()
18450
+ });
18451
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
18452
+ kind: "mutation",
18453
+ auth: "admin"
18454
+ }), method(ProfileRefInputSchema, _void(), {
18455
+ kind: "mutation",
18456
+ auth: "admin"
18457
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
18458
+ kind: "mutation",
18459
+ auth: "admin"
18460
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
18461
+ selector: LlmDefaultSelectorSchema,
18462
+ profileId: string().nullable()
18463
+ }), _void(), {
18464
+ kind: "mutation",
18465
+ auth: "admin"
18466
+ }), method(object({
18467
+ since: number().optional(),
18468
+ until: number().optional(),
18469
+ consumer: string().optional(),
18470
+ profileId: string().optional()
18471
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
18472
+ nodeId: string(),
18473
+ model: ManagedModelRefSchema
18474
+ }), _void(), {
18475
+ kind: "mutation",
18476
+ auth: "admin"
18477
+ }), method(object({
18478
+ nodeId: string(),
18479
+ file: string()
18480
+ }), _void(), {
18481
+ kind: "mutation",
18482
+ auth: "admin"
18483
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
18484
+ kind: "mutation",
18485
+ auth: "admin"
18486
+ }), method(ProfileRefInputSchema, _void(), {
18487
+ kind: "mutation",
18488
+ auth: "admin"
18489
+ });
18490
+ var LogLevelSchema = _enum([
18491
+ "debug",
18492
+ "info",
18493
+ "warn",
18494
+ "error"
18495
+ ]);
18496
+ var LogEntrySchema = object({
18497
+ timestamp: date(),
18498
+ level: LogLevelSchema,
18499
+ scope: array(string()),
18500
+ message: string(),
18501
+ meta: record(string(), unknown()).optional(),
18502
+ tags: record(string(), string()).optional()
18503
+ });
18504
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18505
+ scope: array(string()).optional(),
18506
+ level: LogLevelSchema.optional(),
18507
+ since: date().optional(),
18508
+ until: date().optional(),
18509
+ limit: number().optional(),
18510
+ tags: record(string(), string()).optional()
18511
+ }), array(LogEntrySchema).readonly());
18512
+ /**
18513
+ * `login-method` — collection cap through which auth addons contribute
18514
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
18515
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
18516
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
18517
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
18518
+ * procedure aggregates them for the unauthenticated login page.
18519
+ *
18520
+ * A contribution is a discriminated union on `kind`:
18521
+ *
18522
+ * - `redirect` — a declarative button. The login page renders a generic
18523
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
18524
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
18525
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
18526
+ * login page needs NO change.
18527
+ *
18528
+ * - `widget` — a Module-Federation widget the login page mounts (via
18529
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
18530
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
18531
+ * mechanism kept for future use; no shipped addon uses it on the login
18532
+ * page (the passkey ceremony below runs natively in the shell instead).
18533
+ *
18534
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
18535
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
18536
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
18537
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
18538
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
18539
+ * fetching any remote code pre-auth. Contribution stays unconditional —
18540
+ * enrollment state is never leaked pre-auth; visibility is a shell
18541
+ * decision.
18542
+ *
18543
+ * Every contribution carries a `stage`:
18544
+ * - `primary` — shown on the first credentials screen (OIDC /
18545
+ * magic-link buttons; a future usernameless passkey).
18546
+ * - `second-factor` — shown AFTER the password leg, gated on the
18547
+ * returned `factors` (passkey-as-2FA today).
18548
+ *
18549
+ * `mount: skip` — the cap is read server-side by the core auth router
18550
+ * (`registry.getCollection('login-method')`), never mounted as its own
18551
+ * tRPC router.
18552
+ */
18553
+ /** When a login method renders in the two-phase login flow. */
18554
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
18555
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
18556
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
18557
+ object({
18558
+ kind: literal("redirect"),
18559
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
18560
+ id: string(),
18561
+ /** Operator-facing button label. */
18562
+ label: string(),
18563
+ /** lucide-react icon name. */
18564
+ icon: string().optional(),
18565
+ /** Addon-owned HTTP route the button navigates to (GET). */
18566
+ startUrl: string(),
18567
+ stage: LoginStageEnum
18568
+ }),
18569
+ object({
18570
+ kind: literal("widget"),
18571
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
18572
+ id: string(),
18573
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
18574
+ addonId: string(),
18575
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
18576
+ bundle: string(),
18577
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
18578
+ remote: WidgetRemoteSchema,
18579
+ stage: LoginStageEnum
18580
+ }),
18581
+ object({
18582
+ kind: literal("passkey"),
18583
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
18584
+ id: string(),
18585
+ /** Operator-facing button label. */
18586
+ label: string(),
18587
+ stage: LoginStageEnum,
18588
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
18589
+ rpId: string(),
18590
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
18591
+ origin: string().nullable()
18592
+ })
18593
+ ]);
18594
+ method(_void(), array(LoginMethodContributionSchema).readonly());
18595
+ var CpuBreakdownSchema = object({
18596
+ total: number(),
18597
+ user: number(),
18598
+ system: number(),
18599
+ irq: number(),
18600
+ nice: number(),
18601
+ loadAvg: tuple([
18602
+ number(),
18603
+ number(),
18604
+ number()
18605
+ ]),
18606
+ cores: number()
18607
+ });
18608
+ var MemoryInfoSchema = object({
18609
+ percent: number(),
18610
+ totalBytes: number(),
18611
+ usedBytes: number(),
18612
+ availableBytes: number(),
18613
+ swapUsedBytes: number(),
18614
+ swapTotalBytes: number()
18615
+ });
18616
+ var DiskIoSnapshotSchema = object({
18617
+ readBytes: number(),
18618
+ writeBytes: number(),
18619
+ readOps: number(),
18620
+ writeOps: number(),
18621
+ timestampMs: number()
18622
+ });
18623
+ var NetworkIoSnapshotSchema = object({
18624
+ rxBytes: number(),
18625
+ txBytes: number(),
18626
+ rxPackets: number(),
18627
+ txPackets: number(),
18628
+ rxErrors: number(),
18629
+ txErrors: number(),
18630
+ timestampMs: number()
18631
+ });
18632
+ var MetricsGpuInfoSchema = object({
18633
+ utilization: number(),
18634
+ model: string(),
18635
+ memoryUsedBytes: number(),
18636
+ memoryTotalBytes: number(),
18637
+ temperature: number().nullable()
18638
+ });
18639
+ var ProcessResourceInfoSchema = object({
18640
+ openFds: number(),
18641
+ threadCount: number(),
18642
+ activeHandles: number(),
18643
+ activeRequests: number()
18644
+ });
18645
+ var PressureAvgsSchema = object({
18646
+ avg10: number(),
18647
+ avg60: number(),
18648
+ avg300: number()
18649
+ });
18650
+ var PressureInfoSchema = object({
18651
+ some: PressureAvgsSchema,
18652
+ full: PressureAvgsSchema.nullable()
18653
+ });
18654
+ var SystemResourceSnapshotSchema = object({
18655
+ cpu: CpuBreakdownSchema,
18656
+ memory: MemoryInfoSchema,
18657
+ gpu: MetricsGpuInfoSchema.nullable(),
18658
+ network: NetworkIoSnapshotSchema,
18659
+ disk: DiskIoSnapshotSchema,
18660
+ pressure: object({
18661
+ cpu: PressureInfoSchema.nullable(),
18662
+ memory: PressureInfoSchema.nullable(),
18663
+ io: PressureInfoSchema.nullable()
18664
+ }),
18665
+ process: ProcessResourceInfoSchema,
18666
+ cpuTemperature: number().nullable(),
18667
+ timestampMs: number()
18668
+ });
18669
+ var DiskSpaceInfoSchema = object({
18670
+ path: string(),
18671
+ totalBytes: number(),
18672
+ usedBytes: number(),
18673
+ availableBytes: number(),
18674
+ percent: number()
18675
+ });
18676
+ var PidResourceStatsSchema = object({
18677
+ pid: number(),
18678
+ cpu: number(),
18679
+ memory: number(),
18680
+ /**
18681
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
18682
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
18683
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
18684
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
18685
+ * Undefined where /proc is unavailable (e.g. macOS).
18686
+ */
18687
+ privateBytes: number().optional(),
18688
+ /**
18689
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18690
+ * code shared copy-on-write across runners. Undefined on macOS.
18691
+ */
18692
+ sharedBytes: number().optional()
18693
+ });
18694
+ var AddonInstanceSchema = object({
18695
+ addonId: string(),
18696
+ nodeId: string(),
18697
+ role: _enum(["hub", "worker"]),
18698
+ pid: number(),
18699
+ state: _enum([
18700
+ "starting",
18701
+ "running",
18702
+ "stopping",
18703
+ "stopped",
18704
+ "crashed"
18705
+ ]),
18706
+ uptimeSec: number()
18707
+ });
18708
+ var NodeProcessSchema = object({
18709
+ pid: number(),
18710
+ ppid: number(),
18711
+ pgid: number(),
18712
+ classification: _enum([
18713
+ "root",
18714
+ "managed",
18715
+ "system",
18716
+ "ghost"
18717
+ ]),
18718
+ /** `$process` addon binding when `managed`, else null. */
18719
+ addonId: string().nullable(),
18720
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
18721
+ nodeId: string().nullable(),
18722
+ /** Truncated command line. */
18723
+ command: string(),
18724
+ cpuPercent: number(),
18725
+ memoryRssBytes: number(),
18726
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18727
+ uptimeSec: number(),
18728
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18729
+ orphaned: boolean()
18730
+ });
18731
+ var KillProcessInputSchema = object({
18732
+ pid: number(),
18733
+ /** Force = SIGKILL. Default is SIGTERM. */
18734
+ force: boolean().optional()
18735
+ });
18736
+ var KillProcessResultSchema = object({
18737
+ success: boolean(),
18738
+ reason: string().optional(),
18739
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18740
+ });
18741
+ var DumpHeapSnapshotInputSchema = object({
18742
+ /** The addon whose runner should dump a heap snapshot. */
18743
+ addonId: string() });
18744
+ var DumpHeapSnapshotResultSchema = object({
18745
+ success: boolean(),
18746
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
18747
+ path: string().optional(),
18748
+ /** Process pid that was signalled. */
18749
+ pid: number().optional(),
18750
+ reason: string().optional()
18751
+ });
18752
+ var SystemMetricsSchema = object({
18753
+ cpuPercent: number(),
18754
+ memoryPercent: number(),
18755
+ memoryUsedMB: number(),
18756
+ memoryTotalMB: number(),
18757
+ diskPercent: number().optional(),
18758
+ temperature: number().optional(),
18759
+ gpuPercent: number().optional(),
18760
+ gpuMemoryPercent: number().optional()
18761
+ });
18762
+ 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, {
18763
+ kind: "mutation",
18764
+ auth: "admin"
18765
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
18766
+ kind: "mutation",
18767
+ auth: "admin"
18768
+ });
18769
+ method(object({
18770
+ sourceUrl: string(),
18771
+ metadata: ModelConvertMetadataSchema,
18772
+ targets: array(ConvertTargetSchema).min(1).readonly(),
18773
+ calibrationRef: string().optional(),
18774
+ sessionId: string().optional()
18775
+ }), ConvertResultSchema, {
18776
+ kind: "mutation",
18777
+ auth: "admin",
18778
+ timeoutMs: 6e5
18779
+ });
18780
+ method(object({
18781
+ nodeId: string(),
18782
+ modelId: string(),
18783
+ format: _enum(MODEL_FORMATS),
18784
+ entry: ModelCatalogEntrySchema
18785
+ }), object({
18786
+ ok: boolean(),
18787
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
18788
+ sha256: string(),
18789
+ bytes: number(),
18790
+ /** The target node's modelsDir the artifact landed in. */
18791
+ path: string()
18792
+ }), {
18793
+ kind: "mutation",
18794
+ auth: "admin"
18795
+ });
18796
+ /**
18797
+ * `mqtt-broker` — broker-registry cap.
18798
+ *
18799
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
18800
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
18801
+ * and (b) the connection details a consumer addon needs to spin up
18802
+ * its OWN `mqtt.js` client.
18803
+ *
18804
+ * Why: pub/sub routing over the system event-bus loses fidelity
18805
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
18806
+ * refcount bookkeeping that addons would rather own themselves. The
18807
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
18808
+ * features anyway — give it the connection config, get out of the way.
18501
18809
  *
18502
18810
  * Consumer flow:
18503
18811
  * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
@@ -18715,398 +19023,594 @@ var NotificationSchema = object({
18715
19023
  });
18716
19024
  /** One declared native severity/priority level for a kind. */
18717
19025
  var TargetKindLevelSchema = object({
18718
- id: string(),
18719
- label: string(),
18720
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
18721
- ordinal: number().int().min(1).max(5).nullable(),
18722
- flags: object({
18723
- critical: boolean().optional(),
18724
- silent: boolean().optional(),
18725
- noPush: boolean().optional()
18726
- }).optional(),
18727
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
18728
- requires: array(string()).optional(),
18729
- description: string().optional()
18730
- });
18731
- /** The full capability block consulted before dispatch. */
18732
- var TargetKindCapsSchema = object({
18733
- attachments: object({
18734
- mediaTypes: array(AttachmentMediaTypeSchema),
18735
- mode: _enum([
18736
- "url",
18737
- "bytes",
18738
- "both"
18739
- ]),
18740
- max: number().int().nonnegative(),
18741
- maxBytes: number().int().positive().optional()
18742
- }),
18743
- /** Max action buttons (0 = none). */
18744
- actions: number().int().nonnegative(),
18745
- levels: array(TargetKindLevelSchema),
18746
- format: array(NotificationFormatSchema),
18747
- clickUrl: boolean(),
18748
- sound: boolean(),
18749
- ttl: boolean(),
18750
- bodyMaxLen: number().int().positive()
18751
- });
18752
- /**
18753
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
18754
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
18755
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
18756
- * the union is large and not meant for runtime validation here; the exported
18757
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
18758
- */
18759
- var ConfigSchemaPassthrough$1 = unknown();
18760
- var TargetKindSchema = object({
18761
- kind: string(),
18762
- label: string(),
18763
- icon: string(),
18764
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
18765
- addonId: string(),
18766
- configSchema: ConfigSchemaPassthrough$1,
18767
- supportsDiscovery: boolean(),
18768
- caps: TargetKindCapsSchema
18769
- });
18770
- /**
18771
- * A persisted target. `config` holds secrets; providers REDACT secret fields
18772
- * (return a presence marker only) when serving `listTargets` — never
18773
- * round-trip a stored secret to the UI.
18774
- */
18775
- var TargetSchema = object({
18776
- id: string(),
18777
- name: string(),
18778
- kind: string(),
18779
- addonId: string(),
18780
- enabled: boolean(),
18781
- config: record(string(), unknown())
18782
- });
18783
- /** A discovery-surfaced candidate (config is partial + non-secret). */
18784
- var DiscoveredTargetSchema = object({
18785
- kind: string(),
18786
- suggestedName: string(),
18787
- config: record(string(), unknown())
18788
- });
18789
- /** The degrade engine's report — what was resolved / dropped / degraded. */
18790
- var RenderedAsSchema = object({
18791
- level: string(),
18792
- format: NotificationFormatSchema,
18793
- attachmentsSent: number().int().nonnegative(),
18794
- actionsSent: number().int().nonnegative(),
18795
- truncated: boolean(),
18796
- dropped: array(string())
18797
- });
18798
- var SendResultSchema = object({
18799
- success: boolean(),
18800
- error: string().optional(),
18801
- renderedAs: RenderedAsSchema.optional()
18802
- });
18803
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
18804
- var TestResultSchema = SendResultSchema;
18805
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
18806
- kind: string(),
18807
- config: record(string(), unknown()).optional()
18808
- }), array(DiscoveredTargetSchema)), method(object({
18809
- targetId: string(),
18810
- notification: NotificationSchema
18811
- }), SendResultSchema, { kind: "mutation" }), method(object({
18812
- targetId: string(),
18813
- sample: NotificationSchema.optional()
18814
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
18815
- targetId: string(),
18816
- enabled: boolean()
18817
- }), _void(), { kind: "mutation" });
18818
- /**
18819
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18820
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18821
- * caps stay wire-compatible without a circular cap→cap import.
18822
- *
18823
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
18824
- * every transport tier structurally, and failed calls still write usage rows.
18825
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18826
- */
18827
- var LlmUsageSchema = object({
18828
- inputTokens: number(),
18829
- outputTokens: number()
18830
- });
18831
- var LlmErrorCodeSchema = _enum([
18832
- "timeout",
18833
- "rate-limited",
18834
- "auth",
18835
- "refusal",
18836
- "bad-request",
18837
- "unavailable",
18838
- "no-profile",
18839
- "budget-exceeded",
18840
- "adapter-error"
18841
- ]);
18842
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18843
- ok: literal(true),
18844
- text: string(),
18845
- model: string(),
18846
- usage: LlmUsageSchema,
18847
- truncated: boolean(),
18848
- latencyMs: number()
18849
- }), object({
18850
- ok: literal(false),
18851
- code: LlmErrorCodeSchema,
18852
- message: string(),
18853
- retryAfterMs: number().optional()
18854
- })]);
18855
- /**
18856
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18857
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18858
- * notification-output.cap.ts:27-31 precedents).
18859
- */
18860
- var LlmImageSchema = object({
18861
- bytes: _instanceof(Uint8Array),
18862
- mimeType: string()
18863
- });
18864
- var LlmGenerateBaseInputSchema = object({
18865
- /** Collection routing (the notification-output posture). */
18866
- addonId: string().optional(),
18867
- /** Explicit profile; else the resolution chain (spec §3). */
18868
- profileId: string().optional(),
18869
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18870
- consumer: string(),
18871
- system: string().optional(),
18872
- /** v1: single-turn. `messages[]` is a v2 additive field. */
18873
- prompt: string(),
18874
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18875
- jsonSchema: record(string(), unknown()).optional(),
18876
- /** Per-call override of the profile default. */
18877
- maxTokens: number().int().positive().optional(),
18878
- temperature: number().optional()
18879
- });
18880
- /**
18881
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18882
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18883
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18884
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18885
- * this only through the `llm` cap's methods.
18886
- *
18887
- * One running llama-server child per node in v1 (models are RAM-heavy).
18888
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18889
- * watchdog — operator decision #3).
18890
- */
18891
- var ManagedModelRefSchema = discriminatedUnion("kind", [
18892
- object({
18893
- kind: literal("catalog"),
18894
- catalogId: string()
18895
- }),
18896
- object({
18897
- kind: literal("url"),
18898
- url: string(),
18899
- sha256: string().optional()
18900
- }),
18901
- object({
18902
- kind: literal("path"),
18903
- path: string()
18904
- })
18905
- ]);
18906
- var ManagedRuntimeConfigSchema = object({
18907
- /** WHERE the runtime lives — hub or any agent. */
18908
- nodeId: string(),
18909
- /** Closed for v1; 'ollama' is a v2 candidate. */
18910
- engine: _enum(["llama-cpp"]),
18911
- model: ManagedModelRefSchema,
18912
- contextSize: number().int().default(4096),
18913
- /** 0 = CPU-only. */
18914
- gpuLayers: number().int().default(0),
18915
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18916
- threads: number().int().optional(),
18917
- /** Concurrent slots. */
18918
- parallel: number().int().default(1),
18919
- /** Else lazy: first generate boots it. */
18920
- autoStart: boolean().default(false),
18921
- /** 0 = never; frees RAM after quiet periods. */
18922
- idleStopMinutes: number().int().default(30)
18923
- });
18924
- var LlmRuntimeStatusSchema = object({
18925
- /** Status is ALWAYS node-qualified. */
18926
- nodeId: string(),
18927
- state: _enum([
18928
- "stopped",
18929
- "downloading",
18930
- "starting",
18931
- "ready",
18932
- "crashed",
18933
- "failed"
18934
- ]),
18935
- pid: number().optional(),
18936
- port: number().optional(),
18937
- modelPath: string().optional(),
18938
- modelId: string().optional(),
18939
- downloadProgress: number().min(0).max(1).optional(),
18940
- lastError: string().optional(),
18941
- crashesInWindow: number(),
18942
- /** Child RSS (sampled best-effort). */
18943
- memoryBytes: number().optional(),
18944
- vramBytes: number().optional()
19026
+ id: string(),
19027
+ label: string(),
19028
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
19029
+ ordinal: number().int().min(1).max(5).nullable(),
19030
+ flags: object({
19031
+ critical: boolean().optional(),
19032
+ silent: boolean().optional(),
19033
+ noPush: boolean().optional()
19034
+ }).optional(),
19035
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
19036
+ requires: array(string()).optional(),
19037
+ description: string().optional()
18945
19038
  });
18946
- var LlmNodeModelSchema = object({
18947
- file: string(),
18948
- sizeBytes: number(),
18949
- catalogId: string().optional(),
18950
- installedAt: number().optional()
19039
+ /** The full capability block consulted before dispatch. */
19040
+ var TargetKindCapsSchema = object({
19041
+ attachments: object({
19042
+ mediaTypes: array(AttachmentMediaTypeSchema),
19043
+ mode: _enum([
19044
+ "url",
19045
+ "bytes",
19046
+ "both"
19047
+ ]),
19048
+ max: number().int().nonnegative(),
19049
+ maxBytes: number().int().positive().optional()
19050
+ }),
19051
+ /** Max action buttons (0 = none). */
19052
+ actions: number().int().nonnegative(),
19053
+ levels: array(TargetKindLevelSchema),
19054
+ format: array(NotificationFormatSchema),
19055
+ clickUrl: boolean(),
19056
+ sound: boolean(),
19057
+ ttl: boolean(),
19058
+ bodyMaxLen: number().int().positive()
18951
19059
  });
18952
- var LlmRuntimeDiskUsageSchema = object({
18953
- nodeId: string(),
18954
- modelsBytes: number(),
18955
- freeBytes: number().optional()
19060
+ /**
19061
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
19062
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
19063
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
19064
+ * the union is large and not meant for runtime validation here; the exported
19065
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
19066
+ */
19067
+ var ConfigSchemaPassthrough = unknown();
19068
+ var TargetKindSchema = object({
19069
+ kind: string(),
19070
+ label: string(),
19071
+ icon: string(),
19072
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
19073
+ addonId: string(),
19074
+ configSchema: ConfigSchemaPassthrough,
19075
+ supportsDiscovery: boolean(),
19076
+ caps: TargetKindCapsSchema
18956
19077
  });
18957
- method(LlmGenerateBaseInputSchema.extend({
18958
- images: array(LlmImageSchema).optional(),
18959
- runtime: ManagedRuntimeConfigSchema,
18960
- /** The managed profile's timeout, threaded by the hub provider. */
18961
- timeoutMs: number().int().positive().optional()
18962
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18963
- kind: "mutation",
18964
- auth: "admin"
18965
- }), method(object({}), _void(), {
18966
- kind: "mutation",
18967
- auth: "admin"
18968
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18969
- kind: "mutation",
18970
- auth: "admin"
18971
- }), method(object({ file: string() }), _void(), {
18972
- kind: "mutation",
18973
- auth: "admin"
18974
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18975
19078
  /**
18976
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18977
- * methods concat-fan across providers; single-row methods route to ONE
18978
- * provider by the `addonId` in the call input (the notification-output
18979
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18980
- * (hub-placed); the cap stays open for future providers.
18981
- *
18982
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18983
- * `apiKey` is a password field — providers REDACT it on read and merge on
18984
- * write; a stored key NEVER round-trips to a client.
19079
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
19080
+ * (return a presence marker only) when serving `listTargets` — never
19081
+ * round-trip a stored secret to the UI.
18985
19082
  */
18986
- var LlmProfileKindSchema = _enum([
18987
- "openai-compatible",
18988
- "openai",
18989
- "anthropic",
18990
- "google",
18991
- "managed-local"
18992
- ]);
18993
- var LlmProfileSchema = object({
19083
+ var TargetSchema = object({
18994
19084
  id: string(),
18995
19085
  name: string(),
18996
- kind: LlmProfileKindSchema,
18997
- /** Stamped by the provider — keeps the fanned catalog routable. */
19086
+ kind: string(),
18998
19087
  addonId: string(),
18999
19088
  enabled: boolean(),
19000
- /** Vendor model id, or the managed runtime's loaded model. */
19001
- model: string(),
19002
- /** Required for openai-compatible; override for cloud kinds. */
19003
- baseUrl: string().optional(),
19004
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
19005
- apiKey: string().optional(),
19006
- supportsVision: boolean(),
19007
- temperature: number().min(0).max(2).optional(),
19008
- maxTokens: number().int().positive().optional(),
19009
- timeoutMs: number().int().positive().default(6e4),
19010
- extraHeaders: record(string(), string()).optional(),
19011
- /** kind === 'managed-local' only (spec §4). */
19012
- runtime: ManagedRuntimeConfigSchema.optional()
19089
+ config: record(string(), unknown())
19013
19090
  });
19014
- /** ConfigUISchema tree passed through untyped on the wire (the
19015
- * notification-output `ConfigSchemaPassthrough` precedent at
19016
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
19017
- var ConfigSchemaPassthrough = unknown();
19018
- var LlmProfileKindDescriptorSchema = object({
19019
- kind: LlmProfileKindSchema,
19020
- label: string(),
19021
- icon: string(),
19022
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
19023
- addonId: string(),
19024
- configSchema: ConfigSchemaPassthrough
19091
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
19092
+ var DiscoveredTargetSchema = object({
19093
+ kind: string(),
19094
+ suggestedName: string(),
19095
+ config: record(string(), unknown())
19025
19096
  });
19026
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
19027
- var LlmDefaultSchema = object({
19028
- selector: LlmDefaultSelectorSchema,
19029
- profileId: string()
19097
+ /** The degrade engine's report what was resolved / dropped / degraded. */
19098
+ var RenderedAsSchema = object({
19099
+ level: string(),
19100
+ format: NotificationFormatSchema,
19101
+ attachmentsSent: number().int().nonnegative(),
19102
+ actionsSent: number().int().nonnegative(),
19103
+ truncated: boolean(),
19104
+ dropped: array(string())
19030
19105
  });
19031
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
19032
- var LlmUsageRollupSchema = object({
19033
- day: string(),
19034
- consumer: string(),
19035
- profileId: string(),
19036
- calls: number(),
19037
- okCalls: number(),
19038
- errorCalls: number(),
19039
- inputTokens: number(),
19040
- outputTokens: number(),
19041
- avgLatencyMs: number()
19106
+ var SendResultSchema = object({
19107
+ success: boolean(),
19108
+ error: string().optional(),
19109
+ renderedAs: RenderedAsSchema.optional()
19042
19110
  });
19043
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
19044
- var ManagedModelCatalogEntrySchema = object({
19111
+ /** Same shape as SendResult kept as a distinct name for the test panel. */
19112
+ var TestResultSchema = SendResultSchema;
19113
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
19114
+ kind: string(),
19115
+ config: record(string(), unknown()).optional()
19116
+ }), array(DiscoveredTargetSchema)), method(object({
19117
+ targetId: string(),
19118
+ notification: NotificationSchema
19119
+ }), SendResultSchema, { kind: "mutation" }), method(object({
19120
+ targetId: string(),
19121
+ sample: NotificationSchema.optional()
19122
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
19123
+ targetId: string(),
19124
+ enabled: boolean()
19125
+ }), _void(), { kind: "mutation" });
19126
+ /**
19127
+ * notification-rules — the Notification Center rule surface (P1 core).
19128
+ *
19129
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
19130
+ * (operator decisions D-1/D-2/D-3 are binding):
19131
+ *
19132
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
19133
+ * `notification-center` module), hooked on the durable persistence
19134
+ * moments (object-event insert, TrackCloser.closeExpired) with a
19135
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
19136
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
19137
+ * FIRST persisted detection matching the conditions (per-track dedup,
19138
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
19139
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
19140
+ * - DISPATCH stays behind `notification-output` (rules reference targets
19141
+ * by id; per-backend params are a passthrough blob capped by the
19142
+ * target kind's own caps/degrade engine).
19143
+ *
19144
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
19145
+ * server-injected caller identity — the first `caller: 'required'`
19146
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
19147
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
19148
+ * windows, and the optional label/identity/plate matchers. User rules,
19149
+ * private zones, per-recipient fan-out and the wider condition table are
19150
+ * P2+ (see spec §7).
19151
+ *
19152
+ * All schemas here are the single source of truth — `NcRule` etc. are
19153
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
19154
+ * schema/interface drift is explicitly not repeated).
19155
+ */
19156
+ /**
19157
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
19158
+ * The value maps 1:1 onto the evaluated record kind:
19159
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
19160
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
19161
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
19162
+ * change of a LINKED device, one row per linked camera)
19163
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
19164
+ * delivery / pick-up)
19165
+ *
19166
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
19167
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
19168
+ * this one field keeps the schema additive — a rule still declares exactly
19169
+ * one trigger.
19170
+ */
19171
+ var NcDeliverySchema = _enum([
19172
+ "immediate",
19173
+ "track-end",
19174
+ "device-event",
19175
+ "package-event"
19176
+ ]);
19177
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
19178
+ var NcScheduleSchema = object({
19179
+ windows: array(object({
19180
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
19181
+ days: array(number().int().min(0).max(6)).min(1),
19182
+ startMinute: number().int().min(0).max(1439),
19183
+ endMinute: number().int().min(0).max(1439)
19184
+ })).min(1),
19185
+ /** IANA timezone; default = hub host timezone. */
19186
+ timezone: string().optional(),
19187
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
19188
+ invert: boolean().optional()
19189
+ });
19190
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
19191
+ var NcPlateMatcherSchema = object({
19192
+ values: array(string().min(1)).min(1),
19193
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
19194
+ maxDistance: number().int().min(0).max(3).default(1)
19195
+ });
19196
+ /**
19197
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
19198
+ * occupancy edge for a device — optionally narrowed to a single admin
19199
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
19200
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
19201
+ * - `became-free` — count crossed ≥ `count` → below it
19202
+ * - `>=` / `<=` — count is at/over or at/under `count`
19203
+ * `sustainSeconds` requires the condition hold continuously that long
19204
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
19205
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
19206
+ * the condition never matches. Confirmed edge-state survives addon restarts
19207
+ * (declared SQLite collection, reseeded on boot).
19208
+ */
19209
+ var NcOccupancyConditionSchema = object({
19210
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
19211
+ zoneId: string().optional(),
19212
+ /** Object class to count; absent = any class. */
19213
+ className: string().optional(),
19214
+ op: _enum([
19215
+ "became-occupied",
19216
+ "became-free",
19217
+ ">=",
19218
+ "<="
19219
+ ]).default("became-occupied"),
19220
+ count: number().int().min(0).default(1),
19221
+ sustainSeconds: number().int().min(0).max(3600).default(15)
19222
+ });
19223
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
19224
+ var NcZoneConditionSchema = object({
19225
+ ids: array(string().min(1)).min(1),
19226
+ /** Quantifier over `ids` — at least one / every one visited. */
19227
+ match: _enum(["any", "all"]).default("any")
19228
+ });
19229
+ /**
19230
+ * The P1 condition set — a flat AND of groups; absent group = pass;
19231
+ * membership lists are OR within the list (spec §2.3).
19232
+ */
19233
+ var NcConditionsSchema = object({
19234
+ /** Device scope — absent = all devices. */
19235
+ devices: array(number()).optional(),
19236
+ /** Detector class names (any overlap with the record's class set). */
19237
+ classes: array(string().min(1)).optional(),
19238
+ /** Veto classes — any overlap fails the rule. */
19239
+ classesExclude: array(string().min(1)).optional(),
19240
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
19241
+ minConfidence: number().min(0).max(1).optional(),
19242
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
19243
+ zones: NcZoneConditionSchema.optional(),
19244
+ /** Veto zones — any hit fails the rule. */
19245
+ zonesExclude: array(string().min(1)).optional(),
19246
+ /**
19247
+ * Exact (case-insensitive) match on the record's collapsed `label`
19248
+ * (identity name / plate text / subclass).
19249
+ */
19250
+ labelEquals: array(string().min(1)).optional(),
19251
+ /**
19252
+ * Identity matcher. P1 boundary: matched against the record's collapsed
19253
+ * `label` (the identity display name propagated by the face pipeline) —
19254
+ * identity-ID matching rides in P2 when identity ids reach the record.
19255
+ */
19256
+ identities: array(string().min(1)).optional(),
19257
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
19258
+ plates: NcPlateMatcherSchema.optional(),
19259
+ /**
19260
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
19261
+ * Same P1 boundary: matched against the record's collapsed `label` (the
19262
+ * identity display name). A record with NO label passes (nothing to
19263
+ * exclude), unlike the include variant which fails on an absent label.
19264
+ */
19265
+ identitiesExclude: array(string().min(1)).optional(),
19266
+ /**
19267
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
19268
+ * TRACK-END only: importance is scored at track close, so it does not exist
19269
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
19270
+ * close the value is threaded via the close-time info (the `Track` clone is
19271
+ * captured before the DB row is updated, so it would otherwise read stale).
19272
+ * Fails when the record carries no importance (never guess quality — the
19273
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
19274
+ */
19275
+ minImportance: number().min(0).max(1).optional(),
19276
+ /**
19277
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
19278
+ * TRACK-END only: an `immediate` / object-event subject has no closed
19279
+ * lifespan, so a dwell condition never matches immediate delivery
19280
+ * (documented choice — the object-event record carries no `firstSeen`,
19281
+ * so dwell cannot be computed from what the subject actually carries).
19282
+ */
19283
+ minDwellSeconds: number().min(0).optional(),
19284
+ /**
19285
+ * Detection provenance filter. `any` (default / absent) matches every
19286
+ * source; otherwise the subject's source must equal it. Legacy records
19287
+ * with no stamped source are treated as `pipeline`. The union spans both
19288
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
19289
+ * tracks carry `sensor`.
19290
+ */
19291
+ source: _enum([
19292
+ "pipeline",
19293
+ "onboard",
19294
+ "sensor",
19295
+ "any"
19296
+ ]).optional(),
19297
+ /**
19298
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
19299
+ * detector `minConfidence` (that gates the object-detection score; this
19300
+ * gates the recognition/OCR match score). Fails when the subject carries
19301
+ * no label-match confidence (never guess). TRACK-END only: the confidence
19302
+ * lives on the recognition result and reaches the subject at track close.
19303
+ *
19304
+ * What it measures precisely (plumbed at track close — the closer threads
19305
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
19306
+ * `importance`): the BEST recognition match confidence observed for the
19307
+ * label the track carries at close — for a face, the peak cosine similarity
19308
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
19309
+ * for a plate, the peak OCR read score of the best-held plate
19310
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
19311
+ * one track the higher of the two is used. A track that ended with no
19312
+ * confident identity/plate match carries no value, so the condition fails
19313
+ * closed for it (an un-recognized subject).
19314
+ */
19315
+ minLabelConfidence: number().min(0).max(1).optional(),
19316
+ /**
19317
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
19318
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
19319
+ * against the token carried on the device-event subject (extracted from the
19320
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
19321
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
19322
+ * eventType, so gate those with {@link sensorKinds} instead.
19323
+ */
19324
+ eventTypeTokens: array(string().min(1)).optional(),
19325
+ /**
19326
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
19327
+ * `contact`, `button`, `device-event`) — matched against the persisted
19328
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
19329
+ */
19330
+ sensorKinds: array(string().min(1)).optional(),
19331
+ /**
19332
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
19333
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
19334
+ * when the subject's phase does not match (a subject always carries a phase
19335
+ * on the package-event trigger).
19336
+ */
19337
+ packagePhase: _enum([
19338
+ "delivered",
19339
+ "picked-up",
19340
+ "both"
19341
+ ]).optional(),
19342
+ /**
19343
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
19344
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
19345
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
19346
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
19347
+ */
19348
+ customZones: array(MaskPolygonShapeSchema).optional(),
19349
+ /**
19350
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
19351
+ * (optionally zone/class-scoped) occupancy count crosses the configured
19352
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
19353
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
19354
+ */
19355
+ occupancy: NcOccupancyConditionSchema.optional()
19356
+ });
19357
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
19358
+ var NcRuleTargetSchema = object({
19359
+ /** `notification-output` Target id. */
19360
+ targetId: string().min(1),
19361
+ /**
19362
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
19363
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
19364
+ * degrade engine drops what the backend can't render.
19365
+ */
19366
+ params: record(string(), unknown()).optional()
19367
+ });
19368
+ /**
19369
+ * Media attachment policy (P1 still-image subset).
19370
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
19371
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
19372
+ * matched on identities attaches the subject's `faceCrop`, one matched on
19373
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
19374
+ * (or when the specific crop is missing) degrades to `best`, then
19375
+ * `keyFrame`, then no attachment — never delaying the send. The matched
19376
+ * condition summary is frozen on the outbox row at enqueue (like the rule
19377
+ * name), so the choice never drifts from the record that fired it.
19378
+ * - `keyFrame` — the clean scene frame (no subject box).
19379
+ * - `none` — no attachment.
19380
+ */
19381
+ var NcMediaPolicySchema = object({ attach: _enum([
19382
+ "best",
19383
+ "best-matching",
19384
+ "keyFrame",
19385
+ "none"
19386
+ ]).default("best") });
19387
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
19388
+ var NcThrottleSchema = object({
19389
+ cooldownSec: number().int().min(0).max(86400).default(60),
19390
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
19391
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
19392
+ });
19393
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
19394
+ var NcRuleInputSchema = object({
19395
+ name: string().min(1).max(200),
19396
+ enabled: boolean().default(true),
19397
+ delivery: NcDeliverySchema,
19398
+ conditions: NcConditionsSchema.default({}),
19399
+ schedule: NcScheduleSchema.optional(),
19400
+ targets: array(NcRuleTargetSchema).min(1),
19401
+ media: NcMediaPolicySchema.default({ attach: "best" }),
19402
+ throttle: NcThrottleSchema.default({
19403
+ cooldownSec: 60,
19404
+ scope: "rule-device"
19405
+ }),
19406
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
19407
+ template: object({
19408
+ title: string().max(500).optional(),
19409
+ body: string().max(2e3).optional()
19410
+ }).optional(),
19411
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
19412
+ priority: number().int().min(1).max(5).default(3),
19413
+ /**
19414
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
19415
+ * behaviour, visible to all, read-only in the viewer). Present = personal
19416
+ * rule owned by this userId. Server-stamped; never trusted from a client.
19417
+ */
19418
+ ownerUserId: string().optional()
19419
+ });
19420
+ /**
19421
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
19422
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
19423
+ * NOT a client-authored input field (it lives on the persisted rule, not the
19424
+ * input), so it is added here explicitly to let the store's per-target opt-out
19425
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
19426
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
19427
+ * `updateRule` patch.
19428
+ */
19429
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
19430
+ /** A persisted rule. */
19431
+ var NcRuleSchema = NcRuleInputSchema.extend({
19432
+ id: string(),
19433
+ /** userId of the admin who created the rule (server-stamped caller). */
19434
+ createdBy: string(),
19435
+ createdAt: number(),
19436
+ updatedAt: number(),
19437
+ /**
19438
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
19439
+ * send time. Only a target's OWNER may add/remove its id (server-checked
19440
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
19441
+ */
19442
+ disabledTargetIds: array(string()).default([])
19443
+ });
19444
+ var NcTestResultSchema = object({
19445
+ recordId: string(),
19446
+ recordKind: _enum([
19447
+ "object-event",
19448
+ "track",
19449
+ "device-event",
19450
+ "package-event"
19451
+ ]),
19452
+ deviceId: number(),
19453
+ timestamp: number(),
19454
+ wouldFire: boolean(),
19455
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
19456
+ failedCondition: string().optional(),
19457
+ className: string().optional(),
19458
+ label: string().optional()
19459
+ });
19460
+ var NcConditionDescriptorSchema = object({
19461
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
19045
19462
  id: string(),
19463
+ group: _enum([
19464
+ "scope",
19465
+ "class",
19466
+ "zones",
19467
+ "quality",
19468
+ "label",
19469
+ "schedule",
19470
+ "device",
19471
+ "package",
19472
+ "occupancy"
19473
+ ]),
19046
19474
  label: string(),
19047
- family: string(),
19048
- purpose: _enum(["text", "vision"]),
19049
- url: string(),
19050
- sha256: string(),
19051
- sizeBytes: number(),
19052
- quantization: string(),
19053
- /** Load-time guidance shown in the picker. */
19054
- minRamBytes: number(),
19055
- contextSizeDefault: number().int(),
19056
- /** Vision models: companion projector file. */
19057
- mmprojUrl: string().optional()
19475
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
19476
+ valueType: _enum([
19477
+ "deviceIdList",
19478
+ "stringList",
19479
+ "number01",
19480
+ "number",
19481
+ "sourceSelect",
19482
+ "zoneSelection",
19483
+ "zoneIdList",
19484
+ "schedule",
19485
+ "plateMatcher",
19486
+ "packagePhase",
19487
+ "polygonDraw",
19488
+ "occupancy"
19489
+ ]),
19490
+ operator: _enum([
19491
+ "in",
19492
+ "notIn",
19493
+ "anyOf",
19494
+ "allOf",
19495
+ "gte",
19496
+ "fuzzyIn",
19497
+ "withinSchedule"
19498
+ ]),
19499
+ /** Which delivery kinds the condition applies to. */
19500
+ appliesTo: array(NcDeliverySchema),
19501
+ phase: string(),
19502
+ description: string().optional()
19058
19503
  });
19059
- var LlmRuntimeNodeSchema = object({
19060
- nodeId: string(),
19061
- reachable: boolean(),
19062
- status: LlmRuntimeStatusSchema.optional(),
19063
- disk: LlmRuntimeDiskUsageSchema.optional(),
19064
- error: string().optional()
19504
+ /**
19505
+ * The delivery lifecycle status of a history row — a straight read of the
19506
+ * durable outbox row's own status (single source of truth):
19507
+ * - `pending` — enqueued, in-flight or retrying with backoff
19508
+ * - `sent` — delivered (terminal)
19509
+ * - `dead` — dead-lettered after exhausting retries / a permanent
19510
+ * backend rejection / a deleted target (terminal; carries
19511
+ * the failure `error`)
19512
+ *
19513
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
19514
+ * user dimension (quiet hours / snooze) and are additive when they land.
19515
+ */
19516
+ var NcHistoryStatusSchema = _enum([
19517
+ "pending",
19518
+ "sent",
19519
+ "dead"
19520
+ ]);
19521
+ /** The evaluated record kind a history row descends from (one per trigger). */
19522
+ var NcHistoryRecordKindSchema = _enum([
19523
+ "object-event",
19524
+ "track-end",
19525
+ "device-event",
19526
+ "package-event"
19527
+ ]);
19528
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
19529
+ var NcHistorySubjectSchema = object({
19530
+ className: string(),
19531
+ label: string().optional(),
19532
+ confidence: number().optional(),
19533
+ zones: array(string()),
19534
+ timestamp: number()
19535
+ });
19536
+ /**
19537
+ * One delivery-history row. This is a read-only VIEW over the durable
19538
+ * outbox row (single source of truth — the same row the drain loop drives;
19539
+ * NO second write path, so history can never drift from delivery state).
19540
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
19541
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
19542
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
19543
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
19544
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
19545
+ * P1 (admin scope only).
19546
+ */
19547
+ var NcHistoryEntrySchema = object({
19548
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
19549
+ id: string(),
19550
+ ruleId: string(),
19551
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
19552
+ ruleName: string(),
19553
+ /** The rule urgency/trigger that produced this delivery. */
19554
+ delivery: NcDeliverySchema,
19555
+ targetId: string(),
19556
+ deviceId: number(),
19557
+ recordKind: NcHistoryRecordKindSchema,
19558
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
19559
+ recordId: string(),
19560
+ /** Present for track-scoped deliveries (object-event / track-end). */
19561
+ trackId: string().optional(),
19562
+ status: NcHistoryStatusSchema,
19563
+ /** Delivery attempts made so far. */
19564
+ attempts: number().int(),
19565
+ /** Fire time (outbox enqueue). */
19566
+ createdAt: number(),
19567
+ /** Last transition time (terminal for sent / dead). */
19568
+ updatedAt: number(),
19569
+ /** Failure detail — present on a `dead` row. */
19570
+ error: string().optional(),
19571
+ subject: NcHistorySubjectSchema
19065
19572
  });
19066
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
19067
- var ProfileRefInputSchema = object({
19068
- addonId: string(),
19069
- profileId: string()
19573
+ /**
19574
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
19575
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
19576
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
19577
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
19578
+ */
19579
+ var NcHistoryFilterSchema = object({
19580
+ ruleId: string().optional(),
19581
+ deviceId: number().optional(),
19582
+ status: NcHistoryStatusSchema.optional(),
19583
+ since: number().optional(),
19584
+ until: number().optional(),
19585
+ limit: number().int().min(1).max(500).default(100)
19070
19586
  });
19071
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
19072
- kind: "mutation",
19073
- auth: "admin"
19074
- }), method(ProfileRefInputSchema, _void(), {
19587
+ 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 }), {
19075
19588
  kind: "mutation",
19076
- auth: "admin"
19077
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
19589
+ auth: "admin",
19590
+ caller: "required"
19591
+ }), method(object({
19592
+ ruleId: string(),
19593
+ patch: NcRulePatchSchema
19594
+ }), object({ rule: NcRuleSchema }), {
19078
19595
  kind: "mutation",
19079
- auth: "admin"
19080
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
19081
- selector: LlmDefaultSelectorSchema,
19082
- profileId: string().nullable()
19083
- }), _void(), {
19596
+ auth: "admin",
19597
+ caller: "required"
19598
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
19084
19599
  kind: "mutation",
19085
19600
  auth: "admin"
19086
19601
  }), method(object({
19087
- since: number().optional(),
19088
- until: number().optional(),
19089
- consumer: string().optional(),
19090
- profileId: string().optional()
19091
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
19092
- nodeId: string(),
19093
- model: ManagedModelRefSchema
19094
- }), _void(), {
19602
+ ruleId: string(),
19603
+ enabled: boolean()
19604
+ }), object({ success: literal(true) }), {
19095
19605
  kind: "mutation",
19096
19606
  auth: "admin"
19097
19607
  }), method(object({
19098
- nodeId: string(),
19099
- file: string()
19100
- }), _void(), {
19101
- kind: "mutation",
19102
- auth: "admin"
19103
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
19104
- kind: "mutation",
19105
- auth: "admin"
19106
- }), method(ProfileRefInputSchema, _void(), {
19608
+ rule: NcRuleInputSchema,
19609
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
19610
+ }), object({ results: array(NcTestResultSchema) }), {
19107
19611
  kind: "mutation",
19108
19612
  auth: "admin"
19109
- });
19613
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
19110
19614
  /**
19111
19615
  * Zod schemas for persisted record types.
19112
19616
  *
@@ -19792,7 +20296,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19792
20296
  }), method(object({
19793
20297
  eventId: string(),
19794
20298
  kind: MediaFileKindEnum.optional()
19795
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
20299
+ }), array(MediaFileSchema).readonly()), method(object({
20300
+ trackId: string(),
20301
+ kinds: array(MediaFileKindEnum).optional()
20302
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
19796
20303
  deviceId: number(),
19797
20304
  timestamp: number(),
19798
20305
  frameWidth: number(),
@@ -19813,76 +20320,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19813
20320
  eventId: string(),
19814
20321
  timestamp: number()
19815
20322
  });
19816
- /**
19817
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
19818
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
19819
- * caps into per-camera event-kind descriptors.
19820
- *
19821
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
19822
- * is NOT duplicated here — every entry is derived from the single
19823
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
19824
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
19825
- * control cap means adding one line here (and a taxonomy entry); the anti-
19826
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
19827
- * eventful cap is missing.
19828
- */
19829
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
19830
- var LEGACY_ICON = {
19831
- motion: "motion",
19832
- audio: "audio",
19833
- person: "person",
19834
- vehicle: "vehicle",
19835
- animal: "animal",
19836
- package: "package",
19837
- door: "door",
19838
- pir: "pir",
19839
- smoke: "smoke",
19840
- water: "water",
19841
- button: "button",
19842
- generic: "generic",
19843
- gas: "smoke",
19844
- vibration: "generic",
19845
- tamper: "generic",
19846
- presence: "person",
19847
- lock: "generic",
19848
- siren: "generic",
19849
- switch: "generic",
19850
- doorbell: "button"
19851
- };
19852
- function legacyIcon(iconId) {
19853
- return LEGACY_ICON[iconId] ?? "generic";
19854
- }
19855
- /**
19856
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
19857
- * The anti-drift guard cross-checks this against the eventful caps declared
19858
- * in `packages/types/src/capabilities/*.cap.ts`.
19859
- */
19860
- var CAP_TO_KIND = {
19861
- contact: "contact",
19862
- motion: "motion-sensor",
19863
- smoke: "smoke",
19864
- flood: "flood",
19865
- gas: "gas",
19866
- "carbon-monoxide": "carbon-monoxide",
19867
- vibration: "vibration",
19868
- tamper: "tamper",
19869
- presence: "presence",
19870
- "enum-sensor": "enum-sensor",
19871
- "event-emitter": "device-event",
19872
- "lock-control": "lock",
19873
- switch: "switch",
19874
- button: "button",
19875
- doorbell: "doorbell"
19876
- };
19877
- function buildDescriptor(capName, kind) {
19878
- const t = EVENT_TAXONOMY[kind];
19879
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
19880
- return {
19881
- ...t,
19882
- icon: legacyIcon(t.iconId)
19883
- };
19884
- }
19885
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
19886
20323
  var CameraPipelineConfigSchema = object({
19887
20324
  engine: PipelineEngineChoiceSchema.optional(),
19888
20325
  steps: array(PipelineStepInputSchema).readonly(),
@@ -20368,6 +20805,76 @@ method(object({
20368
20805
  auth: "admin"
20369
20806
  });
20370
20807
  /**
20808
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
20809
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
20810
+ * caps into per-camera event-kind descriptors.
20811
+ *
20812
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
20813
+ * is NOT duplicated here — every entry is derived from the single
20814
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
20815
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
20816
+ * control cap means adding one line here (and a taxonomy entry); the anti-
20817
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
20818
+ * eventful cap is missing.
20819
+ */
20820
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
20821
+ var LEGACY_ICON = {
20822
+ motion: "motion",
20823
+ audio: "audio",
20824
+ person: "person",
20825
+ vehicle: "vehicle",
20826
+ animal: "animal",
20827
+ package: "package",
20828
+ door: "door",
20829
+ pir: "pir",
20830
+ smoke: "smoke",
20831
+ water: "water",
20832
+ button: "button",
20833
+ generic: "generic",
20834
+ gas: "smoke",
20835
+ vibration: "generic",
20836
+ tamper: "generic",
20837
+ presence: "person",
20838
+ lock: "generic",
20839
+ siren: "generic",
20840
+ switch: "generic",
20841
+ doorbell: "button"
20842
+ };
20843
+ function legacyIcon(iconId) {
20844
+ return LEGACY_ICON[iconId] ?? "generic";
20845
+ }
20846
+ /**
20847
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
20848
+ * The anti-drift guard cross-checks this against the eventful caps declared
20849
+ * in `packages/types/src/capabilities/*.cap.ts`.
20850
+ */
20851
+ var CAP_TO_KIND = {
20852
+ contact: "contact",
20853
+ motion: "motion-sensor",
20854
+ smoke: "smoke",
20855
+ flood: "flood",
20856
+ gas: "gas",
20857
+ "carbon-monoxide": "carbon-monoxide",
20858
+ vibration: "vibration",
20859
+ tamper: "tamper",
20860
+ presence: "presence",
20861
+ "enum-sensor": "enum-sensor",
20862
+ "event-emitter": "device-event",
20863
+ "lock-control": "lock",
20864
+ switch: "switch",
20865
+ button: "button",
20866
+ doorbell: "doorbell"
20867
+ };
20868
+ function buildDescriptor(capName, kind) {
20869
+ const t = EVENT_TAXONOMY[kind];
20870
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
20871
+ return {
20872
+ ...t,
20873
+ icon: legacyIcon(t.iconId)
20874
+ };
20875
+ }
20876
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
20877
+ /**
20371
20878
  * server-management — per-NODE singleton capability for a node's ROOT
20372
20879
  * package lifecycle (runtime-updatable node packages).
20373
20880
  *
@@ -21873,7 +22380,28 @@ var FaceInfoSchema = object({
21873
22380
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
21874
22381
  * track produced no key frame (e.g. native/onboard source) — the UI falls
21875
22382
  * back to the inline `base64` face crop. */
21876
- keyFrameMediaKey: string().optional()
22383
+ keyFrameMediaKey: string().optional(),
22384
+ /** Winning identity-match cosine (0..1) for this face's track, when an
22385
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
22386
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
22387
+ * faces that were never auto-recognized. */
22388
+ bestMatchScore: number().optional(),
22389
+ /** Native-scale face short side (px) at recognition time, when the runner
22390
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
22391
+ * legacy rows / runners that reported no native measure. */
22392
+ nativeFaceShortSidePx: number().optional(),
22393
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
22394
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
22395
+ * but blocked only by the recognition size floor). Mutually exclusive with
22396
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
22397
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
22398
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
22399
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
22400
+ suggestedIdentityId: string().optional(),
22401
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
22402
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
22403
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
22404
+ suggestedMatchScore: number().optional()
21877
22405
  });
21878
22406
  var FaceFilterEnum = _enum([
21879
22407
  "unassigned",
@@ -24215,36 +24743,6 @@ Object.freeze({
24215
24743
  addonId: null,
24216
24744
  access: "view"
24217
24745
  },
24218
- "advancedNotifier.deleteRule": {
24219
- capName: "advanced-notifier",
24220
- capScope: "system",
24221
- addonId: null,
24222
- access: "delete"
24223
- },
24224
- "advancedNotifier.getHistory": {
24225
- capName: "advanced-notifier",
24226
- capScope: "system",
24227
- addonId: null,
24228
- access: "view"
24229
- },
24230
- "advancedNotifier.getRules": {
24231
- capName: "advanced-notifier",
24232
- capScope: "system",
24233
- addonId: null,
24234
- access: "view"
24235
- },
24236
- "advancedNotifier.testRule": {
24237
- capName: "advanced-notifier",
24238
- capScope: "system",
24239
- addonId: null,
24240
- access: "create"
24241
- },
24242
- "advancedNotifier.upsertRule": {
24243
- capName: "advanced-notifier",
24244
- capScope: "system",
24245
- addonId: null,
24246
- access: "create"
24247
- },
24248
24746
  "alarmPanel.arm": {
24249
24747
  capName: "alarm-panel",
24250
24748
  capScope: "device",
@@ -26549,6 +27047,60 @@ Object.freeze({
26549
27047
  addonId: null,
26550
27048
  access: "create"
26551
27049
  },
27050
+ "notificationRules.createRule": {
27051
+ capName: "notification-rules",
27052
+ capScope: "system",
27053
+ addonId: null,
27054
+ access: "create"
27055
+ },
27056
+ "notificationRules.deleteRule": {
27057
+ capName: "notification-rules",
27058
+ capScope: "system",
27059
+ addonId: null,
27060
+ access: "delete"
27061
+ },
27062
+ "notificationRules.getConditionCatalog": {
27063
+ capName: "notification-rules",
27064
+ capScope: "system",
27065
+ addonId: null,
27066
+ access: "view"
27067
+ },
27068
+ "notificationRules.getHistory": {
27069
+ capName: "notification-rules",
27070
+ capScope: "system",
27071
+ addonId: null,
27072
+ access: "view"
27073
+ },
27074
+ "notificationRules.getRule": {
27075
+ capName: "notification-rules",
27076
+ capScope: "system",
27077
+ addonId: null,
27078
+ access: "view"
27079
+ },
27080
+ "notificationRules.listRules": {
27081
+ capName: "notification-rules",
27082
+ capScope: "system",
27083
+ addonId: null,
27084
+ access: "view"
27085
+ },
27086
+ "notificationRules.setRuleEnabled": {
27087
+ capName: "notification-rules",
27088
+ capScope: "system",
27089
+ addonId: null,
27090
+ access: "create"
27091
+ },
27092
+ "notificationRules.testRule": {
27093
+ capName: "notification-rules",
27094
+ capScope: "system",
27095
+ addonId: null,
27096
+ access: "create"
27097
+ },
27098
+ "notificationRules.updateRule": {
27099
+ capName: "notification-rules",
27100
+ capScope: "system",
27101
+ addonId: null,
27102
+ access: "create"
27103
+ },
26552
27104
  "notifier.cancel": {
26553
27105
  capName: "notifier",
26554
27106
  capScope: "device",