@camstack/addon-mqtt-broker 1.2.3 → 1.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -39,7 +39,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
39
39
  var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
40
40
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
41
41
  //#endregion
42
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
42
+ //#region ../types/dist/event-category-BLcNejAE.mjs
43
43
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
44
44
  EventCategory["SystemBoot"] = "system.boot";
45
45
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -189,9 +189,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
189
189
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
190
190
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
191
191
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
192
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
193
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
194
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
195
192
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
196
193
  * progress bar the client reconciles via `recordingExport.getExport`. */
197
194
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6856,7 +6853,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6856
6853
  patch: record(string(), unknown())
6857
6854
  }), object({ success: literal(true) });
6858
6855
  object({ deviceId: number() }), unknown().nullable();
6859
- /** Shorthand to define a method schema */
6860
6856
  function method(input, output, options) {
6861
6857
  return {
6862
6858
  input,
@@ -6864,6 +6860,7 @@ function method(input, output, options) {
6864
6860
  kind: options?.kind ?? "query",
6865
6861
  auth: options?.auth ?? "protected",
6866
6862
  ...options?.access !== void 0 ? { access: options.access } : {},
6863
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6867
6864
  timeoutMs: options?.timeoutMs
6868
6865
  };
6869
6866
  }
@@ -8217,6 +8214,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8217
8214
  /** The complete taxonomy dictionary, keyed by kind. */
8218
8215
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8219
8216
  /**
8217
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8218
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8219
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8220
+ * taxonomy surface (timeline, filters, event page).
8221
+ *
8222
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8223
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8224
+ * for the `classes` / `classesExclude` conditions.
8225
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8226
+ * the same class picker, grouped under an Audio header.
8227
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8228
+ * lock / …) for the `sensorKinds` device-event condition.
8229
+ *
8230
+ * Each entry carries `parentKind` so the client can group video subs under
8231
+ * their macro and sensor/control kinds under their category. This surface is
8232
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8233
+ * method, no codegen — so it ships train-free with an addon deploy.
8234
+ */
8235
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8236
+ var NcTaxonomyEntrySchema = object({
8237
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8238
+ kind: string(),
8239
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8240
+ label: string(),
8241
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8242
+ parentKind: string().nullable()
8243
+ });
8244
+ object({
8245
+ videoClasses: array(NcTaxonomyEntrySchema),
8246
+ audioKinds: array(NcTaxonomyEntrySchema),
8247
+ labels: array(NcTaxonomyEntrySchema)
8248
+ });
8249
+ function toEntry(kind, label, parentKind) {
8250
+ return {
8251
+ kind,
8252
+ label,
8253
+ parentKind
8254
+ };
8255
+ }
8256
+ /**
8257
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8258
+ * (macros before their subs), which the client relies on for stable grouping.
8259
+ */
8260
+ function buildNcTaxonomy() {
8261
+ const all = Object.values(EVENT_TAXONOMY);
8262
+ return {
8263
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8264
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8265
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8266
+ };
8267
+ }
8268
+ Object.freeze(buildNcTaxonomy());
8269
+ /**
8220
8270
  * Error types for the safe expression engine. Two distinct classes so callers
8221
8271
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8222
8272
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -10925,6 +10975,22 @@ var CameraMetricsSchema = object({
10925
10975
  ])
10926
10976
  });
10927
10977
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
10978
+ /**
10979
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
10980
+ * within the frame, so the executor can re-cut a leaf child ROI at native
10981
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
10982
+ */
10983
+ var NativeCropRefSchema = object({
10984
+ /** Handle keying the retained native surface (node-pinned to its owner). */
10985
+ handle: FrameHandleSchema,
10986
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
10987
+ cropFrameSpace: object({
10988
+ x: number(),
10989
+ y: number(),
10990
+ w: number(),
10991
+ h: number()
10992
+ })
10993
+ });
10928
10994
  var ModelFormatSchema$1 = _enum([
10929
10995
  "onnx",
10930
10996
  "coreml",
@@ -11200,7 +11266,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
11200
11266
  * Omitted ⇒ the runner's default device (current single-engine
11201
11267
  * behaviour). Selects WHICH device pool of the node runs the call.
11202
11268
  */
11203
- deviceKey: string().optional()
11269
+ deviceKey: string().optional(),
11270
+ /**
11271
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
11272
+ * when the parent crop was resolved from the frame's retained NATIVE
11273
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
11274
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
11275
+ * resolution from that surface — the SAME quality path faces already
11276
+ * had — instead of the downscaled parent tile. `handle` keys the native
11277
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
11278
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
11279
+ * the executor's crop-normalized child ROI back into frame-normalized
11280
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
11281
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
11282
+ * (today's behaviour on the fallback path).
11283
+ */
11284
+ nativeCropRef: NativeCropRefSchema.optional()
11204
11285
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
11205
11286
  engine: PipelineEngineChoiceSchema.optional(),
11206
11287
  steps: array(PipelineStepInputSchema).min(1),
@@ -11416,7 +11497,11 @@ var DetailResultSchema = object({
11416
11497
  bbox: NativeCropBboxSchema.optional(),
11417
11498
  embedding: string().optional(),
11418
11499
  label: string().optional(),
11419
- alignedCropJpeg: string().optional()
11500
+ alignedCropJpeg: string().optional(),
11501
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
11502
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
11503
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
11504
+ nativeFaceShortSidePx: number().optional()
11420
11505
  });
11421
11506
  /**
11422
11507
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -11430,6 +11515,12 @@ var motionCooldownMsField = {
11430
11515
  default: 3e4,
11431
11516
  step: 500
11432
11517
  };
11518
+ var maxSessionHoldMsField = {
11519
+ min: 0,
11520
+ max: 6e5,
11521
+ default: 12e4,
11522
+ step: 5e3
11523
+ };
11433
11524
  var motionFpsField = {
11434
11525
  min: 1,
11435
11526
  max: 30,
@@ -11577,6 +11668,19 @@ var RunnerCameraConfigSchema = object({
11577
11668
  "on-motion"
11578
11669
  ]).default("always-on"),
11579
11670
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
11671
+ /**
11672
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
11673
+ * detection session is active and ≥1 confirmed non-stationary track is
11674
+ * still live, the orchestrator keeps the session open past
11675
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
11676
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
11677
+ * ms since the session opened, after which it closes regardless. `0`
11678
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
11679
+ * runner itself — carried here so it shares the per-camera device-settings
11680
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
11681
+ * resolved `CameraDetectionConfig`.
11682
+ */
11683
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
11580
11684
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
11581
11685
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
11582
11686
  motionStreamId: string(),
@@ -11666,7 +11770,7 @@ var RunnerCameraConfigSchema = object({
11666
11770
  */
11667
11771
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
11668
11772
  });
11669
- 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;
11773
+ 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;
11670
11774
  /**
11671
11775
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
11672
11776
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -13520,94 +13624,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
13520
13624
  bundleUrl: string()
13521
13625
  });
13522
13626
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
13523
- var NotificationRuleConditionsSchema = object({
13524
- deviceIds: array(number()).readonly().optional(),
13525
- classNames: array(string()).readonly().optional(),
13526
- zoneIds: array(string()).readonly().optional(),
13527
- minConfidence: number().optional(),
13528
- source: _enum([
13529
- "pipeline",
13530
- "onboard",
13531
- "any"
13532
- ]).optional(),
13533
- schedule: object({
13534
- days: array(number()).readonly(),
13535
- startHour: number(),
13536
- endHour: number()
13537
- }).optional(),
13538
- cooldownSeconds: number().optional(),
13539
- minDwellSeconds: number().optional(),
13540
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
13541
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
13542
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
13543
- eventTypeTokens: array(string()).readonly().optional(),
13544
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
13545
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
13546
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
13547
- clipDescription: object({
13548
- text: string().min(1),
13549
- minSimilarity: number().min(0).max(1)
13550
- }).optional(),
13551
- /** Match events whose recognized-entity label (face identity name or plate
13552
- * vehicle name, propagated onto `event.data.label`) is one of these values.
13553
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
13554
- * vehicle/person> is seen". */
13555
- labels: array(string()).readonly().optional()
13556
- });
13557
- var NotificationRuleTemplateSchema = object({
13558
- title: string(),
13559
- body: string(),
13560
- imageMode: _enum([
13561
- "crop",
13562
- "annotated",
13563
- "full",
13564
- "none"
13565
- ])
13566
- });
13567
- var NotificationRuleSchema = object({
13568
- id: string(),
13569
- name: string(),
13570
- enabled: boolean(),
13571
- eventTypes: array(string()).readonly(),
13572
- conditions: NotificationRuleConditionsSchema,
13573
- outputs: array(string()).readonly(),
13574
- template: NotificationRuleTemplateSchema.optional(),
13575
- priority: _enum([
13576
- "low",
13577
- "normal",
13578
- "high",
13579
- "critical"
13580
- ])
13581
- });
13582
- var NotificationTestResultSchema = object({
13583
- ruleId: string(),
13584
- eventId: string(),
13585
- timestamp: number(),
13586
- wouldFire: boolean(),
13587
- reason: string().optional()
13588
- });
13589
- var NotificationHistoryEntrySchema = object({
13590
- id: string(),
13591
- ruleId: string(),
13592
- ruleName: string(),
13593
- eventId: string(),
13594
- timestamp: number(),
13595
- outputs: array(string()).readonly(),
13596
- success: boolean(),
13597
- error: string().optional(),
13598
- deviceId: number().optional()
13599
- });
13600
- var NotificationHistoryFilterSchema = object({
13601
- ruleId: string().optional(),
13602
- deviceId: number().optional(),
13603
- from: number().optional(),
13604
- to: number().optional(),
13605
- limit: number().optional()
13606
- });
13607
- 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({
13608
- ruleId: string(),
13609
- lookbackMinutes: number()
13610
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
13611
13627
  /**
13612
13628
  * Alerts capability — collection-based internal alert system.
13613
13629
  *
@@ -13794,89 +13810,6 @@ method(object({
13794
13810
  password: string()
13795
13811
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
13796
13812
  /**
13797
- * `login-method` — collection cap through which auth addons contribute
13798
- * their pre-auth login surfaces to the login page. This is the SINGLE,
13799
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
13800
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
13801
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
13802
- * procedure aggregates them for the unauthenticated login page.
13803
- *
13804
- * A contribution is a discriminated union on `kind`:
13805
- *
13806
- * - `redirect` — a declarative button. The login page renders a generic
13807
- * button that navigates to `startUrl` (an addon-owned HTTP route).
13808
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
13809
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
13810
- * login page needs NO change.
13811
- *
13812
- * - `widget` — a Module-Federation widget the login page mounts (via
13813
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
13814
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
13815
- * mechanism kept for future use; no shipped addon uses it on the login
13816
- * page (the passkey ceremony below runs natively in the shell instead).
13817
- *
13818
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
13819
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
13820
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
13821
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
13822
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
13823
- * fetching any remote code pre-auth. Contribution stays unconditional —
13824
- * enrollment state is never leaked pre-auth; visibility is a shell
13825
- * decision.
13826
- *
13827
- * Every contribution carries a `stage`:
13828
- * - `primary` — shown on the first credentials screen (OIDC /
13829
- * magic-link buttons; a future usernameless passkey).
13830
- * - `second-factor` — shown AFTER the password leg, gated on the
13831
- * returned `factors` (passkey-as-2FA today).
13832
- *
13833
- * `mount: skip` — the cap is read server-side by the core auth router
13834
- * (`registry.getCollection('login-method')`), never mounted as its own
13835
- * tRPC router.
13836
- */
13837
- /** When a login method renders in the two-phase login flow. */
13838
- var LoginStageEnum = _enum(["primary", "second-factor"]);
13839
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
13840
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
13841
- object({
13842
- kind: literal("redirect"),
13843
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
13844
- id: string(),
13845
- /** Operator-facing button label. */
13846
- label: string(),
13847
- /** lucide-react icon name. */
13848
- icon: string().optional(),
13849
- /** Addon-owned HTTP route the button navigates to (GET). */
13850
- startUrl: string(),
13851
- stage: LoginStageEnum
13852
- }),
13853
- object({
13854
- kind: literal("widget"),
13855
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
13856
- id: string(),
13857
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
13858
- addonId: string(),
13859
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
13860
- bundle: string(),
13861
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
13862
- remote: WidgetRemoteSchema,
13863
- stage: LoginStageEnum
13864
- }),
13865
- object({
13866
- kind: literal("passkey"),
13867
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
13868
- id: string(),
13869
- /** Operator-facing button label. */
13870
- label: string(),
13871
- stage: LoginStageEnum,
13872
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
13873
- rpId: string(),
13874
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
13875
- origin: string().nullable()
13876
- })
13877
- ]);
13878
- method(_void(), array(LoginMethodContributionSchema).readonly());
13879
- /**
13880
13813
  * Orchestrator-side destination metadata. The orchestrator computes
13881
13814
  * `id = <addonId>:<subId>` from its provider lookup so consumers
13882
13815
  * (admin UI, restore flow) see one canonical key.
@@ -15269,240 +15202,615 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
15269
15202
  kind: "mutation",
15270
15203
  auth: "admin"
15271
15204
  });
15272
- var LogLevelSchema = _enum([
15273
- "debug",
15274
- "info",
15275
- "warn",
15276
- "error"
15205
+ /**
15206
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15207
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15208
+ * caps stay wire-compatible without a circular cap→cap import.
15209
+ *
15210
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
15211
+ * every transport tier structurally, and failed calls still write usage rows.
15212
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15213
+ */
15214
+ var LlmUsageSchema = object({
15215
+ inputTokens: number(),
15216
+ outputTokens: number()
15217
+ });
15218
+ var LlmErrorCodeSchema = _enum([
15219
+ "timeout",
15220
+ "rate-limited",
15221
+ "auth",
15222
+ "refusal",
15223
+ "bad-request",
15224
+ "unavailable",
15225
+ "no-profile",
15226
+ "budget-exceeded",
15227
+ "adapter-error"
15277
15228
  ]);
