@camstack/addon-provider-petkit 0.2.4 → 0.2.5

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