@camstack/addon-provider-homematic 1.2.3 → 1.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1410 -858
  2. package/dist/addon.mjs +1410 -858
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -8,7 +8,7 @@ let http = require("http");
8
8
  let crypto$1 = require("crypto");
9
9
  let fs_promises = require("fs/promises");
10
10
  let path = require("path");
11
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
11
+ //#region ../types/dist/event-category-BLcNejAE.mjs
12
12
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
13
13
  EventCategory["SystemBoot"] = "system.boot";
14
14
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -158,9 +158,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
158
158
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
159
159
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
160
160
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
161
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
162
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
163
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
164
161
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
165
162
  * progress bar the client reconciles via `recordingExport.getExport`. */
166
163
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6839,7 +6836,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6839
6836
  patch: record(string(), unknown())
6840
6837
  }), object({ success: literal(true) });
6841
6838
  object({ deviceId: number() }), unknown().nullable();
6842
- /** Shorthand to define a method schema */
6843
6839
  function method(input, output, options) {
6844
6840
  return {
6845
6841
  input,
@@ -6847,6 +6843,7 @@ function method(input, output, options) {
6847
6843
  kind: options?.kind ?? "query",
6848
6844
  auth: options?.auth ?? "protected",
6849
6845
  ...options?.access !== void 0 ? { access: options.access } : {},
6846
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6850
6847
  timeoutMs: options?.timeoutMs
6851
6848
  };
6852
6849
  }
@@ -8216,6 +8213,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8216
8213
  /** The complete taxonomy dictionary, keyed by kind. */
8217
8214
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8218
8215
  /**
8216
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8217
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8218
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8219
+ * taxonomy surface (timeline, filters, event page).
8220
+ *
8221
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8222
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8223
+ * for the `classes` / `classesExclude` conditions.
8224
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8225
+ * the same class picker, grouped under an Audio header.
8226
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8227
+ * lock / …) for the `sensorKinds` device-event condition.
8228
+ *
8229
+ * Each entry carries `parentKind` so the client can group video subs under
8230
+ * their macro and sensor/control kinds under their category. This surface is
8231
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8232
+ * method, no codegen — so it ships train-free with an addon deploy.
8233
+ */
8234
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8235
+ var NcTaxonomyEntrySchema = object({
8236
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8237
+ kind: string(),
8238
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8239
+ label: string(),
8240
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8241
+ parentKind: string().nullable()
8242
+ });
8243
+ object({
8244
+ videoClasses: array(NcTaxonomyEntrySchema),
8245
+ audioKinds: array(NcTaxonomyEntrySchema),
8246
+ labels: array(NcTaxonomyEntrySchema)
8247
+ });
8248
+ function toEntry(kind, label, parentKind) {
8249
+ return {
8250
+ kind,
8251
+ label,
8252
+ parentKind
8253
+ };
8254
+ }
8255
+ /**
8256
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8257
+ * (macros before their subs), which the client relies on for stable grouping.
8258
+ */
8259
+ function buildNcTaxonomy() {
8260
+ const all = Object.values(EVENT_TAXONOMY);
8261
+ return {
8262
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8263
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8264
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8265
+ };
8266
+ }
8267
+ Object.freeze(buildNcTaxonomy());
8268
+ /**
8219
8269
  * Error types for the safe expression engine. Two distinct classes so callers
8220
8270
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8221
8271
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -12201,6 +12251,22 @@ var CameraMetricsSchema = object({
12201
12251
  ])
12202
12252
  });
12203
12253
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
12254
+ /**
12255
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
12256
+ * within the frame, so the executor can re-cut a leaf child ROI at native
12257
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
12258
+ */
12259
+ var NativeCropRefSchema = object({
12260
+ /** Handle keying the retained native surface (node-pinned to its owner). */
12261
+ handle: FrameHandleSchema,
12262
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
12263
+ cropFrameSpace: object({
12264
+ x: number(),
12265
+ y: number(),
12266
+ w: number(),
12267
+ h: number()
12268
+ })
12269
+ });
12204
12270
  var ModelFormatSchema$1 = _enum([
12205
12271
  "onnx",
12206
12272
  "coreml",
@@ -12476,7 +12542,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
12476
12542
  * Omitted ⇒ the runner's default device (current single-engine
12477
12543
  * behaviour). Selects WHICH device pool of the node runs the call.
12478
12544
  */
12479
- deviceKey: string().optional()
12545
+ deviceKey: string().optional(),
12546
+ /**
12547
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
12548
+ * when the parent crop was resolved from the frame's retained NATIVE
12549
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
12550
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
12551
+ * resolution from that surface — the SAME quality path faces already
12552
+ * had — instead of the downscaled parent tile. `handle` keys the native
12553
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
12554
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
12555
+ * the executor's crop-normalized child ROI back into frame-normalized
12556
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
12557
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
12558
+ * (today's behaviour on the fallback path).
12559
+ */
12560
+ nativeCropRef: NativeCropRefSchema.optional()
12480
12561
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
12481
12562
  engine: PipelineEngineChoiceSchema.optional(),
12482
12563
  steps: array(PipelineStepInputSchema).min(1),
@@ -12725,7 +12806,11 @@ var DetailResultSchema = object({
12725
12806
  bbox: NativeCropBboxSchema.optional(),
12726
12807
  embedding: string().optional(),
12727
12808
  label: string().optional(),
12728
- alignedCropJpeg: string().optional()
12809
+ alignedCropJpeg: string().optional(),
12810
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
12811
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
12812
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
12813
+ nativeFaceShortSidePx: number().optional()
12729
12814
  });
12730
12815
  /**
12731
12816
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -12739,6 +12824,12 @@ var motionCooldownMsField = {
12739
12824
  default: 3e4,
12740
12825
  step: 500
12741
12826
  };
12827
+ var maxSessionHoldMsField = {
12828
+ min: 0,
12829
+ max: 6e5,
12830
+ default: 12e4,
12831
+ step: 5e3
12832
+ };
12742
12833
  var motionFpsField = {
12743
12834
  min: 1,
12744
12835
  max: 30,
@@ -12886,6 +12977,19 @@ var RunnerCameraConfigSchema = object({
12886
12977
  "on-motion"
12887
12978
  ]).default("always-on"),
12888
12979
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
12980
+ /**
12981
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
12982
+ * detection session is active and ≥1 confirmed non-stationary track is
12983
+ * still live, the orchestrator keeps the session open past
12984
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
12985
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
12986
+ * ms since the session opened, after which it closes regardless. `0`
12987
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
12988
+ * runner itself — carried here so it shares the per-camera device-settings
12989
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
12990
+ * resolved `CameraDetectionConfig`.
12991
+ */
12992
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
12889
12993
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
12890
12994
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
12891
12995
  motionStreamId: string(),
@@ -12975,7 +13079,7 @@ var RunnerCameraConfigSchema = object({
12975
13079
  */
12976
13080
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
12977
13081
  });
12978
- 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;
13082
+ 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;
12979
13083
  /**
12980
13084
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
12981
13085
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -16502,94 +16606,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
16502
16606
  bundleUrl: string()
16503
16607
  });
16504
16608
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
16505
- var NotificationRuleConditionsSchema = object({
16506
- deviceIds: array(number()).readonly().optional(),
16507
- classNames: array(string()).readonly().optional(),
16508
- zoneIds: array(string()).readonly().optional(),
16509
- minConfidence: number().optional(),
16510
- source: _enum([
16511
- "pipeline",
16512
- "onboard",
16513
- "any"
16514
- ]).optional(),
16515
- schedule: object({
16516
- days: array(number()).readonly(),
16517
- startHour: number(),
16518
- endHour: number()
16519
- }).optional(),
16520
- cooldownSeconds: number().optional(),
16521
- minDwellSeconds: number().optional(),
16522
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
16523
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
16524
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
16525
- eventTypeTokens: array(string()).readonly().optional(),
16526
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
16527
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
16528
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
16529
- clipDescription: object({
16530
- text: string().min(1),
16531
- minSimilarity: number().min(0).max(1)
16532
- }).optional(),
16533
- /** Match events whose recognized-entity label (face identity name or plate
16534
- * vehicle name, propagated onto `event.data.label`) is one of these values.
16535
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
16536
- * vehicle/person> is seen". */
16537
- labels: array(string()).readonly().optional()
16538
- });
16539
- var NotificationRuleTemplateSchema = object({
16540
- title: string(),
16541
- body: string(),
16542
- imageMode: _enum([
16543
- "crop",
16544
- "annotated",
16545
- "full",
16546
- "none"
16547
- ])
16548
- });
16549
- var NotificationRuleSchema = object({
16550
- id: string(),
16551
- name: string(),
16552
- enabled: boolean(),
16553
- eventTypes: array(string()).readonly(),
16554
- conditions: NotificationRuleConditionsSchema,
16555
- outputs: array(string()).readonly(),
16556
- template: NotificationRuleTemplateSchema.optional(),
16557
- priority: _enum([
16558
- "low",
16559
- "normal",
16560
- "high",
16561
- "critical"
16562
- ])
16563
- });
16564
- var NotificationTestResultSchema = object({
16565
- ruleId: string(),
16566
- eventId: string(),
16567
- timestamp: number(),
16568
- wouldFire: boolean(),
16569
- reason: string().optional()
16570
- });
16571
- var NotificationHistoryEntrySchema = object({
16572
- id: string(),
16573
- ruleId: string(),
16574
- ruleName: string(),
16575
- eventId: string(),
16576
- timestamp: number(),
16577
- outputs: array(string()).readonly(),
16578
- success: boolean(),
16579
- error: string().optional(),
16580
- deviceId: number().optional()
16581
- });
16582
- var NotificationHistoryFilterSchema = object({
16583
- ruleId: string().optional(),
16584
- deviceId: number().optional(),
16585
- from: number().optional(),
16586
- to: number().optional(),
16587
- limit: number().optional()
16588
- });
16589
- 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({
16590
- ruleId: string(),
16591
- lookbackMinutes: number()
16592
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
16593
16609
  /**
16594
16610
  * Alerts capability — collection-based internal alert system.
16595
16611
  *
@@ -16776,89 +16792,6 @@ method(object({
16776
16792
  password: string()
16777
16793
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
16778
16794
  /**
16779
- * `login-method` — collection cap through which auth addons contribute
16780
- * their pre-auth login surfaces to the login page. This is the SINGLE,
16781
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
16782
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
16783
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
16784
- * procedure aggregates them for the unauthenticated login page.
16785
- *
16786
- * A contribution is a discriminated union on `kind`:
16787
- *
16788
- * - `redirect` — a declarative button. The login page renders a generic
16789
- * button that navigates to `startUrl` (an addon-owned HTTP route).
16790
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
16791
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
16792
- * login page needs NO change.
16793
- *
16794
- * - `widget` — a Module-Federation widget the login page mounts (via
16795
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
16796
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
16797
- * mechanism kept for future use; no shipped addon uses it on the login
16798
- * page (the passkey ceremony below runs natively in the shell instead).
16799
- *
16800
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
16801
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
16802
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
16803
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
16804
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
16805
- * fetching any remote code pre-auth. Contribution stays unconditional —
16806
- * enrollment state is never leaked pre-auth; visibility is a shell
16807
- * decision.
16808
- *
16809
- * Every contribution carries a `stage`:
16810
- * - `primary` — shown on the first credentials screen (OIDC /
16811
- * magic-link buttons; a future usernameless passkey).
16812
- * - `second-factor` — shown AFTER the password leg, gated on the
16813
- * returned `factors` (passkey-as-2FA today).
16814
- *
16815
- * `mount: skip` — the cap is read server-side by the core auth router
16816
- * (`registry.getCollection('login-method')`), never mounted as its own
16817
- * tRPC router.
16818
- */
16819
- /** When a login method renders in the two-phase login flow. */
16820
- var LoginStageEnum = _enum(["primary", "second-factor"]);
16821
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
16822
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
16823
- object({
16824
- kind: literal("redirect"),
16825
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
16826
- id: string(),
16827
- /** Operator-facing button label. */
16828
- label: string(),
16829
- /** lucide-react icon name. */
16830
- icon: string().optional(),
16831
- /** Addon-owned HTTP route the button navigates to (GET). */
16832
- startUrl: string(),
16833
- stage: LoginStageEnum
16834
- }),
16835
- object({
16836
- kind: literal("widget"),
16837
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
16838
- id: string(),
16839
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
16840
- addonId: string(),
16841
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
16842
- bundle: string(),
16843
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
16844
- remote: WidgetRemoteSchema,
16845
- stage: LoginStageEnum
16846
- }),
16847
- object({
16848
- kind: literal("passkey"),
16849
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
16850
- id: string(),
16851
- /** Operator-facing button label. */
16852
- label: string(),
16853
- stage: LoginStageEnum,
16854
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
16855
- rpId: string(),
16856
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
16857
- origin: string().nullable()
16858
- })
16859
- ]);
16860
- method(_void(), array(LoginMethodContributionSchema).readonly());
16861
- /**
16862
16795
  * Orchestrator-side destination metadata. The orchestrator computes
16863
16796
  * `id = <addonId>:<subId>` from its provider lookup so consumers
16864
16797
  * (admin UI, restore flow) see one canonical key.
@@ -18268,242 +18201,617 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
18268
18201
  kind: "mutation",
18269
18202
  auth: "admin"
18270
18203
  });
18271
- var LogLevelSchema = _enum([
18272
- "debug",
18273
- "info",
18274
- "warn",
18275
- "error"
18204
+ /**
18205
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18206
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18207
+ * caps stay wire-compatible without a circular cap→cap import.
18208
+ *
18209
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
18210
+ * every transport tier structurally, and failed calls still write usage rows.
18211
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18212
+ */
18213
+ var LlmUsageSchema = object({
18214
+ inputTokens: number(),
18215
+ outputTokens: number()
18216
+ });
18217
+ var LlmErrorCodeSchema = _enum([
18218
+ "timeout",
18219
+ "rate-limited",
18220
+ "auth",
18221
+ "refusal",
18222
+ "bad-request",
18223
+ "unavailable",
18224
+ "no-profile",
18225
+ "budget-exceeded",
18226
+ "adapter-error"
18276
18227
  ]);
