@camstack/addon-provider-hikvision 1.2.4 → 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 +1455 -861
  2. package/dist/addon.mjs +1455 -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
@@ -12992,6 +13077,12 @@ var motionCooldownMsField = {
12992
13077
  default: 3e4,
12993
13078
  step: 500
12994
13079
  };
13080
+ var maxSessionHoldMsField = {
13081
+ min: 0,
13082
+ max: 6e5,
13083
+ default: 12e4,
13084
+ step: 5e3
13085
+ };
12995
13086
  var motionFpsField = {
12996
13087
  min: 1,
12997
13088
  max: 30,
@@ -13139,6 +13230,19 @@ var RunnerCameraConfigSchema = object({
13139
13230
  "on-motion"
13140
13231
  ]).default("always-on"),
13141
13232
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
13233
+ /**
13234
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
13235
+ * detection session is active and ≥1 confirmed non-stationary track is
13236
+ * still live, the orchestrator keeps the session open past
13237
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
13238
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
13239
+ * ms since the session opened, after which it closes regardless. `0`
13240
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
13241
+ * runner itself — carried here so it shares the per-camera device-settings
13242
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
13243
+ * resolved `CameraDetectionConfig`.
13244
+ */
13245
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
13142
13246
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
13143
13247
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
13144
13248
  motionStreamId: string(),
@@ -13228,7 +13332,7 @@ var RunnerCameraConfigSchema = object({
13228
13332
  */
13229
13333
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
13230
13334
  });
13231
- motionFpsField.min, motionFpsField.max, motionFpsField.step, motionFpsField.default, detectionFpsField.min, detectionFpsField.max, detectionFpsField.step, detectionFpsField.default, motionCooldownMsField.min, motionCooldownMsField.max, motionCooldownMsField.step, motionCooldownMsField.default, occupancyRecheckSecField.min, occupancyRecheckSecField.max, occupancyRecheckSecField.step, occupancyRecheckSecField.default, occupancyRecheckFramesField.min, occupancyRecheckFramesField.max, occupancyRecheckFramesField.step, occupancyRecheckFramesField.default;
13335
+ motionFpsField.min, motionFpsField.max, motionFpsField.step, motionFpsField.default, detectionFpsField.min, detectionFpsField.max, detectionFpsField.step, detectionFpsField.default, motionCooldownMsField.min, motionCooldownMsField.max, motionCooldownMsField.step, motionCooldownMsField.default, maxSessionHoldMsField.min, maxSessionHoldMsField.max, maxSessionHoldMsField.step, maxSessionHoldMsField.default, occupancyRecheckSecField.min, occupancyRecheckSecField.max, occupancyRecheckSecField.step, occupancyRecheckSecField.default, occupancyRecheckFramesField.min, occupancyRecheckFramesField.max, occupancyRecheckFramesField.step, occupancyRecheckFramesField.default;
13232
13336
  /**
13233
13337
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
13234
13338
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -16755,94 +16859,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
16755
16859
  bundleUrl: string()
16756
16860
  });
16757
16861
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
16758
- var NotificationRuleConditionsSchema = object({
16759
- deviceIds: array(number()).readonly().optional(),
16760
- classNames: array(string()).readonly().optional(),
16761
- zoneIds: array(string()).readonly().optional(),
16762
- minConfidence: number().optional(),
16763
- source: _enum([
16764
- "pipeline",
16765
- "onboard",
16766
- "any"
16767
- ]).optional(),
16768
- schedule: object({
16769
- days: array(number()).readonly(),
16770
- startHour: number(),
16771
- endHour: number()
16772
- }).optional(),
16773
- cooldownSeconds: number().optional(),
16774
- minDwellSeconds: number().optional(),
16775
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
16776
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
16777
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
16778
- eventTypeTokens: array(string()).readonly().optional(),
16779
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
16780
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
16781
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
16782
- clipDescription: object({
16783
- text: string().min(1),
16784
- minSimilarity: number().min(0).max(1)
16785
- }).optional(),
16786
- /** Match events whose recognized-entity label (face identity name or plate
16787
- * vehicle name, propagated onto `event.data.label`) is one of these values.
16788
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
16789
- * vehicle/person> is seen". */
16790
- labels: array(string()).readonly().optional()
16791
- });
16792
- var NotificationRuleTemplateSchema = object({
16793
- title: string(),
16794
- body: string(),
16795
- imageMode: _enum([
16796
- "crop",
16797
- "annotated",
16798
- "full",
16799
- "none"
16800
- ])
16801
- });
16802
- var NotificationRuleSchema = object({
16803
- id: string(),
16804
- name: string(),
16805
- enabled: boolean(),
16806
- eventTypes: array(string()).readonly(),
16807
- conditions: NotificationRuleConditionsSchema,
16808
- outputs: array(string()).readonly(),
16809
- template: NotificationRuleTemplateSchema.optional(),
16810
- priority: _enum([
16811
- "low",
16812
- "normal",
16813
- "high",
16814
- "critical"
16815
- ])
16816
- });
16817
- var NotificationTestResultSchema = object({
16818
- ruleId: string(),
16819
- eventId: string(),
16820
- timestamp: number(),
16821
- wouldFire: boolean(),
16822
- reason: string().optional()
16823
- });
16824
- var NotificationHistoryEntrySchema = object({
16825
- id: string(),
16826
- ruleId: string(),
16827
- ruleName: string(),
16828
- eventId: string(),
16829
- timestamp: number(),
16830
- outputs: array(string()).readonly(),
16831
- success: boolean(),
16832
- error: string().optional(),
16833
- deviceId: number().optional()
16834
- });
16835
- var NotificationHistoryFilterSchema = object({
16836
- ruleId: string().optional(),
16837
- deviceId: number().optional(),
16838
- from: number().optional(),
16839
- to: number().optional(),
16840
- limit: number().optional()
16841
- });
16842
- 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({
16843
- ruleId: string(),
16844
- lookbackMinutes: number()
16845
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
16846
16862
  /**
16847
16863
  * Alerts capability — collection-based internal alert system.
16848
16864
  *
@@ -17029,89 +17045,6 @@ method(object({
17029
17045
  password: string()
17030
17046
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
17031
17047
  /**
17032
- * `login-method` — collection cap through which auth addons contribute
17033
- * their pre-auth login surfaces to the login page. This is the SINGLE,
17034
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
17035
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
17036
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
17037
- * procedure aggregates them for the unauthenticated login page.
17038
- *
17039
- * A contribution is a discriminated union on `kind`:
17040
- *
17041
- * - `redirect` — a declarative button. The login page renders a generic
17042
- * button that navigates to `startUrl` (an addon-owned HTTP route).
17043
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
17044
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
17045
- * login page needs NO change.
17046
- *
17047
- * - `widget` — a Module-Federation widget the login page mounts (via
17048
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
17049
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
17050
- * mechanism kept for future use; no shipped addon uses it on the login
17051
- * page (the passkey ceremony below runs natively in the shell instead).
17052
- *
17053
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
17054
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
17055
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
17056
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
17057
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
17058
- * fetching any remote code pre-auth. Contribution stays unconditional —
17059
- * enrollment state is never leaked pre-auth; visibility is a shell
17060
- * decision.
17061
- *
17062
- * Every contribution carries a `stage`:
17063
- * - `primary` — shown on the first credentials screen (OIDC /
17064
- * magic-link buttons; a future usernameless passkey).
17065
- * - `second-factor` — shown AFTER the password leg, gated on the
17066
- * returned `factors` (passkey-as-2FA today).
17067
- *
17068
- * `mount: skip` — the cap is read server-side by the core auth router
17069
- * (`registry.getCollection('login-method')`), never mounted as its own
17070
- * tRPC router.
17071
- */
17072
- /** When a login method renders in the two-phase login flow. */
17073
- var LoginStageEnum = _enum(["primary", "second-factor"]);
17074
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
17075
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
17076
- object({
17077
- kind: literal("redirect"),
17078
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
17079
- id: string(),
17080
- /** Operator-facing button label. */
17081
- label: string(),
17082
- /** lucide-react icon name. */
17083
- icon: string().optional(),
17084
- /** Addon-owned HTTP route the button navigates to (GET). */
17085
- startUrl: string(),
17086
- stage: LoginStageEnum
17087
- }),
17088
- object({
17089
- kind: literal("widget"),
17090
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
17091
- id: string(),
17092
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
17093
- addonId: string(),
17094
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
17095
- bundle: string(),
17096
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
17097
- remote: WidgetRemoteSchema,
17098
- stage: LoginStageEnum
17099
- }),
17100
- object({
17101
- kind: literal("passkey"),
17102
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
17103
- id: string(),
17104
- /** Operator-facing button label. */
17105
- label: string(),
17106
- stage: LoginStageEnum,
17107
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
17108
- rpId: string(),
17109
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
17110
- origin: string().nullable()
17111
- })
17112
- ]);
17113
- method(_void(), array(LoginMethodContributionSchema).readonly());
17114
- /**
17115
17048
  * Orchestrator-side destination metadata. The orchestrator computes
17116
17049
  * `id = <addonId>:<subId>` from its provider lookup so consumers
17117
17050
  * (admin UI, restore flow) see one canonical key.
@@ -18467,242 +18400,617 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
18467
18400
  kind: "mutation",
18468
18401
  auth: "admin"
18469
18402
  });
18470
- var LogLevelSchema = _enum([
18471
- "debug",
18472
- "info",
18473
- "warn",
18474
- "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"
18475
18426
  ]);
18476
- var LogEntrySchema = object({
18477
- timestamp: date(),
18478
- level: LogLevelSchema,
18479
- 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,
18480
18437
  message: string(),
18481
- meta: record(string(), unknown()).optional(),
18482
- tags: record(string(), string()).optional()
18483
- });
18484
- method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18485
- scope: array(string()).optional(),
18486
- level: LogLevelSchema.optional(),
18487
- since: date().optional(),
18488
- until: date().optional(),
18489
- limit: number().optional(),
18490
- tags: record(string(), string()).optional()
18491
- }), array(LogEntrySchema).readonly());
18492
- var CpuBreakdownSchema = object({
18493
- total: number(),
18494
- user: number(),
18495
- system: number(),
18496
- irq: number(),
18497
- nice: number(),
18498
- loadAvg: tuple([
18499
- number(),
18500
- number(),
18501
- number()
18502
- ]),
18503
- 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()
18504
18448
  });
18505
- var MemoryInfoSchema = object({
18506
- percent: number(),
18507
- totalBytes: number(),
18508
- usedBytes: number(),
18509
- availableBytes: number(),
18510
- swapUsedBytes: number(),
18511
- 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()
18512
18464
  });
18513
- var DiskIoSnapshotSchema = object({
18514
- readBytes: number(),
18515
- writeBytes: number(),
18516
- readOps: number(),
18517
- writeOps: number(),
18518
- timestampMs: number()
18519
- });
18520
- var NetworkIoSnapshotSchema = object({
18521
- rxBytes: number(),
18522
- txBytes: number(),
18523
- rxPackets: number(),
18524
- txPackets: number(),
18525
- rxErrors: number(),
18526
- txErrors: number(),
18527
- timestampMs: number()
18528
- });
18529
- var MetricsGpuInfoSchema = object({
18530
- utilization: number(),
18531
- model: string(),
18532
- memoryUsedBytes: number(),
18533
- memoryTotalBytes: number(),
18534
- temperature: number().nullable()
18535
- });
18536
- var ProcessResourceInfoSchema = object({
18537
- openFds: number(),
18538
- threadCount: number(),
18539
- activeHandles: number(),
18540
- activeRequests: number()
18541
- });
18542
- var PressureAvgsSchema = object({
18543
- avg10: number(),
18544
- avg60: number(),
18545
- avg300: number()
18546
- });
18547
- var PressureInfoSchema = object({
18548
- some: PressureAvgsSchema,
18549
- full: PressureAvgsSchema.nullable()
18550
- });
18551
- var SystemResourceSnapshotSchema = object({
18552
- cpu: CpuBreakdownSchema,
18553
- memory: MemoryInfoSchema,
18554
- gpu: MetricsGpuInfoSchema.nullable(),
18555
- network: NetworkIoSnapshotSchema,
18556
- disk: DiskIoSnapshotSchema,
18557
- pressure: object({
18558
- cpu: PressureInfoSchema.nullable(),
18559
- memory: PressureInfoSchema.nullable(),
18560
- 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()
18561
18480
  }),
18562
- process: ProcessResourceInfoSchema,
18563
- cpuTemperature: number().nullable(),
18564
- timestampMs: number()
18565
- });
18566
- var DiskSpaceInfoSchema = object({
18567
- path: string(),
18568
- totalBytes: number(),
18569
- usedBytes: number(),
18570
- availableBytes: number(),
18571
- percent: number()
18572
- });
18573
- var PidResourceStatsSchema = object({
18574
- pid: number(),
18575
- cpu: number(),
18576
- memory: number(),
18577
- /**
18578
- * Private (anonymous) resident bytes — the per-process V8 heap + native
18579
- * allocations NOT shared with other processes (Linux RssAnon). This is the
18580
- * "real" per-runner cost; summing it across runners is meaningful, unlike
18581
- * `memory` (RSS), which double-counts the shared mmap'd framework code.
18582
- * Undefined where /proc is unavailable (e.g. macOS).
18583
- */
18584
- privateBytes: number().optional(),
18585
- /**
18586
- * Shared file-backed resident bytes (Linux RssFile) — mmap'd framework/lib
18587
- * code shared copy-on-write across runners. Undefined on macOS.
18588
- */
18589
- 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)
18590
18508
  });