15278
- var LogEntrySchema = object({
15279
- timestamp: date(),
15280
- level: LogLevelSchema,
15281
- scope: array(string()),
15229
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15230
+ ok: literal(true),
15231
+ text: string(),
15232
+ model: string(),
15233
+ usage: LlmUsageSchema,
15234
+ truncated: boolean(),
15235
+ latencyMs: number()
15236
+ }), object({
15237
+ ok: literal(false),
15238
+ code: LlmErrorCodeSchema,
15282
15239
  message: string(),
15283
- meta: record(string(), unknown()).optional(),
15284
- tags: record(string(), string()).optional()
15285
- });
15286
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15287
- scope: array(string()).optional(),
15288
- level: LogLevelSchema.optional(),
15289
- since: date().optional(),
15290
- until: date().optional(),
15291
- limit: number().optional(),
15292
- tags: record(string(), string()).optional()
15293
- }), array(LogEntrySchema).readonly());
15294
- var CpuBreakdownSchema = object({
15295
- total: number(),
15296
- user: number(),
15297
- system: number(),
15298
- irq: number(),
15299
- nice: number(),
15300
- loadAvg: tuple([
15301
- number(),
15302
- number(),
15303
- number()
15304
- ]),
15305
- cores: number()
15240
+ retryAfterMs: number().optional()
15241
+ })]);
15242
+ /**
15243
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15244
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15245
+ * notification-output.cap.ts:27-31 precedents).
15246
+ */
15247
+ var LlmImageSchema = object({
15248
+ bytes: _instanceof(Uint8Array),
15249
+ mimeType: string()
15306
15250
  });
