@camstack/addon-provider-hikvision 1.2.5 → 1.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1391 -861
  2. package/dist/addon.mjs +1391 -861
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -7,7 +7,7 @@ import { networkInterfaces } from "node:os";
7
7
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
8
8
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
9
9
  //#endregion
10
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
10
+ //#region ../types/dist/event-category-BLcNejAE.mjs
11
11
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
12
12
  EventCategory["SystemBoot"] = "system.boot";
13
13
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -157,9 +157,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
157
157
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
158
158
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
159
159
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
160
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
161
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
162
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
163
160
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
164
161
  * progress bar the client reconciles via `recordingExport.getExport`. */
165
162
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6824,7 +6821,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6824
6821
  patch: record(string(), unknown())
6825
6822
  }), object({ success: literal(true) });
6826
6823
  object({ deviceId: number() }), unknown().nullable();
6827
- /** Shorthand to define a method schema */
6828
6824
  function method(input, output, options) {
6829
6825
  return {
6830
6826
  input,
@@ -6832,6 +6828,7 @@ function method(input, output, options) {
6832
6828
  kind: options?.kind ?? "query",
6833
6829
  auth: options?.auth ?? "protected",
6834
6830
  ...options?.access !== void 0 ? { access: options.access } : {},
6831
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6835
6832
  timeoutMs: options?.timeoutMs
6836
6833
  };
6837
6834
  }
@@ -8364,6 +8361,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8364
8361
  /** The complete taxonomy dictionary, keyed by kind. */
8365
8362
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8366
8363
  /**
8364
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8365
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8366
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8367
+ * taxonomy surface (timeline, filters, event page).
8368
+ *
8369
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8370
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8371
+ * for the `classes` / `classesExclude` conditions.
8372
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8373
+ * the same class picker, grouped under an Audio header.
8374
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8375
+ * lock / …) for the `sensorKinds` device-event condition.
8376
+ *
8377
+ * Each entry carries `parentKind` so the client can group video subs under
8378
+ * their macro and sensor/control kinds under their category. This surface is
8379
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8380
+ * method, no codegen — so it ships train-free with an addon deploy.
8381
+ */
8382
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8383
+ var NcTaxonomyEntrySchema = object({
8384
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8385
+ kind: string(),
8386
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8387
+ label: string(),
8388
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8389
+ parentKind: string().nullable()
8390
+ });
8391
+ object({
8392
+ videoClasses: array(NcTaxonomyEntrySchema),
8393
+ audioKinds: array(NcTaxonomyEntrySchema),
8394
+ labels: array(NcTaxonomyEntrySchema)
8395
+ });
8396
+ function toEntry(kind, label, parentKind) {
8397
+ return {
8398
+ kind,
8399
+ label,
8400
+ parentKind
8401
+ };
8402
+ }
8403
+ /**
8404
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8405
+ * (macros before their subs), which the client relies on for stable grouping.
8406
+ */
8407
+ function buildNcTaxonomy() {
8408
+ const all = Object.values(EVENT_TAXONOMY);
8409
+ return {
8410
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8411
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8412
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8413
+ };
8414
+ }
8415
+ Object.freeze(buildNcTaxonomy());
8416
+ /**
8367
8417
  * Error types for the safe expression engine. Two distinct classes so callers
8368
8418
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8369
8419
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -12454,6 +12504,22 @@ var CameraMetricsSchema = object({
12454
12504
  ])
12455
12505
  });
12456
12506
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
12507
+ /**
12508
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
12509
+ * within the frame, so the executor can re-cut a leaf child ROI at native
12510
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
12511
+ */
12512
+ var NativeCropRefSchema = object({
12513
+ /** Handle keying the retained native surface (node-pinned to its owner). */
12514
+ handle: FrameHandleSchema,
12515
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
12516
+ cropFrameSpace: object({
12517
+ x: number(),
12518
+ y: number(),
12519
+ w: number(),
12520
+ h: number()
12521
+ })
12522
+ });
12457
12523
  var ModelFormatSchema$1 = _enum([
12458
12524
  "onnx",
12459
12525
  "coreml",
@@ -12729,7 +12795,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
12729
12795
  * Omitted ⇒ the runner's default device (current single-engine
12730
12796
  * behaviour). Selects WHICH device pool of the node runs the call.
12731
12797
  */
12732
- deviceKey: string().optional()
12798
+ deviceKey: string().optional(),
12799
+ /**
12800
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
12801
+ * when the parent crop was resolved from the frame's retained NATIVE
12802
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
12803
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
12804
+ * resolution from that surface — the SAME quality path faces already
12805
+ * had — instead of the downscaled parent tile. `handle` keys the native
12806
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
12807
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
12808
+ * the executor's crop-normalized child ROI back into frame-normalized
12809
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
12810
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
12811
+ * (today's behaviour on the fallback path).
12812
+ */
12813
+ nativeCropRef: NativeCropRefSchema.optional()
12733
12814
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
12734
12815
  engine: PipelineEngineChoiceSchema.optional(),
12735
12816
  steps: array(PipelineStepInputSchema).min(1),
@@ -12978,7 +13059,11 @@ var DetailResultSchema = object({
12978
13059
  bbox: NativeCropBboxSchema.optional(),
12979
13060
  embedding: string().optional(),
12980
13061
  label: string().optional(),
12981
- alignedCropJpeg: string().optional()
13062
+ alignedCropJpeg: string().optional(),
13063
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
13064
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
13065
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
13066
+ nativeFaceShortSidePx: number().optional()
12982
13067
  });
12983
13068
  /**
12984
13069
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -16774,94 +16859,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
16774
16859
  bundleUrl: string()
16775
16860
  });
16776
16861
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
16777
- var NotificationRuleConditionsSchema = object({
16778
- deviceIds: array(number()).readonly().optional(),
16779
- classNames: array(string()).readonly().optional(),
16780
- zoneIds: array(string()).readonly().optional(),
16781
- minConfidence: number().optional(),
16782
- source: _enum([
16783
- "pipeline",
16784
- "onboard",
16785
- "any"
16786
- ]).optional(),
16787
- schedule: object({
16788
- days: array(number()).readonly(),
16789
- startHour: number(),
16790
- endHour: number()
16791
- }).optional(),
16792
- cooldownSeconds: number().optional(),
16793
- minDwellSeconds: number().optional(),
16794
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
16795
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
16796
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
16797
- eventTypeTokens: array(string()).readonly().optional(),
16798
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
16799
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
16800
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
16801
- clipDescription: object({
16802
- text: string().min(1),
16803
- minSimilarity: number().min(0).max(1)
16804
- }).optional(),
16805
- /** Match events whose recognized-entity label (face identity name or plate
16806
- * vehicle name, propagated onto `event.data.label`) is one of these values.
16807
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
16808
- * vehicle/person> is seen". */
16809
- labels: array(string()).readonly().optional()
16810
- });
16811
- var NotificationRuleTemplateSchema = object({
16812
- title: string(),
16813
- body: string(),
16814
- imageMode: _enum([
16815
- "crop",
16816
- "annotated",
16817
- "full",
16818
- "none"
16819
- ])
16820
- });
16821
- var NotificationRuleSchema = object({
16822
- id: string(),
16823
- name: string(),
16824
- enabled: boolean(),
16825
- eventTypes: array(string()).readonly(),
16826
- conditions: NotificationRuleConditionsSchema,
16827
- outputs: array(string()).readonly(),
16828
- template: NotificationRuleTemplateSchema.optional(),
16829
- priority: _enum([
16830
- "low",
16831
- "normal",
16832
- "high",
16833
- "critical"
16834
- ])
16835
- });
16836
- var NotificationTestResultSchema = object({
16837
- ruleId: string(),
16838
- eventId: string(),
16839
- timestamp: number(),
16840
- wouldFire: boolean(),
16841
- reason: string().optional()
16842
- });
16843
- var NotificationHistoryEntrySchema = object({
16844
- id: string(),
16845
- ruleId: string(),
16846
- ruleName: string(),
16847
- eventId: string(),
16848
- timestamp: number(),
16849
- outputs: array(string()).readonly(),
16850
- success: boolean(),
16851
- error: string().optional(),
16852
- deviceId: number().optional()
16853
- });
16854
- var NotificationHistoryFilterSchema = object({
16855
- ruleId: string().optional(),
16856
- deviceId: number().optional(),
16857
- from: number().optional(),
16858
- to: number().optional(),
16859
- limit: number().optional()
16860
- });
16861
- 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({
16862
- ruleId: string(),
16863
- lookbackMinutes: number()
16864
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
16865
16862
  /**
16866
16863
  * Alerts capability — collection-based internal alert system.
16867
16864
  *
@@ -17048,89 +17045,6 @@ method(object({
17048
17045
  password: string()
17049
17046
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
17050
17047
  /**
17051
- * `login-method` — collection cap through which auth addons contribute
17052
- * their pre-auth login surfaces to the login page. This is the SINGLE,
17053
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
17054
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
17055
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
17056
- * procedure aggregates them for the unauthenticated login page.
17057
- *
17058
- * A contribution is a discriminated union on `kind`:
17059
- *
17060
- * - `redirect` — a declarative button. The login page renders a generic
17061
- * button that navigates to `startUrl` (an addon-owned HTTP route).
17062
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
17063
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
17064
- * login page needs NO change.
17065
- *
17066
- * - `widget` — a Module-Federation widget the login page mounts (via
17067
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
17068
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
17069
- * mechanism kept for future use; no shipped addon uses it on the login
17070
- * page (the passkey ceremony below runs natively in the shell instead).
17071
- *
17072
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
17073
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
17074
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
17075
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
17076
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
17077
- * fetching any remote code pre-auth. Contribution stays unconditional —
17078
- * enrollment state is never leaked pre-auth; visibility is a shell
17079
- * decision.
17080
- *
17081
- * Every contribution carries a `stage`:
17082
- * - `primary` — shown on the first credentials screen (OIDC /
17083
- * magic-link buttons; a future usernameless passkey).
17084
- * - `second-factor` — shown AFTER the password leg, gated on the
17085
- * returned `factors` (passkey-as-2FA today).
17086
- *
17087
- * `mount: skip` — the cap is read server-side by the core auth router
17088
- * (`registry.getCollection('login-method')`), never mounted as its own
17089
- * tRPC router.
17090
- */
17091
- /** When a login method renders in the two-phase login flow. */
17092
- var LoginStageEnum = _enum(["primary", "second-factor"]);
17093
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
17094
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
17095
- object({
17096
- kind: literal("redirect"),
17097
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
17098
- id: string(),
17099
- /** Operator-facing button label. */
17100
- label: string(),
17101
- /** lucide-react icon name. */
17102
- icon: string().optional(),
17103
- /** Addon-owned HTTP route the button navigates to (GET). */
17104
- startUrl: string(),
17105
- stage: LoginStageEnum
17106
- }),
17107
- object({
17108
- kind: literal("widget"),
17109
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
17110
- id: string(),
17111
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
17112
- addonId: string(),
17113
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
17114
- bundle: string(),
17115
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
17116
- remote: WidgetRemoteSchema,
17117
- stage: LoginStageEnum
17118
- }),
17119
- object({
17120
- kind: literal("passkey"),
17121
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
17122
- id: string(),
17123
- /** Operator-facing button label. */
17124
- label: string(),
17125
- stage: LoginStageEnum,
17126
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
17127
- rpId: string(),
17128
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
17129
- origin: string().nullable()
17130
- })
17131
- ]);
17132
- method(_void(), array(LoginMethodContributionSchema).readonly());
17133
- /**
17134
17048
  * Orchestrator-side destination metadata. The orchestrator computes
17135
17049
  * `id = <addonId>:<subId>` from its provider lookup so consumers
17136
17050
  * (admin UI, restore flow) see one canonical key.
@@ -18486,245 +18400,620 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
18486
18400
  kind: "mutation",
18487
18401
  auth: "admin"
18488
18402
  });
18489
- var LogLevelSchema = _enum([
18490
- "debug",
18491
- "info",
18492
- "warn",
18493
- "error"
18403
+ /**
18404
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18405
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18406
+ * caps stay wire-compatible without a circular cap→cap import.
18407
+ *
18408
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
18409
+ * every transport tier structurally, and failed calls still write usage rows.
18410
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18411
+ */
18412
+ var LlmUsageSchema = object({
18413
+ inputTokens: number(),
18414
+ outputTokens: number()
18415
+ });
18416
+ var LlmErrorCodeSchema = _enum([
18417
+ "timeout",
18418
+ "rate-limited",
18419
+ "auth",
18420
+ "refusal",
18421
+ "bad-request",
18422
+ "unavailable",
18423
+ "no-profile",
18424
+ "budget-exceeded",
18425
+ "adapter-error"
18494
18426
  ]);
