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