@camstack/addon-provider-reolink 1.2.162 → 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-i3eUVc-d.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",
@@ -7713,7 +7731,7 @@ var AdoptionJobSchema = object({
7713
7731
  * component's original options — detection to the detection-pipeline wrapper
7714
7732
  * binding, audio analysis to its own, recording to `RecordingConfig.enabled`
7715
7733
  * (which was always first-class; the switch was a veneer over
7716
- * `recording.setDeviceConfig`), notifications to a notification-center
7734
+ * `recordingArchive.setDeviceConfig`), notifications to a notification-center
7717
7735
  * per-device setting, the two camera planes to their own components.
7718
7736
  *
7719
7737
  * What survives is {@link composeSwitchedOff}: `CameraStatus.switchedOff`, the
@@ -7739,7 +7757,7 @@ var AdoptionJobSchema = object({
7739
7757
  * | `stream-broker` | `deviceManager.setDisabled` | `StreamBrokerManager.reconcileAllCatalogs` releases the brokers; `ensureBroker` refuses re-creation |
7740
7758
  * | `object-detection` | `deviceManager.setWrapperActive('detection-pipeline')` | `PipelineSettingsStore.resolvePipelineForDevice` returns `{ steps: [], audio: null }` |
7741
7759
  * | `audio-analysis` | `deviceManager.setWrapperActive('audio-analysis')` | `AudioSubscriptionController.subscribeAudioStream` returns `null` before opening the stream |
7742
- * | `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 |
7743
7761
  * | `notifications` | `notificationRules.setDeviceMuted` | `NotificationCenter.evaluateAndEnqueue` returns before any rule is evaluated |
7744
7762
  * | `privacy-mask` | `privacyMask.setMask({ enabled })` → the CAMERA | the camera blanks the masked regions itself; every stream and recording carries the black boxes |
7745
7763
  * | `device-audio` | `privacyMask.setAudioEnabled` → the CAMERA | the camera stops encoding an audio track at all; every consumer sees silent video |
@@ -12169,87 +12187,6 @@ method(ListInputSchema, array(BrokerInfoSchema$1)), method(GetInputSchema, Broke
12169
12187
  auth: "admin"
12170
12188
  }), method(GetStateInputSchema, unknown().nullable()), method(_void(), RegistryStatusSchema);
12171
12189
  DeviceType.Camera;
12172
- /**
12173
- * The signals a device can emit to WAKE its own stream.
12174
- *
12175
- * A camera whose stream is built on demand sleeps until something asks for it,
12176
- * and "something" cannot be a consumer that is merely attached — a Frigate-style
12177
- * puller holds a session open for ever, and treating that as demand would keep
12178
- * a battery camera awake for ever, which is the whole thing the battery is for
12179
- * (D173). So the wake has to come from the CAMERA: an event it noticed by
12180
- * itself, with no stream running.
12181
- *
12182
- * ## The vocabulary is the PROVIDER'S, not ours
12183
- *
12184
- * Like `consumables`, this cap declares no vocabulary of its own. A provider
12185
- * names each signal with a `code` it chooses and a `label` an operator reads.
12186
- * Reolink offers motion and camera-native detection; another provider may offer
12187
- * a tamper, a doorbell press, a PIR, or something no camera in this fleet has
12188
- * yet. A fixed enum here would mean every new signal is a framework release.
12189
- *
12190
- * It is deliberately NOT derived from the caps a device already binds. Whether
12191
- * a camera CAN push firmware motion is expressed by `motionSources` containing
12192
- * `'onboard'`, and whether it does AI on-camera by the `native-object-detection`
12193
- * binding — but both answer "what drives the detection pipeline", which is a
12194
- * different question from "what may wake a sleeping stream". A camera can do
12195
- * the first and not be trusted with the second, and the operator picks per
12196
- * camera. Two questions, two authorities.
12197
- *
12198
- * ## Availability is not permission
12199
- *
12200
- * `listSignals` says what the device CAN emit. Whether a given signal actually
12201
- * wakes the stream is the operator's per-camera choice, held by the broker
12202
- * alongside the cooldown — see the stream-broker cap's wake settings. A
12203
- * provider declaring a signal is not a provider enabling it.
12204
- */
12205
- /** One signal a device can emit. */
12206
- var StreamSignalSchema = object({
12207
- /** Stable id chosen by the provider, e.g. `'motion'`, `'person'`, `'tamper'`. */
12208
- code: string().min(1),
12209
- /** What an operator reads in the picker. The provider's own wording. */
12210
- label: string().min(1),
12211
- /**
12212
- * Whether the provider recommends this signal ON when a camera is first set
12213
- * up. A provider knows which of its signals are cheap and reliable; an
12214
- * operator should not have to discover that by trial. Reolink recommends
12215
- * both of its own.
12216
- */
12217
- recommended: boolean()
12218
- });
12219
- var StreamSignalsStatusSchema = object({
12220
- signals: array(StreamSignalSchema),
12221
- lastFetchedAt: number()
12222
- });
12223
- var streamSignalsCapability = {
12224
- name: "stream-signals",
12225
- scope: "device",
12226
- deviceNative: true,
12227
- mode: "singleton",
12228
- deviceTypes: Object.values(DeviceType),
12229
- runtimeState: StreamSignalsStatusSchema,
12230
- /**
12231
- * Runtime-state durability: **session** — mirrored in RAM, never written.
12232
- *
12233
- * The slice holds what the DEVICE says it can emit. That is a probed fact,
12234
- * not an operator choice: the provider re-declares it on every registration,
12235
- * so losing it loses nothing and persisting it would freeze an answer the
12236
- * camera is entitled to change. Measured the same day on the sibling case —
12237
- * `native-object-detection.supportedClasses` was persisted, and a firmware
12238
- * class the camera really detected stayed missing for the life of the row
12239
- * because the fix could not reach it.
12240
- *
12241
- * See `RuntimeStateDurability`. Enforced by
12242
- * `scripts/check-runtime-state-durability.ts`.
12243
- */
12244
- durability: "session",
12245
- methods: {
12246
- /**
12247
- * What this device can emit. Empty is a valid and common answer — most
12248
- * cameras have nothing to offer here, and an empty list is what makes the
12249
- * broker's picker show nothing rather than a false choice.
12250
- */
12251
- listSignals: method(_void(), array(StreamSignalSchema).readonly()) }
12252
- };
12253
12190
  /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
12254
12191
  var StreamFormatSchema = _enum([
12255
12192
  "webrtc",
@@ -13715,6 +13652,210 @@ method(object({ codec: string() }), boolean()), method(_void(), object({
13715
13652
  });
13716
13653
  DeviceType.Camera;
13717
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
+ /**
13718
13859
  * Identity envelope for a device's upstream-system metadata.
13719
13860
  *
13720
13861
  * Two jobs:
@@ -14149,210 +14290,6 @@ method(object({ integrationId: string() }), object({ filters: array(AdoptionFilt
14149
14290
  auth: "admin"
14150
14291
  });
14151
14292
  /**
14152
- * device-admin-link — "this device has a management page of its own, and here
14153
- * is its address".
14154
- *
14155
- * ## Why this is not a `deviceConfig` cap
14156
- *
14157
- * There is nothing to edit. A `deviceConfig` cap (D14) exists so the framework
14158
- * can DERIVE a settings form from `getOptions` + `getStatus` and route a flat
14159
- * patch back through a setter; it costs a `builderId` reducer in
14160
- * `device-config-contribution.ts` and a `*-config-schema.ts` beside it, and it
14161
- * renders a form section. This cap answers ONE question with ONE read and
14162
- * renders a button. Nothing about it is a form, so it carries no `deviceConfig`
14163
- * block, no `settings`, no `runtimeState` and no reducer — exactly like
14164
- * `reboot`, the other pure-RPC device-native cap.
14165
- *
14166
- * ## Absent, and the difference between "no page" and "we cannot say"
14167
- *
14168
- * The two are answered at DIFFERENT layers, on purpose:
14169
- *
14170
- * - **"We cannot say"** → the provider never registers the cap for that
14171
- * device. A VeSync humidifier, a Petkit feeder, a Dreame vacuum and a Dreo
14172
- * fan are reached only through a vendor cloud; there is no address to hand
14173
- * out and no page to open. A Tuya plug, a Wyze camera and a Gree air
14174
- * conditioner DO have a LAN IP, and still have no HTTP management page
14175
- * behind it. None of them register, so `deviceManager.getBindings` never
14176
- * lists the cap and no surface asks.
14177
- * - **"This device has no page, and I know that"** → the provider registers
14178
- * and `getAdminLink` returns `null`. This is the answer for a device whose
14179
- * sibling DOES have a page: a Reolink battery camera reached over UDP by
14180
- * `uid` with a blank `host`, an Ecowitt gateway configured in `listener`
14181
- * transport, a Home Assistant broker authenticated by supervisor token
14182
- * (which carries no `baseUrl` at all).
14183
- *
14184
- * Both draw NOTHING. A button that opens a browser error is worse than no
14185
- * button, and D62 is the same rule from the other side: an off switch is
14186
- * reported off, never made to look broken. There is no third state where the
14187
- * UI renders a disabled button "because the device might have a page".
14188
- *
14189
- * ## The URL never carries credentials
14190
- *
14191
- * Not in userinfo, not in a query string. Every provider builds through
14192
- * `buildDeviceAdminUrl` (`device-admin-link-url.ts`), which takes host, port,
14193
- * scheme and path as separate arguments — there is no parameter a secret could
14194
- * arrive in — and re-checks its own output for the `scheme://user:pass@` shape
14195
- * that `scripts/check-no-credential-urls-in-fixtures.ts` bans from recorded
14196
- * output. `scripts/check-admin-link-builder-is-the-only-url-source.ts` is what
14197
- * keeps providers from hand-rolling one anyway.
14198
- *
14199
- * This matters here more than anywhere else in the repo, because every provider
14200
- * that knows a device's host knows its PASSWORD too: `{ host, port, username,
14201
- * password }` sit in one object on Hikvision, Amcrest, Reolink and ONVIF alike,
14202
- * and `http://admin:hunter2@192.168.50.139/` is a URL a browser accepts. The
14203
- * camera's own page will ask for its own login. That is correct, and pre-
14204
- * filling it is the operator's business, not ours.
14205
- *
14206
- * ## It is a LAN fact
14207
- *
14208
- * The URL addresses the device where the NODE can see it. It is not proxied,
14209
- * not made reachable from outside, and not sent anywhere. A surface renders it
14210
- * as a link the operator's own browser follows, on the operator's own network,
14211
- * or renders nothing.
14212
- */
14213
- /**
14214
- * Whose page is it. The distinction is for the OPERATOR, who needs to know
14215
- * before clicking whether he is about to land on a camera's own web server or
14216
- * inside Home Assistant.
14217
- */
14218
- var AdminLinkTargetEnum = _enum(["device", "integration"]);
14219
- var DeviceAdminLinkSchema = object({
14220
- /**
14221
- * Absolute `http(s)://` URL. Built by `buildDeviceAdminUrl` and therefore
14222
- * free of userinfo and of any credential-shaped query key.
14223
- */
14224
- url: string(),
14225
- /**
14226
- * What the surface calls it — "Web UI", "Home Assistant", "UniFi controller".
14227
- * The PROVIDER names it, because only the provider knows what the page is;
14228
- * a UI that invented the label from the addon id would call the Home
14229
- * Assistant device page "Provider Homeassistant".
14230
- */
14231
- label: string(),
14232
- target: AdminLinkTargetEnum,
14233
- /**
14234
- * Host the URL points at, without scheme, port or path — for the tooltip, so
14235
- * an operator can see WHERE the button goes before he follows it. Redundant
14236
- * with `url` by construction; carried separately so no surface has to parse
14237
- * a URL to show it.
14238
- */
14239
- host: string()
14240
- });
14241
- var deviceAdminLinkCapability = {
14242
- name: "device-admin-link",
14243
- scope: "device",
14244
- deviceNative: true,
14245
- mode: "singleton",
14246
- methods: {
14247
- /**
14248
- * The device's management page, or `null` when this device has none.
14249
- *
14250
- * `auth: 'admin'` deliberately. This is administration, not actuation —
14251
- * the same bucket as `reboot` and `camera-credentials`, and explicitly NOT
14252
- * the actuation set `scripts/check-actuation-not-admin.ts` protects (D403).
14253
- * The URL is also a statement about the LAN, which a household member with
14254
- * a `view` grant on a light has no reason to be handed.
14255
- *
14256
- * The surfaces gate on the QUERY, never on a role they guessed: a caller
14257
- * without the right loses the query and draws nothing, which is the same
14258
- * thing a device with no page draws. There is no path on which a button
14259
- * appears and then fails — the D403 failure mode, from the other end.
14260
- */
14261
- getAdminLink: method(object({ deviceId: number().int().nonnegative() }), DeviceAdminLinkSchema.nullable(), { auth: "admin" }) }
14262
- };
14263
- /**
14264
- * Query keys that may never appear on an admin link. A credential smuggled as
14265
- * `?password=` is the same leak as userinfo, in a form the userinfo check
14266
- * cannot see: it survives copy-paste, referrer headers and proxy logs
14267
- * identically.
14268
- */
14269
- var CREDENTIAL_QUERY_KEYS = [
14270
- "password",
14271
- "passwd",
14272
- "pwd",
14273
- "pass",
14274
- "user",
14275
- "username",
14276
- "usr",
14277
- "login",
14278
- "token",
14279
- "access_token",
14280
- "auth",
14281
- "authorization",
14282
- "apikey",
14283
- "api_key",
14284
- "secret",
14285
- "credential",
14286
- "credentials",
14287
- "session",
14288
- "sessionid",
14289
- "key"
14290
- ];
14291
- /**
14292
- * The same userinfo shape `scripts/check-no-credential-urls-in-fixtures.ts`
14293
- * scans recorded fixtures for, applied to what we are about to EMIT. Kept
14294
- * structurally identical on purpose: a URL this function returns is a URL that
14295
- * guard would pass.
14296
- */
14297
- var CREDENTIAL_URL = /[a-z][a-z0-9+.-]*:\/\/[^/\s:@'"]+:[^/\s:@'"]+@/i;
14298
- /** A host that is safe to place in an authority component verbatim. */
14299
- var PLAIN_HOST = /^[a-zA-Z0-9._-]+$/;
14300
- /** A bracketed IPv6 literal, the only other authority form we emit. */
14301
- var IPV6_HOST = /^\[[0-9a-fA-F:.]+\]$/;
14302
- function defaultPortFor(scheme) {
14303
- return scheme === "https" ? 443 : 80;
14304
- }
14305
- /**
14306
- * Build the admin-page URL, or refuse by name.
14307
- *
14308
- * The refusal is never thrown: a provider answering "no page for this device"
14309
- * is an ordinary answer (`getAdminLink` → `null`), and a throw here would turn
14310
- * a missing host on one device into a failed query for the whole surface.
14311
- */
14312
- function buildDeviceAdminUrl(parts) {
14313
- const host = parts.host.trim();
14314
- if (host.length === 0) return {
14315
- ok: false,
14316
- reason: "empty-host"
14317
- };
14318
- if (host.includes("@")) return {
14319
- ok: false,
14320
- reason: "host-carries-userinfo"
14321
- };
14322
- if (!PLAIN_HOST.test(host) && !IPV6_HOST.test(host)) return {
14323
- ok: false,
14324
- reason: "host-not-plain"
14325
- };
14326
- if (parts.port !== null) {
14327
- if (!Number.isInteger(parts.port) || parts.port < 1 || parts.port > 65535) return {
14328
- ok: false,
14329
- reason: "port-out-of-range"
14330
- };
14331
- }
14332
- if (!parts.path.startsWith("/")) return {
14333
- ok: false,
14334
- reason: "path-not-absolute"
14335
- };
14336
- const query = parts.query ?? {};
14337
- for (const key of Object.keys(query)) if (CREDENTIAL_QUERY_KEYS.includes(key.toLowerCase())) return {
14338
- ok: false,
14339
- reason: "credential-query-key"
14340
- };
14341
- const authority = parts.port === null || parts.port === defaultPortFor(parts.scheme) ? host : `${host}:${String(parts.port)}`;
14342
- const search = new URLSearchParams();
14343
- for (const [key, value] of Object.entries(query)) search.append(key, value);
14344
- const suffix = search.size > 0 ? `?${search.toString()}` : "";
14345
- const url = `${parts.scheme}://${authority}${parts.path}${suffix}`;
14346
- if (CREDENTIAL_URL.test(url)) return {
14347
- ok: false,
14348
- reason: "userinfo-in-result"
14349
- };
14350
- return {
14351
- ok: true,
14352
- url
14353
- };
14354
- }
14355
- /**
14356
14293
  * `device-export` — collection cap for addons that export camstack
14357
14294
  * devices to external ecosystems (HomeAssistant via MQTT discovery,
14358
14295
  * HomeKit/HAP, Alexa Smart Home, …).
@@ -24775,6 +24712,87 @@ method(_void(), ProviderInfoSchema, { auth: "admin" }), method(object({ config:
24775
24712
  kind: "mutation",
24776
24713
  auth: "admin"
24777
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
+ };
24778
24796
  /** Profile-exported FormBuilder schema. Shape is ConfigUISchema at the UI. */
24779
24797
  var ProfileSettingsSchemaBridge = unknown().nullable();
24780
24798
  var ProfileSettingsBagSchema = record(string(), unknown());
@@ -25347,6 +25365,7 @@ _enum([
25347
25365
  "sleeping",
25348
25366
  "camera-refused",
25349
25367
  "no-keyframe",
25368
+ "decode-failed",
25350
25369
  "no-catalog-row",
25351
25370
  "unsupported",
25352
25371
  "unknown-device",
@@ -25650,12 +25669,37 @@ var ClipWakeSchema = _enum(["authorised"]);
25650
25669
  * the size in the message, never truncates. Half a video is worse than an
25651
25670
  * honest refusal.
25652
25671
  *
25653
- * The clean follow-on is a CHUNKED read so a `high` twin of a long clip stops
25654
- * being refusable at all. That is a later slice, named here so the bound is
25655
- * not mistaken for a design ceiling.
25672
+ * **Superseded as the way a clip export gets its bytes** (D613). The bound is
25673
+ * a property of the ENVELOPE, not of clips, so the cure was a transport with
25674
+ * no envelope: {@link videoclipsCapability.methods.offerClipBytes} hands back
25675
+ * a one-shot `peerBytes` ticket and the consumer streams it straight to disk,
25676
+ * holding nothing. This method stays for a consumer that genuinely wants the
25677
+ * bytes in hand, and for a provider not yet redeployed — with this bound,
25678
+ * which for an inline read is not going to move.
25656
25679
  */
25657
25680
  var VIDEOCLIPS_MAX_READ_BYTES = 50 * 1024 * 1024;
25658
25681
  /**
25682
+ * Hard ceiling on ONE {@link videoclipsCapability.methods.offerClipBytes}
25683
+ * transfer — ten times {@link VIDEOCLIPS_MAX_READ_BYTES}, and the reasoning is
25684
+ * not "ten times more comfortable".
25685
+ *
25686
+ * The inline bound is set by what is HELD: a base64 envelope is the payload at
25687
+ * ~1.33× in the provider AND the same again in the caller, so 50 MiB of clip
25688
+ * is ~133 MiB of heap across two processes. Over `peerBytes` the consumer
25689
+ * holds one socket chunk at a time and writes straight through to the export
25690
+ * file, so its contribution is flat whatever the clip weighs. What is left is
25691
+ * the PRODUCER's own copy, and that is a property of how each provider makes a
25692
+ * clip rather than of this transport: Hikvision's fetch writes to a scratch
25693
+ * FILE and offers it (nothing is held), Reolink's cmd-5 transfer is collected
25694
+ * in memory and offered from there (one copy, the one it already had).
25695
+ *
25696
+ * So this number bounds the worst provider, not the transport, and it is named
25697
+ * separately so that lifting it is a statement about a provider rather than
25698
+ * about clips. Above it the provider REFUSES with the size in the message and
25699
+ * never truncates: half a video is worse than an honest refusal.
25700
+ */
25701
+ var VIDEOCLIPS_MAX_OFFER_BYTES = 500 * 1024 * 1024;
25702
+ /**
25659
25703
  * A clip's finished bytes, inline — the twin of `recordingExport.readExportBytes`.
25660
25704
  *
25661
25705
  * `bytes` is the DECODED length, so nobody infers it from the base64 length,
@@ -25687,6 +25731,32 @@ var ClipBytesSchema = object({
25687
25731
  durationMs: number().positive().optional()
25688
25732
  });
25689
25733
  /**
25734
+ * Where a clip's finished bytes can be TAKEN (D613) — the answer to
25735
+ * {@link videoclipsCapability.methods.offerClipBytes}.
25736
+ *
25737
+ * Everything {@link ClipBytesSchema} carries except the bytes themselves, plus
25738
+ * the one-shot ticket that leads to them. The metadata is answered BEFORE the
25739
+ * transfer on purpose: a consumer learns which twin it got, what to call the
25740
+ * file and how long the clip runs without having to read a byte, so a decision
25741
+ * it would make on that metadata (a wrong twin, an implausible duration) costs
25742
+ * no transfer at all.
25743
+ */
25744
+ var ClipBytesOfferSchema = object({
25745
+ /**
25746
+ * One shot, seconds-long, loopback, on the PROVIDER's own host. Open it with
25747
+ * `ctx.peerBytes.open(...)`, which refuses a ticket from another node by
25748
+ * name rather than dialling a port that means something else here.
25749
+ */
25750
+ ticket: PeerBytesTicketSchema,
25751
+ contentType: string(),
25752
+ /** Suggested filename, extension included. */
25753
+ name: string(),
25754
+ /** Which twin was actually served — see {@link ClipBytesSchema.served}. */
25755
+ served: CamProfileSchema,
25756
+ /** See {@link ClipBytesSchema.durationMs}. Absent when nothing measured it. */
25757
+ durationMs: number().positive().optional()
25758
+ });
25759
+ /**
25690
25760
  * Where a clip's STREAM can be dialled (D597) — the answer to
25691
25761
  * {@link videoclipsCapability.methods.dialClipStream}.
25692
25762
  *
@@ -25762,6 +25832,152 @@ var ClipStreamDialSchema = object({
25762
25832
  /** Why `servedAudio` is `none` although sound was asked for. */
25763
25833
  audioReason: ClipStreamAudioReasonSchema.optional()
25764
25834
  });
25835
+ /**
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.
25839
+ *
25840
+ * These are the BROKER's: it re-paces frames it has already demuxed — the
25841
+ * `MonotonicClock` divides source elapsed time by the factor and the pacer
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}).
25874
+ */
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 = [
25904
+ .25,
25905
+ .5,
25906
+ 1,
25907
+ 1.5,
25908
+ 2,
25909
+ 4
25910
+ ];
25911
+ /**
25912
+ * The rates a REALTIME-BOUND stream can be delivered at.
25913
+ *
25914
+ * **Measured, and it is the whole reason this second ladder exists.** A
25915
+ * Hikvision RTSP replay is not a fast fetch: it delivers the recording at the
25916
+ * speed it was recorded. On 1436, 2026-09-23, one stream carried 176 access
25917
+ * units in 14 274 ms of wall clock at a measured 12.5 fps — 14.08 s of media
25918
+ * in 14.27 s, **1.01× realtime** — and a whole 18 s clip took 22.3 s to fetch
25919
+ * end to end. Reolink's cmd-5 transfer, which {@link CLIP_BROKER_PACED_RATES}
25920
+ * was written for, lands the same bytes at 49–62× and therefore has the entire
25921
+ * clip in hand within the first second.
25922
+ *
25923
+ * The broker's pacer consumes `rate` seconds of media per second of wall
25924
+ * clock while the socket supplies one. So at any rate above 1 the buffer
25925
+ * drains at `(rate − 1)×` and a stream that is only seconds old runs dry
25926
+ * almost at once — the viewer stops, the queue empties, and the provider's
25927
+ * own drain gate eventually reports `peer-stalled`. Nothing about that is a
25928
+ * bug to be fixed with a bigger buffer: there is no buffer, because the bytes
25929
+ * do not exist yet.
25930
+ *
25931
+ * So the honest answer is the DECLARATION (D612's own rule, applied to the
25932
+ * case it did not yet have): a rate this transport cannot deliver is never
25933
+ * offered. Below 1 is free — a slower pacer only lets the buffer grow.
25934
+ *
25935
+ * When a clip is served from a FILE the constraint is gone with the transport,
25936
+ * which is why `file` keeps the full ladder.
25937
+ */
25938
+ var CLIP_REALTIME_SOURCE_RATES = [
25939
+ .25,
25940
+ .5,
25941
+ 1
25942
+ ];
25943
+ /**
25944
+ * What a surface may DRAW for this provider's clips — the answer to
25945
+ * {@link videoclipsCapability.methods.getPlaybackOptions} (D612).
25946
+ *
25947
+ * The envelope is a PROVIDER fact, not a clip fact, and that is measured, not
25948
+ * assumed: the broker's `chooseClipPath` reads exactly two inputs — whether
25949
+ * `dialClipStream` and `readClipBytes` are wired — and both are constants of
25950
+ * the broker's own closure over the provider's methods. The `profile` it is
25951
+ * handed is explicitly not read. So every clip of a provider is served the
25952
+ * same way, and a per-clip channel carried a value that could not vary. The
25953
+ * per-clip `clipTransport` server message was removed for exactly that reason.
25954
+ *
25955
+ * Queried per camera, before a clip is picked, so a control is rendered or
25956
+ * DISABLED rather than offered and refused at play time (D62: a disabled
25957
+ * control reads as unavailable, one that undoes the gesture reads as broken).
25958
+ */
25959
+ var ClipPlaybackOptionsSchema = object({
25960
+ /**
25961
+ * How this provider's clips reach the player. `stream` is the provider's
25962
+ * forward-only fMP4 (D597); `file` is one bounded by-handle fetch of the
25963
+ * whole clip, `stbl` indexed (D575).
25964
+ */
25965
+ transport: _enum(["stream", "file"]),
25966
+ /** `forward` = only ahead of the playhead. `free` = anywhere. */
25967
+ seek: _enum(["forward", "free"]),
25968
+ /** Frame-step BACKWARD is meaningful. Forward always is. */
25969
+ stepBack: boolean(),
25970
+ /** Whether the scrub gesture is served, as opposed to refused by name. */
25971
+ scrub: boolean(),
25972
+ /**
25973
+ * The rates that can be delivered, ascending, always containing `1`. The
25974
+ * viewer draws its picker from this and from nothing else — a constant it
25975
+ * keeps instead is the second authority that produced the defect: `8` and
25976
+ * `16` were offered, the broker clamped them to `4`, and no line anywhere
25977
+ * said so. `0` is not a member: pause is the absence of a rate.
25978
+ */
25979
+ rates: array(number().positive()).min(1).readonly()
25980
+ });
25765
25981
  var ClipSourceAvailabilitySchema = object({
25766
25982
  state: _enum([
25767
25983
  "ok",
@@ -25940,14 +26156,18 @@ var videoclipsCapability = {
25940
26156
  *
25941
26157
  * `getClipPlayback` is the right answer for a player: it hands back a URL
25942
26158
  * on a plane the hub serves `access:'authenticated'`, which a browser and a
25943
- * viewer session satisfy. It is the wrong answer for another ADDON. There
25944
- * is no addon→addon byte transport in this framework — `AddonDataPlane`
25945
- * only lets an addon SERVE, on `127.0.0.1` behind a per-listener secret
25946
- * only the hub may present — so a recorder that wants a camera's clip
25947
- * cannot fetch that URL. This method is the one seam that exists for it,
25948
- * and it is deliberately the same shape (and the same bound) as
25949
- * `recordingExport.readExportBytes`, which exists for the mirror-image
25950
- * reason.
26159
+ * viewer session satisfy. It is the wrong answer for another ADDON: the
26160
+ * hub's proxy in front of that plane takes only a user credential, which
26161
+ * an addon does not hold, so a recorder that wants a camera's clip cannot
26162
+ * fetch that URL. This method is the shape that answer forced — the same
26163
+ * one (and the same bound) as `recordingExport.readExportBytes`.
26164
+ *
26165
+ * **It is no longer the only seam.** Until D613 there was no addon→addon
26166
+ * byte transport at all; there is now
26167
+ * ({@link offerClipBytes}, over `ctx.peerBytes`), it holds nothing on
26168
+ * either side, and it is what a clip EXPORT uses. This method remains for
26169
+ * a consumer that genuinely wants the bytes in hand, and as the named
26170
+ * fallback for a provider not yet redeployed.
25951
26171
  *
25952
26172
  * Routing needs no `provider` pin: the id is source-prefixed and
25953
26173
  * self-contained, so `device-collection-dispatch.ts` rule 3 hands the call
@@ -26014,6 +26234,65 @@ var videoclipsCapability = {
26014
26234
  auth: "protected"
26015
26235
  }),
26016
26236
  /**
26237
+ * Where this clip's finished bytes can be TAKEN — the by-handle read a
26238
+ * clip EXPORT pulls, over the addon→addon byte transport (D613).
26239
+ *
26240
+ * This is {@link readClipBytes} with the envelope removed. Same gates,
26241
+ * same vocabulary, same completion rules, same `served` contract — the
26242
+ * only difference is that the bytes travel over a one-shot loopback
26243
+ * socket instead of inside a base64 field, so neither side holds the
26244
+ * payload whole and the 50 MiB refusal on a long `high` twin stops
26245
+ * existing. The bound that remains is
26246
+ * {@link VIDEOCLIPS_MAX_OFFER_BYTES}, and it bounds the PRODUCER's own
26247
+ * copy rather than the transport.
26248
+ *
26249
+ * **The ticket is loopback and same-host.** A provider on an agent mints a
26250
+ * URL that means nothing on the hub, and `ctx.peerBytes.open` refuses it
26251
+ * `cross-node` by name rather than dialling whatever else holds that port
26252
+ * here. A consumer that can be on the other side of a node boundary from
26253
+ * its provider must be able to read that refusal and say so; it must not
26254
+ * treat it as "no bytes".
26255
+ *
26256
+ * **A ticket is a one-shot bearer credential with a seconds-long life.**
26257
+ * Take it immediately, never persist it, never log its `url`. An untaken
26258
+ * ticket costs the provider one map entry until its TTL, and outstanding
26259
+ * tickets are bounded — which is also what makes a per-frame misuse of
26260
+ * this method refuse by name rather than work slowly (D9/D18: this is a
26261
+ * by-handle fetch of finished media, not a frame pipe).
26262
+ *
26263
+ * Optional on the provider for the same reason `readClipBytes` is: a
26264
+ * source with no camera socket behind it has no bytes. A provider that
26265
+ * predates this method answers `NOT_IMPLEMENTED`, and a consumer may fall
26266
+ * back to `readClipBytes` — but it says so in the log, with the deploy
26267
+ * hint, because that fallback re-imposes the 50 MiB refusal and an
26268
+ * operator who sees `too-large-to-transfer` after this shipped is looking
26269
+ * at a stale addon, not at a clip that cannot be exported.
26270
+ */
26271
+ offerClipBytes: optionalMethod(object({
26272
+ deviceId: number(),
26273
+ clipId: string().min(1),
26274
+ /** WHICH provider holds the bytes — see `readClipBytes.provider`. */
26275
+ provider: string().min(1),
26276
+ /** Which twin — `low | mid` → the sub file, `high` → the main twin. */
26277
+ profile: CamProfileSchema.optional(),
26278
+ /**
26279
+ * The CALLER's byte bound, so an over-size clip is refused before the
26280
+ * camera is touched rather than after. Capped by
26281
+ * {@link VIDEOCLIPS_MAX_OFFER_BYTES} whatever is passed; absent means
26282
+ * that ceiling.
26283
+ */
26284
+ maxBytes: number().int().positive().optional(),
26285
+ /**
26286
+ * The operator's authorisation to wake a sleeping camera for this
26287
+ * read. Absent — the default — means a sleeping standalone battery
26288
+ * camera is REFUSED by name, before any session is opened.
26289
+ */
26290
+ wake: ClipWakeSchema.optional()
26291
+ }), ClipBytesOfferSchema, {
26292
+ kind: "query",
26293
+ auth: "protected"
26294
+ }),
26295
+ /**
26017
26296
  * Where this clip's STREAM can be dialled (D597) — the forward-only
26018
26297
  * fMP4 the provider writes from the first muxed byte, for the broker to
26019
26298
  * play through the same WebRTC session as recorded footage, with the
@@ -26050,10 +26329,88 @@ var videoclipsCapability = {
26050
26329
  }), ClipStreamDialSchema, {
26051
26330
  kind: "query",
26052
26331
  auth: "protected"
26332
+ }),
26333
+ /**
26334
+ * What a surface may DRAW for this provider's clips: the rates it can be
26335
+ * played at, whether scrub is served, how far a position may be moved,
26336
+ * and whether a backward frame-step means anything (D612).
26337
+ *
26338
+ * **The only authority.** The per-clip `clipTransport` server message
26339
+ * that used to carry the same answer was removed: the broker's transport
26340
+ * choice reads nothing that varies per clip, so the clip level had no
26341
+ * information the provider does not already have, and two channels that
26342
+ * can disagree are worse than one (D62).
26343
+ *
26344
+ * Asked per camera and per provider, so it must stay CHEAP — it is a
26345
+ * statement about wiring, answered from a constant, never a call to the
26346
+ * camera. A provider answers with one of {@link CLIP_PLAYBACK_OPTIONS}
26347
+ * and never composes an envelope of its own.
26348
+ *
26349
+ * Optional, and absence is load-bearing: a provider that has not answered
26350
+ * has not restricted anything, and a viewer reads it as the freedom it
26351
+ * always had. See D612 on the rollout order that absence implies.
26352
+ */
26353
+ getPlaybackOptions: optionalMethod(object({
26354
+ deviceId: number(),
26355
+ /** WHICH provider to ask — the `addonId` a {@link ClipSourceSchema}
26356
+ * row carries. Required for the same reason `listClips` requires it:
26357
+ * a collection cap has no "the bound one" to resolve to (D554). */
26358
+ provider: string().min(1)
26359
+ }), ClipPlaybackOptionsSchema, {
26360
+ kind: "query",
26361
+ auth: "protected"
26053
26362
  })
26054
26363
  }
26055
26364
  };
26056
26365
  /**
26366
+ * NOTE ON PLACEMENT: this block lives AFTER the capability definition on
26367
+ * purpose. `scripts/lib/parse-cap.ts` finds a cap by the FIRST
26368
+ * `export const <X> = {` in the file, so an object literal declared above
26369
+ * `videoclipsCapability` is silently taken for the capability itself and
26370
+ * codegen emits a `DeviceProxy` entry that does not type-check. Found the
26371
+ * hard way, 2026-09-23.
26372
+ */
26373
+ /**
26374
+ * The two envelopes, spelled ONCE.
26375
+ *
26376
+ * A provider answers with the entry for the transport its own wiring buys —
26377
+ * `stream` if it implements `dialClipStream`, `file` if it implements only
26378
+ * `readClipBytes` — and never composes one of its own. One table is what
26379
+ * makes "the provider may not promise what no clip can be given" structural
26380
+ * instead of a discipline: there is nothing else to promise.
26381
+ */
26382
+ var CLIP_PLAYBACK_OPTIONS = {
26383
+ stream: {
26384
+ transport: "stream",
26385
+ seek: "forward",
26386
+ stepBack: false,
26387
+ scrub: false,
26388
+ rates: CLIP_STREAM_SOURCE_RATES
26389
+ },
26390
+ /**
26391
+ * A `stream` whose SOURCE runs at realtime — a Hikvision RTSP replay.
26392
+ *
26393
+ * Same verbs as `stream`, a shorter rate ladder, and the difference is a
26394
+ * measurement rather than a preference: see
26395
+ * {@link CLIP_REALTIME_SOURCE_RATES}. A third entry rather than a parameter,
26396
+ * because a provider must still be able to do nothing but NAME one of these.
26397
+ */
26398
+ realtimeStream: {
26399
+ transport: "stream",
26400
+ seek: "forward",
26401
+ stepBack: false,
26402
+ scrub: false,
26403
+ rates: CLIP_REALTIME_SOURCE_RATES
26404
+ },
26405
+ file: {
26406
+ transport: "file",
26407
+ seek: "free",
26408
+ stepBack: true,
26409
+ scrub: true,
26410
+ rates: CLIP_BROKER_PACED_RATES
26411
+ }
26412
+ };
26413
+ /**
26057
26414
  * Optional client-side hints sent at session creation to help the provider
26058
26415
  * pick the best native source. All fields optional — a viewer that knows
26059
26416
  * nothing still gets a sane default. (Relocated from the retired `webrtc`
@@ -27412,6 +27769,143 @@ DeviceType.Camera, method(object({ deviceId: number() }), CameraCredentialsSchem
27412
27769
  auth: "admin"
27413
27770
  });
27414
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
+ /**
27415
27909
  * Carbon-monoxide alarm sensor. Drives Home Assistant `binary_sensor`
27416
27910
  * entries with `device_class: carbon_monoxide`. Push-driven.
27417
27911
  */
@@ -28214,511 +28708,6 @@ var dayNightCapability = {
28214
28708
  volatileStateFields: ["lastFetchedAt"]
28215
28709
  };
28216
28710
  /**
28217
- * Vendor-neutral **onboard** recording + storage cap — what the CAMERA
28218
- * writes to the CAMERA's own card, on the camera's own schedule.
28219
- *
28220
- * This is NOT `recording.cap.ts`. That one is CamStack's recorder: our
28221
- * footage ledger, our storage locations, our retention. This one has a
28222
- * different authority — the camera's firmware — and per D62 it stores
28223
- * nothing of its own. Every value here is read from the camera and every
28224
- * write goes back to the camera; there is no CamStack-side mirror that
28225
- * could disagree with the device.
28226
- *
28227
- * ## One shape, two firmwares
28228
- *
28229
- * Measured 2026-09-22 against the live fleet:
28230
- *
28231
- * | fact | Hikvision (ISAPI) | Reolink (Baichuan) |
28232
- * | --- | --- | --- |
28233
- * | storage | `ContentMgmt/Storage` `<hdd>` rows: status, capacity, freeSpace (MB) | `getHddInfoList` (cmd 102): `mount`, `format`, `capacity` GB + `capacityM` MB remainder |
28234
- * | tracks | several (101 **and** 103 on both 1436 and 3833), each with its own schedule | one per channel |
28235
- * | schedule | per track, 7 `ScheduleAction` blocks: DayOfWeek + TimeOfDay range + ONE `ActionRecordingMode` | per trigger type, a 168-char weekly HOUR mask |
28236
- * | triggers | `CMR`, `MOTION` | `Normal`, `MD`, `people`, `vehicle`, `dog_cat`, `crossline`, `intrude`, `loitering` |
28237
- * | pre-record | `PreRecordTimeSeconds` | `preRecordTime` |
28238
- * | post-record | `PostRecordTimeSeconds` | `recordDelayTime` |
28239
- * | overwrite | per track `LoopEnable` | `cycle`, with `cycleList` enumerating the accepted values |
28240
- * | segment length | not exposed on V5.7.1 | `packageTime` (minutes) |
28241
- *
28242
- * The two schedule models look different and are the same thing in
28243
- * different coordinates: both answer "for this trigger, during which
28244
- * weekly windows does the camera record". {@link RecordWindow} is that
28245
- * question in one shape — Hikvision's ranges map straight onto it,
28246
- * Reolink's mask expands into hour-aligned windows.
28247
- *
28248
- * ## Union, not intersection
28249
- *
28250
- * **The same fields exist on every camera.** What differs per device is
28251
- * which VALUES that device accepts, and that is what {@link
28252
- * RecordingOnboardOptions} reports — a `{ readable, writable, reason }`
28253
- * per field plus the schedule's own limits. A control a camera cannot
28254
- * honour is rendered DISABLED WITH ITS REASON, never missing and never
28255
- * dead: disabled must not look like broken.
28256
- *
28257
- * ## Refusal by name
28258
- *
28259
- * A write a camera cannot honour is refused with a sentence the operator
28260
- * can read — never accepted and dropped. Both providers refuse through
28261
- * {@link describeOnboardRefusal}, so the vocabulary is one function and
28262
- * one test, not two hand-written vendor opinions.
28263
- *
28264
- * Follows the D14 `deviceConfig` archetype (see `stream-params.cap.ts`):
28265
- * `getOptions` advertises per-camera availability, `getStatus` (auto-
28266
- * injected from `status`) reports the live values, and a single
28267
- * `setSettings` mutation applies a partial change. No hand-written
28268
- * settings-contribution methods.
28269
- */
28270
- /**
28271
- * What makes the camera start recording during a window.
28272
- *
28273
- * The union of both vendors' vocabularies. `continuous` is Hikvision's
28274
- * `CMR` and Reolink's `Normal`; `motion` is `MOTION` / `MD`. The
28275
- * object-class triggers are Reolink-only today and the smart-event ones
28276
- * (`lineCrossing`, `intrusion`, `loitering`) are Reolink-only on the
28277
- * firmwares measured — a camera that cannot record on a trigger simply
28278
- * does not list it in `options.schedule.triggers`, and a window naming
28279
- * it is REFUSED, not dropped.
28280
- */
28281
- var RecordTriggerSchema = _enum([
28282
- "continuous",
28283
- "motion",
28284
- "person",
28285
- "vehicle",
28286
- "animal",
28287
- "lineCrossing",
28288
- "intrusion",
28289
- "loitering",
28290
- "alarmInput"
28291
- ]);
28292
- /**
28293
- * One weekly recording window: "on `day`, from `startMinute` to
28294
- * `endMinute`, record on `trigger`".
28295
- *
28296
- * `day` is 0 = Monday … 6 = Sunday (ISO order, which is also the order
28297
- * both firmwares enumerate). Minutes are local camera time since
28298
- * midnight; `endMinute` may be 1440, meaning end of day — that is
28299
- * Hikvision's literal `24:00` and Reolink's 24th mask slot, and
28300
- * collapsing it to 0 would turn a whole-day window into an empty one.
28301
- */
28302
- var RecordWindowSchema = object({
28303
- trigger: RecordTriggerSchema,
28304
- day: number().int().min(0).max(6),
28305
- startMinute: number().int().min(0).max(1439),
28306
- endMinute: number().int().min(1).max(1440)
28307
- });
28308
- /** Status of one physical volume, as the camera itself describes it. */
28309
- var OnboardStorageVolumeSchema = object({
28310
- /** The camera's own id for the volume (`hdd/id`, Reolink `HddInfo/number`). */
28311
- id: string(),
28312
- /** The camera's own name for it, when it gives one (`hddName`). */
28313
- label: string().optional(),
28314
- status: _enum([
28315
- "ok",
28316
- "unformatted",
28317
- "error",
28318
- "offline",
28319
- "unknown"
28320
- ]),
28321
- /**
28322
- * Total size in MB, or **null when the camera did not say**.
28323
- *
28324
- * Never 0 for an unreadable value: a measurement that failed is not a
28325
- * measurement (D393), and a card whose size is unknown must not be
28326
- * rendered as a card of size zero.
28327
- */
28328
- capacityMb: number().nullable(),
28329
- /**
28330
- * Free space in MB, or null when unknown.
28331
- *
28332
- * **Not a proxy for "has footage".** Measured 2026-09-22: 1436 and
28333
- * 1439 both report exactly 11776 MB free — the fixed reserve a looping
28334
- * card converges on once it has wrapped. At loop steady state the
28335
- * number is identical whether the camera recorded yesterday or stopped
28336
- * a month ago.
28337
- */
28338
- freeMb: number().nullable(),
28339
- /** True when the camera reports the volume writable (`property` RW). */
28340
- writable: boolean().optional()
28341
- });
28342
- /**
28343
- * What the camera is doing with its own storage, right now.
28344
- *
28345
- * Every scalar is nullable and **null means the camera did not answer**,
28346
- * never a default. A form that seeds `0` from an unanswered read invites
28347
- * the operator to save that 0 back onto the camera.
28348
- */
28349
- var RecordingOnboardStatusSchema = object({
28350
- storage: discriminatedUnion("kind", [
28351
- object({
28352
- kind: literal("present"),
28353
- volumes: array(OnboardStorageVolumeSchema)
28354
- }),
28355
- object({
28356
- kind: literal("absent"),
28357
- reason: string()
28358
- }),
28359
- object({
28360
- kind: literal("unknown"),
28361
- reason: string()
28362
- })
28363
- ]),
28364
- tracks: array(object({
28365
- id: string(),
28366
- enabled: boolean(),
28367
- isVideo: boolean(),
28368
- /** From the camera's own track description. Null when it does not say. */
28369
- codec: string().nullable(),
28370
- resolution: string().nullable(),
28371
- /** Per-track overwrite flag, where the firmware keeps it per track. */
28372
- overwriteWhenFull: boolean().nullable()
28373
- })),
28374
- /**
28375
- * The track the write path targets — the enabled VIDEO one. Null when
28376
- * no track could be identified, which is itself a refusal reason.
28377
- */
28378
- primaryTrackId: string().nullable(),
28379
- /** Master "record to the card at all" switch. */
28380
- enabled: boolean().nullable(),
28381
- overwriteWhenFull: boolean().nullable(),
28382
- preRecordSec: number().nullable(),
28383
- postRecordSec: number().nullable(),
28384
- /** Length of one recorded file, in minutes. */
28385
- segmentMinutes: number().nullable(),
28386
- /** The primary track's weekly windows, flattened. */
28387
- windows: array(RecordWindowSchema),
28388
- /**
28389
- * How many windows the camera described that CamStack could NOT read —
28390
- * an unrecognised trigger, an unparseable clock, a weekday it does not
28391
- * name.
28392
- *
28393
- * A dropped window is work the reader threw away, and a schedule that
28394
- * silently shows fewer rows than the camera holds is how an operator
28395
- * saves back a schedule shorter than the one they were looking at
28396
- * (D391). Non-zero means the window list is INCOMPLETE and a write
28397
- * that replaces it would delete what was not shown — which is why a
28398
- * provider reporting a non-zero count also reports the schedule as not
28399
- * writable.
28400
- */
28401
- unreadableWindows: number(),
28402
- /**
28403
- * The camera is scheduled to record and has NO usable storage.
28404
- *
28405
- * A first-class fact because it is the fleet's most common silent
28406
- * defect: measured 2026-09-22, 1441 and 3831 are both motion-recording
28407
- * to a card that is not there. Neither the schedule nor the storage
28408
- * read says anything wrong on its own; only the pair does.
28409
- */
28410
- recordingToNowhere: boolean(),
28411
- lastFetchedAt: number()
28412
- });
28413
- /** Numeric range descriptor — `{ min, max, step }` per the getOptions convention. */
28414
- var RangeSchema = object({
28415
- min: number(),
28416
- max: number(),
28417
- step: number()
28418
- });
28419
- /**
28420
- * The values a camera actually takes for a numeric field, when they are a SET
28421
- * rather than a range.
28422
- *
28423
- * `{min,max,step}` cannot say what these two firmwares do. Measured on 1436
28424
- * (I91DN) on 2026-09-22 by writing each value and reading it back:
28425
- *
28426
- * - pre-record: `0, 5, 10, 15, 20, 25, 30` and `2147483647` (INT32_MAX, the
28427
- * camera's "no limit" — `-1` and `4294967295` both land on it);
28428
- * - post-record: `5, 10, 30, 60, 120, 300, 600`.
28429
- *
28430
- * Neither is expressible as a step: the first has a sentinel two billion away
28431
- * from its neighbours, the second doubles and then jumps. A range that tried
28432
- * would forbid values the camera takes AND permit values it silently replaces
28433
- * with 5 — wrong in both directions at once.
28434
- *
28435
- * `sentinel` names the member that is not a duration, so a surface can render
28436
- * "no limit" instead of `2147483647` seconds.
28437
- */
28438
- var AllowedValuesSchema = object({
28439
- values: array(number()).min(1),
28440
- sentinel: object({
28441
- value: number(),
28442
- meaning: _enum(["no-limit", "disabled"])
28443
- }).optional()
28444
- });
28445
- /**
28446
- * Per-field availability on ONE camera.
28447
- *
28448
- * The field exists on every camera — this says whether this one can be
28449
- * read and whether it can be written, and `reason` says why not when
28450
- * either is false. The UI renders the control DISABLED with the reason
28451
- * rather than hiding it, so a limitation is legible instead of looking
28452
- * like a missing feature.
28453
- */
28454
- var OnboardFieldSupportSchema = object({
28455
- readable: boolean(),
28456
- writable: boolean(),
28457
- /** Required whenever `readable` or `writable` is false. */
28458
- reason: string().optional()
28459
- });
28460
- /** What this camera's schedule model can express. */
28461
- var OnboardScheduleSupportSchema = object({
28462
- support: OnboardFieldSupportSchema,
28463
- /**
28464
- * The smallest time step the camera can express, in minutes.
28465
- *
28466
- * Hikvision takes arbitrary minutes (`00:05:00`–`23:57:00` observed on
28467
- * 1436's track 103). Reolink's schedule is a 7×24 HOUR mask, so 60. A
28468
- * window whose edges are not a multiple of this is REFUSED rather than
28469
- * quietly rounded — rounding is how an operator's 06:30 becomes 06:00
28470
- * and nothing says so.
28471
- */
28472
- granularityMinutes: number(),
28473
- /** Triggers this camera can record on. A window naming another is refused. */
28474
- triggers: array(RecordTriggerSchema),
28475
- /**
28476
- * False when the camera stores ONE trigger per time range, so two
28477
- * windows overlapping on the same day cannot carry different triggers.
28478
- * True on Reolink, whose mask is per-trigger and independent.
28479
- */
28480
- supportsOverlappingTriggers: boolean()
28481
- });
28482
- var RecordingOnboardOptionsSchema = object({
28483
- enabled: OnboardFieldSupportSchema,
28484
- overwriteWhenFull: OnboardFieldSupportSchema,
28485
- preRecordSec: OnboardFieldSupportSchema,
28486
- preRecordSecRange: RangeSchema.optional(),
28487
- /** Preferred over the range when the camera takes a SET, not a span. */
28488
- preRecordSecAllowed: AllowedValuesSchema.optional(),
28489
- postRecordSec: OnboardFieldSupportSchema,
28490
- postRecordSecRange: RangeSchema.optional(),
28491
- /** Preferred over the range when the camera takes a SET, not a span. */
28492
- postRecordSecAllowed: AllowedValuesSchema.optional(),
28493
- segmentMinutes: OnboardFieldSupportSchema,
28494
- segmentMinutesRange: RangeSchema.optional(),
28495
- /** Preferred over the range when the camera takes a SET, not a span. */
28496
- segmentMinutesAllowed: AllowedValuesSchema.optional(),
28497
- schedule: OnboardScheduleSupportSchema
28498
- });
28499
- /**
28500
- * A partial change. Every field optional.
28501
- *
28502
- * Unlike the other `deviceConfig` caps, a provider here does **NOT**
28503
- * silently ignore a field it cannot support — it refuses, by name,
28504
- * through {@link describeOnboardRefusal}. Silence on a recording setting
28505
- * is the failure D62 exists to prevent: the operator believes the camera
28506
- * is recording the way the form says, and it is not.
28507
- */
28508
- var RecordingOnboardPatchSchema = object({
28509
- enabled: boolean().optional(),
28510
- overwriteWhenFull: boolean().optional(),
28511
- preRecordSec: number().optional(),
28512
- postRecordSec: number().optional(),
28513
- segmentMinutes: number().optional(),
28514
- /** The complete new window set for the primary track — not a delta. */
28515
- windows: array(RecordWindowSchema).optional()
28516
- });
28517
- var recordingOnboardCapability = {
28518
- name: "recording-onboard",
28519
- scope: "device",
28520
- deviceNative: true,
28521
- mode: "singleton",
28522
- deviceTypes: [DeviceType.Camera],
28523
- deviceConfig: { ui: {
28524
- kind: "derived-form",
28525
- builderId: "recording-onboard",
28526
- tab: "recording"
28527
- } },
28528
- methods: {
28529
- getOptions: method(object({ deviceId: number() }), RecordingOnboardOptionsSchema),
28530
- setSettings: method(object({
28531
- deviceId: number(),
28532
- settings: RecordingOnboardPatchSchema
28533
- }), _void(), {
28534
- kind: "mutation",
28535
- auth: "admin"
28536
- })
28537
- },
28538
- status: {
28539
- schema: RecordingOnboardStatusSchema,
28540
- kind: "poll"
28541
- },
28542
- runtimeState: RecordingOnboardStatusSchema,
28543
- /**
28544
- * Runtime-state durability: **restored** — operator-set camera-side
28545
- * recording config; mutation-driven, and the storage half is the last
28546
- * thing the camera said about its own card.
28547
- *
28548
- * See `RuntimeStateDurability`. Enforced by
28549
- * `scripts/check-runtime-state-durability.ts`.
28550
- */
28551
- durability: "restored",
28552
- /** Clock fields: written, but excluded from the compare that decides
28553
- * whether persisting is worth a SQLite commit. */
28554
- volatileStateFields: ["lastFetchedAt"]
28555
- };
28556
- /**
28557
- * Day-of-week names in the cap's index order (0 = Monday), for messages
28558
- * an operator reads and for Hikvision's `<DayOfWeek>` element.
28559
- */
28560
- var DAY_NAMES = [
28561
- "Monday",
28562
- "Tuesday",
28563
- "Wednesday",
28564
- "Thursday",
28565
- "Friday",
28566
- "Saturday",
28567
- "Sunday"
28568
- ];
28569
- /**
28570
- * Does `patch` ask this camera for something it cannot do?
28571
- *
28572
- * Returns the operator-readable reason, or `null` when every field in
28573
- * the patch is within what `options` says this camera accepts. A
28574
- * provider calls this BEFORE touching the camera and throws the string:
28575
- * refusing is the point, and refusing identically on both vendors is why
28576
- * this is one function.
28577
- *
28578
- * The order of checks is the order an operator would read them: the
28579
- * scalar knobs first, then the schedule, because a schedule complaint is
28580
- * longer and a scalar one is usually the real problem.
28581
- */
28582
- function describeOnboardRefusal(options, patch) {
28583
- if (patch.enabled !== void 0 && !options.enabled.writable) return unwritable("the master recording switch", options.enabled.reason);
28584
- if (patch.overwriteWhenFull !== void 0 && !options.overwriteWhenFull.writable) return unwritable("overwrite-when-full", options.overwriteWhenFull.reason);
28585
- const preRefusal = refuseNumeric("pre-record seconds", patch.preRecordSec, options.preRecordSec, options.preRecordSecRange, options.preRecordSecAllowed);
28586
- if (preRefusal) return preRefusal;
28587
- const postRefusal = refuseNumeric("post-record seconds", patch.postRecordSec, options.postRecordSec, options.postRecordSecRange, options.postRecordSecAllowed);
28588
- if (postRefusal) return postRefusal;
28589
- const segmentRefusal = refuseNumeric("segment length (minutes)", patch.segmentMinutes, options.segmentMinutes, options.segmentMinutesRange, options.segmentMinutesAllowed);
28590
- if (segmentRefusal) return segmentRefusal;
28591
- if (patch.windows !== void 0) {
28592
- const scheduleRefusal = refuseSchedule(options, patch.windows);
28593
- if (scheduleRefusal) return scheduleRefusal;
28594
- }
28595
- return null;
28596
- }
28597
- function unwritable(what, reason) {
28598
- return reason ? `this camera cannot change ${what}: ${reason}` : `this camera cannot change ${what}`;
28599
- }
28600
- function refuseNumeric(what, value, support, range, allowed) {
28601
- if (value === void 0) return null;
28602
- if (!support.writable) return unwritable(what, support.reason);
28603
- if (!Number.isFinite(value)) return `${what} must be a number, got ${String(value)}`;
28604
- if (allowed) {
28605
- if (allowed.values.includes(value)) return null;
28606
- const say = (v) => allowed.sentinel !== void 0 && v === allowed.sentinel.value ? allowed.sentinel.meaning === "no-limit" ? "no limit" : "off" : String(v);
28607
- return `this camera accepts ${what} only as ${allowed.values.map(say).join(", ")}; ${say(value)} is not one of them`;
28608
- }
28609
- if (!range) return null;
28610
- 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`;
28611
- 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`;
28612
- return null;
28613
- }
28614
- function refuseSchedule(options, windows) {
28615
- const schedule = options.schedule;
28616
- if (!schedule.support.writable) return unwritable("the recording schedule", schedule.support.reason);
28617
- const allowed = new Set(schedule.triggers);
28618
- for (const window of windows) {
28619
- if (!allowed.has(window.trigger)) {
28620
- const offer = schedule.triggers.length > 0 ? schedule.triggers.join(", ") : "none";
28621
- return `this camera cannot record on "${window.trigger}"; it records on: ${offer}`;
28622
- }
28623
- if (window.endMinute <= window.startMinute) return `a window on ${dayName(window.day)} ends at or before it starts (${String(window.startMinute)} → ${String(window.endMinute)})`;
28624
- const step = schedule.granularityMinutes;
28625
- 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`;
28626
- }
28627
- if (!schedule.supportsOverlappingTriggers) {
28628
- const clash = findOverlapWithDifferentTrigger(windows);
28629
- 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))}`;
28630
- }
28631
- return null;
28632
- }
28633
- function findOverlapWithDifferentTrigger(windows) {
28634
- for (let i = 0; i < windows.length; i += 1) for (let j = i + 1; j < windows.length; j += 1) {
28635
- const a = windows[i];
28636
- const b = windows[j];
28637
- if (!a || !b) continue;
28638
- if (a.day !== b.day) continue;
28639
- if (a.trigger === b.trigger) continue;
28640
- if (a.startMinute < b.endMinute && b.startMinute < a.endMinute) return {
28641
- a,
28642
- b
28643
- };
28644
- }
28645
- return null;
28646
- }
28647
- function dayName(day) {
28648
- return DAY_NAMES[day] ?? `day ${String(day)}`;
28649
- }
28650
- /** `510` → `08:30`. For messages, not for the wire. */
28651
- function formatMinutes(minute) {
28652
- const hour = Math.floor(minute / 60);
28653
- const rest = minute % 60;
28654
- return `${String(hour).padStart(2, "0")}:${String(rest).padStart(2, "0")}`;
28655
- }
28656
- /**
28657
- * Index of the mask character covering `day` at `hour`.
28658
- *
28659
- * **Layout: day-major, Monday first** — `day * 24 + hour`.
28660
- *
28661
- * This is an ASSUMPTION, and it is recorded as one because the fleet
28662
- * cannot currently confirm it: every `valueTable` on every Reolink
28663
- * measured on 2026-09-22 is uniform (all `1` or all `0`), and a uniform
28664
- * mask reads identically under either layout. To settle it, set a single
28665
- * hour on one day from the Reolink app and re-read `getRecordSchedule`.
28666
- * Until then, a NON-uniform mask is reported as windows under this
28667
- * layout and the day labels may be transposed; a uniform one is exact.
28668
- */
28669
- function weeklyMaskIndex(day, hour) {
28670
- return day * 24 + hour;
28671
- }
28672
- /**
28673
- * Expand one trigger's weekly hour mask into windows, merging adjacent
28674
- * set hours into one window per run so a full day is ONE window rather
28675
- * than twenty-four.
28676
- *
28677
- * A mask of the wrong length yields no windows: a truncated table is not
28678
- * a schedule of fewer days, it is an answer we did not understand.
28679
- */
28680
- function weeklyMaskToWindows(mask, trigger) {
28681
- if (mask.length !== 168) return [];
28682
- const out = [];
28683
- for (let day = 0; day < 7; day += 1) {
28684
- let runStart = null;
28685
- for (let hour = 0; hour <= 24; hour += 1) {
28686
- const set = hour < 24 && mask[weeklyMaskIndex(day, hour)] === "1";
28687
- if (set && runStart === null) runStart = hour;
28688
- else if (!set && runStart !== null) {
28689
- out.push({
28690
- trigger,
28691
- day,
28692
- startMinute: runStart * 60,
28693
- endMinute: hour * 60
28694
- });
28695
- runStart = null;
28696
- }
28697
- }
28698
- }
28699
- return out;
28700
- }
28701
- /**
28702
- * Collapse this trigger's windows back into a weekly hour mask.
28703
- *
28704
- * Windows for other triggers are ignored — the mask is per trigger. A
28705
- * window that is not hour-aligned is REFUSED upstream by
28706
- * {@link describeOnboardRefusal}; this function rounds nothing, it
28707
- * simply sets every hour the window fully or partly covers, so a caller
28708
- * that skipped the refusal cannot silently lose coverage.
28709
- */
28710
- function windowsToWeeklyMask(windows, trigger) {
28711
- const slots = new Array(168).fill("0");
28712
- for (const window of windows) {
28713
- if (window.trigger !== trigger) continue;
28714
- if (window.day < 0 || window.day >= 7) continue;
28715
- const firstHour = Math.floor(window.startMinute / 60);
28716
- const lastHour = Math.ceil(window.endMinute / 60);
28717
- for (let hour = firstHour; hour < lastHour && hour < 24; hour += 1) slots[weeklyMaskIndex(window.day, hour)] = "1";
28718
- }
28719
- return slots.join("");
28720
- }
28721
- /**
28722
28711
  * Generic device-level status snapshot. Auto-registered by `BaseDevice`
28723
28712
  * for every device, regardless of provider — the kernel needs a uniform
28724
28713
  * cap-keyed slice for the basic device flags every consumer expects to
@@ -28937,30 +28926,6 @@ var eventEmitterCapability = {
28937
28926
  */
28938
28927
  durability: "session"
28939
28928
  };
28940
- var EventItemSchema = object({
28941
- id: string(),
28942
- type: string(),
28943
- timestamp: number(),
28944
- label: string().optional(),
28945
- thumbnailUrl: string().optional(),
28946
- clipUrl: string().optional(),
28947
- metadata: record(string(), unknown()).optional()
28948
- });
28949
- DeviceType.Camera, method(object({
28950
- deviceId: number(),
28951
- from: number().optional(),
28952
- to: number().optional(),
28953
- limit: number().optional()
28954
- }), array(EventItemSchema)), method(object({
28955
- deviceId: number(),
28956
- eventId: string()
28957
- }), object({
28958
- base64: string(),
28959
- contentType: string()
28960
- }).nullable()), method(object({
28961
- deviceId: number(),
28962
- eventId: string()
28963
- }), string().nullable());
28964
28929
  var IdentitySchema = object({
28965
28930
  id: string(),
28966
28931
  name: string(),
@@ -31213,143 +31178,6 @@ var motionTriggerCapability = {
31213
31178
  durability: "session"
31214
31179
  };
31215
31180
  /**
31216
- * camera-grid-layout — the geometry of a COMPOSITE camera, on the camera's own
31217
- * page.
31218
- *
31219
- * ## Why this is a capability and not an addon settings schema
31220
- *
31221
- * It was one, and it did not render. The addon declared the editor as a
31222
- * `type: 'widget'` field inside its own `deviceSettingsSchema()`; the hub
31223
- * returned that section correctly and `ConfigFormField` renders `type:'widget'`
31224
- * perfectly well — and nothing ever asked camera-grid for it. The Cluster →
31225
- * Pipeline → Device Overrides page interrogates a HAND-WRITTEN list of four
31226
- * addons (`PIPELINE_CLUSTER_DEVICE_ADDONS`), whose own comment says an addon
31227
- * not on it "falls off silently".
31228
- *
31229
- * Adding a fifth name to that list would have been the wrong fix twice over:
31230
- * that page is per-camera DETECTION tuning, and a grid's geometry belongs
31231
- * beside PTZ and motion zones on the camera itself. The device page is
31232
- * BINDING-driven (D12), so the way in is a capability bound to the device —
31233
- * and this cap carries its section the way `recording` does, by RETURNING it
31234
- * from `getDeviceSettingsContribution`.
31235
- *
31236
- * Seven other widgets are still declared the other way, through a
31237
- * `deviceConfig.ui` block the framework derives a section from. That route
31238
- * gives the addon no say in where its own panel lands and no way to decline
31239
- * for a device the panel does not suit, which is why this one does not use it.
31240
- *
31241
- * ## Why one addon may implement it
31242
- *
31243
- * It is a device-scoped NATIVE cap, registered by the grid camera device
31244
- * itself. Nothing else declares a composite camera, so nothing else has a
31245
- * layout — and the device-scoped route means the widget asks THE camera, not
31246
- * "the camera-grid addon", which is what let the old custom-action pair be
31247
- * reached only by a caller that already knew the addon id.
31248
- *
31249
- * ## The tab
31250
- *
31251
- * `streaming`, not a top-tab of its own. A grid's geometry IS what its stream
31252
- * is, so the Streaming tab is where it belongs; a `grid` top-tab would need an
31253
- * entry in `WELL_KNOWN_TAB_MAP` or the device page renders the raw id as the
31254
- * label (measured on the robot camera, 2026-09-06 — a tab called "navigation"
31255
- * next to "PTZ").
31256
- */
31257
- /** A rectangle in normalized [0,1] coordinates of whatever contains it. */
31258
- var GridNormalizedRectSchema = object({
31259
- x: number().min(0).max(1),
31260
- y: number().min(0).max(1),
31261
- width: number().gt(0).max(1),
31262
- height: number().gt(0).max(1)
31263
- });
31264
- /**
31265
- * One source camera, the part of its picture taken, and where that part lands.
31266
- *
31267
- * Both rectangles are NORMALIZED (D519): a source camera can change resolution
31268
- * — a profile switch, a firmware update, a substream that comes back different
31269
- * — and a stored PIXEL rectangle would quietly start cutting the wrong region,
31270
- * which is the class of bug nobody files.
31271
- */
31272
- var GridLayoutCellSchema = object({
31273
- deviceId: number().int().positive(),
31274
- /** The part of the SOURCE taken, normalized against the source. */
31275
- source: GridNormalizedRectSchema,
31276
- /** Where it lands, normalized against the CANVAS. */
31277
- cell: GridNormalizedRectSchema
31278
- });
31279
- /**
31280
- * Which profiles this grid can actually compose, and why not.
31281
- *
31282
- * A grid's `high` composes its sources' `high` and its `low` their `low`, so a
31283
- * profile is on offer only when EVERY source can serve it. The refusal NAMES
31284
- * the sources, because "this grid has no low" is not a finding — "615 has no
31285
- * low" is, and it is the one an operator can act on.
31286
- */
31287
- var GridProfileOfferSchema = object({
31288
- profile: _enum([
31289
- "high",
31290
- "mid",
31291
- "low"
31292
- ]),
31293
- offered: boolean(),
31294
- /** Sources that cannot serve it. Empty when it is offered, or when there are no cells. */
31295
- missingSources: array(number().int().positive()),
31296
- /**
31297
- * The canvas this profile composes onto, `WxH`, or empty when it is not
31298
- * offered. DERIVED from the cells and the sources' own size at this profile —
31299
- * it is reported because nothing else in the system would ever say what the
31300
- * grid came out as, and because it is the number an operator would otherwise
31301
- * expect to type.
31302
- */
31303
- canvas: string(),
31304
- /**
31305
- * Whether this profile is PUBLISHED, of the ones the grid could serve.
31306
- *
31307
- * A grid's `high` is composed of its sources' `high`, so on a 4K fleet it is
31308
- * a 4K canvas built from 4K decodes — something to opt into, not something a
31309
- * viewer's adaptive should be handed by climbing to the top rung it can see.
31310
- * Default is `mid` + `low`.
31311
- */
31312
- published: boolean()
31313
- });
31314
- var GridLayoutViewSchema = object({
31315
- /** The persisted grid row this camera was declared from. */
31316
- instanceId: string(),
31317
- deviceId: number().int().nonnegative(),
31318
- name: string(),
31319
- /**
31320
- * NO canvas size. A grid's resolution is not authored: each profile derives
31321
- * its own from the cells and its sources' dimensions. The two numbers that
31322
- * used to be here were a text field that silently decided both how much the
31323
- * composite cost and how sharp it was — see `profiles[].canvas` for what it
31324
- * came out as.
31325
- */
31326
- fps: number().int(),
31327
- cells: array(GridLayoutCellSchema),
31328
- /** What the catalog will publish, and what it refuses to. Read-only. */
31329
- profiles: array(GridProfileOfferSchema)
31330
- });
31331
- var GridLayoutPatchSchema = object({
31332
- deviceId: number().int().nonnegative(),
31333
- name: string().min(1).max(160).optional(),
31334
- fps: number().int().min(1).max(60).optional(),
31335
- /** Which profiles to publish. See `GridProfileOffer.published`. */
31336
- publishedProfiles: array(_enum([
31337
- "high",
31338
- "mid",
31339
- "low"
31340
- ])).max(3).optional(),
31341
- /**
31342
- * The whole cell list at once. A per-cell patch would need an ordering the
31343
- * editor does not have, and a half-applied layout is a picture nobody asked
31344
- * for.
31345
- */
31346
- cells: array(GridLayoutCellSchema).max(16)
31347
- });
31348
- DeviceType.Camera, method(object({ deviceId: number().int().nonnegative() }), GridLayoutViewSchema.nullable(), { auth: "admin" }), method(GridLayoutPatchSchema, GridLayoutViewSchema, {
31349
- kind: "mutation",
31350
- auth: "admin"
31351
- });
31352
- /**
31353
31181
  * Motion-zones share the same MaskShape vocabulary as privacy-mask — the
31354
31182
  * on-camera motion-detection mask is a single `grid` region (a row-major
31355
31183
  * boolean cell lattice the camera's onboard VMD evaluates). Composing it as
@@ -33869,37 +33697,37 @@ var rebootCapability = {
33869
33697
  auth: "admin"
33870
33698
  }) }
33871
33699
  };
33872
- /**
33873
- * `recording` cap — footage availability + HLS playback manifests + per-device
33874
- * recording config. NOTE on events (source of truth, R5/C3): this cap carries
33875
- * NO event surface — `getPlaybackManifest` returns playlist URLs only. Timeline
33876
- * events (motion/object/audio) come from `pipelineAnalytics` (durable SQLite
33877
- * rows) and are the ONLY event surface — the recorder has none. The in-RAM
33878
- * playback markers it used to build were deleted on 2026-08-29 because nothing
33879
- * ever read them. Event<->footage joins are by time, padded with the shared
33880
- * `EVENT_PAD_MS` (`interfaces/recording-config.ts`).
33881
- */
33882
- var RecordingStatusSchema = object({
33883
- deviceId: number(),
33884
- enabled: boolean(),
33885
- /** THE derived storage mode, from the one definition
33886
- * (`deriveRecordingMode`) — never a second enum. A duplicated list is how
33887
- * `on-device-decision` could have reached the recorder and not the status. */
33888
- activeMode: RecordingStorageModeSchema,
33889
- nodeId: string(),
33890
- storageBytes: number()
33891
- });
33892
33700
  var RecordingRangeSchema = object({
33893
33701
  profile: string(),
33894
33702
  startMs: number(),
33895
33703
  endMs: number()
33896
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"]);
33897
33722
  var RecordingAvailabilitySchema = object({
33898
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,
33899
33727
  ranges: array(RecordingRangeSchema),
33900
33728
  /**
33901
- * Every profile this camera has footage in — not only the one `ranges`
33902
- * describes (D433).
33729
+ * Every profile this camera has footage in AT THIS SOURCE — not only the one
33730
+ * `ranges` describes (D433).
33903
33731
  *
33904
33732
  * `ranges` answers for ONE profile by design: the timeline is a single bar,
33905
33733
  * and enumerating all of them triples the directory reads for a bar that
@@ -33916,15 +33744,285 @@ var RecordingAvailabilitySchema = object({
33916
33744
  });
33917
33745
  var RecordingDaysSchema = object({
33918
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,
33919
33751
  /** Local-midnight epochs (UTC ms) of days that have ≥1 recorded segment. */
33920
33752
  days: array(number())
33921
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
+ });
33922
34020
  /**
33923
34021
  * One camera's row in a `getAvailabilityBatch` answer.
33924
34022
  *
33925
- * `ranges` is EXACTLY what `getAvailability` returns for that camera — the
33926
- * batch collapses the transport, not the work — plus the one thing the singular
33927
- * 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):
33928
34026
  *
33929
34027
  * - `read: 'read'` — answered. `ranges: []` means "read, and this camera has
33930
34028
  * no footage in the window", which is a real claim.
@@ -33956,22 +34054,6 @@ var RecordingDaysForDeviceSchema = object({
33956
34054
  /** Local-midnight epochs (UTC ms) of days that have ≥1 recorded segment. */
33957
34055
  days: array(number()).readonly()
33958
34056
  });
33959
- var RecordingManifestSchema = object({
33960
- deviceId: number(),
33961
- /** Local filesystem path to the master playlist; null when no recording exists for the requested range. */
33962
- localMasterPath: string().nullable(),
33963
- /** HTTP(S) URL to the master playlist on the recording node's playback server
33964
- * (the PRIMARY candidate); null when no recording / server. Carries the
33965
- * scoped playback token in its path. */
33966
- playbackUrl: string().nullable(),
33967
- /**
33968
- * Candidate master-playlist URLs the client tries in order (LAN first, then
33969
- * remote — Tailscale/Cloudflare if the operator configured extra hosts), each
33970
- * carrying the same scoped token. `playbackUrl` is the first entry. Empty when
33971
- * there is no recording / server.
33972
- */
33973
- playbackEndpoints: array(string())
33974
- });
33975
34057
  /**
33976
34058
  * Recording storage usage for one camera — what the ARCHIVE holds for it,
33977
34059
  * across every profile and every resolvable location on this node.
@@ -34230,34 +34312,12 @@ var ReadWindowBytesResultSchema = discriminatedUnion("kind", [object({
34230
34312
  segmentEndMs: number()
34231
34313
  })]);
34232
34314
  method(object({
34233
- deviceId: number(),
34234
- fromMs: number(),
34235
- toMs: number(),
34236
- /**
34237
- * Answer for THIS profile instead of the preferred one (D433). Absent
34238
- * keeps the timeline's behaviour — one bar, one profile, one set of
34239
- * reads. `profilesWithFootage` on the answer says what may be asked
34240
- * for.
34241
- */
34242
- profile: string().optional()
34243
- }), RecordingAvailabilitySchema, {
34244
- kind: "query",
34245
- auth: "protected"
34246
- }), method(object({
34247
34315
  deviceIds: array(number()).min(1).max(200),
34248
34316
  fromMs: number(),
34249
34317
  toMs: number()
34250
34318
  }), array(RecordingAvailabilityForDeviceSchema).readonly(), {
34251
34319
  kind: "query",
34252
34320
  auth: "protected"
34253
- }), method(object({
34254
- deviceId: number(),
34255
- fromMs: number(),
34256
- toMs: number(),
34257
- tzOffsetMinutes: number()
34258
- }), RecordingDaysSchema, {
34259
- kind: "query",
34260
- auth: "protected"
34261
34321
  }), method(object({
34262
34322
  deviceIds: array(number()).min(1).max(200),
34263
34323
  fromMs: number(),
@@ -34266,13 +34326,6 @@ method(object({
34266
34326
  }), array(RecordingDaysForDeviceSchema).readonly(), {
34267
34327
  kind: "query",
34268
34328
  auth: "protected"
34269
- }), method(object({
34270
- deviceId: number(),
34271
- fromMs: number(),
34272
- toMs: number()
34273
- }), RecordingManifestSchema, {
34274
- kind: "query",
34275
- auth: "protected"
34276
34329
  }), method(object({}), RecordingStorageUsageSchema, {
34277
34330
  kind: "query",
34278
34331
  auth: "admin"
@@ -34724,6 +34777,511 @@ method(object({
34724
34777
  auth: "protected"
34725
34778
  });
34726
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
+ /**
34727
35285
  * A camera's own "record me NOW" LEVEL — a signal the device raises while
34728
35286
  * something it knows about is happening (a robot vacuum cleaning, a machine
34729
35287
  * running, a gate open) and lowers when it stops.
@@ -42560,24 +43118,6 @@ Object.freeze({
42560
43118
  addonId: null,
42561
43119
  access: "view"
42562
43120
  },
42563
- "events.getEventClipUrl": {
42564
- capName: "events",
42565
- capScope: "device",
42566
- addonId: null,
42567
- access: "view"
42568
- },
42569
- "events.getEvents": {
42570
- capName: "events",
42571
- capScope: "device",
42572
- addonId: null,
42573
- access: "view"
42574
- },
42575
- "events.getEventThumbnail": {
42576
- capName: "events",
42577
- capScope: "device",
42578
- addonId: null,
42579
- access: "view"
42580
- },
42581
43121
  "faceGallery.assignFace": {
42582
43122
  capName: "face-gallery",
42583
43123
  capScope: "system",
@@ -45452,224 +45992,236 @@ Object.freeze({
45452
45992
  addonId: null,
45453
45993
  access: "create"
45454
45994
  },
45455
- "recording.applyDeviceSettingsPatch": {
45995
+ "recording.getAvailability": {
45456
45996
  capName: "recording",
45457
- capScope: "system",
45997
+ capScope: "device",
45458
45998
  addonId: null,
45459
- access: "create"
45999
+ access: "view"
45460
46000
  },
45461
- "recording.cancelRelocateJob": {
46001
+ "recording.getDaysWithRecordings": {
45462
46002
  capName: "recording",
45463
- capScope: "system",
46003
+ capScope: "device",
45464
46004
  addonId: null,
45465
- access: "create"
46005
+ access: "view"
45466
46006
  },
45467
- "recording.cancelStorageMigrationMove": {
46007
+ "recording.getPlayback": {
45468
46008
  capName: "recording",
45469
- capScope: "system",
46009
+ capScope: "device",
45470
46010
  addonId: null,
45471
- access: "create"
46011
+ access: "view"
45472
46012
  },
45473
- "recording.deleteFootprint": {
46013
+ "recording.getPlaybackOptions": {
45474
46014
  capName: "recording",
45475
- capScope: "system",
46015
+ capScope: "device",
45476
46016
  addonId: null,
45477
- access: "delete"
46017
+ access: "view"
45478
46018
  },
45479
- "recording.getAvailability": {
46019
+ "recording.listSources": {
45480
46020
  capName: "recording",
45481
- capScope: "system",
46021
+ capScope: "device",
45482
46022
  addonId: null,
45483
46023
  access: "view"
45484
46024
  },
45485
- "recording.getAvailabilityBatch": {
45486
- capName: "recording",
46025
+ "recordingArchive.applyDeviceSettingsPatch": {
46026
+ capName: "recording-archive",
45487
46027
  capScope: "system",
45488
46028
  addonId: null,
45489
- access: "view"
46029
+ access: "create"
45490
46030
  },
45491
- "recording.getDaysWithRecordings": {
45492
- capName: "recording",
46031
+ "recordingArchive.cancelRelocateJob": {
46032
+ capName: "recording-archive",
45493
46033
  capScope: "system",
45494
46034
  addonId: null,
45495
- access: "view"
46035
+ access: "create"
45496
46036
  },
45497
- "recording.getDaysWithRecordingsBatch": {
45498
- 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",
45499
46051
  capScope: "system",
45500
46052
  addonId: null,
45501
46053
  access: "view"
45502
46054
  },
45503
- "recording.getDeviceConfig": {
45504
- capName: "recording",
46055
+ "recordingArchive.getDaysWithRecordingsBatch": {
46056
+ capName: "recording-archive",
45505
46057
  capScope: "system",
45506
46058
  addonId: null,
45507
46059
  access: "view"
45508
46060
  },
45509
- "recording.getDeviceLiveContribution": {
45510
- capName: "recording",
46061
+ "recordingArchive.getDeviceConfig": {
46062
+ capName: "recording-archive",
45511
46063
  capScope: "system",
45512
46064
  addonId: null,
45513
46065
  access: "view"
45514
46066
  },
45515
- "recording.getDeviceSettingsContribution": {
45516
- capName: "recording",
46067
+ "recordingArchive.getDeviceLiveContribution": {
46068
+ capName: "recording-archive",
45517
46069
  capScope: "system",
45518
46070
  addonId: null,
45519
46071
  access: "view"
45520
46072
  },
45521
- "recording.getPlacement": {
45522
- capName: "recording",
46073
+ "recordingArchive.getDeviceSettingsContribution": {
46074
+ capName: "recording-archive",
45523
46075
  capScope: "system",
45524
46076
  addonId: null,
45525
46077
  access: "view"
45526
46078
  },
45527
- "recording.getPlaybackManifest": {
45528
- capName: "recording",
46079
+ "recordingArchive.getPlacement": {
46080
+ capName: "recording-archive",
45529
46081
  capScope: "system",
45530
46082
  addonId: null,
45531
46083
  access: "view"
45532
46084
  },
45533
- "recording.getRelocateResidue": {
45534
- capName: "recording",
46085
+ "recordingArchive.getRelocateResidue": {
46086
+ capName: "recording-archive",
45535
46087
  capScope: "system",
45536
46088
  addonId: null,
45537
46089
  access: "view"
45538
46090
  },
45539
- "recording.getStatus": {
45540
- capName: "recording",
46091
+ "recordingArchive.getStatus": {
46092
+ capName: "recording-archive",
45541
46093
  capScope: "system",
45542
46094
  addonId: null,
45543
46095
  access: "view"
45544
46096
  },
45545
- "recording.getStorageMigrationMoveStatus": {
45546
- capName: "recording",
46097
+ "recordingArchive.getStorageMigrationMoveStatus": {
46098
+ capName: "recording-archive",
45547
46099
  capScope: "system",
45548
46100
  addonId: null,
45549
46101
  access: "view"
45550
46102
  },
45551
- "recording.getStorageUsage": {
45552
- capName: "recording",
46103
+ "recordingArchive.getStorageUsage": {
46104
+ capName: "recording-archive",
45553
46105
  capScope: "system",
45554
46106
  addonId: null,
45555
46107
  access: "view"
45556
46108
  },
45557
- "recording.listOpsLog": {
45558
- capName: "recording",
46109
+ "recordingArchive.listOpsLog": {
46110
+ capName: "recording-archive",
45559
46111
  capScope: "system",
45560
46112
  addonId: null,
45561
46113
  access: "view"
45562
46114
  },
45563
- "recording.listRelocateJobs": {
45564
- capName: "recording",
46115
+ "recordingArchive.listRelocateJobs": {
46116
+ capName: "recording-archive",
45565
46117
  capScope: "system",
45566
46118
  addonId: null,
45567
46119
  access: "view"
45568
46120
  },
45569
- "recording.locateSegment": {
45570
- capName: "recording",
46121
+ "recordingArchive.locateSegment": {
46122
+ capName: "recording-archive",
45571
46123
  capScope: "system",
45572
46124
  addonId: null,
45573
46125
  access: "view"
45574
46126
  },
45575
- "recording.pauseForStorageMigration": {
45576
- capName: "recording",
46127
+ "recordingArchive.pauseForStorageMigration": {
46128
+ capName: "recording-archive",
45577
46129
  capScope: "system",
45578
46130
  addonId: null,
45579
46131
  access: "create"
45580
46132
  },
45581
- "recording.planStorageRebalance": {
45582
- capName: "recording",
46133
+ "recordingArchive.planStorageRebalance": {
46134
+ capName: "recording-archive",
45583
46135
  capScope: "system",
45584
46136
  addonId: null,
45585
46137
  access: "view"
45586
46138
  },
45587
- "recording.pruneFootage": {
45588
- capName: "recording",
46139
+ "recordingArchive.pruneFootage": {
46140
+ capName: "recording-archive",
45589
46141
  capScope: "system",
45590
46142
  addonId: null,
45591
46143
  access: "create"
45592
46144
  },
45593
- "recording.readGopBytes": {
45594
- capName: "recording",
46145
+ "recordingArchive.readGopBytes": {
46146
+ capName: "recording-archive",
45595
46147
  capScope: "system",
45596
46148
  addonId: null,
45597
46149
  access: "view"
45598
46150
  },
45599
- "recording.readSegmentBytes": {
45600
- capName: "recording",
46151
+ "recordingArchive.readSegmentBytes": {
46152
+ capName: "recording-archive",
45601
46153
  capScope: "system",
45602
46154
  addonId: null,
45603
46155
  access: "view"
45604
46156
  },
45605
- "recording.readWindowBytes": {
45606
- capName: "recording",
46157
+ "recordingArchive.readWindowBytes": {
46158
+ capName: "recording-archive",
45607
46159
  capScope: "system",
45608
46160
  addonId: null,
45609
46161
  access: "view"
45610
46162
  },
45611
- "recording.reconcileLedgerAgainstDisk": {
45612
- capName: "recording",
46163
+ "recordingArchive.reconcileLedgerAgainstDisk": {
46164
+ capName: "recording-archive",
45613
46165
  capScope: "system",
45614
46166
  addonId: null,
45615
46167
  access: "create"
45616
46168
  },
45617
- "recording.refreshStorageLocationsForMigration": {
45618
- capName: "recording",
46169
+ "recordingArchive.refreshStorageLocationsForMigration": {
46170
+ capName: "recording-archive",
45619
46171
  capScope: "system",
45620
46172
  addonId: null,
45621
46173
  access: "create"
45622
46174
  },
45623
- "recording.relocateFootage": {
45624
- capName: "recording",
46175
+ "recordingArchive.relocateFootage": {
46176
+ capName: "recording-archive",
45625
46177
  capScope: "system",
45626
46178
  addonId: null,
45627
46179
  access: "create"
45628
46180
  },
45629
- "recording.renderClip": {
45630
- capName: "recording",
46181
+ "recordingArchive.renderClip": {
46182
+ capName: "recording-archive",
45631
46183
  capScope: "system",
45632
46184
  addonId: null,
45633
46185
  access: "create"
45634
46186
  },
45635
- "recording.renderGif": {
45636
- capName: "recording",
46187
+ "recordingArchive.renderGif": {
46188
+ capName: "recording-archive",
45637
46189
  capScope: "system",
45638
46190
  addonId: null,
45639
46191
  access: "create"
45640
46192
  },
45641
- "recording.rescanStorage": {
45642
- capName: "recording",
46193
+ "recordingArchive.rescanStorage": {
46194
+ capName: "recording-archive",
45643
46195
  capScope: "system",
45644
46196
  addonId: null,
45645
46197
  access: "create"
45646
46198
  },
45647
- "recording.resumeForStorageMigration": {
45648
- capName: "recording",
46199
+ "recordingArchive.resumeForStorageMigration": {
46200
+ capName: "recording-archive",
45649
46201
  capScope: "system",
45650
46202
  addonId: null,
45651
46203
  access: "create"
45652
46204
  },
45653
- "recording.setDeviceConfig": {
45654
- capName: "recording",
46205
+ "recordingArchive.setDeviceConfig": {
46206
+ capName: "recording-archive",
45655
46207
  capScope: "system",
45656
46208
  addonId: null,
45657
46209
  access: "create"
45658
46210
  },
45659
- "recording.setDevicePlacement": {
45660
- capName: "recording",
46211
+ "recordingArchive.setDevicePlacement": {
46212
+ capName: "recording-archive",
45661
46213
  capScope: "system",
45662
46214
  addonId: null,
45663
46215
  access: "create"
45664
46216
  },
45665
- "recording.startStorageMigrationMove": {
45666
- capName: "recording",
46217
+ "recordingArchive.startStorageMigrationMove": {
46218
+ capName: "recording-archive",
45667
46219
  capScope: "system",
45668
46220
  addonId: null,
45669
46221
  access: "create"
45670
46222
  },
45671
- "recording.startStorageRebalance": {
45672
- capName: "recording",
46223
+ "recordingArchive.startStorageRebalance": {
46224
+ capName: "recording-archive",
45673
46225
  capScope: "system",
45674
46226
  addonId: null,
45675
46227
  access: "create"
@@ -47198,6 +47750,12 @@ Object.freeze({
47198
47750
  addonId: null,
47199
47751
  access: "view"
47200
47752
  },
47753
+ "videoclips.getPlaybackOptions": {
47754
+ capName: "videoclips",
47755
+ capScope: "device",
47756
+ addonId: null,
47757
+ access: "view"
47758
+ },
47201
47759
  "videoclips.listClips": {
47202
47760
  capName: "videoclips",
47203
47761
  capScope: "device",
@@ -47210,6 +47768,12 @@ Object.freeze({
47210
47768
  addonId: null,
47211
47769
  access: "view"
47212
47770
  },
47771
+ "videoclips.offerClipBytes": {
47772
+ capName: "videoclips",
47773
+ capScope: "device",
47774
+ addonId: null,
47775
+ access: "view"
47776
+ },
47213
47777
  "videoclips.readClipBytes": {
47214
47778
  capName: "videoclips",
47215
47779
  capScope: "device",
@@ -47962,21 +48526,6 @@ Object.freeze({
47962
48526
  form: "single",
47963
48527
  optional: false
47964
48528
  }],
47965
- "events.getEventClipUrl": [{
47966
- name: "deviceId",
47967
- form: "single",
47968
- optional: false
47969
- }],
47970
- "events.getEvents": [{
47971
- name: "deviceId",
47972
- form: "single",
47973
- optional: false
47974
- }],
47975
- "events.getEventThumbnail": [{
47976
- name: "deviceId",
47977
- form: "single",
47978
- optional: false
47979
- }],
47980
48529
  "faceGallery.getFaceByTrack": [{
47981
48530
  name: "deviceId",
47982
48531
  form: "single",
@@ -48895,107 +49444,117 @@ Object.freeze({
48895
49444
  form: "single",
48896
49445
  optional: false
48897
49446
  }],
48898
- "recording.deleteFootprint": [{
49447
+ "recording.getAvailability": [{
49448
+ name: "deviceId",
49449
+ form: "single",
49450
+ optional: false
49451
+ }],
49452
+ "recording.getDaysWithRecordings": [{
48899
49453
  name: "deviceId",
48900
49454
  form: "single",
48901
49455
  optional: false
48902
49456
  }],
48903
- "recording.getAvailability": [{
49457
+ "recording.getPlayback": [{
48904
49458
  name: "deviceId",
48905
49459
  form: "single",
48906
49460
  optional: false
48907
49461
  }],
48908
- "recording.getAvailabilityBatch": [{
48909
- name: "deviceIds",
48910
- form: "array",
49462
+ "recording.getPlaybackOptions": [{
49463
+ name: "deviceId",
49464
+ form: "single",
48911
49465
  optional: false
48912
49466
  }],
48913
- "recording.getDaysWithRecordings": [{
49467
+ "recording.listSources": [{
49468
+ name: "deviceId",
49469
+ form: "single",
49470
+ optional: false
49471
+ }],
49472
+ "recordingArchive.deleteFootprint": [{
48914
49473
  name: "deviceId",
48915
49474
  form: "single",
48916
49475
  optional: false
48917
49476
  }],
48918
- "recording.getDaysWithRecordingsBatch": [{
49477
+ "recordingArchive.getAvailabilityBatch": [{
48919
49478
  name: "deviceIds",
48920
49479
  form: "array",
48921
49480
  optional: false
48922
49481
  }],
48923
- "recording.getDeviceConfig": [{
48924
- name: "deviceId",
48925
- form: "single",
49482
+ "recordingArchive.getDaysWithRecordingsBatch": [{
49483
+ name: "deviceIds",
49484
+ form: "array",
48926
49485
  optional: false
48927
49486
  }],
48928
- "recording.getPlaybackManifest": [{
49487
+ "recordingArchive.getDeviceConfig": [{
48929
49488
  name: "deviceId",
48930
49489
  form: "single",
48931
49490
  optional: false
48932
49491
  }],
48933
- "recording.listOpsLog": [{
49492
+ "recordingArchive.listOpsLog": [{
48934
49493
  name: "deviceId",
48935
49494
  form: "single",
48936
49495
  optional: true
48937
49496
  }],
48938
- "recording.locateSegment": [{
49497
+ "recordingArchive.locateSegment": [{
48939
49498
  name: "deviceId",
48940
49499
  form: "single",
48941
49500
  optional: false
48942
49501
  }],
48943
- "recording.pruneFootage": [{
49502
+ "recordingArchive.pruneFootage": [{
48944
49503
  name: "deviceId",
48945
49504
  form: "single",
48946
49505
  optional: false
48947
49506
  }],
48948
- "recording.readGopBytes": [{
49507
+ "recordingArchive.readGopBytes": [{
48949
49508
  name: "deviceId",
48950
49509
  form: "single",
48951
49510
  optional: false
48952
49511
  }],
48953
- "recording.readSegmentBytes": [{
49512
+ "recordingArchive.readSegmentBytes": [{
48954
49513
  name: "deviceId",
48955
49514
  form: "single",
48956
49515
  optional: false
48957
49516
  }],
48958
- "recording.readWindowBytes": [{
49517
+ "recordingArchive.readWindowBytes": [{
48959
49518
  name: "deviceId",
48960
49519
  form: "single",
48961
49520
  optional: false
48962
49521
  }],
48963
- "recording.reconcileLedgerAgainstDisk": [{
49522
+ "recordingArchive.reconcileLedgerAgainstDisk": [{
48964
49523
  name: "deviceId",
48965
49524
  form: "single",
48966
49525
  optional: true
48967
49526
  }],
48968
- "recording.relocateFootage": [{
49527
+ "recordingArchive.relocateFootage": [{
48969
49528
  name: "deviceId",
48970
49529
  form: "single",
48971
49530
  optional: true
48972
49531
  }],
48973
- "recording.renderClip": [{
49532
+ "recordingArchive.renderClip": [{
48974
49533
  name: "deviceId",
48975
49534
  form: "single",
48976
49535
  optional: false
48977
49536
  }],
48978
- "recording.renderGif": [{
49537
+ "recordingArchive.renderGif": [{
48979
49538
  name: "deviceId",
48980
49539
  form: "single",
48981
49540
  optional: false
48982
49541
  }],
48983
- "recording.rescanStorage": [{
49542
+ "recordingArchive.rescanStorage": [{
48984
49543
  name: "deviceId",
48985
49544
  form: "single",
48986
49545
  optional: false
48987
49546
  }],
48988
- "recording.setDeviceConfig": [{
49547
+ "recordingArchive.setDeviceConfig": [{
48989
49548
  name: "deviceId",
48990
49549
  form: "single",
48991
49550
  optional: false
48992
49551
  }],
48993
- "recording.setDevicePlacement": [{
49552
+ "recordingArchive.setDevicePlacement": [{
48994
49553
  name: "deviceId",
48995
49554
  form: "single",
48996
49555
  optional: false
48997
49556
  }],
48998
- "recording.startStorageMigrationMove": [{
49557
+ "recordingArchive.startStorageMigrationMove": [{
48999
49558
  name: "deviceId",
49000
49559
  form: "single",
49001
49560
  optional: true
@@ -49256,6 +49815,11 @@ Object.freeze({
49256
49815
  form: "single",
49257
49816
  optional: false
49258
49817
  }],
49818
+ "videoclips.getPlaybackOptions": [{
49819
+ name: "deviceId",
49820
+ form: "single",
49821
+ optional: false
49822
+ }],
49259
49823
  "videoclips.listClips": [{
49260
49824
  name: "deviceId",
49261
49825
  form: "single",
@@ -49266,6 +49830,11 @@ Object.freeze({
49266
49830
  form: "single",
49267
49831
  optional: false
49268
49832
  }],
49833
+ "videoclips.offerClipBytes": [{
49834
+ name: "deviceId",
49835
+ form: "single",
49836
+ optional: false
49837
+ }],
49269
49838
  "videoclips.readClipBytes": [{
49270
49839
  name: "deviceId",
49271
49840
  form: "single",
@@ -72579,7 +73148,7 @@ var require_yazl = /* @__PURE__ */ __commonJSMin(((exports) => {
72579
73148
  }
72580
73149
  }));
72581
73150
  //#endregion
72582
- //#region node_modules/@apocaliss92/nodelink-js/dist/chunk-E2N7WTCC.js
73151
+ //#region node_modules/@apocaliss92/nodelink-js/dist/chunk-AQQAL7CF.js
72583
73152
  var import_undici = require_undici();
72584
73153
  var import_yazl = /* @__PURE__ */ __toESM(require_yazl(), 1);
72585
73154
  var formatterCache = /* @__PURE__ */ new Map();
@@ -79065,9 +79634,16 @@ var require_lz4 = /* @__PURE__ */ __commonJSMin(((exports) => {
79065
79634
  };
79066
79635
  }));
79067
79636
  //#endregion
79068
- //#region node_modules/@apocaliss92/nodelink-js/dist/chunk-IPKY5AWA.js
79637
+ //#region node_modules/@apocaliss92/nodelink-js/dist/chunk-OXQH2ZT3.js
79069
79638
  var import_fxp = require_fxp();
79070
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
+ }
79071
79647
  function encodeHeader(h) {
79072
79648
  const hasOffset = bcHeaderHasPayloadOffset(h.messageClass);
79073
79649
  const headerLen = hasOffset ? 24 : 20;
@@ -79096,7 +79672,7 @@ function decodeHeader(buf) {
79096
79672
  const msgNum = buf.readUInt16LE(14);
79097
79673
  const responseCode = buf.readUInt16LE(16);
79098
79674
  const messageClass = buf.readUInt16LE(18);
79099
- const headerLen = bcHeaderHasPayloadOffset(messageClass) ? 24 : 20;
79675
+ const headerLen = bcHeaderLen(messageClass, buf, bodyLen);
79100
79676
  if (buf.length < headerLen) throw new Error("not enough data for Baichuan header (needs 24 bytes)");
79101
79677
  const messageKey = buf.readUInt32LE(12);
79102
79678
  const header = {
@@ -81029,6 +81605,9 @@ function createDebugGateLogger(base, enabled = false) {
81029
81605
  function isTalkCmd(cmdId) {
81030
81606
  return cmdId === 10 || cmdId === 11 || cmdId === 201 || cmdId === 202;
81031
81607
  }
81608
+ function toWireChannelId(channelId) {
81609
+ return channelId & 255;
81610
+ }
81032
81611
  var BaichuanClient = class _BaichuanClient extends EventEmitter {
81033
81612
  /**
81034
81613
  * Process-wide streaming activity registry.
@@ -82574,6 +83153,7 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
82574
83153
  if (prev.superseded) continue;
82575
83154
  prev.superseded = true;
82576
83155
  this.logger?.warn?.(`[BaichuanClient] cmd 5 replay session #${prev.id} (channelId=${prev.discriminator.channelId}, ${prev.discriminator.kind}) superseded by #${this.replaySessionSeq + 1} after ${prev.acceptedFrames} accepted frame(s). Frames still in flight for #${prev.id} will be dropped, not handed to its successor.`);
83156
+ prev.onSuperseded?.(/* @__PURE__ */ new Error(`cmd 5 replay session #${prev.id} was superseded by a later transfer on this socket after ${prev.acceptedFrames} accepted frame(s)`));
82577
83157
  }
82578
83158
  const session = {
82579
83159
  id: ++this.replaySessionSeq,
@@ -83196,7 +83776,7 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
83196
83776
  await this.connect();
83197
83777
  params.channel ?? this.opts.channel;
83198
83778
  const sessionCounter = this.nextMsgNum();
83199
- const channelId = params.channelIdOverride ?? sessionCounter;
83779
+ const channelId = toWireChannelId(params.channelIdOverride ?? sessionCounter);
83200
83780
  const discriminator = params.channelIdOverride == null ? {
83201
83781
  kind: "minted",
83202
83782
  channelId
@@ -83296,6 +83876,10 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
83296
83876
  cleanup();
83297
83877
  reject(e instanceof Error ? e : new Error(String(e)));
83298
83878
  };
83879
+ session.onSuperseded = (reason) => {
83880
+ if (chunks.length > 0) finish(Buffer.concat(chunks));
83881
+ else fail(reason);
83882
+ };
83299
83883
  const armIdleFinish = () => {
83300
83884
  if (idleTimer) clearTimeout(idleTimer);
83301
83885
  idleTimer = setTimeout(() => {
@@ -83309,25 +83893,25 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
83309
83893
  return;
83310
83894
  }
83311
83895
  if (lockedStreamType !== void 0 && frame.header.streamType !== lockedStreamType) return;
83312
- if (lockedChannelId !== void 0 && frame.header.channelId !== lockedChannelId) {
83896
+ if (lockedChannelId !== void 0 && frame.header.channelId !== toWireChannelId(lockedChannelId)) {
83313
83897
  this.countReplayDrop(session, frame, "foreign-channel");
83314
83898
  return;
83315
83899
  }
83316
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 {}
83317
83909
  const rc = frame.header.responseCode;
83318
- 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) {
83319
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})`));
83320
83912
  return;
83321
83913
  }
83322
83914
  try {
83323
- let markedBinary = false;
83324
- let encryptLen;
83325
- if (frame.extension.length > 0) try {
83326
- const extDec = this.tryDecryptXml(frame.extension, frame.header.channelId, enc);
83327
- if (extDec.includes("<binaryData>1</binaryData>")) markedBinary = true;
83328
- const encryptLenMatch = extDec.match(/<encryptLen>(\d+)<\/encryptLen>/i);
83329
- if (encryptLenMatch && encryptLenMatch[1]) encryptLen = parseInt(encryptLenMatch[1], 10);
83330
- } catch {}
83331
83915
  const decrypted = decryptBinaryForReplay(frame.payload, frame.header.channelId, encryptLen);
83332
83916
  if (decrypted.length === 0) return;
83333
83917
  if (!markedBinary && looksLikeXml(decrypted)) return;
@@ -83557,7 +84141,7 @@ var BaichuanClient = class _BaichuanClient extends EventEmitter {
83557
84141
  await this.connect();
83558
84142
  params.channel ?? this.opts.channel;
83559
84143
  const sessionCounter = this.nextMsgNum();
83560
- const channelId = params.channelIdOverride ?? sessionCounter;
84144
+ const channelId = toWireChannelId(params.channelIdOverride ?? sessionCounter);
83561
84145
  const msgNum = params.msgNumOverride ?? 0;
83562
84146
  const cmdId = params.cmdId;
83563
84147
  const extXml = params.extensionXml ?? "";
@@ -87827,6 +88411,117 @@ var estimateVideoTiming = (params) => {
87827
88411
  fpsSource: "unknown"
87828
88412
  };
87829
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
+ };
87830
88525
  function daysInMonth(year, month) {
87831
88526
  return new Date(Date.UTC(year, month, 0)).getUTCDate();
87832
88527
  }
@@ -89772,71 +90467,6 @@ var buildFileInfoListDownloadXml = (params) => {
89772
90467
  </FileInfoList>
89773
90468
  </body>`;
89774
90469
  };
89775
- var parseRecStartParamIfPresent = (fileName) => {
89776
- const m = /Rec(\w{3})(?:_|_DST)(\d{8})_(\d{6})_.*/.exec(fileName);
89777
- if (!m) return void 0;
89778
- return `${m[2]}${m[3]}`;
89779
- };
89780
- var buildReplayStopNameFromFileName = (fileName, channel = 0) => {
89781
- const trimmed = (fileName ?? "").trim();
89782
- if (/^\d{2}\d{14}$/.test(trimmed)) return trimmed;
89783
- const start = parseRecStartParamIfPresent(fileName);
89784
- if (!start) return void 0;
89785
- return `${String(channel + 1).padStart(2, "0")}${start}`;
89786
- };
89787
- var buildFileInfoListReplayByIdXml = (params) => {
89788
- const st = params.streamType ?? "mainStream";
89789
- const supportSub = st === "subStream" ? 1 : 0;
89790
- const xmlCh = params.xmlChannelId ?? params.channel;
89791
- const iframe = params.iframeReplay;
89792
- const iframeXml = iframe === true || iframe === "both" ? "<bIframeReplay>1</bIframeReplay><iIframeReplay>1</iIframeReplay>" : iframe === "b" ? "<bIframeReplay>1</bIframeReplay>" : iframe === "i" ? "<iIframeReplay>1</iIframeReplay>" : "";
89793
- const lines = [
89794
- "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>",
89795
- "<body>",
89796
- "<FileInfoList version=\"1.1\">",
89797
- "<FileInfo>",
89798
- `<channelId>${xmlCh}</channelId>`,
89799
- `<Id>${xmlEscape(params.id)}</Id>`
89800
- ];
89801
- if (params.uid) lines.push(`<uid>${xmlEscape(params.uid)}</uid>`);
89802
- lines.push(`<supportSub>${supportSub}</supportSub>`, "<playSpeed>1</playSpeed>", `<streamType>${xmlEscape(st)}</streamType>`);
89803
- if (iframeXml) lines.push(iframeXml);
89804
- lines.push("</FileInfo>", "</FileInfoList>", "</body>");
89805
- return lines.join("\n");
89806
- };
89807
- var buildFileInfoListReplayByNameXml = (params) => {
89808
- const st = params.streamType ?? "mainStream";
89809
- const supportSub = st === "subStream" ? 1 : 0;
89810
- const xmlCh = params.xmlChannelId ?? params.channel;
89811
- const iframe = params.iframeReplay;
89812
- const iframeXml = iframe === true || iframe === "both" ? "<bIframeReplay>1</bIframeReplay><iIframeReplay>1</iIframeReplay>" : iframe === "b" ? "<bIframeReplay>1</bIframeReplay>" : iframe === "i" ? "<iIframeReplay>1</iIframeReplay>" : "";
89813
- const lines = [
89814
- "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>",
89815
- "<body>",
89816
- "<FileInfoList version=\"1.1\">",
89817
- "<FileInfo>",
89818
- `<channelId>${xmlCh}</channelId>`,
89819
- `<Id>${xmlEscape(params.name)}</Id>`
89820
- ];
89821
- if (params.uid) lines.push(`<uid>${xmlEscape(params.uid)}</uid>`);
89822
- lines.push(`<supportSub>${supportSub}</supportSub>`, "<playSpeed>1</playSpeed>", `<streamType>${xmlEscape(st)}</streamType>`);
89823
- if (iframeXml) lines.push(iframeXml);
89824
- lines.push("</FileInfo>", "</FileInfoList>", "</body>");
89825
- return lines.join("\n");
89826
- };
89827
- var buildFileInfoListStopXml = (params) => {
89828
- const st = params.streamType ?? "mainStream";
89829
- return `<?xml version="1.0" encoding="UTF-8" ?>
89830
- <body>
89831
- <FileInfoList version="1.1">
89832
- <FileInfo>
89833
- <channelId>${params.channel}</channelId>
89834
- <name>${xmlEscape(params.name)}</name>
89835
- <streamType>${xmlEscape(st)}</streamType>
89836
- </FileInfo>
89837
- </FileInfoList>
89838
- </body>`;
89839
- };
89840
90470
  var videoCodecMap = {
89841
90471
  0: "H.264",
89842
90472
  1: "H.265",
@@ -90725,6 +91355,7 @@ var isNvrHubModel = (model) => {
90725
91355
  if (NVR_HUB_EXACT_TYPES.includes(upper)) return true;
90726
91356
  return NVR_HUB_MODEL_PATTERNS.some((pattern) => pattern.test(normalized));
90727
91357
  };
91358
+ var SEEKED_CHANNELS = /* @__PURE__ */ new WeakMap();
90728
91359
  var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
90729
91360
  logger;
90730
91361
  httpClient;
@@ -92482,7 +93113,7 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
92482
93113
  return;
92483
93114
  }
92484
93115
  entry.startInFlight = (async () => {
92485
- const { BaichuanVideoStream: BaichuanVideoStream2 } = await import("./BaichuanVideoStream-UG3DIMIE-BRbIHCdL.mjs");
93116
+ const { BaichuanVideoStream: BaichuanVideoStream2 } = await import("./BaichuanVideoStream-PR2SYJAE-DX1rTJzR.mjs");
92486
93117
  const sessionKey = `live:object-detections:ch${entry.channel}:${entry.profile}`;
92487
93118
  const dedicated = await this.createDedicatedSession(sessionKey);
92488
93119
  const stream = new BaichuanVideoStream2({
@@ -95505,6 +96136,44 @@ ${stderr}`));
95505
96136
  trace(`download: channel=${channel} uid=${uid || "(missing)"} ident=${ident} streamType=${streamType} isNvr=${isNvr} timeoutMs=${timeoutMs}`);
95506
96137
  const pinnedHeaderChannelId = params.headerChannelIdOverride;
95507
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
+ };
95508
96177
  try {
95509
96178
  return await this.client.sendBinary({
95510
96179
  cmdId: 5,
@@ -95516,13 +96185,17 @@ ${stderr}`));
95516
96185
  streamType: 0,
95517
96186
  timeoutMs,
95518
96187
  ...params.idleTimeoutMs != null ? { idleTimeoutMs: params.idleTimeoutMs } : {},
95519
- ...params.onChunk ? { onChunk: params.onChunk } : {}
96188
+ onChunk: (chunk) => {
96189
+ observeChunk(chunk);
96190
+ params.onChunk?.(chunk);
96191
+ }
95520
96192
  });
95521
96193
  } catch (e) {
95522
96194
  trace(`download failed: ${e instanceof Error ? e.message : String(e)}`);
95523
96195
  abandoned = true;
95524
96196
  throw e;
95525
96197
  } finally {
96198
+ settleOutcome();
95526
96199
  await this.stopFileInfoListReplay({
95527
96200
  channel,
95528
96201
  fileName: ident,
@@ -95532,6 +96205,76 @@ ${stderr}`));
95532
96205
  }
95533
96206
  }
95534
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
+ /**
95535
96278
  * Close a cmd 5 replay session at the camera (cmd 7) and wait for the wire to
95536
96279
  * go quiet.
95537
96280
  *
@@ -98686,7 +99429,7 @@ ${xml}`);
98686
99429
  * @returns Test results for all stream types and profiles
98687
99430
  */
98688
99431
  async testChannelStreams(channel, logger) {
98689
- const { testChannelStreams } = await import("./DiagnosticsTools-YIWXO7IJ-9NV95vRN.mjs");
99432
+ const { testChannelStreams } = await import("./DiagnosticsTools-DS5X2UVY-9NV95vRN.mjs");
98690
99433
  return await testChannelStreams({
98691
99434
  api: this,
98692
99435
  channel: this.normalizeChannel(channel),
@@ -98702,7 +99445,7 @@ ${xml}`);
98702
99445
  * @returns Complete diagnostics for all channels and streams
98703
99446
  */
98704
99447
  async collectMultifocalDiagnostics(logger) {
98705
- const { collectMultifocalDiagnostics } = await import("./DiagnosticsTools-YIWXO7IJ-9NV95vRN.mjs");
99448
+ const { collectMultifocalDiagnostics } = await import("./DiagnosticsTools-DS5X2UVY-9NV95vRN.mjs");
98706
99449
  return await collectMultifocalDiagnostics({
98707
99450
  api: this,
98708
99451
  logger
@@ -152281,6 +153024,7 @@ function createClipStreamProducer(deps) {
152281
153024
  const createDecoder = deps.createDecoder ?? defaultDecoder;
152282
153025
  const drainTimeoutMs = deps.drainTimeoutMs ?? 1e4;
152283
153026
  const flushTimeoutMs = deps.flushTimeoutMs ?? 15e3;
153027
+ const cutGraceMs = deps.cutGraceMs ?? 5e3;
152284
153028
  const lanes = /* @__PURE__ */ new Map();
152285
153029
  const activeByHost = /* @__PURE__ */ new Map();
152286
153030
  const runAttempt = (input, attempt) => new ClipStreamRun({
@@ -152288,7 +153032,8 @@ function createClipStreamProducer(deps) {
152288
153032
  spawnMux: deps.spawnMux,
152289
153033
  createDecoder,
152290
153034
  drainTimeoutMs,
152291
- flushTimeoutMs
153035
+ flushTimeoutMs,
153036
+ cutGraceMs
152292
153037
  }, input, attempt).run();
152293
153038
  const runAttempts = async (input) => {
152294
153039
  const { deviceId } = input.device;
@@ -152389,6 +153134,8 @@ var ClipStreamRun = class {
152389
153134
  input;
152390
153135
  attempt;
152391
153136
  accessUnits = 0;
153137
+ /** Armed by {@link sever}; cleared when the run finally returns. */
153138
+ cutWatch = null;
152392
153139
  /** Every audio frame the decoder handed over, of any codec. */
152393
153140
  audioFrames = 0;
152394
153141
  audioFramesDropped = 0;
@@ -152493,6 +153240,8 @@ var ClipStreamRun = class {
152493
153240
  return await this.onTransferEnded();
152494
153241
  } finally {
152495
153242
  this.done = true;
153243
+ if (this.cutWatch !== null) clearTimeout(this.cutWatch);
153244
+ this.cutWatch = null;
152496
153245
  this.disposeGates();
152497
153246
  }
152498
153247
  }
@@ -152770,6 +153519,36 @@ var ClipStreamRun = class {
152770
153519
  this.input.sink.end();
152771
153520
  }
152772
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
+ }
152773
153552
  sever(reason, detail) {
152774
153553
  if (this.cut !== null || this.done) return;
152775
153554
  this.cut = {
@@ -152794,6 +153573,7 @@ var ClipStreamRun = class {
152794
153573
  }
152795
153574
  });
152796
153575
  if (this.begun) this.input.sink.destroy();
153576
+ this.armCutWatch(reason);
152797
153577
  }
152798
153578
  cutOutcome(cut) {
152799
153579
  if (this.begun) return {
@@ -154597,6 +155377,131 @@ function createReolinkVideoclipsProvider(deps) {
154597
155377
  };
154598
155378
  },
154599
155379
  /**
155380
+ * The same clip, over the addon→addon byte transport (D613).
155381
+ *
155382
+ * Every gate {@link readClipBytes} runs, in the same order and with the
155383
+ * same vocabulary — the id, the row, a clip still being written, the twin,
155384
+ * the size the ROW declares, and the sleep gate, which the producer
155385
+ * decides before `getApi()` because on UDP the login IS the wake. The one
155386
+ * difference is the envelope: the bytes leave over a one-shot loopback
155387
+ * socket instead of inside a base64 field, so the caller holds nothing and
155388
+ * this process holds the one copy the cmd-5 transfer already produced.
155389
+ *
155390
+ * The bound is {@link VIDEOCLIPS_MAX_OFFER_BYTES}: ten times the inline
155391
+ * one, because the inline one was paying for two inflated copies and this
155392
+ * pays for one plain one.
155393
+ */
155394
+ offerClipBytes: async ({ deviceId, clipId, profile, maxBytes, wake }) => {
155395
+ const tags = { deviceId };
155396
+ const refuse = (code, detail, meta) => {
155397
+ deps.logger.warn("videoclips: refusing a clip byte offer", {
155398
+ tags,
155399
+ meta: {
155400
+ clipId,
155401
+ branch: code,
155402
+ ...meta
155403
+ }
155404
+ });
155405
+ throw new Error(clipExportFailure(code, detail));
155406
+ };
155407
+ const parsed = parseClipId(clipId);
155408
+ if (parsed === null) return refuse("catalog-miss", `clip id "${clipId}" was not minted by the Reolink provider`, {});
155409
+ const clipKey = clipKeyFor(parsed.channel, parsed.fileName);
155410
+ const row = rowsByKey.get(`${deviceId}|${clipKey}`);
155411
+ if (row === void 0) return refuse("catalog-miss", `clip "${clipId}" is not in this node's catalog for device ${deviceId} — list the day that holds it first`, { clipKey });
155412
+ if (row.inProgress === true) return refuse("clip-in-progress", `clip "${clipId}" is still being written, so it has no end to export`, { clipKey });
155413
+ const chosen = chooseClipTwin(profile, row);
155414
+ if (chosen.downgraded) deps.logger.warn("videoclips: no main twin for this clip — serving the sub copy", {
155415
+ tags,
155416
+ meta: {
155417
+ clipId,
155418
+ clipKey,
155419
+ branch: "no-main-twin",
155420
+ asked: profile
155421
+ }
155422
+ });
155423
+ const twin = chosen.twin;
155424
+ const fileName = chosen.fileName;
155425
+ if (fileName === "") return refuse("no-file-for-window", `clip "${clipId}" is listed with no byte handle behind it`, {
155426
+ clipKey,
155427
+ twin
155428
+ });
155429
+ const served = chosen.served;
155430
+ const bound = Math.min(maxBytes ?? 524288e3, VIDEOCLIPS_MAX_OFFER_BYTES);
155431
+ const declaredBytes = twin === "main" ? row.mainBytes : row.subBytes;
155432
+ if (declaredBytes !== void 0 && declaredBytes > bound) return refuse("too-large-to-transfer", `the camera lists the ${twin} file of clip "${clipId}" as ${declaredBytes} bytes, over the ${bound}-byte bound for one transfer`, {
155433
+ clipKey,
155434
+ twin,
155435
+ declaredBytes,
155436
+ bound
155437
+ });
155438
+ const outcome = await deps.prepareOffer({
155439
+ deviceId,
155440
+ row,
155441
+ fileName,
155442
+ twin,
155443
+ ...wake !== void 0 ? { wake } : {}
155444
+ });
155445
+ if (outcome.kind === "refused") throw new Error(clipExportFailure(outcome.code, outcome.detail));
155446
+ if (outcome.bytes > bound) return refuse("too-large-to-transfer", `clip "${clipId}" muxed to ${outcome.bytes} bytes, over the ${bound}-byte bound for one transfer`, {
155447
+ clipKey,
155448
+ twin,
155449
+ bytes: outcome.bytes,
155450
+ bound
155451
+ });
155452
+ deps.logger.info("videoclips: offered a Reolink clip by handle", {
155453
+ tags,
155454
+ meta: {
155455
+ clipId,
155456
+ clipKey,
155457
+ twin,
155458
+ served,
155459
+ asked: profile ?? null,
155460
+ bytes: outcome.bytes,
155461
+ durationMs: outcome.durationMs,
155462
+ wake: wake ?? "none"
155463
+ }
155464
+ });
155465
+ return {
155466
+ ticket: outcome.ticket,
155467
+ contentType: "video/mp4",
155468
+ name: clipFileLabel(fileName),
155469
+ served,
155470
+ ...outcome.durationMs !== null ? { durationMs: outcome.durationMs } : {}
155471
+ };
155472
+ },
155473
+ /**
155474
+ * What a surface may DRAW for this camera's clips (D612).
155475
+ *
155476
+ * A CONSTANT, and it has to be: this method is asked per camera, and the
155477
+ * answer is a fact about which accessors this provider wires, not about
155478
+ * the camera. Every clip here reaches the player over
155479
+ * {@link dialClipStream}'s forward-only stream, so every clip gets the
155480
+ * `stream` envelope — measured, not assumed: the broker's `chooseClipPath`
155481
+ * reads only whether the dial and the file read are wired, and never the
155482
+ * clip or the profile.
155483
+ *
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.
155502
+ */
155503
+ getPlaybackOptions: async () => CLIP_PLAYBACK_OPTIONS.stream,
155504
+ /**
154600
155505
  * Where this clip's STREAM is dialled (D597) — the same questions
154601
155506
  * `readClipBytes` asks before the camera is touched (the id, the row, a
154602
155507
  * file still being written), the same vocabulary, and NO fetch: the URL
@@ -155567,6 +156472,62 @@ function createClipService(deps) {
155567
156472
  return outcome;
155568
156473
  };
155569
156474
  /**
156475
+ * The same clip, offered over the addon→addon byte transport (D613).
156476
+ *
156477
+ * It reuses {@link prepareBytes} whole — one fetch path, one set of
156478
+ * completion rules, one scratch. A second producer here would be the second
156479
+ * authority D558 refuses to create. What changes is only how the result
156480
+ * LEAVES: `offerBuffer` writes it to a one-shot loopback socket in bounded
156481
+ * chunks, honouring `write()`'s return (D447), instead of base64-ing it into
156482
+ * a cap envelope that the caller then copies again.
156483
+ */
156484
+ const prepareOffer = async (input) => {
156485
+ const peerBytes = deps.peerBytes;
156486
+ if (peerBytes === void 0) {
156487
+ deps.logger.warn("videoclips: no peer-bytes transport on this node", {
156488
+ tags: { deviceId: input.deviceId },
156489
+ meta: {
156490
+ clipKey: input.row.clipKey,
156491
+ branch: "no-peer-bytes"
156492
+ }
156493
+ });
156494
+ return {
156495
+ kind: "refused",
156496
+ code: "fetch-failed",
156497
+ detail: "this node has no addon-to-addon byte transport wired"
156498
+ };
156499
+ }
156500
+ const outcome = await prepareBytes(input);
156501
+ if (outcome.kind === "refused") return outcome;
156502
+ const offered = await peerBytes.offerBuffer({
156503
+ bytes: outcome.bytes,
156504
+ contentType: "video/mp4",
156505
+ label: "reolink-clip",
156506
+ deviceId: input.deviceId
156507
+ });
156508
+ if (offered.kind === "refused") {
156509
+ deps.logger.warn("videoclips: the clip byte offer could not be minted", {
156510
+ tags: { deviceId: input.deviceId },
156511
+ meta: {
156512
+ clipKey: input.row.clipKey,
156513
+ branch: offered.code,
156514
+ detail: offered.detail
156515
+ }
156516
+ });
156517
+ return {
156518
+ kind: "refused",
156519
+ code: "fetch-failed",
156520
+ detail: `${offered.code}: ${offered.detail}`
156521
+ };
156522
+ }
156523
+ return {
156524
+ kind: "ok",
156525
+ ticket: offered.ticket,
156526
+ durationMs: outcome.durationMs,
156527
+ bytes: outcome.bytes.byteLength
156528
+ };
156529
+ };
156530
+ /**
155570
156531
  * The STREAM's path (`clip-stream-route.ts`): the same gates, the same row,
155571
156532
  * nothing written. Beside the file path, not in its place.
155572
156533
  */
@@ -155606,6 +156567,7 @@ function createClipService(deps) {
155606
156567
  served: profile === "high" ? "high" : "low"
155607
156568
  }),
155608
156569
  prepareBytes,
156570
+ prepareOffer,
155609
156571
  prepareStreamDial: async ({ deviceId, row, twin, audio }) => {
155610
156572
  const gate = await gateClipDevice({
155611
156573
  deviceId,
@@ -170284,6 +171246,7 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
170284
171246
  this.clipService = createClipService({
170285
171247
  dataDir: this.ctx.dataDir,
170286
171248
  logger: this.ctx.logger,
171249
+ ...this.ctx.peerBytes !== void 0 ? { peerBytes: this.ctx.peerBytes } : {},
170287
171250
  resolveDevice: async (deviceId) => {
170288
171251
  const device = this.ctx.kernel.deviceRegistry?.getById(deviceId);
170289
171252
  return device instanceof ReolinkCamera ? device.getClipDeviceRef() : null;