@camstack/addon-provider-ecowitt 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1411 -859
  2. package/dist/addon.mjs +1411 -859
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -2,7 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let http = require("http");
3
3
  let events = require("events");
4
4
  let dgram = require("dgram");
5
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
5
+ //#region ../types/dist/event-category-BLcNejAE.mjs
6
6
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
7
7
  EventCategory["SystemBoot"] = "system.boot";
8
8
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -152,9 +152,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
152
152
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
153
153
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
154
154
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
155
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
156
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
157
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
158
155
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
159
156
  * progress bar the client reconciles via `recordingExport.getExport`. */
160
157
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6833,7 +6830,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6833
6830
  patch: record(string(), unknown())
6834
6831
  }), object({ success: literal(true) });
6835
6832
  object({ deviceId: number() }), unknown().nullable();
6836
- /** Shorthand to define a method schema */
6837
6833
  function method(input, output, options) {
6838
6834
  return {
6839
6835
  input,
@@ -6841,6 +6837,7 @@ function method(input, output, options) {
6841
6837
  kind: options?.kind ?? "query",
6842
6838
  auth: options?.auth ?? "protected",
6843
6839
  ...options?.access !== void 0 ? { access: options.access } : {},
6840
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6844
6841
  timeoutMs: options?.timeoutMs
6845
6842
  };
6846
6843
  }
@@ -8210,6 +8207,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8210
8207
  /** The complete taxonomy dictionary, keyed by kind. */
8211
8208
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8212
8209
  /**
8210
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8211
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8212
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8213
+ * taxonomy surface (timeline, filters, event page).
8214
+ *
8215
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8216
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8217
+ * for the `classes` / `classesExclude` conditions.
8218
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8219
+ * the same class picker, grouped under an Audio header.
8220
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8221
+ * lock / …) for the `sensorKinds` device-event condition.
8222
+ *
8223
+ * Each entry carries `parentKind` so the client can group video subs under
8224
+ * their macro and sensor/control kinds under their category. This surface is
8225
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8226
+ * method, no codegen — so it ships train-free with an addon deploy.
8227
+ */
8228
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8229
+ var NcTaxonomyEntrySchema = object({
8230
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8231
+ kind: string(),
8232
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8233
+ label: string(),
8234
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8235
+ parentKind: string().nullable()
8236
+ });
8237
+ object({
8238
+ videoClasses: array(NcTaxonomyEntrySchema),
8239
+ audioKinds: array(NcTaxonomyEntrySchema),
8240
+ labels: array(NcTaxonomyEntrySchema)
8241
+ });
8242
+ function toEntry(kind, label, parentKind) {
8243
+ return {
8244
+ kind,
8245
+ label,
8246
+ parentKind
8247
+ };
8248
+ }
8249
+ /**
8250
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8251
+ * (macros before their subs), which the client relies on for stable grouping.
8252
+ */
8253
+ function buildNcTaxonomy() {
8254
+ const all = Object.values(EVENT_TAXONOMY);
8255
+ return {
8256
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8257
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8258
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8259
+ };
8260
+ }
8261
+ Object.freeze(buildNcTaxonomy());
8262
+ /**
8213
8263
  * Error types for the safe expression engine. Two distinct classes so callers
8214
8264
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8215
8265
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -12195,6 +12245,22 @@ var CameraMetricsSchema = object({
12195
12245
  ])
12196
12246
  });
12197
12247
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
12248
+ /**
12249
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
12250
+ * within the frame, so the executor can re-cut a leaf child ROI at native
12251
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
12252
+ */
12253
+ var NativeCropRefSchema = object({
12254
+ /** Handle keying the retained native surface (node-pinned to its owner). */
12255
+ handle: FrameHandleSchema,
12256
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
12257
+ cropFrameSpace: object({
12258
+ x: number(),
12259
+ y: number(),
12260
+ w: number(),
12261
+ h: number()
12262
+ })
12263
+ });
12198
12264
  var ModelFormatSchema$1 = _enum([
12199
12265
  "onnx",
12200
12266
  "coreml",
@@ -12470,7 +12536,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
12470
12536
  * Omitted ⇒ the runner's default device (current single-engine
12471
12537
  * behaviour). Selects WHICH device pool of the node runs the call.
12472
12538
  */
12473
- deviceKey: string().optional()
12539
+ deviceKey: string().optional(),
12540
+ /**
12541
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
12542
+ * when the parent crop was resolved from the frame's retained NATIVE
12543
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
12544
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
12545
+ * resolution from that surface — the SAME quality path faces already
12546
+ * had — instead of the downscaled parent tile. `handle` keys the native
12547
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
12548
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
12549
+ * the executor's crop-normalized child ROI back into frame-normalized
12550
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
12551
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
12552
+ * (today's behaviour on the fallback path).
12553
+ */
12554
+ nativeCropRef: NativeCropRefSchema.optional()
12474
12555
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
12475
12556
  engine: PipelineEngineChoiceSchema.optional(),
12476
12557
  steps: array(PipelineStepInputSchema).min(1),
@@ -12719,7 +12800,11 @@ var DetailResultSchema = object({
12719
12800
  bbox: NativeCropBboxSchema.optional(),
12720
12801
  embedding: string().optional(),
12721
12802
  label: string().optional(),
12722
- alignedCropJpeg: string().optional()
12803
+ alignedCropJpeg: string().optional(),
12804
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
12805
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
12806
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
12807
+ nativeFaceShortSidePx: number().optional()
12723
12808
  });
12724
12809
  /**
12725
12810
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -12733,6 +12818,12 @@ var motionCooldownMsField = {
12733
12818
  default: 3e4,
12734
12819
  step: 500
12735
12820
  };
12821
+ var maxSessionHoldMsField = {
12822
+ min: 0,
12823
+ max: 6e5,
12824
+ default: 12e4,
12825
+ step: 5e3
12826
+ };
12736
12827
  var motionFpsField = {
12737
12828
  min: 1,
12738
12829
  max: 30,
@@ -12880,6 +12971,19 @@ var RunnerCameraConfigSchema = object({
12880
12971
  "on-motion"
12881
12972
  ]).default("always-on"),
12882
12973
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
12974
+ /**
12975
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
12976
+ * detection session is active and ≥1 confirmed non-stationary track is
12977
+ * still live, the orchestrator keeps the session open past
12978
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
12979
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
12980
+ * ms since the session opened, after which it closes regardless. `0`
12981
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
12982
+ * runner itself — carried here so it shares the per-camera device-settings
12983
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
12984
+ * resolved `CameraDetectionConfig`.
12985
+ */
12986
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
12883
12987
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
12884
12988
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
12885
12989
  motionStreamId: string(),
@@ -12969,7 +13073,7 @@ var RunnerCameraConfigSchema = object({
12969
13073
  */
12970
13074
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
12971
13075
  });
12972
- 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;
13076
+ 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;
12973
13077
  /**
12974
13078
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
12975
13079
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -16496,94 +16600,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
16496
16600
  bundleUrl: string()
16497
16601
  });
16498
16602
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
16499
- var NotificationRuleConditionsSchema = object({
16500
- deviceIds: array(number()).readonly().optional(),
16501
- classNames: array(string()).readonly().optional(),
16502
- zoneIds: array(string()).readonly().optional(),
16503
- minConfidence: number().optional(),
16504
- source: _enum([
16505
- "pipeline",
16506
- "onboard",
16507
- "any"
16508
- ]).optional(),
16509
- schedule: object({
16510
- days: array(number()).readonly(),
16511
- startHour: number(),
16512
- endHour: number()
16513
- }).optional(),
16514
- cooldownSeconds: number().optional(),
16515
- minDwellSeconds: number().optional(),
16516
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
16517
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
16518
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
16519
- eventTypeTokens: array(string()).readonly().optional(),
16520
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
16521
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
16522
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
16523
- clipDescription: object({
16524
- text: string().min(1),
16525
- minSimilarity: number().min(0).max(1)
16526
- }).optional(),
16527
- /** Match events whose recognized-entity label (face identity name or plate
16528
- * vehicle name, propagated onto `event.data.label`) is one of these values.
16529
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
16530
- * vehicle/person> is seen". */
16531
- labels: array(string()).readonly().optional()
16532
- });
16533
- var NotificationRuleTemplateSchema = object({
16534
- title: string(),
16535
- body: string(),
16536
- imageMode: _enum([
16537
- "crop",
16538
- "annotated",
16539
- "full",
16540
- "none"
16541
- ])
16542
- });
16543
- var NotificationRuleSchema = object({
16544
- id: string(),
16545
- name: string(),
16546
- enabled: boolean(),
16547
- eventTypes: array(string()).readonly(),
16548
- conditions: NotificationRuleConditionsSchema,
16549
- outputs: array(string()).readonly(),
16550
- template: NotificationRuleTemplateSchema.optional(),
16551
- priority: _enum([
16552
- "low",
16553
- "normal",
16554
- "high",
16555
- "critical"
16556
- ])
16557
- });
16558
- var NotificationTestResultSchema = object({
16559
- ruleId: string(),
16560
- eventId: string(),
16561
- timestamp: number(),
16562
- wouldFire: boolean(),
16563
- reason: string().optional()
16564
- });
16565
- var NotificationHistoryEntrySchema = object({
16566
- id: string(),
16567
- ruleId: string(),
16568
- ruleName: string(),
16569
- eventId: string(),
16570
- timestamp: number(),
16571
- outputs: array(string()).readonly(),
16572
- success: boolean(),
16573
- error: string().optional(),
16574
- deviceId: number().optional()
16575
- });
16576
- var NotificationHistoryFilterSchema = object({
16577
- ruleId: string().optional(),
16578
- deviceId: number().optional(),
16579
- from: number().optional(),
16580
- to: number().optional(),
16581
- limit: number().optional()
16582
- });
16583
- 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({
16584
- ruleId: string(),
16585
- lookbackMinutes: number()
16586
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
16587
16603
  /**
16588
16604
  * Alerts capability — collection-based internal alert system.
16589
16605
  *
@@ -16770,89 +16786,6 @@ method(object({
16770
16786
  password: string()
16771
16787
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
16772
16788
  /**
16773
- * `login-method` — collection cap through which auth addons contribute
16774
- * their pre-auth login surfaces to the login page. This is the SINGLE,
16775
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
16776
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
16777
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
16778
- * procedure aggregates them for the unauthenticated login page.
16779
- *
16780
- * A contribution is a discriminated union on `kind`:
16781
- *
16782
- * - `redirect` — a declarative button. The login page renders a generic
16783
- * button that navigates to `startUrl` (an addon-owned HTTP route).
16784
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
16785
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
16786
- * login page needs NO change.
16787
- *
16788
- * - `widget` — a Module-Federation widget the login page mounts (via
16789
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
16790
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
16791
- * mechanism kept for future use; no shipped addon uses it on the login
16792
- * page (the passkey ceremony below runs natively in the shell instead).
16793
- *
16794
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
16795
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
16796
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
16797
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
16798
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
16799
- * fetching any remote code pre-auth. Contribution stays unconditional —
16800
- * enrollment state is never leaked pre-auth; visibility is a shell
16801
- * decision.
16802
- *
16803
- * Every contribution carries a `stage`:
16804
- * - `primary` — shown on the first credentials screen (OIDC /
16805
- * magic-link buttons; a future usernameless passkey).
16806
- * - `second-factor` — shown AFTER the password leg, gated on the
16807
- * returned `factors` (passkey-as-2FA today).
16808
- *
16809
- * `mount: skip` — the cap is read server-side by the core auth router
16810
- * (`registry.getCollection('login-method')`), never mounted as its own
16811
- * tRPC router.
16812
- */
16813
- /** When a login method renders in the two-phase login flow. */
16814
- var LoginStageEnum = _enum(["primary", "second-factor"]);
16815
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
16816
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
16817
- object({
16818
- kind: literal("redirect"),
16819
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
16820
- id: string(),
16821
- /** Operator-facing button label. */
16822
- label: string(),
16823
- /** lucide-react icon name. */
16824
- icon: string().optional(),
16825
- /** Addon-owned HTTP route the button navigates to (GET). */
16826
- startUrl: string(),
16827
- stage: LoginStageEnum
16828
- }),
16829
- object({
16830
- kind: literal("widget"),
16831
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
16832
- id: string(),
16833
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
16834
- addonId: string(),
16835
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
16836
- bundle: string(),
16837
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
16838
- remote: WidgetRemoteSchema,
16839
- stage: LoginStageEnum
16840
- }),
16841
- object({
16842
- kind: literal("passkey"),
16843
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
16844
- id: string(),
16845
- /** Operator-facing button label. */
16846
- label: string(),
16847
- stage: LoginStageEnum,
16848
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
16849
- rpId: string(),
16850
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
16851
- origin: string().nullable()
16852
- })
16853
- ]);
16854
- method(_void(), array(LoginMethodContributionSchema).readonly());
16855
- /**
16856
16789
  * Orchestrator-side destination metadata. The orchestrator computes
16857
16790
  * `id = <addonId>:<subId>` from its provider lookup so consumers
16858
16791
  * (admin UI, restore flow) see one canonical key.
@@ -18196,242 +18129,617 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
18196
18129
  kind: "mutation",
18197
18130
  auth: "admin"
18198
18131
  });
18199
- var LogLevelSchema = _enum([
18200
- "debug",
18201
- "info",
18202
- "warn",
18203
- "error"
18132
+ /**
18133
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18134
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18135
+ * caps stay wire-compatible without a circular cap→cap import.
18136
+ *
18137
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
18138
+ * every transport tier structurally, and failed calls still write usage rows.
18139
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18140
+ */
18141
+ var LlmUsageSchema = object({
18142
+ inputTokens: number(),
18143
+ outputTokens: number()
18144
+ });
18145
+ var LlmErrorCodeSchema = _enum([
18146
+ "timeout",
18147
+ "rate-limited",
18148
+ "auth",
18149
+ "refusal",
18150
+ "bad-request",
18151
+ "unavailable",
18152
+ "no-profile",
18153
+ "budget-exceeded",
18154
+ "adapter-error"
18204
18155
  ]);