18591
- var AddonInstanceSchema = object({
18592
- addonId: string(),
18509
+ var LlmRuntimeStatusSchema = object({
18510
+ /** Status is ALWAYS node-qualified. */
18593
18511
  nodeId: string(),
18594
- role: _enum(["hub", "worker"]),
18595
- pid: number(),
18596
18512
  state: _enum([
18597
- "starting",
18598
- "running",
18599
- "stopping",
18600
18513
  "stopped",
18601
- "crashed"
18602
- ]),
18603
- uptimeSec: number()
18604
- });
18605
- var NodeProcessSchema = object({
18606
- pid: number(),
18607
- ppid: number(),
18608
- pgid: number(),
18609
- classification: _enum([
18610
- "root",
18611
- "managed",
18612
- "system",
18613
- "ghost"
18514
+ "downloading",
18515
+ "starting",
18516
+ "ready",
18517
+ "crashed",
18518
+ "failed"
18614
18519
  ]),
18615
- /** `$process` addon binding when `managed`, else null. */
18616
- addonId: string().nullable(),
18617
- /** Kernel-reported nodeId when the process is a known agent/worker. */
18618
- nodeId: string().nullable(),
18619
- /** Truncated command line. */
18620
- command: string(),
18621
- cpuPercent: number(),
18622
- memoryRssBytes: number(),
18623
- /** Wall-clock uptime (seconds). Parsed from `ps etime`. */
18624
- uptimeSec: number(),
18625
- /** True when ancestor walk reaches `ppid=1` (reparented to init/launchd). */
18626
- orphaned: boolean()
18627
- });
18628
- var KillProcessInputSchema = object({
18629
- pid: number(),
18630
- /** Force = SIGKILL. Default is SIGTERM. */
18631
- force: boolean().optional()
18632
- });
18633
- var KillProcessResultSchema = object({
18634
- success: boolean(),
18635
- reason: string().optional(),
18636
- signal: _enum(["SIGTERM", "SIGKILL"]).optional()
18637
- });
18638
- var DumpHeapSnapshotInputSchema = object({
18639
- /** The addon whose runner should dump a heap snapshot. */
18640
- addonId: string() });
18641
- var DumpHeapSnapshotResultSchema = object({
18642
- success: boolean(),
18643
- /** Path of the written .heapsnapshot inside the runner's container/host. */
18644
- path: string().optional(),
18645
- /** Process pid that was signalled. */
18646
18520
  pid: number().optional(),
18647
- 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()
18648
18530
  });
18649
- var SystemMetricsSchema = object({
18650
- cpuPercent: number(),
18651
- memoryPercent: number(),
18652
- memoryUsedMB: number(),
18653
- memoryTotalMB: number(),
18654
- diskPercent: number().optional(),
18655
- temperature: number().optional(),
18656
- gpuPercent: number().optional(),
18657
- gpuMemoryPercent: number().optional()
18531
+ var LlmNodeModelSchema = object({
18532
+ file: string(),
18533
+ sizeBytes: number(),
18534
+ catalogId: string().optional(),
18535
+ installedAt: number().optional()
18658
18536
  });
18659
- 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, {
18660
18548
  kind: "mutation",
18661
18549
  auth: "admin"
18662
- }), method(DumpHeapSnapshotInputSchema, DumpHeapSnapshotResultSchema, {
18550
+ }), method(object({}), _void(), {
18663
18551
  kind: "mutation",
18664
18552
  auth: "admin"
18665
- });
18666
- method(object({
18667
- sourceUrl: string(),
18668
- metadata: ModelConvertMetadataSchema,
18669
- targets: array(ConvertTargetSchema).min(1).readonly(),
18670
- calibrationRef: string().optional(),
18671
- sessionId: string().optional()
18672
- }), ConvertResultSchema, {
18553
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18673
18554
  kind: "mutation",
18674
- auth: "admin",
18675
- timeoutMs: 6e5
18676
- });
18677
- method(object({
18678
- nodeId: string(),
18679
- modelId: string(),
18680
- format: _enum(MODEL_FORMATS),
18681
- entry: ModelCatalogEntrySchema
18682
- }), object({
18683
- ok: boolean(),
18684
- /** sha256 of the staged tarball (empty for a hub-local no-op). */
18685
- sha256: string(),
18686
- bytes: number(),
18687
- /** The target node's modelsDir the artifact landed in. */
18688
- path: string()
18689
- }), {
18555
+ auth: "admin"
18556
+ }), method(object({ file: string() }), _void(), {
18690
18557
  kind: "mutation",
18691
18558
  auth: "admin"
18692
- });
18559
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18693
18560
  /**
18694
- * `mqtt-broker` — broker-registry cap.
18695
- *
18696
- * NOT a pub/sub proxy. The cap exposes (a) a registry of configured
18697
- * MQTT brokers (external + optionally an embedded `aedes`-backed one)
18698
- * and (b) the connection details a consumer addon needs to spin up
18699
- * its OWN `mqtt.js` client.
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.
18700
18566
  *
18701
- * Why: pub/sub routing over the system event-bus loses fidelity
18702
- * (callback shape, QoS guarantees, will/retain semantics) and adds
18703
- * refcount bookkeeping that addons would rather own themselves. The
18704
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
18705
- * features anyway — give it the connection config, get out of the way.
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.
18706
19014
  *
18707
19015
  * Consumer flow:
18708
19016
  * const cfg = await ctx.api.mqttBroker.getBrokerConfig({ id })
@@ -18926,392 +19234,588 @@ var TargetKindLevelSchema = object({
18926
19234
  ordinal: number().int().min(1).max(5).nullable(),
18927
19235
  flags: object({
18928
19236
  critical: boolean().optional(),
18929
- silent: boolean().optional(),
18930
- noPush: boolean().optional()
18931
- }).optional(),
18932
- /** e.g. Pushover `emergency` requires `retry` / `expire`. */
18933
- requires: array(string()).optional(),
18934
- description: string().optional()
18935
- });
18936
- /** The full capability block consulted before dispatch. */
18937
- var TargetKindCapsSchema = object({
18938
- attachments: object({
18939
- mediaTypes: array(AttachmentMediaTypeSchema),
18940
- mode: _enum([
18941
- "url",
18942
- "bytes",
18943
- "both"
18944
- ]),
18945
- max: number().int().nonnegative(),
18946
- maxBytes: number().int().positive().optional()
18947
- }),
18948
- /** Max action buttons (0 = none). */
18949
- actions: number().int().nonnegative(),
18950
- levels: array(TargetKindLevelSchema),
18951
- format: array(NotificationFormatSchema),
18952
- clickUrl: boolean(),
18953
- sound: boolean(),
18954
- ttl: boolean(),
18955
- bodyMaxLen: number().int().positive()
18956
- });
18957
- /**
18958
- * `configSchema` is a `ConfigUISchema` tree passed through to the admin
18959
- * FormBuilder. Stored as `z.unknown()` at the cap seam (mirrors
18960
- * `device-provider.getChildCreationSchema` `CreationSchemaOutputSchema`) —
18961
- * the union is large and not meant for runtime validation here; the exported
18962
- * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
18963
- */
18964
- var ConfigSchemaPassthrough$1 = unknown();
18965
- var TargetKindSchema = object({
18966
- kind: string(),
18967
- label: string(),
18968
- icon: string(),
18969
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
18970
- addonId: string(),
18971
- configSchema: ConfigSchemaPassthrough$1,
18972
- supportsDiscovery: boolean(),
18973
- caps: TargetKindCapsSchema
18974
- });
18975
- /**
18976
- * A persisted target. `config` holds secrets; providers REDACT secret fields
18977
- * (return a presence marker only) when serving `listTargets` — never
18978
- * round-trip a stored secret to the UI.
18979
- */
18980
- var TargetSchema = object({
18981
- id: string(),
18982
- name: string(),
18983
- kind: string(),
18984
- addonId: string(),
18985
- enabled: boolean(),
18986
- config: record(string(), unknown())
18987
- });
18988
- /** A discovery-surfaced candidate (config is partial + non-secret). */
18989
- var DiscoveredTargetSchema = object({
18990
- kind: string(),
18991
- suggestedName: string(),
18992
- config: record(string(), unknown())
18993
- });
18994
- /** The degrade engine's report — what was resolved / dropped / degraded. */
18995
- var RenderedAsSchema = object({
18996
- level: string(),
18997
- format: NotificationFormatSchema,
18998
- attachmentsSent: number().int().nonnegative(),
18999
- actionsSent: number().int().nonnegative(),
19000
- truncated: boolean(),
19001
- dropped: array(string())
19002
- });
19003
- var SendResultSchema = object({
19004
- success: boolean(),
19005
- error: string().optional(),
19006
- renderedAs: RenderedAsSchema.optional()
19007
- });
19008
- /** Same shape as SendResult — kept as a distinct name for the test panel. */
19009
- var TestResultSchema = SendResultSchema;
19010
- method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSchema)), method(object({
19011
- kind: string(),
19012
- config: record(string(), unknown()).optional()
19013
- }), array(DiscoveredTargetSchema)), method(object({
19014
- targetId: string(),
19015
- notification: NotificationSchema
19016
- }), SendResultSchema, { kind: "mutation" }), method(object({
19017
- targetId: string(),
19018
- sample: NotificationSchema.optional()
19019
- }), TestResultSchema, { kind: "mutation" }), method(object({ target: TargetSchema }), TargetSchema, { kind: "mutation" }), method(object({ targetId: string() }), _void(), { kind: "mutation" }), method(object({
19020
- targetId: string(),
19021
- enabled: boolean()
19022
- }), _void(), { kind: "mutation" });
19023
- /**
19024
- * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
19025
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
19026
- * caps stay wire-compatible without a circular cap→cap import.
19027
- *
19028
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
19029
- * every transport tier structurally, and failed calls still write usage rows.
19030
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
19031
- */
19032
- var LlmUsageSchema = object({
19033
- inputTokens: number(),
19034
- outputTokens: number()
19035
- });
19036
- var LlmErrorCodeSchema = _enum([
19037
- "timeout",
19038
- "rate-limited",
19039
- "auth",
19040
- "refusal",
19041
- "bad-request",
19042
- "unavailable",
19043
- "no-profile",
19044
- "budget-exceeded",
19045
- "adapter-error"
19046
- ]);
19047
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
19048
- ok: literal(true),
19049
- text: string(),
19050
- model: string(),
19051
- usage: LlmUsageSchema,
19052
- truncated: boolean(),
19053
- latencyMs: number()
19054
- }), object({
19055
- ok: literal(false),
19056
- code: LlmErrorCodeSchema,
19057
- message: string(),
19058
- retryAfterMs: number().optional()
19059
- })]);
19060
- /**
19061
- * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
19062
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
19063
- * notification-output.cap.ts:27-31 precedents).
19064
- */
19065
- var LlmImageSchema = object({
19066
- bytes: _instanceof(Uint8Array),
19067
- mimeType: string()
19068
- });
19069
- var LlmGenerateBaseInputSchema = object({
19070
- /** Collection routing (the notification-output posture). */
19071
- addonId: string().optional(),
19072
- /** Explicit profile; else the resolution chain (spec §3). */
19073
- profileId: string().optional(),
19074
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
19075
- consumer: string(),
19076
- system: string().optional(),
19077
- /** v1: single-turn. `messages[]` is a v2 additive field. */
19078
- prompt: string(),
19079
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
19080
- jsonSchema: record(string(), unknown()).optional(),
19081
- /** Per-call override of the profile default. */
19082
- maxTokens: number().int().positive().optional(),
19083
- temperature: number().optional()
19084
- });
19085
- /**
19086
- * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
19087
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
19088
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
19089
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
19090
- * this only through the `llm` cap's methods.
19091
- *
19092
- * One running llama-server child per node in v1 (models are RAM-heavy).
19093
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
19094
- * watchdog — operator decision #3).
19095
- */
19096
- var ManagedModelRefSchema = discriminatedUnion("kind", [
19097
- object({
19098
- kind: literal("catalog"),
19099
- catalogId: string()
19100
- }),
19101
- object({
19102
- kind: literal("url"),
19103
- url: string(),
19104
- sha256: string().optional()
19105
- }),
19106
- object({
19107
- kind: literal("path"),
19108
- path: string()
19109
- })
19110
- ]);
19111
- var ManagedRuntimeConfigSchema = object({
19112
- /** WHERE the runtime lives — hub or any agent. */
19113
- nodeId: string(),
19114
- /** Closed for v1; 'ollama' is a v2 candidate. */
19115
- engine: _enum(["llama-cpp"]),
19116
- model: ManagedModelRefSchema,
19117
- contextSize: number().int().default(4096),
19118
- /** 0 = CPU-only. */
19119
- gpuLayers: number().int().default(0),
19120
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
19121
- threads: number().int().optional(),
19122
- /** Concurrent slots. */
19123
- parallel: number().int().default(1),
19124
- /** Else lazy: first generate boots it. */
19125
- autoStart: boolean().default(false),
19126
- /** 0 = never; frees RAM after quiet periods. */
19127
- idleStopMinutes: number().int().default(30)
19128
- });
19129
- var LlmRuntimeStatusSchema = object({
19130
- /** Status is ALWAYS node-qualified. */
19131
- nodeId: string(),
19132
- state: _enum([
19133
- "stopped",
19134
- "downloading",
19135
- "starting",
19136
- "ready",
19137
- "crashed",
19138
- "failed"
19139
- ]),
19140
- pid: number().optional(),
19141
- port: number().optional(),
19142
- modelPath: string().optional(),
19143
- modelId: string().optional(),
19144
- downloadProgress: number().min(0).max(1).optional(),
19145
- lastError: string().optional(),
19146
- crashesInWindow: number(),
19147
- /** Child RSS (sampled best-effort). */
19148
- memoryBytes: number().optional(),
19149
- vramBytes: number().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()
19150
19243
  });
