@camstack/addon-provider-reolink 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 +1635 -698
  2. package/dist/addon.mjs +1635 -698
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -21,7 +21,7 @@ import netImpl from "net";
21
21
  import { fileURLToPath } from "url";
22
22
  import { mkdir } from "fs/promises";
23
23
  import os from "node:os";
24
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
24
+ //#region ../types/dist/event-category-BLcNejAE.mjs
25
25
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
26
26
  EventCategory["SystemBoot"] = "system.boot";
27
27
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -171,9 +171,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
171
171
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
172
172
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
173
173
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
174
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
175
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
176
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
177
174
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
178
175
  * progress bar the client reconciles via `recordingExport.getExport`. */
179
176
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6838,7 +6835,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6838
6835
  patch: record(string(), unknown())
6839
6836
  }), object({ success: literal(true) });
6840
6837
  object({ deviceId: number() }), unknown().nullable();
6841
- /** Shorthand to define a method schema */
6842
6838
  function method(input, output, options) {
6843
6839
  return {
6844
6840
  input,
@@ -6846,6 +6842,7 @@ function method(input, output, options) {
6846
6842
  kind: options?.kind ?? "query",
6847
6843
  auth: options?.auth ?? "protected",
6848
6844
  ...options?.access !== void 0 ? { access: options.access } : {},
6845
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6849
6846
  timeoutMs: options?.timeoutMs
6850
6847
  };
6851
6848
  }
@@ -8402,6 +8399,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8402
8399
  /** The complete taxonomy dictionary, keyed by kind. */
8403
8400
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8404
8401
  /**
8402
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8403
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8404
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8405
+ * taxonomy surface (timeline, filters, event page).
8406
+ *
8407
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8408
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8409
+ * for the `classes` / `classesExclude` conditions.
8410
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8411
+ * the same class picker, grouped under an Audio header.
8412
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8413
+ * lock / …) for the `sensorKinds` device-event condition.
8414
+ *
8415
+ * Each entry carries `parentKind` so the client can group video subs under
8416
+ * their macro and sensor/control kinds under their category. This surface is
8417
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8418
+ * method, no codegen — so it ships train-free with an addon deploy.
8419
+ */
8420
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8421
+ var NcTaxonomyEntrySchema = object({
8422
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8423
+ kind: string(),
8424
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8425
+ label: string(),
8426
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8427
+ parentKind: string().nullable()
8428
+ });
8429
+ object({
8430
+ videoClasses: array(NcTaxonomyEntrySchema),
8431
+ audioKinds: array(NcTaxonomyEntrySchema),
8432
+ labels: array(NcTaxonomyEntrySchema)
8433
+ });
8434
+ function toEntry(kind, label, parentKind) {
8435
+ return {
8436
+ kind,
8437
+ label,
8438
+ parentKind
8439
+ };
8440
+ }
8441
+ /**
8442
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8443
+ * (macros before their subs), which the client relies on for stable grouping.
8444
+ */
8445
+ function buildNcTaxonomy() {
8446
+ const all = Object.values(EVENT_TAXONOMY);
8447
+ return {
8448
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8449
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8450
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8451
+ };
8452
+ }
8453
+ Object.freeze(buildNcTaxonomy());
8454
+ /**
8405
8455
  * Error types for the safe expression engine. Two distinct classes so callers
8406
8456
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8407
8457
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -12426,6 +12476,22 @@ var CameraMetricsSchema = object({
12426
12476
  ])
12427
12477
  });
12428
12478
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
12479
+ /**
12480
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
12481
+ * within the frame, so the executor can re-cut a leaf child ROI at native
12482
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
12483
+ */
12484
+ var NativeCropRefSchema = object({
12485
+ /** Handle keying the retained native surface (node-pinned to its owner). */
12486
+ handle: FrameHandleSchema,
12487
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
12488
+ cropFrameSpace: object({
12489
+ x: number(),
12490
+ y: number(),
12491
+ w: number(),
12492
+ h: number()
12493
+ })
12494
+ });
12429
12495
  var ModelFormatSchema$1 = _enum([
12430
12496
  "onnx",
12431
12497
  "coreml",
@@ -12701,7 +12767,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
12701
12767
  * Omitted ⇒ the runner's default device (current single-engine
12702
12768
  * behaviour). Selects WHICH device pool of the node runs the call.
12703
12769
  */
12704
- deviceKey: string().optional()
12770
+ deviceKey: string().optional(),
12771
+ /**
12772
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
12773
+ * when the parent crop was resolved from the frame's retained NATIVE
12774
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
12775
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
12776
+ * resolution from that surface — the SAME quality path faces already
12777
+ * had — instead of the downscaled parent tile. `handle` keys the native
12778
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
12779
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
12780
+ * the executor's crop-normalized child ROI back into frame-normalized
12781
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
12782
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
12783
+ * (today's behaviour on the fallback path).
12784
+ */
12785
+ nativeCropRef: NativeCropRefSchema.optional()
12705
12786
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
12706
12787
  engine: PipelineEngineChoiceSchema.optional(),
12707
12788
  steps: array(PipelineStepInputSchema).min(1),
@@ -12950,7 +13031,11 @@ var DetailResultSchema = object({
12950
13031
  bbox: NativeCropBboxSchema.optional(),
12951
13032
  embedding: string().optional(),
12952
13033
  label: string().optional(),
12953
- alignedCropJpeg: string().optional()
13034
+ alignedCropJpeg: string().optional(),
13035
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
13036
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
13037
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
13038
+ nativeFaceShortSidePx: number().optional()
12954
13039
  });
12955
13040
  /**
12956
13041
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -12964,6 +13049,12 @@ var motionCooldownMsField = {
12964
13049
  default: 3e4,
12965
13050
  step: 500
12966
13051
  };
13052
+ var maxSessionHoldMsField = {
13053
+ min: 0,
13054
+ max: 6e5,
13055
+ default: 12e4,
13056
+ step: 5e3
13057
+ };
12967
13058
  var motionFpsField = {
12968
13059
  min: 1,
12969
13060
  max: 30,
@@ -13111,6 +13202,19 @@ var RunnerCameraConfigSchema = object({
13111
13202
  "on-motion"
13112
13203
  ]).default("always-on"),
13113
13204
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
13205
+ /**
13206
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
13207
+ * detection session is active and ≥1 confirmed non-stationary track is
13208
+ * still live, the orchestrator keeps the session open past
13209
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
13210
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
13211
+ * ms since the session opened, after which it closes regardless. `0`
13212
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
13213
+ * runner itself — carried here so it shares the per-camera device-settings
13214
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
13215
+ * resolved `CameraDetectionConfig`.
13216
+ */
13217
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
13114
13218
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
13115
13219
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
13116
13220
  motionStreamId: string(),
@@ -13200,7 +13304,7 @@ var RunnerCameraConfigSchema = object({
13200
13304
  */
13201
13305
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
13202
13306
  });
13203
- 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;
13307
+ 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;
13204
13308
  /**
13205
13309
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
13206
13310
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -16727,94 +16831,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
16727
16831
  bundleUrl: string()
16728
16832
  });
16729
16833
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
16730
- var NotificationRuleConditionsSchema = object({
16731
- deviceIds: array(number()).readonly().optional(),
16732
- classNames: array(string()).readonly().optional(),
16733
- zoneIds: array(string()).readonly().optional(),
16734
- minConfidence: number().optional(),
16735
- source: _enum([
16736
- "pipeline",
16737
- "onboard",
16738
- "any"
16739
- ]).optional(),
16740
- schedule: object({
16741
- days: array(number()).readonly(),
16742
- startHour: number(),
16743
- endHour: number()
16744
- }).optional(),
16745
- cooldownSeconds: number().optional(),
16746
- minDwellSeconds: number().optional(),
16747
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
16748
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
16749
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
16750
- eventTypeTokens: array(string()).readonly().optional(),
16751
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
16752
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
16753
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
16754
- clipDescription: object({
16755
- text: string().min(1),
16756
- minSimilarity: number().min(0).max(1)
16757
- }).optional(),
16758
- /** Match events whose recognized-entity label (face identity name or plate
16759
- * vehicle name, propagated onto `event.data.label`) is one of these values.
16760
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
16761
- * vehicle/person> is seen". */
16762
- labels: array(string()).readonly().optional()
16763
- });
16764
- var NotificationRuleTemplateSchema = object({
16765
- title: string(),
16766
- body: string(),
16767
- imageMode: _enum([
16768
- "crop",
16769
- "annotated",
16770
- "full",
16771
- "none"
16772
- ])
16773
- });
16774
- var NotificationRuleSchema = object({
16775
- id: string(),
16776
- name: string(),
16777
- enabled: boolean(),
16778
- eventTypes: array(string()).readonly(),
16779
- conditions: NotificationRuleConditionsSchema,
16780
- outputs: array(string()).readonly(),
16781
- template: NotificationRuleTemplateSchema.optional(),
16782
- priority: _enum([
16783
- "low",
16784
- "normal",
16785
- "high",
16786
- "critical"
16787
- ])
16788
- });
16789
- var NotificationTestResultSchema = object({
16790
- ruleId: string(),
16791
- eventId: string(),
16792
- timestamp: number(),
16793
- wouldFire: boolean(),
16794
- reason: string().optional()
16795
- });
16796
- var NotificationHistoryEntrySchema = object({
16797
- id: string(),
16798
- ruleId: string(),
16799
- ruleName: string(),
16800
- eventId: string(),
16801
- timestamp: number(),
16802
- outputs: array(string()).readonly(),
16803
- success: boolean(),
16804
- error: string().optional(),
16805
- deviceId: number().optional()
16806
- });
16807
- var NotificationHistoryFilterSchema = object({
16808
- ruleId: string().optional(),
16809
- deviceId: number().optional(),
16810
- from: number().optional(),
16811
- to: number().optional(),
16812
- limit: number().optional()
16813
- });
16814
- 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({
16815
- ruleId: string(),
16816
- lookbackMinutes: number()
16817
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
16818
16834
  /**
16819
16835
  * Alerts capability — collection-based internal alert system.
16820
16836
  *
@@ -17001,89 +17017,6 @@ method(object({
17001
17017
  password: string()
17002
17018
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
17003
17019
  /**
17004
- * `login-method` — collection cap through which auth addons contribute
17005
- * their pre-auth login surfaces to the login page. This is the SINGLE,
17006
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
17007
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
17008
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
17009
- * procedure aggregates them for the unauthenticated login page.
17010
- *
17011
- * A contribution is a discriminated union on `kind`:
17012
- *
17013
- * - `redirect` — a declarative button. The login page renders a generic
17014
- * button that navigates to `startUrl` (an addon-owned HTTP route).
17015
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
17016
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
17017
- * login page needs NO change.
17018
- *
17019
- * - `widget` — a Module-Federation widget the login page mounts (via
17020
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
17021
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
17022
- * mechanism kept for future use; no shipped addon uses it on the login
17023
- * page (the passkey ceremony below runs natively in the shell instead).
17024
- *
17025
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
17026
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
17027
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
17028
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
17029
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
17030
- * fetching any remote code pre-auth. Contribution stays unconditional —
17031
- * enrollment state is never leaked pre-auth; visibility is a shell
17032
- * decision.
17033
- *
17034
- * Every contribution carries a `stage`:
17035
- * - `primary` — shown on the first credentials screen (OIDC /
17036
- * magic-link buttons; a future usernameless passkey).
17037
- * - `second-factor` — shown AFTER the password leg, gated on the
17038
- * returned `factors` (passkey-as-2FA today).
17039
- *
17040
- * `mount: skip` — the cap is read server-side by the core auth router
17041
- * (`registry.getCollection('login-method')`), never mounted as its own
17042
- * tRPC router.
17043
- */
17044
- /** When a login method renders in the two-phase login flow. */
17045
- var LoginStageEnum = _enum(["primary", "second-factor"]);
17046
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
17047
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
17048
- object({
17049
- kind: literal("redirect"),
17050
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
17051
- id: string(),
17052
- /** Operator-facing button label. */
17053
- label: string(),
17054
- /** lucide-react icon name. */
17055
- icon: string().optional(),
17056
- /** Addon-owned HTTP route the button navigates to (GET). */
17057
- startUrl: string(),
17058
- stage: LoginStageEnum
17059
- }),
17060
- object({
17061
- kind: literal("widget"),
17062
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
17063
- id: string(),
17064
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
17065
- addonId: string(),
17066
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
17067
- bundle: string(),
17068
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
17069
- remote: WidgetRemoteSchema,
17070
- stage: LoginStageEnum
17071
- }),
17072
- object({
17073
- kind: literal("passkey"),
17074
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
17075
- id: string(),
17076
- /** Operator-facing button label. */
17077
- label: string(),
17078
- stage: LoginStageEnum,
17079
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
17080
- rpId: string(),
17081
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
17082
- origin: string().nullable()
17083
- })
17084
- ]);
17085
- method(_void(), array(LoginMethodContributionSchema).readonly());
17086
- /**
17087
17020
  * Orchestrator-side destination metadata. The orchestrator computes
17088
17021
  * `id = <addonId>:<subId>` from its provider lookup so consumers
17089
17022
  * (admin UI, restore flow) see one canonical key.
@@ -18439,6 +18372,298 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
18439
18372
  kind: "mutation",
18440
18373
  auth: "admin"
18441
18374
  });
18375
+ /**
18376
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18377
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18378
+ * caps stay wire-compatible without a circular cap→cap import.
18379
+ *
18380
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
18381
+ * every transport tier structurally, and failed calls still write usage rows.
18382
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18383
+ */
18384
+ var LlmUsageSchema = object({
18385
+ inputTokens: number(),
18386
+ outputTokens: number()
18387
+ });
18388
+ var LlmErrorCodeSchema = _enum([
18389
+ "timeout",
18390
+ "rate-limited",
18391
+ "auth",
18392
+ "refusal",
18393
+ "bad-request",
18394
+ "unavailable",
18395
+ "no-profile",
18396
+ "budget-exceeded",
18397
+ "adapter-error"
18398
+ ]);
18399
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18400
+ ok: literal(true),
18401
+ text: string(),
18402
+ model: string(),
18403
+ usage: LlmUsageSchema,
18404
+ truncated: boolean(),
18405
+ latencyMs: number()
18406
+ }), object({
18407
+ ok: literal(false),
18408
+ code: LlmErrorCodeSchema,
18409
+ message: string(),
18410
+ retryAfterMs: number().optional()
18411
+ })]);
18412
+ /**
18413
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18414
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18415
+ * notification-output.cap.ts:27-31 precedents).
18416
+ */
18417
+ var LlmImageSchema = object({
18418
+ bytes: _instanceof(Uint8Array),
18419
+ mimeType: string()
18420
+ });
18421
+ var LlmGenerateBaseInputSchema = object({
18422
+ /** Collection routing (the notification-output posture). */
18423
+ addonId: string().optional(),
18424
+ /** Explicit profile; else the resolution chain (spec §3). */
18425
+ profileId: string().optional(),
18426
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18427
+ consumer: string(),
18428
+ system: string().optional(),
18429
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
18430
+ prompt: string(),
18431
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18432
+ jsonSchema: record(string(), unknown()).optional(),
18433
+ /** Per-call override of the profile default. */
18434
+ maxTokens: number().int().positive().optional(),
18435
+ temperature: number().optional()
18436
+ });
18437
+ /**
18438
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18439
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18440
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18441
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18442
+ * this only through the `llm` cap's methods.
18443
+ *
18444
+ * One running llama-server child per node in v1 (models are RAM-heavy).
18445
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18446
+ * watchdog — operator decision #3).
18447
+ */
18448
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
18449
+ object({
18450
+ kind: literal("catalog"),
18451
+ catalogId: string()
18452
+ }),
18453
+ object({
18454
+ kind: literal("url"),
18455
+ url: string(),
18456
+ sha256: string().optional()
18457
+ }),
18458
+ object({
18459
+ kind: literal("path"),
18460
+ path: string()
18461
+ })
18462
+ ]);
18463
+ var ManagedRuntimeConfigSchema = object({
18464
+ /** WHERE the runtime lives — hub or any agent. */
18465
+ nodeId: string(),
18466
+ /** Closed for v1; 'ollama' is a v2 candidate. */
18467
+ engine: _enum(["llama-cpp"]),
18468
+ model: ManagedModelRefSchema,
18469
+ contextSize: number().int().default(4096),
18470
+ /** 0 = CPU-only. */
18471
+ gpuLayers: number().int().default(0),
18472
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18473
+ threads: number().int().optional(),
18474
+ /** Concurrent slots. */
18475
+ parallel: number().int().default(1),
18476
+ /** Else lazy: first generate boots it. */
18477
+ autoStart: boolean().default(false),
18478
+ /** 0 = never; frees RAM after quiet periods. */
18479
+ idleStopMinutes: number().int().default(30)
18480
+ });
18481
+ var LlmRuntimeStatusSchema = object({
18482
+ /** Status is ALWAYS node-qualified. */
18483
+ nodeId: string(),
18484
+ state: _enum([
18485
+ "stopped",
18486
+ "downloading",
18487
+ "starting",
18488
+ "ready",
18489
+ "crashed",
18490
+ "failed"
18491
+ ]),
18492
+ pid: number().optional(),
18493
+ port: number().optional(),
18494
+ modelPath: string().optional(),
18495
+ modelId: string().optional(),
18496
+ downloadProgress: number().min(0).max(1).optional(),
18497
+ lastError: string().optional(),
18498
+ crashesInWindow: number(),
18499
+ /** Child RSS (sampled best-effort). */
18500
+ memoryBytes: number().optional(),
18501
+ vramBytes: number().optional()
18502
+ });
18503
+ var LlmNodeModelSchema = object({
18504
+ file: string(),
18505
+ sizeBytes: number(),
18506
+ catalogId: string().optional(),
18507
+ installedAt: number().optional()
18508
+ });
18509
+ var LlmRuntimeDiskUsageSchema = object({
18510
+ nodeId: string(),
18511
+ modelsBytes: number(),
18512
+ freeBytes: number().optional()
18513
+ });
18514
+ method(LlmGenerateBaseInputSchema.extend({
18515
+ images: array(LlmImageSchema).optional(),
18516
+ runtime: ManagedRuntimeConfigSchema,
18517
+ /** The managed profile's timeout, threaded by the hub provider. */
18518
+ timeoutMs: number().int().positive().optional()
18519
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18520
+ kind: "mutation",
18521
+ auth: "admin"
18522
+ }), method(object({}), _void(), {
18523
+ kind: "mutation",
18524
+ auth: "admin"
18525
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18526
+ kind: "mutation",
18527
+ auth: "admin"
18528
+ }), method(object({ file: string() }), _void(), {
18529
+ kind: "mutation",
18530
+ auth: "admin"
18531
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18532
+ /**
18533
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18534
+ * methods concat-fan across providers; single-row methods route to ONE
18535
+ * provider by the `addonId` in the call input (the notification-output
18536
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18537
+ * (hub-placed); the cap stays open for future providers.
18538
+ *
18539
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18540
+ * `apiKey` is a password field — providers REDACT it on read and merge on
18541
+ * write; a stored key NEVER round-trips to a client.
18542
+ */
18543
+ var LlmProfileKindSchema = _enum([
18544
+ "openai-compatible",
18545
+ "openai",
18546
+ "anthropic",
18547
+ "google",
18548
+ "managed-local"
18549
+ ]);
18550
+ var LlmProfileSchema = object({
18551
+ id: string(),
18552
+ name: string(),
18553
+ kind: LlmProfileKindSchema,
18554
+ /** Stamped by the provider — keeps the fanned catalog routable. */
18555
+ addonId: string(),
18556
+ enabled: boolean(),
18557
+ /** Vendor model id, or the managed runtime's loaded model. */
18558
+ model: string(),
18559
+ /** Required for openai-compatible; override for cloud kinds. */
18560
+ baseUrl: string().optional(),
18561
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
18562
+ apiKey: string().optional(),
18563
+ supportsVision: boolean(),
18564
+ temperature: number().min(0).max(2).optional(),
18565
+ maxTokens: number().int().positive().optional(),
18566
+ timeoutMs: number().int().positive().default(6e4),
18567
+ extraHeaders: record(string(), string()).optional(),
18568
+ /** kind === 'managed-local' only (spec §4). */
18569
+ runtime: ManagedRuntimeConfigSchema.optional()
18570
+ });
18571
+ /** ConfigUISchema tree passed through untyped on the wire (the
18572
+ * notification-output `ConfigSchemaPassthrough` precedent at
18573
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
18574
+ var ConfigSchemaPassthrough$1 = unknown();
18575
+ var LlmProfileKindDescriptorSchema = object({
18576
+ kind: LlmProfileKindSchema,
18577
+ label: string(),
18578
+ icon: string(),
18579
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
18580
+ addonId: string(),
18581
+ configSchema: ConfigSchemaPassthrough$1
18582
+ });
18583
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
18584
+ var LlmDefaultSchema = object({
18585
+ selector: LlmDefaultSelectorSchema,
18586
+ profileId: string()
18587
+ });
18588
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
18589
+ var LlmUsageRollupSchema = object({
18590
+ day: string(),
18591
+ consumer: string(),
18592
+ profileId: string(),
18593
+ calls: number(),
18594
+ okCalls: number(),
18595
+ errorCalls: number(),
18596
+ inputTokens: number(),
18597
+ outputTokens: number(),
18598
+ avgLatencyMs: number()
18599
+ });
18600
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
18601
+ var ManagedModelCatalogEntrySchema = object({
18602
+ id: string(),
18603
+ label: string(),
18604
+ family: string(),
18605
+ purpose: _enum(["text", "vision"]),
18606
+ url: string(),
18607
+ sha256: string(),
18608
+ sizeBytes: number(),
18609
+ quantization: string(),
18610
+ /** Load-time guidance shown in the picker. */
18611
+ minRamBytes: number(),
18612
+ contextSizeDefault: number().int(),
18613
+ /** Vision models: companion projector file. */
18614
+ mmprojUrl: string().optional()
18615
+ });
18616
+ var LlmRuntimeNodeSchema = object({
18617
+ nodeId: string(),
18618
+ reachable: boolean(),
18619
+ status: LlmRuntimeStatusSchema.optional(),
18620
+ disk: LlmRuntimeDiskUsageSchema.optional(),
18621
+ error: string().optional()
18622
+ });
18623
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
18624
+ var ProfileRefInputSchema = object({
18625
+ addonId: string(),
18626
+ profileId: string()
18627
+ });
18628
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
18629
+ kind: "mutation",
18630
+ auth: "admin"
18631
+ }), method(ProfileRefInputSchema, _void(), {
18632
+ kind: "mutation",
18633
+ auth: "admin"
18634
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
18635
+ kind: "mutation",
18636
+ auth: "admin"
18637
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
18638
+ selector: LlmDefaultSelectorSchema,
18639
+ profileId: string().nullable()
18640
+ }), _void(), {
18641
+ kind: "mutation",
18642
+ auth: "admin"
18643
+ }), method(object({
18644
+ since: number().optional(),
18645
+ until: number().optional(),
18646
+ consumer: string().optional(),
18647
+ profileId: string().optional()
18648
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
18649
+ nodeId: string(),
18650
+ model: ManagedModelRefSchema
18651
+ }), _void(), {
18652
+ kind: "mutation",
18653
+ auth: "admin"
18654
+ }), method(object({
18655
+ nodeId: string(),
18656
+ file: string()
18657
+ }), _void(), {
18658
+ kind: "mutation",
18659
+ auth: "admin"
18660
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
18661
+ kind: "mutation",
18662
+ auth: "admin"
18663
+ }), method(ProfileRefInputSchema, _void(), {
18664
+ kind: "mutation",
18665
+ auth: "admin"
18666
+ });
18442
18667
  var LogLevelSchema = _enum([
18443
18668
  "debug",
18444
18669
  "info",
@@ -18461,6 +18686,89 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18461
18686
  limit: number().optional(),
18462
18687
  tags: record(string(), string()).optional()
18463
18688
  }), array(LogEntrySchema).readonly());