18205
- var LogEntrySchema = object({
18206
- timestamp: date(),
18207
- level: LogLevelSchema,
18208
- scope: array(string()),
18156
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18157
+ ok: literal(true),
18158
+ text: string(),
18159
+ model: string(),
18160
+ usage: LlmUsageSchema,
18161
+ truncated: boolean(),
18162
+ latencyMs: number()
18163
+ }), object({
18164
+ ok: literal(false),
18165
+ code: LlmErrorCodeSchema,
18209
18166
  message: string(),
18210
- meta: record(string(), unknown()).optional(),
18211
- tags: record(string(), string()).optional()
18212
- });
18213
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18214
- scope: array(string()).optional(),
18215
- level: LogLevelSchema.optional(),
18216
- since: date().optional(),
18217
- until: date().optional(),
18218
- limit: number().optional(),
18219
- tags: record(string(), string()).optional()
18220
- }), array(LogEntrySchema).readonly());
18221
- var CpuBreakdownSchema = object({
18222
- total: number(),
18223
- user: number(),
18224
- system: number(),
18225
- irq: number(),
18226
- nice: number(),
18227
- loadAvg: tuple([
18228
- number(),
18229
- number(),
18230
- number()
18231
- ]),
18232
- cores: number()
18167
+ retryAfterMs: number().optional()
18168
+ })]);
18169
+ /**
18170
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18171
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18172
+ * notification-output.cap.ts:27-31 precedents).
18173
+ */
18174
+ var LlmImageSchema = object({
18175
+ bytes: _instanceof(Uint8Array),
18176
+ mimeType: string()
18233
18177
  });