15307
- var MemoryInfoSchema = object({
15308
- percent: number(),
15309
- totalBytes: number(),
15310
- usedBytes: number(),
15311
- availableBytes: number(),
15312
- swapUsedBytes: number(),
15313
- swapTotalBytes: number()
15251
+ var LlmGenerateBaseInputSchema = object({
15252
+ /** Collection routing (the notification-output posture). */
15253
+ addonId: string().optional(),
15254
+ /** Explicit profile; else the resolution chain (spec §3). */
15255
+ profileId: string().optional(),
15256
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15257
+ consumer: string(),
15258
+ system: string().optional(),
15259
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
15260
+ prompt: string(),
15261
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15262
+ jsonSchema: record(string(), unknown()).optional(),
15263
+ /** Per-call override of the profile default. */
15264
+ maxTokens: number().int().positive().optional(),
15265
+ temperature: number().optional()
15314
15266
  });
15315
- var DiskIoSnapshotSchema = object({
15316
- readBytes: number(),
15317
- writeBytes: number(),
15318
- readOps: number(),
15319
- writeOps: number(),
15320
- timestampMs: number()
15321
- });
15322
- var NetworkIoSnapshotSchema = object({
15323
- rxBytes: number(),
15324
- txBytes: number(),
15325
- rxPackets: number(),
15326
- txPackets: number(),
15327
- rxErrors: number(),
15328
- txErrors: number(),
15329
- timestampMs: number()
15330
- });
15331
- var MetricsGpuInfoSchema = object({
15332
- utilization: number(),
15333
- model: string(),
15334
- memoryUsedBytes: number(),
15335
- memoryTotalBytes: number(),
15336
- temperature: number().nullable()
15337
- });
15338
- var ProcessResourceInfoSchema = object({
15339
- openFds: number(),
15340
- threadCount: number(),
15341
- activeHandles: number(),
15342
- activeRequests: number()
15343
- });
15344
- var PressureAvgsSchema = object({
15345
- avg10: number(),
15346
- avg60: number(),
15347
- avg300: number()
15348
- });
15349
- var PressureInfoSchema = object({
15350
- some: PressureAvgsSchema,
15351
- full: PressureAvgsSchema.nullable()
15352
- });
15353
- var SystemResourceSnapshotSchema = object({
15354
- cpu: CpuBreakdownSchema,
15355
- memory: MemoryInfoSchema,
15356
- gpu: MetricsGpuInfoSchema.nullable(),
15357
- network: NetworkIoSnapshotSchema,
15358
- disk: DiskIoSnapshotSchema,
15359
- pressure: object({
15360
- cpu: PressureInfoSchema.nullable(),
15361
- memory: PressureInfoSchema.nullable(),
15362
- io: PressureInfoSchema.nullable()
15267
+ /**
15268
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15269
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15270
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15271
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15272
+ * this only through the `llm` cap's methods.
15273
+ *
15274
+ * One running llama-server child per node in v1 (models are RAM-heavy).
15275
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15276
+ * watchdog — operator decision #3).
15277
+ */
15278
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
15279
+ object({
15280
+ kind: literal("catalog"),
15281
+ catalogId: string()
15363
15282
  }),
15364
- process: ProcessResourceInfoSchema,
15365
- cpuTemperature: number().nullable(),
15366
- timestampMs: number()
15367
- });
15368
- var DiskSpaceInfoSchema = object({
15369
- path: string(),
15370
- totalBytes: number(),
15371
- usedBytes: number(),
15372
- availableBytes: number(),
15373
- percent: number()
15374
- });
15375
- var PidResourceStatsSchema = object({
15376
- pid: number(),
15377
- cpu: number(),
15378
- memory: number(),
15379
- /**
15380
- * Private (anonymous) resident bytes — the per-process V8 heap + native
15381
- * allocations NOT shared with other processes (Linux RssAnon). This is the
15382
- * "real" per-runner cost; summing it across runners is meaningful, unlike
15383
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
15384
- * Undefined where /proc is unavailable (e.g. macOS).
15385
- */
15386
- privateBytes: number().optional(),
15387
- /**
15388
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15389
- * code shared copy-on-write across runners. Undefined on macOS.
15390
- */
15391
- sharedBytes: number().optional()
15283
+ object({
15284
+ kind: literal("url"),
15285
+ url: string(),
15286
+ sha256: string().optional()
15287
+ }),
15288
+ object({
15289
+ kind: literal("path"),
15290
+ path: string()
15291
+ })
15292
+ ]);
15293
+ var ManagedRuntimeConfigSchema = object({
15294
+ /** WHERE the runtime lives — hub or any agent. */
15295
+ nodeId: string(),
15296
+ /** Closed for v1; 'ollama' is a v2 candidate. */
15297
+ engine: _enum(["llama-cpp"]),
15298
+ model: ManagedModelRefSchema,
15299
+ contextSize: number().int().default(4096),
15300
+ /** 0 = CPU-only. */
15301
+ gpuLayers: number().int().default(0),
15302
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15303
+ threads: number().int().optional(),
15304
+ /** Concurrent slots. */
15305
+ parallel: number().int().default(1),
15306
+ /** Else lazy: first generate boots it. */
15307
+ autoStart: boolean().default(false),
15308
+ /** 0 = never; frees RAM after quiet periods. */
15309
+ idleStopMinutes: number().int().default(30)
15392
15310
  });
15393
- var AddonInstanceSchema = object({
15394
- addonId: string(),
15311
+ var LlmRuntimeStatusSchema = object({
15312
+ /** Status is ALWAYS node-qualified. */
15395
15313
  nodeId: string(),
15396
- role: _enum(["hub", "worker"]),
15397
- pid: number(),
15398
15314
  state: _enum([
15399
- "starting",
15400
- "running",
15401
- "stopping",
15402
15315
  "stopped",
15403
- "crashed"
15404
- ]),
15405
- uptimeSec: number()
15406
- });
15407
- var NodeProcessSchema = object({
15408
- pid: number(),
15409
- ppid: number(),
15410
- pgid: number(),
15411
- classification: _enum([
15412
- "root",
15413
- "managed",
15414
- "system",
15415
- "ghost"
15316
+ "downloading",
15317
+ "starting",
15318
+ "ready",
15319
+ "crashed",
15320
+ "failed"
15416
15321
  ]),
15417
- /** `$process` addon binding when `managed`, else null. */
15418
- addonId: string().nullable(),
15419
- /** Kernel-reported nodeId when the process is a known agent/worker. */
15420
- nodeId: string().nullable(),
15421
- /** Truncated command line. */
15422
- command: string(),
15423
- cpuPercent: number(),
15424
- memoryRssBytes: number(),
15425
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15426
- uptimeSec: number(),
15427
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15428
- orphaned: boolean()
15429
- });
15430
- var KillProcessInputSchema = object({
15431
- pid: number(),
15432
- /** Force = SIGKILL. Default is SIGTERM. */
15433
- force: boolean().optional()
15434
- });
15435
- var KillProcessResultSchema = object({
15436
- success: boolean(),
15437
- reason: string().optional(),
15438
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15439
- });
15440
- var DumpHeapSnapshotInputSchema = object({
15441
- /** The addon whose runner should dump a heap snapshot. */
15442
- addonId: string() });
15443
- var DumpHeapSnapshotResultSchema = object({
15444
- success: boolean(),
15445
- /** Path of the written .heapsnapshot inside the runner's container/host. */
15446
- path: string().optional(),
15447
- /** Process pid that was signalled. */
15448
15322
  pid: number().optional(),
15449
- reason: string().optional()
15323
+ port: number().optional(),
15324
+ modelPath: string().optional(),
15325
+ modelId: string().optional(),
15326
+ downloadProgress: number().min(0).max(1).optional(),
15327
+ lastError: string().optional(),
15328
+ crashesInWindow: number(),
15329
+ /** Child RSS (sampled best-effort). */
15330
+ memoryBytes: number().optional(),
15331
+ vramBytes: number().optional()
15450
15332
  });
15451
- var SystemMetricsSchema = object({
15452
- cpuPercent: number(),
15453
- memoryPercent: number(),
15454
- memoryUsedMB: number(),
15455
- memoryTotalMB: number(),
15456
- diskPercent: number().optional(),
15457
- temperature: number().optional(),
15458
- gpuPercent: number().optional(),
15459
- gpuMemoryPercent: number().optional()
15333
+ var LlmNodeModelSchema = object({
15334
+ file: string(),
15335
+ sizeBytes: number(),
15336
+ catalogId: string().optional(),
15337
+ installedAt: number().optional()
15460
15338
  });
15461
- 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, {
15339
+ var LlmRuntimeDiskUsageSchema = object({
15340
+ nodeId: string(),
15341
+ modelsBytes: number(),
15342
+ freeBytes: number().optional()
15343
+ });
15344
+ method(LlmGenerateBaseInputSchema.extend({
15345
+ images: array(LlmImageSchema).optional(),
15346
+ runtime: ManagedRuntimeConfigSchema,
15347
+ /** The managed profile's timeout, threaded by the hub provider. */
15348
+ timeoutMs: number().int().positive().optional()
15349
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15462
15350
  kind: "mutation",
15463
15351
  auth: "admin"
15464
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15352
+ }), method(object({}), _void(), {
15465
15353
  kind: "mutation",
15466
15354
  auth: "admin"
15467
- });
15468
- method(object({
15469
- sourceUrl: string(),
15470
- metadata: ModelConvertMetadataSchema,
15471
- targets: array(ConvertTargetSchema).min(1).readonly(),
15472
- calibrationRef: string().optional(),
15473
- sessionId: string().optional()
15474
- }), ConvertResultSchema, {
15355
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15475
15356
  kind: "mutation",
15476
- auth: "admin",
15477
- timeoutMs: 6e5
15478
- });
15479
- method(object({
15480
- nodeId: string(),
15481
- modelId: string(),
15482
- format: _enum(MODEL_FORMATS),
15483
- entry: ModelCatalogEntrySchema
15484
- }), object({
15485
- ok: boolean(),
15486
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
15487
- sha256: string(),
15488
- bytes: number(),
15489
- /** The target node's modelsDir the artifact landed in. */
15490
- path: string()
15491
- }), {
15357
+ auth: "admin"
15358
+ }), method(object({ file: string() }), _void(), {
15492
15359
  kind: "mutation",
15493
15360
  auth: "admin"
15494
- });
15361
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15495
15362
  /**
15496
- * `mqtt-broker` — broker-registry cap.
15497
- *
15498
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15499
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15500
- * and (b) the connection details a consumer addon needs to spin up
15501
- * its OWN `mqtt.js` client.
15363
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15364
+ * methods concat-fan across providers; single-row methods route to ONE
15365
+ * provider by the `addonId` in the call input (the notification-output
15366
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15367
+ * (hub-placed); the cap stays open for future providers.
15502
15368
  *
15503
- * Why: pub/sub routing over the system event-bus loses fidelity
15504
- * (callback shape, QoS guarantees, will/retain semantics) and adds
15505
- * refcount bookkeeping that addons would rather own themselves. The
15369
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15370
+ * `apiKey` is a password field providers REDACT it on read and merge on
15371
+ * write; a stored key NEVER round-trips to a client.
15372
+ */
15373
+ var LlmProfileKindSchema = _enum([
15374
+ "openai-compatible",
15375
+ "openai",
15376
+ "anthropic",
15377
+ "google",
15378
+ "managed-local"
15379
+ ]);
15380
+ var LlmProfileSchema = object({
15381
+ id: string(),
15382
+ name: string(),
15383
+ kind: LlmProfileKindSchema,
15384
+ /** Stamped by the provider — keeps the fanned catalog routable. */
15385
+ addonId: string(),
15386
+ enabled: boolean(),
15387
+ /** Vendor model id, or the managed runtime's loaded model. */
15388
+ model: string(),
15389
+ /** Required for openai-compatible; override for cloud kinds. */
15390
+ baseUrl: string().optional(),
15391
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
15392
+ apiKey: string().optional(),
15393
+ supportsVision: boolean(),
15394
+ temperature: number().min(0).max(2).optional(),
15395
+ maxTokens: number().int().positive().optional(),
15396
+ timeoutMs: number().int().positive().default(6e4),
15397
+ extraHeaders: record(string(), string()).optional(),
15398
+ /** kind === 'managed-local' only (spec §4). */
15399
+ runtime: ManagedRuntimeConfigSchema.optional()
15400
+ });
15401
+ /** ConfigUISchema tree passed through untyped on the wire (the
15402
+ * notification-output `ConfigSchemaPassthrough` precedent at
15403
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15404
+ var ConfigSchemaPassthrough$1 = unknown();
15405
+ var LlmProfileKindDescriptorSchema = object({
15406
+ kind: LlmProfileKindSchema,
15407
+ label: string(),
15408
+ icon: string(),
15409
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
15410
+ addonId: string(),
15411
+ configSchema: ConfigSchemaPassthrough$1
15412
+ });
15413
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15414
+ var LlmDefaultSchema = object({
15415
+ selector: LlmDefaultSelectorSchema,
15416
+ profileId: string()
15417
+ });
15418
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
15419
+ var LlmUsageRollupSchema = object({
15420
+ day: string(),
15421
+ consumer: string(),
15422
+ profileId: string(),
15423
+ calls: number(),
15424
+ okCalls: number(),
15425
+ errorCalls: number(),
15426
+ inputTokens: number(),
15427
+ outputTokens: number(),
15428
+ avgLatencyMs: number()
15429
+ });
15430
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15431
+ var ManagedModelCatalogEntrySchema = object({
15432
+ id: string(),
15433
+ label: string(),
15434
+ family: string(),
15435
+ purpose: _enum(["text", "vision"]),
15436
+ url: string(),
15437
+ sha256: string(),
15438
+ sizeBytes: number(),
15439
+ quantization: string(),
15440
+ /** Load-time guidance shown in the picker. */
15441
+ minRamBytes: number(),
15442
+ contextSizeDefault: number().int(),
15443
+ /** Vision models: companion projector file. */
15444
+ mmprojUrl: string().optional()
15445
+ });
15446
+ var LlmRuntimeNodeSchema = object({
15447
+ nodeId: string(),
15448
+ reachable: boolean(),
15449
+ status: LlmRuntimeStatusSchema.optional(),
15450
+ disk: LlmRuntimeDiskUsageSchema.optional(),
15451
+ error: string().optional()
15452
+ });
15453
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
15454
+ var ProfileRefInputSchema = object({
15455
+ addonId: string(),
15456
+ profileId: string()
15457
+ });
15458
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
15459
+ kind: "mutation",
15460
+ auth: "admin"
15461
+ }), method(ProfileRefInputSchema, _void(), {
15462
+ kind: "mutation",
15463
+ auth: "admin"
15464
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
15465
+ kind: "mutation",
15466
+ auth: "admin"
15467
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
15468
+ selector: LlmDefaultSelectorSchema,
15469
+ profileId: string().nullable()
15470
+ }), _void(), {
15471
+ kind: "mutation",
15472
+ auth: "admin"
15473
+ }), method(object({
15474
+ since: number().optional(),
15475
+ until: number().optional(),
15476
+ consumer: string().optional(),
15477
+ profileId: string().optional()
15478
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
15479
+ nodeId: string(),
15480
+ model: ManagedModelRefSchema
15481
+ }), _void(), {
15482
+ kind: "mutation",
15483
+ auth: "admin"
15484
+ }), method(object({
15485
+ nodeId: string(),
15486
+ file: string()
15487
+ }), _void(), {
15488
+ kind: "mutation",
15489
+ auth: "admin"
15490
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
15491
+ kind: "mutation",
15492
+ auth: "admin"
15493
+ }), method(ProfileRefInputSchema, _void(), {
15494
+ kind: "mutation",
15495
+ auth: "admin"
15496
+ });
15497
+ var LogLevelSchema = _enum([
15498
+ "debug",
15499
+ "info",
15500
+ "warn",
15501
+ "error"
15502
+ ]);
15503
+ var LogEntrySchema = object({
15504
+ timestamp: date(),
15505
+ level: LogLevelSchema,
15506
+ scope: array(string()),
15507
+ message: string(),
15508
+ meta: record(string(), unknown()).optional(),
15509
+ tags: record(string(), string()).optional()
15510
+ });
15511
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15512
+ scope: array(string()).optional(),
15513
+ level: LogLevelSchema.optional(),
15514
+ since: date().optional(),
15515
+ until: date().optional(),
15516
+ limit: number().optional(),
15517
+ tags: record(string(), string()).optional()
15518
+ }), array(LogEntrySchema).readonly());
15519
+ /**
15520
+ * `login-method` — collection cap through which auth addons contribute
15521
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
15522
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
15523
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
15524
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
15525
+ * procedure aggregates them for the unauthenticated login page.
15526
+ *
15527
+ * A contribution is a discriminated union on `kind`:
15528
+ *
15529
+ * - `redirect` — a declarative button. The login page renders a generic
15530
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
15531
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
15532
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
15533
+ * login page needs NO change.
15534
+ *
15535
+ * - `widget` — a Module-Federation widget the login page mounts (via
15536
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
15537
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
15538
+ * mechanism kept for future use; no shipped addon uses it on the login
15539
+ * page (the passkey ceremony below runs natively in the shell instead).
15540
+ *
15541
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
15542
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
15543
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
15544
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
15545
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
15546
+ * fetching any remote code pre-auth. Contribution stays unconditional —
15547
+ * enrollment state is never leaked pre-auth; visibility is a shell
15548
+ * decision.
15549
+ *
15550
+ * Every contribution carries a `stage`:
15551
+ * - `primary` — shown on the first credentials screen (OIDC /
15552
+ * magic-link buttons; a future usernameless passkey).
15553
+ * - `second-factor` — shown AFTER the password leg, gated on the
15554
+ * returned `factors` (passkey-as-2FA today).
15555
+ *
15556
+ * `mount: skip` — the cap is read server-side by the core auth router
15557
+ * (`registry.getCollection('login-method')`), never mounted as its own
15558
+ * tRPC router.
15559
+ */
15560
+ /** When a login method renders in the two-phase login flow. */
15561
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
15562
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
15563
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
15564
+ object({
15565
+ kind: literal("redirect"),
15566
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
15567
+ id: string(),
15568
+ /** Operator-facing button label. */
15569
+ label: string(),
15570
+ /** lucide-react icon name. */
15571
+ icon: string().optional(),
15572
+ /** Addon-owned HTTP route the button navigates to (GET). */
15573
+ startUrl: string(),
15574
+ stage: LoginStageEnum
15575
+ }),
15576
+ object({
15577
+ kind: literal("widget"),
15578
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
15579
+ id: string(),
15580
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
15581
+ addonId: string(),
15582
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
15583
+ bundle: string(),
15584
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
15585
+ remote: WidgetRemoteSchema,
15586
+ stage: LoginStageEnum
15587
+ }),
15588
+ object({
15589
+ kind: literal("passkey"),
15590
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
15591
+ id: string(),
15592
+ /** Operator-facing button label. */
15593
+ label: string(),
15594
+ stage: LoginStageEnum,
15595
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
15596
+ rpId: string(),
15597
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
15598
+ origin: string().nullable()
15599
+ })
15600
+ ]);
15601
+ method(_void(), array(LoginMethodContributionSchema).readonly());
15602
+ var CpuBreakdownSchema = object({
15603
+ total: number(),
15604
+ user: number(),
15605
+ system: number(),
15606
+ irq: number(),
15607
+ nice: number(),
15608
+ loadAvg: tuple([
15609
+ number(),
15610
+ number(),
15611
+ number()
15612
+ ]),
15613
+ cores: number()
15614
+ });
15615
+ var MemoryInfoSchema = object({
15616
+ percent: number(),
15617
+ totalBytes: number(),
15618
+ usedBytes: number(),
15619
+ availableBytes: number(),
15620
+ swapUsedBytes: number(),
15621
+ swapTotalBytes: number()
15622
+ });
15623
+ var DiskIoSnapshotSchema = object({
15624
+ readBytes: number(),
15625
+ writeBytes: number(),
15626
+ readOps: number(),
15627
+ writeOps: number(),
15628
+ timestampMs: number()
15629
+ });
15630
+ var NetworkIoSnapshotSchema = object({
15631
+ rxBytes: number(),
15632
+ txBytes: number(),
15633
+ rxPackets: number(),
15634
+ txPackets: number(),
15635
+ rxErrors: number(),
15636
+ txErrors: number(),
15637
+ timestampMs: number()
15638
+ });
15639
+ var MetricsGpuInfoSchema = object({
15640
+ utilization: number(),
15641
+ model: string(),
15642
+ memoryUsedBytes: number(),
15643
+ memoryTotalBytes: number(),
15644
+ temperature: number().nullable()
15645
+ });
15646
+ var ProcessResourceInfoSchema = object({
15647
+ openFds: number(),
15648
+ threadCount: number(),
15649
+ activeHandles: number(),
15650
+ activeRequests: number()
15651
+ });
15652
+ var PressureAvgsSchema = object({
15653
+ avg10: number(),
15654
+ avg60: number(),
15655
+ avg300: number()
15656
+ });
15657
+ var PressureInfoSchema = object({
15658
+ some: PressureAvgsSchema,
15659
+ full: PressureAvgsSchema.nullable()
15660
+ });
15661
+ var SystemResourceSnapshotSchema = object({
15662
+ cpu: CpuBreakdownSchema,
15663
+ memory: MemoryInfoSchema,
15664
+ gpu: MetricsGpuInfoSchema.nullable(),
15665
+ network: NetworkIoSnapshotSchema,
15666
+ disk: DiskIoSnapshotSchema,
15667
+ pressure: object({
15668
+ cpu: PressureInfoSchema.nullable(),
15669
+ memory: PressureInfoSchema.nullable(),
15670
+ io: PressureInfoSchema.nullable()
15671
+ }),
15672
+ process: ProcessResourceInfoSchema,
15673
+ cpuTemperature: number().nullable(),
15674
+ timestampMs: number()
15675
+ });
15676
+ var DiskSpaceInfoSchema = object({
15677
+ path: string(),
15678
+ totalBytes: number(),
15679
+ usedBytes: number(),
15680
+ availableBytes: number(),
15681
+ percent: number()
15682
+ });
15683
+ var PidResourceStatsSchema = object({
15684
+ pid: number(),
15685
+ cpu: number(),
15686
+ memory: number(),
15687
+ /**
15688
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
15689
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
15690
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
15691
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
15692
+ * Undefined where /proc is unavailable (e.g. macOS).
15693
+ */
15694
+ privateBytes: number().optional(),
15695
+ /**
15696
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15697
+ * code shared copy-on-write across runners. Undefined on macOS.
15698
+ */
15699
+ sharedBytes: number().optional()
15700
+ });
15701
+ var AddonInstanceSchema = object({
15702
+ addonId: string(),
15703
+ nodeId: string(),
15704
+ role: _enum(["hub", "worker"]),
15705
+ pid: number(),
15706
+ state: _enum([
15707
+ "starting",
15708
+ "running",
15709
+ "stopping",
15710
+ "stopped",
15711
+ "crashed"
15712
+ ]),
15713
+ uptimeSec: number()
15714
+ });
15715
+ var NodeProcessSchema = object({
15716
+ pid: number(),
15717
+ ppid: number(),
15718
+ pgid: number(),
15719
+ classification: _enum([
15720
+ "root",
15721
+ "managed",
15722
+ "system",
15723
+ "ghost"
15724
+ ]),
15725
+ /** `$process` addon binding when `managed`, else null. */
15726
+ addonId: string().nullable(),
15727
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
15728
+ nodeId: string().nullable(),
15729
+ /** Truncated command line. */
15730
+ command: string(),
15731
+ cpuPercent: number(),
15732
+ memoryRssBytes: number(),
15733
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15734
+ uptimeSec: number(),
15735
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15736
+ orphaned: boolean()
15737
+ });
15738
+ var KillProcessInputSchema = object({
15739
+ pid: number(),
15740
+ /** Force = SIGKILL. Default is SIGTERM. */
15741
+ force: boolean().optional()
15742
+ });
15743
+ var KillProcessResultSchema = object({
15744
+ success: boolean(),
15745
+ reason: string().optional(),
15746
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15747
+ });
15748
+ var DumpHeapSnapshotInputSchema = object({
15749
+ /** The addon whose runner should dump a heap snapshot. */
15750
+ addonId: string() });
15751
+ var DumpHeapSnapshotResultSchema = object({
15752
+ success: boolean(),
15753
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
15754
+ path: string().optional(),
15755
+ /** Process pid that was signalled. */
15756
+ pid: number().optional(),
15757
+ reason: string().optional()
15758
+ });
15759
+ var SystemMetricsSchema = object({
15760
+ cpuPercent: number(),
15761
+ memoryPercent: number(),
15762
+ memoryUsedMB: number(),
15763
+ memoryTotalMB: number(),
15764
+ diskPercent: number().optional(),
15765
+ temperature: number().optional(),
15766
+ gpuPercent: number().optional(),
15767
+ gpuMemoryPercent: number().optional()
15768
+ });
15769
+ 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, {
15770
+ kind: "mutation",
15771
+ auth: "admin"
15772
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15773
+ kind: "mutation",
15774
+ auth: "admin"
15775
+ });
15776
+ method(object({
15777
+ sourceUrl: string(),
15778
+ metadata: ModelConvertMetadataSchema,
15779
+ targets: array(ConvertTargetSchema).min(1).readonly(),
15780
+ calibrationRef: string().optional(),
15781
+ sessionId: string().optional()
15782
+ }), ConvertResultSchema, {
15783
+ kind: "mutation",
15784
+ auth: "admin",
15785
+ timeoutMs: 6e5
15786
+ });
15787
+ method(object({
15788
+ nodeId: string(),
15789
+ modelId: string(),
15790
+ format: _enum(MODEL_FORMATS),
15791
+ entry: ModelCatalogEntrySchema
15792
+ }), object({
15793
+ ok: boolean(),
15794
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
15795
+ sha256: string(),
15796
+ bytes: number(),
15797
+ /** The target node's modelsDir the artifact landed in. */
15798
+ path: string()
15799
+ }), {
15800
+ kind: "mutation",
15801
+ auth: "admin"
15802
+ });
15803
+ /**
15804
+ * `mqtt-broker` — broker-registry cap.
15805
+ *
15806
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15807
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15808
+ * and (b) the connection details a consumer addon needs to spin up
15809
+ * its OWN `mqtt.js` client.
15810
+ *
15811
+ * Why: pub/sub routing over the system event-bus loses fidelity
15812
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
15813
+ * refcount bookkeeping that addons would rather own themselves. The
15506
15814
  * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
15507
15815
  * features anyway — give it the connection config, get out of the way.
15508
15816
  *
@@ -15747,392 +16055,588 @@ var TargetKindLevelSchema = object({
15747
16055
  ordinal: number().int().min(1).max(5).nullable(),
15748
16056
  flags: object({
15749
16057
  critical: boolean().optional(),
15750
- silent: boolean().optional(),
15751
- noPush: boolean().optional()
15752
- }).optional(),
15753
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
15754
- requires: array(string()).optional(),
15755
- description: string().optional()
15756
- });
15757
- /** The full capability block consulted before dispatch. */
15758
- var TargetKindCapsSchema = object({
15759
- attachments: object({
15760
- mediaTypes: array(AttachmentMediaTypeSchema),
15761
- mode: _enum([
15762
- "url",
15763
- "bytes",
15764
- "both"
15765
- ]),
15766
- max: number().int().nonnegative(),
15767
- maxBytes: number().int().positive().optional()
15768
- }),
15769
- /** Max action buttons (0 = none). */
15770
- actions: number().int().nonnegative(),
15771
- levels: array(TargetKindLevelSchema),
15772
- format: array(NotificationFormatSchema),
15773
- clickUrl: boolean(),
15774
- sound: boolean(),
15775
- ttl: boolean(),
15776
- bodyMaxLen: number().int().positive()
15777
- });
15778
- /**
15779
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
15780
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
15781
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
15782
- * the union is large and not meant for runtime validation here; the exported
15783
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
15784
- */
15785
- var ConfigSchemaPassthrough$1 = unknown();
15786
- var TargetKindSchema = object({
15787
- kind: string(),
15788
- label: string(),
15789
- icon: string(),
15790
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
15791
- addonId: string(),
15792
- configSchema: ConfigSchemaPassthrough$1,
15793
- supportsDiscovery: boolean(),
15794
- caps: TargetKindCapsSchema
15795
- });
15796
- /**
15797
- * A persisted target. `config` holds secrets; providers REDACT secret fields
15798
- * (return a presence marker only) when serving `listTargets` — never
15799
- * round-trip a stored secret to the UI.
15800
- */
15801
- var TargetSchema = object({
15802
- id: string(),
15803
- name: string(),
15804
- kind: string(),
15805
- addonId: string(),
15806
- enabled: boolean(),
15807
- config: record(string(), unknown())
15808
- });
15809
- /** A discovery-surfaced candidate (config is partial + non-secret). */
15810
- var DiscoveredTargetSchema = object({
15811
- kind: string(),
15812
- suggestedName: string(),
15813
- config: record(string(), unknown())
15814
- });
15815
- /** The degrade engine's report — what was resolved / dropped / degraded. */
15816
- var RenderedAsSchema = object({
15817
- level: string(),
15818
- format: NotificationFormatSchema,
15819
- attachmentsSent: number().int().nonnegative(),
15820
- actionsSent: number().int().nonnegative(),
15821
- truncated: boolean(),
15822
- dropped: array(string())
15823
- });
15824
- var SendResultSchema = object({
15825
- success: boolean(),
15826
- error: string().optional(),
15827
- renderedAs: RenderedAsSchema.optional()
15828
- });
15829
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
15830
- var TestResultSchema = SendResultSchema;
15831
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
15832
- kind: string(),
15833
- config: record(string(), unknown()).optional()
15834
- }), array(DiscoveredTargetSchema)), method(object({
15835
- targetId: string(),
15836
- notification: NotificationSchema
15837
- }), SendResultSchema, { kind: "mutation" }), method(object({
15838
- targetId: string(),
15839
- sample: NotificationSchema.optional()
15840
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
15841
- targetId: string(),
15842
- enabled: boolean()
15843
- }), _void(), { kind: "mutation" });
15844
- /**
15845
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15846
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15847
- * caps stay wire-compatible without a circular cap→cap import.
15848
- *
15849
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
15850
- * every transport tier structurally, and failed calls still write usage rows.
15851
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15852
- */
15853
- var LlmUsageSchema = object({
15854
- inputTokens: number(),
15855
- outputTokens: number()
15856
- });
15857
- var LlmErrorCodeSchema = _enum([
15858
- "timeout",
15859
- "rate-limited",
15860
- "auth",
15861
- "refusal",
15862
- "bad-request",
15863
- "unavailable",
15864
- "no-profile",
15865
- "budget-exceeded",
15866
- "adapter-error"
15867
- ]);
15868
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15869
- ok: literal(true),
15870
- text: string(),
15871
- model: string(),
15872
- usage: LlmUsageSchema,
15873
- truncated: boolean(),
15874
- latencyMs: number()
15875
- }), object({
15876
- ok: literal(false),
15877
- code: LlmErrorCodeSchema,
15878
- message: string(),
15879
- retryAfterMs: number().optional()
15880
- })]);
15881
- /**
15882
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15883
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15884
- * notification-output.cap.ts:27-31 precedents).
15885
- */
15886
- var LlmImageSchema = object({
15887
- bytes: _instanceof(Uint8Array),
15888
- mimeType: string()
15889
- });
15890
- var LlmGenerateBaseInputSchema = object({
15891
- /** Collection routing (the notification-output posture). */
15892
- addonId: string().optional(),
15893
- /** Explicit profile; else the resolution chain (spec §3). */
15894
- profileId: string().optional(),
15895
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15896
- consumer: string(),
15897
- system: string().optional(),
15898
- /** v1: single-turn. `messages[]` is a v2 additive field. */
15899
- prompt: string(),
15900
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15901
- jsonSchema: record(string(), unknown()).optional(),
15902
- /** Per-call override of the profile default. */
15903
- maxTokens: number().int().positive().optional(),
15904
- temperature: number().optional()
15905
- });
15906
- /**
15907
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15908
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15909
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15910
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15911
- * this only through the `llm` cap's methods.
15912
- *
15913
- * One running llama-server child per node in v1 (models are RAM-heavy).
15914
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15915
- * watchdog — operator decision #3).
15916
- */
15917
- var ManagedModelRefSchema = discriminatedUnion("kind", [
15918
- object({
15919
- kind: literal("catalog"),
15920
- catalogId: string()
15921
- }),
15922
- object({
15923
- kind: literal("url"),
15924
- url: string(),
15925
- sha256: string().optional()
15926
- }),
15927
- object({
15928
- kind: literal("path"),
15929
- path: string()
15930
- })
15931
- ]);
15932
- var ManagedRuntimeConfigSchema = object({
15933
- /** WHERE the runtime lives — hub or any agent. */
15934
- nodeId: string(),
15935
- /** Closed for v1; 'ollama' is a v2 candidate. */
15936
- engine: _enum(["llama-cpp"]),
15937
- model: ManagedModelRefSchema,
15938
- contextSize: number().int().default(4096),
15939
- /** 0 = CPU-only. */
15940
- gpuLayers: number().int().default(0),
15941
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15942
- threads: number().int().optional(),
15943
- /** Concurrent slots. */
15944
- parallel: number().int().default(1),
15945
- /** Else lazy: first generate boots it. */
15946
- autoStart: boolean().default(false),
15947
- /** 0 = never; frees RAM after quiet periods. */
15948
- idleStopMinutes: number().int().default(30)
15949
- });
15950
- var LlmRuntimeStatusSchema = object({
15951
- /** Status is ALWAYS node-qualified. */
15952
- nodeId: string(),
15953
- state: _enum([
15954
- "stopped",
15955
- "downloading",
15956
- "starting",
15957
- "ready",
15958
- "crashed",
15959
- "failed"
15960
- ]),
15961
- pid: number().optional(),
15962
- port: number().optional(),
15963
- modelPath: string().optional(),
15964
- modelId: string().optional(),
15965
- downloadProgress: number().min(0).max(1).optional(),
15966
- lastError: string().optional(),
15967
- crashesInWindow: number(),
15968
- /** Child RSS (sampled best-effort). */
15969
- memoryBytes: number().optional(),
15970
- vramBytes: number().optional()
16058
+ silent: boolean().optional(),
16059
+ noPush: boolean().optional()
16060
+ }).optional(),
16061
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
16062
+ requires: array(string()).optional(),
16063
+ description: string().optional()
15971
16064
  });