18689
+ /**
18690
+ * `login-method` — collection cap through which auth addons contribute
18691
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
18692
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
18693
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
18694
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
18695
+ * procedure aggregates them for the unauthenticated login page.
18696
+ *
18697
+ * A contribution is a discriminated union on `kind`:
18698
+ *
18699
+ * - `redirect` — a declarative button. The login page renders a generic
18700
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
18701
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
18702
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
18703
+ * login page needs NO change.
18704
+ *
18705
+ * - `widget` — a Module-Federation widget the login page mounts (via
18706
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
18707
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
18708
+ * mechanism kept for future use; no shipped addon uses it on the login
18709
+ * page (the passkey ceremony below runs natively in the shell instead).
18710
+ *
18711
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
18712
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
18713
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
18714
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
18715
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
18716
+ * fetching any remote code pre-auth. Contribution stays unconditional —
18717
+ * enrollment state is never leaked pre-auth; visibility is a shell
18718
+ * decision.
18719
+ *
18720
+ * Every contribution carries a `stage`:
18721
+ * - `primary` — shown on the first credentials screen (OIDC /
18722
+ * magic-link buttons; a future usernameless passkey).
18723
+ * - `second-factor` — shown AFTER the password leg, gated on the
18724
+ * returned `factors` (passkey-as-2FA today).
18725
+ *
18726
+ * `mount: skip` — the cap is read server-side by the core auth router
18727
+ * (`registry.getCollection('login-method')`), never mounted as its own
18728
+ * tRPC router.
18729
+ */
18730
+ /** When a login method renders in the two-phase login flow. */
18731
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
18732
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
18733
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
18734
+ object({
18735
+ kind: literal("redirect"),
18736
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
18737
+ id: string(),
18738
+ /** Operator-facing button label. */
18739
+ label: string(),
18740
+ /** lucide-react icon name. */
18741
+ icon: string().optional(),
18742
+ /** Addon-owned HTTP route the button navigates to (GET). */
18743
+ startUrl: string(),
18744
+ stage: LoginStageEnum
18745
+ }),
18746
+ object({
18747
+ kind: literal("widget"),
18748
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
18749
+ id: string(),
18750
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
18751
+ addonId: string(),
18752
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
18753
+ bundle: string(),
18754
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
18755
+ remote: WidgetRemoteSchema,
18756
+ stage: LoginStageEnum
18757
+ }),
18758
+ object({
18759
+ kind: literal("passkey"),
18760
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
18761
+ id: string(),
18762
+ /** Operator-facing button label. */
18763
+ label: string(),
18764
+ stage: LoginStageEnum,
18765
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
18766
+ rpId: string(),
18767
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
18768
+ origin: string().nullable()
18769
+ })
18770
+ ]);
18771
+ method(_void(), array(LoginMethodContributionSchema).readonly());
18464
18772
  var CpuBreakdownSchema = object({
18465
18773
  total: number(),
18466
18774
  user: number(),
@@ -18933,14 +19241,14 @@ var TargetKindCapsSchema = object({
18933
19241
  * the union is large and not meant for runtime validation here; the exported
18934
19242
  * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
18935
19243
  */
18936
- var ConfigSchemaPassthrough$1 = unknown();
19244
+ var ConfigSchemaPassthrough = unknown();
18937
19245
  var TargetKindSchema = object({
18938
19246
  kind: string(),
18939
19247
  label: string(),
18940
19248
  icon: string(),
18941
19249
  /** Stamped by each provider so the concat-fanned catalog stays routable. */
18942
19250
  addonId: string(),
18943
- configSchema: ConfigSchemaPassthrough$1,
19251
+ configSchema: ConfigSchemaPassthrough,
18944
19252
  supportsDiscovery: boolean(),
18945
19253
  caps: TargetKindCapsSchema
18946
19254
  });
@@ -18993,297 +19301,493 @@ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSche
18993
19301
  enabled: boolean()
18994
19302
  }), _void(), { kind: "mutation" });
18995
19303
  /**
18996
- * Shared LLM generate contracts imported by BOTH `llm.cap.ts` (consumer
18997
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18998
- * caps stay wire-compatible without a circular cap→cap import.
19304
+ * notification-rules the Notification Center rule surface (P1 core).
18999
19305
  *
19000
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
19001
- * every transport tier structurally, and failed calls still write usage rows.
19002
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
19306
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
19307
+ * (operator decisions D-1/D-2/D-3 are binding):
19308
+ *
19309
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
19310
+ * `notification-center` module), hooked on the durable persistence
19311
+ * moments (object-event insert, TrackCloser.closeExpired) with a
19312
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
19313
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
19314
+ * FIRST persisted detection matching the conditions (per-track dedup,
19315
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
19316
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
19317
+ * - DISPATCH stays behind `notification-output` (rules reference targets
19318
+ * by id; per-backend params are a passthrough blob capped by the
19319
+ * target kind's own caps/degrade engine).
19320
+ *
19321
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
19322
+ * server-injected caller identity — the first `caller: 'required'`
19323
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
19324
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
19325
+ * windows, and the optional label/identity/plate matchers. User rules,
19326
+ * private zones, per-recipient fan-out and the wider condition table are
19327
+ * P2+ (see spec §7).
19328
+ *
19329
+ * All schemas here are the single source of truth — `NcRule` etc. are
19330
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
19331
+ * schema/interface drift is explicitly not repeated).
19003
19332
  */
19004
- var LlmUsageSchema = object({
19005
- inputTokens: number(),
19006
- outputTokens: number()
19007
- });
19008
- var LlmErrorCodeSchema = _enum([
19009
- "timeout",
19010
- "rate-limited",
19011
- "auth",
19012
- "refusal",
19013
- "bad-request",
19014
- "unavailable",
19015
- "no-profile",
19016
- "budget-exceeded",
19017
- "adapter-error"
19018
- ]);
19019
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
19020
- ok: literal(true),
19021
- text: string(),
19022
- model: string(),
19023
- usage: LlmUsageSchema,
19024
- truncated: boolean(),
19025
- latencyMs: number()
19026
- }), object({
19027
- ok: literal(false),
19028
- code: LlmErrorCodeSchema,
19029
- message: string(),
19030
- retryAfterMs: number().optional()
19031
- })]);
19032
19333
  /**
19033
- * `Uint8Array` is the sanctioned binary conventionsuperjson + the UDS
19034
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
19035
- * notification-output.cap.ts:27-31 precedents).
19334
+ * D-3: the trigger/urgency of a rule which persistence moment evaluates it.
19335
+ * The value maps 1:1 onto the evaluated record kind:
19336
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
19337
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
19338
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
19339
+ * change of a LINKED device, one row per linked camera)
19340
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
19341
+ * delivery / pick-up)
19342
+ *
19343
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
19344
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
19345
+ * this one field keeps the schema additive — a rule still declares exactly
19346
+ * one trigger.
19036
19347
  */