18234
- var MemoryInfoSchema = object({
18235
- percent: number(),
18236
- totalBytes: number(),
18237
- usedBytes: number(),
18238
- availableBytes: number(),
18239
- swapUsedBytes: number(),
18240
- swapTotalBytes: number()
18178
+ var LlmGenerateBaseInputSchema = object({
18179
+ /** Collection routing (the notification-output posture). */
18180
+ addonId: string().optional(),
18181
+ /** Explicit profile; else the resolution chain (spec §3). */
18182
+ profileId: string().optional(),
18183
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18184
+ consumer: string(),
18185
+ system: string().optional(),
18186
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
18187
+ prompt: string(),
18188
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18189
+ jsonSchema: record(string(), unknown()).optional(),
18190
+ /** Per-call override of the profile default. */
18191
+ maxTokens: number().int().positive().optional(),
18192
+ temperature: number().optional()
18241
18193
  });
18242
- var DiskIoSnapshotSchema = object({
18243
- readBytes: number(),
18244
- writeBytes: number(),
18245
- readOps: number(),
18246
- writeOps: number(),
18247
- timestampMs: number()
18248
- });
18249
- var NetworkIoSnapshotSchema = object({
18250
- rxBytes: number(),
18251
- txBytes: number(),
18252
- rxPackets: number(),
18253
- txPackets: number(),
18254
- rxErrors: number(),
18255
- txErrors: number(),
18256
- timestampMs: number()
18257
- });
18258
- var MetricsGpuInfoSchema = object({
18259
- utilization: number(),
18260
- model: string(),
18261
- memoryUsedBytes: number(),
18262
- memoryTotalBytes: number(),
18263
- temperature: number().nullable()
18264
- });
18265
- var ProcessResourceInfoSchema = object({
18266
- openFds: number(),
18267
- threadCount: number(),
18268
- activeHandles: number(),
18269
- activeRequests: number()
18270
- });
18271
- var PressureAvgsSchema = object({
18272
- avg10: number(),
18273
- avg60: number(),
18274
- avg300: number()
18275
- });
18276
- var PressureInfoSchema = object({
18277
- some: PressureAvgsSchema,
18278
- full: PressureAvgsSchema.nullable()
18279
- });
18280
- var SystemResourceSnapshotSchema = object({
18281
- cpu: CpuBreakdownSchema,
18282
- memory: MemoryInfoSchema,
18283
- gpu: MetricsGpuInfoSchema.nullable(),
18284
- network: NetworkIoSnapshotSchema,
18285
- disk: DiskIoSnapshotSchema,
18286
- pressure: object({
18287
- cpu: PressureInfoSchema.nullable(),
18288
- memory: PressureInfoSchema.nullable(),
18289
- io: PressureInfoSchema.nullable()
18194
+ /**
18195
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18196
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18197
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18198
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18199
+ * this only through the `llm` cap's methods.
18200
+ *
18201
+ * One running llama-server child per node in v1 (models are RAM-heavy).
18202
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18203
+ * watchdog — operator decision #3).
18204
+ */
18205
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
18206
+ object({
18207
+ kind: literal("catalog"),
18208
+ catalogId: string()
18290
18209
  }),
18291
- process: ProcessResourceInfoSchema,
18292
- cpuTemperature: number().nullable(),
18293
- timestampMs: number()
18294
- });
18295
- var DiskSpaceInfoSchema = object({
18296
- path: string(),
18297
- totalBytes: number(),
18298
- usedBytes: number(),
18299
- availableBytes: number(),
18300
- percent: number()
18301
- });
18302
- var PidResourceStatsSchema = object({
18303
- pid: number(),
18304
- cpu: number(),
18305
- memory: number(),
18306
- /**
18307
- * Private (anonymous) resident bytes — the per-process V8 heap + native
18308
- * allocations NOT shared with other processes (Linux RssAnon). This is the
18309
- * "real" per-runner cost; summing it across runners is meaningful, unlike
18310
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
18311
- * Undefined where /proc is unavailable (e.g. macOS).
18312
- */
18313
- privateBytes: number().optional(),
18314
- /**
18315
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18316
- * code shared copy-on-write across runners. Undefined on macOS.
18317
- */
18318
- sharedBytes: number().optional()
18210
+ object({
18211
+ kind: literal("url"),
18212
+ url: string(),
18213
+ sha256: string().optional()
18214
+ }),
18215
+ object({
18216
+ kind: literal("path"),
18217
+ path: string()
18218
+ })
18219
+ ]);
18220
+ var ManagedRuntimeConfigSchema = object({
18221
+ /** WHERE the runtime lives — hub or any agent. */
18222
+ nodeId: string(),
18223
+ /** Closed for v1; 'ollama' is a v2 candidate. */
18224
+ engine: _enum(["llama-cpp"]),
18225
+ model: ManagedModelRefSchema,
18226
+ contextSize: number().int().default(4096),
18227
+ /** 0 = CPU-only. */
18228
+ gpuLayers: number().int().default(0),
18229
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18230
+ threads: number().int().optional(),
18231
+ /** Concurrent slots. */
18232
+ parallel: number().int().default(1),
18233
+ /** Else lazy: first generate boots it. */
18234
+ autoStart: boolean().default(false),
18235
+ /** 0 = never; frees RAM after quiet periods. */
18236
+ idleStopMinutes: number().int().default(30)
18319
18237
  });
18320
- var AddonInstanceSchema = object({
18321
- addonId: string(),
18238
+ var LlmRuntimeStatusSchema = object({
18239
+ /** Status is ALWAYS node-qualified. */
18322
18240
  nodeId: string(),
18323
- role: _enum(["hub", "worker"]),
18324
- pid: number(),
18325
18241
  state: _enum([
18326
- "starting",
18327
- "running",
18328
- "stopping",
18329
18242
  "stopped",
18330
- "crashed"
18331
- ]),
18332
- uptimeSec: number()
18333
- });
18334
- var NodeProcessSchema = object({
18335
- pid: number(),
18336
- ppid: number(),
18337
- pgid: number(),
18338
- classification: _enum([
18339
- "root",
18340
- "managed",
18341
- "system",
18342
- "ghost"
18243
+ "downloading",
18244
+ "starting",
18245
+ "ready",
18246
+ "crashed",
18247
+ "failed"
18343
18248
  ]),
18344
- /** `$process` addon binding when `managed`, else null. */
18345
- addonId: string().nullable(),
18346
- /** Kernel-reported nodeId when the process is a known agent/worker. */
18347
- nodeId: string().nullable(),
18348
- /** Truncated command line. */
18349
- command: string(),
18350
- cpuPercent: number(),
18351
- memoryRssBytes: number(),
18352
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18353
- uptimeSec: number(),
18354
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18355
- orphaned: boolean()
18356
- });
18357
- var KillProcessInputSchema = object({
18358
- pid: number(),
18359
- /** Force = SIGKILL. Default is SIGTERM. */
18360
- force: boolean().optional()
18361
- });
18362
- var KillProcessResultSchema = object({
18363
- success: boolean(),
18364
- reason: string().optional(),
18365
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18366
- });
18367
- var DumpHeapSnapshotInputSchema = object({
18368
- /** The addon whose runner should dump a heap snapshot. */
18369
- addonId: string() });
18370
- var DumpHeapSnapshotResultSchema = object({
18371
- success: boolean(),
18372
- /** Path of the written .heapsnapshot inside the runner's container/host. */
18373
- path: string().optional(),
18374
- /** Process pid that was signalled. */
18375
18249
  pid: number().optional(),
18376
- reason: string().optional()
18250
+ port: number().optional(),
18251
+ modelPath: string().optional(),
18252
+ modelId: string().optional(),
18253
+ downloadProgress: number().min(0).max(1).optional(),
18254
+ lastError: string().optional(),
18255
+ crashesInWindow: number(),
18256
+ /** Child RSS (sampled best-effort). */
18257
+ memoryBytes: number().optional(),
18258
+ vramBytes: number().optional()
18377
18259
  });
18378
- var SystemMetricsSchema = object({
18379
- cpuPercent: number(),
18380
- memoryPercent: number(),
18381
- memoryUsedMB: number(),
18382
- memoryTotalMB: number(),
18383
- diskPercent: number().optional(),
18384
- temperature: number().optional(),
18385
- gpuPercent: number().optional(),
18386
- gpuMemoryPercent: number().optional()
18260
+ var LlmNodeModelSchema = object({
18261
+ file: string(),
18262
+ sizeBytes: number(),
18263
+ catalogId: string().optional(),
18264
+ installedAt: number().optional()
18387
18265
  });
18388
- 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, {
18266
+ var LlmRuntimeDiskUsageSchema = object({
18267
+ nodeId: string(),
18268
+ modelsBytes: number(),
18269
+ freeBytes: number().optional()
18270
+ });
18271
+ method(LlmGenerateBaseInputSchema.extend({
18272
+ images: array(LlmImageSchema).optional(),
18273
+ runtime: ManagedRuntimeConfigSchema,
18274
+ /** The managed profile's timeout, threaded by the hub provider. */
18275
+ timeoutMs: number().int().positive().optional()
18276
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18389
18277
  kind: "mutation",
18390
18278
  auth: "admin"
18391
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
18279
+ }), method(object({}), _void(), {
18392
18280
  kind: "mutation",
18393
18281
  auth: "admin"
18394
- });
18395
- method(object({
18396
- sourceUrl: string(),
18397
- metadata: ModelConvertMetadataSchema,
18398
- targets: array(ConvertTargetSchema).min(1).readonly(),
18399
- calibrationRef: string().optional(),
18400
- sessionId: string().optional()
18401
- }), ConvertResultSchema, {
18282
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18402
18283
  kind: "mutation",
18403
- auth: "admin",
18404
- timeoutMs: 6e5
18405
- });
18406
- method(object({
18407
- nodeId: string(),
18408
- modelId: string(),
18409
- format: _enum(MODEL_FORMATS),
18410
- entry: ModelCatalogEntrySchema
18411
- }), object({
18412
- ok: boolean(),
18413
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
18414
- sha256: string(),
18415
- bytes: number(),
18416
- /** The target node's modelsDir the artifact landed in. */
18417
- path: string()
18418
- }), {
18284
+ auth: "admin"
18285
+ }), method(object({ file: string() }), _void(), {
18419
18286
  kind: "mutation",
18420
18287
  auth: "admin"
18421
- });
18288
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18422
18289
  /**
18423
- * `mqtt-broker` — broker-registry cap.
18424
- *
18425
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
18426
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
18427
- * and (b) the connection details a consumer addon needs to spin up
18428
- * its OWN `mqtt.js` client.
18290
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18291
+ * methods concat-fan across providers; single-row methods route to ONE
18292
+ * provider by the `addonId` in the call input (the notification-output
18293
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18294
+ * (hub-placed); the cap stays open for future providers.
18429
18295
  *
18430
- * Why: pub/sub routing over the system event-bus loses fidelity
18431
- * (callback shape, QoS guarantees, will/retain semantics) and adds
18432
- * refcount bookkeeping that addons would rather own themselves. The
18433
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
18434
- * features anyway — give it the connection config, get out of the way.
18296
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18297
+ * `apiKey` is a password field providers REDACT it on read and merge on
18298
+ * write; a stored key NEVER round-trips to a client.
18299
+ */
18300
+ var LlmProfileKindSchema = _enum([
18301
+ "openai-compatible",
18302
+ "openai",
18303
+ "anthropic",
18304
+ "google",
18305
+ "managed-local"
18306
+ ]);
18307
+ var LlmProfileSchema = object({
18308
+ id: string(),
18309
+ name: string(),
18310
+ kind: LlmProfileKindSchema,
18311
+ /** Stamped by the provider — keeps the fanned catalog routable. */
18312
+ addonId: string(),
18313
+ enabled: boolean(),
18314
+ /** Vendor model id, or the managed runtime's loaded model. */
18315
+ model: string(),
18316
+ /** Required for openai-compatible; override for cloud kinds. */
18317
+ baseUrl: string().optional(),
18318
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
18319
+ apiKey: string().optional(),
18320
+ supportsVision: boolean(),
18321
+ temperature: number().min(0).max(2).optional(),
18322
+ maxTokens: number().int().positive().optional(),
18323
+ timeoutMs: number().int().positive().default(6e4),
18324
+ extraHeaders: record(string(), string()).optional(),
18325
+ /** kind === 'managed-local' only (spec §4). */
18326
+ runtime: ManagedRuntimeConfigSchema.optional()
18327
+ });
18328
+ /** ConfigUISchema tree passed through untyped on the wire (the
18329
+ * notification-output `ConfigSchemaPassthrough` precedent at
18330
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
18331
+ var ConfigSchemaPassthrough$1 = unknown();
18332
+ var LlmProfileKindDescriptorSchema = object({
18333
+ kind: LlmProfileKindSchema,
18334
+ label: string(),
18335
+ icon: string(),
18336
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
18337
+ addonId: string(),
18338
+ configSchema: ConfigSchemaPassthrough$1
18339
+ });
18340
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
18341
+ var LlmDefaultSchema = object({
18342
+ selector: LlmDefaultSelectorSchema,
18343
+ profileId: string()
18344
+ });
18345
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
18346
+ var LlmUsageRollupSchema = object({
18347
+ day: string(),
18348
+ consumer: string(),
18349
+ profileId: string(),
18350
+ calls: number(),
18351
+ okCalls: number(),
18352
+ errorCalls: number(),
18353
+ inputTokens: number(),
18354
+ outputTokens: number(),
18355
+ avgLatencyMs: number()
18356
+ });
18357
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
18358
+ var ManagedModelCatalogEntrySchema = object({
18359
+ id: string(),
18360
+ label: string(),
18361
+ family: string(),
18362
+ purpose: _enum(["text", "vision"]),
18363
+ url: string(),
18364
+ sha256: string(),
18365
+ sizeBytes: number(),
18366
+ quantization: string(),
18367
+ /** Load-time guidance shown in the picker. */
18368
+ minRamBytes: number(),
18369
+ contextSizeDefault: number().int(),
18370
+ /** Vision models: companion projector file. */
18371
+ mmprojUrl: string().optional()
18372
+ });
18373
+ var LlmRuntimeNodeSchema = object({
18374
+ nodeId: string(),
18375
+ reachable: boolean(),
18376
+ status: LlmRuntimeStatusSchema.optional(),
18377
+ disk: LlmRuntimeDiskUsageSchema.optional(),
18378
+ error: string().optional()
18379
+ });
18380
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
18381
+ var ProfileRefInputSchema = object({
18382
+ addonId: string(),
18383
+ profileId: string()
18384
+ });
18385
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
18386
+ kind: "mutation",
18387
+ auth: "admin"
18388
+ }), method(ProfileRefInputSchema, _void(), {
18389
+ kind: "mutation",
18390
+ auth: "admin"
18391
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
18392
+ kind: "mutation",
18393
+ auth: "admin"
18394
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
18395
+ selector: LlmDefaultSelectorSchema,
18396
+ profileId: string().nullable()
18397
+ }), _void(), {
18398
+ kind: "mutation",
18399
+ auth: "admin"
18400
+ }), method(object({
18401
+ since: number().optional(),
18402
+ until: number().optional(),
18403
+ consumer: string().optional(),
18404
+ profileId: string().optional()
18405
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
18406
+ nodeId: string(),
18407
+ model: ManagedModelRefSchema
18408
+ }), _void(), {
18409
+ kind: "mutation",
18410
+ auth: "admin"
18411
+ }), method(object({
18412
+ nodeId: string(),
18413
+ file: string()
18414
+ }), _void(), {
18415
+ kind: "mutation",
18416
+ auth: "admin"
18417
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
18418
+ kind: "mutation",
18419
+ auth: "admin"
18420
+ }), method(ProfileRefInputSchema, _void(), {
18421
+ kind: "mutation",
18422
+ auth: "admin"
18423
+ });
18424
+ var LogLevelSchema = _enum([
18425
+ "debug",
18426
+ "info",
18427
+ "warn",
18428
+ "error"
18429
+ ]);
18430
+ var LogEntrySchema = object({
18431
+ timestamp: date(),
18432
+ level: LogLevelSchema,
18433
+ scope: array(string()),
18434
+ message: string(),
18435
+ meta: record(string(), unknown()).optional(),
18436
+ tags: record(string(), string()).optional()
18437
+ });
18438
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18439
+ scope: array(string()).optional(),
18440
+ level: LogLevelSchema.optional(),
18441
+ since: date().optional(),
18442
+ until: date().optional(),
18443
+ limit: number().optional(),
18444
+ tags: record(string(), string()).optional()
18445
+ }), array(LogEntrySchema).readonly());
18446
+ /**
18447
+ * `login-method` — collection cap through which auth addons contribute
18448
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
18449
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
18450
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
18451
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
18452
+ * procedure aggregates them for the unauthenticated login page.
18453
+ *
18454
+ * A contribution is a discriminated union on `kind`:
18455
+ *
18456
+ * - `redirect` — a declarative button. The login page renders a generic
18457
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
18458
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
18459
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
18460
+ * login page needs NO change.
18461
+ *
18462
+ * - `widget` — a Module-Federation widget the login page mounts (via
18463
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
18464
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
18465
+ * mechanism kept for future use; no shipped addon uses it on the login
18466
+ * page (the passkey ceremony below runs natively in the shell instead).
18467
+ *
18468
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
18469
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
18470
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
18471
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
18472
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
18473
+ * fetching any remote code pre-auth. Contribution stays unconditional —
18474
+ * enrollment state is never leaked pre-auth; visibility is a shell
18475
+ * decision.
18476
+ *
18477
+ * Every contribution carries a `stage`:
18478
+ * - `primary` — shown on the first credentials screen (OIDC /
18479
+ * magic-link buttons; a future usernameless passkey).
18480
+ * - `second-factor` — shown AFTER the password leg, gated on the
18481
+ * returned `factors` (passkey-as-2FA today).
18482
+ *
18483
+ * `mount: skip` — the cap is read server-side by the core auth router
18484
+ * (`registry.getCollection('login-method')`), never mounted as its own
18485
+ * tRPC router.
18486
+ */
18487
+ /** When a login method renders in the two-phase login flow. */
18488
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
18489
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
18490
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
18491
+ object({
18492
+ kind: literal("redirect"),
18493
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
18494
+ id: string(),
18495
+ /** Operator-facing button label. */
18496
+ label: string(),
18497
+ /** lucide-react icon name. */
18498
+ icon: string().optional(),
18499
+ /** Addon-owned HTTP route the button navigates to (GET). */
18500
+ startUrl: string(),
18501
+ stage: LoginStageEnum
18502
+ }),
18503
+ object({
18504
+ kind: literal("widget"),
18505
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
18506
+ id: string(),
18507
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
18508
+ addonId: string(),
18509
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
18510
+ bundle: string(),
18511
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
18512
+ remote: WidgetRemoteSchema,
18513
+ stage: LoginStageEnum
18514
+ }),
18515
+ object({
18516
+ kind: literal("passkey"),
18517
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
18518
+ id: string(),
18519
+ /** Operator-facing button label. */
18520
+ label: string(),
18521
+ stage: LoginStageEnum,
18522
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
18523
+ rpId: string(),
18524
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
18525
+ origin: string().nullable()
18526
+ })
18527
+ ]);
18528
+ method(_void(), array(LoginMethodContributionSchema).readonly());
18529
+ var CpuBreakdownSchema = object({
18530
+ total: number(),
18531
+ user: number(),
18532
+ system: number(),
18533
+ irq: number(),
18534
+ nice: number(),
18535
+ loadAvg: tuple([
18536
+ number(),
18537
+ number(),
18538
+ number()
18539
+ ]),
18540
+ cores: number()
18541
+ });
18542
+ var MemoryInfoSchema = object({
18543
+ percent: number(),
18544
+ totalBytes: number(),
18545
+ usedBytes: number(),
18546
+ availableBytes: number(),
18547
+ swapUsedBytes: number(),
18548
+ swapTotalBytes: number()
18549
+ });
18550
+ var DiskIoSnapshotSchema = object({
18551
+ readBytes: number(),
18552
+ writeBytes: number(),
18553
+ readOps: number(),
18554
+ writeOps: number(),
18555
+ timestampMs: number()
18556
+ });
18557
+ var NetworkIoSnapshotSchema = object({
18558
+ rxBytes: number(),
18559
+ txBytes: number(),
18560
+ rxPackets: number(),
18561
+ txPackets: number(),
18562
+ rxErrors: number(),
18563
+ txErrors: number(),
18564
+ timestampMs: number()
18565
+ });
18566
+ var MetricsGpuInfoSchema = object({
18567
+ utilization: number(),
18568
+ model: string(),
18569
+ memoryUsedBytes: number(),
18570
+ memoryTotalBytes: number(),
18571
+ temperature: number().nullable()
18572
+ });
18573
+ var ProcessResourceInfoSchema = object({
18574
+ openFds: number(),
18575
+ threadCount: number(),
18576
+ activeHandles: number(),
18577
+ activeRequests: number()
18578
+ });
18579
+ var PressureAvgsSchema = object({
18580
+ avg10: number(),
18581
+ avg60: number(),
18582
+ avg300: number()
18583
+ });
18584
+ var PressureInfoSchema = object({
18585
+ some: PressureAvgsSchema,
18586
+ full: PressureAvgsSchema.nullable()
18587
+ });
18588
+ var SystemResourceSnapshotSchema = object({
18589
+ cpu: CpuBreakdownSchema,
18590
+ memory: MemoryInfoSchema,
18591
+ gpu: MetricsGpuInfoSchema.nullable(),
18592
+ network: NetworkIoSnapshotSchema,
18593
+ disk: DiskIoSnapshotSchema,
18594
+ pressure: object({
18595
+ cpu: PressureInfoSchema.nullable(),
18596
+ memory: PressureInfoSchema.nullable(),
18597
+ io: PressureInfoSchema.nullable()
18598
+ }),
18599
+ process: ProcessResourceInfoSchema,
18600
+ cpuTemperature: number().nullable(),
18601
+ timestampMs: number()
18602
+ });
18603
+ var DiskSpaceInfoSchema = object({
18604
+ path: string(),
18605
+ totalBytes: number(),
18606
+ usedBytes: number(),
18607
+ availableBytes: number(),
18608
+ percent: number()
18609
+ });
18610
+ var PidResourceStatsSchema = object({
18611
+ pid: number(),
18612
+ cpu: number(),
18613
+ memory: number(),
18614
+ /**
18615
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
18616
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
18617
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
18618
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
18619
+ * Undefined where /proc is unavailable (e.g. macOS).
18620
+ */
18621
+ privateBytes: number().optional(),
18622
+ /**
18623
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18624
+ * code shared copy-on-write across runners. Undefined on macOS.
18625
+ */
18626
+ sharedBytes: number().optional()
18627
+ });
18628
+ var AddonInstanceSchema = object({
18629
+ addonId: string(),
18630
+ nodeId: string(),
18631
+ role: _enum(["hub", "worker"]),
18632
+ pid: number(),
18633
+ state: _enum([
18634
+ "starting",
18635
+ "running",
18636
+ "stopping",
18637
+ "stopped",
18638
+ "crashed"
18639
+ ]),
18640
+ uptimeSec: number()
18641
+ });
18642
+ var NodeProcessSchema = object({
18643
+ pid: number(),
18644
+ ppid: number(),
18645
+ pgid: number(),
18646
+ classification: _enum([
18647
+ "root",
18648
+ "managed",
18649
+ "system",
18650
+ "ghost"
18651
+ ]),
18652
+ /** `$process` addon binding when `managed`, else null. */
18653
+ addonId: string().nullable(),
18654
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
18655
+ nodeId: string().nullable(),
18656
+ /** Truncated command line. */
18657
+ command: string(),
18658
+ cpuPercent: number(),
18659
+ memoryRssBytes: number(),
18660
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18661
+ uptimeSec: number(),
18662
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18663
+ orphaned: boolean()
18664
+ });
18665
+ var KillProcessInputSchema = object({
18666
+ pid: number(),
18667
+ /** Force = SIGKILL. Default is SIGTERM. */
18668
+ force: boolean().optional()
18669
+ });
18670
+ var KillProcessResultSchema = object({
18671
+ success: boolean(),
18672
+ reason: string().optional(),
18673
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18674
+ });
18675
+ var DumpHeapSnapshotInputSchema = object({
18676
+ /** The addon whose runner should dump a heap snapshot. */
18677
+ addonId: string() });
18678
+ var DumpHeapSnapshotResultSchema = object({
18679
+ success: boolean(),
18680
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
18681
+ path: string().optional(),
18682
+ /** Process pid that was signalled. */
18683
+ pid: number().optional(),
18684
+ reason: string().optional()
18685
+ });
18686
+ var SystemMetricsSchema = object({
18687
+ cpuPercent: number(),
18688
+ memoryPercent: number(),
18689
+ memoryUsedMB: number(),
18690
+ memoryTotalMB: number(),
18691
+ diskPercent: number().optional(),
18692
+ temperature: number().optional(),
18693
+ gpuPercent: number().optional(),
18694
+ gpuMemoryPercent: number().optional()
18695
+ });
18696
+ 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, {
18697
+ kind: "mutation",
18698
+ auth: "admin"
18699
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
18700
+ kind: "mutation",
18701
+ auth: "admin"
18702
+ });
18703
+ method(object({
18704
+ sourceUrl: string(),
18705
+ metadata: ModelConvertMetadataSchema,
18706
+ targets: array(ConvertTargetSchema).min(1).readonly(),
18707
+ calibrationRef: string().optional(),
18708
+ sessionId: string().optional()
18709
+ }), ConvertResultSchema, {
18710
+ kind: "mutation",
18711
+ auth: "admin",
18712
+ timeoutMs: 6e5
18713
+ });
18714
+ method(object({
18715
+ nodeId: string(),
18716
+ modelId: string(),
18717
+ format: _enum(MODEL_FORMATS),
18718
+ entry: ModelCatalogEntrySchema
18719
+ }), object({
18720
+ ok: boolean(),
18721
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
18722
+ sha256: string(),
18723
+ bytes: number(),
18724
+ /** The target node's modelsDir the artifact landed in. */
18725
+ path: string()
18726
+ }), {
18727
+ kind: "mutation",
18728
+ auth: "admin"
18729
+ });
18730
+ /**
18731
+ * `mqtt-broker` — broker-registry cap.
18732
+ *
18733
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
18734
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
18735
+ * and (b) the connection details a consumer addon needs to spin up
18736
+ * its OWN `mqtt.js` client.
18737
+ *
18738
+ * Why: pub/sub routing over the system event-bus loses fidelity
18739
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
18740
+ * refcount bookkeeping that addons would rather own themselves. The
18741
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
18742
+ * features anyway — give it the connection config, get out of the way.
18435
18743
  *
18436
18744
  * Consumer flow:
18437
18745
  * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
@@ -18649,398 +18957,594 @@ var NotificationSchema = object({
18649
18957
  });
18650
18958
  /** One declared native severity/priority level for a kind. */
