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