19037
- var LlmImageSchema = object({
19038
- bytes: _instanceof(Uint8Array),
19039
- mimeType: string()
19348
+ var NcDeliverySchema = _enum([
19349
+ "immediate",
19350
+ "track-end",
19351
+ "device-event",
19352
+ "package-event"
19353
+ ]);
19354
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
19355
+ var NcScheduleSchema = object({
19356
+ windows: array(object({
19357
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
19358
+ days: array(number().int().min(0).max(6)).min(1),
19359
+ startMinute: number().int().min(0).max(1439),
19360
+ endMinute: number().int().min(0).max(1439)
19361
+ })).min(1),
19362
+ /** IANA timezone; default = hub host timezone. */
19363
+ timezone: string().optional(),
19364
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
19365
+ invert: boolean().optional()
19040
19366
  });
19041
- var LlmGenerateBaseInputSchema = object({
19042
- /** Collection routing (the notification-output posture). */
19043
- addonId: string().optional(),
19044
- /** Explicit profile; else the resolution chain (spec §3). */
19045
- profileId: string().optional(),
19046
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
19047
- consumer: string(),
19048
- system: string().optional(),
19049
- /** v1: single-turn. `messages[]` is a v2 additive field. */
19050
- prompt: string(),
19051
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
19052
- jsonSchema: record(string(), unknown()).optional(),
19053
- /** Per-call override of the profile default. */
19054
- maxTokens: number().int().positive().optional(),
19055
- temperature: number().optional()
19367
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
19368
+ var NcPlateMatcherSchema = object({
19369
+ values: array(string().min(1)).min(1),
19370
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
19371
+ maxDistance: number().int().min(0).max(3).default(1)
19056
19372
  });
19057
19373
  /**
19058
- * `llm-runtime` node-side managed llama.cpp executor (spec §4). Registered
19059
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
19060
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` normal
19061
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
19062
- * this only through the `llm` cap's methods.
19063
- *
19064
- * One running llama-server child per node in v1 (models are RAM-heavy).
19065
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
19066
- * watchdog operator decision #3).
19374
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
19375
+ * occupancy edge for a device optionally narrowed to a single admin
19376
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
19377
+ * - `became-occupied` (default) count crossed 0 `count`
19378
+ * - `became-free` — count crossed `count` below it
19379
+ * - `>=` / `<=` — count is at/over or at/under `count`
19380
+ * `sustainSeconds` requires the condition hold continuously that long
19381
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
19382
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
19383
+ * the condition never matches. Confirmed edge-state survives addon restarts
19384
+ * (declared SQLite collection, reseeded on boot).
19067
19385
  */
19068
- var ManagedModelRefSchema = discriminatedUnion("kind", [
19069
- object({
19070
- kind: literal("catalog"),
19071
- catalogId: string()
19072
- }),
19073
- object({
19074
- kind: literal("url"),
19075
- url: string(),
19076
- sha256: string().optional()
19077
- }),
19078
- object({
19079
- kind: literal("path"),
19080
- path: string()
19081
- })
19082
- ]);
19083
- var ManagedRuntimeConfigSchema = object({
19084
- /** WHERE the runtime lives — hub or any agent. */
19085
- nodeId: string(),
19086
- /** Closed for v1; 'ollama' is a v2 candidate. */
19087
- engine: _enum(["llama-cpp"]),
19088
- model: ManagedModelRefSchema,
19089
- contextSize: number().int().default(4096),
19090
- /** 0 = CPU-only. */
19091
- gpuLayers: number().int().default(0),
19092
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
19093
- threads: number().int().optional(),
19094
- /** Concurrent slots. */
19095
- parallel: number().int().default(1),
19096
- /** Else lazy: first generate boots it. */
19097
- autoStart: boolean().default(false),
19098
- /** 0 = never; frees RAM after quiet periods. */
19099
- idleStopMinutes: number().int().default(30)
19386
+ var NcOccupancyConditionSchema = object({
19387
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
19388
+ zoneId: string().optional(),
19389
+ /** Object class to count; absent = any class. */
19390
+ className: string().optional(),
19391
+ op: _enum([
19392
+ "became-occupied",
19393
+ "became-free",
19394
+ ">=",
19395
+ "<="
19396
+ ]).default("became-occupied"),
19397
+ count: number().int().min(0).default(1),
19398
+ sustainSeconds: number().int().min(0).max(3600).default(15)
19399
+ });
19400
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
19401
+ var NcZoneConditionSchema = object({
19402
+ ids: array(string().min(1)).min(1),
19403
+ /** Quantifier over `ids` — at least one / every one visited. */
19404
+ match: _enum(["any", "all"]).default("any")
19100
19405
  });
19101
- var LlmRuntimeStatusSchema = object({
19102
- /** Status is ALWAYS node-qualified. */
19103
- nodeId: string(),
19104
- state: _enum([
19105
- "stopped",
19106
- "downloading",
19107
- "starting",
19108
- "ready",
19109
- "crashed",
19110
- "failed"
19111
- ]),
19112
- pid: number().optional(),
19113
- port: number().optional(),
19114
- modelPath: string().optional(),
19115
- modelId: string().optional(),
19116
- downloadProgress: number().min(0).max(1).optional(),
19117
- lastError: string().optional(),
19118
- crashesInWindow: number(),
19119
- /** Child RSS (sampled best-effort). */
19120
- memoryBytes: number().optional(),
19121
- vramBytes: number().optional()
19406
+ /**
19407
+ * The P1 condition set — a flat AND of groups; absent group = pass;
19408
+ * membership lists are OR within the list (spec §2.3).
19409
+ */
19410
+ var NcConditionsSchema = object({
19411
+ /** Device scope — absent = all devices. */
19412
+ devices: array(number()).optional(),
19413
+ /** Detector class names (any overlap with the record's class set). */
19414
+ classes: array(string().min(1)).optional(),
19415
+ /** Veto classes — any overlap fails the rule. */
19416
+ classesExclude: array(string().min(1)).optional(),
19417
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
19418
+ minConfidence: number().min(0).max(1).optional(),
19419
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
19420
+ zones: NcZoneConditionSchema.optional(),
19421
+ /** Veto zones — any hit fails the rule. */
19422
+ zonesExclude: array(string().min(1)).optional(),
19423
+ /**
19424
+ * Exact (case-insensitive) match on the record's collapsed `label`
19425
+ * (identity name / plate text / subclass).
19426
+ */
19427
+ labelEquals: array(string().min(1)).optional(),
19428
+ /**
19429
+ * Identity matcher. P1 boundary: matched against the record's collapsed
19430
+ * `label` (the identity display name propagated by the face pipeline) —
19431
+ * identity-ID matching rides in P2 when identity ids reach the record.
19432
+ */
19433
+ identities: array(string().min(1)).optional(),
19434
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
19435
+ plates: NcPlateMatcherSchema.optional(),
19436
+ /**
19437
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
19438
+ * Same P1 boundary: matched against the record's collapsed `label` (the
19439
+ * identity display name). A record with NO label passes (nothing to
19440
+ * exclude), unlike the include variant which fails on an absent label.
19441
+ */
19442
+ identitiesExclude: array(string().min(1)).optional(),
19443
+ /**
19444
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
19445
+ * TRACK-END only: importance is scored at track close, so it does not exist
19446
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
19447
+ * close the value is threaded via the close-time info (the `Track` clone is
19448
+ * captured before the DB row is updated, so it would otherwise read stale).
19449
+ * Fails when the record carries no importance (never guess quality — the
19450
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
19451
+ */
19452
+ minImportance: number().min(0).max(1).optional(),
19453
+ /**
19454
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
19455
+ * TRACK-END only: an `immediate` / object-event subject has no closed
19456
+ * lifespan, so a dwell condition never matches immediate delivery
19457
+ * (documented choice — the object-event record carries no `firstSeen`,
19458
+ * so dwell cannot be computed from what the subject actually carries).
19459
+ */
19460
+ minDwellSeconds: number().min(0).optional(),
19461
+ /**
19462
+ * Detection provenance filter. `any` (default / absent) matches every
19463
+ * source; otherwise the subject's source must equal it. Legacy records
19464
+ * with no stamped source are treated as `pipeline`. The union spans both
19465
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
19466
+ * tracks carry `sensor`.
19467
+ */
19468
+ source: _enum([
19469
+ "pipeline",
19470
+ "onboard",
19471
+ "sensor",
19472
+ "any"
19473
+ ]).optional(),
19474
+ /**
19475
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
19476
+ * detector `minConfidence` (that gates the object-detection score; this
19477
+ * gates the recognition/OCR match score). Fails when the subject carries
19478
+ * no label-match confidence (never guess). TRACK-END only: the confidence
19479
+ * lives on the recognition result and reaches the subject at track close.
19480
+ *
19481
+ * What it measures precisely (plumbed at track close — the closer threads
19482
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
19483
+ * `importance`): the BEST recognition match confidence observed for the
19484
+ * label the track carries at close — for a face, the peak cosine similarity
19485
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
19486
+ * for a plate, the peak OCR read score of the best-held plate
19487
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
19488
+ * one track the higher of the two is used. A track that ended with no
19489
+ * confident identity/plate match carries no value, so the condition fails
19490
+ * closed for it (an un-recognized subject).
19491
+ */
19492
+ minLabelConfidence: number().min(0).max(1).optional(),
19493
+ /**
19494
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
19495
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
19496
+ * against the token carried on the device-event subject (extracted from the
19497
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
19498
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
19499
+ * eventType, so gate those with {@link sensorKinds} instead.
19500
+ */
19501
+ eventTypeTokens: array(string().min(1)).optional(),
19502
+ /**
19503
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
19504
+ * `contact`, `button`, `device-event`) — matched against the persisted
19505
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
19506
+ */
19507
+ sensorKinds: array(string().min(1)).optional(),
19508
+ /**
19509
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
19510
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
19511
+ * when the subject's phase does not match (a subject always carries a phase
19512
+ * on the package-event trigger).
19513
+ */
19514
+ packagePhase: _enum([
19515
+ "delivered",
19516
+ "picked-up",
19517
+ "both"
19518
+ ]).optional(),
19519
+ /**
19520
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
19521
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
19522
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
19523
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
19524
+ */
19525
+ customZones: array(MaskPolygonShapeSchema).optional(),
19526
+ /**
19527
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
19528
+ * (optionally zone/class-scoped) occupancy count crosses the configured
19529
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
19530
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
19531
+ */
19532
+ occupancy: NcOccupancyConditionSchema.optional()
19122
19533
  });
19123
- var LlmNodeModelSchema = object({
19124
- file: string(),
19125
- sizeBytes: number(),
19126
- catalogId: string().optional(),
19127
- installedAt: number().optional()
19534
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
19535
+ var NcRuleTargetSchema = object({
19536
+ /** `notification-output` Target id. */
19537
+ targetId: string().min(1),
19538
+ /**
19539
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
19540
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
19541
+ * degrade engine drops what the backend can't render.
19542
+ */
19543
+ params: record(string(), unknown()).optional()
19128
19544
  });
19129
- var LlmRuntimeDiskUsageSchema = object({
19130
- nodeId: string(),
19131
- modelsBytes: number(),
19132
- freeBytes: number().optional()
19545
+ /**
19546
+ * Media attachment policy (P1 still-image subset).
19547
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
19548
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
19549
+ * matched on identities attaches the subject's `faceCrop`, one matched on
19550
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
19551
+ * (or when the specific crop is missing) degrades to `best`, then
19552
+ * `keyFrame`, then no attachment — never delaying the send. The matched
19553
+ * condition summary is frozen on the outbox row at enqueue (like the rule
19554
+ * name), so the choice never drifts from the record that fired it.
19555
+ * - `keyFrame` — the clean scene frame (no subject box).
19556
+ * - `none` — no attachment.
19557
+ */
19558
+ var NcMediaPolicySchema = object({ attach: _enum([
19559
+ "best",
19560
+ "best-matching",
19561
+ "keyFrame",
19562
+ "none"
19563
+ ]).default("best") });
19564
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
19565
+ var NcThrottleSchema = object({
19566
+ cooldownSec: number().int().min(0).max(86400).default(60),
19567
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
19568
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
19569
+ });
19570
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
19571
+ var NcRuleInputSchema = object({
19572
+ name: string().min(1).max(200),
19573
+ enabled: boolean().default(true),
19574
+ delivery: NcDeliverySchema,
19575
+ conditions: NcConditionsSchema.default({}),
19576
+ schedule: NcScheduleSchema.optional(),
19577
+ targets: array(NcRuleTargetSchema).min(1),
19578
+ media: NcMediaPolicySchema.default({ attach: "best" }),
19579
+ throttle: NcThrottleSchema.default({
19580
+ cooldownSec: 60,
19581
+ scope: "rule-device"
19582
+ }),
19583
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
19584
+ template: object({
19585
+ title: string().max(500).optional(),
19586
+ body: string().max(2e3).optional()
19587
+ }).optional(),
19588
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
19589
+ priority: number().int().min(1).max(5).default(3),
19590
+ /**
19591
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
19592
+ * behaviour, visible to all, read-only in the viewer). Present = personal
19593
+ * rule owned by this userId. Server-stamped; never trusted from a client.
19594
+ */
19595
+ ownerUserId: string().optional()
19133
19596
  });
19134
- method(LlmGenerateBaseInputSchema.extend({
19135
- images: array(LlmImageSchema).optional(),
19136
- runtime: ManagedRuntimeConfigSchema,
19137
- /** The managed profile's timeout, threaded by the hub provider. */
19138
- timeoutMs: number().int().positive().optional()
19139
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
19140
- kind: "mutation",
19141
- auth: "admin"
19142
- }), method(object({}), _void(), {
19143
- kind: "mutation",
19144
- auth: "admin"
19145
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
19146
- kind: "mutation",
19147
- auth: "admin"
19148
- }), method(object({ file: string() }), _void(), {
19149
- kind: "mutation",
19150
- auth: "admin"
19151
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
19152
19597
  /**
19153
- * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
19154
- * methods concat-fan across providers; single-row methods route to ONE
19155
- * provider by the `addonId` in the call input (the notification-output
19156
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
19157
- * (hub-placed); the cap stays open for future providers.
19158
- *
19159
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
19160
- * `apiKey` is a password field — providers REDACT it on read and merge on
19161
- * write; a stored key NEVER round-trips to a client.
19598
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
19599
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
19600
+ * NOT a client-authored input field (it lives on the persisted rule, not the
19601
+ * input), so it is added here explicitly to let the store's per-target opt-out
19602
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
19603
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
19604
+ * `updateRule` patch.
19162
19605
  */
19163
- var LlmProfileKindSchema = _enum([
19164
- "openai-compatible",
19165
- "openai",
19166
- "anthropic",
19167
- "google",
19168
- "managed-local"
19169
- ]);
19170
- var LlmProfileSchema = object({
19606
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
19607
+ /** A persisted rule. */
19608
+ var NcRuleSchema = NcRuleInputSchema.extend({
19171
19609
  id: string(),
19172
- name: string(),
19173
- kind: LlmProfileKindSchema,
19174
- /** Stamped by the provider — keeps the fanned catalog routable. */
19175
- addonId: string(),
19176
- enabled: boolean(),
19177
- /** Vendor model id, or the managed runtime's loaded model. */
19178
- model: string(),
19179
- /** Required for openai-compatible; override for cloud kinds. */
19180
- baseUrl: string().optional(),
19181
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
19182
- apiKey: string().optional(),
19183
- supportsVision: boolean(),
19184
- temperature: number().min(0).max(2).optional(),
19185
- maxTokens: number().int().positive().optional(),
19186
- timeoutMs: number().int().positive().default(6e4),
19187
- extraHeaders: record(string(), string()).optional(),
19188
- /** kind === 'managed-local' only (spec §4). */
19189
- runtime: ManagedRuntimeConfigSchema.optional()
19190
- });
19191
- /** ConfigUISchema tree passed through untyped on the wire (the
19192
- * notification-output `ConfigSchemaPassthrough` precedent at
19193
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
19194
- var ConfigSchemaPassthrough = unknown();
19195
- var LlmProfileKindDescriptorSchema = object({
19196
- kind: LlmProfileKindSchema,
19197
- label: string(),
19198
- icon: string(),
19199
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
19200
- addonId: string(),
19201
- configSchema: ConfigSchemaPassthrough
19202
- });
19203
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
19204
- var LlmDefaultSchema = object({
19205
- selector: LlmDefaultSelectorSchema,
19206
- profileId: string()
19610
+ /** userId of the admin who created the rule (server-stamped caller). */
19611
+ createdBy: string(),
19612
+ createdAt: number(),
19613
+ updatedAt: number(),
19614
+ /**
19615
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
19616
+ * send time. Only a target's OWNER may add/remove its id (server-checked
19617
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
19618
+ */
19619
+ disabledTargetIds: array(string()).default([])
19207
19620
  });
19208
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
19209
- var LlmUsageRollupSchema = object({
19210
- day: string(),
19211
- consumer: string(),
19212
- profileId: string(),
19213
- calls: number(),
19214
- okCalls: number(),
19215
- errorCalls: number(),
19216
- inputTokens: number(),
19217
- outputTokens: number(),
19218
- avgLatencyMs: number()
19621
+ var NcTestResultSchema = object({
19622
+ recordId: string(),
19623
+ recordKind: _enum([
19624
+ "object-event",
19625
+ "track",
19626
+ "device-event",
19627
+ "package-event"
19628
+ ]),
19629
+ deviceId: number(),
19630
+ timestamp: number(),
19631
+ wouldFire: boolean(),
19632
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
19633
+ failedCondition: string().optional(),
19634
+ className: string().optional(),
19635
+ label: string().optional()
19219
19636
  });
19220
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
19221
- var ManagedModelCatalogEntrySchema = object({
19637
+ var NcConditionDescriptorSchema = object({
19638
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
19222
19639
  id: string(),
19640
+ group: _enum([
19641
+ "scope",
19642
+ "class",
19643
+ "zones",
19644
+ "quality",
19645
+ "label",
19646
+ "schedule",
19647
+ "device",
19648
+ "package",
19649
+ "occupancy"
19650
+ ]),
19223
19651
  label: string(),
19224
- family: string(),
19225
- purpose: _enum(["text", "vision"]),
19226
- url: string(),
19227
- sha256: string(),
19228
- sizeBytes: number(),
19229
- quantization: string(),
19230
- /** Load-time guidance shown in the picker. */
19231
- minRamBytes: number(),
19232
- contextSizeDefault: number().int(),
19233
- /** Vision models: companion projector file. */
19234
- mmprojUrl: string().optional()
19652
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
19653
+ valueType: _enum([
19654
+ "deviceIdList",
19655
+ "stringList",
19656
+ "number01",
19657
+ "number",
19658
+ "sourceSelect",
19659
+ "zoneSelection",
19660
+ "zoneIdList",
19661
+ "schedule",
19662
+ "plateMatcher",
19663
+ "packagePhase",
19664
+ "polygonDraw",
19665
+ "occupancy"
19666
+ ]),
19667
+ operator: _enum([
19668
+ "in",
19669
+ "notIn",
19670
+ "anyOf",
19671
+ "allOf",
19672
+ "gte",
19673
+ "fuzzyIn",
19674
+ "withinSchedule"
19675
+ ]),
19676
+ /** Which delivery kinds the condition applies to. */
19677
+ appliesTo: array(NcDeliverySchema),
19678
+ phase: string(),
19679
+ description: string().optional()
19235
19680
  });
19236
- var LlmRuntimeNodeSchema = object({
19237
- nodeId: string(),
19238
- reachable: boolean(),
19239
- status: LlmRuntimeStatusSchema.optional(),
19240
- disk: LlmRuntimeDiskUsageSchema.optional(),
19241
- error: string().optional()
19681
+ /**
19682
+ * The delivery lifecycle status of a history row — a straight read of the
19683
+ * durable outbox row's own status (single source of truth):
19684
+ * - `pending` — enqueued, in-flight or retrying with backoff
19685
+ * - `sent` — delivered (terminal)
19686
+ * - `dead` — dead-lettered after exhausting retries / a permanent
19687
+ * backend rejection / a deleted target (terminal; carries
19688
+ * the failure `error`)
19689
+ *
19690
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
19691
+ * user dimension (quiet hours / snooze) and are additive when they land.
19692
+ */
19693
+ var NcHistoryStatusSchema = _enum([
19694
+ "pending",
19695
+ "sent",
19696
+ "dead"
19697
+ ]);
19698
+ /** The evaluated record kind a history row descends from (one per trigger). */
19699
+ var NcHistoryRecordKindSchema = _enum([
19700
+ "object-event",
19701
+ "track-end",
19702
+ "device-event",
19703
+ "package-event"
19704
+ ]);
19705
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
19706
+ var NcHistorySubjectSchema = object({
19707
+ className: string(),
19708
+ label: string().optional(),
19709
+ confidence: number().optional(),
19710
+ zones: array(string()),
19711
+ timestamp: number()
19242
19712
  });
19243
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
19244
- var ProfileRefInputSchema = object({
19245
- addonId: string(),
19246
- profileId: string()
19713
+ /**
19714
+ * One delivery-history row. This is a read-only VIEW over the durable
19715
+ * outbox row (single source of truth — the same row the drain loop drives;
19716
+ * NO second write path, so history can never drift from delivery state).
19717
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
19718
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
19719
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
19720
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
19721
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
19722
+ * P1 (admin scope only).
19723
+ */
19724
+ var NcHistoryEntrySchema = object({
19725
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
19726
+ id: string(),
19727
+ ruleId: string(),
19728
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
19729
+ ruleName: string(),
19730
+ /** The rule urgency/trigger that produced this delivery. */
19731
+ delivery: NcDeliverySchema,
19732
+ targetId: string(),
19733
+ deviceId: number(),
19734
+ recordKind: NcHistoryRecordKindSchema,
19735
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
19736
+ recordId: string(),
19737
+ /** Present for track-scoped deliveries (object-event / track-end). */
19738
+ trackId: string().optional(),
19739
+ status: NcHistoryStatusSchema,
19740
+ /** Delivery attempts made so far. */
19741
+ attempts: number().int(),
19742
+ /** Fire time (outbox enqueue). */
19743
+ createdAt: number(),
19744
+ /** Last transition time (terminal for sent / dead). */
19745
+ updatedAt: number(),
19746
+ /** Failure detail — present on a `dead` row. */
19747
+ error: string().optional(),
19748
+ subject: NcHistorySubjectSchema
19247
19749
  });
19248
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
19249
- kind: "mutation",
19250
- auth: "admin"
19251
- }), method(ProfileRefInputSchema, _void(), {
19252
- kind: "mutation",
19253
- auth: "admin"
19254
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
19255
- kind: "mutation",
19256
- auth: "admin"
19257
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
19258
- selector: LlmDefaultSelectorSchema,
19259
- profileId: string().nullable()
19260
- }), _void(), {
19261
- kind: "mutation",
19262
- auth: "admin"
19263
- }), method(object({
19750
+ /**
19751
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
19752
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
19753
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
19754
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
19755
+ */
19756
+ var NcHistoryFilterSchema = object({
19757
+ ruleId: string().optional(),
19758
+ deviceId: number().optional(),
19759
+ status: NcHistoryStatusSchema.optional(),
19264
19760
  since: number().optional(),
19265
19761
  until: number().optional(),
19266
- consumer: string().optional(),
19267
- profileId: string().optional()
19268
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
19269
- nodeId: string(),
19270
- model: ManagedModelRefSchema
19271
- }), _void(), {
19762
+ limit: number().int().min(1).max(500).default(100)
19763
+ });
19764
+ 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 }), {
19272
19765
  kind: "mutation",
19273
- auth: "admin"
19766
+ auth: "admin",
19767
+ caller: "required"
19274
19768
  }), method(object({
19275
- nodeId: string(),
19276
- file: string()
19277
- }), _void(), {
19769
+ ruleId: string(),
19770
+ patch: NcRulePatchSchema
19771
+ }), object({ rule: NcRuleSchema }), {
19772
+ kind: "mutation",
19773
+ auth: "admin",
19774
+ caller: "required"
19775
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
19278
19776
  kind: "mutation",
19279
19777
  auth: "admin"
19280
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
19778
+ }), method(object({
19779
+ ruleId: string(),
19780
+ enabled: boolean()
19781
+ }), object({ success: literal(true) }), {
19281
19782
  kind: "mutation",
19282
19783
  auth: "admin"
19283
- }), method(ProfileRefInputSchema, _void(), {
19784
+ }), method(object({
19785
+ rule: NcRuleInputSchema,
19786
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
19787
+ }), object({ results: array(NcTestResultSchema) }), {
19284
19788
  kind: "mutation",
19285
19789
  auth: "admin"
19286
- });
19790
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
19287
19791
  /**
19288
19792
  * Zod schemas for persisted record types.
19289
19793
  *
@@ -19969,7 +20473,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19969
20473
  }), method(object({
19970
20474
  eventId: string(),
19971
20475
  kind: MediaFileKindEnum.optional()
19972
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
20476
+ }), array(MediaFileSchema).readonly()), method(object({
20477
+ trackId: string(),
20478
+ kinds: array(MediaFileKindEnum).optional()
20479
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
19973
20480
  deviceId: number(),
19974
20481
  timestamp: number(),
19975
20482
  frameWidth: number(),
@@ -19990,76 +20497,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19990
20497
  eventId: string(),
19991
20498
  timestamp: number()
19992
20499
  });
19993
- /**
19994
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
19995
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
19996
- * caps into per-camera event-kind descriptors.
19997
- *
19998
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
19999
- * is NOT duplicated here — every entry is derived from the single
20000
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
20001
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
20002
- * control cap means adding one line here (and a taxonomy entry); the anti-
20003
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
20004
- * eventful cap is missing.
20005
- */
20006
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
20007
- var LEGACY_ICON = {
20008
- motion: "motion",
20009
- audio: "audio",
20010
- person: "person",
20011
- vehicle: "vehicle",
20012
- animal: "animal",
20013
- package: "package",
20014
- door: "door",
20015
- pir: "pir",
20016
- smoke: "smoke",
20017
- water: "water",
20018
- button: "button",
20019
- generic: "generic",
20020
- gas: "smoke",
20021
- vibration: "generic",
20022
- tamper: "generic",
20023
- presence: "person",
20024
- lock: "generic",
20025
- siren: "generic",
20026
- switch: "generic",
20027
- doorbell: "button"
20028
- };
20029
- function legacyIcon(iconId) {
20030
- return LEGACY_ICON[iconId] ?? "generic";
20031
- }
20032
- /**
20033
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
20034
- * The anti-drift guard cross-checks this against the eventful caps declared
20035
- * in `packages/types/src/capabilities/*.cap.ts`.
20036
- */
20037
- var CAP_TO_KIND = {
20038
- contact: "contact",
20039
- motion: "motion-sensor",
20040
- smoke: "smoke",
20041
- flood: "flood",
20042
- gas: "gas",
20043
- "carbon-monoxide": "carbon-monoxide",
20044
- vibration: "vibration",
20045
- tamper: "tamper",
20046
- presence: "presence",
20047
- "enum-sensor": "enum-sensor",
20048
- "event-emitter": "device-event",
20049
- "lock-control": "lock",
20050
- switch: "switch",
20051
- button: "button",
20052
- doorbell: "doorbell"
20053
- };
20054
- function buildDescriptor(capName, kind) {
20055
- const t = EVENT_TAXONOMY[kind];
20056
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
20057
- return {
20058
- ...t,
20059
- icon: legacyIcon(t.iconId)
20060
- };
20061
- }
20062
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
20063
20500
  var CameraPipelineConfigSchema = object({
20064
20501
  engine: PipelineEngineChoiceSchema.optional(),
20065
20502
  steps: array(PipelineStepInputSchema).readonly(),
@@ -20545,6 +20982,76 @@ method(object({
20545
20982
  auth: "admin"
20546
20983
  });
20547
20984
  /**
20985
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
20986
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
20987
+ * caps into per-camera event-kind descriptors.
20988
+ *
20989
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
20990
+ * is NOT duplicated here — every entry is derived from the single
20991
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
20992
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
20993
+ * control cap means adding one line here (and a taxonomy entry); the anti-
20994
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
20995
+ * eventful cap is missing.
20996
+ */
20997
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
20998
+ var LEGACY_ICON = {
20999
+ motion: "motion",
21000
+ audio: "audio",
21001
+ person: "person",
21002
+ vehicle: "vehicle",
21003
+ animal: "animal",
21004
+ package: "package",
21005
+ door: "door",
21006
+ pir: "pir",
21007
+ smoke: "smoke",
21008
+ water: "water",
21009
+ button: "button",
21010
+ generic: "generic",
21011
+ gas: "smoke",
21012
+ vibration: "generic",
21013
+ tamper: "generic",
21014
+ presence: "person",
21015
+ lock: "generic",
21016
+ siren: "generic",
21017
+ switch: "generic",
21018
+ doorbell: "button"
21019
+ };
21020
+ function legacyIcon(iconId) {
21021
+ return LEGACY_ICON[iconId] ?? "generic";
21022
+ }
21023
+ /**
21024
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
21025
+ * The anti-drift guard cross-checks this against the eventful caps declared
21026
+ * in `packages/types/src/capabilities/*.cap.ts`.
21027
+ */
21028
+ var CAP_TO_KIND = {
21029
+ contact: "contact",
21030
+ motion: "motion-sensor",
21031
+ smoke: "smoke",
21032
+ flood: "flood",
21033
+ gas: "gas",
21034
+ "carbon-monoxide": "carbon-monoxide",
21035
+ vibration: "vibration",
21036
+ tamper: "tamper",
21037
+ presence: "presence",
21038
+ "enum-sensor": "enum-sensor",
21039
+ "event-emitter": "device-event",
21040
+ "lock-control": "lock",
21041
+ switch: "switch",
21042
+ button: "button",
21043
+ doorbell: "doorbell"
21044
+ };
21045
+ function buildDescriptor(capName, kind) {
21046
+ const t = EVENT_TAXONOMY[kind];
21047
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
21048
+ return {
21049
+ ...t,
21050
+ icon: legacyIcon(t.iconId)
21051
+ };
21052
+ }
21053
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
21054
+ /**
20548
21055
  * server-management — per-NODE singleton capability for a node's ROOT
20549
21056
  * package lifecycle (runtime-updatable node packages).
20550
21057
  *
@@ -22050,7 +22557,28 @@ var FaceInfoSchema = object({
22050
22557
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
22051
22558
  * track produced no key frame (e.g. native/onboard source) — the UI falls
22052
22559
  * back to the inline `base64` face crop. */
22053
- keyFrameMediaKey: string().optional()
22560
+ keyFrameMediaKey: string().optional(),
22561
+ /** Winning identity-match cosine (0..1) for this face's track, when an
22562
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
22563
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
22564
+ * faces that were never auto-recognized. */
22565
+ bestMatchScore: number().optional(),
22566
+ /** Native-scale face short side (px) at recognition time, when the runner
22567
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
22568
+ * legacy rows / runners that reported no native measure. */
22569
+ nativeFaceShortSidePx: number().optional(),
22570
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
22571
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
22572
+ * but blocked only by the recognition size floor). Mutually exclusive with
22573
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
22574
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
22575
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
22576
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
22577
+ suggestedIdentityId: string().optional(),
22578
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
22579
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
22580
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
22581
+ suggestedMatchScore: number().optional()
22054
22582
  });
22055
22583
  var FaceFilterEnum = _enum([
22056
22584
  "unassigned",
@@ -24422,36 +24950,6 @@ Object.freeze({
24422
24950
  addonId: null,
24423
24951
  access: "view"
24424
24952
  },
24425
- "advancedNotifier.deleteRule": {
24426
- capName: "advanced-notifier",
24427
- capScope: "system",
24428
- addonId: null,
24429
- access: "delete"
24430
- },
24431
- "advancedNotifier.getHistory": {
24432
- capName: "advanced-notifier",
24433
- capScope: "system",
24434
- addonId: null,
24435
- access: "view"
24436
- },
24437
- "advancedNotifier.getRules": {
24438
- capName: "advanced-notifier",
24439
- capScope: "system",
24440
- addonId: null,
24441
- access: "view"
24442
- },
24443
- "advancedNotifier.testRule": {
24444
- capName: "advanced-notifier",
24445
- capScope: "system",
24446
- addonId: null,
24447
- access: "create"
24448
- },
24449
- "advancedNotifier.upsertRule": {
24450
- capName: "advanced-notifier",
24451
- capScope: "system",
24452
- addonId: null,
24453
- access: "create"
24454
- },
24455
24953
  "alarmPanel.arm": {
24456
24954
  capName: "alarm-panel",
24457
24955
  capScope: "device",
@@ -26756,6 +27254,60 @@ Object.freeze({
26756
27254
  addonId: null,
26757
27255
  access: "create"
26758
27256
  },
27257
+ "notificationRules.createRule": {
27258
+ capName: "notification-rules",
27259
+ capScope: "system",
27260
+ addonId: null,
27261
+ access: "create"
27262
+ },
27263
+ "notificationRules.deleteRule": {
27264
+ capName: "notification-rules",
27265
+ capScope: "system",
27266
+ addonId: null,
27267
+ access: "delete"
27268
+ },
27269
+ "notificationRules.getConditionCatalog": {
27270
+ capName: "notification-rules",
27271
+ capScope: "system",
27272
+ addonId: null,
27273
+ access: "view"
27274
+ },
27275
+ "notificationRules.getHistory": {
27276
+ capName: "notification-rules",
27277
+ capScope: "system",
27278
+ addonId: null,
27279
+ access: "view"
27280
+ },
27281
+ "notificationRules.getRule": {
27282
+ capName: "notification-rules",
27283
+ capScope: "system",
27284
+ addonId: null,
27285
+ access: "view"
27286
+ },
27287
+ "notificationRules.listRules": {
27288
+ capName: "notification-rules",
27289
+ capScope: "system",
27290
+ addonId: null,
27291
+ access: "view"
27292
+ },
27293
+ "notificationRules.setRuleEnabled": {
27294
+ capName: "notification-rules",
27295
+ capScope: "system",
27296
+ addonId: null,
27297
+ access: "create"
27298
+ },
27299
+ "notificationRules.testRule": {
27300
+ capName: "notification-rules",
27301
+ capScope: "system",
27302
+ addonId: null,
27303
+ access: "create"
27304
+ },
27305
+ "notificationRules.updateRule": {
27306
+ capName: "notification-rules",
27307
+ capScope: "system",
27308
+ addonId: null,
27309
+ access: "create"
27310
+ },
26759
27311
  "notifier.cancel": {
26760
27312
  capName: "notifier",
26761
27313
  capScope: "device",
@@ -219003,6 +219555,31 @@ var reolinkCameraSchema = object({
219003
219555
  ext: ReolinkStreamProfileOptionsSchema.optional()
219004
219556
  }).optional(),
219005
219557
  /**
219558
+ * Persisted `getOptions` descriptors for the device-config caps
219559
+ * (`stream-params`, `motion-zones`, `privacy-mask`, `day-night`,
219560
+ * `image-settings`, `ptz`), keyed by cap name.
219561
+ *
219562
+ * WHY: the device-detail aggregate (`deviceManager.getDeviceAggregate`)
219563
+ * calls `getOptions` + `getStatus` on EVERY bound device-config cap,
219564
+ * and the admin UI polls it every 2.5s while the Config tab is open.
219565
+ * Un-cached, that is ~7 Baichuan round-trips every 2.5s — which keeps
219566
+ * a battery camera permanently awake and wakes a sleeping one on a
219567
+ * plain page visit. These descriptors are static per camera model
219568
+ * (advertised ranges / codec sets / supported axes), so they are read
219569
+ * once, persisted here, and served from the blob until the TTL
219570
+ * expires (see `ReolinkCamera.resolveCapOptions`).
219571
+ *
219572
+ * `value` is intentionally `unknown`: this blob stays self-contained
219573
+ * (no cross-package schema identity — same rationale as
219574
+ * `ReolinkStreamProfileOptionsSchema` above). The reader validates
219575
+ * each entry with the cap's own Zod schema, so a stale/incompatible
219576
+ * shape is discarded instead of cast.
219577
+ */
219578
+ capOptionsSnapshot: record(string(), object({
219579
+ value: unknown(),
219580
+ fetchedAt: number()
219581
+ })).optional(),
219582
+ /**
219006
219583
  * Snapshot of the camera's privacy mask master switch from
219007
219584
  * `getMask` (cmdId=52). Zone editing is a separate flow —
219008
219585
  * we only expose the master enable.
@@ -221022,15 +221599,48 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
221022
221599
  */
221023
221600
  sleepStateChangedAt = 0;
221024
221601
  /**
221025
- * Min time between observed sleep transitions before we honour
221026
- * another flip. Picked >= the lib's full UDP inference cycle
221027
- * (~12s on battery cams with idle-disconnect) so a single
221028
- * inference flap doesn't pass through. 30s is also longer than
221029
- * `getIdleDisconnectTimeoutMs` (default 30s in the lib), which
221030
- * means a transient socket close → reopen pattern can't drive
221031
- * us through a full state cycle either.
221032
- */
221033
- static SLEEP_HYSTERESIS_MS = 3e4;
221602
+ * Hysteresis is ASYMMETRIC, because the two directions have very
221603
+ * different costs when we get them wrong.
221604
+ *
221605
+ * `→ awake` (`WAKE_HYSTERESIS_MS`): expensive if wrong. Believing an
221606
+ * asleep camera is awake un-gates every background probe
221607
+ * (`refreshParentSettingsSnapshot`, the device-config cap refreshes,
221608
+ * aux align) and makes `wakeForStream` early-out without actually
221609
+ * waking. Keep the full window >= the lib's UDP inference cycle
221610
+ * (~12s on battery cams with idle-disconnect) and >= the lib's
221611
+ * `getIdleDisconnectTimeoutMs` (30s default), so neither an
221612
+ * inference flap nor a transient socket close→reopen can walk us
221613
+ * into a false "awake".
221614
+ *
221615
+ * `→ sleeping` (`SLEEP_HYSTERESIS_MS`): cheap if wrong. Believing an
221616
+ * awake camera is asleep only means we skip background probes and
221617
+ * serve cached values; the demand paths (`wakeForStream`,
221618
+ * `wakeIfSleeping`) still drive a real wake. The old symmetric 30s
221619
+ * window was LONGER than the camera's own awake window (~14s — see
221620
+ * `onWakeTransition`), so a natural wake→sleep cycle had its
221621
+ * `sleeping` transition dropped and the slice stayed stuck on
221622
+ * "awake" while the camera slept: the exact "at rest we lose the
221623
+ * sleeping state" symptom. 5s still absorbs a single 2s inference
221624
+ * tick while tracking the real cycle.
221625
+ */
221626
+ static WAKE_HYSTERESIS_MS = 3e4;
221627
+ static SLEEP_HYSTERESIS_MS = 5e3;
221628
+ /**
221629
+ * Wall-clock ms of the last PROACTIVE wake — one we issued on our own
221630
+ * initiative (background snapshot refresh), not because the operator
221631
+ * or a stream consumer asked for the camera. Drives
221632
+ * `canProactivelyWake` below.
221633
+ */
221634
+ lastProactiveWakeAt = 0;
221635
+ /**
221636
+ * Minimum gap between two proactive wakes. Demand-driven wakes
221637
+ * (`wakeForStream` from the broker, `wakeIfSleeping` behind an
221638
+ * operator action, the intercom pre-wake) bypass this entirely —
221639
+ * the operator asked, the operator gets the camera. Only
221640
+ * self-initiated wakes are rate-limited, so a thumbnail cache miss
221641
+ * can't wake a doorbell every few minutes.
221642
+ */
221643
+ static PROACTIVE_WAKE_COOLDOWN_MS = 10 * 6e4;
221034
221644
  /** Background timer that runs the passive sleep poll (battery cams only). */
221035
221645
  sleepPollTimer = null;
221036
221646
  /** Periodic timer driving `alignAuxDevicesState()` on wired cams.
@@ -221514,6 +222124,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
221514
222124
  } catch {
221515
222125
  return false;
221516
222126
  }
222127
+ this.markWakeIssued();
221517
222128
  this.ctx.logger.info("proactive action: waking sleeping battery cam", {
221518
222129
  tags: { deviceId: this.id },
221519
222130
  meta: { timeoutMs }
@@ -221810,6 +222421,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
221810
222421
  durationMs: Date.now() - startedAt
221811
222422
  };
221812
222423
  }
222424
+ this.markWakeIssued();
221813
222425
  this.ctx.logger.info("battery wakeForStream: cam sleeping — issuing wake", {
221814
222426
  tags: { deviceId: this.id },
221815
222427
  meta: { timeoutMs }
@@ -221882,7 +222494,8 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
221882
222494
  /**
221883
222495
  * Decide whether to honour a sleep-state transition. Returns
221884
222496
  * `false` when the lib's UDP inference is still inside the
221885
- * hysteresis window (8s by default) so we don't flap. The first
222497
+ * hysteresis window so we don't flap. The window is asymmetric —
222498
+ * see `WAKE_HYSTERESIS_MS` / `SLEEP_HYSTERESIS_MS`. The first
221886
222499
  * transition AFTER an api login / restart is always honoured —
221887
222500
  * no prior-flip timestamp gating it.
221888
222501
  *
@@ -221892,11 +222505,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
221892
222505
  acceptSleepingTransition(next) {
221893
222506
  if (this.sleeping === next) return false;
221894
222507
  const now = Date.now();
221895
- if (this.sleepStateChangedAt > 0 && now - this.sleepStateChangedAt < ReolinkCamera.SLEEP_HYSTERESIS_MS) {
222508
+ const windowMs = next ? ReolinkCamera.SLEEP_HYSTERESIS_MS : ReolinkCamera.WAKE_HYSTERESIS_MS;
222509
+ if (this.sleepStateChangedAt > 0 && now - this.sleepStateChangedAt < windowMs) {
221896
222510
  this.ctx.logger.debug("ignoring sleep inference flap within hysteresis window", {
221897
222511
  tags: { deviceId: this.id },
221898
222512
  meta: {
221899
222513
  next,
222514
+ windowMs,
221900
222515
  sinceLastChangeMs: now - this.sleepStateChangedAt
221901
222516
  }
221902
222517
  });
@@ -221905,6 +222520,113 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
221905
222520
  this.sleepStateChangedAt = now;
221906
222521
  return true;
221907
222522
  }
222523
+ /**
222524
+ * THE single writer of the `battery.sleeping` slice.
222525
+ *
222526
+ * Before this existed the state had three independent writers with
222527
+ * three different rules: the `awake`/`sleeping` simpleEvent handlers
222528
+ * (hysteresis-gated) and the sleep poll (which wrote the slice
222529
+ * directly, bypassing the hysteresis AND leaving
222530
+ * `sleepStateChangedAt` stale so the NEXT event compared against an
222531
+ * ancient timestamp). Funnelling every writer through here keeps one
222532
+ * rule set and one timestamp.
222533
+ *
222534
+ * @param source - `'hub-summary'` is AUTHORITATIVE (the NVR reports
222535
+ * per-channel sleep state from its own firmware, not from socket
222536
+ * I/O inference) and therefore bypasses the hysteresis. The other
222537
+ * two sources are inference-derived and stay gated.
222538
+ * @returns `true` when the slice actually changed.
222539
+ */
222540
+ commitSleepState(next, source) {
222541
+ if (!this.isBattery) return false;
222542
+ if (this.sleeping === next) return false;
222543
+ if (source !== "hub-summary" && !this.acceptSleepingTransition(next)) return false;
222544
+ if (source === "hub-summary") this.sleepStateChangedAt = Date.now();
222545
+ this.state.battery.sleeping = next;
222546
+ this.ctx.logger.info("battery sleep state committed", {
222547
+ tags: { deviceId: this.id },
222548
+ meta: {
222549
+ sleeping: next,
222550
+ source
222551
+ }
222552
+ });
222553
+ return true;
222554
+ }
222555
+ /**
222556
+ * Hub-driven sleep reconcile. The NVR's `getNvrChannelsSummary`
222557
+ * carries a per-channel `sleeping` flag that the parent Hub already
222558
+ * pulls on every discovery refresh — firmware truth, obtained over
222559
+ * the Hub's own mains-powered socket, costing the battery channel
222560
+ * nothing. Before this the flag died inside the Hub's
222561
+ * `device-discovery` slice and the adopted child's sleep state
222562
+ * depended entirely on routed simpleEvents; a child that missed a
222563
+ * transition (or whose channel dropped out of the routing map while
222564
+ * deep-asleep) kept serving a stale value indefinitely.
222565
+ *
222566
+ * No-op for non-battery children. Called by `ReolinkHub` after each
222567
+ * successful discovery refresh.
222568
+ */
222569
+ applyHubSleepState(sleeping) {
222570
+ if (!this.isBattery) return;
222571
+ if (this.commitSleepState(sleeping, "hub-summary") && !sleeping) this.onWakeTransition("hub-summary").catch(() => {});
222572
+ }
222573
+ /**
222574
+ * Rate-limit for wakes we issue on our OWN initiative. Returns
222575
+ * `false` when a proactive wake happened less than
222576
+ * `PROACTIVE_WAKE_COOLDOWN_MS` ago — the caller must then serve
222577
+ * whatever it has cached instead of reaching for the radio.
222578
+ *
222579
+ * Demand-driven paths never call this: `wakeForStream` (a consumer
222580
+ * wants live video), `wakeIfSleeping` (an operator clicked
222581
+ * something) and the intercom pre-wake all wake unconditionally.
222582
+ */
222583
+ canProactivelyWake(reason) {
222584
+ if (this.lastProactiveWakeAt === 0) return true;
222585
+ const sinceMs = Date.now() - this.lastProactiveWakeAt;
222586
+ if (sinceMs >= ReolinkCamera.PROACTIVE_WAKE_COOLDOWN_MS) return true;
222587
+ this.ctx.logger.debug("proactive wake suppressed by cooldown", {
222588
+ tags: { deviceId: this.id },
222589
+ meta: {
222590
+ reason,
222591
+ sinceMs,
222592
+ cooldownMs: ReolinkCamera.PROACTIVE_WAKE_COOLDOWN_MS
222593
+ }
222594
+ });
222595
+ return false;
222596
+ }
222597
+ /** Stamp the proactive-wake cooldown. Called by every path that
222598
+ * actually issues a wake — demand-driven ones included, so an
222599
+ * operator-triggered wake also postpones the next proactive one. */
222600
+ markWakeIssued() {
222601
+ this.lastProactiveWakeAt = Date.now();
222602
+ }
222603
+ /**
222604
+ * Gate for a PROACTIVE camera read, checked BEFORE `ensureApi()`.
222605
+ *
222606
+ * The login itself is the wake. On a sleeping UDP/battery camera the
222607
+ * lib's discovery + handshake nudges the firmware awake (same reason
222608
+ * `refreshParentSettingsSnapshot` refuses to call `ensureApi` while
222609
+ * asleep), so gating only the explicit `wakeUp()` call is useless —
222610
+ * by the time we reach it the camera is already up. Production logs
222611
+ * showed exactly that: a background read produced a full
222612
+ * `Connecting to Reolink` → BCUDP discovery → `battery sleep state
222613
+ * committed` (awake) → whole refresh cascade, on a camera that had
222614
+ * been asleep for six minutes.
222615
+ *
222616
+ * Returns `false` when the caller must serve cache / bail out without
222617
+ * touching the socket. Stamps the cooldown when it does let a wake
222618
+ * through, so "at most one proactive wake per
222619
+ * `PROACTIVE_WAKE_COOLDOWN_MS`" holds across ALL proactive callers
222620
+ * rather than per-caller.
222621
+ *
222622
+ * Demand-driven paths never call this — see `canProactivelyWake`.
222623
+ */
222624
+ allowProactiveCameraAccess(reason) {
222625
+ if (!this.isBattery || !this.sleeping) return true;
222626
+ if (!this.canProactivelyWake(reason)) return false;
222627
+ this.markWakeIssued();
222628
+ return true;
222629
+ }
221908
222630
  updateBatteryCache(info) {
221909
222631
  this.setCapSlice(batteryCapability, this.mapBatteryInfo(info));
221910
222632
  }
@@ -222150,6 +222872,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222150
222872
  }
222151
222873
  async fetchSnapshotWithSingleFlight() {
222152
222874
  if (this.snapshotInFlight) return this.snapshotInFlight;
222875
+ if (!this.allowProactiveCameraAccess("snapshot")) {
222876
+ this.ctx.logger.debug("snapshot: skipped — sleeping battery cam inside wake cooldown", { tags: { deviceId: this.id } });
222877
+ return null;
222878
+ }
222153
222879
  const promise = (async () => {
222154
222880
  let api;
222155
222881
  try {
@@ -222628,6 +223354,117 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222628
223354
  await (await this.ensureApi()).setEnc(this.getChannel(), { [streamKey]: encPatch });
222629
223355
  this.cachedStreamDescriptors = void 0;
222630
223356
  }
223357
+ /** How long a persisted `getOptions` descriptor stays authoritative.
223358
+ * These describe model capabilities (advertised ranges, codec sets,
223359
+ * supported axes), not runtime state — they change on a firmware
223360
+ * update, not during operation. 6h keeps a firmware upgrade visible
223361
+ * within a day while removing the per-poll round-trip entirely. */
223362
+ static CAP_OPTIONS_TTL_MS = 360 * 6e4;
223363
+ /**
223364
+ * Read a persisted `getOptions` descriptor, validated with the cap's
223365
+ * OWN Zod schema. Validation (not a cast) is what makes the
223366
+ * `z.unknown()` blob type-safe: an entry written by an older addon
223367
+ * whose shape no longer parses is simply discarded, and the caller
223368
+ * re-probes.
223369
+ */
223370
+ readCapOptionsCache(capName, schema) {
223371
+ const entry = this.config.get("deviceCache")?.capOptionsSnapshot?.[capName];
223372
+ if (!entry) return null;
223373
+ const parsed = schema.safeParse(entry.value);
223374
+ if (!parsed.success) return null;
223375
+ return {
223376
+ value: parsed.data,
223377
+ fetchedAt: entry.fetchedAt
223378
+ };
223379
+ }
223380
+ /** Persist a freshly-probed descriptor. Best-effort — a failed write
223381
+ * only costs the next caller another probe. */
223382
+ async persistCapOptions(capName, value) {
223383
+ try {
223384
+ const current = this.config.get("deviceCache") ?? {};
223385
+ await this.config.setAll({ deviceCache: {
223386
+ ...current,
223387
+ capOptionsSnapshot: {
223388
+ ...current.capOptionsSnapshot,
223389
+ [capName]: {
223390
+ value,
223391
+ fetchedAt: Date.now()
223392
+ }
223393
+ }
223394
+ } });
223395
+ } catch (err) {
223396
+ this.ctx.logger.debug("cap options persist failed", {
223397
+ tags: { deviceId: this.id },
223398
+ meta: {
223399
+ capName,
223400
+ error: err instanceof Error ? err.message : String(err)
223401
+ }
223402
+ });
223403
+ }
223404
+ }
223405
+ /**
223406
+ * Resolve a device-config cap's `getOptions` descriptor without
223407
+ * touching a sleeping camera and without re-probing on every
223408
+ * aggregate poll.
223409
+ *
223410
+ * Order of resolution:
223411
+ * 1. fresh persisted entry (within `CAP_OPTIONS_TTL_MS`) → serve it;
223412
+ * 2. battery cam believed asleep → serve the stale persisted entry
223413
+ * if we have one, otherwise `fallback()`. NEVER probes: this is
223414
+ * the path a page visit takes on a sleeping doorbell.
223415
+ * 3. otherwise probe the camera, persist, serve.
223416
+ * A probe failure falls back to the stale entry, then `fallback()`.
223417
+ */
223418
+ async resolveCapOptions(params) {
223419
+ const { capName, schema, probe, fallback } = params;
223420
+ const cached = this.readCapOptionsCache(capName, schema);
223421
+ if (cached && Date.now() - cached.fetchedAt < ReolinkCamera.CAP_OPTIONS_TTL_MS) return cached.value;
223422
+ if (this.isBattery && this.sleeping) {
223423
+ this.ctx.logger.debug("cap options: battery cam sleeping — serving cache, not probing", {
223424
+ tags: { deviceId: this.id },
223425
+ meta: {
223426
+ capName,
223427
+ hasCache: cached !== null
223428
+ }
223429
+ });
223430
+ return cached?.value ?? fallback();
223431
+ }
223432
+ try {
223433
+ const value = await probe();
223434
+ await this.persistCapOptions(capName, value);
223435
+ return value;
223436
+ } catch (err) {
223437
+ this.ctx.logger.debug("cap options probe failed — serving cache/fallback", {
223438
+ tags: { deviceId: this.id },
223439
+ meta: {
223440
+ capName,
223441
+ error: err instanceof Error ? err.message : String(err)
223442
+ }
223443
+ });
223444
+ return cached?.value ?? fallback();
223445
+ }
223446
+ }
223447
+ /**
223448
+ * Wrap a cap's `refreshFromCamera` so the READ side (the bridge's
223449
+ * stale-check behind `getStatus`) never wakes a sleeping battery cam.
223450
+ * The bridge then projects whatever the slice last held — which is
223451
+ * exactly what the operator should see for a camera that is asleep.
223452
+ *
223453
+ * Only the bridge gets the wrapped version; `setX` mutations keep the
223454
+ * raw refresh so a write still re-reads the firmware's clamped result.
223455
+ */
223456
+ sleepGatedRefresh(capName, refresh) {
223457
+ return async () => {
223458
+ if (this.isBattery && this.sleeping) {
223459
+ this.ctx.logger.debug("cap status refresh skipped — battery cam is sleeping", {
223460
+ tags: { deviceId: this.id },
223461
+ meta: { capName }
223462
+ });
223463
+ return;
223464
+ }
223465
+ await refresh();
223466
+ };
223467
+ }
222631
223468
  /**
222632
223469
  * Register the `stream-params` native cap provider.
222633
223470
  *
@@ -222635,9 +223472,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222635
223472
  * source of truth is `runtimeState['stream-params']`, kept fresh via a
222636
223473
  * `createRuntimeStateBridge` with a `refresh` that round-trips `getEnc`.
222637
223474
  *
222638
- * - `getStatus` — slice-driven via bridge (stale → refresh from camera).
222639
- * - `getOptions` on-demand `getEncOptions` call; not cached in the
222640
- * runtimeState slice (options don't change at runtime).
223475
+ * - `getStatus` — slice-driven via bridge (stale → refresh from camera,
223476
+ * sleep-gated so a read never wakes a battery cam).
223477
+ * - `getOptions` persisted descriptor via `resolveCapOptions`; the
223478
+ * `getEncOptions` round-trip runs at most once per TTL.
222641
223479
  * - `setProfile` — translates cap patch → `EncStreamPatch`, calls
222642
223480
  * `setEnc`, then refreshes the slice.
222643
223481
  */
@@ -222682,19 +223520,25 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222682
223520
  runtimeState: this.runtimeState,
222683
223521
  cap: streamParamsCapability,
222684
223522
  ownDeviceId: this.id,
222685
- refresh: refreshFromCamera,
223523
+ refresh: this.sleepGatedRefresh(CAP_NAME, refreshFromCamera),
222686
223524
  staleMs: STALE_MS,
222687
223525
  empty: () => ({ lastFetchedAt: 0 })
222688
223526
  });
223527
+ const resolveOptions = async () => this.resolveCapOptions({
223528
+ capName: CAP_NAME,
223529
+ schema: StreamParamsOptionsSchema,
223530
+ probe: () => this.probeStreamParamsOptions(),
223531
+ fallback: () => ({})
223532
+ });
222689
223533
  const provider = {
222690
223534
  getStatus: bridge.getStatus,
222691
223535
  getOptions: async ({ deviceId }) => {
222692
223536
  if (deviceId !== this.id) return {};
222693
- return this.probeStreamParamsOptions();
223537
+ return resolveOptions();
222694
223538
  },
222695
223539
  getConfigSchema: async ({ deviceId }) => {
222696
223540
  if (deviceId !== this.id) return null;
222697
- const opts = await this.probeStreamParamsOptions();
223541
+ const opts = await resolveOptions();
222698
223542
  await bridge.ensureFresh();
222699
223543
  return buildStreamParamsConfigSchema(opts, this.runtimeState.getCapState(CAP_NAME) ?? null);
222700
223544
  },
@@ -222807,7 +223651,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222807
223651
  runtimeState: this.runtimeState,
222808
223652
  cap: motionZonesCapability,
222809
223653
  ownDeviceId: this.id,
222810
- refresh: refreshFromCamera,
223654
+ refresh: this.sleepGatedRefresh(CAP_NAME, refreshFromCamera),
222811
223655
  staleMs: STALE_MS,
222812
223656
  empty: () => ({
222813
223657
  enabled: false,
@@ -222818,27 +223662,46 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222818
223662
  }).getStatus,
222819
223663
  getOptions: async ({ deviceId }) => {
222820
223664
  if (deviceId !== this.id) throw new Error(`ReolinkCamera: deviceId mismatch, expected ${this.id}, got ${deviceId}`);
222821
- const raw = await (await this.ensureApi()).getMotionAlarm(channel);
222822
- const { scope } = this.parseMotionAlarm(raw);
222823
- this.motionZonesGrid = {
222824
- columns: scope.columns,
222825
- rows: scope.rows,
222826
- width: scope.width,
222827
- height: scope.height
222828
- };
222829
- return {
222830
- maxRegions: 1,
222831
- supportedShapes: ["grid"],
222832
- grid: {
222833
- width: scope.width,
222834
- height: scope.height
223665
+ return this.resolveCapOptions({
223666
+ capName: CAP_NAME,
223667
+ schema: MotionZoneOptionsSchema,
223668
+ probe: async () => {
223669
+ const raw = await (await this.ensureApi()).getMotionAlarm(channel);
223670
+ const { scope } = this.parseMotionAlarm(raw);
223671
+ this.motionZonesGrid = {
223672
+ columns: scope.columns,
223673
+ rows: scope.rows,
223674
+ width: scope.width,
223675
+ height: scope.height
223676
+ };
223677
+ return {
223678
+ maxRegions: 1,
223679
+ supportedShapes: ["grid"],
223680
+ grid: {
223681
+ width: scope.width,
223682
+ height: scope.height
223683
+ },
223684
+ sensitivity: {
223685
+ min: 1,
223686
+ max: 50,
223687
+ step: 1
223688
+ }
223689
+ };
222835
223690
  },
222836
- sensitivity: {
222837
- min: 1,
222838
- max: 50,
222839
- step: 1
222840
- }
222841
- };
223691
+ fallback: () => ({
223692
+ maxRegions: 1,
223693
+ supportedShapes: [],
223694
+ grid: {
223695
+ width: 0,
223696
+ height: 0
223697
+ },
223698
+ sensitivity: {
223699
+ min: 1,
223700
+ max: 50,
223701
+ step: 1
223702
+ }
223703
+ })
223704
+ });
222842
223705
  },
222843
223706
  setZone: async ({ deviceId, patch }) => {
222844
223707
  if (deviceId !== this.id) return;
@@ -222946,7 +223809,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222946
223809
  runtimeState: this.runtimeState,
222947
223810
  cap: privacyMaskCapability,
222948
223811
  ownDeviceId: this.id,
222949
- refresh: refreshFromCamera,
223812
+ refresh: this.sleepGatedRefresh(CAP_NAME, refreshFromCamera),
222950
223813
  staleMs: STALE_MS,
222951
223814
  empty: () => ({
222952
223815
  enabled: false,
@@ -222959,18 +223822,21 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222959
223822
  maxRegions: 4,
222960
223823
  supportedShapes: ["rect"]
222961
223824
  };
222962
- try {
222963
- const zones = await (await this.ensureApi()).getMaskZones(channel);
222964
- return {
222965
- maxRegions: zones.maxNum,
222966
- supportedShapes: zones.maxNum > 0 ? ["rect"] : []
222967
- };
222968
- } catch {
222969
- return {
223825
+ return this.resolveCapOptions({
223826
+ capName: CAP_NAME,
223827
+ schema: PrivacyMaskOptionsSchema,
223828
+ probe: async () => {
223829
+ const zones = await (await this.ensureApi()).getMaskZones(channel);
223830
+ return {
223831
+ maxRegions: zones.maxNum,
223832
+ supportedShapes: zones.maxNum > 0 ? ["rect"] : []
223833
+ };
223834
+ },
223835
+ fallback: () => ({
222970
223836
  maxRegions: 4,
222971
223837
  supportedShapes: ["rect"]
222972
- };
222973
- }
223838
+ })
223839
+ });
222974
223840
  },
222975
223841
  setMask: async ({ deviceId, patch }) => {
222976
223842
  if (deviceId !== this.id) return;
@@ -223077,7 +223943,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
223077
223943
  runtimeState: this.runtimeState,
223078
223944
  cap: dayNightCapability,
223079
223945
  ownDeviceId: this.id,
223080
- refresh: refreshFromCamera,
223946
+ refresh: this.sleepGatedRefresh(CAP_NAME, refreshFromCamera),
223081
223947
  staleMs: STALE_MS,
223082
223948
  empty: () => ({
223083
223949
  mode: "auto",
@@ -223086,36 +223952,47 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
223086
223952
  }).getStatus,
223087
223953
  getOptions: async ({ deviceId }) => {
223088
223954
  if (deviceId !== this.id) throw new Error(`ReolinkCamera: deviceId mismatch, expected ${this.id}, got ${deviceId}`);
223089
- const api = await this.ensureApi();
223090
- const modes = ((await api.getVideoInput(channel))?.body?.VideoInput)?.dayNight !== void 0 ? [
223091
- "auto",
223092
- "day",
223093
- "night"
223094
- ] : [];
223095
- let supportsSensitivity = false;
223096
- let sensitivityRange;
223097
- try {
223098
- const range = (await api.getDayNightThreshold(channel))?.body?.DayNightThreshold?.thresholdval;
223099
- if (typeof range?.min === "number" && typeof range?.max === "number") {
223100
- supportsSensitivity = true;
223101
- sensitivityRange = {
223102
- min: 0,
223103
- max: 100,
223104
- step: 1
223955
+ return this.resolveCapOptions({
223956
+ capName: CAP_NAME,
223957
+ schema: DayNightOptionsSchema,
223958
+ probe: async () => {
223959
+ const api = await this.ensureApi();
223960
+ const modes = ((await api.getVideoInput(channel))?.body?.VideoInput)?.dayNight !== void 0 ? [
223961
+ "auto",
223962
+ "day",
223963
+ "night"
223964
+ ] : [];
223965
+ let supportsSensitivity = false;
223966
+ let sensitivityRange;
223967
+ try {
223968
+ const range = (await api.getDayNightThreshold(channel))?.body?.DayNightThreshold?.thresholdval;
223969
+ if (typeof range?.min === "number" && typeof range?.max === "number") {
223970
+ supportsSensitivity = true;
223971
+ sensitivityRange = {
223972
+ min: 0,
223973
+ max: 100,
223974
+ step: 1
223975
+ };
223976
+ }
223977
+ } catch (err) {
223978
+ this.ctx.logger.debug("day-night threshold options probe failed", {
223979
+ tags: { deviceId: this.id },
223980
+ meta: { error: err instanceof Error ? err.message : String(err) }
223981
+ });
223982
+ }
223983
+ return {
223984
+ modes,
223985
+ supportsSensitivity,
223986
+ ...sensitivityRange !== void 0 ? { sensitivity: sensitivityRange } : {},
223987
+ supportsSwitchDelay: false
223105
223988
  };
223106
- }
223107
- } catch (err) {
223108
- this.ctx.logger.debug("day-night threshold options probe failed", {
223109
- tags: { deviceId: this.id },
223110
- meta: { error: err instanceof Error ? err.message : String(err) }
223111
- });
223112
- }
223113
- return {
223114
- modes,
223115
- supportsSensitivity,
223116
- ...sensitivityRange !== void 0 ? { sensitivity: sensitivityRange } : {},
223117
- supportsSwitchDelay: false
223118
- };
223989
+ },
223990
+ fallback: () => ({
223991
+ modes: [],
223992
+ supportsSensitivity: false,
223993
+ supportsSwitchDelay: false
223994
+ })
223995
+ });
223119
223996
  },
223120
223997
  setSettings: async ({ deviceId, settings }) => {
223121
223998
  if (deviceId !== this.id) return;
@@ -223199,37 +224076,60 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
223199
224076
  runtimeState: this.runtimeState,
223200
224077
  cap: imageSettingsCapability,
223201
224078
  ownDeviceId: this.id,
223202
- refresh: refreshFromCamera,
224079
+ refresh: this.sleepGatedRefresh(CAP_NAME, refreshFromCamera),
223203
224080
  staleMs: STALE_MS,
223204
224081
  empty: () => ({ lastFetchedAt: 0 })
223205
224082
  }).getStatus,
223206
224083
  getOptions: async ({ deviceId }) => {
223207
224084
  if (deviceId !== this.id) throw new Error(`ReolinkCamera: deviceId mismatch, expected ${this.id}, got ${deviceId}`);
223208
- const isp = await (await this.ensureApi()).getIsp(channel);
223209
- const vi = isp?.body?.VideoInput;
223210
- const exposureRaw = isp?.body?.InputAdvanceCfg?.Exposure?.mode;
223211
- const supportsBrightness = typeof vi?.bright === "number";
223212
- const supportsContrast = typeof vi?.contrast === "number";
223213
- const supportsSaturation = typeof vi?.saturation === "number";
223214
- const supportsSharpness = typeof vi?.sharpen === "number";
223215
- const exposureModes = typeof exposureRaw === "string" ? ["auto", "manual"] : [];
223216
- return {
223217
- supportsBrightness,
223218
- ...supportsBrightness ? { brightness: NORMALIZED_RANGE } : {},
223219
- supportsContrast,
223220
- ...supportsContrast ? { contrast: NORMALIZED_RANGE } : {},
223221
- supportsSaturation,
223222
- ...supportsSaturation ? { saturation: NORMALIZED_RANGE } : {},
223223
- supportsSharpness,
223224
- ...supportsSharpness ? { sharpness: NORMALIZED_RANGE } : {},
224085
+ const staticOptions = {
223225
224086
  supportsMirror: false,
223226
224087
  supportsFlip: false,
223227
224088
  rotateOptions: [],
223228
224089
  whiteBalanceModes: [],
223229
224090
  supportsWarmth: false,
223230
- exposureModes,
223231
224091
  backlightModes: []
223232
224092
  };
224093
+ return this.resolveCapOptions({
224094
+ capName: CAP_NAME,
224095
+ schema: ImageSettingsOptionsSchema,
224096
+ probe: async () => {
224097
+ const isp = await (await this.ensureApi()).getIsp(channel);
224098
+ const vi = isp?.body?.VideoInput;
224099
+ const exposureRaw = isp?.body?.InputAdvanceCfg?.Exposure?.mode;
224100
+ const supportsBrightness = typeof vi?.bright === "number";
224101
+ const supportsContrast = typeof vi?.contrast === "number";
224102
+ const supportsSaturation = typeof vi?.saturation === "number";
224103
+ const supportsSharpness = typeof vi?.sharpen === "number";
224104
+ const exposureModes = typeof exposureRaw === "string" ? ["auto", "manual"] : [];
224105
+ return {
224106
+ supportsBrightness,
224107
+ ...supportsBrightness ? { brightness: NORMALIZED_RANGE } : {},
224108
+ supportsContrast,
224109
+ ...supportsContrast ? { contrast: NORMALIZED_RANGE } : {},
224110
+ supportsSaturation,
224111
+ ...supportsSaturation ? { saturation: NORMALIZED_RANGE } : {},
224112
+ supportsSharpness,
224113
+ ...supportsSharpness ? { sharpness: NORMALIZED_RANGE } : {},
224114
+ ...staticOptions,
224115
+ rotateOptions: [...staticOptions.rotateOptions],
224116
+ whiteBalanceModes: [...staticOptions.whiteBalanceModes],
224117
+ backlightModes: [...staticOptions.backlightModes],
224118
+ exposureModes
224119
+ };
224120
+ },
224121
+ fallback: () => ({
224122
+ supportsBrightness: false,
224123
+ supportsContrast: false,
224124
+ supportsSaturation: false,
224125
+ supportsSharpness: false,
224126
+ ...staticOptions,
224127
+ rotateOptions: [...staticOptions.rotateOptions],
224128
+ whiteBalanceModes: [...staticOptions.whiteBalanceModes],
224129
+ backlightModes: [...staticOptions.backlightModes],
224130
+ exposureModes: []
224131
+ })
224132
+ });
223233
224133
  },
223234
224134
  setSettings: async ({ deviceId, settings }) => {
223235
224135
  if (deviceId !== this.id) return;
@@ -223467,7 +224367,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
223467
224367
  runtimeState: this.runtimeState,
223468
224368
  cap: ptzAutotrackCapability,
223469
224369
  ownDeviceId: this.id,
223470
- refresh: refreshFromCamera,
224370
+ refresh: this.sleepGatedRefresh(CAP_NAME, refreshFromCamera),
223471
224371
  staleMs: STALE_MS,
223472
224372
  empty: () => ({
223473
224373
  enabled: false,
@@ -223588,25 +224488,30 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
223588
224488
  hasAutofocus: false
223589
224489
  };
223590
224490
  const hasAutofocus = this.config.get("deviceCache")?.autoFocusSnapshot?.supported === true;
223591
- try {
223592
- const { capabilities } = await (await this.ensureApi()).getDeviceCapabilities(this.getChannel());
223593
- return {
223594
- hasPan: capabilities.hasPan,
223595
- hasTilt: capabilities.hasTilt,
223596
- hasZoom: capabilities.hasZoom,
223597
- supportsPresets: capabilities.hasPresets,
223598
- hasAutofocus
223599
- };
223600
- } catch {
223601
- const hasPtz = this.getProbeFlags().hasPtz === true;
223602
- return {
223603
- hasPan: hasPtz,
223604
- hasTilt: hasPtz,
223605
- hasZoom: hasPtz,
223606
- supportsPresets: hasPtz,
223607
- hasAutofocus
223608
- };
223609
- }
224491
+ return this.resolveCapOptions({
224492
+ capName: "ptz",
224493
+ schema: PtzOptionsSchema,
224494
+ probe: async () => {
224495
+ const { capabilities } = await (await this.ensureApi()).getDeviceCapabilities(this.getChannel());
224496
+ return {
224497
+ hasPan: capabilities.hasPan,
224498
+ hasTilt: capabilities.hasTilt,
224499
+ hasZoom: capabilities.hasZoom,
224500
+ supportsPresets: capabilities.hasPresets,
224501
+ hasAutofocus
224502
+ };
224503
+ },
224504
+ fallback: () => {
224505
+ const hasPtz = this.getProbeFlags().hasPtz === true;
224506
+ return {
224507
+ hasPan: hasPtz,
224508
+ hasTilt: hasPtz,
224509
+ hasZoom: hasPtz,
224510
+ supportsPresets: hasPtz,
224511
+ hasAutofocus
224512
+ };
224513
+ }
224514
+ });
223610
224515
  },
223611
224516
  goHome: async ({ deviceId }) => {
223612
224517
  if (deviceId !== this.id) return;
@@ -224222,14 +225127,14 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
224222
225127
  });
224223
225128
  return;
224224
225129
  }
224225
- this.state.battery.sleeping = true;
225130
+ if (!this.commitSleepState(true, "sleep-poll")) return;
224226
225131
  this.ctx.logger.info("Sleep poll detected sleep — closing active streams", {
224227
225132
  tags: { deviceId: this.id },
224228
225133
  meta: { idleMs: status.idleMs }
224229
225134
  });
224230
225135
  this.closeActiveStreams("sleep-poll").catch(() => {});
224231
225136
  } else if (status.state === "awake" && this.sleeping) {
224232
- this.state.battery.sleeping = false;
225137
+ if (!this.commitSleepState(false, "sleep-poll")) return;
224233
225138
  this.ctx.logger.debug("Sleep poll detected awake", { tags: { deviceId: this.id } });
224234
225139
  this.onWakeTransition("sleep-poll").catch(() => {});
224235
225140
  }
@@ -224361,6 +225266,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
224361
225266
  if (this.batteryUpdateInFlight) return this.batteryUpdateInFlight;
224362
225267
  const cycle = (async () => {
224363
225268
  try {
225269
+ if (!this.allowProactiveCameraAccess("battery-update")) {
225270
+ this.ctx.logger.debug("battery-update: cam sleeping — skipping cycle without connecting", { tags: { deviceId: this.id } });
225271
+ return;
225272
+ }
224364
225273
  let api;
224365
225274
  try {
224366
225275
  api = await this.ensureApi();
@@ -226212,6 +227121,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
226212
227121
  }
226213
227122
  if (this.api) return this.api;
226214
227123
  if (this.loginPromise) return this.loginPromise;
227124
+ if (this.isBattery && this.sleeping) {
227125
+ const frames = (/* @__PURE__ */ new Error("wake-attribution")).stack?.split("\n").slice(2, 7).join(" | ");
227126
+ this.ctx.logger.info("battery cam login while sleeping — this wakes the camera", {
227127
+ tags: { deviceId: this.id },
227128
+ meta: { caller: frames ?? "unavailable" }
227129
+ });
227130
+ }
226215
227131
  const host = this.config.get("host");
226216
227132
  const port = this.config.get("port");
226217
227133
  const username = this.config.get("username");
@@ -226396,17 +227312,14 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
226396
227312
  }
226397
227313
  if (event.type === "awake") {
226398
227314
  const wasSleeping = this.sleeping;
226399
- if (this.acceptSleepingTransition(false)) {
226400
- if (this.isBattery) this.state.battery.sleeping = false;
226401
- if (wasSleeping) {
226402
- this.ctx.logger.info("Reolink camera woke up", { tags: { deviceId: this.id } });
226403
- this.ctx.eventBus.emit(createEvent(EventCategory.DeviceAwake, eventSource, {
226404
- deviceId: this.id,
226405
- providerId: REOLINK_ADDON_ID,
226406
- reason: "awake"
226407
- }));
226408
- this.onWakeTransition("simple-event").catch(() => {});
226409
- }
227315
+ if (this.commitSleepState(false, "simple-event") && wasSleeping) {
227316
+ this.ctx.logger.info("Reolink camera woke up", { tags: { deviceId: this.id } });
227317
+ this.ctx.eventBus.emit(createEvent(EventCategory.DeviceAwake, eventSource, {
227318
+ deviceId: this.id,
227319
+ providerId: REOLINK_ADDON_ID,
227320
+ reason: "awake"
227321
+ }));
227322
+ this.onWakeTransition("simple-event").catch(() => {});
226410
227323
  }
226411
227324
  return;
226412
227325
  }
@@ -226429,21 +227342,19 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
226429
227342
  }
226430
227343
  if (event.type === "sleeping") {
226431
227344
  const wasSleeping = this.sleeping;
226432
- if (this.acceptSleepingTransition(true)) {
226433
- if (this.isBattery) this.state.battery.sleeping = true;
226434
- if (!wasSleeping) this.ctx.eventBus.emit(createEvent(EventCategory.DeviceSleeping, eventSource, {
226435
- deviceId: this.id,
226436
- providerId: REOLINK_ADDON_ID,
226437
- reason: "sleeping"
226438
- }));
226439
- if (this.active.size > 0) {
226440
- this.ctx.logger.info("Reolink camera went to sleep — closing active streams", {
226441
- tags: { deviceId: this.id },
226442
- meta: { activeStreams: this.active.size }
226443
- });
226444
- this.closeActiveStreams("sleeping").catch(() => {});
226445
- } else this.ctx.logger.debug("Reolink camera sleep transition (no active streams)", { tags: { deviceId: this.id } });
226446
- }
227345
+ if (!this.commitSleepState(true, "simple-event")) return;
227346
+ if (!wasSleeping) this.ctx.eventBus.emit(createEvent(EventCategory.DeviceSleeping, eventSource, {
227347
+ deviceId: this.id,
227348
+ providerId: REOLINK_ADDON_ID,
227349
+ reason: "sleeping"
227350
+ }));
227351
+ if (this.active.size > 0) {
227352
+ this.ctx.logger.info("Reolink camera went to sleep — closing active streams", {
227353
+ tags: { deviceId: this.id },
227354
+ meta: { activeStreams: this.active.size }
227355
+ });
227356
+ this.closeActiveStreams("sleeping").catch(() => {});
227357
+ } else this.ctx.logger.debug("Reolink camera sleep transition (no active streams)", { tags: { deviceId: this.id } });
226447
227358
  return;
226448
227359
  }
226449
227360
  if (event.type === "battery" && event.battery) {
@@ -226515,7 +227426,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
226515
227426
  const persistedModel = this.config.get("deviceCache")?.model ?? null;
226516
227427
  const flags = {
226517
227428
  ...prevFlags,
226518
- hasBattery: hasBattery ?? prevFlags.hasBattery ?? this.isBattery,
227429
+ hasBattery: hasBattery === true || prevFlags.hasBattery === true || this.isBattery,
226519
227430
  ...hasPtz !== void 0 ? { hasPtz } : {},
226520
227431
  ...hasIntercom !== void 0 ? { hasIntercom } : {},
226521
227432
  ...hasDoorbell !== void 0 ? { hasDoorbell } : {},
@@ -227082,13 +227993,14 @@ var ReolinkHub = class ReolinkHub extends BaseDevice {
227082
227993
  source: "cgi",
227083
227994
  timeoutMs: HUB_DISCOVERY_REFRESH_TIMEOUT_MS
227084
227995
  } });
227996
+ const adoptedByChannel = await this.loadAdoptedChildrenByChannel();
227997
+ this.channelToDeviceId.clear();
227998
+ for (const [channel, deviceId] of adoptedByChannel) this.channelToDeviceId.set(channel, deviceId);
227085
227999
  try {
227086
- const summary = await (await this.ensureApi()).getNvrChannelsSummary({
228000
+ discovered = (await (await this.ensureApi()).getNvrChannelsSummary({
227087
228001
  source: "cgi",
227088
228002
  timeoutMs: HUB_DISCOVERY_REFRESH_TIMEOUT_MS
227089
- });
227090
- const adoptedByChannel = await this.loadAdoptedChildrenByChannel();
227091
- discovered = summary.devices.map((d) => {
228003
+ })).devices.map((d) => {
227092
228004
  const childNativeId = computeChildNativeId(this.stableId, d.channel, d.uid);
227093
228005
  const adoptedDeviceId = adoptedByChannel.get(d.channel) ?? null;
227094
228006
  return {
@@ -227141,12 +228053,37 @@ var ReolinkHub = class ReolinkHub extends BaseDevice {
227141
228053
  }))
227142
228054
  } });
227143
228055
  }
227144
- this.channelToDeviceId.clear();
227145
- for (const entry of discovered) {
227146
- const ch = entry.metadata.rtspChannel;
227147
- if (typeof ch === "number" && entry.adoptedDeviceId !== null) this.channelToDeviceId.set(ch, entry.adoptedDeviceId);
228056
+ if (lastError === null) {
228057
+ await this.reconcileAdoptedChildOnline(discovered);
228058
+ await this.reconcileAdoptedChildSleepState(discovered);
228059
+ }
228060
+ }
228061
+ /**
228062
+ * Push the NVR's per-channel sleep state into each adopted battery
228063
+ * child's `battery.sleeping` slice.
228064
+ *
228065
+ * `getNvrChannelsSummary` carries a `sleeping` flag straight from the
228066
+ * Hub firmware — obtained over the Hub's own mains-powered socket, so
228067
+ * it costs the battery channel nothing, and it is real firmware state
228068
+ * rather than the socket-I/O inference a standalone camera has to rely
228069
+ * on. Before this it only ever reached the discovery panel; the
228070
+ * adopted child's sleep state depended entirely on routed simpleEvents
228071
+ * and went stale the moment one was missed. This is the "the NVR
228072
+ * already tells us everything" path — with it, a hub-attached battery
228073
+ * camera needs no email-push server and no sleep poll of its own.
228074
+ *
228075
+ * Only `online` / `sleeping` are acted on: `offline` and `unknown`
228076
+ * carry no sleep information, so the last known value stands.
228077
+ */
228078
+ async reconcileAdoptedChildSleepState(discovered) {
228079
+ const actionable = discovered.filter((e) => e.adoptedDeviceId !== null && (e.status === "sleeping" || e.status === "online"));
228080
+ if (actionable.length === 0) return;
228081
+ const all = await this.ctx.devices.getAll();
228082
+ for (const entry of actionable) {
228083
+ const child = all.find((d) => d.id === entry.adoptedDeviceId);
228084
+ if (!(child instanceof ReolinkCamera)) continue;
228085
+ child.applyHubSleepState(entry.status === "sleeping");
227148
228086
  }
227149
- if (lastError === null) await this.reconcileAdoptedChildOnline(discovered);
227150
228087
  }
227151
228088
  /**
227152
228089
  * After a successful discovery refresh, mark every adopted child