@camstack/addon-mqtt-broker 1.2.3 → 1.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.
@@ -44,7 +44,7 @@ let crypto$10 = __toESM(crypto$1, 1);
44
44
  crypto$1 = __toESM(crypto$1);
45
45
  let node_fs = require("node:fs");
46
46
  let node_path = require("node:path");
47
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
47
+ //#region ../types/dist/event-category-BLcNejAE.mjs
48
48
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
49
49
  EventCategory["SystemBoot"] = "system.boot";
50
50
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -194,9 +194,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
194
194
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
195
195
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
196
196
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
197
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
198
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
199
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
200
197
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
201
198
  * progress bar the client reconciles via `recordingExport.getExport`. */
202
199
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6861,7 +6858,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6861
6858
  patch: record(string(), unknown())
6862
6859
  }), object({ success: literal(true) });
6863
6860
  object({ deviceId: number() }), unknown().nullable();
6864
- /** Shorthand to define a method schema */
6865
6861
  function method(input, output, options) {
6866
6862
  return {
6867
6863
  input,
@@ -6869,6 +6865,7 @@ function method(input, output, options) {
6869
6865
  kind: options?.kind ?? "query",
6870
6866
  auth: options?.auth ?? "protected",
6871
6867
  ...options?.access !== void 0 ? { access: options.access } : {},
6868
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6872
6869
  timeoutMs: options?.timeoutMs
6873
6870
  };
6874
6871
  }
@@ -8222,6 +8219,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8222
8219
  /** The complete taxonomy dictionary, keyed by kind. */
8223
8220
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8224
8221
  /**
8222
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8223
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8224
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8225
+ * taxonomy surface (timeline, filters, event page).
8226
+ *
8227
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8228
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8229
+ * for the `classes` / `classesExclude` conditions.
8230
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8231
+ * the same class picker, grouped under an Audio header.
8232
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8233
+ * lock / …) for the `sensorKinds` device-event condition.
8234
+ *
8235
+ * Each entry carries `parentKind` so the client can group video subs under
8236
+ * their macro and sensor/control kinds under their category. This surface is
8237
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8238
+ * method, no codegen — so it ships train-free with an addon deploy.
8239
+ */
8240
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8241
+ var NcTaxonomyEntrySchema = object({
8242
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8243
+ kind: string(),
8244
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8245
+ label: string(),
8246
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8247
+ parentKind: string().nullable()
8248
+ });
8249
+ object({
8250
+ videoClasses: array(NcTaxonomyEntrySchema),
8251
+ audioKinds: array(NcTaxonomyEntrySchema),
8252
+ labels: array(NcTaxonomyEntrySchema)
8253
+ });
8254
+ function toEntry(kind, label, parentKind) {
8255
+ return {
8256
+ kind,
8257
+ label,
8258
+ parentKind
8259
+ };
8260
+ }
8261
+ /**
8262
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8263
+ * (macros before their subs), which the client relies on for stable grouping.
8264
+ */
8265
+ function buildNcTaxonomy() {
8266
+ const all = Object.values(EVENT_TAXONOMY);
8267
+ return {
8268
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8269
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8270
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8271
+ };
8272
+ }
8273
+ Object.freeze(buildNcTaxonomy());
8274
+ /**
8225
8275
  * Error types for the safe expression engine. Two distinct classes so callers
8226
8276
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8227
8277
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -10930,6 +10980,22 @@ var CameraMetricsSchema = object({
10930
10980
  ])
10931
10981
  });
10932
10982
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
10983
+ /**
10984
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
10985
+ * within the frame, so the executor can re-cut a leaf child ROI at native
10986
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
10987
+ */
10988
+ var NativeCropRefSchema = object({
10989
+ /** Handle keying the retained native surface (node-pinned to its owner). */
10990
+ handle: FrameHandleSchema,
10991
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
10992
+ cropFrameSpace: object({
10993
+ x: number(),
10994
+ y: number(),
10995
+ w: number(),
10996
+ h: number()
10997
+ })
10998
+ });
10933
10999
  var ModelFormatSchema$1 = _enum([
10934
11000
  "onnx",
10935
11001
  "coreml",
@@ -11205,7 +11271,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
11205
11271
  * Omitted ⇒ the runner's default device (current single-engine
11206
11272
  * behaviour). Selects WHICH device pool of the node runs the call.
11207
11273
  */
11208
- deviceKey: string().optional()
11274
+ deviceKey: string().optional(),
11275
+ /**
11276
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
11277
+ * when the parent crop was resolved from the frame's retained NATIVE
11278
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
11279
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
11280
+ * resolution from that surface — the SAME quality path faces already
11281
+ * had — instead of the downscaled parent tile. `handle` keys the native
11282
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
11283
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
11284
+ * the executor's crop-normalized child ROI back into frame-normalized
11285
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
11286
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
11287
+ * (today's behaviour on the fallback path).
11288
+ */
11289
+ nativeCropRef: NativeCropRefSchema.optional()
11209
11290
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
11210
11291
  engine: PipelineEngineChoiceSchema.optional(),
11211
11292
  steps: array(PipelineStepInputSchema).min(1),
@@ -11421,7 +11502,11 @@ var DetailResultSchema = object({
11421
11502
  bbox: NativeCropBboxSchema.optional(),
11422
11503
  embedding: string().optional(),
11423
11504
  label: string().optional(),
11424
- alignedCropJpeg: string().optional()
11505
+ alignedCropJpeg: string().optional(),
11506
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
11507
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
11508
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
11509
+ nativeFaceShortSidePx: number().optional()
11425
11510
  });
11426
11511
  /**
11427
11512
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -11435,6 +11520,12 @@ var motionCooldownMsField = {
11435
11520
  default: 3e4,
11436
11521
  step: 500
11437
11522
  };
11523
+ var maxSessionHoldMsField = {
11524
+ min: 0,
11525
+ max: 6e5,
11526
+ default: 12e4,
11527
+ step: 5e3
11528
+ };
11438
11529
  var motionFpsField = {
11439
11530
  min: 1,
11440
11531
  max: 30,
@@ -11582,6 +11673,19 @@ var RunnerCameraConfigSchema = object({
11582
11673
  "on-motion"
11583
11674
  ]).default("always-on"),
11584
11675
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
11676
+ /**
11677
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
11678
+ * detection session is active and ≥1 confirmed non-stationary track is
11679
+ * still live, the orchestrator keeps the session open past
11680
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
11681
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
11682
+ * ms since the session opened, after which it closes regardless. `0`
11683
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
11684
+ * runner itself — carried here so it shares the per-camera device-settings
11685
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
11686
+ * resolved `CameraDetectionConfig`.
11687
+ */
11688
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
11585
11689
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
11586
11690
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
11587
11691
  motionStreamId: string(),
@@ -11671,7 +11775,7 @@ var RunnerCameraConfigSchema = object({
11671
11775
  */
11672
11776
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
11673
11777
  });
11674
- 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;
11778
+ 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;
11675
11779
  /**
11676
11780
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
11677
11781
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -13525,94 +13629,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
13525
13629
  bundleUrl: string()
13526
13630
  });
13527
13631
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
13528
- var NotificationRuleConditionsSchema = object({
13529
- deviceIds: array(number()).readonly().optional(),
13530
- classNames: array(string()).readonly().optional(),
13531
- zoneIds: array(string()).readonly().optional(),
13532
- minConfidence: number().optional(),
13533
- source: _enum([
13534
- "pipeline",
13535
- "onboard",
13536
- "any"
13537
- ]).optional(),
13538
- schedule: object({
13539
- days: array(number()).readonly(),
13540
- startHour: number(),
13541
- endHour: number()
13542
- }).optional(),
13543
- cooldownSeconds: number().optional(),
13544
- minDwellSeconds: number().optional(),
13545
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
13546
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
13547
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
13548
- eventTypeTokens: array(string()).readonly().optional(),
13549
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
13550
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
13551
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
13552
- clipDescription: object({
13553
- text: string().min(1),
13554
- minSimilarity: number().min(0).max(1)
13555
- }).optional(),
13556
- /** Match events whose recognized-entity label (face identity name or plate
13557
- * vehicle name, propagated onto `event.data.label`) is one of these values.
13558
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
13559
- * vehicle/person> is seen". */
13560
- labels: array(string()).readonly().optional()
13561
- });
13562
- var NotificationRuleTemplateSchema = object({
13563
- title: string(),
13564
- body: string(),
13565
- imageMode: _enum([
13566
- "crop",
13567
- "annotated",
13568
- "full",
13569
- "none"
13570
- ])
13571
- });
13572
- var NotificationRuleSchema = object({
13573
- id: string(),
13574
- name: string(),
13575
- enabled: boolean(),
13576
- eventTypes: array(string()).readonly(),
13577
- conditions: NotificationRuleConditionsSchema,
13578
- outputs: array(string()).readonly(),
13579
- template: NotificationRuleTemplateSchema.optional(),
13580
- priority: _enum([
13581
- "low",
13582
- "normal",
13583
- "high",
13584
- "critical"
13585
- ])
13586
- });
13587
- var NotificationTestResultSchema = object({
13588
- ruleId: string(),
13589
- eventId: string(),
13590
- timestamp: number(),
13591
- wouldFire: boolean(),
13592
- reason: string().optional()
13593
- });
13594
- var NotificationHistoryEntrySchema = object({
13595
- id: string(),
13596
- ruleId: string(),
13597
- ruleName: string(),
13598
- eventId: string(),
13599
- timestamp: number(),
13600
- outputs: array(string()).readonly(),
13601
- success: boolean(),
13602
- error: string().optional(),
13603
- deviceId: number().optional()
13604
- });
13605
- var NotificationHistoryFilterSchema = object({
13606
- ruleId: string().optional(),
13607
- deviceId: number().optional(),
13608
- from: number().optional(),
13609
- to: number().optional(),
13610
- limit: number().optional()
13611
- });
13612
- 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({
13613
- ruleId: string(),
13614
- lookbackMinutes: number()
13615
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
13616
13632
  /**
13617
13633
  * Alerts capability — collection-based internal alert system.
13618
13634
  *
@@ -13799,89 +13815,6 @@ method(object({
13799
13815
  password: string()
13800
13816
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
13801
13817
  /**
13802
- * `login-method` — collection cap through which auth addons contribute
13803
- * their pre-auth login surfaces to the login page. This is the SINGLE,
13804
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
13805
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
13806
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
13807
- * procedure aggregates them for the unauthenticated login page.
13808
- *
13809
- * A contribution is a discriminated union on `kind`:
13810
- *
13811
- * - `redirect` — a declarative button. The login page renders a generic
13812
- * button that navigates to `startUrl` (an addon-owned HTTP route).
13813
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
13814
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
13815
- * login page needs NO change.
13816
- *
13817
- * - `widget` — a Module-Federation widget the login page mounts (via
13818
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
13819
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
13820
- * mechanism kept for future use; no shipped addon uses it on the login
13821
- * page (the passkey ceremony below runs natively in the shell instead).
13822
- *
13823
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
13824
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
13825
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
13826
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
13827
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
13828
- * fetching any remote code pre-auth. Contribution stays unconditional —
13829
- * enrollment state is never leaked pre-auth; visibility is a shell
13830
- * decision.
13831
- *
13832
- * Every contribution carries a `stage`:
13833
- * - `primary` — shown on the first credentials screen (OIDC /
13834
- * magic-link buttons; a future usernameless passkey).
13835
- * - `second-factor` — shown AFTER the password leg, gated on the
13836
- * returned `factors` (passkey-as-2FA today).
13837
- *
13838
- * `mount: skip` — the cap is read server-side by the core auth router
13839
- * (`registry.getCollection('login-method')`), never mounted as its own
13840
- * tRPC router.
13841
- */
13842
- /** When a login method renders in the two-phase login flow. */
13843
- var LoginStageEnum = _enum(["primary", "second-factor"]);
13844
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
13845
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
13846
- object({
13847
- kind: literal("redirect"),
13848
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
13849
- id: string(),
13850
- /** Operator-facing button label. */
13851
- label: string(),
13852
- /** lucide-react icon name. */
13853
- icon: string().optional(),
13854
- /** Addon-owned HTTP route the button navigates to (GET). */
13855
- startUrl: string(),
13856
- stage: LoginStageEnum
13857
- }),
13858
- object({
13859
- kind: literal("widget"),
13860
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
13861
- id: string(),
13862
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
13863
- addonId: string(),
13864
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
13865
- bundle: string(),
13866
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
13867
- remote: WidgetRemoteSchema,
13868
- stage: LoginStageEnum
13869
- }),
13870
- object({
13871
- kind: literal("passkey"),
13872
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
13873
- id: string(),
13874
- /** Operator-facing button label. */
13875
- label: string(),
13876
- stage: LoginStageEnum,
13877
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
13878
- rpId: string(),
13879
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
13880
- origin: string().nullable()
13881
- })
13882
- ]);
13883
- method(_void(), array(LoginMethodContributionSchema).readonly());
13884
- /**
13885
13818
  * Orchestrator-side destination metadata. The orchestrator computes
13886
13819
  * `id = <addonId>:<subId>` from its provider lookup so consumers
13887
13820
  * (admin UI, restore flow) see one canonical key.
@@ -15274,240 +15207,615 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
15274
15207
  kind: "mutation",
15275
15208
  auth: "admin"
15276
15209
  });
15277
- var LogLevelSchema = _enum([
15278
- "debug",
15279
- "info",
15280
- "warn",
15281
- "error"
15210
+ /**
15211
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15212
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15213
+ * caps stay wire-compatible without a circular cap→cap import.
15214
+ *
15215
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
15216
+ * every transport tier structurally, and failed calls still write usage rows.
15217
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15218
+ */
15219
+ var LlmUsageSchema = object({
15220
+ inputTokens: number(),
15221
+ outputTokens: number()
15222
+ });
15223
+ var LlmErrorCodeSchema = _enum([
15224
+ "timeout",
15225
+ "rate-limited",
15226
+ "auth",
15227
+ "refusal",
15228
+ "bad-request",
15229
+ "unavailable",
15230
+ "no-profile",
15231
+ "budget-exceeded",
15232
+ "adapter-error"
15282
15233
  ]);