19151
- var LlmNodeModelSchema = object({
19152
- file: string(),
19153
- sizeBytes: number(),
19154
- catalogId: string().optional(),
19155
- 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()
19156
19264
  });
19157
- var LlmRuntimeDiskUsageSchema = object({
19158
- nodeId: string(),
19159
- modelsBytes: number(),
19160
- 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
19161
19282
  });
19162
- method(LlmGenerateBaseInputSchema.extend({
19163
- images: array(LlmImageSchema).optional(),
19164
- runtime: ManagedRuntimeConfigSchema,
19165
- /** The managed profile's timeout, threaded by the hub provider. */
19166
- timeoutMs: number().int().positive().optional()
19167
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
19168
- kind: "mutation",
19169
- auth: "admin"
19170
- }), method(object({}), _void(), {
19171
- kind: "mutation",
19172
- auth: "admin"
19173
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
19174
- kind: "mutation",
19175
- auth: "admin"
19176
- }), method(object({ file: string() }), _void(), {
19177
- kind: "mutation",
19178
- auth: "admin"
19179
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
19180
19283
  /**
19181
- * `llm` consumer-facing LLM surface (spec §1-§3). Collection-mode: array
19182
- * methods concat-fan across providers; single-row methods route to ONE
19183
- * provider by the `addonId` in the call input (the notification-output
19184
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
19185
- * (hub-placed); the cap stays open for future providers.
19186
- *
19187
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
19188
- * `apiKey` is a password field — providers REDACT it on read and merge on
19189
- * 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.
19190
19287
  */
19191
- var LlmProfileKindSchema = _enum([
19192
- "openai-compatible",
19193
- "openai",
19194
- "anthropic",
19195
- "google",
19196
- "managed-local"
19197
- ]);
19198
- var LlmProfileSchema = object({
19288
+ var TargetSchema = object({
19199
19289
  id: string(),
19200
19290
  name: string(),
19201
- kind: LlmProfileKindSchema,
19202
- /** Stamped by the provider — keeps the fanned catalog routable. */
19291
+ kind: string(),
19203
19292
  addonId: string(),
19204
19293
  enabled: boolean(),
19205
- /** Vendor model id, or the managed runtime's loaded model. */
19206
- model: string(),
19207
- /** Required for openai-compatible; override for cloud kinds. */
19208
- baseUrl: string().optional(),
19209
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
19210
- apiKey: string().optional(),
19211
- supportsVision: boolean(),
19212
- temperature: number().min(0).max(2).optional(),
19213
- maxTokens: number().int().positive().optional(),
19214
- timeoutMs: number().int().positive().default(6e4),
19215
- extraHeaders: record(string(), string()).optional(),
19216
- /** kind === 'managed-local' only (spec §4). */
19217
- runtime: ManagedRuntimeConfigSchema.optional()
19294
+ config: record(string(), unknown())
19218
19295
  });
19219
- /** ConfigUISchema tree passed through untyped on the wire (the
19220
- * notification-output `ConfigSchemaPassthrough` precedent at
19221
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
19222
- var ConfigSchemaPassthrough = unknown();
19223
- var LlmProfileKindDescriptorSchema = object({
19224
- kind: LlmProfileKindSchema,
19225
- label: string(),
19226
- icon: string(),
19227
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
19228
- addonId: string(),
19229
- 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())
19230
19301
  });
19231
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
19232
- var LlmDefaultSchema = object({
19233
- selector: LlmDefaultSelectorSchema,
19234
- 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())
19235
19310
  });
19236
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
19237
- var LlmUsageRollupSchema = object({
19238
- day: string(),
19239
- consumer: string(),
19240
- profileId: string(),
19241
- calls: number(),
19242
- okCalls: number(),
19243
- errorCalls: number(),
19244
- inputTokens: number(),
19245
- outputTokens: number(),
19246
- avgLatencyMs: number()
19311
+ var SendResultSchema = object({
19312
+ success: boolean(),
19313
+ error: string().optional(),
19314
+ renderedAs: RenderedAsSchema.optional()
19247
19315
  });
19248
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
19249
- 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). */
19250
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
+ ]),
19251
19679
  label: string(),
19252
- family: string(),
19253
- purpose: _enum(["text", "vision"]),
19254
- url: string(),
19255
- sha256: string(),
19256
- sizeBytes: number(),
19257
- quantization: string(),
19258
- /** Load-time guidance shown in the picker. */
19259
- minRamBytes: number(),
19260
- contextSizeDefault: number().int(),
19261
- /** Vision models: companion projector file. */
19262
- 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()
19263
19708
  });
19264
- var LlmRuntimeNodeSchema = object({
19265
- nodeId: string(),
19266
- reachable: boolean(),
19267
- status: LlmRuntimeStatusSchema.optional(),
19268
- disk: LlmRuntimeDiskUsageSchema.optional(),
19269
- 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()
19740
+ });
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
19270
19777
  });
