@camstack/addon-provider-reolink 1.2.163 → 1.2.164

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.
package/dist/addon.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as __toCommonJS, i as __require, n as __esmMin, o as __toESM, r as __exportAll, t as __commonJSMin } from "./chunk-CNf5ZN-e.mjs";
2
- import { A as recordingsTraceLog, C as extractPpsFromAnnexB, D as isH265Irap, E as getH265NalType, M as splitAnnexBToNalPayloads2, N as talkTraceLog, O as md5StrModern, P as traceLog, S as eventTraceLog, T as extractVpsFromAnnexB, _ as bcHeaderHasPayloadOffset, a as BC_MAGIC, b as debugLog, c as BaichuanVideoStream, f as __require$1, g as bcEncrypt, h as bcDecrypt, i as BC_CLASS_MODERN_24, j as splitAnnexBToNalPayloads, k as normalizeDebugOptions, l as BcMediaAnnexBDecoder, m as aesEncrypt, n as BC_CLASS_LEGACY, o as BC_MAGIC_REV, p as aesDecrypt, r as BC_CLASS_MODERN_20, t as BC_CLASS_FILE_DOWNLOAD, v as convertToAnnexB, w as extractSpsFromAnnexB, x as deriveAesKey, y as convertToAnnexB2 } from "./chunk-OSVYEFMM-Bl0F4OJc.mjs";
2
+ import { A as normalizeDebugOptions, C as eventTraceLog, D as getH265NalType, E as extractVpsFromAnnexB, F as traceLog, M as splitAnnexBToNalPayloads, N as splitAnnexBToNalPayloads2, O as isH265Irap, P as talkTraceLog, S as deriveAesKey, T as extractSpsFromAnnexB, _ as bcHeaderHasPayloadOffset, a as BC_MAGIC, b as convertToAnnexB2, c as BaichuanVideoStream, f as __require$1, g as bcEncrypt, h as bcDecrypt, i as BC_CLASS_MODERN_24, j as recordingsTraceLog, k as md5StrModern, l as BcMediaAnnexBDecoder, m as aesEncrypt, n as BC_CLASS_LEGACY, o as BC_MAGIC_REV, p as aesDecrypt, r as BC_CLASS_MODERN_20, t as BC_CLASS_FILE_DOWNLOAD, v as bcHeaderIsKnown20, w as extractPpsFromAnnexB, x as debugLog, y as convertToAnnexB } from "./chunk-XAKOGDFB-BI9G4P5_.mjs";
3
3
  import { createHash, randomBytes } from "node:crypto";
4
4
  import { EventEmitter } from "events";
5
5
  import * as fs2 from "fs";
@@ -5386,7 +5386,7 @@ var ZodIssueCode = {
5386
5386
  var ZodFirstPartyTypeKind;
5387
5387
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5388
5388
  //#endregion
5389
- //#region ../types/dist/sleep-COWaSCAi.mjs
5389
+ //#region ../types/dist/sleep-PEo0-Fz9.mjs
5390
5390
  /**
5391
5391
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5392
5392
  * window to float samples (D455).
@@ -6522,6 +6522,24 @@ function normalizeAddonInitResult(result) {
6522
6522
  if (Array.isArray(result)) return { providers: result };
6523
6523
  return result;
6524
6524
  }
6525
+ /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
6526
+ var PeerBytesTicketSchema = object({
6527
+ /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
6528
+ url: string().min(1),
6529
+ /**
6530
+ * The HOST node this URL means something on — the hub or a named agent,
6531
+ * never a runner. {@link AddonPeerBytes.open} compares it to its own and
6532
+ * refuses `cross-node` by name when they differ, without dialling.
6533
+ */
6534
+ hostNodeId: string().min(1),
6535
+ expiresAtMs: number().int().nonnegative(),
6536
+ /**
6537
+ * What the producer DECLARED the body to be, when it knows — `null` when it
6538
+ * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
6539
+ * must be able to tell "the producer did not say" from "the body is empty".
6540
+ */
6541
+ declaredBytes: number().int().nonnegative().nullable()
6542
+ });
6525
6543
  /** Shared Zod schemas used across streaming capabilities. */
6526
6544
  var CamProfileSchema = _enum([
6527
6545
  "high",
@@ -7602,24 +7620,6 @@ object({
7602
7620
  unreachable: number()
7603
7621
  })
7604
7622
  });
7605
- /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
7606
- var PeerBytesTicketSchema = object({
7607
- /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
7608
- url: string().min(1),
7609
- /**
7610
- * The HOST node this URL means something on — the hub or a named agent,
7611
- * never a runner. {@link AddonPeerBytes.open} compares it to its own and
7612
- * refuses `cross-node` by name when they differ, without dialling.
7613
- */
7614
- hostNodeId: string().min(1),
7615
- expiresAtMs: number().int().nonnegative(),
7616
- /**
7617
- * What the producer DECLARED the body to be, when it knows — `null` when it
7618
- * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
7619
- * must be able to tell "the producer did not say" from "the body is empty".
7620
- */
7621
- declaredBytes: number().int().nonnegative().nullable()
7622
- });
7623
7623
  /**
7624
7624
  * Adoption job — the background form of `device-adoption.adopt`.
7625
7625
  *
@@ -7731,7 +7731,7 @@ var AdoptionJobSchema = object({
7731
7731
  * component's original options — detection to the detection-pipeline wrapper
7732
7732
  * binding, audio analysis to its own, recording to `RecordingConfig.enabled`
7733
7733
  * (which was always first-class; the switch was a veneer over
7734
- * `recording.setDeviceConfig`), notifications to a notification-center
7734
+ * `recordingArchive.setDeviceConfig`), notifications to a notification-center
7735
7735
  * per-device setting, the two camera planes to their own components.
7736
7736
  *
7737
7737
  * What survives is {@link composeSwitchedOff}: `CameraStatus.switchedOff`, the
@@ -7757,7 +7757,7 @@ var AdoptionJobSchema = object({
7757
7757
  * | `stream-broker` | `deviceManager.setDisabled` | `StreamBrokerManager.reconcileAllCatalogs` releases the brokers; `ensureBroker` refuses re-creation |
7758
7758
  * | `object-detection` | `deviceManager.setWrapperActive('detection-pipeline')` | `PipelineSettingsStore.resolvePipelineForDevice` returns `{ steps: [], audio: null }` |
7759
7759
  * | `audio-analysis` | `deviceManager.setWrapperActive('audio-analysis')` | `AudioSubscriptionController.subscribeAudioStream` returns `null` before opening the stream |
7760
- * | `recording` | `recording.setDeviceConfig` → `RecordingConfig.enabled` | `band-decision.shouldRecord` returns false; the controller detaches the device |
7760
+ * | `recording` | `recordingArchive.setDeviceConfig` → `RecordingConfig.enabled` | `band-decision.shouldRecord` returns false; the controller detaches the device |
7761
7761
  * | `notifications` | `notificationRules.setDeviceMuted` | `NotificationCenter.evaluateAndEnqueue` returns before any rule is evaluated |
7762
7762
  * | `privacy-mask` | `privacyMask.setMask({ enabled })` → the CAMERA | the camera blanks the masked regions itself; every stream and recording carries the black boxes |
7763
7763
  * | `device-audio` | `privacyMask.setAudioEnabled` → the CAMERA | the camera stops encoding an audio track at all; every consumer sees silent video |
@@ -12187,87 +12187,6 @@ method(ListInputSchema, array(BrokerInfoSchema$1)), method(GetInputSchema, Broke
12187
12187
  auth: "admin"
12188
12188
  }), method(GetStateInputSchema, unknown().nullable()), method(_void(), RegistryStatusSchema);
12189
12189
  DeviceType.Camera;
12190
- /**
12191
- * The signals a device can emit to WAKE its own stream.
12192
- *
12193
- * A camera whose stream is built on demand sleeps until something asks for it,
12194
- * and "something" cannot be a consumer that is merely attached — a Frigate-style
12195
- * puller holds a session open for ever, and treating that as demand would keep
12196
- * a battery camera awake for ever, which is the whole thing the battery is for
12197
- * (D173). So the wake has to come from the CAMERA: an event it noticed by
12198
- * itself, with no stream running.
12199
- *
12200
- * ## The vocabulary is the PROVIDER'S, not ours
12201
- *
12202
- * Like `consumables`, this cap declares no vocabulary of its own. A provider
12203
- * names each signal with a `code` it chooses and a `label` an operator reads.
12204
- * Reolink offers motion and camera-native detection; another provider may offer
12205
- * a tamper, a doorbell press, a PIR, or something no camera in this fleet has
12206
- * yet. A fixed enum here would mean every new signal is a framework release.
12207
- *
12208
- * It is deliberately NOT derived from the caps a device already binds. Whether
12209
- * a camera CAN push firmware motion is expressed by `motionSources` containing
12210
- * `'onboard'`, and whether it does AI on-camera by the `native-object-detection`
12211
- * binding — but both answer "what drives the detection pipeline", which is a
12212
- * different question from "what may wake a sleeping stream". A camera can do
12213
- * the first and not be trusted with the second, and the operator picks per
12214
- * camera. Two questions, two authorities.
12215
- *
12216
- * ## Availability is not permission
12217
- *
12218
- * `listSignals` says what the device CAN emit. Whether a given signal actually
12219
- * wakes the stream is the operator's per-camera choice, held by the broker
12220
- * alongside the cooldown — see the stream-broker cap's wake settings. A
12221
- * provider declaring a signal is not a provider enabling it.
12222
- */
12223
- /** One signal a device can emit. */
12224
- var StreamSignalSchema = object({
12225
- /** Stable id chosen by the provider, e.g. `'motion'`, `'person'`, `'tamper'`. */
12226
- code: string().min(1),
12227
- /** What an operator reads in the picker. The provider's own wording. */
12228
- label: string().min(1),
12229
- /**
12230
- * Whether the provider recommends this signal ON when a camera is first set
12231
- * up. A provider knows which of its signals are cheap and reliable; an
12232
- * operator should not have to discover that by trial. Reolink recommends
12233
- * both of its own.
12234
- */
12235
- recommended: boolean()
12236
- });
12237
- var StreamSignalsStatusSchema = object({
12238
- signals: array(StreamSignalSchema),
12239
- lastFetchedAt: number()
12240
- });
12241
- var streamSignalsCapability = {
12242
- name: "stream-signals",
12243
- scope: "device",
12244
- deviceNative: true,
12245
- mode: "singleton",
12246
- deviceTypes: Object.values(DeviceType),
12247
- runtimeState: StreamSignalsStatusSchema,
12248
- /**
12249
- * Runtime-state durability: **session** — mirrored in RAM, never written.
12250
- *
12251
- * The slice holds what the DEVICE says it can emit. That is a probed fact,
12252
- * not an operator choice: the provider re-declares it on every registration,
12253
- * so losing it loses nothing and persisting it would freeze an answer the
12254
- * camera is entitled to change. Measured the same day on the sibling case —
12255
- * `native-object-detection.supportedClasses` was persisted, and a firmware
12256
- * class the camera really detected stayed missing for the life of the row
12257
- * because the fix could not reach it.
12258
- *
12259
- * See `RuntimeStateDurability`. Enforced by
12260
- * `scripts/check-runtime-state-durability.ts`.
12261
- */
12262
- durability: "session",
12263
- methods: {
12264
- /**
12265
- * What this device can emit. Empty is a valid and common answer — most
12266
- * cameras have nothing to offer here, and an empty list is what makes the
12267
- * broker's picker show nothing rather than a false choice.
12268
- */
12269
- listSignals: method(_void(), array(StreamSignalSchema).readonly()) }
12270
- };
12271
12190
  /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