15283
- var LogEntrySchema = object({
15284
- timestamp: date(),
15285
- level: LogLevelSchema,
15286
- scope: array(string()),
15234
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15235
+ ok: literal(true),
15236
+ text: string(),
15237
+ model: string(),
15238
+ usage: LlmUsageSchema,
15239
+ truncated: boolean(),
15240
+ latencyMs: number()
15241
+ }), object({
15242
+ ok: literal(false),
15243
+ code: LlmErrorCodeSchema,
15287
15244
  message: string(),
15288
- meta: record(string(), unknown()).optional(),
15289
- tags: record(string(), string()).optional()
15290
- });
15291
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15292
- scope: array(string()).optional(),
15293
- level: LogLevelSchema.optional(),
15294
- since: date().optional(),
15295
- until: date().optional(),
15296
- limit: number().optional(),
15297
- tags: record(string(), string()).optional()
15298
- }), array(LogEntrySchema).readonly());
15299
- var CpuBreakdownSchema = object({
15300
- total: number(),
15301
- user: number(),
15302
- system: number(),
15303
- irq: number(),
15304
- nice: number(),
15305
- loadAvg: tuple([
15306
- number(),
15307
- number(),
15308
- number()
15309
- ]),
15310
- cores: number()
15245
+ retryAfterMs: number().optional()
15246
+ })]);
15247
+ /**
15248
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15249
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15250
+ * notification-output.cap.ts:27-31 precedents).
15251
+ */
15252
+ var LlmImageSchema = object({
15253
+ bytes: _instanceof(Uint8Array),
15254
+ mimeType: string()
15311
15255
  });
