@camstack/addon-provider-amcrest 0.2.4 → 0.2.5

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