18495
- var LogEntrySchema = object({
18496
- timestamp: date(),
18497
- level: LogLevelSchema,
18498
- scope: array(string()),
18427
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18428
+ ok: literal(true),
18429
+ text: string(),
18430
+ model: string(),
18431
+ usage: LlmUsageSchema,
18432
+ truncated: boolean(),
18433
+ latencyMs: number()
18434
+ }), object({
18435
+ ok: literal(false),
18436
+ code: LlmErrorCodeSchema,
18499
18437
  message: string(),
18500
- meta: record(string(), unknown()).optional(),
18501
- tags: record(string(), string()).optional()
18502
- });
18503
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18504
- scope: array(string()).optional(),
18505
- level: LogLevelSchema.optional(),
18506
- since: date().optional(),
18507
- until: date().optional(),
18508
- limit: number().optional(),
18509
- tags: record(string(), string()).optional()
18510
- }), array(LogEntrySchema).readonly());
18511
- var CpuBreakdownSchema = object({
18512
- total: number(),
18513
- user: number(),
18514
- system: number(),
18515
- irq: number(),
18516
- nice: number(),
18517
- loadAvg: tuple([
18518
- number(),
18519
- number(),
18520
- number()
18521
- ]),
18522
- cores: number()
18438
+ retryAfterMs: number().optional()
18439
+ })]);
18440
+ /**
18441
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18442
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18443
+ * notification-output.cap.ts:27-31 precedents).
18444
+ */
18445
+ var LlmImageSchema = object({
18446
+ bytes: _instanceof(Uint8Array),
18447
+ mimeType: string()
18523
18448
  });