15312
- var MemoryInfoSchema = object({
15313
- percent: number(),
15314
- totalBytes: number(),
15315
- usedBytes: number(),
15316
- availableBytes: number(),
15317
- swapUsedBytes: number(),
15318
- swapTotalBytes: number()
15256
+ var LlmGenerateBaseInputSchema = object({
15257
+ /** Collection routing (the notification-output posture). */
15258
+ addonId: string().optional(),
15259
+ /** Explicit profile; else the resolution chain (spec §3). */
15260
+ profileId: string().optional(),
15261
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15262
+ consumer: string(),
15263
+ system: string().optional(),
15264
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
15265
+ prompt: string(),
15266
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15267
+ jsonSchema: record(string(), unknown()).optional(),
15268
+ /** Per-call override of the profile default. */
15269
+ maxTokens: number().int().positive().optional(),
15270
+ temperature: number().optional()
15319
15271
  });
15320
- var DiskIoSnapshotSchema = object({
15321
- readBytes: number(),
15322
- writeBytes: number(),
15323
- readOps: number(),
15324
- writeOps: number(),
15325
- timestampMs: number()
15326
- });
15327
- var NetworkIoSnapshotSchema = object({
15328
- rxBytes: number(),
15329
- txBytes: number(),
15330
- rxPackets: number(),
15331
- txPackets: number(),
15332
- rxErrors: number(),
15333
- txErrors: number(),
15334
- timestampMs: number()
15335
- });
15336
- var MetricsGpuInfoSchema = object({
15337
- utilization: number(),
15338
- model: string(),
15339
- memoryUsedBytes: number(),
15340
- memoryTotalBytes: number(),
15341
- temperature: number().nullable()
15342
- });
15343
- var ProcessResourceInfoSchema = object({
15344
- openFds: number(),
15345
- threadCount: number(),
15346
- activeHandles: number(),
15347
- activeRequests: number()
15348
- });
15349
- var PressureAvgsSchema = object({
15350
- avg10: number(),
15351
- avg60: number(),
15352
- avg300: number()
15353
- });
15354
- var PressureInfoSchema = object({
15355
- some: PressureAvgsSchema,
15356
- full: PressureAvgsSchema.nullable()
15357
- });
15358
- var SystemResourceSnapshotSchema = object({
15359
- cpu: CpuBreakdownSchema,
15360
- memory: MemoryInfoSchema,
15361
- gpu: MetricsGpuInfoSchema.nullable(),
15362
- network: NetworkIoSnapshotSchema,
15363
- disk: DiskIoSnapshotSchema,
15364
- pressure: object({
15365
- cpu: PressureInfoSchema.nullable(),
15366
- memory: PressureInfoSchema.nullable(),
15367
- io: PressureInfoSchema.nullable()
15272
+ /**
15273
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15274
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15275
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15276
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15277
+ * this only through the `llm` cap's methods.
15278
+ *
15279
+ * One running llama-server child per node in v1 (models are RAM-heavy).
15280
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15281
+ * watchdog — operator decision #3).
15282
+ */
15283
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
15284
+ object({
15285
+ kind: literal("catalog"),
15286
+ catalogId: string()
15368
15287
  }),
15369
- process: ProcessResourceInfoSchema,
15370
- cpuTemperature: number().nullable(),
15371
- timestampMs: number()
15372
- });
15373
- var DiskSpaceInfoSchema = object({
15374
- path: string(),
15375
- totalBytes: number(),
15376
- usedBytes: number(),
15377
- availableBytes: number(),
15378
- percent: number()
15379
- });
15380
- var PidResourceStatsSchema = object({
15381
- pid: number(),
15382
- cpu: number(),
15383
- memory: number(),
15384
- /**
15385
- * Private (anonymous) resident bytes — the per-process V8 heap + native
15386
- * allocations NOT shared with other processes (Linux RssAnon). This is the
15387
- * "real" per-runner cost; summing it across runners is meaningful, unlike
15388
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
15389
- * Undefined where /proc is unavailable (e.g. macOS).
15390
- */
15391
- privateBytes: number().optional(),
15392
- /**
15393
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15394
- * code shared copy-on-write across runners. Undefined on macOS.
15395
- */
15396
- sharedBytes: number().optional()
15288
+ object({
15289
+ kind: literal("url"),
15290
+ url: string(),
15291
+ sha256: string().optional()
15292
+ }),
15293
+ object({
15294
+ kind: literal("path"),
15295
+ path: string()
15296
+ })
15297
+ ]);
15298
+ var ManagedRuntimeConfigSchema = object({
15299
+ /** WHERE the runtime lives — hub or any agent. */
15300
+ nodeId: string(),
15301
+ /** Closed for v1; 'ollama' is a v2 candidate. */
15302
+ engine: _enum(["llama-cpp"]),
15303
+ model: ManagedModelRefSchema,
15304
+ contextSize: number().int().default(4096),
15305
+ /** 0 = CPU-only. */
15306
+ gpuLayers: number().int().default(0),
15307
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15308
+ threads: number().int().optional(),
15309
+ /** Concurrent slots. */
15310
+ parallel: number().int().default(1),
15311
+ /** Else lazy: first generate boots it. */
15312
+ autoStart: boolean().default(false),
15313
+ /** 0 = never; frees RAM after quiet periods. */
15314
+ idleStopMinutes: number().int().default(30)
15397
15315
  });
15398
- var AddonInstanceSchema = object({
15399
- addonId: string(),
15316
+ var LlmRuntimeStatusSchema = object({
15317
+ /** Status is ALWAYS node-qualified. */
15400
15318
  nodeId: string(),
15401
- role: _enum(["hub", "worker"]),
15402
- pid: number(),
15403
15319
  state: _enum([
15404
- "starting",
15405
- "running",
15406
- "stopping",
15407
15320
  "stopped",
15408
- "crashed"
15409
- ]),
15410
- uptimeSec: number()
15411
- });
15412
- var NodeProcessSchema = object({
15413
- pid: number(),
15414
- ppid: number(),
15415
- pgid: number(),
15416
- classification: _enum([
15417
- "root",
15418
- "managed",
15419
- "system",
15420
- "ghost"
15321
+ "downloading",
15322
+ "starting",
15323
+ "ready",
15324
+ "crashed",
15325
+ "failed"
15421
15326
  ]),
15422
- /** `$process` addon binding when `managed`, else null. */
15423
- addonId: string().nullable(),
15424
- /** Kernel-reported nodeId when the process is a known agent/worker. */
15425
- nodeId: string().nullable(),
15426
- /** Truncated command line. */
15427
- command: string(),
15428
- cpuPercent: number(),
15429
- memoryRssBytes: number(),
15430
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15431
- uptimeSec: number(),
15432
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15433
- orphaned: boolean()
15434
- });
15435
- var KillProcessInputSchema = object({
15436
- pid: number(),
15437
- /** Force = SIGKILL. Default is SIGTERM. */
15438
- force: boolean().optional()
15439
- });
15440
- var KillProcessResultSchema = object({
15441
- success: boolean(),
15442
- reason: string().optional(),
15443
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15444
- });
15445
- var DumpHeapSnapshotInputSchema = object({
15446
- /** The addon whose runner should dump a heap snapshot. */
15447
- addonId: string() });
15448
- var DumpHeapSnapshotResultSchema = object({
15449
- success: boolean(),
15450
- /** Path of the written .heapsnapshot inside the runner's container/host. */
15451
- path: string().optional(),
15452
- /** Process pid that was signalled. */
15453
15327
  pid: number().optional(),
15454
- reason: string().optional()
15328
+ port: number().optional(),
15329
+ modelPath: string().optional(),
15330
+ modelId: string().optional(),
15331
+ downloadProgress: number().min(0).max(1).optional(),
15332
+ lastError: string().optional(),
15333
+ crashesInWindow: number(),
15334
+ /** Child RSS (sampled best-effort). */
15335
+ memoryBytes: number().optional(),
15336
+ vramBytes: number().optional()
15455
15337
  });
15456
- var SystemMetricsSchema = object({
15457
- cpuPercent: number(),
15458
- memoryPercent: number(),
15459
- memoryUsedMB: number(),
15460
- memoryTotalMB: number(),
15461
- diskPercent: number().optional(),
15462
- temperature: number().optional(),
15463
- gpuPercent: number().optional(),
15464
- gpuMemoryPercent: number().optional()
15338
+ var LlmNodeModelSchema = object({
15339
+ file: string(),
15340
+ sizeBytes: number(),
15341
+ catalogId: string().optional(),
15342
+ installedAt: number().optional()
15465
15343
  });
15466
- 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, {
15344
+ var LlmRuntimeDiskUsageSchema = object({
15345
+ nodeId: string(),
15346
+ modelsBytes: number(),
15347
+ freeBytes: number().optional()
15348
+ });
15349
+ method(LlmGenerateBaseInputSchema.extend({
15350
+ images: array(LlmImageSchema).optional(),
15351
+ runtime: ManagedRuntimeConfigSchema,
15352
+ /** The managed profile's timeout, threaded by the hub provider. */
15353
+ timeoutMs: number().int().positive().optional()
15354
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15467
15355
  kind: "mutation",
15468
15356
  auth: "admin"
15469
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15357
+ }), method(object({}), _void(), {
15470
15358
  kind: "mutation",
15471
15359
  auth: "admin"
15472
- });
15473
- method(object({
15474
- sourceUrl: string(),
15475
- metadata: ModelConvertMetadataSchema,
15476
- targets: array(ConvertTargetSchema).min(1).readonly(),
15477
- calibrationRef: string().optional(),
15478
- sessionId: string().optional()
15479
- }), ConvertResultSchema, {
15360
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
15480
15361
  kind: "mutation",
15481
- auth: "admin",
15482
- timeoutMs: 6e5
15483
- });
15484
- method(object({
15485
- nodeId: string(),
15486
- modelId: string(),
15487
- format: _enum(MODEL_FORMATS),
15488
- entry: ModelCatalogEntrySchema
15489
- }), object({
15490
- ok: boolean(),
15491
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
15492
- sha256: string(),
15493
- bytes: number(),
15494
- /** The target node's modelsDir the artifact landed in. */
15495
- path: string()
15496
- }), {
15362
+ auth: "admin"
15363
+ }), method(object({ file: string() }), _void(), {
15497
15364
  kind: "mutation",
15498
15365
  auth: "admin"
15499
- });
15366
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
15500
15367
  /**
15501
- * `mqtt-broker` — broker-registry cap.
15502
- *
15503
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15504
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15505
- * and (b) the connection details a consumer addon needs to spin up
15506
- * its OWN `mqtt.js` client.
15368
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
15369
+ * methods concat-fan across providers; single-row methods route to ONE
15370
+ * provider by the `addonId` in the call input (the notification-output
15371
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
15372
+ * (hub-placed); the cap stays open for future providers.
15507
15373
  *
15508
- * Why: pub/sub routing over the system event-bus loses fidelity
15509
- * (callback shape, QoS guarantees, will/retain semantics) and adds
15510
- * refcount bookkeeping that addons would rather own themselves. The
15374
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
15375
+ * `apiKey` is a password field providers REDACT it on read and merge on
15376
+ * write; a stored key NEVER round-trips to a client.
15377
+ */
15378
+ var LlmProfileKindSchema = _enum([
15379
+ "openai-compatible",
15380
+ "openai",
15381
+ "anthropic",
15382
+ "google",
15383
+ "managed-local"
15384
+ ]);
15385
+ var LlmProfileSchema = object({
15386
+ id: string(),
15387
+ name: string(),
15388
+ kind: LlmProfileKindSchema,
15389
+ /** Stamped by the provider — keeps the fanned catalog routable. */
15390
+ addonId: string(),
15391
+ enabled: boolean(),
15392
+ /** Vendor model id, or the managed runtime's loaded model. */
15393
+ model: string(),
15394
+ /** Required for openai-compatible; override for cloud kinds. */
15395
+ baseUrl: string().optional(),
15396
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
15397
+ apiKey: string().optional(),
15398
+ supportsVision: boolean(),
15399
+ temperature: number().min(0).max(2).optional(),
15400
+ maxTokens: number().int().positive().optional(),
15401
+ timeoutMs: number().int().positive().default(6e4),
15402
+ extraHeaders: record(string(), string()).optional(),
15403
+ /** kind === 'managed-local' only (spec §4). */
15404
+ runtime: ManagedRuntimeConfigSchema.optional()
15405
+ });
15406
+ /** ConfigUISchema tree passed through untyped on the wire (the
15407
+ * notification-output `ConfigSchemaPassthrough` precedent at
15408
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
15409
+ var ConfigSchemaPassthrough$1 = unknown();
15410
+ var LlmProfileKindDescriptorSchema = object({
15411
+ kind: LlmProfileKindSchema,
15412
+ label: string(),
15413
+ icon: string(),
15414
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
15415
+ addonId: string(),
15416
+ configSchema: ConfigSchemaPassthrough$1
15417
+ });
15418
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
15419
+ var LlmDefaultSchema = object({
15420
+ selector: LlmDefaultSelectorSchema,
15421
+ profileId: string()
15422
+ });
15423
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
15424
+ var LlmUsageRollupSchema = object({
15425
+ day: string(),
15426
+ consumer: string(),
15427
+ profileId: string(),
15428
+ calls: number(),
15429
+ okCalls: number(),
15430
+ errorCalls: number(),
15431
+ inputTokens: number(),
15432
+ outputTokens: number(),
15433
+ avgLatencyMs: number()
15434
+ });
15435
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
15436
+ var ManagedModelCatalogEntrySchema = object({
15437
+ id: string(),
15438
+ label: string(),
15439
+ family: string(),
15440
+ purpose: _enum(["text", "vision"]),
15441
+ url: string(),
15442
+ sha256: string(),
15443
+ sizeBytes: number(),
15444
+ quantization: string(),
15445
+ /** Load-time guidance shown in the picker. */
15446
+ minRamBytes: number(),
15447
+ contextSizeDefault: number().int(),
15448
+ /** Vision models: companion projector file. */
15449
+ mmprojUrl: string().optional()
15450
+ });
15451
+ var LlmRuntimeNodeSchema = object({
15452
+ nodeId: string(),
15453
+ reachable: boolean(),
15454
+ status: LlmRuntimeStatusSchema.optional(),
15455
+ disk: LlmRuntimeDiskUsageSchema.optional(),
15456
+ error: string().optional()
15457
+ });
15458
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
15459
+ var ProfileRefInputSchema = object({
15460
+ addonId: string(),
15461
+ profileId: string()
15462
+ });
15463
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
15464
+ kind: "mutation",
15465
+ auth: "admin"
15466
+ }), method(ProfileRefInputSchema, _void(), {
15467
+ kind: "mutation",
15468
+ auth: "admin"
15469
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
15470
+ kind: "mutation",
15471
+ auth: "admin"
15472
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
15473
+ selector: LlmDefaultSelectorSchema,
15474
+ profileId: string().nullable()
15475
+ }), _void(), {
15476
+ kind: "mutation",
15477
+ auth: "admin"
15478
+ }), method(object({
15479
+ since: number().optional(),
15480
+ until: number().optional(),
15481
+ consumer: string().optional(),
15482
+ profileId: string().optional()
15483
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
15484
+ nodeId: string(),
15485
+ model: ManagedModelRefSchema
15486
+ }), _void(), {
15487
+ kind: "mutation",
15488
+ auth: "admin"
15489
+ }), method(object({
15490
+ nodeId: string(),
15491
+ file: string()
15492
+ }), _void(), {
15493
+ kind: "mutation",
15494
+ auth: "admin"
15495
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
15496
+ kind: "mutation",
15497
+ auth: "admin"
15498
+ }), method(ProfileRefInputSchema, _void(), {
15499
+ kind: "mutation",
15500
+ auth: "admin"
15501
+ });
15502
+ var LogLevelSchema = _enum([
15503
+ "debug",
15504
+ "info",
15505
+ "warn",
15506
+ "error"
15507
+ ]);
15508
+ var LogEntrySchema = object({
15509
+ timestamp: date(),
15510
+ level: LogLevelSchema,
15511
+ scope: array(string()),
15512
+ message: string(),
15513
+ meta: record(string(), unknown()).optional(),
15514
+ tags: record(string(), string()).optional()
15515
+ });
15516
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
15517
+ scope: array(string()).optional(),
15518
+ level: LogLevelSchema.optional(),
15519
+ since: date().optional(),
15520
+ until: date().optional(),
15521
+ limit: number().optional(),
15522
+ tags: record(string(), string()).optional()
15523
+ }), array(LogEntrySchema).readonly());
15524
+ /**
15525
+ * `login-method` — collection cap through which auth addons contribute
15526
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
15527
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
15528
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
15529
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
15530
+ * procedure aggregates them for the unauthenticated login page.
15531
+ *
15532
+ * A contribution is a discriminated union on `kind`:
15533
+ *
15534
+ * - `redirect` — a declarative button. The login page renders a generic
15535
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
15536
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
15537
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
15538
+ * login page needs NO change.
15539
+ *
15540
+ * - `widget` — a Module-Federation widget the login page mounts (via
15541
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
15542
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
15543
+ * mechanism kept for future use; no shipped addon uses it on the login
15544
+ * page (the passkey ceremony below runs natively in the shell instead).
15545
+ *
15546
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
15547
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
15548
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
15549
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
15550
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
15551
+ * fetching any remote code pre-auth. Contribution stays unconditional —
15552
+ * enrollment state is never leaked pre-auth; visibility is a shell
15553
+ * decision.
15554
+ *
15555
+ * Every contribution carries a `stage`:
15556
+ * - `primary` — shown on the first credentials screen (OIDC /
15557
+ * magic-link buttons; a future usernameless passkey).
15558
+ * - `second-factor` — shown AFTER the password leg, gated on the
15559
+ * returned `factors` (passkey-as-2FA today).
15560
+ *
15561
+ * `mount: skip` — the cap is read server-side by the core auth router
15562
+ * (`registry.getCollection('login-method')`), never mounted as its own
15563
+ * tRPC router.
15564
+ */
15565
+ /** When a login method renders in the two-phase login flow. */
15566
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
15567
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
15568
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
15569
+ object({
15570
+ kind: literal("redirect"),
15571
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
15572
+ id: string(),
15573
+ /** Operator-facing button label. */
15574
+ label: string(),
15575
+ /** lucide-react icon name. */
15576
+ icon: string().optional(),
15577
+ /** Addon-owned HTTP route the button navigates to (GET). */
15578
+ startUrl: string(),
15579
+ stage: LoginStageEnum
15580
+ }),
15581
+ object({
15582
+ kind: literal("widget"),
15583
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
15584
+ id: string(),
15585
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
15586
+ addonId: string(),
15587
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
15588
+ bundle: string(),
15589
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
15590
+ remote: WidgetRemoteSchema,
15591
+ stage: LoginStageEnum
15592
+ }),
15593
+ object({
15594
+ kind: literal("passkey"),
15595
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
15596
+ id: string(),
15597
+ /** Operator-facing button label. */
15598
+ label: string(),
15599
+ stage: LoginStageEnum,
15600
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
15601
+ rpId: string(),
15602
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
15603
+ origin: string().nullable()
15604
+ })
15605
+ ]);
15606
+ method(_void(), array(LoginMethodContributionSchema).readonly());
15607
+ var CpuBreakdownSchema = object({
15608
+ total: number(),
15609
+ user: number(),
15610
+ system: number(),
15611
+ irq: number(),
15612
+ nice: number(),
15613
+ loadAvg: tuple([
15614
+ number(),
15615
+ number(),
15616
+ number()
15617
+ ]),
15618
+ cores: number()
15619
+ });
15620
+ var MemoryInfoSchema = object({
15621
+ percent: number(),
15622
+ totalBytes: number(),
15623
+ usedBytes: number(),
15624
+ availableBytes: number(),
15625
+ swapUsedBytes: number(),
15626
+ swapTotalBytes: number()
15627
+ });
15628
+ var DiskIoSnapshotSchema = object({
15629
+ readBytes: number(),
15630
+ writeBytes: number(),
15631
+ readOps: number(),
15632
+ writeOps: number(),
15633
+ timestampMs: number()
15634
+ });
15635
+ var NetworkIoSnapshotSchema = object({
15636
+ rxBytes: number(),
15637
+ txBytes: number(),
15638
+ rxPackets: number(),
15639
+ txPackets: number(),
15640
+ rxErrors: number(),
15641
+ txErrors: number(),
15642
+ timestampMs: number()
15643
+ });
15644
+ var MetricsGpuInfoSchema = object({
15645
+ utilization: number(),
15646
+ model: string(),
15647
+ memoryUsedBytes: number(),
15648
+ memoryTotalBytes: number(),
15649
+ temperature: number().nullable()
15650
+ });
15651
+ var ProcessResourceInfoSchema = object({
15652
+ openFds: number(),
15653
+ threadCount: number(),
15654
+ activeHandles: number(),
15655
+ activeRequests: number()
15656
+ });
15657
+ var PressureAvgsSchema = object({
15658
+ avg10: number(),
15659
+ avg60: number(),
15660
+ avg300: number()
15661
+ });
15662
+ var PressureInfoSchema = object({
15663
+ some: PressureAvgsSchema,
15664
+ full: PressureAvgsSchema.nullable()
15665
+ });
15666
+ var SystemResourceSnapshotSchema = object({
15667
+ cpu: CpuBreakdownSchema,
15668
+ memory: MemoryInfoSchema,
15669
+ gpu: MetricsGpuInfoSchema.nullable(),
15670
+ network: NetworkIoSnapshotSchema,
15671
+ disk: DiskIoSnapshotSchema,
15672
+ pressure: object({
15673
+ cpu: PressureInfoSchema.nullable(),
15674
+ memory: PressureInfoSchema.nullable(),
15675
+ io: PressureInfoSchema.nullable()
15676
+ }),
15677
+ process: ProcessResourceInfoSchema,
15678
+ cpuTemperature: number().nullable(),
15679
+ timestampMs: number()
15680
+ });
15681
+ var DiskSpaceInfoSchema = object({
15682
+ path: string(),
15683
+ totalBytes: number(),
15684
+ usedBytes: number(),
15685
+ availableBytes: number(),
15686
+ percent: number()
15687
+ });
15688
+ var PidResourceStatsSchema = object({
15689
+ pid: number(),
15690
+ cpu: number(),
15691
+ memory: number(),
15692
+ /**
15693
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
15694
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
15695
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
15696
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
15697
+ * Undefined where /proc is unavailable (e.g. macOS).
15698
+ */
15699
+ privateBytes: number().optional(),
15700
+ /**
15701
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
15702
+ * code shared copy-on-write across runners. Undefined on macOS.
15703
+ */
15704
+ sharedBytes: number().optional()
15705
+ });
15706
+ var AddonInstanceSchema = object({
15707
+ addonId: string(),
15708
+ nodeId: string(),
15709
+ role: _enum(["hub", "worker"]),
15710
+ pid: number(),
15711
+ state: _enum([
15712
+ "starting",
15713
+ "running",
15714
+ "stopping",
15715
+ "stopped",
15716
+ "crashed"
15717
+ ]),
15718
+ uptimeSec: number()
15719
+ });
15720
+ var NodeProcessSchema = object({
15721
+ pid: number(),
15722
+ ppid: number(),
15723
+ pgid: number(),
15724
+ classification: _enum([
15725
+ "root",
15726
+ "managed",
15727
+ "system",
15728
+ "ghost"
15729
+ ]),
15730
+ /** `$process` addon binding when `managed`, else null. */
15731
+ addonId: string().nullable(),
15732
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
15733
+ nodeId: string().nullable(),
15734
+ /** Truncated command line. */
15735
+ command: string(),
15736
+ cpuPercent: number(),
15737
+ memoryRssBytes: number(),
15738
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
15739
+ uptimeSec: number(),
15740
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
15741
+ orphaned: boolean()
15742
+ });
15743
+ var KillProcessInputSchema = object({
15744
+ pid: number(),
15745
+ /** Force = SIGKILL. Default is SIGTERM. */
15746
+ force: boolean().optional()
15747
+ });
15748
+ var KillProcessResultSchema = object({
15749
+ success: boolean(),
15750
+ reason: string().optional(),
15751
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
15752
+ });
15753
+ var DumpHeapSnapshotInputSchema = object({
15754
+ /** The addon whose runner should dump a heap snapshot. */
15755
+ addonId: string() });
15756
+ var DumpHeapSnapshotResultSchema = object({
15757
+ success: boolean(),
15758
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
15759
+ path: string().optional(),
15760
+ /** Process pid that was signalled. */
15761
+ pid: number().optional(),
15762
+ reason: string().optional()
15763
+ });
15764
+ var SystemMetricsSchema = object({
15765
+ cpuPercent: number(),
15766
+ memoryPercent: number(),
15767
+ memoryUsedMB: number(),
15768
+ memoryTotalMB: number(),
15769
+ diskPercent: number().optional(),
15770
+ temperature: number().optional(),
15771
+ gpuPercent: number().optional(),
15772
+ gpuMemoryPercent: number().optional()
15773
+ });
15774
+ 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, {
15775
+ kind: "mutation",
15776
+ auth: "admin"
15777
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
15778
+ kind: "mutation",
15779
+ auth: "admin"
15780
+ });
15781
+ method(object({
15782
+ sourceUrl: string(),
15783
+ metadata: ModelConvertMetadataSchema,
15784
+ targets: array(ConvertTargetSchema).min(1).readonly(),
15785
+ calibrationRef: string().optional(),
15786
+ sessionId: string().optional()
15787
+ }), ConvertResultSchema, {
15788
+ kind: "mutation",
15789
+ auth: "admin",
15790
+ timeoutMs: 6e5
15791
+ });
15792
+ method(object({
15793
+ nodeId: string(),
15794
+ modelId: string(),
15795
+ format: _enum(MODEL_FORMATS),
15796
+ entry: ModelCatalogEntrySchema
15797
+ }), object({
15798
+ ok: boolean(),
15799
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
15800
+ sha256: string(),
15801
+ bytes: number(),
15802
+ /** The target node's modelsDir the artifact landed in. */
15803
+ path: string()
15804
+ }), {
15805
+ kind: "mutation",
15806
+ auth: "admin"
15807
+ });
15808
+ /**
15809
+ * `mqtt-broker` — broker-registry cap.
15810
+ *
15811
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
15812
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
15813
+ * and (b) the connection details a consumer addon needs to spin up
15814
+ * its OWN `mqtt.js` client.
15815
+ *
15816
+ * Why: pub/sub routing over the system event-bus loses fidelity
15817
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
15818
+ * refcount bookkeeping that addons would rather own themselves. The
15511
15819
  * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
15512
15820
  * features anyway — give it the connection config, get out of the way.
15513
15821
  *
@@ -15752,392 +16060,588 @@ var TargetKindLevelSchema = object({
15752
16060
  ordinal: number().int().min(1).max(5).nullable(),
15753
16061
  flags: object({
15754
16062
  critical: boolean().optional(),
15755
- silent: boolean().optional(),
15756
- noPush: boolean().optional()
15757
- }).optional(),
15758
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
15759
- requires: array(string()).optional(),
15760
- description: string().optional()
15761
- });
15762
- /** The full capability block consulted before dispatch. */
15763
- var TargetKindCapsSchema = object({
15764
- attachments: object({
15765
- mediaTypes: array(AttachmentMediaTypeSchema),
15766
- mode: _enum([
15767
- "url",
15768
- "bytes",
15769
- "both"
15770
- ]),
15771
- max: number().int().nonnegative(),
15772
- maxBytes: number().int().positive().optional()
15773
- }),
15774
- /** Max action buttons (0 = none). */
15775
- actions: number().int().nonnegative(),
15776
- levels: array(TargetKindLevelSchema),
15777
- format: array(NotificationFormatSchema),
15778
- clickUrl: boolean(),
15779
- sound: boolean(),
15780
- ttl: boolean(),
15781
- bodyMaxLen: number().int().positive()
15782
- });
15783
- /**
15784
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
15785
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
15786
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
15787
- * the union is large and not meant for runtime validation here; the exported
15788
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
15789
- */
15790
- var ConfigSchemaPassthrough$1 = unknown();
15791
- var TargetKindSchema = object({
15792
- kind: string(),
15793
- label: string(),
15794
- icon: string(),
15795
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
15796
- addonId: string(),
15797
- configSchema: ConfigSchemaPassthrough$1,
15798
- supportsDiscovery: boolean(),
15799
- caps: TargetKindCapsSchema
15800
- });
15801
- /**
15802
- * A persisted target. `config` holds secrets; providers REDACT secret fields
15803
- * (return a presence marker only) when serving `listTargets` — never
15804
- * round-trip a stored secret to the UI.
15805
- */
15806
- var TargetSchema = object({
15807
- id: string(),
15808
- name: string(),
15809
- kind: string(),
15810
- addonId: string(),
15811
- enabled: boolean(),
15812
- config: record(string(), unknown())
15813
- });
15814
- /** A discovery-surfaced candidate (config is partial + non-secret). */
15815
- var DiscoveredTargetSchema = object({
15816
- kind: string(),
15817
- suggestedName: string(),
15818
- config: record(string(), unknown())
15819
- });
15820
- /** The degrade engine's report — what was resolved / dropped / degraded. */
15821
- var RenderedAsSchema = object({
15822
- level: string(),
15823
- format: NotificationFormatSchema,
15824
- attachmentsSent: number().int().nonnegative(),
15825
- actionsSent: number().int().nonnegative(),
15826
- truncated: boolean(),
15827
- dropped: array(string())
15828
- });
15829
- var SendResultSchema = object({
15830
- success: boolean(),
15831
- error: string().optional(),
15832
- renderedAs: RenderedAsSchema.optional()
15833
- });
15834
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
15835
- var TestResultSchema = SendResultSchema;
15836
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
15837
- kind: string(),
15838
- config: record(string(), unknown()).optional()
15839
- }), array(DiscoveredTargetSchema)), method(object({
15840
- targetId: string(),
15841
- notification: NotificationSchema
15842
- }), SendResultSchema, { kind: "mutation" }), method(object({
15843
- targetId: string(),
15844
- sample: NotificationSchema.optional()
15845
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
15846
- targetId: string(),
15847
- enabled: boolean()
15848
- }), _void(), { kind: "mutation" });
15849
- /**
15850
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
15851
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
15852
- * caps stay wire-compatible without a circular cap→cap import.
15853
- *
15854
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
15855
- * every transport tier structurally, and failed calls still write usage rows.
15856
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
15857
- */
15858
- var LlmUsageSchema = object({
15859
- inputTokens: number(),
15860
- outputTokens: number()
15861
- });
15862
- var LlmErrorCodeSchema = _enum([
15863
- "timeout",
15864
- "rate-limited",
15865
- "auth",
15866
- "refusal",
15867
- "bad-request",
15868
- "unavailable",
15869
- "no-profile",
15870
- "budget-exceeded",
15871
- "adapter-error"
15872
- ]);
15873
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
15874
- ok: literal(true),
15875
- text: string(),
15876
- model: string(),
15877
- usage: LlmUsageSchema,
15878
- truncated: boolean(),
15879
- latencyMs: number()
15880
- }), object({
15881
- ok: literal(false),
15882
- code: LlmErrorCodeSchema,
15883
- message: string(),
15884
- retryAfterMs: number().optional()
15885
- })]);
15886
- /**
15887
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
15888
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
15889
- * notification-output.cap.ts:27-31 precedents).
15890
- */
15891
- var LlmImageSchema = object({
15892
- bytes: _instanceof(Uint8Array),
15893
- mimeType: string()
15894
- });
15895
- var LlmGenerateBaseInputSchema = object({
15896
- /** Collection routing (the notification-output posture). */
15897
- addonId: string().optional(),
15898
- /** Explicit profile; else the resolution chain (spec §3). */
15899
- profileId: string().optional(),
15900
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
15901
- consumer: string(),
15902
- system: string().optional(),
15903
- /** v1: single-turn. `messages[]` is a v2 additive field. */
15904
- prompt: string(),
15905
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
15906
- jsonSchema: record(string(), unknown()).optional(),
15907
- /** Per-call override of the profile default. */
15908
- maxTokens: number().int().positive().optional(),
15909
- temperature: number().optional()
15910
- });
15911
- /**
15912
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
15913
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
15914
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
15915
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
15916
- * this only through the `llm` cap's methods.
15917
- *
15918
- * One running llama-server child per node in v1 (models are RAM-heavy).
15919
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
15920
- * watchdog — operator decision #3).
15921
- */
15922
- var ManagedModelRefSchema = discriminatedUnion("kind", [
15923
- object({
15924
- kind: literal("catalog"),
15925
- catalogId: string()
15926
- }),
15927
- object({
15928
- kind: literal("url"),
15929
- url: string(),
15930
- sha256: string().optional()
15931
- }),
15932
- object({
15933
- kind: literal("path"),
15934
- path: string()
15935
- })
15936
- ]);
15937
- var ManagedRuntimeConfigSchema = object({
15938
- /** WHERE the runtime lives — hub or any agent. */
15939
- nodeId: string(),
15940
- /** Closed for v1; 'ollama' is a v2 candidate. */
15941
- engine: _enum(["llama-cpp"]),
15942
- model: ManagedModelRefSchema,
15943
- contextSize: number().int().default(4096),
15944
- /** 0 = CPU-only. */
15945
- gpuLayers: number().int().default(0),
15946
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
15947
- threads: number().int().optional(),
15948
- /** Concurrent slots. */
15949
- parallel: number().int().default(1),
15950
- /** Else lazy: first generate boots it. */
15951
- autoStart: boolean().default(false),
15952
- /** 0 = never; frees RAM after quiet periods. */
15953
- idleStopMinutes: number().int().default(30)
15954
- });
15955
- var LlmRuntimeStatusSchema = object({
15956
- /** Status is ALWAYS node-qualified. */
15957
- nodeId: string(),
15958
- state: _enum([
15959
- "stopped",
15960
- "downloading",
15961
- "starting",
15962
- "ready",
15963
- "crashed",
15964
- "failed"
15965
- ]),
15966
- pid: number().optional(),
15967
- port: number().optional(),
15968
- modelPath: string().optional(),
15969
- modelId: string().optional(),
15970
- downloadProgress: number().min(0).max(1).optional(),
15971
- lastError: string().optional(),
15972
- crashesInWindow: number(),
15973
- /** Child RSS (sampled best-effort). */
15974
- memoryBytes: number().optional(),
15975
- vramBytes: number().optional()
16063
+ silent: boolean().optional(),
16064
+ noPush: boolean().optional()
16065
+ }).optional(),
16066
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
16067
+ requires: array(string()).optional(),
16068
+ description: string().optional()
15976
16069
  });
