@camstack/addon-provider-tuya 0.2.3 → 0.2.5

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