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