15972
- var LlmNodeModelSchema = object({
15973
- file: string(),
15974
- sizeBytes: number(),
15975
- catalogId: string().optional(),
15976
- installedAt: number().optional()
16065
+ /** The full capability block consulted before dispatch. */
16066
+ var TargetKindCapsSchema = object({
16067
+ attachments: object({
16068
+ mediaTypes: array(AttachmentMediaTypeSchema),
16069
+ mode: _enum([
16070
+ "url",
16071
+ "bytes",
16072
+ "both"
16073
+ ]),
16074
+ max: number().int().nonnegative(),
16075
+ maxBytes: number().int().positive().optional()
16076
+ }),
16077
+ /** Max action buttons (0 = none). */
16078
+ actions: number().int().nonnegative(),
16079
+ levels: array(TargetKindLevelSchema),
16080
+ format: array(NotificationFormatSchema),
16081
+ clickUrl: boolean(),
16082
+ sound: boolean(),
16083
+ ttl: boolean(),
16084
+ bodyMaxLen: number().int().positive()
15977
16085
  });
15978
- var LlmRuntimeDiskUsageSchema = object({
15979
- nodeId: string(),
15980
- modelsBytes: number(),
15981
- freeBytes: number().optional()
16086
+ /**
16087
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
16088
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
16089
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
16090
+ * the union is large and not meant for runtime validation here; the exported
16091
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
16092
+ */
16093
+ var ConfigSchemaPassthrough = unknown();
16094
+ var TargetKindSchema = object({
16095
+ kind: string(),
16096
+ label: string(),
16097
+ icon: string(),
16098
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
16099
+ addonId: string(),
16100
+ configSchema: ConfigSchemaPassthrough,
16101
+ supportsDiscovery: boolean(),
16102
+ caps: TargetKindCapsSchema
15982
16103
  });
15983
- method(LlmGenerateBaseInputSchema.extend({
15984
- images: array(LlmImageSchema).optional(),
15985
- runtime: ManagedRuntimeConfigSchema,
15986
- /** The managed profile's timeout, threaded by the hub provider. */
15987
- timeoutMs: number().int().positive().optional()
15988
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15989
- kind: "mutation",
15990
- auth: "admin"
15991
- }), method(object({}), _void(), {
15992
- kind: "mutation",
15993
- auth: "admin"
15994
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15995
- kind: "mutation",
15996
- auth: "admin"
15997
- }), method(object({ file: string() }), _void(), {
15998
- kind: "mutation",
15999
- auth: "admin"
16000
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
16001
16104
  /**
16002
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
16003
- * methods concat-fan across providers; single-row methods route to ONE
16004
- * provider by the `addonId` in the call input (the notification-output
16005
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
16006
- * (hub-placed); the cap stays open for future providers.
16007
- *
16008
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
16009
- * `apiKey` is a password field — providers REDACT it on read and merge on
16010
- * write; a stored key NEVER round-trips to a client.
16105
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
16106
+ * (return a presence marker only) when serving `listTargets` — never
16107
+ * round-trip a stored secret to the UI.
16011
16108
  */
16012
- var LlmProfileKindSchema = _enum([
16013
- "openai-compatible",
16014
- "openai",
16015
- "anthropic",
16016
- "google",
16017
- "managed-local"
16018
- ]);
16019
- var LlmProfileSchema = object({
16109
+ var TargetSchema = object({
16020
16110
  id: string(),
16021
16111
  name: string(),
16022
- kind: LlmProfileKindSchema,
16023
- /** Stamped by the provider — keeps the fanned catalog routable. */
16112
+ kind: string(),
16024
16113
  addonId: string(),
16025
16114
  enabled: boolean(),
16026
- /** Vendor model id, or the managed runtime's loaded model. */
16027
- model: string(),
16028
- /** Required for openai-compatible; override for cloud kinds. */
16029
- baseUrl: string().optional(),
16030
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
16031
- apiKey: string().optional(),
16032
- supportsVision: boolean(),
16033
- temperature: number().min(0).max(2).optional(),
16034
- maxTokens: number().int().positive().optional(),
16035
- timeoutMs: number().int().positive().default(6e4),
16036
- extraHeaders: record(string(), string()).optional(),
16037
- /** kind === 'managed-local' only (spec §4). */
16038
- runtime: ManagedRuntimeConfigSchema.optional()
16115
+ config: record(string(), unknown())
16039
16116
  });
16040
- /** ConfigUISchema tree passed through untyped on the wire (the
16041
- * notification-output `ConfigSchemaPassthrough` precedent at
16042
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
16043
- var ConfigSchemaPassthrough = unknown();
16044
- var LlmProfileKindDescriptorSchema = object({
16045
- kind: LlmProfileKindSchema,
16046
- label: string(),
16047
- icon: string(),
16048
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
16049
- addonId: string(),
16050
- configSchema: ConfigSchemaPassthrough
16117
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
16118
+ var DiscoveredTargetSchema = object({
16119
+ kind: string(),
16120
+ suggestedName: string(),
16121
+ config: record(string(), unknown())
16051
16122
  });
16052
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
16053
- var LlmDefaultSchema = object({
16054
- selector: LlmDefaultSelectorSchema,
16055
- profileId: string()
16123
+ /** The degrade engine's report what was resolved / dropped / degraded. */
16124
+ var RenderedAsSchema = object({
16125
+ level: string(),
16126
+ format: NotificationFormatSchema,
16127
+ attachmentsSent: number().int().nonnegative(),
16128
+ actionsSent: number().int().nonnegative(),
16129
+ truncated: boolean(),
16130
+ dropped: array(string())
16056
16131
  });
16057
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
16058
- var LlmUsageRollupSchema = object({
16059
- day: string(),
16060
- consumer: string(),
16061
- profileId: string(),
16062
- calls: number(),
16063
- okCalls: number(),
16064
- errorCalls: number(),
16065
- inputTokens: number(),
16066
- outputTokens: number(),
16067
- avgLatencyMs: number()
16132
+ var SendResultSchema = object({
16133
+ success: boolean(),
16134
+ error: string().optional(),
16135
+ renderedAs: RenderedAsSchema.optional()
16068
16136
  });
16069
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
16070
- var ManagedModelCatalogEntrySchema = object({
16137
+ /** Same shape as SendResult kept as a distinct name for the test panel. */
16138
+ var TestResultSchema = SendResultSchema;
16139
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
16140
+ kind: string(),
16141
+ config: record(string(), unknown()).optional()
16142
+ }), array(DiscoveredTargetSchema)), method(object({
16143
+ targetId: string(),
16144
+ notification: NotificationSchema
16145
+ }), SendResultSchema, { kind: "mutation" }), method(object({
16146
+ targetId: string(),
16147
+ sample: NotificationSchema.optional()
16148
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
16149
+ targetId: string(),
16150
+ enabled: boolean()
16151
+ }), _void(), { kind: "mutation" });
16152
+ /**
16153
+ * notification-rules — the Notification Center rule surface (P1 core).
16154
+ *
16155
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16156
+ * (operator decisions D-1/D-2/D-3 are binding):
16157
+ *
16158
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16159
+ * `notification-center` module), hooked on the durable persistence
16160
+ * moments (object-event insert, TrackCloser.closeExpired) with a
16161
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
16162
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16163
+ * FIRST persisted detection matching the conditions (per-track dedup,
16164
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16165
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
16166
+ * - DISPATCH stays behind `notification-output` (rules reference targets
16167
+ * by id; per-backend params are a passthrough blob capped by the
16168
+ * target kind's own caps/degrade engine).
16169
+ *
16170
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
16171
+ * server-injected caller identity — the first `caller: 'required'`
16172
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
16173
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
16174
+ * windows, and the optional label/identity/plate matchers. User rules,
16175
+ * private zones, per-recipient fan-out and the wider condition table are
16176
+ * P2+ (see spec §7).
16177
+ *
16178
+ * All schemas here are the single source of truth — `NcRule` etc. are
16179
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16180
+ * schema/interface drift is explicitly not repeated).
16181
+ */
16182
+ /**
16183
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
16184
+ * The value maps 1:1 onto the evaluated record kind:
16185
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16186
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16187
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16188
+ * change of a LINKED device, one row per linked camera)
16189
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16190
+ * delivery / pick-up)
16191
+ *
16192
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16193
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
16194
+ * this one field keeps the schema additive — a rule still declares exactly
16195
+ * one trigger.
16196
+ */
16197
+ var NcDeliverySchema = _enum([
16198
+ "immediate",
16199
+ "track-end",
16200
+ "device-event",
16201
+ "package-event"
16202
+ ]);
16203
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
16204
+ var NcScheduleSchema = object({
16205
+ windows: array(object({
16206
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16207
+ days: array(number().int().min(0).max(6)).min(1),
16208
+ startMinute: number().int().min(0).max(1439),
16209
+ endMinute: number().int().min(0).max(1439)
16210
+ })).min(1),
16211
+ /** IANA timezone; default = hub host timezone. */
16212
+ timezone: string().optional(),
16213
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16214
+ invert: boolean().optional()
16215
+ });
16216
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16217
+ var NcPlateMatcherSchema = object({
16218
+ values: array(string().min(1)).min(1),
16219
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16220
+ maxDistance: number().int().min(0).max(3).default(1)
16221
+ });
16222
+ /**
16223
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16224
+ * occupancy edge for a device — optionally narrowed to a single admin
16225
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16226
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
16227
+ * - `became-free` — count crossed ≥ `count` → below it
16228
+ * - `>=` / `<=` — count is at/over or at/under `count`
16229
+ * `sustainSeconds` requires the condition hold continuously that long
16230
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
16231
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16232
+ * the condition never matches. Confirmed edge-state survives addon restarts
16233
+ * (declared SQLite collection, reseeded on boot).
16234
+ */
16235
+ var NcOccupancyConditionSchema = object({
16236
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16237
+ zoneId: string().optional(),
16238
+ /** Object class to count; absent = any class. */
16239
+ className: string().optional(),
16240
+ op: _enum([
16241
+ "became-occupied",
16242
+ "became-free",
16243
+ ">=",
16244
+ "<="
16245
+ ]).default("became-occupied"),
16246
+ count: number().int().min(0).default(1),
16247
+ sustainSeconds: number().int().min(0).max(3600).default(15)
16248
+ });
16249
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16250
+ var NcZoneConditionSchema = object({
16251
+ ids: array(string().min(1)).min(1),
16252
+ /** Quantifier over `ids` — at least one / every one visited. */
16253
+ match: _enum(["any", "all"]).default("any")
16254
+ });
16255
+ /**
16256
+ * The P1 condition set — a flat AND of groups; absent group = pass;
16257
+ * membership lists are OR within the list (spec §2.3).
16258
+ */
16259
+ var NcConditionsSchema = object({
16260
+ /** Device scope — absent = all devices. */
16261
+ devices: array(number()).optional(),
16262
+ /** Detector class names (any overlap with the record's class set). */
16263
+ classes: array(string().min(1)).optional(),
16264
+ /** Veto classes — any overlap fails the rule. */
16265
+ classesExclude: array(string().min(1)).optional(),
16266
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
16267
+ minConfidence: number().min(0).max(1).optional(),
16268
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
16269
+ zones: NcZoneConditionSchema.optional(),
16270
+ /** Veto zones — any hit fails the rule. */
16271
+ zonesExclude: array(string().min(1)).optional(),
16272
+ /**
16273
+ * Exact (case-insensitive) match on the record's collapsed `label`
16274
+ * (identity name / plate text / subclass).
16275
+ */
16276
+ labelEquals: array(string().min(1)).optional(),
16277
+ /**
16278
+ * Identity matcher. P1 boundary: matched against the record's collapsed
16279
+ * `label` (the identity display name propagated by the face pipeline) —
16280
+ * identity-ID matching rides in P2 when identity ids reach the record.
16281
+ */
16282
+ identities: array(string().min(1)).optional(),
16283
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
16284
+ plates: NcPlateMatcherSchema.optional(),
16285
+ /**
16286
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16287
+ * Same P1 boundary: matched against the record's collapsed `label` (the
16288
+ * identity display name). A record with NO label passes (nothing to
16289
+ * exclude), unlike the include variant which fails on an absent label.
16290
+ */
16291
+ identitiesExclude: array(string().min(1)).optional(),
16292
+ /**
16293
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16294
+ * TRACK-END only: importance is scored at track close, so it does not exist
16295
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16296
+ * close the value is threaded via the close-time info (the `Track` clone is
16297
+ * captured before the DB row is updated, so it would otherwise read stale).
16298
+ * Fails when the record carries no importance (never guess quality — the
16299
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
16300
+ */
16301
+ minImportance: number().min(0).max(1).optional(),
16302
+ /**
16303
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16304
+ * TRACK-END only: an `immediate` / object-event subject has no closed
16305
+ * lifespan, so a dwell condition never matches immediate delivery
16306
+ * (documented choice — the object-event record carries no `firstSeen`,
16307
+ * so dwell cannot be computed from what the subject actually carries).
16308
+ */
16309
+ minDwellSeconds: number().min(0).optional(),
16310
+ /**
16311
+ * Detection provenance filter. `any` (default / absent) matches every
16312
+ * source; otherwise the subject's source must equal it. Legacy records
16313
+ * with no stamped source are treated as `pipeline`. The union spans both
16314
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
16315
+ * tracks carry `sensor`.
16316
+ */
16317
+ source: _enum([
16318
+ "pipeline",
16319
+ "onboard",
16320
+ "sensor",
16321
+ "any"
16322
+ ]).optional(),
16323
+ /**
16324
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16325
+ * detector `minConfidence` (that gates the object-detection score; this
16326
+ * gates the recognition/OCR match score). Fails when the subject carries
16327
+ * no label-match confidence (never guess). TRACK-END only: the confidence
16328
+ * lives on the recognition result and reaches the subject at track close.
16329
+ *
16330
+ * What it measures precisely (plumbed at track close — the closer threads
16331
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16332
+ * `importance`): the BEST recognition match confidence observed for the
16333
+ * label the track carries at close — for a face, the peak cosine similarity
16334
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16335
+ * for a plate, the peak OCR read score of the best-held plate
16336
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16337
+ * one track the higher of the two is used. A track that ended with no
16338
+ * confident identity/plate match carries no value, so the condition fails
16339
+ * closed for it (an un-recognized subject).
16340
+ */
16341
+ minLabelConfidence: number().min(0).max(1).optional(),
16342
+ /**
16343
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16344
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16345
+ * against the token carried on the device-event subject (extracted from the
16346
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16347
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16348
+ * eventType, so gate those with {@link sensorKinds} instead.
16349
+ */
16350
+ eventTypeTokens: array(string().min(1)).optional(),
16351
+ /**
16352
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16353
+ * `contact`, `button`, `device-event`) — matched against the persisted
16354
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16355
+ */
16356
+ sensorKinds: array(string().min(1)).optional(),
16357
+ /**
16358
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16359
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16360
+ * when the subject's phase does not match (a subject always carries a phase
16361
+ * on the package-event trigger).
16362
+ */
16363
+ packagePhase: _enum([
16364
+ "delivered",
16365
+ "picked-up",
16366
+ "both"
16367
+ ]).optional(),
16368
+ /**
16369
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16370
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16371
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
16372
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16373
+ */
16374
+ customZones: array(MaskPolygonShapeSchema).optional(),
16375
+ /**
16376
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16377
+ * (optionally zone/class-scoped) occupancy count crosses the configured
16378
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
16379
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16380
+ */
16381
+ occupancy: NcOccupancyConditionSchema.optional()
16382
+ });
16383
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
16384
+ var NcRuleTargetSchema = object({
16385
+ /** `notification-output` Target id. */
16386
+ targetId: string().min(1),
16387
+ /**
16388
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
16389
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16390
+ * degrade engine drops what the backend can't render.
16391
+ */
16392
+ params: record(string(), unknown()).optional()
16393
+ });
16394
+ /**
16395
+ * Media attachment policy (P1 still-image subset).
16396
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
16397
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
16398
+ * matched on identities attaches the subject's `faceCrop`, one matched on
16399
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
16400
+ * (or when the specific crop is missing) degrades to `best`, then
16401
+ * `keyFrame`, then no attachment — never delaying the send. The matched
16402
+ * condition summary is frozen on the outbox row at enqueue (like the rule
16403
+ * name), so the choice never drifts from the record that fired it.
16404
+ * - `keyFrame` — the clean scene frame (no subject box).
16405
+ * - `none` — no attachment.
16406
+ */
16407
+ var NcMediaPolicySchema = object({ attach: _enum([
16408
+ "best",
16409
+ "best-matching",
16410
+ "keyFrame",
16411
+ "none"
16412
+ ]).default("best") });
16413
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16414
+ var NcThrottleSchema = object({
16415
+ cooldownSec: number().int().min(0).max(86400).default(60),
16416
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16417
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
16418
+ });
16419
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16420
+ var NcRuleInputSchema = object({
16421
+ name: string().min(1).max(200),
16422
+ enabled: boolean().default(true),
16423
+ delivery: NcDeliverySchema,
16424
+ conditions: NcConditionsSchema.default({}),
16425
+ schedule: NcScheduleSchema.optional(),
16426
+ targets: array(NcRuleTargetSchema).min(1),
16427
+ media: NcMediaPolicySchema.default({ attach: "best" }),
16428
+ throttle: NcThrottleSchema.default({
16429
+ cooldownSec: 60,
16430
+ scope: "rule-device"
16431
+ }),
16432
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16433
+ template: object({
16434
+ title: string().max(500).optional(),
16435
+ body: string().max(2e3).optional()
16436
+ }).optional(),
16437
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
16438
+ priority: number().int().min(1).max(5).default(3),
16439
+ /**
16440
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16441
+ * behaviour, visible to all, read-only in the viewer). Present = personal
16442
+ * rule owned by this userId. Server-stamped; never trusted from a client.
16443
+ */
16444
+ ownerUserId: string().optional()
16445
+ });
16446
+ /**
16447
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
16448
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16449
+ * NOT a client-authored input field (it lives on the persisted rule, not the
16450
+ * input), so it is added here explicitly to let the store's per-target opt-out
16451
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16452
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16453
+ * `updateRule` patch.
16454
+ */
16455
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
16456
+ /** A persisted rule. */
16457
+ var NcRuleSchema = NcRuleInputSchema.extend({
16458
+ id: string(),
16459
+ /** userId of the admin who created the rule (server-stamped caller). */
16460
+ createdBy: string(),
16461
+ createdAt: number(),
16462
+ updatedAt: number(),
16463
+ /**
16464
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16465
+ * send time. Only a target's OWNER may add/remove its id (server-checked
16466
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
16467
+ */
16468
+ disabledTargetIds: array(string()).default([])
16469
+ });
16470
+ var NcTestResultSchema = object({
16471
+ recordId: string(),
16472
+ recordKind: _enum([
16473
+ "object-event",
16474
+ "track",
16475
+ "device-event",
16476
+ "package-event"
16477
+ ]),
16478
+ deviceId: number(),
16479
+ timestamp: number(),
16480
+ wouldFire: boolean(),
16481
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
16482
+ failedCondition: string().optional(),
16483
+ className: string().optional(),
16484
+ label: string().optional()
16485
+ });
16486
+ var NcConditionDescriptorSchema = object({
16487
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16071
16488
  id: string(),
16489
+ group: _enum([
16490
+ "scope",
16491
+ "class",
16492
+ "zones",
16493
+ "quality",
16494
+ "label",
16495
+ "schedule",
16496
+ "device",
16497
+ "package",
16498
+ "occupancy"
16499
+ ]),
16072
16500
  label: string(),
16073
- family: string(),
16074
- purpose: _enum(["text", "vision"]),
16075
- url: string(),
16076
- sha256: string(),
16077
- sizeBytes: number(),
16078
- quantization: string(),
16079
- /** Load-time guidance shown in the picker. */
16080
- minRamBytes: number(),
16081
- contextSizeDefault: number().int(),
16082
- /** Vision models: companion projector file. */
16083
- mmprojUrl: string().optional()
16501
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
16502
+ valueType: _enum([
16503
+ "deviceIdList",
16504
+ "stringList",
16505
+ "number01",
16506
+ "number",
16507
+ "sourceSelect",
16508
+ "zoneSelection",
16509
+ "zoneIdList",
16510
+ "schedule",
16511
+ "plateMatcher",
16512
+ "packagePhase",
16513
+ "polygonDraw",
16514
+ "occupancy"
16515
+ ]),
16516
+ operator: _enum([
16517
+ "in",
16518
+ "notIn",
16519
+ "anyOf",
16520
+ "allOf",
16521
+ "gte",
16522
+ "fuzzyIn",
16523
+ "withinSchedule"
16524
+ ]),
16525
+ /** Which delivery kinds the condition applies to. */
16526
+ appliesTo: array(NcDeliverySchema),
16527
+ phase: string(),
16528
+ description: string().optional()
16084
16529
  });
16085
- var LlmRuntimeNodeSchema = object({
16086
- nodeId: string(),
16087
- reachable: boolean(),
16088
- status: LlmRuntimeStatusSchema.optional(),
16089
- disk: LlmRuntimeDiskUsageSchema.optional(),
16090
- error: string().optional()
16530
+ /**
16531
+ * The delivery lifecycle status of a history row — a straight read of the
16532
+ * durable outbox row's own status (single source of truth):
16533
+ * - `pending` — enqueued, in-flight or retrying with backoff
16534
+ * - `sent` — delivered (terminal)
16535
+ * - `dead` — dead-lettered after exhausting retries / a permanent
16536
+ * backend rejection / a deleted target (terminal; carries
16537
+ * the failure `error`)
16538
+ *
16539
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
16540
+ * user dimension (quiet hours / snooze) and are additive when they land.
16541
+ */
16542
+ var NcHistoryStatusSchema = _enum([
16543
+ "pending",
16544
+ "sent",
16545
+ "dead"
16546
+ ]);
16547
+ /** The evaluated record kind a history row descends from (one per trigger). */
16548
+ var NcHistoryRecordKindSchema = _enum([
16549
+ "object-event",
16550
+ "track-end",
16551
+ "device-event",
16552
+ "package-event"
16553
+ ]);
16554
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16555
+ var NcHistorySubjectSchema = object({
16556
+ className: string(),
16557
+ label: string().optional(),
16558
+ confidence: number().optional(),
16559
+ zones: array(string()),
16560
+ timestamp: number()
16561
+ });
16562
+ /**
16563
+ * One delivery-history row. This is a read-only VIEW over the durable
16564
+ * outbox row (single source of truth — the same row the drain loop drives;
16565
+ * NO second write path, so history can never drift from delivery state).
16566
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16567
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16568
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
16569
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16570
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16571
+ * P1 (admin scope only).
16572
+ */
16573
+ var NcHistoryEntrySchema = object({
16574
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16575
+ id: string(),
16576
+ ruleId: string(),
16577
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
16578
+ ruleName: string(),
16579
+ /** The rule urgency/trigger that produced this delivery. */
16580
+ delivery: NcDeliverySchema,
16581
+ targetId: string(),
16582
+ deviceId: number(),
16583
+ recordKind: NcHistoryRecordKindSchema,
16584
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16585
+ recordId: string(),
16586
+ /** Present for track-scoped deliveries (object-event / track-end). */
16587
+ trackId: string().optional(),
16588
+ status: NcHistoryStatusSchema,
16589
+ /** Delivery attempts made so far. */
16590
+ attempts: number().int(),
16591
+ /** Fire time (outbox enqueue). */
16592
+ createdAt: number(),
16593
+ /** Last transition time (terminal for sent / dead). */
16594
+ updatedAt: number(),
16595
+ /** Failure detail — present on a `dead` row. */
16596
+ error: string().optional(),
16597
+ subject: NcHistorySubjectSchema
16091
16598
  });
16092
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16093
- var ProfileRefInputSchema = object({
16094
- addonId: string(),
16095
- profileId: string()
16599
+ /**
16600
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16601
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16602
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16603
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16604
+ */
16605
+ var NcHistoryFilterSchema = object({
16606
+ ruleId: string().optional(),
16607
+ deviceId: number().optional(),
16608
+ status: NcHistoryStatusSchema.optional(),
16609
+ since: number().optional(),
16610
+ until: number().optional(),
16611
+ limit: number().int().min(1).max(500).default(100)
16096
16612
  });
16097
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16098
- kind: "mutation",
16099
- auth: "admin"
16100
- }), method(ProfileRefInputSchema, _void(), {
16613
+ 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 }), {
16101
16614
  kind: "mutation",
16102
- auth: "admin"
16103
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16615
+ auth: "admin",
16616
+ caller: "required"
16617
+ }), method(object({
16618
+ ruleId: string(),
16619
+ patch: NcRulePatchSchema
16620
+ }), object({ rule: NcRuleSchema }), {
16104
16621
  kind: "mutation",
16105
- auth: "admin"
16106
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
16107
- selector: LlmDefaultSelectorSchema,
16108
- profileId: string().nullable()
16109
- }), _void(), {
16622
+ auth: "admin",
16623
+ caller: "required"
16624
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
16110
16625
  kind: "mutation",
16111
16626
  auth: "admin"
16112
16627
  }), method(object({
16113
- since: number().optional(),
16114
- until: number().optional(),
16115
- consumer: string().optional(),
16116
- profileId: string().optional()
16117
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
16118
- nodeId: string(),
16119
- model: ManagedModelRefSchema
16120
- }), _void(), {
16628
+ ruleId: string(),
16629
+ enabled: boolean()
16630
+ }), object({ success: literal(true) }), {
16121
16631
  kind: "mutation",
16122
16632
  auth: "admin"
16123
16633
  }), method(object({
16124
- nodeId: string(),
16125
- file: string()
16126
- }), _void(), {
16127
- kind: "mutation",
16128
- auth: "admin"
16129
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16130
- kind: "mutation",
16131
- auth: "admin"
16132
- }), method(ProfileRefInputSchema, _void(), {
16634
+ rule: NcRuleInputSchema,
16635
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
16636
+ }), object({ results: array(NcTestResultSchema) }), {
16133
16637
  kind: "mutation",
16134
16638
  auth: "admin"
16135
- });
16639
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
16136
16640
  /**
16137
16641
  * Zod schemas for persisted record types.
16138
16642
  *
@@ -16818,7 +17322,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16818
17322
  }), method(object({
16819
17323
  eventId: string(),
16820
17324
  kind: MediaFileKindEnum.optional()
16821
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
17325
+ }), array(MediaFileSchema).readonly()), method(object({
17326
+ trackId: string(),
17327
+ kinds: array(MediaFileKindEnum).optional()
17328
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
16822
17329
  deviceId: number(),
16823
17330
  timestamp: number(),
16824
17331
  frameWidth: number(),
@@ -16839,76 +17346,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16839
17346
  eventId: string(),
16840
17347
  timestamp: number()
16841
17348
  });
16842
- /**
16843
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
16844
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
16845
- * caps into per-camera event-kind descriptors.
16846
- *
16847
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
16848
- * is NOT duplicated here — every entry is derived from the single
16849
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
16850
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
16851
- * control cap means adding one line here (and a taxonomy entry); the anti-
16852
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
16853
- * eventful cap is missing.
16854
- */
16855
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
16856
- var LEGACY_ICON = {
16857
- motion: "motion",
16858
- audio: "audio",
16859
- person: "person",
16860
- vehicle: "vehicle",
16861
- animal: "animal",
16862
- package: "package",
16863
- door: "door",
16864
- pir: "pir",
16865
- smoke: "smoke",
16866
- water: "water",
16867
- button: "button",
16868
- generic: "generic",
16869
- gas: "smoke",
16870
- vibration: "generic",
16871
- tamper: "generic",
16872
- presence: "person",
16873
- lock: "generic",
16874
- siren: "generic",
16875
- switch: "generic",
16876
- doorbell: "button"
16877
- };
16878
- function legacyIcon(iconId) {
16879
- return LEGACY_ICON[iconId] ?? "generic";
16880
- }
16881
- /**
16882
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
16883
- * The anti-drift guard cross-checks this against the eventful caps declared
16884
- * in `packages/types/src/capabilities/*.cap.ts`.
16885
- */
16886
- var CAP_TO_KIND = {
16887
- contact: "contact",
16888
- motion: "motion-sensor",
16889
- smoke: "smoke",
16890
- flood: "flood",
16891
- gas: "gas",
16892
- "carbon-monoxide": "carbon-monoxide",
16893
- vibration: "vibration",
16894
- tamper: "tamper",
16895
- presence: "presence",
16896
- "enum-sensor": "enum-sensor",
16897
- "event-emitter": "device-event",
16898
- "lock-control": "lock",
16899
- switch: "switch",
16900
- button: "button",
16901
- doorbell: "doorbell"
16902
- };
16903
- function buildDescriptor(capName, kind) {
16904
- const t = EVENT_TAXONOMY[kind];
16905
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
16906
- return {
16907
- ...t,
16908
- icon: legacyIcon(t.iconId)
16909
- };
16910
- }
16911
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
16912
17349
  var CameraPipelineConfigSchema = object({
16913
17350
  engine: PipelineEngineChoiceSchema.optional(),
16914
17351
  steps: array(PipelineStepInputSchema).readonly(),
@@ -17394,6 +17831,76 @@ method(object({
17394
17831
  auth: "admin"
17395
17832
  });
17396
17833
  /**
17834
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
17835
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
17836
+ * caps into per-camera event-kind descriptors.
17837
+ *
17838
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
17839
+ * is NOT duplicated here — every entry is derived from the single
17840
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
17841
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
17842
+ * control cap means adding one line here (and a taxonomy entry); the anti-
17843
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
17844
+ * eventful cap is missing.
17845
+ */
17846
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
17847
+ var LEGACY_ICON = {
17848
+ motion: "motion",
17849
+ audio: "audio",
17850
+ person: "person",
17851
+ vehicle: "vehicle",
17852
+ animal: "animal",
17853
+ package: "package",
17854
+ door: "door",
17855
+ pir: "pir",
17856
+ smoke: "smoke",
17857
+ water: "water",
17858
+ button: "button",
17859
+ generic: "generic",
17860
+ gas: "smoke",
17861
+ vibration: "generic",
17862
+ tamper: "generic",
17863
+ presence: "person",
17864
+ lock: "generic",
17865
+ siren: "generic",
17866
+ switch: "generic",
17867
+ doorbell: "button"
17868
+ };
17869
+ function legacyIcon(iconId) {
17870
+ return LEGACY_ICON[iconId] ?? "generic";
17871
+ }
17872
+ /**
17873
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
17874
+ * The anti-drift guard cross-checks this against the eventful caps declared
17875
+ * in `packages/types/src/capabilities/*.cap.ts`.
17876
+ */
17877
+ var CAP_TO_KIND = {
17878
+ contact: "contact",
17879
+ motion: "motion-sensor",
17880
+ smoke: "smoke",
17881
+ flood: "flood",
17882
+ gas: "gas",
17883
+ "carbon-monoxide": "carbon-monoxide",
17884
+ vibration: "vibration",
17885
+ tamper: "tamper",
17886
+ presence: "presence",
17887
+ "enum-sensor": "enum-sensor",
17888
+ "event-emitter": "device-event",
17889
+ "lock-control": "lock",
17890
+ switch: "switch",
17891
+ button: "button",
17892
+ doorbell: "doorbell"
17893
+ };
17894
+ function buildDescriptor(capName, kind) {
17895
+ const t = EVENT_TAXONOMY[kind];
17896
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
17897
+ return {
17898
+ ...t,
17899
+ icon: legacyIcon(t.iconId)
17900
+ };
17901
+ }
17902
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
17903
+ /**
17397
17904
  * server-management — per-NODE singleton capability for a node's ROOT
17398
17905
  * package lifecycle (runtime-updatable node packages).
17399
17906
  *
@@ -18848,7 +19355,28 @@ var FaceInfoSchema = object({
18848
19355
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
18849
19356
  * track produced no key frame (e.g. native/onboard source) — the UI falls
18850
19357
  * back to the inline `base64` face crop. */
18851
- keyFrameMediaKey: string().optional()
19358
+ keyFrameMediaKey: string().optional(),
19359
+ /** Winning identity-match cosine (0..1) for this face's track, when an
19360
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
19361
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
19362
+ * faces that were never auto-recognized. */
19363
+ bestMatchScore: number().optional(),
19364
+ /** Native-scale face short side (px) at recognition time, when the runner
19365
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
19366
+ * legacy rows / runners that reported no native measure. */
19367
+ nativeFaceShortSidePx: number().optional(),
19368
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
19369
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
19370
+ * but blocked only by the recognition size floor). Mutually exclusive with
19371
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
19372
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
19373
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
19374
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
19375
+ suggestedIdentityId: string().optional(),
19376
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
19377
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
19378
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
19379
+ suggestedMatchScore: number().optional()
18852
19380
  });
18853
19381
  var FaceFilterEnum = _enum([
18854
19382
  "unassigned",
@@ -20891,36 +21419,6 @@ Object.freeze({
20891
21419
  addonId: null,
20892
21420
  access: "view"
20893
21421
  },
20894
- "advancedNotifier.deleteRule": {
20895
- capName: "advanced-notifier",
20896
- capScope: "system",
20897
- addonId: null,
20898
- access: "delete"
20899
- },
20900
- "advancedNotifier.getHistory": {
20901
- capName: "advanced-notifier",
20902
- capScope: "system",
20903
- addonId: null,
20904
- access: "view"
20905
- },
20906
- "advancedNotifier.getRules": {
20907
- capName: "advanced-notifier",
20908
- capScope: "system",
20909
- addonId: null,
20910
- access: "view"
20911
- },
20912
- "advancedNotifier.testRule": {
20913
- capName: "advanced-notifier",
20914
- capScope: "system",
20915
- addonId: null,
20916
- access: "create"
20917
- },
20918
- "advancedNotifier.upsertRule": {
20919
- capName: "advanced-notifier",
20920
- capScope: "system",
20921
- addonId: null,
20922
- access: "create"
20923
- },
20924
21422
  "alarmPanel.arm": {
20925
21423
  capName: "alarm-panel",
20926
21424
  capScope: "device",
@@ -23225,6 +23723,60 @@ Object.freeze({
23225
23723
  addonId: null,
23226
23724
  access: "create"
23227
23725
  },
23726
+ "notificationRules.createRule": {
23727
+ capName: "notification-rules",
23728
+ capScope: "system",
23729
+ addonId: null,
23730
+ access: "create"
23731
+ },
23732
+ "notificationRules.deleteRule": {
23733
+ capName: "notification-rules",
23734
+ capScope: "system",
23735
+ addonId: null,
23736
+ access: "delete"
23737
+ },
23738
+ "notificationRules.getConditionCatalog": {
23739
+ capName: "notification-rules",
23740
+ capScope: "system",
23741
+ addonId: null,
23742
+ access: "view"
23743
+ },
23744
+ "notificationRules.getHistory": {
23745
+ capName: "notification-rules",
23746
+ capScope: "system",
23747
+ addonId: null,
23748
+ access: "view"
23749
+ },
23750
+ "notificationRules.getRule": {
23751
+ capName: "notification-rules",
23752
+ capScope: "system",
23753
+ addonId: null,
23754
+ access: "view"
23755
+ },
23756
+ "notificationRules.listRules": {
23757
+ capName: "notification-rules",
23758
+ capScope: "system",
23759
+ addonId: null,
23760
+ access: "view"
23761
+ },
23762
+ "notificationRules.setRuleEnabled": {
23763
+ capName: "notification-rules",
23764
+ capScope: "system",
23765
+ addonId: null,
23766
+ access: "create"
23767
+ },
23768
+ "notificationRules.testRule": {
23769
+ capName: "notification-rules",
23770
+ capScope: "system",
23771
+ addonId: null,
23772
+ access: "create"
23773
+ },
23774
+ "notificationRules.updateRule": {
23775
+ capName: "notification-rules",
23776
+ capScope: "system",
23777
+ addonId: null,
23778
+ access: "create"
23779
+ },
23228
23780
  "notifier.cancel": {
23229
23781
  capName: "notifier",
23230
23782
  capScope: "device",