12272
12191
  var StreamFormatSchema = _enum([
12273
12192
  "webrtc",
@@ -13733,6 +13652,210 @@ method(object({ codec: string() }), boolean()), method(_void(), object({
13733
13652
  });
13734
13653
  DeviceType.Camera;
13735
13654
  /**
13655
+ * device-admin-link — "this device has a management page of its own, and here
13656
+ * is its address".
13657
+ *
13658
+ * ## Why this is not a `deviceConfig` cap
13659
+ *
13660
+ * There is nothing to edit. A `deviceConfig` cap (D14) exists so the framework
13661
+ * can DERIVE a settings form from `getOptions` + `getStatus` and route a flat
13662
+ * patch back through a setter; it costs a `builderId` reducer in
13663
+ * `device-config-contribution.ts` and a `*-config-schema.ts` beside it, and it
13664
+ * renders a form section. This cap answers ONE question with ONE read and
13665
+ * renders a button. Nothing about it is a form, so it carries no `deviceConfig`
13666
+ * block, no `settings`, no `runtimeState` and no reducer — exactly like
13667
+ * `reboot`, the other pure-RPC device-native cap.
13668
+ *
13669
+ * ## Absent, and the difference between "no page" and "we cannot say"
13670
+ *
13671
+ * The two are answered at DIFFERENT layers, on purpose:
13672
+ *
13673
+ * - **"We cannot say"** → the provider never registers the cap for that
13674
+ * device. A VeSync humidifier, a Petkit feeder, a Dreame vacuum and a Dreo
13675
+ * fan are reached only through a vendor cloud; there is no address to hand
13676
+ * out and no page to open. A Tuya plug, a Wyze camera and a Gree air
13677
+ * conditioner DO have a LAN IP, and still have no HTTP management page
13678
+ * behind it. None of them register, so `deviceManager.getBindings` never
13679
+ * lists the cap and no surface asks.
13680
+ * - **"This device has no page, and I know that"** → the provider registers
13681
+ * and `getAdminLink` returns `null`. This is the answer for a device whose
13682
+ * sibling DOES have a page: a Reolink battery camera reached over UDP by
13683
+ * `uid` with a blank `host`, an Ecowitt gateway configured in `listener`
13684
+ * transport, a Home Assistant broker authenticated by supervisor token
13685
+ * (which carries no `baseUrl` at all).
13686
+ *
13687
+ * Both draw NOTHING. A button that opens a browser error is worse than no
13688
+ * button, and D62 is the same rule from the other side: an off switch is
13689
+ * reported off, never made to look broken. There is no third state where the
13690
+ * UI renders a disabled button "because the device might have a page".
13691
+ *
13692
+ * ## The URL never carries credentials
13693
+ *
13694
+ * Not in userinfo, not in a query string. Every provider builds through
13695
+ * `buildDeviceAdminUrl` (`device-admin-link-url.ts`), which takes host, port,
13696
+ * scheme and path as separate arguments — there is no parameter a secret could
13697
+ * arrive in — and re-checks its own output for the `scheme://user:pass@` shape
13698
+ * that `scripts/check-no-credential-urls-in-fixtures.ts` bans from recorded
13699
+ * output. `scripts/check-admin-link-builder-is-the-only-url-source.ts` is what
13700
+ * keeps providers from hand-rolling one anyway.
13701
+ *
13702
+ * This matters here more than anywhere else in the repo, because every provider
13703
+ * that knows a device's host knows its PASSWORD too: `{ host, port, username,
13704
+ * password }` sit in one object on Hikvision, Amcrest, Reolink and ONVIF alike,
13705
+ * and `http://admin:hunter2@192.168.50.139/` is a URL a browser accepts. The
13706
+ * camera's own page will ask for its own login. That is correct, and pre-
13707
+ * filling it is the operator's business, not ours.
13708
+ *
13709
+ * ## It is a LAN fact
13710
+ *
13711
+ * The URL addresses the device where the NODE can see it. It is not proxied,
13712
+ * not made reachable from outside, and not sent anywhere. A surface renders it
13713
+ * as a link the operator's own browser follows, on the operator's own network,
13714
+ * or renders nothing.
13715
+ */
13716
+ /**
13717
+ * Whose page is it. The distinction is for the OPERATOR, who needs to know
13718
+ * before clicking whether he is about to land on a camera's own web server or
13719
+ * inside Home Assistant.
13720
+ */
13721
+ var AdminLinkTargetEnum = _enum(["device", "integration"]);
13722
+ var DeviceAdminLinkSchema = object({
13723
+ /**
13724
+ * Absolute `http(s)://` URL. Built by `buildDeviceAdminUrl` and therefore
13725
+ * free of userinfo and of any credential-shaped query key.
13726
+ */
13727
+ url: string(),
13728
+ /**
13729
+ * What the surface calls it — "Web UI", "Home Assistant", "UniFi controller".
13730
+ * The PROVIDER names it, because only the provider knows what the page is;
13731
+ * a UI that invented the label from the addon id would call the Home
13732
+ * Assistant device page "Provider Homeassistant".
13733
+ */
13734
+ label: string(),
13735
+ target: AdminLinkTargetEnum,
13736
+ /**
13737
+ * Host the URL points at, without scheme, port or path — for the tooltip, so
13738
+ * an operator can see WHERE the button goes before he follows it. Redundant
13739
+ * with `url` by construction; carried separately so no surface has to parse
13740
+ * a URL to show it.
13741
+ */
13742
+ host: string()
13743
+ });
13744
+ var deviceAdminLinkCapability = {
13745
+ name: "device-admin-link",
13746
+ scope: "device",
13747
+ deviceNative: true,
13748
+ mode: "singleton",
13749
+ methods: {
13750
+ /**
13751
+ * The device's management page, or `null` when this device has none.
13752
+ *
13753
+ * `auth: 'admin'` deliberately. This is administration, not actuation —
13754
+ * the same bucket as `reboot` and `camera-credentials`, and explicitly NOT
13755
+ * the actuation set `scripts/check-actuation-not-admin.ts` protects (D403).
13756
+ * The URL is also a statement about the LAN, which a household member with
13757
+ * a `view` grant on a light has no reason to be handed.
13758
+ *
13759
+ * The surfaces gate on the QUERY, never on a role they guessed: a caller
13760
+ * without the right loses the query and draws nothing, which is the same
13761
+ * thing a device with no page draws. There is no path on which a button
13762
+ * appears and then fails — the D403 failure mode, from the other end.
13763
+ */
13764
+ getAdminLink: method(object({ deviceId: number().int().nonnegative() }), DeviceAdminLinkSchema.nullable(), { auth: "admin" }) }
13765
+ };
13766
+ /**
13767
+ * Query keys that may never appear on an admin link. A credential smuggled as
13768
+ * `?password=` is the same leak as userinfo, in a form the userinfo check
13769
+ * cannot see: it survives copy-paste, referrer headers and proxy logs
13770
+ * identically.
13771
+ */
13772
+ var CREDENTIAL_QUERY_KEYS = [
13773
+ "password",
13774
+ "passwd",
13775
+ "pwd",
13776
+ "pass",
13777
+ "user",
13778
+ "username",
13779
+ "usr",
13780
+ "login",
13781
+ "token",
13782
+ "access_token",
13783
+ "auth",
13784
+ "authorization",
13785
+ "apikey",
13786
+ "api_key",
13787
+ "secret",
13788
+ "credential",
13789
+ "credentials",
13790
+ "session",
13791
+ "sessionid",
13792
+ "key"
13793
+ ];
13794
+ /**
13795
+ * The same userinfo shape `scripts/check-no-credential-urls-in-fixtures.ts`
13796
+ * scans recorded fixtures for, applied to what we are about to EMIT. Kept
13797
+ * structurally identical on purpose: a URL this function returns is a URL that
13798
+ * guard would pass.
13799
+ */
13800
+ var CREDENTIAL_URL = /[a-z][a-z0-9+.-]*:\/\/[^/\s:@'"]+:[^/\s:@'"]+@/i;
13801
+ /** A host that is safe to place in an authority component verbatim. */
13802
+ var PLAIN_HOST = /^[a-zA-Z0-9._-]+$/;
13803
+ /** A bracketed IPv6 literal, the only other authority form we emit. */
13804
+ var IPV6_HOST = /^\[[0-9a-fA-F:.]+\]$/;
13805
+ function defaultPortFor(scheme) {
13806
+ return scheme === "https" ? 443 : 80;
13807
+ }
13808
+ /**
13809
+ * Build the admin-page URL, or refuse by name.
13810
+ *
13811
+ * The refusal is never thrown: a provider answering "no page for this device"
13812
+ * is an ordinary answer (`getAdminLink` → `null`), and a throw here would turn
13813
+ * a missing host on one device into a failed query for the whole surface.
13814
+ */
13815
+ function buildDeviceAdminUrl(parts) {
13816
+ const host = parts.host.trim();
13817
+ if (host.length === 0) return {
13818
+ ok: false,
13819
+ reason: "empty-host"
13820
+ };
13821
+ if (host.includes("@")) return {
13822
+ ok: false,
13823
+ reason: "host-carries-userinfo"
13824
+ };
13825
+ if (!PLAIN_HOST.test(host) && !IPV6_HOST.test(host)) return {
13826
+ ok: false,
13827
+ reason: "host-not-plain"
13828
+ };
13829
+ if (parts.port !== null) {
13830
+ if (!Number.isInteger(parts.port) || parts.port < 1 || parts.port > 65535) return {
13831
+ ok: false,
13832
+ reason: "port-out-of-range"
13833
+ };
13834
+ }
13835
+ if (!parts.path.startsWith("/")) return {
13836
+ ok: false,
13837
+ reason: "path-not-absolute"
13838
+ };
13839
+ const query = parts.query ?? {};
13840
+ for (const key of Object.keys(query)) if (CREDENTIAL_QUERY_KEYS.includes(key.toLowerCase())) return {
13841
+ ok: false,
13842
+ reason: "credential-query-key"
13843
+ };
13844
+ const authority = parts.port === null || parts.port === defaultPortFor(parts.scheme) ? host : `${host}:${String(parts.port)}`;
13845
+ const search = new URLSearchParams();
13846
+ for (const [key, value] of Object.entries(query)) search.append(key, value);
13847
+ const suffix = search.size > 0 ? `?${search.toString()}` : "";
13848
+ const url = `${parts.scheme}://${authority}${parts.path}${suffix}`;
13849
+ if (CREDENTIAL_URL.test(url)) return {
13850
+ ok: false,
13851
+ reason: "userinfo-in-result"
13852
+ };
13853
+ return {
13854
+ ok: true,
13855
+ url
13856
+ };
13857
+ }
13858
+ /**
13736
13859
  * Identity envelope for a device's upstream-system metadata.
13737
13860
  *
13738
13861
  * Two jobs:
@@ -14167,210 +14290,6 @@ method(object({ integrationId: string() }), object({ filters: array(AdoptionFilt
14167
14290
  auth: "admin"
14168
14291
  });
14169
14292
  /**
14170
- * device-admin-link — "this device has a management page of its own, and here
14171
- * is its address".
14172
- *
14173
- * ## Why this is not a `deviceConfig` cap
14174
- *
14175
- * There is nothing to edit. A `deviceConfig` cap (D14) exists so the framework
14176
- * can DERIVE a settings form from `getOptions` + `getStatus` and route a flat
14177
- * patch back through a setter; it costs a `builderId` reducer in
14178
- * `device-config-contribution.ts` and a `*-config-schema.ts` beside it, and it
14179
- * renders a form section. This cap answers ONE question with ONE read and
14180
- * renders a button. Nothing about it is a form, so it carries no `deviceConfig`
14181
- * block, no `settings`, no `runtimeState` and no reducer — exactly like
14182
- * `reboot`, the other pure-RPC device-native cap.
14183
- *
14184
- * ## Absent, and the difference between "no page" and "we cannot say"
14185
- *
14186
- * The two are answered at DIFFERENT layers, on purpose:
14187
- *
14188
- * - **"We cannot say"** → the provider never registers the cap for that
14189
- * device. A VeSync humidifier, a Petkit feeder, a Dreame vacuum and a Dreo
14190
- * fan are reached only through a vendor cloud; there is no address to hand
14191
- * out and no page to open. A Tuya plug, a Wyze camera and a Gree air
14192
- * conditioner DO have a LAN IP, and still have no HTTP management page
14193
- * behind it. None of them register, so `deviceManager.getBindings` never
14194
- * lists the cap and no surface asks.
14195
- * - **"This device has no page, and I know that"** → the provider registers
14196
- * and `getAdminLink` returns `null`. This is the answer for a device whose
14197
- * sibling DOES have a page: a Reolink battery camera reached over UDP by
14198
- * `uid` with a blank `host`, an Ecowitt gateway configured in `listener`
14199
- * transport, a Home Assistant broker authenticated by supervisor token
14200
- * (which carries no `baseUrl` at all).
14201
- *
14202
- * Both draw NOTHING. A button that opens a browser error is worse than no
14203
- * button, and D62 is the same rule from the other side: an off switch is
14204
- * reported off, never made to look broken. There is no third state where the
14205
- * UI renders a disabled button "because the device might have a page".
14206
- *
14207
- * ## The URL never carries credentials
14208
- *
14209
- * Not in userinfo, not in a query string. Every provider builds through
14210
- * `buildDeviceAdminUrl` (`device-admin-link-url.ts`), which takes host, port,
14211
- * scheme and path as separate arguments — there is no parameter a secret could
14212
- * arrive in — and re-checks its own output for the `scheme://user:pass@` shape
14213
- * that `scripts/check-no-credential-urls-in-fixtures.ts` bans from recorded
14214
- * output. `scripts/check-admin-link-builder-is-the-only-url-source.ts` is what
14215
- * keeps providers from hand-rolling one anyway.
14216
- *
14217
- * This matters here more than anywhere else in the repo, because every provider
14218
- * that knows a device's host knows its PASSWORD too: `{ host, port, username,
14219
- * password }` sit in one object on Hikvision, Amcrest, Reolink and ONVIF alike,
14220
- * and `http://admin:hunter2@192.168.50.139/` is a URL a browser accepts. The
14221
- * camera's own page will ask for its own login. That is correct, and pre-
14222
- * filling it is the operator's business, not ours.
14223
- *
14224
- * ## It is a LAN fact
14225
- *
14226
- * The URL addresses the device where the NODE can see it. It is not proxied,
14227
- * not made reachable from outside, and not sent anywhere. A surface renders it
14228
- * as a link the operator's own browser follows, on the operator's own network,
14229
- * or renders nothing.
14230
- */
14231
- /**
14232
- * Whose page is it. The distinction is for the OPERATOR, who needs to know
14233
- * before clicking whether he is about to land on a camera's own web server or
14234
- * inside Home Assistant.
14235
- */
14236
- var AdminLinkTargetEnum = _enum(["device", "integration"]);
14237
- var DeviceAdminLinkSchema = object({
14238
- /**
14239
- * Absolute `http(s)://` URL. Built by `buildDeviceAdminUrl` and therefore
14240
- * free of userinfo and of any credential-shaped query key.
14241
- */
14242
- url: string(),
14243
- /**
14244
- * What the surface calls it — "Web UI", "Home Assistant", "UniFi controller".
14245
- * The PROVIDER names it, because only the provider knows what the page is;
14246
- * a UI that invented the label from the addon id would call the Home
14247
- * Assistant device page "Provider Homeassistant".
14248
- */
14249
- label: string(),
14250
- target: AdminLinkTargetEnum,
14251
- /**
14252
- * Host the URL points at, without scheme, port or path — for the tooltip, so
14253
- * an operator can see WHERE the button goes before he follows it. Redundant
14254
- * with `url` by construction; carried separately so no surface has to parse
14255
- * a URL to show it.
14256
- */
14257
- host: string()
14258
- });
14259
- var deviceAdminLinkCapability = {
14260
- name: "device-admin-link",
14261
- scope: "device",
14262
- deviceNative: true,
14263
- mode: "singleton",
14264
- methods: {
14265
- /**
14266
- * The device's management page, or `null` when this device has none.
14267
- *
14268
- * `auth: 'admin'` deliberately. This is administration, not actuation —
14269
- * the same bucket as `reboot` and `camera-credentials`, and explicitly NOT
14270
- * the actuation set `scripts/check-actuation-not-admin.ts` protects (D403).
14271
- * The URL is also a statement about the LAN, which a household member with
14272
- * a `view` grant on a light has no reason to be handed.
14273
- *
14274
- * The surfaces gate on the QUERY, never on a role they guessed: a caller
14275
- * without the right loses the query and draws nothing, which is the same
14276
- * thing a device with no page draws. There is no path on which a button
14277
- * appears and then fails — the D403 failure mode, from the other end.
14278
- */
14279
- getAdminLink: method(object({ deviceId: number().int().nonnegative() }), DeviceAdminLinkSchema.nullable(), { auth: "admin" }) }
14280
- };
14281
- /**
14282
- * Query keys that may never appear on an admin link. A credential smuggled as
14283
- * `?password=` is the same leak as userinfo, in a form the userinfo check
14284
- * cannot see: it survives copy-paste, referrer headers and proxy logs
14285
- * identically.
14286
- */
14287
- var CREDENTIAL_QUERY_KEYS = [
14288
- "password",
14289
- "passwd",
14290
- "pwd",
14291
- "pass",
14292
- "user",
14293
- "username",
14294
- "usr",
14295
- "login",
14296
- "token",
14297
- "access_token",
14298
- "auth",
14299
- "authorization",
14300
- "apikey",
14301
- "api_key",
14302
- "secret",
14303
- "credential",
14304
- "credentials",
14305
- "session",
14306
- "sessionid",
14307
- "key"
14308
- ];
14309
- /**
14310
- * The same userinfo shape `scripts/check-no-credential-urls-in-fixtures.ts`
14311
- * scans recorded fixtures for, applied to what we are about to EMIT. Kept
14312
- * structurally identical on purpose: a URL this function returns is a URL that
14313
- * guard would pass.
14314
- */
14315
- var CREDENTIAL_URL = /[a-z][a-z0-9+.-]*:\/\/[^/\s:@'"]+:[^/\s:@'"]+@/i;
14316
- /** A host that is safe to place in an authority component verbatim. */
14317
- var PLAIN_HOST = /^[a-zA-Z0-9._-]+$/;
14318
- /** A bracketed IPv6 literal, the only other authority form we emit. */
14319
- var IPV6_HOST = /^\[[0-9a-fA-F:.]+\]$/;
14320
- function defaultPortFor(scheme) {
14321
- return scheme === "https" ? 443 : 80;
14322
- }
14323
- /**
14324
- * Build the admin-page URL, or refuse by name.
14325
- *
14326
- * The refusal is never thrown: a provider answering "no page for this device"
14327
- * is an ordinary answer (`getAdminLink` → `null`), and a throw here would turn
14328
- * a missing host on one device into a failed query for the whole surface.
14329
- */
14330
- function buildDeviceAdminUrl(parts) {
14331
- const host = parts.host.trim();
14332
- if (host.length === 0) return {
14333
- ok: false,
14334
- reason: "empty-host"
14335
- };
14336
- if (host.includes("@")) return {
14337
- ok: false,
14338
- reason: "host-carries-userinfo"
14339
- };
14340
- if (!PLAIN_HOST.test(host) && !IPV6_HOST.test(host)) return {
14341
- ok: false,
14342
- reason: "host-not-plain"
14343
- };
14344
- if (parts.port !== null) {
14345
- if (!Number.isInteger(parts.port) || parts.port < 1 || parts.port > 65535) return {
14346
- ok: false,
14347
- reason: "port-out-of-range"
14348
- };
14349
- }
14350
- if (!parts.path.startsWith("/")) return {
14351
- ok: false,
14352
- reason: "path-not-absolute"
14353
- };
14354
- const query = parts.query ?? {};
14355
- for (const key of Object.keys(query)) if (CREDENTIAL_QUERY_KEYS.includes(key.toLowerCase())) return {
14356
- ok: false,
14357
- reason: "credential-query-key"
14358
- };
14359
- const authority = parts.port === null || parts.port === defaultPortFor(parts.scheme) ? host : `${host}:${String(parts.port)}`;
14360
- const search = new URLSearchParams();
14361
- for (const [key, value] of Object.entries(query)) search.append(key, value);
14362
- const suffix = search.size > 0 ? `?${search.toString()}` : "";
14363
- const url = `${parts.scheme}://${authority}${parts.path}${suffix}`;
14364
- if (CREDENTIAL_URL.test(url)) return {
14365
- ok: false,
14366
- reason: "userinfo-in-result"
14367
- };
14368
- return {
14369
- ok: true,
14370
- url
14371
- };
14372
- }
14373
- /**
14374
14293
  * `device-export` — collection cap for addons that export camstack
14375
14294
  * devices to external ecosystems (HomeAssistant via MQTT discovery,
14376
14295
  * HomeKit/HAP, Alexa Smart Home, …).
@@ -24793,6 +24712,87 @@ method(_void(), ProviderInfoSchema, { auth: "admin" }), method(object({ config:
24793
24712
  kind: "mutation",
24794
24713
  auth: "admin"
24795
24714
  });
24715
+ /**
24716
+ * The signals a device can emit to WAKE its own stream.
24717
+ *
24718
+ * A camera whose stream is built on demand sleeps until something asks for it,
24719
+ * and "something" cannot be a consumer that is merely attached — a Frigate-style
24720
+ * puller holds a session open for ever, and treating that as demand would keep
24721
+ * a battery camera awake for ever, which is the whole thing the battery is for
24722
+ * (D173). So the wake has to come from the CAMERA: an event it noticed by
24723
+ * itself, with no stream running.
24724
+ *
24725
+ * ## The vocabulary is the PROVIDER'S, not ours
24726
+ *
24727
+ * Like `consumables`, this cap declares no vocabulary of its own. A provider
24728
+ * names each signal with a `code` it chooses and a `label` an operator reads.
24729
+ * Reolink offers motion and camera-native detection; another provider may offer
24730
+ * a tamper, a doorbell press, a PIR, or something no camera in this fleet has
24731
+ * yet. A fixed enum here would mean every new signal is a framework release.
24732
+ *
24733
+ * It is deliberately NOT derived from the caps a device already binds. Whether
24734
+ * a camera CAN push firmware motion is expressed by `motionSources` containing
24735
+ * `'onboard'`, and whether it does AI on-camera by the `native-object-detection`
24736
+ * binding — but both answer "what drives the detection pipeline", which is a
24737
+ * different question from "what may wake a sleeping stream". A camera can do
24738
+ * the first and not be trusted with the second, and the operator picks per
24739
+ * camera. Two questions, two authorities.
24740
+ *
24741
+ * ## Availability is not permission
24742
+ *
24743
+ * `listSignals` says what the device CAN emit. Whether a given signal actually
24744
+ * wakes the stream is the operator's per-camera choice, held by the broker
24745
+ * alongside the cooldown — see the stream-broker cap's wake settings. A
24746
+ * provider declaring a signal is not a provider enabling it.
24747
+ */
24748
+ /** One signal a device can emit. */
24749
+ var StreamSignalSchema = object({
24750
+ /** Stable id chosen by the provider, e.g. `'motion'`, `'person'`, `'tamper'`. */
24751
+ code: string().min(1),
24752
+ /** What an operator reads in the picker. The provider's own wording. */
24753
+ label: string().min(1),
24754
+ /**
24755
+ * Whether the provider recommends this signal ON when a camera is first set
24756
+ * up. A provider knows which of its signals are cheap and reliable; an
24757
+ * operator should not have to discover that by trial. Reolink recommends
24758
+ * both of its own.
24759
+ */
24760
+ recommended: boolean()
24761
+ });
24762
+ var StreamSignalsStatusSchema = object({
24763
+ signals: array(StreamSignalSchema),
24764
+ lastFetchedAt: number()
24765
+ });
24766
+ var streamSignalsCapability = {
24767
+ name: "stream-signals",
24768
+ scope: "device",
24769
+ deviceNative: true,
24770
+ mode: "singleton",
24771
+ deviceTypes: Object.values(DeviceType),
24772
+ runtimeState: StreamSignalsStatusSchema,
24773
+ /**
24774
+ * Runtime-state durability: **session** — mirrored in RAM, never written.
24775
+ *
24776
+ * The slice holds what the DEVICE says it can emit. That is a probed fact,
24777
+ * not an operator choice: the provider re-declares it on every registration,
24778
+ * so losing it loses nothing and persisting it would freeze an answer the
24779
+ * camera is entitled to change. Measured the same day on the sibling case —
24780
+ * `native-object-detection.supportedClasses` was persisted, and a firmware
24781
+ * class the camera really detected stayed missing for the life of the row
24782
+ * because the fix could not reach it.
24783
+ *
24784
+ * See `RuntimeStateDurability`. Enforced by
24785
+ * `scripts/check-runtime-state-durability.ts`.
24786
+ */
24787
+ durability: "session",
24788
+ methods: {
24789
+ /**
24790
+ * What this device can emit. Empty is a valid and common answer — most
24791
+ * cameras have nothing to offer here, and an empty list is what makes the
24792
+ * broker's picker show nothing rather than a false choice.
24793
+ */
24794
+ listSignals: method(_void(), array(StreamSignalSchema).readonly()) }
24795
+ };
24796
24796
  /** Profile-exported FormBuilder schema. Shape is ConfigUISchema at the UI. */
24797
24797
  var ProfileSettingsSchemaBridge = unknown().nullable();
24798
24798
  var ProfileSettingsBagSchema = record(string(), unknown());
@@ -25833,27 +25833,74 @@ var ClipStreamDialSchema = object({
25833
25833
  audioReason: ClipStreamAudioReasonSchema.optional()
25834
25834
  });
25835
25835
  /**
25836
- * The playback rates a clip can be DELIVERED at, ascending, always with `1`.
25836
+ * The playback rates the broker can pace over media it HOLDS, ascending,
25837
+ * always with `1` — and the WIDEST ladder there is. It is the domain the
25838
+ * broker's `clampPlaybackRate` is derived from, at both ends.
25837
25839
  *
25838
25840
  * These are the BROKER's: it re-paces frames it has already demuxed — the
25839
25841
  * `MonotonicClock` divides source elapsed time by the factor and the pacer
25840
- * pushes that much faster — so the domain is the recorded one, {0} ∪ [0.25, 4],
25841
- * and this is the discrete ladder drawn from it. `1.5` is in it because a
25842
- * re-pacer has no reason to refuse it.
25843
- *
25844
- * `8` and `16` are deliberately NOT here. They are the CAMERA's own
25845
- * `<playSpeed>` (Reolink cmd-5 replay), a different mechanism, still unwired
25846
- * (D597, D600) — a rate change there costs a new dial and a new stream, and
25847
- * the camera's 8x would need a resample the clip audio path has no decoder
25848
- * for. Offering them today accepts a rate and delivers 1x, which is the whole
25849
- * defect this list exists to end (D612). When `playSpeed` IS wired its rates
25850
- * join THIS array — a second list elsewhere is the second authority D62
25851
- * forbids.
25852
- *
25853
- * Every entry must survive the broker's `clampPlaybackRate` unchanged: a set
25854
- * that offers what the clamp then moves is the same lie one step later.
25842
+ * pushes that much faster. `1.5` is in it because a re-pacer has no reason to
25843
+ * refuse it.
25844
+ *
25845
+ * **`8` is here since D621, and it is the pacer's, not a camera's.** D620
25846
+ * measured the thing that was assumed for a year and was never true: a
25847
+ * Reolink `<playSpeed>` does not time-compress anything. At 1, 2, 4 and 8 the
25848
+ * transfer is byte-identical — same 947 472 bytes, same 594 access units,
25849
+ * same 39.855 s presentation span, same 624 AAC frames — and only the wall
25850
+ * clock moves. It buys SUPPLY, never speed. So there was never a second
25851
+ * mechanism to wire for 8×: there is one, this one, and what it needs is
25852
+ * media in hand and a clamp that does not move the number.
25853
+ *
25854
+ * **`16` is deliberately NOT here, and will not join by widening this array.**
25855
+ * The camera's `playSpeed 16` is not a rate at all but an I-frame-only MODE —
25856
+ * measured on 592: 10 access units for a whole 36.3 s sub clip, 20 for the
25857
+ * main twin at a 2 025 ms median spacing, and no audio track. That is
25858
+ * different CONTENT, a stream of its own, and the honest broker-side twin of
25859
+ * it would be a pacer that DROPS whole GOPs rather than one that pushes 16×
25860
+ * the bitrate at a live WebRTC track. Neither exists. A `16` in this array
25861
+ * today would be a rate accepted and delivered at 8 — D612's defect, which
25862
+ * this list exists to end, one number further along.
25863
+ *
25864
+ * Every entry must survive the broker's `clampPlaybackRate` unchanged. Since
25865
+ * D621 that is structural rather than a discipline: the clamp reads this
25866
+ * array's own ends. What still has to be proved behaviourally — and is, in
25867
+ * the broker's `clip-stream-feeder.spec` — is that the PACER really empties a
25868
+ * clip `rate` times faster, because a clamp agreeing with a ladder is a
25869
+ * constant compared against itself.
25870
+ *
25871
+ * Narrower ladders exist for transports whose SUPPLY is bounded; they are
25872
+ * subsets of this one ({@link CLIP_STREAM_SOURCE_RATES},
25873
+ * {@link CLIP_REALTIME_SOURCE_RATES}).
25855
25874
  */
25856
25875
  var CLIP_BROKER_PACED_RATES = [
25876
+ .25,
25877
+ .5,
25878
+ 1,
25879
+ 1.5,
25880
+ 2,
25881
+ 4,
25882
+ 8
25883
+ ];
25884
+ /**
25885
+ * The rates a provider-STREAMED clip can be delivered at — a subset of
25886
+ * {@link CLIP_BROKER_PACED_RATES}, and frozen below it on purpose (D621).
25887
+ *
25888
+ * A `stream` clip's media does not exist yet: it arrives on a socket from the
25889
+ * camera while the pacer consumes it. The pacer takes `rate` seconds of media
25890
+ * per second of wall clock, so the ceiling is whatever the SOURCE supplies,
25891
+ * and that is a measurement per vendor rather than a preference.
25892
+ *
25893
+ * Reolink, the one provider on this envelope, was measured on 592
25894
+ * (2026-09-23, D620): with the `<ReplaySeek>` that 0.11.1 sends before every
25895
+ * replay, a sub clip arrives at **1.2×** and a main twin at **1.37×**. The
25896
+ * ladder below is therefore ALREADY beyond this transport above 1 — the D612
25897
+ * defect returned through a door nobody opened — and D620 fixed the repair
25898
+ * order: the supply first, the ladder after. So this array does not move with
25899
+ * the broker's, and it does not gain `8`; what it gains, when the library
25900
+ * forwards a `<playSpeed>` large enough to feed the rate being paced over it,
25901
+ * is the right to be widened on a measurement rather than shortened on one.
25902
+ */
25903
+ var CLIP_STREAM_SOURCE_RATES = [
25857
25904
  .25,
25858
25905
  .5,
25859
25906
  1,
@@ -26338,7 +26385,7 @@ var CLIP_PLAYBACK_OPTIONS = {
26338
26385
  seek: "forward",
26339
26386
  stepBack: false,
26340
26387
  scrub: false,
26341
- rates: CLIP_BROKER_PACED_RATES
26388
+ rates: CLIP_STREAM_SOURCE_RATES
26342
26389
  },
26343
26390
  /**
26344
26391
  * A `stream` whose SOURCE runs at realtime — a Hikvision RTSP replay.
@@ -27722,6 +27769,143 @@ DeviceType.Camera, method(object({ deviceId: number() }), CameraCredentialsSchem
27722
27769
  auth: "admin"
27723
27770
  });
27724
27771
  /**
27772
+ * camera-grid-layout — the geometry of a COMPOSITE camera, on the camera's own
27773
+ * page.
27774
+ *
27775
+ * ## Why this is a capability and not an addon settings schema
27776
+ *
27777
+ * It was one, and it did not render. The addon declared the editor as a
27778
+ * `type: 'widget'` field inside its own `deviceSettingsSchema()`; the hub
27779
+ * returned that section correctly and `ConfigFormField` renders `type:'widget'`
27780
+ * perfectly well — and nothing ever asked camera-grid for it. The Cluster →
27781
+ * Pipeline → Device Overrides page interrogates a HAND-WRITTEN list of four
27782
+ * addons (`PIPELINE_CLUSTER_DEVICE_ADDONS`), whose own comment says an addon
27783
+ * not on it "falls off silently".
27784
+ *
27785
+ * Adding a fifth name to that list would have been the wrong fix twice over:
27786
+ * that page is per-camera DETECTION tuning, and a grid's geometry belongs
27787
+ * beside PTZ and motion zones on the camera itself. The device page is
27788
+ * BINDING-driven (D12), so the way in is a capability bound to the device —
27789
+ * and this cap carries its section the way `recording` does, by RETURNING it
27790
+ * from `getDeviceSettingsContribution`.
27791
+ *
27792
+ * Seven other widgets are still declared the other way, through a
27793
+ * `deviceConfig.ui` block the framework derives a section from. That route
27794
+ * gives the addon no say in where its own panel lands and no way to decline
27795
+ * for a device the panel does not suit, which is why this one does not use it.
27796
+ *
27797
+ * ## Why one addon may implement it
27798
+ *
27799
+ * It is a device-scoped NATIVE cap, registered by the grid camera device
27800
+ * itself. Nothing else declares a composite camera, so nothing else has a
27801
+ * layout — and the device-scoped route means the widget asks THE camera, not
27802
+ * "the camera-grid addon", which is what let the old custom-action pair be
27803
+ * reached only by a caller that already knew the addon id.
27804
+ *
27805
+ * ## The tab
27806
+ *
27807
+ * `streaming`, not a top-tab of its own. A grid's geometry IS what its stream
27808
+ * is, so the Streaming tab is where it belongs; a `grid` top-tab would need an
27809
+ * entry in `WELL_KNOWN_TAB_MAP` or the device page renders the raw id as the
27810
+ * label (measured on the robot camera, 2026-09-06 — a tab called "navigation"
27811
+ * next to "PTZ").
27812
+ */
27813
+ /** A rectangle in normalized [0,1] coordinates of whatever contains it. */
27814
+ var GridNormalizedRectSchema = object({
27815
+ x: number().min(0).max(1),
27816
+ y: number().min(0).max(1),
27817
+ width: number().gt(0).max(1),
27818
+ height: number().gt(0).max(1)
27819
+ });
27820
+ /**
27821
+ * One source camera, the part of its picture taken, and where that part lands.
27822
+ *
27823
+ * Both rectangles are NORMALIZED (D519): a source camera can change resolution
27824
+ * — a profile switch, a firmware update, a substream that comes back different
27825
+ * — and a stored PIXEL rectangle would quietly start cutting the wrong region,
27826
+ * which is the class of bug nobody files.
27827
+ */
27828
+ var GridLayoutCellSchema = object({
27829
+ deviceId: number().int().positive(),
27830
+ /** The part of the SOURCE taken, normalized against the source. */
27831
+ source: GridNormalizedRectSchema,
27832
+ /** Where it lands, normalized against the CANVAS. */
27833
+ cell: GridNormalizedRectSchema
27834
+ });
27835
+ /**
27836
+ * Which profiles this grid can actually compose, and why not.
27837
+ *
27838
+ * A grid's `high` composes its sources' `high` and its `low` their `low`, so a
27839
+ * profile is on offer only when EVERY source can serve it. The refusal NAMES
27840
+ * the sources, because "this grid has no low" is not a finding — "615 has no
27841
+ * low" is, and it is the one an operator can act on.
27842
+ */
27843
+ var GridProfileOfferSchema = object({
27844
+ profile: _enum([
27845
+ "high",
27846
+ "mid",
27847
+ "low"
27848
+ ]),
27849
+ offered: boolean(),
27850
+ /** Sources that cannot serve it. Empty when it is offered, or when there are no cells. */
27851
+ missingSources: array(number().int().positive()),
27852
+ /**
27853
+ * The canvas this profile composes onto, `WxH`, or empty when it is not
27854
+ * offered. DERIVED from the cells and the sources' own size at this profile —
27855
+ * it is reported because nothing else in the system would ever say what the
27856
+ * grid came out as, and because it is the number an operator would otherwise
27857
+ * expect to type.
27858
+ */
27859
+ canvas: string(),
27860
+ /**
27861
+ * Whether this profile is PUBLISHED, of the ones the grid could serve.
27862
+ *
27863
+ * A grid's `high` is composed of its sources' `high`, so on a 4K fleet it is
27864
+ * a 4K canvas built from 4K decodes — something to opt into, not something a
27865
+ * viewer's adaptive should be handed by climbing to the top rung it can see.
27866
+ * Default is `mid` + `low`.
27867
+ */
27868
+ published: boolean()
27869
+ });
27870
+ var GridLayoutViewSchema = object({
27871
+ /** The persisted grid row this camera was declared from. */
27872
+ instanceId: string(),
27873
+ deviceId: number().int().nonnegative(),
27874
+ name: string(),
27875
+ /**
27876
+ * NO canvas size. A grid's resolution is not authored: each profile derives
27877
+ * its own from the cells and its sources' dimensions. The two numbers that
27878
+ * used to be here were a text field that silently decided both how much the
27879
+ * composite cost and how sharp it was — see `profiles[].canvas` for what it
27880
+ * came out as.
27881
+ */
27882
+ fps: number().int(),
27883
+ cells: array(GridLayoutCellSchema),
27884
+ /** What the catalog will publish, and what it refuses to. Read-only. */
27885
+ profiles: array(GridProfileOfferSchema)
27886
+ });
27887
+ var GridLayoutPatchSchema = object({
27888
+ deviceId: number().int().nonnegative(),
27889
+ name: string().min(1).max(160).optional(),
27890
+ fps: number().int().min(1).max(60).optional(),
27891
+ /** Which profiles to publish. See `GridProfileOffer.published`. */
27892
+ publishedProfiles: array(_enum([
27893
+ "high",
27894
+ "mid",
27895
+ "low"
27896
+ ])).max(3).optional(),
27897
+ /**
27898
+ * The whole cell list at once. A per-cell patch would need an ordering the
27899
+ * editor does not have, and a half-applied layout is a picture nobody asked
27900
+ * for.
27901
+ */
27902
+ cells: array(GridLayoutCellSchema).max(16)
27903
+ });
27904
+ DeviceType.Camera, method(object({ deviceId: number().int().nonnegative() }), GridLayoutViewSchema.nullable(), { auth: "admin" }), method(GridLayoutPatchSchema, GridLayoutViewSchema, {
27905
+ kind: "mutation",
27906
+ auth: "admin"
27907
+ });
27908
+ /**
27725
27909
  * Carbon-monoxide alarm sensor. Drives Home Assistant `binary_sensor`
27726
27910
  * entries with `device_class: carbon_monoxide`. Push-driven.
27727
27911
  */
@@ -28524,511 +28708,6 @@ var dayNightCapability = {
28524
28708
  volatileStateFields: ["lastFetchedAt"]
28525
28709
  };
28526
28710
  /**
28527
- * Vendor-neutral **onboard** recording + storage cap — what the CAMERA
28528
- * writes to the CAMERA's own card, on the camera's own schedule.
28529
- *
28530
- * This is NOT `recording.cap.ts`. That one is CamStack's recorder: our
28531
- * footage ledger, our storage locations, our retention. This one has a
28532
- * different authority — the camera's firmware — and per D62 it stores
28533
- * nothing of its own. Every value here is read from the camera and every
28534
- * write goes back to the camera; there is no CamStack-side mirror that
28535
- * could disagree with the device.
28536
- *
28537
- * ## One shape, two firmwares
28538
- *
28539
- * Measured 2026-09-22 against the live fleet:
28540
- *
28541
- * | fact | Hikvision (ISAPI) | Reolink (Baichuan) |
28542
- * | --- | --- | --- |
28543
- * | storage | `ContentMgmt/Storage` `<hdd>` rows: status, capacity, freeSpace (MB) | `getHddInfoList` (cmd 102): `mount`, `format`, `capacity` GB + `capacityM` MB remainder |
28544
- * | tracks | several (101 **and** 103 on both 1436 and 3833), each with its own schedule | one per channel |
28545
- * | schedule | per track, 7 `ScheduleAction` blocks: DayOfWeek + TimeOfDay range + ONE `ActionRecordingMode` | per trigger type, a 168-char weekly HOUR mask |
28546
- * | triggers | `CMR`, `MOTION` | `Normal`, `MD`, `people`, `vehicle`, `dog_cat`, `crossline`, `intrude`, `loitering` |
28547
- * | pre-record | `PreRecordTimeSeconds` | `preRecordTime` |
28548
- * | post-record | `PostRecordTimeSeconds` | `recordDelayTime` |
28549
- * | overwrite | per track `LoopEnable` | `cycle`, with `cycleList` enumerating the accepted values |
28550
- * | segment length | not exposed on V5.7.1 | `packageTime` (minutes) |
28551
- *
28552
- * The two schedule models look different and are the same thing in
28553
- * different coordinates: both answer "for this trigger, during which
28554
- * weekly windows does the camera record". {@link RecordWindow} is that
28555
- * question in one shape — Hikvision's ranges map straight onto it,
28556
- * Reolink's mask expands into hour-aligned windows.
28557
- *
28558
- * ## Union, not intersection
28559
- *
28560
- * **The same fields exist on every camera.** What differs per device is
28561
- * which VALUES that device accepts, and that is what {@link
28562
- * RecordingOnboardOptions} reports — a `{ readable, writable, reason }`
28563
- * per field plus the schedule's own limits. A control a camera cannot
28564
- * honour is rendered DISABLED WITH ITS REASON, never missing and never
28565
- * dead: disabled must not look like broken.
28566
- *
28567
- * ## Refusal by name
28568
- *
28569
- * A write a camera cannot honour is refused with a sentence the operator
28570
- * can read — never accepted and dropped. Both providers refuse through
28571
- * {@link describeOnboardRefusal}, so the vocabulary is one function and
28572
- * one test, not two hand-written vendor opinions.
28573
- *
28574
- * Follows the D14 `deviceConfig` archetype (see `stream-params.cap.ts`):
28575
- * `getOptions` advertises per-camera availability, `getStatus` (auto-
28576
- * injected from `status`) reports the live values, and a single
28577
- * `setSettings` mutation applies a partial change. No hand-written
28578
- * settings-contribution methods.
28579
- */
28580
- /**
28581
- * What makes the camera start recording during a window.
28582
- *
28583
- * The union of both vendors' vocabularies. `continuous` is Hikvision's
28584
- * `CMR` and Reolink's `Normal`; `motion` is `MOTION` / `MD`. The
28585
- * object-class triggers are Reolink-only today and the smart-event ones
28586
- * (`lineCrossing`, `intrusion`, `loitering`) are Reolink-only on the
28587
- * firmwares measured — a camera that cannot record on a trigger simply
28588
- * does not list it in `options.schedule.triggers`, and a window naming
28589
- * it is REFUSED, not dropped.
28590
- */
28591
- var RecordTriggerSchema = _enum([
28592
- "continuous",
28593
- "motion",
28594
- "person",
28595
- "vehicle",
28596
- "animal",
28597
- "lineCrossing",
28598
- "intrusion",
28599
- "loitering",
28600
- "alarmInput"
28601
- ]);
28602
- /**
28603
- * One weekly recording window: "on `day`, from `startMinute` to
28604
- * `endMinute`, record on `trigger`".
28605
- *
28606
- * `day` is 0 = Monday … 6 = Sunday (ISO order, which is also the order
28607
- * both firmwares enumerate). Minutes are local camera time since
28608
- * midnight; `endMinute` may be 1440, meaning end of day — that is
28609
- * Hikvision's literal `24:00` and Reolink's 24th mask slot, and
28610
- * collapsing it to 0 would turn a whole-day window into an empty one.
28611
- */
28612
- var RecordWindowSchema = object({
28613
- trigger: RecordTriggerSchema,
28614
- day: number().int().min(0).max(6),
28615
- startMinute: number().int().min(0).max(1439),
28616
- endMinute: number().int().min(1).max(1440)
28617
- });
28618
- /** Status of one physical volume, as the camera itself describes it. */
28619
- var OnboardStorageVolumeSchema = object({
28620
- /** The camera's own id for the volume (`hdd/id`, Reolink `HddInfo/number`). */
28621
- id: string(),
28622
- /** The camera's own name for it, when it gives one (`hddName`). */
28623
- label: string().optional(),
28624
- status: _enum([
28625
- "ok",
28626
- "unformatted",
28627
- "error",
28628
- "offline",
28629
- "unknown"
28630
- ]),
28631
- /**
28632
- * Total size in MB, or **null when the camera did not say**.
28633
- *
28634
- * Never 0 for an unreadable value: a measurement that failed is not a
28635
- * measurement (D393), and a card whose size is unknown must not be
28636
- * rendered as a card of size zero.
28637
- */
28638
- capacityMb: number().nullable(),
28639
- /**
28640
- * Free space in MB, or null when unknown.
28641
- *
28642
- * **Not a proxy for "has footage".** Measured 2026-09-22: 1436 and
28643
- * 1439 both report exactly 11776 MB free — the fixed reserve a looping
28644
- * card converges on once it has wrapped. At loop steady state the
28645
- * number is identical whether the camera recorded yesterday or stopped
28646
- * a month ago.
28647
- */
28648
- freeMb: number().nullable(),
28649
- /** True when the camera reports the volume writable (`property` RW). */
28650
- writable: boolean().optional()
28651
- });
28652
- /**
28653
- * What the camera is doing with its own storage, right now.
28654
- *
28655
- * Every scalar is nullable and **null means the camera did not answer**,
28656
- * never a default. A form that seeds `0` from an unanswered read invites
28657
- * the operator to save that 0 back onto the camera.
28658
- */
28659
- var RecordingOnboardStatusSchema = object({
28660
- storage: discriminatedUnion("kind", [
28661
- object({
28662
- kind: literal("present"),
28663
- volumes: array(OnboardStorageVolumeSchema)
28664
- }),
28665
- object({
28666
- kind: literal("absent"),
28667
- reason: string()
28668
- }),
28669
- object({
28670
- kind: literal("unknown"),
28671
- reason: string()
28672
- })
28673
- ]),
28674
- tracks: array(object({
28675
- id: string(),
28676
- enabled: boolean(),
28677
- isVideo: boolean(),
28678
- /** From the camera's own track description. Null when it does not say. */
28679
- codec: string().nullable(),
28680
- resolution: string().nullable(),
28681
- /** Per-track overwrite flag, where the firmware keeps it per track. */
28682
- overwriteWhenFull: boolean().nullable()
28683
- })),
28684
- /**
28685
- * The track the write path targets — the enabled VIDEO one. Null when
28686
- * no track could be identified, which is itself a refusal reason.
28687
- */
28688
- primaryTrackId: string().nullable(),
28689
- /** Master "record to the card at all" switch. */
28690
- enabled: boolean().nullable(),
28691
- overwriteWhenFull: boolean().nullable(),
28692
- preRecordSec: number().nullable(),
28693
- postRecordSec: number().nullable(),
28694
- /** Length of one recorded file, in minutes. */
28695
- segmentMinutes: number().nullable(),
28696
- /** The primary track's weekly windows, flattened. */
28697
- windows: array(RecordWindowSchema),
28698
- /**
28699
- * How many windows the camera described that CamStack could NOT read —
28700
- * an unrecognised trigger, an unparseable clock, a weekday it does not
28701
- * name.
28702
- *
28703
- * A dropped window is work the reader threw away, and a schedule that
28704
- * silently shows fewer rows than the camera holds is how an operator
28705
- * saves back a schedule shorter than the one they were looking at
28706
- * (D391). Non-zero means the window list is INCOMPLETE and a write
28707
- * that replaces it would delete what was not shown — which is why a
28708
- * provider reporting a non-zero count also reports the schedule as not
28709
- * writable.
28710
- */
28711
- unreadableWindows: number(),
28712
- /**
28713
- * The camera is scheduled to record and has NO usable storage.
28714
- *
28715
- * A first-class fact because it is the fleet's most common silent
28716
- * defect: measured 2026-09-22, 1441 and 3831 are both motion-recording
28717
- * to a card that is not there. Neither the schedule nor the storage
28718
- * read says anything wrong on its own; only the pair does.
28719
- */
28720
- recordingToNowhere: boolean(),
28721
- lastFetchedAt: number()
28722
- });
28723
- /** Numeric range descriptor — `{ min, max, step }` per the getOptions convention. */
28724
- var RangeSchema = object({
28725
- min: number(),
28726
- max: number(),
28727
- step: number()
28728
- });
28729
- /**
28730
- * The values a camera actually takes for a numeric field, when they are a SET
28731
- * rather than a range.
28732
- *
28733
- * `{min,max,step}` cannot say what these two firmwares do. Measured on 1436
28734
- * (I91DN) on 2026-09-22 by writing each value and reading it back:
28735
- *
28736
- * - pre-record: `0, 5, 10, 15, 20, 25, 30` and `2147483647` (INT32_MAX, the
28737
- * camera's "no limit" — `-1` and `4294967295` both land on it);
28738
- * - post-record: `5, 10, 30, 60, 120, 300, 600`.
28739
- *
28740
- * Neither is expressible as a step: the first has a sentinel two billion away
28741
- * from its neighbours, the second doubles and then jumps. A range that tried
28742
- * would forbid values the camera takes AND permit values it silently replaces
28743
- * with 5 — wrong in both directions at once.
28744
- *
28745
- * `sentinel` names the member that is not a duration, so a surface can render
28746
- * "no limit" instead of `2147483647` seconds.
28747
- */
28748
- var AllowedValuesSchema = object({
28749
- values: array(number()).min(1),
28750
- sentinel: object({
28751
- value: number(),
28752
- meaning: _enum(["no-limit", "disabled"])
28753
- }).optional()
28754
- });
28755
- /**
28756
- * Per-field availability on ONE camera.
28757
- *
28758
- * The field exists on every camera — this says whether this one can be
28759
- * read and whether it can be written, and `reason` says why not when
28760
- * either is false. The UI renders the control DISABLED with the reason
28761
- * rather than hiding it, so a limitation is legible instead of looking
28762
- * like a missing feature.
28763
- */
28764
- var OnboardFieldSupportSchema = object({
28765
- readable: boolean(),
28766
- writable: boolean(),
28767
- /** Required whenever `readable` or `writable` is false. */
28768
- reason: string().optional()
28769
- });
28770
- /** What this camera's schedule model can express. */
28771
- var OnboardScheduleSupportSchema = object({
28772
- support: OnboardFieldSupportSchema,
28773
- /**
28774
- * The smallest time step the camera can express, in minutes.
28775
- *
28776
- * Hikvision takes arbitrary minutes (`00:05:00`–`23:57:00` observed on
28777
- * 1436's track 103). Reolink's schedule is a 7×24 HOUR mask, so 60. A
28778
- * window whose edges are not a multiple of this is REFUSED rather than
28779
- * quietly rounded — rounding is how an operator's 06:30 becomes 06:00
28780
- * and nothing says so.
28781
- */
28782
- granularityMinutes: number(),
28783
- /** Triggers this camera can record on. A window naming another is refused. */
28784
- triggers: array(RecordTriggerSchema),
28785
- /**
28786
- * False when the camera stores ONE trigger per time range, so two
28787
- * windows overlapping on the same day cannot carry different triggers.
28788
- * True on Reolink, whose mask is per-trigger and independent.
28789
- */
28790
- supportsOverlappingTriggers: boolean()
28791
- });
28792
- var RecordingOnboardOptionsSchema = object({
28793
- enabled: OnboardFieldSupportSchema,
28794
- overwriteWhenFull: OnboardFieldSupportSchema,
28795
- preRecordSec: OnboardFieldSupportSchema,
28796
- preRecordSecRange: RangeSchema.optional(),
28797
- /** Preferred over the range when the camera takes a SET, not a span. */
28798
- preRecordSecAllowed: AllowedValuesSchema.optional(),
28799
- postRecordSec: OnboardFieldSupportSchema,
28800
- postRecordSecRange: RangeSchema.optional(),
28801
- /** Preferred over the range when the camera takes a SET, not a span. */
28802
- postRecordSecAllowed: AllowedValuesSchema.optional(),
28803
- segmentMinutes: OnboardFieldSupportSchema,
28804
- segmentMinutesRange: RangeSchema.optional(),
28805
- /** Preferred over the range when the camera takes a SET, not a span. */
28806
- segmentMinutesAllowed: AllowedValuesSchema.optional(),
28807
- schedule: OnboardScheduleSupportSchema
28808
- });
28809
- /**
28810
- * A partial change. Every field optional.
28811
- *
28812
- * Unlike the other `deviceConfig` caps, a provider here does **NOT**
28813
- * silently ignore a field it cannot support — it refuses, by name,
28814
- * through {@link describeOnboardRefusal}. Silence on a recording setting
28815
- * is the failure D62 exists to prevent: the operator believes the camera
28816
- * is recording the way the form says, and it is not.
28817
- */
28818
- var RecordingOnboardPatchSchema = object({
28819
- enabled: boolean().optional(),
28820
- overwriteWhenFull: boolean().optional(),
28821
- preRecordSec: number().optional(),
28822
- postRecordSec: number().optional(),
28823
- segmentMinutes: number().optional(),
28824
- /** The complete new window set for the primary track — not a delta. */
28825
- windows: array(RecordWindowSchema).optional()
28826
- });
28827
- var recordingOnboardCapability = {
28828
- name: "recording-onboard",
28829
- scope: "device",
28830
- deviceNative: true,
28831
- mode: "singleton",
28832
- deviceTypes: [DeviceType.Camera],
28833
- deviceConfig: { ui: {
28834
- kind: "derived-form",
28835
- builderId: "recording-onboard",
28836
- tab: "recording"
28837
- } },
28838
- methods: {
28839
- getOptions: method(object({ deviceId: number() }), RecordingOnboardOptionsSchema),
28840
- setSettings: method(object({
28841
- deviceId: number(),
28842
- settings: RecordingOnboardPatchSchema
28843
- }), _void(), {
28844
- kind: "mutation",
28845
- auth: "admin"
28846
- })
28847
- },
28848
- status: {
28849
- schema: RecordingOnboardStatusSchema,
28850
- kind: "poll"
28851
- },
28852
- runtimeState: RecordingOnboardStatusSchema,
28853
- /**
28854
- * Runtime-state durability: **restored** — operator-set camera-side
28855
- * recording config; mutation-driven, and the storage half is the last
28856
- * thing the camera said about its own card.
28857
- *
28858
- * See `RuntimeStateDurability`. Enforced by
28859
- * `scripts/check-runtime-state-durability.ts`.
28860
- */
28861
- durability: "restored",
28862
- /** Clock fields: written, but excluded from the compare that decides
28863
- * whether persisting is worth a SQLite commit. */
28864
- volatileStateFields: ["lastFetchedAt"]
28865
- };
28866
- /**
28867
- * Day-of-week names in the cap's index order (0 = Monday), for messages
28868
- * an operator reads and for Hikvision's `<DayOfWeek>` element.
28869
- */
28870
- var DAY_NAMES = [
28871
- "Monday",
28872
- "Tuesday",
28873
- "Wednesday",
28874
- "Thursday",
28875
- "Friday",
28876
- "Saturday",
28877
- "Sunday"
28878
- ];
28879
- /**
28880
- * Does `patch` ask this camera for something it cannot do?
28881
- *
28882
- * Returns the operator-readable reason, or `null` when every field in
28883
- * the patch is within what `options` says this camera accepts. A
28884
- * provider calls this BEFORE touching the camera and throws the string:
28885
- * refusing is the point, and refusing identically on both vendors is why
28886
- * this is one function.
28887
- *
28888
- * The order of checks is the order an operator would read them: the
28889
- * scalar knobs first, then the schedule, because a schedule complaint is
28890
- * longer and a scalar one is usually the real problem.
28891
- */
28892
- function describeOnboardRefusal(options, patch) {
28893
- if (patch.enabled !== void 0 && !options.enabled.writable) return unwritable("the master recording switch", options.enabled.reason);
28894
- if (patch.overwriteWhenFull !== void 0 && !options.overwriteWhenFull.writable) return unwritable("overwrite-when-full", options.overwriteWhenFull.reason);
28895
- const preRefusal = refuseNumeric("pre-record seconds", patch.preRecordSec, options.preRecordSec, options.preRecordSecRange, options.preRecordSecAllowed);
28896
- if (preRefusal) return preRefusal;
28897
- const postRefusal = refuseNumeric("post-record seconds", patch.postRecordSec, options.postRecordSec, options.postRecordSecRange, options.postRecordSecAllowed);
28898
- if (postRefusal) return postRefusal;
28899
- const segmentRefusal = refuseNumeric("segment length (minutes)", patch.segmentMinutes, options.segmentMinutes, options.segmentMinutesRange, options.segmentMinutesAllowed);
28900
- if (segmentRefusal) return segmentRefusal;
28901
- if (patch.windows !== void 0) {
28902
- const scheduleRefusal = refuseSchedule(options, patch.windows);
28903
- if (scheduleRefusal) return scheduleRefusal;
28904
- }
28905
- return null;
28906
- }
28907
- function unwritable(what, reason) {
28908
- return reason ? `this camera cannot change ${what}: ${reason}` : `this camera cannot change ${what}`;
28909
- }
28910
- function refuseNumeric(what, value, support, range, allowed) {
28911
- if (value === void 0) return null;
28912
- if (!support.writable) return unwritable(what, support.reason);
28913
- if (!Number.isFinite(value)) return `${what} must be a number, got ${String(value)}`;
28914
- if (allowed) {
28915
- if (allowed.values.includes(value)) return null;
28916
- const say = (v) => allowed.sentinel !== void 0 && v === allowed.sentinel.value ? allowed.sentinel.meaning === "no-limit" ? "no limit" : "off" : String(v);
28917
- return `this camera accepts ${what} only as ${allowed.values.map(say).join(", ")}; ${say(value)} is not one of them`;
28918
- }
28919
- if (!range) return null;
28920
- if (value < range.min || value > range.max) return `this camera accepts ${what} between ${String(range.min)} and ${String(range.max)}; ${String(value)} is outside that`;
28921
- if (range.step > 0 && (value - range.min) % range.step !== 0) return `this camera accepts ${what} in steps of ${String(range.step)} from ${String(range.min)}; ${String(value)} is not one of them`;
28922
- return null;
28923
- }
28924
- function refuseSchedule(options, windows) {
28925
- const schedule = options.schedule;
28926
- if (!schedule.support.writable) return unwritable("the recording schedule", schedule.support.reason);
28927
- const allowed = new Set(schedule.triggers);
28928
- for (const window of windows) {
28929
- if (!allowed.has(window.trigger)) {
28930
- const offer = schedule.triggers.length > 0 ? schedule.triggers.join(", ") : "none";
28931
- return `this camera cannot record on "${window.trigger}"; it records on: ${offer}`;
28932
- }
28933
- if (window.endMinute <= window.startMinute) return `a window on ${dayName(window.day)} ends at or before it starts (${String(window.startMinute)} → ${String(window.endMinute)})`;
28934
- const step = schedule.granularityMinutes;
28935
- if (step > 1 && (window.startMinute % step !== 0 || window.endMinute % step !== 0)) return `this camera's schedule only moves in ${String(step)}-minute steps; the ${dayName(window.day)} window ${formatMinutes(window.startMinute)}–${formatMinutes(window.endMinute)} is not aligned to them`;
28936
- }
28937
- if (!schedule.supportsOverlappingTriggers) {
28938
- const clash = findOverlapWithDifferentTrigger(windows);
28939
- if (clash) return `this camera stores one trigger per time range, so "${clash.a.trigger}" and "${clash.b.trigger}" cannot both cover ${dayName(clash.a.day)} ${formatMinutes(Math.max(clash.a.startMinute, clash.b.startMinute))}–${formatMinutes(Math.min(clash.a.endMinute, clash.b.endMinute))}`;
28940
- }
28941
- return null;
28942
- }
28943
- function findOverlapWithDifferentTrigger(windows) {
28944
- for (let i = 0; i < windows.length; i += 1) for (let j = i + 1; j < windows.length; j += 1) {
28945
- const a = windows[i];
28946
- const b = windows[j];
28947
- if (!a || !b) continue;
28948
- if (a.day !== b.day) continue;
28949
- if (a.trigger === b.trigger) continue;
28950
- if (a.startMinute < b.endMinute && b.startMinute < a.endMinute) return {
28951
- a,
28952
- b
28953
- };
28954
- }
28955
- return null;
28956
- }
28957
- function dayName(day) {
28958
- return DAY_NAMES[day] ?? `day ${String(day)}`;
28959
- }
28960
- /** `510` → `08:30`. For messages, not for the wire. */
28961
- function formatMinutes(minute) {
28962
- const hour = Math.floor(minute / 60);
28963
- const rest = minute % 60;
28964
- return `${String(hour).padStart(2, "0")}:${String(rest).padStart(2, "0")}`;
28965
- }
28966
- /**
28967
- * Index of the mask character covering `day` at `hour`.
28968
- *
28969
- * **Layout: day-major, Monday first** — `day * 24 + hour`.
28970
- *
28971
- * This is an ASSUMPTION, and it is recorded as one because the fleet
28972
- * cannot currently confirm it: every `valueTable` on every Reolink
28973
- * measured on 2026-09-22 is uniform (all `1` or all `0`), and a uniform
28974
- * mask reads identically under either layout. To settle it, set a single
28975
- * hour on one day from the Reolink app and re-read `getRecordSchedule`.
28976
- * Until then, a NON-uniform mask is reported as windows under this
28977
- * layout and the day labels may be transposed; a uniform one is exact.
28978
- */
28979
- function weeklyMaskIndex(day, hour) {
28980
- return day * 24 + hour;
28981
- }
28982
- /**
28983
- * Expand one trigger's weekly hour mask into windows, merging adjacent
28984
- * set hours into one window per run so a full day is ONE window rather
28985
- * than twenty-four.
28986
- *
28987
- * A mask of the wrong length yields no windows: a truncated table is not
28988
- * a schedule of fewer days, it is an answer we did not understand.
28989
- */
28990
- function weeklyMaskToWindows(mask, trigger) {
28991
- if (mask.length !== 168) return [];
28992
- const out = [];
28993
- for (let day = 0; day < 7; day += 1) {
28994
- let runStart = null;
28995
- for (let hour = 0; hour <= 24; hour += 1) {
28996
- const set = hour < 24 && mask[weeklyMaskIndex(day, hour)] === "1";
28997
- if (set && runStart === null) runStart = hour;
28998
- else if (!set && runStart !== null) {
28999
- out.push({
29000
- trigger,
29001
- day,
29002
- startMinute: runStart * 60,
29003
- endMinute: hour * 60
29004
- });
29005
- runStart = null;
29006
- }
29007
- }
29008
- }
29009
- return out;
29010
- }
29011
- /**
29012
- * Collapse this trigger's windows back into a weekly hour mask.
29013
- *
29014
- * Windows for other triggers are ignored — the mask is per trigger. A
29015
- * window that is not hour-aligned is REFUSED upstream by
29016
- * {@link describeOnboardRefusal}; this function rounds nothing, it
29017
- * simply sets every hour the window fully or partly covers, so a caller
29018
- * that skipped the refusal cannot silently lose coverage.
29019
- */
29020
- function windowsToWeeklyMask(windows, trigger) {
29021
- const slots = new Array(168).fill("0");
29022
- for (const window of windows) {
29023
- if (window.trigger !== trigger) continue;
29024
- if (window.day < 0 || window.day >= 7) continue;
29025
- const firstHour = Math.floor(window.startMinute / 60);
29026
- const lastHour = Math.ceil(window.endMinute / 60);
29027
- for (let hour = firstHour; hour < lastHour && hour < 24; hour += 1) slots[weeklyMaskIndex(window.day, hour)] = "1";
29028
- }
29029
- return slots.join("");
29030
- }
29031
- /**
29032
28711
  * Generic device-level status snapshot. Auto-registered by `BaseDevice`
29033
28712
  * for every device, regardless of provider — the kernel needs a uniform
29034
28713
  * cap-keyed slice for the basic device flags every consumer expects to
@@ -29247,30 +28926,6 @@ var eventEmitterCapability = {
29247
28926
  */
29248
28927
  durability: "session"
29249
28928
  };
29250
- var EventItemSchema = object({
29251
- id: string(),
29252
- type: string(),
29253
- timestamp: number(),
29254
- label: string().optional(),
29255
- thumbnailUrl: string().optional(),
29256
- clipUrl: string().optional(),
29257
- metadata: record(string(), unknown()).optional()
29258
- });
29259
- DeviceType.Camera, method(object({
29260
- deviceId: number(),
29261
- from: number().optional(),
29262
- to: number().optional(),
29263
- limit: number().optional()
29264
- }), array(EventItemSchema)), method(object({
29265
- deviceId: number(),
29266
- eventId: string()
29267
- }), object({
29268
- base64: string(),
29269
- contentType: string()
29270
- }).nullable()), method(object({
29271
- deviceId: number(),
29272
- eventId: string()
29273
- }), string().nullable());
29274
28929
  var IdentitySchema = object({
29275
28930
  id: string(),
29276
28931
  name: string(),
@@ -31523,143 +31178,6 @@ var motionTriggerCapability = {
31523
31178
  durability: "session"
31524
31179
  };
31525
31180
  /**
31526
- * camera-grid-layout — the geometry of a COMPOSITE camera, on the camera's own
31527
- * page.
31528
- *
31529
- * ## Why this is a capability and not an addon settings schema
31530
- *
31531
- * It was one, and it did not render. The addon declared the editor as a
31532
- * `type: 'widget'` field inside its own `deviceSettingsSchema()`; the hub
31533
- * returned that section correctly and `ConfigFormField` renders `type:'widget'`
31534
- * perfectly well — and nothing ever asked camera-grid for it. The Cluster →
31535
- * Pipeline → Device Overrides page interrogates a HAND-WRITTEN list of four
31536
- * addons (`PIPELINE_CLUSTER_DEVICE_ADDONS`), whose own comment says an addon
31537
- * not on it "falls off silently".
31538
- *
31539
- * Adding a fifth name to that list would have been the wrong fix twice over:
31540
- * that page is per-camera DETECTION tuning, and a grid's geometry belongs
31541
- * beside PTZ and motion zones on the camera itself. The device page is
31542
- * BINDING-driven (D12), so the way in is a capability bound to the device —
31543
- * and this cap carries its section the way `recording` does, by RETURNING it
31544
- * from `getDeviceSettingsContribution`.
31545
- *
31546
- * Seven other widgets are still declared the other way, through a
31547
- * `deviceConfig.ui` block the framework derives a section from. That route
31548
- * gives the addon no say in where its own panel lands and no way to decline
31549
- * for a device the panel does not suit, which is why this one does not use it.
31550
- *
31551
- * ## Why one addon may implement it
31552
- *
31553
- * It is a device-scoped NATIVE cap, registered by the grid camera device
31554
- * itself. Nothing else declares a composite camera, so nothing else has a
31555
- * layout — and the device-scoped route means the widget asks THE camera, not
31556
- * "the camera-grid addon", which is what let the old custom-action pair be
31557
- * reached only by a caller that already knew the addon id.
31558
- *
31559
- * ## The tab
31560
- *
31561
- * `streaming`, not a top-tab of its own. A grid's geometry IS what its stream
31562
- * is, so the Streaming tab is where it belongs; a `grid` top-tab would need an
31563
- * entry in `WELL_KNOWN_TAB_MAP` or the device page renders the raw id as the
31564
- * label (measured on the robot camera, 2026-09-06 — a tab called "navigation"
31565
- * next to "PTZ").
31566
- */
31567
- /** A rectangle in normalized [0,1] coordinates of whatever contains it. */
31568
- var GridNormalizedRectSchema = object({
31569
- x: number().min(0).max(1),
31570
- y: number().min(0).max(1),
31571
- width: number().gt(0).max(1),
31572
- height: number().gt(0).max(1)
31573
- });
31574
- /**
31575
- * One source camera, the part of its picture taken, and where that part lands.
31576
- *
31577
- * Both rectangles are NORMALIZED (D519): a source camera can change resolution
31578
- * — a profile switch, a firmware update, a substream that comes back different
31579
- * — and a stored PIXEL rectangle would quietly start cutting the wrong region,
31580
- * which is the class of bug nobody files.
31581
- */
31582
- var GridLayoutCellSchema = object({
31583
- deviceId: number().int().positive(),
31584
- /** The part of the SOURCE taken, normalized against the source. */
31585
- source: GridNormalizedRectSchema,
31586
- /** Where it lands, normalized against the CANVAS. */
31587
- cell: GridNormalizedRectSchema
31588
- });
31589
- /**
31590
- * Which profiles this grid can actually compose, and why not.
31591
- *
31592
- * A grid's `high` composes its sources' `high` and its `low` their `low`, so a
31593
- * profile is on offer only when EVERY source can serve it. The refusal NAMES
31594
- * the sources, because "this grid has no low" is not a finding — "615 has no
31595
- * low" is, and it is the one an operator can act on.
31596
- */
31597
- var GridProfileOfferSchema = object({
31598
- profile: _enum([
31599
- "high",
31600
- "mid",
31601
- "low"
31602
- ]),
31603
- offered: boolean(),
31604
- /** Sources that cannot serve it. Empty when it is offered, or when there are no cells. */
31605
- missingSources: array(number().int().positive()),
31606
- /**
31607
- * The canvas this profile composes onto, `WxH`, or empty when it is not
31608
- * offered. DERIVED from the cells and the sources' own size at this profile —
31609
- * it is reported because nothing else in the system would ever say what the
31610
- * grid came out as, and because it is the number an operator would otherwise
31611
- * expect to type.
31612
- */
31613
- canvas: string(),
31614
- /**
31615
- * Whether this profile is PUBLISHED, of the ones the grid could serve.
31616
- *
31617
- * A grid's `high` is composed of its sources' `high`, so on a 4K fleet it is
31618
- * a 4K canvas built from 4K decodes — something to opt into, not something a
31619
- * viewer's adaptive should be handed by climbing to the top rung it can see.
31620
- * Default is `mid` + `low`.
31621
- */
31622
- published: boolean()
31623
- });
31624
- var GridLayoutViewSchema = object({
31625
- /** The persisted grid row this camera was declared from. */
31626
- instanceId: string(),
31627
- deviceId: number().int().nonnegative(),
31628
- name: string(),
31629
- /**
31630
- * NO canvas size. A grid's resolution is not authored: each profile derives
31631
- * its own from the cells and its sources' dimensions. The two numbers that
31632
- * used to be here were a text field that silently decided both how much the
31633
- * composite cost and how sharp it was — see `profiles[].canvas` for what it
31634
- * came out as.
31635
- */
31636
- fps: number().int(),
31637
- cells: array(GridLayoutCellSchema),
31638
- /** What the catalog will publish, and what it refuses to. Read-only. */
31639
- profiles: array(GridProfileOfferSchema)
31640
- });
31641
- var GridLayoutPatchSchema = object({
31642
- deviceId: number().int().nonnegative(),
31643
- name: string().min(1).max(160).optional(),
31644
- fps: number().int().min(1).max(60).optional(),
31645
- /** Which profiles to publish. See `GridProfileOffer.published`. */
31646
- publishedProfiles: array(_enum([
31647
- "high",
31648
- "mid",
31649
- "low"
31650
- ])).max(3).optional(),
31651
- /**
31652
- * The whole cell list at once. A per-cell patch would need an ordering the
31653
- * editor does not have, and a half-applied layout is a picture nobody asked
31654
- * for.
31655
- */
31656
- cells: array(GridLayoutCellSchema).max(16)
31657
- });
31658
- DeviceType.Camera, method(object({ deviceId: number().int().nonnegative() }), GridLayoutViewSchema.nullable(), { auth: "admin" }), method(GridLayoutPatchSchema, GridLayoutViewSchema, {
31659
- kind: "mutation",
31660
- auth: "admin"
31661
- });
31662
- /**
31663
31181
  * Motion-zones share the same MaskShape vocabulary as privacy-mask — the
31664
31182
  * on-camera motion-detection mask is a single `grid` region (a row-major
31665
31183
  * boolean cell lattice the camera's onboard VMD evaluates). Composing it as
@@ -34179,37 +33697,37 @@ var rebootCapability = {
34179
33697
  auth: "admin"
34180
33698
  }) }
34181
33699
  };
34182
- /**
34183
- * `recording` cap — footage availability + HLS playback manifests + per-device
34184
- * recording config. NOTE on events (source of truth, R5/C3): this cap carries
34185
- * NO event surface — `getPlaybackManifest` returns playlist URLs only. Timeline
34186
- * events (motion/object/audio) come from `pipelineAnalytics` (durable SQLite
34187
- * rows) and are the ONLY event surface — the recorder has none. The in-RAM
34188
- * playback markers it used to build were deleted on 2026-08-29 because nothing
34189
- * ever read them. Event<->footage joins are by time, padded with the shared
34190
- * `EVENT_PAD_MS` (`interfaces/recording-config.ts`).
34191
- */
34192
- var RecordingStatusSchema = object({
34193
- deviceId: number(),
34194
- enabled: boolean(),
34195
- /** THE derived storage mode, from the one definition
34196
- * (`deriveRecordingMode`) — never a second enum. A duplicated list is how
34197
- * `on-device-decision` could have reached the recorder and not the status. */
34198
- activeMode: RecordingStorageModeSchema,
34199
- nodeId: string(),
34200
- storageBytes: number()
34201
- });
34202
33700
  var RecordingRangeSchema = object({
34203
33701
  profile: string(),
34204
33702
  startMs: number(),
34205
33703
  endMs: number()
34206
33704
  });
33705
+ /**
33706
+ * How a source ANSWERED, on every singular read of this cap.
33707
+ *
33708
+ * `'read'` — it looked. `ranges: []` / `days: []` is then a real claim: this
33709
+ * source has no coverage in the window. `'unreadable'` — nobody could look
33710
+ * (the camera was unreachable, the calendar rung threw, the location is
33711
+ * unmounted, the node is still on the old build), and the emptiness beside it
33712
+ * means NOTHING.
33713
+ *
33714
+ * The batch rows have carried this since the grid existed; the SINGULAR
33715
+ * answers gained it with the collection (D625 §10.4), because they are the
33716
+ * ones the single-camera picker uses and because a half-converted fleet makes
33717
+ * "nobody looked" common for the length of a deploy. Without it the timeline
33718
+ * has no vocabulary for it, and `(data ?? [])` in a viewer turns a rollout into
33719
+ * a fleet of cameras that appear to have lost their recordings (D315, D393).
33720
+ */
33721
+ var RecordingReadSchema = _enum(["read", "unreadable"]);
34207
33722
  var RecordingAvailabilitySchema = object({
34208
33723
  deviceId: number(),
33724
+ /** See {@link RecordingReadSchema}. An `'unreadable'` answer carries an empty
33725
+ * `ranges` that means nothing — never draw it as "no footage". */
33726
+ read: RecordingReadSchema,
34209
33727
  ranges: array(RecordingRangeSchema),
34210
33728
  /**
34211
- * Every profile this camera has footage in — not only the one `ranges`
34212
- * describes (D433).
33729
+ * Every profile this camera has footage in AT THIS SOURCE — not only the one
33730
+ * `ranges` describes (D433).
34213
33731
  *
34214
33732
  * `ranges` answers for ONE profile by design: the timeline is a single bar,
34215
33733
  * and enumerating all of them triples the directory reads for a bar that
@@ -34226,15 +33744,285 @@ var RecordingAvailabilitySchema = object({
34226
33744
  });
34227
33745
  var RecordingDaysSchema = object({
34228
33746
  deviceId: number(),
33747
+ /** See {@link RecordingReadSchema}. `days: []` on an `'unreadable'` answer is
33748
+ * "nobody could look", and the date-picker must not spell it the same as
33749
+ * "no footage this month". */
33750
+ read: RecordingReadSchema,
34229
33751
  /** Local-midnight epochs (UTC ms) of days that have ≥1 recorded segment. */
34230
33752
  days: array(number())
34231
33753
  });
33754
+ var RecordingManifestSchema = object({
33755
+ deviceId: number(),
33756
+ /** Local filesystem path to the master playlist; null when no recording exists for the requested range. */
33757
+ localMasterPath: string().nullable(),
33758
+ /** HTTP(S) URL to the master playlist on the recording node's playback server
33759
+ * (the PRIMARY candidate); null when no recording / server. Carries the
33760
+ * scoped playback token in its path. */
33761
+ playbackUrl: string().nullable(),
33762
+ /**
33763
+ * Candidate master-playlist URLs the client tries in order (LAN first, then
33764
+ * remote — Tailscale/Cloudflare if the operator configured extra hosts), each
33765
+ * carrying the same scoped token. `playbackUrl` is the first entry. Empty when
33766
+ * there is no recording / server.
33767
+ */
33768
+ playbackEndpoints: array(string())
33769
+ });
33770
+ var RecordingSourceAvailabilitySchema = object({
33771
+ state: _enum([
33772
+ "ok",
33773
+ "sleeping",
33774
+ "unreachable",
33775
+ "no-storage",
33776
+ "index-empty"
33777
+ ]),
33778
+ /** Free text, shown verbatim. Names the camera's own refusal when there is one. */
33779
+ reason: string().optional(),
33780
+ /** When this source's coverage was last CONFIRMED. A cached answer is never
33781
+ * drawn as current: the surface shows the age whenever it is older than the
33782
+ * refresh interval. The clip catalog's `catalogAsOf`, under the name the
33783
+ * timeline uses for it. */
33784
+ coverageAsOf: number().optional()
33785
+ });
33786
+ /**
33787
+ * One SOURCE of recorded coverage for a camera — a row of the picker.
33788
+ *
33789
+ * A provider lists the sources IT serves for that device, and answers for each
33790
+ * of them whether it can answer at all. A provider with nothing to offer on a
33791
+ * camera returns `[]` — it is not that camera's business. The five availability
33792
+ * states are `ClipSourceAvailability`'s verbatim: they mean exactly the same
33793
+ * things about a coverage index as about a clip catalog, and `sleeping` in
33794
+ * particular is what stops a battery camera being woken to paint a bar.
33795
+ */
33796
+ var RecordingSourceSchema = object({
33797
+ /** The source id. {@link RECORDING_SOURCE_CAMSTACK} for ours (RESERVED), a
33798
+ * vendor namespace (`native:reolink:onboard`, …) for a camera's own store. */
33799
+ source: string(),
33800
+ /** Operator-facing name of the source ("CamStack recordings", "SD card"). */
33801
+ label: string(),
33802
+ /**
33803
+ * The addon that SERVES this row, and the value a later call passes as
33804
+ * `provider`.
33805
+ *
33806
+ * Optional for version skew only. The collection dispatcher stamps it from
33807
+ * the registry, so a row that travelled through the fan-out carries the
33808
+ * authoritative id whatever the provider filled in (D557 §4).
33809
+ */
33810
+ addonId: string().optional(),
33811
+ availability: RecordingSourceAvailabilitySchema
33812
+ });
33813
+ /**
33814
+ * What a surface may DRAW for this (camera, source) — D612's rule applied to a
33815
+ * timeline: **the source declares what it can do, and the surface draws what
33816
+ * was declared. It never assumes, and never offers a gesture it will then
33817
+ * refuse.** D612 exists because `8` and `16` were offered as clip rates, the
33818
+ * broker clamped them to `4`, and no line anywhere said so.
33819
+ *
33820
+ * Asked once per (camera, source) before anything is drawn — never replaced by
33821
+ * a constant the surface keeps, which is the second authority D612 ends.
33822
+ */
33823
+ var RecordingSourceOptionsSchema = object({
33824
+ /** How this source's media reaches the player.
33825
+ * `archive` = our own indexed segment tree; `stream` = the provider's
33826
+ * forward-only fMP4 (D597); `realtime` = a replay bound to wall clock. */
33827
+ transport: _enum([
33828
+ "archive",
33829
+ "stream",
33830
+ "realtime"
33831
+ ]),
33832
+ /** What the BAR means. `continuous` = gaps are holes in a recording;
33833
+ * `sparse` = gaps are the absence of one, and must be drawn as such.
33834
+ *
33835
+ * Not an onboard-only concession: measured 2026-09-24, OUR bar covers 98.8 %
33836
+ * of 592's day and 1.2 % of 1436's. It is a fact about a (source, camera)
33837
+ * pair, and ours answers it per camera from `deriveRecordingMode`. */
33838
+ coverage: _enum(["continuous", "sparse"]),
33839
+ /** Where the playhead may be put.
33840
+ * `free` — anywhere, to the frame.
33841
+ * `forward` — only ahead of the current position.
33842
+ * `segment` — a position SNAPS to the head of the covering segment; a finer
33843
+ * ask is accepted by the camera and SILENTLY IGNORED. Measured
33844
+ * on 1436 (Hikvision V5.7.1, 2026-09-23): a window-narrowed
33845
+ * `ContentMgmt/search` returns a row and a `playbackURI`, the
33846
+ * replay opens 200 and delivers media — and the burned-in OSD of
33847
+ * the first frame reads the SEGMENT HEAD every time. Calling
33848
+ * that `forward` would tell the surface it may move the playhead
33849
+ * ahead within a loaded segment, which it may not. */
33850
+ seek: _enum([
33851
+ "free",
33852
+ "forward",
33853
+ "segment"
33854
+ ]),
33855
+ /** Frame-step BACKWARD is meaningful. */
33856
+ stepBack: boolean(),
33857
+ /** Whether the drag-scrub gesture is served, as opposed to refused by name. */
33858
+ scrub: boolean(),
33859
+ /** Deliverable rates, ascending, always containing `1`. The surface draws its
33860
+ * picker from this and from NOTHING else (D612, D620, D621). `0` is not a
33861
+ * member: pause is the absence of a rate. */
33862
+ rates: array(number().positive()).min(1).readonly(),
33863
+ /** TRUE when a read of this source HOLDS the camera's only playback session.
33864
+ * A surface with this set makes at most ONE read at a time and draws no
33865
+ * scrub-thumbnail strip, no hover preview, no prefetch and no background
33866
+ * refresh. The precedent is exact and expensive: filling one screen of
33867
+ * Hikvision thumbnails at 1.01× realtime consumed fifteen minutes of that
33868
+ * camera's only playback session (1.2.126, reported within minutes), and a
33869
+ * timeline is a screenful of reads by construction. */
33870
+ exclusive: boolean()
33871
+ });
33872
+ /**
33873
+ * How to PLAY the instant that was asked for, from the chosen source.
33874
+ *
33875
+ * No new media transport is built for onboard sources: the `clip` arm is a
33876
+ * DELEGATION to the `videoclips` transport that vendor already has (D597 /
33877
+ * D616 / D617). The onboard half of this collection is a PROJECTION of
33878
+ * `videoclips` for coverage and a delegation to it for bytes.
33879
+ */
33880
+ var RecordingPlaybackSchema = discriminatedUnion("kind", [
33881
+ object({
33882
+ kind: literal("hls"),
33883
+ manifest: RecordingManifestSchema
33884
+ }),
33885
+ object({
33886
+ kind: literal("clip"),
33887
+ /** The `videoclips` source namespace this clip id belongs to. */
33888
+ source: string(),
33889
+ clipId: string(),
33890
+ /** Where this clip actually STARTS. On a `seek: 'segment'` source the
33891
+ * playhead lands here, not at the requested instant — the surface must be
33892
+ * TOLD, not left to discover it from a burned-in OSD. */
33893
+ startsAtMs: number()
33894
+ }),
33895
+ object({
33896
+ kind: literal("none"),
33897
+ reason: string()
33898
+ })
33899
+ ]);
33900
+ DeviceType.Camera, method(object({ deviceId: number() }), array(RecordingSourceSchema).readonly(), {
33901
+ kind: "query",
33902
+ auth: "protected"
33903
+ }), method(object({
33904
+ deviceId: number(),
33905
+ /**
33906
+ * WHICH provider to ask — the `addonId` a {@link RecordingSourceSchema}
33907
+ * row carries, never a source id and never a list. **REQUIRED**, in the
33908
+ * schema, where the generated types make it unomittable rather than
33909
+ * merely discouraged (D554 amended).
33910
+ *
33911
+ * It was learned the expensive way on `videoclips.listClips`: measured
33912
+ * on the live hub 2026-09-20, device 592 bound to `recorder` AND
33913
+ * `provider-reolink`, a bare call with `limit: 3` answered SIX rows,
33914
+ * three from each source, merged — `device-collection-dispatch.ts`
33915
+ * leaves an unpinned fan-out un-narrowed, so absence buys the union the
33916
+ * method exists not to be. An un-narrowed `getAvailability` would do
33917
+ * that to a TIMELINE: our ranges and the card's clips unioned into one
33918
+ * bar, which is "two sources are never drawn together" broken in the
33919
+ * one place it matters most.
33920
+ *
33921
+ * A provider the device is not bound to is refused BY NAME (D552's
33922
+ * `rejectUnresolvedAddonPin`), never answered by another one.
33923
+ */
33924
+ provider: string().min(1),
33925
+ fromMs: number(),
33926
+ toMs: number(),
33927
+ /**
33928
+ * Answer for THIS profile instead of the source's preferred one (D433).
33929
+ * Absent keeps the timeline's behaviour — one bar, one profile, one set
33930
+ * of reads. `profilesWithFootage` on the answer says what may be asked
33931
+ * for.
33932
+ */
33933
+ profile: string().optional()
33934
+ }), RecordingAvailabilitySchema, {
33935
+ kind: "query",
33936
+ auth: "protected"
33937
+ }), method(object({
33938
+ deviceId: number(),
33939
+ provider: string().min(1),
33940
+ fromMs: number(),
33941
+ toMs: number(),
33942
+ tzOffsetMinutes: number()
33943
+ }), RecordingDaysSchema, {
33944
+ kind: "query",
33945
+ auth: "protected"
33946
+ }), method(object({
33947
+ deviceId: number(),
33948
+ provider: string().min(1),
33949
+ fromMs: number(),
33950
+ toMs: number(),
33951
+ profile: CamProfileSchema.optional()
33952
+ }), RecordingPlaybackSchema, {
33953
+ kind: "query",
33954
+ auth: "protected"
33955
+ }), method(object({
33956
+ deviceId: number(),
33957
+ provider: string().min(1)
33958
+ }), RecordingSourceOptionsSchema, {
33959
+ kind: "query",
33960
+ auth: "protected"
33961
+ });
33962
+ /**
33963
+ * `recording-archive` — OUR archive, and the intent that fills it.
33964
+ *
33965
+ * The system-singleton half of the 2026-09-24 cut (D625). `recording` used to
33966
+ * be one 33-method system singleton holding two unrelated subjects: three
33967
+ * per-camera READS about coverage and playback, and everything else — storage
33968
+ * locations, retention, relocation, rebalance, the ops log, the placement
33969
+ * table and the byte-plane primitives our scrub and export are built on.
33970
+ *
33971
+ * The reads became a device-scoped COLLECTION, so a camera's own card can be a
33972
+ * source beside ours (`recording.cap.ts`). Everything that is about OUR store,
33973
+ * or unimplementable by a camera, stayed here.
33974
+ *
33975
+ * ## On the name
33976
+ *
33977
+ * `recording-storage` was the obvious choice and is wrong: this cap also holds
33978
+ * `getDeviceConfig`/`setDeviceConfig`, which are recording INTENT — bands,
33979
+ * retention, the D62 switch authority — and a name that says "storage" invites
33980
+ * the next reader to move them out again. An archive is a thing we keep, and
33981
+ * what we keep it under is a policy; the name covers both halves honestly and
33982
+ * sits in the existing family (`recording-onboard`, `recording-export`,
33983
+ * `recording-signal`).
33984
+ *
33985
+ * ## What must NOT happen to it
33986
+ *
33987
+ * It stays a SINGLETON. It is registered by `recorder`, which is
33988
+ * `placement: 'any-node'` and runs on every recording node; the hub dispatches
33989
+ * to one of them. Putting the ledger, the placement table or the relocation
33990
+ * jobs behind a fan-out is the one genuinely dangerous move in this cut.
33991
+ *
33992
+ * `getDeviceConfig` / `setDeviceConfig` in particular are the D62 recording
33993
+ * authority (`CameraSwitch.authority`). If a write reached a different provider
33994
+ * than the read — which a collection fan-out permits — two authorities would
33995
+ * decide when one camera records, and the symptom (recording silently off, or
33996
+ * a `bands` array clobbered by a partial write) is durable and silent. Keeping
33997
+ * them here means the worst case during a rollout is a 412: the switch refuses
33998
+ * to flip and SAYS so. **Do not move them into the collection, at any point,
33999
+ * for any reason.**
34000
+ *
34001
+ * ## The two batch reads
34002
+ *
34003
+ * `getAvailabilityBatch` / `getDaysWithRecordingsBatch` take `deviceIds:
34004
+ * number[]` with no single `deviceId`, and a device-scoped mount routes
34005
+ * through `getProviderForDevice(deviceId)` — there is nothing for it to route
34006
+ * on. They stay here, and on this cap the batch is explicitly OURS: a grid has
34007
+ * no per-camera picker, and a caller that wants another source's coverage asks
34008
+ * `recording.getAvailability` per device with that source's `provider`.
34009
+ */
34010
+ var RecordingStatusSchema = object({
34011
+ deviceId: number(),
34012
+ enabled: boolean(),
34013
+ /** THE derived storage mode, from the one definition
34014
+ * (`deriveRecordingMode`) — never a second enum. A duplicated list is how
34015
+ * `on-device-decision` could have reached the recorder and not the status. */
34016
+ activeMode: RecordingStorageModeSchema,
34017
+ nodeId: string(),
34018
+ storageBytes: number()
34019
+ });
34232
34020
  /**
34233
34021
  * One camera's row in a `getAvailabilityBatch` answer.
34234
34022
  *
34235
- * `ranges` is EXACTLY what `getAvailability` returns for that camera — the
34236
- * batch collapses the transport, not the work — plus the one thing the singular
34237
- * method never had to say:
34023
+ * `ranges` is EXACTLY what `recording.getAvailability` returns for that camera
34024
+ * at OUR source — the batch collapses the transport, not the work — plus the
34025
+ * `read` mark the singular answer now carries too (D625):
34238
34026
  *
34239
34027
  * - `read: 'read'` — answered. `ranges: []` means "read, and this camera has
34240
34028
  * no footage in the window", which is a real claim.
@@ -34266,22 +34054,6 @@ var RecordingDaysForDeviceSchema = object({
34266
34054
  /** Local-midnight epochs (UTC ms) of days that have ≥1 recorded segment. */
34267
34055
  days: array(number()).readonly()
34268
34056
  });
34269
- var RecordingManifestSchema = object({
34270
- deviceId: number(),
34271
- /** Local filesystem path to the master playlist; null when no recording exists for the requested range. */
34272
- localMasterPath: string().nullable(),
34273
- /** HTTP(S) URL to the master playlist on the recording node's playback server
34274
- * (the PRIMARY candidate); null when no recording / server. Carries the
34275
- * scoped playback token in its path. */
34276
- playbackUrl: string().nullable(),
34277
- /**
34278
- * Candidate master-playlist URLs the client tries in order (LAN first, then
34279
- * remote — Tailscale/Cloudflare if the operator configured extra hosts), each
34280
- * carrying the same scoped token. `playbackUrl` is the first entry. Empty when
34281
- * there is no recording / server.
34282
- */
34283
- playbackEndpoints: array(string())
34284
- });
34285
34057
  /**
34286
34058
  * Recording storage usage for one camera — what the ARCHIVE holds for it,
34287
34059
  * across every profile and every resolvable location on this node.
@@ -34540,34 +34312,12 @@ var ReadWindowBytesResultSchema = discriminatedUnion("kind", [object({
34540
34312
  segmentEndMs: number()
34541
34313
  })]);
34542
34314
  method(object({
34543
- deviceId: number(),
34544
- fromMs: number(),
34545
- toMs: number(),
34546
- /**
34547
- * Answer for THIS profile instead of the preferred one (D433). Absent
34548
- * keeps the timeline's behaviour — one bar, one profile, one set of
34549
- * reads. `profilesWithFootage` on the answer says what may be asked
34550
- * for.
34551
- */
34552
- profile: string().optional()
34553
- }), RecordingAvailabilitySchema, {
34554
- kind: "query",
34555
- auth: "protected"
34556
- }), method(object({
34557
34315
  deviceIds: array(number()).min(1).max(200),
34558
34316
  fromMs: number(),
34559
34317
  toMs: number()
34560
34318
  }), array(RecordingAvailabilityForDeviceSchema).readonly(), {
34561
34319
  kind: "query",
34562
34320
  auth: "protected"
34563
- }), method(object({
34564
- deviceId: number(),
34565
- fromMs: number(),
34566
- toMs: number(),
34567
- tzOffsetMinutes: number()
34568
- }), RecordingDaysSchema, {
34569
- kind: "query",
34570
- auth: "protected"
34571
34321
  }), method(object({
34572
34322
  deviceIds: array(number()).min(1).max(200),
34573
34323
  fromMs: number(),
@@ -34576,13 +34326,6 @@ method(object({
34576
34326
  }), array(RecordingDaysForDeviceSchema).readonly(), {
34577
34327
  kind: "query",
34578
34328
  auth: "protected"
34579
- }), method(object({
34580
- deviceId: number(),
34581
- fromMs: number(),
34582
- toMs: number()
34583
- }), RecordingManifestSchema, {
34584
- kind: "query",
34585
- auth: "protected"
34586
34329
  }), method(object({}), RecordingStorageUsageSchema, {
34587
34330
  kind: "query",
34588
34331
  auth: "admin"
@@ -35034,6 +34777,511 @@ method(object({
35034
34777
  auth: "protected"
35035
34778
  });
35036
34779
  /**
34780
+ * Vendor-neutral **onboard** recording + storage cap — what the CAMERA
34781
+ * writes to the CAMERA's own card, on the camera's own schedule.
34782
+ *
34783
+ * This is NOT `recording.cap.ts`. That one is CamStack's recorder: our
34784
+ * footage ledger, our storage locations, our retention. This one has a
34785
+ * different authority — the camera's firmware — and per D62 it stores
34786
+ * nothing of its own. Every value here is read from the camera and every
34787
+ * write goes back to the camera; there is no CamStack-side mirror that
34788
+ * could disagree with the device.
34789
+ *
34790
+ * ## One shape, two firmwares
34791
+ *
34792
+ * Measured 2026-09-22 against the live fleet:
34793
+ *
34794
+ * | fact | Hikvision (ISAPI) | Reolink (Baichuan) |
34795
+ * | --- | --- | --- |
34796
+ * | storage | `ContentMgmt/Storage` `<hdd>` rows: status, capacity, freeSpace (MB) | `getHddInfoList` (cmd 102): `mount`, `format`, `capacity` GB + `capacityM` MB remainder |
34797
+ * | tracks | several (101 **and** 103 on both 1436 and 3833), each with its own schedule | one per channel |
34798
+ * | schedule | per track, 7 `ScheduleAction` blocks: DayOfWeek + TimeOfDay range + ONE `ActionRecordingMode` | per trigger type, a 168-char weekly HOUR mask |
34799
+ * | triggers | `CMR`, `MOTION` | `Normal`, `MD`, `people`, `vehicle`, `dog_cat`, `crossline`, `intrude`, `loitering` |
34800
+ * | pre-record | `PreRecordTimeSeconds` | `preRecordTime` |
34801
+ * | post-record | `PostRecordTimeSeconds` | `recordDelayTime` |
34802
+ * | overwrite | per track `LoopEnable` | `cycle`, with `cycleList` enumerating the accepted values |
34803
+ * | segment length | not exposed on V5.7.1 | `packageTime` (minutes) |
34804
+ *
34805
+ * The two schedule models look different and are the same thing in
34806
+ * different coordinates: both answer "for this trigger, during which
34807
+ * weekly windows does the camera record". {@link RecordWindow} is that
34808
+ * question in one shape — Hikvision's ranges map straight onto it,
34809
+ * Reolink's mask expands into hour-aligned windows.
34810
+ *
34811
+ * ## Union, not intersection
34812
+ *
34813
+ * **The same fields exist on every camera.** What differs per device is
34814
+ * which VALUES that device accepts, and that is what {@link
34815
+ * RecordingOnboardOptions} reports — a `{ readable, writable, reason }`
34816
+ * per field plus the schedule's own limits. A control a camera cannot
34817
+ * honour is rendered DISABLED WITH ITS REASON, never missing and never
34818
+ * dead: disabled must not look like broken.
34819
+ *
34820
+ * ## Refusal by name
34821
+ *
34822
+ * A write a camera cannot honour is refused with a sentence the operator
34823
+ * can read — never accepted and dropped. Both providers refuse through
34824
+ * {@link describeOnboardRefusal}, so the vocabulary is one function and
34825
+ * one test, not two hand-written vendor opinions.
34826
+ *
34827
+ * Follows the D14 `deviceConfig` archetype (see `stream-params.cap.ts`):
34828
+ * `getOptions` advertises per-camera availability, `getStatus` (auto-
34829
+ * injected from `status`) reports the live values, and a single
34830
+ * `setSettings` mutation applies a partial change. No hand-written
34831
+ * settings-contribution methods.
34832
+ */
34833
+ /**
34834
+ * What makes the camera start recording during a window.
34835
+ *
34836
+ * The union of both vendors' vocabularies. `continuous` is Hikvision's
34837
+ * `CMR` and Reolink's `Normal`; `motion` is `MOTION` / `MD`. The
34838
+ * object-class triggers are Reolink-only today and the smart-event ones
34839
+ * (`lineCrossing`, `intrusion`, `loitering`) are Reolink-only on the
34840
+ * firmwares measured — a camera that cannot record on a trigger simply
34841
+ * does not list it in `options.schedule.triggers`, and a window naming
34842
+ * it is REFUSED, not dropped.
34843
+ */
34844
+ var RecordTriggerSchema = _enum([
34845
+ "continuous",
34846
+ "motion",
34847
+ "person",
34848
+ "vehicle",
34849
+ "animal",
34850
+ "lineCrossing",
34851
+ "intrusion",
34852
+ "loitering",
34853
+ "alarmInput"
34854
+ ]);
34855
+ /**
34856
+ * One weekly recording window: "on `day`, from `startMinute` to
34857
+ * `endMinute`, record on `trigger`".
34858
+ *
34859
+ * `day` is 0 = Monday … 6 = Sunday (ISO order, which is also the order
34860
+ * both firmwares enumerate). Minutes are local camera time since
34861
+ * midnight; `endMinute` may be 1440, meaning end of day — that is
34862
+ * Hikvision's literal `24:00` and Reolink's 24th mask slot, and
34863
+ * collapsing it to 0 would turn a whole-day window into an empty one.
34864
+ */
34865
+ var RecordWindowSchema = object({
34866
+ trigger: RecordTriggerSchema,
34867
+ day: number().int().min(0).max(6),
34868
+ startMinute: number().int().min(0).max(1439),
34869
+ endMinute: number().int().min(1).max(1440)
34870
+ });
34871
+ /** Status of one physical volume, as the camera itself describes it. */
34872
+ var OnboardStorageVolumeSchema = object({
34873
+ /** The camera's own id for the volume (`hdd/id`, Reolink `HddInfo/number`). */
34874
+ id: string(),
34875
+ /** The camera's own name for it, when it gives one (`hddName`). */
34876
+ label: string().optional(),
34877
+ status: _enum([
34878
+ "ok",
34879
+ "unformatted",
34880
+ "error",
34881
+ "offline",
34882
+ "unknown"
34883
+ ]),
34884
+ /**
34885
+ * Total size in MB, or **null when the camera did not say**.
34886
+ *
34887
+ * Never 0 for an unreadable value: a measurement that failed is not a
34888
+ * measurement (D393), and a card whose size is unknown must not be
34889
+ * rendered as a card of size zero.
34890
+ */
34891
+ capacityMb: number().nullable(),
34892
+ /**
34893
+ * Free space in MB, or null when unknown.
34894
+ *
34895
+ * **Not a proxy for "has footage".** Measured 2026-09-22: 1436 and
34896
+ * 1439 both report exactly 11776 MB free — the fixed reserve a looping
34897
+ * card converges on once it has wrapped. At loop steady state the
34898
+ * number is identical whether the camera recorded yesterday or stopped
34899
+ * a month ago.
34900
+ */
34901
+ freeMb: number().nullable(),
34902
+ /** True when the camera reports the volume writable (`property` RW). */
34903
+ writable: boolean().optional()
34904
+ });
34905
+ /**
34906
+ * What the camera is doing with its own storage, right now.
34907
+ *
34908
+ * Every scalar is nullable and **null means the camera did not answer**,
34909
+ * never a default. A form that seeds `0` from an unanswered read invites
34910
+ * the operator to save that 0 back onto the camera.
34911
+ */
34912
+ var RecordingOnboardStatusSchema = object({
34913
+ storage: discriminatedUnion("kind", [
34914
+ object({
34915
+ kind: literal("present"),
34916
+ volumes: array(OnboardStorageVolumeSchema)
34917
+ }),
34918
+ object({
34919
+ kind: literal("absent"),
34920
+ reason: string()
34921
+ }),
34922
+ object({
34923
+ kind: literal("unknown"),
34924
+ reason: string()
34925
+ })
34926
+ ]),
34927
+ tracks: array(object({
34928
+ id: string(),
34929
+ enabled: boolean(),
34930
+ isVideo: boolean(),
34931
+ /** From the camera's own track description. Null when it does not say. */
34932
+ codec: string().nullable(),
34933
+ resolution: string().nullable(),
34934
+ /** Per-track overwrite flag, where the firmware keeps it per track. */
34935
+ overwriteWhenFull: boolean().nullable()
34936
+ })),
34937
+ /**
34938
+ * The track the write path targets — the enabled VIDEO one. Null when
34939
+ * no track could be identified, which is itself a refusal reason.
34940
+ */
34941
+ primaryTrackId: string().nullable(),
34942
+ /** Master "record to the card at all" switch. */
34943
+ enabled: boolean().nullable(),
34944
+ overwriteWhenFull: boolean().nullable(),
34945
+ preRecordSec: number().nullable(),
34946
+ postRecordSec: number().nullable(),
34947
+ /** Length of one recorded file, in minutes. */
34948
+ segmentMinutes: number().nullable(),
34949
+ /** The primary track's weekly windows, flattened. */
34950
+ windows: array(RecordWindowSchema),
34951
+ /**
34952
+ * How many windows the camera described that CamStack could NOT read —
34953
+ * an unrecognised trigger, an unparseable clock, a weekday it does not
34954
+ * name.
34955
+ *
34956
+ * A dropped window is work the reader threw away, and a schedule that
34957
+ * silently shows fewer rows than the camera holds is how an operator
34958
+ * saves back a schedule shorter than the one they were looking at
34959
+ * (D391). Non-zero means the window list is INCOMPLETE and a write
34960
+ * that replaces it would delete what was not shown — which is why a
34961
+ * provider reporting a non-zero count also reports the schedule as not
34962
+ * writable.
34963
+ */
34964
+ unreadableWindows: number(),
34965
+ /**
34966
+ * The camera is scheduled to record and has NO usable storage.
34967
+ *
34968
+ * A first-class fact because it is the fleet's most common silent
34969
+ * defect: measured 2026-09-22, 1441 and 3831 are both motion-recording
34970
+ * to a card that is not there. Neither the schedule nor the storage
34971
+ * read says anything wrong on its own; only the pair does.
34972
+ */
34973
+ recordingToNowhere: boolean(),
34974
+ lastFetchedAt: number()
34975
+ });
34976
+ /** Numeric range descriptor — `{ min, max, step }` per the getOptions convention. */
34977
+ var RangeSchema = object({
34978
+ min: number(),
34979
+ max: number(),
34980
+ step: number()
34981
+ });
34982
+ /**
34983
+ * The values a camera actually takes for a numeric field, when they are a SET
34984
+ * rather than a range.
34985
+ *
34986
+ * `{min,max,step}` cannot say what these two firmwares do. Measured on 1436
34987
+ * (I91DN) on 2026-09-22 by writing each value and reading it back:
34988
+ *
34989
+ * - pre-record: `0, 5, 10, 15, 20, 25, 30` and `2147483647` (INT32_MAX, the
34990
+ * camera's "no limit" — `-1` and `4294967295` both land on it);
34991
+ * - post-record: `5, 10, 30, 60, 120, 300, 600`.
34992
+ *
34993
+ * Neither is expressible as a step: the first has a sentinel two billion away
34994
+ * from its neighbours, the second doubles and then jumps. A range that tried
34995
+ * would forbid values the camera takes AND permit values it silently replaces
34996
+ * with 5 — wrong in both directions at once.
34997
+ *
34998
+ * `sentinel` names the member that is not a duration, so a surface can render
34999
+ * "no limit" instead of `2147483647` seconds.
35000
+ */
35001
+ var AllowedValuesSchema = object({
35002
+ values: array(number()).min(1),
35003
+ sentinel: object({
35004
+ value: number(),
35005
+ meaning: _enum(["no-limit", "disabled"])
35006
+ }).optional()
35007
+ });
35008
+ /**
35009
+ * Per-field availability on ONE camera.
35010
+ *
35011
+ * The field exists on every camera — this says whether this one can be
35012
+ * read and whether it can be written, and `reason` says why not when
35013
+ * either is false. The UI renders the control DISABLED with the reason
35014
+ * rather than hiding it, so a limitation is legible instead of looking
35015
+ * like a missing feature.
35016
+ */
35017
+ var OnboardFieldSupportSchema = object({
35018
+ readable: boolean(),
35019
+ writable: boolean(),
35020
+ /** Required whenever `readable` or `writable` is false. */
35021
+ reason: string().optional()
35022
+ });
35023
+ /** What this camera's schedule model can express. */
35024
+ var OnboardScheduleSupportSchema = object({
35025
+ support: OnboardFieldSupportSchema,
35026
+ /**
35027
+ * The smallest time step the camera can express, in minutes.
35028
+ *
35029
+ * Hikvision takes arbitrary minutes (`00:05:00`–`23:57:00` observed on
35030
+ * 1436's track 103). Reolink's schedule is a 7×24 HOUR mask, so 60. A
35031
+ * window whose edges are not a multiple of this is REFUSED rather than
35032
+ * quietly rounded — rounding is how an operator's 06:30 becomes 06:00
35033
+ * and nothing says so.
35034
+ */
35035
+ granularityMinutes: number(),
35036
+ /** Triggers this camera can record on. A window naming another is refused. */
35037
+ triggers: array(RecordTriggerSchema),
35038
+ /**
35039
+ * False when the camera stores ONE trigger per time range, so two
35040
+ * windows overlapping on the same day cannot carry different triggers.
35041
+ * True on Reolink, whose mask is per-trigger and independent.
35042
+ */
35043
+ supportsOverlappingTriggers: boolean()
35044
+ });
35045
+ var RecordingOnboardOptionsSchema = object({
35046
+ enabled: OnboardFieldSupportSchema,
35047
+ overwriteWhenFull: OnboardFieldSupportSchema,
35048
+ preRecordSec: OnboardFieldSupportSchema,
35049
+ preRecordSecRange: RangeSchema.optional(),
35050
+ /** Preferred over the range when the camera takes a SET, not a span. */
35051
+ preRecordSecAllowed: AllowedValuesSchema.optional(),
35052
+ postRecordSec: OnboardFieldSupportSchema,
35053
+ postRecordSecRange: RangeSchema.optional(),
35054
+ /** Preferred over the range when the camera takes a SET, not a span. */
35055
+ postRecordSecAllowed: AllowedValuesSchema.optional(),
35056
+ segmentMinutes: OnboardFieldSupportSchema,
35057
+ segmentMinutesRange: RangeSchema.optional(),
35058
+ /** Preferred over the range when the camera takes a SET, not a span. */
35059
+ segmentMinutesAllowed: AllowedValuesSchema.optional(),
35060
+ schedule: OnboardScheduleSupportSchema
35061
+ });
35062
+ /**
35063
+ * A partial change. Every field optional.
35064
+ *
35065
+ * Unlike the other `deviceConfig` caps, a provider here does **NOT**
35066
+ * silently ignore a field it cannot support — it refuses, by name,
35067
+ * through {@link describeOnboardRefusal}. Silence on a recording setting
35068
+ * is the failure D62 exists to prevent: the operator believes the camera
35069
+ * is recording the way the form says, and it is not.
35070
+ */
35071
+ var RecordingOnboardPatchSchema = object({
35072
+ enabled: boolean().optional(),
35073
+ overwriteWhenFull: boolean().optional(),
35074
+ preRecordSec: number().optional(),
35075
+ postRecordSec: number().optional(),
35076
+ segmentMinutes: number().optional(),
35077
+ /** The complete new window set for the primary track — not a delta. */
35078
+ windows: array(RecordWindowSchema).optional()
35079
+ });
35080
+ var recordingOnboardCapability = {
35081
+ name: "recording-onboard",
35082
+ scope: "device",
35083
+ deviceNative: true,
35084
+ mode: "singleton",
35085
+ deviceTypes: [DeviceType.Camera],
35086
+ deviceConfig: { ui: {
35087
+ kind: "derived-form",
35088
+ builderId: "recording-onboard",
35089
+ tab: "recording"
35090
+ } },
35091
+ methods: {
35092
+ getOptions: method(object({ deviceId: number() }), RecordingOnboardOptionsSchema),
35093
+ setSettings: method(object({
35094
+ deviceId: number(),
35095
+ settings: RecordingOnboardPatchSchema
35096
+ }), _void(), {
35097
+ kind: "mutation",
35098
+ auth: "admin"
35099
+ })
35100
+ },
35101
+ status: {
35102
+ schema: RecordingOnboardStatusSchema,
35103
+ kind: "poll"
35104
+ },
35105
+ runtimeState: RecordingOnboardStatusSchema,
35106
+ /**
35107
+ * Runtime-state durability: **restored** — operator-set camera-side
35108
+ * recording config; mutation-driven, and the storage half is the last
35109
+ * thing the camera said about its own card.
35110
+ *
35111
+ * See `RuntimeStateDurability`. Enforced by
35112
+ * `scripts/check-runtime-state-durability.ts`.
35113
+ */
35114
+ durability: "restored",
35115
+ /** Clock fields: written, but excluded from the compare that decides
35116
+ * whether persisting is worth a SQLite commit. */
35117
+ volatileStateFields: ["lastFetchedAt"]
35118
+ };
35119
+ /**
35120
+ * Day-of-week names in the cap's index order (0 = Monday), for messages
35121
+ * an operator reads and for Hikvision's `<DayOfWeek>` element.
35122
+ */
35123
+ var DAY_NAMES = [
35124
+ "Monday",
35125
+ "Tuesday",
35126
+ "Wednesday",
35127
+ "Thursday",
35128
+ "Friday",
35129
+ "Saturday",
35130
+ "Sunday"
35131
+ ];
35132
+ /**
35133
+ * Does `patch` ask this camera for something it cannot do?
35134
+ *
35135
+ * Returns the operator-readable reason, or `null` when every field in
35136
+ * the patch is within what `options` says this camera accepts. A
35137
+ * provider calls this BEFORE touching the camera and throws the string:
35138
+ * refusing is the point, and refusing identically on both vendors is why
35139
+ * this is one function.
35140
+ *
35141
+ * The order of checks is the order an operator would read them: the
35142
+ * scalar knobs first, then the schedule, because a schedule complaint is
35143
+ * longer and a scalar one is usually the real problem.
35144
+ */
35145
+ function describeOnboardRefusal(options, patch) {
35146
+ if (patch.enabled !== void 0 && !options.enabled.writable) return unwritable("the master recording switch", options.enabled.reason);
35147
+ if (patch.overwriteWhenFull !== void 0 && !options.overwriteWhenFull.writable) return unwritable("overwrite-when-full", options.overwriteWhenFull.reason);
35148
+ const preRefusal = refuseNumeric("pre-record seconds", patch.preRecordSec, options.preRecordSec, options.preRecordSecRange, options.preRecordSecAllowed);
35149
+ if (preRefusal) return preRefusal;
35150
+ const postRefusal = refuseNumeric("post-record seconds", patch.postRecordSec, options.postRecordSec, options.postRecordSecRange, options.postRecordSecAllowed);
35151
+ if (postRefusal) return postRefusal;
35152
+ const segmentRefusal = refuseNumeric("segment length (minutes)", patch.segmentMinutes, options.segmentMinutes, options.segmentMinutesRange, options.segmentMinutesAllowed);
35153
+ if (segmentRefusal) return segmentRefusal;
35154
+ if (patch.windows !== void 0) {
35155
+ const scheduleRefusal = refuseSchedule(options, patch.windows);
35156
+ if (scheduleRefusal) return scheduleRefusal;
35157
+ }
35158
+ return null;
35159
+ }
35160
+ function unwritable(what, reason) {
35161
+ return reason ? `this camera cannot change ${what}: ${reason}` : `this camera cannot change ${what}`;
35162
+ }
35163
+ function refuseNumeric(what, value, support, range, allowed) {
35164
+ if (value === void 0) return null;
35165
+ if (!support.writable) return unwritable(what, support.reason);
35166
+ if (!Number.isFinite(value)) return `${what} must be a number, got ${String(value)}`;
35167
+ if (allowed) {
35168
+ if (allowed.values.includes(value)) return null;
35169
+ const say = (v) => allowed.sentinel !== void 0 && v === allowed.sentinel.value ? allowed.sentinel.meaning === "no-limit" ? "no limit" : "off" : String(v);
35170
+ return `this camera accepts ${what} only as ${allowed.values.map(say).join(", ")}; ${say(value)} is not one of them`;
35171
+ }
35172
+ if (!range) return null;
35173
+ if (value < range.min || value > range.max) return `this camera accepts ${what} between ${String(range.min)} and ${String(range.max)}; ${String(value)} is outside that`;
35174
+ if (range.step > 0 && (value - range.min) % range.step !== 0) return `this camera accepts ${what} in steps of ${String(range.step)} from ${String(range.min)}; ${String(value)} is not one of them`;
35175
+ return null;
35176
+ }
35177
+ function refuseSchedule(options, windows) {
35178
+ const schedule = options.schedule;
35179
+ if (!schedule.support.writable) return unwritable("the recording schedule", schedule.support.reason);
35180
+ const allowed = new Set(schedule.triggers);
35181
+ for (const window of windows) {
35182
+ if (!allowed.has(window.trigger)) {
35183
+ const offer = schedule.triggers.length > 0 ? schedule.triggers.join(", ") : "none";
35184
+ return `this camera cannot record on "${window.trigger}"; it records on: ${offer}`;
35185
+ }
35186
+ if (window.endMinute <= window.startMinute) return `a window on ${dayName(window.day)} ends at or before it starts (${String(window.startMinute)} → ${String(window.endMinute)})`;
35187
+ const step = schedule.granularityMinutes;
35188
+ if (step > 1 && (window.startMinute % step !== 0 || window.endMinute % step !== 0)) return `this camera's schedule only moves in ${String(step)}-minute steps; the ${dayName(window.day)} window ${formatMinutes(window.startMinute)}–${formatMinutes(window.endMinute)} is not aligned to them`;
35189
+ }
35190
+ if (!schedule.supportsOverlappingTriggers) {
35191
+ const clash = findOverlapWithDifferentTrigger(windows);
35192
+ if (clash) return `this camera stores one trigger per time range, so "${clash.a.trigger}" and "${clash.b.trigger}" cannot both cover ${dayName(clash.a.day)} ${formatMinutes(Math.max(clash.a.startMinute, clash.b.startMinute))}–${formatMinutes(Math.min(clash.a.endMinute, clash.b.endMinute))}`;
35193
+ }
35194
+ return null;
35195
+ }
35196
+ function findOverlapWithDifferentTrigger(windows) {
35197
+ for (let i = 0; i < windows.length; i += 1) for (let j = i + 1; j < windows.length; j += 1) {
35198
+ const a = windows[i];
35199
+ const b = windows[j];
35200
+ if (!a || !b) continue;
35201
+ if (a.day !== b.day) continue;
35202
+ if (a.trigger === b.trigger) continue;
35203
+ if (a.startMinute < b.endMinute && b.startMinute < a.endMinute) return {
35204
+ a,
35205
+ b
35206
+ };
35207
+ }
35208
+ return null;
35209
+ }
35210
+ function dayName(day) {
35211
+ return DAY_NAMES[day] ?? `day ${String(day)}`;
35212
+ }
35213
+ /** `510` → `08:30`. For messages, not for the wire. */
35214
+ function formatMinutes(minute) {
35215
+ const hour = Math.floor(minute / 60);
35216
+ const rest = minute % 60;
35217
+ return `${String(hour).padStart(2, "0")}:${String(rest).padStart(2, "0")}`;
35218
+ }
35219
+ /**
35220
+ * Index of the mask character covering `day` at `hour`.
35221
+ *
35222
+ * **Layout: day-major, Monday first** — `day * 24 + hour`.
35223
+ *
35224
+ * This is an ASSUMPTION, and it is recorded as one because the fleet
35225
+ * cannot currently confirm it: every `valueTable` on every Reolink
35226
+ * measured on 2026-09-22 is uniform (all `1` or all `0`), and a uniform
35227
+ * mask reads identically under either layout. To settle it, set a single
35228
+ * hour on one day from the Reolink app and re-read `getRecordSchedule`.
35229
+ * Until then, a NON-uniform mask is reported as windows under this
35230
+ * layout and the day labels may be transposed; a uniform one is exact.
35231
+ */
35232
+ function weeklyMaskIndex(day, hour) {
35233
+ return day * 24 + hour;
35234
+ }
35235
+ /**
35236
+ * Expand one trigger's weekly hour mask into windows, merging adjacent
35237
+ * set hours into one window per run so a full day is ONE window rather
35238
+ * than twenty-four.
35239
+ *
35240
+ * A mask of the wrong length yields no windows: a truncated table is not
35241
+ * a schedule of fewer days, it is an answer we did not understand.
35242
+ */
35243
+ function weeklyMaskToWindows(mask, trigger) {
35244
+ if (mask.length !== 168) return [];
35245
+ const out = [];
35246
+ for (let day = 0; day < 7; day += 1) {
35247
+ let runStart = null;
35248
+ for (let hour = 0; hour <= 24; hour += 1) {
35249
+ const set = hour < 24 && mask[weeklyMaskIndex(day, hour)] === "1";
35250
+ if (set && runStart === null) runStart = hour;
35251
+ else if (!set && runStart !== null) {
35252
+ out.push({
35253
+ trigger,
35254
+ day,
35255
+ startMinute: runStart * 60,
35256
+ endMinute: hour * 60
35257
+ });
35258
+ runStart = null;
35259
+ }
35260
+ }
35261
+ }
35262
+ return out;
35263
+ }
35264
+ /**
35265
+ * Collapse this trigger's windows back into a weekly hour mask.
35266
+ *
35267
+ * Windows for other triggers are ignored — the mask is per trigger. A
35268
+ * window that is not hour-aligned is REFUSED upstream by
35269
+ * {@link describeOnboardRefusal}; this function rounds nothing, it
35270
+ * simply sets every hour the window fully or partly covers, so a caller
35271
+ * that skipped the refusal cannot silently lose coverage.
35272
+ */
35273
+ function windowsToWeeklyMask(windows, trigger) {
35274
+ const slots = new Array(168).fill("0");
35275
+ for (const window of windows) {
35276
+ if (window.trigger !== trigger) continue;
35277
+ if (window.day < 0 || window.day >= 7) continue;
35278
+ const firstHour = Math.floor(window.startMinute / 60);
35279
+ const lastHour = Math.ceil(window.endMinute / 60);
35280
+ for (let hour = firstHour; hour < lastHour && hour < 24; hour += 1) slots[weeklyMaskIndex(window.day, hour)] = "1";
35281
+ }
35282
+ return slots.join("");
35283
+ }
35284
+ /**
35037
35285
  * A camera's own "record me NOW" LEVEL — a signal the device raises while
35038
35286
  * something it knows about is happening (a robot vacuum cleaning, a machine
35039
35287
  * running, a gate open) and lowers when it stops.
@@ -42870,24 +43118,6 @@ Object.freeze({
42870
43118
  addonId: null,
42871
43119
  access: "view"
42872
43120
  },
42873
- "events.getEventClipUrl": {
42874
- capName: "events",
42875
- capScope: "device",
42876
- addonId: null,
42877
- access: "view"
42878
- },
42879
- "events.getEvents": {
42880
- capName: "events",
42881
- capScope: "device",
42882
- addonId: null,
42883
- access: "view"
42884
- },
42885
- "events.getEventThumbnail": {
42886
- capName: "events",
42887
- capScope: "device",
42888
- addonId: null,
42889
- access: "view"
42890
- },
42891
43121
  "faceGallery.assignFace": {
42892
43122
  capName: "face-gallery",
42893
43123
  capScope: "system",
@@ -45762,224 +45992,236 @@ Object.freeze({
45762
45992
  addonId: null,
45763
45993
  access: "create"
45764
45994
  },
45765
- "recording.applyDeviceSettingsPatch": {
45995
+ "recording.getAvailability": {
45766
45996
  capName: "recording",
45767
- capScope: "system",
45997
+ capScope: "device",
45768
45998
  addonId: null,
45769
- access: "create"
45999
+ access: "view"
45770
46000
  },
45771
- "recording.cancelRelocateJob": {
46001
+ "recording.getDaysWithRecordings": {
45772
46002
  capName: "recording",
45773
- capScope: "system",
46003
+ capScope: "device",
45774
46004
  addonId: null,
45775
- access: "create"
46005
+ access: "view"
45776
46006
  },
45777
- "recording.cancelStorageMigrationMove": {
46007
+ "recording.getPlayback": {
45778
46008
  capName: "recording",
45779
- capScope: "system",
46009
+ capScope: "device",
45780
46010
  addonId: null,
45781
- access: "create"
46011
+ access: "view"
45782
46012
  },
45783
- "recording.deleteFootprint": {
46013
+ "recording.getPlaybackOptions": {
45784
46014
  capName: "recording",
45785
- capScope: "system",
46015
+ capScope: "device",
45786
46016
  addonId: null,
45787
- access: "delete"
46017
+ access: "view"
45788
46018
  },
45789
- "recording.getAvailability": {
46019
+ "recording.listSources": {
45790
46020
  capName: "recording",
45791
- capScope: "system",
46021
+ capScope: "device",
45792
46022
  addonId: null,
45793
46023
  access: "view"
45794
46024
  },
45795
- "recording.getAvailabilityBatch": {
45796
- capName: "recording",
46025
+ "recordingArchive.applyDeviceSettingsPatch": {
46026
+ capName: "recording-archive",
45797
46027
  capScope: "system",
45798
46028
  addonId: null,
45799
- access: "view"
46029
+ access: "create"
45800
46030
  },
45801
- "recording.getDaysWithRecordings": {
45802
- capName: "recording",
46031
+ "recordingArchive.cancelRelocateJob": {
46032
+ capName: "recording-archive",
45803
46033
  capScope: "system",
45804
46034
  addonId: null,
45805
- access: "view"
46035
+ access: "create"
45806
46036
  },
45807
- "recording.getDaysWithRecordingsBatch": {
45808
- capName: "recording",
46037
+ "recordingArchive.cancelStorageMigrationMove": {
46038
+ capName: "recording-archive",
46039
+ capScope: "system",
46040
+ addonId: null,
46041
+ access: "create"
46042
+ },
46043
+ "recordingArchive.deleteFootprint": {
46044
+ capName: "recording-archive",
46045
+ capScope: "system",
46046
+ addonId: null,
46047
+ access: "delete"
46048
+ },
46049
+ "recordingArchive.getAvailabilityBatch": {
46050
+ capName: "recording-archive",
45809
46051
  capScope: "system",
45810
46052
  addonId: null,
45811
46053
  access: "view"
45812
46054
  },
45813
- "recording.getDeviceConfig": {
45814
- capName: "recording",
46055
+ "recordingArchive.getDaysWithRecordingsBatch": {
46056
+ capName: "recording-archive",
45815
46057
  capScope: "system",
45816
46058
  addonId: null,
45817
46059
  access: "view"
45818
46060
  },
45819
- "recording.getDeviceLiveContribution": {
45820
- capName: "recording",
46061
+ "recordingArchive.getDeviceConfig": {
46062
+ capName: "recording-archive",
45821
46063
  capScope: "system",
45822
46064
  addonId: null,
45823
46065
  access: "view"
45824
46066
  },
45825
- "recording.getDeviceSettingsContribution": {
45826
- capName: "recording",
46067
+ "recordingArchive.getDeviceLiveContribution": {
46068
+ capName: "recording-archive",
45827
46069
  capScope: "system",
45828
46070
  addonId: null,
45829
46071
  access: "view"
45830
46072
  },
45831
- "recording.getPlacement": {
45832
- capName: "recording",
46073
+ "recordingArchive.getDeviceSettingsContribution": {
46074
+ capName: "recording-archive",
45833
46075
  capScope: "system",
45834
46076
  addonId: null,
45835
46077
  access: "view"
45836
46078
  },
45837
- "recording.getPlaybackManifest": {
45838
- capName: "recording",
46079
+ "recordingArchive.getPlacement": {
46080
+ capName: "recording-archive",
45839
46081
  capScope: "system",
45840
46082
  addonId: null,
45841
46083
  access: "view"
45842
46084
  },
45843
- "recording.getRelocateResidue": {
45844
- capName: "recording",
46085
+ "recordingArchive.getRelocateResidue": {
46086
+ capName: "recording-archive",
45845
46087
  capScope: "system",
45846
46088
  addonId: null,
45847
46089
  access: "view"
45848
46090
  },
45849
- "recording.getStatus": {
45850
- capName: "recording",
46091
+ "recordingArchive.getStatus": {
46092
+ capName: "recording-archive",
45851
46093
  capScope: "system",
45852
46094
  addonId: null,
45853
46095
  access: "view"
45854
46096
  },
45855
- "recording.getStorageMigrationMoveStatus": {
45856
- capName: "recording",
46097
+ "recordingArchive.getStorageMigrationMoveStatus": {
46098
+ capName: "recording-archive",
45857
46099
  capScope: "system",
45858
46100
  addonId: null,
45859
46101
  access: "view"
45860
46102
  },
45861
- "recording.getStorageUsage": {
45862
- capName: "recording",
46103
+ "recordingArchive.getStorageUsage": {
46104
+ capName: "recording-archive",
45863
46105
  capScope: "system",
45864
46106
  addonId: null,
45865
46107
  access: "view"
45866
46108
  },
45867
- "recording.listOpsLog": {
45868
- capName: "recording",
46109
+ "recordingArchive.listOpsLog": {
46110
+ capName: "recording-archive",
45869
46111
  capScope: "system",
45870
46112
  addonId: null,
45871
46113
  access: "view"
45872
46114
  },
45873
- "recording.listRelocateJobs": {
45874
- capName: "recording",
46115
+ "recordingArchive.listRelocateJobs": {
46116
+ capName: "recording-archive",
45875
46117
  capScope: "system",
45876
46118
  addonId: null,
45877
46119
  access: "view"
45878
46120
  },
45879
- "recording.locateSegment": {
45880
- capName: "recording",
46121
+ "recordingArchive.locateSegment": {
46122
+ capName: "recording-archive",
45881
46123
  capScope: "system",
45882
46124
  addonId: null,
45883
46125
  access: "view"
45884
46126
  },
45885
- "recording.pauseForStorageMigration": {
45886
- capName: "recording",
46127
+ "recordingArchive.pauseForStorageMigration": {
46128
+ capName: "recording-archive",
45887
46129
  capScope: "system",
45888
46130
  addonId: null,
45889
46131
  access: "create"
45890
46132
  },
45891
- "recording.planStorageRebalance": {
45892
- capName: "recording",
46133
+ "recordingArchive.planStorageRebalance": {
46134
+ capName: "recording-archive",
45893
46135
  capScope: "system",
45894
46136
  addonId: null,
45895
46137
  access: "view"
45896
46138
  },
45897
- "recording.pruneFootage": {
45898
- capName: "recording",
46139
+ "recordingArchive.pruneFootage": {
46140
+ capName: "recording-archive",
45899
46141
  capScope: "system",
45900
46142
  addonId: null,
45901
46143
  access: "create"
45902
46144
  },
45903
- "recording.readGopBytes": {
45904
- capName: "recording",
46145
+ "recordingArchive.readGopBytes": {
46146
+ capName: "recording-archive",
45905
46147
  capScope: "system",
45906
46148
  addonId: null,
45907
46149
  access: "view"
45908
46150
  },
45909
- "recording.readSegmentBytes": {
45910
- capName: "recording",
46151
+ "recordingArchive.readSegmentBytes": {
46152
+ capName: "recording-archive",
45911
46153
  capScope: "system",
45912
46154
  addonId: null,
45913
46155
  access: "view"
45914
46156
  },
45915
- "recording.readWindowBytes": {
45916
- capName: "recording",
46157
+ "recordingArchive.readWindowBytes": {
46158
+ capName: "recording-archive",
45917
46159
  capScope: "system",
45918
46160
  addonId: null,
45919
46161
  access: "view"
45920
46162
  },
45921
- "recording.reconcileLedgerAgainstDisk": {
45922
- capName: "recording",
46163
+ "recordingArchive.reconcileLedgerAgainstDisk": {
46164
+ capName: "recording-archive",
45923
46165
  capScope: "system",
45924
46166
  addonId: null,
45925
46167
  access: "create"
45926
46168
  },
45927
- "recording.refreshStorageLocationsForMigration": {
45928
- capName: "recording",
46169
+ "recordingArchive.refreshStorageLocationsForMigration": {
46170
+ capName: "recording-archive",
45929
46171
  capScope: "system",
45930
46172
  addonId: null,
45931
46173
  access: "create"
45932
46174
  },
45933
- "recording.relocateFootage": {
45934
- capName: "recording",
46175
+ "recordingArchive.relocateFootage": {
46176
+ capName: "recording-archive",
45935
46177
  capScope: "system",
45936
46178
  addonId: null,
45937
46179
  access: "create"
45938
46180
  },
45939
- "recording.renderClip": {
45940
- capName: "recording",
46181
+ "recordingArchive.renderClip": {
46182
+ capName: "recording-archive",
45941
46183
  capScope: "system",
45942
46184
  addonId: null,
45943
46185
  access: "create"
45944
46186
  },
45945
- "recording.renderGif": {
45946
- capName: "recording",
46187
+ "recordingArchive.renderGif": {
46188
+ capName: "recording-archive",
45947
46189
  capScope: "system",
45948
46190
  addonId: null,
45949
46191
  access: "create"
45950
46192
  },
45951
- "recording.rescanStorage": {
45952
- capName: "recording",
46193
+ "recordingArchive.rescanStorage": {
46194
+ capName: "recording-archive",
45953
46195
  capScope: "system",
45954
46196
  addonId: null,
45955
46197
  access: "create"
45956
46198
  },
45957
- "recording.resumeForStorageMigration": {
45958
- capName: "recording",
46199
+ "recordingArchive.resumeForStorageMigration": {
46200
+ capName: "recording-archive",
45959
46201
  capScope: "system",
45960
46202
  addonId: null,
45961
46203
  access: "create"
45962
46204
  },
45963
- "recording.setDeviceConfig": {
45964
- capName: "recording",
46205
+ "recordingArchive.setDeviceConfig": {
46206
+ capName: "recording-archive",
45965
46207
  capScope: "system",
45966
46208
  addonId: null,
45967
46209
  access: "create"
45968
46210
  },
45969
- "recording.setDevicePlacement": {
45970
- capName: "recording",
46211
+ "recordingArchive.setDevicePlacement": {
46212
+ capName: "recording-archive",
45971
46213
  capScope: "system",
45972
46214
  addonId: null,
45973
46215
  access: "create"
45974
46216
  },
45975
- "recording.startStorageMigrationMove": {
45976
- capName: "recording",
46217
+ "recordingArchive.startStorageMigrationMove": {
46218
+ capName: "recording-archive",
45977
46219
  capScope: "system",
45978
46220
  addonId: null,
45979
46221
  access: "create"
45980
46222
  },
45981
- "recording.startStorageRebalance": {
45982
- capName: "recording",
46223
+ "recordingArchive.startStorageRebalance": {
46224
+ capName: "recording-archive",
45983
46225
  capScope: "system",
45984
46226
  addonId: null,
45985
46227
  access: "create"
@@ -48284,21 +48526,6 @@ Object.freeze({
48284
48526
  form: "single",
48285
48527
  optional: false
48286
48528
  }],
48287
- "events.getEventClipUrl": [{
48288
- name: "deviceId",
48289
- form: "single",
48290
- optional: false
48291
- }],
48292
- "events.getEvents": [{
48293
- name: "deviceId",
48294
- form: "single",
48295
- optional: false
48296
- }],
48297
- "events.getEventThumbnail": [{
48298
- name: "deviceId",
48299
- form: "single",
48300
- optional: false
48301
- }],
48302
48529
  "faceGallery.getFaceByTrack": [{
48303
48530
  name: "deviceId",
48304
48531
  form: "single",
@@ -49217,107 +49444,117 @@ Object.freeze({
49217
49444
  form: "single",
49218
49445
  optional: false
49219
49446
  }],
49220
- "recording.deleteFootprint": [{
49447
+ "recording.getAvailability": [{
49221
49448
  name: "deviceId",
49222
49449
  form: "single",
49223
49450
  optional: false
49224
49451
  }],
49225
- "recording.getAvailability": [{
49452
+ "recording.getDaysWithRecordings": [{
49226
49453
  name: "deviceId",
49227
49454
  form: "single",
49228
49455
  optional: false
49229
49456
  }],
49230
- "recording.getAvailabilityBatch": [{
49231
- name: "deviceIds",
49232
- form: "array",
49457
+ "recording.getPlayback": [{
49458
+ name: "deviceId",
49459
+ form: "single",
49233
49460
  optional: false
49234
49461
  }],
49235
- "recording.getDaysWithRecordings": [{
49462
+ "recording.getPlaybackOptions": [{
49236
49463
  name: "deviceId",
49237
49464
  form: "single",
49238
49465
  optional: false
49239
49466
  }],
49240
- "recording.getDaysWithRecordingsBatch": [{
49241
- name: "deviceIds",
49242
- form: "array",
49467
+ "recording.listSources": [{
49468
+ name: "deviceId",
49469
+ form: "single",
49243
49470
  optional: false
49244
49471
  }],
49245
- "recording.getDeviceConfig": [{
49472
+ "recordingArchive.deleteFootprint": [{
49246
49473
  name: "deviceId",
49247
49474
  form: "single",
49248
49475
  optional: false
49249
49476
  }],
49250
- "recording.getPlaybackManifest": [{
49477
+ "recordingArchive.getAvailabilityBatch": [{
49478
+ name: "deviceIds",
49479
+ form: "array",
49480
+ optional: false
49481
+ }],
49482
+ "recordingArchive.getDaysWithRecordingsBatch": [{
49483
+ name: "deviceIds",
49484
+ form: "array",
49485
+ optional: false
49486
+ }],
49487
+ "recordingArchive.getDeviceConfig": [{
49251
49488
  name: "deviceId",
49252
49489
  form: "single",
49253
49490
  optional: false
49254
49491
  }],
49255
- "recording.listOpsLog": [{
49492
+ "recordingArchive.listOpsLog": [{
49256
49493
  name: "deviceId",
49257
49494
  form: "single",
49258
49495
  optional: true
49259
49496
  }],
49260
- "recording.locateSegment": [{
49497
+ "recordingArchive.locateSegment": [{
49261
49498
  name: "deviceId",
49262
49499
  form: "single",
49263
49500
  optional: false
49264
49501
  }],
49265
- "recording.pruneFootage": [{
49502
+ "recordingArchive.pruneFootage": [{
49266
49503
  name: "deviceId",
49267
49504
  form: "single",
49268
49505
  optional: false
49269
49506
  }],
49270
- "recording.readGopBytes": [{
49507
+ "recordingArchive.readGopBytes": [{
49271
49508
  name: "deviceId",
49272
49509
  form: "single",
49273
49510
  optional: false
49274
49511
  }],
49275
- "recording.readSegmentBytes": [{
49512
+ "recordingArchive.readSegmentBytes": [{
49276
49513
  name: "deviceId",
49277
49514
  form: "single",
49278
49515
  optional: false
49279
49516
  }],
49280
- "recording.readWindowBytes": [{
49517
+ "recordingArchive.readWindowBytes": [{
49281
49518
  name: "deviceId",
49282
49519
  form: "single",
49283
49520
  optional: false
49284
49521
  }],
49285
- "recording.reconcileLedgerAgainstDisk": [{
49522
+ "recordingArchive.reconcileLedgerAgainstDisk": [{
49286
49523
  name: "deviceId",
49287
49524
  form: "single",
49288
49525
  optional: true
49289
49526
  }],
49290
- "recording.relocateFootage": [{
49527
+ "recordingArchive.relocateFootage": [{
49291
49528
  name: "deviceId",
49292
49529
  form: "single",
49293
49530
  optional: true
49294
49531
  }],
49295
- "recording.renderClip": [{
49532
+ "recordingArchive.renderClip": [{
49296
49533
  name: "deviceId",
49297
49534
  form: "single",
49298
49535
  optional: false
49299
49536
  }],
49300
- "recording.renderGif": [{
49537
+ "recordingArchive.renderGif": [{
49301
49538
  name: "deviceId",
49302
49539
  form: "single",
49303
49540
  optional: false
49304
49541
  }],
49305
- "recording.rescanStorage": [{
49542
+ "recordingArchive.rescanStorage": [{
49306
49543
  name: "deviceId",
49307
49544
  form: "single",
49308
49545
  optional: false
49309
49546
  }],
49310
- "recording.setDeviceConfig": [{
49547
+ "recordingArchive.setDeviceConfig": [{
49311
49548
  name: "deviceId",
49312
49549
  form: "single",
49313
49550
  optional: false
49314
49551
  }],
49315
- "recording.setDevicePlacement": [{
49552
+ "recordingArchive.setDevicePlacement": [{
49316
49553
  name: "deviceId",
49317
49554
  form: "single",
49318
49555
  optional: false
49319
49556
  }],
49320
- "recording.startStorageMigrationMove": [{
49557
+ "recordingArchive.startStorageMigrationMove": [{
49321
49558
  name: "deviceId",
49322
49559
  form: "single",
49323
49560
  optional: true
@@ -72911,7 +73148,7 @@ var require_yazl = /* @__PURE__ */ __commonJSMin(((exports) => {
72911
73148
  }
72912
73149
  }));
72913
73150
  //#endregion
72914
- //#region node_modules/@apocaliss92/nodelink-js/dist/chunk-E2N7WTCC.js
73151
+ //#region node_modules/@apocaliss92/nodelink-js/dist/chunk-AQQAL7CF.js
72915
73152
  var import_undici = require_undici();
72916
73153
  var import_yazl = /* @__PURE__ */ __toESM(require_yazl(), 1);
72917
73154
  var formatterCache = /* @__PURE__ */ new Map();
@@ -79397,9 +79634,16 @@ var require_lz4 = /* @__PURE__ */ __commonJSMin(((exports) => {
79397
79634
  };
79398
79635
  }));
79399
79636
  //#endregion
79400
- //#region node_modules/@apocaliss92/nodelink-js/dist/chunk-7B2Z5FIA.js
79637
+ //#region node_modules/@apocaliss92/nodelink-js/dist/chunk-OXQH2ZT3.js
79401
79638
  var import_fxp = require_fxp();
79402
79639
  var import_lz4 = /* @__PURE__ */ __toESM(require_lz4(), 1);
79640
+ function bcHeaderLen(messageClass, buf, bodyLen) {
79641
+ if (bcHeaderHasPayloadOffset(messageClass)) return 24;
79642
+ if (bcHeaderIsKnown20(messageClass)) return 20;
79643
+ if (buf.length < 24) throw new Error("not enough data for Baichuan header (needs 24 bytes)");
79644
+ const candidate = buf.readUInt32LE(20);
79645
+ return candidate >= 20 && candidate <= bodyLen ? 24 : 20;
79646
+ }
79403
79647
  function encodeHeader(h) {
79404
79648
  const hasOffset = bcHeaderHasPayloadOffset(h.messageClass);
79405
79649
  const headerLen = hasOffset ? 24 : 20;
@@ -79428,7 +79672,7 @@ function decodeHeader(buf) {
79428
79672
  const msgNum = buf.readUInt16LE(14);
79429
79673
  const responseCode = buf.readUInt16LE(16);
79430
79674
  const messageClass = buf.readUInt16LE(18);
79431
- const headerLen = bcHeaderHasPayloadOffset(messageClass) ? 24 : 20;
79675
+ const headerLen = bcHeaderLen(messageClass, buf, bodyLen);
79432
79676
  if (buf.length < headerLen) throw new Error("not enough data for Baichuan header (needs 24 bytes)");
79433
79677
  const messageKey = buf.readUInt32LE(12);
79434
79678
  const header = {
@@ -81361,6 +81605,9 @@ function createDebugGateLogger(base, enabled = false) {
81361
81605
  function isTalkCmd(cmdId) {
81362
81606
  return cmdId === 10 || cmdId === 11 || cmdId === 201 || cmdId === 202;
81363
81607
  }
81608
+ function toWireChannelId(channelId) {
81609
+ return channelId & 255;
81610
+ }
81364
81611
  var BaichuanClient = class _BaichuanClient extends EventEmitter {
81365
81612
  /**
81366
81613
  * Process-wide streaming activity registry.
@@ -83529,7 +83776,7 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
83529
83776
  await this.connect();
83530
83777
  params.channel ?? this.opts.channel;
83531
83778
  const sessionCounter = this.nextMsgNum();
83532
- const channelId = params.channelIdOverride ?? sessionCounter;
83779
+ const channelId = toWireChannelId(params.channelIdOverride ?? sessionCounter);
83533
83780
  const discriminator = params.channelIdOverride == null ? {
83534
83781
  kind: "minted",
83535
83782
  channelId
@@ -83646,25 +83893,25 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
83646
83893
  return;
83647
83894
  }
83648
83895
  if (lockedStreamType !== void 0 && frame.header.streamType !== lockedStreamType) return;
83649
- if (lockedChannelId !== void 0 && frame.header.channelId !== lockedChannelId) {
83896
+ if (lockedChannelId !== void 0 && frame.header.channelId !== toWireChannelId(lockedChannelId)) {
83650
83897
  this.countReplayDrop(session, frame, "foreign-channel");
83651
83898
  return;
83652
83899
  }
83653
83900
  if (streamMsgNum !== void 0 && frame.header.msgNum !== streamMsgNum) return;
83901
+ let markedBinary = false;
83902
+ let encryptLen;
83903
+ if (frame.extension.length > 0) try {
83904
+ const extDec = this.tryDecryptXml(frame.extension, frame.header.channelId, enc);
83905
+ if (extDec.includes("<binaryData>1</binaryData>")) markedBinary = true;
83906
+ const encryptLenMatch = extDec.match(/<encryptLen>(\d+)<\/encryptLen>/i);
83907
+ if (encryptLenMatch && encryptLenMatch[1]) encryptLen = parseInt(encryptLenMatch[1], 10);
83908
+ } catch {}
83654
83909
  const rc = frame.header.responseCode;
83655
- if (rc >= 400 && rc < 6e4 && frame.header.msgNum === msgNum) {
83910
+ if (streamMsgNum === void 0 && !markedBinary && !(rc === 0 || rc === 200 || rc === 201) && frame.header.msgNum === msgNum) {
83656
83911
  fail(/* @__PURE__ */ new Error(`Baichuan FileInfoList replay rejected (cmdId=${cmdId} reqChannelId=${channelId} rspChannelId=${frame.header.channelId} streamType=${expectedStreamType} msgNum=${frame.header.msgNum} responseCode=${rc})`));
83657
83912
  return;
83658
83913
  }
83659
83914
  try {
83660
- let markedBinary = false;
83661
- let encryptLen;
83662
- if (frame.extension.length > 0) try {
83663
- const extDec = this.tryDecryptXml(frame.extension, frame.header.channelId, enc);
83664
- if (extDec.includes("<binaryData>1</binaryData>")) markedBinary = true;
83665
- const encryptLenMatch = extDec.match(/<encryptLen>(\d+)<\/encryptLen>/i);
83666
- if (encryptLenMatch && encryptLenMatch[1]) encryptLen = parseInt(encryptLenMatch[1], 10);
83667
- } catch {}
83668
83915
  const decrypted = decryptBinaryForReplay(frame.payload, frame.header.channelId, encryptLen);
83669
83916
  if (decrypted.length === 0) return;
83670
83917
  if (!markedBinary && looksLikeXml(decrypted)) return;
@@ -83894,7 +84141,7 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
83894
84141
  await this.connect();
83895
84142
  params.channel ?? this.opts.channel;
83896
84143
  const sessionCounter = this.nextMsgNum();
83897
- const channelId = params.channelIdOverride ?? sessionCounter;
84144
+ const channelId = toWireChannelId(params.channelIdOverride ?? sessionCounter);
83898
84145
  const msgNum = params.msgNumOverride ?? 0;
83899
84146
  const cmdId = params.cmdId;
83900
84147
  const extXml = params.extensionXml ?? "";
@@ -88164,6 +88411,117 @@ var estimateVideoTiming = (params) => {
88164
88411
  fpsSource: "unknown"
88165
88412
  };
88166
88413
  };
88414
+ var parseRecStartParamIfPresent = (fileName) => {
88415
+ const m = /Rec(\w{3})(?:_|_DST)(\d{8})_(\d{6})_.*/.exec(fileName);
88416
+ if (!m) return void 0;
88417
+ return `${m[2]}${m[3]}`;
88418
+ };
88419
+ var buildReplayStopNameFromFileName = (fileName, channel = 0) => {
88420
+ const trimmed = (fileName ?? "").trim();
88421
+ if (/^\d{2}\d{14}$/.test(trimmed)) return trimmed;
88422
+ const start = parseRecStartParamIfPresent(fileName);
88423
+ if (!start) return void 0;
88424
+ return `${String(channel + 1).padStart(2, "0")}${start}`;
88425
+ };
88426
+ var buildFileInfoListReplayByIdXml = (params) => {
88427
+ const st = params.streamType ?? "mainStream";
88428
+ const supportSub = st === "subStream" ? 1 : 0;
88429
+ const xmlCh = params.xmlChannelId ?? params.channel;
88430
+ const iframe = params.iframeReplay;
88431
+ const iframeXml = iframe === true || iframe === "both" ? "<bIframeReplay>1</bIframeReplay><iIframeReplay>1</iIframeReplay>" : iframe === "b" ? "<bIframeReplay>1</bIframeReplay>" : iframe === "i" ? "<iIframeReplay>1</iIframeReplay>" : "";
88432
+ const lines = [
88433
+ "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>",
88434
+ "<body>",
88435
+ "<FileInfoList version=\"1.1\">",
88436
+ "<FileInfo>",
88437
+ `<channelId>${xmlCh}</channelId>`,
88438
+ `<Id>${xmlEscape(params.id)}</Id>`
88439
+ ];
88440
+ if (params.uid) lines.push(`<uid>${xmlEscape(params.uid)}</uid>`);
88441
+ lines.push(`<supportSub>${supportSub}</supportSub>`, "<playSpeed>1</playSpeed>", `<streamType>${xmlEscape(st)}</streamType>`);
88442
+ if (iframeXml) lines.push(iframeXml);
88443
+ lines.push("</FileInfo>", "</FileInfoList>", "</body>");
88444
+ return lines.join("\n");
88445
+ };
88446
+ var buildFileInfoListReplayByNameXml = (params) => {
88447
+ const st = params.streamType ?? "mainStream";
88448
+ const supportSub = st === "subStream" ? 1 : 0;
88449
+ const xmlCh = params.xmlChannelId ?? params.channel;
88450
+ const iframe = params.iframeReplay;
88451
+ const iframeXml = iframe === true || iframe === "both" ? "<bIframeReplay>1</bIframeReplay><iIframeReplay>1</iIframeReplay>" : iframe === "b" ? "<bIframeReplay>1</bIframeReplay>" : iframe === "i" ? "<iIframeReplay>1</iIframeReplay>" : "";
88452
+ const lines = [
88453
+ "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>",
88454
+ "<body>",
88455
+ "<FileInfoList version=\"1.1\">",
88456
+ "<FileInfo>",
88457
+ `<channelId>${xmlCh}</channelId>`,
88458
+ `<Id>${xmlEscape(params.name)}</Id>`
88459
+ ];
88460
+ if (params.uid) lines.push(`<uid>${xmlEscape(params.uid)}</uid>`);
88461
+ lines.push(`<supportSub>${supportSub}</supportSub>`, "<playSpeed>1</playSpeed>", `<streamType>${xmlEscape(st)}</streamType>`);
88462
+ if (iframeXml) lines.push(iframeXml);
88463
+ lines.push("</FileInfo>", "</FileInfoList>", "</body>");
88464
+ return lines.join("\n");
88465
+ };
88466
+ var buildFileInfoListStopXml = (params) => {
88467
+ const st = params.streamType ?? "mainStream";
88468
+ return `<?xml version="1.0" encoding="UTF-8" ?>
88469
+ <body>
88470
+ <FileInfoList version="1.1">
88471
+ <FileInfo>
88472
+ <channelId>${params.channel}</channelId>
88473
+ <name>${xmlEscape(params.name)}</name>
88474
+ <streamType>${xmlEscape(st)}</streamType>
88475
+ </FileInfo>
88476
+ </FileInfoList>
88477
+ </body>`;
88478
+ };
88479
+ var REPLAY_SEEK_MAX_DRIFT_MS = 3e3;
88480
+ var buildReplaySeekXml = (params) => {
88481
+ const p = params.parts;
88482
+ const seq = params.seq ?? Math.floor(Date.now() / 1e3);
88483
+ return `<?xml version="1.0" encoding="UTF-8" ?>
88484
+ <body>
88485
+ <ReplaySeek version="1.1">
88486
+ <channelId>${params.channel}</channelId>
88487
+ <seq>${seq}</seq>
88488
+ <seekTime>
88489
+ <year>${p.year}</year>
88490
+ <month>${p.month}</month>
88491
+ <day>${p.day}</day>
88492
+ <hour>${p.hour}</hour>
88493
+ <minute>${p.minute}</minute>
88494
+ <second>${p.second}</second>
88495
+ </seekTime>
88496
+ </ReplaySeek>
88497
+ </body>
88498
+ `;
88499
+ };
88500
+ var BC_IFRAME_MAGIC_MIN = 1667510320;
88501
+ var BC_IFRAME_MAGIC_MAX = 1667510329;
88502
+ var BC_MAX_ADDITIONAL_HEADER = 4096;
88503
+ var readFirstIframeWallClock = (chunk) => {
88504
+ const limit = chunk.length - 28;
88505
+ for (let i = 0; i <= limit; i++) {
88506
+ const magic = chunk.readUInt32LE(i);
88507
+ if (magic < BC_IFRAME_MAGIC_MIN || magic > BC_IFRAME_MAGIC_MAX) continue;
88508
+ const videoType = chunk.toString("utf8", i + 4, i + 8);
88509
+ if (videoType !== "H264" && videoType !== "H265") continue;
88510
+ const additionalHeaderSize = chunk.readUInt32LE(i + 12);
88511
+ if (additionalHeaderSize < 4 || additionalHeaderSize > BC_MAX_ADDITIONAL_HEADER) continue;
88512
+ const t = chunk.readUInt32LE(i + 24);
88513
+ if (t < 1e9 || t > 4e9) continue;
88514
+ const d = /* @__PURE__ */ new Date(t * 1e3);
88515
+ return {
88516
+ year: d.getUTCFullYear(),
88517
+ month: d.getUTCMonth() + 1,
88518
+ day: d.getUTCDate(),
88519
+ hour: d.getUTCHours(),
88520
+ minute: d.getUTCMinutes(),
88521
+ second: d.getUTCSeconds()
88522
+ };
88523
+ }
88524
+ };
88167
88525
  function daysInMonth(year, month) {
88168
88526
  return new Date(Date.UTC(year, month, 0)).getUTCDate();
88169
88527
  }
@@ -90109,71 +90467,6 @@ var buildFileInfoListDownloadXml = (params) => {
90109
90467
  </FileInfoList>
90110
90468
  </body>`;
90111
90469
  };
90112
- var parseRecStartParamIfPresent = (fileName) => {
90113
- const m = /Rec(\w{3})(?:_|_DST)(\d{8})_(\d{6})_.*/.exec(fileName);
90114
- if (!m) return void 0;
90115
- return `${m[2]}${m[3]}`;
90116
- };
90117
- var buildReplayStopNameFromFileName = (fileName, channel = 0) => {
90118
- const trimmed = (fileName ?? "").trim();
90119
- if (/^\d{2}\d{14}$/.test(trimmed)) return trimmed;
90120
- const start = parseRecStartParamIfPresent(fileName);
90121
- if (!start) return void 0;
90122
- return `${String(channel + 1).padStart(2, "0")}${start}`;
90123
- };
90124
- var buildFileInfoListReplayByIdXml = (params) => {
90125
- const st = params.streamType ?? "mainStream";
90126
- const supportSub = st === "subStream" ? 1 : 0;
90127
- const xmlCh = params.xmlChannelId ?? params.channel;
90128
- const iframe = params.iframeReplay;
90129
- const iframeXml = iframe === true || iframe === "both" ? "<bIframeReplay>1</bIframeReplay><iIframeReplay>1</iIframeReplay>" : iframe === "b" ? "<bIframeReplay>1</bIframeReplay>" : iframe === "i" ? "<iIframeReplay>1</iIframeReplay>" : "";
90130
- const lines = [
90131
- "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>",
90132
- "<body>",
90133
- "<FileInfoList version=\"1.1\">",
90134
- "<FileInfo>",
90135
- `<channelId>${xmlCh}</channelId>`,
90136
- `<Id>${xmlEscape(params.id)}</Id>`
90137
- ];
90138
- if (params.uid) lines.push(`<uid>${xmlEscape(params.uid)}</uid>`);
90139
- lines.push(`<supportSub>${supportSub}</supportSub>`, "<playSpeed>1</playSpeed>", `<streamType>${xmlEscape(st)}</streamType>`);
90140
- if (iframeXml) lines.push(iframeXml);
90141
- lines.push("</FileInfo>", "</FileInfoList>", "</body>");
90142
- return lines.join("\n");
90143
- };
90144
- var buildFileInfoListReplayByNameXml = (params) => {
90145
- const st = params.streamType ?? "mainStream";
90146
- const supportSub = st === "subStream" ? 1 : 0;
90147
- const xmlCh = params.xmlChannelId ?? params.channel;
90148
- const iframe = params.iframeReplay;
90149
- const iframeXml = iframe === true || iframe === "both" ? "<bIframeReplay>1</bIframeReplay><iIframeReplay>1</iIframeReplay>" : iframe === "b" ? "<bIframeReplay>1</bIframeReplay>" : iframe === "i" ? "<iIframeReplay>1</iIframeReplay>" : "";
90150
- const lines = [
90151
- "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>",
90152
- "<body>",
90153
- "<FileInfoList version=\"1.1\">",
90154
- "<FileInfo>",
90155
- `<channelId>${xmlCh}</channelId>`,
90156
- `<Id>${xmlEscape(params.name)}</Id>`
90157
- ];
90158
- if (params.uid) lines.push(`<uid>${xmlEscape(params.uid)}</uid>`);
90159
- lines.push(`<supportSub>${supportSub}</supportSub>`, "<playSpeed>1</playSpeed>", `<streamType>${xmlEscape(st)}</streamType>`);
90160
- if (iframeXml) lines.push(iframeXml);
90161
- lines.push("</FileInfo>", "</FileInfoList>", "</body>");
90162
- return lines.join("\n");
90163
- };
90164
- var buildFileInfoListStopXml = (params) => {
90165
- const st = params.streamType ?? "mainStream";
90166
- return `<?xml version="1.0" encoding="UTF-8" ?>
90167
- <body>
90168
- <FileInfoList version="1.1">
90169
- <FileInfo>
90170
- <channelId>${params.channel}</channelId>
90171
- <name>${xmlEscape(params.name)}</name>
90172
- <streamType>${xmlEscape(st)}</streamType>
90173
- </FileInfo>
90174
- </FileInfoList>
90175
- </body>`;
90176
- };
90177
90470
  var videoCodecMap = {
90178
90471
  0: "H.264",
90179
90472
  1: "H.265",
@@ -91062,6 +91355,7 @@ var isNvrHubModel = (model) => {
91062
91355
  if (NVR_HUB_EXACT_TYPES.includes(upper)) return true;
91063
91356
  return NVR_HUB_MODEL_PATTERNS.some((pattern) => pattern.test(normalized));
91064
91357
  };
91358
+ var SEEKED_CHANNELS = /* @__PURE__ */ new WeakMap();
91065
91359
  var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
91066
91360
  logger;
91067
91361
  httpClient;
@@ -92819,7 +93113,7 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
92819
93113
  return;
92820
93114
  }
92821
93115
  entry.startInFlight = (async () => {
92822
- const { BaichuanVideoStream: BaichuanVideoStream2 } = await import("./BaichuanVideoStream-UG3DIMIE-BRbIHCdL.mjs");
93116
+ const { BaichuanVideoStream: BaichuanVideoStream2 } = await import("./BaichuanVideoStream-PR2SYJAE-DX1rTJzR.mjs");
92823
93117
  const sessionKey = `live:object-detections:ch${entry.channel}:${entry.profile}`;
92824
93118
  const dedicated = await this.createDedicatedSession(sessionKey);
92825
93119
  const stream = new BaichuanVideoStream2({
@@ -95842,6 +96136,44 @@ ${stderr}`));
95842
96136
  trace(`download: channel=${channel} uid=${uid || "(missing)"} ident=${ident} streamType=${streamType} isNvr=${isNvr} timeoutMs=${timeoutMs}`);
95843
96137
  const pinnedHeaderChannelId = params.headerChannelIdOverride;
95844
96138
  let abandoned = false;
96139
+ const timeZone = params.timeZone ?? this.recordingsTimeZone;
96140
+ const clipStart = this.replayStartInstantOf(ident, timeZone);
96141
+ const requestedAt = params.seekTo ?? clipStart;
96142
+ const outcome = {
96143
+ requestedAt: params.seekTo ?? null,
96144
+ deliveredAt: null,
96145
+ driftMs: null,
96146
+ seekApplied: false
96147
+ };
96148
+ const dirty = SEEKED_CHANNELS.get(this.client)?.has(channel) === true;
96149
+ if (requestedAt && (params.seekTo !== void 0 || dirty)) {
96150
+ outcome.seekApplied = await this.replaySeek({
96151
+ channel,
96152
+ at: requestedAt,
96153
+ ...timeZone !== void 0 ? { timeZone } : {}
96154
+ });
96155
+ if (!outcome.seekApplied) {
96156
+ outcome.reason = "camera did not accept cmd 123 <ReplaySeek>; the transfer runs unpositioned";
96157
+ trace(`seek not applied for ${ident}: ${outcome.reason}`);
96158
+ }
96159
+ } else if (!requestedAt) {
96160
+ outcome.reason = `no start instant derivable from ${ident}; the transfer runs unpositioned`;
96161
+ trace(outcome.reason);
96162
+ } else trace(`channel ${String(channel)} never seeked on this connection; ${ident} runs unpositioned at full rate`);
96163
+ let deliveredParts;
96164
+ const observeChunk = (chunk) => {
96165
+ if (deliveredParts === void 0) deliveredParts = readFirstIframeWallClock(chunk);
96166
+ };
96167
+ const settleOutcome = () => {
96168
+ if (deliveredParts !== void 0) {
96169
+ outcome.deliveredAt = dateFromWallClock(deliveredParts, timeZone);
96170
+ if (outcome.requestedAt) {
96171
+ outcome.driftMs = outcome.deliveredAt.getTime() - outcome.requestedAt.getTime();
96172
+ if (Math.abs(outcome.driftMs) > 3e3) this.logger?.warn?.(`[fileInfoListReplayBinaryDownload] seek drift ${outcome.driftMs} ms for ${ident}: asked ${outcome.requestedAt.toISOString()}, delivered ${outcome.deliveredAt.toISOString()} (> ${REPLAY_SEEK_MAX_DRIFT_MS} ms \u2014 the camera did not honour the position)`);
96173
+ }
96174
+ } else if (outcome.reason === void 0) outcome.reason = "no I-frame in the transfer; delivered position unknown";
96175
+ params.onSeekOutcome?.(outcome);
96176
+ };
95845
96177
  try {
95846
96178
  return await this.client.sendBinary({
95847
96179
  cmdId: 5,
@@ -95853,13 +96185,17 @@ ${stderr}`));
95853
96185
  streamType: 0,
95854
96186
  timeoutMs,
95855
96187
  ...params.idleTimeoutMs != null ? { idleTimeoutMs: params.idleTimeoutMs } : {},
95856
- ...params.onChunk ? { onChunk: params.onChunk } : {}
96188
+ onChunk: (chunk) => {
96189
+ observeChunk(chunk);
96190
+ params.onChunk?.(chunk);
96191
+ }
95857
96192
  });
95858
96193
  } catch (e) {
95859
96194
  trace(`download failed: ${e instanceof Error ? e.message : String(e)}`);
95860
96195
  abandoned = true;
95861
96196
  throw e;
95862
96197
  } finally {
96198
+ settleOutcome();
95863
96199
  await this.stopFileInfoListReplay({
95864
96200
  channel,
95865
96201
  fileName: ident,
@@ -95869,6 +96205,76 @@ ${stderr}`));
95869
96205
  }
95870
96206
  }
95871
96207
  /**
96208
+ * The instant a recording begins, read out of its own file name.
96209
+ *
96210
+ * `Rec*_YYYYMMDD_HHMMSS_…` is the camera's wall clock with no offset on the
96211
+ * wire, so it is resolved through the same zone as every other recording
96212
+ * timestamp. `undefined` for a name that does not carry one — an identifier
96213
+ * this library did not get from a FileInfoList listing, for instance.
96214
+ */
96215
+ replayStartInstantOf(fileName, timeZone) {
96216
+ const stamp = parseRecStartParamIfPresent(fileName);
96217
+ if (!stamp) return void 0;
96218
+ return dateFromWallClock({
96219
+ year: Number(stamp.slice(0, 4)),
96220
+ month: Number(stamp.slice(4, 6)),
96221
+ day: Number(stamp.slice(6, 8)),
96222
+ hour: Number(stamp.slice(8, 10)),
96223
+ minute: Number(stamp.slice(10, 12)),
96224
+ second: Number(stamp.slice(12, 14))
96225
+ }, timeZone);
96226
+ }
96227
+ /**
96228
+ * Position the NEXT replay of this channel — cmd 123 `<ReplaySeek>`.
96229
+ *
96230
+ * The camera can replay one recording from an arbitrary instant inside it,
96231
+ * and this is how the official app asks: a wall-clock second, sent BEFORE
96232
+ * the cmd 5 that opens the stream. Measured 2026-09-23 — asked +40 s into a
96233
+ * 75 s clip, the first I-frame delivered was the clip's start +40 s, on an
96234
+ * E1 Outdoor PoE (v3.1.0.5223) and on a Home Hub child (v3.3.0.456).
96235
+ *
96236
+ * Two things a caller must know:
96237
+ *
96238
+ * - **The granularity is a KEYFRAME, not a second.** The stream begins at
96239
+ * the I-frame nearest the instant asked for — 592 rounded up, the hub
96240
+ * child rounded down, both by up to one GOP (~2 s). Read the position back
96241
+ * (`fileInfoListReplayBinaryDownload` reports it) rather than assuming it.
96242
+ * - **The position is STICKY for the life of the connection.** Measured: a
96243
+ * seek, then a replay, then ANOTHER replay that asked for no seek — and
96244
+ * the second one still started at the seek point. This is why
96245
+ * `fileInfoListReplayBinaryDownload` always sends a `<ReplaySeek>`, to the
96246
+ * clip's own start when the caller asked for no offset. Calling this
96247
+ * method directly leaves that discipline to you.
96248
+ *
96249
+ * Returns `true` when the camera accepted the command. A camera that does
96250
+ * not support cmd 123 returns `false` rather than throwing, because a seek
96251
+ * is an enhancement to a download and must never be the reason one fails.
96252
+ */
96253
+ async replaySeek(params) {
96254
+ const channel = this.normalizeChannel(params.channel);
96255
+ const timeZone = params.timeZone ?? this.recordingsTimeZone;
96256
+ const payloadXml = buildReplaySeekXml({
96257
+ channel,
96258
+ parts: wallClockParts(params.at, timeZone)
96259
+ });
96260
+ try {
96261
+ await this.client.sendXml({
96262
+ cmdId: 123,
96263
+ extensionXml: "",
96264
+ payloadXml,
96265
+ timeoutMs: params.timeoutMs ?? 8e3
96266
+ });
96267
+ const client = this.client;
96268
+ const seeked = SEEKED_CHANNELS.get(client) ?? /* @__PURE__ */ new Set();
96269
+ seeked.add(channel);
96270
+ SEEKED_CHANNELS.set(client, seeked);
96271
+ return true;
96272
+ } catch (e) {
96273
+ this.logger?.warn?.(`[replaySeek] channel=${channel} at=${params.at.toISOString()} not applied: ${e instanceof Error ? e.message : String(e)}`);
96274
+ return false;
96275
+ }
96276
+ }
96277
+ /**
95872
96278
  * Close a cmd 5 replay session at the camera (cmd 7) and wait for the wire to
95873
96279
  * go quiet.
95874
96280
  *
@@ -99023,7 +99429,7 @@ ${xml}`);
99023
99429
  * @returns Test results for all stream types and profiles
99024
99430
  */
99025
99431
  async testChannelStreams(channel, logger) {
99026
- const { testChannelStreams } = await import("./DiagnosticsTools-YIWXO7IJ-9NV95vRN.mjs");
99432
+ const { testChannelStreams } = await import("./DiagnosticsTools-DS5X2UVY-9NV95vRN.mjs");
99027
99433
  return await testChannelStreams({
99028
99434
  api: this,
99029
99435
  channel: this.normalizeChannel(channel),
@@ -99039,7 +99445,7 @@ ${xml}`);
99039
99445
  * @returns Complete diagnostics for all channels and streams
99040
99446
  */
99041
99447
  async collectMultifocalDiagnostics(logger) {
99042
- const { collectMultifocalDiagnostics } = await import("./DiagnosticsTools-YIWXO7IJ-9NV95vRN.mjs");
99448
+ const { collectMultifocalDiagnostics } = await import("./DiagnosticsTools-DS5X2UVY-9NV95vRN.mjs");
99043
99449
  return await collectMultifocalDiagnostics({
99044
99450
  api: this,
99045
99451
  logger
@@ -152618,6 +153024,7 @@ function createClipStreamProducer(deps) {
152618
153024
  const createDecoder = deps.createDecoder ?? defaultDecoder;
152619
153025
  const drainTimeoutMs = deps.drainTimeoutMs ?? 1e4;
152620
153026
  const flushTimeoutMs = deps.flushTimeoutMs ?? 15e3;
153027
+ const cutGraceMs = deps.cutGraceMs ?? 5e3;
152621
153028
  const lanes = /* @__PURE__ */ new Map();
152622
153029
  const activeByHost = /* @__PURE__ */ new Map();
152623
153030
  const runAttempt = (input, attempt) => new ClipStreamRun({
@@ -152625,7 +153032,8 @@ function createClipStreamProducer(deps) {
152625
153032
  spawnMux: deps.spawnMux,
152626
153033
  createDecoder,
152627
153034
  drainTimeoutMs,
152628
- flushTimeoutMs
153035
+ flushTimeoutMs,
153036
+ cutGraceMs
152629
153037
  }, input, attempt).run();
152630
153038
  const runAttempts = async (input) => {
152631
153039
  const { deviceId } = input.device;
@@ -152726,6 +153134,8 @@ var ClipStreamRun = class {
152726
153134
  input;
152727
153135
  attempt;
152728
153136
  accessUnits = 0;
153137
+ /** Armed by {@link sever}; cleared when the run finally returns. */
153138
+ cutWatch = null;
152729
153139
  /** Every audio frame the decoder handed over, of any codec. */
152730
153140
  audioFrames = 0;
152731
153141
  audioFramesDropped = 0;
@@ -152830,6 +153240,8 @@ var ClipStreamRun = class {
152830
153240
  return await this.onTransferEnded();
152831
153241
  } finally {
152832
153242
  this.done = true;
153243
+ if (this.cutWatch !== null) clearTimeout(this.cutWatch);
153244
+ this.cutWatch = null;
152833
153245
  this.disposeGates();
152834
153246
  }
152835
153247
  }
@@ -153107,6 +153519,36 @@ var ClipStreamRun = class {
153107
153519
  this.input.sink.end();
153108
153520
  }
153109
153521
  /** Sever every hop, once, and say why. */
153522
+ /**
153523
+ * The lane this run is still holding, some time after it was cut.
153524
+ *
153525
+ * D391: a branch that ACCEPTED work and produces nothing is the same branch
153526
+ * as one that drops it. `sever()` already says the stream was cut; it does
153527
+ * not say that the camera never let go, which is the part that makes every
153528
+ * later tap on this host fail.
153529
+ */
153530
+ armCutWatch(reason) {
153531
+ const cutAt = Date.now();
153532
+ this.cutWatch = setTimeout(() => {
153533
+ this.cutWatch = null;
153534
+ if (this.done) return;
153535
+ this.deps.logger.warn("videoclips: a cut clip stream is still holding its camera lane", {
153536
+ tags: this.tags,
153537
+ meta: {
153538
+ clipKey: this.input.row.clipKey,
153539
+ twin: this.input.twin,
153540
+ branch: "cut-not-honoured",
153541
+ reason,
153542
+ hostKey: this.input.device.hostKey,
153543
+ heldSinceCutMs: Date.now() - cutAt,
153544
+ accessUnits: this.accessUnits,
153545
+ bytesOut: this.bytesOut,
153546
+ begun: this.begun
153547
+ }
153548
+ });
153549
+ }, this.deps.cutGraceMs);
153550
+ this.cutWatch.unref?.();
153551
+ }
153110
153552
  sever(reason, detail) {
153111
153553
  if (this.cut !== null || this.done) return;
153112
153554
  this.cut = {
@@ -153131,6 +153573,7 @@ var ClipStreamRun = class {
153131
153573
  }
153132
153574
  });
153133
153575
  if (this.begun) this.input.sink.destroy();
153576
+ this.armCutWatch(reason);
153134
153577
  }
153135
153578
  cutOutcome(cut) {
153136
153579
  if (this.begun) return {
@@ -155038,11 +155481,24 @@ function createReolinkVideoclipsProvider(deps) {
155038
155481
  * reads only whether the dial and the file read are wired, and never the
155039
155482
  * clip or the profile.
155040
155483
  *
155041
- * The rates are the BROKER's re-pacing ladder. The camera's own
155042
- * `<playSpeed>` (8, 16) is real and still unwired (D597, D600): it would
155043
- * ride on the dial and cost a new stream per change, and its audio has no
155044
- * resampler on this path. When it is wired its rates join
155045
- * `CLIP_BROKER_PACED_RATES` — not a second list here.
155484
+ * The rates are the BROKER's re-pacing ladder, and they are the only
155485
+ * rates there are. The camera's own `<playSpeed>` is NOT a second rate
155486
+ * mechanism waiting to be wired — measured on 592, 2026-09-23 (D620):
155487
+ * at 1, 2, 4 and 8 it returns a byte-identical transfer (947 472 B, 594
155488
+ * access units, the same 39.855 s presentation span, the same 624 AAC
155489
+ * frames) and changes only how fast those bytes cross. It buys SUPPLY,
155490
+ * never speed. `playSpeed 16` is not a rate either: the camera switches
155491
+ * to one frame per GOP across the whole clip (20 units, 2 025 ms apart,
155492
+ * no audio) — a different STREAM, dialled as one, never a rate applied to
155493
+ * this one.
155494
+ *
155495
+ * So 8x and 16x do not arrive here. They arrive when the broker's pacer
155496
+ * is allowed above 4 (`clampPlaybackRate`, the `setRate` bound and
155497
+ * `CLIP_BROKER_PACED_RATES`, together) — and only once the supply behind
155498
+ * them is real: D620 measured this camera delivering at 1.2–1.37x while
155499
+ * the library positions every replay with cmd 123, against 95–116x when
155500
+ * it does not. A ladder widened before that is a rate accepted and not
155501
+ * delivered, which is the whole defect D612 exists to end.
155046
155502
  */
155047
155503
  getPlaybackOptions: async () => CLIP_PLAYBACK_OPTIONS.stream,
155048
155504
  /**