18277
- var LogEntrySchema = object({
18278
- timestamp: date(),
18279
- level: LogLevelSchema,
18280
- scope: array(string()),
18228
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18229
+ ok: literal(true),
18230
+ text: string(),
18231
+ model: string(),
18232
+ usage: LlmUsageSchema,
18233
+ truncated: boolean(),
18234
+ latencyMs: number()
18235
+ }), object({
18236
+ ok: literal(false),
18237
+ code: LlmErrorCodeSchema,
18281
18238
  message: string(),
18282
- meta: record(string(), unknown()).optional(),
18283
- tags: record(string(), string()).optional()
18284
- });
18285
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18286
- scope: array(string()).optional(),
18287
- level: LogLevelSchema.optional(),
18288
- since: date().optional(),
18289
- until: date().optional(),
18290
- limit: number().optional(),
18291
- tags: record(string(), string()).optional()
18292
- }), array(LogEntrySchema).readonly());
18293
- var CpuBreakdownSchema = object({
18294
- total: number(),
18295
- user: number(),
18296
- system: number(),
18297
- irq: number(),
18298
- nice: number(),
18299
- loadAvg: tuple([
18300
- number(),
18301
- number(),
18302
- number()
18303
- ]),
18304
- cores: number()
18239
+ retryAfterMs: number().optional()
18240
+ })]);
18241
+ /**
18242
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18243
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18244
+ * notification-output.cap.ts:27-31 precedents).
18245
+ */
18246
+ var LlmImageSchema = object({
18247
+ bytes: _instanceof(Uint8Array),
18248
+ mimeType: string()
18305
18249
  });
