@camstack/addon-provider-wyze 0.2.4 → 0.2.5

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