@camstack/addon-provider-reolink 1.2.4 → 1.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1610 -708
  2. package/dist/addon.mjs +1610 -708
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -26,7 +26,7 @@ let fs_promises = require("fs/promises");
26
26
  fs_promises = require_chunk.__toESM(fs_promises, 1);
27
27
  let node_os = require("node:os");
28
28
  node_os = require_chunk.__toESM(node_os);
29
- //#region ../types/dist/event-category-D4HJq7Mw.mjs
29
+ //#region ../types/dist/event-category-BLcNejAE.mjs
30
30
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
31
31
  EventCategory["SystemBoot"] = "system.boot";
32
32
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -176,9 +176,6 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
176
176
  EventCategory["RecordingSegmentWritten"] = "recording.segment.written";
177
177
  EventCategory["RecordingPolicyFallback"] = "recording.policy.fallback";
178
178
  EventCategory["RecordingRetentionCompleted"] = "recording.retention.completed";
179
- /** Runner-sampled scrub thumbnail (~1/5 s/camera). Telemetry (D8): a lost
180
- * thumb is a scrub gap the recorder's keyframe backfill covers. */
181
- EventCategory["RecordingThumbSampled"] = "recording.thumb-sampled";
182
179
  /** Export render progress (0–100). Telemetry (D8): a lost tick is a stale
183
180
  * progress bar the client reconciles via `recordingExport.getExport`. */
184
181
  EventCategory["RecordingExportProgress"] = "recording.export.progress";
@@ -6843,7 +6840,6 @@ object({ deviceId: number() }), object({ deviceId: number() }), object({
6843
6840
  patch: record(string(), unknown())
6844
6841
  }), object({ success: literal(true) });
6845
6842
  object({ deviceId: number() }), unknown().nullable();