18306
- var MemoryInfoSchema = object({
18307
- percent: number(),
18308
- totalBytes: number(),
18309
- usedBytes: number(),
18310
- availableBytes: number(),
18311
- swapUsedBytes: number(),
18312
- swapTotalBytes: number()
18250
+ var LlmGenerateBaseInputSchema = object({
18251
+ /** Collection routing (the notification-output posture). */
18252
+ addonId: string().optional(),
18253
+ /** Explicit profile; else the resolution chain (spec §3). */
18254
+ profileId: string().optional(),
18255
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18256
+ consumer: string(),
18257
+ system: string().optional(),
18258
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
18259
+ prompt: string(),
18260
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18261
+ jsonSchema: record(string(), unknown()).optional(),
18262
+ /** Per-call override of the profile default. */
18263
+ maxTokens: number().int().positive().optional(),
18264
+ temperature: number().optional()
18313
18265
  });
18314
- var DiskIoSnapshotSchema = object({
18315
- readBytes: number(),
18316
- writeBytes: number(),
18317
- readOps: number(),
18318
- writeOps: number(),
18319
- timestampMs: number()
18320
- });
18321
- var NetworkIoSnapshotSchema = object({
18322
- rxBytes: number(),
18323
- txBytes: number(),
18324
- rxPackets: number(),
18325
- txPackets: number(),
18326
- rxErrors: number(),
18327
- txErrors: number(),
18328
- timestampMs: number()
18329
- });
18330
- var MetricsGpuInfoSchema = object({
18331
- utilization: number(),
18332
- model: string(),
18333
- memoryUsedBytes: number(),
18334
- memoryTotalBytes: number(),
18335
- temperature: number().nullable()
18336
- });
18337
- var ProcessResourceInfoSchema = object({
18338
- openFds: number(),
18339
- threadCount: number(),
18340
- activeHandles: number(),
18341
- activeRequests: number()
18342
- });
18343
- var PressureAvgsSchema = object({
18344
- avg10: number(),
18345
- avg60: number(),
18346
- avg300: number()
18347
- });
18348
- var PressureInfoSchema = object({
18349
- some: PressureAvgsSchema,
18350
- full: PressureAvgsSchema.nullable()
18351
- });
18352
- var SystemResourceSnapshotSchema = object({
18353
- cpu: CpuBreakdownSchema,
18354
- memory: MemoryInfoSchema,
18355
- gpu: MetricsGpuInfoSchema.nullable(),
18356
- network: NetworkIoSnapshotSchema,
18357
- disk: DiskIoSnapshotSchema,
18358
- pressure: object({
18359
- cpu: PressureInfoSchema.nullable(),
18360
- memory: PressureInfoSchema.nullable(),
18361
- io: PressureInfoSchema.nullable()
18266
+ /**
18267
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18268
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18269
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18270
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18271
+ * this only through the `llm` cap's methods.
18272
+ *
18273
+ * One running llama-server child per node in v1 (models are RAM-heavy).
18274
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18275
+ * watchdog — operator decision #3).
18276
+ */
18277
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
18278
+ object({
18279
+ kind: literal("catalog"),
18280
+ catalogId: string()
18362
18281
  }),
18363
- process: ProcessResourceInfoSchema,
18364
- cpuTemperature: number().nullable(),
18365
- timestampMs: number()
18366
- });
18367
- var DiskSpaceInfoSchema = object({
18368
- path: string(),
18369
- totalBytes: number(),
18370
- usedBytes: number(),
18371
- availableBytes: number(),
18372
- percent: number()
18373
- });
18374
- var PidResourceStatsSchema = object({
18375
- pid: number(),
18376
- cpu: number(),
18377
- memory: number(),
18378
- /**
18379
- * Private (anonymous) resident bytes — the per-process V8 heap + native
18380
- * allocations NOT shared with other processes (Linux RssAnon). This is the
18381
- * "real" per-runner cost; summing it across runners is meaningful, unlike
18382
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
18383
- * Undefined where /proc is unavailable (e.g. macOS).
18384
- */
18385
- privateBytes: number().optional(),
18386
- /**
18387
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18388
- * code shared copy-on-write across runners. Undefined on macOS.
18389
- */
18390
- sharedBytes: number().optional()
18282
+ object({
18283
+ kind: literal("url"),
18284
+ url: string(),
18285
+ sha256: string().optional()
18286
+ }),
18287
+ object({
18288
+ kind: literal("path"),
18289
+ path: string()
18290
+ })
18291
+ ]);
18292
+ var ManagedRuntimeConfigSchema = object({
18293
+ /** WHERE the runtime lives — hub or any agent. */
18294
+ nodeId: string(),
18295
+ /** Closed for v1; 'ollama' is a v2 candidate. */
18296
+ engine: _enum(["llama-cpp"]),
18297
+ model: ManagedModelRefSchema,
18298
+ contextSize: number().int().default(4096),
18299
+ /** 0 = CPU-only. */
18300
+ gpuLayers: number().int().default(0),
18301
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18302
+ threads: number().int().optional(),
18303
+ /** Concurrent slots. */
18304
+ parallel: number().int().default(1),
18305
+ /** Else lazy: first generate boots it. */
18306
+ autoStart: boolean().default(false),
18307
+ /** 0 = never; frees RAM after quiet periods. */
18308
+ idleStopMinutes: number().int().default(30)
18391
18309
  });
18392
- var AddonInstanceSchema = object({
18393
- addonId: string(),
18310
+ var LlmRuntimeStatusSchema = object({
18311
+ /** Status is ALWAYS node-qualified. */
18394
18312
  nodeId: string(),
18395
- role: _enum(["hub", "worker"]),
18396
- pid: number(),
18397
18313
  state: _enum([
18398
- "starting",
18399
- "running",
18400
- "stopping",
18401
18314
  "stopped",
18402
- "crashed"
18403
- ]),
18404
- uptimeSec: number()
18405
- });
18406
- var NodeProcessSchema = object({
18407
- pid: number(),
18408
- ppid: number(),
18409
- pgid: number(),
18410
- classification: _enum([
18411
- "root",
18412
- "managed",
18413
- "system",
18414
- "ghost"
18315
+ "downloading",
18316
+ "starting",
18317
+ "ready",
18318
+ "crashed",
18319
+ "failed"
18415
18320
  ]),
18416
- /** `$process` addon binding when `managed`, else null. */
18417
- addonId: string().nullable(),
18418
- /** Kernel-reported nodeId when the process is a known agent/worker. */
18419
- nodeId: string().nullable(),
18420
- /** Truncated command line. */
18421
- command: string(),
18422
- cpuPercent: number(),
18423
- memoryRssBytes: number(),
18424
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18425
- uptimeSec: number(),
18426
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18427
- orphaned: boolean()
18428
- });
18429
- var KillProcessInputSchema = object({
18430
- pid: number(),
18431
- /** Force = SIGKILL. Default is SIGTERM. */
18432
- force: boolean().optional()
18433
- });
18434
- var KillProcessResultSchema = object({
18435
- success: boolean(),
18436
- reason: string().optional(),
18437
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18438
- });
18439
- var DumpHeapSnapshotInputSchema = object({
18440
- /** The addon whose runner should dump a heap snapshot. */
18441
- addonId: string() });
18442
- var DumpHeapSnapshotResultSchema = object({
18443
- success: boolean(),
18444
- /** Path of the written .heapsnapshot inside the runner's container/host. */
18445
- path: string().optional(),
18446
- /** Process pid that was signalled. */
18447
18321
  pid: number().optional(),
18448
- reason: string().optional()
18322
+ port: number().optional(),
18323
+ modelPath: string().optional(),
18324
+ modelId: string().optional(),
18325
+ downloadProgress: number().min(0).max(1).optional(),
18326
+ lastError: string().optional(),
18327
+ crashesInWindow: number(),
18328
+ /** Child RSS (sampled best-effort). */
18329
+ memoryBytes: number().optional(),
18330
+ vramBytes: number().optional()
18449
18331
  });
18450
- var SystemMetricsSchema = object({
18451
- cpuPercent: number(),
18452
- memoryPercent: number(),
18453
- memoryUsedMB: number(),
18454
- memoryTotalMB: number(),
18455
- diskPercent: number().optional(),
18456
- temperature: number().optional(),
18457
- gpuPercent: number().optional(),
18458
- gpuMemoryPercent: number().optional()
18332
+ var LlmNodeModelSchema = object({
18333
+ file: string(),
18334
+ sizeBytes: number(),
18335
+ catalogId: string().optional(),
18336
+ installedAt: number().optional()
18459
18337
  });
18460
- 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, {
18338
+ var LlmRuntimeDiskUsageSchema = object({
18339
+ nodeId: string(),
18340
+ modelsBytes: number(),
18341
+ freeBytes: number().optional()
18342
+ });
18343
+ method(LlmGenerateBaseInputSchema.extend({
18344
+ images: array(LlmImageSchema).optional(),
18345
+ runtime: ManagedRuntimeConfigSchema,
18346
+ /** The managed profile's timeout, threaded by the hub provider. */
18347
+ timeoutMs: number().int().positive().optional()
18348
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18461
18349
  kind: "mutation",
18462
18350
  auth: "admin"
18463
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
18351
+ }), method(object({}), _void(), {
18464
18352
  kind: "mutation",
18465
18353
  auth: "admin"
18466
- });
18467
- method(object({
18468
- sourceUrl: string(),
18469
- metadata: ModelConvertMetadataSchema,
18470
- targets: array(ConvertTargetSchema).min(1).readonly(),
18471
- calibrationRef: string().optional(),
18472
- sessionId: string().optional()
18473
- }), ConvertResultSchema, {
18354
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18474
18355
  kind: "mutation",
18475
- auth: "admin",
18476
- timeoutMs: 6e5
18477
- });
18478
- method(object({
18479
- nodeId: string(),
18480
- modelId: string(),
18481
- format: _enum(MODEL_FORMATS),
18482
- entry: ModelCatalogEntrySchema
18483
- }), object({
18484
- ok: boolean(),
18485
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
18486
- sha256: string(),
18487
- bytes: number(),
18488
- /** The target node's modelsDir the artifact landed in. */
18489
- path: string()
18490
- }), {
18356
+ auth: "admin"
18357
+ }), method(object({ file: string() }), _void(), {
18491
18358
  kind: "mutation",
18492
18359
  auth: "admin"
18493
- });
18360
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18494
18361
  /**
18495
- * `mqtt-broker` — broker-registry cap.
18496
- *
18497
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
18498
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
18499
- * and (b) the connection details a consumer addon needs to spin up
18500
- * its OWN `mqtt.js` client.
18362
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18363
+ * methods concat-fan across providers; single-row methods route to ONE
18364
+ * provider by the `addonId` in the call input (the notification-output
18365
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18366
+ * (hub-placed); the cap stays open for future providers.
18501
18367
  *
18502
- * Why: pub/sub routing over the system event-bus loses fidelity
18503
- * (callback shape, QoS guarantees, will/retain semantics) and adds
18504
- * refcount bookkeeping that addons would rather own themselves. The
18505
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
18506
- * features anyway — give it the connection config, get out of the way.
18368
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18369
+ * `apiKey` is a password field — providers REDACT it on read and merge on
18370
+ * write; a stored key NEVER round-trips to a client.
18371
+ */
18372
+ var LlmProfileKindSchema = _enum([
18373
+ "openai-compatible",
18374
+ "openai",
18375
+ "anthropic",
18376
+ "google",
18377
+ "managed-local"
18378
+ ]);
18379
+ var LlmProfileSchema = object({
18380
+ id: string(),
18381
+ name: string(),
18382
+ kind: LlmProfileKindSchema,
18383
+ /** Stamped by the provider — keeps the fanned catalog routable. */
18384
+ addonId: string(),
18385
+ enabled: boolean(),
18386
+ /** Vendor model id, or the managed runtime's loaded model. */
18387
+ model: string(),
18388
+ /** Required for openai-compatible; override for cloud kinds. */
18389
+ baseUrl: string().optional(),
18390
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
18391
+ apiKey: string().optional(),
18392
+ supportsVision: boolean(),
18393
+ temperature: number().min(0).max(2).optional(),
18394
+ maxTokens: number().int().positive().optional(),
18395
+ timeoutMs: number().int().positive().default(6e4),
18396
+ extraHeaders: record(string(), string()).optional(),
18397
+ /** kind === 'managed-local' only (spec §4). */
18398
+ runtime: ManagedRuntimeConfigSchema.optional()
18399
+ });
18400
+ /** ConfigUISchema tree passed through untyped on the wire (the
18401
+ * notification-output `ConfigSchemaPassthrough` precedent at
18402
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
18403
+ var ConfigSchemaPassthrough$1 = unknown();
18404
+ var LlmProfileKindDescriptorSchema = object({
18405
+ kind: LlmProfileKindSchema,
18406
+ label: string(),
18407
+ icon: string(),
18408
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
18409
+ addonId: string(),
18410
+ configSchema: ConfigSchemaPassthrough$1
18411
+ });
18412
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
18413
+ var LlmDefaultSchema = object({
18414
+ selector: LlmDefaultSelectorSchema,
18415
+ profileId: string()
18416
+ });
18417
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
18418
+ var LlmUsageRollupSchema = object({
18419
+ day: string(),
18420
+ consumer: string(),
18421
+ profileId: string(),
18422
+ calls: number(),
18423
+ okCalls: number(),
18424
+ errorCalls: number(),
18425
+ inputTokens: number(),
18426
+ outputTokens: number(),
18427
+ avgLatencyMs: number()
18428
+ });
18429
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
18430
+ var ManagedModelCatalogEntrySchema = object({
18431
+ id: string(),
18432
+ label: string(),
18433
+ family: string(),
18434
+ purpose: _enum(["text", "vision"]),
18435
+ url: string(),
18436
+ sha256: string(),
18437
+ sizeBytes: number(),
18438
+ quantization: string(),
18439
+ /** Load-time guidance shown in the picker. */
18440
+ minRamBytes: number(),
18441
+ contextSizeDefault: number().int(),
18442
+ /** Vision models: companion projector file. */
18443
+ mmprojUrl: string().optional()
18444
+ });
18445
+ var LlmRuntimeNodeSchema = object({
18446
+ nodeId: string(),
18447
+ reachable: boolean(),
18448
+ status: LlmRuntimeStatusSchema.optional(),
18449
+ disk: LlmRuntimeDiskUsageSchema.optional(),
18450
+ error: string().optional()
18451
+ });
18452
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
18453
+ var ProfileRefInputSchema = object({
18454
+ addonId: string(),
18455
+ profileId: string()
18456
+ });
18457
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
18458
+ kind: "mutation",
18459
+ auth: "admin"
18460
+ }), method(ProfileRefInputSchema, _void(), {
18461
+ kind: "mutation",
18462
+ auth: "admin"
18463
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
18464
+ kind: "mutation",
18465
+ auth: "admin"
18466
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
18467
+ selector: LlmDefaultSelectorSchema,
18468
+ profileId: string().nullable()
18469
+ }), _void(), {
18470
+ kind: "mutation",
18471
+ auth: "admin"
18472
+ }), method(object({
18473
+ since: number().optional(),
18474
+ until: number().optional(),
18475
+ consumer: string().optional(),
18476
+ profileId: string().optional()
18477
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
18478
+ nodeId: string(),
18479
+ model: ManagedModelRefSchema
18480
+ }), _void(), {
18481
+ kind: "mutation",
18482
+ auth: "admin"
18483
+ }), method(object({
18484
+ nodeId: string(),
18485
+ file: string()
18486
+ }), _void(), {
18487
+ kind: "mutation",
18488
+ auth: "admin"
18489
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
18490
+ kind: "mutation",
18491
+ auth: "admin"
18492
+ }), method(ProfileRefInputSchema, _void(), {
18493
+ kind: "mutation",
18494
+ auth: "admin"
18495
+ });
18496
+ var LogLevelSchema = _enum([
18497
+ "debug",
18498
+ "info",
18499
+ "warn",
18500
+ "error"
18501
+ ]);
18502
+ var LogEntrySchema = object({
18503
+ timestamp: date(),
18504
+ level: LogLevelSchema,
18505
+ scope: array(string()),
18506
+ message: string(),
18507
+ meta: record(string(), unknown()).optional(),
18508
+ tags: record(string(), string()).optional()
18509
+ });
18510
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18511
+ scope: array(string()).optional(),
18512
+ level: LogLevelSchema.optional(),
18513
+ since: date().optional(),
18514
+ until: date().optional(),
18515
+ limit: number().optional(),
18516
+ tags: record(string(), string()).optional()
18517
+ }), array(LogEntrySchema).readonly());
18518
+ /**
18519
+ * `login-method` — collection cap through which auth addons contribute
18520
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
18521
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
18522
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
18523
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
18524
+ * procedure aggregates them for the unauthenticated login page.
18525
+ *
18526
+ * A contribution is a discriminated union on `kind`:
18527
+ *
18528
+ * - `redirect` — a declarative button. The login page renders a generic
18529
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
18530
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
18531
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
18532
+ * login page needs NO change.
18533
+ *
18534
+ * - `widget` — a Module-Federation widget the login page mounts (via
18535
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
18536
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
18537
+ * mechanism kept for future use; no shipped addon uses it on the login
18538
+ * page (the passkey ceremony below runs natively in the shell instead).
18539
+ *
18540
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
18541
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
18542
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
18543
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
18544
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
18545
+ * fetching any remote code pre-auth. Contribution stays unconditional —
18546
+ * enrollment state is never leaked pre-auth; visibility is a shell
18547
+ * decision.
18548
+ *
18549
+ * Every contribution carries a `stage`:
18550
+ * - `primary` — shown on the first credentials screen (OIDC /
18551
+ * magic-link buttons; a future usernameless passkey).
18552
+ * - `second-factor` — shown AFTER the password leg, gated on the
18553
+ * returned `factors` (passkey-as-2FA today).
18554
+ *
18555
+ * `mount: skip` — the cap is read server-side by the core auth router
18556
+ * (`registry.getCollection('login-method')`), never mounted as its own
18557
+ * tRPC router.
18558
+ */
18559
+ /** When a login method renders in the two-phase login flow. */
18560
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
18561
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
18562
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
18563
+ object({
18564
+ kind: literal("redirect"),
18565
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
18566
+ id: string(),
18567
+ /** Operator-facing button label. */
18568
+ label: string(),
18569
+ /** lucide-react icon name. */
18570
+ icon: string().optional(),
18571
+ /** Addon-owned HTTP route the button navigates to (GET). */
18572
+ startUrl: string(),
18573
+ stage: LoginStageEnum
18574
+ }),
18575
+ object({
18576
+ kind: literal("widget"),
18577
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
18578
+ id: string(),
18579
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
18580
+ addonId: string(),
18581
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
18582
+ bundle: string(),
18583
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
18584
+ remote: WidgetRemoteSchema,
18585
+ stage: LoginStageEnum
18586
+ }),
18587
+ object({
18588
+ kind: literal("passkey"),
18589
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
18590
+ id: string(),
18591
+ /** Operator-facing button label. */
18592
+ label: string(),
18593
+ stage: LoginStageEnum,
18594
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
18595
+ rpId: string(),
18596
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
18597
+ origin: string().nullable()
18598
+ })
18599
+ ]);
18600
+ method(_void(), array(LoginMethodContributionSchema).readonly());
18601
+ var CpuBreakdownSchema = object({
18602
+ total: number(),
18603
+ user: number(),
18604
+ system: number(),
18605
+ irq: number(),
18606
+ nice: number(),
18607
+ loadAvg: tuple([
18608
+ number(),
18609
+ number(),
18610
+ number()
18611
+ ]),
18612
+ cores: number()
18613
+ });
18614
+ var MemoryInfoSchema = object({
18615
+ percent: number(),
18616
+ totalBytes: number(),
18617
+ usedBytes: number(),
18618
+ availableBytes: number(),
18619
+ swapUsedBytes: number(),
18620
+ swapTotalBytes: number()
18621
+ });
18622
+ var DiskIoSnapshotSchema = object({
18623
+ readBytes: number(),
18624
+ writeBytes: number(),
18625
+ readOps: number(),
18626
+ writeOps: number(),
18627
+ timestampMs: number()
18628
+ });
18629
+ var NetworkIoSnapshotSchema = object({
18630
+ rxBytes: number(),
18631
+ txBytes: number(),
18632
+ rxPackets: number(),
18633
+ txPackets: number(),
18634
+ rxErrors: number(),
18635
+ txErrors: number(),
18636
+ timestampMs: number()
18637
+ });
18638
+ var MetricsGpuInfoSchema = object({
18639
+ utilization: number(),
18640
+ model: string(),
18641
+ memoryUsedBytes: number(),
18642
+ memoryTotalBytes: number(),
18643
+ temperature: number().nullable()
18644
+ });
18645
+ var ProcessResourceInfoSchema = object({
18646
+ openFds: number(),
18647
+ threadCount: number(),
18648
+ activeHandles: number(),
18649
+ activeRequests: number()
18650
+ });
18651
+ var PressureAvgsSchema = object({
18652
+ avg10: number(),
18653
+ avg60: number(),
18654
+ avg300: number()
18655
+ });
18656
+ var PressureInfoSchema = object({
18657
+ some: PressureAvgsSchema,
18658
+ full: PressureAvgsSchema.nullable()
18659
+ });
18660
+ var SystemResourceSnapshotSchema = object({
18661
+ cpu: CpuBreakdownSchema,
18662
+ memory: MemoryInfoSchema,
18663
+ gpu: MetricsGpuInfoSchema.nullable(),
18664
+ network: NetworkIoSnapshotSchema,
18665
+ disk: DiskIoSnapshotSchema,
18666
+ pressure: object({
18667
+ cpu: PressureInfoSchema.nullable(),
18668
+ memory: PressureInfoSchema.nullable(),
18669
+ io: PressureInfoSchema.nullable()
18670
+ }),
18671
+ process: ProcessResourceInfoSchema,
18672
+ cpuTemperature: number().nullable(),
18673
+ timestampMs: number()
18674
+ });
18675
+ var DiskSpaceInfoSchema = object({
18676
+ path: string(),
18677
+ totalBytes: number(),
18678
+ usedBytes: number(),
18679
+ availableBytes: number(),
18680
+ percent: number()
18681
+ });
18682
+ var PidResourceStatsSchema = object({
18683
+ pid: number(),
18684
+ cpu: number(),
18685
+ memory: number(),
18686
+ /**
18687
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
18688
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
18689
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
18690
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
18691
+ * Undefined where /proc is unavailable (e.g. macOS).
18692
+ */
18693
+ privateBytes: number().optional(),
18694
+ /**
18695
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18696
+ * code shared copy-on-write across runners. Undefined on macOS.
18697
+ */
18698
+ sharedBytes: number().optional()
18699
+ });
18700
+ var AddonInstanceSchema = object({
18701
+ addonId: string(),
18702
+ nodeId: string(),
18703
+ role: _enum(["hub", "worker"]),
18704
+ pid: number(),
18705
+ state: _enum([
18706
+ "starting",
18707
+ "running",
18708
+ "stopping",
18709
+ "stopped",
18710
+ "crashed"
18711
+ ]),
18712
+ uptimeSec: number()
18713
+ });
18714
+ var NodeProcessSchema = object({
18715
+ pid: number(),
18716
+ ppid: number(),
18717
+ pgid: number(),
18718
+ classification: _enum([
18719
+ "root",
18720
+ "managed",
18721
+ "system",
18722
+ "ghost"
18723
+ ]),
18724
+ /** `$process` addon binding when `managed`, else null. */
18725
+ addonId: string().nullable(),
18726
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
18727
+ nodeId: string().nullable(),
18728
+ /** Truncated command line. */
18729
+ command: string(),
18730
+ cpuPercent: number(),
18731
+ memoryRssBytes: number(),
18732
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18733
+ uptimeSec: number(),
18734
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18735
+ orphaned: boolean()
18736
+ });
18737
+ var KillProcessInputSchema = object({
18738
+ pid: number(),
18739
+ /** Force = SIGKILL. Default is SIGTERM. */
18740
+ force: boolean().optional()
18741
+ });
18742
+ var KillProcessResultSchema = object({
18743
+ success: boolean(),
18744
+ reason: string().optional(),
18745
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18746
+ });
18747
+ var DumpHeapSnapshotInputSchema = object({
18748
+ /** The addon whose runner should dump a heap snapshot. */
18749
+ addonId: string() });
18750
+ var DumpHeapSnapshotResultSchema = object({
18751
+ success: boolean(),
18752
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
18753
+ path: string().optional(),
18754
+ /** Process pid that was signalled. */
18755
+ pid: number().optional(),
18756
+ reason: string().optional()
18757
+ });
18758
+ var SystemMetricsSchema = object({
18759
+ cpuPercent: number(),
18760
+ memoryPercent: number(),
18761
+ memoryUsedMB: number(),
18762
+ memoryTotalMB: number(),
18763
+ diskPercent: number().optional(),
18764
+ temperature: number().optional(),
18765
+ gpuPercent: number().optional(),
18766
+ gpuMemoryPercent: number().optional()
18767
+ });
18768
+ 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, {
18769
+ kind: "mutation",
18770
+ auth: "admin"
18771
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
18772
+ kind: "mutation",
18773
+ auth: "admin"
18774
+ });
18775
+ method(object({
18776
+ sourceUrl: string(),
18777
+ metadata: ModelConvertMetadataSchema,
18778
+ targets: array(ConvertTargetSchema).min(1).readonly(),
18779
+ calibrationRef: string().optional(),
18780
+ sessionId: string().optional()
18781
+ }), ConvertResultSchema, {
18782
+ kind: "mutation",
18783
+ auth: "admin",
18784
+ timeoutMs: 6e5
18785
+ });
18786
+ method(object({
18787
+ nodeId: string(),
18788
+ modelId: string(),
18789
+ format: _enum(MODEL_FORMATS),
18790
+ entry: ModelCatalogEntrySchema
18791
+ }), object({
18792
+ ok: boolean(),
18793
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
18794
+ sha256: string(),
18795
+ bytes: number(),
18796
+ /** The target node's modelsDir the artifact landed in. */
18797
+ path: string()
18798
+ }), {
18799
+ kind: "mutation",
18800
+ auth: "admin"
18801
+ });
18802
+ /**
18803
+ * `mqtt-broker` — broker-registry cap.
18804
+ *
18805
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
18806
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
18807
+ * and (b) the connection details a consumer addon needs to spin up
18808
+ * its OWN `mqtt.js` client.
18809
+ *
18810
+ * Why: pub/sub routing over the system event-bus loses fidelity
18811
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
18812
+ * refcount bookkeeping that addons would rather own themselves. The
18813
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
18814
+ * features anyway — give it the connection config, get out of the way.
18507
18815
  *
18508
18816
  * Consumer flow:
18509
18817
  * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
@@ -18722,397 +19030,593 @@ var NotificationSchema = object({
18722
19030
  /** One declared native severity/priority level for a kind. */
