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