6846
- /** Shorthand to define a method schema */
6847
6843
  function method(input, output, options) {
6848
6844
  return {
6849
6845
  input,
@@ -6851,6 +6847,7 @@ function method(input, output, options) {
6851
6847
  kind: options?.kind ?? "query",
6852
6848
  auth: options?.auth ?? "protected",
6853
6849
  ...options?.access !== void 0 ? { access: options.access } : {},
6850
+ ...options?.caller !== void 0 ? { caller: options.caller } : {},
6854
6851
  timeoutMs: options?.timeoutMs
6855
6852
  };
6856
6853
  }
@@ -8407,6 +8404,59 @@ for (const l of AUDIO_MACRO_LABELS) {
8407
8404
  /** The complete taxonomy dictionary, keyed by kind. */
8408
8405
  var EVENT_TAXONOMY = Object.freeze(Object.fromEntries(entries));
8409
8406
  /**
8407
+ * Notification-Center taxonomy — the fixed vocabulary the NC rule editor
8408
+ * offers as pickers instead of free text. Derived (never hand-listed) from the
8409
+ * single `EVENT_TAXONOMY` dictionary so it stays in lockstep with every other
8410
+ * taxonomy surface (timeline, filters, event page).
8411
+ *
8412
+ * Three buckets, mapped onto the rule editor's `stringList` conditions:
8413
+ * - `videoClasses` → detection classes (person / vehicle / animal + subs)
8414
+ * for the `classes` / `classesExclude` conditions.
8415
+ * - `audioKinds` → audio-analyzer sub kinds (`audio-scream`, …) shown in
8416
+ * the same class picker, grouped under an Audio header.
8417
+ * - `labels` → sensor + control taxonomy kinds (doorbell / contact /
8418
+ * lock / …) for the `sensorKinds` device-event condition.
8419
+ *
8420
+ * Each entry carries `parentKind` so the client can group video subs under
8421
+ * their macro and sensor/control kinds under their category. This surface is
8422
+ * served ADDITIVELY on the `nc.getConditionCatalog` bridge response — no cap
8423
+ * method, no codegen — so it ships train-free with an addon deploy.
8424
+ */
8425
+ /** One selectable taxonomy value: a stable kind id + display label + parent. */
8426
+ var NcTaxonomyEntrySchema = object({
8427
+ /** Stable kind id (e.g. 'person', 'car', 'audio-scream', 'doorbell'). */
8428
+ kind: string(),
8429
+ /** English fallback label (the UI translates via the event-kind i18n key). */
8430
+ label: string(),
8431
+ /** Macro/category parent for grouping ('car' → 'vehicle'); null for a top. */
8432
+ parentKind: string().nullable()
8433
+ });
8434
+ object({
8435
+ videoClasses: array(NcTaxonomyEntrySchema),
8436
+ audioKinds: array(NcTaxonomyEntrySchema),
8437
+ labels: array(NcTaxonomyEntrySchema)
8438
+ });
8439
+ function toEntry(kind, label, parentKind) {
8440
+ return {
8441
+ kind,
8442
+ label,
8443
+ parentKind
8444
+ };
8445
+ }
8446
+ /**
8447
+ * Build the NC taxonomy from `EVENT_TAXONOMY`. Insertion order is preserved
8448
+ * (macros before their subs), which the client relies on for stable grouping.
8449
+ */
8450
+ function buildNcTaxonomy() {
8451
+ const all = Object.values(EVENT_TAXONOMY);
8452
+ return {
8453
+ videoClasses: all.filter((e) => e.category === "detection").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8454
+ audioKinds: all.filter((e) => e.category === "audio" && e.level === "sub").map((e) => toEntry(e.kind, e.label, e.parentKind)),
8455
+ labels: all.filter((e) => e.category === "sensor" || e.category === "control").map((e) => toEntry(e.kind, e.label, e.parentKind))
8456
+ };
8457
+ }
8458
+ Object.freeze(buildNcTaxonomy());
8459
+ /**
8410
8460
  * Error types for the safe expression engine. Two distinct classes so callers
8411
8461
  * can tell a compile-time (grammar) failure from a runtime (evaluation)
8412
8462
  * failure — both are non-fatal to the host: read paths degrade to "skip link".
@@ -12431,6 +12481,22 @@ var CameraMetricsSchema = object({
12431
12481
  ])
12432
12482
  });
12433
12483
  var CameraMetricsWithDeviceIdSchema = CameraMetricsSchema.extend({ deviceId: number() });
12484
+ /**
12485
+ * Reference to the frame's retained NATIVE surface + the parent crop's placement
12486
+ * within the frame, so the executor can re-cut a leaf child ROI at native
12487
+ * resolution on the detail plane. See the `runPipeline` `nativeCropRef` field.
12488
+ */
12489
+ var NativeCropRefSchema = object({
12490
+ /** Handle keying the retained native surface (node-pinned to its owner). */
12491
+ handle: FrameHandleSchema,
12492
+ /** The parent crop's padded/clamped rectangle in FRAME-space pixels. */
12493
+ cropFrameSpace: object({
12494
+ x: number(),
12495
+ y: number(),
12496
+ w: number(),
12497
+ h: number()
12498
+ })
12499
+ });
12434
12500
  var ModelFormatSchema$1 = _enum([
12435
12501
  "onnx",
12436
12502
  "coreml",
@@ -12706,7 +12772,22 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
12706
12772
  * Omitted ⇒ the runner's default device (current single-engine
12707
12773
  * behaviour). Selects WHICH device pool of the node runs the call.
12708
12774
  */
12709
- deviceKey: string().optional()
12775
+ deviceKey: string().optional(),
12776
+ /**
12777
+ * Two-plane NATIVE child-crop reference. Set by `runDetailSubtree` ONLY
12778
+ * when the parent crop was resolved from the frame's retained NATIVE
12779
+ * surface (a frameHandle HIT). Lets the executor re-cut a LEAF crop
12780
+ * child's ROI (plate-ocr, face-embedding, leaf classifiers) at native
12781
+ * resolution from that surface — the SAME quality path faces already
12782
+ * had — instead of the downscaled parent tile. `handle` keys the native
12783
+ * surface (node-pinned to its owner); `cropFrameSpace` is the parent
12784
+ * crop's padded/clamped rectangle in FRAME-space pixels, used to compose
12785
+ * the executor's crop-normalized child ROI back into frame-normalized
12786
+ * coordinates. Auxiliary to the image source (`image`/`frame`/…), NOT one
12787
+ * of the mutually-exclusive image inputs. Absent ⇒ tile-crop children
12788
+ * (today's behaviour on the fallback path).
12789
+ */
12790
+ nativeCropRef: NativeCropRefSchema.optional()
12710
12791
  }), PipelineRunResultBridge, { kind: "mutation" }), method(object({
12711
12792
  engine: PipelineEngineChoiceSchema.optional(),
12712
12793
  steps: array(PipelineStepInputSchema).min(1),
@@ -12955,7 +13036,11 @@ var DetailResultSchema = object({
12955
13036
  bbox: NativeCropBboxSchema.optional(),
12956
13037
  embedding: string().optional(),
12957
13038
  label: string().optional(),
12958
- alignedCropJpeg: string().optional()
13039
+ alignedCropJpeg: string().optional(),
13040
+ /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
13041
+ * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
13042
+ * consumers MUST prefer this when present (2026-07-22 native-gate fix). */
13043
+ nativeFaceShortSidePx: number().optional()
12959
13044
  });
12960
13045
  /**
12961
13046
  * Per-camera tunable ranges + defaults. Single source of truth used
@@ -12969,6 +13054,12 @@ var motionCooldownMsField = {
12969
13054
  default: 3e4,
12970
13055
  step: 500
12971
13056
  };
13057
+ var maxSessionHoldMsField = {
13058
+ min: 0,
13059
+ max: 6e5,
13060
+ default: 12e4,
13061
+ step: 5e3
13062
+ };
12972
13063
  var motionFpsField = {
12973
13064
  min: 1,
12974
13065
  max: 30,
@@ -13116,6 +13207,19 @@ var RunnerCameraConfigSchema = object({
13116
13207
  "on-motion"
13117
13208
  ]).default("always-on"),
13118
13209
  motionCooldownMs: number().min(motionCooldownMsField.min).default(motionCooldownMsField.default),
13210
+ /**
13211
+ * Orchestrator-side on-motion session-hold cap (ms). While an on-motion
13212
+ * detection session is active and ≥1 confirmed non-stationary track is
13213
+ * still live, the orchestrator keeps the session open past
13214
+ * `motionCooldownMs` (a slowly-moving subject can stop re-triggering the
13215
+ * camera's VMD yet is still being tracked frame-to-frame) — up to this many
13216
+ * ms since the session opened, after which it closes regardless. `0`
13217
+ * disables the hold (legacy cooldown-only teardown). Not consumed by the
13218
+ * runner itself — carried here so it shares the per-camera device-settings
13219
+ * surface with `motionCooldownMs`; the orchestrator reads it off the
13220
+ * resolved `CameraDetectionConfig`.
13221
+ */
13222
+ maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
13119
13223
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
13120
13224
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
13121
13225
  motionStreamId: string(),
@@ -13205,7 +13309,7 @@ var RunnerCameraConfigSchema = object({
13205
13309
  */
13206
13310
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
13207
13311
  });
13208
- 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;
13312
+ 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;
13209
13313
  /**
13210
13314
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
13211
13315
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -16732,94 +16836,6 @@ var EnrichedWidgetMetadataSchema = WidgetMetadataSchema.extend({
16732
16836
  bundleUrl: string()
16733
16837
  });
16734
16838
  method(_void(), array(EnrichedWidgetMetadataSchema).readonly());
16735
- var NotificationRuleConditionsSchema = object({
16736
- deviceIds: array(number()).readonly().optional(),
16737
- classNames: array(string()).readonly().optional(),
16738
- zoneIds: array(string()).readonly().optional(),
16739
- minConfidence: number().optional(),
16740
- source: _enum([
16741
- "pipeline",
16742
- "onboard",
16743
- "any"
16744
- ]).optional(),
16745
- schedule: object({
16746
- days: array(number()).readonly(),
16747
- startHour: number(),
16748
- endHour: number()
16749
- }).optional(),
16750
- cooldownSeconds: number().optional(),
16751
- minDwellSeconds: number().optional(),
16752
- /** Match against `event.data.eventType` token (e.g. `'press_long'`). When non-empty, only events
16753
- * carrying a matching `data.eventType` string pass this condition. Rules without this field are
16754
- * unaffected (back-compat). Distinct from `rule.eventTypes` which holds EventCategory strings. */
16755
- eventTypeTokens: array(string()).readonly().optional(),
16756
- /** Match detections whose CLIP image embedding is semantically similar to this free-text
16757
- * description. Requires the embedding-encoder cap to have pre-warmed the text vector.
16758
- * `minSimilarity` is the cosine similarity threshold in [0, 1]. */
16759
- clipDescription: object({
16760
- text: string().min(1),
16761
- minSimilarity: number().min(0).max(1)
16762
- }).optional(),
16763
- /** Match events whose recognized-entity label (face identity name or plate
16764
- * vehicle name, propagated onto `event.data.label`) is one of these values.
16765
- * Empty/absent → unaffected (back-compat). Enables "notify me when <named
16766
- * vehicle/person> is seen". */
16767
- labels: array(string()).readonly().optional()
16768
- });
16769
- var NotificationRuleTemplateSchema = object({
16770
- title: string(),
16771
- body: string(),
16772
- imageMode: _enum([
16773
- "crop",
16774
- "annotated",
16775
- "full",
16776
- "none"
16777
- ])
16778
- });
16779
- var NotificationRuleSchema = object({
16780
- id: string(),
16781
- name: string(),
16782
- enabled: boolean(),
16783
- eventTypes: array(string()).readonly(),
16784
- conditions: NotificationRuleConditionsSchema,
16785
- outputs: array(string()).readonly(),
16786
- template: NotificationRuleTemplateSchema.optional(),
16787
- priority: _enum([
16788
- "low",
16789
- "normal",
16790
- "high",
16791
- "critical"
16792
- ])
16793
- });
16794
- var NotificationTestResultSchema = object({
16795
- ruleId: string(),
16796
- eventId: string(),
16797
- timestamp: number(),
16798
- wouldFire: boolean(),
16799
- reason: string().optional()
16800
- });
16801
- var NotificationHistoryEntrySchema = object({
16802
- id: string(),
16803
- ruleId: string(),
16804
- ruleName: string(),
16805
- eventId: string(),
16806
- timestamp: number(),
16807
- outputs: array(string()).readonly(),
16808
- success: boolean(),
16809
- error: string().optional(),
16810
- deviceId: number().optional()
16811
- });
16812
- var NotificationHistoryFilterSchema = object({
16813
- ruleId: string().optional(),
16814
- deviceId: number().optional(),
16815
- from: number().optional(),
16816
- to: number().optional(),
16817
- limit: number().optional()
16818
- });
16819
- 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({
16820
- ruleId: string(),
16821
- lookbackMinutes: number()
16822
- }), object({ results: array(NotificationTestResultSchema).readonly() }), { kind: "mutation" }), method(object({ filter: NotificationHistoryFilterSchema.optional() }), object({ entries: array(NotificationHistoryEntrySchema).readonly() }));
16823
16839
  /**
16824
16840
  * Alerts capability — collection-based internal alert system.
16825
16841
  *
@@ -17006,89 +17022,6 @@ method(object({
17006
17022
  password: string()
17007
17023
  }), AuthResultSchema.nullable(), { kind: "mutation" }), method(object({ state: string() }), string()), method(record(string(), string()), AuthResultSchema, { kind: "mutation" }), method(object({ token: string() }), AuthResultSchema.nullable());
17008
17024
  /**
17009
- * `login-method` — collection cap through which auth addons contribute
17010
- * their pre-auth login surfaces to the login page. This is the SINGLE,
17011
- * generic mechanism that supersedes the dead `auth.listProviders` reader:
17012
- * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
17013
- * `login-method` provider and the PUBLIC `auth.listLoginMethods`
17014
- * procedure aggregates them for the unauthenticated login page.
17015
- *
17016
- * A contribution is a discriminated union on `kind`:
17017
- *
17018
- * - `redirect` — a declarative button. The login page renders a generic
17019
- * button that navigates to `startUrl` (an addon-owned HTTP route).
17020
- * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
17021
- * ZERO shell-side JS. A future SSO addon plugs in the same way — the
17022
- * login page needs NO change.
17023
- *
17024
- * - `widget` — a Module-Federation widget the login page mounts (via
17025
- * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
17026
- * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
17027
- * mechanism kept for future use; no shipped addon uses it on the login
17028
- * page (the passkey ceremony below runs natively in the shell instead).
17029
- *
17030
- * - `passkey` — a declarative WebAuthn ceremony the shell renders
17031
- * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
17032
- * a remotely-loaded bundle). Carries the addon's effective `rpId` /
17033
- * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
17034
- * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
17035
- * fetching any remote code pre-auth. Contribution stays unconditional —
17036
- * enrollment state is never leaked pre-auth; visibility is a shell
17037
- * decision.
17038
- *
17039
- * Every contribution carries a `stage`:
17040
- * - `primary` — shown on the first credentials screen (OIDC /
17041
- * magic-link buttons; a future usernameless passkey).
17042
- * - `second-factor` — shown AFTER the password leg, gated on the
17043
- * returned `factors` (passkey-as-2FA today).
17044
- *
17045
- * `mount: skip` — the cap is read server-side by the core auth router
17046
- * (`registry.getCollection('login-method')`), never mounted as its own
17047
- * tRPC router.
17048
- */
17049
- /** When a login method renders in the two-phase login flow. */
17050
- var LoginStageEnum = _enum(["primary", "second-factor"]);
17051
- /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
17052
- var LoginMethodContributionSchema = discriminatedUnion("kind", [
17053
- object({
17054
- kind: literal("redirect"),
17055
- /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
17056
- id: string(),
17057
- /** Operator-facing button label. */
17058
- label: string(),
17059
- /** lucide-react icon name. */
17060
- icon: string().optional(),
17061
- /** Addon-owned HTTP route the button navigates to (GET). */
17062
- startUrl: string(),
17063
- stage: LoginStageEnum
17064
- }),
17065
- object({
17066
- kind: literal("widget"),
17067
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
17068
- id: string(),
17069
- /** Owning addon id — drives the public bundle URL + the MF namespace. */
17070
- addonId: string(),
17071
- /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
17072
- bundle: string(),
17073
- /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
17074
- remote: WidgetRemoteSchema,
17075
- stage: LoginStageEnum
17076
- }),
17077
- object({
17078
- kind: literal("passkey"),
17079
- /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
17080
- id: string(),
17081
- /** Operator-facing button label. */
17082
- label: string(),
17083
- stage: LoginStageEnum,
17084
- /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
17085
- rpId: string(),
17086
- /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
17087
- origin: string().nullable()
17088
- })
17089
- ]);
17090
- method(_void(), array(LoginMethodContributionSchema).readonly());
17091
- /**
17092
17025
  * Orchestrator-side destination metadata. The orchestrator computes
17093
17026
  * `id = <addonId>:<subId>` from its provider lookup so consumers
17094
17027
  * (admin UI, restore flow) see one canonical key.
@@ -18444,6 +18377,298 @@ method(_void(), array(string()).readonly(), { auth: "admin" }), method(object({
18444
18377
  kind: "mutation",
18445
18378
  auth: "admin"
18446
18379
  });
18380
+ /**
18381
+ * Shared LLM generate contracts — imported by BOTH `llm.cap.ts` (consumer
18382
+ * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
18383
+ * caps stay wire-compatible without a circular cap→cap import.
18384
+ *
18385
+ * Errors are a discriminated-union RESULT, never thrown: the shape survives
18386
+ * every transport tier structurally, and failed calls still write usage rows.
18387
+ * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
18388
+ */
18389
+ var LlmUsageSchema = object({
18390
+ inputTokens: number(),
18391
+ outputTokens: number()
18392
+ });
18393
+ var LlmErrorCodeSchema = _enum([
18394
+ "timeout",
18395
+ "rate-limited",
18396
+ "auth",
18397
+ "refusal",
18398
+ "bad-request",
18399
+ "unavailable",
18400
+ "no-profile",
18401
+ "budget-exceeded",
18402
+ "adapter-error"
18403
+ ]);
18404
+ var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
18405
+ ok: literal(true),
18406
+ text: string(),
18407
+ model: string(),
18408
+ usage: LlmUsageSchema,
18409
+ truncated: boolean(),
18410
+ latencyMs: number()
18411
+ }), object({
18412
+ ok: literal(false),
18413
+ code: LlmErrorCodeSchema,
18414
+ message: string(),
18415
+ retryAfterMs: number().optional()
18416
+ })]);
18417
+ /**
18418
+ * `Uint8Array` is the sanctioned binary convention — superjson + the UDS
18419
+ * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
18420
+ * notification-output.cap.ts:27-31 precedents).
18421
+ */
18422
+ var LlmImageSchema = object({
18423
+ bytes: _instanceof(Uint8Array),
18424
+ mimeType: string()
18425
+ });
18426
+ var LlmGenerateBaseInputSchema = object({
18427
+ /** Collection routing (the notification-output posture). */
18428
+ addonId: string().optional(),
18429
+ /** Explicit profile; else the resolution chain (spec §3). */
18430
+ profileId: string().optional(),
18431
+ /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
18432
+ consumer: string(),
18433
+ system: string().optional(),
18434
+ /** v1: single-turn. `messages[]` is a v2 additive field. */
18435
+ prompt: string(),
18436
+ /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
18437
+ jsonSchema: record(string(), unknown()).optional(),
18438
+ /** Per-call override of the profile default. */
18439
+ maxTokens: number().int().positive().optional(),
18440
+ temperature: number().optional()
18441
+ });
18442
+ /**
18443
+ * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
18444
+ * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
18445
+ * a specific node's runtime with `nodePin(profile.runtime.nodeId)` — normal
18446
+ * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
18447
+ * this only through the `llm` cap's methods.
18448
+ *
18449
+ * One running llama-server child per node in v1 (models are RAM-heavy).
18450
+ * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
18451
+ * watchdog — operator decision #3).
18452
+ */
18453
+ var ManagedModelRefSchema = discriminatedUnion("kind", [
18454
+ object({
18455
+ kind: literal("catalog"),
18456
+ catalogId: string()
18457
+ }),
18458
+ object({
18459
+ kind: literal("url"),
18460
+ url: string(),
18461
+ sha256: string().optional()
18462
+ }),
18463
+ object({
18464
+ kind: literal("path"),
18465
+ path: string()
18466
+ })
18467
+ ]);
18468
+ var ManagedRuntimeConfigSchema = object({
18469
+ /** WHERE the runtime lives — hub or any agent. */
18470
+ nodeId: string(),
18471
+ /** Closed for v1; 'ollama' is a v2 candidate. */
18472
+ engine: _enum(["llama-cpp"]),
18473
+ model: ManagedModelRefSchema,
18474
+ contextSize: number().int().default(4096),
18475
+ /** 0 = CPU-only. */
18476
+ gpuLayers: number().int().default(0),
18477
+ /** Default: cpus-2, clamped ≥1 (resolved node-side). */
18478
+ threads: number().int().optional(),
18479
+ /** Concurrent slots. */
18480
+ parallel: number().int().default(1),
18481
+ /** Else lazy: first generate boots it. */
18482
+ autoStart: boolean().default(false),
18483
+ /** 0 = never; frees RAM after quiet periods. */
18484
+ idleStopMinutes: number().int().default(30)
18485
+ });
18486
+ var LlmRuntimeStatusSchema = object({
18487
+ /** Status is ALWAYS node-qualified. */
18488
+ nodeId: string(),
18489
+ state: _enum([
18490
+ "stopped",
18491
+ "downloading",
18492
+ "starting",
18493
+ "ready",
18494
+ "crashed",
18495
+ "failed"
18496
+ ]),
18497
+ pid: number().optional(),
18498
+ port: number().optional(),
18499
+ modelPath: string().optional(),
18500
+ modelId: string().optional(),
18501
+ downloadProgress: number().min(0).max(1).optional(),
18502
+ lastError: string().optional(),
18503
+ crashesInWindow: number(),
18504
+ /** Child RSS (sampled best-effort). */
18505
+ memoryBytes: number().optional(),
18506
+ vramBytes: number().optional()
18507
+ });
18508
+ var LlmNodeModelSchema = object({
18509
+ file: string(),
18510
+ sizeBytes: number(),
18511
+ catalogId: string().optional(),
18512
+ installedAt: number().optional()
18513
+ });
18514
+ var LlmRuntimeDiskUsageSchema = object({
18515
+ nodeId: string(),
18516
+ modelsBytes: number(),
18517
+ freeBytes: number().optional()
18518
+ });
18519
+ method(LlmGenerateBaseInputSchema.extend({
18520
+ images: array(LlmImageSchema).optional(),
18521
+ runtime: ManagedRuntimeConfigSchema,
18522
+ /** The managed profile's timeout, threaded by the hub provider. */
18523
+ timeoutMs: number().int().positive().optional()
18524
+ }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
18525
+ kind: "mutation",
18526
+ auth: "admin"
18527
+ }), method(object({}), _void(), {
18528
+ kind: "mutation",
18529
+ auth: "admin"
18530
+ }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
18531
+ kind: "mutation",
18532
+ auth: "admin"
18533
+ }), method(object({ file: string() }), _void(), {
18534
+ kind: "mutation",
18535
+ auth: "admin"
18536
+ }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
18537
+ /**
18538
+ * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
18539
+ * methods concat-fan across providers; single-row methods route to ONE
18540
+ * provider by the `addonId` in the call input (the notification-output
18541
+ * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
18542
+ * (hub-placed); the cap stays open for future providers.
18543
+ *
18544
+ * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
18545
+ * `apiKey` is a password field — providers REDACT it on read and merge on
18546
+ * write; a stored key NEVER round-trips to a client.
18547
+ */
18548
+ var LlmProfileKindSchema = _enum([
18549
+ "openai-compatible",
18550
+ "openai",
18551
+ "anthropic",
18552
+ "google",
18553
+ "managed-local"
18554
+ ]);
18555
+ var LlmProfileSchema = object({
18556
+ id: string(),
18557
+ name: string(),
18558
+ kind: LlmProfileKindSchema,
18559
+ /** Stamped by the provider — keeps the fanned catalog routable. */
18560
+ addonId: string(),
18561
+ enabled: boolean(),
18562
+ /** Vendor model id, or the managed runtime's loaded model. */
18563
+ model: string(),
18564
+ /** Required for openai-compatible; override for cloud kinds. */
18565
+ baseUrl: string().optional(),
18566
+ /** ConfigUISchema type:'password' — never round-trips (spec §5). */
18567
+ apiKey: string().optional(),
18568
+ supportsVision: boolean(),
18569
+ temperature: number().min(0).max(2).optional(),
18570
+ maxTokens: number().int().positive().optional(),
18571
+ timeoutMs: number().int().positive().default(6e4),
18572
+ extraHeaders: record(string(), string()).optional(),
18573
+ /** kind === 'managed-local' only (spec §4). */
18574
+ runtime: ManagedRuntimeConfigSchema.optional()
18575
+ });
18576
+ /** ConfigUISchema tree passed through untyped on the wire (the
18577
+ * notification-output `ConfigSchemaPassthrough` precedent at
18578
+ * notification-output.cap.ts:151); the exported TS type re-tightens it. */
18579
+ var ConfigSchemaPassthrough$1 = unknown();
18580
+ var LlmProfileKindDescriptorSchema = object({
18581
+ kind: LlmProfileKindSchema,
18582
+ label: string(),
18583
+ icon: string(),
18584
+ /** Stamped by each provider so the concat-fanned catalog stays routable. */
18585
+ addonId: string(),
18586
+ configSchema: ConfigSchemaPassthrough$1
18587
+ });
18588
+ var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
18589
+ var LlmDefaultSchema = object({
18590
+ selector: LlmDefaultSelectorSchema,
18591
+ profileId: string()
18592
+ });
18593
+ /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
18594
+ var LlmUsageRollupSchema = object({
18595
+ day: string(),
18596
+ consumer: string(),
18597
+ profileId: string(),
18598
+ calls: number(),
18599
+ okCalls: number(),
18600
+ errorCalls: number(),
18601
+ inputTokens: number(),
18602
+ outputTokens: number(),
18603
+ avgLatencyMs: number()
18604
+ });
18605
+ /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
18606
+ var ManagedModelCatalogEntrySchema = object({
18607
+ id: string(),
18608
+ label: string(),
18609
+ family: string(),
18610
+ purpose: _enum(["text", "vision"]),
18611
+ url: string(),
18612
+ sha256: string(),
18613
+ sizeBytes: number(),
18614
+ quantization: string(),
18615
+ /** Load-time guidance shown in the picker. */
18616
+ minRamBytes: number(),
18617
+ contextSizeDefault: number().int(),
18618
+ /** Vision models: companion projector file. */
18619
+ mmprojUrl: string().optional()
18620
+ });
18621
+ var LlmRuntimeNodeSchema = object({
18622
+ nodeId: string(),
18623
+ reachable: boolean(),
18624
+ status: LlmRuntimeStatusSchema.optional(),
18625
+ disk: LlmRuntimeDiskUsageSchema.optional(),
18626
+ error: string().optional()
18627
+ });
18628
+ var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
18629
+ var ProfileRefInputSchema = object({
18630
+ addonId: string(),
18631
+ profileId: string()
18632
+ });
18633
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
18634
+ kind: "mutation",
18635
+ auth: "admin"
18636
+ }), method(ProfileRefInputSchema, _void(), {
18637
+ kind: "mutation",
18638
+ auth: "admin"
18639
+ }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
18640
+ kind: "mutation",
18641
+ auth: "admin"
18642
+ }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
18643
+ selector: LlmDefaultSelectorSchema,
18644
+ profileId: string().nullable()
18645
+ }), _void(), {
18646
+ kind: "mutation",
18647
+ auth: "admin"
18648
+ }), method(object({
18649
+ since: number().optional(),
18650
+ until: number().optional(),
18651
+ consumer: string().optional(),
18652
+ profileId: string().optional()
18653
+ }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
18654
+ nodeId: string(),
18655
+ model: ManagedModelRefSchema
18656
+ }), _void(), {
18657
+ kind: "mutation",
18658
+ auth: "admin"
18659
+ }), method(object({
18660
+ nodeId: string(),
18661
+ file: string()
18662
+ }), _void(), {
18663
+ kind: "mutation",
18664
+ auth: "admin"
18665
+ }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
18666
+ kind: "mutation",
18667
+ auth: "admin"
18668
+ }), method(ProfileRefInputSchema, _void(), {
18669
+ kind: "mutation",
18670
+ auth: "admin"
18671
+ });
18447
18672
  var LogLevelSchema = _enum([
18448
18673
  "debug",
18449
18674
  "info",
@@ -18466,6 +18691,89 @@ method(LogEntrySchema, _void(), { kind: "mutation" }), method(object({
18466
18691
  limit: number().optional(),
18467
18692
  tags: record(string(), string()).optional()
18468
18693
  }), array(LogEntrySchema).readonly());
18694
+ /**
18695
+ * `login-method` — collection cap through which auth addons contribute
18696
+ * their pre-auth login surfaces to the login page. This is the SINGLE,
18697
+ * generic mechanism that supersedes the dead `auth.listProviders` reader:
18698
+ * every auth addon (OIDC, magic-link, WebAuthn/passkey) registers a
18699
+ * `login-method` provider and the PUBLIC `auth.listLoginMethods`
18700
+ * procedure aggregates them for the unauthenticated login page.
18701
+ *
18702
+ * A contribution is a discriminated union on `kind`:
18703
+ *
18704
+ * - `redirect` — a declarative button. The login page renders a generic
18705
+ * button that navigates to `startUrl` (an addon-owned HTTP route).
18706
+ * Covers OIDC (`/addon/auth-oidc/<id>/start`) and magic-link with
18707
+ * ZERO shell-side JS. A future SSO addon plugs in the same way — the
18708
+ * login page needs NO change.
18709
+ *
18710
+ * - `widget` — a Module-Federation widget the login page mounts (via
18711
+ * `loadRemoteBundle`) for an in-page ceremony. `auth.listLoginMethods`
18712
+ * stamps a public `bundleUrl` from `addonId` + `bundle`. Generic
18713
+ * mechanism kept for future use; no shipped addon uses it on the login
18714
+ * page (the passkey ceremony below runs natively in the shell instead).
18715
+ *
18716
+ * - `passkey` — a declarative WebAuthn ceremony the shell renders
18717
+ * natively (`@simplewebauthn/browser` lives in `addon-admin-ui`, not in
18718
+ * a remotely-loaded bundle). Carries the addon's effective `rpId` /
18719
+ * `origin` (from its `resolveRpID()` / `resolveOrigin()`) so the shell
18720
+ * can gate visibility (IP-literal origin, hostname/rpId mismatch) WITHOUT
18721
+ * fetching any remote code pre-auth. Contribution stays unconditional —
18722
+ * enrollment state is never leaked pre-auth; visibility is a shell
18723
+ * decision.
18724
+ *
18725
+ * Every contribution carries a `stage`:
18726
+ * - `primary` — shown on the first credentials screen (OIDC /
18727
+ * magic-link buttons; a future usernameless passkey).
18728
+ * - `second-factor` — shown AFTER the password leg, gated on the
18729
+ * returned `factors` (passkey-as-2FA today).
18730
+ *
18731
+ * `mount: skip` — the cap is read server-side by the core auth router
18732
+ * (`registry.getCollection('login-method')`), never mounted as its own
18733
+ * tRPC router.
18734
+ */
18735
+ /** When a login method renders in the two-phase login flow. */
18736
+ var LoginStageEnum = _enum(["primary", "second-factor"]);
18737
+ /** One login-method contribution — redirect button, pre-auth widget, or native passkey ceremony. */
18738
+ var LoginMethodContributionSchema = discriminatedUnion("kind", [
18739
+ object({
18740
+ kind: literal("redirect"),
18741
+ /** Stable id within the login-method set (e.g. `auth-oidc/google`). */
18742
+ id: string(),
18743
+ /** Operator-facing button label. */
18744
+ label: string(),
18745
+ /** lucide-react icon name. */
18746
+ icon: string().optional(),
18747
+ /** Addon-owned HTTP route the button navigates to (GET). */
18748
+ startUrl: string(),
18749
+ stage: LoginStageEnum
18750
+ }),
18751
+ object({
18752
+ kind: literal("widget"),
18753
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-login`). */
18754
+ id: string(),
18755
+ /** Owning addon id — drives the public bundle URL + the MF namespace. */
18756
+ addonId: string(),
18757
+ /** Bundle filename inside the addon's dist dir (`remoteEntry.js`). */
18758
+ bundle: string(),
18759
+ /** MF remote descriptor — `{ remoteName, exposedModule, componentKey }`. */
18760
+ remote: WidgetRemoteSchema,
18761
+ stage: LoginStageEnum
18762
+ }),
18763
+ object({
18764
+ kind: literal("passkey"),
18765
+ /** Stable id within the login-method set (e.g. `auth-webauthn/passkey-direct-login`). */
18766
+ id: string(),
18767
+ /** Operator-facing button label. */
18768
+ label: string(),
18769
+ stage: LoginStageEnum,
18770
+ /** Effective WebAuthn RP ID (`resolveRpID()`) — the shell gates visibility on it. */
18771
+ rpId: string(),
18772
+ /** Effective expected origin (`resolveOrigin()`), null when unconfigured. */
18773
+ origin: string().nullable()
18774
+ })
18775
+ ]);
18776
+ method(_void(), array(LoginMethodContributionSchema).readonly());
18469
18777
  var CpuBreakdownSchema = object({
18470
18778
  total: number(),
18471
18779
  user: number(),
@@ -18938,14 +19246,14 @@ var TargetKindCapsSchema = object({
18938
19246
  * the union is large and not meant for runtime validation here; the exported
18939
19247
  * `TargetKind` type re-tightens `configSchema` to `ConfigUISchema`.
18940
19248
  */
18941
- var ConfigSchemaPassthrough$1 = unknown();
19249
+ var ConfigSchemaPassthrough = unknown();
18942
19250
  var TargetKindSchema = object({
18943
19251
  kind: string(),
18944
19252
  label: string(),
18945
19253
  icon: string(),
18946
19254
  /** Stamped by each provider so the concat-fanned catalog stays routable. */
18947
19255
  addonId: string(),
18948
- configSchema: ConfigSchemaPassthrough$1,
19256
+ configSchema: ConfigSchemaPassthrough,
18949
19257
  supportsDiscovery: boolean(),
18950
19258
  caps: TargetKindCapsSchema
18951
19259
  });
@@ -18998,297 +19306,493 @@ method(object({}), array(TargetKindSchema)), method(object({}), array(TargetSche
18998
19306
  enabled: boolean()
18999
19307
  }), _void(), { kind: "mutation" });
19000
19308
  /**
19001
- * Shared LLM generate contracts imported by BOTH `llm.cap.ts` (consumer
19002
- * surface) and `llm-runtime.cap.ts` (node-side managed executor) so the two
19003
- * caps stay wire-compatible without a circular cap→cap import.
19309
+ * notification-rules the Notification Center rule surface (P1 core).
19004
19310
  *
19005
- * Errors are a discriminated-union RESULT, never thrown: the shape survives
19006
- * every transport tier structurally, and failed calls still write usage rows.
19007
- * Token counts only in v1 — no costUsd (operator decision, 2026-07-15).
19311
+ * Spec: `docs/superpowers/specs/2026-07-22-notification-center-requirements.md`
19312
+ * (operator decisions D-1/D-2/D-3 are binding):
19313
+ *
19314
+ * - D-2: rule EVALUATION lives in `addon-post-analysis` (the
19315
+ * `notification-center` module), hooked on the durable persistence
19316
+ * moments (object-event insert, TrackCloser.closeExpired) with a
19317
+ * persisted outbox + retry — never the lossy telemetry bus (D8).
19318
+ * - D-3: urgency belongs to the RULE. `delivery: 'immediate'` fires on the
19319
+ * FIRST persisted detection matching the conditions (per-track dedup,
19320
+ * `maxPerTrack` fixed at 1 — see {@link NC_MAX_PER_TRACK_IMMEDIATE});
19321
+ * `delivery: 'track-end'` evaluates the finalized track record at close.
19322
+ * - DISPATCH stays behind `notification-output` (rules reference targets
19323
+ * by id; per-backend params are a passthrough blob capped by the
19324
+ * target kind's own caps/degrade engine).
19325
+ *
19326
+ * P1 scope: admin-authored rules only (`createdBy` stamped from the
19327
+ * server-injected caller identity — the first `caller: 'required'`
19328
+ * adopter). The P1 condition subset is: devices, classes(+exclude),
19329
+ * minConfidence, admin zones (any/all + exclude), weekly schedule
19330
+ * windows, and the optional label/identity/plate matchers. User rules,
19331
+ * private zones, per-recipient fan-out and the wider condition table are
19332
+ * P2+ (see spec §7).
19333
+ *
19334
+ * All schemas here are the single source of truth — `NcRule` etc. are
19335
+ * `z.infer` exports; no duplicate interfaces (the advanced-notifier
19336
+ * schema/interface drift is explicitly not repeated).
19008
19337
  */
19009
- var LlmUsageSchema = object({
19010
- inputTokens: number(),
19011
- outputTokens: number()
19012
- });
19013
- var LlmErrorCodeSchema = _enum([
19014
- "timeout",
19015
- "rate-limited",
19016
- "auth",
19017
- "refusal",
19018
- "bad-request",
19019
- "unavailable",
19020
- "no-profile",
19021
- "budget-exceeded",
19022
- "adapter-error"
19023
- ]);
19024
- var LlmGenerateResultSchema = discriminatedUnion("ok", [object({
19025
- ok: literal(true),
19026
- text: string(),
19027
- model: string(),
19028
- usage: LlmUsageSchema,
19029
- truncated: boolean(),
19030
- latencyMs: number()
19031
- }), object({
19032
- ok: literal(false),
19033
- code: LlmErrorCodeSchema,
19034
- message: string(),
19035
- retryAfterMs: number().optional()
19036
- })]);
19037
19338
  /**
19038
- * `Uint8Array` is the sanctioned binary conventionsuperjson + the UDS
19039
- * MsgPack channel round-trip typed arrays (embedding-encoder.cap.ts:29,
19040
- * notification-output.cap.ts:27-31 precedents).
19339
+ * D-3: the trigger/urgency of a rule which persistence moment evaluates it.
19340
+ * The value maps 1:1 onto the evaluated record kind:
19341
+ * - `immediate` ↔ object-event persist (lowest-latency detection burst)
19342
+ * - `track-end` ↔ TrackCloser.closeExpired (finalized track record)
19343
+ * - `device-event` ↔ SensorEventStore insert (doorbell press / sensor state
19344
+ * change of a LINKED device, one row per linked camera)
19345
+ * - `package-event` ↔ PackageDropDetector object-event insert (a `package`
19346
+ * delivery / pick-up)
19347
+ *
19348
+ * `immediate`/`track-end` carry the D-3 urgency semantics; `device-event`/
19349
+ * `package-event` are pure trigger kinds (no urgency dimension). Extending
19350
+ * this one field keeps the schema additive — a rule still declares exactly
19351
+ * one trigger.
19041
19352
  */
19042
- var LlmImageSchema = object({
19043
- bytes: _instanceof(Uint8Array),
19044
- mimeType: string()
19353
+ var NcDeliverySchema = _enum([
19354
+ "immediate",
19355
+ "track-end",
19356
+ "device-event",
19357
+ "package-event"
19358
+ ]);
19359
+ /** Weekly schedule — OR of windows; absence on the rule = always active. */
19360
+ var NcScheduleSchema = object({
19361
+ windows: array(object({
19362
+ /** Days of week the window STARTS on (0 = Sunday … 6 = Saturday). */
19363
+ days: array(number().int().min(0).max(6)).min(1),
19364
+ startMinute: number().int().min(0).max(1439),
19365
+ endMinute: number().int().min(0).max(1439)
19366
+ })).min(1),
19367
+ /** IANA timezone; default = hub host timezone. */
19368
+ timezone: string().optional(),
19369
+ /** Active OUTSIDE the windows (e.g. "only outside business hours"). */
19370
+ invert: boolean().optional()
19045
19371
  });
19046
- var LlmGenerateBaseInputSchema = object({
19047
- /** Collection routing (the notification-output posture). */
19048
- addonId: string().optional(),
19049
- /** Explicit profile; else the resolution chain (spec §3). */
19050
- profileId: string().optional(),
19051
- /** MANDATORY usage tag: 'ai-summary', 'notifier-rules', 'adhoc-ui', … */
19052
- consumer: string(),
19053
- system: string().optional(),
19054
- /** v1: single-turn. `messages[]` is a v2 additive field. */
19055
- prompt: string(),
19056
- /** Structured output — adapter-mapped (response_format / forced tool / responseSchema). */
19057
- jsonSchema: record(string(), unknown()).optional(),
19058
- /** Per-call override of the profile default. */
19059
- maxTokens: number().int().positive().optional(),
19060
- temperature: number().optional()
19372
+ /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
19373
+ var NcPlateMatcherSchema = object({
19374
+ values: array(string().min(1)).min(1),
19375
+ /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
19376
+ maxDistance: number().int().min(0).max(3).default(1)
19061
19377
  });
19062
19378
  /**
19063
- * `llm-runtime` node-side managed llama.cpp executor (spec §4). Registered
19064
- * on EVERY node where `addon-ai` is installed; the hub `llm` provider reaches
19065
- * a specific node's runtime with `nodePin(profile.runtime.nodeId)` normal
19066
- * cap routing, zero bespoke plumbing. `internal: true`: the operator reaches
19067
- * this only through the `llm` cap's methods.
19068
- *
19069
- * One running llama-server child per node in v1 (models are RAM-heavy).
19070
- * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
19071
- * watchdog operator decision #3).
19379
+ * Occupancy condition (DEVICE-EVENT trigger). Fires on a ZoneAnalytics
19380
+ * occupancy edge for a device optionally narrowed to a single admin
19381
+ * `zoneId` and/or object `className`. `op` selects the edge/threshold:
19382
+ * - `became-occupied` (default) count crossed 0 `count`
19383
+ * - `became-free` — count crossed `count` below it
19384
+ * - `>=` / `<=` — count is at/over or at/under `count`
19385
+ * `sustainSeconds` requires the condition hold continuously that long
19386
+ * before firing (debounces flicker; 0 = fire on the first matching edge).
19387
+ * Fail-closed: no ZoneAnalytics snapshot / missing zone / null snapshot ⇒
19388
+ * the condition never matches. Confirmed edge-state survives addon restarts
19389
+ * (declared SQLite collection, reseeded on boot).
19072
19390
  */
19073
- var ManagedModelRefSchema = discriminatedUnion("kind", [
19074
- object({
19075
- kind: literal("catalog"),
19076
- catalogId: string()
19077
- }),
19078
- object({
19079
- kind: literal("url"),
19080
- url: string(),
19081
- sha256: string().optional()
19082
- }),
19083
- object({
19084
- kind: literal("path"),
19085
- path: string()
19086
- })
19087
- ]);
19088
- var ManagedRuntimeConfigSchema = object({
19089
- /** WHERE the runtime lives — hub or any agent. */
19090
- nodeId: string(),
19091
- /** Closed for v1; 'ollama' is a v2 candidate. */
19092
- engine: _enum(["llama-cpp"]),
19093
- model: ManagedModelRefSchema,
19094
- contextSize: number().int().default(4096),
19095
- /** 0 = CPU-only. */
19096
- gpuLayers: number().int().default(0),
19097
- /** Default: cpus-2, clamped ≥1 (resolved node-side). */
19098
- threads: number().int().optional(),
19099
- /** Concurrent slots. */
19100
- parallel: number().int().default(1),
19101
- /** Else lazy: first generate boots it. */
19102
- autoStart: boolean().default(false),
19103
- /** 0 = never; frees RAM after quiet periods. */
19104
- idleStopMinutes: number().int().default(30)
19391
+ var NcOccupancyConditionSchema = object({
19392
+ /** Admin zone id to scope the count to; absent = whole-frame occupancy. */
19393
+ zoneId: string().optional(),
19394
+ /** Object class to count; absent = any class. */
19395
+ className: string().optional(),
19396
+ op: _enum([
19397
+ "became-occupied",
19398
+ "became-free",
19399
+ ">=",
19400
+ "<="
19401
+ ]).default("became-occupied"),
19402
+ count: number().int().min(0).default(1),
19403
+ sustainSeconds: number().int().min(0).max(3600).default(15)
19404
+ });
19405
+ /** Admin-zone membership condition (zone IDs as stamped by the ZoneEngine). */
19406
+ var NcZoneConditionSchema = object({
19407
+ ids: array(string().min(1)).min(1),
19408
+ /** Quantifier over `ids` — at least one / every one visited. */
19409
+ match: _enum(["any", "all"]).default("any")
19105
19410
  });
19106
- var LlmRuntimeStatusSchema = object({
19107
- /** Status is ALWAYS node-qualified. */
19108
- nodeId: string(),
19109
- state: _enum([
19110
- "stopped",
19111
- "downloading",
19112
- "starting",
19113
- "ready",
19114
- "crashed",
19115
- "failed"
19116
- ]),
19117
- pid: number().optional(),
19118
- port: number().optional(),
19119
- modelPath: string().optional(),
19120
- modelId: string().optional(),
19121
- downloadProgress: number().min(0).max(1).optional(),
19122
- lastError: string().optional(),
19123
- crashesInWindow: number(),
19124
- /** Child RSS (sampled best-effort). */
19125
- memoryBytes: number().optional(),
19126
- vramBytes: number().optional()
19411
+ /**
19412
+ * The P1 condition set — a flat AND of groups; absent group = pass;
19413
+ * membership lists are OR within the list (spec §2.3).
19414
+ */
19415
+ var NcConditionsSchema = object({
19416
+ /** Device scope — absent = all devices. */
19417
+ devices: array(number()).optional(),
19418
+ /** Detector class names (any overlap with the record's class set). */
19419
+ classes: array(string().min(1)).optional(),
19420
+ /** Veto classes — any overlap fails the rule. */
19421
+ classesExclude: array(string().min(1)).optional(),
19422
+ /** Minimum detection confidence 0–1 (fails when the record has none). */
19423
+ minConfidence: number().min(0).max(1).optional(),
19424
+ /** Admin zone membership over event `zones` / track `zonesVisited`. */
19425
+ zones: NcZoneConditionSchema.optional(),
19426
+ /** Veto zones — any hit fails the rule. */
19427
+ zonesExclude: array(string().min(1)).optional(),
19428
+ /**
19429
+ * Exact (case-insensitive) match on the record's collapsed `label`
19430
+ * (identity name / plate text / subclass).
19431
+ */
19432
+ labelEquals: array(string().min(1)).optional(),
19433
+ /**
19434
+ * Identity matcher. P1 boundary: matched against the record's collapsed
19435
+ * `label` (the identity display name propagated by the face pipeline) —
19436
+ * identity-ID matching rides in P2 when identity ids reach the record.
19437
+ */
19438
+ identities: array(string().min(1)).optional(),
19439
+ /** Fuzzy plate matcher against the record's `label` (plate text). */
19440
+ plates: NcPlateMatcherSchema.optional(),
19441
+ /**
19442
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
19443
+ * Same P1 boundary: matched against the record's collapsed `label` (the
19444
+ * identity display name). A record with NO label passes (nothing to
19445
+ * exclude), unlike the include variant which fails on an absent label.
19446
+ */
19447
+ identitiesExclude: array(string().min(1)).optional(),
19448
+ /**
19449
+ * Minimum server-computed key-event importance in [0,1] (`Track.importance`).
19450
+ * TRACK-END only: importance is scored at track close, so it does not exist
19451
+ * at immediate / object-event evaluation time (see catalog `appliesTo`). At
19452
+ * close the value is threaded via the close-time info (the `Track` clone is
19453
+ * captured before the DB row is updated, so it would otherwise read stale).
19454
+ * Fails when the record carries no importance (never guess quality — the
19455
+ * `minConfidence` precedent). MVP cut: a single scalar threshold.
19456
+ */
19457
+ minImportance: number().min(0).max(1).optional(),
19458
+ /**
19459
+ * Minimum track dwell in SECONDS — `(lastSeen − firstSeen) / 1000`.
19460
+ * TRACK-END only: an `immediate` / object-event subject has no closed
19461
+ * lifespan, so a dwell condition never matches immediate delivery
19462
+ * (documented choice — the object-event record carries no `firstSeen`,
19463
+ * so dwell cannot be computed from what the subject actually carries).
19464
+ */
19465
+ minDwellSeconds: number().min(0).optional(),
19466
+ /**
19467
+ * Detection provenance filter. `any` (default / absent) matches every
19468
+ * source; otherwise the subject's source must equal it. Legacy records
19469
+ * with no stamped source are treated as `pipeline`. The union spans both
19470
+ * record kinds — object events carry `pipeline` | `onboard`, synthetic
19471
+ * tracks carry `sensor`.
19472
+ */
19473
+ source: _enum([
19474
+ "pipeline",
19475
+ "onboard",
19476
+ "sensor",
19477
+ "any"
19478
+ ]).optional(),
19479
+ /**
19480
+ * Minimum identity / plate MATCH confidence in [0,1] — DISTINCT from the
19481
+ * detector `minConfidence` (that gates the object-detection score; this
19482
+ * gates the recognition/OCR match score). Fails when the subject carries
19483
+ * no label-match confidence (never guess). TRACK-END only: the confidence
19484
+ * lives on the recognition result and reaches the subject at track close.
19485
+ *
19486
+ * What it measures precisely (plumbed at track close — the closer threads
19487
+ * the value into `NcTrackClosedInfo.labelConfidence`, the same seam as
19488
+ * `importance`): the BEST recognition match confidence observed for the
19489
+ * label the track carries at close — for a face, the peak cosine similarity
19490
+ * of the ASSIGNED identity (`FaceMatch.score`, reset on an identity switch);
19491
+ * for a plate, the peak OCR read score of the best-held plate
19492
+ * (`plateText.confidence`). When BOTH a face and a plate were recognized on
19493
+ * one track the higher of the two is used. A track that ended with no
19494
+ * confident identity/plate match carries no value, so the condition fails
19495
+ * closed for it (an un-recognized subject).
19496
+ */
19497
+ minLabelConfidence: number().min(0).max(1).optional(),
19498
+ /**
19499
+ * DEVICE-EVENT only. Raw device event-type tokens (`EventFire.eventType`,
19500
+ * e.g. a doorbell `press` / `press_long`) — matched case-insensitively
19501
+ * against the token carried on the device-event subject (extracted from the
19502
+ * event-emitter runtime slice's `lastEvent.eventType`). Fails when the
19503
+ * subject carries no token. Doorbell-pulse / passive-sensor kinds emit no
19504
+ * eventType, so gate those with {@link sensorKinds} instead.
19505
+ */
19506
+ eventTypeTokens: array(string().min(1)).optional(),
19507
+ /**
19508
+ * DEVICE-EVENT only. Sensor/control taxonomy kinds (e.g. `doorbell`,
19509
+ * `contact`, `button`, `device-event`) — matched against the persisted
19510
+ * `SensorEvent.kind` (see `sensor-event-kinds.ts`). Membership is OR.
19511
+ */
19512
+ sensorKinds: array(string().min(1)).optional(),
19513
+ /**
19514
+ * PACKAGE-EVENT only. Which package phase fires the rule — `delivered`
19515
+ * (a parked parcel appeared), `picked-up` (it departed), or `both`. Fails
19516
+ * when the subject's phase does not match (a subject always carries a phase
19517
+ * on the package-event trigger).
19518
+ */
19519
+ packagePhase: _enum([
19520
+ "delivered",
19521
+ "picked-up",
19522
+ "both"
19523
+ ]).optional(),
19524
+ /**
19525
+ * PERSONAL-RULE custom zones (viewer-drawn). Inline normalized polygons
19526
+ * (MaskShape vocabulary). A record passes when its bbox overlaps ANY
19527
+ * listed polygon (ZoneEngine membership semantics). Evaluated only when
19528
+ * the subject carries a bbox; absent bbox ⇒ the condition FAILS.
19529
+ */
19530
+ customZones: array(MaskPolygonShapeSchema).optional(),
19531
+ /**
19532
+ * DEVICE-EVENT only. ZoneAnalytics occupancy edge — fires when a device's
19533
+ * (optionally zone/class-scoped) occupancy count crosses the configured
19534
+ * threshold and holds for `sustainSeconds`. Fail-closed on missing
19535
+ * substrate (no snapshot / missing zone). See {@link NcOccupancyCondition}.
19536
+ */
19537
+ occupancy: NcOccupancyConditionSchema.optional()
19127
19538
  });
19128
- var LlmNodeModelSchema = object({
19129
- file: string(),
19130
- sizeBytes: number(),
19131
- catalogId: string().optional(),
19132
- installedAt: number().optional()
19539
+ /** One delivery target: a `notification-output` Target ref + passthrough params. */
19540
+ var NcRuleTargetSchema = object({
19541
+ /** `notification-output` Target id. */
19542
+ targetId: string().min(1),
19543
+ /**
19544
+ * Per-backend passthrough. Recognized keys are mapped onto the canonical
19545
+ * Notification (`priority`, `level`, `sound`, `clickUrl`, `ttl`); the
19546
+ * degrade engine drops what the backend can't render.
19547
+ */
19548
+ params: record(string(), unknown()).optional()
19133
19549
  });
19134
- var LlmRuntimeDiskUsageSchema = object({
19135
- nodeId: string(),
19136
- modelsBytes: number(),
19137
- freeBytes: number().optional()
19550
+ /**
19551
+ * Media attachment policy (P1 still-image subset).
19552
+ * - `best` — the best AVAILABLE subject image at dispatch time (D-3).
19553
+ * - `best-matching` — the media that explains WHY the rule fired: a rule
19554
+ * matched on identities attaches the subject's `faceCrop`, one matched on
19555
+ * plates attaches the `plateCrop`; a rule with no identity/plate condition
19556
+ * (or when the specific crop is missing) degrades to `best`, then
19557
+ * `keyFrame`, then no attachment — never delaying the send. The matched
19558
+ * condition summary is frozen on the outbox row at enqueue (like the rule
19559
+ * name), so the choice never drifts from the record that fired it.
19560
+ * - `keyFrame` — the clean scene frame (no subject box).
19561
+ * - `none` — no attachment.
19562
+ */
19563
+ var NcMediaPolicySchema = object({ attach: _enum([
19564
+ "best",
19565
+ "best-matching",
19566
+ "keyFrame",
19567
+ "none"
19568
+ ]).default("best") });
19569
+ /** Throttle — cooldown survives restarts (rebuilt from the outbox on boot). */
19570
+ var NcThrottleSchema = object({
19571
+ cooldownSec: number().int().min(0).max(86400).default(60),
19572
+ /** `rule` = one shared cooldown; `rule-device` = per-camera cooldown. */
19573
+ scope: _enum(["rule", "rule-device"]).default("rule-device")
19574
+ });
19575
+ /** Client-supplied rule fields (server stamps id/createdBy/createdAt/updatedAt). */
19576
+ var NcRuleInputSchema = object({
19577
+ name: string().min(1).max(200),
19578
+ enabled: boolean().default(true),
19579
+ delivery: NcDeliverySchema,
19580
+ conditions: NcConditionsSchema.default({}),
19581
+ schedule: NcScheduleSchema.optional(),
19582
+ targets: array(NcRuleTargetSchema).min(1),
19583
+ media: NcMediaPolicySchema.default({ attach: "best" }),
19584
+ throttle: NcThrottleSchema.default({
19585
+ cooldownSec: 60,
19586
+ scope: "rule-device"
19587
+ }),
19588
+ /** `{{var}}` templating over camera/class/label/zones/confidence/time. */
19589
+ template: object({
19590
+ title: string().max(500).optional(),
19591
+ body: string().max(2e3).optional()
19592
+ }).optional(),
19593
+ /** Canonical notification priority ordinal (1..5); per-target overridable. */
19594
+ priority: number().int().min(1).max(5).default(3),
19595
+ /**
19596
+ * Ownership/visibility key. Absent = admin/global rule (unchanged legacy
19597
+ * behaviour, visible to all, read-only in the viewer). Present = personal
19598
+ * rule owned by this userId. Server-stamped; never trusted from a client.
19599
+ */
19600
+ ownerUserId: string().optional()
19138
19601
  });
19139
- method(LlmGenerateBaseInputSchema.extend({
19140
- images: array(LlmImageSchema).optional(),
19141
- runtime: ManagedRuntimeConfigSchema,
19142
- /** The managed profile's timeout, threaded by the hub provider. */
19143
- timeoutMs: number().int().positive().optional()
19144
- }), LlmGenerateResultSchema, { kind: "mutation" }), method(object({ runtime: ManagedRuntimeConfigSchema }), LlmRuntimeStatusSchema, {
19145
- kind: "mutation",
19146
- auth: "admin"
19147
- }), method(object({}), _void(), {
19148
- kind: "mutation",
19149
- auth: "admin"
19150
- }), method(object({}), LlmRuntimeStatusSchema), method(object({ model: ManagedModelRefSchema }), _void(), {
19151
- kind: "mutation",
19152
- auth: "admin"
19153
- }), method(object({ file: string() }), _void(), {
19154
- kind: "mutation",
19155
- auth: "admin"
19156
- }), method(object({}), array(LlmNodeModelSchema)), method(object({}), LlmRuntimeDiskUsageSchema);
19157
19602
  /**
19158
- * `llm` — consumer-facing LLM surface (spec §1-§3). Collection-mode: array
19159
- * methods concat-fan across providers; single-row methods route to ONE
19160
- * provider by the `addonId` in the call input (the notification-output
19161
- * posture, notification-output.cap.ts:215-250). Provided by `addon-ai`
19162
- * (hub-placed); the cap stays open for future providers.
19163
- *
19164
- * Profiles are ROWS (data), not addons: one row = one usable model endpoint.
19165
- * `apiKey` is a password field — providers REDACT it on read and merge on
19166
- * write; a stored key NEVER round-trips to a client.
19603
+ * Partial patch for `updateRule` — any subset of the input fields, plus the
19604
+ * persisted-only {@link NcRuleSchema} `disabledTargetIds` set. The latter is
19605
+ * NOT a client-authored input field (it lives on the persisted rule, not the
19606
+ * input), so it is added here explicitly to let the store's per-target opt-out
19607
+ * toggle round-trip through the shared `update` path. Viewer opt-out mutations
19608
+ * still flow through `nc.setRuleTargetEnabled` (owner-checked), never a raw
19609
+ * `updateRule` patch.
19167
19610
  */
19168
- var LlmProfileKindSchema = _enum([
19169
- "openai-compatible",
19170
- "openai",
19171
- "anthropic",
19172
- "google",
19173
- "managed-local"
19174
- ]);
19175
- var LlmProfileSchema = object({
19611
+ var NcRulePatchSchema = NcRuleInputSchema.partial().extend({ disabledTargetIds: array(string()).optional() });
19612
+ /** A persisted rule. */
19613
+ var NcRuleSchema = NcRuleInputSchema.extend({
19176
19614
  id: string(),
19177
- name: string(),
19178
- kind: LlmProfileKindSchema,
19179
- /** Stamped by the provider — keeps the fanned catalog routable. */
19180
- addonId: string(),
19181
- enabled: boolean(),
19182
- /** Vendor model id, or the managed runtime's loaded model. */
19183
- model: string(),
19184
- /** Required for openai-compatible; override for cloud kinds. */
19185
- baseUrl: string().optional(),
19186
- /** ConfigUISchema type:'password' — never round-trips (spec §5). */
19187
- apiKey: string().optional(),
19188
- supportsVision: boolean(),
19189
- temperature: number().min(0).max(2).optional(),
19190
- maxTokens: number().int().positive().optional(),
19191
- timeoutMs: number().int().positive().default(6e4),
19192
- extraHeaders: record(string(), string()).optional(),
19193
- /** kind === 'managed-local' only (spec §4). */
19194
- runtime: ManagedRuntimeConfigSchema.optional()
19195
- });
19196
- /** ConfigUISchema tree passed through untyped on the wire (the
19197
- * notification-output `ConfigSchemaPassthrough` precedent at
19198
- * notification-output.cap.ts:151); the exported TS type re-tightens it. */
19199
- var ConfigSchemaPassthrough = unknown();
19200
- var LlmProfileKindDescriptorSchema = object({
19201
- kind: LlmProfileKindSchema,
19202
- label: string(),
19203
- icon: string(),
19204
- /** Stamped by each provider so the concat-fanned catalog stays routable. */
19205
- addonId: string(),
19206
- configSchema: ConfigSchemaPassthrough
19207
- });
19208
- var LlmDefaultSelectorSchema = union([object({ consumer: string() }), object({ purpose: _enum(["text", "vision"]) })]);
19209
- var LlmDefaultSchema = object({
19210
- selector: LlmDefaultSelectorSchema,
19211
- profileId: string()
19615
+ /** userId of the admin who created the rule (server-stamped caller). */
19616
+ createdBy: string(),
19617
+ createdAt: number(),
19618
+ updatedAt: number(),
19619
+ /**
19620
+ * Per-target opt-out set. A targetId here is suppressed for THIS rule at
19621
+ * send time. Only a target's OWNER may add/remove its id (server-checked
19622
+ * in `nc.setRuleTargetEnabled`). Defaults to empty.
19623
+ */
19624
+ disabledTargetIds: array(string()).default([])
19212
19625
  });
19213
- /** Server-side rollup row — getUsage never dumps raw call rows (spec §6). */
19214
- var LlmUsageRollupSchema = object({
19215
- day: string(),
19216
- consumer: string(),
19217
- profileId: string(),
19218
- calls: number(),
19219
- okCalls: number(),
19220
- errorCalls: number(),
19221
- inputTokens: number(),
19222
- outputTokens: number(),
19223
- avgLatencyMs: number()
19626
+ var NcTestResultSchema = object({
19627
+ recordId: string(),
19628
+ recordKind: _enum([
19629
+ "object-event",
19630
+ "track",
19631
+ "device-event",
19632
+ "package-event"
19633
+ ]),
19634
+ deviceId: number(),
19635
+ timestamp: number(),
19636
+ wouldFire: boolean(),
19637
+ /** Condition id that failed (first failing group), when `wouldFire` is false. */
19638
+ failedCondition: string().optional(),
19639
+ className: string().optional(),
19640
+ label: string().optional()
19224
19641
  });
19225
- /** LLM-facing view over the reused ModelCatalogEntry mechanism (spec §4.2). */
19226
- var ManagedModelCatalogEntrySchema = object({
19642
+ var NcConditionDescriptorSchema = object({
19643
+ /** Field id inside `NcConditions` (or `'schedule'` for the rule-level group). */
19227
19644
  id: string(),
19645
+ group: _enum([
19646
+ "scope",
19647
+ "class",
19648
+ "zones",
19649
+ "quality",
19650
+ "label",
19651
+ "schedule",
19652
+ "device",
19653
+ "package",
19654
+ "occupancy"
19655
+ ]),
19228
19656
  label: string(),
19229
- family: string(),
19230
- purpose: _enum(["text", "vision"]),
19231
- url: string(),
19232
- sha256: string(),
19233
- sizeBytes: number(),
19234
- quantization: string(),
19235
- /** Load-time guidance shown in the picker. */
19236
- minRamBytes: number(),
19237
- contextSizeDefault: number().int(),
19238
- /** Vision models: companion projector file. */
19239
- mmprojUrl: string().optional()
19657
+ /** Editor widget the UI renders — never hardcode per-condition forms. */
19658
+ valueType: _enum([
19659
+ "deviceIdList",
19660
+ "stringList",
19661
+ "number01",
19662
+ "number",
19663
+ "sourceSelect",
19664
+ "zoneSelection",
19665
+ "zoneIdList",
19666
+ "schedule",
19667
+ "plateMatcher",
19668
+ "packagePhase",
19669
+ "polygonDraw",
19670
+ "occupancy"
19671
+ ]),
19672
+ operator: _enum([
19673
+ "in",
19674
+ "notIn",
19675
+ "anyOf",
19676
+ "allOf",
19677
+ "gte",
19678
+ "fuzzyIn",
19679
+ "withinSchedule"
19680
+ ]),
19681
+ /** Which delivery kinds the condition applies to. */
19682
+ appliesTo: array(NcDeliverySchema),
19683
+ phase: string(),
19684
+ description: string().optional()
19240
19685
  });
19241
- var LlmRuntimeNodeSchema = object({
19242
- nodeId: string(),
19243
- reachable: boolean(),
19244
- status: LlmRuntimeStatusSchema.optional(),
19245
- disk: LlmRuntimeDiskUsageSchema.optional(),
19246
- error: string().optional()
19686
+ /**
19687
+ * The delivery lifecycle status of a history row — a straight read of the
19688
+ * durable outbox row's own status (single source of truth):
19689
+ * - `pending` — enqueued, in-flight or retrying with backoff
19690
+ * - `sent` — delivered (terminal)
19691
+ * - `dead` — dead-lettered after exhausting retries / a permanent
19692
+ * backend rejection / a deleted target (terminal; carries
19693
+ * the failure `error`)
19694
+ *
19695
+ * P1 has no `suppressed-quiet-hours` / `snoozed` states — those ride the P2
19696
+ * user dimension (quiet hours / snooze) and are additive when they land.
19697
+ */
19698
+ var NcHistoryStatusSchema = _enum([
19699
+ "pending",
19700
+ "sent",
19701
+ "dead"
19702
+ ]);
19703
+ /** The evaluated record kind a history row descends from (one per trigger). */
19704
+ var NcHistoryRecordKindSchema = _enum([
19705
+ "object-event",
19706
+ "track-end",
19707
+ "device-event",
19708
+ "package-event"
19709
+ ]);
19710
+ /** Subject summary frozen on the row at fire time (survives rule/record edits). */
19711
+ var NcHistorySubjectSchema = object({
19712
+ className: string(),
19713
+ label: string().optional(),
19714
+ confidence: number().optional(),
19715
+ zones: array(string()),
19716
+ timestamp: number()
19247
19717
  });
19248
- var GenerateVisionInputSchema = LlmGenerateBaseInputSchema.extend({ images: array(LlmImageSchema).min(1) });
19249
- var ProfileRefInputSchema = object({
19250
- addonId: string(),
19251
- profileId: string()
19718
+ /**
19719
+ * One delivery-history row. This is a read-only VIEW over the durable
19720
+ * outbox row (single source of truth — the same row the drain loop drives;
19721
+ * NO second write path, so history can never drift from delivery state).
19722
+ * The §3.2 fields map directly: `ruleId`/`targetId`/`deviceId` are columns,
19723
+ * `eventRef` is `recordKind`+`recordId`, `timestamps` are `createdAt`
19724
+ * (fire) / `updatedAt` (last transition), `status` + `error` are the
19725
+ * lifecycle. `ruleName` + `subject` are the intent snapshot frozen at
19726
+ * enqueue. `userId?` (per-recipient history) is P2 — no user dimension in
19727
+ * P1 (admin scope only).
19728
+ */
19729
+ var NcHistoryEntrySchema = object({
19730
+ /** Outbox row id — the stable dedup id `ruleId:dedupRef:targetId`. */
19731
+ id: string(),
19732
+ ruleId: string(),
19733
+ /** Rule name frozen at fire time (outlives a later rename / delete). */
19734
+ ruleName: string(),
19735
+ /** The rule urgency/trigger that produced this delivery. */
19736
+ delivery: NcDeliverySchema,
19737
+ targetId: string(),
19738
+ deviceId: number(),
19739
+ recordKind: NcHistoryRecordKindSchema,
19740
+ /** Event / track ref of the evaluated record (§3.2 `eventRef`). */
19741
+ recordId: string(),
19742
+ /** Present for track-scoped deliveries (object-event / track-end). */
19743
+ trackId: string().optional(),
19744
+ status: NcHistoryStatusSchema,
19745
+ /** Delivery attempts made so far. */
19746
+ attempts: number().int(),
19747
+ /** Fire time (outbox enqueue). */
19748
+ createdAt: number(),
19749
+ /** Last transition time (terminal for sent / dead). */
19750
+ updatedAt: number(),
19751
+ /** Failure detail — present on a `dead` row. */
19752
+ error: string().optional(),
19753
+ subject: NcHistorySubjectSchema
19252
19754
  });
19253
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
19254
- kind: "mutation",
19255
- auth: "admin"
19256
- }), method(ProfileRefInputSchema, _void(), {
19257
- kind: "mutation",
19258
- auth: "admin"
19259
- }), method(ProfileRefInputSchema, LlmGenerateResultSchema, {
19260
- kind: "mutation",
19261
- auth: "admin"
19262
- }), method(ProfileRefInputSchema, array(string())), method(object({}), array(LlmDefaultSchema)), method(object({
19263
- selector: LlmDefaultSelectorSchema,
19264
- profileId: string().nullable()
19265
- }), _void(), {
19266
- kind: "mutation",
19267
- auth: "admin"
19268
- }), method(object({
19755
+ /**
19756
+ * Query filter for `getHistory` (spec §4.2). Every field is a narrowing
19757
+ * AND; absent = unbounded on that axis. `since`/`until` bound the fire time
19758
+ * (`createdAt`, epoch ms, inclusive). `limit` is clamped to
19759
+ * {@link NC_HISTORY_LIMIT_MAX}. `userId` (per-recipient filtering) is P2.
19760
+ */
19761
+ var NcHistoryFilterSchema = object({
19762
+ ruleId: string().optional(),
19763
+ deviceId: number().optional(),
19764
+ status: NcHistoryStatusSchema.optional(),
19269
19765
  since: number().optional(),
19270
19766
  until: number().optional(),
19271
- consumer: string().optional(),
19272
- profileId: string().optional()
19273
- }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
19274
- nodeId: string(),
19275
- model: ManagedModelRefSchema
19276
- }), _void(), {
19767
+ limit: number().int().min(1).max(500).default(100)
19768
+ });
19769
+ method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), method(object({ ruleId: string() }), object({ rule: NcRuleSchema.nullable() }), { auth: "admin" }), method(object({ rule: NcRuleInputSchema }), object({ rule: NcRuleSchema }), {
19277
19770
  kind: "mutation",
19278
- auth: "admin"
19771
+ auth: "admin",
19772
+ caller: "required"
19279
19773
  }), method(object({
19280
- nodeId: string(),
19281
- file: string()
19282
- }), _void(), {
19774
+ ruleId: string(),
19775
+ patch: NcRulePatchSchema
19776
+ }), object({ rule: NcRuleSchema }), {
19777
+ kind: "mutation",
19778
+ auth: "admin",
19779
+ caller: "required"
19780
+ }), method(object({ ruleId: string() }), object({ success: literal(true) }), {
19283
19781
  kind: "mutation",
19284
19782
  auth: "admin"
19285
- }), method(ProfileRefInputSchema, LlmRuntimeStatusSchema), method(ProfileRefInputSchema, LlmRuntimeStatusSchema, {
19783
+ }), method(object({
19784
+ ruleId: string(),
19785
+ enabled: boolean()
19786
+ }), object({ success: literal(true) }), {
19286
19787
  kind: "mutation",
19287
19788
  auth: "admin"
19288
- }), method(ProfileRefInputSchema, _void(), {
19789
+ }), method(object({
19790
+ rule: NcRuleInputSchema,
19791
+ lookbackMinutes: number().int().min(1).max(1440).default(60)
19792
+ }), object({ results: array(NcTestResultSchema) }), {
19289
19793
  kind: "mutation",
19290
19794
  auth: "admin"
19291
- });
19795
+ }), method(object({}), object({ catalog: array(NcConditionDescriptorSchema) })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
19292
19796
  /**
19293
19797
  * Zod schemas for persisted record types.
19294
19798
  *
@@ -19974,7 +20478,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19974
20478
  }), method(object({
19975
20479
  eventId: string(),
19976
20480
  kind: MediaFileKindEnum.optional()
19977
- }), array(MediaFileSchema).readonly()), method(object({ trackId: string() }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
20481
+ }), array(MediaFileSchema).readonly()), method(object({
20482
+ trackId: string(),
20483
+ kinds: array(MediaFileKindEnum).optional()
20484
+ }), array(MediaFileSchema).readonly()), method(SearchObjectEventsInput, array(ScoredObjectEventSchema).readonly()), object({
19978
20485
  deviceId: number(),
19979
20486
  timestamp: number(),
19980
20487
  frameWidth: number(),
@@ -19995,76 +20502,6 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
19995
20502
  eventId: string(),
19996
20503
  timestamp: number()
19997
20504
  });
19998
- /**
19999
- * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
20000
- * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
20001
- * caps into per-camera event-kind descriptors.
20002
- *
20003
- * The descriptor DATA (color / iconId / labelKey / parentKind / category)
20004
- * is NOT duplicated here — every entry is derived from the single
20005
- * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
20006
- * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
20007
- * control cap means adding one line here (and a taxonomy entry); the anti-
20008
- * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
20009
- * eventful cap is missing.
20010
- */
20011
- /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
20012
- var LEGACY_ICON = {
20013
- motion: "motion",
20014
- audio: "audio",
20015
- person: "person",
20016
- vehicle: "vehicle",
20017
- animal: "animal",
20018
- package: "package",
20019
- door: "door",
20020
- pir: "pir",
20021
- smoke: "smoke",
20022
- water: "water",
20023
- button: "button",
20024
- generic: "generic",
20025
- gas: "smoke",
20026
- vibration: "generic",
20027
- tamper: "generic",
20028
- presence: "person",
20029
- lock: "generic",
20030
- siren: "generic",
20031
- switch: "generic",
20032
- doorbell: "button"
20033
- };
20034
- function legacyIcon(iconId) {
20035
- return LEGACY_ICON[iconId] ?? "generic";
20036
- }
20037
- /**
20038
- * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
20039
- * The anti-drift guard cross-checks this against the eventful caps declared
20040
- * in `packages/types/src/capabilities/*.cap.ts`.
20041
- */
20042
- var CAP_TO_KIND = {
20043
- contact: "contact",
20044
- motion: "motion-sensor",
20045
- smoke: "smoke",
20046
- flood: "flood",
20047
- gas: "gas",
20048
- "carbon-monoxide": "carbon-monoxide",
20049
- vibration: "vibration",
20050
- tamper: "tamper",
20051
- presence: "presence",
20052
- "enum-sensor": "enum-sensor",
20053
- "event-emitter": "device-event",
20054
- "lock-control": "lock",
20055
- switch: "switch",
20056
- button: "button",
20057
- doorbell: "doorbell"
20058
- };
20059
- function buildDescriptor(capName, kind) {
20060
- const t = EVENT_TAXONOMY[kind];
20061
- if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
20062
- return {
20063
- ...t,
20064
- icon: legacyIcon(t.iconId)
20065
- };
20066
- }
20067
- Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
20068
20505
  var CameraPipelineConfigSchema = object({
20069
20506
  engine: PipelineEngineChoiceSchema.optional(),
20070
20507
  steps: array(PipelineStepInputSchema).readonly(),
@@ -20550,6 +20987,76 @@ method(object({
20550
20987
  auth: "admin"
20551
20988
  });
20552
20989
  /**
20990
+ * Cap → event-kind mapping for the SENSOR / CONTROL cap families — the table
20991
+ * `pipeline-analytics.listEventKinds` uses to turn a linked device's bound
20992
+ * caps into per-camera event-kind descriptors.
20993
+ *
20994
+ * The descriptor DATA (color / iconId / labelKey / parentKind / category)
20995
+ * is NOT duplicated here — every entry is derived from the single
20996
+ * `EVENT_TAXONOMY` dictionary (`catalogs/event-taxonomy.ts`). This file owns
20997
+ * ONLY the cap-name → taxonomy-kind mapping. Adding a new eventful sensor /
20998
+ * control cap means adding one line here (and a taxonomy entry); the anti-
20999
+ * drift guard `scripts/check-event-kind-coverage.ts` fails the build if an
21000
+ * eventful cap is missing.
21001
+ */
21002
+ /** Map a taxonomy `iconId` onto the legacy closed `EventKindIcon` enum. */
21003
+ var LEGACY_ICON = {
21004
+ motion: "motion",
21005
+ audio: "audio",
21006
+ person: "person",
21007
+ vehicle: "vehicle",
21008
+ animal: "animal",
21009
+ package: "package",
21010
+ door: "door",
21011
+ pir: "pir",
21012
+ smoke: "smoke",
21013
+ water: "water",
21014
+ button: "button",
21015
+ generic: "generic",
21016
+ gas: "smoke",
21017
+ vibration: "generic",
21018
+ tamper: "generic",
21019
+ presence: "person",
21020
+ lock: "generic",
21021
+ siren: "generic",
21022
+ switch: "generic",
21023
+ doorbell: "button"
21024
+ };
21025
+ function legacyIcon(iconId) {
21026
+ return LEGACY_ICON[iconId] ?? "generic";
21027
+ }
21028
+ /**
21029
+ * Cap name → taxonomy kind id. Covers EVERY eventful sensor / control cap.
21030
+ * The anti-drift guard cross-checks this against the eventful caps declared
21031
+ * in `packages/types/src/capabilities/*.cap.ts`.
21032
+ */
21033
+ var CAP_TO_KIND = {
21034
+ contact: "contact",
21035
+ motion: "motion-sensor",
21036
+ smoke: "smoke",
21037
+ flood: "flood",
21038
+ gas: "gas",
21039
+ "carbon-monoxide": "carbon-monoxide",
21040
+ vibration: "vibration",
21041
+ tamper: "tamper",
21042
+ presence: "presence",
21043
+ "enum-sensor": "enum-sensor",
21044
+ "event-emitter": "device-event",
21045
+ "lock-control": "lock",
21046
+ switch: "switch",
21047
+ button: "button",
21048
+ doorbell: "doorbell"
21049
+ };
21050
+ function buildDescriptor(capName, kind) {
21051
+ const t = EVENT_TAXONOMY[kind];
21052
+ if (t === void 0) throw new Error(`EVENT_KIND_BY_CAP: cap '${capName}' maps to unknown taxonomy kind '${kind}'`);
21053
+ return {
21054
+ ...t,
21055
+ icon: legacyIcon(t.iconId)
21056
+ };
21057
+ }
21058
+ Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
21059
+ /**
20553
21060
  * server-management — per-NODE singleton capability for a node's ROOT
20554
21061
  * package lifecycle (runtime-updatable node packages).
20555
21062
  *
@@ -22055,7 +22562,28 @@ var FaceInfoSchema = object({
22055
22562
  * (`/addon/<addonId>/event-media/<keyFrameMediaKey>`). Absent when the
22056
22563
  * track produced no key frame (e.g. native/onboard source) — the UI falls
22057
22564
  * back to the inline `base64` face crop. */
22058
- keyFrameMediaKey: string().optional()
22565
+ keyFrameMediaKey: string().optional(),
22566
+ /** Winning identity-match cosine (0..1) for this face's track, when an
22567
+ * identity was auto-confirmed. Lets the UI surface WHY a face was assigned
22568
+ * (confidence badge / low-confidence audit). Absent on legacy rows and on
22569
+ * faces that were never auto-recognized. */
22570
+ bestMatchScore: number().optional(),
22571
+ /** Native-scale face short side (px) at recognition time, when the runner
22572
+ * measured it. Lets the UI flag low-resolution auto-assignments. Absent on
22573
+ * legacy rows / runners that reported no native measure. */
22574
+ nativeFaceShortSidePx: number().optional(),
22575
+ /** SUGGESTED identity for this face — a plausible-but-not-confident match that
22576
+ * MISSED auto-assignment (cosine in the suggestion band, or above threshold
22577
+ * but blocked only by the recognition size floor). Mutually exclusive with
22578
+ * `recognizedIdentityId` (a suggestion is NEVER an assignment): the face stays
22579
+ * UNASSIGNED and everything else keeps treating it as unrecognized — the UI
22580
+ * merely offers a one-tap "is this <name>?" confirm. Absent on legacy rows and
22581
+ * on faces that were auto-assigned or below the suggestion band. (2026-07-24) */
22582
+ suggestedIdentityId: string().optional(),
22583
+ /** Peak identity-match cosine (0..1) for `suggestedIdentityId`, captured at the
22584
+ * same moment as `bestMatchScore` (track peak, at close). Lets the UI rank /
22585
+ * badge suggestion confidence. Present iff `suggestedIdentityId` is. (2026-07-24) */
22586
+ suggestedMatchScore: number().optional()
22059
22587
  });
22060
22588
  var FaceFilterEnum = _enum([
22061
22589
  "unassigned",
@@ -24427,36 +24955,6 @@ Object.freeze({
24427
24955
  addonId: null,
24428
24956
  access: "view"
24429
24957
  },
24430
- "advancedNotifier.deleteRule": {
24431
- capName: "advanced-notifier",
24432
- capScope: "system",
24433
- addonId: null,
24434
- access: "delete"
24435
- },
24436
- "advancedNotifier.getHistory": {
24437
- capName: "advanced-notifier",
24438
- capScope: "system",
24439
- addonId: null,
24440
- access: "view"
24441
- },
24442
- "advancedNotifier.getRules": {
24443
- capName: "advanced-notifier",
24444
- capScope: "system",
24445
- addonId: null,
24446
- access: "view"
24447
- },
24448
- "advancedNotifier.testRule": {
24449
- capName: "advanced-notifier",
24450
- capScope: "system",
24451
- addonId: null,
24452
- access: "create"
24453
- },
24454
- "advancedNotifier.upsertRule": {
24455
- capName: "advanced-notifier",
24456
- capScope: "system",
24457
- addonId: null,
24458
- access: "create"
24459
- },
24460
24958
  "alarmPanel.arm": {
24461
24959
  capName: "alarm-panel",
24462
24960
  capScope: "device",
@@ -26761,6 +27259,60 @@ Object.freeze({
26761
27259
  addonId: null,
26762
27260
  access: "create"
26763
27261
  },
27262
+ "notificationRules.createRule": {
27263
+ capName: "notification-rules",
27264
+ capScope: "system",
27265
+ addonId: null,
27266
+ access: "create"
27267
+ },
27268
+ "notificationRules.deleteRule": {
27269
+ capName: "notification-rules",
27270
+ capScope: "system",
27271
+ addonId: null,
27272
+ access: "delete"
27273
+ },
27274
+ "notificationRules.getConditionCatalog": {
27275
+ capName: "notification-rules",
27276
+ capScope: "system",
27277
+ addonId: null,
27278
+ access: "view"
27279
+ },
27280
+ "notificationRules.getHistory": {
27281
+ capName: "notification-rules",
27282
+ capScope: "system",
27283
+ addonId: null,
27284
+ access: "view"
27285
+ },
27286
+ "notificationRules.getRule": {
27287
+ capName: "notification-rules",
27288
+ capScope: "system",
27289
+ addonId: null,
27290
+ access: "view"
27291
+ },
27292
+ "notificationRules.listRules": {
27293
+ capName: "notification-rules",
27294
+ capScope: "system",
27295
+ addonId: null,
27296
+ access: "view"
27297
+ },
27298
+ "notificationRules.setRuleEnabled": {
27299
+ capName: "notification-rules",
27300
+ capScope: "system",
27301
+ addonId: null,
27302
+ access: "create"
27303
+ },
27304
+ "notificationRules.testRule": {
27305
+ capName: "notification-rules",
27306
+ capScope: "system",
27307
+ addonId: null,
27308
+ access: "create"
27309
+ },
27310
+ "notificationRules.updateRule": {
27311
+ capName: "notification-rules",
27312
+ capScope: "system",
27313
+ addonId: null,
27314
+ access: "create"
27315
+ },
26764
27316
  "notifier.cancel": {
26765
27317
  capName: "notifier",
26766
27318
  capScope: "device",
@@ -219023,6 +219575,31 @@ var reolinkCameraSchema = object({
219023
219575
  ext: ReolinkStreamProfileOptionsSchema.optional()
219024
219576
  }).optional(),
219025
219577
  /**
219578
+ * Persisted `getOptions` descriptors for the device-config caps
219579
+ * (`stream-params`, `motion-zones`, `privacy-mask`, `day-night`,
219580
+ * `image-settings`, `ptz`), keyed by cap name.
219581
+ *
219582
+ * WHY: the device-detail aggregate (`deviceManager.getDeviceAggregate`)
219583
+ * calls `getOptions` + `getStatus` on EVERY bound device-config cap,
219584
+ * and the admin UI polls it every 2.5s while the Config tab is open.
219585
+ * Un-cached, that is ~7 Baichuan round-trips every 2.5s — which keeps
219586
+ * a battery camera permanently awake and wakes a sleeping one on a
219587
+ * plain page visit. These descriptors are static per camera model
219588
+ * (advertised ranges / codec sets / supported axes), so they are read
219589
+ * once, persisted here, and served from the blob until the TTL
219590
+ * expires (see `ReolinkCamera.resolveCapOptions`).
219591
+ *
219592
+ * `value` is intentionally `unknown`: this blob stays self-contained
219593
+ * (no cross-package schema identity — same rationale as
219594
+ * `ReolinkStreamProfileOptionsSchema` above). The reader validates
219595
+ * each entry with the cap's own Zod schema, so a stale/incompatible
219596
+ * shape is discarded instead of cast.
219597
+ */
219598
+ capOptionsSnapshot: record(string(), object({
219599
+ value: unknown(),
219600
+ fetchedAt: number()
219601
+ })).optional(),
219602
+ /**
219026
219603
  * Snapshot of the camera's privacy mask master switch from
219027
219604
  * `getMask` (cmdId=52). Zone editing is a separate flow —
219028
219605
  * we only expose the master enable.
@@ -221042,15 +221619,48 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
221042
221619
  */
221043
221620
  sleepStateChangedAt = 0;
221044
221621
  /**
221045
- * Min time between observed sleep transitions before we honour
221046
- * another flip. Picked >= the lib's full UDP inference cycle
221047
- * (~12s on battery cams with idle-disconnect) so a single
221048
- * inference flap doesn't pass through. 30s is also longer than
221049
- * `getIdleDisconnectTimeoutMs` (default 30s in the lib), which
221050
- * means a transient socket close → reopen pattern can't drive
221051
- * us through a full state cycle either.
221052
- */
221053
- static SLEEP_HYSTERESIS_MS = 3e4;
221622
+ * Hysteresis is ASYMMETRIC, because the two directions have very
221623
+ * different costs when we get them wrong.
221624
+ *
221625
+ * `→ awake` (`WAKE_HYSTERESIS_MS`): expensive if wrong. Believing an
221626
+ * asleep camera is awake un-gates every background probe
221627
+ * (`refreshParentSettingsSnapshot`, the device-config cap refreshes,
221628
+ * aux align) and makes `wakeForStream` early-out without actually
221629
+ * waking. Keep the full window >= the lib's UDP inference cycle
221630
+ * (~12s on battery cams with idle-disconnect) and >= the lib's
221631
+ * `getIdleDisconnectTimeoutMs` (30s default), so neither an
221632
+ * inference flap nor a transient socket close→reopen can walk us
221633
+ * into a false "awake".
221634
+ *
221635
+ * `→ sleeping` (`SLEEP_HYSTERESIS_MS`): cheap if wrong. Believing an
221636
+ * awake camera is asleep only means we skip background probes and
221637
+ * serve cached values; the demand paths (`wakeForStream`,
221638
+ * `wakeIfSleeping`) still drive a real wake. The old symmetric 30s
221639
+ * window was LONGER than the camera's own awake window (~14s — see
221640
+ * `onWakeTransition`), so a natural wake→sleep cycle had its
221641
+ * `sleeping` transition dropped and the slice stayed stuck on
221642
+ * "awake" while the camera slept: the exact "at rest we lose the
221643
+ * sleeping state" symptom. 5s still absorbs a single 2s inference
221644
+ * tick while tracking the real cycle.
221645
+ */
221646
+ static WAKE_HYSTERESIS_MS = 3e4;
221647
+ static SLEEP_HYSTERESIS_MS = 5e3;
221648
+ /**
221649
+ * Wall-clock ms of the last PROACTIVE wake — one we issued on our own
221650
+ * initiative (background snapshot refresh), not because the operator
221651
+ * or a stream consumer asked for the camera. Drives
221652
+ * `canProactivelyWake` below.
221653
+ */
221654
+ lastProactiveWakeAt = 0;
221655
+ /**
221656
+ * Minimum gap between two proactive wakes. Demand-driven wakes
221657
+ * (`wakeForStream` from the broker, `wakeIfSleeping` behind an
221658
+ * operator action, the intercom pre-wake) bypass this entirely —
221659
+ * the operator asked, the operator gets the camera. Only
221660
+ * self-initiated wakes are rate-limited, so a thumbnail cache miss
221661
+ * can't wake a doorbell every few minutes.
221662
+ */
221663
+ static PROACTIVE_WAKE_COOLDOWN_MS = 10 * 6e4;
221054
221664
  /** Background timer that runs the passive sleep poll (battery cams only). */
221055
221665
  sleepPollTimer = null;
221056
221666
  /** Periodic timer driving `alignAuxDevicesState()` on wired cams.
@@ -221534,6 +222144,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
221534
222144
  } catch {
221535
222145
  return false;
221536
222146
  }
222147
+ this.markWakeIssued();
221537
222148
  this.ctx.logger.info("proactive action: waking sleeping battery cam", {
221538
222149
  tags: { deviceId: this.id },
221539
222150
  meta: { timeoutMs }
@@ -221830,6 +222441,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
221830
222441
  durationMs: Date.now() - startedAt
221831
222442
  };
221832
222443
  }
222444
+ this.markWakeIssued();
221833
222445
  this.ctx.logger.info("battery wakeForStream: cam sleeping — issuing wake", {
221834
222446
  tags: { deviceId: this.id },
221835
222447
  meta: { timeoutMs }
@@ -221902,7 +222514,8 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
221902
222514
  /**
221903
222515
  * Decide whether to honour a sleep-state transition. Returns
221904
222516
  * `false` when the lib's UDP inference is still inside the
221905
- * hysteresis window (8s by default) so we don't flap. The first
222517
+ * hysteresis window so we don't flap. The window is asymmetric —
222518
+ * see `WAKE_HYSTERESIS_MS` / `SLEEP_HYSTERESIS_MS`. The first
221906
222519
  * transition AFTER an api login / restart is always honoured —
221907
222520
  * no prior-flip timestamp gating it.
221908
222521
  *
@@ -221912,11 +222525,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
221912
222525
  acceptSleepingTransition(next) {
221913
222526
  if (this.sleeping === next) return false;
221914
222527
  const now = Date.now();
221915
- if (this.sleepStateChangedAt > 0 && now - this.sleepStateChangedAt < ReolinkCamera.SLEEP_HYSTERESIS_MS) {
222528
+ const windowMs = next ? ReolinkCamera.SLEEP_HYSTERESIS_MS : ReolinkCamera.WAKE_HYSTERESIS_MS;
222529
+ if (this.sleepStateChangedAt > 0 && now - this.sleepStateChangedAt < windowMs) {
221916
222530
  this.ctx.logger.debug("ignoring sleep inference flap within hysteresis window", {
221917
222531
  tags: { deviceId: this.id },
221918
222532
  meta: {
221919
222533
  next,
222534
+ windowMs,
221920
222535
  sinceLastChangeMs: now - this.sleepStateChangedAt
221921
222536
  }
221922
222537
  });
@@ -221925,6 +222540,86 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
221925
222540
  this.sleepStateChangedAt = now;
221926
222541
  return true;
221927
222542
  }
222543
+ /**
222544
+ * THE single writer of the `battery.sleeping` slice.
222545
+ *
222546
+ * Before this existed the state had three independent writers with
222547
+ * three different rules: the `awake`/`sleeping` simpleEvent handlers
222548
+ * (hysteresis-gated) and the sleep poll (which wrote the slice
222549
+ * directly, bypassing the hysteresis AND leaving
222550
+ * `sleepStateChangedAt` stale so the NEXT event compared against an
222551
+ * ancient timestamp). Funnelling every writer through here keeps one
222552
+ * rule set and one timestamp.
222553
+ *
222554
+ * @param source - `'hub-summary'` is AUTHORITATIVE (the NVR reports
222555
+ * per-channel sleep state from its own firmware, not from socket
222556
+ * I/O inference) and therefore bypasses the hysteresis. The other
222557
+ * two sources are inference-derived and stay gated.
222558
+ * @returns `true` when the slice actually changed.
222559
+ */
222560
+ commitSleepState(next, source) {
222561
+ if (!this.isBattery) return false;
222562
+ if (this.sleeping === next) return false;
222563
+ if (source !== "hub-summary" && !this.acceptSleepingTransition(next)) return false;
222564
+ if (source === "hub-summary") this.sleepStateChangedAt = Date.now();
222565
+ this.state.battery.sleeping = next;
222566
+ this.ctx.logger.info("battery sleep state committed", {
222567
+ tags: { deviceId: this.id },
222568
+ meta: {
222569
+ sleeping: next,
222570
+ source
222571
+ }
222572
+ });
222573
+ return true;
222574
+ }
222575
+ /**
222576
+ * Hub-driven sleep reconcile. The NVR's `getNvrChannelsSummary`
222577
+ * carries a per-channel `sleeping` flag that the parent Hub already
222578
+ * pulls on every discovery refresh — firmware truth, obtained over
222579
+ * the Hub's own mains-powered socket, costing the battery channel
222580
+ * nothing. Before this the flag died inside the Hub's
222581
+ * `device-discovery` slice and the adopted child's sleep state
222582
+ * depended entirely on routed simpleEvents; a child that missed a
222583
+ * transition (or whose channel dropped out of the routing map while
222584
+ * deep-asleep) kept serving a stale value indefinitely.
222585
+ *
222586
+ * No-op for non-battery children. Called by `ReolinkHub` after each
222587
+ * successful discovery refresh.
222588
+ */
222589
+ applyHubSleepState(sleeping) {
222590
+ if (!this.isBattery) return;
222591
+ if (this.commitSleepState(sleeping, "hub-summary") && !sleeping) this.onWakeTransition("hub-summary").catch(() => {});
222592
+ }
222593
+ /**
222594
+ * Rate-limit for wakes we issue on our OWN initiative. Returns
222595
+ * `false` when a proactive wake happened less than
222596
+ * `PROACTIVE_WAKE_COOLDOWN_MS` ago — the caller must then serve
222597
+ * whatever it has cached instead of reaching for the radio.
222598
+ *
222599
+ * Demand-driven paths never call this: `wakeForStream` (a consumer
222600
+ * wants live video), `wakeIfSleeping` (an operator clicked
222601
+ * something) and the intercom pre-wake all wake unconditionally.
222602
+ */
222603
+ canProactivelyWake(reason) {
222604
+ if (this.lastProactiveWakeAt === 0) return true;
222605
+ const sinceMs = Date.now() - this.lastProactiveWakeAt;
222606
+ if (sinceMs >= ReolinkCamera.PROACTIVE_WAKE_COOLDOWN_MS) return true;
222607
+ this.ctx.logger.debug("proactive wake suppressed by cooldown", {
222608
+ tags: { deviceId: this.id },
222609
+ meta: {
222610
+ reason,
222611
+ sinceMs,
222612
+ cooldownMs: ReolinkCamera.PROACTIVE_WAKE_COOLDOWN_MS
222613
+ }
222614
+ });
222615
+ return false;
222616
+ }
222617
+ /** Stamp the proactive-wake cooldown. Called by every path that
222618
+ * actually issues a wake — demand-driven ones included, so an
222619
+ * operator-triggered wake also postpones the next proactive one. */
222620
+ markWakeIssued() {
222621
+ this.lastProactiveWakeAt = Date.now();
222622
+ }
221928
222623
  updateBatteryCache(info) {
221929
222624
  this.setCapSlice(batteryCapability, this.mapBatteryInfo(info));
221930
222625
  }
@@ -222187,16 +222882,23 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222187
222882
  } catch {
222188
222883
  return true;
222189
222884
  }
222190
- })()) try {
222191
- await api.wakeUp(this.getChannel(), {
222192
- waitAfterWakeMs: 1500,
222193
- attempts: 2
222194
- });
222195
- } catch (err) {
222196
- this.ctx.logger.debug("snapshot: pre-wake failed (will still try getSnapshot)", {
222197
- tags: { deviceId: this.id },
222198
- meta: { error: err instanceof Error ? err.message : String(err) }
222199
- });
222885
+ })()) {
222886
+ if (!this.canProactivelyWake("snapshot")) {
222887
+ this.ctx.logger.debug("snapshot: skipped — sleeping battery cam inside wake cooldown", { tags: { deviceId: this.id } });
222888
+ return null;
222889
+ }
222890
+ this.markWakeIssued();
222891
+ try {
222892
+ await api.wakeUp(this.getChannel(), {
222893
+ waitAfterWakeMs: 1500,
222894
+ attempts: 2
222895
+ });
222896
+ } catch (err) {
222897
+ this.ctx.logger.debug("snapshot: pre-wake failed (will still try getSnapshot)", {
222898
+ tags: { deviceId: this.id },
222899
+ meta: { error: err instanceof Error ? err.message : String(err) }
222900
+ });
222901
+ }
222200
222902
  }
222201
222903
  const tryOnce = async (timeoutMs) => {
222202
222904
  const buf = await api.getSnapshot(this.getChannel(), {
@@ -222648,6 +223350,117 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222648
223350
  await (await this.ensureApi()).setEnc(this.getChannel(), { [streamKey]: encPatch });
222649
223351
  this.cachedStreamDescriptors = void 0;
222650
223352
  }
223353
+ /** How long a persisted `getOptions` descriptor stays authoritative.
223354
+ * These describe model capabilities (advertised ranges, codec sets,
223355
+ * supported axes), not runtime state — they change on a firmware
223356
+ * update, not during operation. 6h keeps a firmware upgrade visible
223357
+ * within a day while removing the per-poll round-trip entirely. */
223358
+ static CAP_OPTIONS_TTL_MS = 360 * 6e4;
223359
+ /**
223360
+ * Read a persisted `getOptions` descriptor, validated with the cap's
223361
+ * OWN Zod schema. Validation (not a cast) is what makes the
223362
+ * `z.unknown()` blob type-safe: an entry written by an older addon
223363
+ * whose shape no longer parses is simply discarded, and the caller
223364
+ * re-probes.
223365
+ */
223366
+ readCapOptionsCache(capName, schema) {
223367
+ const entry = this.config.get("deviceCache")?.capOptionsSnapshot?.[capName];
223368
+ if (!entry) return null;
223369
+ const parsed = schema.safeParse(entry.value);
223370
+ if (!parsed.success) return null;
223371
+ return {
223372
+ value: parsed.data,
223373
+ fetchedAt: entry.fetchedAt
223374
+ };
223375
+ }
223376
+ /** Persist a freshly-probed descriptor. Best-effort — a failed write
223377
+ * only costs the next caller another probe. */
223378
+ async persistCapOptions(capName, value) {
223379
+ try {
223380
+ const current = this.config.get("deviceCache") ?? {};
223381
+ await this.config.setAll({ deviceCache: {
223382
+ ...current,
223383
+ capOptionsSnapshot: {
223384
+ ...current.capOptionsSnapshot,
223385
+ [capName]: {
223386
+ value,
223387
+ fetchedAt: Date.now()
223388
+ }
223389
+ }
223390
+ } });
223391
+ } catch (err) {
223392
+ this.ctx.logger.debug("cap options persist failed", {
223393
+ tags: { deviceId: this.id },
223394
+ meta: {
223395
+ capName,
223396
+ error: err instanceof Error ? err.message : String(err)
223397
+ }
223398
+ });
223399
+ }
223400
+ }
223401
+ /**
223402
+ * Resolve a device-config cap's `getOptions` descriptor without
223403
+ * touching a sleeping camera and without re-probing on every
223404
+ * aggregate poll.
223405
+ *
223406
+ * Order of resolution:
223407
+ * 1. fresh persisted entry (within `CAP_OPTIONS_TTL_MS`) → serve it;
223408
+ * 2. battery cam believed asleep → serve the stale persisted entry
223409
+ * if we have one, otherwise `fallback()`. NEVER probes: this is
223410
+ * the path a page visit takes on a sleeping doorbell.
223411
+ * 3. otherwise probe the camera, persist, serve.
223412
+ * A probe failure falls back to the stale entry, then `fallback()`.
223413
+ */
223414
+ async resolveCapOptions(params) {
223415
+ const { capName, schema, probe, fallback } = params;
223416
+ const cached = this.readCapOptionsCache(capName, schema);
223417
+ if (cached && Date.now() - cached.fetchedAt < ReolinkCamera.CAP_OPTIONS_TTL_MS) return cached.value;
223418
+ if (this.isBattery && this.sleeping) {
223419
+ this.ctx.logger.debug("cap options: battery cam sleeping — serving cache, not probing", {
223420
+ tags: { deviceId: this.id },
223421
+ meta: {
223422
+ capName,
223423
+ hasCache: cached !== null
223424
+ }
223425
+ });
223426
+ return cached?.value ?? fallback();
223427
+ }
223428
+ try {
223429
+ const value = await probe();
223430
+ await this.persistCapOptions(capName, value);
223431
+ return value;
223432
+ } catch (err) {
223433
+ this.ctx.logger.debug("cap options probe failed — serving cache/fallback", {
223434
+ tags: { deviceId: this.id },
223435
+ meta: {
223436
+ capName,
223437
+ error: err instanceof Error ? err.message : String(err)
223438
+ }
223439
+ });
223440
+ return cached?.value ?? fallback();
223441
+ }
223442
+ }
223443
+ /**
223444
+ * Wrap a cap's `refreshFromCamera` so the READ side (the bridge's
223445
+ * stale-check behind `getStatus`) never wakes a sleeping battery cam.
223446
+ * The bridge then projects whatever the slice last held — which is
223447
+ * exactly what the operator should see for a camera that is asleep.
223448
+ *
223449
+ * Only the bridge gets the wrapped version; `setX` mutations keep the
223450
+ * raw refresh so a write still re-reads the firmware's clamped result.
223451
+ */
223452
+ sleepGatedRefresh(capName, refresh) {
223453
+ return async () => {
223454
+ if (this.isBattery && this.sleeping) {
223455
+ this.ctx.logger.debug("cap status refresh skipped — battery cam is sleeping", {
223456
+ tags: { deviceId: this.id },
223457
+ meta: { capName }
223458
+ });
223459
+ return;
223460
+ }
223461
+ await refresh();
223462
+ };
223463
+ }
222651
223464
  /**
222652
223465
  * Register the `stream-params` native cap provider.
222653
223466
  *
@@ -222655,9 +223468,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222655
223468
  * source of truth is `runtimeState['stream-params']`, kept fresh via a
222656
223469
  * `createRuntimeStateBridge` with a `refresh` that round-trips `getEnc`.
222657
223470
  *
222658
- * - `getStatus` — slice-driven via bridge (stale → refresh from camera).
222659
- * - `getOptions` on-demand `getEncOptions` call; not cached in the
222660
- * runtimeState slice (options don't change at runtime).
223471
+ * - `getStatus` — slice-driven via bridge (stale → refresh from camera,
223472
+ * sleep-gated so a read never wakes a battery cam).
223473
+ * - `getOptions` persisted descriptor via `resolveCapOptions`; the
223474
+ * `getEncOptions` round-trip runs at most once per TTL.
222661
223475
  * - `setProfile` — translates cap patch → `EncStreamPatch`, calls
222662
223476
  * `setEnc`, then refreshes the slice.
222663
223477
  */
@@ -222702,19 +223516,25 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222702
223516
  runtimeState: this.runtimeState,
222703
223517
  cap: streamParamsCapability,
222704
223518
  ownDeviceId: this.id,
222705
- refresh: refreshFromCamera,
223519
+ refresh: this.sleepGatedRefresh(CAP_NAME, refreshFromCamera),
222706
223520
  staleMs: STALE_MS,
222707
223521
  empty: () => ({ lastFetchedAt: 0 })
222708
223522
  });
223523
+ const resolveOptions = async () => this.resolveCapOptions({
223524
+ capName: CAP_NAME,
223525
+ schema: StreamParamsOptionsSchema,
223526
+ probe: () => this.probeStreamParamsOptions(),
223527
+ fallback: () => ({})
223528
+ });
222709
223529
  const provider = {
222710
223530
  getStatus: bridge.getStatus,
222711
223531
  getOptions: async ({ deviceId }) => {
222712
223532
  if (deviceId !== this.id) return {};
222713
- return this.probeStreamParamsOptions();
223533
+ return resolveOptions();
222714
223534
  },
222715
223535
  getConfigSchema: async ({ deviceId }) => {
222716
223536
  if (deviceId !== this.id) return null;
222717
- const opts = await this.probeStreamParamsOptions();
223537
+ const opts = await resolveOptions();
222718
223538
  await bridge.ensureFresh();
222719
223539
  return buildStreamParamsConfigSchema(opts, this.runtimeState.getCapState(CAP_NAME) ?? null);
222720
223540
  },
@@ -222827,7 +223647,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222827
223647
  runtimeState: this.runtimeState,
222828
223648
  cap: motionZonesCapability,
222829
223649
  ownDeviceId: this.id,
222830
- refresh: refreshFromCamera,
223650
+ refresh: this.sleepGatedRefresh(CAP_NAME, refreshFromCamera),
222831
223651
  staleMs: STALE_MS,
222832
223652
  empty: () => ({
222833
223653
  enabled: false,
@@ -222838,27 +223658,46 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222838
223658
  }).getStatus,
222839
223659
  getOptions: async ({ deviceId }) => {
222840
223660
  if (deviceId !== this.id) throw new Error(`ReolinkCamera: deviceId mismatch, expected ${this.id}, got ${deviceId}`);
222841
- const raw = await (await this.ensureApi()).getMotionAlarm(channel);
222842
- const { scope } = this.parseMotionAlarm(raw);
222843
- this.motionZonesGrid = {
222844
- columns: scope.columns,
222845
- rows: scope.rows,
222846
- width: scope.width,
222847
- height: scope.height
222848
- };
222849
- return {
222850
- maxRegions: 1,
222851
- supportedShapes: ["grid"],
222852
- grid: {
222853
- width: scope.width,
222854
- height: scope.height
223661
+ return this.resolveCapOptions({
223662
+ capName: CAP_NAME,
223663
+ schema: MotionZoneOptionsSchema,
223664
+ probe: async () => {
223665
+ const raw = await (await this.ensureApi()).getMotionAlarm(channel);
223666
+ const { scope } = this.parseMotionAlarm(raw);
223667
+ this.motionZonesGrid = {
223668
+ columns: scope.columns,
223669
+ rows: scope.rows,
223670
+ width: scope.width,
223671
+ height: scope.height
223672
+ };
223673
+ return {
223674
+ maxRegions: 1,
223675
+ supportedShapes: ["grid"],
223676
+ grid: {
223677
+ width: scope.width,
223678
+ height: scope.height
223679
+ },
223680
+ sensitivity: {
223681
+ min: 1,
223682
+ max: 50,
223683
+ step: 1
223684
+ }
223685
+ };
222855
223686
  },
222856
- sensitivity: {
222857
- min: 1,
222858
- max: 50,
222859
- step: 1
222860
- }
222861
- };
223687
+ fallback: () => ({
223688
+ maxRegions: 1,
223689
+ supportedShapes: [],
223690
+ grid: {
223691
+ width: 0,
223692
+ height: 0
223693
+ },
223694
+ sensitivity: {
223695
+ min: 1,
223696
+ max: 50,
223697
+ step: 1
223698
+ }
223699
+ })
223700
+ });
222862
223701
  },
222863
223702
  setZone: async ({ deviceId, patch }) => {
222864
223703
  if (deviceId !== this.id) return;
@@ -222966,7 +223805,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222966
223805
  runtimeState: this.runtimeState,
222967
223806
  cap: privacyMaskCapability,
222968
223807
  ownDeviceId: this.id,
222969
- refresh: refreshFromCamera,
223808
+ refresh: this.sleepGatedRefresh(CAP_NAME, refreshFromCamera),
222970
223809
  staleMs: STALE_MS,
222971
223810
  empty: () => ({
222972
223811
  enabled: false,
@@ -222979,18 +223818,21 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
222979
223818
  maxRegions: 4,
222980
223819
  supportedShapes: ["rect"]
222981
223820
  };
222982
- try {
222983
- const zones = await (await this.ensureApi()).getMaskZones(channel);
222984
- return {
222985
- maxRegions: zones.maxNum,
222986
- supportedShapes: zones.maxNum > 0 ? ["rect"] : []
222987
- };
222988
- } catch {
222989
- return {
223821
+ return this.resolveCapOptions({
223822
+ capName: CAP_NAME,
223823
+ schema: PrivacyMaskOptionsSchema,
223824
+ probe: async () => {
223825
+ const zones = await (await this.ensureApi()).getMaskZones(channel);
223826
+ return {
223827
+ maxRegions: zones.maxNum,
223828
+ supportedShapes: zones.maxNum > 0 ? ["rect"] : []
223829
+ };
223830
+ },
223831
+ fallback: () => ({
222990
223832
  maxRegions: 4,
222991
223833
  supportedShapes: ["rect"]
222992
- };
222993
- }
223834
+ })
223835
+ });
222994
223836
  },
222995
223837
  setMask: async ({ deviceId, patch }) => {
222996
223838
  if (deviceId !== this.id) return;
@@ -223097,7 +223939,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
223097
223939
  runtimeState: this.runtimeState,
223098
223940
  cap: dayNightCapability,
223099
223941
  ownDeviceId: this.id,
223100
- refresh: refreshFromCamera,
223942
+ refresh: this.sleepGatedRefresh(CAP_NAME, refreshFromCamera),
223101
223943
  staleMs: STALE_MS,
223102
223944
  empty: () => ({
223103
223945
  mode: "auto",
@@ -223106,36 +223948,47 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
223106
223948
  }).getStatus,
223107
223949
  getOptions: async ({ deviceId }) => {
223108
223950
  if (deviceId !== this.id) throw new Error(`ReolinkCamera: deviceId mismatch, expected ${this.id}, got ${deviceId}`);
223109
- const api = await this.ensureApi();
223110
- const modes = ((await api.getVideoInput(channel))?.body?.VideoInput)?.dayNight !== void 0 ? [
223111
- "auto",
223112
- "day",
223113
- "night"
223114
- ] : [];
223115
- let supportsSensitivity = false;
223116
- let sensitivityRange;
223117
- try {
223118
- const range = (await api.getDayNightThreshold(channel))?.body?.DayNightThreshold?.thresholdval;
223119
- if (typeof range?.min === "number" && typeof range?.max === "number") {
223120
- supportsSensitivity = true;
223121
- sensitivityRange = {
223122
- min: 0,
223123
- max: 100,
223124
- step: 1
223951
+ return this.resolveCapOptions({
223952
+ capName: CAP_NAME,
223953
+ schema: DayNightOptionsSchema,
223954
+ probe: async () => {
223955
+ const api = await this.ensureApi();
223956
+ const modes = ((await api.getVideoInput(channel))?.body?.VideoInput)?.dayNight !== void 0 ? [
223957
+ "auto",
223958
+ "day",
223959
+ "night"
223960
+ ] : [];
223961
+ let supportsSensitivity = false;
223962
+ let sensitivityRange;
223963
+ try {
223964
+ const range = (await api.getDayNightThreshold(channel))?.body?.DayNightThreshold?.thresholdval;
223965
+ if (typeof range?.min === "number" && typeof range?.max === "number") {
223966
+ supportsSensitivity = true;
223967
+ sensitivityRange = {
223968
+ min: 0,
223969
+ max: 100,
223970
+ step: 1
223971
+ };
223972
+ }
223973
+ } catch (err) {
223974
+ this.ctx.logger.debug("day-night threshold options probe failed", {
223975
+ tags: { deviceId: this.id },
223976
+ meta: { error: err instanceof Error ? err.message : String(err) }
223977
+ });
223978
+ }
223979
+ return {
223980
+ modes,
223981
+ supportsSensitivity,
223982
+ ...sensitivityRange !== void 0 ? { sensitivity: sensitivityRange } : {},
223983
+ supportsSwitchDelay: false
223125
223984
  };
223126
- }
223127
- } catch (err) {
223128
- this.ctx.logger.debug("day-night threshold options probe failed", {
223129
- tags: { deviceId: this.id },
223130
- meta: { error: err instanceof Error ? err.message : String(err) }
223131
- });
223132
- }
223133
- return {
223134
- modes,
223135
- supportsSensitivity,
223136
- ...sensitivityRange !== void 0 ? { sensitivity: sensitivityRange } : {},
223137
- supportsSwitchDelay: false
223138
- };
223985
+ },
223986
+ fallback: () => ({
223987
+ modes: [],
223988
+ supportsSensitivity: false,
223989
+ supportsSwitchDelay: false
223990
+ })
223991
+ });
223139
223992
  },
223140
223993
  setSettings: async ({ deviceId, settings }) => {
223141
223994
  if (deviceId !== this.id) return;
@@ -223219,37 +224072,60 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
223219
224072
  runtimeState: this.runtimeState,
223220
224073
  cap: imageSettingsCapability,
223221
224074
  ownDeviceId: this.id,
223222
- refresh: refreshFromCamera,
224075
+ refresh: this.sleepGatedRefresh(CAP_NAME, refreshFromCamera),
223223
224076
  staleMs: STALE_MS,
223224
224077
  empty: () => ({ lastFetchedAt: 0 })
223225
224078
  }).getStatus,
223226
224079
  getOptions: async ({ deviceId }) => {
223227
224080
  if (deviceId !== this.id) throw new Error(`ReolinkCamera: deviceId mismatch, expected ${this.id}, got ${deviceId}`);
223228
- const isp = await (await this.ensureApi()).getIsp(channel);
223229
- const vi = isp?.body?.VideoInput;
223230
- const exposureRaw = isp?.body?.InputAdvanceCfg?.Exposure?.mode;
223231
- const supportsBrightness = typeof vi?.bright === "number";
223232
- const supportsContrast = typeof vi?.contrast === "number";
223233
- const supportsSaturation = typeof vi?.saturation === "number";
223234
- const supportsSharpness = typeof vi?.sharpen === "number";
223235
- const exposureModes = typeof exposureRaw === "string" ? ["auto", "manual"] : [];
223236
- return {
223237
- supportsBrightness,
223238
- ...supportsBrightness ? { brightness: NORMALIZED_RANGE } : {},
223239
- supportsContrast,
223240
- ...supportsContrast ? { contrast: NORMALIZED_RANGE } : {},
223241
- supportsSaturation,
223242
- ...supportsSaturation ? { saturation: NORMALIZED_RANGE } : {},
223243
- supportsSharpness,
223244
- ...supportsSharpness ? { sharpness: NORMALIZED_RANGE } : {},
224081
+ const staticOptions = {
223245
224082
  supportsMirror: false,
223246
224083
  supportsFlip: false,
223247
224084
  rotateOptions: [],
223248
224085
  whiteBalanceModes: [],
223249
224086
  supportsWarmth: false,
223250
- exposureModes,
223251
224087
  backlightModes: []
223252
224088
  };
224089
+ return this.resolveCapOptions({
224090
+ capName: CAP_NAME,
224091
+ schema: ImageSettingsOptionsSchema,
224092
+ probe: async () => {
224093
+ const isp = await (await this.ensureApi()).getIsp(channel);
224094
+ const vi = isp?.body?.VideoInput;
224095
+ const exposureRaw = isp?.body?.InputAdvanceCfg?.Exposure?.mode;
224096
+ const supportsBrightness = typeof vi?.bright === "number";
224097
+ const supportsContrast = typeof vi?.contrast === "number";
224098
+ const supportsSaturation = typeof vi?.saturation === "number";
224099
+ const supportsSharpness = typeof vi?.sharpen === "number";
224100
+ const exposureModes = typeof exposureRaw === "string" ? ["auto", "manual"] : [];
224101
+ return {
224102
+ supportsBrightness,
224103
+ ...supportsBrightness ? { brightness: NORMALIZED_RANGE } : {},
224104
+ supportsContrast,
224105
+ ...supportsContrast ? { contrast: NORMALIZED_RANGE } : {},
224106
+ supportsSaturation,
224107
+ ...supportsSaturation ? { saturation: NORMALIZED_RANGE } : {},
224108
+ supportsSharpness,
224109
+ ...supportsSharpness ? { sharpness: NORMALIZED_RANGE } : {},
224110
+ ...staticOptions,
224111
+ rotateOptions: [...staticOptions.rotateOptions],
224112
+ whiteBalanceModes: [...staticOptions.whiteBalanceModes],
224113
+ backlightModes: [...staticOptions.backlightModes],
224114
+ exposureModes
224115
+ };
224116
+ },
224117
+ fallback: () => ({
224118
+ supportsBrightness: false,
224119
+ supportsContrast: false,
224120
+ supportsSaturation: false,
224121
+ supportsSharpness: false,
224122
+ ...staticOptions,
224123
+ rotateOptions: [...staticOptions.rotateOptions],
224124
+ whiteBalanceModes: [...staticOptions.whiteBalanceModes],
224125
+ backlightModes: [...staticOptions.backlightModes],
224126
+ exposureModes: []
224127
+ })
224128
+ });
223253
224129
  },
223254
224130
  setSettings: async ({ deviceId, settings }) => {
223255
224131
  if (deviceId !== this.id) return;
@@ -223487,7 +224363,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
223487
224363
  runtimeState: this.runtimeState,
223488
224364
  cap: ptzAutotrackCapability,
223489
224365
  ownDeviceId: this.id,
223490
- refresh: refreshFromCamera,
224366
+ refresh: this.sleepGatedRefresh(CAP_NAME, refreshFromCamera),
223491
224367
  staleMs: STALE_MS,
223492
224368
  empty: () => ({
223493
224369
  enabled: false,
@@ -223608,25 +224484,30 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
223608
224484
  hasAutofocus: false
223609
224485
  };
223610
224486
  const hasAutofocus = this.config.get("deviceCache")?.autoFocusSnapshot?.supported === true;
223611
- try {
223612
- const { capabilities } = await (await this.ensureApi()).getDeviceCapabilities(this.getChannel());
223613
- return {
223614
- hasPan: capabilities.hasPan,
223615
- hasTilt: capabilities.hasTilt,
223616
- hasZoom: capabilities.hasZoom,
223617
- supportsPresets: capabilities.hasPresets,
223618
- hasAutofocus
223619
- };
223620
- } catch {
223621
- const hasPtz = this.getProbeFlags().hasPtz === true;
223622
- return {
223623
- hasPan: hasPtz,
223624
- hasTilt: hasPtz,
223625
- hasZoom: hasPtz,
223626
- supportsPresets: hasPtz,
223627
- hasAutofocus
223628
- };
223629
- }
224487
+ return this.resolveCapOptions({
224488
+ capName: "ptz",
224489
+ schema: PtzOptionsSchema,
224490
+ probe: async () => {
224491
+ const { capabilities } = await (await this.ensureApi()).getDeviceCapabilities(this.getChannel());
224492
+ return {
224493
+ hasPan: capabilities.hasPan,
224494
+ hasTilt: capabilities.hasTilt,
224495
+ hasZoom: capabilities.hasZoom,
224496
+ supportsPresets: capabilities.hasPresets,
224497
+ hasAutofocus
224498
+ };
224499
+ },
224500
+ fallback: () => {
224501
+ const hasPtz = this.getProbeFlags().hasPtz === true;
224502
+ return {
224503
+ hasPan: hasPtz,
224504
+ hasTilt: hasPtz,
224505
+ hasZoom: hasPtz,
224506
+ supportsPresets: hasPtz,
224507
+ hasAutofocus
224508
+ };
224509
+ }
224510
+ });
223630
224511
  },
223631
224512
  goHome: async ({ deviceId }) => {
223632
224513
  if (deviceId !== this.id) return;
@@ -224242,14 +225123,14 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
224242
225123
  });
224243
225124
  return;
224244
225125
  }
224245
- this.state.battery.sleeping = true;
225126
+ if (!this.commitSleepState(true, "sleep-poll")) return;
224246
225127
  this.ctx.logger.info("Sleep poll detected sleep — closing active streams", {
224247
225128
  tags: { deviceId: this.id },
224248
225129
  meta: { idleMs: status.idleMs }
224249
225130
  });
224250
225131
  this.closeActiveStreams("sleep-poll").catch(() => {});
224251
225132
  } else if (status.state === "awake" && this.sleeping) {
224252
- this.state.battery.sleeping = false;
225133
+ if (!this.commitSleepState(false, "sleep-poll")) return;
224253
225134
  this.ctx.logger.debug("Sleep poll detected awake", { tags: { deviceId: this.id } });
224254
225135
  this.onWakeTransition("sleep-poll").catch(() => {});
224255
225136
  }
@@ -226416,17 +227297,14 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
226416
227297
  }
226417
227298
  if (event.type === "awake") {
226418
227299
  const wasSleeping = this.sleeping;
226419
- if (this.acceptSleepingTransition(false)) {
226420
- if (this.isBattery) this.state.battery.sleeping = false;
226421
- if (wasSleeping) {
226422
- this.ctx.logger.info("Reolink camera woke up", { tags: { deviceId: this.id } });
226423
- this.ctx.eventBus.emit(createEvent(EventCategory.DeviceAwake, eventSource, {
226424
- deviceId: this.id,
226425
- providerId: REOLINK_ADDON_ID,
226426
- reason: "awake"
226427
- }));
226428
- this.onWakeTransition("simple-event").catch(() => {});
226429
- }
227300
+ if (this.commitSleepState(false, "simple-event") && wasSleeping) {
227301
+ this.ctx.logger.info("Reolink camera woke up", { tags: { deviceId: this.id } });
227302
+ this.ctx.eventBus.emit(createEvent(EventCategory.DeviceAwake, eventSource, {
227303
+ deviceId: this.id,
227304
+ providerId: REOLINK_ADDON_ID,
227305
+ reason: "awake"
227306
+ }));
227307
+ this.onWakeTransition("simple-event").catch(() => {});
226430
227308
  }
226431
227309
  return;
226432
227310
  }
@@ -226449,21 +227327,19 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
226449
227327
  }
226450
227328
  if (event.type === "sleeping") {
226451
227329
  const wasSleeping = this.sleeping;
226452
- if (this.acceptSleepingTransition(true)) {
226453
- if (this.isBattery) this.state.battery.sleeping = true;
226454
- if (!wasSleeping) this.ctx.eventBus.emit(createEvent(EventCategory.DeviceSleeping, eventSource, {
226455
- deviceId: this.id,
226456
- providerId: REOLINK_ADDON_ID,
226457
- reason: "sleeping"
226458
- }));
226459
- if (this.active.size > 0) {
226460
- this.ctx.logger.info("Reolink camera went to sleep — closing active streams", {
226461
- tags: { deviceId: this.id },
226462
- meta: { activeStreams: this.active.size }
226463
- });
226464
- this.closeActiveStreams("sleeping").catch(() => {});
226465
- } else this.ctx.logger.debug("Reolink camera sleep transition (no active streams)", { tags: { deviceId: this.id } });
226466
- }
227330
+ if (!this.commitSleepState(true, "simple-event")) return;
227331
+ if (!wasSleeping) this.ctx.eventBus.emit(createEvent(EventCategory.DeviceSleeping, eventSource, {
227332
+ deviceId: this.id,
227333
+ providerId: REOLINK_ADDON_ID,
227334
+ reason: "sleeping"
227335
+ }));
227336
+ if (this.active.size > 0) {
227337
+ this.ctx.logger.info("Reolink camera went to sleep — closing active streams", {
227338
+ tags: { deviceId: this.id },
227339
+ meta: { activeStreams: this.active.size }
227340
+ });
227341
+ this.closeActiveStreams("sleeping").catch(() => {});
227342
+ } else this.ctx.logger.debug("Reolink camera sleep transition (no active streams)", { tags: { deviceId: this.id } });
226467
227343
  return;
226468
227344
  }
226469
227345
  if (event.type === "battery" && event.battery) {
@@ -226535,7 +227411,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
226535
227411
  const persistedModel = this.config.get("deviceCache")?.model ?? null;
226536
227412
  const flags = {
226537
227413
  ...prevFlags,
226538
- hasBattery: hasBattery ?? prevFlags.hasBattery ?? this.isBattery,
227414
+ hasBattery: hasBattery === true || prevFlags.hasBattery === true || this.isBattery,
226539
227415
  ...hasPtz !== void 0 ? { hasPtz } : {},
226540
227416
  ...hasIntercom !== void 0 ? { hasIntercom } : {},
226541
227417
  ...hasDoorbell !== void 0 ? { hasDoorbell } : {},
@@ -227102,13 +227978,14 @@ var ReolinkHub = class ReolinkHub extends BaseDevice {
227102
227978
  source: "cgi",
227103
227979
  timeoutMs: HUB_DISCOVERY_REFRESH_TIMEOUT_MS
227104
227980
  } });
227981
+ const adoptedByChannel = await this.loadAdoptedChildrenByChannel();
227982
+ this.channelToDeviceId.clear();
227983
+ for (const [channel, deviceId] of adoptedByChannel) this.channelToDeviceId.set(channel, deviceId);
227105
227984
  try {
227106
- const summary = await (await this.ensureApi()).getNvrChannelsSummary({
227985
+ discovered = (await (await this.ensureApi()).getNvrChannelsSummary({
227107
227986
  source: "cgi",
227108
227987
  timeoutMs: HUB_DISCOVERY_REFRESH_TIMEOUT_MS
227109
- });
227110
- const adoptedByChannel = await this.loadAdoptedChildrenByChannel();
227111
- discovered = summary.devices.map((d) => {
227988
+ })).devices.map((d) => {
227112
227989
  const childNativeId = computeChildNativeId(this.stableId, d.channel, d.uid);
227113
227990
  const adoptedDeviceId = adoptedByChannel.get(d.channel) ?? null;
227114
227991
  return {
@@ -227161,12 +228038,37 @@ var ReolinkHub = class ReolinkHub extends BaseDevice {
227161
228038
  }))
227162
228039
  } });
227163
228040
  }
227164
- this.channelToDeviceId.clear();
227165
- for (const entry of discovered) {
227166
- const ch = entry.metadata.rtspChannel;
227167
- if (typeof ch === "number" && entry.adoptedDeviceId !== null) this.channelToDeviceId.set(ch, entry.adoptedDeviceId);
228041
+ if (lastError === null) {
228042
+ await this.reconcileAdoptedChildOnline(discovered);
228043
+ await this.reconcileAdoptedChildSleepState(discovered);
228044
+ }
228045
+ }
228046
+ /**
228047
+ * Push the NVR's per-channel sleep state into each adopted battery
228048
+ * child's `battery.sleeping` slice.
228049
+ *
228050
+ * `getNvrChannelsSummary` carries a `sleeping` flag straight from the
228051
+ * Hub firmware — obtained over the Hub's own mains-powered socket, so
228052
+ * it costs the battery channel nothing, and it is real firmware state
228053
+ * rather than the socket-I/O inference a standalone camera has to rely
228054
+ * on. Before this it only ever reached the discovery panel; the
228055
+ * adopted child's sleep state depended entirely on routed simpleEvents
228056
+ * and went stale the moment one was missed. This is the "the NVR
228057
+ * already tells us everything" path — with it, a hub-attached battery
228058
+ * camera needs no email-push server and no sleep poll of its own.
228059
+ *
228060
+ * Only `online` / `sleeping` are acted on: `offline` and `unknown`
228061
+ * carry no sleep information, so the last known value stands.
228062
+ */
228063
+ async reconcileAdoptedChildSleepState(discovered) {
228064
+ const actionable = discovered.filter((e) => e.adoptedDeviceId !== null && (e.status === "sleeping" || e.status === "online"));
228065
+ if (actionable.length === 0) return;
228066
+ const all = await this.ctx.devices.getAll();
228067
+ for (const entry of actionable) {
228068
+ const child = all.find((d) => d.id === entry.adoptedDeviceId);
228069
+ if (!(child instanceof ReolinkCamera)) continue;
228070
+ child.applyHubSleepState(entry.status === "sleeping");
227168
228071
  }
227169
- if (lastError === null) await this.reconcileAdoptedChildOnline(discovered);
227170
228072
  }
227171
228073
  /**
227172
228074
  * After a successful discovery refresh, mark every adopted child