18524
- var MemoryInfoSchema = object({
18525
- percent: number(),
18526
- totalBytes: number(),
18527
- usedBytes: number(),
18528
- availableBytes: number(),
18529
- swapUsedBytes: number(),
18530
- swapTotalBytes: number()
18449
+ var LlmGenerateBaseInputSchema = object({
18450
+ /** Collection routing (the notification-output posture). */
18451
+ addonId: string().optional(),
18452
+ /** Explicit profile; else the resolution chain (spec §3). */
18453
+ profileId: string().optional(),
18454
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18455
+ consumer: string(),
18456
+ system: string().optional(),
18457
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
18458
+ prompt: string(),
18459
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18460
+ jsonSchema: record(string(), unknown()).optional(),
18461
+ /** Per-call override of the profile default. */
18462
+ maxTokens: number().int().positive().optional(),
18463
+ temperature: number().optional()
18531
18464
  });
18532
- var DiskIoSnapshotSchema = object({
18533
- readBytes: number(),
18534
- writeBytes: number(),
18535
- readOps: number(),
18536
- writeOps: number(),
18537
- timestampMs: number()
18538
- });
18539
- var NetworkIoSnapshotSchema = object({
18540
- rxBytes: number(),
18541
- txBytes: number(),
18542
- rxPackets: number(),
18543
- txPackets: number(),
18544
- rxErrors: number(),
18545
- txErrors: number(),
18546
- timestampMs: number()
18547
- });
18548
- var MetricsGpuInfoSchema = object({
18549
- utilization: number(),
18550
- model: string(),
18551
- memoryUsedBytes: number(),
18552
- memoryTotalBytes: number(),
18553
- temperature: number().nullable()
18554
- });
18555
- var ProcessResourceInfoSchema = object({
18556
- openFds: number(),
18557
- threadCount: number(),
18558
- activeHandles: number(),
18559
- activeRequests: number()
18560
- });
18561
- var PressureAvgsSchema = object({
18562
- avg10: number(),
18563
- avg60: number(),
18564
- avg300: number()
18565
- });
18566
- var PressureInfoSchema = object({
18567
- some: PressureAvgsSchema,
18568
- full: PressureAvgsSchema.nullable()
18569
- });
18570
- var SystemResourceSnapshotSchema = object({
18571
- cpu: CpuBreakdownSchema,
18572
- memory: MemoryInfoSchema,
18573
- gpu: MetricsGpuInfoSchema.nullable(),
18574
- network: NetworkIoSnapshotSchema,
18575
- disk: DiskIoSnapshotSchema,
18576
- pressure: object({
18577
- cpu: PressureInfoSchema.nullable(),
18578
- memory: PressureInfoSchema.nullable(),
18579
- io: PressureInfoSchema.nullable()
18465
+ /**
18466
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18467
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18468
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18469
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18470
+ * this only through the `llm` cap's methods.
18471
+ *
18472
+ * One running llama-server child per node in v1 (models are RAM-heavy).
18473
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18474
+ * watchdog — operator decision #3).
18475
+ */
18476
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
18477
+ object({
18478
+ kind: literal("catalog"),
18479
+ catalogId: string()
18580
18480
  }),
18581
- process: ProcessResourceInfoSchema,
18582
- cpuTemperature: number().nullable(),
18583
- timestampMs: number()
18584
- });
18585
- var DiskSpaceInfoSchema = object({
18586
- path: string(),
18587
- totalBytes: number(),
18588
- usedBytes: number(),
18589
- availableBytes: number(),
18590
- percent: number()
18591
- });
18592
- var PidResourceStatsSchema = object({
18593
- pid: number(),
18594
- cpu: number(),
18595
- memory: number(),
18596
- /**
18597
- * Private (anonymous) resident bytes — the per-process V8 heap + native
18598
- * allocations NOT shared with other processes (Linux RssAnon). This is the
18599
- * "real" per-runner cost; summing it across runners is meaningful, unlike
18600
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
18601
- * Undefined where /proc is unavailable (e.g. macOS).
18602
- */
18603
- privateBytes: number().optional(),
18604
- /**
18605
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18606
- * code shared copy-on-write across runners. Undefined on macOS.
18607
- */
18608
- sharedBytes: number().optional()
18481
+ object({
18482
+ kind: literal("url"),
18483
+ url: string(),
18484
+ sha256: string().optional()
18485
+ }),
18486
+ object({
18487
+ kind: literal("path"),
18488
+ path: string()
18489
+ })
18490
+ ]);
18491
+ var ManagedRuntimeConfigSchema = object({
18492
+ /** WHERE the runtime lives — hub or any agent. */
18493
+ nodeId: string(),
18494
+ /** Closed for v1; 'ollama' is a v2 candidate. */
18495
+ engine: _enum(["llama-cpp"]),
18496
+ model: ManagedModelRefSchema,
18497
+ contextSize: number().int().default(4096),
18498
+ /** 0 = CPU-only. */
18499
+ gpuLayers: number().int().default(0),
18500
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18501
+ threads: number().int().optional(),
18502
+ /** Concurrent slots. */
18503
+ parallel: number().int().default(1),
18504
+ /** Else lazy: first generate boots it. */
18505
+ autoStart: boolean().default(false),
18506
+ /** 0 = never; frees RAM after quiet periods. */
18507
+ idleStopMinutes: number().int().default(30)
18609
18508
  });
18610
- var AddonInstanceSchema = object({
18611
- addonId: string(),
18509
+ var LlmRuntimeStatusSchema = object({
18510
+ /** Status is ALWAYS node-qualified. */
18612
18511
  nodeId: string(),
18613
- role: _enum(["hub", "worker"]),
18614
- pid: number(),
18615
18512
  state: _enum([
18616
- "starting",
18617
- "running",
18618
- "stopping",
18619
18513
  "stopped",
18620
- "crashed"
18621
- ]),
18622
- uptimeSec: number()
18623
- });
18624
- var NodeProcessSchema = object({
18625
- pid: number(),
18626
- ppid: number(),
18627
- pgid: number(),
18628
- classification: _enum([
18629
- "root",
18630
- "managed",
18631
- "system",
18632
- "ghost"
18514
+ "downloading",
18515
+ "starting",
18516
+ "ready",
18517
+ "crashed",
18518
+ "failed"
18633
18519
  ]),
18634
- /** `$process` addon binding when `managed`, else null. */
18635
- addonId: string().nullable(),
18636
- /** Kernel-reported nodeId when the process is a known agent/worker. */
18637
- nodeId: string().nullable(),
18638
- /** Truncated command line. */
18639
- command: string(),
18640
- cpuPercent: number(),
18641
- memoryRssBytes: number(),
18642
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18643
- uptimeSec: number(),
18644
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18645
- orphaned: boolean()
18646
- });
18647
- var KillProcessInputSchema = object({
18648
- pid: number(),
18649
- /** Force = SIGKILL. Default is SIGTERM. */
18650
- force: boolean().optional()
18651
- });
18652
- var KillProcessResultSchema = object({
18653
- success: boolean(),
18654
- reason: string().optional(),
18655
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18656
- });
18657
- var DumpHeapSnapshotInputSchema = object({
18658
- /** The addon whose runner should dump a heap snapshot. */
18659
- addonId: string() });
18660
- var DumpHeapSnapshotResultSchema = object({
18661
- success: boolean(),
18662
- /** Path of the written .heapsnapshot inside the runner's container/host. */
18663
- path: string().optional(),
18664
- /** Process pid that was signalled. */
18665
18520
  pid: number().optional(),
18666
- reason: string().optional()
18521
+ port: number().optional(),
18522
+ modelPath: string().optional(),
18523
+ modelId: string().optional(),
18524
+ downloadProgress: number().min(0).max(1).optional(),
18525
+ lastError: string().optional(),
18526
+ crashesInWindow: number(),
18527
+ /** Child RSS (sampled best-effort). */
18528
+ memoryBytes: number().optional(),
18529
+ vramBytes: number().optional()
18667
18530
  });
18668
- var SystemMetricsSchema = object({
18669
- cpuPercent: number(),
18670
- memoryPercent: number(),
18671
- memoryUsedMB: number(),
18672
- memoryTotalMB: number(),
18673
- diskPercent: number().optional(),
18674
- temperature: number().optional(),
18675
- gpuPercent: number().optional(),
18676
- gpuMemoryPercent: number().optional()
18531
+ var LlmNodeModelSchema = object({
18532
+ file: string(),
18533
+ sizeBytes: number(),
18534
+ catalogId: string().optional(),
18535
+ installedAt: number().optional()
18677
18536
  });
18678
- 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, {
18537
+ var LlmRuntimeDiskUsageSchema = object({
18538
+ nodeId: string(),
18539
+ modelsBytes: number(),
18540
+ freeBytes: number().optional()
18541
+ });
18542
+ method(LlmGenerateBaseInputSchema.extend({
18543
+ images: array(LlmImageSchema).optional(),
18544
+ runtime: ManagedRuntimeConfigSchema,
18545
+ /** The managed profile's timeout, threaded by the hub provider. */
18546
+ timeoutMs: number().int().positive().optional()
18547
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18679
18548
  kind: "mutation",
18680
18549
  auth: "admin"
18681
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
18550
+ }), method(object({}), _void(), {
18682
18551
  kind: "mutation",
18683
18552
  auth: "admin"
18684
- });
18685
- method(object({
18686
- sourceUrl: string(),
18687
- metadata: ModelConvertMetadataSchema,
18688
- targets: array(ConvertTargetSchema).min(1).readonly(),
18689
- calibrationRef: string().optional(),
18690
- sessionId: string().optional()
18691
- }), ConvertResultSchema, {
18553
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18692
18554
  kind: "mutation",
18693
- auth: "admin",
18694
- timeoutMs: 6e5
18695
- });
18696
- method(object({
18697
- nodeId: string(),
18698
- modelId: string(),
18699
- format: _enum(MODEL_FORMATS),
18700
- entry: ModelCatalogEntrySchema
18701
- }), object({
18702
- ok: boolean(),
18703
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
18704
- sha256: string(),
18705
- bytes: number(),
18706
- /** The target node's modelsDir the artifact landed in. */
18707
- path: string()
18708
- }), {
18555
+ auth: "admin"
18556
+ }), method(object({ file: string() }), _void(), {
18709
18557
  kind: "mutation",
18710
18558
  auth: "admin"
18711
- });
18559
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18712
18560
  /**
18713
- * `mqtt-broker` — broker-registry cap.
18714
- *
18715
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
18716
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
18717
- * and (b) the connection details a consumer addon needs to spin up
18718
- * its OWN `mqtt.js` client.
18719
- *
18720
- * Why: pub/sub routing over the system event-bus loses fidelity
18721
- * (callback shape, QoS guarantees, will/retain semantics) and adds
18722
- * refcount bookkeeping that addons would rather own themselves. The
18723
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
18724
- * features anyway — give it the connection config, get out of the way.
18561
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18562
+ * methods concat-fan across providers; single-row methods route to ONE
18563
+ * provider by the `addonId` in the call input (the notification-output
18564
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18565
+ * (hub-placed); the cap stays open for future providers.
18725
18566
  *
18726
- * Consumer flow:
18727
- * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
18567
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18568
+ * `apiKey` is a password field — providers REDACT it on read and merge on
18569
+ * write; a stored key NEVER round-trips to a client.
18570
+ */
18571
+ var LlmProfileKindSchema = _enum([
18572
+ "openai-compatible",
18573
+ "openai",
18574
+ "anthropic",
18575
+ "google",
18576
+ "managed-local"
18577
+ ]);
18578
+ var LlmProfileSchema = object({
18579
+ id: string(),
18580
+ name: string(),
18581
+ kind: LlmProfileKindSchema,
18582
+ /** Stamped by the provider — keeps the fanned catalog routable. */
18583
+ addonId: string(),
18584
+ enabled: boolean(),
18585
+ /** Vendor model id, or the managed runtime's loaded model. */
18586
+ model: string(),
18587
+ /** Required for openai-compatible; override for cloud kinds. */
18588
+ baseUrl: string().optional(),
18589
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
18590
+ apiKey: string().optional(),
18591
+ supportsVision: boolean(),
18592
+ temperature: number().min(0).max(2).optional(),
18593
+ maxTokens: number().int().positive().optional(),
18594
+ timeoutMs: number().int().positive().default(6e4),
18595
+ extraHeaders: record(string(), string()).optional(),
18596
+ /** kind === 'managed-local' only (spec §4). */
18597
+ runtime: ManagedRuntimeConfigSchema.optional()
18598
+ });
18599
+ /** ConfigUISchema tree passed through untyped on the wire (the
18600
+ * notification-output `ConfigSchemaPassthrough` precedent at
18601
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
18602
+ var ConfigSchemaPassthrough$1 = unknown();
18603
+ var LlmProfileKindDescriptorSchema = object({
18604
+ kind: LlmProfileKindSchema,
18605
+ label: string(),
18606
+ icon: string(),
18607
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
18608
+ addonId: string(),
18609
+ configSchema: ConfigSchemaPassthrough$1
18610
+ });
18611
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
18612
+ var LlmDefaultSchema = object({
18613
+ selector: LlmDefaultSelectorSchema,
18614
+ profileId: string()
18615
+ });
18616
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
18617
+ var LlmUsageRollupSchema = object({
18618
+ day: string(),
18619
+ consumer: string(),
18620
+ profileId: string(),
18621
+ calls: number(),
18622
+ okCalls: number(),
18623
+ errorCalls: number(),
18624
+ inputTokens: number(),
18625
+ outputTokens: number(),
18626
+ avgLatencyMs: number()
18627
+ });
18628
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
18629
+ var ManagedModelCatalogEntrySchema = object({
18630
+ id: string(),
18631
+ label: string(),
18632
+ family: string(),
18633
+ purpose: _enum(["text", "vision"]),
18634
+ url: string(),
18635
+ sha256: string(),
18636
+ sizeBytes: number(),
18637
+ quantization: string(),
18638
+ /** Load-time guidance shown in the picker. */
18639
+ minRamBytes: number(),
18640
+ contextSizeDefault: number().int(),
18641
+ /** Vision models: companion projector file. */
18642
+ mmprojUrl: string().optional()
18643
+ });
18644
+ var LlmRuntimeNodeSchema = object({
18645
+ nodeId: string(),
18646
+ reachable: boolean(),
18647
+ status: LlmRuntimeStatusSchema.optional(),
18648
+ disk: LlmRuntimeDiskUsageSchema.optional(),
18649
+ error: string().optional()
18650
+ });
18651
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
18652
+ var ProfileRefInputSchema = object({
18653
+ addonId: string(),
18654
+ profileId: string()
18655
+ });
18656
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
18657
+ kind: "mutation",
18658
+ auth: "admin"
18659
+ }), method(ProfileRefInputSchema, _void(), {
18660
+ kind: "mutation",
18661
+ auth: "admin"
18662
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
18663
+ kind: "mutation",
18664
+ auth: "admin"
18665
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
18666
+ selector: LlmDefaultSelectorSchema,
18667
+ profileId: string().nullable()
18668
+ }), _void(), {
18669
+ kind: "mutation",
18670
+ auth: "admin"
18671
+ }), method(object({
18672
+ since: number().optional(),
18673
+ until: number().optional(),
18674
+ consumer: string().optional(),
18675
+ profileId: string().optional()
18676
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
18677
+ nodeId: string(),
18678
+ model: ManagedModelRefSchema
18679
+ }), _void(), {
18680
+ kind: "mutation",
18681
+ auth: "admin"
18682
+ }), method(object({
18683
+ nodeId: string(),
18684
+ file: string()
18685
+ }), _void(), {
18686
+ kind: "mutation",
18687
+ auth: "admin"
18688
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
18689
+ kind: "mutation",
18690
+ auth: "admin"
18691
+ }), method(ProfileRefInputSchema, _void(), {
18692
+ kind: "mutation",
18693
+ auth: "admin"
18694
+ });
18695
+ var LogLevelSchema = _enum([
18696
+ "debug",
18697
+ "info",
18698
+ "warn",
18699
+ "error"
18700
+ ]);
18701
+ var LogEntrySchema = object({
18702
+ timestamp: date(),
18703
+ level: LogLevelSchema,
18704
+ scope: array(string()),
18705
+ message: string(),
18706
+ meta: record(string(), unknown()).optional(),
18707
+ tags: record(string(), string()).optional()
18708
+ });
18709
+ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18710
+ scope: array(string()).optional(),
18711
+ level: LogLevelSchema.optional(),
18712
+ since: date().optional(),
18713
+ until: date().optional(),
18714
+ limit: number().optional(),
18715
+ tags: record(string(), string()).optional()
18716
+ }), array(LogEntrySchema).readonly());
18717
+ /**
18718
+ * `login-method` — collection cap through which auth addons contribute
18719
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
18720
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
18721
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
18722
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
18723
+ * procedure aggregates them for the unauthenticated login page.
18724
+ *
18725
+ * A contribution is a discriminated union on `kind`:
18726
+ *
18727
+ * - `redirect` — a declarative button. The login page renders a generic
18728
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
18729
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
18730
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
18731
+ * login page needs NO change.
18732
+ *
18733
+ * - `widget` — a Module-Federation widget the login page mounts (via
18734
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
18735
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
18736
+ * mechanism kept for future use; no shipped addon uses it on the login
18737
+ * page (the passkey ceremony below runs natively in the shell instead).
18738
+ *
18739
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
18740
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
18741
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
18742
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
18743
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
18744
+ * fetching any remote code pre-auth. Contribution stays unconditional —
18745
+ * enrollment state is never leaked pre-auth; visibility is a shell
18746
+ * decision.
18747
+ *
18748
+ * Every contribution carries a `stage`:
18749
+ * - `primary` — shown on the first credentials screen (OIDC /
18750
+ * magic-link buttons; a future usernameless passkey).
18751
+ * - `second-factor` — shown AFTER the password leg, gated on the
18752
+ * returned `factors` (passkey-as-2FA today).
18753
+ *
18754
+ * `mount: skip` — the cap is read server-side by the core auth router
18755
+ * (`registry.getCollection('login-method')`), never mounted as its own
18756
+ * tRPC router.
18757
+ */
18758
+ /** When a login method renders in the two-phase login flow. */
18759
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
18760
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
18761
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
18762
+ object({
18763
+ kind: literal("redirect"),
18764
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
18765
+ id: string(),
18766
+ /** Operator-facing button label. */
18767
+ label: string(),
18768
+ /** lucide-react icon name. */
18769
+ icon: string().optional(),
18770
+ /** Addon-owned HTTP route the button navigates to (GET). */
18771
+ startUrl: string(),
18772
+ stage: LoginStageEnum
18773
+ }),
18774
+ object({
18775
+ kind: literal("widget"),
18776
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
18777
+ id: string(),
18778
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
18779
+ addonId: string(),
18780
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
18781
+ bundle: string(),
18782
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
18783
+ remote: WidgetRemoteSchema,
18784
+ stage: LoginStageEnum
18785
+ }),
18786
+ object({
18787
+ kind: literal("passkey"),
18788
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
18789
+ id: string(),
18790
+ /** Operator-facing button label. */
18791
+ label: string(),
18792
+ stage: LoginStageEnum,
18793
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
18794
+ rpId: string(),
18795
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
18796
+ origin: string().nullable()
18797
+ })
18798
+ ]);
18799
+ method(_void(), array(LoginMethodContributionSchema).readonly());
18800
+ var CpuBreakdownSchema = object({
18801
+ total: number(),
18802
+ user: number(),
18803
+ system: number(),
18804
+ irq: number(),
18805
+ nice: number(),
18806
+ loadAvg: tuple([
18807
+ number(),
18808
+ number(),
18809
+ number()
18810
+ ]),
18811
+ cores: number()
18812
+ });
18813
+ var MemoryInfoSchema = object({
18814
+ percent: number(),
18815
+ totalBytes: number(),
18816
+ usedBytes: number(),
18817
+ availableBytes: number(),
18818
+ swapUsedBytes: number(),
18819
+ swapTotalBytes: number()
18820
+ });
18821
+ var DiskIoSnapshotSchema = object({
18822
+ readBytes: number(),
18823
+ writeBytes: number(),
18824
+ readOps: number(),
18825
+ writeOps: number(),
18826
+ timestampMs: number()
18827
+ });
18828
+ var NetworkIoSnapshotSchema = object({
18829
+ rxBytes: number(),
18830
+ txBytes: number(),
18831
+ rxPackets: number(),
18832
+ txPackets: number(),
18833
+ rxErrors: number(),
18834
+ txErrors: number(),
18835
+ timestampMs: number()
18836
+ });
18837
+ var MetricsGpuInfoSchema = object({
18838
+ utilization: number(),
18839
+ model: string(),
18840
+ memoryUsedBytes: number(),
18841
+ memoryTotalBytes: number(),
18842
+ temperature: number().nullable()
18843
+ });
18844
+ var ProcessResourceInfoSchema = object({
18845
+ openFds: number(),
18846
+ threadCount: number(),
18847
+ activeHandles: number(),
18848
+ activeRequests: number()
18849
+ });
18850
+ var PressureAvgsSchema = object({
18851
+ avg10: number(),
18852
+ avg60: number(),
18853
+ avg300: number()
18854
+ });
18855
+ var PressureInfoSchema = object({
18856
+ some: PressureAvgsSchema,
18857
+ full: PressureAvgsSchema.nullable()
18858
+ });
18859
+ var SystemResourceSnapshotSchema = object({
18860
+ cpu: CpuBreakdownSchema,
18861
+ memory: MemoryInfoSchema,
18862
+ gpu: MetricsGpuInfoSchema.nullable(),
18863
+ network: NetworkIoSnapshotSchema,
18864
+ disk: DiskIoSnapshotSchema,
18865
+ pressure: object({
18866
+ cpu: PressureInfoSchema.nullable(),
18867
+ memory: PressureInfoSchema.nullable(),
18868
+ io: PressureInfoSchema.nullable()
18869
+ }),
18870
+ process: ProcessResourceInfoSchema,
18871
+ cpuTemperature: number().nullable(),
18872
+ timestampMs: number()
18873
+ });
18874
+ var DiskSpaceInfoSchema = object({
18875
+ path: string(),
18876
+ totalBytes: number(),
18877
+ usedBytes: number(),
18878
+ availableBytes: number(),
18879
+ percent: number()
18880
+ });
18881
+ var PidResourceStatsSchema = object({
18882
+ pid: number(),
18883
+ cpu: number(),
18884
+ memory: number(),
18885
+ /**
18886
+ * Private (anonymous) resident bytes — the per-process V8 heap + native
18887
+ * allocations NOT shared with other processes (Linux RssAnon). This is the
18888
+ * "real" per-runner cost; summing it across runners is meaningful, unlike
18889
+ * `memory` (RSS), which double-counts the shared mmap'd framework code.
18890
+ * Undefined where /proc is unavailable (e.g. macOS).
18891
+ */
18892
+ privateBytes: number().optional(),
18893
+ /**
18894
+ * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18895
+ * code shared copy-on-write across runners. Undefined on macOS.
18896
+ */
18897
+ sharedBytes: number().optional()
18898
+ });
18899
+ var AddonInstanceSchema = object({
18900
+ addonId: string(),
18901
+ nodeId: string(),
18902
+ role: _enum(["hub", "worker"]),
18903
+ pid: number(),
18904
+ state: _enum([
18905
+ "starting",
18906
+ "running",
18907
+ "stopping",
18908
+ "stopped",
18909
+ "crashed"
18910
+ ]),
18911
+ uptimeSec: number()
18912
+ });
18913
+ var NodeProcessSchema = object({
18914
+ pid: number(),
18915
+ ppid: number(),
18916
+ pgid: number(),
18917
+ classification: _enum([
18918
+ "root",
18919
+ "managed",
18920
+ "system",
18921
+ "ghost"
18922
+ ]),
18923
+ /** `$process` addon binding when `managed`, else null. */
18924
+ addonId: string().nullable(),
18925
+ /** Kernel-reported nodeId when the process is a known agent/worker. */
18926
+ nodeId: string().nullable(),
18927
+ /** Truncated command line. */
18928
+ command: string(),
18929
+ cpuPercent: number(),
18930
+ memoryRssBytes: number(),
18931
+ /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18932
+ uptimeSec: number(),
18933
+ /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18934
+ orphaned: boolean()
18935
+ });
18936
+ var KillProcessInputSchema = object({
18937
+ pid: number(),
18938
+ /** Force = SIGKILL. Default is SIGTERM. */
18939
+ force: boolean().optional()
18940
+ });
18941
+ var KillProcessResultSchema = object({
18942
+ success: boolean(),
18943
+ reason: string().optional(),
18944
+ signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18945
+ });
18946
+ var DumpHeapSnapshotInputSchema = object({
18947
+ /** The addon whose runner should dump a heap snapshot. */
18948
+ addonId: string() });
18949
+ var DumpHeapSnapshotResultSchema = object({
18950
+ success: boolean(),
18951
+ /** Path of the written .heapsnapshot inside the runner's container/host. */
18952
+ path: string().optional(),
18953
+ /** Process pid that was signalled. */
18954
+ pid: number().optional(),
18955
+ reason: string().optional()
18956
+ });
18957
+ var SystemMetricsSchema = object({
18958
+ cpuPercent: number(),
18959
+ memoryPercent: number(),
18960
+ memoryUsedMB: number(),
18961
+ memoryTotalMB: number(),
18962
+ diskPercent: number().optional(),
18963
+ temperature: number().optional(),
18964
+ gpuPercent: number().optional(),
18965
+ gpuMemoryPercent: number().optional()
18966
+ });
18967
+ 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, {
18968
+ kind: "mutation",
18969
+ auth: "admin"
18970
+ }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
18971
+ kind: "mutation",
18972
+ auth: "admin"
18973
+ });
18974
+ method(object({
18975
+ sourceUrl: string(),
18976
+ metadata: ModelConvertMetadataSchema,
18977
+ targets: array(ConvertTargetSchema).min(1).readonly(),
18978
+ calibrationRef: string().optional(),
18979
+ sessionId: string().optional()
18980
+ }), ConvertResultSchema, {
18981
+ kind: "mutation",
18982
+ auth: "admin",
18983
+ timeoutMs: 6e5
18984
+ });
18985
+ method(object({
18986
+ nodeId: string(),
18987
+ modelId: string(),
18988
+ format: _enum(MODEL_FORMATS),
18989
+ entry: ModelCatalogEntrySchema
18990
+ }), object({
18991
+ ok: boolean(),
18992
+ /** sha256 of the staged tarball (empty for a hub-local no-op). */
18993
+ sha256: string(),
18994
+ bytes: number(),
18995
+ /** The target node's modelsDir the artifact landed in. */
18996
+ path: string()
18997
+ }), {
18998
+ kind: "mutation",
18999
+ auth: "admin"
19000
+ });
19001
+ /**
19002
+ * `mqtt-broker` — broker-registry cap.
19003
+ *
19004
+ * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
19005
+ * MQTT brokers (external + optionally an embedded `aedes`-backed one)
19006
+ * and (b) the connection details a consumer addon needs to spin up
19007
+ * its OWN `mqtt.js` client.
19008
+ *
19009
+ * Why: pub/sub routing over the system event-bus loses fidelity
19010
+ * (callback shape, QoS guarantees, will/retain semantics) and adds
19011
+ * refcount bookkeeping that addons would rather own themselves. The
19012
+ * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
19013
+ * features anyway — give it the connection config, get out of the way.
19014
+ *
19015
+ * Consumer flow:
19016
+ * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
18728
19017
  * const client = mqtt.connect(cfg.url, { username: cfg.username, … })
18729
19018
  * client.subscribe('zigbee2mqtt/+')
18730
19019
  *
@@ -18938,399 +19227,595 @@ var NotificationSchema = object({
18938
19227
  metadata: record(string(), unknown()).optional()
18939
19228
  });
18940
19229
  /** One declared native severity/priority level for a kind. */