18651
18959
  var TargetKindLevelSchema = object({
18652
- id: string(),
18653
- label: string(),
18654
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
18655
- ordinal: number().int().min(1).max(5).nullable(),
18656
- flags: object({
18657
- critical: boolean().optional(),
18658
- silent: boolean().optional(),
18659
- noPush: boolean().optional()
18660
- }).optional(),
18661
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
18662
- requires: array(string()).optional(),
18663
- description: string().optional()
18664
- });
18665
- /** The full capability block consulted before dispatch. */
18666
- var TargetKindCapsSchema = object({
18667
- attachments: object({
18668
- mediaTypes: array(AttachmentMediaTypeSchema),
18669
- mode: _enum([
18670
- "url",
18671
- "bytes",
18672
- "both"
18673
- ]),
18674
- max: number().int().nonnegative(),
18675
- maxBytes: number().int().positive().optional()
18676
- }),
18677
- /** Max action buttons (0 = none). */
18678
- actions: number().int().nonnegative(),
18679
- levels: array(TargetKindLevelSchema),
18680
- format: array(NotificationFormatSchema),
18681
- clickUrl: boolean(),
18682
- sound: boolean(),
18683
- ttl: boolean(),
18684
- bodyMaxLen: number().int().positive()
18685
- });
18686
- /**
18687
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
18688
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
18689
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
18690
- * the union is large and not meant for runtime validation here; the exported
18691
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
18692
- */
18693
- var ConfigSchemaPassthrough$1 = unknown();
18694
- var TargetKindSchema = object({
18695
- kind: string(),
18696
- label: string(),
18697
- icon: string(),
18698
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
18699
- addonId: string(),
18700
- configSchema: ConfigSchemaPassthrough$1,
18701
- supportsDiscovery: boolean(),
18702
- caps: TargetKindCapsSchema
18703
- });
18704
- /**
18705
- * A persisted target. `config` holds secrets; providers REDACT secret fields
18706
- * (return a presence marker only) when serving `listTargets` — never
18707
- * round-trip a stored secret to the UI.
18708
- */
18709
- var TargetSchema = object({
18710
- id: string(),
18711
- name: string(),
18712
- kind: string(),
18713
- addonId: string(),
18714
- enabled: boolean(),
18715
- config: record(string(), unknown())
18716
- });
18717
- /** A discovery-surfaced candidate (config is partial + non-secret). */
18718
- var DiscoveredTargetSchema = object({
18719
- kind: string(),
18720
- suggestedName: string(),
18721
- config: record(string(), unknown())
18722
- });
18723
- /** The degrade engine's report — what was resolved / dropped / degraded. */
18724
- var RenderedAsSchema = object({
18725
- level: string(),
18726
- format: NotificationFormatSchema,
18727
- attachmentsSent: number().int().nonnegative(),
18728
- actionsSent: number().int().nonnegative(),
18729
- truncated: boolean(),
18730
- dropped: array(string())
18731
- });
18732
- var SendResultSchema = object({
18733
- success: boolean(),
18734
- error: string().optional(),
18735
- renderedAs: RenderedAsSchema.optional()
18736
- });
18737
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
18738
- var TestResultSchema = SendResultSchema;
18739
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
18740
- kind: string(),
18741
- config: record(string(), unknown()).optional()
18742
- }), array(DiscoveredTargetSchema)), method(object({
18743
- targetId: string(),
18744
- notification: NotificationSchema
18745
- }), SendResultSchema, { kind: "mutation" }), method(object({
18746
- targetId: string(),
18747
- sample: NotificationSchema.optional()
18748
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
18749
- targetId: string(),
18750
- enabled: boolean()
18751
- }), _void(), { kind: "mutation" });
18752
- /**
18753
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18754
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18755
- * caps stay wire-compatible without a circular cap→cap import.
18756
- *
18757
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
18758
- * every transport tier structurally, and failed calls still write usage rows.
18759
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18760
- */
18761
- var LlmUsageSchema = object({
18762
- inputTokens: number(),
18763
- outputTokens: number()
18764
- });
18765
- var LlmErrorCodeSchema = _enum([
18766
- "timeout",
18767
- "rate-limited",
18768
- "auth",
18769
- "refusal",
18770
- "bad-request",
18771
- "unavailable",
18772
- "no-profile",
18773
- "budget-exceeded",
18774
- "adapter-error"
18775
- ]);
18776
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18777
- ok: literal(true),
18778
- text: string(),
18779
- model: string(),
18780
- usage: LlmUsageSchema,
18781
- truncated: boolean(),
18782
- latencyMs: number()
18783
- }), object({
18784
- ok: literal(false),
18785
- code: LlmErrorCodeSchema,
18786
- message: string(),
18787
- retryAfterMs: number().optional()
18788
- })]);
18789
- /**
18790
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18791
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18792
- * notification-output.cap.ts:27-31 precedents).
18793
- */
18794
- var LlmImageSchema = object({
18795
- bytes: _instanceof(Uint8Array),
18796
- mimeType: string()
18797
- });
18798
- var LlmGenerateBaseInputSchema = object({
18799
- /** Collection routing (the notification-output posture). */
18800
- addonId: string().optional(),
18801
- /** Explicit profile; else the resolution chain (spec §3). */
18802
- profileId: string().optional(),
18803
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18804
- consumer: string(),
18805
- system: string().optional(),
18806
- /** v1: single-turn. `messages[]` is a v2 additive field. */
18807
- prompt: string(),
18808
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18809
- jsonSchema: record(string(), unknown()).optional(),
18810
- /** Per-call override of the profile default. */
18811
- maxTokens: number().int().positive().optional(),
18812
- temperature: number().optional()
18813
- });
18814
- /**
18815
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18816
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18817
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18818
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18819
- * this only through the `llm` cap's methods.
18820
- *
18821
- * One running llama-server child per node in v1 (models are RAM-heavy).
18822
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18823
- * watchdog — operator decision #3).
18824
- */
18825
- var ManagedModelRefSchema = discriminatedUnion("kind", [
18826
- object({
18827
- kind: literal("catalog"),
18828
- catalogId: string()
18829
- }),
18830
- object({
18831
- kind: literal("url"),
18832
- url: string(),
18833
- sha256: string().optional()
18834
- }),
18835
- object({
18836
- kind: literal("path"),
18837
- path: string()
18838
- })
18839
- ]);
18840
- var ManagedRuntimeConfigSchema = object({
18841
- /** WHERE the runtime lives — hub or any agent. */
18842
- nodeId: string(),
18843
- /** Closed for v1; 'ollama' is a v2 candidate. */
18844
- engine: _enum(["llama-cpp"]),
18845
- model: ManagedModelRefSchema,
18846
- contextSize: number().int().default(4096),
18847
- /** 0 = CPU-only. */
18848
- gpuLayers: number().int().default(0),
18849
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18850
- threads: number().int().optional(),
18851
- /** Concurrent slots. */
18852
- parallel: number().int().default(1),
18853
- /** Else lazy: first generate boots it. */
18854
- autoStart: boolean().default(false),
18855
- /** 0 = never; frees RAM after quiet periods. */
18856
- idleStopMinutes: number().int().default(30)
18857
- });
18858
- var LlmRuntimeStatusSchema = object({
18859
- /** Status is ALWAYS node-qualified. */
18860
- nodeId: string(),
18861
- state: _enum([
18862
- "stopped",
18863
- "downloading",
18864
- "starting",
18865
- "ready",
18866
- "crashed",
18867
- "failed"
18868
- ]),
18869
- pid: number().optional(),
18870
- port: number().optional(),
18871
- modelPath: string().optional(),
18872
- modelId: string().optional(),
18873
- downloadProgress: number().min(0).max(1).optional(),
18874
- lastError: string().optional(),
18875
- crashesInWindow: number(),
18876
- /** Child RSS (sampled best-effort). */
18877
- memoryBytes: number().optional(),
18878
- vramBytes: number().optional()
18960
+ id: string(),
18961
+ label: string(),
18962
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
18963
+ ordinal: number().int().min(1).max(5).nullable(),
18964
+ flags: object({
18965
+ critical: boolean().optional(),
18966
+ silent: boolean().optional(),
18967
+ noPush: boolean().optional()
18968
+ }).optional(),
18969
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
18970
+ requires: array(string()).optional(),
18971
+ description: string().optional()
18879
18972
  });