18723
19031
  var TargetKindLevelSchema = object({
18724
19032
  id: string(),
18725
- label: string(),
18726
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
18727
- ordinal: number().int().min(1).max(5).nullable(),
18728
- flags: object({
18729
- critical: boolean().optional(),
18730
- silent: boolean().optional(),
18731
- noPush: boolean().optional()
18732
- }).optional(),
18733
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
18734
- requires: array(string()).optional(),
18735
- description: string().optional()
18736
- });
18737
- /** The full capability block consulted before dispatch. */
18738
- var TargetKindCapsSchema = object({
18739
- attachments: object({
18740
- mediaTypes: array(AttachmentMediaTypeSchema),
18741
- mode: _enum([
18742
- "url",
18743
- "bytes",
18744
- "both"
18745
- ]),
18746
- max: number().int().nonnegative(),
18747
- maxBytes: number().int().positive().optional()
18748
- }),
18749
- /** Max action buttons (0 = none). */
18750
- actions: number().int().nonnegative(),
18751
- levels: array(TargetKindLevelSchema),
18752
- format: array(NotificationFormatSchema),
18753
- clickUrl: boolean(),
18754
- sound: boolean(),
18755
- ttl: boolean(),
18756
- bodyMaxLen: number().int().positive()
18757
- });
18758
- /**
18759
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
18760
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
18761
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
18762
- * the union is large and not meant for runtime validation here; the exported
18763
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
18764
- */
18765
- var ConfigSchemaPassthrough$1 = unknown();
18766
- var TargetKindSchema = object({
18767
- kind: string(),
18768
- label: string(),
18769
- icon: string(),
18770
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
18771
- addonId: string(),
18772
- configSchema: ConfigSchemaPassthrough$1,
18773
- supportsDiscovery: boolean(),
18774
- caps: TargetKindCapsSchema
18775
- });
18776
- /**
18777
- * A persisted target. `config` holds secrets; providers REDACT secret fields
18778
- * (return a presence marker only) when serving `listTargets` — never
18779
- * round-trip a stored secret to the UI.
18780
- */
18781
- var TargetSchema = object({
18782
- id: string(),
18783
- name: string(),
18784
- kind: string(),
18785
- addonId: string(),
18786
- enabled: boolean(),
18787
- config: record(string(), unknown())
18788
- });
18789
- /** A discovery-surfaced candidate (config is partial + non-secret). */
18790
- var DiscoveredTargetSchema = object({
18791
- kind: string(),
18792
- suggestedName: string(),
18793
- config: record(string(), unknown())
18794
- });
18795
- /** The degrade engine's report — what was resolved / dropped / degraded. */
18796
- var RenderedAsSchema = object({
18797
- level: string(),
18798
- format: NotificationFormatSchema,
18799
- attachmentsSent: number().int().nonnegative(),
18800
- actionsSent: number().int().nonnegative(),
18801
- truncated: boolean(),
18802
- dropped: array(string())
18803
- });
18804
- var SendResultSchema = object({
18805
- success: boolean(),
18806
- error: string().optional(),
18807
- renderedAs: RenderedAsSchema.optional()
18808
- });
18809
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
18810
- var TestResultSchema = SendResultSchema;
18811
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
18812
- kind: string(),
18813
- config: record(string(), unknown()).optional()
18814
- }), array(DiscoveredTargetSchema)), method(object({
18815
- targetId: string(),
18816
- notification: NotificationSchema
18817
- }), SendResultSchema, { kind: "mutation" }), method(object({
18818
- targetId: string(),
18819
- sample: NotificationSchema.optional()
18820
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
18821
- targetId: string(),
18822
- enabled: boolean()
18823
- }), _void(), { kind: "mutation" });
18824
- /**
18825
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18826
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18827
- * caps stay wire-compatible without a circular cap→cap import.
18828
- *
18829
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
18830
- * every transport tier structurally, and failed calls still write usage rows.
18831
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18832
- */
18833
- var LlmUsageSchema = object({
18834
- inputTokens: number(),
18835
- outputTokens: number()
18836
- });
18837
- var LlmErrorCodeSchema = _enum([
18838
- "timeout",
18839
- "rate-limited",
18840
- "auth",
18841
- "refusal",
18842
- "bad-request",
18843
- "unavailable",
18844
- "no-profile",
18845
- "budget-exceeded",
18846
- "adapter-error"
18847
- ]);
18848
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18849
- ok: literal(true),
18850
- text: string(),
18851
- model: string(),
18852
- usage: LlmUsageSchema,
18853
- truncated: boolean(),
18854
- latencyMs: number()
18855
- }), object({
18856
- ok: literal(false),
18857
- code: LlmErrorCodeSchema,
18858
- message: string(),
18859
- retryAfterMs: number().optional()
18860
- })]);
18861
- /**
18862
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18863
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18864
- * notification-output.cap.ts:27-31 precedents).
18865
- */
18866
- var LlmImageSchema = object({
18867
- bytes: _instanceof(Uint8Array),
18868
- mimeType: string()
18869
- });
18870
- var LlmGenerateBaseInputSchema = object({
18871
- /** Collection routing (the notification-output posture). */
18872
- addonId: string().optional(),
18873
- /** Explicit profile; else the resolution chain (spec §3). */
18874
- profileId: string().optional(),
18875
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18876
- consumer: string(),
18877
- system: string().optional(),
18878
- /** v1: single-turn. `messages[]` is a v2 additive field. */
18879
- prompt: string(),
18880
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18881
- jsonSchema: record(string(), unknown()).optional(),
18882
- /** Per-call override of the profile default. */
18883
- maxTokens: number().int().positive().optional(),
18884
- temperature: number().optional()
18885
- });
18886
- /**
18887
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18888
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18889
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18890
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18891
- * this only through the `llm` cap's methods.
18892
- *
18893
- * One running llama-server child per node in v1 (models are RAM-heavy).
18894
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18895
- * watchdog — operator decision #3).
18896
- */
18897
- var ManagedModelRefSchema = discriminatedUnion("kind", [
18898
- object({
18899
- kind: literal("catalog"),
18900
- catalogId: string()
18901
- }),
18902
- object({
18903
- kind: literal("url"),
18904
- url: string(),
18905
- sha256: string().optional()
18906
- }),
18907
- object({
18908
- kind: literal("path"),
18909
- path: string()
18910
- })
18911
- ]);
18912
- var ManagedRuntimeConfigSchema = object({
18913
- /** WHERE the runtime lives — hub or any agent. */
18914
- nodeId: string(),
18915
- /** Closed for v1; 'ollama' is a v2 candidate. */
18916
- engine: _enum(["llama-cpp"]),
18917
- model: ManagedModelRefSchema,
18918
- contextSize: number().int().default(4096),
18919
- /** 0 = CPU-only. */
18920
- gpuLayers: number().int().default(0),
18921
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18922
- threads: number().int().optional(),
18923
- /** Concurrent slots. */
18924
- parallel: number().int().default(1),
18925
- /** Else lazy: first generate boots it. */
18926
- autoStart: boolean().default(false),
18927
- /** 0 = never; frees RAM after quiet periods. */
18928
- idleStopMinutes: number().int().default(30)
18929
- });
18930
- var LlmRuntimeStatusSchema = object({
18931
- /** Status is ALWAYS node-qualified. */
18932
- nodeId: string(),
18933
- state: _enum([
18934
- "stopped",
18935
- "downloading",
18936
- "starting",
18937
- "ready",
18938
- "crashed",
18939
- "failed"
18940
- ]),
18941
- pid: number().optional(),
18942
- port: number().optional(),
18943
- modelPath: string().optional(),
18944
- modelId: string().optional(),
18945
- downloadProgress: number().min(0).max(1).optional(),
18946
- lastError: string().optional(),
18947
- crashesInWindow: number(),
18948
- /** Child RSS (sampled best-effort). */
18949
- memoryBytes: number().optional(),
18950
- vramBytes: number().optional()
19033
+ label: string(),
19034
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
19035
+ ordinal: number().int().min(1).max(5).nullable(),
19036
+ flags: object({
19037
+ critical: boolean().optional(),
19038
+ silent: boolean().optional(),
19039
+ noPush: boolean().optional()
19040
+ }).optional(),
19041
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
19042
+ requires: array(string()).optional(),
19043
+ description: string().optional()
18951
19044
  });