15977
- var LlmNodeModelSchema = object({
15978
- file: string(),
15979
- sizeBytes: number(),
15980
- catalogId: string().optional(),
15981
- installedAt: number().optional()
16070
+ /** The full capability block consulted before dispatch. */
16071
+ var TargetKindCapsSchema = object({
16072
+ attachments: object({
16073
+ mediaTypes: array(AttachmentMediaTypeSchema),
16074
+ mode: _enum([
16075
+ "url",
16076
+ "bytes",
16077
+ "both"
16078
+ ]),
16079
+ max: number().int().nonnegative(),
16080
+ maxBytes: number().int().positive().optional()
16081
+ }),
16082
+ /** Max action buttons (0 = none). */
16083
+ actions: number().int().nonnegative(),
16084
+ levels: array(TargetKindLevelSchema),
16085
+ format: array(NotificationFormatSchema),
16086
+ clickUrl: boolean(),
16087
+ sound: boolean(),
16088
+ ttl: boolean(),
16089
+ bodyMaxLen: number().int().positive()
15982
16090
  });
15983
- var LlmRuntimeDiskUsageSchema = object({
15984
- nodeId: string(),
15985
- modelsBytes: number(),
15986
- freeBytes: number().optional()
16091
+ /**
16092
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
16093
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
16094
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
16095
+ * the union is large and not meant for runtime validation here; the exported
16096
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
16097
+ */
16098
+ var ConfigSchemaPassthrough = unknown();
16099
+ var TargetKindSchema = object({
16100
+ kind: string(),
16101
+ label: string(),
16102
+ icon: string(),
16103
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
16104
+ addonId: string(),
16105
+ configSchema: ConfigSchemaPassthrough,
16106
+ supportsDiscovery: boolean(),
16107
+ caps: TargetKindCapsSchema
15987
16108
  });
15988
- method(LlmGenerateBaseInputSchema.extend({
15989
- images: array(LlmImageSchema).optional(),
15990
- runtime: ManagedRuntimeConfigSchema,
15991
- /** The managed profile's timeout, threaded by the hub provider. */
15992
- timeoutMs: number().int().positive().optional()
15993
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
15994
- kind: "mutation",
15995
- auth: "admin"
15996
- }), method(object({}), _void(), {
15997
- kind: "mutation",
15998
- auth: "admin"
15999
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
16000
- kind: "mutation",
16001
- auth: "admin"
16002
- }), method(object({ file: string() }), _void(), {
16003
- kind: "mutation",
16004
- auth: "admin"
16005
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
16006
16109
  /**
16007
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
16008
- * methods concat-fan across providers; single-row methods route to ONE
16009
- * provider by the `addonId` in the call input (the notification-output
16010
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
16011
- * (hub-placed); the cap stays open for future providers.
16012
- *
16013
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
16014
- * `apiKey` is a password field — providers REDACT it on read and merge on
16015
- * write; a stored key NEVER round-trips to a client.
16110
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
16111
+ * (return a presence marker only) when serving `listTargets` — never
16112
+ * round-trip a stored secret to the UI.
16016
16113
  */
16017
- var LlmProfileKindSchema = _enum([
16018
- "openai-compatible",
16019
- "openai",
16020
- "anthropic",
16021
- "google",
16022
- "managed-local"
16023
- ]);
16024
- var LlmProfileSchema = object({
16114
+ var TargetSchema = object({
16025
16115
  id: string(),
16026
16116
  name: string(),
16027
- kind: LlmProfileKindSchema,
16028
- /** Stamped by the provider — keeps the fanned catalog routable. */
16117
+ kind: string(),
16029
16118
  addonId: string(),
16030
16119
  enabled: boolean(),
16031
- /** Vendor model id, or the managed runtime's loaded model. */
16032
- model: string(),
16033
- /** Required for openai-compatible; override for cloud kinds. */
16034
- baseUrl: string().optional(),
16035
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
16036
- apiKey: string().optional(),
16037
- supportsVision: boolean(),
16038
- temperature: number().min(0).max(2).optional(),
16039
- maxTokens: number().int().positive().optional(),
16040
- timeoutMs: number().int().positive().default(6e4),
16041
- extraHeaders: record(string(), string()).optional(),
16042
- /** kind === 'managed-local' only (spec §4). */
16043
- runtime: ManagedRuntimeConfigSchema.optional()
16120
+ config: record(string(), unknown())
16044
16121
  });
16045
- /** ConfigUISchema tree passed through untyped on the wire (the
16046
- * notification-output `ConfigSchemaPassthrough` precedent at
16047
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
16048
- var ConfigSchemaPassthrough = unknown();
16049
- var LlmProfileKindDescriptorSchema = object({
16050
- kind: LlmProfileKindSchema,
16051
- label: string(),
16052
- icon: string(),
16053
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
16054
- addonId: string(),
16055
- configSchema: ConfigSchemaPassthrough
16122
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
16123
+ var DiscoveredTargetSchema = object({
16124
+ kind: string(),
16125
+ suggestedName: string(),
16126
+ config: record(string(), unknown())
16056
16127
  });
16057
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
16058
- var LlmDefaultSchema = object({
16059
- selector: LlmDefaultSelectorSchema,
16060
- profileId: string()
16128
+ /** The degrade engine's report what was resolved / dropped / degraded. */
16129
+ var RenderedAsSchema = object({
16130
+ level: string(),
16131
+ format: NotificationFormatSchema,
16132
+ attachmentsSent: number().int().nonnegative(),
16133
+ actionsSent: number().int().nonnegative(),
16134
+ truncated: boolean(),
16135
+ dropped: array(string())
16061
16136
  });
16062
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
16063
- var LlmUsageRollupSchema = object({
16064
- day: string(),
16065
- consumer: string(),
16066
- profileId: string(),
16067
- calls: number(),
16068
- okCalls: number(),
16069
- errorCalls: number(),
16070
- inputTokens: number(),
16071
- outputTokens: number(),
16072
- avgLatencyMs: number()
16137
+ var SendResultSchema = object({
16138
+ success: boolean(),
16139
+ error: string().optional(),
16140
+ renderedAs: RenderedAsSchema.optional()
16073
16141
  });
16074
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
16075
- var ManagedModelCatalogEntrySchema = object({
16142
+ /** Same shape as SendResult kept as a distinct name for the test panel. */
16143
+ var TestResultSchema = SendResultSchema;
16144
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
16145
+ kind: string(),
16146
+ config: record(string(), unknown()).optional()
16147
+ }), array(DiscoveredTargetSchema)), method(object({
16148
+ targetId: string(),
16149
+ notification: NotificationSchema
16150
+ }), SendResultSchema, { kind: "mutation" }), method(object({
16151
+ targetId: string(),
16152
+ sample: NotificationSchema.optional()
16153
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
16154
+ targetId: string(),
16155
+ enabled: boolean()
16156
+ }), _void(), { kind: "mutation" });
16157
+ /**
16158
+ * notification-rules — the Notification Center rule surface (P1 core).
16159
+ *
16160
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
16161
+ * (operator decisions D-1/D-2/D-3 are binding):
16162
+ *
16163
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
16164
+ * `notification-center` module), hooked on the durable persistence
16165
+ * moments (object-event insert, TrackCloser.closeExpired) with a
16166
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
16167
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
16168
+ * FIRST persisted detection matching the conditions (per-track dedup,
16169
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
16170
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
16171
+ * - DISPATCH stays behind `notification-output` (rules reference targets
16172
+ * by id; per-backend params are a passthrough blob capped by the
16173
+ * target kind's own caps/degrade engine).
16174
+ *
16175
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
16176
+ * server-injected caller identity — the first `caller: 'required'`
16177
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
16178
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
16179
+ * windows, and the optional label/identity/plate matchers. User rules,
16180
+ * private zones, per-recipient fan-out and the wider condition table are
16181
+ * P2+ (see spec §7).
16182
+ *
16183
+ * All schemas here are the single source of truth — `NcRule` etc. are
16184
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
16185
+ * schema/interface drift is explicitly not repeated).
16186
+ */
16187
+ /**
16188
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
16189
+ * The value maps 1:1 onto the evaluated record kind:
16190
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
16191
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
16192
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
16193
+ * change of a LINKED device, one row per linked camera)
16194
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
16195
+ * delivery / pick-up)
16196
+ *
16197
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
16198
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
16199
+ * this one field keeps the schema additive — a rule still declares exactly
16200
+ * one trigger.
16201
+ */
16202
+ var NcDeliverySchema = _enum([
16203
+ "immediate",
16204
+ "track-end",
16205
+ "device-event",
16206
+ "package-event"
16207
+ ]);
16208
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
16209
+ var NcScheduleSchema = object({
16210
+ windows: array(object({
16211
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
16212
+ days: array(number().int().min(0).max(6)).min(1),
16213
+ startMinute: number().int().min(0).max(1439),
16214
+ endMinute: number().int().min(0).max(1439)
16215
+ })).min(1),
16216
+ /** IANA timezone; default = hub host timezone. */
16217
+ timezone: string().optional(),
16218
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
16219
+ invert: boolean().optional()
16220
+ });
16221
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
16222
+ var NcPlateMatcherSchema = object({
16223
+ values: array(string().min(1)).min(1),
16224
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
16225
+ maxDistance: number().int().min(0).max(3).default(1)
16226
+ });
16227
+ /**
16228
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
16229
+ * occupancy edge for a device — optionally narrowed to a single admin
16230
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
16231
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
16232
+ * - `became-free` — count crossed ≥ `count` → below it
16233
+ * - `>=` / `<=` — count is at/over or at/under `count`
16234
+ * `sustainSeconds` requires the condition hold continuously that long
16235
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
16236
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
16237
+ * the condition never matches. Confirmed edge-state survives addon restarts
16238
+ * (declared SQLite collection, reseeded on boot).
16239
+ */
16240
+ var NcOccupancyConditionSchema = object({
16241
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
16242
+ zoneId: string().optional(),
16243
+ /** Object class to count; absent = any class. */
16244
+ className: string().optional(),
16245
+ op: _enum([
16246
+ "became-occupied",
16247
+ "became-free",
16248
+ ">=",
16249
+ "<="
16250
+ ]).default("became-occupied"),
16251
+ count: number().int().min(0).default(1),
16252
+ sustainSeconds: number().int().min(0).max(3600).default(15)
16253
+ });
16254
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
16255
+ var NcZoneConditionSchema = object({
16256
+ ids: array(string().min(1)).min(1),
16257
+ /** Quantifier over `ids` — at least one / every one visited. */
16258
+ match: _enum(["any", "all"]).default("any")
16259
+ });
16260
+ /**
16261
+ * The P1 condition set — a flat AND of groups; absent group = pass;
16262
+ * membership lists are OR within the list (spec §2.3).
16263
+ */
16264
+ var NcConditionsSchema = object({
16265
+ /** Device scope — absent = all devices. */
16266
+ devices: array(number()).optional(),
16267
+ /** Detector class names (any overlap with the record's class set). */
16268
+ classes: array(string().min(1)).optional(),
16269
+ /** Veto classes — any overlap fails the rule. */
16270
+ classesExclude: array(string().min(1)).optional(),
16271
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
16272
+ minConfidence: number().min(0).max(1).optional(),
16273
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
16274
+ zones: NcZoneConditionSchema.optional(),
16275
+ /** Veto zones — any hit fails the rule. */
16276
+ zonesExclude: array(string().min(1)).optional(),
16277
+ /**
16278
+ * Exact (case-insensitive) match on the record's collapsed `label`
16279
+ * (identity name / plate text / subclass).
16280
+ */
16281
+ labelEquals: array(string().min(1)).optional(),
16282
+ /**
16283
+ * Identity matcher. P1 boundary: matched against the record's collapsed
16284
+ * `label` (the identity display name propagated by the face pipeline) —
16285
+ * identity-ID matching rides in P2 when identity ids reach the record.
16286
+ */
16287
+ identities: array(string().min(1)).optional(),
16288
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
16289
+ plates: NcPlateMatcherSchema.optional(),
16290
+ /**
16291
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
16292
+ * Same P1 boundary: matched against the record's collapsed `label` (the
16293
+ * identity display name). A record with NO label passes (nothing to
16294
+ * exclude), unlike the include variant which fails on an absent label.
16295
+ */
16296
+ identitiesExclude: array(string().min(1)).optional(),
16297
+ /**
16298
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
16299
+ * TRACK-END only: importance is scored at track close, so it does not exist
16300
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
16301
+ * close the value is threaded via the close-time info (the `Track` clone is
16302
+ * captured before the DB row is updated, so it would otherwise read stale).
16303
+ * Fails when the record carries no importance (never guess quality — the
16304
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
16305
+ */
16306
+ minImportance: number().min(0).max(1).optional(),
16307
+ /**
16308
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
16309
+ * TRACK-END only: an `immediate` / object-event subject has no closed
16310
+ * lifespan, so a dwell condition never matches immediate delivery
16311
+ * (documented choice — the object-event record carries no `firstSeen`,
16312
+ * so dwell cannot be computed from what the subject actually carries).
16313
+ */
16314
+ minDwellSeconds: number().min(0).optional(),
16315
+ /**
16316
+ * Detection provenance filter. `any` (default / absent) matches every
16317
+ * source; otherwise the subject's source must equal it. Legacy records
16318
+ * with no stamped source are treated as `pipeline`. The union spans both
16319
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
16320
+ * tracks carry `sensor`.
16321
+ */
16322
+ source: _enum([
16323
+ "pipeline",
16324
+ "onboard",
16325
+ "sensor",
16326
+ "any"
16327
+ ]).optional(),
16328
+ /**
16329
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
16330
+ * detector `minConfidence` (that gates the object-detection score; this
16331
+ * gates the recognition/OCR match score). Fails when the subject carries
16332
+ * no label-match confidence (never guess). TRACK-END only: the confidence
16333
+ * lives on the recognition result and reaches the subject at track close.
16334
+ *
16335
+ * What it measures precisely (plumbed at track close — the closer threads
16336
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
16337
+ * `importance`): the BEST recognition match confidence observed for the
16338
+ * label the track carries at close — for a face, the peak cosine similarity
16339
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
16340
+ * for a plate, the peak OCR read score of the best-held plate
16341
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
16342
+ * one track the higher of the two is used. A track that ended with no
16343
+ * confident identity/plate match carries no value, so the condition fails
16344
+ * closed for it (an un-recognized subject).
16345
+ */
16346
+ minLabelConfidence: number().min(0).max(1).optional(),
16347
+ /**
16348
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
16349
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
16350
+ * against the token carried on the device-event subject (extracted from the
16351
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
16352
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
16353
+ * eventType, so gate those with {@link sensorKinds} instead.
16354
+ */
16355
+ eventTypeTokens: array(string().min(1)).optional(),
16356
+ /**
16357
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
16358
+ * `contact`, `button`, `device-event`) — matched against the persisted
16359
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
16360
+ */
16361
+ sensorKinds: array(string().min(1)).optional(),
16362
+ /**
16363
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
16364
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
16365
+ * when the subject's phase does not match (a subject always carries a phase
16366
+ * on the package-event trigger).
16367
+ */
16368
+ packagePhase: _enum([
16369
+ "delivered",
16370
+ "picked-up",
16371
+ "both"
16372
+ ]).optional(),
16373
+ /**
16374
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
16375
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
16376
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
16377
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
16378
+ */
16379
+ customZones: array(MaskPolygonShapeSchema).optional(),
16380
+ /**
16381
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
16382
+ * (optionally zone/class-scoped) occupancy count crosses the configured
16383
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
16384
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
16385
+ */
16386
+ occupancy: NcOccupancyConditionSchema.optional()
16387
+ });
16388
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
16389
+ var NcRuleTargetSchema = object({
16390
+ /** `notification-output` Target id. */
16391
+ targetId: string().min(1),
16392
+ /**
16393
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
16394
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
16395
+ * degrade engine drops what the backend can't render.
16396
+ */
16397
+ params: record(string(), unknown()).optional()
16398
+ });
16399
+ /**
16400
+ * Media attachment policy (P1 still-image subset).
16401
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
16402
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
16403
+ * matched on identities attaches the subject's `faceCrop`, one matched on
16404
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
16405
+ * (or when the specific crop is missing) degrades to `best`, then
16406
+ * `keyFrame`, then no attachment — never delaying the send. The matched
16407
+ * condition summary is frozen on the outbox row at enqueue (like the rule
16408
+ * name), so the choice never drifts from the record that fired it.
16409
+ * - `keyFrame` — the clean scene frame (no subject box).
16410
+ * - `none` — no attachment.
16411
+ */
16412
+ var NcMediaPolicySchema = object({ attach: _enum([
16413
+ "best",
16414
+ "best-matching",
16415
+ "keyFrame",
16416
+ "none"
16417
+ ]).default("best") });
16418
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
16419
+ var NcThrottleSchema = object({
16420
+ cooldownSec: number().int().min(0).max(86400).default(60),
16421
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
16422
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
16423
+ });
16424
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
16425
+ var NcRuleInputSchema = object({
16426
+ name: string().min(1).max(200),
16427
+ enabled: boolean().default(true),
16428
+ delivery: NcDeliverySchema,
16429
+ conditions: NcConditionsSchema.default({}),
16430
+ schedule: NcScheduleSchema.optional(),
16431
+ targets: array(NcRuleTargetSchema).min(1),
16432
+ media: NcMediaPolicySchema.default({ attach: "best" }),
16433
+ throttle: NcThrottleSchema.default({
16434
+ cooldownSec: 60,
16435
+ scope: "rule-device"
16436
+ }),
16437
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
16438
+ template: object({
16439
+ title: string().max(500).optional(),
16440
+ body: string().max(2e3).optional()
16441
+ }).optional(),
16442
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
16443
+ priority: number().int().min(1).max(5).default(3),
16444
+ /**
16445
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
16446
+ * behaviour, visible to all, read-only in the viewer). Present = personal
16447
+ * rule owned by this userId. Server-stamped; never trusted from a client.
16448
+ */
16449
+ ownerUserId: string().optional()
16450
+ });
16451
+ /**
16452
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
16453
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
16454
+ * NOT a client-authored input field (it lives on the persisted rule, not the
16455
+ * input), so it is added here explicitly to let the store's per-target opt-out
16456
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
16457
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
16458
+ * `updateRule` patch.
16459
+ */
16460
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
16461
+ /** A persisted rule. */
16462
+ var NcRuleSchema = NcRuleInputSchema.extend({
16463
+ id: string(),
16464
+ /** userId of the admin who created the rule (server-stamped caller). */
16465
+ createdBy: string(),
16466
+ createdAt: number(),
16467
+ updatedAt: number(),
16468
+ /**
16469
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
16470
+ * send time. Only a target's OWNER may add/remove its id (server-checked
16471
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
16472
+ */
16473
+ disabledTargetIds: array(string()).default([])
16474
+ });
16475
+ var NcTestResultSchema = object({
16476
+ recordId: string(),
16477
+ recordKind: _enum([
16478
+ "object-event",
16479
+ "track",
16480
+ "device-event",
16481
+ "package-event"
16482
+ ]),
16483
+ deviceId: number(),
16484
+ timestamp: number(),
16485
+ wouldFire: boolean(),
16486
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
16487
+ failedCondition: string().optional(),
16488
+ className: string().optional(),
16489
+ label: string().optional()
16490
+ });
16491
+ var NcConditionDescriptorSchema = object({
16492
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
16076
16493
  id: string(),
16494
+ group: _enum([
16495
+ "scope",
16496
+ "class",
16497
+ "zones",
16498
+ "quality",
16499
+ "label",
16500
+ "schedule",
16501
+ "device",
16502
+ "package",
16503
+ "occupancy"
16504
+ ]),
16077
16505
  label: string(),
16078
- family: string(),
16079
- purpose: _enum(["text", "vision"]),
16080
- url: string(),
16081
- sha256: string(),
16082
- sizeBytes: number(),
16083
- quantization: string(),
16084
- /** Load-time guidance shown in the picker. */
16085
- minRamBytes: number(),
16086
- contextSizeDefault: number().int(),
16087
- /** Vision models: companion projector file. */
16088
- mmprojUrl: string().optional()
16506
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
16507
+ valueType: _enum([
16508
+ "deviceIdList",
16509
+ "stringList",
16510
+ "number01",
16511
+ "number",
16512
+ "sourceSelect",
16513
+ "zoneSelection",
16514
+ "zoneIdList",
16515
+ "schedule",
16516
+ "plateMatcher",
16517
+ "packagePhase",
16518
+ "polygonDraw",
16519
+ "occupancy"
16520
+ ]),
16521
+ operator: _enum([
16522
+ "in",
16523
+ "notIn",
16524
+ "anyOf",
16525
+ "allOf",
16526
+ "gte",
16527
+ "fuzzyIn",
16528
+ "withinSchedule"
16529
+ ]),
16530
+ /** Which delivery kinds the condition applies to. */
16531
+ appliesTo: array(NcDeliverySchema),
16532
+ phase: string(),
16533
+ description: string().optional()
16089
16534
  });
16090
- var LlmRuntimeNodeSchema = object({
16091
- nodeId: string(),
16092
- reachable: boolean(),
16093
- status: LlmRuntimeStatusSchema.optional(),
16094
- disk: LlmRuntimeDiskUsageSchema.optional(),
16095
- error: string().optional()
16535
+ /**
16536
+ * The delivery lifecycle status of a history row — a straight read of the
16537
+ * durable outbox row's own status (single source of truth):
16538
+ * - `pending` — enqueued, in-flight or retrying with backoff
16539
+ * - `sent` — delivered (terminal)
16540
+ * - `dead` — dead-lettered after exhausting retries / a permanent
16541
+ * backend rejection / a deleted target (terminal; carries
16542
+ * the failure `error`)
16543
+ *
16544
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
16545
+ * user dimension (quiet hours / snooze) and are additive when they land.
16546
+ */
16547
+ var NcHistoryStatusSchema = _enum([
16548
+ "pending",
16549
+ "sent",
16550
+ "dead"
16551
+ ]);
16552
+ /** The evaluated record kind a history row descends from (one per trigger). */
16553
+ var NcHistoryRecordKindSchema = _enum([
16554
+ "object-event",
16555
+ "track-end",
16556
+ "device-event",
16557
+ "package-event"
16558
+ ]);
16559
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
16560
+ var NcHistorySubjectSchema = object({
16561
+ className: string(),
16562
+ label: string().optional(),
16563
+ confidence: number().optional(),
16564
+ zones: array(string()),
16565
+ timestamp: number()
16566
+ });
16567
+ /**
16568
+ * One delivery-history row. This is a read-only VIEW over the durable
16569
+ * outbox row (single source of truth — the same row the drain loop drives;
16570
+ * NO second write path, so history can never drift from delivery state).
16571
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
16572
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
16573
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
16574
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
16575
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
16576
+ * P1 (admin scope only).
16577
+ */
16578
+ var NcHistoryEntrySchema = object({
16579
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
16580
+ id: string(),
16581
+ ruleId: string(),
16582
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
16583
+ ruleName: string(),
16584
+ /** The rule urgency/trigger that produced this delivery. */
16585
+ delivery: NcDeliverySchema,
16586
+ targetId: string(),
16587
+ deviceId: number(),
16588
+ recordKind: NcHistoryRecordKindSchema,
16589
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
16590
+ recordId: string(),
16591
+ /** Present for track-scoped deliveries (object-event / track-end). */
16592
+ trackId: string().optional(),
16593
+ status: NcHistoryStatusSchema,
16594
+ /** Delivery attempts made so far. */
16595
+ attempts: number().int(),
16596
+ /** Fire time (outbox enqueue). */
16597
+ createdAt: number(),
16598
+ /** Last transition time (terminal for sent / dead). */
16599
+ updatedAt: number(),
16600
+ /** Failure detail — present on a `dead` row. */
16601
+ error: string().optional(),
16602
+ subject: NcHistorySubjectSchema
16096
16603
  });
16097
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
16098
- var ProfileRefInputSchema = object({
16099
- addonId: string(),
16100
- profileId: string()
16604
+ /**
16605
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
16606
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
16607
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
16608
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
16609
+ */
16610
+ var NcHistoryFilterSchema = object({
16611
+ ruleId: string().optional(),
16612
+ deviceId: number().optional(),
16613
+ status: NcHistoryStatusSchema.optional(),
16614
+ since: number().optional(),
16615
+ until: number().optional(),
16616
+ limit: number().int().min(1).max(500).default(100)
16101
16617
  });
16102
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
16103
- kind: "mutation",
16104
- auth: "admin"
16105
- }), method(ProfileRefInputSchema, _void(), {
16618
+ 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 }), {
16106
16619
  kind: "mutation",
16107
- auth: "admin"
16108
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
16620
+ auth: "admin",
16621
+ caller: "required"
16622
+ }), method(object({
16623
+ ruleId: string(),
16624
+ patch: NcRulePatchSchema
16625
+ }), object({ rule: NcRuleSchema }), {
16109
16626
  kind: "mutation",
16110
- auth: "admin"
16111
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
16112
- selector: LlmDefaultSelectorSchema,
16113
- profileId: string().nullable()
16114
- }), _void(), {
16627
+ auth: "admin",
16628
+ caller: "required"
16629
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
16115
16630
  kind: "mutation",
16116
16631
  auth: "admin"
16117
16632
  }), method(object({
16118
- since: number().optional(),
16119
- until: number().optional(),
16120
- consumer: string().optional(),
16121
- profileId: string().optional()
16122
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
16123
- nodeId: string(),
16124
- model: ManagedModelRefSchema
16125
- }), _void(), {
16633
+ ruleId: string(),
16634
+ enabled: boolean()
16635
+ }), object({ success: literal(true) }), {
16126
16636
  kind: "mutation",
16127
16637
  auth: "admin"
16128
16638
  }), method(object({
16129
- nodeId: string(),
16130
- file: string()
16131
- }), _void(), {
16132
- kind: "mutation",
16133
- auth: "admin"
16134
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
16135
- kind: "mutation",
16136
- auth: "admin"
16137
- }), method(ProfileRefInputSchema, _void(), {
16639
+ rule: NcRuleInputSchema,
16640
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
16641
+ }), object({ results: array(NcTestResultSchema) }), {
16138
16642
  kind: "mutation",
16139
16643
  auth: "admin"
16140
- });
16644
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
16141
16645
  /**
16142
16646
  * Zod schemas for persisted record types.
16143
16647
  *
@@ -16823,7 +17327,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16823
17327
  }), method(object({
16824
17328
  eventId: string(),
16825
17329
  kind: MediaFileKindEnum.optional()
16826
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
17330
+ }), array(MediaFileSchema).readonly()), method(object({
17331
+ trackId: string(),
17332
+ kinds: array(MediaFileKindEnum).optional()
17333
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
16827
17334
  deviceId: number(),
16828
17335
  timestamp: number(),
16829
17336
  frameWidth: number(),
@@ -16844,76 +17351,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
16844
17351
  eventId: string(),
16845
17352
  timestamp: number()
16846
17353
  });
16847
- /**
16848
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
16849
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
16850
- * caps into per-camera event-kind descriptors.
16851
- *
16852
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
16853
- * is NOT duplicated here — every entry is derived from the single
16854
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
16855
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
16856
- * control cap means adding one line here (and a taxonomy entry); the anti-
16857
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
16858
- * eventful cap is missing.
16859
- */
16860
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
16861
- var LEGACY_ICON = {
16862
- motion: "motion",
16863
- audio: "audio",
16864
- person: "person",
16865
- vehicle: "vehicle",
16866
- animal: "animal",
16867
- package: "package",
16868
- door: "door",
16869
- pir: "pir",
16870
- smoke: "smoke",
16871
- water: "water",
16872
- button: "button",
16873
- generic: "generic",
16874
- gas: "smoke",
16875
- vibration: "generic",
16876
- tamper: "generic",
16877
- presence: "person",
16878
- lock: "generic",
16879
- siren: "generic",
16880
- switch: "generic",
16881
- doorbell: "button"
16882
- };
16883
- function legacyIcon(iconId) {
16884
- return LEGACY_ICON[iconId] ?? "generic";
16885
- }
16886
- /**
16887
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
16888
- * The anti-drift guard cross-checks this against the eventful caps declared
16889
- * in `packages/types/src/capabilities/*.cap.ts`.
16890
- */
16891
- var CAP_TO_KIND = {
16892
- contact: "contact",
16893
- motion: "motion-sensor",
16894
- smoke: "smoke",
16895
- flood: "flood",
16896
- gas: "gas",
16897
- "carbon-monoxide": "carbon-monoxide",
16898
- vibration: "vibration",
16899
- tamper: "tamper",
16900
- presence: "presence",
16901
- "enum-sensor": "enum-sensor",
16902
- "event-emitter": "device-event",
16903
- "lock-control": "lock",
16904
- switch: "switch",
16905
- button: "button",
16906
- doorbell: "doorbell"
16907
- };
16908
- function buildDescriptor(capName, kind) {
16909
- const t = EVENT_TAXONOMY[kind];
16910
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
16911
- return {
16912
- ...t,
16913
- icon: legacyIcon(t.iconId)
16914
- };
16915
- }
16916
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
16917
17354
  var CameraPipelineConfigSchema = object({
16918
17355
  engine: PipelineEngineChoiceSchema.optional(),
16919
17356
  steps: array(PipelineStepInputSchema).readonly(),
@@ -17399,6 +17836,76 @@ method(object({
17399
17836
  auth: "admin"
17400
17837
  });
17401
17838
  /**
17839
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
17840
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
17841
+ * caps into per-camera event-kind descriptors.
17842
+ *
17843
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
17844
+ * is NOT duplicated here — every entry is derived from the single
17845
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
17846
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
17847
+ * control cap means adding one line here (and a taxonomy entry); the anti-
17848
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
17849
+ * eventful cap is missing.
17850
+ */
17851
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
17852
+ var LEGACY_ICON = {
17853
+ motion: "motion",
17854
+ audio: "audio",
17855
+ person: "person",
17856
+ vehicle: "vehicle",
17857
+ animal: "animal",
17858
+ package: "package",
17859
+ door: "door",
17860
+ pir: "pir",
17861
+ smoke: "smoke",
17862
+ water: "water",
17863
+ button: "button",
17864
+ generic: "generic",
17865
+ gas: "smoke",
17866
+ vibration: "generic",
17867
+ tamper: "generic",
17868
+ presence: "person",
17869
+ lock: "generic",
17870
+ siren: "generic",
17871
+ switch: "generic",
17872
+ doorbell: "button"
17873
+ };
17874
+ function legacyIcon(iconId) {
17875
+ return LEGACY_ICON[iconId] ?? "generic";
17876
+ }
17877
+ /**
17878
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
17879
+ * The anti-drift guard cross-checks this against the eventful caps declared
17880
+ * in `packages/types/src/capabilities/*.cap.ts`.
17881
+ */
17882
+ var CAP_TO_KIND = {
17883
+ contact: "contact",
17884
+ motion: "motion-sensor",
17885
+ smoke: "smoke",
17886
+ flood: "flood",
17887
+ gas: "gas",
17888
+ "carbon-monoxide": "carbon-monoxide",
17889
+ vibration: "vibration",
17890
+ tamper: "tamper",
17891
+ presence: "presence",
17892
+ "enum-sensor": "enum-sensor",
17893
+ "event-emitter": "device-event",
17894
+ "lock-control": "lock",
17895
+ switch: "switch",
17896
+ button: "button",
17897
+ doorbell: "doorbell"
17898
+ };
17899
+ function buildDescriptor(capName, kind) {
17900
+ const t = EVENT_TAXONOMY[kind];
17901
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
17902
+ return {
17903
+ ...t,
17904
+ icon: legacyIcon(t.iconId)
17905
+ };
17906
+ }
17907
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
17908
+ /**
17402
17909
  * server-management — per-NODE singleton capability for a node's ROOT
17403
17910
  * package lifecycle (runtime-updatable node packages).
17404
17911
  *
@@ -18853,7 +19360,28 @@ var FaceInfoSchema = object({
18853
19360
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
18854
19361
  * track produced no key frame (e.g. native/onboard source) — the UI falls
18855
19362
  * back to the inline `base64` face crop. */
18856
- keyFrameMediaKey: string().optional()
19363
+ keyFrameMediaKey: string().optional(),
19364
+ /** Winning identity-match cosine (0..1) for this face's track, when an
19365
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
19366
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
19367
+ * faces that were never auto-recognized. */
19368
+ bestMatchScore: number().optional(),
19369
+ /** Native-scale face short side (px) at recognition time, when the runner
19370
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
19371
+ * legacy rows / runners that reported no native measure. */
19372
+ nativeFaceShortSidePx: number().optional(),
19373
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
19374
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
19375
+ * but blocked only by the recognition size floor). Mutually exclusive with
19376
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
19377
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
19378
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
19379
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
19380
+ suggestedIdentityId: string().optional(),
19381
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
19382
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
19383
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
19384
+ suggestedMatchScore: number().optional()
18857
19385
  });
18858
19386
  var FaceFilterEnum = _enum([
18859
19387
  "unassigned",
@@ -20896,36 +21424,6 @@ Object.freeze({
20896
21424
  addonId: null,
20897
21425
  access: "view"
20898
21426
  },
20899
- "advancedNotifier.deleteRule": {
20900
- capName: "advanced-notifier",
20901
- capScope: "system",
20902
- addonId: null,
20903
- access: "delete"
20904
- },
20905
- "advancedNotifier.getHistory": {
20906
- capName: "advanced-notifier",
20907
- capScope: "system",
20908
- addonId: null,
20909
- access: "view"
20910
- },
20911
- "advancedNotifier.getRules": {
20912
- capName: "advanced-notifier",
20913
- capScope: "system",
20914
- addonId: null,
20915
- access: "view"
20916
- },
20917
- "advancedNotifier.testRule": {
20918
- capName: "advanced-notifier",
20919
- capScope: "system",
20920
- addonId: null,
20921
- access: "create"
20922
- },
20923
- "advancedNotifier.upsertRule": {
20924
- capName: "advanced-notifier",
20925
- capScope: "system",
20926
- addonId: null,
20927
- access: "create"
20928
- },
20929
21427
  "alarmPanel.arm": {
20930
21428
  capName: "alarm-panel",
20931
21429
  capScope: "device",
@@ -23230,6 +23728,60 @@ Object.freeze({
23230
23728
  addonId: null,
23231
23729
  access: "create"
23232
23730
  },
23731
+ "notificationRules.createRule": {
23732
+ capName: "notification-rules",
23733
+ capScope: "system",
23734
+ addonId: null,
23735
+ access: "create"
23736
+ },
23737
+ "notificationRules.deleteRule": {
23738
+ capName: "notification-rules",
23739
+ capScope: "system",
23740
+ addonId: null,
23741
+ access: "delete"
23742
+ },
23743
+ "notificationRules.getConditionCatalog": {
23744
+ capName: "notification-rules",
23745
+ capScope: "system",
23746
+ addonId: null,
23747
+ access: "view"
23748
+ },
23749
+ "notificationRules.getHistory": {
23750
+ capName: "notification-rules",
23751
+ capScope: "system",
23752
+ addonId: null,
23753
+ access: "view"
23754
+ },
23755
+ "notificationRules.getRule": {
23756
+ capName: "notification-rules",
23757
+ capScope: "system",
23758
+ addonId: null,
23759
+ access: "view"
23760
+ },
23761
+ "notificationRules.listRules": {
23762
+ capName: "notification-rules",
23763
+ capScope: "system",
23764
+ addonId: null,
23765
+ access: "view"
23766
+ },
23767
+ "notificationRules.setRuleEnabled": {
23768
+ capName: "notification-rules",
23769
+ capScope: "system",
23770
+ addonId: null,
23771
+ access: "create"
23772
+ },
23773
+ "notificationRules.testRule": {
23774
+ capName: "notification-rules",
23775
+ capScope: "system",
23776
+ addonId: null,
23777
+ access: "create"
23778
+ },
23779
+ "notificationRules.updateRule": {
23780
+ capName: "notification-rules",
23781
+ capScope: "system",
23782
+ addonId: null,
23783
+ access: "create"
23784
+ },
23233
23785
  "notifier.cancel": {
23234
23786
  capName: "notifier",
23235
23787
  capScope: "device",