18880
- var LlmNodeModelSchema = object({
18881
- file: string(),
18882
- sizeBytes: number(),
18883
- catalogId: string().optional(),
18884
- installedAt: number().optional()
18973
+ /** The full capability block consulted before dispatch. */
18974
+ var TargetKindCapsSchema = object({
18975
+ attachments: object({
18976
+ mediaTypes: array(AttachmentMediaTypeSchema),
18977
+ mode: _enum([
18978
+ "url",
18979
+ "bytes",
18980
+ "both"
18981
+ ]),
18982
+ max: number().int().nonnegative(),
18983
+ maxBytes: number().int().positive().optional()
18984
+ }),
18985
+ /** Max action buttons (0 = none). */
18986
+ actions: number().int().nonnegative(),
18987
+ levels: array(TargetKindLevelSchema),
18988
+ format: array(NotificationFormatSchema),
18989
+ clickUrl: boolean(),
18990
+ sound: boolean(),
18991
+ ttl: boolean(),
18992
+ bodyMaxLen: number().int().positive()
18885
18993
  });
18886
- var LlmRuntimeDiskUsageSchema = object({
18887
- nodeId: string(),
18888
- modelsBytes: number(),
18889
- freeBytes: number().optional()
18994
+ /**
18995
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
18996
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
18997
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
18998
+ * the union is large and not meant for runtime validation here; the exported
18999
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
19000
+ */
19001
+ var ConfigSchemaPassthrough = unknown();
19002
+ var TargetKindSchema = object({
19003
+ kind: string(),
19004
+ label: string(),
19005
+ icon: string(),
19006
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
19007
+ addonId: string(),
19008
+ configSchema: ConfigSchemaPassthrough,
19009
+ supportsDiscovery: boolean(),
19010
+ caps: TargetKindCapsSchema
18890
19011
  });
18891
- method(LlmGenerateBaseInputSchema.extend({
18892
- images: array(LlmImageSchema).optional(),
18893
- runtime: ManagedRuntimeConfigSchema,
18894
- /** The managed profile's timeout, threaded by the hub provider. */
18895
- timeoutMs: number().int().positive().optional()
18896
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18897
- kind: "mutation",
18898
- auth: "admin"
18899
- }), method(object({}), _void(), {
18900
- kind: "mutation",
18901
- auth: "admin"
18902
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18903
- kind: "mutation",
18904
- auth: "admin"
18905
- }), method(object({ file: string() }), _void(), {
18906
- kind: "mutation",
18907
- auth: "admin"
18908
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18909
19012
  /**
18910
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18911
- * methods concat-fan across providers; single-row methods route to ONE
18912
- * provider by the `addonId` in the call input (the notification-output
18913
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18914
- * (hub-placed); the cap stays open for future providers.
18915
- *
18916
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18917
- * `apiKey` is a password field — providers REDACT it on read and merge on
18918
- * write; a stored key NEVER round-trips to a client.
19013
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
19014
+ * (return a presence marker only) when serving `listTargets` — never
19015
+ * round-trip a stored secret to the UI.
18919
19016
  */
18920
- var LlmProfileKindSchema = _enum([
18921
- "openai-compatible",
18922
- "openai",
18923
- "anthropic",
18924
- "google",
18925
- "managed-local"
18926
- ]);
18927
- var LlmProfileSchema = object({
19017
+ var TargetSchema = object({
18928
19018
  id: string(),
18929
19019
  name: string(),
18930
- kind: LlmProfileKindSchema,
18931
- /** Stamped by the provider — keeps the fanned catalog routable. */
19020
+ kind: string(),
18932
19021
  addonId: string(),
18933
19022
  enabled: boolean(),
18934
- /** Vendor model id, or the managed runtime's loaded model. */
18935
- model: string(),
18936
- /** Required for openai-compatible; override for cloud kinds. */
18937
- baseUrl: string().optional(),
18938
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
18939
- apiKey: string().optional(),
18940
- supportsVision: boolean(),
18941
- temperature: number().min(0).max(2).optional(),
18942
- maxTokens: number().int().positive().optional(),
18943
- timeoutMs: number().int().positive().default(6e4),
18944
- extraHeaders: record(string(), string()).optional(),
18945
- /** kind === 'managed-local' only (spec §4). */
18946
- runtime: ManagedRuntimeConfigSchema.optional()
19023
+ config: record(string(), unknown())
18947
19024
  });
18948
- /** ConfigUISchema tree passed through untyped on the wire (the
18949
- * notification-output `ConfigSchemaPassthrough` precedent at
18950
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
18951
- var ConfigSchemaPassthrough = unknown();
18952
- var LlmProfileKindDescriptorSchema = object({
18953
- kind: LlmProfileKindSchema,
18954
- label: string(),
18955
- icon: string(),
18956
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
18957
- addonId: string(),
18958
- configSchema: ConfigSchemaPassthrough
19025
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
19026
+ var DiscoveredTargetSchema = object({
19027
+ kind: string(),
19028
+ suggestedName: string(),
19029
+ config: record(string(), unknown())
18959
19030
  });
18960
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
18961
- var LlmDefaultSchema = object({
18962
- selector: LlmDefaultSelectorSchema,
18963
- profileId: string()
19031
+ /** The degrade engine's report what was resolved / dropped / degraded. */
19032
+ var RenderedAsSchema = object({
19033
+ level: string(),
19034
+ format: NotificationFormatSchema,
19035
+ attachmentsSent: number().int().nonnegative(),
19036
+ actionsSent: number().int().nonnegative(),
19037
+ truncated: boolean(),
19038
+ dropped: array(string())
18964
19039
  });
18965
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
18966
- var LlmUsageRollupSchema = object({
18967
- day: string(),
18968
- consumer: string(),
18969
- profileId: string(),
18970
- calls: number(),
18971
- okCalls: number(),
18972
- errorCalls: number(),
18973
- inputTokens: number(),
18974
- outputTokens: number(),
18975
- avgLatencyMs: number()
19040
+ var SendResultSchema = object({
19041
+ success: boolean(),
19042
+ error: string().optional(),
19043
+ renderedAs: RenderedAsSchema.optional()
18976
19044
  });
18977
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
18978
- var ManagedModelCatalogEntrySchema = object({
19045
+ /** Same shape as SendResult kept as a distinct name for the test panel. */
19046
+ var TestResultSchema = SendResultSchema;
19047
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
19048
+ kind: string(),
19049
+ config: record(string(), unknown()).optional()
19050
+ }), array(DiscoveredTargetSchema)), method(object({
19051
+ targetId: string(),
19052
+ notification: NotificationSchema
19053
+ }), SendResultSchema, { kind: "mutation" }), method(object({
19054
+ targetId: string(),
19055
+ sample: NotificationSchema.optional()
19056
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
19057
+ targetId: string(),
19058
+ enabled: boolean()
19059
+ }), _void(), { kind: "mutation" });
19060
+ /**
19061
+ * notification-rules — the Notification Center rule surface (P1 core).
19062
+ *
19063
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
19064
+ * (operator decisions D-1/D-2/D-3 are binding):
19065
+ *
19066
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
19067
+ * `notification-center` module), hooked on the durable persistence
19068
+ * moments (object-event insert, TrackCloser.closeExpired) with a
19069
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
19070
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
19071
+ * FIRST persisted detection matching the conditions (per-track dedup,
19072
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
19073
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
19074
+ * - DISPATCH stays behind `notification-output` (rules reference targets
19075
+ * by id; per-backend params are a passthrough blob capped by the
19076
+ * target kind's own caps/degrade engine).
19077
+ *
19078
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
19079
+ * server-injected caller identity — the first `caller: 'required'`
19080
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
19081
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
19082
+ * windows, and the optional label/identity/plate matchers. User rules,
19083
+ * private zones, per-recipient fan-out and the wider condition table are
19084
+ * P2+ (see spec §7).
19085
+ *
19086
+ * All schemas here are the single source of truth — `NcRule` etc. are
19087
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
19088
+ * schema/interface drift is explicitly not repeated).
19089
+ */
19090
+ /**
19091
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
19092
+ * The value maps 1:1 onto the evaluated record kind:
19093
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
19094
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
19095
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
19096
+ * change of a LINKED device, one row per linked camera)
19097
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
19098
+ * delivery / pick-up)
19099
+ *
19100
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
19101
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
19102
+ * this one field keeps the schema additive — a rule still declares exactly
19103
+ * one trigger.
19104
+ */
19105
+ var NcDeliverySchema = _enum([
19106
+ "immediate",
19107
+ "track-end",
19108
+ "device-event",
19109
+ "package-event"
19110
+ ]);
19111
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
19112
+ var NcScheduleSchema = object({
19113
+ windows: array(object({
19114
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
19115
+ days: array(number().int().min(0).max(6)).min(1),
19116
+ startMinute: number().int().min(0).max(1439),
19117
+ endMinute: number().int().min(0).max(1439)
19118
+ })).min(1),
19119
+ /** IANA timezone; default = hub host timezone. */
19120
+ timezone: string().optional(),
19121
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
19122
+ invert: boolean().optional()
19123
+ });
19124
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
19125
+ var NcPlateMatcherSchema = object({
19126
+ values: array(string().min(1)).min(1),
19127
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
19128
+ maxDistance: number().int().min(0).max(3).default(1)
19129
+ });
19130
+ /**
19131
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
19132
+ * occupancy edge for a device — optionally narrowed to a single admin
19133
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
19134
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
19135
+ * - `became-free` — count crossed ≥ `count` → below it
19136
+ * - `>=` / `<=` — count is at/over or at/under `count`
19137
+ * `sustainSeconds` requires the condition hold continuously that long
19138
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
19139
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
19140
+ * the condition never matches. Confirmed edge-state survives addon restarts
19141
+ * (declared SQLite collection, reseeded on boot).
19142
+ */
19143
+ var NcOccupancyConditionSchema = object({
19144
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
19145
+ zoneId: string().optional(),
19146
+ /** Object class to count; absent = any class. */
19147
+ className: string().optional(),
19148
+ op: _enum([
19149
+ "became-occupied",
19150
+ "became-free",
19151
+ ">=",
19152
+ "<="
19153
+ ]).default("became-occupied"),
19154
+ count: number().int().min(0).default(1),
19155
+ sustainSeconds: number().int().min(0).max(3600).default(15)
19156
+ });
19157
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
19158
+ var NcZoneConditionSchema = object({
19159
+ ids: array(string().min(1)).min(1),
19160
+ /** Quantifier over `ids` — at least one / every one visited. */
19161
+ match: _enum(["any", "all"]).default("any")
19162
+ });
19163
+ /**
19164
+ * The P1 condition set — a flat AND of groups; absent group = pass;
19165
+ * membership lists are OR within the list (spec §2.3).
19166
+ */
19167
+ var NcConditionsSchema = object({
19168
+ /** Device scope — absent = all devices. */
19169
+ devices: array(number()).optional(),
19170
+ /** Detector class names (any overlap with the record's class set). */
19171
+ classes: array(string().min(1)).optional(),
19172
+ /** Veto classes — any overlap fails the rule. */
19173
+ classesExclude: array(string().min(1)).optional(),
19174
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
19175
+ minConfidence: number().min(0).max(1).optional(),
19176
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
19177
+ zones: NcZoneConditionSchema.optional(),
19178
+ /** Veto zones — any hit fails the rule. */
19179
+ zonesExclude: array(string().min(1)).optional(),
19180
+ /**
19181
+ * Exact (case-insensitive) match on the record's collapsed `label`
19182
+ * (identity name / plate text / subclass).
19183
+ */
19184
+ labelEquals: array(string().min(1)).optional(),
19185
+ /**
19186
+ * Identity matcher. P1 boundary: matched against the record's collapsed
19187
+ * `label` (the identity display name propagated by the face pipeline) —
19188
+ * identity-ID matching rides in P2 when identity ids reach the record.
19189
+ */
19190
+ identities: array(string().min(1)).optional(),
19191
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
19192
+ plates: NcPlateMatcherSchema.optional(),
19193
+ /**
19194
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
19195
+ * Same P1 boundary: matched against the record's collapsed `label` (the
19196
+ * identity display name). A record with NO label passes (nothing to
19197
+ * exclude), unlike the include variant which fails on an absent label.
19198
+ */
19199
+ identitiesExclude: array(string().min(1)).optional(),
19200
+ /**
19201
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
19202
+ * TRACK-END only: importance is scored at track close, so it does not exist
19203
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
19204
+ * close the value is threaded via the close-time info (the `Track` clone is
19205
+ * captured before the DB row is updated, so it would otherwise read stale).
19206
+ * Fails when the record carries no importance (never guess quality — the
19207
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
19208
+ */
19209
+ minImportance: number().min(0).max(1).optional(),
19210
+ /**
19211
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
19212
+ * TRACK-END only: an `immediate` / object-event subject has no closed
19213
+ * lifespan, so a dwell condition never matches immediate delivery
19214
+ * (documented choice — the object-event record carries no `firstSeen`,
19215
+ * so dwell cannot be computed from what the subject actually carries).
19216
+ */
19217
+ minDwellSeconds: number().min(0).optional(),
19218
+ /**
19219
+ * Detection provenance filter. `any` (default / absent) matches every
19220
+ * source; otherwise the subject's source must equal it. Legacy records
19221
+ * with no stamped source are treated as `pipeline`. The union spans both
19222
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
19223
+ * tracks carry `sensor`.
19224
+ */
19225
+ source: _enum([
19226
+ "pipeline",
19227
+ "onboard",
19228
+ "sensor",
19229
+ "any"
19230
+ ]).optional(),
19231
+ /**
19232
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
19233
+ * detector `minConfidence` (that gates the object-detection score; this
19234
+ * gates the recognition/OCR match score). Fails when the subject carries
19235
+ * no label-match confidence (never guess). TRACK-END only: the confidence
19236
+ * lives on the recognition result and reaches the subject at track close.
19237
+ *
19238
+ * What it measures precisely (plumbed at track close — the closer threads
19239
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
19240
+ * `importance`): the BEST recognition match confidence observed for the
19241
+ * label the track carries at close — for a face, the peak cosine similarity
19242
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
19243
+ * for a plate, the peak OCR read score of the best-held plate
19244
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
19245
+ * one track the higher of the two is used. A track that ended with no
19246
+ * confident identity/plate match carries no value, so the condition fails
19247
+ * closed for it (an un-recognized subject).
19248
+ */
19249
+ minLabelConfidence: number().min(0).max(1).optional(),
19250
+ /**
19251
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
19252
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
19253
+ * against the token carried on the device-event subject (extracted from the
19254
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
19255
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
19256
+ * eventType, so gate those with {@link sensorKinds} instead.
19257
+ */
19258
+ eventTypeTokens: array(string().min(1)).optional(),
19259
+ /**
19260
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
19261
+ * `contact`, `button`, `device-event`) — matched against the persisted
19262
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
19263
+ */
19264
+ sensorKinds: array(string().min(1)).optional(),
19265
+ /**
19266
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
19267
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
19268
+ * when the subject's phase does not match (a subject always carries a phase
19269
+ * on the package-event trigger).
19270
+ */
19271
+ packagePhase: _enum([
19272
+ "delivered",
19273
+ "picked-up",
19274
+ "both"
19275
+ ]).optional(),
19276
+ /**
19277
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
19278
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
19279
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
19280
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
19281
+ */
19282
+ customZones: array(MaskPolygonShapeSchema).optional(),
19283
+ /**
19284
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
19285
+ * (optionally zone/class-scoped) occupancy count crosses the configured
19286
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
19287
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
19288
+ */
19289
+ occupancy: NcOccupancyConditionSchema.optional()
19290
+ });
19291
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
19292
+ var NcRuleTargetSchema = object({
19293
+ /** `notification-output` Target id. */
19294
+ targetId: string().min(1),
19295
+ /**
19296
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
19297
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
19298
+ * degrade engine drops what the backend can't render.
19299
+ */
19300
+ params: record(string(), unknown()).optional()
19301
+ });
19302
+ /**
19303
+ * Media attachment policy (P1 still-image subset).
19304
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
19305
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
19306
+ * matched on identities attaches the subject's `faceCrop`, one matched on
19307
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
19308
+ * (or when the specific crop is missing) degrades to `best`, then
19309
+ * `keyFrame`, then no attachment — never delaying the send. The matched
19310
+ * condition summary is frozen on the outbox row at enqueue (like the rule
19311
+ * name), so the choice never drifts from the record that fired it.
19312
+ * - `keyFrame` — the clean scene frame (no subject box).
19313
+ * - `none` — no attachment.
19314
+ */
19315
+ var NcMediaPolicySchema = object({ attach: _enum([
19316
+ "best",
19317
+ "best-matching",
19318
+ "keyFrame",
19319
+ "none"
19320
+ ]).default("best") });
19321
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
19322
+ var NcThrottleSchema = object({
19323
+ cooldownSec: number().int().min(0).max(86400).default(60),
19324
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
19325
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
19326
+ });
19327
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
19328
+ var NcRuleInputSchema = object({
19329
+ name: string().min(1).max(200),
19330
+ enabled: boolean().default(true),
19331
+ delivery: NcDeliverySchema,
19332
+ conditions: NcConditionsSchema.default({}),
19333
+ schedule: NcScheduleSchema.optional(),
19334
+ targets: array(NcRuleTargetSchema).min(1),
19335
+ media: NcMediaPolicySchema.default({ attach: "best" }),
19336
+ throttle: NcThrottleSchema.default({
19337
+ cooldownSec: 60,
19338
+ scope: "rule-device"
19339
+ }),
19340
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
19341
+ template: object({
19342
+ title: string().max(500).optional(),
19343
+ body: string().max(2e3).optional()
19344
+ }).optional(),
19345
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
19346
+ priority: number().int().min(1).max(5).default(3),
19347
+ /**
19348
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
19349
+ * behaviour, visible to all, read-only in the viewer). Present = personal
19350
+ * rule owned by this userId. Server-stamped; never trusted from a client.
19351
+ */
19352
+ ownerUserId: string().optional()
19353
+ });
19354
+ /**
19355
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
19356
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
19357
+ * NOT a client-authored input field (it lives on the persisted rule, not the
19358
+ * input), so it is added here explicitly to let the store's per-target opt-out
19359
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
19360
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
19361
+ * `updateRule` patch.
19362
+ */
19363
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
19364
+ /** A persisted rule. */
19365
+ var NcRuleSchema = NcRuleInputSchema.extend({
19366
+ id: string(),
19367
+ /** userId of the admin who created the rule (server-stamped caller). */
19368
+ createdBy: string(),
19369
+ createdAt: number(),
19370
+ updatedAt: number(),
19371
+ /**
19372
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
19373
+ * send time. Only a target's OWNER may add/remove its id (server-checked
19374
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
19375
+ */
19376
+ disabledTargetIds: array(string()).default([])
19377
+ });
19378
+ var NcTestResultSchema = object({
19379
+ recordId: string(),
19380
+ recordKind: _enum([
19381
+ "object-event",
19382
+ "track",
19383
+ "device-event",
19384
+ "package-event"
19385
+ ]),
19386
+ deviceId: number(),
19387
+ timestamp: number(),
19388
+ wouldFire: boolean(),
19389
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
19390
+ failedCondition: string().optional(),
19391
+ className: string().optional(),
19392
+ label: string().optional()
19393
+ });
19394
+ var NcConditionDescriptorSchema = object({
19395
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
18979
19396
  id: string(),
19397
+ group: _enum([
19398
+ "scope",
19399
+ "class",
19400
+ "zones",
19401
+ "quality",
19402
+ "label",
19403
+ "schedule",
19404
+ "device",
19405
+ "package",
19406
+ "occupancy"
19407
+ ]),
18980
19408
  label: string(),
18981
- family: string(),
18982
- purpose: _enum(["text", "vision"]),
18983
- url: string(),
18984
- sha256: string(),
18985
- sizeBytes: number(),
18986
- quantization: string(),
18987
- /** Load-time guidance shown in the picker. */
18988
- minRamBytes: number(),
18989
- contextSizeDefault: number().int(),
18990
- /** Vision models: companion projector file. */
18991
- mmprojUrl: string().optional()
19409
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
19410
+ valueType: _enum([
19411
+ "deviceIdList",
19412
+ "stringList",
19413
+ "number01",
19414
+ "number",
19415
+ "sourceSelect",
19416
+ "zoneSelection",
19417
+ "zoneIdList",
19418
+ "schedule",
19419
+ "plateMatcher",
19420
+ "packagePhase",
19421
+ "polygonDraw",
19422
+ "occupancy"
19423
+ ]),
19424
+ operator: _enum([
19425
+ "in",
19426
+ "notIn",
19427
+ "anyOf",
19428
+ "allOf",
19429
+ "gte",
19430
+ "fuzzyIn",
19431
+ "withinSchedule"
19432
+ ]),
19433
+ /** Which delivery kinds the condition applies to. */
19434
+ appliesTo: array(NcDeliverySchema),
19435
+ phase: string(),
19436
+ description: string().optional()
18992
19437
  });
18993
- var LlmRuntimeNodeSchema = object({
18994
- nodeId: string(),
18995
- reachable: boolean(),
18996
- status: LlmRuntimeStatusSchema.optional(),
18997
- disk: LlmRuntimeDiskUsageSchema.optional(),
18998
- error: string().optional()
19438
+ /**
19439
+ * The delivery lifecycle status of a history row — a straight read of the
19440
+ * durable outbox row's own status (single source of truth):
19441
+ * - `pending` — enqueued, in-flight or retrying with backoff
19442
+ * - `sent` — delivered (terminal)
19443
+ * - `dead` — dead-lettered after exhausting retries / a permanent
19444
+ * backend rejection / a deleted target (terminal; carries
19445
+ * the failure `error`)
19446
+ *
19447
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
19448
+ * user dimension (quiet hours / snooze) and are additive when they land.
19449
+ */
19450
+ var NcHistoryStatusSchema = _enum([
19451
+ "pending",
19452
+ "sent",
19453
+ "dead"
19454
+ ]);
19455
+ /** The evaluated record kind a history row descends from (one per trigger). */
19456
+ var NcHistoryRecordKindSchema = _enum([
19457
+ "object-event",
19458
+ "track-end",
19459
+ "device-event",
19460
+ "package-event"
19461
+ ]);
19462
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
19463
+ var NcHistorySubjectSchema = object({
19464
+ className: string(),
19465
+ label: string().optional(),
19466
+ confidence: number().optional(),
19467
+ zones: array(string()),
19468
+ timestamp: number()
19469
+ });
19470
+ /**
19471
+ * One delivery-history row. This is a read-only VIEW over the durable
19472
+ * outbox row (single source of truth — the same row the drain loop drives;
19473
+ * NO second write path, so history can never drift from delivery state).
19474
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
19475
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
19476
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
19477
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
19478
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
19479
+ * P1 (admin scope only).
19480
+ */
19481
+ var NcHistoryEntrySchema = object({
19482
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
19483
+ id: string(),
19484
+ ruleId: string(),
19485
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
19486
+ ruleName: string(),
19487
+ /** The rule urgency/trigger that produced this delivery. */
19488
+ delivery: NcDeliverySchema,
19489
+ targetId: string(),
19490
+ deviceId: number(),
19491
+ recordKind: NcHistoryRecordKindSchema,
19492
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
19493
+ recordId: string(),
19494
+ /** Present for track-scoped deliveries (object-event / track-end). */
19495
+ trackId: string().optional(),
19496
+ status: NcHistoryStatusSchema,
19497
+ /** Delivery attempts made so far. */
19498
+ attempts: number().int(),
19499
+ /** Fire time (outbox enqueue). */
19500
+ createdAt: number(),
19501
+ /** Last transition time (terminal for sent / dead). */
19502
+ updatedAt: number(),
19503
+ /** Failure detail — present on a `dead` row. */
19504
+ error: string().optional(),
19505
+ subject: NcHistorySubjectSchema
18999
19506
  });
19000
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
19001
- var ProfileRefInputSchema = object({
19002
- addonId: string(),
19003
- profileId: string()
19507
+ /**
19508
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
19509
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
19510
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
19511
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
19512
+ */
19513
+ var NcHistoryFilterSchema = object({
19514
+ ruleId: string().optional(),
19515
+ deviceId: number().optional(),
19516
+ status: NcHistoryStatusSchema.optional(),
19517
+ since: number().optional(),
19518
+ until: number().optional(),
19519
+ limit: number().int().min(1).max(500).default(100)
19004
19520
  });
19005
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
19006
- kind: "mutation",
19007
- auth: "admin"
19008
- }), method(ProfileRefInputSchema, _void(), {
19521
+ 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 }), {
19009
19522
  kind: "mutation",
19010
- auth: "admin"
19011
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
19523
+ auth: "admin",
19524
+ caller: "required"
19525
+ }), method(object({
19526
+ ruleId: string(),
19527
+ patch: NcRulePatchSchema
19528
+ }), object({ rule: NcRuleSchema }), {
19012
19529
  kind: "mutation",
19013
- auth: "admin"
19014
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
19015
- selector: LlmDefaultSelectorSchema,
19016
- profileId: string().nullable()
19017
- }), _void(), {
19530
+ auth: "admin",
19531
+ caller: "required"
19532
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
19018
19533
  kind: "mutation",
19019
19534
  auth: "admin"
19020
19535
  }), method(object({
19021
- since: number().optional(),
19022
- until: number().optional(),
19023
- consumer: string().optional(),
19024
- profileId: string().optional()
19025
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
19026
- nodeId: string(),
19027
- model: ManagedModelRefSchema
19028
- }), _void(), {
19536
+ ruleId: string(),
19537
+ enabled: boolean()
19538
+ }), object({ success: literal(true) }), {
19029
19539
  kind: "mutation",
19030
19540
  auth: "admin"
19031
19541
  }), method(object({
19032
- nodeId: string(),
19033
- file: string()
19034
- }), _void(), {
19035
- kind: "mutation",
19036
- auth: "admin"
19037
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
19038
- kind: "mutation",
19039
- auth: "admin"
19040
- }), method(ProfileRefInputSchema, _void(), {
19542
+ rule: NcRuleInputSchema,
19543
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
19544
+ }), object({ results: array(NcTestResultSchema) }), {
19041
19545
  kind: "mutation",
19042
19546
  auth: "admin"
19043
- });
19547
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
19044
19548
  /**
19045
19549
  * Zod schemas for persisted record types.
19046
19550
  *
@@ -19726,7 +20230,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19726
20230
  }), method(object({
19727
20231
  eventId: string(),
19728
20232
  kind: MediaFileKindEnum.optional()
19729
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
20233
+ }), array(MediaFileSchema).readonly()), method(object({
20234
+ trackId: string(),
20235
+ kinds: array(MediaFileKindEnum).optional()
20236
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
19730
20237
  deviceId: number(),
19731
20238
  timestamp: number(),
19732
20239
  frameWidth: number(),
@@ -19747,76 +20254,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19747
20254
  eventId: string(),
19748
20255
  timestamp: number()
19749
20256
  });
19750
- /**
19751
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
19752
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
19753
- * caps into per-camera event-kind descriptors.
19754
- *
19755
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
19756
- * is NOT duplicated here — every entry is derived from the single
19757
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
19758
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
19759
- * control cap means adding one line here (and a taxonomy entry); the anti-
19760
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
19761
- * eventful cap is missing.
19762
- */
19763
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
19764
- var LEGACY_ICON = {
19765
- motion: "motion",
19766
- audio: "audio",
19767
- person: "person",
19768
- vehicle: "vehicle",
19769
- animal: "animal",
19770
- package: "package",
19771
- door: "door",
19772
- pir: "pir",
19773
- smoke: "smoke",
19774
- water: "water",
19775
- button: "button",
19776
- generic: "generic",
19777
- gas: "smoke",
19778
- vibration: "generic",
19779
- tamper: "generic",
19780
- presence: "person",
19781
- lock: "generic",
19782
- siren: "generic",
19783
- switch: "generic",
19784
- doorbell: "button"
19785
- };
19786
- function legacyIcon(iconId) {
19787
- return LEGACY_ICON[iconId] ?? "generic";
19788
- }
19789
- /**
19790
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
19791
- * The anti-drift guard cross-checks this against the eventful caps declared
19792
- * in `packages/types/src/capabilities/*.cap.ts`.
19793
- */
19794
- var CAP_TO_KIND = {
19795
- contact: "contact",
19796
- motion: "motion-sensor",
19797
- smoke: "smoke",
19798
- flood: "flood",
19799
- gas: "gas",
19800
- "carbon-monoxide": "carbon-monoxide",
19801
- vibration: "vibration",
19802
- tamper: "tamper",
19803
- presence: "presence",
19804
- "enum-sensor": "enum-sensor",
19805
- "event-emitter": "device-event",
19806
- "lock-control": "lock",
19807
- switch: "switch",
19808
- button: "button",
19809
- doorbell: "doorbell"
19810
- };
19811
- function buildDescriptor(capName, kind) {
19812
- const t = EVENT_TAXONOMY[kind];
19813
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
19814
- return {
19815
- ...t,
19816
- icon: legacyIcon(t.iconId)
19817
- };
19818
- }
19819
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
19820
20257
  var CameraPipelineConfigSchema = object({
19821
20258
  engine: PipelineEngineChoiceSchema.optional(),
19822
20259
  steps: array(PipelineStepInputSchema).readonly(),
@@ -20302,6 +20739,76 @@ method(object({
20302
20739
  auth: "admin"
20303
20740
  });
20304
20741
  /**
20742
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
20743
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
20744
+ * caps into per-camera event-kind descriptors.
20745
+ *
20746
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
20747
+ * is NOT duplicated here — every entry is derived from the single
20748
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
20749
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
20750
+ * control cap means adding one line here (and a taxonomy entry); the anti-
20751
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
20752
+ * eventful cap is missing.
20753
+ */
20754
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
20755
+ var LEGACY_ICON = {
20756
+ motion: "motion",
20757
+ audio: "audio",
20758
+ person: "person",
20759
+ vehicle: "vehicle",
20760
+ animal: "animal",
20761
+ package: "package",
20762
+ door: "door",
20763
+ pir: "pir",
20764
+ smoke: "smoke",
20765
+ water: "water",
20766
+ button: "button",
20767
+ generic: "generic",
20768
+ gas: "smoke",
20769
+ vibration: "generic",
20770
+ tamper: "generic",
20771
+ presence: "person",
20772
+ lock: "generic",
20773
+ siren: "generic",
20774
+ switch: "generic",
20775
+ doorbell: "button"
20776
+ };
20777
+ function legacyIcon(iconId) {
20778
+ return LEGACY_ICON[iconId] ?? "generic";
20779
+ }
20780
+ /**
20781
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
20782
+ * The anti-drift guard cross-checks this against the eventful caps declared
20783
+ * in `packages/types/src/capabilities/*.cap.ts`.
20784
+ */
20785
+ var CAP_TO_KIND = {
20786
+ contact: "contact",
20787
+ motion: "motion-sensor",
20788
+ smoke: "smoke",
20789
+ flood: "flood",
20790
+ gas: "gas",
20791
+ "carbon-monoxide": "carbon-monoxide",
20792
+ vibration: "vibration",
20793
+ tamper: "tamper",
20794
+ presence: "presence",
20795
+ "enum-sensor": "enum-sensor",
20796
+ "event-emitter": "device-event",
20797
+ "lock-control": "lock",
20798
+ switch: "switch",
20799
+ button: "button",
20800
+ doorbell: "doorbell"
20801
+ };
20802
+ function buildDescriptor(capName, kind) {
20803
+ const t = EVENT_TAXONOMY[kind];
20804
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
20805
+ return {
20806
+ ...t,
20807
+ icon: legacyIcon(t.iconId)
20808
+ };
20809
+ }
20810
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
20811
+ /**
20305
20812
  * server-management — per-NODE singleton capability for a node's ROOT
20306
20813
  * package lifecycle (runtime-updatable node packages).
20307
20814
  *
@@ -21756,7 +22263,28 @@ var FaceInfoSchema = object({
21756
22263
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
21757
22264
  * track produced no key frame (e.g. native/onboard source) — the UI falls
21758
22265
  * back to the inline `base64` face crop. */
21759
- keyFrameMediaKey: string().optional()
22266
+ keyFrameMediaKey: string().optional(),
22267
+ /** Winning identity-match cosine (0..1) for this face's track, when an
22268
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
22269
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
22270
+ * faces that were never auto-recognized. */
22271
+ bestMatchScore: number().optional(),
22272
+ /** Native-scale face short side (px) at recognition time, when the runner
22273
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
22274
+ * legacy rows / runners that reported no native measure. */
22275
+ nativeFaceShortSidePx: number().optional(),
22276
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
22277
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
22278
+ * but blocked only by the recognition size floor). Mutually exclusive with
22279
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
22280
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
22281
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
22282
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
22283
+ suggestedIdentityId: string().optional(),
22284
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
22285
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
22286
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
22287
+ suggestedMatchScore: number().optional()
21760
22288
  });
21761
22289
  var FaceFilterEnum = _enum([
21762
22290
  "unassigned",
@@ -23799,36 +24327,6 @@ Object.freeze({
23799
24327
  addonId: null,
23800
24328
  access: "view"
23801
24329
  },
23802
- "advancedNotifier.deleteRule": {
23803
- capName: "advanced-notifier",
23804
- capScope: "system",
23805
- addonId: null,
23806
- access: "delete"
23807
- },
23808
- "advancedNotifier.getHistory": {
23809
- capName: "advanced-notifier",
23810
- capScope: "system",
23811
- addonId: null,
23812
- access: "view"
23813
- },
23814
- "advancedNotifier.getRules": {
23815
- capName: "advanced-notifier",
23816
- capScope: "system",
23817
- addonId: null,
23818
- access: "view"
23819
- },
23820
- "advancedNotifier.testRule": {
23821
- capName: "advanced-notifier",
23822
- capScope: "system",
23823
- addonId: null,
23824
- access: "create"
23825
- },
23826
- "advancedNotifier.upsertRule": {
23827
- capName: "advanced-notifier",
23828
- capScope: "system",
23829
- addonId: null,
23830
- access: "create"
23831
- },
23832
24330
  "alarmPanel.arm": {
23833
24331
  capName: "alarm-panel",
23834
24332
  capScope: "device",
@@ -26133,6 +26631,60 @@ Object.freeze({
26133
26631
  addonId: null,
26134
26632
  access: "create"
26135
26633
  },
26634
+ "notificationRules.createRule": {
26635
+ capName: "notification-rules",
26636
+ capScope: "system",
26637
+ addonId: null,
26638
+ access: "create"
26639
+ },
26640
+ "notificationRules.deleteRule": {
26641
+ capName: "notification-rules",
26642
+ capScope: "system",
26643
+ addonId: null,
26644
+ access: "delete"
26645
+ },
26646
+ "notificationRules.getConditionCatalog": {
26647
+ capName: "notification-rules",
26648
+ capScope: "system",
26649
+ addonId: null,
26650
+ access: "view"
26651
+ },
26652
+ "notificationRules.getHistory": {
26653
+ capName: "notification-rules",
26654
+ capScope: "system",
26655
+ addonId: null,
26656
+ access: "view"
26657
+ },
26658
+ "notificationRules.getRule": {
26659
+ capName: "notification-rules",
26660
+ capScope: "system",
26661
+ addonId: null,
26662
+ access: "view"
26663
+ },
26664
+ "notificationRules.listRules": {
26665
+ capName: "notification-rules",
26666
+ capScope: "system",
26667
+ addonId: null,
26668
+ access: "view"
26669
+ },
26670
+ "notificationRules.setRuleEnabled": {
26671
+ capName: "notification-rules",
26672
+ capScope: "system",
26673
+ addonId: null,
26674
+ access: "create"
26675
+ },
26676
+ "notificationRules.testRule": {
26677
+ capName: "notification-rules",
26678
+ capScope: "system",
26679
+ addonId: null,
26680
+ access: "create"
26681
+ },
26682
+ "notificationRules.updateRule": {
26683
+ capName: "notification-rules",
26684
+ capScope: "system",
26685
+ addonId: null,
26686
+ access: "create"
26687
+ },
26136
26688
  "notifier.cancel": {
26137
26689
  capName: "notifier",
26138
26690
  capScope: "device",