18952
- var LlmNodeModelSchema = object({
18953
- file: string(),
18954
- sizeBytes: number(),
18955
- catalogId: string().optional(),
18956
- installedAt: number().optional()
19045
+ /** The full capability block consulted before dispatch. */
19046
+ var TargetKindCapsSchema = object({
19047
+ attachments: object({
19048
+ mediaTypes: array(AttachmentMediaTypeSchema),
19049
+ mode: _enum([
19050
+ "url",
19051
+ "bytes",
19052
+ "both"
19053
+ ]),
19054
+ max: number().int().nonnegative(),
19055
+ maxBytes: number().int().positive().optional()
19056
+ }),
19057
+ /** Max action buttons (0 = none). */
19058
+ actions: number().int().nonnegative(),
19059
+ levels: array(TargetKindLevelSchema),
19060
+ format: array(NotificationFormatSchema),
19061
+ clickUrl: boolean(),
19062
+ sound: boolean(),
19063
+ ttl: boolean(),
19064
+ bodyMaxLen: number().int().positive()
18957
19065
  });
18958
- var LlmRuntimeDiskUsageSchema = object({
18959
- nodeId: string(),
18960
- modelsBytes: number(),
18961
- freeBytes: number().optional()
19066
+ /**
19067
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
19068
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
19069
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
19070
+ * the union is large and not meant for runtime validation here; the exported
19071
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
19072
+ */
19073
+ var ConfigSchemaPassthrough = unknown();
19074
+ var TargetKindSchema = object({
19075
+ kind: string(),
19076
+ label: string(),
19077
+ icon: string(),
19078
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
19079
+ addonId: string(),
19080
+ configSchema: ConfigSchemaPassthrough,
19081
+ supportsDiscovery: boolean(),
19082
+ caps: TargetKindCapsSchema
18962
19083
  });
18963
- method(LlmGenerateBaseInputSchema.extend({
18964
- images: array(LlmImageSchema).optional(),
18965
- runtime: ManagedRuntimeConfigSchema,
18966
- /** The managed profile's timeout, threaded by the hub provider. */
18967
- timeoutMs: number().int().positive().optional()
18968
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18969
- kind: "mutation",
18970
- auth: "admin"
18971
- }), method(object({}), _void(), {
18972
- kind: "mutation",
18973
- auth: "admin"
18974
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18975
- kind: "mutation",
18976
- auth: "admin"
18977
- }), method(object({ file: string() }), _void(), {
18978
- kind: "mutation",
18979
- auth: "admin"
18980
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18981
19084
  /**
18982
- * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18983
- * methods concat-fan across providers; single-row methods route to ONE
18984
- * provider by the `addonId` in the call input (the notification-output
18985
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18986
- * (hub-placed); the cap stays open for future providers.
18987
- *
18988
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18989
- * `apiKey` is a password field — providers REDACT it on read and merge on
18990
- * write; a stored key NEVER round-trips to a client.
19085
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
19086
+ * (return a presence marker only) when serving `listTargets` — never
19087
+ * round-trip a stored secret to the UI.
18991
19088
  */
18992
- var LlmProfileKindSchema = _enum([
18993
- "openai-compatible",
18994
- "openai",
18995
- "anthropic",
18996
- "google",
18997
- "managed-local"
18998
- ]);
18999
- var LlmProfileSchema = object({
19089
+ var TargetSchema = object({
19000
19090
  id: string(),
19001
19091
  name: string(),
19002
- kind: LlmProfileKindSchema,
19003
- /** Stamped by the provider — keeps the fanned catalog routable. */
19092
+ kind: string(),
19004
19093
  addonId: string(),
19005
19094
  enabled: boolean(),
19006
- /** Vendor model id, or the managed runtime's loaded model. */
19007
- model: string(),
19008
- /** Required for openai-compatible; override for cloud kinds. */
19009
- baseUrl: string().optional(),
19010
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
19011
- apiKey: string().optional(),
19012
- supportsVision: boolean(),
19013
- temperature: number().min(0).max(2).optional(),
19014
- maxTokens: number().int().positive().optional(),
19015
- timeoutMs: number().int().positive().default(6e4),
19016
- extraHeaders: record(string(), string()).optional(),
19017
- /** kind === 'managed-local' only (spec §4). */
19018
- runtime: ManagedRuntimeConfigSchema.optional()
19095
+ config: record(string(), unknown())
19019
19096
  });
19020
- /** ConfigUISchema tree passed through untyped on the wire (the
19021
- * notification-output `ConfigSchemaPassthrough` precedent at
19022
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
19023
- var ConfigSchemaPassthrough = unknown();
19024
- var LlmProfileKindDescriptorSchema = object({
19025
- kind: LlmProfileKindSchema,
19026
- label: string(),
19027
- icon: string(),
19028
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
19029
- addonId: string(),
19030
- configSchema: ConfigSchemaPassthrough
19097
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
19098
+ var DiscoveredTargetSchema = object({
19099
+ kind: string(),
19100
+ suggestedName: string(),
19101
+ config: record(string(), unknown())
19031
19102
  });
19032
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
19033
- var LlmDefaultSchema = object({
19034
- selector: LlmDefaultSelectorSchema,
19035
- profileId: string()
19103
+ /** The degrade engine's report — what was resolved / dropped / degraded. */
19104
+ var RenderedAsSchema = object({
19105
+ level: string(),
19106
+ format: NotificationFormatSchema,
19107
+ attachmentsSent: number().int().nonnegative(),
19108
+ actionsSent: number().int().nonnegative(),
19109
+ truncated: boolean(),
19110
+ dropped: array(string())
19036
19111
  });
19037
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
19038
- var LlmUsageRollupSchema = object({
19039
- day: string(),
19040
- consumer: string(),
19041
- profileId: string(),
19042
- calls: number(),
19043
- okCalls: number(),
19044
- errorCalls: number(),
19045
- inputTokens: number(),
19046
- outputTokens: number(),
19047
- avgLatencyMs: number()
19112
+ var SendResultSchema = object({
19113
+ success: boolean(),
19114
+ error: string().optional(),
19115
+ renderedAs: RenderedAsSchema.optional()
19048
19116
  });
19049
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
19050
- var ManagedModelCatalogEntrySchema = object({
19117
+ /** Same shape as SendResult — kept as a distinct name for the test panel. */
19118
+ var TestResultSchema = SendResultSchema;
19119
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
19120
+ kind: string(),
19121
+ config: record(string(), unknown()).optional()
19122
+ }), array(DiscoveredTargetSchema)), method(object({
19123
+ targetId: string(),
19124
+ notification: NotificationSchema
19125
+ }), SendResultSchema, { kind: "mutation" }), method(object({
19126
+ targetId: string(),
19127
+ sample: NotificationSchema.optional()
19128
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
19129
+ targetId: string(),
19130
+ enabled: boolean()
19131
+ }), _void(), { kind: "mutation" });
19132
+ /**
19133
+ * notification-rules — the Notification Center rule surface (P1 core).
19134
+ *
19135
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
19136
+ * (operator decisions D-1/D-2/D-3 are binding):
19137
+ *
19138
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
19139
+ * `notification-center` module), hooked on the durable persistence
19140
+ * moments (object-event insert, TrackCloser.closeExpired) with a
19141
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
19142
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
19143
+ * FIRST persisted detection matching the conditions (per-track dedup,
19144
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
19145
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
19146
+ * - DISPATCH stays behind `notification-output` (rules reference targets
19147
+ * by id; per-backend params are a passthrough blob capped by the
19148
+ * target kind's own caps/degrade engine).
19149
+ *
19150
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
19151
+ * server-injected caller identity — the first `caller: 'required'`
19152
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
19153
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
19154
+ * windows, and the optional label/identity/plate matchers. User rules,
19155
+ * private zones, per-recipient fan-out and the wider condition table are
19156
+ * P2+ (see spec §7).
19157
+ *
19158
+ * All schemas here are the single source of truth — `NcRule` etc. are
19159
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
19160
+ * schema/interface drift is explicitly not repeated).
19161
+ */
19162
+ /**
19163
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
19164
+ * The value maps 1:1 onto the evaluated record kind:
19165
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
19166
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
19167
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
19168
+ * change of a LINKED device, one row per linked camera)
19169
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
19170
+ * delivery / pick-up)
19171
+ *
19172
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
19173
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
19174
+ * this one field keeps the schema additive — a rule still declares exactly
19175
+ * one trigger.
19176
+ */
19177
+ var NcDeliverySchema = _enum([
19178
+ "immediate",
19179
+ "track-end",
19180
+ "device-event",
19181
+ "package-event"
19182
+ ]);
19183
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
19184
+ var NcScheduleSchema = object({
19185
+ windows: array(object({
19186
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
19187
+ days: array(number().int().min(0).max(6)).min(1),
19188
+ startMinute: number().int().min(0).max(1439),
19189
+ endMinute: number().int().min(0).max(1439)
19190
+ })).min(1),
19191
+ /** IANA timezone; default = hub host timezone. */
19192
+ timezone: string().optional(),
19193
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
19194
+ invert: boolean().optional()
19195
+ });
19196
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
19197
+ var NcPlateMatcherSchema = object({
19198
+ values: array(string().min(1)).min(1),
19199
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
19200
+ maxDistance: number().int().min(0).max(3).default(1)
19201
+ });
19202
+ /**
19203
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
19204
+ * occupancy edge for a device — optionally narrowed to a single admin
19205
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
19206
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
19207
+ * - `became-free` — count crossed ≥ `count` → below it
19208
+ * - `>=` / `<=` — count is at/over or at/under `count`
19209
+ * `sustainSeconds` requires the condition hold continuously that long
19210
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
19211
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
19212
+ * the condition never matches. Confirmed edge-state survives addon restarts
19213
+ * (declared SQLite collection, reseeded on boot).
19214
+ */
19215
+ var NcOccupancyConditionSchema = object({
19216
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
19217
+ zoneId: string().optional(),
19218
+ /** Object class to count; absent = any class. */
19219
+ className: string().optional(),
19220
+ op: _enum([
19221
+ "became-occupied",
19222
+ "became-free",
19223
+ ">=",
19224
+ "<="
19225
+ ]).default("became-occupied"),
19226
+ count: number().int().min(0).default(1),
19227
+ sustainSeconds: number().int().min(0).max(3600).default(15)
19228
+ });
19229
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
19230
+ var NcZoneConditionSchema = object({
19231
+ ids: array(string().min(1)).min(1),
19232
+ /** Quantifier over `ids` — at least one / every one visited. */
19233
+ match: _enum(["any", "all"]).default("any")
19234
+ });
19235
+ /**
19236
+ * The P1 condition set — a flat AND of groups; absent group = pass;
19237
+ * membership lists are OR within the list (spec §2.3).
19238
+ */
19239
+ var NcConditionsSchema = object({
19240
+ /** Device scope — absent = all devices. */
19241
+ devices: array(number()).optional(),
19242
+ /** Detector class names (any overlap with the record's class set). */
19243
+ classes: array(string().min(1)).optional(),
19244
+ /** Veto classes — any overlap fails the rule. */
19245
+ classesExclude: array(string().min(1)).optional(),
19246
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
19247
+ minConfidence: number().min(0).max(1).optional(),
19248
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
19249
+ zones: NcZoneConditionSchema.optional(),
19250
+ /** Veto zones — any hit fails the rule. */
19251
+ zonesExclude: array(string().min(1)).optional(),
19252
+ /**
19253
+ * Exact (case-insensitive) match on the record's collapsed `label`
19254
+ * (identity name / plate text / subclass).
19255
+ */
19256
+ labelEquals: array(string().min(1)).optional(),
19257
+ /**
19258
+ * Identity matcher. P1 boundary: matched against the record's collapsed
19259
+ * `label` (the identity display name propagated by the face pipeline) —
19260
+ * identity-ID matching rides in P2 when identity ids reach the record.
19261
+ */
19262
+ identities: array(string().min(1)).optional(),
19263
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
19264
+ plates: NcPlateMatcherSchema.optional(),
19265
+ /**
19266
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
19267
+ * Same P1 boundary: matched against the record's collapsed `label` (the
19268
+ * identity display name). A record with NO label passes (nothing to
19269
+ * exclude), unlike the include variant which fails on an absent label.
19270
+ */
19271
+ identitiesExclude: array(string().min(1)).optional(),
19272
+ /**
19273
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
19274
+ * TRACK-END only: importance is scored at track close, so it does not exist
19275
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
19276
+ * close the value is threaded via the close-time info (the `Track` clone is
19277
+ * captured before the DB row is updated, so it would otherwise read stale).
19278
+ * Fails when the record carries no importance (never guess quality — the
19279
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
19280
+ */
19281
+ minImportance: number().min(0).max(1).optional(),
19282
+ /**
19283
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
19284
+ * TRACK-END only: an `immediate` / object-event subject has no closed
19285
+ * lifespan, so a dwell condition never matches immediate delivery
19286
+ * (documented choice — the object-event record carries no `firstSeen`,
19287
+ * so dwell cannot be computed from what the subject actually carries).
19288
+ */
19289
+ minDwellSeconds: number().min(0).optional(),
19290
+ /**
19291
+ * Detection provenance filter. `any` (default / absent) matches every
19292
+ * source; otherwise the subject's source must equal it. Legacy records
19293
+ * with no stamped source are treated as `pipeline`. The union spans both
19294
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
19295
+ * tracks carry `sensor`.
19296
+ */
19297
+ source: _enum([
19298
+ "pipeline",
19299
+ "onboard",
19300
+ "sensor",
19301
+ "any"
19302
+ ]).optional(),
19303
+ /**
19304
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
19305
+ * detector `minConfidence` (that gates the object-detection score; this
19306
+ * gates the recognition/OCR match score). Fails when the subject carries
19307
+ * no label-match confidence (never guess). TRACK-END only: the confidence
19308
+ * lives on the recognition result and reaches the subject at track close.
19309
+ *
19310
+ * What it measures precisely (plumbed at track close — the closer threads
19311
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
19312
+ * `importance`): the BEST recognition match confidence observed for the
19313
+ * label the track carries at close — for a face, the peak cosine similarity
19314
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
19315
+ * for a plate, the peak OCR read score of the best-held plate
19316
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
19317
+ * one track the higher of the two is used. A track that ended with no
19318
+ * confident identity/plate match carries no value, so the condition fails
19319
+ * closed for it (an un-recognized subject).
19320
+ */
19321
+ minLabelConfidence: number().min(0).max(1).optional(),
19322
+ /**
19323
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
19324
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
19325
+ * against the token carried on the device-event subject (extracted from the
19326
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
19327
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
19328
+ * eventType, so gate those with {@link sensorKinds} instead.
19329
+ */
19330
+ eventTypeTokens: array(string().min(1)).optional(),
19331
+ /**
19332
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
19333
+ * `contact`, `button`, `device-event`) — matched against the persisted
19334
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
19335
+ */
19336
+ sensorKinds: array(string().min(1)).optional(),
19337
+ /**
19338
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
19339
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
19340
+ * when the subject's phase does not match (a subject always carries a phase
19341
+ * on the package-event trigger).
19342
+ */
19343
+ packagePhase: _enum([
19344
+ "delivered",
19345
+ "picked-up",
19346
+ "both"
19347
+ ]).optional(),
19348
+ /**
19349
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
19350
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
19351
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
19352
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
19353
+ */
19354
+ customZones: array(MaskPolygonShapeSchema).optional(),
19355
+ /**
19356
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
19357
+ * (optionally zone/class-scoped) occupancy count crosses the configured
19358
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
19359
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
19360
+ */
19361
+ occupancy: NcOccupancyConditionSchema.optional()
19362
+ });
19363
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
19364
+ var NcRuleTargetSchema = object({
19365
+ /** `notification-output` Target id. */
19366
+ targetId: string().min(1),
19367
+ /**
19368
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
19369
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
19370
+ * degrade engine drops what the backend can't render.
19371
+ */
19372
+ params: record(string(), unknown()).optional()
19373
+ });
19374
+ /**
19375
+ * Media attachment policy (P1 still-image subset).
19376
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
19377
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
19378
+ * matched on identities attaches the subject's `faceCrop`, one matched on
19379
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
19380
+ * (or when the specific crop is missing) degrades to `best`, then
19381
+ * `keyFrame`, then no attachment — never delaying the send. The matched
19382
+ * condition summary is frozen on the outbox row at enqueue (like the rule
19383
+ * name), so the choice never drifts from the record that fired it.
19384
+ * - `keyFrame` — the clean scene frame (no subject box).
19385
+ * - `none` — no attachment.
19386
+ */
19387
+ var NcMediaPolicySchema = object({ attach: _enum([
19388
+ "best",
19389
+ "best-matching",
19390
+ "keyFrame",
19391
+ "none"
19392
+ ]).default("best") });
19393
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
19394
+ var NcThrottleSchema = object({
19395
+ cooldownSec: number().int().min(0).max(86400).default(60),
19396
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
19397
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
19398
+ });
19399
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
19400
+ var NcRuleInputSchema = object({
19401
+ name: string().min(1).max(200),
19402
+ enabled: boolean().default(true),
19403
+ delivery: NcDeliverySchema,
19404
+ conditions: NcConditionsSchema.default({}),
19405
+ schedule: NcScheduleSchema.optional(),
19406
+ targets: array(NcRuleTargetSchema).min(1),
19407
+ media: NcMediaPolicySchema.default({ attach: "best" }),
19408
+ throttle: NcThrottleSchema.default({
19409
+ cooldownSec: 60,
19410
+ scope: "rule-device"
19411
+ }),
19412
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
19413
+ template: object({
19414
+ title: string().max(500).optional(),
19415
+ body: string().max(2e3).optional()
19416
+ }).optional(),
19417
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
19418
+ priority: number().int().min(1).max(5).default(3),
19419
+ /**
19420
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
19421
+ * behaviour, visible to all, read-only in the viewer). Present = personal
19422
+ * rule owned by this userId. Server-stamped; never trusted from a client.
19423
+ */
19424
+ ownerUserId: string().optional()
19425
+ });
19426
+ /**
19427
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
19428
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
19429
+ * NOT a client-authored input field (it lives on the persisted rule, not the
19430
+ * input), so it is added here explicitly to let the store's per-target opt-out
19431
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
19432
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
19433
+ * `updateRule` patch.
19434
+ */
19435
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
19436
+ /** A persisted rule. */
19437
+ var NcRuleSchema = NcRuleInputSchema.extend({
19438
+ id: string(),
19439
+ /** userId of the admin who created the rule (server-stamped caller). */
19440
+ createdBy: string(),
19441
+ createdAt: number(),
19442
+ updatedAt: number(),
19443
+ /**
19444
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
19445
+ * send time. Only a target's OWNER may add/remove its id (server-checked
19446
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
19447
+ */
19448
+ disabledTargetIds: array(string()).default([])
19449
+ });
19450
+ var NcTestResultSchema = object({
19451
+ recordId: string(),
19452
+ recordKind: _enum([
19453
+ "object-event",
19454
+ "track",
19455
+ "device-event",
19456
+ "package-event"
19457
+ ]),
19458
+ deviceId: number(),
19459
+ timestamp: number(),
19460
+ wouldFire: boolean(),
19461
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
19462
+ failedCondition: string().optional(),
19463
+ className: string().optional(),
19464
+ label: string().optional()
19465
+ });
19466
+ var NcConditionDescriptorSchema = object({
19467
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
19051
19468
  id: string(),
19469
+ group: _enum([
19470
+ "scope",
19471
+ "class",
19472
+ "zones",
19473
+ "quality",
19474
+ "label",
19475
+ "schedule",
19476
+ "device",
19477
+ "package",
19478
+ "occupancy"
19479
+ ]),
19052
19480
  label: string(),
19053
- family: string(),
19054
- purpose: _enum(["text", "vision"]),
19055
- url: string(),
19056
- sha256: string(),
19057
- sizeBytes: number(),
19058
- quantization: string(),
19059
- /** Load-time guidance shown in the picker. */
19060
- minRamBytes: number(),
19061
- contextSizeDefault: number().int(),
19062
- /** Vision models: companion projector file. */
19063
- mmprojUrl: string().optional()
19481
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
19482
+ valueType: _enum([
19483
+ "deviceIdList",
19484
+ "stringList",
19485
+ "number01",
19486
+ "number",
19487
+ "sourceSelect",
19488
+ "zoneSelection",
19489
+ "zoneIdList",
19490
+ "schedule",
19491
+ "plateMatcher",
19492
+ "packagePhase",
19493
+ "polygonDraw",
19494
+ "occupancy"
19495
+ ]),
19496
+ operator: _enum([
19497
+ "in",
19498
+ "notIn",
19499
+ "anyOf",
19500
+ "allOf",
19501
+ "gte",
19502
+ "fuzzyIn",
19503
+ "withinSchedule"
19504
+ ]),
19505
+ /** Which delivery kinds the condition applies to. */
19506
+ appliesTo: array(NcDeliverySchema),
19507
+ phase: string(),
19508
+ description: string().optional()
19064
19509
  });
19065
- var LlmRuntimeNodeSchema = object({
19066
- nodeId: string(),
19067
- reachable: boolean(),
19068
- status: LlmRuntimeStatusSchema.optional(),
19069
- disk: LlmRuntimeDiskUsageSchema.optional(),
19070
- error: string().optional()
19510
+ /**
19511
+ * The delivery lifecycle status of a history row — a straight read of the
19512
+ * durable outbox row's own status (single source of truth):
19513
+ * - `pending` — enqueued, in-flight or retrying with backoff
19514
+ * - `sent` — delivered (terminal)
19515
+ * - `dead` — dead-lettered after exhausting retries / a permanent
19516
+ * backend rejection / a deleted target (terminal; carries
19517
+ * the failure `error`)
19518
+ *
19519
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
19520
+ * user dimension (quiet hours / snooze) and are additive when they land.
19521
+ */
19522
+ var NcHistoryStatusSchema = _enum([
19523
+ "pending",
19524
+ "sent",
19525
+ "dead"
19526
+ ]);
19527
+ /** The evaluated record kind a history row descends from (one per trigger). */
19528
+ var NcHistoryRecordKindSchema = _enum([
19529
+ "object-event",
19530
+ "track-end",
19531
+ "device-event",
19532
+ "package-event"
19533
+ ]);
19534
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
19535
+ var NcHistorySubjectSchema = object({
19536
+ className: string(),
19537
+ label: string().optional(),
19538
+ confidence: number().optional(),
19539
+ zones: array(string()),
19540
+ timestamp: number()
19541
+ });
19542
+ /**
19543
+ * One delivery-history row. This is a read-only VIEW over the durable
19544
+ * outbox row (single source of truth — the same row the drain loop drives;
19545
+ * NO second write path, so history can never drift from delivery state).
19546
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
19547
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
19548
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
19549
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
19550
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
19551
+ * P1 (admin scope only).
19552
+ */
19553
+ var NcHistoryEntrySchema = object({
19554
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
19555
+ id: string(),
19556
+ ruleId: string(),
19557
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
19558
+ ruleName: string(),
19559
+ /** The rule urgency/trigger that produced this delivery. */
19560
+ delivery: NcDeliverySchema,
19561
+ targetId: string(),
19562
+ deviceId: number(),
19563
+ recordKind: NcHistoryRecordKindSchema,
19564
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
19565
+ recordId: string(),
19566
+ /** Present for track-scoped deliveries (object-event / track-end). */
19567
+ trackId: string().optional(),
19568
+ status: NcHistoryStatusSchema,
19569
+ /** Delivery attempts made so far. */
19570
+ attempts: number().int(),
19571
+ /** Fire time (outbox enqueue). */
19572
+ createdAt: number(),
19573
+ /** Last transition time (terminal for sent / dead). */
19574
+ updatedAt: number(),
19575
+ /** Failure detail — present on a `dead` row. */
19576
+ error: string().optional(),
19577
+ subject: NcHistorySubjectSchema
19071
19578
  });
19072
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
19073
- var ProfileRefInputSchema = object({
19074
- addonId: string(),
19075
- profileId: string()
19579
+ /**
19580
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
19581
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
19582
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
19583
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
19584
+ */
19585
+ var NcHistoryFilterSchema = object({
19586
+ ruleId: string().optional(),
19587
+ deviceId: number().optional(),
19588
+ status: NcHistoryStatusSchema.optional(),
19589
+ since: number().optional(),
19590
+ until: number().optional(),
19591
+ limit: number().int().min(1).max(500).default(100)
19076
19592
  });
19077
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
19078
- kind: "mutation",
19079
- auth: "admin"
19080
- }), method(ProfileRefInputSchema, _void(), {
19593
+ 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 }), {
19081
19594
  kind: "mutation",
19082
- auth: "admin"
19083
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
19595
+ auth: "admin",
19596
+ caller: "required"
19597
+ }), method(object({
19598
+ ruleId: string(),
19599
+ patch: NcRulePatchSchema
19600
+ }), object({ rule: NcRuleSchema }), {
19084
19601
  kind: "mutation",
19085
- auth: "admin"
19086
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
19087
- selector: LlmDefaultSelectorSchema,
19088
- profileId: string().nullable()
19089
- }), _void(), {
19602
+ auth: "admin",
19603
+ caller: "required"
19604
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
19090
19605
  kind: "mutation",
19091
19606
  auth: "admin"
19092
19607
  }), method(object({
19093
- since: number().optional(),
19094
- until: number().optional(),
19095
- consumer: string().optional(),
19096
- profileId: string().optional()
19097
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
19098
- nodeId: string(),
19099
- model: ManagedModelRefSchema
19100
- }), _void(), {
19608
+ ruleId: string(),
19609
+ enabled: boolean()
19610
+ }), object({ success: literal(true) }), {
19101
19611
  kind: "mutation",
19102
19612
  auth: "admin"
19103
19613
  }), method(object({
19104
- nodeId: string(),
19105
- file: string()
19106
- }), _void(), {
19107
- kind: "mutation",
19108
- auth: "admin"
19109
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
19110
- kind: "mutation",
19111
- auth: "admin"
19112
- }), method(ProfileRefInputSchema, _void(), {
19614
+ rule: NcRuleInputSchema,
19615
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
19616
+ }), object({ results: array(NcTestResultSchema) }), {
19113
19617
  kind: "mutation",
19114
19618
  auth: "admin"
19115
- });
19619
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
19116
19620
  /**
19117
19621
  * Zod schemas for persisted record types.
19118
19622
  *
@@ -19798,7 +20302,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19798
20302
  }), method(object({
19799
20303
  eventId: string(),
19800
20304
  kind: MediaFileKindEnum.optional()
19801
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
20305
+ }), array(MediaFileSchema).readonly()), method(object({
20306
+ trackId: string(),
20307
+ kinds: array(MediaFileKindEnum).optional()
20308
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
19802
20309
  deviceId: number(),
19803
20310
  timestamp: number(),
19804
20311
  frameWidth: number(),
@@ -19819,76 +20326,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19819
20326
  eventId: string(),
19820
20327
  timestamp: number()
19821
20328
  });
19822
- /**
19823
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
19824
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
19825
- * caps into per-camera event-kind descriptors.
19826
- *
19827
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
19828
- * is NOT duplicated here — every entry is derived from the single
19829
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
19830
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
19831
- * control cap means adding one line here (and a taxonomy entry); the anti-
19832
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
19833
- * eventful cap is missing.
19834
- */
19835
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
19836
- var LEGACY_ICON = {
19837
- motion: "motion",
19838
- audio: "audio",
19839
- person: "person",
19840
- vehicle: "vehicle",
19841
- animal: "animal",
19842
- package: "package",
19843
- door: "door",
19844
- pir: "pir",
19845
- smoke: "smoke",
19846
- water: "water",
19847
- button: "button",
19848
- generic: "generic",
19849
- gas: "smoke",
19850
- vibration: "generic",
19851
- tamper: "generic",
19852
- presence: "person",
19853
- lock: "generic",
19854
- siren: "generic",
19855
- switch: "generic",
19856
- doorbell: "button"
19857
- };
19858
- function legacyIcon(iconId) {
19859
- return LEGACY_ICON[iconId] ?? "generic";
19860
- }
19861
- /**
19862
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
19863
- * The anti-drift guard cross-checks this against the eventful caps declared
19864
- * in `packages/types/src/capabilities/*.cap.ts`.
19865
- */
19866
- var CAP_TO_KIND = {
19867
- contact: "contact",
19868
- motion: "motion-sensor",
19869
- smoke: "smoke",
19870
- flood: "flood",
19871
- gas: "gas",
19872
- "carbon-monoxide": "carbon-monoxide",
19873
- vibration: "vibration",
19874
- tamper: "tamper",
19875
- presence: "presence",
19876
- "enum-sensor": "enum-sensor",
19877
- "event-emitter": "device-event",
19878
- "lock-control": "lock",
19879
- switch: "switch",
19880
- button: "button",
19881
- doorbell: "doorbell"
19882
- };
19883
- function buildDescriptor(capName, kind) {
19884
- const t = EVENT_TAXONOMY[kind];
19885
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
19886
- return {
19887
- ...t,
19888
- icon: legacyIcon(t.iconId)
19889
- };
19890
- }
19891
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
19892
20329
  var CameraPipelineConfigSchema = object({
19893
20330
  engine: PipelineEngineChoiceSchema.optional(),
19894
20331
  steps: array(PipelineStepInputSchema).readonly(),
@@ -20374,6 +20811,76 @@ method(object({
20374
20811
  auth: "admin"
20375
20812
  });
20376
20813
  /**
20814
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
20815
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
20816
+ * caps into per-camera event-kind descriptors.
20817
+ *
20818
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
20819
+ * is NOT duplicated here — every entry is derived from the single
20820
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
20821
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
20822
+ * control cap means adding one line here (and a taxonomy entry); the anti-
20823
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
20824
+ * eventful cap is missing.
20825
+ */
20826
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
20827
+ var LEGACY_ICON = {
20828
+ motion: "motion",
20829
+ audio: "audio",
20830
+ person: "person",
20831
+ vehicle: "vehicle",
20832
+ animal: "animal",
20833
+ package: "package",
20834
+ door: "door",
20835
+ pir: "pir",
20836
+ smoke: "smoke",
20837
+ water: "water",
20838
+ button: "button",
20839
+ generic: "generic",
20840
+ gas: "smoke",
20841
+ vibration: "generic",
20842
+ tamper: "generic",
20843
+ presence: "person",
20844
+ lock: "generic",
20845
+ siren: "generic",
20846
+ switch: "generic",
20847
+ doorbell: "button"
20848
+ };
20849
+ function legacyIcon(iconId) {
20850
+ return LEGACY_ICON[iconId] ?? "generic";
20851
+ }
20852
+ /**
20853
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
20854
+ * The anti-drift guard cross-checks this against the eventful caps declared
20855
+ * in `packages/types/src/capabilities/*.cap.ts`.
20856
+ */
20857
+ var CAP_TO_KIND = {
20858
+ contact: "contact",
20859
+ motion: "motion-sensor",
20860
+ smoke: "smoke",
20861
+ flood: "flood",
20862
+ gas: "gas",
20863
+ "carbon-monoxide": "carbon-monoxide",
20864
+ vibration: "vibration",
20865
+ tamper: "tamper",
20866
+ presence: "presence",
20867
+ "enum-sensor": "enum-sensor",
20868
+ "event-emitter": "device-event",
20869
+ "lock-control": "lock",
20870
+ switch: "switch",
20871
+ button: "button",
20872
+ doorbell: "doorbell"
20873
+ };
20874
+ function buildDescriptor(capName, kind) {
20875
+ const t = EVENT_TAXONOMY[kind];
20876
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
20877
+ return {
20878
+ ...t,
20879
+ icon: legacyIcon(t.iconId)
20880
+ };
20881
+ }
20882
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
20883
+ /**
20377
20884
  * server-management — per-NODE singleton capability for a node's ROOT
20378
20885
  * package lifecycle (runtime-updatable node packages).
20379
20886
  *
@@ -21828,7 +22335,28 @@ var FaceInfoSchema = object({
21828
22335
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
21829
22336
  * track produced no key frame (e.g. native/onboard source) — the UI falls
21830
22337
  * back to the inline `base64` face crop. */
21831
- keyFrameMediaKey: string().optional()
22338
+ keyFrameMediaKey: string().optional(),
22339
+ /** Winning identity-match cosine (0..1) for this face's track, when an
22340
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
22341
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
22342
+ * faces that were never auto-recognized. */
22343
+ bestMatchScore: number().optional(),
22344
+ /** Native-scale face short side (px) at recognition time, when the runner
22345
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
22346
+ * legacy rows / runners that reported no native measure. */
22347
+ nativeFaceShortSidePx: number().optional(),
22348
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
22349
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
22350
+ * but blocked only by the recognition size floor). Mutually exclusive with
22351
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
22352
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
22353
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
22354
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
22355
+ suggestedIdentityId: string().optional(),
22356
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
22357
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
22358
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
22359
+ suggestedMatchScore: number().optional()
21832
22360
  });
21833
22361
  var FaceFilterEnum = _enum([
21834
22362
  "unassigned",
@@ -23871,36 +24399,6 @@ Object.freeze({
23871
24399
  addonId: null,
23872
24400
  access: "view"
23873
24401
  },
23874
- "advancedNotifier.deleteRule": {
23875
- capName: "advanced-notifier",
23876
- capScope: "system",
23877
- addonId: null,
23878
- access: "delete"
23879
- },
23880
- "advancedNotifier.getHistory": {
23881
- capName: "advanced-notifier",
23882
- capScope: "system",
23883
- addonId: null,
23884
- access: "view"
23885
- },
23886
- "advancedNotifier.getRules": {
23887
- capName: "advanced-notifier",
23888
- capScope: "system",
23889
- addonId: null,
23890
- access: "view"
23891
- },
23892
- "advancedNotifier.testRule": {
23893
- capName: "advanced-notifier",
23894
- capScope: "system",
23895
- addonId: null,
23896
- access: "create"
23897
- },
23898
- "advancedNotifier.upsertRule": {
23899
- capName: "advanced-notifier",
23900
- capScope: "system",
23901
- addonId: null,
23902
- access: "create"
23903
- },
23904
24402
  "alarmPanel.arm": {
23905
24403
  capName: "alarm-panel",
23906
24404
  capScope: "device",
@@ -26205,6 +26703,60 @@ Object.freeze({
26205
26703
  addonId: null,
26206
26704
  access: "create"
26207
26705
  },
26706
+ "notificationRules.createRule": {
26707
+ capName: "notification-rules",
26708
+ capScope: "system",
26709
+ addonId: null,
26710
+ access: "create"
26711
+ },
26712
+ "notificationRules.deleteRule": {
26713
+ capName: "notification-rules",
26714
+ capScope: "system",
26715
+ addonId: null,
26716
+ access: "delete"
26717
+ },
26718
+ "notificationRules.getConditionCatalog": {
26719
+ capName: "notification-rules",
26720
+ capScope: "system",
26721
+ addonId: null,
26722
+ access: "view"
26723
+ },
26724
+ "notificationRules.getHistory": {
26725
+ capName: "notification-rules",
26726
+ capScope: "system",
26727
+ addonId: null,
26728
+ access: "view"
26729
+ },
26730
+ "notificationRules.getRule": {
26731
+ capName: "notification-rules",
26732
+ capScope: "system",
26733
+ addonId: null,
26734
+ access: "view"
26735
+ },
26736
+ "notificationRules.listRules": {
26737
+ capName: "notification-rules",
26738
+ capScope: "system",
26739
+ addonId: null,
26740
+ access: "view"
26741
+ },
26742
+ "notificationRules.setRuleEnabled": {
26743
+ capName: "notification-rules",
26744
+ capScope: "system",
26745
+ addonId: null,
26746
+ access: "create"
26747
+ },
26748
+ "notificationRules.testRule": {
26749
+ capName: "notification-rules",
26750
+ capScope: "system",
26751
+ addonId: null,
26752
+ access: "create"
26753
+ },
26754
+ "notificationRules.updateRule": {
26755
+ capName: "notification-rules",
26756
+ capScope: "system",
26757
+ addonId: null,
26758
+ access: "create"
26759
+ },
26208
26760
  "notifier.cancel": {
26209
26761
  capName: "notifier",
26210
26762
  capScope: "device",