@camstack/addon-provider-reolink 1.2.27 → 1.2.29

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 +1123 -102
  2. package/dist/addon.mjs +1123 -102
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -21,7 +21,7 @@ import netImpl from "net";
21
21
  import { fileURLToPath } from "url";
22
22
  import { mkdir } from "fs/promises";
23
23
  import os from "node:os";
24
- //#region ../types/dist/event-category-Cv9dO26A.mjs
24
+ //#region ../types/dist/event-category-Bxo5yJjt.mjs
25
25
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
26
26
  EventCategory["SystemBoot"] = "system.boot";
27
27
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -228,6 +228,33 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
228
228
  EventCategory["PipelineCameraAssigned"] = "pipeline.camera-assigned";
229
229
  EventCategory["PipelineCameraUnassigned"] = "pipeline.camera-unassigned";
230
230
  /**
231
+ * A node the orchestrator would otherwise place cameras on has NO usable
232
+ * inference device: the operator enabled one or more accelerators there and
233
+ * the live probe reports every one of them unavailable. Emitted once per
234
+ * TRANSITION into that state (never per dispatch), and the node is dropped
235
+ * from the placement candidate set for as long as it holds.
236
+ *
237
+ * This exists because the state was previously invisible: little-unraid
238
+ * absorbed 283k inference errors in a day while still being handed cameras,
239
+ * and nothing in the system said so.
240
+ *
241
+ * A node with no accelerators configured at all is NOT this — its devices
242
+ * are `disabled`, not `unavailable`, and the runner's default CPU pool
243
+ * serves it exactly as before.
244
+ */
245
+ EventCategory["PipelineNodeInferenceUnavailable"] = "pipeline.node-inference-unavailable";
246
+ /**
247
+ * A camera has an OPEN detection session and has produced no detection at
248
+ * all for longer than the blind threshold — the camera is being decoded and
249
+ * inferred and is returning nothing. Emitted once per transition into blind,
250
+ * per camera.
251
+ *
252
+ * The failure it reports: a 1h43 detection blackout on the entrance camera
253
+ * that nobody noticed, because "a camera that detects nothing" and "a quiet
254
+ * camera" produce byte-identical silence.
255
+ */
256
+ EventCategory["PipelineDetectionBlind"] = "pipeline.detection-blind";
257
+ /**
231
258
  * Per-camera pipeline config was mutated by the orchestrator
232
259
  * (3-level settings change via `setAgentAddonDefaults` /
233
260
  * `setCameraStepToggle` / `setCameraPipelineForAgent` or a
@@ -12649,6 +12676,17 @@ var LlmImageSchema = object({
12649
12676
  bytes: _instanceof(Uint8Array),
12650
12677
  mimeType: string()
12651
12678
  });
12679
+ /**
12680
+ * Retry policy. `enabled: false` is NOT the same as `maxAttempts: 1` in intent —
12681
+ * the flag is what a consumer table flips, the count is what the operator tunes.
12682
+ * A retry doubles the wall time of a call, so the two gates that run inside a
12683
+ * notification's budget keep it off (see `CONSUMER_RETRY_POLICY` in addon-ai).
12684
+ */
12685
+ var LlmRetryPolicySchema = object({
12686
+ enabled: boolean().default(false),
12687
+ /** Total attempts INCLUDING the first. 1 = no retry. */
12688
+ maxAttempts: number().int().min(1).max(5).default(1)
12689
+ });
12652
12690
  var LlmGenerateBaseInputSchema = object({
12653
12691
  /** Collection routing (the notification-output posture). */
12654
12692
  addonId: string().optional(),
@@ -12663,7 +12701,28 @@ var LlmGenerateBaseInputSchema = object({
12663
12701
  jsonSchema: record(string(), unknown()).optional(),
12664
12702
  /** Per-call override of the profile default. */
12665
12703
  maxTokens: number().int().positive().optional(),
12666
- temperature: number().optional()
12704
+ temperature: number().optional(),
12705
+ /** Per-call override of the profile default (nucleus sampling). */
12706
+ topP: number().min(0).max(1).optional(),
12707
+ /** Per-call override of the profile default (top-k sampling). */
12708
+ topK: number().int().positive().optional(),
12709
+ /** Per-call override of `profile.timeoutMs` — the total generation bound. */
12710
+ timeoutMs: number().int().positive().optional(),
12711
+ /** Per-call override; beats both the consumer table and the profile. */
12712
+ retry: LlmRetryPolicySchema.optional(),
12713
+ /**
12714
+ * Caller-minted id that makes this generation CANCELLABLE.
12715
+ *
12716
+ * Without it a caller that stops waiting cannot stop the work: the gates race
12717
+ * the call against 8 s and free their own slot when the timer wins, while the
12718
+ * generation upstream keeps running to `profile.timeoutMs` — 60 s by default,
12719
+ * on a single-threaded local model. The per-camera bound then counts WAITS,
12720
+ * not generations, and the real load is unbounded.
12721
+ *
12722
+ * `AbortSignal` cannot cross a process boundary; an id can. Pass one here and
12723
+ * `llm.cancel({ requestId })` tears the socket down.
12724
+ */
12725
+ requestId: string().optional()
12667
12726
  });
12668
12727
  /**
12669
12728
  * `llm-runtime` — node-side managed llama.cpp executor (spec §4). Registered
@@ -12676,6 +12735,18 @@ var LlmGenerateBaseInputSchema = object({
12676
12735
  * Resource ceiling = llama-server flags + idleStopMinutes ONLY (no RSS
12677
12736
  * watchdog — operator decision #3).
12678
12737
  */
12738
+ /**
12739
+ * A companion artifact that MUST land beside the main GGUF: the `mmproj`
12740
+ * projector of a vision model, or shards 2..N of a split GGUF. Carried on the
12741
+ * REF rather than looked up at install time, so what the operator approved in
12742
+ * the preview is exactly what the node downloads.
12743
+ */
12744
+ var ManagedModelExtraFileSchema = object({
12745
+ url: string(),
12746
+ filename: string(),
12747
+ sizeBytes: number(),
12748
+ sha256: string().optional()
12749
+ });
12679
12750
  var ManagedModelRefSchema = discriminatedUnion("kind", [
12680
12751
  object({
12681
12752
  kind: literal("catalog"),
@@ -12684,7 +12755,11 @@ var ManagedModelRefSchema = discriminatedUnion("kind", [
12684
12755
  object({
12685
12756
  kind: literal("url"),
12686
12757
  url: string(),
12687
- sha256: string().optional()
12758
+ sha256: string().optional(),
12759
+ /** Picker/status label; the file basename when absent. */
12760
+ label: string().optional(),
12761
+ sizeBytes: number().optional(),
12762
+ extraFiles: array(ManagedModelExtraFileSchema).optional()
12688
12763
  }),
12689
12764
  object({
12690
12765
  kind: literal("path"),
@@ -12702,13 +12777,82 @@ var ManagedRuntimeConfigSchema = object({
12702
12777
  gpuLayers: number().int().default(0),
12703
12778
  /** Default: cpus-2, clamped ≥1 (resolved node-side). */
12704
12779
  threads: number().int().optional(),
12705
- /** Concurrent slots. */
12780
+ /** Concurrent slots (`--parallel`). */
12706
12781
  parallel: number().int().default(1),
12782
+ /** Logical batch size (`-b`). Larger = faster prompt ingest, more RAM. */
12783
+ batchSize: number().int().positive().optional(),
12784
+ /** Physical batch / micro-batch (`-ub`). */
12785
+ ubatchSize: number().int().positive().optional(),
12786
+ /**
12787
+ * `--flash-attn`. Cuts KV-cache memory on the backends that implement it and
12788
+ * is a no-op elsewhere, so it is offered rather than assumed.
12789
+ */
12790
+ flashAttention: boolean().default(false),
12791
+ /**
12792
+ * `--mlock`. Pins the weights in RAM so the OS cannot page them out mid
12793
+ * inference. Costs the full model size in resident memory — which is exactly
12794
+ * what the RAM budget is counting.
12795
+ */
12796
+ mlock: boolean().default(false),
12797
+ /**
12798
+ * `--no-mmap`. Reads the whole GGUF up front instead of mapping it. Slower to
12799
+ * start, but avoids the page-fault stalls a network or spinning-disk model
12800
+ * store produces on every first token.
12801
+ */
12802
+ noMmap: boolean().default(false),
12803
+ /** `--cache-type-k` / `--cache-type-v` — quantising the KV cache is the
12804
+ * cheapest way to fit a longer context in the same RAM. */
12805
+ cacheTypeK: _enum([
12806
+ "f32",
12807
+ "f16",
12808
+ "q8_0",
12809
+ "q5_1",
12810
+ "q5_0",
12811
+ "q4_1",
12812
+ "q4_0"
12813
+ ]).optional(),
12814
+ cacheTypeV: _enum([
12815
+ "f32",
12816
+ "f16",
12817
+ "q8_0",
12818
+ "q5_1",
12819
+ "q5_0",
12820
+ "q4_1",
12821
+ "q4_0"
12822
+ ]).optional(),
12823
+ /**
12824
+ * Escape hatch for llama-server flags this schema does NOT model — `--jinja`
12825
+ * (which most vision chat templates need and some language-only models
12826
+ * dislike), `--cont-batching`, `--rope-scaling`, …
12827
+ *
12828
+ * It is NOT a second place to set the flags above. A token that collides
12829
+ * with a typed field is REJECTED at start, naming the field that owns it
12830
+ * (`assertNoOwnedFlags`), because two knobs writing the same argv is exactly
12831
+ * the "two switches that disagree" failure this repo has already shipped
12832
+ * twice (D62).
12833
+ */
12834
+ extraArgs: array(string()).default([]),
12707
12835
  /** Else lazy: first generate boots it. */
12708
12836
  autoStart: boolean().default(false),
12709
12837
  /** 0 = never; frees RAM after quiet periods. */
12710
12838
  idleStopMinutes: number().int().default(30)
12711
12839
  });
12840
+ /**
12841
+ * Where a multi-GB install currently is. A single 0..1 fraction cannot answer
12842
+ * "is it stuck?" for an install that is three files (shards + mmproj) followed
12843
+ * by a sha256 pass over 22 GB — during which the fraction sat at 1.0 and the
12844
+ * node looked hung. Phase + file + bytes is the smallest shape that does.
12845
+ */
12846
+ var LlmDownloadProgressSchema = object({
12847
+ phase: _enum(["downloading", "verifying"]),
12848
+ /** The artifact currently moving, e.g. `mmproj-F16.gguf`. */
12849
+ file: string(),
12850
+ fileIndex: number().int(),
12851
+ fileCount: number().int(),
12852
+ /** Across the WHOLE install, not the current file. */
12853
+ downloadedBytes: number(),
12854
+ totalBytes: number().optional()
12855
+ });
12712
12856
  var LlmRuntimeStatusSchema = object({
12713
12857
  /** Status is ALWAYS node-qualified. */
12714
12858
  nodeId: string(),
@@ -12725,6 +12869,8 @@ var LlmRuntimeStatusSchema = object({
12725
12869
  modelPath: string().optional(),
12726
12870
  modelId: string().optional(),
12727
12871
  downloadProgress: number().min(0).max(1).optional(),
12872
+ /** Detail behind `downloadProgress`; present for the same lifetime. */
12873
+ download: LlmDownloadProgressSchema.optional(),
12728
12874
  lastError: string().optional(),
12729
12875
  crashesInWindow: number(),
12730
12876
  /** Child RSS (sampled best-effort). */
@@ -12735,7 +12881,14 @@ var LlmNodeModelSchema = object({
12735
12881
  file: string(),
12736
12882
  sizeBytes: number(),
12737
12883
  catalogId: string().optional(),
12738
- installedAt: number().optional()
12884
+ installedAt: number().optional(),
12885
+ /**
12886
+ * Absolute path on the node. Present so a file that is on disk but matches
12887
+ * no catalog entry — a custom Hugging Face install, or a GGUF the operator
12888
+ * copied in by hand — is still SELECTABLE, as a `{kind:'path'}` ref. Without
12889
+ * it the picker could list such a file and do nothing with it.
12890
+ */
12891
+ path: string().optional()
12739
12892
  });
12740
12893
  var LlmRuntimeDiskUsageSchema = object({
12741
12894
  nodeId: string(),
@@ -12791,10 +12944,47 @@ var LlmProfileSchema = object({
12791
12944
  baseUrl: string().optional(),
12792
12945
  /** ConfigUISchema type:'password' — never round-trips (spec §5). */
12793
12946
  apiKey: string().optional(),
12947
+ /** Vision on/off. A vision call against a `false` profile is REFUSED, never
12948
+ * degraded to text — that shipped once and produced a confident answer to a
12949
+ * question about a picture nobody sent. */
12794
12950
  supportsVision: boolean(),
12795
12951
  temperature: number().min(0).max(2).optional(),
12952
+ /** Nucleus sampling. Every wire we speak has it. */
12953
+ topP: number().min(0).max(1).optional(),
12954
+ /** Top-k sampling. Carried only by the wires that have it — NEITHER OpenAI
12955
+ * wire does, and the client drops it there (measured: the request body gets
12956
+ * `top_p` and no `top_k`). The profile editor hides the field wherever it
12957
+ * would change nothing; `KINDS_WITH_TOP_K` is the single owner of that list. */
12958
+ topK: number().int().positive().optional(),
12796
12959
  maxTokens: number().int().positive().optional(),
12960
+ /** Prompt context window. Advisory for cloud kinds (they enforce their own);
12961
+ * for `managed-local` it is the llama.cpp `--ctx-size` the runtime starts
12962
+ * the model with, so it is the one field that changes a PROCESS. */
12963
+ contextLength: number().int().positive().optional(),
12964
+ /** Default system prompt. A caller's `system` REPLACES it (never appends —
12965
+ * two system prompts fighting is worse than either alone). */
12966
+ systemPrompt: string().optional(),
12967
+ /** Total generation bound — the only one a unary call has. */
12797
12968
  timeoutMs: number().int().positive().default(6e4),
12969
+ /** The TCP handshake only — "is the port even open". NOT the wait for
12970
+ * response headers: on the LM Studio / llama-server wire those are written
12971
+ * once the model has finished loading, so they belong to the bound below. */
12972
+ connectTimeoutMs: number().int().positive().default(1e4),
12973
+ /** Accepted, but no output yet — response headers included, because a cold
12974
+ * GPU load is exactly what happens before them. */
12975
+ firstTokenTimeoutMs: number().int().positive().default(12e4),
12976
+ /** Output started then stopped. */
12977
+ idleTimeoutMs: number().int().positive().default(6e4),
12978
+ /** Profile-level default. The per-consumer table and a per-call override
12979
+ * both beat it — see `resolveRetryPolicy`. */
12980
+ retry: LlmRetryPolicySchema.default({
12981
+ enabled: false,
12982
+ maxAttempts: 1
12983
+ }),
12984
+ /** Whether this profile may use tools. The tool-call plumbing rides the
12985
+ * library; the REGISTRY of callable tools is ours and is empty in v1, so a
12986
+ * `true` here buys the wiring, not behaviour, until tools are registered. */
12987
+ toolsEnabled: boolean().default(false),
12798
12988
  extraHeaders: record(string(), string()).optional(),
12799
12989
  /** kind === 'managed-local' only (spec §4). */
12800
12990
  runtime: ManagedRuntimeConfigSchema.optional()
@@ -12844,6 +13034,36 @@ var ManagedModelCatalogEntrySchema = object({
12844
13034
  /** Vision models: companion projector file. */
12845
13035
  mmprojUrl: string().optional()
12846
13036
  });
13037
+ /**
13038
+ * The outcome of turning one operator-typed Hugging Face reference into a
13039
+ * download plan. A RESULT, never a throw: "this repo has 24 quantizations and
13040
+ * I will not pick for you" is a normal answer the UI has to render, not an
13041
+ * exception.
13042
+ *
13043
+ * `candidates` is the whole reason the refusal is usable — every string in it
13044
+ * is a tag that resolves when pasted back as `<org>/<repo>:<TAG>`.
13045
+ */
13046
+ var HfModelResolutionSchema = discriminatedUnion("ok", [object({
13047
+ ok: literal(true),
13048
+ /** Ready to hand to `installModel` unchanged. */
13049
+ model: ManagedModelRefSchema,
13050
+ label: string(),
13051
+ repo: string(),
13052
+ quantization: string(),
13053
+ purpose: _enum(["text", "vision"]),
13054
+ totalBytes: number(),
13055
+ /** mmproj + shards, for the preview: an operator approving 23 GB should
13056
+ * see that 0.9 GB of it is a projector they did not name. */
13057
+ extraFilenames: array(string())
13058
+ }), object({
13059
+ ok: literal(false),
13060
+ code: string(),
13061
+ message: string(),
13062
+ candidates: array(string()).optional(),
13063
+ /** Set when the refusal was only the ceiling: re-calling with
13064
+ * `maxBytes: requiredBytes` is the operator's explicit override. */
13065
+ requiredBytes: number().optional()
13066
+ })]);
12847
13067
  var LlmRuntimeNodeSchema = object({
12848
13068
  nodeId: string(),
12849
13069
  reachable: boolean(),
@@ -12856,7 +13076,10 @@ var ProfileRefInputSchema = object({
12856
13076
  addonId: string(),
12857
13077
  profileId: string()
12858
13078
  });
12859
- method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
13079
+ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(GenerateVisionInputSchema, LlmGenerateResultSchema, { kind: "mutation" }), method(object({
13080
+ addonId: string().optional(),
13081
+ requestId: string()
13082
+ }), _void(), { kind: "mutation" }), method(object({}), array(LlmProfileKindDescriptorSchema)), method(object({}), array(LlmProfileSchema)), method(object({ profile: LlmProfileSchema }), LlmProfileSchema, {
12860
13083
  kind: "mutation",
12861
13084
  auth: "admin"
12862
13085
  }), method(ProfileRefInputSchema, _void(), {
@@ -12877,6 +13100,15 @@ method(LlmGenerateBaseInputSchema, LlmGenerateResultSchema, { kind: "mutation" }
12877
13100
  consumer: string().optional(),
12878
13101
  profileId: string().optional()
12879
13102
  }), array(LlmUsageRollupSchema)), method(object({}), array(ManagedModelCatalogEntrySchema)), method(object({}), array(LlmRuntimeNodeSchema)), method(object({ nodeId: string() }), array(LlmNodeModelSchema)), method(object({
13103
+ /** `https://huggingface.co/<org>/<repo>/resolve/main/<f>.gguf`,
13104
+ * `<org>/<repo>/<f>.gguf`, `<org>/<repo>` or `<org>/<repo>:<QUANT>`. */
13105
+ ref: string(),
13106
+ /** Explicit ceiling override, in bytes. Absent = the built-in ceiling. */
13107
+ maxBytes: number().positive().optional()
13108
+ }), HfModelResolutionSchema, {
13109
+ kind: "mutation",
13110
+ auth: "admin"
13111
+ }), method(object({
12880
13112
  nodeId: string(),
12881
13113
  model: ManagedModelRefSchema
12882
13114
  }), _void(), {
@@ -14524,6 +14756,8 @@ var NcSystemEventKindSchema = _enum([
14524
14756
  "stream-offline",
14525
14757
  "node-online",
14526
14758
  "node-offline",
14759
+ "node-inference-unavailable",
14760
+ "detection-blind",
14527
14761
  "addon-update-available",
14528
14762
  "server-update-available",
14529
14763
  "alarm-triggered",
@@ -14585,7 +14819,16 @@ var NcScheduleSchema = object({
14585
14819
  });
14586
14820
  /** Fuzzy plate matcher — OCR noise makes exact match useless (spec row 12/13). */
14587
14821
  var NcPlateMatcherSchema = object({
14588
- values: array(string().min(1)).min(1),
14822
+ /**
14823
+ * Plate texts (or gallery vehicle names) to match. EMPTY = **any plate the
14824
+ * pipeline could read** — the plate half of "no selection = no narrowing",
14825
+ * and the switch that says this rule is about vehicles that were IDENTIFIED
14826
+ * rather than merely seen. A subject carrying no plate still fails.
14827
+ *
14828
+ * The `.min(1)` this used to carry made that state unauthorable; nothing has
14829
+ * ever persisted an empty list, so widening it cannot change an existing rule.
14830
+ */
14831
+ values: array(string().min(1)),
14589
14832
  /** Max Levenshtein distance after normalization (uppercase alphanumeric). */
14590
14833
  maxDistance: number().int().min(0).max(3).default(1)
14591
14834
  });
@@ -14619,28 +14862,36 @@ var NcOccupancyConditionSchema = object({
14619
14862
  /**
14620
14863
  * Audio condition (IMMEDIATE trigger) — a rule on SOUND, not on a picture.
14621
14864
  *
14622
- * Operator-approved vocabulary (2026-08-12, option A — the same one the
14623
- * reference notifier uses, so an operator moving between them re-uses what
14624
- * they already know): a rule matches when, over a sampling window of
14625
- * `samplingSeconds`, at least `hitPercent`% of the audio samples in that
14626
- * window are HITS. A sample is a hit when it satisfies BOTH present filters:
14627
- *
14628
- * - `dbThreshold` its level is at or above this many dBFS (see
14629
- * {@link NC_AUDIO_DBFS_FLOOR}: negative-going, `0` = full scale);
14630
- * - `labels` the classifier put at least one of these labels on it.
14631
- *
14632
- * Both are OPTIONAL and independent, which is the point of the shape: a
14633
- * loudness rule ("something loud at 3am") needs no model to be right, and a
14634
- * label rule ("a dog barked") needs no threshold. **Fail-closed when NEITHER
14635
- * is given** a window in which every sample is trivially a hit would fire on
14636
- * silence, so the engine refuses such a condition rather than notifying on
14637
- * nothing (the schema cannot express "at least one of" without becoming a
14638
- * ZodEffects the cap path would have to special-case).
14639
- *
14640
- * `hitPercent` is over the samples the window actually HOLDS, and the window
14641
- * must be FULL before it can match a window that has been open for two
14642
- * seconds of its ten is 100% of nothing, and firing on it would make
14643
- * `samplingSeconds` decorative.
14865
+ * **TWO EXCLUSIVE MODES** (operator decision 2026-08-14, D157). Which one a
14866
+ * rule is in is not a stored field it is WHICH FILTER the rule carries, so
14867
+ * there is no second switch that can disagree with the first and every rule
14868
+ * authored before the decision migrates for free (`audioModeOf`):
14869
+ *
14870
+ * - **LABEL mode — `labels` present.** The rule fires on the FIRST frame the
14871
+ * classifier labels with one of them. No window, no percentage:
14872
+ * `hitPercent` and `samplingSeconds` are ignored, and the rule's own
14873
+ * `throttle` cooldown is the only brake. The per-label confidence floor is
14874
+ * the analyzer's (`classificationMinScore`, per device) — a label only
14875
+ * reaches this condition if the classifier was already confident enough.
14876
+ * - **LEVEL mode `dbThreshold` present, no labels.** The sampling window IS
14877
+ * the condition: at least `hitPercent`% of the samples over
14878
+ * `samplingSeconds` must be at or above `dbThreshold` dBFS (see
14879
+ * {@link NC_AUDIO_DBFS_FLOOR}: negative-going, `0` = full scale). The window
14880
+ * must be FULL before it can match a window open for two of its ten
14881
+ * seconds is 100% of nothing.
14882
+ *
14883
+ * **Why label mode has no window.** It had one, and it never fired: the
14884
+ * analyzer emits ~1 audio frame per second but YAMNet only LABELS one to three
14885
+ * of them per episode, even through continuous crying. The measured maximum
14886
+ * `hitPercent` over the whole live history was 40 — under the shipped default
14887
+ * of 60, so a label rule could not fire at all, ever. A percentage of frames is
14888
+ * the wrong question to ask of a sparse classifier.
14889
+ *
14890
+ * **Fail-closed when NEITHER is given** — every sample would be a trivial hit
14891
+ * and the rule would fire on silence. The schema cannot express "exactly one
14892
+ * of" without becoming a ZodEffects the cap path would have to special-case, so
14893
+ * the exclusivity is enforced where every editor writes (`patchAudio`) and a
14894
+ * legacy rule carrying both resolves to LABEL (the mode that fires).
14644
14895
  *
14645
14896
  * Labels are the audio macro classes (`AUDIO_MACRO_LABELS` / the NC taxonomy's
14646
14897
  * `audio-*` ids). Both spellings are accepted — the matcher normalizes the
@@ -14648,13 +14899,13 @@ var NcOccupancyConditionSchema = object({
14648
14899
  * an operator who typed `dog` mean the same thing.
14649
14900
  */
14650
14901
  var NcAudioConditionSchema = object({
14651
- /** Audio macro labels; absent = any sound (level-only rule). */
14902
+ /** LABEL MODE: audio macro labels. Present fires on the first labelled frame. */
14652
14903
  labels: array(string().min(1)).min(1).optional(),
14653
- /** Level floor in dBFS (negative-going, `0` = full scale); absent = any level. */
14904
+ /** LEVEL MODE: floor in dBFS (negative-going, `0` = full scale). */
14654
14905
  dbThreshold: number().min(-96).max(0).optional(),
14655
- /** Percentage of the window's samples that must be hits (1–100). */
14906
+ /** LEVEL MODE ONLY: percentage of the window's samples that must be hits (1–100). */
14656
14907
  hitPercent: number().int().min(1).max(100).default(60),
14657
- /** Length of the sampling window in seconds. */
14908
+ /** LEVEL MODE ONLY: length of the sampling window in seconds. */
14658
14909
  samplingSeconds: number().int().min(1).max(300).default(10)
14659
14910
  });
14660
14911
  /**
@@ -14792,13 +15043,81 @@ var NcRuleActionsSchema = object({
14792
15043
  */
14793
15044
  buttons: array(NcRuleNotificationButtonSchema).max(8).optional()
14794
15045
  });
15046
+ /**
15047
+ * "This rule applies only while `deviceId` is in one of `states`."
15048
+ *
15049
+ * The states are the DEVICE's own vocabulary — `AlarmState` for a panel,
15050
+ * `on`/`off` for a switch — not a normalised set, because normalising would
15051
+ * make the condition lie about devices whose states have no equivalent.
15052
+ *
15053
+ * An unreadable state does NOT match: see the engine's fail-closed gate. A
15054
+ * condition that fired on "I could not read it" would be worse than no gate.
15055
+ */
15056
+ var NcDeviceStateConditionSchema = object({
15057
+ deviceId: number().int(),
15058
+ /** Any of these matches. */
15059
+ states: array(string().min(1)).min(1)
15060
+ });
15061
+ /**
15062
+ * "This rule applies only while scene `sceneId` is `matched` / `diverged`."
15063
+ *
15064
+ * A GATE, not a trigger. `occupancy` and `audio` each DISCRIMINATE their rule —
15065
+ * carrying one makes the rule fire on that subject and nothing else. Scene is
15066
+ * the other shape entirely, the `deviceState` shape: it narrows a rule that
15067
+ * already has a trigger ("tell me about a person at the front door, but only
15068
+ * while the bin is still out"). That is why it composes with every delivery
15069
+ * instead of owning one, and why no new `NcDelivery` member and no new subject
15070
+ * kind exist for it — see D159.
15071
+ *
15072
+ * ── Identity ───────────────────────────────────────────────────────────────
15073
+ * `sceneId` is `SceneMonitor.id`, a `randomUUID()` minted by `createScene` —
15074
+ * globally unique, so it needs no device to disambiguate it. `deviceId` is
15075
+ * carried as a HINT for the editor and for the log line, never as part of the
15076
+ * lookup key: a rule whose hint drifted must still gate correctly.
15077
+ *
15078
+ * ── Which boolean ──────────────────────────────────────────────────────────
15079
+ * `latched` ABSENT means "whatever the scene itself says" — `SceneMonitor.emit`
15080
+ * already declares which boolean drives notification rules, and a second knob
15081
+ * that could disagree with it is exactly the D62 failure. Set it only to
15082
+ * override one rule against the scene's own default.
15083
+ *
15084
+ * - LIVE reading (`emit`/`latched` resolve to live): passes iff
15085
+ * `verdict === requiredState`. `unknown` — no reference for this light, view
15086
+ * shifted, no snapshot — passes NEITHER. A scene that cannot judge is not
15087
+ * evidence, in either direction.
15088
+ * - LATCHED reading: passes iff `latched === (requiredState === 'diverged')`.
15089
+ * The latch is a durable fact about the past ("it has diverged since I armed
15090
+ * it"), so a camera that has gone dark does not clear it — that is the whole
15091
+ * reason the operator asked for a latch.
15092
+ *
15093
+ * The gate reads an in-memory mirror (`NcSceneStateCache`) refreshed OFF the
15094
+ * event path, never the cap: D49. A mirror that has never loaded, or a scene it
15095
+ * does not carry, reads absent and the rule does NOT fire — fail closed, and
15096
+ * said out loud in the log rather than dropped in silence.
15097
+ */
15098
+ var NcSceneConditionSchema = object({
15099
+ /** `SceneMonitor.id` — the uuid the cap mints. The whole lookup key. */
15100
+ sceneId: string().min(1),
15101
+ /** The camera the scene lives on. A hint for the editor and the log line. */
15102
+ deviceId: number().int().optional(),
15103
+ /** The state the scene must be in for the rule to fire. */
15104
+ requiredState: _enum(["matched", "diverged"]),
15105
+ /**
15106
+ * Read the LATCH (`true`) or the LIVE verdict (`false`). Absent = follow the
15107
+ * scene's own `emit` field, which is the only place that decision belongs.
15108
+ */
15109
+ latched: boolean().optional()
15110
+ });
14795
15111
  var NcConditionsSchema = object({
14796
15112
  /** Gate on ANOTHER device's current state (the alarm armed, a switch on). */
14797
- deviceState: object({
14798
- deviceId: number().int(),
14799
- /** Any of these matches. */
14800
- states: array(string().min(1)).min(1)
14801
- }).optional(),
15113
+ deviceState: NcDeviceStateConditionSchema.optional(),
15114
+ /**
15115
+ * Gate on a SCENE's state — "only while the bin is still out". Composes with
15116
+ * every trigger (detection, occupancy, audio, sensor, package, track-end);
15117
+ * unlike `occupancy`/`audio` it discriminates nothing. See
15118
+ * {@link NcSceneCondition} and D159.
15119
+ */
15120
+ scene: NcSceneConditionSchema.optional(),
14802
15121
  /** Device scope — absent = all devices. */
14803
15122
  devices: array(number()).optional(),
14804
15123
  /** Detector class names (any overlap with the record's class set). */
@@ -14824,18 +15143,47 @@ var NcConditionsSchema = object({
14824
15143
  */
14825
15144
  labelEquals: array(string().min(1)).optional(),
14826
15145
  /**
14827
- * Identity matcher. P1 boundary: matched against the record's collapsed
14828
- * `label` (the identity display name propagated by the face pipeline) —
14829
- * identity-ID matching rides in P2 when identity ids reach the record.
15146
+ * KNOWN FACES the rule's identity scope, and the switch that says the rule
15147
+ * is about recognised people at all.
15148
+ *
15149
+ * Three states, and the empty one is the point:
15150
+ *
15151
+ * | value | meaning |
15152
+ * | --- | --- |
15153
+ * | absent | the rule does not care who it is; an unrecognised person matches |
15154
+ * | `[]` | **only known faces** — any identity in the gallery, nobody in particular |
15155
+ * | a list | only these identities |
15156
+ *
15157
+ * `[]` is the repo-wide "no selection = no narrowing" reading (an absent
15158
+ * `devices` list is every device), applied one level down: the operator has
15159
+ * turned the face scope ON and narrowed it to nothing, which is every known
15160
+ * face. No second field states the same thing — a switch that can disagree
15161
+ * with the list under it is worse than no switch (D62).
15162
+ *
15163
+ * MEMBERS ARE FACE-GALLERY `Identity.id`s (uuid), not display names. A name is
15164
+ * renameable, and a rule authored on "Gianluca" went silently dark the moment
15165
+ * the operator fixed the spelling. The id reaches the record on
15166
+ * `LabelAttribution.identityId`; the name is what the editor shows and what
15167
+ * `{{label}}` renders.
15168
+ *
15169
+ * Rules written before this carry NAMES, and are resolved to ids lazily at
15170
+ * load (`NcRuleStore.load`) against the live gallery — a name nothing answers
15171
+ * for is left as it stands and reported, never dropped. The engine also
15172
+ * accepts a display-name hit as a compatibility leg, so a rule whose
15173
+ * migration could not resolve keeps matching exactly what it matched before.
14830
15174
  */
14831
15175
  identities: array(string().min(1)).optional(),
14832
- /** Fuzzy plate matcher against the record's `label` (plate text). */
15176
+ /**
15177
+ * KNOWN PLATES / VEHICLES — the plate mirror of {@link identities}, including
15178
+ * the empty-list reading: `values: []` is "any plate the OCR could read",
15179
+ * a non-empty list is those plates (fuzzily). See {@link NcPlateMatcherSchema}.
15180
+ */
14833
15181
  plates: NcPlateMatcherSchema.optional(),
14834
15182
  /**
14835
- * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics.
14836
- * Same P1 boundary: matched against the record's collapsed `label` (the
14837
- * identity display name). A record with NO label passes (nothing to
14838
- * exclude), unlike the include variant which fails on an absent label.
15183
+ * Identity EXCLUDE — mirror of {@link identities} with `notIn` semantics, and
15184
+ * the same id members and the same lazy name→id migration. A record with NO
15185
+ * identity passes (nothing to exclude), unlike the include variant which
15186
+ * fails on an unrecognised subject. An EMPTY list excludes nobody.
14839
15187
  */
14840
15188
  identitiesExclude: array(string().min(1)).optional(),
14841
15189
  /**
@@ -15227,7 +15575,80 @@ var NcRuleInputSchema = object({
15227
15575
  * a rule that predates the gate must keep delivering byte-for-byte as it
15228
15576
  * did, and absent is the only way to say that without a migration.
15229
15577
  */
15230
- confirm: NcConfirmSchema.optional()
15578
+ confirm: NcConfirmSchema.optional(),
15579
+ /**
15580
+ * WAIT for face/plate recognition before saying anything.
15581
+ *
15582
+ * A notification's TEXT is frozen at enqueue and its media is re-resolved at
15583
+ * send; the identity is neither. A face is confirmed after `confirmFrames`
15584
+ * agreeing observations — p50 **11.4 s** after the track was first seen,
15585
+ * measured on this hub — and an `immediate` rule enqueues on the first object
15586
+ * event, seconds before that. So "Gianluca è arrivato" is unsayable on the
15587
+ * immediate path, and no amount of media re-resolution fixes a sentence.
15588
+ *
15589
+ * Only two honest answers exist, and this flag picks between them. It has
15590
+ * effect ONLY on a rule that declares a recognition scope
15591
+ * ({@link NcConditions.identities} or {@link NcConditions.plates}) — on any
15592
+ * other rule there is nothing to wait for and the flag is inert.
15593
+ *
15594
+ * | value | what happens |
15595
+ * | --- | --- |
15596
+ * | `true` | the rule stops firing on the object event and fires at TRACK CLOSE instead, once, with the name — later, and complete |
15597
+ * | absent / `false` | it fires at once WITHOUT the name, and if recognition lands before the track closes a SECOND, "…is Gianluca" notification follows (one per track, per rule, per target) |
15598
+ *
15599
+ * `.optional()` and deliberately NOT `.default()`: a Zod default does not run
15600
+ * on the addon cap path, and absent has to keep meaning exactly what every
15601
+ * rule authored before this field meant.
15602
+ *
15603
+ * The cost of `true` is stated here because the editor states it too: a rule
15604
+ * that waits also inherits track-close SEMANTICS — its `zones` condition
15605
+ * tests every zone the track visited and a `crossing` condition can no longer
15606
+ * be satisfied, because a closed track carries no crossing.
15607
+ */
15608
+ waitForEnhancement: boolean().optional(),
15609
+ /**
15610
+ * GROUP a burst of subjects into ONE notification that grows.
15611
+ *
15612
+ * Seconds of quiet after the last matching subject before the burst is
15613
+ * considered over. While it is open, the first subject enqueues immediately —
15614
+ * **exactly as today, with no added latency** — and every real growth (a new
15615
+ * subject, or a name confirmed on one already in it) REPLACES that
15616
+ * notification with an updated one naming everybody. The push carries the
15617
+ * group's own coalescing tag, so the phone replaces rather than stacks.
15618
+ *
15619
+ * `0` / absent = off, and off is today's behaviour byte for byte.
15620
+ *
15621
+ * ### Why an idle cutoff and not a window
15622
+ *
15623
+ * The measured seven-person arrival on device 590 spans 110 s with every
15624
+ * internal gap under 30 s. A 12 s fixed window cuts it into three groups; an
15625
+ * idle cutoff holds it as one and ends it when the arrival actually ends.
15626
+ * 30 is Frigate's shipped value for the same decision.
15627
+ *
15628
+ * ### What it replaces
15629
+ *
15630
+ * The blind cooldown, which collapses a burst by DISCARDING it. Measured on
15631
+ * device 615 / *Persona su Uscio* over six days: 116 qualifying tracks → 74
15632
+ * notifications, **44 (37.9%) suppressed outright**, 23 of them overlapping a
15633
+ * track that did fire and 7 carrying a confirmed identity nobody heard about.
15634
+ * A group collapses the same volume by MERGING, so the cooldown becomes a
15635
+ * budget over GROUPS — which is what it always meant — and a growth is never
15636
+ * throttled by the window its own first member spent.
15637
+ *
15638
+ * ### Interaction with {@link waitForEnhancement}
15639
+ *
15640
+ * They compose, and the order matters. `waitForEnhancement` defers the rule to
15641
+ * TRACK CLOSE, so with both set the group is opened by the first member to
15642
+ * CLOSE — already carrying its name — and grows as later members close. That
15643
+ * is later, and complete. With grouping alone the group opens on the first
15644
+ * object event and picks up names as they are confirmed, through the growth
15645
+ * path. Neither combination fires twice for one subject.
15646
+ *
15647
+ * `.optional()` and deliberately NOT `.default()`: a Zod default does not run
15648
+ * on the addon cap path, so absent must keep meaning what it meant before this
15649
+ * field existed.
15650
+ */
15651
+ groupIdleSec: number().int().min(0).max(600).optional()
15231
15652
  });
15232
15653
  /**
15233
15654
  * Partial patch for `updateRule` — any subset of the input fields, plus the
@@ -15334,6 +15755,7 @@ var NcConditionDescriptorSchema = object({
15334
15755
  "occupancy",
15335
15756
  "audio",
15336
15757
  "deviceState",
15758
+ "scene",
15337
15759
  "systemEvent"
15338
15760
  ]),
15339
15761
  operator: _enum([
@@ -16153,7 +16575,7 @@ var TrackEnvelopeSchema = object({
16153
16575
  * `snapshots[]` references — megabytes across a page of tracks. `slim`
16154
16576
  * keeps every scalar the list surfaces actually render (ids, class(es),
16155
16577
  * label / audioLabels / importance enrichment, firstSeen/lastSeen, state,
16156
- * zonesVisited, bestEventId, envelope, hasFace) and returns `positions` /
16578
+ * zonesVisited, bestEventId, envelope, hasFace, hasRider) and returns `positions` /
16157
16579
  * `snapshots` as EMPTY arrays — detail views re-fetch the full row via
16158
16580
  * `getTrack`. Mirrors the event-store `projection` convention
16159
16581
  * (`getObjectEvents` et al.).
@@ -16289,7 +16711,21 @@ union([literal(1), literal(2)]);
16289
16711
  var LabelAttributionSchema = object({
16290
16712
  stepId: string(),
16291
16713
  modelId: string().optional(),
16292
- decidedAt: number()
16714
+ decidedAt: number(),
16715
+ /**
16716
+ * The GALLERY id behind a recognised tier-2 label — a face-gallery
16717
+ * `Identity.id` or a plate-gallery `Vehicle.id` (both `randomUUID`).
16718
+ *
16719
+ * The text alone is a DISPLAY NAME, and a display name is renameable: a
16720
+ * notification rule authored on "Gianluca" stopped matching the moment the
16721
+ * operator fixed the spelling in the gallery, and nothing said so. The id is
16722
+ * the thing that does not move, so it is what a rule matches on
16723
+ * (`NcConditions.identities`) and the text is what a human is shown.
16724
+ *
16725
+ * Absent when the label names no gallery row — a plate the OCR read but no
16726
+ * vehicle claims, a sub-class, a species, any tier-1 value.
16727
+ */
16728
+ identityId: string().optional()
16293
16729
  });
16294
16730
  /**
16295
16731
  * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
@@ -16426,6 +16862,28 @@ var TrackSchema = object({
16426
16862
  * `=== true` and render nothing otherwise, never infer "no face".
16427
16863
  */
16428
16864
  hasFace: boolean().optional(),
16865
+ /**
16866
+ * This subject CONTAINS a folded rider — a person the rider-pairing step
16867
+ * ([D34](../decisions/adr-0034.md)) removed from the frame BEFORE the tracker,
16868
+ * so the passage is tracked once and as a VEHICLE.
16869
+ *
16870
+ * It exists because the fold's record was dishonest. D34 and the code both
16871
+ * said "the person is not lost — it is reported so both entities stay on the
16872
+ * record"; in fact the pair went into a per-processor RAM field behind an
16873
+ * accessor nobody called, and every durable surface said `vehicle`, full
16874
+ * stop. This is the composition note that makes the row true.
16875
+ *
16876
+ * A COMPOSITION, never a class and never a label. "This vehicle contains a
16877
+ * person" is not an answer to "what is this" — both label tiers would refuse
16878
+ * a macro token anyway (D89), and correctly. Nothing here changes what the
16879
+ * subject IS: a cyclist stays one vehicle track, occupancy still counts one,
16880
+ * and a `person` rule still does not fire for someone cycling past.
16881
+ *
16882
+ * **Absent ≠ false**, exactly like {@link hasFace}: every row written before
16883
+ * the column, and every hub that predates the field, omits it. Test
16884
+ * `=== true` and render nothing otherwise — never infer "no rider".
16885
+ */
16886
+ hasRider: boolean().optional(),
16429
16887
  ...TrackFlagFields,
16430
16888
  ...TrackRetrainFields
16431
16889
  });
@@ -17861,6 +18319,17 @@ var maxSessionHoldMsField = {
17861
18319
  default: 12e4,
17862
18320
  step: 5e3
17863
18321
  };
18322
+ /**
18323
+ * Quiet period that closes an `audioMode: 'on-motion'` audio window. Floor of
18324
+ * 5s so a rearm can never degenerate into per-event stream churn; default 90s
18325
+ * comfortably outlives the gap between two PIR wakes on a battery camera.
18326
+ */
18327
+ var audioMotionWindowMsField = {
18328
+ min: 5e3,
18329
+ max: 6e5,
18330
+ default: 9e4,
18331
+ step: 5e3
18332
+ };
17864
18333
  var motionFpsField = {
17865
18334
  min: 1,
17866
18335
  max: 30,
@@ -18037,6 +18506,27 @@ var RunnerCameraConfigSchema = object({
18037
18506
  * resolved `CameraDetectionConfig`.
18038
18507
  */
18039
18508
  maxSessionHoldMs: number().min(maxSessionHoldMsField.min).max(maxSessionHoldMsField.max).optional(),
18509
+ /**
18510
+ * Orchestrator-side quiet period (ms) that closes an `audioMode:
18511
+ * 'on-motion'` audio window, measured from the LAST motion event.
18512
+ *
18513
+ * This exists because the falling edge cannot be relied on. Camera-native
18514
+ * providers emit motion as a RISING EDGE ONLY (Reolink's Baichuan push and
18515
+ * its email-push SMTP path both emit `detected: true` and never the
18516
+ * counterpart); only the frame-diff analyzer emits falls. So on an
18517
+ * onboard-only camera a window that closed only on `detected: false` never
18518
+ * closed at all, and `on-motion` silently behaved as `always-on` — on a
18519
+ * battery camera, the one failure mode the mode exists to prevent.
18520
+ *
18521
+ * Every motion event rearms this timer WITHOUT restarting the stream, so a
18522
+ * burst of re-fires costs nothing. A falling edge, when one does arrive,
18523
+ * still closes earlier via `motionCooldownMs` — whichever comes first wins.
18524
+ *
18525
+ * Not consumed by the runner: carried here so it shares the per-camera
18526
+ * device-settings surface with `motionCooldownMs`, exactly like
18527
+ * `maxSessionHoldMs`.
18528
+ */
18529
+ audioMotionWindowMs: number().min(audioMotionWindowMsField.min).max(audioMotionWindowMsField.max).optional(),
18040
18530
  motionFps: number().min(motionFpsField.min).max(motionFpsField.max).default(motionFpsField.default),
18041
18531
  detectionFps: number().min(detectionFpsField.min).max(detectionFpsField.max).default(detectionFpsField.default),
18042
18532
  motionStreamId: string(),
@@ -18132,7 +18622,7 @@ var RunnerCameraConfigSchema = object({
18132
18622
  */
18133
18623
  inferenceDevices: array(RunnerInferenceDeviceSchema).readonly().optional()
18134
18624
  });
18135
- 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;
18625
+ 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, audioMotionWindowMsField.min, audioMotionWindowMsField.max, audioMotionWindowMsField.step, audioMotionWindowMsField.default, occupancyRecheckSecField.min, occupancyRecheckSecField.max, occupancyRecheckSecField.step, occupancyRecheckSecField.default, occupancyRecheckFramesField.min, occupancyRecheckFramesField.max, occupancyRecheckFramesField.step, occupancyRecheckFramesField.default;
18136
18626
  /**
18137
18627
  * Runtime load summary returned by `getLocalLoad`. Used by the orchestrator's
18138
18628
  * load-balancing levels (L2 capacity-based, L3 hardware-aware) to decide
@@ -20897,6 +21387,25 @@ var BatteryStatusSchema = object({
20897
21387
  /** Ms epoch of the last observation. Lets consumers reason about freshness. */
20898
21388
  lastUpdated: number(),
20899
21389
  /**
21390
+ * Ms epoch of the last time the device PROVED it was reachable — a
21391
+ * completed firmware round-trip, an observed wake, or an inbound push
21392
+ * (firmware event, email). `0`/absent = never since this slice was born.
21393
+ *
21394
+ * This is the ONLY input that separates "asleep" from "gone", and it is
21395
+ * fed exclusively by PASSIVE signals: nothing may write it by reaching
21396
+ * for the radio, because a poll that confirms reachability is the same
21397
+ * poll that drains the battery. See {@link deriveBatteryPresence} — the
21398
+ * single derivation every consumer must use; no surface computes its own.
21399
+ *
21400
+ * It is deliberately NOT a clock in the
21401
+ * `scripts/check-runtime-state-durability.ts` sense: it is the
21402
+ * observation itself, and it is the only thing a 30-hour silence is
21403
+ * visible in. Writers quantise it (see `CONTACT_WRITE_QUANTUM_MS` in the
21404
+ * Reolink provider) so a value that means "recently" cannot cost a
21405
+ * SQLite commit per round-trip.
21406
+ */
21407
+ lastContactAt: number().optional(),
21408
+ /**
20900
21409
  * True when the source is a BINARY low-battery indicator (HA
20901
21410
  * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
20902
21411
  * charge level — `percentage` is then a coarse stand-in (100 = normal,
@@ -26382,14 +26891,77 @@ method(object({
26382
26891
  * thing except the comparator: `similarity` (CLIP cosine at the same ROI coords
26383
26892
  * vs condition-tagged references) and `llm` (vision-LLM judgment over the crop).
26384
26893
  *
26385
- * D14 device-config archetype (`deviceConfig.ui.kind:'widget'`) the framework
26386
- * derives the device-detail contribution; the provider carries NO hand-written
26387
- * settings-contribution methods. `status.kind:'push'` the engine pushes on
26388
- * every hysteresis flip / availability change; consumers never poll.
26389
- */
26390
- /** Extensible condition tag. Seeded 'day' | 'night'; open by design so more can
26391
- * be added without a wire break (matching falls back to any-condition refs). */
26894
+ * **No `deviceConfig`, deliberately.** This shipped as the D14 widget archetype,
26895
+ * which put a "Scenes" tab on one camera's detail page. That is the wrong shape
26896
+ * for the thing: a scene is a standing question about the property ("is the bin
26897
+ * still out"), and the operator's question is "which of my scenes have tripped",
26898
+ * across every camera at once — not "what does camera 617 think". Buried one
26899
+ * camera deep it also could not be found. The surface is now a top-level admin
26900
+ * page (`/scenes`, `pages/Scenes.tsx`) that lists every scene on every camera and
26901
+ * picks the camera inside the create flow, the same shape Events and Faces have.
26902
+ *
26903
+ * The consequence to keep in mind: `host/scene-monitor-editor` is gone from
26904
+ * `HOST_WIDGETS` too. `scripts/check-host-widget-resolves.ts` asserts BOTH
26905
+ * directions, so a registration nobody declares fails exactly as loudly as a
26906
+ * declaration nobody registers. The editor is imported directly by the page.
26907
+ *
26908
+ * `status.kind:'push'` — the engine pushes on every hysteresis flip /
26909
+ * availability change; consumers never poll.
26910
+ */
26911
+ /** Extensible condition tag. Seeded 'day' | 'ir' (the two variants the operator
26912
+ * captures) plus 'night' | 'dawn' | 'dusk' from the resolver's sun-times band.
26913
+ * Open by design so more can be added without a wire break.
26914
+ *
26915
+ * Matching does NOT fall back across conditions: cross-condition cosines are
26916
+ * not comparable, so "I have never seen this scene in this light" is reported
26917
+ * as `unknown`, never guessed. A day reference scored against an IR frame
26918
+ * collapses the cosine and would latch a false alarm every single night. */
26392
26919
  var SceneConditionSchema = string();
26920
+ /**
26921
+ * What a scene does when the CURRENT light has no reference of its own.
26922
+ *
26923
+ * The lighting variants are not equally likely to exist. Almost every operator
26924
+ * captures daylight and then never stands outside at 22:00 to capture IR, and a
26925
+ * scene that is only ever going to be asked about a daytime question ("is the
26926
+ * bin still on the kerb at 08:00") does not need a night reference at all. The
26927
+ * night half must therefore be OPTIONAL, and optional means the scene keeps
26928
+ * working without it rather than degrading into a permanent complaint.
26929
+ *
26930
+ * - `skip` (default) — the check in that light is not made. Not a verdict, not
26931
+ * an alarm, not even an `unknown`: the live state simply stays whatever the
26932
+ * last covered light left it at, the latch is untouched, and the hysteresis
26933
+ * run is neither spent nor cleared. The scene resumes by itself at first
26934
+ * light. This is the only behaviour under which "I never captured IR" is a
26935
+ * configuration choice instead of a nightly fault.
26936
+ * - `judge-anyway` — score against the OTHER conditions' references. Available
26937
+ * for cameras whose IR frame is close enough to daylight (a floodlit
26938
+ * driveway, an always-white-light doorbell), and wrong for everything else:
26939
+ * cross-condition cosines are not comparable, so a day reference against a
26940
+ * true IR frame collapses and the scene reports a theft at 21:40.
26941
+ *
26942
+ * Never applies when the scene has NO comparable reference at all — that is
26943
+ * "not armed yet", it is reported as `no-reference-for-condition`, and silence
26944
+ * there would hide a scene the operator never finished setting up.
26945
+ */
26946
+ var SceneUncoveredPolicySchema = _enum(["skip", "judge-anyway"]);
26947
+ /** `matched` = the baseline is what we see; `diverged` = it demonstrably is not;
26948
+ * `unknown` = we cannot judge (no reference for this condition, encoder model
26949
+ * changed, view shifted, no snapshot). `unknown` is a real value, not a null,
26950
+ * and never counts toward hysteresis in either direction. */
26951
+ var SceneVerdictSchema = _enum([
26952
+ "matched",
26953
+ "diverged",
26954
+ "unknown"
26955
+ ]);
26956
+ /** Why a scene cannot judge. Named, because this feature's failure mode is
26957
+ * silence that reads as "nothing has happened". */
26958
+ var SceneUnavailableSchema = _enum([
26959
+ "no-reference-for-condition",
26960
+ "view-shifted",
26961
+ "no-vision-profile",
26962
+ "encoder-model-changed",
26963
+ "no-snapshot"
26964
+ ]);
26393
26965
  /** One captured reference — condition-tagged, model-version-gated. `embedding`
26394
26966
  * is `number[]` (Float32Array does NOT survive MsgPack/UDS). */
26395
26967
  var SceneReferenceSchema = object({
@@ -26397,7 +26969,14 @@ var SceneReferenceSchema = object({
26397
26969
  modelId: string(),
26398
26970
  condition: SceneConditionSchema,
26399
26971
  capturedAt: number(),
26400
- thumbnailMediaId: string().optional()
26972
+ thumbnailMediaId: string().optional(),
26973
+ /** Whole-frame (downscaled) embedding captured alongside the ROI crop. The
26974
+ * anti-view-shift anchor: a bumped camera, a PTZ preset or a re-aim makes the
26975
+ * normalized rect frame a different piece of world, and the scene would
26976
+ * diverge forever with a perfectly plausible cosine. Checked LAZILY, only
26977
+ * when hysteresis is about to flip — one extra encode per candidate
26978
+ * transition, not per poll. */
26979
+ anchorEmbedding: array(number()).optional()
26401
26980
  });
26402
26981
  var SceneMonitorStateSchema = object({
26403
26982
  id: string(),
@@ -26419,6 +26998,28 @@ var SceneCheckSchema = discriminatedUnion("mode", [object({
26419
26998
  profileId: string().optional(),
26420
26999
  hysteresisCount: number().int().positive()
26421
27000
  })]);
27001
+ var SCENE_DEFAULT_ANCHOR_THRESHOLD = .85;
27002
+ /** Night is OPTIONAL. A scene with only a daylight reference sits the IR hours
27003
+ * out in silence rather than reporting a fault every night. */
27004
+ var SCENE_DEFAULT_UNCOVERED_POLICY = "skip";
27005
+ /**
27006
+ * Vision-model adjudication of a candidate flip. Field names deliberately
27007
+ * mirror `NcConfirmSchema` so an operator meets one vocabulary, not two.
27008
+ *
27009
+ * `onTimeout` defaults to **'hold'**, the OPPOSITE of `NcConfirmGate`'s
27010
+ * fail-open: a notification suppressed is the worse error there, but a vision
27011
+ * model that timed out has not told us the bin is gone, and a latch is a
27012
+ * stateful claim that costs the operator a trip to reset.
27013
+ */
27014
+ var SceneConfirmSchema = object({
27015
+ enabled: boolean().default(false),
27016
+ prompt: string().min(1).max(1e3),
27017
+ profileId: string().optional(),
27018
+ timeoutMs: number().int().min(1e3).max(2e4).default(8e3),
27019
+ maxImagePx: number().int().min(64).max(2048).default(448),
27020
+ /** What a timeout / unavailable model means for the PENDING flip. */
27021
+ onTimeout: _enum(["flip", "hold"]).default("hold")
27022
+ });
26422
27023
  var SceneMonitorSchema = object({
26423
27024
  id: string(),
26424
27025
  label: string(),
@@ -26437,7 +27038,56 @@ var SceneMonitorSchema = object({
26437
27038
  lastConfidence: number().nullable(),
26438
27039
  currentCondition: SceneConditionSchema.nullable(),
26439
27040
  availability: _enum(["ok", "unavailable"]),
26440
- unavailableReason: string().nullable()
27041
+ unavailableReason: string().nullable(),
27042
+ /** Which state is "the initial screen". `null` until the first capture. */
27043
+ baselineStateId: string().nullable(),
27044
+ /** Which boolean drives notification rules and any export. */
27045
+ emit: _enum(["latched", "live"]).default("latched"),
27046
+ /** Live: does the region match the baseline RIGHT NOW. */
27047
+ verdict: SceneVerdictSchema,
27048
+ /** Has it been `diverged` at least once since `armedAt` — the operator's boolean. */
27049
+ latched: boolean(),
27050
+ /** Last reset (or creation). */
27051
+ armedAt: number(),
27052
+ divergedAt: number().nullable(),
27053
+ restoredAt: number().nullable(),
27054
+ /** A check is only COUNTED when the device has been quiet this long. Motion
27055
+ * during the window DISCARDS the observation — a car pulling up in front of
27056
+ * the bin must not be able to spend hysteresis credit. */
27057
+ quietSeconds: number().int().min(0).max(3600).default(60),
27058
+ /** An observation only advances the pending count when it is at least this
27059
+ * far from the previously counted one, so N agreeing checks span real time
27060
+ * rather than N adjacent polls inside one occlusion. */
27061
+ minObservationSpacingSec: number().int().min(0).max(3600).default(120),
27062
+ /** Vision-model adjudication of a candidate flip. Similarity primary only. */
27063
+ confirm: SceneConfirmSchema.optional(),
27064
+ /** Whole-frame anchor cosine below which a flip is REFUSED as `view-shifted`. */
27065
+ anchorThreshold: number().min(0).max(1).default(SCENE_DEFAULT_ANCHOR_THRESHOLD),
27066
+ /** Clear the latch on its own when the scene matches again? Default false —
27067
+ * `restoredAt` and the `scene-restored` edge are recorded regardless, so an
27068
+ * automation can react to the bin coming back without the operator's own
27069
+ * alarm silently clearing itself. */
27070
+ autoRestore: boolean().default(false),
27071
+ /** What to do when the current light has no reference of its own. See
27072
+ * {@link SceneUncoveredPolicySchema} — the default makes night OPTIONAL. */
27073
+ onUncoveredCondition: SceneUncoveredPolicySchema.default(SCENE_DEFAULT_UNCOVERED_POLICY),
27074
+ /**
27075
+ * The light whose checks are currently being SAT OUT under
27076
+ * `onUncoveredCondition: 'skip'` — `null` when the scene is checking normally.
27077
+ *
27078
+ * Engine-reported and advisory only: it moves no verdict, no latch and no
27079
+ * hysteresis. It exists so the card can say *"night (IR) — checks paused,
27080
+ * nothing captured in this light"* in the same calm voice as the coverage
27081
+ * line, because the alternative is a scene that silently stops answering
27082
+ * after sunset with nothing anywhere saying why. A skipped check must never
27083
+ * read as a broken one.
27084
+ */
27085
+ suspendedCondition: SceneConditionSchema.nullable().default(null),
27086
+ /** Named cause when `verdict === 'unknown'`. */
27087
+ unavailable: SceneUnavailableSchema.nullable(),
27088
+ /** Conditions that have at least one comparable reference — the coverage line
27089
+ * ("day ✓ · ir ✓ · dusk ✗") that turns a silent fallback into a visible fact. */
27090
+ coveredConditions: array(SceneConditionSchema)
26441
27091
  });
26442
27092
  var SceneMonitorStatusSchema = object({
26443
27093
  monitors: array(SceneMonitorSchema),
@@ -26450,12 +27100,6 @@ var sceneMonitorCapability = {
26450
27100
  kind: "wrapper",
26451
27101
  defaultActive: true,
26452
27102
  deviceTypes: [DeviceType.Camera],
26453
- deviceConfig: { ui: {
26454
- kind: "widget",
26455
- widgetId: "host/scene-monitor-editor",
26456
- tab: "scenes",
26457
- label: "Scenes"
26458
- } },
26459
27103
  methods: {
26460
27104
  listScenes: method(object({ deviceId: number() }), SceneMonitorStatusSchema),
26461
27105
  createScene: method(object({
@@ -26486,7 +27130,15 @@ var sceneMonitorCapability = {
26486
27130
  "both"
26487
27131
  ]).optional(),
26488
27132
  checkIntervalSec: number().optional(),
26489
- check: SceneCheckSchema.optional()
27133
+ check: SceneCheckSchema.optional(),
27134
+ emit: _enum(["latched", "live"]).optional(),
27135
+ quietSeconds: number().int().min(0).max(3600).optional(),
27136
+ minObservationSpacingSec: number().int().min(0).max(3600).optional(),
27137
+ anchorThreshold: number().min(0).max(1).optional(),
27138
+ autoRestore: boolean().optional(),
27139
+ onUncoveredCondition: SceneUncoveredPolicySchema.optional(),
27140
+ /** `null` clears the vision-model adjudicator. */
27141
+ confirm: SceneConfirmSchema.nullable().optional()
26490
27142
  })
26491
27143
  }), _void(), {
26492
27144
  kind: "mutation",
@@ -26527,6 +27179,26 @@ var sceneMonitorCapability = {
26527
27179
  }), _void(), {
26528
27180
  kind: "mutation",
26529
27181
  auth: "admin"
27182
+ }),
27183
+ /**
27184
+ * Clear the latch, re-arm, and — by default — RE-CAPTURE the baseline for
27185
+ * the CURRENT condition. The bin never goes back in exactly the same spot;
27186
+ * "reset" in the operator's head means *this is the new normal*, and
27187
+ * re-capture is what makes the feature self-healing against slow drift
27188
+ * instead of failing silently weeks later.
27189
+ *
27190
+ * Reachable from three surfaces on this one mutation: the scene card, a
27191
+ * notification button (an `onTrigger` sequence with a `kind:'cap'` step —
27192
+ * no new Notification-Center code at all), and tRPC for scripts.
27193
+ */
27194
+ resetScene: method(object({
27195
+ deviceId: number(),
27196
+ monitorId: string(),
27197
+ /** Defaults to TRUE at the provider seam — see `SCENE_RESET_RECAPTURES`. */
27198
+ recapture: boolean().optional()
27199
+ }), _void(), {
27200
+ kind: "mutation",
27201
+ auth: "admin"
26530
27202
  })
26531
27203
  },
26532
27204
  status: {
@@ -26769,13 +27441,63 @@ var CamStreamDescriptorSchema = object({
26769
27441
  * set of stream descriptors it can offer for the device, synchronously, so the
26770
27442
  * broker can reconcile its registry against the authoritative provider state.
26771
27443
  */
27444
+ /**
27445
+ * The catalog as a DURABLE fact rather than a live answer.
27446
+ *
27447
+ * A battery camera's descriptors are profile-stable — they change when the
27448
+ * operator rewrites an encoder profile, not minute to minute — but building
27449
+ * them costs a Baichuan login, which on a sleeping Argus IS a wake. So the
27450
+ * provider is allowed to build them exactly once per profile and must serve
27451
+ * every later pull from a cache.
27452
+ *
27453
+ * Holding that cache only in RAM is what turned a restart into an outage. The
27454
+ * runner comes back with the camera asleep, `buildStreamCatalogUncached`
27455
+ * correctly refuses to wake it, the pull answers `[]`, the broker has no
27456
+ * cam-stream entry to build a broker from, and `webrtcSession.handleOffer`
27457
+ * fails with a flat "No broker for stream" — for as long as the camera sleeps,
27458
+ * which on a battery cam is most of the day. The camera was fine. The stream
27459
+ * was unreachable because the process had forgotten what the camera offers.
27460
+ *
27461
+ * Declaring it here puts it in `device-runtime-state`, the kernel's canonical
27462
+ * declared collection, with the same `restored` durability `battery` uses for
27463
+ * the same reason: the last known value is the only value there is while the
27464
+ * device is asleep. The broker's brokers are therefore always DEFINABLE — it
27465
+ * is the DIAL that wakes a camera, never the catalog (D173).
27466
+ */
27467
+ var StreamCatalogStateSchema = object({
27468
+ /** The descriptors as last built from a real camera response. Never a guess:
27469
+ * a failed or refused build writes NOTHING, so a restored catalog is always
27470
+ * one the camera itself once produced. */
27471
+ descriptors: array(CamStreamDescriptorSchema),
27472
+ /** Ms epoch of the build that produced {@link descriptors}. Lets the wake
27473
+ * path decide whether the camera's own awake window is worth spending on a
27474
+ * re-read. */
27475
+ lastFetchedAt: number()
27476
+ });
26772
27477
  var streamCatalogCapability = {
26773
27478
  name: "stream-catalog",
26774
27479
  scope: "device",
26775
27480
  deviceNative: true,
26776
27481
  mode: "singleton",
26777
27482
  deviceTypes: [DeviceType.Camera],
26778
- methods: { getCatalog: method(object({ deviceId: number().int().nonnegative() }), array(CamStreamDescriptorSchema).readonly()) }
27483
+ methods: { getCatalog: method(object({ deviceId: number().int().nonnegative() }), array(CamStreamDescriptorSchema).readonly()) },
27484
+ runtimeState: StreamCatalogStateSchema,
27485
+ /**
27486
+ * Runtime-state durability: **restored** — see the schema doc. A cold
27487
+ * catalog on a sleeping battery camera is not a slow first frame, it is a
27488
+ * camera that cannot be watched at all until it happens to wake.
27489
+ *
27490
+ * Churn is nil by construction: the slice is written only by a SUCCESSFUL
27491
+ * build, and a build only runs when there is no cached copy (or the copy is
27492
+ * a day old and the camera is awake anyway).
27493
+ *
27494
+ * See `RuntimeStateDurability`. Enforced by
27495
+ * `scripts/check-runtime-state-durability.ts`.
27496
+ */
27497
+ durability: "restored",
27498
+ /** Clock field: written, but excluded from the compare that decides whether
27499
+ * persisting is worth a SQLite commit — the descriptors are the value. */
27500
+ volatileStateFields: ["lastFetchedAt"]
26779
27501
  };
26780
27502
  /** One of the camera's stream profiles. */
26781
27503
  var StreamProfileSchema = _enum([
@@ -27228,12 +27950,64 @@ var NetworkAddressSchema = object({
27228
27950
  family: string(),
27229
27951
  internal: boolean()
27230
27952
  });
27953
+ /**
27954
+ * Provenance of the site coordinates, and the whole reason this is not just two
27955
+ * numbers.
27956
+ *
27957
+ * - `operator-set` — a human typed it, or accepted a detection. Authoritative;
27958
+ * nothing overwrites it.
27959
+ * - `derived-from-ip` — the hub geolocated its own public IP once, because a
27960
+ * default that is right to a few kilometres beats the coarse UTC clock split
27961
+ * the sun-times consumers otherwise fall back to.
27962
+ *
27963
+ * The UI shows which one it is. An operator who cannot tell a guess from their
27964
+ * own input will eventually trust the guess.
27965
+ */
27966
+ var SiteLocationSourceSchema = _enum(["operator-set", "derived-from-ip"]);
27967
+ /**
27968
+ * The read shape: the location plus the honest state of the one-shot derivation.
27969
+ *
27970
+ * `derivationAttemptedAt` is what makes the "one call, ever" contract
27971
+ * inspectable. When it is set and `location` is null, the geo-IP lookup ran and
27972
+ * failed; the hub will NOT try again on its own — the fallback is declared
27973
+ * (consumers degrade to their own last resort) and the operator either types the
27974
+ * coordinates or presses detect.
27975
+ */
27976
+ var SiteLocationStatusSchema = object({
27977
+ location: object({
27978
+ /** WGS84 decimal degrees. */
27979
+ latitude: number().min(-90).max(90),
27980
+ longitude: number().min(-180).max(180),
27981
+ source: SiteLocationSourceSchema,
27982
+ /** Epoch ms the value was last written. */
27983
+ updatedAt: number(),
27984
+ /**
27985
+ * Human-readable place the geo-IP service reported ("Napoli, IT"). Display
27986
+ * only — never parsed, never matched on. Absent for an operator-typed value.
27987
+ */
27988
+ label: string().optional()
27989
+ }).nullable(),
27990
+ derivationAttemptedAt: number().nullable(),
27991
+ /** Why the last derivation failed, for the UI to show instead of a shrug. */
27992
+ derivationError: string().nullable()
27993
+ });
27994
+ /** `null` clears the location and re-arms nothing — the derivation stays spent. */
27995
+ var SetSiteLocationInputSchema = object({
27996
+ latitude: number().min(-90).max(90),
27997
+ longitude: number().min(-180).max(180)
27998
+ }).nullable();
27231
27999
  method(_void(), FeatureManifestSchema), method(_void(), HealthStatusSchema), method(_void(), FeatureManifestSchema), method(_void(), array(NetworkAddressSchema).readonly()), method(_void(), unknown().nullable(), { auth: "admin" }), method(record(string(), unknown()), _null(), {
27232
28000
  kind: "mutation",
27233
28001
  auth: "admin"
27234
28002
  }), method(_void(), _void(), {
27235
28003
  kind: "mutation",
27236
28004
  auth: "admin"
28005
+ }), method(_void(), SiteLocationStatusSchema), method(SetSiteLocationInputSchema, SiteLocationStatusSchema, {
28006
+ kind: "mutation",
28007
+ auth: "admin"
28008
+ }), method(_void(), SiteLocationStatusSchema, {
28009
+ kind: "mutation",
28010
+ auth: "admin"
27237
28011
  });
27238
28012
  /**
27239
28013
  * Tamper / case-open detection sensor. Drives Home Assistant
@@ -28587,6 +29361,7 @@ var DEVICE_LOCAL_STATE_CAPS = {
28587
29361
  sceneMonitor: sceneMonitorCapability,
28588
29362
  scriptRunner: scriptRunnerCapability,
28589
29363
  smoke: smokeCapability,
29364
+ streamCatalog: streamCatalogCapability,
28590
29365
  streamParams: streamParamsCapability,
28591
29366
  switch: switchCapability,
28592
29367
  tamper: tamperCapability,
@@ -29240,6 +30015,15 @@ var BaseDeviceProvider = class extends BaseAddon {
29240
30015
  labels: ["probe not implemented"]
29241
30016
  };
29242
30017
  }
30018
+ /**
30019
+ * Top-level devices restored at once in {@link onRestoreDevices}.
30020
+ *
30021
+ * Four covers the fleets this ships to without turning a boot into a burst a
30022
+ * camera NVR answers with a refusal. A provider whose upstream is a single
30023
+ * session with a serial command channel (a Baichuan hub, an NVR that
30024
+ * serialises ISAPI) should lower it; nothing needs to raise it.
30025
+ */
30026
+ restoreConcurrency = 4;
29243
30027
  async restoreDevices(savedDevices) {
29244
30028
  await this.onRestoreDevices(savedDevices);
29245
30029
  if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
@@ -29271,15 +30055,15 @@ var BaseDeviceProvider = class extends BaseAddon {
29271
30055
  */
29272
30056
  async onRestoreDevices(savedDevices) {
29273
30057
  const restored = /* @__PURE__ */ new Set();
29274
- for (const saved of savedDevices) {
29275
- if (saved.parentDeviceId !== null) continue;
30058
+ const topLevel = savedDevices.filter((saved) => saved.parentDeviceId === null);
30059
+ const restoreOne = async (saved) => {
29276
30060
  const Class = this.deviceClasses[saved.type];
29277
30061
  if (!Class) {
29278
30062
  this.ctx.logger.warn("No device class registered for restored type — skipping", {
29279
30063
  tags: { stableId: saved.stableId },
29280
30064
  meta: { type: saved.type }
29281
30065
  });
29282
- continue;
30066
+ return;
29283
30067
  }
29284
30068
  try {
29285
30069
  await this.ctx.kernel.devices.create(saved.stableId, Class, {});
@@ -29293,7 +30077,15 @@ var BaseDeviceProvider = class extends BaseAddon {
29293
30077
  }
29294
30078
  });
29295
30079
  }
29296
- }
30080
+ };
30081
+ let nextTopLevel = 0;
30082
+ await Promise.all(Array.from({ length: Math.min(Math.max(1, this.restoreConcurrency), topLevel.length) }, async () => {
30083
+ for (;;) {
30084
+ const saved = topLevel[nextTopLevel++];
30085
+ if (saved === void 0) return;
30086
+ await restoreOne(saved);
30087
+ }
30088
+ }));
29297
30089
  const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
29298
30090
  for (const saved of childRows) {
29299
30091
  const Class = this.deviceClasses[saved.type];
@@ -31449,6 +32241,12 @@ Object.freeze({
31449
32241
  addonId: null,
31450
32242
  access: "create"
31451
32243
  },
32244
+ "llm.cancel": {
32245
+ capName: "llm",
32246
+ capScope: "system",
32247
+ addonId: null,
32248
+ access: "create"
32249
+ },
31452
32250
  "llm.deleteModel": {
31453
32251
  capName: "llm",
31454
32252
  capScope: "system",
@@ -31533,6 +32331,12 @@ Object.freeze({
31533
32331
  addonId: null,
31534
32332
  access: "view"
31535
32333
  },
32334
+ "llm.resolveModelRef": {
32335
+ capName: "llm",
32336
+ capScope: "system",
32337
+ addonId: null,
32338
+ access: "create"
32339
+ },
31536
32340
  "llm.setDefault": {
31537
32341
  capName: "llm",
31538
32342
  capScope: "system",
@@ -33699,6 +34503,12 @@ Object.freeze({
33699
34503
  addonId: null,
33700
34504
  access: "create"
33701
34505
  },
34506
+ "sceneMonitor.resetScene": {
34507
+ capName: "scene-monitor",
34508
+ capScope: "device",
34509
+ addonId: null,
34510
+ access: "delete"
34511
+ },
33702
34512
  "sceneMonitor.updateScene": {
33703
34513
  capName: "scene-monitor",
33704
34514
  capScope: "device",
@@ -34377,6 +35187,12 @@ Object.freeze({
34377
35187
  addonId: null,
34378
35188
  access: "create"
34379
35189
  },
35190
+ "system.detectSiteLocation": {
35191
+ capName: "system",
35192
+ capScope: "system",
35193
+ addonId: null,
35194
+ access: "create"
35195
+ },
34380
35196
  "system.featureFlags": {
34381
35197
  capName: "system",
34382
35198
  capScope: "system",
@@ -34395,6 +35211,12 @@ Object.freeze({
34395
35211
  addonId: null,
34396
35212
  access: "view"
34397
35213
  },
35214
+ "system.getSiteLocation": {
35215
+ capName: "system",
35216
+ capScope: "system",
35217
+ addonId: null,
35218
+ access: "view"
35219
+ },
34398
35220
  "system.health": {
34399
35221
  capName: "system",
34400
35222
  capScope: "system",
@@ -34419,6 +35241,12 @@ Object.freeze({
34419
35241
  addonId: null,
34420
35242
  access: "create"
34421
35243
  },
35244
+ "system.setSiteLocation": {
35245
+ capName: "system",
35246
+ capScope: "system",
35247
+ addonId: null,
35248
+ access: "create"
35249
+ },
34422
35250
  "terminalSession.adoptLegacyMonitor": {
34423
35251
  capName: "terminal-session",
34424
35252
  capScope: "system",
@@ -36381,6 +37209,11 @@ Object.freeze({
36381
37209
  form: "single",
36382
37210
  optional: false
36383
37211
  }],
37212
+ "sceneMonitor.resetScene": [{
37213
+ name: "deviceId",
37214
+ form: "single",
37215
+ optional: false
37216
+ }],
36384
37217
  "sceneMonitor.updateScene": [{
36385
37218
  name: "deviceId",
36386
37219
  form: "single",
@@ -225446,6 +226279,44 @@ function capDayNightModeToReolink(mode) {
225446
226279
  }
225447
226280
  }
225448
226281
  //#endregion
226282
+ //#region src/device-features.ts
226283
+ /**
226284
+ * Derive the device-manager feature set for a Reolink camera.
226285
+ *
226286
+ * `battery-operated` is derived from the probe flag **OR** the driver's own
226287
+ * `isBattery` discriminator — never the probe alone. The probe slice is
226288
+ * written only by a SUCCESSFUL `feature-probe` round-trip, and a battery
226289
+ * camera that is asleep (or flat, or off-LAN) never answers one: device 640
226290
+ * "Baby monitor" held `deviceCache.deviceType === 'battery-cam'`, a
226291
+ * `battery` runtime slice reporting `sleeping: true`, and STILL published
226292
+ * `features = ['native-snapshot','rebootable']` because the `feature-probe`
226293
+ * slice had never been written.
226294
+ *
226295
+ * That miss is not cosmetic. `DeviceFeature.BatteryOperated` is the gate for:
226296
+ * - the viewer's battery badge + sleeping overlay (`use-cameras.ts` FEATURE
226297
+ * map) — without it the camera is drawn as an ordinary awake camera;
226298
+ * - the snapshot wrapper's sleep gate (`snapshot.addon.ts`
226299
+ * `lookupDeviceMeta().isBattery`) — without it every thumbnail refresh
226300
+ * issues a Baichuan login and WAKES the camera (observed hourly on 640
226301
+ * while it sat at 14%);
226302
+ * - the broker's `preBufferSec = 0` battery rule and its relaxed stall
226303
+ * watchdog.
226304
+ *
226305
+ * The probe's own `hasBattery` is already sticky-true (`applyProbe` never
226306
+ * clears it). This makes the DERIVED answer sticky the same way, for the
226307
+ * window before any probe has ever succeeded.
226308
+ */
226309
+ function deriveReolinkCameraFeatures(inputs) {
226310
+ const { probe, isBattery } = inputs;
226311
+ const out = [DeviceFeature.NativeSnapshot, DeviceFeature.Rebootable];
226312
+ if (probe.hasBattery === true || isBattery) out.push(DeviceFeature.BatteryOperated);
226313
+ if (probe.hasPtz === true) out.push(DeviceFeature.PanTiltZoom);
226314
+ if (probe.hasAutotrack === true) out.push(DeviceFeature.PtzAutotrack);
226315
+ if (probe.hasIntercom === true) out.push(DeviceFeature.TwoWayAudio);
226316
+ if (probe.hasDoorbell === true) out.push(DeviceFeature.DoorbellButton);
226317
+ return out;
226318
+ }
226319
+ //#endregion
225449
226320
  //#region src/image-settings-mapping.ts
225450
226321
  /**
225451
226322
  * Reolink's `InputAdvanceCfg.Exposure.mode` (Baichuan cmdId 25/26, via
@@ -228965,6 +229836,15 @@ function coerceNumber(value) {
228965
229836
  return null;
228966
229837
  }
228967
229838
  /**
229839
+ * Per-device transient diagnostics blob populated from the lib's
229840
+ * `getOnlineUserSessionsForUi` + `getSocketPoolSummary` +
229841
+ * `getSocketPoolCooldownStatus` calls. NOT persisted — recomputed on
229842
+ * demand and shown in the device's "Sessions" tab. The aggregator UI
229843
+ * polls the device aggregate every ~2.5s and a stale snapshot triggers
229844
+ * a background refresh; the operator can also force one via the
229845
+ * tab's Refresh button (`_refreshSessions` patch sentinel).
229846
+ */
229847
+ /**
228968
229848
  * Reolink camera device — connects via Baichuan protocol and pushes
228969
229849
  * Annex-B H.264/H.265 directly to the stream broker.
228970
229850
  *
@@ -229055,24 +229935,24 @@ function slicesForPatch(patch) {
229055
229935
  var ReolinkCamera = class ReolinkCamera extends BaseDevice {
229056
229936
  type = DeviceType.Camera;
229057
229937
  /**
229058
- * Features derived from the post-probe `feature-probe` runtime-state
229059
- * slice. Surfaced via `device-manager.getDevice` so any service in
229060
- * the cluster (stream-broker, snapshot orchestrator, pipeline-runner)
229061
- * can derive policy from a single source.
229938
+ * Features derived from the `feature-probe` runtime-state slice AND the
229939
+ * driver's own `isBattery` discriminator. Surfaced via
229940
+ * `device-manager.getDevice` so any service in the cluster (stream-broker,
229941
+ * snapshot orchestrator, pipeline-runner) can derive policy from a single
229942
+ * source.
229943
+ *
229944
+ * The rule itself lives in `deriveReolinkCameraFeatures` — see that
229945
+ * function for why `battery-operated` must NOT wait for a probe.
229062
229946
  *
229063
229947
  * Returns a fresh array on each read so consumers can't mutate the
229064
229948
  * underlying state. The set is small (≤6 entries) so allocation cost
229065
229949
  * is negligible vs the staleness of caching.
229066
229950
  */
229067
229951
  get features() {
229068
- const probe = this.getProbeFlags();
229069
- const out = [DeviceFeature.NativeSnapshot, DeviceFeature.Rebootable];
229070
- if (probe.hasBattery === true) out.push(DeviceFeature.BatteryOperated);
229071
- if (probe.hasPtz === true) out.push(DeviceFeature.PanTiltZoom);
229072
- if (probe.hasAutotrack === true) out.push(DeviceFeature.PtzAutotrack);
229073
- if (probe.hasIntercom === true) out.push(DeviceFeature.TwoWayAudio);
229074
- if (probe.hasDoorbell === true) out.push(DeviceFeature.DoorbellButton);
229075
- return out;
229952
+ return deriveReolinkCameraFeatures({
229953
+ probe: this.getProbeFlags(),
229954
+ isBattery: this.isBattery
229955
+ });
229076
229956
  }
229077
229957
  /** Lazy-connected Baichuan API. Spans the lifetime of every active stream. */
229078
229958
  api = null;
@@ -229341,6 +230221,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
229341
230221
  * retries.
229342
230222
  */
229343
230223
  async onProbe() {
230224
+ if (this.isBattery && this.sleeping) {
230225
+ this.ctx.logger.info("onProbe skipped — battery cam is sleeping (no login, no wake)", {
230226
+ tags: { deviceId: this.id },
230227
+ meta: { probeRetriesAvoided: true }
230228
+ });
230229
+ return;
230230
+ }
229344
230231
  let api;
229345
230232
  try {
229346
230233
  api = await this.ensureApi();
@@ -230041,9 +230928,21 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
230041
230928
  status: slice
230042
230929
  }));
230043
230930
  });
230044
- this.refreshBatteryFromApi();
230931
+ this.refreshBatteryFromApi("register");
230045
230932
  }
230046
- async refreshBatteryFromApi() {
230933
+ /**
230934
+ * @param reason - `'register'` and `'periodic'` are OUR initiative and are
230935
+ * refused while the camera sleeps; `'wake'` and `'demand'` run because
230936
+ * something already has the camera awake or is entitled to wake it.
230937
+ */
230938
+ async refreshBatteryFromApi(reason) {
230939
+ if (this.isBattery && this.sleeping && (reason === "register" || reason === "periodic")) {
230940
+ this.ctx.logger.debug("battery refresh skipped — cam sleeping, reading restored slice", {
230941
+ tags: { deviceId: this.id },
230942
+ meta: { reason }
230943
+ });
230944
+ return;
230945
+ }
230047
230946
  let api;
230048
230947
  try {
230049
230948
  api = await this.ensureApi();
@@ -230201,7 +231100,14 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
230201
231100
  return true;
230202
231101
  }
230203
231102
  updateBatteryCache(info) {
230204
- this.setCapSlice(batteryCapability, this.mapBatteryInfo(info));
231103
+ const mapped = this.mapBatteryInfo(info);
231104
+ const now = Date.now();
231105
+ const quantised = now - now % ReolinkCamera.CONTACT_WRITE_QUANTUM_MS;
231106
+ const previousContact = this.state.battery.lastContactAt ?? 0;
231107
+ this.setCapSlice(batteryCapability, {
231108
+ ...mapped,
231109
+ lastContactAt: Math.max(previousContact, quantised)
231110
+ });
230205
231111
  }
230206
231112
  /**
230207
231113
  * Battery cams require an explicit wake before cmd_id 109 will
@@ -232526,6 +233432,8 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
232526
233432
  */
232527
233433
  async buildStreamCatalog() {
232528
233434
  if (this.cachedStreamDescriptors?.length) return this.withLiveNativeSdp(this.cachedStreamDescriptors);
233435
+ const restored = this.restoreStreamCatalogFromLedger();
233436
+ if (restored) return this.withLiveNativeSdp(restored);
232529
233437
  if (this.buildStreamCatalogInFlight) return this.withLiveNativeSdp(await this.buildStreamCatalogInFlight);
232530
233438
  const build = this.buildStreamCatalogUncached();
232531
233439
  this.buildStreamCatalogInFlight = build;
@@ -232698,6 +233606,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
232698
233606
  autoEligible: e.autoEligible
232699
233607
  }));
232700
233608
  this.cachedStreamDescriptors = descriptors;
233609
+ this.persistStreamCatalogToLedger(descriptors);
232701
233610
  return descriptors;
232702
233611
  }
232703
233612
  /** Profile-stable stream descriptors, cached after the first successful
@@ -232705,6 +233614,66 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
232705
233614
  * sleeping battery cam is never woken by a catalog poll. Invalidated by
232706
233615
  * `applyStreamProfilePatch` (codec/resolution may change). */
232707
233616
  cachedStreamDescriptors;
233617
+ /**
233618
+ * Write the just-built catalog to the durable `stream-catalog` slice, so a
233619
+ * restart with the camera asleep still has descriptors to serve (D173).
233620
+ *
233621
+ * Best-effort by design: the RAM copy is already advanced by the caller, and
233622
+ * losing this write costs one cold catalog after the next restart — never a
233623
+ * wrong catalog. A build that FAILED writes nothing at all and therefore
233624
+ * cannot demote a good stored copy (D49's failure direction).
233625
+ */
233626
+ persistStreamCatalogToLedger(descriptors) {
233627
+ if (descriptors.length === 0) return;
233628
+ try {
233629
+ const state = {
233630
+ descriptors: [...descriptors],
233631
+ lastFetchedAt: Date.now()
233632
+ };
233633
+ this.runtimeState.setCapState(streamCatalogCapability.name, state);
233634
+ this.ctx.logger.debug("stream catalog persisted to the durable slice", {
233635
+ tags: { deviceId: this.id },
233636
+ meta: { count: descriptors.length }
233637
+ });
233638
+ } catch (err) {
233639
+ this.ctx.logger.debug("stream catalog persist failed — RAM copy stands", {
233640
+ tags: { deviceId: this.id },
233641
+ meta: { error: err instanceof Error ? err.message : String(err) }
233642
+ });
233643
+ }
233644
+ }
233645
+ /**
233646
+ * Rehydrate `cachedStreamDescriptors` from the durable slice. Returns the
233647
+ * restored descriptors, or `null` when there is nothing to restore.
233648
+ *
233649
+ * Logged at `info` when it fires: "these descriptors came from before the
233650
+ * restart" must never be something a reader has to infer (the DurableLedger
233651
+ * contract, D132).
233652
+ */
233653
+ restoreStreamCatalogFromLedger() {
233654
+ const stored = this.runtimeState.getCapState(streamCatalogCapability.name);
233655
+ const descriptors = stored?.descriptors;
233656
+ if (!descriptors || descriptors.length === 0) return null;
233657
+ this.cachedStreamDescriptors = [...descriptors];
233658
+ this.ctx.logger.info("stream catalog restored from the durable slice (no camera contact)", {
233659
+ tags: { deviceId: this.id },
233660
+ meta: {
233661
+ count: descriptors.length,
233662
+ builtAt: stored?.lastFetchedAt ?? 0,
233663
+ ageMs: Date.now() - (stored?.lastFetchedAt ?? 0),
233664
+ sleeping: this.sleeping
233665
+ }
233666
+ });
233667
+ return this.cachedStreamDescriptors;
233668
+ }
233669
+ /**
233670
+ * How old a RESTORED catalog may get before a natural wake is worth spending
233671
+ * on a re-read. The catalog is profile-stable, so this is not about
233672
+ * freshness — it is the backstop for a profile changed by something that did
233673
+ * not invalidate the cache (a firmware update, an edit made on the Reolink
233674
+ * app). A day is several natural wakes on any camera that is working.
233675
+ */
233676
+ static CATALOG_REFRESH_ON_WAKE_MS = 1440 * 6e4;
232708
233677
  /** Single-flight guard for `buildStreamCatalog`. */
232709
233678
  buildStreamCatalogInFlight = null;
232710
233679
  /**
@@ -233167,7 +234136,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
233167
234136
  auxAccessoryCount: this.auxAccessoryRefs.size
233168
234137
  }
233169
234138
  });
233170
- await this.refreshBatteryFromApi().catch(() => {});
234139
+ await this.refreshBatteryFromApi("periodic").catch(() => {});
233171
234140
  await this.alignAuxDevicesState("periodic").catch(() => {});
233172
234141
  await this.refreshParentSettingsSnapshot().catch(() => {});
233173
234142
  } finally {
@@ -233202,6 +234171,44 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
233202
234171
  }
233203
234172
  }
233204
234173
  /**
234174
+ * Is this wake worth spending on a catalog re-read? See
234175
+ * `CATALOG_REFRESH_ON_WAKE_MS`. Held apart from `onWakeTransition` so the
234176
+ * decision is one expression a test can pin.
234177
+ */
234178
+ shouldRebuildCatalogOnWake() {
234179
+ if (!this.cachedStreamDescriptors?.length) {
234180
+ if (!this.restoreStreamCatalogFromLedger()) return true;
234181
+ }
234182
+ const builtAt = this.runtimeState.getCapState(streamCatalogCapability.name)?.lastFetchedAt ?? 0;
234183
+ if (builtAt <= 0) return true;
234184
+ return Date.now() - builtAt > ReolinkCamera.CATALOG_REFRESH_ON_WAKE_MS;
234185
+ }
234186
+ /**
234187
+ * A PASSIVE proof of reachability just arrived — stamp `battery.lastContactAt`
234188
+ * so `deriveBatteryPresence` can tell "asleep" from "gone" (D173).
234189
+ *
234190
+ * Callable only from paths where the evidence cost us nothing: an inbound
234191
+ * firmware push, an observed wake, a round-trip somebody else's demand
234192
+ * already paid for. Never from a poll issued to answer this question — that
234193
+ * poll is the wake it is trying to detect.
234194
+ *
234195
+ * Quantised to `CONTACT_WRITE_QUANTUM_MS`: the value means "recently", and
234196
+ * writing it at millisecond resolution would put a SQLite commit behind
234197
+ * every Baichuan reply on the hub's busiest write path (the exact cost
234198
+ * `scripts/check-runtime-state-durability.ts` exists to bound).
234199
+ */
234200
+ markPassiveContact() {
234201
+ if (!this.isBattery) return;
234202
+ const now = Date.now();
234203
+ const quantised = now - now % ReolinkCamera.CONTACT_WRITE_QUANTUM_MS;
234204
+ if (quantised <= (this.state.battery.lastContactAt ?? 0)) return;
234205
+ this.state.battery.lastContactAt = quantised;
234206
+ }
234207
+ /** Write granularity for `battery.lastContactAt` — see `markPassiveContact`.
234208
+ * Bounds the commit rate this field can cost at 12/hour/device, and only
234209
+ * for a device something is actually reaching. */
234210
+ static CONTACT_WRITE_QUANTUM_MS = 5 * 6e4;
234211
+ /**
233205
234212
  * Shared wake-transition handler invoked by both the simpleEvent
233206
234213
  * `awake` push (canonical fast path) and the sleep poll's
233207
234214
  * `sleeping → awake` flip (backstop). Mirrors Scrypted's
@@ -233226,7 +234233,8 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
233226
234233
  isBattery: this.isBattery
233227
234234
  }
233228
234235
  });
233229
- if (!this.cachedStreamDescriptors?.length) try {
234236
+ if (this.shouldRebuildCatalogOnWake()) try {
234237
+ this.cachedStreamDescriptors = void 0;
233230
234238
  if ((await this.buildStreamCatalog()).length > 0) this.ctx.eventBus.emit(createEvent(EventCategory.StreamParamsChanged, this.eventSource(), { deviceId: this.id }));
233231
234239
  } catch (err) {
233232
234240
  this.ctx.logger.debug("onWakeTransition: stream catalog build failed — will retry on next wake", {
@@ -234939,7 +235947,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
234939
235947
  this.startSleepPoll();
234940
235948
  this.startBatteryUpdatePolling();
234941
235949
  this.registerBatteryIfSupported();
234942
- this.refreshBatteryFromApi();
235950
+ this.refreshBatteryFromApi("demand");
234943
235951
  } else this.startAlignAuxPolling();
234944
235952
  this.resubscribeSimpleEvents(api, "adoptApi").catch((err) => {
234945
235953
  this.ctx.logger.debug("Reolink adoptApi: simple-event subscribe failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
@@ -235051,7 +236059,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
235051
236059
  this.startSleepPoll();
235052
236060
  this.startBatteryUpdatePolling();
235053
236061
  this.registerBatteryIfSupported();
235054
- this.refreshBatteryFromApi();
236062
+ this.refreshBatteryFromApi("demand");
235055
236063
  }
235056
236064
  this.startWatchdogs();
235057
236065
  this.probeAndPersistFeatures(api).catch((err) => {
@@ -235135,6 +236143,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
235135
236143
  this.lastEventAt = Date.now();
235136
236144
  this.consecutiveStaleHealthChecks = 0;
235137
236145
  this.nextEventHealthCheckAt = 0;
236146
+ this.markPassiveContact();
235138
236147
  const eventSource = this.eventSource();
235139
236148
  if (event.type !== "battery") this.ctx.logger.info("Reolink simpleEvent received", { meta: {
235140
236149
  type: event.type,
@@ -235567,6 +236576,9 @@ var ReolinkHub = class ReolinkHub extends BaseDevice {
235567
236576
  const data = event.data;
235568
236577
  if (data.parentDeviceId !== this.id) return;
235569
236578
  const cid = typeof data.deviceId === "number" ? data.deviceId : null;
236579
+ if (cid !== null) {
236580
+ for (const [ch, did] of this.channelToDeviceId.entries()) if (did === cid) this.channelToDeviceId.delete(ch);
236581
+ }
235570
236582
  this.ctx.logger.info("Reolink Hub: child unregistered externally — refreshing discovery", cid !== null ? { tags: { deviceId: cid } } : {});
235571
236583
  this.refreshDiscoveryFromCamera().catch(() => {});
235572
236584
  }));
@@ -235863,7 +236875,6 @@ var ReolinkHub = class ReolinkHub extends BaseDevice {
235863
236875
  timeoutMs: HUB_DISCOVERY_REFRESH_TIMEOUT_MS
235864
236876
  } });
235865
236877
  const adoptedByChannel = await this.loadAdoptedChildrenByChannel();
235866
- this.channelToDeviceId.clear();
235867
236878
  for (const [channel, deviceId] of adoptedByChannel) this.channelToDeviceId.set(channel, deviceId);
235868
236879
  try {
235869
236880
  discovered = (await (await this.ensureApi()).getNvrChannelsSummary({
@@ -235871,7 +236882,7 @@ var ReolinkHub = class ReolinkHub extends BaseDevice {
235871
236882
  timeoutMs: HUB_DISCOVERY_REFRESH_TIMEOUT_MS
235872
236883
  })).devices.map((d) => {
235873
236884
  const childNativeId = computeChildNativeId(this.stableId, d.channel, d.uid);
235874
- const adoptedDeviceId = adoptedByChannel.get(d.channel) ?? null;
236885
+ const adoptedDeviceId = this.channelToDeviceId.get(d.channel) ?? null;
235875
236886
  return {
235876
236887
  childNativeId,
235877
236888
  name: d.name ?? `Channel ${d.channel}`,
@@ -236573,21 +237584,31 @@ var AutodetectCache = class {
236573
237584
  //#endregion
236574
237585
  //#region src/email-push-shared.ts
236575
237586
  /**
236576
- * Map the lib's email-push classifier output onto a `ReolinkSimpleEvent`
236577
- * type the camera understands. AI subtypes + motion + doorbell pass
236578
- * through; anything else collapses to plain `motion` so a wake is never
237587
+ * Map the lib's email-push classifier output onto the `ReolinkSimpleEvent`
237588
+ * types the camera should be fed. AI subtypes + motion pass through;
237589
+ * anything unrecognised collapses to plain `motion` so a wake is never
236579
237590
  * silently dropped.
236580
- */
236581
- function mapInferredTypeToSimpleEvent(inferred) {
237591
+ *
237592
+ * Returns a LIST rather than a single type because of `doorbell`. The
237593
+ * camera's `handleSimpleEvent` emits `MotionOnMotionChanged` for `motion`
237594
+ * and for every AI class, but the `doorbell` branch emits ONLY
237595
+ * `DoorbellOnPressed` and returns. An email is the sole signal a sleeping
237596
+ * battery camera can send, so a doorbell-classified email mapped to
237597
+ * `doorbell` alone rang the bell and left motion, recording and
237598
+ * notification rules blind — the exact "silently dropped wake" this mapping
237599
+ * exists to prevent. Pairing it with `motion` keeps the doorbell semantic
237600
+ * AND the wake.
237601
+ */
237602
+ function mapInferredTypeToSimpleEvents(inferred) {
236582
237603
  switch (inferred) {
236583
237604
  case "people":
236584
237605
  case "vehicle":
236585
237606
  case "animal":
236586
237607
  case "face":
236587
237608
  case "package":
236588
- case "doorbell":
236589
- case "motion": return inferred;
236590
- default: return "motion";
237609
+ case "motion": return [inferred];
237610
+ case "doorbell": return ["doorbell", "motion"];
237611
+ default: return ["motion"];
236591
237612
  }
236592
237613
  }
236593
237614
  /** Default SMTP listen port. Avoid privileged 25; Reolink firmwares are
@@ -236743,8 +237764,8 @@ var ReolinkEmailPushServer = class {
236743
237764
  subject: event.subject.slice(0, 80)
236744
237765
  }
236745
237766
  });
236746
- cam.handleSimpleEvent({
236747
- type: mapInferredTypeToSimpleEvent(event.inferredType),
237767
+ for (const type of mapInferredTypeToSimpleEvents(event.inferredType)) cam.handleSimpleEvent({
237768
+ type,
236748
237769
  channel: cam.emailPushChannel,
236749
237770
  timestamp: event.receivedAtMs
236750
237771
  });