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