18941
- var TargetKindLevelSchema = object({
18942
- id: string(),
18943
- label: string(),
18944
- /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
18945
- ordinal: number().int().min(1).max(5).nullable(),
18946
- flags: object({
18947
- critical: boolean().optional(),
18948
- silent: boolean().optional(),
18949
- noPush: boolean().optional()
18950
- }).optional(),
18951
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
18952
- requires: array(string()).optional(),
18953
- description: string().optional()
18954
- });
18955
- /** The full capability block consulted before dispatch. */
18956
- var TargetKindCapsSchema = object({
18957
- attachments: object({
18958
- mediaTypes: array(AttachmentMediaTypeSchema),
18959
- mode: _enum([
18960
- "url",
18961
- "bytes",
18962
- "both"
18963
- ]),
18964
- max: number().int().nonnegative(),
18965
- maxBytes: number().int().positive().optional()
18966
- }),
18967
- /** Max action buttons (0 = none). */
18968
- actions: number().int().nonnegative(),
18969
- levels: array(TargetKindLevelSchema),
18970
- format: array(NotificationFormatSchema),
18971
- clickUrl: boolean(),
18972
- sound: boolean(),
18973
- ttl: boolean(),
18974
- bodyMaxLen: number().int().positive()
18975
- });
18976
- /**
18977
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
18978
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
18979
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
18980
- * the union is large and not meant for runtime validation here; the exported
18981
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
18982
- */
18983
- var ConfigSchemaPassthrough$1 = unknown();
18984
- var TargetKindSchema = object({
18985
- kind: string(),
18986
- label: string(),
18987
- icon: string(),
18988
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
18989
- addonId: string(),
18990
- configSchema: ConfigSchemaPassthrough$1,
18991
- supportsDiscovery: boolean(),
18992
- caps: TargetKindCapsSchema
18993
- });
18994
- /**
18995
- * A persisted target. `config` holds secrets; providers REDACT secret fields
18996
- * (return a presence marker only) when serving `listTargets` — never
18997
- * round-trip a stored secret to the UI.
18998
- */
18999
- var TargetSchema = object({
19000
- id: string(),
19001
- name: string(),
19002
- kind: string(),
19003
- addonId: string(),
19004
- enabled: boolean(),
19005
- config: record(string(), unknown())
19006
- });
19007
- /** A discovery-surfaced candidate (config is partial + non-secret). */
19008
- var DiscoveredTargetSchema = object({
19009
- kind: string(),
19010
- suggestedName: string(),
19011
- config: record(string(), unknown())
19012
- });
19013
- /** The degrade engine's report — what was resolved / dropped / degraded. */
19014
- var RenderedAsSchema = object({
19015
- level: string(),
19016
- format: NotificationFormatSchema,
19017
- attachmentsSent: number().int().nonnegative(),
19018
- actionsSent: number().int().nonnegative(),
19019
- truncated: boolean(),
19020
- dropped: array(string())
19021
- });
19022
- var SendResultSchema = object({
19023
- success: boolean(),
19024
- error: string().optional(),
19025
- renderedAs: RenderedAsSchema.optional()
19026
- });
19027
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
19028
- var TestResultSchema = SendResultSchema;
19029
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
19030
- kind: string(),
19031
- config: record(string(), unknown()).optional()
19032
- }), array(DiscoveredTargetSchema)), method(object({
19033
- targetId: string(),
19034
- notification: NotificationSchema
19035
- }), SendResultSchema, { kind: "mutation" }), method(object({
19036
- targetId: string(),
19037
- sample: NotificationSchema.optional()
19038
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
19039
- targetId: string(),
19040
- enabled: boolean()
19041
- }), _void(), { kind: "mutation" });
19042
- /**
19043
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
19044
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
19045
- * caps stay wire-compatible without a circular cap→cap import.
19046
- *
19047
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
19048
- * every transport tier structurally, and failed calls still write usage rows.
19049
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
19050
- */
19051
- var LlmUsageSchema = object({
19052
- inputTokens: number(),
19053
- outputTokens: number()
19054
- });
19055
- var LlmErrorCodeSchema = _enum([
19056
- "timeout",
19057
- "rate-limited",
19058
- "auth",
19059
- "refusal",
19060
- "bad-request",
19061
- "unavailable",
19062
- "no-profile",
19063
- "budget-exceeded",
19064
- "adapter-error"
19065
- ]);
19066
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
19067
- ok: literal(true),
19068
- text: string(),
19069
- model: string(),
19070
- usage: LlmUsageSchema,
19071
- truncated: boolean(),
19072
- latencyMs: number()
19073
- }), object({
19074
- ok: literal(false),
19075
- code: LlmErrorCodeSchema,
19076
- message: string(),
19077
- retryAfterMs: number().optional()
19078
- })]);
19079
- /**
19080
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
19081
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
19082
- * notification-output.cap.ts:27-31 precedents).
19083
- */
19084
- var LlmImageSchema = object({
19085
- bytes: _instanceof(Uint8Array),
19086
- mimeType: string()
19087
- });
19088
- var LlmGenerateBaseInputSchema = object({
19089
- /** Collection routing (the notification-output posture). */
19090
- addonId: string().optional(),
19091
- /** Explicit profile; else the resolution chain (spec §3). */
19092
- profileId: string().optional(),
19093
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
19094
- consumer: string(),
19095
- system: string().optional(),
19096
- /** v1: single-turn. `messages[]` is a v2 additive field. */
19097
- prompt: string(),
19098
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
19099
- jsonSchema: record(string(), unknown()).optional(),
19100
- /** Per-call override of the profile default. */
19101
- maxTokens: number().int().positive().optional(),
19102
- temperature: number().optional()
19103
- });
19104
- /**
19105
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
19106
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
19107
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
19108
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
19109
- * this only through the `llm` cap's methods.
19110
- *
19111
- * One running llama-server child per node in v1 (models are RAM-heavy).
19112
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
19113
- * watchdog — operator decision #3).
19114
- */
19115
- var ManagedModelRefSchema = discriminatedUnion("kind", [
19116
- object({
19117
- kind: literal("catalog"),
19118
- catalogId: string()
19119
- }),
19120
- object({
19121
- kind: literal("url"),
19122
- url: string(),
19123
- sha256: string().optional()
19124
- }),
19125
- object({
19126
- kind: literal("path"),
19127
- path: string()
19128
- })
19129
- ]);
19130
- var ManagedRuntimeConfigSchema = object({
19131
- /** WHERE the runtime lives — hub or any agent. */
19132
- nodeId: string(),
19133
- /** Closed for v1; 'ollama' is a v2 candidate. */
19134
- engine: _enum(["llama-cpp"]),
19135
- model: ManagedModelRefSchema,
19136
- contextSize: number().int().default(4096),
19137
- /** 0 = CPU-only. */
19138
- gpuLayers: number().int().default(0),
19139
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
19140
- threads: number().int().optional(),
19141
- /** Concurrent slots. */
19142
- parallel: number().int().default(1),
19143
- /** Else lazy: first generate boots it. */
19144
- autoStart: boolean().default(false),
19145
- /** 0 = never; frees RAM after quiet periods. */
19146
- idleStopMinutes: number().int().default(30)
19147
- });
19148
- var LlmRuntimeStatusSchema = object({
19149
- /** Status is ALWAYS node-qualified. */
19150
- nodeId: string(),
19151
- state: _enum([
19152
- "stopped",
19153
- "downloading",
19154
- "starting",
19155
- "ready",
19156
- "crashed",
19157
- "failed"
19158
- ]),
19159
- pid: number().optional(),
19160
- port: number().optional(),
19161
- modelPath: string().optional(),
19162
- modelId: string().optional(),
19163
- downloadProgress: number().min(0).max(1).optional(),
19164
- lastError: string().optional(),
19165
- crashesInWindow: number(),
19166
- /** Child RSS (sampled best-effort). */
19167
- memoryBytes: number().optional(),
19168
- vramBytes: number().optional()
19230
+ var TargetKindLevelSchema = object({
19231
+ id: string(),
19232
+ label: string(),
19233
+ /** Which canonical priority (1..5) this level maps to. `null` = qualitative-only. */
19234
+ ordinal: number().int().min(1).max(5).nullable(),
19235
+ flags: object({
19236
+ critical: boolean().optional(),
19237
+ silent: boolean().optional(),
19238
+ noPush: boolean().optional()
19239
+ }).optional(),
19240
+ /** e.g. Pushover `emergency` requires `retry` / `expire`. */
19241
+ requires: array(string()).optional(),
19242
+ description: string().optional()
19169
19243
  });
19170
- var LlmNodeModelSchema = object({
19171
- file: string(),
19172
- sizeBytes: number(),
19173
- catalogId: string().optional(),
19174
- installedAt: number().optional()
19244
+ /** The full capability block consulted before dispatch. */
19245
+ var TargetKindCapsSchema = object({
19246
+ attachments: object({
19247
+ mediaTypes: array(AttachmentMediaTypeSchema),
19248
+ mode: _enum([
19249
+ "url",
19250
+ "bytes",
19251
+ "both"
19252
+ ]),
19253
+ max: number().int().nonnegative(),
19254
+ maxBytes: number().int().positive().optional()
19255
+ }),
19256
+ /** Max action buttons (0 = none). */
19257
+ actions: number().int().nonnegative(),
19258
+ levels: array(TargetKindLevelSchema),
19259
+ format: array(NotificationFormatSchema),
19260
+ clickUrl: boolean(),
19261
+ sound: boolean(),
19262
+ ttl: boolean(),
19263
+ bodyMaxLen: number().int().positive()
19175
19264
  });
19176
- var LlmRuntimeDiskUsageSchema = object({
19177
- nodeId: string(),
19178
- modelsBytes: number(),
19179
- freeBytes: number().optional()
19265
+ /**
19266
+ * `configSchema` is a `ConfigUISchema` tree passed through to the admin
19267
+ * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
19268
+ * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`)
19269
+ * the union is large and not meant for runtime validation here; the exported
19270
+ * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
19271
+ */
19272
+ var ConfigSchemaPassthrough = unknown();
19273
+ var TargetKindSchema = object({
19274
+ kind: string(),
19275
+ label: string(),
19276
+ icon: string(),
19277
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
19278
+ addonId: string(),
19279
+ configSchema: ConfigSchemaPassthrough,
19280
+ supportsDiscovery: boolean(),
19281
+ caps: TargetKindCapsSchema
19180
19282
  });
19181
- method(LlmGenerateBaseInputSchema.extend({
19182
- images: array(LlmImageSchema).optional(),
19183
- runtime: ManagedRuntimeConfigSchema,
19184
- /** The managed profile's timeout, threaded by the hub provider. */
19185
- timeoutMs: number().int().positive().optional()
19186
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
19187
- kind: "mutation",
19188
- auth: "admin"
19189
- }), method(object({}), _void(), {
19190
- kind: "mutation",
19191
- auth: "admin"
19192
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
19193
- kind: "mutation",
19194
- auth: "admin"
19195
- }), method(object({ file: string() }), _void(), {
19196
- kind: "mutation",
19197
- auth: "admin"
19198
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
19199
19283
  /**
19200
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
19201
- * methods concat-fan across providers; single-row methods route to ONE
19202
- * provider by the `addonId` in the call input (the notification-output
19203
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
19204
- * (hub-placed); the cap stays open for future providers.
19205
- *
19206
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
19207
- * `apiKey` is a password field — providers REDACT it on read and merge on
19208
- * write; a stored key NEVER round-trips to a client.
19284
+ * A persisted target. `config` holds secrets; providers REDACT secret fields
19285
+ * (return a presence marker only) when serving `listTargets` — never
19286
+ * round-trip a stored secret to the UI.
19209
19287
  */
19210
- var LlmProfileKindSchema = _enum([
19211
- "openai-compatible",
19212
- "openai",
19213
- "anthropic",
19214
- "google",
19215
- "managed-local"
19216
- ]);
19217
- var LlmProfileSchema = object({
19288
+ var TargetSchema = object({
19218
19289
  id: string(),
19219
19290
  name: string(),
19220
- kind: LlmProfileKindSchema,
19221
- /** Stamped by the provider — keeps the fanned catalog routable. */
19291
+ kind: string(),
19222
19292
  addonId: string(),
19223
19293
  enabled: boolean(),
19224
- /** Vendor model id, or the managed runtime's loaded model. */
19225
- model: string(),
19226
- /** Required for openai-compatible; override for cloud kinds. */
19227
- baseUrl: string().optional(),
19228
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
19229
- apiKey: string().optional(),
19230
- supportsVision: boolean(),
19231
- temperature: number().min(0).max(2).optional(),
19232
- maxTokens: number().int().positive().optional(),
19233
- timeoutMs: number().int().positive().default(6e4),
19234
- extraHeaders: record(string(), string()).optional(),
19235
- /** kind === 'managed-local' only (spec §4). */
19236
- runtime: ManagedRuntimeConfigSchema.optional()
19294
+ config: record(string(), unknown())
19237
19295
  });
19238
- /** ConfigUISchema tree passed through untyped on the wire (the
19239
- * notification-output `ConfigSchemaPassthrough` precedent at
19240
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
19241
- var ConfigSchemaPassthrough = unknown();
19242
- var LlmProfileKindDescriptorSchema = object({
19243
- kind: LlmProfileKindSchema,
19244
- label: string(),
19245
- icon: string(),
19246
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
19247
- addonId: string(),
19248
- configSchema: ConfigSchemaPassthrough
19296
+ /** A discovery-surfaced candidate (config is partial + non-secret). */
19297
+ var DiscoveredTargetSchema = object({
19298
+ kind: string(),
19299
+ suggestedName: string(),
19300
+ config: record(string(), unknown())
19249
19301
  });
19250
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
19251
- var LlmDefaultSchema = object({
19252
- selector: LlmDefaultSelectorSchema,
19253
- profileId: string()
19302
+ /** The degrade engine's report what was resolved / dropped / degraded. */
19303
+ var RenderedAsSchema = object({
19304
+ level: string(),
19305
+ format: NotificationFormatSchema,
19306
+ attachmentsSent: number().int().nonnegative(),
19307
+ actionsSent: number().int().nonnegative(),
19308
+ truncated: boolean(),
19309
+ dropped: array(string())
19254
19310
  });
19255
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
19256
- var LlmUsageRollupSchema = object({
19257
- day: string(),
19258
- consumer: string(),
19259
- profileId: string(),
19260
- calls: number(),
19261
- okCalls: number(),
19262
- errorCalls: number(),
19263
- inputTokens: number(),
19264
- outputTokens: number(),
19265
- avgLatencyMs: number()
19311
+ var SendResultSchema = object({
19312
+ success: boolean(),
19313
+ error: string().optional(),
19314
+ renderedAs: RenderedAsSchema.optional()
19266
19315
  });
19267
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
19268
- var ManagedModelCatalogEntrySchema = object({
19316
+ /** Same shape as SendResult kept as a distinct name for the test panel. */
19317
+ var TestResultSchema = SendResultSchema;
19318
+ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
19319
+ kind: string(),
19320
+ config: record(string(), unknown()).optional()
19321
+ }), array(DiscoveredTargetSchema)), method(object({
19322
+ targetId: string(),
19323
+ notification: NotificationSchema
19324
+ }), SendResultSchema, { kind: "mutation" }), method(object({
19325
+ targetId: string(),
19326
+ sample: NotificationSchema.optional()
19327
+ }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
19328
+ targetId: string(),
19329
+ enabled: boolean()
19330
+ }), _void(), { kind: "mutation" });
19331
+ /**
19332
+ * notification-rules — the Notification Center rule surface (P1 core).
19333
+ *
19334
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
19335
+ * (operator decisions D-1/D-2/D-3 are binding):
19336
+ *
19337
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
19338
+ * `notification-center` module), hooked on the durable persistence
19339
+ * moments (object-event insert, TrackCloser.closeExpired) with a
19340
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
19341
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
19342
+ * FIRST persisted detection matching the conditions (per-track dedup,
19343
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
19344
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
19345
+ * - DISPATCH stays behind `notification-output` (rules reference targets
19346
+ * by id; per-backend params are a passthrough blob capped by the
19347
+ * target kind's own caps/degrade engine).
19348
+ *
19349
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
19350
+ * server-injected caller identity — the first `caller: 'required'`
19351
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
19352
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
19353
+ * windows, and the optional label/identity/plate matchers. User rules,
19354
+ * private zones, per-recipient fan-out and the wider condition table are
19355
+ * P2+ (see spec §7).
19356
+ *
19357
+ * All schemas here are the single source of truth — `NcRule` etc. are
19358
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
19359
+ * schema/interface drift is explicitly not repeated).
19360
+ */
19361
+ /**
19362
+ * D-3: the trigger/urgency of a rule — which persistence moment evaluates it.
19363
+ * The value maps 1:1 onto the evaluated record kind:
19364
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
19365
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
19366
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
19367
+ * change of a LINKED device, one row per linked camera)
19368
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
19369
+ * delivery / pick-up)
19370
+ *
19371
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
19372
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
19373
+ * this one field keeps the schema additive — a rule still declares exactly
19374
+ * one trigger.
19375
+ */
19376
+ var NcDeliverySchema = _enum([
19377
+ "immediate",
19378
+ "track-end",
19379
+ "device-event",
19380
+ "package-event"
19381
+ ]);
19382
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
19383
+ var NcScheduleSchema = object({
19384
+ windows: array(object({
19385
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
19386
+ days: array(number().int().min(0).max(6)).min(1),
19387
+ startMinute: number().int().min(0).max(1439),
19388
+ endMinute: number().int().min(0).max(1439)
19389
+ })).min(1),
19390
+ /** IANA timezone; default = hub host timezone. */
19391
+ timezone: string().optional(),
19392
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
19393
+ invert: boolean().optional()
19394
+ });
19395
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
19396
+ var NcPlateMatcherSchema = object({
19397
+ values: array(string().min(1)).min(1),
19398
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
19399
+ maxDistance: number().int().min(0).max(3).default(1)
19400
+ });
19401
+ /**
19402
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
19403
+ * occupancy edge for a device — optionally narrowed to a single admin
19404
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
19405
+ * - `became-occupied` (default) — count crossed 0 → ≥ `count`
19406
+ * - `became-free` — count crossed ≥ `count` → below it
19407
+ * - `>=` / `<=` — count is at/over or at/under `count`
19408
+ * `sustainSeconds` requires the condition hold continuously that long
19409
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
19410
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
19411
+ * the condition never matches. Confirmed edge-state survives addon restarts
19412
+ * (declared SQLite collection, reseeded on boot).
19413
+ */
19414
+ var NcOccupancyConditionSchema = object({
19415
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
19416
+ zoneId: string().optional(),
19417
+ /** Object class to count; absent = any class. */
19418
+ className: string().optional(),
19419
+ op: _enum([
19420
+ "became-occupied",
19421
+ "became-free",
19422
+ ">=",
19423
+ "<="
19424
+ ]).default("became-occupied"),
19425
+ count: number().int().min(0).default(1),
19426
+ sustainSeconds: number().int().min(0).max(3600).default(15)
19427
+ });
19428
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
19429
+ var NcZoneConditionSchema = object({
19430
+ ids: array(string().min(1)).min(1),
19431
+ /** Quantifier over `ids` — at least one / every one visited. */
19432
+ match: _enum(["any", "all"]).default("any")
19433
+ });
19434
+ /**
19435
+ * The P1 condition set — a flat AND of groups; absent group = pass;
19436
+ * membership lists are OR within the list (spec §2.3).
19437
+ */
19438
+ var NcConditionsSchema = object({
19439
+ /** Device scope — absent = all devices. */
19440
+ devices: array(number()).optional(),
19441
+ /** Detector class names (any overlap with the record's class set). */
19442
+ classes: array(string().min(1)).optional(),
19443
+ /** Veto classes — any overlap fails the rule. */
19444
+ classesExclude: array(string().min(1)).optional(),
19445
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
19446
+ minConfidence: number().min(0).max(1).optional(),
19447
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
19448
+ zones: NcZoneConditionSchema.optional(),
19449
+ /** Veto zones — any hit fails the rule. */
19450
+ zonesExclude: array(string().min(1)).optional(),
19451
+ /**
19452
+ * Exact (case-insensitive) match on the record's collapsed `label`
19453
+ * (identity name / plate text / subclass).
19454
+ */
19455
+ labelEquals: array(string().min(1)).optional(),
19456
+ /**
19457
+ * Identity matcher. P1 boundary: matched against the record's collapsed
19458
+ * `label` (the identity display name propagated by the face pipeline) —
19459
+ * identity-ID matching rides in P2 when identity ids reach the record.
19460
+ */
19461
+ identities: array(string().min(1)).optional(),
19462
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
19463
+ plates: NcPlateMatcherSchema.optional(),
19464
+ /**
19465
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
19466
+ * Same P1 boundary: matched against the record's collapsed `label` (the
19467
+ * identity display name). A record with NO label passes (nothing to
19468
+ * exclude), unlike the include variant which fails on an absent label.
19469
+ */
19470
+ identitiesExclude: array(string().min(1)).optional(),
19471
+ /**
19472
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
19473
+ * TRACK-END only: importance is scored at track close, so it does not exist
19474
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
19475
+ * close the value is threaded via the close-time info (the `Track` clone is
19476
+ * captured before the DB row is updated, so it would otherwise read stale).
19477
+ * Fails when the record carries no importance (never guess quality — the
19478
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
19479
+ */
19480
+ minImportance: number().min(0).max(1).optional(),
19481
+ /**
19482
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
19483
+ * TRACK-END only: an `immediate` / object-event subject has no closed
19484
+ * lifespan, so a dwell condition never matches immediate delivery
19485
+ * (documented choice — the object-event record carries no `firstSeen`,
19486
+ * so dwell cannot be computed from what the subject actually carries).
19487
+ */
19488
+ minDwellSeconds: number().min(0).optional(),
19489
+ /**
19490
+ * Detection provenance filter. `any` (default / absent) matches every
19491
+ * source; otherwise the subject's source must equal it. Legacy records
19492
+ * with no stamped source are treated as `pipeline`. The union spans both
19493
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
19494
+ * tracks carry `sensor`.
19495
+ */
19496
+ source: _enum([
19497
+ "pipeline",
19498
+ "onboard",
19499
+ "sensor",
19500
+ "any"
19501
+ ]).optional(),
19502
+ /**
19503
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
19504
+ * detector `minConfidence` (that gates the object-detection score; this
19505
+ * gates the recognition/OCR match score). Fails when the subject carries
19506
+ * no label-match confidence (never guess). TRACK-END only: the confidence
19507
+ * lives on the recognition result and reaches the subject at track close.
19508
+ *
19509
+ * What it measures precisely (plumbed at track close — the closer threads
19510
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
19511
+ * `importance`): the BEST recognition match confidence observed for the
19512
+ * label the track carries at close — for a face, the peak cosine similarity
19513
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
19514
+ * for a plate, the peak OCR read score of the best-held plate
19515
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
19516
+ * one track the higher of the two is used. A track that ended with no
19517
+ * confident identity/plate match carries no value, so the condition fails
19518
+ * closed for it (an un-recognized subject).
19519
+ */
19520
+ minLabelConfidence: number().min(0).max(1).optional(),
19521
+ /**
19522
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
19523
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
19524
+ * against the token carried on the device-event subject (extracted from the
19525
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
19526
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
19527
+ * eventType, so gate those with {@link sensorKinds} instead.
19528
+ */
19529
+ eventTypeTokens: array(string().min(1)).optional(),
19530
+ /**
19531
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
19532
+ * `contact`, `button`, `device-event`) — matched against the persisted
19533
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
19534
+ */
19535
+ sensorKinds: array(string().min(1)).optional(),
19536
+ /**
19537
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
19538
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
19539
+ * when the subject's phase does not match (a subject always carries a phase
19540
+ * on the package-event trigger).
19541
+ */
19542
+ packagePhase: _enum([
19543
+ "delivered",
19544
+ "picked-up",
19545
+ "both"
19546
+ ]).optional(),
19547
+ /**
19548
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
19549
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
19550
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
19551
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
19552
+ */
19553
+ customZones: array(MaskPolygonShapeSchema).optional(),
19554
+ /**
19555
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
19556
+ * (optionally zone/class-scoped) occupancy count crosses the configured
19557
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
19558
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
19559
+ */
19560
+ occupancy: NcOccupancyConditionSchema.optional()
19561
+ });
19562
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
19563
+ var NcRuleTargetSchema = object({
19564
+ /** `notification-output` Target id. */
19565
+ targetId: string().min(1),
19566
+ /**
19567
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
19568
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
19569
+ * degrade engine drops what the backend can't render.
19570
+ */
19571
+ params: record(string(), unknown()).optional()
19572
+ });
19573
+ /**
19574
+ * Media attachment policy (P1 still-image subset).
19575
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
19576
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
19577
+ * matched on identities attaches the subject's `faceCrop`, one matched on
19578
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
19579
+ * (or when the specific crop is missing) degrades to `best`, then
19580
+ * `keyFrame`, then no attachment — never delaying the send. The matched
19581
+ * condition summary is frozen on the outbox row at enqueue (like the rule
19582
+ * name), so the choice never drifts from the record that fired it.
19583
+ * - `keyFrame` — the clean scene frame (no subject box).
19584
+ * - `none` — no attachment.
19585
+ */
19586
+ var NcMediaPolicySchema = object({ attach: _enum([
19587
+ "best",
19588
+ "best-matching",
19589
+ "keyFrame",
19590
+ "none"
19591
+ ]).default("best") });
19592
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
19593
+ var NcThrottleSchema = object({
19594
+ cooldownSec: number().int().min(0).max(86400).default(60),
19595
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
19596
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
19597
+ });
19598
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
19599
+ var NcRuleInputSchema = object({
19600
+ name: string().min(1).max(200),
19601
+ enabled: boolean().default(true),
19602
+ delivery: NcDeliverySchema,
19603
+ conditions: NcConditionsSchema.default({}),
19604
+ schedule: NcScheduleSchema.optional(),
19605
+ targets: array(NcRuleTargetSchema).min(1),
19606
+ media: NcMediaPolicySchema.default({ attach: "best" }),
19607
+ throttle: NcThrottleSchema.default({
19608
+ cooldownSec: 60,
19609
+ scope: "rule-device"
19610
+ }),
19611
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
19612
+ template: object({
19613
+ title: string().max(500).optional(),
19614
+ body: string().max(2e3).optional()
19615
+ }).optional(),
19616
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
19617
+ priority: number().int().min(1).max(5).default(3),
19618
+ /**
19619
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
19620
+ * behaviour, visible to all, read-only in the viewer). Present = personal
19621
+ * rule owned by this userId. Server-stamped; never trusted from a client.
19622
+ */
19623
+ ownerUserId: string().optional()
19624
+ });
19625
+ /**
19626
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
19627
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
19628
+ * NOT a client-authored input field (it lives on the persisted rule, not the
19629
+ * input), so it is added here explicitly to let the store's per-target opt-out
19630
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
19631
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
19632
+ * `updateRule` patch.
19633
+ */
19634
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
19635
+ /** A persisted rule. */
19636
+ var NcRuleSchema = NcRuleInputSchema.extend({
19637
+ id: string(),
19638
+ /** userId of the admin who created the rule (server-stamped caller). */
19639
+ createdBy: string(),
19640
+ createdAt: number(),
19641
+ updatedAt: number(),
19642
+ /**
19643
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
19644
+ * send time. Only a target's OWNER may add/remove its id (server-checked
19645
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
19646
+ */
19647
+ disabledTargetIds: array(string()).default([])
19648
+ });
19649
+ var NcTestResultSchema = object({
19650
+ recordId: string(),
19651
+ recordKind: _enum([
19652
+ "object-event",
19653
+ "track",
19654
+ "device-event",
19655
+ "package-event"
19656
+ ]),
19657
+ deviceId: number(),
19658
+ timestamp: number(),
19659
+ wouldFire: boolean(),
19660
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
19661
+ failedCondition: string().optional(),
19662
+ className: string().optional(),
19663
+ label: string().optional()
19664
+ });
19665
+ var NcConditionDescriptorSchema = object({
19666
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
19269
19667
  id: string(),
19668
+ group: _enum([
19669
+ "scope",
19670
+ "class",
19671
+ "zones",
19672
+ "quality",
19673
+ "label",
19674
+ "schedule",
19675
+ "device",
19676
+ "package",
19677
+ "occupancy"
19678
+ ]),
19270
19679
  label: string(),
19271
- family: string(),
19272
- purpose: _enum(["text", "vision"]),
19273
- url: string(),
19274
- sha256: string(),
19275
- sizeBytes: number(),
19276
- quantization: string(),
19277
- /** Load-time guidance shown in the picker. */
19278
- minRamBytes: number(),
19279
- contextSizeDefault: number().int(),
19280
- /** Vision models: companion projector file. */
19281
- mmprojUrl: string().optional()
19680
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
19681
+ valueType: _enum([
19682
+ "deviceIdList",
19683
+ "stringList",
19684
+ "number01",
19685
+ "number",
19686
+ "sourceSelect",
19687
+ "zoneSelection",
19688
+ "zoneIdList",
19689
+ "schedule",
19690
+ "plateMatcher",
19691
+ "packagePhase",
19692
+ "polygonDraw",
19693
+ "occupancy"
19694
+ ]),
19695
+ operator: _enum([
19696
+ "in",
19697
+ "notIn",
19698
+ "anyOf",
19699
+ "allOf",
19700
+ "gte",
19701
+ "fuzzyIn",
19702
+ "withinSchedule"
19703
+ ]),
19704
+ /** Which delivery kinds the condition applies to. */
19705
+ appliesTo: array(NcDeliverySchema),
19706
+ phase: string(),
19707
+ description: string().optional()
19282
19708
  });
19283
- var LlmRuntimeNodeSchema = object({
19284
- nodeId: string(),
19285
- reachable: boolean(),
19286
- status: LlmRuntimeStatusSchema.optional(),
19287
- disk: LlmRuntimeDiskUsageSchema.optional(),
19288
- error: string().optional()
19709
+ /**
19710
+ * The delivery lifecycle status of a history row — a straight read of the
19711
+ * durable outbox row's own status (single source of truth):
19712
+ * - `pending` — enqueued, in-flight or retrying with backoff
19713
+ * - `sent` — delivered (terminal)
19714
+ * - `dead` — dead-lettered after exhausting retries / a permanent
19715
+ * backend rejection / a deleted target (terminal; carries
19716
+ * the failure `error`)
19717
+ *
19718
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
19719
+ * user dimension (quiet hours / snooze) and are additive when they land.
19720
+ */
19721
+ var NcHistoryStatusSchema = _enum([
19722
+ "pending",
19723
+ "sent",
19724
+ "dead"
19725
+ ]);
19726
+ /** The evaluated record kind a history row descends from (one per trigger). */
19727
+ var NcHistoryRecordKindSchema = _enum([
19728
+ "object-event",
19729
+ "track-end",
19730
+ "device-event",
19731
+ "package-event"
19732
+ ]);
19733
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
19734
+ var NcHistorySubjectSchema = object({
19735
+ className: string(),
19736
+ label: string().optional(),
19737
+ confidence: number().optional(),
19738
+ zones: array(string()),
19739
+ timestamp: number()
19289
19740
  });
19290
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
19291
- var ProfileRefInputSchema = object({
19292
- addonId: string(),
19293
- profileId: string()
19741
+ /**
19742
+ * One delivery-history row. This is a read-only VIEW over the durable
19743
+ * outbox row (single source of truth — the same row the drain loop drives;
19744
+ * NO second write path, so history can never drift from delivery state).
19745
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
19746
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
19747
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
19748
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
19749
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
19750
+ * P1 (admin scope only).
19751
+ */
19752
+ var NcHistoryEntrySchema = object({
19753
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
19754
+ id: string(),
19755
+ ruleId: string(),
19756
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
19757
+ ruleName: string(),
19758
+ /** The rule urgency/trigger that produced this delivery. */
19759
+ delivery: NcDeliverySchema,
19760
+ targetId: string(),
19761
+ deviceId: number(),
19762
+ recordKind: NcHistoryRecordKindSchema,
19763
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
19764
+ recordId: string(),
19765
+ /** Present for track-scoped deliveries (object-event / track-end). */
19766
+ trackId: string().optional(),
19767
+ status: NcHistoryStatusSchema,
19768
+ /** Delivery attempts made so far. */
19769
+ attempts: number().int(),
19770
+ /** Fire time (outbox enqueue). */
19771
+ createdAt: number(),
19772
+ /** Last transition time (terminal for sent / dead). */
19773
+ updatedAt: number(),
19774
+ /** Failure detail — present on a `dead` row. */
19775
+ error: string().optional(),
19776
+ subject: NcHistorySubjectSchema
19294
19777
  });
19295
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
19296
- kind: "mutation",
19297
- auth: "admin"
19298
- }), method(ProfileRefInputSchema, _void(), {
19299
- kind: "mutation",
19300
- auth: "admin"
19301
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
19302
- kind: "mutation",
19303
- auth: "admin"
19304
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
19305
- selector: LlmDefaultSelectorSchema,
19306
- profileId: string().nullable()
19307
- }), _void(), {
19308
- kind: "mutation",
19309
- auth: "admin"
19310
- }), method(object({
19778
+ /**
19779
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
19780
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
19781
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
19782
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
19783
+ */
19784
+ var NcHistoryFilterSchema = object({
19785
+ ruleId: string().optional(),
19786
+ deviceId: number().optional(),
19787
+ status: NcHistoryStatusSchema.optional(),
19311
19788
  since: number().optional(),
19312
19789
  until: number().optional(),
19313
- consumer: string().optional(),
19314
- profileId: string().optional()
19315
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
19316
- nodeId: string(),
19317
- model: ManagedModelRefSchema
19318
- }), _void(), {
19790
+ limit: number().int().min(1).max(500).default(100)
19791
+ });
19792
+ 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 }), {
19319
19793
  kind: "mutation",
19320
- auth: "admin"
19794
+ auth: "admin",
19795
+ caller: "required"
19321
19796
  }), method(object({
19322
- nodeId: string(),
19323
- file: string()
19324
- }), _void(), {
19797
+ ruleId: string(),
19798
+ patch: NcRulePatchSchema
19799
+ }), object({ rule: NcRuleSchema }), {
19800
+ kind: "mutation",
19801
+ auth: "admin",
19802
+ caller: "required"
19803
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
19325
19804
  kind: "mutation",
19326
19805
  auth: "admin"
19327
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
19806
+ }), method(object({
19807
+ ruleId: string(),
19808
+ enabled: boolean()
19809
+ }), object({ success: literal(true) }), {
19328
19810
  kind: "mutation",
19329
19811
  auth: "admin"
19330
- }), method(ProfileRefInputSchema, _void(), {
19812
+ }), method(object({
19813
+ rule: NcRuleInputSchema,
19814
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
19815
+ }), object({ results: array(NcTestResultSchema) }), {
19331
19816
  kind: "mutation",
19332
19817
  auth: "admin"
19333
- });
19818
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
19334
19819
  /**
19335
19820
  * Zod schemas for persisted record types.
19336
19821
  *
@@ -20040,76 +20525,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
20040
20525
  eventId: string(),
20041
20526
  timestamp: number()
20042
20527
  });
20043
- /**
20044
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
20045
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
20046
- * caps into per-camera event-kind descriptors.
20047
- *
20048
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
20049
- * is NOT duplicated here — every entry is derived from the single
20050
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
20051
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
20052
- * control cap means adding one line here (and a taxonomy entry); the anti-
20053
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
20054
- * eventful cap is missing.
20055
- */
20056
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
20057
- var LEGACY_ICON = {
20058
- motion: "motion",
20059
- audio: "audio",
20060
- person: "person",
20061
- vehicle: "vehicle",
20062
- animal: "animal",
20063
- package: "package",
20064
- door: "door",
20065
- pir: "pir",
20066
- smoke: "smoke",
20067
- water: "water",
20068
- button: "button",
20069
- generic: "generic",
20070
- gas: "smoke",
20071
- vibration: "generic",
20072
- tamper: "generic",
20073
- presence: "person",
20074
- lock: "generic",
20075
- siren: "generic",
20076
- switch: "generic",
20077
- doorbell: "button"
20078
- };
20079
- function legacyIcon(iconId) {
20080
- return LEGACY_ICON[iconId] ?? "generic";
20081
- }
20082
- /**
20083
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
20084
- * The anti-drift guard cross-checks this against the eventful caps declared
20085
- * in `packages/types/src/capabilities/*.cap.ts`.
20086
- */
20087
- var CAP_TO_KIND = {
20088
- contact: "contact",
20089
- motion: "motion-sensor",
20090
- smoke: "smoke",
20091
- flood: "flood",
20092
- gas: "gas",
20093
- "carbon-monoxide": "carbon-monoxide",
20094
- vibration: "vibration",
20095
- tamper: "tamper",
20096
- presence: "presence",
20097
- "enum-sensor": "enum-sensor",
20098
- "event-emitter": "device-event",
20099
- "lock-control": "lock",
20100
- switch: "switch",
20101
- button: "button",
20102
- doorbell: "doorbell"
20103
- };
20104
- function buildDescriptor(capName, kind) {
20105
- const t = EVENT_TAXONOMY[kind];
20106
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
20107
- return {
20108
- ...t,
20109
- icon: legacyIcon(t.iconId)
20110
- };
20111
- }
20112
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
20113
20528
  var CameraPipelineConfigSchema = object({
20114
20529
  engine: PipelineEngineChoiceSchema.optional(),
20115
20530
  steps: array(PipelineStepInputSchema).readonly(),
@@ -20595,6 +21010,76 @@ method(object({
20595
21010
  auth: "admin"
20596
21011
  });
20597
21012
  /**
21013
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
21014
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
21015
+ * caps into per-camera event-kind descriptors.
21016
+ *
21017
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
21018
+ * is NOT duplicated here — every entry is derived from the single
21019
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
21020
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
21021
+ * control cap means adding one line here (and a taxonomy entry); the anti-
21022
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
21023
+ * eventful cap is missing.
21024
+ */
21025
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
21026
+ var LEGACY_ICON = {
21027
+ motion: "motion",
21028
+ audio: "audio",
21029
+ person: "person",
21030
+ vehicle: "vehicle",
21031
+ animal: "animal",
21032
+ package: "package",
21033
+ door: "door",
21034
+ pir: "pir",
21035
+ smoke: "smoke",
21036
+ water: "water",
21037
+ button: "button",
21038
+ generic: "generic",
21039
+ gas: "smoke",
21040
+ vibration: "generic",
21041
+ tamper: "generic",
21042
+ presence: "person",
21043
+ lock: "generic",
21044
+ siren: "generic",
21045
+ switch: "generic",
21046
+ doorbell: "button"
21047
+ };
21048
+ function legacyIcon(iconId) {
21049
+ return LEGACY_ICON[iconId] ?? "generic";
21050
+ }
21051
+ /**
21052
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
21053
+ * The anti-drift guard cross-checks this against the eventful caps declared
21054
+ * in `packages/types/src/capabilities/*.cap.ts`.
21055
+ */
21056
+ var CAP_TO_KIND = {
21057
+ contact: "contact",
21058
+ motion: "motion-sensor",
21059
+ smoke: "smoke",
21060
+ flood: "flood",
21061
+ gas: "gas",
21062
+ "carbon-monoxide": "carbon-monoxide",
21063
+ vibration: "vibration",
21064
+ tamper: "tamper",
21065
+ presence: "presence",
21066
+ "enum-sensor": "enum-sensor",
21067
+ "event-emitter": "device-event",
21068
+ "lock-control": "lock",
21069
+ switch: "switch",
21070
+ button: "button",
21071
+ doorbell: "doorbell"
21072
+ };
21073
+ function buildDescriptor(capName, kind) {
21074
+ const t = EVENT_TAXONOMY[kind];
21075
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
21076
+ return {
21077
+ ...t,
21078
+ icon: legacyIcon(t.iconId)
21079
+ };
21080
+ }
21081
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
21082
+ /**
20598
21083
  * server-management — per-NODE singleton capability for a node's ROOT
20599
21084
  * package lifecycle (runtime-updatable node packages).
20600
21085
  *
@@ -22100,7 +22585,28 @@ var FaceInfoSchema = object({
22100
22585
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
22101
22586
  * track produced no key frame (e.g. native/onboard source) — the UI falls
22102
22587
  * back to the inline `base64` face crop. */
22103
- keyFrameMediaKey: string().optional()
22588
+ keyFrameMediaKey: string().optional(),
22589
+ /** Winning identity-match cosine (0..1) for this face's track, when an
22590
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
22591
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
22592
+ * faces that were never auto-recognized. */
22593
+ bestMatchScore: number().optional(),
22594
+ /** Native-scale face short side (px) at recognition time, when the runner
22595
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
22596
+ * legacy rows / runners that reported no native measure. */
22597
+ nativeFaceShortSidePx: number().optional(),
22598
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
22599
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
22600
+ * but blocked only by the recognition size floor). Mutually exclusive with
22601
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
22602
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
22603
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
22604
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
22605
+ suggestedIdentityId: string().optional(),
22606
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
22607
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
22608
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
22609
+ suggestedMatchScore: number().optional()
22104
22610
  });
22105
22611
  var FaceFilterEnum = _enum([
22106
22612
  "unassigned",
@@ -24518,36 +25024,6 @@ Object.freeze({
24518
25024
  addonId: null,
24519
25025
  access: "view"
24520
25026
  },
24521
- "advancedNotifier.deleteRule": {
24522
- capName: "advanced-notifier",
24523
- capScope: "system",
24524
- addonId: null,
24525
- access: "delete"
24526
- },
24527
- "advancedNotifier.getHistory": {
24528
- capName: "advanced-notifier",
24529
- capScope: "system",
24530
- addonId: null,
24531
- access: "view"
24532
- },
24533
- "advancedNotifier.getRules": {
24534
- capName: "advanced-notifier",
24535
- capScope: "system",
24536
- addonId: null,
24537
- access: "view"
24538
- },
24539
- "advancedNotifier.testRule": {
24540
- capName: "advanced-notifier",
24541
- capScope: "system",
24542
- addonId: null,
24543
- access: "create"
24544
- },
24545
- "advancedNotifier.upsertRule": {
24546
- capName: "advanced-notifier",
24547
- capScope: "system",
24548
- addonId: null,
24549
- access: "create"
24550
- },
24551
25027
  "alarmPanel.arm": {
24552
25028
  capName: "alarm-panel",
24553
25029
  capScope: "device",
@@ -26852,6 +27328,60 @@ Object.freeze({
26852
27328
  addonId: null,
26853
27329
  access: "create"
26854
27330
  },
27331
+ "notificationRules.createRule": {
27332
+ capName: "notification-rules",
27333
+ capScope: "system",
27334
+ addonId: null,
27335
+ access: "create"
27336
+ },
27337
+ "notificationRules.deleteRule": {
27338
+ capName: "notification-rules",
27339
+ capScope: "system",
27340
+ addonId: null,
27341
+ access: "delete"
27342
+ },
27343
+ "notificationRules.getConditionCatalog": {
27344
+ capName: "notification-rules",
27345
+ capScope: "system",
27346
+ addonId: null,
27347
+ access: "view"
27348
+ },
27349
+ "notificationRules.getHistory": {
27350
+ capName: "notification-rules",
27351
+ capScope: "system",
27352
+ addonId: null,
27353
+ access: "view"
27354
+ },
27355
+ "notificationRules.getRule": {
27356
+ capName: "notification-rules",
27357
+ capScope: "system",
27358
+ addonId: null,
27359
+ access: "view"
27360
+ },
27361
+ "notificationRules.listRules": {
27362
+ capName: "notification-rules",
27363
+ capScope: "system",
27364
+ addonId: null,
27365
+ access: "view"
27366
+ },
27367
+ "notificationRules.setRuleEnabled": {
27368
+ capName: "notification-rules",
27369
+ capScope: "system",
27370
+ addonId: null,
27371
+ access: "create"
27372
+ },
27373
+ "notificationRules.testRule": {
27374
+ capName: "notification-rules",
27375
+ capScope: "system",
27376
+ addonId: null,
27377
+ access: "create"
27378
+ },
27379
+ "notificationRules.updateRule": {
27380
+ capName: "notification-rules",
27381
+ capScope: "system",
27382
+ addonId: null,
27383
+ access: "create"
27384
+ },
26855
27385
  "notifier.cancel": {
26856
27386
  capName: "notifier",
26857
27387
  capScope: "device",