19271
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
19272
- var ProfileRefInputSchema = object({
19273
- addonId: string(),
19274
- profileId: string()
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(),
19788
+ since: number().optional(),
19789
+ until: number().optional(),
19790
+ limit: number().int().min(1).max(500).default(100)
19275
19791
  });
19276
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
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 }), {
19277
19793
  kind: "mutation",
19278
- auth: "admin"
19279
- }), method(ProfileRefInputSchema, _void(), {
19280
- kind: "mutation",
19281
- auth: "admin"
19282
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
19794
+ auth: "admin",
19795
+ caller: "required"
19796
+ }), method(object({
19797
+ ruleId: string(),
19798
+ patch: NcRulePatchSchema
19799
+ }), object({ rule: NcRuleSchema }), {
19283
19800
  kind: "mutation",
19284
- auth: "admin"
19285
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
19286
- selector: LlmDefaultSelectorSchema,
19287
- profileId: string().nullable()
19288
- }), _void(), {
19801
+ auth: "admin",
19802
+ caller: "required"
19803
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
19289
19804
  kind: "mutation",
19290
19805
  auth: "admin"
19291
19806
  }), method(object({
19292
- since: number().optional(),
19293
- until: number().optional(),
19294
- consumer: string().optional(),
19295
- profileId: string().optional()
19296
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
19297
- nodeId: string(),
19298
- model: ManagedModelRefSchema
19299
- }), _void(), {
19807
+ ruleId: string(),
19808
+ enabled: boolean()
19809
+ }), object({ success: literal(true) }), {
19300
19810
  kind: "mutation",
19301
19811
  auth: "admin"
19302
19812
  }), method(object({
19303
- nodeId: string(),
19304
- file: string()
19305
- }), _void(), {
19306
- kind: "mutation",
19307
- auth: "admin"
19308
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
19309
- kind: "mutation",
19310
- auth: "admin"
19311
- }), method(ProfileRefInputSchema, _void(), {
19813
+ rule: NcRuleInputSchema,
19814
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
19815
+ }), object({ results: array(NcTestResultSchema) }), {
19312
19816
  kind: "mutation",
19313
19817
  auth: "admin"
19314
- });
19818
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
19315
19819
  /**
19316
19820
  * Zod schemas for persisted record types.
19317
19821
  *
@@ -19997,7 +20501,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19997
20501
  }), method(object({
19998
20502
  eventId: string(),
19999
20503
  kind: MediaFileKindEnum.optional()
20000
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
20504
+ }), array(MediaFileSchema).readonly()), method(object({
20505
+ trackId: string(),
20506
+ kinds: array(MediaFileKindEnum).optional()
20507
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
20001
20508
  deviceId: number(),
20002
20509
  timestamp: number(),
20003
20510
  frameWidth: number(),
@@ -20018,76 +20525,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
20018
20525
  eventId: string(),
20019
20526
  timestamp: number()
20020
20527
  });
20021
- /**
20022
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
20023
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
20024
- * caps into per-camera event-kind descriptors.
20025
- *
20026
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
20027
- * is NOT duplicated here — every entry is derived from the single
20028
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
20029
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
20030
- * control cap means adding one line here (and a taxonomy entry); the anti-
20031
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
20032
- * eventful cap is missing.
20033
- */
20034
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
20035
- var LEGACY_ICON = {
20036
- motion: "motion",
20037
- audio: "audio",
20038
- person: "person",
20039
- vehicle: "vehicle",
20040
- animal: "animal",
20041
- package: "package",
20042
- door: "door",
20043
- pir: "pir",
20044
- smoke: "smoke",
20045
- water: "water",
20046
- button: "button",
20047
- generic: "generic",
20048
- gas: "smoke",
20049
- vibration: "generic",
20050
- tamper: "generic",
20051
- presence: "person",
20052
- lock: "generic",
20053
- siren: "generic",
20054
- switch: "generic",
20055
- doorbell: "button"
20056
- };
20057
- function legacyIcon(iconId) {
20058
- return LEGACY_ICON[iconId] ?? "generic";
20059
- }
20060
- /**
20061
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
20062
- * The anti-drift guard cross-checks this against the eventful caps declared
20063
- * in `packages/types/src/capabilities/*.cap.ts`.
20064
- */
20065
- var CAP_TO_KIND = {
20066
- contact: "contact",
20067
- motion: "motion-sensor",
20068
- smoke: "smoke",
20069
- flood: "flood",
20070
- gas: "gas",
20071
- "carbon-monoxide": "carbon-monoxide",
20072
- vibration: "vibration",
20073
- tamper: "tamper",
20074
- presence: "presence",
20075
- "enum-sensor": "enum-sensor",
20076
- "event-emitter": "device-event",
20077
- "lock-control": "lock",
20078
- switch: "switch",
20079
- button: "button",
20080
- doorbell: "doorbell"
20081
- };
20082
- function buildDescriptor(capName, kind) {
20083
- const t = EVENT_TAXONOMY[kind];
20084
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
20085
- return {
20086
- ...t,
20087
- icon: legacyIcon(t.iconId)
20088
- };
20089
- }
20090
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
20091
20528
  var CameraPipelineConfigSchema = object({
20092
20529
  engine: PipelineEngineChoiceSchema.optional(),
20093
20530
  steps: array(PipelineStepInputSchema).readonly(),
@@ -20573,6 +21010,76 @@ method(object({
20573
21010
  auth: "admin"
20574
21011
  });
20575
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
+ /**
20576
21083
  * server-management — per-NODE singleton capability for a node's ROOT
20577
21084
  * package lifecycle (runtime-updatable node packages).
20578
21085
  *
@@ -22078,7 +22585,28 @@ var FaceInfoSchema = object({
22078
22585
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
22079
22586
  * track produced no key frame (e.g. native/onboard source) — the UI falls
22080
22587
  * back to the inline `base64` face crop. */
22081
- 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()
22082
22610
  });
22083
22611
  var FaceFilterEnum = _enum([
22084
22612
  "unassigned",
@@ -24496,36 +25024,6 @@ Object.freeze({
24496
25024
  addonId: null,
24497
25025
  access: "view"
24498
25026
  },
24499
- "advancedNotifier.deleteRule": {
24500
- capName: "advanced-notifier",
24501
- capScope: "system",
24502
- addonId: null,
24503
- access: "delete"
24504
- },
24505
- "advancedNotifier.getHistory": {
24506
- capName: "advanced-notifier",
24507
- capScope: "system",
24508
- addonId: null,
24509
- access: "view"
24510
- },
24511
- "advancedNotifier.getRules": {
24512
- capName: "advanced-notifier",
24513
- capScope: "system",
24514
- addonId: null,
24515
- access: "view"
24516
- },
24517
- "advancedNotifier.testRule": {
24518
- capName: "advanced-notifier",
24519
- capScope: "system",
24520
- addonId: null,
24521
- access: "create"
24522
- },
24523
- "advancedNotifier.upsertRule": {
24524
- capName: "advanced-notifier",
24525
- capScope: "system",
24526
- addonId: null,
24527
- access: "create"
24528
- },
24529
25027
  "alarmPanel.arm": {
24530
25028
  capName: "alarm-panel",
24531
25029
  capScope: "device",
@@ -26830,6 +27328,60 @@ Object.freeze({
26830
27328
  addonId: null,
26831
27329
  access: "create"
26832
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
+ },
26833
27385
  "notifier.cancel": {
26834
27386
  capName: "notifier",
26835
27387
  capScope: "device",
@@ -31195,13 +31747,44 @@ function parseTwoWayAudioChannels(xml) {
31195
31747
  return out;
31196
31748
  }
31197
31749
  /**
31750
+ * Idle watchdog for the alarm stream. Hikvision firmware emits a keep-alive
31751
+ * heartbeat (typically a `videoloss`/`inactive` alert) roughly every ~5s even
31752
+ * when nothing is happening, so a total absence of ANY bytes for this long
31753
+ * means the pipe is dead — either a half-open TCP connection (no FIN, no data)
31754
+ * that would otherwise block `reader.read()` forever, or a stalled proxy/NAT
31755
+ * conntrack entry between the hub and a camera on a different subnet. When it
31756
+ * fires we cancel the reader, surfacing a clean stream-end that the reconnect
31757
+ * path treats as a recoverable disconnect.
31758
+ */
31759
+ var ALARM_STREAM_IDLE_TIMEOUT_MS = 3e4;
31760
+ /**
31198
31761
  * Subscribe to the camera's alarm stream. Returns an `AbortController`
31199
31762
  * — `controller.abort()` tears the subscription down. Reconnect logic
31200
31763
  * is the caller's responsibility (we keep the parser simple and let
31201
31764
  * the device class own the lifecycle / backoff timing).
31202
- */
31203
- function subscribeAlarms(client, handlers) {
31765
+ *
31766
+ * Every terminal outcome that is NOT a deliberate `controller.abort()` is
31767
+ * reported through `onError` exactly once, so the caller's reconnect logic
31768
+ * always fires:
31769
+ * - HTTP / boundary failure at subscribe time,
31770
+ * - a thrown error while pumping,
31771
+ * - AND a clean stream-end (`done`). Hikvision cameras recycle the
31772
+ * alertStream HTTP connection periodically (firmware keep-alive limits,
31773
+ * internal event-subsystem restarts, or an idle NAT/proxy hop closing the
31774
+ * socket). A clean close used to fall through silently — `onError` never
31775
+ * fired, the caller's `alarmController` stayed non-null, and the device
31776
+ * never resubscribed — so motion stopped permanently until the provider
31777
+ * restarted. Treating clean-end as a recoverable disconnect closes that gap.
31778
+ */
31779
+ function subscribeAlarms(client, handlers, idleTimeoutMs = ALARM_STREAM_IDLE_TIMEOUT_MS) {
31204
31780
  const controller = new AbortController();
31781
+ let settled = false;
31782
+ const fail = (err) => {
31783
+ if (settled) return;
31784
+ settled = true;
31785
+ if (controller.signal.aborted) return;
31786
+ handlers.onError(err);
31787
+ };
31205
31788
  (async () => {
31206
31789
  try {
31207
31790
  const res = await client.request("/ISAPI/Event/notification/alertStream", {
@@ -31210,20 +31793,20 @@ function subscribeAlarms(client, handlers) {
31210
31793
  timeoutMs: null
31211
31794
  });
31212
31795
  if (!res.ok || !res.body) {
31213
- handlers.onError(/* @__PURE__ */ new Error(`alarm stream HTTP ${res.status}`));
31796
+ fail(/* @__PURE__ */ new Error(`alarm stream HTTP ${res.status}`));
31214
31797
  return;
31215
31798
  }
31216
31799
  const ct = res.headers.get("content-type") ?? "";
31217
31800
  const boundary = parseBoundary(ct);
31218
31801
  if (!boundary) {
31219
- handlers.onError(/* @__PURE__ */ new Error(`alarm stream missing multipart boundary in Content-Type: "${ct}"`));
31802
+ fail(/* @__PURE__ */ new Error(`alarm stream missing multipart boundary in Content-Type: "${ct}"`));
31220
31803
  return;
31221
31804
  }
31222
31805
  handlers.onConnected?.();
31223
- await pumpAlarmStream(res.body, boundary, handlers);
31806
+ await pumpAlarmStream(res.body, boundary, handlers, idleTimeoutMs);
31807
+ fail(/* @__PURE__ */ new Error("alarm stream ended"));
31224
31808
  } catch (err) {
31225
- if (controller.signal.aborted) return;
31226
- handlers.onError(err);
31809
+ fail(err);
31227
31810
  }
31228
31811
  })();
31229
31812
  return controller;
@@ -31232,14 +31815,24 @@ function parseBoundary(contentType) {
31232
31815
  const m = /boundary\s*=\s*"?([^";\s]+)"?/i.exec(contentType);
31233
31816
  return m ? m[1].trim() : null;
31234
31817
  }
31235
- async function pumpAlarmStream(stream, boundary, handlers) {
31818
+ async function pumpAlarmStream(stream, boundary, handlers, idleTimeoutMs = ALARM_STREAM_IDLE_TIMEOUT_MS) {
31236
31819
  const reader = stream.getReader();
31237
31820
  const dashBoundary = `--${boundary}`;
31238
31821
  let bufferedBytes = new Uint8Array(0);
31822
+ let idleTimer = null;
31823
+ const armIdle = () => {
31824
+ if (idleTimeoutMs <= 0) return;
31825
+ if (idleTimer) clearTimeout(idleTimer);
31826
+ idleTimer = setTimeout(() => {
31827
+ reader.cancel().catch(() => {});
31828
+ }, idleTimeoutMs);
31829
+ };
31239
31830
  try {
31831
+ armIdle();
31240
31832
  while (true) {
31241
31833
  const { value, done } = await reader.read();
31242
31834
  if (done) break;
31835
+ armIdle();
31243
31836
  if (!value || value.byteLength === 0) continue;
31244
31837
  bufferedBytes = concat(bufferedBytes, value);
31245
31838
  const parts = splitOnBoundary(bufferedBytes, dashBoundary);
@@ -31254,6 +31847,7 @@ async function pumpAlarmStream(stream, boundary, handlers) {
31254
31847
  }
31255
31848
  }
31256
31849
  } finally {
31850
+ if (idleTimer) clearTimeout(idleTimer);
31257
31851
  try {
31258
31852
  reader.releaseLock();
31259
31853
  } catch {}