@camstack/addon-provider-hikvision 1.2.126 → 1.2.131

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +2258 -1706
  2. package/dist/addon.mjs +2258 -1706
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -5373,7 +5373,7 @@ var ZodIssueCode = {
5373
5373
  var ZodFirstPartyTypeKind;
5374
5374
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5375
5375
  //#endregion
5376
- //#region ../types/dist/sleep-COWaSCAi.mjs
5376
+ //#region ../types/dist/sleep-PEo0-Fz9.mjs
5377
5377
  /**
5378
5378
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5379
5379
  * window to float samples (D455).
@@ -6509,6 +6509,24 @@ function normalizeAddonInitResult(result) {
6509
6509
  if (Array.isArray(result)) return { providers: result };
6510
6510
  return result;
6511
6511
  }
6512
+ /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
6513
+ var PeerBytesTicketSchema = object({
6514
+ /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
6515
+ url: string().min(1),
6516
+ /**
6517
+ * The HOST node this URL means something on — the hub or a named agent,
6518
+ * never a runner. {@link AddonPeerBytes.open} compares it to its own and
6519
+ * refuses `cross-node` by name when they differ, without dialling.
6520
+ */
6521
+ hostNodeId: string().min(1),
6522
+ expiresAtMs: number().int().nonnegative(),
6523
+ /**
6524
+ * What the producer DECLARED the body to be, when it knows — `null` when it
6525
+ * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
6526
+ * must be able to tell "the producer did not say" from "the body is empty".
6527
+ */
6528
+ declaredBytes: number().int().nonnegative().nullable()
6529
+ });
6512
6530
  /** Shared Zod schemas used across streaming capabilities. */
6513
6531
  var CamProfileSchema = _enum([
6514
6532
  "high",
@@ -7543,24 +7561,6 @@ object({
7543
7561
  unreachable: number()
7544
7562
  })
7545
7563
  });
7546
- /** The wire shape of {@link PeerBytesTicket} — see the type for what it is. */
7547
- var PeerBytesTicketSchema = object({
7548
- /** `http://127.0.0.1:<port>/<token>`. One `GET` takes it. */
7549
- url: string().min(1),
7550
- /**
7551
- * The HOST node this URL means something on — the hub or a named agent,
7552
- * never a runner. {@link AddonPeerBytes.open} compares it to its own and
7553
- * refuses `cross-node` by name when they differ, without dialling.
7554
- */
7555
- hostNodeId: string().min(1),
7556
- expiresAtMs: number().int().nonnegative(),
7557
- /**
7558
- * What the producer DECLARED the body to be, when it knows — `null` when it
7559
- * does not. Never `0` for unknown (D393): a consumer sizing a bound off this
7560
- * must be able to tell "the producer did not say" from "the body is empty".
7561
- */
7562
- declaredBytes: number().int().nonnegative().nullable()
7563
- });
7564
7564
  /**
7565
7565
  * Adoption job — the background form of `device-adoption.adopt`.
7566
7566
  *
@@ -7672,7 +7672,7 @@ var AdoptionJobSchema = object({
7672
7672
  * component's original options — detection to the detection-pipeline wrapper
7673
7673
  * binding, audio analysis to its own, recording to `RecordingConfig.enabled`
7674
7674
  * (which was always first-class; the switch was a veneer over
7675
- * `recording.setDeviceConfig`), notifications to a notification-center
7675
+ * `recordingArchive.setDeviceConfig`), notifications to a notification-center
7676
7676
  * per-device setting, the two camera planes to their own components.
7677
7677
  *
7678
7678
  * What survives is {@link composeSwitchedOff}: `CameraStatus.switchedOff`, the
@@ -7698,7 +7698,7 @@ var AdoptionJobSchema = object({
7698
7698
  * | `stream-broker` | `deviceManager.setDisabled` | `StreamBrokerManager.reconcileAllCatalogs` releases the brokers; `ensureBroker` refuses re-creation |
7699
7699
  * | `object-detection` | `deviceManager.setWrapperActive('detection-pipeline')` | `PipelineSettingsStore.resolvePipelineForDevice` returns `{ steps: [], audio: null }` |
7700
7700
  * | `audio-analysis` | `deviceManager.setWrapperActive('audio-analysis')` | `AudioSubscriptionController.subscribeAudioStream` returns `null` before opening the stream |
7701
- * | `recording` | `recording.setDeviceConfig` → `RecordingConfig.enabled` | `band-decision.shouldRecord` returns false; the controller detaches the device |
7701
+ * | `recording` | `recordingArchive.setDeviceConfig` → `RecordingConfig.enabled` | `band-decision.shouldRecord` returns false; the controller detaches the device |
7702
7702
  * | `notifications` | `notificationRules.setDeviceMuted` | `NotificationCenter.evaluateAndEnqueue` returns before any rule is evaluated |
7703
7703
  * | `privacy-mask` | `privacyMask.setMask({ enabled })` → the CAMERA | the camera blanks the masked regions itself; every stream and recording carries the black boxes |
7704
7704
  * | `device-audio` | `privacyMask.setAudioEnabled` → the CAMERA | the camera stops encoding an audio track at all; every consumer sees silent video |
@@ -11877,87 +11877,6 @@ method(ListInputSchema, array(BrokerInfoSchema$1)), method(GetInputSchema, Broke
11877
11877
  auth: "admin"
11878
11878
  }), method(GetStateInputSchema, unknown().nullable()), method(_void(), RegistryStatusSchema);
11879
11879
  DeviceType.Camera;
11880
- /**
11881
- * The signals a device can emit to WAKE its own stream.
11882
- *
11883
- * A camera whose stream is built on demand sleeps until something asks for it,
11884
- * and "something" cannot be a consumer that is merely attached — a Frigate-style
11885
- * puller holds a session open for ever, and treating that as demand would keep
11886
- * a battery camera awake for ever, which is the whole thing the battery is for
11887
- * (D173). So the wake has to come from the CAMERA: an event it noticed by
11888
- * itself, with no stream running.
11889
- *
11890
- * ## The vocabulary is the PROVIDER'S, not ours
11891
- *
11892
- * Like `consumables`, this cap declares no vocabulary of its own. A provider
11893
- * names each signal with a `code` it chooses and a `label` an operator reads.
11894
- * Reolink offers motion and camera-native detection; another provider may offer
11895
- * a tamper, a doorbell press, a PIR, or something no camera in this fleet has
11896
- * yet. A fixed enum here would mean every new signal is a framework release.
11897
- *
11898
- * It is deliberately NOT derived from the caps a device already binds. Whether
11899
- * a camera CAN push firmware motion is expressed by `motionSources` containing
11900
- * `'onboard'`, and whether it does AI on-camera by the `native-object-detection`
11901
- * binding — but both answer "what drives the detection pipeline", which is a
11902
- * different question from "what may wake a sleeping stream". A camera can do
11903
- * the first and not be trusted with the second, and the operator picks per
11904
- * camera. Two questions, two authorities.
11905
- *
11906
- * ## Availability is not permission
11907
- *
11908
- * `listSignals` says what the device CAN emit. Whether a given signal actually
11909
- * wakes the stream is the operator's per-camera choice, held by the broker
11910
- * alongside the cooldown — see the stream-broker cap's wake settings. A
11911
- * provider declaring a signal is not a provider enabling it.
11912
- */
11913
- /** One signal a device can emit. */
11914
- var StreamSignalSchema = object({
11915
- /** Stable id chosen by the provider, e.g. `'motion'`, `'person'`, `'tamper'`. */
11916
- code: string().min(1),
11917
- /** What an operator reads in the picker. The provider's own wording. */
11918
- label: string().min(1),
11919
- /**
11920
- * Whether the provider recommends this signal ON when a camera is first set
11921
- * up. A provider knows which of its signals are cheap and reliable; an
11922
- * operator should not have to discover that by trial. Reolink recommends
11923
- * both of its own.
11924
- */
11925
- recommended: boolean()
11926
- });
11927
- var StreamSignalsStatusSchema = object({
11928
- signals: array(StreamSignalSchema),
11929
- lastFetchedAt: number()
11930
- });
11931
- var streamSignalsCapability = {
11932
- name: "stream-signals",
11933
- scope: "device",
11934
- deviceNative: true,
11935
- mode: "singleton",
11936
- deviceTypes: Object.values(DeviceType),
11937
- runtimeState: StreamSignalsStatusSchema,
11938
- /**
11939
- * Runtime-state durability: **session** — mirrored in RAM, never written.
11940
- *
11941
- * The slice holds what the DEVICE says it can emit. That is a probed fact,
11942
- * not an operator choice: the provider re-declares it on every registration,
11943
- * so losing it loses nothing and persisting it would freeze an answer the
11944
- * camera is entitled to change. Measured the same day on the sibling case —
11945
- * `native-object-detection.supportedClasses` was persisted, and a firmware
11946
- * class the camera really detected stayed missing for the life of the row
11947
- * because the fix could not reach it.
11948
- *
11949
- * See `RuntimeStateDurability`. Enforced by
11950
- * `scripts/check-runtime-state-durability.ts`.
11951
- */
11952
- durability: "session",
11953
- methods: {
11954
- /**
11955
- * What this device can emit. Empty is a valid and common answer — most
11956
- * cameras have nothing to offer here, and an empty list is what makes the
11957
- * broker's picker show nothing rather than a false choice.
11958
- */
11959
- listSignals: method(_void(), array(StreamSignalSchema).readonly()) }
11960
- };
11961
11880
  /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
11962
11881
  var StreamFormatSchema = _enum([
11963
11882
  "webrtc",
@@ -13423,6 +13342,210 @@ method(object({ codec: string() }), boolean()), method(_void(), object({
13423
13342
  });
13424
13343
  DeviceType.Camera;
13425
13344
  /**
13345
+ * device-admin-link — "this device has a management page of its own, and here
13346
+ * is its address".
13347
+ *
13348
+ * ## Why this is not a `deviceConfig` cap
13349
+ *
13350
+ * There is nothing to edit. A `deviceConfig` cap (D14) exists so the framework
13351
+ * can DERIVE a settings form from `getOptions` + `getStatus` and route a flat
13352
+ * patch back through a setter; it costs a `builderId` reducer in
13353
+ * `device-config-contribution.ts` and a `*-config-schema.ts` beside it, and it
13354
+ * renders a form section. This cap answers ONE question with ONE read and
13355
+ * renders a button. Nothing about it is a form, so it carries no `deviceConfig`
13356
+ * block, no `settings`, no `runtimeState` and no reducer — exactly like
13357
+ * `reboot`, the other pure-RPC device-native cap.
13358
+ *
13359
+ * ## Absent, and the difference between "no page" and "we cannot say"
13360
+ *
13361
+ * The two are answered at DIFFERENT layers, on purpose:
13362
+ *
13363
+ * - **"We cannot say"** → the provider never registers the cap for that
13364
+ * device. A VeSync humidifier, a Petkit feeder, a Dreame vacuum and a Dreo
13365
+ * fan are reached only through a vendor cloud; there is no address to hand
13366
+ * out and no page to open. A Tuya plug, a Wyze camera and a Gree air
13367
+ * conditioner DO have a LAN IP, and still have no HTTP management page
13368
+ * behind it. None of them register, so `deviceManager.getBindings` never
13369
+ * lists the cap and no surface asks.
13370
+ * - **"This device has no page, and I know that"** → the provider registers
13371
+ * and `getAdminLink` returns `null`. This is the answer for a device whose
13372
+ * sibling DOES have a page: a Reolink battery camera reached over UDP by
13373
+ * `uid` with a blank `host`, an Ecowitt gateway configured in `listener`
13374
+ * transport, a Home Assistant broker authenticated by supervisor token
13375
+ * (which carries no `baseUrl` at all).
13376
+ *
13377
+ * Both draw NOTHING. A button that opens a browser error is worse than no
13378
+ * button, and D62 is the same rule from the other side: an off switch is
13379
+ * reported off, never made to look broken. There is no third state where the
13380
+ * UI renders a disabled button "because the device might have a page".
13381
+ *
13382
+ * ## The URL never carries credentials
13383
+ *
13384
+ * Not in userinfo, not in a query string. Every provider builds through
13385
+ * `buildDeviceAdminUrl` (`device-admin-link-url.ts`), which takes host, port,
13386
+ * scheme and path as separate arguments — there is no parameter a secret could
13387
+ * arrive in — and re-checks its own output for the `scheme://user:pass@` shape
13388
+ * that `scripts/check-no-credential-urls-in-fixtures.ts` bans from recorded
13389
+ * output. `scripts/check-admin-link-builder-is-the-only-url-source.ts` is what
13390
+ * keeps providers from hand-rolling one anyway.
13391
+ *
13392
+ * This matters here more than anywhere else in the repo, because every provider
13393
+ * that knows a device's host knows its PASSWORD too: `{ host, port, username,
13394
+ * password }` sit in one object on Hikvision, Amcrest, Reolink and ONVIF alike,
13395
+ * and `http://admin:hunter2@192.168.50.139/` is a URL a browser accepts. The
13396
+ * camera's own page will ask for its own login. That is correct, and pre-
13397
+ * filling it is the operator's business, not ours.
13398
+ *
13399
+ * ## It is a LAN fact
13400
+ *
13401
+ * The URL addresses the device where the NODE can see it. It is not proxied,
13402
+ * not made reachable from outside, and not sent anywhere. A surface renders it
13403
+ * as a link the operator's own browser follows, on the operator's own network,
13404
+ * or renders nothing.
13405
+ */
13406
+ /**
13407
+ * Whose page is it. The distinction is for the OPERATOR, who needs to know
13408
+ * before clicking whether he is about to land on a camera's own web server or
13409
+ * inside Home Assistant.
13410
+ */
13411
+ var AdminLinkTargetEnum = _enum(["device", "integration"]);
13412
+ var DeviceAdminLinkSchema = object({
13413
+ /**
13414
+ * Absolute `http(s)://` URL. Built by `buildDeviceAdminUrl` and therefore
13415
+ * free of userinfo and of any credential-shaped query key.
13416
+ */
13417
+ url: string(),
13418
+ /**
13419
+ * What the surface calls it — "Web UI", "Home Assistant", "UniFi controller".
13420
+ * The PROVIDER names it, because only the provider knows what the page is;
13421
+ * a UI that invented the label from the addon id would call the Home
13422
+ * Assistant device page "Provider Homeassistant".
13423
+ */
13424
+ label: string(),
13425
+ target: AdminLinkTargetEnum,
13426
+ /**
13427
+ * Host the URL points at, without scheme, port or path — for the tooltip, so
13428
+ * an operator can see WHERE the button goes before he follows it. Redundant
13429
+ * with `url` by construction; carried separately so no surface has to parse
13430
+ * a URL to show it.
13431
+ */
13432
+ host: string()
13433
+ });
13434
+ var deviceAdminLinkCapability = {
13435
+ name: "device-admin-link",
13436
+ scope: "device",
13437
+ deviceNative: true,
13438
+ mode: "singleton",
13439
+ methods: {
13440
+ /**
13441
+ * The device's management page, or `null` when this device has none.
13442
+ *
13443
+ * `auth: 'admin'` deliberately. This is administration, not actuation —
13444
+ * the same bucket as `reboot` and `camera-credentials`, and explicitly NOT
13445
+ * the actuation set `scripts/check-actuation-not-admin.ts` protects (D403).
13446
+ * The URL is also a statement about the LAN, which a household member with
13447
+ * a `view` grant on a light has no reason to be handed.
13448
+ *
13449
+ * The surfaces gate on the QUERY, never on a role they guessed: a caller
13450
+ * without the right loses the query and draws nothing, which is the same
13451
+ * thing a device with no page draws. There is no path on which a button
13452
+ * appears and then fails — the D403 failure mode, from the other end.
13453
+ */
13454
+ getAdminLink: method(object({ deviceId: number().int().nonnegative() }), DeviceAdminLinkSchema.nullable(), { auth: "admin" }) }
13455
+ };
13456
+ /**
13457
+ * Query keys that may never appear on an admin link. A credential smuggled as
13458
+ * `?password=` is the same leak as userinfo, in a form the userinfo check
13459
+ * cannot see: it survives copy-paste, referrer headers and proxy logs
13460
+ * identically.
13461
+ */
13462
+ var CREDENTIAL_QUERY_KEYS = [
13463
+ "password",
13464
+ "passwd",
13465
+ "pwd",
13466
+ "pass",
13467
+ "user",
13468
+ "username",
13469
+ "usr",
13470
+ "login",
13471
+ "token",
13472
+ "access_token",
13473
+ "auth",
13474
+ "authorization",
13475
+ "apikey",
13476
+ "api_key",
13477
+ "secret",
13478
+ "credential",
13479
+ "credentials",
13480
+ "session",
13481
+ "sessionid",
13482
+ "key"
13483
+ ];
13484
+ /**
13485
+ * The same userinfo shape `scripts/check-no-credential-urls-in-fixtures.ts`
13486
+ * scans recorded fixtures for, applied to what we are about to EMIT. Kept
13487
+ * structurally identical on purpose: a URL this function returns is a URL that
13488
+ * guard would pass.
13489
+ */
13490
+ var CREDENTIAL_URL = /[a-z][a-z0-9+.-]*:\/\/[^/\s:@'"]+:[^/\s:@'"]+@/i;
13491
+ /** A host that is safe to place in an authority component verbatim. */
13492
+ var PLAIN_HOST = /^[a-zA-Z0-9._-]+$/;
13493
+ /** A bracketed IPv6 literal, the only other authority form we emit. */
13494
+ var IPV6_HOST = /^\[[0-9a-fA-F:.]+\]$/;
13495
+ function defaultPortFor(scheme) {
13496
+ return scheme === "https" ? 443 : 80;
13497
+ }
13498
+ /**
13499
+ * Build the admin-page URL, or refuse by name.
13500
+ *
13501
+ * The refusal is never thrown: a provider answering "no page for this device"
13502
+ * is an ordinary answer (`getAdminLink` → `null`), and a throw here would turn
13503
+ * a missing host on one device into a failed query for the whole surface.
13504
+ */
13505
+ function buildDeviceAdminUrl(parts) {
13506
+ const host = parts.host.trim();
13507
+ if (host.length === 0) return {
13508
+ ok: false,
13509
+ reason: "empty-host"
13510
+ };
13511
+ if (host.includes("@")) return {
13512
+ ok: false,
13513
+ reason: "host-carries-userinfo"
13514
+ };
13515
+ if (!PLAIN_HOST.test(host) && !IPV6_HOST.test(host)) return {
13516
+ ok: false,
13517
+ reason: "host-not-plain"
13518
+ };
13519
+ if (parts.port !== null) {
13520
+ if (!Number.isInteger(parts.port) || parts.port < 1 || parts.port > 65535) return {
13521
+ ok: false,
13522
+ reason: "port-out-of-range"
13523
+ };
13524
+ }
13525
+ if (!parts.path.startsWith("/")) return {
13526
+ ok: false,
13527
+ reason: "path-not-absolute"
13528
+ };
13529
+ const query = parts.query ?? {};
13530
+ for (const key of Object.keys(query)) if (CREDENTIAL_QUERY_KEYS.includes(key.toLowerCase())) return {
13531
+ ok: false,
13532
+ reason: "credential-query-key"
13533
+ };
13534
+ const authority = parts.port === null || parts.port === defaultPortFor(parts.scheme) ? host : `${host}:${String(parts.port)}`;
13535
+ const search = new URLSearchParams();
13536
+ for (const [key, value] of Object.entries(query)) search.append(key, value);
13537
+ const suffix = search.size > 0 ? `?${search.toString()}` : "";
13538
+ const url = `${parts.scheme}://${authority}${parts.path}${suffix}`;
13539
+ if (CREDENTIAL_URL.test(url)) return {
13540
+ ok: false,
13541
+ reason: "userinfo-in-result"
13542
+ };
13543
+ return {
13544
+ ok: true,
13545
+ url
13546
+ };
13547
+ }
13548
+ /**
13426
13549
  * Identity envelope for a device's upstream-system metadata.
13427
13550
  *
13428
13551
  * Two jobs:
@@ -13857,210 +13980,6 @@ method(object({ integrationId: string() }), object({ filters: array(AdoptionFilt
13857
13980
  auth: "admin"
13858
13981
  });
13859
13982
  /**
13860
- * device-admin-link — "this device has a management page of its own, and here
13861
- * is its address".
13862
- *
13863
- * ## Why this is not a `deviceConfig` cap
13864
- *
13865
- * There is nothing to edit. A `deviceConfig` cap (D14) exists so the framework
13866
- * can DERIVE a settings form from `getOptions` + `getStatus` and route a flat
13867
- * patch back through a setter; it costs a `builderId` reducer in
13868
- * `device-config-contribution.ts` and a `*-config-schema.ts` beside it, and it
13869
- * renders a form section. This cap answers ONE question with ONE read and
13870
- * renders a button. Nothing about it is a form, so it carries no `deviceConfig`
13871
- * block, no `settings`, no `runtimeState` and no reducer — exactly like
13872
- * `reboot`, the other pure-RPC device-native cap.
13873
- *
13874
- * ## Absent, and the difference between "no page" and "we cannot say"
13875
- *
13876
- * The two are answered at DIFFERENT layers, on purpose:
13877
- *
13878
- * - **"We cannot say"** → the provider never registers the cap for that
13879
- * device. A VeSync humidifier, a Petkit feeder, a Dreame vacuum and a Dreo
13880
- * fan are reached only through a vendor cloud; there is no address to hand
13881
- * out and no page to open. A Tuya plug, a Wyze camera and a Gree air
13882
- * conditioner DO have a LAN IP, and still have no HTTP management page
13883
- * behind it. None of them register, so `deviceManager.getBindings` never
13884
- * lists the cap and no surface asks.
13885
- * - **"This device has no page, and I know that"** → the provider registers
13886
- * and `getAdminLink` returns `null`. This is the answer for a device whose
13887
- * sibling DOES have a page: a Reolink battery camera reached over UDP by
13888
- * `uid` with a blank `host`, an Ecowitt gateway configured in `listener`
13889
- * transport, a Home Assistant broker authenticated by supervisor token
13890
- * (which carries no `baseUrl` at all).
13891
- *
13892
- * Both draw NOTHING. A button that opens a browser error is worse than no
13893
- * button, and D62 is the same rule from the other side: an off switch is
13894
- * reported off, never made to look broken. There is no third state where the
13895
- * UI renders a disabled button "because the device might have a page".
13896
- *
13897
- * ## The URL never carries credentials
13898
- *
13899
- * Not in userinfo, not in a query string. Every provider builds through
13900
- * `buildDeviceAdminUrl` (`device-admin-link-url.ts`), which takes host, port,
13901
- * scheme and path as separate arguments — there is no parameter a secret could
13902
- * arrive in — and re-checks its own output for the `scheme://user:pass@` shape
13903
- * that `scripts/check-no-credential-urls-in-fixtures.ts` bans from recorded
13904
- * output. `scripts/check-admin-link-builder-is-the-only-url-source.ts` is what
13905
- * keeps providers from hand-rolling one anyway.
13906
- *
13907
- * This matters here more than anywhere else in the repo, because every provider
13908
- * that knows a device's host knows its PASSWORD too: `{ host, port, username,
13909
- * password }` sit in one object on Hikvision, Amcrest, Reolink and ONVIF alike,
13910
- * and `http://admin:hunter2@192.168.50.139/` is a URL a browser accepts. The
13911
- * camera's own page will ask for its own login. That is correct, and pre-
13912
- * filling it is the operator's business, not ours.
13913
- *
13914
- * ## It is a LAN fact
13915
- *
13916
- * The URL addresses the device where the NODE can see it. It is not proxied,
13917
- * not made reachable from outside, and not sent anywhere. A surface renders it
13918
- * as a link the operator's own browser follows, on the operator's own network,
13919
- * or renders nothing.
13920
- */
13921
- /**
13922
- * Whose page is it. The distinction is for the OPERATOR, who needs to know
13923
- * before clicking whether he is about to land on a camera's own web server or
13924
- * inside Home Assistant.
13925
- */
13926
- var AdminLinkTargetEnum = _enum(["device", "integration"]);
13927
- var DeviceAdminLinkSchema = object({
13928
- /**
13929
- * Absolute `http(s)://` URL. Built by `buildDeviceAdminUrl` and therefore
13930
- * free of userinfo and of any credential-shaped query key.
13931
- */
13932
- url: string(),
13933
- /**
13934
- * What the surface calls it — "Web UI", "Home Assistant", "UniFi controller".
13935
- * The PROVIDER names it, because only the provider knows what the page is;
13936
- * a UI that invented the label from the addon id would call the Home
13937
- * Assistant device page "Provider Homeassistant".
13938
- */
13939
- label: string(),
13940
- target: AdminLinkTargetEnum,
13941
- /**
13942
- * Host the URL points at, without scheme, port or path — for the tooltip, so
13943
- * an operator can see WHERE the button goes before he follows it. Redundant
13944
- * with `url` by construction; carried separately so no surface has to parse
13945
- * a URL to show it.
13946
- */
13947
- host: string()
13948
- });
13949
- var deviceAdminLinkCapability = {
13950
- name: "device-admin-link",
13951
- scope: "device",
13952
- deviceNative: true,
13953
- mode: "singleton",
13954
- methods: {
13955
- /**
13956
- * The device's management page, or `null` when this device has none.
13957
- *
13958
- * `auth: 'admin'` deliberately. This is administration, not actuation —
13959
- * the same bucket as `reboot` and `camera-credentials`, and explicitly NOT
13960
- * the actuation set `scripts/check-actuation-not-admin.ts` protects (D403).
13961
- * The URL is also a statement about the LAN, which a household member with
13962
- * a `view` grant on a light has no reason to be handed.
13963
- *
13964
- * The surfaces gate on the QUERY, never on a role they guessed: a caller
13965
- * without the right loses the query and draws nothing, which is the same
13966
- * thing a device with no page draws. There is no path on which a button
13967
- * appears and then fails — the D403 failure mode, from the other end.
13968
- */
13969
- getAdminLink: method(object({ deviceId: number().int().nonnegative() }), DeviceAdminLinkSchema.nullable(), { auth: "admin" }) }
13970
- };
13971
- /**
13972
- * Query keys that may never appear on an admin link. A credential smuggled as
13973
- * `?password=` is the same leak as userinfo, in a form the userinfo check
13974
- * cannot see: it survives copy-paste, referrer headers and proxy logs
13975
- * identically.
13976
- */
13977
- var CREDENTIAL_QUERY_KEYS = [
13978
- "password",
13979
- "passwd",
13980
- "pwd",
13981
- "pass",
13982
- "user",
13983
- "username",
13984
- "usr",
13985
- "login",
13986
- "token",
13987
- "access_token",
13988
- "auth",
13989
- "authorization",
13990
- "apikey",
13991
- "api_key",
13992
- "secret",
13993
- "credential",
13994
- "credentials",
13995
- "session",
13996
- "sessionid",
13997
- "key"
13998
- ];
13999
- /**
14000
- * The same userinfo shape `scripts/check-no-credential-urls-in-fixtures.ts`
14001
- * scans recorded fixtures for, applied to what we are about to EMIT. Kept
14002
- * structurally identical on purpose: a URL this function returns is a URL that
14003
- * guard would pass.
14004
- */
14005
- var CREDENTIAL_URL = /[a-z][a-z0-9+.-]*:\/\/[^/\s:@'"]+:[^/\s:@'"]+@/i;
14006
- /** A host that is safe to place in an authority component verbatim. */
14007
- var PLAIN_HOST = /^[a-zA-Z0-9._-]+$/;
14008
- /** A bracketed IPv6 literal, the only other authority form we emit. */
14009
- var IPV6_HOST = /^\[[0-9a-fA-F:.]+\]$/;
14010
- function defaultPortFor(scheme) {
14011
- return scheme === "https" ? 443 : 80;
14012
- }
14013
- /**
14014
- * Build the admin-page URL, or refuse by name.
14015
- *
14016
- * The refusal is never thrown: a provider answering "no page for this device"
14017
- * is an ordinary answer (`getAdminLink` → `null`), and a throw here would turn
14018
- * a missing host on one device into a failed query for the whole surface.
14019
- */
14020
- function buildDeviceAdminUrl(parts) {
14021
- const host = parts.host.trim();
14022
- if (host.length === 0) return {
14023
- ok: false,
14024
- reason: "empty-host"
14025
- };
14026
- if (host.includes("@")) return {
14027
- ok: false,
14028
- reason: "host-carries-userinfo"
14029
- };
14030
- if (!PLAIN_HOST.test(host) && !IPV6_HOST.test(host)) return {
14031
- ok: false,
14032
- reason: "host-not-plain"
14033
- };
14034
- if (parts.port !== null) {
14035
- if (!Number.isInteger(parts.port) || parts.port < 1 || parts.port > 65535) return {
14036
- ok: false,
14037
- reason: "port-out-of-range"
14038
- };
14039
- }
14040
- if (!parts.path.startsWith("/")) return {
14041
- ok: false,
14042
- reason: "path-not-absolute"
14043
- };
14044
- const query = parts.query ?? {};
14045
- for (const key of Object.keys(query)) if (CREDENTIAL_QUERY_KEYS.includes(key.toLowerCase())) return {
14046
- ok: false,
14047
- reason: "credential-query-key"
14048
- };
14049
- const authority = parts.port === null || parts.port === defaultPortFor(parts.scheme) ? host : `${host}:${String(parts.port)}`;
14050
- const search = new URLSearchParams();
14051
- for (const [key, value] of Object.entries(query)) search.append(key, value);
14052
- const suffix = search.size > 0 ? `?${search.toString()}` : "";
14053
- const url = `${parts.scheme}://${authority}${parts.path}${suffix}`;
14054
- if (CREDENTIAL_URL.test(url)) return {
14055
- ok: false,
14056
- reason: "userinfo-in-result"
14057
- };
14058
- return {
14059
- ok: true,
14060
- url
14061
- };
14062
- }
14063
- /**
14064
13983
  * `device-export` — collection cap for addons that export camstack
14065
13984
  * devices to external ecosystems (HomeAssistant via MQTT discovery,
14066
13985
  * HomeKit/HAP, Alexa Smart Home, …).
@@ -24462,6 +24381,87 @@ method(_void(), ProviderInfoSchema, { auth: "admin" }), method(object({ config:
24462
24381
  kind: "mutation",
24463
24382
  auth: "admin"
24464
24383
  });
24384
+ /**
24385
+ * The signals a device can emit to WAKE its own stream.
24386
+ *
24387
+ * A camera whose stream is built on demand sleeps until something asks for it,
24388
+ * and "something" cannot be a consumer that is merely attached — a Frigate-style
24389
+ * puller holds a session open for ever, and treating that as demand would keep
24390
+ * a battery camera awake for ever, which is the whole thing the battery is for
24391
+ * (D173). So the wake has to come from the CAMERA: an event it noticed by
24392
+ * itself, with no stream running.
24393
+ *
24394
+ * ## The vocabulary is the PROVIDER'S, not ours
24395
+ *
24396
+ * Like `consumables`, this cap declares no vocabulary of its own. A provider
24397
+ * names each signal with a `code` it chooses and a `label` an operator reads.
24398
+ * Reolink offers motion and camera-native detection; another provider may offer
24399
+ * a tamper, a doorbell press, a PIR, or something no camera in this fleet has
24400
+ * yet. A fixed enum here would mean every new signal is a framework release.
24401
+ *
24402
+ * It is deliberately NOT derived from the caps a device already binds. Whether
24403
+ * a camera CAN push firmware motion is expressed by `motionSources` containing
24404
+ * `'onboard'`, and whether it does AI on-camera by the `native-object-detection`
24405
+ * binding — but both answer "what drives the detection pipeline", which is a
24406
+ * different question from "what may wake a sleeping stream". A camera can do
24407
+ * the first and not be trusted with the second, and the operator picks per
24408
+ * camera. Two questions, two authorities.
24409
+ *
24410
+ * ## Availability is not permission
24411
+ *
24412
+ * `listSignals` says what the device CAN emit. Whether a given signal actually
24413
+ * wakes the stream is the operator's per-camera choice, held by the broker
24414
+ * alongside the cooldown — see the stream-broker cap's wake settings. A
24415
+ * provider declaring a signal is not a provider enabling it.
24416
+ */
24417
+ /** One signal a device can emit. */
24418
+ var StreamSignalSchema = object({
24419
+ /** Stable id chosen by the provider, e.g. `'motion'`, `'person'`, `'tamper'`. */
24420
+ code: string().min(1),
24421
+ /** What an operator reads in the picker. The provider's own wording. */
24422
+ label: string().min(1),
24423
+ /**
24424
+ * Whether the provider recommends this signal ON when a camera is first set
24425
+ * up. A provider knows which of its signals are cheap and reliable; an
24426
+ * operator should not have to discover that by trial. Reolink recommends
24427
+ * both of its own.
24428
+ */
24429
+ recommended: boolean()
24430
+ });
24431
+ var StreamSignalsStatusSchema = object({
24432
+ signals: array(StreamSignalSchema),
24433
+ lastFetchedAt: number()
24434
+ });
24435
+ var streamSignalsCapability = {
24436
+ name: "stream-signals",
24437
+ scope: "device",
24438
+ deviceNative: true,
24439
+ mode: "singleton",
24440
+ deviceTypes: Object.values(DeviceType),
24441
+ runtimeState: StreamSignalsStatusSchema,
24442
+ /**
24443
+ * Runtime-state durability: **session** — mirrored in RAM, never written.
24444
+ *
24445
+ * The slice holds what the DEVICE says it can emit. That is a probed fact,
24446
+ * not an operator choice: the provider re-declares it on every registration,
24447
+ * so losing it loses nothing and persisting it would freeze an answer the
24448
+ * camera is entitled to change. Measured the same day on the sibling case —
24449
+ * `native-object-detection.supportedClasses` was persisted, and a firmware
24450
+ * class the camera really detected stayed missing for the life of the row
24451
+ * because the fix could not reach it.
24452
+ *
24453
+ * See `RuntimeStateDurability`. Enforced by
24454
+ * `scripts/check-runtime-state-durability.ts`.
24455
+ */
24456
+ durability: "session",
24457
+ methods: {
24458
+ /**
24459
+ * What this device can emit. Empty is a valid and common answer — most
24460
+ * cameras have nothing to offer here, and an empty list is what makes the
24461
+ * broker's picker show nothing rather than a false choice.
24462
+ */
24463
+ listSignals: method(_void(), array(StreamSignalSchema).readonly()) }
24464
+ };
24465
24465
  /** Profile-exported FormBuilder schema. Shape is ConfigUISchema at the UI. */
24466
24466
  var ProfileSettingsSchemaBridge = unknown().nullable();
24467
24467
  var ProfileSettingsBagSchema = record(string(), unknown());
@@ -25502,27 +25502,74 @@ var ClipStreamDialSchema = object({
25502
25502
  audioReason: ClipStreamAudioReasonSchema.optional()
25503
25503
  });
25504
25504
  /**
25505
- * The playback rates a clip can be DELIVERED at, ascending, always with `1`.
25505
+ * The playback rates the broker can pace over media it HOLDS, ascending,
25506
+ * always with `1` — and the WIDEST ladder there is. It is the domain the
25507
+ * broker's `clampPlaybackRate` is derived from, at both ends.
25506
25508
  *
25507
25509
  * These are the BROKER's: it re-paces frames it has already demuxed — the
25508
25510
  * `MonotonicClock` divides source elapsed time by the factor and the pacer
25509
- * pushes that much faster — so the domain is the recorded one, {0} ∪ [0.25, 4],
25510
- * and this is the discrete ladder drawn from it. `1.5` is in it because a
25511
- * re-pacer has no reason to refuse it.
25512
- *
25513
- * `8` and `16` are deliberately NOT here. They are the CAMERA's own
25514
- * `<playSpeed>` (Reolink cmd-5 replay), a different mechanism, still unwired
25515
- * (D597, D600) — a rate change there costs a new dial and a new stream, and
25516
- * the camera's 8x would need a resample the clip audio path has no decoder
25517
- * for. Offering them today accepts a rate and delivers 1x, which is the whole
25518
- * defect this list exists to end (D612). When `playSpeed` IS wired its rates
25519
- * join THIS array — a second list elsewhere is the second authority D62
25520
- * forbids.
25521
- *
25522
- * Every entry must survive the broker's `clampPlaybackRate` unchanged: a set
25523
- * that offers what the clamp then moves is the same lie one step later.
25511
+ * pushes that much faster. `1.5` is in it because a re-pacer has no reason to
25512
+ * refuse it.
25513
+ *
25514
+ * **`8` is here since D621, and it is the pacer's, not a camera's.** D620
25515
+ * measured the thing that was assumed for a year and was never true: a
25516
+ * Reolink `<playSpeed>` does not time-compress anything. At 1, 2, 4 and 8 the
25517
+ * transfer is byte-identical — same 947 472 bytes, same 594 access units,
25518
+ * same 39.855 s presentation span, same 624 AAC frames — and only the wall
25519
+ * clock moves. It buys SUPPLY, never speed. So there was never a second
25520
+ * mechanism to wire for 8×: there is one, this one, and what it needs is
25521
+ * media in hand and a clamp that does not move the number.
25522
+ *
25523
+ * **`16` is deliberately NOT here, and will not join by widening this array.**
25524
+ * The camera's `playSpeed 16` is not a rate at all but an I-frame-only MODE —
25525
+ * measured on 592: 10 access units for a whole 36.3 s sub clip, 20 for the
25526
+ * main twin at a 2 025 ms median spacing, and no audio track. That is
25527
+ * different CONTENT, a stream of its own, and the honest broker-side twin of
25528
+ * it would be a pacer that DROPS whole GOPs rather than one that pushes 16×
25529
+ * the bitrate at a live WebRTC track. Neither exists. A `16` in this array
25530
+ * today would be a rate accepted and delivered at 8 — D612's defect, which
25531
+ * this list exists to end, one number further along.
25532
+ *
25533
+ * Every entry must survive the broker's `clampPlaybackRate` unchanged. Since
25534
+ * D621 that is structural rather than a discipline: the clamp reads this
25535
+ * array's own ends. What still has to be proved behaviourally — and is, in
25536
+ * the broker's `clip-stream-feeder.spec` — is that the PACER really empties a
25537
+ * clip `rate` times faster, because a clamp agreeing with a ladder is a
25538
+ * constant compared against itself.
25539
+ *
25540
+ * Narrower ladders exist for transports whose SUPPLY is bounded; they are
25541
+ * subsets of this one ({@link CLIP_STREAM_SOURCE_RATES},
25542
+ * {@link CLIP_REALTIME_SOURCE_RATES}).
25524
25543
  */
25525
25544
  var CLIP_BROKER_PACED_RATES = [
25545
+ .25,
25546
+ .5,
25547
+ 1,
25548
+ 1.5,
25549
+ 2,
25550
+ 4,
25551
+ 8
25552
+ ];
25553
+ /**
25554
+ * The rates a provider-STREAMED clip can be delivered at — a subset of
25555
+ * {@link CLIP_BROKER_PACED_RATES}, and frozen below it on purpose (D621).
25556
+ *
25557
+ * A `stream` clip's media does not exist yet: it arrives on a socket from the
25558
+ * camera while the pacer consumes it. The pacer takes `rate` seconds of media
25559
+ * per second of wall clock, so the ceiling is whatever the SOURCE supplies,
25560
+ * and that is a measurement per vendor rather than a preference.
25561
+ *
25562
+ * Reolink, the one provider on this envelope, was measured on 592
25563
+ * (2026-09-23, D620): with the `<ReplaySeek>` that 0.11.1 sends before every
25564
+ * replay, a sub clip arrives at **1.2×** and a main twin at **1.37×**. The
25565
+ * ladder below is therefore ALREADY beyond this transport above 1 — the D612
25566
+ * defect returned through a door nobody opened — and D620 fixed the repair
25567
+ * order: the supply first, the ladder after. So this array does not move with
25568
+ * the broker's, and it does not gain `8`; what it gains, when the library
25569
+ * forwards a `<playSpeed>` large enough to feed the rate being paced over it,
25570
+ * is the right to be widened on a measurement rather than shortened on one.
25571
+ */
25572
+ var CLIP_STREAM_SOURCE_RATES = [
25526
25573
  .25,
25527
25574
  .5,
25528
25575
  1,
@@ -26007,7 +26054,7 @@ var CLIP_PLAYBACK_OPTIONS = {
26007
26054
  seek: "forward",
26008
26055
  stepBack: false,
26009
26056
  scrub: false,
26010
- rates: CLIP_BROKER_PACED_RATES
26057
+ rates: CLIP_STREAM_SOURCE_RATES
26011
26058
  },
26012
26059
  /**
26013
26060
  * A `stream` whose SOURCE runs at realtime — a Hikvision RTSP replay.
@@ -27391,6 +27438,143 @@ DeviceType.Camera, method(object({ deviceId: number() }), CameraCredentialsSchem
27391
27438
  auth: "admin"
27392
27439
  });
27393
27440
  /**
27441
+ * camera-grid-layout — the geometry of a COMPOSITE camera, on the camera's own
27442
+ * page.
27443
+ *
27444
+ * ## Why this is a capability and not an addon settings schema
27445
+ *
27446
+ * It was one, and it did not render. The addon declared the editor as a
27447
+ * `type: 'widget'` field inside its own `deviceSettingsSchema()`; the hub
27448
+ * returned that section correctly and `ConfigFormField` renders `type:'widget'`
27449
+ * perfectly well — and nothing ever asked camera-grid for it. The Cluster →
27450
+ * Pipeline → Device Overrides page interrogates a HAND-WRITTEN list of four
27451
+ * addons (`PIPELINE_CLUSTER_DEVICE_ADDONS`), whose own comment says an addon
27452
+ * not on it "falls off silently".
27453
+ *
27454
+ * Adding a fifth name to that list would have been the wrong fix twice over:
27455
+ * that page is per-camera DETECTION tuning, and a grid's geometry belongs
27456
+ * beside PTZ and motion zones on the camera itself. The device page is
27457
+ * BINDING-driven (D12), so the way in is a capability bound to the device —
27458
+ * and this cap carries its section the way `recording` does, by RETURNING it
27459
+ * from `getDeviceSettingsContribution`.
27460
+ *
27461
+ * Seven other widgets are still declared the other way, through a
27462
+ * `deviceConfig.ui` block the framework derives a section from. That route
27463
+ * gives the addon no say in where its own panel lands and no way to decline
27464
+ * for a device the panel does not suit, which is why this one does not use it.
27465
+ *
27466
+ * ## Why one addon may implement it
27467
+ *
27468
+ * It is a device-scoped NATIVE cap, registered by the grid camera device
27469
+ * itself. Nothing else declares a composite camera, so nothing else has a
27470
+ * layout — and the device-scoped route means the widget asks THE camera, not
27471
+ * "the camera-grid addon", which is what let the old custom-action pair be
27472
+ * reached only by a caller that already knew the addon id.
27473
+ *
27474
+ * ## The tab
27475
+ *
27476
+ * `streaming`, not a top-tab of its own. A grid's geometry IS what its stream
27477
+ * is, so the Streaming tab is where it belongs; a `grid` top-tab would need an
27478
+ * entry in `WELL_KNOWN_TAB_MAP` or the device page renders the raw id as the
27479
+ * label (measured on the robot camera, 2026-09-06 — a tab called "navigation"
27480
+ * next to "PTZ").
27481
+ */
27482
+ /** A rectangle in normalized [0,1] coordinates of whatever contains it. */
27483
+ var GridNormalizedRectSchema = object({
27484
+ x: number().min(0).max(1),
27485
+ y: number().min(0).max(1),
27486
+ width: number().gt(0).max(1),
27487
+ height: number().gt(0).max(1)
27488
+ });
27489
+ /**
27490
+ * One source camera, the part of its picture taken, and where that part lands.
27491
+ *
27492
+ * Both rectangles are NORMALIZED (D519): a source camera can change resolution
27493
+ * — a profile switch, a firmware update, a substream that comes back different
27494
+ * — and a stored PIXEL rectangle would quietly start cutting the wrong region,
27495
+ * which is the class of bug nobody files.
27496
+ */
27497
+ var GridLayoutCellSchema = object({
27498
+ deviceId: number().int().positive(),
27499
+ /** The part of the SOURCE taken, normalized against the source. */
27500
+ source: GridNormalizedRectSchema,
27501
+ /** Where it lands, normalized against the CANVAS. */
27502
+ cell: GridNormalizedRectSchema
27503
+ });
27504
+ /**
27505
+ * Which profiles this grid can actually compose, and why not.
27506
+ *
27507
+ * A grid's `high` composes its sources' `high` and its `low` their `low`, so a
27508
+ * profile is on offer only when EVERY source can serve it. The refusal NAMES
27509
+ * the sources, because "this grid has no low" is not a finding — "615 has no
27510
+ * low" is, and it is the one an operator can act on.
27511
+ */
27512
+ var GridProfileOfferSchema = object({
27513
+ profile: _enum([
27514
+ "high",
27515
+ "mid",
27516
+ "low"
27517
+ ]),
27518
+ offered: boolean(),
27519
+ /** Sources that cannot serve it. Empty when it is offered, or when there are no cells. */
27520
+ missingSources: array(number().int().positive()),
27521
+ /**
27522
+ * The canvas this profile composes onto, `WxH`, or empty when it is not
27523
+ * offered. DERIVED from the cells and the sources' own size at this profile —
27524
+ * it is reported because nothing else in the system would ever say what the
27525
+ * grid came out as, and because it is the number an operator would otherwise
27526
+ * expect to type.
27527
+ */
27528
+ canvas: string(),
27529
+ /**
27530
+ * Whether this profile is PUBLISHED, of the ones the grid could serve.
27531
+ *
27532
+ * A grid's `high` is composed of its sources' `high`, so on a 4K fleet it is
27533
+ * a 4K canvas built from 4K decodes — something to opt into, not something a
27534
+ * viewer's adaptive should be handed by climbing to the top rung it can see.
27535
+ * Default is `mid` + `low`.
27536
+ */
27537
+ published: boolean()
27538
+ });
27539
+ var GridLayoutViewSchema = object({
27540
+ /** The persisted grid row this camera was declared from. */
27541
+ instanceId: string(),
27542
+ deviceId: number().int().nonnegative(),
27543
+ name: string(),
27544
+ /**
27545
+ * NO canvas size. A grid's resolution is not authored: each profile derives
27546
+ * its own from the cells and its sources' dimensions. The two numbers that
27547
+ * used to be here were a text field that silently decided both how much the
27548
+ * composite cost and how sharp it was — see `profiles[].canvas` for what it
27549
+ * came out as.
27550
+ */
27551
+ fps: number().int(),
27552
+ cells: array(GridLayoutCellSchema),
27553
+ /** What the catalog will publish, and what it refuses to. Read-only. */
27554
+ profiles: array(GridProfileOfferSchema)
27555
+ });
27556
+ var GridLayoutPatchSchema = object({
27557
+ deviceId: number().int().nonnegative(),
27558
+ name: string().min(1).max(160).optional(),
27559
+ fps: number().int().min(1).max(60).optional(),
27560
+ /** Which profiles to publish. See `GridProfileOffer.published`. */
27561
+ publishedProfiles: array(_enum([
27562
+ "high",
27563
+ "mid",
27564
+ "low"
27565
+ ])).max(3).optional(),
27566
+ /**
27567
+ * The whole cell list at once. A per-cell patch would need an ordering the
27568
+ * editor does not have, and a half-applied layout is a picture nobody asked
27569
+ * for.
27570
+ */
27571
+ cells: array(GridLayoutCellSchema).max(16)
27572
+ });
27573
+ DeviceType.Camera, method(object({ deviceId: number().int().nonnegative() }), GridLayoutViewSchema.nullable(), { auth: "admin" }), method(GridLayoutPatchSchema, GridLayoutViewSchema, {
27574
+ kind: "mutation",
27575
+ auth: "admin"
27576
+ });
27577
+ /**
27394
27578
  * Carbon-monoxide alarm sensor. Drives Home Assistant `binary_sensor`
27395
27579
  * entries with `device_class: carbon_monoxide`. Push-driven.
27396
27580
  */
@@ -28193,764 +28377,224 @@ var dayNightCapability = {
28193
28377
  volatileStateFields: ["lastFetchedAt"]
28194
28378
  };
28195
28379
  /**
28196
- * Vendor-neutral **onboard** recording + storage cap — what the CAMERA
28197
- * writes to the CAMERA's own card, on the camera's own schedule.
28198
- *
28199
- * This is NOT `recording.cap.ts`. That one is CamStack's recorder: our
28200
- * footage ledger, our storage locations, our retention. This one has a
28201
- * different authority — the camera's firmware — and per D62 it stores
28202
- * nothing of its own. Every value here is read from the camera and every
28203
- * write goes back to the camera; there is no CamStack-side mirror that
28204
- * could disagree with the device.
28205
- *
28206
- * ## One shape, two firmwares
28207
- *
28208
- * Measured 2026-09-22 against the live fleet:
28209
- *
28210
- * | fact | Hikvision (ISAPI) | Reolink (Baichuan) |
28211
- * | --- | --- | --- |
28212
- * | storage | `ContentMgmt/Storage` `<hdd>` rows: status, capacity, freeSpace (MB) | `getHddInfoList` (cmd 102): `mount`, `format`, `capacity` GB + `capacityM` MB remainder |
28213
- * | tracks | several (101 **and** 103 on both 1436 and 3833), each with its own schedule | one per channel |
28214
- * | schedule | per track, 7 `ScheduleAction` blocks: DayOfWeek + TimeOfDay range + ONE `ActionRecordingMode` | per trigger type, a 168-char weekly HOUR mask |
28215
- * | triggers | `CMR`, `MOTION` | `Normal`, `MD`, `people`, `vehicle`, `dog_cat`, `crossline`, `intrude`, `loitering` |
28216
- * | pre-record | `PreRecordTimeSeconds` | `preRecordTime` |
28217
- * | post-record | `PostRecordTimeSeconds` | `recordDelayTime` |
28218
- * | overwrite | per track `LoopEnable` | `cycle`, with `cycleList` enumerating the accepted values |
28219
- * | segment length | not exposed on V5.7.1 | `packageTime` (minutes) |
28220
- *
28221
- * The two schedule models look different and are the same thing in
28222
- * different coordinates: both answer "for this trigger, during which
28223
- * weekly windows does the camera record". {@link RecordWindow} is that
28224
- * question in one shape — Hikvision's ranges map straight onto it,
28225
- * Reolink's mask expands into hour-aligned windows.
28226
- *
28227
- * ## Union, not intersection
28228
- *
28229
- * **The same fields exist on every camera.** What differs per device is
28230
- * which VALUES that device accepts, and that is what {@link
28231
- * RecordingOnboardOptions} reports — a `{ readable, writable, reason }`
28232
- * per field plus the schedule's own limits. A control a camera cannot
28233
- * honour is rendered DISABLED WITH ITS REASON, never missing and never
28234
- * dead: disabled must not look like broken.
28235
- *
28236
- * ## Refusal by name
28237
- *
28238
- * A write a camera cannot honour is refused with a sentence the operator
28239
- * can read — never accepted and dropped. Both providers refuse through
28240
- * {@link describeOnboardRefusal}, so the vocabulary is one function and
28241
- * one test, not two hand-written vendor opinions.
28380
+ * Generic device-level status snapshot. Auto-registered by `BaseDevice`
28381
+ * for every device, regardless of provider — the kernel needs a uniform
28382
+ * cap-keyed slice for the basic device flags every consumer expects to
28383
+ * read across processes (the `online` flag in particular). Driver-specific
28384
+ * caps (`battery`, `doorbell`, …) carry their domain-specific state on
28385
+ * their own slices.
28242
28386
  *
28243
- * Follows the D14 `deviceConfig` archetype (see `stream-params.cap.ts`):
28244
- * `getOptions` advertises per-camera availability, `getStatus` (auto-
28245
- * injected from `status`) reports the live values, and a single
28246
- * `setSettings` mutation applies a partial change. No hand-written
28247
- * settings-contribution methods.
28387
+ * Pattern is identical to `battery`: schema-bearing `runtimeState`,
28388
+ * empty `methods`, single change event. Reads land at
28389
+ * `runtimeState.getCapState('device-status')`; writes at
28390
+ * `runtimeState.setCapState('device-status', …)`. Cross-process
28391
+ * consumers reach the same data via the `device-state` cap router
28392
+ * (`getCapSlice({deviceId, capName: 'device-status'})`).
28248
28393
  */
28394
+ var DeviceStatusSchema = object({
28395
+ /**
28396
+ * Device-level liveness. Drivers flip via `markOnline(boolean)` on
28397
+ * `BaseDevice`. Provider semantics vary — RTSP aggregates broker
28398
+ * stream-health, Reolink reads firmware push events, ONVIF tracks
28399
+ * ping responses. This cap intentionally does NOT prescribe which
28400
+ * signal drives the flag.
28401
+ */
28402
+ online: boolean(),
28403
+ /** Ms epoch of the last `online` transition. Lets consumers tell
28404
+ * apart "just came online" from "still online". */
28405
+ lastChangedAt: number()
28406
+ });
28407
+ var deviceStatusCapability = {
28408
+ name: "device-status",
28409
+ scope: "device",
28410
+ deviceNative: true,
28411
+ mode: "singleton",
28412
+ methods: {},
28413
+ events: {
28414
+ /** Emitted when `online` transitions. Mirrors the semantics of
28415
+ * `battery.onStatusChanged`. */
28416
+ onStatusChanged: { data: object({
28417
+ deviceId: number(),
28418
+ status: DeviceStatusSchema
28419
+ }) } },
28420
+ status: {
28421
+ schema: DeviceStatusSchema,
28422
+ kind: "push"
28423
+ },
28424
+ runtimeState: DeviceStatusSchema,
28425
+ /**
28426
+ * Runtime-state durability: **restored** — the previous observation is what makes the first reading after a restart a COMPARISON instead of a phantom transition (D130). 32 real flips across 16 devices in 25 min — the busiest slice in the cold half.
28427
+ *
28428
+ * See `RuntimeStateDurability`. Enforced by
28429
+ * `scripts/check-runtime-state-durability.ts`.
28430
+ */
28431
+ durability: "restored",
28432
+ /** Clock fields: written, but excluded from the compare that decides
28433
+ * whether persisting is worth a SQLite commit. */
28434
+ volatileStateFields: ["lastChangedAt"]
28435
+ };
28249
28436
  /**
28250
- * What makes the camera start recording during a window.
28437
+ * Doorbell button cap. Two kinds of providers coexist behind this cap
28438
+ * name (same pattern as `snapshot`):
28251
28439
  *
28252
- * The union of both vendors' vocabularies. `continuous` is Hikvision's
28253
- * `CMR` and Reolink's `Normal`; `motion` is `MOTION` / `MD`. The
28254
- * object-class triggers are Reolink-only today and the smart-event ones
28255
- * (`lineCrossing`, `intrusion`, `loitering`) are Reolink-only on the
28256
- * firmwares measured — a camera that cannot record on a trigger simply
28257
- * does not list it in `options.schedule.triggers`, and a window naming
28258
- * it is REFUSED, not dropped.
28259
- */
28260
- var RecordTriggerSchema = _enum([
28261
- "continuous",
28262
- "motion",
28263
- "person",
28264
- "vehicle",
28265
- "animal",
28266
- "lineCrossing",
28267
- "intrusion",
28268
- "loitering",
28269
- "alarmInput"
28270
- ]);
28271
- /**
28272
- * One weekly recording window: "on `day`, from `startMinute` to
28273
- * `endMinute`, record on `trigger`".
28440
+ * - **Native** providers: registered per-device by device-driver
28441
+ * addons via `ctx.registerNativeCap` — either on a
28442
+ * `DeviceType.Button` accessory with `role: DeviceRole.Doorbell`,
28443
+ * or directly on the camera (Reolink registers at camera level).
28444
+ * Emits an `onPressed` event every time the firmware pushes a
28445
+ * ring; status tracks the last press and a pressCount since start
28446
+ * (diagnostic).
28274
28447
  *
28275
- * `day` is 0 = Monday … 6 = Sunday (ISO order, which is also the order
28276
- * both firmwares enumerate). Minutes are local camera time since
28277
- * midnight; `endMinute` may be 1440, meaning end of day — that is
28278
- * Hikvision's literal `24:00` and Reolink's 24th mask slot, and
28279
- * collapsing it to 0 would turn a whole-day window into an empty one.
28448
+ * - **Wrapper** provider: the `virtual-doorbell` system builtin
28449
+ * (`@camstack/system/builtins/doorbell`). Turns ANY binary-ish
28450
+ * device (contact / switch / event-emitter …) into a doorbell for
28451
+ * a camera. `defaultActive: false` — the operator explicitly binds
28452
+ * it per camera in the device-bindings UI, then picks the source
28453
+ * device + trigger in the per-device settings.
28454
+ *
28455
+ * The DeviceEventPropagator re-emits `onPressed` on the camera parent
28456
+ * — subscribers listening at the camera level receive ring events
28457
+ * with `via[]` populated. No code on the parent needed.
28280
28458
  */
28281
- var RecordWindowSchema = object({
28282
- trigger: RecordTriggerSchema,
28283
- day: number().int().min(0).max(6),
28284
- startMinute: number().int().min(0).max(1439),
28285
- endMinute: number().int().min(1).max(1440)
28459
+ var DoorbellStatusSchema = object({
28460
+ /** Ms epoch of the last press. null = never observed since this provider started. */
28461
+ lastPressedAt: number().nullable(),
28462
+ /** Counter since provider start. Resets on reboot. Useful for metrics/debug. */
28463
+ pressCountSinceStart: number()
28286
28464
  });
28287
- /** Status of one physical volume, as the camera itself describes it. */
28288
- var OnboardStorageVolumeSchema = object({
28289
- /** The camera's own id for the volume (`hdd/id`, Reolink `HddInfo/number`). */
28290
- id: string(),
28291
- /** The camera's own name for it, when it gives one (`hddName`). */
28292
- label: string().optional(),
28293
- status: _enum([
28294
- "ok",
28295
- "unformatted",
28296
- "error",
28297
- "offline",
28298
- "unknown"
28299
- ]),
28465
+ var DoorbellPressEventSchema = object({
28466
+ deviceId: number(),
28467
+ timestamp: number()
28468
+ });
28469
+ var doorbellCapability = {
28470
+ name: "doorbell",
28471
+ scope: "device",
28472
+ deviceNative: true,
28473
+ mode: "singleton",
28474
+ kind: "wrapper",
28475
+ defaultActive: false,
28476
+ deviceTypes: [DeviceType.Button, DeviceType.Camera],
28477
+ exposesDeviceSettings: true,
28478
+ methods: {},
28479
+ events: {
28300
28480
  /**
28301
- * Total size in MB, or **null when the camera did not say**.
28302
- *
28303
- * Never 0 for an unreadable value: a measurement that failed is not a
28304
- * measurement (D393), and a card whose size is unknown must not be
28305
- * rendered as a card of size zero.
28481
+ * Fires once per physical press. Reolink delivers via Baichuan
28482
+ * push (`ReolinkSimpleEvent.type === 'doorbell'`). There is no
28483
+ * release/duration — it's a pulse.
28306
28484
  */
28307
- capacityMb: number().nullable(),
28485
+ onPressed: { data: DoorbellPressEventSchema } },
28486
+ status: {
28487
+ schema: DoorbellStatusSchema,
28488
+ kind: "push"
28489
+ },
28308
28490
  /**
28309
- * Free space in MB, or null when unknown.
28491
+ * Runtime-state slice — last press timestamp + lifetime press count.
28492
+ * Mirrored by the kernel and readable via
28493
+ * `device.state.doorbell.value`. UIs can show "last ring 5m ago"
28494
+ * without subscribing.
28495
+ */
28496
+ runtimeState: DoorbellStatusSchema,
28497
+ /**
28498
+ * Runtime-state durability: **restored** — a monotonic accumulator: the slice IS the record. `lastPressedAt` is content here, not a clock, so it is deliberately NOT volatile.
28310
28499
  *
28311
- * **Not a proxy for "has footage".** Measured 2026-09-22: 1436 and
28312
- * 1439 both report exactly 11776 MB free — the fixed reserve a looping
28313
- * card converges on once it has wrapped. At loop steady state the
28314
- * number is identical whether the camera recorded yesterday or stopped
28315
- * a month ago.
28500
+ * See `RuntimeStateDurability`. Enforced by
28501
+ * `scripts/check-runtime-state-durability.ts`.
28316
28502
  */
28317
- freeMb: number().nullable(),
28318
- /** True when the camera reports the volume writable (`property` RW). */
28319
- writable: boolean().optional()
28320
- });
28503
+ durability: "restored"
28504
+ };
28321
28505
  /**
28322
- * What the camera is doing with its own storage, right now.
28323
- *
28324
- * Every scalar is nullable and **null means the camera did not answer**,
28325
- * never a default. A form that seeds `0` from an unanswered read invites
28326
- * the operator to save that 0 back onto the camera.
28506
+ * Enum-state sensor — a string value picked from a finite option set.
28507
+ * Drives HA `sensor` entries with `state_class: enum` (HVAC action
28508
+ * states, weather conditions, contact-source channels, mode strings).
28509
+ * The option set is stable across observations; it is persisted in the
28510
+ * device config blob (via the control slice at adoption) and is NOT
28511
+ * stored in `sourceInfo`.
28327
28512
  */
28328
- var RecordingOnboardStatusSchema = object({
28329
- storage: discriminatedUnion("kind", [
28330
- object({
28331
- kind: literal("present"),
28332
- volumes: array(OnboardStorageVolumeSchema)
28333
- }),
28334
- object({
28335
- kind: literal("absent"),
28336
- reason: string()
28337
- }),
28338
- object({
28339
- kind: literal("unknown"),
28340
- reason: string()
28341
- })
28342
- ]),
28343
- tracks: array(object({
28344
- id: string(),
28345
- enabled: boolean(),
28346
- isVideo: boolean(),
28347
- /** From the camera's own track description. Null when it does not say. */
28348
- codec: string().nullable(),
28349
- resolution: string().nullable(),
28350
- /** Per-track overwrite flag, where the firmware keeps it per track. */
28351
- overwriteWhenFull: boolean().nullable()
28352
- })),
28513
+ /** Locale-render shape for an ISO `value` carried by a `DateTimeSensor`-role
28514
+ * enum sensor: `date` (date-only), `time` (time-only), `datetime` (both). */
28515
+ var EnumSensorDateTimeFormatSchema = _enum([
28516
+ "date",
28517
+ "time",
28518
+ "datetime"
28519
+ ]);
28520
+ var EnumSensorStatusSchema = object({
28521
+ value: string(),
28353
28522
  /**
28354
- * The track the write path targets — the enabled VIDEO one. Null when
28355
- * no track could be identified, which is itself a refusal reason.
28523
+ * Set for `DateTimeSensor`-role sensors so the UI renders the ISO `value`
28524
+ * as a locale date/time/datetime; absent for plain enum sensors. HA
28525
+ * `device_class=timestamp` → `'datetime'`, `device_class=date` → `'date'`,
28526
+ * a time-only sensor → `'time'`.
28356
28527
  */
28357
- primaryTrackId: string().nullable(),
28358
- /** Master "record to the card at all" switch. */
28359
- enabled: boolean().nullable(),
28360
- overwriteWhenFull: boolean().nullable(),
28361
- preRecordSec: number().nullable(),
28362
- postRecordSec: number().nullable(),
28363
- /** Length of one recorded file, in minutes. */
28364
- segmentMinutes: number().nullable(),
28365
- /** The primary track's weekly windows, flattened. */
28366
- windows: array(RecordWindowSchema),
28528
+ format: EnumSensorDateTimeFormatSchema.optional(),
28529
+ /** Ms epoch when the slice was last updated. */
28530
+ lastFetchedAt: number()
28531
+ });
28532
+ var enumSensorCapability = {
28533
+ name: "enum-sensor",
28534
+ scope: "device",
28535
+ deviceNative: true,
28536
+ mode: "singleton",
28537
+ deviceTypes: [DeviceType.Sensor],
28538
+ methods: {},
28539
+ status: {
28540
+ schema: EnumSensorStatusSchema,
28541
+ kind: "push"
28542
+ },
28543
+ runtimeState: EnumSensorStatusSchema,
28367
28544
  /**
28368
- * How many windows the camera described that CamStack could NOT read —
28369
- * an unrecognised trigger, an unparseable clock, a weekday it does not
28370
- * name.
28545
+ * Runtime-state durability: **restored** — as `numeric-sensor`; 80 devices.
28371
28546
  *
28372
- * A dropped window is work the reader threw away, and a schedule that
28373
- * silently shows fewer rows than the camera holds is how an operator
28374
- * saves back a schedule shorter than the one they were looking at
28375
- * (D391). Non-zero means the window list is INCOMPLETE and a write
28376
- * that replaces it would delete what was not shown — which is why a
28377
- * provider reporting a non-zero count also reports the schedule as not
28378
- * writable.
28547
+ * See `RuntimeStateDurability`. Enforced by
28548
+ * `scripts/check-runtime-state-durability.ts`.
28379
28549
  */
28380
- unreadableWindows: number(),
28550
+ durability: "restored",
28551
+ /** Clock fields: written, but excluded from the compare that decides
28552
+ * whether persisting is worth a SQLite commit. */
28553
+ volatileStateFields: ["lastFetchedAt"]
28554
+ };
28555
+ /**
28556
+ * Generic stateless event emitter. Installed on a `DeviceType.EventEmitter`
28557
+ * device. Carries the device's EXACT declared event vocabulary verbatim
28558
+ * (NO normalization). Two shapes:
28559
+ * - structured source (HA `event.*` entity) → `eventTypes` is the fixed
28560
+ * declared vocabulary (e.g. ['press_short','press_long',...]).
28561
+ * - generic/legacy source (HA bus events, e.g. zha_event) → `eventTypes`
28562
+ * is [] (open) and `lastEvent.data` carries the complex payload.
28563
+ * `seq` is monotonic so two identical events still produce distinct slice writes.
28564
+ */
28565
+ var EventFireSchema = object({
28566
+ deviceId: number(),
28567
+ eventType: string(),
28568
+ data: record(string(), unknown()).nullable(),
28569
+ timestamp: number(),
28570
+ seq: number()
28571
+ });
28572
+ var EventEmitterStatusSchema = object({
28573
+ eventTypes: array(string()),
28574
+ lastEvent: EventFireSchema.nullable(),
28575
+ eventCountSinceStart: number()
28576
+ });
28577
+ var eventEmitterCapability = {
28578
+ name: "event-emitter",
28579
+ scope: "device",
28580
+ deviceNative: true,
28581
+ mode: "singleton",
28582
+ deviceTypes: [DeviceType.EventEmitter],
28583
+ methods: {},
28584
+ events: { onEvent: { data: EventFireSchema } },
28585
+ status: {
28586
+ schema: EventEmitterStatusSchema,
28587
+ kind: "push"
28588
+ },
28589
+ runtimeState: EventEmitterStatusSchema,
28381
28590
  /**
28382
- * The camera is scheduled to record and has NO usable storage.
28591
+ * Runtime-state durability: **session** — `eventCountSinceStart` names its own scope.
28383
28592
  *
28384
- * A first-class fact because it is the fleet's most common silent
28385
- * defect: measured 2026-09-22, 1441 and 3831 are both motion-recording
28386
- * to a card that is not there. Neither the schedule nor the storage
28387
- * read says anything wrong on its own; only the pair does.
28388
- */
28389
- recordingToNowhere: boolean(),
28390
- lastFetchedAt: number()
28391
- });
28392
- /** Numeric range descriptor — `{ min, max, step }` per the getOptions convention. */
28393
- var RangeSchema = object({
28394
- min: number(),
28395
- max: number(),
28396
- step: number()
28397
- });
28398
- /**
28399
- * The values a camera actually takes for a numeric field, when they are a SET
28400
- * rather than a range.
28401
- *
28402
- * `{min,max,step}` cannot say what these two firmwares do. Measured on 1436
28403
- * (I91DN) on 2026-09-22 by writing each value and reading it back:
28404
- *
28405
- * - pre-record: `0, 5, 10, 15, 20, 25, 30` and `2147483647` (INT32_MAX, the
28406
- * camera's "no limit" — `-1` and `4294967295` both land on it);
28407
- * - post-record: `5, 10, 30, 60, 120, 300, 600`.
28408
- *
28409
- * Neither is expressible as a step: the first has a sentinel two billion away
28410
- * from its neighbours, the second doubles and then jumps. A range that tried
28411
- * would forbid values the camera takes AND permit values it silently replaces
28412
- * with 5 — wrong in both directions at once.
28413
- *
28414
- * `sentinel` names the member that is not a duration, so a surface can render
28415
- * "no limit" instead of `2147483647` seconds.
28416
- */
28417
- var AllowedValuesSchema = object({
28418
- values: array(number()).min(1),
28419
- sentinel: object({
28420
- value: number(),
28421
- meaning: _enum(["no-limit", "disabled"])
28422
- }).optional()
28423
- });
28424
- /**
28425
- * Per-field availability on ONE camera.
28426
- *
28427
- * The field exists on every camera — this says whether this one can be
28428
- * read and whether it can be written, and `reason` says why not when
28429
- * either is false. The UI renders the control DISABLED with the reason
28430
- * rather than hiding it, so a limitation is legible instead of looking
28431
- * like a missing feature.
28432
- */
28433
- var OnboardFieldSupportSchema = object({
28434
- readable: boolean(),
28435
- writable: boolean(),
28436
- /** Required whenever `readable` or `writable` is false. */
28437
- reason: string().optional()
28438
- });
28439
- /** What this camera's schedule model can express. */
28440
- var OnboardScheduleSupportSchema = object({
28441
- support: OnboardFieldSupportSchema,
28442
- /**
28443
- * The smallest time step the camera can express, in minutes.
28444
- *
28445
- * Hikvision takes arbitrary minutes (`00:05:00`–`23:57:00` observed on
28446
- * 1436's track 103). Reolink's schedule is a 7×24 HOUR mask, so 60. A
28447
- * window whose edges are not a multiple of this is REFUSED rather than
28448
- * quietly rounded — rounding is how an operator's 06:30 becomes 06:00
28449
- * and nothing says so.
28450
- */
28451
- granularityMinutes: number(),
28452
- /** Triggers this camera can record on. A window naming another is refused. */
28453
- triggers: array(RecordTriggerSchema),
28454
- /**
28455
- * False when the camera stores ONE trigger per time range, so two
28456
- * windows overlapping on the same day cannot carry different triggers.
28457
- * True on Reolink, whose mask is per-trigger and independent.
28458
- */
28459
- supportsOverlappingTriggers: boolean()
28460
- });
28461
- var RecordingOnboardOptionsSchema = object({
28462
- enabled: OnboardFieldSupportSchema,
28463
- overwriteWhenFull: OnboardFieldSupportSchema,
28464
- preRecordSec: OnboardFieldSupportSchema,
28465
- preRecordSecRange: RangeSchema.optional(),
28466
- /** Preferred over the range when the camera takes a SET, not a span. */
28467
- preRecordSecAllowed: AllowedValuesSchema.optional(),
28468
- postRecordSec: OnboardFieldSupportSchema,
28469
- postRecordSecRange: RangeSchema.optional(),
28470
- /** Preferred over the range when the camera takes a SET, not a span. */
28471
- postRecordSecAllowed: AllowedValuesSchema.optional(),
28472
- segmentMinutes: OnboardFieldSupportSchema,
28473
- segmentMinutesRange: RangeSchema.optional(),
28474
- /** Preferred over the range when the camera takes a SET, not a span. */
28475
- segmentMinutesAllowed: AllowedValuesSchema.optional(),
28476
- schedule: OnboardScheduleSupportSchema
28477
- });
28478
- /**
28479
- * A partial change. Every field optional.
28480
- *
28481
- * Unlike the other `deviceConfig` caps, a provider here does **NOT**
28482
- * silently ignore a field it cannot support — it refuses, by name,
28483
- * through {@link describeOnboardRefusal}. Silence on a recording setting
28484
- * is the failure D62 exists to prevent: the operator believes the camera
28485
- * is recording the way the form says, and it is not.
28486
- */
28487
- var RecordingOnboardPatchSchema = object({
28488
- enabled: boolean().optional(),
28489
- overwriteWhenFull: boolean().optional(),
28490
- preRecordSec: number().optional(),
28491
- postRecordSec: number().optional(),
28492
- segmentMinutes: number().optional(),
28493
- /** The complete new window set for the primary track — not a delta. */
28494
- windows: array(RecordWindowSchema).optional()
28495
- });
28496
- var recordingOnboardCapability = {
28497
- name: "recording-onboard",
28498
- scope: "device",
28499
- deviceNative: true,
28500
- mode: "singleton",
28501
- deviceTypes: [DeviceType.Camera],
28502
- deviceConfig: { ui: {
28503
- kind: "derived-form",
28504
- builderId: "recording-onboard",
28505
- tab: "recording"
28506
- } },
28507
- methods: {
28508
- getOptions: method(object({ deviceId: number() }), RecordingOnboardOptionsSchema),
28509
- setSettings: method(object({
28510
- deviceId: number(),
28511
- settings: RecordingOnboardPatchSchema
28512
- }), _void(), {
28513
- kind: "mutation",
28514
- auth: "admin"
28515
- })
28516
- },
28517
- status: {
28518
- schema: RecordingOnboardStatusSchema,
28519
- kind: "poll"
28520
- },
28521
- runtimeState: RecordingOnboardStatusSchema,
28522
- /**
28523
- * Runtime-state durability: **restored** — operator-set camera-side
28524
- * recording config; mutation-driven, and the storage half is the last
28525
- * thing the camera said about its own card.
28526
- *
28527
- * See `RuntimeStateDurability`. Enforced by
28528
- * `scripts/check-runtime-state-durability.ts`.
28529
- */
28530
- durability: "restored",
28531
- /** Clock fields: written, but excluded from the compare that decides
28532
- * whether persisting is worth a SQLite commit. */
28533
- volatileStateFields: ["lastFetchedAt"]
28534
- };
28535
- /**
28536
- * Day-of-week names in the cap's index order (0 = Monday), for messages
28537
- * an operator reads and for Hikvision's `<DayOfWeek>` element.
28538
- */
28539
- var DAY_NAMES = [
28540
- "Monday",
28541
- "Tuesday",
28542
- "Wednesday",
28543
- "Thursday",
28544
- "Friday",
28545
- "Saturday",
28546
- "Sunday"
28547
- ];
28548
- /**
28549
- * Does `patch` ask this camera for something it cannot do?
28550
- *
28551
- * Returns the operator-readable reason, or `null` when every field in
28552
- * the patch is within what `options` says this camera accepts. A
28553
- * provider calls this BEFORE touching the camera and throws the string:
28554
- * refusing is the point, and refusing identically on both vendors is why
28555
- * this is one function.
28556
- *
28557
- * The order of checks is the order an operator would read them: the
28558
- * scalar knobs first, then the schedule, because a schedule complaint is
28559
- * longer and a scalar one is usually the real problem.
28560
- */
28561
- function describeOnboardRefusal(options, patch) {
28562
- if (patch.enabled !== void 0 && !options.enabled.writable) return unwritable("the master recording switch", options.enabled.reason);
28563
- if (patch.overwriteWhenFull !== void 0 && !options.overwriteWhenFull.writable) return unwritable("overwrite-when-full", options.overwriteWhenFull.reason);
28564
- const preRefusal = refuseNumeric("pre-record seconds", patch.preRecordSec, options.preRecordSec, options.preRecordSecRange, options.preRecordSecAllowed);
28565
- if (preRefusal) return preRefusal;
28566
- const postRefusal = refuseNumeric("post-record seconds", patch.postRecordSec, options.postRecordSec, options.postRecordSecRange, options.postRecordSecAllowed);
28567
- if (postRefusal) return postRefusal;
28568
- const segmentRefusal = refuseNumeric("segment length (minutes)", patch.segmentMinutes, options.segmentMinutes, options.segmentMinutesRange, options.segmentMinutesAllowed);
28569
- if (segmentRefusal) return segmentRefusal;
28570
- if (patch.windows !== void 0) {
28571
- const scheduleRefusal = refuseSchedule(options, patch.windows);
28572
- if (scheduleRefusal) return scheduleRefusal;
28573
- }
28574
- return null;
28575
- }
28576
- function unwritable(what, reason) {
28577
- return reason ? `this camera cannot change ${what}: ${reason}` : `this camera cannot change ${what}`;
28578
- }
28579
- function refuseNumeric(what, value, support, range, allowed) {
28580
- if (value === void 0) return null;
28581
- if (!support.writable) return unwritable(what, support.reason);
28582
- if (!Number.isFinite(value)) return `${what} must be a number, got ${String(value)}`;
28583
- if (allowed) {
28584
- if (allowed.values.includes(value)) return null;
28585
- const say = (v) => allowed.sentinel !== void 0 && v === allowed.sentinel.value ? allowed.sentinel.meaning === "no-limit" ? "no limit" : "off" : String(v);
28586
- return `this camera accepts ${what} only as ${allowed.values.map(say).join(", ")}; ${say(value)} is not one of them`;
28587
- }
28588
- if (!range) return null;
28589
- 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`;
28590
- 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`;
28591
- return null;
28592
- }
28593
- function refuseSchedule(options, windows) {
28594
- const schedule = options.schedule;
28595
- if (!schedule.support.writable) return unwritable("the recording schedule", schedule.support.reason);
28596
- const allowed = new Set(schedule.triggers);
28597
- for (const window of windows) {
28598
- if (!allowed.has(window.trigger)) {
28599
- const offer = schedule.triggers.length > 0 ? schedule.triggers.join(", ") : "none";
28600
- return `this camera cannot record on "${window.trigger}"; it records on: ${offer}`;
28601
- }
28602
- if (window.endMinute <= window.startMinute) return `a window on ${dayName(window.day)} ends at or before it starts (${String(window.startMinute)} → ${String(window.endMinute)})`;
28603
- const step = schedule.granularityMinutes;
28604
- 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`;
28605
- }
28606
- if (!schedule.supportsOverlappingTriggers) {
28607
- const clash = findOverlapWithDifferentTrigger(windows);
28608
- 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))}`;
28609
- }
28610
- return null;
28611
- }
28612
- function findOverlapWithDifferentTrigger(windows) {
28613
- for (let i = 0; i < windows.length; i += 1) for (let j = i + 1; j < windows.length; j += 1) {
28614
- const a = windows[i];
28615
- const b = windows[j];
28616
- if (!a || !b) continue;
28617
- if (a.day !== b.day) continue;
28618
- if (a.trigger === b.trigger) continue;
28619
- if (a.startMinute < b.endMinute && b.startMinute < a.endMinute) return {
28620
- a,
28621
- b
28622
- };
28623
- }
28624
- return null;
28625
- }
28626
- function dayName(day) {
28627
- return DAY_NAMES[day] ?? `day ${String(day)}`;
28628
- }
28629
- /** `510` → `08:30`. For messages, not for the wire. */
28630
- function formatMinutes(minute) {
28631
- const hour = Math.floor(minute / 60);
28632
- const rest = minute % 60;
28633
- return `${String(hour).padStart(2, "0")}:${String(rest).padStart(2, "0")}`;
28634
- }
28635
- /**
28636
- * Parse a Hikvision `<TimeOfDay>` into minutes since midnight.
28637
- *
28638
- * The firmware is not self-consistent and both spellings are real, on
28639
- * the same camera in the same block: a start time reads `00:00:00` and
28640
- * the matching end time reads `24:00`. Seconds are accepted and
28641
- * discarded — the cap's resolution is minutes — and `24:00` maps to
28642
- * {@link MINUTES_PER_DAY}, not to 0.
28643
- *
28644
- * Returns null for anything else, which a caller reports as a window it
28645
- * could not read rather than as midnight.
28646
- */
28647
- function timeOfDayToMinutes(value) {
28648
- const match = /^(\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(value.trim());
28649
- if (!match) return null;
28650
- const hour = Number(match[1]);
28651
- const minute = Number(match[2]);
28652
- if (!Number.isInteger(hour) || !Number.isInteger(minute)) return null;
28653
- if (minute > 59) return null;
28654
- const total = hour * 60 + minute;
28655
- if (total > 1440) return null;
28656
- return total;
28657
- }
28658
- /**
28659
- * Render minutes back as a Hikvision `TimeOfDay`.
28660
- *
28661
- * Emits the camera's own two spellings: `24:00` for end-of-day, because
28662
- * that is what the firmware writes and `24:00:00` is not observed, and
28663
- * `HH:MM:SS` otherwise.
28664
- */
28665
- function minutesToTimeOfDay(minute) {
28666
- if (minute >= 1440) return "24:00";
28667
- const hour = Math.floor(minute / 60);
28668
- const rest = minute % 60;
28669
- return `${String(hour).padStart(2, "0")}:${String(rest).padStart(2, "0")}:00`;
28670
- }
28671
- /** `'Monday'` → 0. Case-insensitive. Null for anything unrecognised. */
28672
- function dayOfWeekToIndex(value) {
28673
- const needle = value.trim().toLowerCase();
28674
- const index = DAY_NAMES.findIndex((name) => name.toLowerCase() === needle);
28675
- return index >= 0 ? index : null;
28676
- }
28677
- /**
28678
- * Which fields of a patch the camera did NOT take verbatim.
28679
- *
28680
- * Measured on a Hikvision I91DN (1436, 2026-09-22): a `PUT` of
28681
- * `PreRecordTimeSeconds: 8` answered `200`, `statusCode 1`, `OK` — and stored
28682
- * **5**. Neither the asked value nor the previous one. The camera declares no
28683
- * allowed set for that field, so there is nothing to refuse against before the
28684
- * wire: `/capabilities` returns a plain value where a constrained field would
28685
- * carry an `opt=` list.
28686
- *
28687
- * So the only honest moment is after the read-back, and re-reading alone is
28688
- * not enough — it makes the difference VISIBLE while leaving it unexplained.
28689
- * A write that reports success for a value the camera never took is the same
28690
- * silent substitution D599 removed from the clip path, wearing a different hat.
28691
- *
28692
- * Compares only the fields the patch actually named: a field nobody asked
28693
- * about cannot have been clamped, and a read-back that could not answer it is
28694
- * `stored: null` rather than a claim.
28695
- */
28696
- function describeOnboardClamp(patch, landed) {
28697
- const out = [];
28698
- for (const [field, asked] of Object.entries(patch)) {
28699
- if (asked === void 0) continue;
28700
- if (typeof asked !== "number" && typeof asked !== "boolean" && typeof asked !== "string") continue;
28701
- const raw = landed === null ? void 0 : landed[field];
28702
- const stored = typeof raw === "number" || typeof raw === "boolean" || typeof raw === "string" ? raw : null;
28703
- if (stored !== asked) out.push({
28704
- field,
28705
- asked,
28706
- stored
28707
- });
28708
- }
28709
- return out;
28710
- }
28711
- /**
28712
- * Generic device-level status snapshot. Auto-registered by `BaseDevice`
28713
- * for every device, regardless of provider — the kernel needs a uniform
28714
- * cap-keyed slice for the basic device flags every consumer expects to
28715
- * read across processes (the `online` flag in particular). Driver-specific
28716
- * caps (`battery`, `doorbell`, …) carry their domain-specific state on
28717
- * their own slices.
28718
- *
28719
- * Pattern is identical to `battery`: schema-bearing `runtimeState`,
28720
- * empty `methods`, single change event. Reads land at
28721
- * `runtimeState.getCapState('device-status')`; writes at
28722
- * `runtimeState.setCapState('device-status', …)`. Cross-process
28723
- * consumers reach the same data via the `device-state` cap router
28724
- * (`getCapSlice({deviceId, capName: 'device-status'})`).
28725
- */
28726
- var DeviceStatusSchema = object({
28727
- /**
28728
- * Device-level liveness. Drivers flip via `markOnline(boolean)` on
28729
- * `BaseDevice`. Provider semantics vary — RTSP aggregates broker
28730
- * stream-health, Reolink reads firmware push events, ONVIF tracks
28731
- * ping responses. This cap intentionally does NOT prescribe which
28732
- * signal drives the flag.
28733
- */
28734
- online: boolean(),
28735
- /** Ms epoch of the last `online` transition. Lets consumers tell
28736
- * apart "just came online" from "still online". */
28737
- lastChangedAt: number()
28738
- });
28739
- var deviceStatusCapability = {
28740
- name: "device-status",
28741
- scope: "device",
28742
- deviceNative: true,
28743
- mode: "singleton",
28744
- methods: {},
28745
- events: {
28746
- /** Emitted when `online` transitions. Mirrors the semantics of
28747
- * `battery.onStatusChanged`. */
28748
- onStatusChanged: { data: object({
28749
- deviceId: number(),
28750
- status: DeviceStatusSchema
28751
- }) } },
28752
- status: {
28753
- schema: DeviceStatusSchema,
28754
- kind: "push"
28755
- },
28756
- runtimeState: DeviceStatusSchema,
28757
- /**
28758
- * Runtime-state durability: **restored** — the previous observation is what makes the first reading after a restart a COMPARISON instead of a phantom transition (D130). 32 real flips across 16 devices in 25 min — the busiest slice in the cold half.
28759
- *
28760
- * See `RuntimeStateDurability`. Enforced by
28761
- * `scripts/check-runtime-state-durability.ts`.
28762
- */
28763
- durability: "restored",
28764
- /** Clock fields: written, but excluded from the compare that decides
28765
- * whether persisting is worth a SQLite commit. */
28766
- volatileStateFields: ["lastChangedAt"]
28767
- };
28768
- /**
28769
- * Doorbell button cap. Two kinds of providers coexist behind this cap
28770
- * name (same pattern as `snapshot`):
28771
- *
28772
- * - **Native** providers: registered per-device by device-driver
28773
- * addons via `ctx.registerNativeCap` — either on a
28774
- * `DeviceType.Button` accessory with `role: DeviceRole.Doorbell`,
28775
- * or directly on the camera (Reolink registers at camera level).
28776
- * Emits an `onPressed` event every time the firmware pushes a
28777
- * ring; status tracks the last press and a pressCount since start
28778
- * (diagnostic).
28779
- *
28780
- * - **Wrapper** provider: the `virtual-doorbell` system builtin
28781
- * (`@camstack/system/builtins/doorbell`). Turns ANY binary-ish
28782
- * device (contact / switch / event-emitter …) into a doorbell for
28783
- * a camera. `defaultActive: false` — the operator explicitly binds
28784
- * it per camera in the device-bindings UI, then picks the source
28785
- * device + trigger in the per-device settings.
28786
- *
28787
- * The DeviceEventPropagator re-emits `onPressed` on the camera parent
28788
- * — subscribers listening at the camera level receive ring events
28789
- * with `via[]` populated. No code on the parent needed.
28790
- */
28791
- var DoorbellStatusSchema = object({
28792
- /** Ms epoch of the last press. null = never observed since this provider started. */
28793
- lastPressedAt: number().nullable(),
28794
- /** Counter since provider start. Resets on reboot. Useful for metrics/debug. */
28795
- pressCountSinceStart: number()
28796
- });
28797
- var DoorbellPressEventSchema = object({
28798
- deviceId: number(),
28799
- timestamp: number()
28800
- });
28801
- var doorbellCapability = {
28802
- name: "doorbell",
28803
- scope: "device",
28804
- deviceNative: true,
28805
- mode: "singleton",
28806
- kind: "wrapper",
28807
- defaultActive: false,
28808
- deviceTypes: [DeviceType.Button, DeviceType.Camera],
28809
- exposesDeviceSettings: true,
28810
- methods: {},
28811
- events: {
28812
- /**
28813
- * Fires once per physical press. Reolink delivers via Baichuan
28814
- * push (`ReolinkSimpleEvent.type === 'doorbell'`). There is no
28815
- * release/duration — it's a pulse.
28816
- */
28817
- onPressed: { data: DoorbellPressEventSchema } },
28818
- status: {
28819
- schema: DoorbellStatusSchema,
28820
- kind: "push"
28821
- },
28822
- /**
28823
- * Runtime-state slice — last press timestamp + lifetime press count.
28824
- * Mirrored by the kernel and readable via
28825
- * `device.state.doorbell.value`. UIs can show "last ring 5m ago"
28826
- * without subscribing.
28827
- */
28828
- runtimeState: DoorbellStatusSchema,
28829
- /**
28830
- * Runtime-state durability: **restored** — a monotonic accumulator: the slice IS the record. `lastPressedAt` is content here, not a clock, so it is deliberately NOT volatile.
28831
- *
28832
- * See `RuntimeStateDurability`. Enforced by
28833
- * `scripts/check-runtime-state-durability.ts`.
28834
- */
28835
- durability: "restored"
28836
- };
28837
- /**
28838
- * Enum-state sensor — a string value picked from a finite option set.
28839
- * Drives HA `sensor` entries with `state_class: enum` (HVAC action
28840
- * states, weather conditions, contact-source channels, mode strings).
28841
- * The option set is stable across observations; it is persisted in the
28842
- * device config blob (via the control slice at adoption) and is NOT
28843
- * stored in `sourceInfo`.
28844
- */
28845
- /** Locale-render shape for an ISO `value` carried by a `DateTimeSensor`-role
28846
- * enum sensor: `date` (date-only), `time` (time-only), `datetime` (both). */
28847
- var EnumSensorDateTimeFormatSchema = _enum([
28848
- "date",
28849
- "time",
28850
- "datetime"
28851
- ]);
28852
- var EnumSensorStatusSchema = object({
28853
- value: string(),
28854
- /**
28855
- * Set for `DateTimeSensor`-role sensors so the UI renders the ISO `value`
28856
- * as a locale date/time/datetime; absent for plain enum sensors. HA
28857
- * `device_class=timestamp` → `'datetime'`, `device_class=date` → `'date'`,
28858
- * a time-only sensor → `'time'`.
28859
- */
28860
- format: EnumSensorDateTimeFormatSchema.optional(),
28861
- /** Ms epoch when the slice was last updated. */
28862
- lastFetchedAt: number()
28863
- });
28864
- var enumSensorCapability = {
28865
- name: "enum-sensor",
28866
- scope: "device",
28867
- deviceNative: true,
28868
- mode: "singleton",
28869
- deviceTypes: [DeviceType.Sensor],
28870
- methods: {},
28871
- status: {
28872
- schema: EnumSensorStatusSchema,
28873
- kind: "push"
28874
- },
28875
- runtimeState: EnumSensorStatusSchema,
28876
- /**
28877
- * Runtime-state durability: **restored** — as `numeric-sensor`; 80 devices.
28878
- *
28879
- * See `RuntimeStateDurability`. Enforced by
28880
- * `scripts/check-runtime-state-durability.ts`.
28881
- */
28882
- durability: "restored",
28883
- /** Clock fields: written, but excluded from the compare that decides
28884
- * whether persisting is worth a SQLite commit. */
28885
- volatileStateFields: ["lastFetchedAt"]
28886
- };
28887
- /**
28888
- * Generic stateless event emitter. Installed on a `DeviceType.EventEmitter`
28889
- * device. Carries the device's EXACT declared event vocabulary verbatim
28890
- * (NO normalization). Two shapes:
28891
- * - structured source (HA `event.*` entity) → `eventTypes` is the fixed
28892
- * declared vocabulary (e.g. ['press_short','press_long',...]).
28893
- * - generic/legacy source (HA bus events, e.g. zha_event) → `eventTypes`
28894
- * is [] (open) and `lastEvent.data` carries the complex payload.
28895
- * `seq` is monotonic so two identical events still produce distinct slice writes.
28896
- */
28897
- var EventFireSchema = object({
28898
- deviceId: number(),
28899
- eventType: string(),
28900
- data: record(string(), unknown()).nullable(),
28901
- timestamp: number(),
28902
- seq: number()
28903
- });
28904
- var EventEmitterStatusSchema = object({
28905
- eventTypes: array(string()),
28906
- lastEvent: EventFireSchema.nullable(),
28907
- eventCountSinceStart: number()
28908
- });
28909
- var eventEmitterCapability = {
28910
- name: "event-emitter",
28911
- scope: "device",
28912
- deviceNative: true,
28913
- mode: "singleton",
28914
- deviceTypes: [DeviceType.EventEmitter],
28915
- methods: {},
28916
- events: { onEvent: { data: EventFireSchema } },
28917
- status: {
28918
- schema: EventEmitterStatusSchema,
28919
- kind: "push"
28920
- },
28921
- runtimeState: EventEmitterStatusSchema,
28922
- /**
28923
- * Runtime-state durability: **session** — `eventCountSinceStart` names its own scope.
28924
- *
28925
- * See `RuntimeStateDurability`. Enforced by
28926
- * `scripts/check-runtime-state-durability.ts`.
28593
+ * See `RuntimeStateDurability`. Enforced by
28594
+ * `scripts/check-runtime-state-durability.ts`.
28927
28595
  */
28928
28596
  durability: "session"
28929
28597
  };
28930
- var EventItemSchema = object({
28931
- id: string(),
28932
- type: string(),
28933
- timestamp: number(),
28934
- label: string().optional(),
28935
- thumbnailUrl: string().optional(),
28936
- clipUrl: string().optional(),
28937
- metadata: record(string(), unknown()).optional()
28938
- });
28939
- DeviceType.Camera, method(object({
28940
- deviceId: number(),
28941
- from: number().optional(),
28942
- to: number().optional(),
28943
- limit: number().optional()
28944
- }), array(EventItemSchema)), method(object({
28945
- deviceId: number(),
28946
- eventId: string()
28947
- }), object({
28948
- base64: string(),
28949
- contentType: string()
28950
- }).nullable()), method(object({
28951
- deviceId: number(),
28952
- eventId: string()
28953
- }), string().nullable());
28954
28598
  var IdentitySchema = object({
28955
28599
  id: string(),
28956
28600
  name: string(),
@@ -31228,143 +30872,6 @@ var motionTriggerCapability = {
31228
30872
  durability: "session"
31229
30873
  };
31230
30874
  /**
31231
- * camera-grid-layout — the geometry of a COMPOSITE camera, on the camera's own
31232
- * page.
31233
- *
31234
- * ## Why this is a capability and not an addon settings schema
31235
- *
31236
- * It was one, and it did not render. The addon declared the editor as a
31237
- * `type: 'widget'` field inside its own `deviceSettingsSchema()`; the hub
31238
- * returned that section correctly and `ConfigFormField` renders `type:'widget'`
31239
- * perfectly well — and nothing ever asked camera-grid for it. The Cluster →
31240
- * Pipeline → Device Overrides page interrogates a HAND-WRITTEN list of four
31241
- * addons (`PIPELINE_CLUSTER_DEVICE_ADDONS`), whose own comment says an addon
31242
- * not on it "falls off silently".
31243
- *
31244
- * Adding a fifth name to that list would have been the wrong fix twice over:
31245
- * that page is per-camera DETECTION tuning, and a grid's geometry belongs
31246
- * beside PTZ and motion zones on the camera itself. The device page is
31247
- * BINDING-driven (D12), so the way in is a capability bound to the device —
31248
- * and this cap carries its section the way `recording` does, by RETURNING it
31249
- * from `getDeviceSettingsContribution`.
31250
- *
31251
- * Seven other widgets are still declared the other way, through a
31252
- * `deviceConfig.ui` block the framework derives a section from. That route
31253
- * gives the addon no say in where its own panel lands and no way to decline
31254
- * for a device the panel does not suit, which is why this one does not use it.
31255
- *
31256
- * ## Why one addon may implement it
31257
- *
31258
- * It is a device-scoped NATIVE cap, registered by the grid camera device
31259
- * itself. Nothing else declares a composite camera, so nothing else has a
31260
- * layout — and the device-scoped route means the widget asks THE camera, not
31261
- * "the camera-grid addon", which is what let the old custom-action pair be
31262
- * reached only by a caller that already knew the addon id.
31263
- *
31264
- * ## The tab
31265
- *
31266
- * `streaming`, not a top-tab of its own. A grid's geometry IS what its stream
31267
- * is, so the Streaming tab is where it belongs; a `grid` top-tab would need an
31268
- * entry in `WELL_KNOWN_TAB_MAP` or the device page renders the raw id as the
31269
- * label (measured on the robot camera, 2026-09-06 — a tab called "navigation"
31270
- * next to "PTZ").
31271
- */
31272
- /** A rectangle in normalized [0,1] coordinates of whatever contains it. */
31273
- var GridNormalizedRectSchema = object({
31274
- x: number().min(0).max(1),
31275
- y: number().min(0).max(1),
31276
- width: number().gt(0).max(1),
31277
- height: number().gt(0).max(1)
31278
- });
31279
- /**
31280
- * One source camera, the part of its picture taken, and where that part lands.
31281
- *
31282
- * Both rectangles are NORMALIZED (D519): a source camera can change resolution
31283
- * — a profile switch, a firmware update, a substream that comes back different
31284
- * — and a stored PIXEL rectangle would quietly start cutting the wrong region,
31285
- * which is the class of bug nobody files.
31286
- */
31287
- var GridLayoutCellSchema = object({
31288
- deviceId: number().int().positive(),
31289
- /** The part of the SOURCE taken, normalized against the source. */
31290
- source: GridNormalizedRectSchema,
31291
- /** Where it lands, normalized against the CANVAS. */
31292
- cell: GridNormalizedRectSchema
31293
- });
31294
- /**
31295
- * Which profiles this grid can actually compose, and why not.
31296
- *
31297
- * A grid's `high` composes its sources' `high` and its `low` their `low`, so a
31298
- * profile is on offer only when EVERY source can serve it. The refusal NAMES
31299
- * the sources, because "this grid has no low" is not a finding — "615 has no
31300
- * low" is, and it is the one an operator can act on.
31301
- */
31302
- var GridProfileOfferSchema = object({
31303
- profile: _enum([
31304
- "high",
31305
- "mid",
31306
- "low"
31307
- ]),
31308
- offered: boolean(),
31309
- /** Sources that cannot serve it. Empty when it is offered, or when there are no cells. */
31310
- missingSources: array(number().int().positive()),
31311
- /**
31312
- * The canvas this profile composes onto, `WxH`, or empty when it is not
31313
- * offered. DERIVED from the cells and the sources' own size at this profile —
31314
- * it is reported because nothing else in the system would ever say what the
31315
- * grid came out as, and because it is the number an operator would otherwise
31316
- * expect to type.
31317
- */
31318
- canvas: string(),
31319
- /**
31320
- * Whether this profile is PUBLISHED, of the ones the grid could serve.
31321
- *
31322
- * A grid's `high` is composed of its sources' `high`, so on a 4K fleet it is
31323
- * a 4K canvas built from 4K decodes — something to opt into, not something a
31324
- * viewer's adaptive should be handed by climbing to the top rung it can see.
31325
- * Default is `mid` + `low`.
31326
- */
31327
- published: boolean()
31328
- });
31329
- var GridLayoutViewSchema = object({
31330
- /** The persisted grid row this camera was declared from. */
31331
- instanceId: string(),
31332
- deviceId: number().int().nonnegative(),
31333
- name: string(),
31334
- /**
31335
- * NO canvas size. A grid's resolution is not authored: each profile derives
31336
- * its own from the cells and its sources' dimensions. The two numbers that
31337
- * used to be here were a text field that silently decided both how much the
31338
- * composite cost and how sharp it was — see `profiles[].canvas` for what it
31339
- * came out as.
31340
- */
31341
- fps: number().int(),
31342
- cells: array(GridLayoutCellSchema),
31343
- /** What the catalog will publish, and what it refuses to. Read-only. */
31344
- profiles: array(GridProfileOfferSchema)
31345
- });
31346
- var GridLayoutPatchSchema = object({
31347
- deviceId: number().int().nonnegative(),
31348
- name: string().min(1).max(160).optional(),
31349
- fps: number().int().min(1).max(60).optional(),
31350
- /** Which profiles to publish. See `GridProfileOffer.published`. */
31351
- publishedProfiles: array(_enum([
31352
- "high",
31353
- "mid",
31354
- "low"
31355
- ])).max(3).optional(),
31356
- /**
31357
- * The whole cell list at once. A per-cell patch would need an ordering the
31358
- * editor does not have, and a half-applied layout is a picture nobody asked
31359
- * for.
31360
- */
31361
- cells: array(GridLayoutCellSchema).max(16)
31362
- });
31363
- DeviceType.Camera, method(object({ deviceId: number().int().nonnegative() }), GridLayoutViewSchema.nullable(), { auth: "admin" }), method(GridLayoutPatchSchema, GridLayoutViewSchema, {
31364
- kind: "mutation",
31365
- auth: "admin"
31366
- });
31367
- /**
31368
30875
  * Motion-zones share the same MaskShape vocabulary as privacy-mask — the
31369
30876
  * on-camera motion-detection mask is a single `grid` region (a row-major
31370
30877
  * boolean cell lattice the camera's onboard VMD evaluates). Composing it as
@@ -33910,37 +33417,37 @@ var rebootCapability = {
33910
33417
  auth: "admin"
33911
33418
  }) }
33912
33419
  };
33913
- /**
33914
- * `recording` cap — footage availability + HLS playback manifests + per-device
33915
- * recording config. NOTE on events (source of truth, R5/C3): this cap carries
33916
- * NO event surface — `getPlaybackManifest` returns playlist URLs only. Timeline
33917
- * events (motion/object/audio) come from `pipelineAnalytics` (durable SQLite
33918
- * rows) and are the ONLY event surface — the recorder has none. The in-RAM
33919
- * playback markers it used to build were deleted on 2026-08-29 because nothing
33920
- * ever read them. Event<->footage joins are by time, padded with the shared
33921
- * `EVENT_PAD_MS` (`interfaces/recording-config.ts`).
33922
- */
33923
- var RecordingStatusSchema = object({
33924
- deviceId: number(),
33925
- enabled: boolean(),
33926
- /** THE derived storage mode, from the one definition
33927
- * (`deriveRecordingMode`) — never a second enum. A duplicated list is how
33928
- * `on-device-decision` could have reached the recorder and not the status. */
33929
- activeMode: RecordingStorageModeSchema,
33930
- nodeId: string(),
33931
- storageBytes: number()
33932
- });
33933
33420
  var RecordingRangeSchema = object({
33934
33421
  profile: string(),
33935
33422
  startMs: number(),
33936
33423
  endMs: number()
33937
33424
  });
33425
+ /**
33426
+ * How a source ANSWERED, on every singular read of this cap.
33427
+ *
33428
+ * `'read'` — it looked. `ranges: []` / `days: []` is then a real claim: this
33429
+ * source has no coverage in the window. `'unreadable'` — nobody could look
33430
+ * (the camera was unreachable, the calendar rung threw, the location is
33431
+ * unmounted, the node is still on the old build), and the emptiness beside it
33432
+ * means NOTHING.
33433
+ *
33434
+ * The batch rows have carried this since the grid existed; the SINGULAR
33435
+ * answers gained it with the collection (D625 §10.4), because they are the
33436
+ * ones the single-camera picker uses and because a half-converted fleet makes
33437
+ * "nobody looked" common for the length of a deploy. Without it the timeline
33438
+ * has no vocabulary for it, and `(data ?? [])` in a viewer turns a rollout into
33439
+ * a fleet of cameras that appear to have lost their recordings (D315, D393).
33440
+ */
33441
+ var RecordingReadSchema = _enum(["read", "unreadable"]);
33938
33442
  var RecordingAvailabilitySchema = object({
33939
33443
  deviceId: number(),
33444
+ /** See {@link RecordingReadSchema}. An `'unreadable'` answer carries an empty
33445
+ * `ranges` that means nothing — never draw it as "no footage". */
33446
+ read: RecordingReadSchema,
33940
33447
  ranges: array(RecordingRangeSchema),
33941
33448
  /**
33942
- * Every profile this camera has footage in — not only the one `ranges`
33943
- * describes (D433).
33449
+ * Every profile this camera has footage in AT THIS SOURCE — not only the one
33450
+ * `ranges` describes (D433).
33944
33451
  *
33945
33452
  * `ranges` answers for ONE profile by design: the timeline is a single bar,
33946
33453
  * and enumerating all of them triples the directory reads for a bar that
@@ -33955,17 +33462,287 @@ var RecordingAvailabilitySchema = object({
33955
33462
  */
33956
33463
  profilesWithFootage: array(string())
33957
33464
  });
33958
- var RecordingDaysSchema = object({
33465
+ var RecordingDaysSchema = object({
33466
+ deviceId: number(),
33467
+ /** See {@link RecordingReadSchema}. `days: []` on an `'unreadable'` answer is
33468
+ * "nobody could look", and the date-picker must not spell it the same as
33469
+ * "no footage this month". */
33470
+ read: RecordingReadSchema,
33471
+ /** Local-midnight epochs (UTC ms) of days that have ≥1 recorded segment. */
33472
+ days: array(number())
33473
+ });
33474
+ var RecordingManifestSchema = object({
33475
+ deviceId: number(),
33476
+ /** Local filesystem path to the master playlist; null when no recording exists for the requested range. */
33477
+ localMasterPath: string().nullable(),
33478
+ /** HTTP(S) URL to the master playlist on the recording node's playback server
33479
+ * (the PRIMARY candidate); null when no recording / server. Carries the
33480
+ * scoped playback token in its path. */
33481
+ playbackUrl: string().nullable(),
33482
+ /**
33483
+ * Candidate master-playlist URLs the client tries in order (LAN first, then
33484
+ * remote — Tailscale/Cloudflare if the operator configured extra hosts), each
33485
+ * carrying the same scoped token. `playbackUrl` is the first entry. Empty when
33486
+ * there is no recording / server.
33487
+ */
33488
+ playbackEndpoints: array(string())
33489
+ });
33490
+ var RecordingSourceAvailabilitySchema = object({
33491
+ state: _enum([
33492
+ "ok",
33493
+ "sleeping",
33494
+ "unreachable",
33495
+ "no-storage",
33496
+ "index-empty"
33497
+ ]),
33498
+ /** Free text, shown verbatim. Names the camera's own refusal when there is one. */
33499
+ reason: string().optional(),
33500
+ /** When this source's coverage was last CONFIRMED. A cached answer is never
33501
+ * drawn as current: the surface shows the age whenever it is older than the
33502
+ * refresh interval. The clip catalog's `catalogAsOf`, under the name the
33503
+ * timeline uses for it. */
33504
+ coverageAsOf: number().optional()
33505
+ });
33506
+ /**
33507
+ * One SOURCE of recorded coverage for a camera — a row of the picker.
33508
+ *
33509
+ * A provider lists the sources IT serves for that device, and answers for each
33510
+ * of them whether it can answer at all. A provider with nothing to offer on a
33511
+ * camera returns `[]` — it is not that camera's business. The five availability
33512
+ * states are `ClipSourceAvailability`'s verbatim: they mean exactly the same
33513
+ * things about a coverage index as about a clip catalog, and `sleeping` in
33514
+ * particular is what stops a battery camera being woken to paint a bar.
33515
+ */
33516
+ var RecordingSourceSchema = object({
33517
+ /** The source id. {@link RECORDING_SOURCE_CAMSTACK} for ours (RESERVED), a
33518
+ * vendor namespace (`native:reolink:onboard`, …) for a camera's own store. */
33519
+ source: string(),
33520
+ /** Operator-facing name of the source ("CamStack recordings", "SD card"). */
33521
+ label: string(),
33522
+ /**
33523
+ * The addon that SERVES this row, and the value a later call passes as
33524
+ * `provider`.
33525
+ *
33526
+ * Optional for version skew only. The collection dispatcher stamps it from
33527
+ * the registry, so a row that travelled through the fan-out carries the
33528
+ * authoritative id whatever the provider filled in (D557 §4).
33529
+ */
33530
+ addonId: string().optional(),
33531
+ availability: RecordingSourceAvailabilitySchema
33532
+ });
33533
+ /**
33534
+ * What a surface may DRAW for this (camera, source) — D612's rule applied to a
33535
+ * timeline: **the source declares what it can do, and the surface draws what
33536
+ * was declared. It never assumes, and never offers a gesture it will then
33537
+ * refuse.** D612 exists because `8` and `16` were offered as clip rates, the
33538
+ * broker clamped them to `4`, and no line anywhere said so.
33539
+ *
33540
+ * Asked once per (camera, source) before anything is drawn — never replaced by
33541
+ * a constant the surface keeps, which is the second authority D612 ends.
33542
+ */
33543
+ var RecordingSourceOptionsSchema = object({
33544
+ /** How this source's media reaches the player.
33545
+ * `archive` = our own indexed segment tree; `stream` = the provider's
33546
+ * forward-only fMP4 (D597); `realtime` = a replay bound to wall clock. */
33547
+ transport: _enum([
33548
+ "archive",
33549
+ "stream",
33550
+ "realtime"
33551
+ ]),
33552
+ /** What the BAR means. `continuous` = gaps are holes in a recording;
33553
+ * `sparse` = gaps are the absence of one, and must be drawn as such.
33554
+ *
33555
+ * Not an onboard-only concession: measured 2026-09-24, OUR bar covers 98.8 %
33556
+ * of 592's day and 1.2 % of 1436's. It is a fact about a (source, camera)
33557
+ * pair, and ours answers it per camera from `deriveRecordingMode`. */
33558
+ coverage: _enum(["continuous", "sparse"]),
33559
+ /** Where the playhead may be put.
33560
+ * `free` — anywhere, to the frame.
33561
+ * `forward` — only ahead of the current position.
33562
+ * `segment` — a position SNAPS to the head of the covering segment; a finer
33563
+ * ask is accepted by the camera and SILENTLY IGNORED. Measured
33564
+ * on 1436 (Hikvision V5.7.1, 2026-09-23): a window-narrowed
33565
+ * `ContentMgmt/search` returns a row and a `playbackURI`, the
33566
+ * replay opens 200 and delivers media — and the burned-in OSD of
33567
+ * the first frame reads the SEGMENT HEAD every time. Calling
33568
+ * that `forward` would tell the surface it may move the playhead
33569
+ * ahead within a loaded segment, which it may not. */
33570
+ seek: _enum([
33571
+ "free",
33572
+ "forward",
33573
+ "segment"
33574
+ ]),
33575
+ /** Frame-step BACKWARD is meaningful. */
33576
+ stepBack: boolean(),
33577
+ /** Whether the drag-scrub gesture is served, as opposed to refused by name. */
33578
+ scrub: boolean(),
33579
+ /** Deliverable rates, ascending, always containing `1`. The surface draws its
33580
+ * picker from this and from NOTHING else (D612, D620, D621). `0` is not a
33581
+ * member: pause is the absence of a rate. */
33582
+ rates: array(number().positive()).min(1).readonly(),
33583
+ /** TRUE when a read of this source HOLDS the camera's only playback session.
33584
+ * A surface with this set makes at most ONE read at a time and draws no
33585
+ * scrub-thumbnail strip, no hover preview, no prefetch and no background
33586
+ * refresh. The precedent is exact and expensive: filling one screen of
33587
+ * Hikvision thumbnails at 1.01× realtime consumed fifteen minutes of that
33588
+ * camera's only playback session (1.2.126, reported within minutes), and a
33589
+ * timeline is a screenful of reads by construction. */
33590
+ exclusive: boolean()
33591
+ });
33592
+ /**
33593
+ * How to PLAY the instant that was asked for, from the chosen source.
33594
+ *
33595
+ * No new media transport is built for onboard sources: the `clip` arm is a
33596
+ * DELEGATION to the `videoclips` transport that vendor already has (D597 /
33597
+ * D616 / D617). The onboard half of this collection is a PROJECTION of
33598
+ * `videoclips` for coverage and a delegation to it for bytes.
33599
+ */
33600
+ var RecordingPlaybackSchema = discriminatedUnion("kind", [
33601
+ object({
33602
+ kind: literal("hls"),
33603
+ manifest: RecordingManifestSchema
33604
+ }),
33605
+ object({
33606
+ kind: literal("clip"),
33607
+ /** The `videoclips` source namespace this clip id belongs to. */
33608
+ source: string(),
33609
+ clipId: string(),
33610
+ /** Where this clip actually STARTS. On a `seek: 'segment'` source the
33611
+ * playhead lands here, not at the requested instant — the surface must be
33612
+ * TOLD, not left to discover it from a burned-in OSD. */
33613
+ startsAtMs: number()
33614
+ }),
33615
+ object({
33616
+ kind: literal("none"),
33617
+ reason: string()
33618
+ })
33619
+ ]);
33620
+ DeviceType.Camera, method(object({ deviceId: number() }), array(RecordingSourceSchema).readonly(), {
33621
+ kind: "query",
33622
+ auth: "protected"
33623
+ }), method(object({
33624
+ deviceId: number(),
33625
+ /**
33626
+ * WHICH provider to ask — the `addonId` a {@link RecordingSourceSchema}
33627
+ * row carries, never a source id and never a list. **REQUIRED**, in the
33628
+ * schema, where the generated types make it unomittable rather than
33629
+ * merely discouraged (D554 amended).
33630
+ *
33631
+ * It was learned the expensive way on `videoclips.listClips`: measured
33632
+ * on the live hub 2026-09-20, device 592 bound to `recorder` AND
33633
+ * `provider-reolink`, a bare call with `limit: 3` answered SIX rows,
33634
+ * three from each source, merged — `device-collection-dispatch.ts`
33635
+ * leaves an unpinned fan-out un-narrowed, so absence buys the union the
33636
+ * method exists not to be. An un-narrowed `getAvailability` would do
33637
+ * that to a TIMELINE: our ranges and the card's clips unioned into one
33638
+ * bar, which is "two sources are never drawn together" broken in the
33639
+ * one place it matters most.
33640
+ *
33641
+ * A provider the device is not bound to is refused BY NAME (D552's
33642
+ * `rejectUnresolvedAddonPin`), never answered by another one.
33643
+ */
33644
+ provider: string().min(1),
33645
+ fromMs: number(),
33646
+ toMs: number(),
33647
+ /**
33648
+ * Answer for THIS profile instead of the source's preferred one (D433).
33649
+ * Absent keeps the timeline's behaviour — one bar, one profile, one set
33650
+ * of reads. `profilesWithFootage` on the answer says what may be asked
33651
+ * for.
33652
+ */
33653
+ profile: string().optional()
33654
+ }), RecordingAvailabilitySchema, {
33655
+ kind: "query",
33656
+ auth: "protected"
33657
+ }), method(object({
33658
+ deviceId: number(),
33659
+ provider: string().min(1),
33660
+ fromMs: number(),
33661
+ toMs: number(),
33662
+ tzOffsetMinutes: number()
33663
+ }), RecordingDaysSchema, {
33664
+ kind: "query",
33665
+ auth: "protected"
33666
+ }), method(object({
33667
+ deviceId: number(),
33668
+ provider: string().min(1),
33669
+ fromMs: number(),
33670
+ toMs: number(),
33671
+ profile: CamProfileSchema.optional()
33672
+ }), RecordingPlaybackSchema, {
33673
+ kind: "query",
33674
+ auth: "protected"
33675
+ }), method(object({
33676
+ deviceId: number(),
33677
+ provider: string().min(1)
33678
+ }), RecordingSourceOptionsSchema, {
33679
+ kind: "query",
33680
+ auth: "protected"
33681
+ });
33682
+ /**
33683
+ * `recording-archive` — OUR archive, and the intent that fills it.
33684
+ *
33685
+ * The system-singleton half of the 2026-09-24 cut (D625). `recording` used to
33686
+ * be one 33-method system singleton holding two unrelated subjects: three
33687
+ * per-camera READS about coverage and playback, and everything else — storage
33688
+ * locations, retention, relocation, rebalance, the ops log, the placement
33689
+ * table and the byte-plane primitives our scrub and export are built on.
33690
+ *
33691
+ * The reads became a device-scoped COLLECTION, so a camera's own card can be a
33692
+ * source beside ours (`recording.cap.ts`). Everything that is about OUR store,
33693
+ * or unimplementable by a camera, stayed here.
33694
+ *
33695
+ * ## On the name
33696
+ *
33697
+ * `recording-storage` was the obvious choice and is wrong: this cap also holds
33698
+ * `getDeviceConfig`/`setDeviceConfig`, which are recording INTENT — bands,
33699
+ * retention, the D62 switch authority — and a name that says "storage" invites
33700
+ * the next reader to move them out again. An archive is a thing we keep, and
33701
+ * what we keep it under is a policy; the name covers both halves honestly and
33702
+ * sits in the existing family (`recording-onboard`, `recording-export`,
33703
+ * `recording-signal`).
33704
+ *
33705
+ * ## What must NOT happen to it
33706
+ *
33707
+ * It stays a SINGLETON. It is registered by `recorder`, which is
33708
+ * `placement: 'any-node'` and runs on every recording node; the hub dispatches
33709
+ * to one of them. Putting the ledger, the placement table or the relocation
33710
+ * jobs behind a fan-out is the one genuinely dangerous move in this cut.
33711
+ *
33712
+ * `getDeviceConfig` / `setDeviceConfig` in particular are the D62 recording
33713
+ * authority (`CameraSwitch.authority`). If a write reached a different provider
33714
+ * than the read — which a collection fan-out permits — two authorities would
33715
+ * decide when one camera records, and the symptom (recording silently off, or
33716
+ * a `bands` array clobbered by a partial write) is durable and silent. Keeping
33717
+ * them here means the worst case during a rollout is a 412: the switch refuses
33718
+ * to flip and SAYS so. **Do not move them into the collection, at any point,
33719
+ * for any reason.**
33720
+ *
33721
+ * ## The two batch reads
33722
+ *
33723
+ * `getAvailabilityBatch` / `getDaysWithRecordingsBatch` take `deviceIds:
33724
+ * number[]` with no single `deviceId`, and a device-scoped mount routes
33725
+ * through `getProviderForDevice(deviceId)` — there is nothing for it to route
33726
+ * on. They stay here, and on this cap the batch is explicitly OURS: a grid has
33727
+ * no per-camera picker, and a caller that wants another source's coverage asks
33728
+ * `recording.getAvailability` per device with that source's `provider`.
33729
+ */
33730
+ var RecordingStatusSchema = object({
33959
33731
  deviceId: number(),
33960
- /** Local-midnight epochs (UTC ms) of days that have ≥1 recorded segment. */
33961
- days: array(number())
33732
+ enabled: boolean(),
33733
+ /** THE derived storage mode, from the one definition
33734
+ * (`deriveRecordingMode`) — never a second enum. A duplicated list is how
33735
+ * `on-device-decision` could have reached the recorder and not the status. */
33736
+ activeMode: RecordingStorageModeSchema,
33737
+ nodeId: string(),
33738
+ storageBytes: number()
33962
33739
  });
33963
33740
  /**
33964
33741
  * One camera's row in a `getAvailabilityBatch` answer.
33965
33742
  *
33966
- * `ranges` is EXACTLY what `getAvailability` returns for that camera — the
33967
- * batch collapses the transport, not the work — plus the one thing the singular
33968
- * method never had to say:
33743
+ * `ranges` is EXACTLY what `recording.getAvailability` returns for that camera
33744
+ * at OUR source — the batch collapses the transport, not the work — plus the
33745
+ * `read` mark the singular answer now carries too (D625):
33969
33746
  *
33970
33747
  * - `read: 'read'` — answered. `ranges: []` means "read, and this camera has
33971
33748
  * no footage in the window", which is a real claim.
@@ -33997,22 +33774,6 @@ var RecordingDaysForDeviceSchema = object({
33997
33774
  /** Local-midnight epochs (UTC ms) of days that have ≥1 recorded segment. */
33998
33775
  days: array(number()).readonly()
33999
33776
  });
34000
- var RecordingManifestSchema = object({
34001
- deviceId: number(),
34002
- /** Local filesystem path to the master playlist; null when no recording exists for the requested range. */
34003
- localMasterPath: string().nullable(),
34004
- /** HTTP(S) URL to the master playlist on the recording node's playback server
34005
- * (the PRIMARY candidate); null when no recording / server. Carries the
34006
- * scoped playback token in its path. */
34007
- playbackUrl: string().nullable(),
34008
- /**
34009
- * Candidate master-playlist URLs the client tries in order (LAN first, then
34010
- * remote — Tailscale/Cloudflare if the operator configured extra hosts), each
34011
- * carrying the same scoped token. `playbackUrl` is the first entry. Empty when
34012
- * there is no recording / server.
34013
- */
34014
- playbackEndpoints: array(string())
34015
- });
34016
33777
  /**
34017
33778
  * Recording storage usage for one camera — what the ARCHIVE holds for it,
34018
33779
  * across every profile and every resolvable location on this node.
@@ -34271,34 +34032,12 @@ var ReadWindowBytesResultSchema = discriminatedUnion("kind", [object({
34271
34032
  segmentEndMs: number()
34272
34033
  })]);
34273
34034
  method(object({
34274
- deviceId: number(),
34275
- fromMs: number(),
34276
- toMs: number(),
34277
- /**
34278
- * Answer for THIS profile instead of the preferred one (D433). Absent
34279
- * keeps the timeline's behaviour — one bar, one profile, one set of
34280
- * reads. `profilesWithFootage` on the answer says what may be asked
34281
- * for.
34282
- */
34283
- profile: string().optional()
34284
- }), RecordingAvailabilitySchema, {
34285
- kind: "query",
34286
- auth: "protected"
34287
- }), method(object({
34288
34035
  deviceIds: array(number()).min(1).max(200),
34289
34036
  fromMs: number(),
34290
34037
  toMs: number()
34291
34038
  }), array(RecordingAvailabilityForDeviceSchema).readonly(), {
34292
34039
  kind: "query",
34293
34040
  auth: "protected"
34294
- }), method(object({
34295
- deviceId: number(),
34296
- fromMs: number(),
34297
- toMs: number(),
34298
- tzOffsetMinutes: number()
34299
- }), RecordingDaysSchema, {
34300
- kind: "query",
34301
- auth: "protected"
34302
34041
  }), method(object({
34303
34042
  deviceIds: array(number()).min(1).max(200),
34304
34043
  fromMs: number(),
@@ -34307,13 +34046,6 @@ method(object({
34307
34046
  }), array(RecordingDaysForDeviceSchema).readonly(), {
34308
34047
  kind: "query",
34309
34048
  auth: "protected"
34310
- }), method(object({
34311
- deviceId: number(),
34312
- fromMs: number(),
34313
- toMs: number()
34314
- }), RecordingManifestSchema, {
34315
- kind: "query",
34316
- auth: "protected"
34317
34049
  }), method(object({}), RecordingStorageUsageSchema, {
34318
34050
  kind: "query",
34319
34051
  auth: "admin"
@@ -34525,245 +34257,761 @@ var ExportTimelapseSchema = object({
34525
34257
  * silent. `maxLifeMs` bounds how long the finished file is kept;
34526
34258
  * `deleteAfterDownload` removes it shortly after the first complete download.
34527
34259
  */
34528
- var ExportOptionsSchema = object({
34529
- speed: ExportSpeedSchema.optional(),
34530
- timelapse: ExportTimelapseSchema.optional(),
34531
- includeAudio: boolean(),
34532
- maxLifeMs: number().int().positive(),
34533
- deleteAfterDownload: boolean(),
34534
- title: string().max(200).optional(),
34535
- /** Notification-output target ids to ping when this export becomes ready. */
34536
- notifyTargetIds: array(string().min(1)).max(20).optional()
34537
- }).superRefine((v, ctx) => {
34538
- if (v.speed !== void 0 && v.timelapse !== void 0) ctx.addIssue({
34539
- code: ZodIssueCode.custom,
34540
- message: "speed and timelapse are mutually exclusive",
34541
- path: ["timelapse"]
34542
- });
34260
+ var ExportOptionsSchema = object({
34261
+ speed: ExportSpeedSchema.optional(),
34262
+ timelapse: ExportTimelapseSchema.optional(),
34263
+ includeAudio: boolean(),
34264
+ maxLifeMs: number().int().positive(),
34265
+ deleteAfterDownload: boolean(),
34266
+ title: string().max(200).optional(),
34267
+ /** Notification-output target ids to ping when this export becomes ready. */
34268
+ notifyTargetIds: array(string().min(1)).max(20).optional()
34269
+ }).superRefine((v, ctx) => {
34270
+ if (v.speed !== void 0 && v.timelapse !== void 0) ctx.addIssue({
34271
+ code: ZodIssueCode.custom,
34272
+ message: "speed and timelapse are mutually exclusive",
34273
+ path: ["timelapse"]
34274
+ });
34275
+ });
34276
+ var ExportStateSchema = _enum([
34277
+ "queued",
34278
+ "rendering",
34279
+ "ready",
34280
+ "failed",
34281
+ "expired",
34282
+ "deleted"
34283
+ ]);
34284
+ /**
34285
+ * WHAT an export is — the authority, as opposed to the four top-level fields
34286
+ * the Library sorts and labels on (D558 § 2.2).
34287
+ *
34288
+ * Read it through {@link exportSubjectOf}, never off the record directly: the
34289
+ * field is optional for the history rows written before it existed, and that
34290
+ * absence has exactly one interpreter.
34291
+ */
34292
+ var ExportSubjectSchema = discriminatedUnion("kind", [object({
34293
+ kind: literal("footage"),
34294
+ deviceId: number(),
34295
+ profiles: array(string()).min(1),
34296
+ fromMs: number(),
34297
+ toMs: number()
34298
+ }), object({
34299
+ kind: literal("clip"),
34300
+ deviceId: number(),
34301
+ provider: string().min(1),
34302
+ source: string().min(1),
34303
+ sourceLabel: string().min(1),
34304
+ clipId: string().min(1),
34305
+ /**
34306
+ * WHERE IN THE CATALOG to confirm this clip — the day window the surface was
34307
+ * already listing when the operator picked the segment.
34308
+ *
34309
+ * It is **not** a time range control and it never becomes one: the record's
34310
+ * `fromMs`/`toMs` come from the catalog ROW and from nothing a caller
34311
+ * supplied (D558 § 5.4.3), and a window that does not contain the clip is a
34312
+ * `catalog-miss`, not a silently wider search. It exists because
34313
+ * `videoclips.listClips` takes `since`/`until` and has no by-handle twin:
34314
+ * the catalog check D558 asks for is literally that call, and a call needs a
34315
+ * window. The surface has one — `ClipsBrowser`'s `dayWindow`, one local
34316
+ * wall-clock day, which is also the only width measured to be cheap (one
34317
+ * day on 592 lists 171 clips in 712 ms, a busy day 546 in 2.0 s; twenty days
34318
+ * of one child's events took 3.6–5.4 s).
34319
+ */
34320
+ catalogWindow: object({
34321
+ sinceMs: number(),
34322
+ untilMs: number()
34323
+ }),
34324
+ profile: _enum([
34325
+ "high",
34326
+ "mid",
34327
+ "low"
34328
+ ]),
34329
+ /**
34330
+ * The operator's authorisation to wake a sleeping camera for this export.
34331
+ * ONE definition, in the cap that owns the clip read ({@link ClipWakeSchema}),
34332
+ * because the gate that honours it is the clip provider's sleep gate — a
34333
+ * second enum here would be a second contract. Absent by default; never
34334
+ * settable by a scheduler or a retry.
34335
+ *
34336
+ * **One authorised yes is ONE wake.** A failed clip export is retried only by
34337
+ * an operator act that asks again; a queued job that outlived its wake fails
34338
+ * with a reason rather than waking on its turn; and this subject carries
34339
+ * exactly one profile precisely so one tap is never two fetches (D558 § 5.2).
34340
+ */
34341
+ wake: ClipWakeSchema.optional()
34342
+ })]);
34343
+ /**
34344
+ * One export job / history row.
34345
+ *
34346
+ * **`subject` is the AUTHORITY on what was exported. `deviceId`, `profile`,
34347
+ * `fromMs` and `toMs` are its PROJECTION** — kept top-level because the whole
34348
+ * Library sorts and labels on them (`library-items.ts` orders an export by
34349
+ * `fromMs`; `export-format.ts` draws `rangeLabel` from the pair), and a row
34350
+ * that did not fill them would sort under the epoch and render a blank range.
34351
+ * Write to the subject and read from the projection and the two will disagree;
34352
+ * the projection is derived at creation and never edited afterwards.
34353
+ *
34354
+ * And they mean DIFFERENT FACTS for the two kinds, which is the part a reader
34355
+ * who knows only the recording export will get wrong:
34356
+ *
34357
+ * | field | `kind:'footage'` | `kind:'clip'` |
34358
+ * | --- | --- | --- |
34359
+ * | `fromMs`/`toMs` | the stretch the operator ASKED for | the camera's own boundaries, always `clip.timeRange`, never anything a caller supplied |
34360
+ * | `profile` | the stream rendered | the twin actually SERVED (`subject.profile` is the one asked for) |
34361
+ *
34362
+ * Same type, different fact — the shape this repo keeps getting wrong (D385's
34363
+ * two authorities, D224's second copy).
34364
+ */
34365
+ var ExportRecordSchema = object({
34366
+ id: string(),
34367
+ deviceId: number(),
34368
+ profile: string(),
34369
+ fromMs: number(),
34370
+ toMs: number(),
34371
+ /**
34372
+ * What this export IS. Optional ONLY for the rows written before D558: the
34373
+ * store parses every row through this schema on every read, so a required
34374
+ * field would make the export AUDIT — which is the whole reason rows survive
34375
+ * file deletion — unreadable in one release. Absence means `footage`, and
34376
+ * {@link exportSubjectOf} is the one place that says so.
34377
+ */
34378
+ subject: ExportSubjectSchema.optional(),
34379
+ options: ExportOptionsSchema,
34380
+ state: ExportStateSchema,
34381
+ /** 0–100 while rendering; null otherwise. */
34382
+ progressPct: number().nullable(),
34383
+ /** File size once ready; null before. */
34384
+ fileBytes: number().nullable(),
34385
+ expiresAt: number(),
34386
+ deleteAfterDownload: boolean(),
34387
+ /** Epoch of the first complete download; null until then. */
34388
+ downloadedAt: number().nullable(),
34389
+ createdAt: number(),
34390
+ /** User id/name that requested the export. */
34391
+ createdBy: string(),
34392
+ /** Failure reason when state is 'failed'; null otherwise. */
34393
+ error: string().nullable()
34394
+ });
34395
+ _enum([
34396
+ "catalog-miss",
34397
+ "catalog-unreachable",
34398
+ "no-file-for-window",
34399
+ "clip-in-progress",
34400
+ "unsupported-option",
34401
+ "sleeping",
34402
+ "camera-refused",
34403
+ "fetch-failed",
34404
+ "too-large-to-transfer",
34405
+ "wake-expired"
34406
+ ]);
34407
+ /** `<token>: <prose>` — the ONE composition of a clip export's failure string. */
34408
+ function clipExportFailure(code, detail) {
34409
+ return detail.length > 0 ? `${code}: ${detail}` : code;
34410
+ }
34411
+ /** Candidate download URLs (LAN first, then operator extra hosts). */
34412
+ var ExportDownloadSchema = object({
34413
+ url: string(),
34414
+ endpoints: array(string())
34415
+ });
34416
+ /**
34417
+ * A finished export's bytes, inline.
34418
+ *
34419
+ * `bytes` is the DECODED length — the number the caller bounds and logs
34420
+ * against, so nobody has to infer it from the base64 length.
34421
+ */
34422
+ var ExportBytesSchema = object({
34423
+ base64: string(),
34424
+ contentType: string(),
34425
+ /** Suggested filename, extension included. */
34426
+ name: string(),
34427
+ bytes: number().int().nonnegative()
34428
+ });
34429
+ /** Canonical `profiles[]`, falling back to the legacy singular `profile`. */
34430
+ function resolveExportProfiles(input) {
34431
+ if (input.profiles !== void 0 && input.profiles.length > 0) return [...input.profiles];
34432
+ if (typeof input.profile === "string" && input.profile.length > 0) return [input.profile];
34433
+ return [];
34434
+ }
34435
+ method(object({
34436
+ deviceId: number(),
34437
+ /** @deprecated Prefer `profiles`. Kept so timelapse/notifiers keep working. */
34438
+ profile: string().optional(),
34439
+ profiles: array(string()).min(1).optional(),
34440
+ /** Footage only — a clip's boundaries are the camera's. */
34441
+ fromMs: number().optional(),
34442
+ toMs: number().optional(),
34443
+ /** What to export. Absent means the legacy flat footage request. */
34444
+ subject: ExportSubjectSchema.optional(),
34445
+ options: ExportOptionsSchema
34446
+ }).superRefine((v, ctx) => {
34447
+ if (v.subject?.kind === "clip") {
34448
+ if (v.subject.deviceId !== v.deviceId) ctx.addIssue({
34449
+ code: ZodIssueCode.custom,
34450
+ message: `subject.deviceId (${v.subject.deviceId}) must equal deviceId (${v.deviceId}) — the top-level field is what per-device scope enforcement reads`,
34451
+ path: ["subject", "deviceId"]
34452
+ });
34453
+ if (v.fromMs !== void 0 || v.toMs !== void 0) ctx.addIssue({
34454
+ code: ZodIssueCode.custom,
34455
+ message: "a clip export asks for no time range: the camera chose the boundaries and they are read from the catalog row",
34456
+ path: ["fromMs"]
34457
+ });
34458
+ return;
34459
+ }
34460
+ if (v.subject?.kind === "footage" && v.subject.deviceId !== v.deviceId) ctx.addIssue({
34461
+ code: ZodIssueCode.custom,
34462
+ message: `subject.deviceId (${v.subject.deviceId}) must equal deviceId (${v.deviceId})`,
34463
+ path: ["subject", "deviceId"]
34464
+ });
34465
+ const fromMs = v.subject?.kind === "footage" ? v.subject.fromMs : v.fromMs;
34466
+ const toMs = v.subject?.kind === "footage" ? v.subject.toMs : v.toMs;
34467
+ if (typeof fromMs !== "number" || typeof toMs !== "number") ctx.addIssue({
34468
+ code: ZodIssueCode.custom,
34469
+ message: "a footage export needs fromMs and toMs",
34470
+ path: ["fromMs"]
34471
+ });
34472
+ if ((v.subject?.kind === "footage" ? [...v.subject.profiles] : resolveExportProfiles(v)).length < 1) ctx.addIssue({
34473
+ code: ZodIssueCode.custom,
34474
+ message: "pass profiles[] (min 1) or legacy profile",
34475
+ path: ["profiles"]
34476
+ });
34477
+ }), ExportRecordSchema, {
34478
+ kind: "mutation",
34479
+ auth: "protected"
34480
+ }), method(object({ deviceId: number().optional() }), array(ExportRecordSchema), {
34481
+ kind: "query",
34482
+ auth: "protected"
34483
+ }), method(object({ exportId: string() }), ExportRecordSchema, {
34484
+ kind: "query",
34485
+ auth: "protected"
34486
+ }), method(object({ exportId: string() }), ExportRecordSchema, {
34487
+ kind: "mutation",
34488
+ auth: "protected"
34489
+ }), method(object({ exportId: string() }), ExportRecordSchema, {
34490
+ kind: "mutation",
34491
+ auth: "protected"
34492
+ }), method(object({ exportId: string() }), ExportDownloadSchema, {
34493
+ kind: "query",
34494
+ auth: "protected"
34495
+ }), method(object({ exportId: string() }), ExportBytesSchema, {
34496
+ kind: "query",
34497
+ auth: "protected"
34498
+ });
34499
+ /**
34500
+ * Vendor-neutral **onboard** recording + storage cap — what the CAMERA
34501
+ * writes to the CAMERA's own card, on the camera's own schedule.
34502
+ *
34503
+ * This is NOT `recording.cap.ts`. That one is CamStack's recorder: our
34504
+ * footage ledger, our storage locations, our retention. This one has a
34505
+ * different authority — the camera's firmware — and per D62 it stores
34506
+ * nothing of its own. Every value here is read from the camera and every
34507
+ * write goes back to the camera; there is no CamStack-side mirror that
34508
+ * could disagree with the device.
34509
+ *
34510
+ * ## One shape, two firmwares
34511
+ *
34512
+ * Measured 2026-09-22 against the live fleet:
34513
+ *
34514
+ * | fact | Hikvision (ISAPI) | Reolink (Baichuan) |
34515
+ * | --- | --- | --- |
34516
+ * | storage | `ContentMgmt/Storage` `<hdd>` rows: status, capacity, freeSpace (MB) | `getHddInfoList` (cmd 102): `mount`, `format`, `capacity` GB + `capacityM` MB remainder |
34517
+ * | tracks | several (101 **and** 103 on both 1436 and 3833), each with its own schedule | one per channel |
34518
+ * | schedule | per track, 7 `ScheduleAction` blocks: DayOfWeek + TimeOfDay range + ONE `ActionRecordingMode` | per trigger type, a 168-char weekly HOUR mask |
34519
+ * | triggers | `CMR`, `MOTION` | `Normal`, `MD`, `people`, `vehicle`, `dog_cat`, `crossline`, `intrude`, `loitering` |
34520
+ * | pre-record | `PreRecordTimeSeconds` | `preRecordTime` |
34521
+ * | post-record | `PostRecordTimeSeconds` | `recordDelayTime` |
34522
+ * | overwrite | per track `LoopEnable` | `cycle`, with `cycleList` enumerating the accepted values |
34523
+ * | segment length | not exposed on V5.7.1 | `packageTime` (minutes) |
34524
+ *
34525
+ * The two schedule models look different and are the same thing in
34526
+ * different coordinates: both answer "for this trigger, during which
34527
+ * weekly windows does the camera record". {@link RecordWindow} is that
34528
+ * question in one shape — Hikvision's ranges map straight onto it,
34529
+ * Reolink's mask expands into hour-aligned windows.
34530
+ *
34531
+ * ## Union, not intersection
34532
+ *
34533
+ * **The same fields exist on every camera.** What differs per device is
34534
+ * which VALUES that device accepts, and that is what {@link
34535
+ * RecordingOnboardOptions} reports — a `{ readable, writable, reason }`
34536
+ * per field plus the schedule's own limits. A control a camera cannot
34537
+ * honour is rendered DISABLED WITH ITS REASON, never missing and never
34538
+ * dead: disabled must not look like broken.
34539
+ *
34540
+ * ## Refusal by name
34541
+ *
34542
+ * A write a camera cannot honour is refused with a sentence the operator
34543
+ * can read — never accepted and dropped. Both providers refuse through
34544
+ * {@link describeOnboardRefusal}, so the vocabulary is one function and
34545
+ * one test, not two hand-written vendor opinions.
34546
+ *
34547
+ * Follows the D14 `deviceConfig` archetype (see `stream-params.cap.ts`):
34548
+ * `getOptions` advertises per-camera availability, `getStatus` (auto-
34549
+ * injected from `status`) reports the live values, and a single
34550
+ * `setSettings` mutation applies a partial change. No hand-written
34551
+ * settings-contribution methods.
34552
+ */
34553
+ /**
34554
+ * What makes the camera start recording during a window.
34555
+ *
34556
+ * The union of both vendors' vocabularies. `continuous` is Hikvision's
34557
+ * `CMR` and Reolink's `Normal`; `motion` is `MOTION` / `MD`. The
34558
+ * object-class triggers are Reolink-only today and the smart-event ones
34559
+ * (`lineCrossing`, `intrusion`, `loitering`) are Reolink-only on the
34560
+ * firmwares measured — a camera that cannot record on a trigger simply
34561
+ * does not list it in `options.schedule.triggers`, and a window naming
34562
+ * it is REFUSED, not dropped.
34563
+ */
34564
+ var RecordTriggerSchema = _enum([
34565
+ "continuous",
34566
+ "motion",
34567
+ "person",
34568
+ "vehicle",
34569
+ "animal",
34570
+ "lineCrossing",
34571
+ "intrusion",
34572
+ "loitering",
34573
+ "alarmInput"
34574
+ ]);
34575
+ /**
34576
+ * One weekly recording window: "on `day`, from `startMinute` to
34577
+ * `endMinute`, record on `trigger`".
34578
+ *
34579
+ * `day` is 0 = Monday … 6 = Sunday (ISO order, which is also the order
34580
+ * both firmwares enumerate). Minutes are local camera time since
34581
+ * midnight; `endMinute` may be 1440, meaning end of day — that is
34582
+ * Hikvision's literal `24:00` and Reolink's 24th mask slot, and
34583
+ * collapsing it to 0 would turn a whole-day window into an empty one.
34584
+ */
34585
+ var RecordWindowSchema = object({
34586
+ trigger: RecordTriggerSchema,
34587
+ day: number().int().min(0).max(6),
34588
+ startMinute: number().int().min(0).max(1439),
34589
+ endMinute: number().int().min(1).max(1440)
34590
+ });
34591
+ /** Status of one physical volume, as the camera itself describes it. */
34592
+ var OnboardStorageVolumeSchema = object({
34593
+ /** The camera's own id for the volume (`hdd/id`, Reolink `HddInfo/number`). */
34594
+ id: string(),
34595
+ /** The camera's own name for it, when it gives one (`hddName`). */
34596
+ label: string().optional(),
34597
+ status: _enum([
34598
+ "ok",
34599
+ "unformatted",
34600
+ "error",
34601
+ "offline",
34602
+ "unknown"
34603
+ ]),
34604
+ /**
34605
+ * Total size in MB, or **null when the camera did not say**.
34606
+ *
34607
+ * Never 0 for an unreadable value: a measurement that failed is not a
34608
+ * measurement (D393), and a card whose size is unknown must not be
34609
+ * rendered as a card of size zero.
34610
+ */
34611
+ capacityMb: number().nullable(),
34612
+ /**
34613
+ * Free space in MB, or null when unknown.
34614
+ *
34615
+ * **Not a proxy for "has footage".** Measured 2026-09-22: 1436 and
34616
+ * 1439 both report exactly 11776 MB free — the fixed reserve a looping
34617
+ * card converges on once it has wrapped. At loop steady state the
34618
+ * number is identical whether the camera recorded yesterday or stopped
34619
+ * a month ago.
34620
+ */
34621
+ freeMb: number().nullable(),
34622
+ /** True when the camera reports the volume writable (`property` RW). */
34623
+ writable: boolean().optional()
34624
+ });
34625
+ /**
34626
+ * What the camera is doing with its own storage, right now.
34627
+ *
34628
+ * Every scalar is nullable and **null means the camera did not answer**,
34629
+ * never a default. A form that seeds `0` from an unanswered read invites
34630
+ * the operator to save that 0 back onto the camera.
34631
+ */
34632
+ var RecordingOnboardStatusSchema = object({
34633
+ storage: discriminatedUnion("kind", [
34634
+ object({
34635
+ kind: literal("present"),
34636
+ volumes: array(OnboardStorageVolumeSchema)
34637
+ }),
34638
+ object({
34639
+ kind: literal("absent"),
34640
+ reason: string()
34641
+ }),
34642
+ object({
34643
+ kind: literal("unknown"),
34644
+ reason: string()
34645
+ })
34646
+ ]),
34647
+ tracks: array(object({
34648
+ id: string(),
34649
+ enabled: boolean(),
34650
+ isVideo: boolean(),
34651
+ /** From the camera's own track description. Null when it does not say. */
34652
+ codec: string().nullable(),
34653
+ resolution: string().nullable(),
34654
+ /** Per-track overwrite flag, where the firmware keeps it per track. */
34655
+ overwriteWhenFull: boolean().nullable()
34656
+ })),
34657
+ /**
34658
+ * The track the write path targets — the enabled VIDEO one. Null when
34659
+ * no track could be identified, which is itself a refusal reason.
34660
+ */
34661
+ primaryTrackId: string().nullable(),
34662
+ /** Master "record to the card at all" switch. */
34663
+ enabled: boolean().nullable(),
34664
+ overwriteWhenFull: boolean().nullable(),
34665
+ preRecordSec: number().nullable(),
34666
+ postRecordSec: number().nullable(),
34667
+ /** Length of one recorded file, in minutes. */
34668
+ segmentMinutes: number().nullable(),
34669
+ /** The primary track's weekly windows, flattened. */
34670
+ windows: array(RecordWindowSchema),
34671
+ /**
34672
+ * How many windows the camera described that CamStack could NOT read —
34673
+ * an unrecognised trigger, an unparseable clock, a weekday it does not
34674
+ * name.
34675
+ *
34676
+ * A dropped window is work the reader threw away, and a schedule that
34677
+ * silently shows fewer rows than the camera holds is how an operator
34678
+ * saves back a schedule shorter than the one they were looking at
34679
+ * (D391). Non-zero means the window list is INCOMPLETE and a write
34680
+ * that replaces it would delete what was not shown — which is why a
34681
+ * provider reporting a non-zero count also reports the schedule as not
34682
+ * writable.
34683
+ */
34684
+ unreadableWindows: number(),
34685
+ /**
34686
+ * The camera is scheduled to record and has NO usable storage.
34687
+ *
34688
+ * A first-class fact because it is the fleet's most common silent
34689
+ * defect: measured 2026-09-22, 1441 and 3831 are both motion-recording
34690
+ * to a card that is not there. Neither the schedule nor the storage
34691
+ * read says anything wrong on its own; only the pair does.
34692
+ */
34693
+ recordingToNowhere: boolean(),
34694
+ lastFetchedAt: number()
34695
+ });
34696
+ /** Numeric range descriptor — `{ min, max, step }` per the getOptions convention. */
34697
+ var RangeSchema = object({
34698
+ min: number(),
34699
+ max: number(),
34700
+ step: number()
34701
+ });
34702
+ /**
34703
+ * The values a camera actually takes for a numeric field, when they are a SET
34704
+ * rather than a range.
34705
+ *
34706
+ * `{min,max,step}` cannot say what these two firmwares do. Measured on 1436
34707
+ * (I91DN) on 2026-09-22 by writing each value and reading it back:
34708
+ *
34709
+ * - pre-record: `0, 5, 10, 15, 20, 25, 30` and `2147483647` (INT32_MAX, the
34710
+ * camera's "no limit" — `-1` and `4294967295` both land on it);
34711
+ * - post-record: `5, 10, 30, 60, 120, 300, 600`.
34712
+ *
34713
+ * Neither is expressible as a step: the first has a sentinel two billion away
34714
+ * from its neighbours, the second doubles and then jumps. A range that tried
34715
+ * would forbid values the camera takes AND permit values it silently replaces
34716
+ * with 5 — wrong in both directions at once.
34717
+ *
34718
+ * `sentinel` names the member that is not a duration, so a surface can render
34719
+ * "no limit" instead of `2147483647` seconds.
34720
+ */
34721
+ var AllowedValuesSchema = object({
34722
+ values: array(number()).min(1),
34723
+ sentinel: object({
34724
+ value: number(),
34725
+ meaning: _enum(["no-limit", "disabled"])
34726
+ }).optional()
34543
34727
  });
34544
- var ExportStateSchema = _enum([
34545
- "queued",
34546
- "rendering",
34547
- "ready",
34548
- "failed",
34549
- "expired",
34550
- "deleted"
34551
- ]);
34552
34728
  /**
34553
- * WHAT an export is — the authority, as opposed to the four top-level fields
34554
- * the Library sorts and labels on (D558 § 2.2).
34729
+ * Per-field availability on ONE camera.
34555
34730
  *
34556
- * Read it through {@link exportSubjectOf}, never off the record directly: the
34557
- * field is optional for the history rows written before it existed, and that
34558
- * absence has exactly one interpreter.
34731
+ * The field exists on every camera — this says whether this one can be
34732
+ * read and whether it can be written, and `reason` says why not when
34733
+ * either is false. The UI renders the control DISABLED with the reason
34734
+ * rather than hiding it, so a limitation is legible instead of looking
34735
+ * like a missing feature.
34559
34736
  */
34560
- var ExportSubjectSchema = discriminatedUnion("kind", [object({
34561
- kind: literal("footage"),
34562
- deviceId: number(),
34563
- profiles: array(string()).min(1),
34564
- fromMs: number(),
34565
- toMs: number()
34566
- }), object({
34567
- kind: literal("clip"),
34568
- deviceId: number(),
34569
- provider: string().min(1),
34570
- source: string().min(1),
34571
- sourceLabel: string().min(1),
34572
- clipId: string().min(1),
34737
+ var OnboardFieldSupportSchema = object({
34738
+ readable: boolean(),
34739
+ writable: boolean(),
34740
+ /** Required whenever `readable` or `writable` is false. */
34741
+ reason: string().optional()
34742
+ });
34743
+ /** What this camera's schedule model can express. */
34744
+ var OnboardScheduleSupportSchema = object({
34745
+ support: OnboardFieldSupportSchema,
34573
34746
  /**
34574
- * WHERE IN THE CATALOG to confirm this clip — the day window the surface was
34575
- * already listing when the operator picked the segment.
34747
+ * The smallest time step the camera can express, in minutes.
34576
34748
  *
34577
- * It is **not** a time range control and it never becomes one: the record's
34578
- * `fromMs`/`toMs` come from the catalog ROW and from nothing a caller
34579
- * supplied (D558 § 5.4.3), and a window that does not contain the clip is a
34580
- * `catalog-miss`, not a silently wider search. It exists because
34581
- * `videoclips.listClips` takes `since`/`until` and has no by-handle twin:
34582
- * the catalog check D558 asks for is literally that call, and a call needs a
34583
- * window. The surface has one — `ClipsBrowser`'s `dayWindow`, one local
34584
- * wall-clock day, which is also the only width measured to be cheap (one
34585
- * day on 592 lists 171 clips in 712 ms, a busy day 546 in 2.0 s; twenty days
34586
- * of one child's events took 3.6–5.4 s).
34749
+ * Hikvision takes arbitrary minutes (`00:05:00`–`23:57:00` observed on
34750
+ * 1436's track 103). Reolink's schedule is a 7×24 HOUR mask, so 60. A
34751
+ * window whose edges are not a multiple of this is REFUSED rather than
34752
+ * quietly rounded — rounding is how an operator's 06:30 becomes 06:00
34753
+ * and nothing says so.
34587
34754
  */
34588
- catalogWindow: object({
34589
- sinceMs: number(),
34590
- untilMs: number()
34591
- }),
34592
- profile: _enum([
34593
- "high",
34594
- "mid",
34595
- "low"
34596
- ]),
34755
+ granularityMinutes: number(),
34756
+ /** Triggers this camera can record on. A window naming another is refused. */
34757
+ triggers: array(RecordTriggerSchema),
34597
34758
  /**
34598
- * The operator's authorisation to wake a sleeping camera for this export.
34599
- * ONE definition, in the cap that owns the clip read ({@link ClipWakeSchema}),
34600
- * because the gate that honours it is the clip provider's sleep gate — a
34601
- * second enum here would be a second contract. Absent by default; never
34602
- * settable by a scheduler or a retry.
34759
+ * False when the camera stores ONE trigger per time range, so two
34760
+ * windows overlapping on the same day cannot carry different triggers.
34761
+ * True on Reolink, whose mask is per-trigger and independent.
34762
+ */
34763
+ supportsOverlappingTriggers: boolean()
34764
+ });
34765
+ var RecordingOnboardOptionsSchema = object({
34766
+ enabled: OnboardFieldSupportSchema,
34767
+ overwriteWhenFull: OnboardFieldSupportSchema,
34768
+ preRecordSec: OnboardFieldSupportSchema,
34769
+ preRecordSecRange: RangeSchema.optional(),
34770
+ /** Preferred over the range when the camera takes a SET, not a span. */
34771
+ preRecordSecAllowed: AllowedValuesSchema.optional(),
34772
+ postRecordSec: OnboardFieldSupportSchema,
34773
+ postRecordSecRange: RangeSchema.optional(),
34774
+ /** Preferred over the range when the camera takes a SET, not a span. */
34775
+ postRecordSecAllowed: AllowedValuesSchema.optional(),
34776
+ segmentMinutes: OnboardFieldSupportSchema,
34777
+ segmentMinutesRange: RangeSchema.optional(),
34778
+ /** Preferred over the range when the camera takes a SET, not a span. */
34779
+ segmentMinutesAllowed: AllowedValuesSchema.optional(),
34780
+ schedule: OnboardScheduleSupportSchema
34781
+ });
34782
+ /**
34783
+ * A partial change. Every field optional.
34784
+ *
34785
+ * Unlike the other `deviceConfig` caps, a provider here does **NOT**
34786
+ * silently ignore a field it cannot support — it refuses, by name,
34787
+ * through {@link describeOnboardRefusal}. Silence on a recording setting
34788
+ * is the failure D62 exists to prevent: the operator believes the camera
34789
+ * is recording the way the form says, and it is not.
34790
+ */
34791
+ var RecordingOnboardPatchSchema = object({
34792
+ enabled: boolean().optional(),
34793
+ overwriteWhenFull: boolean().optional(),
34794
+ preRecordSec: number().optional(),
34795
+ postRecordSec: number().optional(),
34796
+ segmentMinutes: number().optional(),
34797
+ /** The complete new window set for the primary track — not a delta. */
34798
+ windows: array(RecordWindowSchema).optional()
34799
+ });
34800
+ var recordingOnboardCapability = {
34801
+ name: "recording-onboard",
34802
+ scope: "device",
34803
+ deviceNative: true,
34804
+ mode: "singleton",
34805
+ deviceTypes: [DeviceType.Camera],
34806
+ deviceConfig: { ui: {
34807
+ kind: "derived-form",
34808
+ builderId: "recording-onboard",
34809
+ tab: "recording"
34810
+ } },
34811
+ methods: {
34812
+ getOptions: method(object({ deviceId: number() }), RecordingOnboardOptionsSchema),
34813
+ setSettings: method(object({
34814
+ deviceId: number(),
34815
+ settings: RecordingOnboardPatchSchema
34816
+ }), _void(), {
34817
+ kind: "mutation",
34818
+ auth: "admin"
34819
+ })
34820
+ },
34821
+ status: {
34822
+ schema: RecordingOnboardStatusSchema,
34823
+ kind: "poll"
34824
+ },
34825
+ runtimeState: RecordingOnboardStatusSchema,
34826
+ /**
34827
+ * Runtime-state durability: **restored** — operator-set camera-side
34828
+ * recording config; mutation-driven, and the storage half is the last
34829
+ * thing the camera said about its own card.
34603
34830
  *
34604
- * **One authorised yes is ONE wake.** A failed clip export is retried only by
34605
- * an operator act that asks again; a queued job that outlived its wake fails
34606
- * with a reason rather than waking on its turn; and this subject carries
34607
- * exactly one profile precisely so one tap is never two fetches (D558 § 5.2).
34831
+ * See `RuntimeStateDurability`. Enforced by
34832
+ * `scripts/check-runtime-state-durability.ts`.
34608
34833
  */
34609
- wake: ClipWakeSchema.optional()
34610
- })]);
34834
+ durability: "restored",
34835
+ /** Clock fields: written, but excluded from the compare that decides
34836
+ * whether persisting is worth a SQLite commit. */
34837
+ volatileStateFields: ["lastFetchedAt"]
34838
+ };
34611
34839
  /**
34612
- * One export job / history row.
34840
+ * Day-of-week names in the cap's index order (0 = Monday), for messages
34841
+ * an operator reads and for Hikvision's `<DayOfWeek>` element.
34842
+ */
34843
+ var DAY_NAMES = [
34844
+ "Monday",
34845
+ "Tuesday",
34846
+ "Wednesday",
34847
+ "Thursday",
34848
+ "Friday",
34849
+ "Saturday",
34850
+ "Sunday"
34851
+ ];
34852
+ /**
34853
+ * Does `patch` ask this camera for something it cannot do?
34613
34854
  *
34614
- * **`subject` is the AUTHORITY on what was exported. `deviceId`, `profile`,
34615
- * `fromMs` and `toMs` are its PROJECTION** — kept top-level because the whole
34616
- * Library sorts and labels on them (`library-items.ts` orders an export by
34617
- * `fromMs`; `export-format.ts` draws `rangeLabel` from the pair), and a row
34618
- * that did not fill them would sort under the epoch and render a blank range.
34619
- * Write to the subject and read from the projection and the two will disagree;
34620
- * the projection is derived at creation and never edited afterwards.
34855
+ * Returns the operator-readable reason, or `null` when every field in
34856
+ * the patch is within what `options` says this camera accepts. A
34857
+ * provider calls this BEFORE touching the camera and throws the string:
34858
+ * refusing is the point, and refusing identically on both vendors is why
34859
+ * this is one function.
34621
34860
  *
34622
- * And they mean DIFFERENT FACTS for the two kinds, which is the part a reader
34623
- * who knows only the recording export will get wrong:
34861
+ * The order of checks is the order an operator would read them: the
34862
+ * scalar knobs first, then the schedule, because a schedule complaint is
34863
+ * longer and a scalar one is usually the real problem.
34864
+ */
34865
+ function describeOnboardRefusal(options, patch) {
34866
+ if (patch.enabled !== void 0 && !options.enabled.writable) return unwritable("the master recording switch", options.enabled.reason);
34867
+ if (patch.overwriteWhenFull !== void 0 && !options.overwriteWhenFull.writable) return unwritable("overwrite-when-full", options.overwriteWhenFull.reason);
34868
+ const preRefusal = refuseNumeric("pre-record seconds", patch.preRecordSec, options.preRecordSec, options.preRecordSecRange, options.preRecordSecAllowed);
34869
+ if (preRefusal) return preRefusal;
34870
+ const postRefusal = refuseNumeric("post-record seconds", patch.postRecordSec, options.postRecordSec, options.postRecordSecRange, options.postRecordSecAllowed);
34871
+ if (postRefusal) return postRefusal;
34872
+ const segmentRefusal = refuseNumeric("segment length (minutes)", patch.segmentMinutes, options.segmentMinutes, options.segmentMinutesRange, options.segmentMinutesAllowed);
34873
+ if (segmentRefusal) return segmentRefusal;
34874
+ if (patch.windows !== void 0) {
34875
+ const scheduleRefusal = refuseSchedule(options, patch.windows);
34876
+ if (scheduleRefusal) return scheduleRefusal;
34877
+ }
34878
+ return null;
34879
+ }
34880
+ function unwritable(what, reason) {
34881
+ return reason ? `this camera cannot change ${what}: ${reason}` : `this camera cannot change ${what}`;
34882
+ }
34883
+ function refuseNumeric(what, value, support, range, allowed) {
34884
+ if (value === void 0) return null;
34885
+ if (!support.writable) return unwritable(what, support.reason);
34886
+ if (!Number.isFinite(value)) return `${what} must be a number, got ${String(value)}`;
34887
+ if (allowed) {
34888
+ if (allowed.values.includes(value)) return null;
34889
+ const say = (v) => allowed.sentinel !== void 0 && v === allowed.sentinel.value ? allowed.sentinel.meaning === "no-limit" ? "no limit" : "off" : String(v);
34890
+ return `this camera accepts ${what} only as ${allowed.values.map(say).join(", ")}; ${say(value)} is not one of them`;
34891
+ }
34892
+ if (!range) return null;
34893
+ 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`;
34894
+ 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`;
34895
+ return null;
34896
+ }
34897
+ function refuseSchedule(options, windows) {
34898
+ const schedule = options.schedule;
34899
+ if (!schedule.support.writable) return unwritable("the recording schedule", schedule.support.reason);
34900
+ const allowed = new Set(schedule.triggers);
34901
+ for (const window of windows) {
34902
+ if (!allowed.has(window.trigger)) {
34903
+ const offer = schedule.triggers.length > 0 ? schedule.triggers.join(", ") : "none";
34904
+ return `this camera cannot record on "${window.trigger}"; it records on: ${offer}`;
34905
+ }
34906
+ if (window.endMinute <= window.startMinute) return `a window on ${dayName(window.day)} ends at or before it starts (${String(window.startMinute)} → ${String(window.endMinute)})`;
34907
+ const step = schedule.granularityMinutes;
34908
+ 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`;
34909
+ }
34910
+ if (!schedule.supportsOverlappingTriggers) {
34911
+ const clash = findOverlapWithDifferentTrigger(windows);
34912
+ 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))}`;
34913
+ }
34914
+ return null;
34915
+ }
34916
+ function findOverlapWithDifferentTrigger(windows) {
34917
+ for (let i = 0; i < windows.length; i += 1) for (let j = i + 1; j < windows.length; j += 1) {
34918
+ const a = windows[i];
34919
+ const b = windows[j];
34920
+ if (!a || !b) continue;
34921
+ if (a.day !== b.day) continue;
34922
+ if (a.trigger === b.trigger) continue;
34923
+ if (a.startMinute < b.endMinute && b.startMinute < a.endMinute) return {
34924
+ a,
34925
+ b
34926
+ };
34927
+ }
34928
+ return null;
34929
+ }
34930
+ function dayName(day) {
34931
+ return DAY_NAMES[day] ?? `day ${String(day)}`;
34932
+ }
34933
+ /** `510` → `08:30`. For messages, not for the wire. */
34934
+ function formatMinutes(minute) {
34935
+ const hour = Math.floor(minute / 60);
34936
+ const rest = minute % 60;
34937
+ return `${String(hour).padStart(2, "0")}:${String(rest).padStart(2, "0")}`;
34938
+ }
34939
+ /**
34940
+ * Parse a Hikvision `<TimeOfDay>` into minutes since midnight.
34624
34941
  *
34625
- * | field | `kind:'footage'` | `kind:'clip'` |
34626
- * | --- | --- | --- |
34627
- * | `fromMs`/`toMs` | the stretch the operator ASKED for | the camera's own boundaries, always `clip.timeRange`, never anything a caller supplied |
34628
- * | `profile` | the stream rendered | the twin actually SERVED (`subject.profile` is the one asked for) |
34942
+ * The firmware is not self-consistent and both spellings are real, on
34943
+ * the same camera in the same block: a start time reads `00:00:00` and
34944
+ * the matching end time reads `24:00`. Seconds are accepted and
34945
+ * discarded — the cap's resolution is minutes — and `24:00` maps to
34946
+ * {@link MINUTES_PER_DAY}, not to 0.
34629
34947
  *
34630
- * Same type, different fact — the shape this repo keeps getting wrong (D385's
34631
- * two authorities, D224's second copy).
34948
+ * Returns null for anything else, which a caller reports as a window it
34949
+ * could not read rather than as midnight.
34632
34950
  */
34633
- var ExportRecordSchema = object({
34634
- id: string(),
34635
- deviceId: number(),
34636
- profile: string(),
34637
- fromMs: number(),
34638
- toMs: number(),
34639
- /**
34640
- * What this export IS. Optional ONLY for the rows written before D558: the
34641
- * store parses every row through this schema on every read, so a required
34642
- * field would make the export AUDIT — which is the whole reason rows survive
34643
- * file deletion — unreadable in one release. Absence means `footage`, and
34644
- * {@link exportSubjectOf} is the one place that says so.
34645
- */
34646
- subject: ExportSubjectSchema.optional(),
34647
- options: ExportOptionsSchema,
34648
- state: ExportStateSchema,
34649
- /** 0–100 while rendering; null otherwise. */
34650
- progressPct: number().nullable(),
34651
- /** File size once ready; null before. */
34652
- fileBytes: number().nullable(),
34653
- expiresAt: number(),
34654
- deleteAfterDownload: boolean(),
34655
- /** Epoch of the first complete download; null until then. */
34656
- downloadedAt: number().nullable(),
34657
- createdAt: number(),
34658
- /** User id/name that requested the export. */
34659
- createdBy: string(),
34660
- /** Failure reason when state is 'failed'; null otherwise. */
34661
- error: string().nullable()
34662
- });
34663
- _enum([
34664
- "catalog-miss",
34665
- "catalog-unreachable",
34666
- "no-file-for-window",
34667
- "clip-in-progress",
34668
- "unsupported-option",
34669
- "sleeping",
34670
- "camera-refused",
34671
- "fetch-failed",
34672
- "too-large-to-transfer",
34673
- "wake-expired"
34674
- ]);
34675
- /** `<token>: <prose>` — the ONE composition of a clip export's failure string. */
34676
- function clipExportFailure(code, detail) {
34677
- return detail.length > 0 ? `${code}: ${detail}` : code;
34951
+ function timeOfDayToMinutes(value) {
34952
+ const match = /^(\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(value.trim());
34953
+ if (!match) return null;
34954
+ const hour = Number(match[1]);
34955
+ const minute = Number(match[2]);
34956
+ if (!Number.isInteger(hour) || !Number.isInteger(minute)) return null;
34957
+ if (minute > 59) return null;
34958
+ const total = hour * 60 + minute;
34959
+ if (total > 1440) return null;
34960
+ return total;
34678
34961
  }
34679
- /** Candidate download URLs (LAN first, then operator extra hosts). */
34680
- var ExportDownloadSchema = object({
34681
- url: string(),
34682
- endpoints: array(string())
34683
- });
34684
34962
  /**
34685
- * A finished export's bytes, inline.
34963
+ * Render minutes back as a Hikvision `TimeOfDay`.
34686
34964
  *
34687
- * `bytes` is the DECODED length — the number the caller bounds and logs
34688
- * against, so nobody has to infer it from the base64 length.
34965
+ * Emits the camera's own two spellings: `24:00` for end-of-day, because
34966
+ * that is what the firmware writes and `24:00:00` is not observed, and
34967
+ * `HH:MM:SS` otherwise.
34689
34968
  */
34690
- var ExportBytesSchema = object({
34691
- base64: string(),
34692
- contentType: string(),
34693
- /** Suggested filename, extension included. */
34694
- name: string(),
34695
- bytes: number().int().nonnegative()
34696
- });
34697
- /** Canonical `profiles[]`, falling back to the legacy singular `profile`. */
34698
- function resolveExportProfiles(input) {
34699
- if (input.profiles !== void 0 && input.profiles.length > 0) return [...input.profiles];
34700
- if (typeof input.profile === "string" && input.profile.length > 0) return [input.profile];
34701
- return [];
34969
+ function minutesToTimeOfDay(minute) {
34970
+ if (minute >= 1440) return "24:00";
34971
+ const hour = Math.floor(minute / 60);
34972
+ const rest = minute % 60;
34973
+ return `${String(hour).padStart(2, "0")}:${String(rest).padStart(2, "0")}:00`;
34702
34974
  }
34703
- method(object({
34704
- deviceId: number(),
34705
- /** @deprecated Prefer `profiles`. Kept so timelapse/notifiers keep working. */
34706
- profile: string().optional(),
34707
- profiles: array(string()).min(1).optional(),
34708
- /** Footage only — a clip's boundaries are the camera's. */
34709
- fromMs: number().optional(),
34710
- toMs: number().optional(),
34711
- /** What to export. Absent means the legacy flat footage request. */
34712
- subject: ExportSubjectSchema.optional(),
34713
- options: ExportOptionsSchema
34714
- }).superRefine((v, ctx) => {
34715
- if (v.subject?.kind === "clip") {
34716
- if (v.subject.deviceId !== v.deviceId) ctx.addIssue({
34717
- code: ZodIssueCode.custom,
34718
- message: `subject.deviceId (${v.subject.deviceId}) must equal deviceId (${v.deviceId}) — the top-level field is what per-device scope enforcement reads`,
34719
- path: ["subject", "deviceId"]
34720
- });
34721
- if (v.fromMs !== void 0 || v.toMs !== void 0) ctx.addIssue({
34722
- code: ZodIssueCode.custom,
34723
- message: "a clip export asks for no time range: the camera chose the boundaries and they are read from the catalog row",
34724
- path: ["fromMs"]
34975
+ /** `'Monday'` → 0. Case-insensitive. Null for anything unrecognised. */
34976
+ function dayOfWeekToIndex(value) {
34977
+ const needle = value.trim().toLowerCase();
34978
+ const index = DAY_NAMES.findIndex((name) => name.toLowerCase() === needle);
34979
+ return index >= 0 ? index : null;
34980
+ }
34981
+ /**
34982
+ * Which fields of a patch the camera did NOT take verbatim.
34983
+ *
34984
+ * Measured on a Hikvision I91DN (1436, 2026-09-22): a `PUT` of
34985
+ * `PreRecordTimeSeconds: 8` answered `200`, `statusCode 1`, `OK` — and stored
34986
+ * **5**. Neither the asked value nor the previous one. The camera declares no
34987
+ * allowed set for that field, so there is nothing to refuse against before the
34988
+ * wire: `/capabilities` returns a plain value where a constrained field would
34989
+ * carry an `opt=` list.
34990
+ *
34991
+ * So the only honest moment is after the read-back, and re-reading alone is
34992
+ * not enough — it makes the difference VISIBLE while leaving it unexplained.
34993
+ * A write that reports success for a value the camera never took is the same
34994
+ * silent substitution D599 removed from the clip path, wearing a different hat.
34995
+ *
34996
+ * Compares only the fields the patch actually named: a field nobody asked
34997
+ * about cannot have been clamped, and a read-back that could not answer it is
34998
+ * `stored: null` rather than a claim.
34999
+ */
35000
+ function describeOnboardClamp(patch, landed) {
35001
+ const out = [];
35002
+ for (const [field, asked] of Object.entries(patch)) {
35003
+ if (asked === void 0) continue;
35004
+ if (typeof asked !== "number" && typeof asked !== "boolean" && typeof asked !== "string") continue;
35005
+ const raw = landed === null ? void 0 : landed[field];
35006
+ const stored = typeof raw === "number" || typeof raw === "boolean" || typeof raw === "string" ? raw : null;
35007
+ if (stored !== asked) out.push({
35008
+ field,
35009
+ asked,
35010
+ stored
34725
35011
  });
34726
- return;
34727
35012
  }
34728
- if (v.subject?.kind === "footage" && v.subject.deviceId !== v.deviceId) ctx.addIssue({
34729
- code: ZodIssueCode.custom,
34730
- message: `subject.deviceId (${v.subject.deviceId}) must equal deviceId (${v.deviceId})`,
34731
- path: ["subject", "deviceId"]
34732
- });
34733
- const fromMs = v.subject?.kind === "footage" ? v.subject.fromMs : v.fromMs;
34734
- const toMs = v.subject?.kind === "footage" ? v.subject.toMs : v.toMs;
34735
- if (typeof fromMs !== "number" || typeof toMs !== "number") ctx.addIssue({
34736
- code: ZodIssueCode.custom,
34737
- message: "a footage export needs fromMs and toMs",
34738
- path: ["fromMs"]
34739
- });
34740
- if ((v.subject?.kind === "footage" ? [...v.subject.profiles] : resolveExportProfiles(v)).length < 1) ctx.addIssue({
34741
- code: ZodIssueCode.custom,
34742
- message: "pass profiles[] (min 1) or legacy profile",
34743
- path: ["profiles"]
34744
- });
34745
- }), ExportRecordSchema, {
34746
- kind: "mutation",
34747
- auth: "protected"
34748
- }), method(object({ deviceId: number().optional() }), array(ExportRecordSchema), {
34749
- kind: "query",
34750
- auth: "protected"
34751
- }), method(object({ exportId: string() }), ExportRecordSchema, {
34752
- kind: "query",
34753
- auth: "protected"
34754
- }), method(object({ exportId: string() }), ExportRecordSchema, {
34755
- kind: "mutation",
34756
- auth: "protected"
34757
- }), method(object({ exportId: string() }), ExportRecordSchema, {
34758
- kind: "mutation",
34759
- auth: "protected"
34760
- }), method(object({ exportId: string() }), ExportDownloadSchema, {
34761
- kind: "query",
34762
- auth: "protected"
34763
- }), method(object({ exportId: string() }), ExportBytesSchema, {
34764
- kind: "query",
34765
- auth: "protected"
34766
- });
35013
+ return out;
35014
+ }
34767
35015
  /**
34768
35016
  * A camera's own "record me NOW" LEVEL — a signal the device raises while
34769
35017
  * something it knows about is happening (a robot vacuum cleaning, a machine
@@ -42656,24 +42904,6 @@ Object.freeze({
42656
42904
  addonId: null,
42657
42905
  access: "view"
42658
42906
  },
42659
- "events.getEventClipUrl": {
42660
- capName: "events",
42661
- capScope: "device",
42662
- addonId: null,
42663
- access: "view"
42664
- },
42665
- "events.getEvents": {
42666
- capName: "events",
42667
- capScope: "device",
42668
- addonId: null,
42669
- access: "view"
42670
- },
42671
- "events.getEventThumbnail": {
42672
- capName: "events",
42673
- capScope: "device",
42674
- addonId: null,
42675
- access: "view"
42676
- },
42677
42907
  "faceGallery.assignFace": {
42678
42908
  capName: "face-gallery",
42679
42909
  capScope: "system",
@@ -45548,224 +45778,236 @@ Object.freeze({
45548
45778
  addonId: null,
45549
45779
  access: "create"
45550
45780
  },
45551
- "recording.applyDeviceSettingsPatch": {
45781
+ "recording.getAvailability": {
45552
45782
  capName: "recording",
45553
- capScope: "system",
45783
+ capScope: "device",
45554
45784
  addonId: null,
45555
- access: "create"
45785
+ access: "view"
45556
45786
  },
45557
- "recording.cancelRelocateJob": {
45787
+ "recording.getDaysWithRecordings": {
45558
45788
  capName: "recording",
45559
- capScope: "system",
45789
+ capScope: "device",
45560
45790
  addonId: null,
45561
- access: "create"
45791
+ access: "view"
45562
45792
  },
45563
- "recording.cancelStorageMigrationMove": {
45793
+ "recording.getPlayback": {
45564
45794
  capName: "recording",
45565
- capScope: "system",
45795
+ capScope: "device",
45566
45796
  addonId: null,
45567
- access: "create"
45797
+ access: "view"
45568
45798
  },
45569
- "recording.deleteFootprint": {
45799
+ "recording.getPlaybackOptions": {
45570
45800
  capName: "recording",
45571
- capScope: "system",
45801
+ capScope: "device",
45572
45802
  addonId: null,
45573
- access: "delete"
45803
+ access: "view"
45574
45804
  },
45575
- "recording.getAvailability": {
45805
+ "recording.listSources": {
45576
45806
  capName: "recording",
45577
- capScope: "system",
45807
+ capScope: "device",
45578
45808
  addonId: null,
45579
45809
  access: "view"
45580
45810
  },
45581
- "recording.getAvailabilityBatch": {
45582
- capName: "recording",
45811
+ "recordingArchive.applyDeviceSettingsPatch": {
45812
+ capName: "recording-archive",
45583
45813
  capScope: "system",
45584
45814
  addonId: null,
45585
- access: "view"
45815
+ access: "create"
45586
45816
  },
45587
- "recording.getDaysWithRecordings": {
45588
- capName: "recording",
45817
+ "recordingArchive.cancelRelocateJob": {
45818
+ capName: "recording-archive",
45589
45819
  capScope: "system",
45590
45820
  addonId: null,
45591
- access: "view"
45821
+ access: "create"
45592
45822
  },
45593
- "recording.getDaysWithRecordingsBatch": {
45594
- capName: "recording",
45823
+ "recordingArchive.cancelStorageMigrationMove": {
45824
+ capName: "recording-archive",
45825
+ capScope: "system",
45826
+ addonId: null,
45827
+ access: "create"
45828
+ },
45829
+ "recordingArchive.deleteFootprint": {
45830
+ capName: "recording-archive",
45831
+ capScope: "system",
45832
+ addonId: null,
45833
+ access: "delete"
45834
+ },
45835
+ "recordingArchive.getAvailabilityBatch": {
45836
+ capName: "recording-archive",
45595
45837
  capScope: "system",
45596
45838
  addonId: null,
45597
45839
  access: "view"
45598
45840
  },
45599
- "recording.getDeviceConfig": {
45600
- capName: "recording",
45841
+ "recordingArchive.getDaysWithRecordingsBatch": {
45842
+ capName: "recording-archive",
45601
45843
  capScope: "system",
45602
45844
  addonId: null,
45603
45845
  access: "view"
45604
45846
  },
45605
- "recording.getDeviceLiveContribution": {
45606
- capName: "recording",
45847
+ "recordingArchive.getDeviceConfig": {
45848
+ capName: "recording-archive",
45607
45849
  capScope: "system",
45608
45850
  addonId: null,
45609
45851
  access: "view"
45610
45852
  },
45611
- "recording.getDeviceSettingsContribution": {
45612
- capName: "recording",
45853
+ "recordingArchive.getDeviceLiveContribution": {
45854
+ capName: "recording-archive",
45613
45855
  capScope: "system",
45614
45856
  addonId: null,
45615
45857
  access: "view"
45616
45858
  },
45617
- "recording.getPlacement": {
45618
- capName: "recording",
45859
+ "recordingArchive.getDeviceSettingsContribution": {
45860
+ capName: "recording-archive",
45619
45861
  capScope: "system",
45620
45862
  addonId: null,
45621
45863
  access: "view"
45622
45864
  },
45623
- "recording.getPlaybackManifest": {
45624
- capName: "recording",
45865
+ "recordingArchive.getPlacement": {
45866
+ capName: "recording-archive",
45625
45867
  capScope: "system",
45626
45868
  addonId: null,
45627
45869
  access: "view"
45628
45870
  },
45629
- "recording.getRelocateResidue": {
45630
- capName: "recording",
45871
+ "recordingArchive.getRelocateResidue": {
45872
+ capName: "recording-archive",
45631
45873
  capScope: "system",
45632
45874
  addonId: null,
45633
45875
  access: "view"
45634
45876
  },
45635
- "recording.getStatus": {
45636
- capName: "recording",
45877
+ "recordingArchive.getStatus": {
45878
+ capName: "recording-archive",
45637
45879
  capScope: "system",
45638
45880
  addonId: null,
45639
45881
  access: "view"
45640
45882
  },
45641
- "recording.getStorageMigrationMoveStatus": {
45642
- capName: "recording",
45883
+ "recordingArchive.getStorageMigrationMoveStatus": {
45884
+ capName: "recording-archive",
45643
45885
  capScope: "system",
45644
45886
  addonId: null,
45645
45887
  access: "view"
45646
45888
  },
45647
- "recording.getStorageUsage": {
45648
- capName: "recording",
45889
+ "recordingArchive.getStorageUsage": {
45890
+ capName: "recording-archive",
45649
45891
  capScope: "system",
45650
45892
  addonId: null,
45651
45893
  access: "view"
45652
45894
  },
45653
- "recording.listOpsLog": {
45654
- capName: "recording",
45895
+ "recordingArchive.listOpsLog": {
45896
+ capName: "recording-archive",
45655
45897
  capScope: "system",
45656
45898
  addonId: null,
45657
45899
  access: "view"
45658
45900
  },
45659
- "recording.listRelocateJobs": {
45660
- capName: "recording",
45901
+ "recordingArchive.listRelocateJobs": {
45902
+ capName: "recording-archive",
45661
45903
  capScope: "system",
45662
45904
  addonId: null,
45663
45905
  access: "view"
45664
45906
  },
45665
- "recording.locateSegment": {
45666
- capName: "recording",
45907
+ "recordingArchive.locateSegment": {
45908
+ capName: "recording-archive",
45667
45909
  capScope: "system",
45668
45910
  addonId: null,
45669
45911
  access: "view"
45670
45912
  },
45671
- "recording.pauseForStorageMigration": {
45672
- capName: "recording",
45913
+ "recordingArchive.pauseForStorageMigration": {
45914
+ capName: "recording-archive",
45673
45915
  capScope: "system",
45674
45916
  addonId: null,
45675
45917
  access: "create"
45676
45918
  },
45677
- "recording.planStorageRebalance": {
45678
- capName: "recording",
45919
+ "recordingArchive.planStorageRebalance": {
45920
+ capName: "recording-archive",
45679
45921
  capScope: "system",
45680
45922
  addonId: null,
45681
45923
  access: "view"
45682
45924
  },
45683
- "recording.pruneFootage": {
45684
- capName: "recording",
45925
+ "recordingArchive.pruneFootage": {
45926
+ capName: "recording-archive",
45685
45927
  capScope: "system",
45686
45928
  addonId: null,
45687
45929
  access: "create"
45688
45930
  },
45689
- "recording.readGopBytes": {
45690
- capName: "recording",
45931
+ "recordingArchive.readGopBytes": {
45932
+ capName: "recording-archive",
45691
45933
  capScope: "system",
45692
45934
  addonId: null,
45693
45935
  access: "view"
45694
45936
  },
45695
- "recording.readSegmentBytes": {
45696
- capName: "recording",
45937
+ "recordingArchive.readSegmentBytes": {
45938
+ capName: "recording-archive",
45697
45939
  capScope: "system",
45698
45940
  addonId: null,
45699
45941
  access: "view"
45700
45942
  },
45701
- "recording.readWindowBytes": {
45702
- capName: "recording",
45943
+ "recordingArchive.readWindowBytes": {
45944
+ capName: "recording-archive",
45703
45945
  capScope: "system",
45704
45946
  addonId: null,
45705
45947
  access: "view"
45706
45948
  },
45707
- "recording.reconcileLedgerAgainstDisk": {
45708
- capName: "recording",
45949
+ "recordingArchive.reconcileLedgerAgainstDisk": {
45950
+ capName: "recording-archive",
45709
45951
  capScope: "system",
45710
45952
  addonId: null,
45711
45953
  access: "create"
45712
45954
  },
45713
- "recording.refreshStorageLocationsForMigration": {
45714
- capName: "recording",
45955
+ "recordingArchive.refreshStorageLocationsForMigration": {
45956
+ capName: "recording-archive",
45715
45957
  capScope: "system",
45716
45958
  addonId: null,
45717
45959
  access: "create"
45718
45960
  },
45719
- "recording.relocateFootage": {
45720
- capName: "recording",
45961
+ "recordingArchive.relocateFootage": {
45962
+ capName: "recording-archive",
45721
45963
  capScope: "system",
45722
45964
  addonId: null,
45723
45965
  access: "create"
45724
45966
  },
45725
- "recording.renderClip": {
45726
- capName: "recording",
45967
+ "recordingArchive.renderClip": {
45968
+ capName: "recording-archive",
45727
45969
  capScope: "system",
45728
45970
  addonId: null,
45729
45971
  access: "create"
45730
45972
  },
45731
- "recording.renderGif": {
45732
- capName: "recording",
45973
+ "recordingArchive.renderGif": {
45974
+ capName: "recording-archive",
45733
45975
  capScope: "system",
45734
45976
  addonId: null,
45735
45977
  access: "create"
45736
45978
  },
45737
- "recording.rescanStorage": {
45738
- capName: "recording",
45979
+ "recordingArchive.rescanStorage": {
45980
+ capName: "recording-archive",
45739
45981
  capScope: "system",
45740
45982
  addonId: null,
45741
45983
  access: "create"
45742
45984
  },
45743
- "recording.resumeForStorageMigration": {
45744
- capName: "recording",
45985
+ "recordingArchive.resumeForStorageMigration": {
45986
+ capName: "recording-archive",
45745
45987
  capScope: "system",
45746
45988
  addonId: null,
45747
45989
  access: "create"
45748
45990
  },
45749
- "recording.setDeviceConfig": {
45750
- capName: "recording",
45991
+ "recordingArchive.setDeviceConfig": {
45992
+ capName: "recording-archive",
45751
45993
  capScope: "system",
45752
45994
  addonId: null,
45753
45995
  access: "create"
45754
45996
  },
45755
- "recording.setDevicePlacement": {
45756
- capName: "recording",
45997
+ "recordingArchive.setDevicePlacement": {
45998
+ capName: "recording-archive",
45757
45999
  capScope: "system",
45758
46000
  addonId: null,
45759
46001
  access: "create"
45760
46002
  },
45761
- "recording.startStorageMigrationMove": {
45762
- capName: "recording",
46003
+ "recordingArchive.startStorageMigrationMove": {
46004
+ capName: "recording-archive",
45763
46005
  capScope: "system",
45764
46006
  addonId: null,
45765
46007
  access: "create"
45766
46008
  },
45767
- "recording.startStorageRebalance": {
45768
- capName: "recording",
46009
+ "recordingArchive.startStorageRebalance": {
46010
+ capName: "recording-archive",
45769
46011
  capScope: "system",
45770
46012
  addonId: null,
45771
46013
  access: "create"
@@ -48070,21 +48312,6 @@ Object.freeze({
48070
48312
  form: "single",
48071
48313
  optional: false
48072
48314
  }],
48073
- "events.getEventClipUrl": [{
48074
- name: "deviceId",
48075
- form: "single",
48076
- optional: false
48077
- }],
48078
- "events.getEvents": [{
48079
- name: "deviceId",
48080
- form: "single",
48081
- optional: false
48082
- }],
48083
- "events.getEventThumbnail": [{
48084
- name: "deviceId",
48085
- form: "single",
48086
- optional: false
48087
- }],
48088
48315
  "faceGallery.getFaceByTrack": [{
48089
48316
  name: "deviceId",
48090
48317
  form: "single",
@@ -49003,107 +49230,117 @@ Object.freeze({
49003
49230
  form: "single",
49004
49231
  optional: false
49005
49232
  }],
49006
- "recording.deleteFootprint": [{
49233
+ "recording.getAvailability": [{
49007
49234
  name: "deviceId",
49008
49235
  form: "single",
49009
49236
  optional: false
49010
49237
  }],
49011
- "recording.getAvailability": [{
49238
+ "recording.getDaysWithRecordings": [{
49012
49239
  name: "deviceId",
49013
49240
  form: "single",
49014
49241
  optional: false
49015
49242
  }],
49016
- "recording.getAvailabilityBatch": [{
49017
- name: "deviceIds",
49018
- form: "array",
49243
+ "recording.getPlayback": [{
49244
+ name: "deviceId",
49245
+ form: "single",
49019
49246
  optional: false
49020
49247
  }],
49021
- "recording.getDaysWithRecordings": [{
49248
+ "recording.getPlaybackOptions": [{
49022
49249
  name: "deviceId",
49023
49250
  form: "single",
49024
49251
  optional: false
49025
49252
  }],
49026
- "recording.getDaysWithRecordingsBatch": [{
49027
- name: "deviceIds",
49028
- form: "array",
49253
+ "recording.listSources": [{
49254
+ name: "deviceId",
49255
+ form: "single",
49029
49256
  optional: false
49030
49257
  }],
49031
- "recording.getDeviceConfig": [{
49258
+ "recordingArchive.deleteFootprint": [{
49032
49259
  name: "deviceId",
49033
49260
  form: "single",
49034
49261
  optional: false
49035
49262
  }],
49036
- "recording.getPlaybackManifest": [{
49263
+ "recordingArchive.getAvailabilityBatch": [{
49264
+ name: "deviceIds",
49265
+ form: "array",
49266
+ optional: false
49267
+ }],
49268
+ "recordingArchive.getDaysWithRecordingsBatch": [{
49269
+ name: "deviceIds",
49270
+ form: "array",
49271
+ optional: false
49272
+ }],
49273
+ "recordingArchive.getDeviceConfig": [{
49037
49274
  name: "deviceId",
49038
49275
  form: "single",
49039
49276
  optional: false
49040
49277
  }],
49041
- "recording.listOpsLog": [{
49278
+ "recordingArchive.listOpsLog": [{
49042
49279
  name: "deviceId",
49043
49280
  form: "single",
49044
49281
  optional: true
49045
49282
  }],
49046
- "recording.locateSegment": [{
49283
+ "recordingArchive.locateSegment": [{
49047
49284
  name: "deviceId",
49048
49285
  form: "single",
49049
49286
  optional: false
49050
49287
  }],
49051
- "recording.pruneFootage": [{
49288
+ "recordingArchive.pruneFootage": [{
49052
49289
  name: "deviceId",
49053
49290
  form: "single",
49054
49291
  optional: false
49055
49292
  }],
49056
- "recording.readGopBytes": [{
49293
+ "recordingArchive.readGopBytes": [{
49057
49294
  name: "deviceId",
49058
49295
  form: "single",
49059
49296
  optional: false
49060
49297
  }],
49061
- "recording.readSegmentBytes": [{
49298
+ "recordingArchive.readSegmentBytes": [{
49062
49299
  name: "deviceId",
49063
49300
  form: "single",
49064
49301
  optional: false
49065
49302
  }],
49066
- "recording.readWindowBytes": [{
49303
+ "recordingArchive.readWindowBytes": [{
49067
49304
  name: "deviceId",
49068
49305
  form: "single",
49069
49306
  optional: false
49070
49307
  }],
49071
- "recording.reconcileLedgerAgainstDisk": [{
49308
+ "recordingArchive.reconcileLedgerAgainstDisk": [{
49072
49309
  name: "deviceId",
49073
49310
  form: "single",
49074
49311
  optional: true
49075
49312
  }],
49076
- "recording.relocateFootage": [{
49313
+ "recordingArchive.relocateFootage": [{
49077
49314
  name: "deviceId",
49078
49315
  form: "single",
49079
49316
  optional: true
49080
49317
  }],
49081
- "recording.renderClip": [{
49318
+ "recordingArchive.renderClip": [{
49082
49319
  name: "deviceId",
49083
49320
  form: "single",
49084
49321
  optional: false
49085
49322
  }],
49086
- "recording.renderGif": [{
49323
+ "recordingArchive.renderGif": [{
49087
49324
  name: "deviceId",
49088
49325
  form: "single",
49089
49326
  optional: false
49090
49327
  }],
49091
- "recording.rescanStorage": [{
49328
+ "recordingArchive.rescanStorage": [{
49092
49329
  name: "deviceId",
49093
49330
  form: "single",
49094
49331
  optional: false
49095
49332
  }],
49096
- "recording.setDeviceConfig": [{
49333
+ "recordingArchive.setDeviceConfig": [{
49097
49334
  name: "deviceId",
49098
49335
  form: "single",
49099
49336
  optional: false
49100
49337
  }],
49101
- "recording.setDevicePlacement": [{
49338
+ "recordingArchive.setDevicePlacement": [{
49102
49339
  name: "deviceId",
49103
49340
  form: "single",
49104
49341
  optional: false
49105
49342
  }],
49106
- "recording.startStorageMigrationMove": [{
49343
+ "recordingArchive.startStorageMigrationMove": [{
49107
49344
  name: "deviceId",
49108
49345
  form: "single",
49109
49346
  optional: true
@@ -50723,8 +50960,14 @@ function createClipThumbHandler(deps) {
50723
50960
  * The 204, with everything the tile needs to decide what to draw next.
50724
50961
  *
50725
50962
  * A FINAL refusal is work that was dropped, so it is warned, per camera. A
50726
- * DEFERRED one dropped nothing — the still is queued behind the camera's one
50727
- * replay slot — and warning it would put a line on the log per tile of a page.
50963
+ * DEFERRED one dropped nothing — the camera's one playback slot is busy, or an
50964
+ * operator's tap evicted this mint mid-replay — and warning it would put a
50965
+ * line on the log per tile of a page.
50966
+ *
50967
+ * There was briefly a third rule here, exempting `media-not-held` from the
50968
+ * warn because it was the steady state of every list. That code is gone
50969
+ * because its cause is: a clip whose bytes are not held now MINTS, in about
50970
+ * half a second off the camera, instead of refusing.
50728
50971
  */
50729
50972
  function writeStillRefusal(res, refusal, deviceId, logger, clipKey) {
50730
50973
  const line = "videoclips: thumbnail not minted";
@@ -50962,25 +51205,58 @@ var CLIP_STREAM_PCMU_RATE_HZ = 8e3;
50962
51205
  /**
50963
51206
  * How much of an input ffmpeg may READ before it will write a header.
50964
51207
  *
50965
- * ffmpeg probes every input to discover what is in it. Both defaults are
50966
- * enormous for this use — `probesize` 5 MB, `analyzeduration` 5 s — and both
51208
+ * ffmpeg probes every input to discover what is in it, and both defaults are
51209
+ * enormous for this use — `probesize` 5 MB, `analyzeduration` 5 s — which here
50967
51210
  * are paid in the operator's wait, because a Hikvision replay arrives at 1×
50968
- * (measured 1.01× on 1436, 2026-09-23) so "5 MB of input" is seconds of wall
50969
- * clock, not microseconds of buffer.
50970
- *
50971
- * **Nothing here is being discovered.** The demuxer is named (`-f hevc` /
50972
- * `-f h264`, from the SDP's own `a=rtpmap`), the frame rate is named (`-r`,
50973
- * measured from the replay's RTP clock and refused when it cannot be), and the
50974
- * µ-law input is named down to its sample rate and channel count. A probe can
50975
- * only re-derive what the caller already stated.
50976
- *
50977
- * Measured end to end against the real 1436 clip (18 s, 4K HEVC, 12.5 fps,
50978
- * GOP 50): with the defaults the init segment reached the peer at 3889 ms and
50979
- * the first media fragment at 3891 ms; with these two flags, 171 ms and
50980
- * 2269 ms. 32 KiB is two orders of magnitude over the parameter sets the hevc
50981
- * demuxer needs and still one one-hundred-and-fiftieth of the default.
50982
- */
50983
- var CLIP_MUX_PROBE_BYTES = 32768;
51211
+ * and "5 MB of input" is seconds of wall clock. `-analyzeduration 0` goes with
51212
+ * it: the demuxer is named (`-f hevc`/`-f h264`, from the SDP's own
51213
+ * `a=rtpmap`), the rate is named (`-r`, measured), and the µ-law input is
51214
+ * named down to its sample rate. A probe can only re-derive what was stated.
51215
+ *
51216
+ * **256 KiB, and the number is a compromise between two measurements.** This
51217
+ * shipped at 32 KiB, which is six per cent of ONE access unit — the first unit
51218
+ * of a 3840×2160 HEVC replay on 1436 measures **550 354 bytes**, a whole 4K
51219
+ * keyframe with its parameter sets — and a bound that cannot hold a single
51220
+ * frame is uncomfortable whatever it gets away with. But widening it is not
51221
+ * free and it fixes nothing: measured against the pinned jellyfin 8.1.2 build
51222
+ * on the real camera, first byte to the peer was **721 ms at 32 KiB, 752 ms at
51223
+ * 256 KiB, 1 126 ms at 768 KiB**. 256 KiB buys eight times the headroom for
51224
+ * 31 ms.
51225
+ *
51226
+ * **It is explicitly NOT the cause of the header-and-no-media failure** that
51227
+ * cost the fleet an afternoon, and it was the first suspect. Every probe size
51228
+ * from 32 KiB to 768 KiB reproduced that fault identically, and removing the
51229
+ * flags altogether reproduced it too; the cause was
51230
+ * {@link CLIP_STREAM_MAX_INTERLEAVE_DELTA_US}. Written down so the hypothesis
51231
+ * is not re-tried.
51232
+ */
51233
+ var CLIP_MUX_PROBE_BYTES = 256 * 1024;
51234
+ /**
51235
+ * How long the muxer may hold one track's packets WAITING for the other.
51236
+ *
51237
+ * **This is the whole reason a clip with sound would not play.** Measured on
51238
+ * 1436, 2026-09-23, through the real producer against the real camera with the
51239
+ * pinned build: a SILENT stream delivered 1 299 KiB to the peer by the
51240
+ * halfway point of a six-second clip, and the same clip with `opus` or `pcmu`
51241
+ * delivered **1 KiB** — the init segment, and nothing else — until the inputs
51242
+ * ENDED, at which point all 3.78 MB arrived in one burst. From the operator's
51243
+ * own session: 129 access units in, `bytesOut: 1298` out, `pushed: 0` on the
51244
+ * broker, and a player that gave up after 10.6 s with nothing to show.
51245
+ *
51246
+ * ffmpeg buffers packets to interleave two inputs, and with video on stdin and
51247
+ * µ-law on `pipe:3` it decided to wait rather than write. It is not a rate
51248
+ * mismatch — the two timelines measured 4.80 s of video against 4.80 s of
51249
+ * audio, a ratio of 1.000 — it is the muxer's own interleaving window, and for
51250
+ * a LIVE fragmented stream any window at all is wrong.
51251
+ *
51252
+ * **`0` does not mean "no window". It means UNLIMITED**, and it reproduced the
51253
+ * fault exactly. The value has to be small and positive. 100 ms is two and a
51254
+ * half of this camera's 40 ms µ-law frames — long enough that ordinary jitter
51255
+ * does not split a fragment, short enough that no consumer notices.
51256
+ *
51257
+ * With it, all three audio asks deliver ~1 278 KiB by the same halfway point.
51258
+ */
51259
+ var CLIP_STREAM_MAX_INTERLEAVE_DELTA_US = 1e5;
50984
51260
  /**
50985
51261
  * How long a fragment may run before it is CLOSED, keyframe or not.
50986
51262
  *
@@ -51071,6 +51347,8 @@ function buildClipStreamMuxArgs(input) {
51071
51347
  CLIP_STREAM_MOVFLAGS,
51072
51348
  "-frag_duration",
51073
51349
  String(CLIP_STREAM_FRAG_DURATION_US),
51350
+ "-max_interleave_delta",
51351
+ String(CLIP_STREAM_MAX_INTERLEAVE_DELTA_US),
51074
51352
  "-flush_packets",
51075
51353
  "1",
51076
51354
  "-f",
@@ -51132,12 +51410,19 @@ function createDrainGate(deps) {
51132
51410
  return {
51133
51411
  wrote(accepted) {
51134
51412
  if (accepted || handle !== null || stalled) return;
51135
- handle = setTimeout(() => {
51136
- handle = null;
51137
- if (stalled) return;
51138
- stalled = true;
51139
- deps.onStall();
51140
- }, deps.timeoutMs);
51413
+ const arm = () => {
51414
+ handle = setTimeout(() => {
51415
+ handle = null;
51416
+ if (stalled) return;
51417
+ if (deps.stillMoving?.() === true) {
51418
+ arm();
51419
+ return;
51420
+ }
51421
+ stalled = true;
51422
+ deps.onStall();
51423
+ }, deps.timeoutMs);
51424
+ };
51425
+ arm();
51141
51426
  },
51142
51427
  drained() {
51143
51428
  disarm();
@@ -52112,26 +52397,8 @@ async function prepareClipFile(input, deps) {
52112
52397
  detail: err instanceof Error ? err.message : String(err)
52113
52398
  };
52114
52399
  }
52115
- const abort = () => void session.close();
52116
- deps.signal?.addEventListener("abort", abort, { once: true });
52117
52400
  const end = await session.ended;
52118
- deps.signal?.removeEventListener("abort", abort);
52119
52401
  await session.close();
52120
- if (deps.signal?.aborted === true) {
52121
- deps.logger.debug("videoclips: a clip fetch gave the slot back", {
52122
- tags,
52123
- meta: {
52124
- ...meta,
52125
- branch: "preempted",
52126
- accessUnits: units.length
52127
- }
52128
- });
52129
- return {
52130
- kind: "refused",
52131
- code: "fetch-failed",
52132
- detail: "preempted: the camera’s one replay slot was wanted by a stream"
52133
- };
52134
- }
52135
52402
  if (end.kind === "failed") return {
52136
52403
  kind: "refused",
52137
52404
  code: "camera-refused",
@@ -52246,19 +52513,7 @@ async function prepareClipFile(input, deps) {
52246
52513
  * than that is a holder that is still playing.
52247
52514
  */
52248
52515
  var REPLAY_LANE_WAIT_MS = RTSP_TEARDOWN_FLUSH_MS + 1e3;
52249
- /**
52250
- * Which purposes are SPECULATIVE — work nobody is waiting on.
52251
- *
52252
- * A still is minted for a tile that is not on screen yet. A stream and a file
52253
- * are an operator who has already tapped. When the two want the same camera,
52254
- * the operator wins: the speculative holder is asked to give the slot back
52255
- * (`yield`) and the ask waits for it, instead of being refused for want of
52256
- * work that could have been done a minute later.
52257
- *
52258
- * Without this, opening a list of clips would start a realtime fetch per tile
52259
- * and every playback tap during it would meet `replay-busy` — which is a
52260
- * regression traded for a thumbnail, and not a trade anyone asked for.
52261
- */
52516
+ /** Work nobody is waiting on, which an operator's tap may evict. */
52262
52517
  var SPECULATIVE = new Set(["still"]);
52263
52518
  function createReplayLane(deps) {
52264
52519
  const now = deps.now ?? (() => Date.now());
@@ -52370,14 +52625,65 @@ function buildClipStillArgs(input) {
52370
52625
  ];
52371
52626
  }
52372
52627
  /**
52628
+ * What ffmpeg is told to cut a still out of RAW ACCESS UNITS.
52629
+ *
52630
+ * The other half of the same job. A clip whose bytes are not on this disk is
52631
+ * never FETCHED — that costs the camera its playback session for the clip's
52632
+ * whole duration — so its FIRST frame is taken off the camera in about half a
52633
+ * second (`clip-first-frame.ts`) and decoded here, from an elementary stream
52634
+ * on stdin rather than from a file.
52635
+ *
52636
+ * No `-ss`: the units ARE the head, and there is no seek inside a Hikvision
52637
+ * replay to reach anything else. No `-r`: one frame carries no rate, which is
52638
+ * the single case `clip-replay-rate.ts`'s rule does not reach.
52639
+ */
52640
+ function buildFirstFrameStillArgs(codec) {
52641
+ return [
52642
+ "-hide_banner",
52643
+ "-loglevel",
52644
+ "error",
52645
+ "-nostdin",
52646
+ "-analyzeduration",
52647
+ "0",
52648
+ "-probesize",
52649
+ String(CLIP_MUX_PROBE_BYTES),
52650
+ "-f",
52651
+ codec === "h265" ? "hevc" : "h264",
52652
+ "-i",
52653
+ "pipe:0",
52654
+ "-frames:v",
52655
+ "1",
52656
+ "-vf",
52657
+ `scale=${String(640)}:-2:flags=bicubic`,
52658
+ "-q:v",
52659
+ String(4),
52660
+ "-f",
52661
+ "mjpeg",
52662
+ "pipe:1"
52663
+ ];
52664
+ }
52665
+ /** The first frame the camera handed over, as a JPEG. Never throws. */
52666
+ async function cutStillFromAccessUnits(units, codec, deps) {
52667
+ return await runStillFfmpeg(buildFirstFrameStillArgs(codec), Buffer.concat(units.map((unit) => Buffer.from(unit.bytes))), deps, "the camera’s first access units");
52668
+ }
52669
+ /**
52373
52670
  * Cut one still. Never throws: every dead end is a named refusal.
52374
52671
  */
52375
52672
  async function cutClipStill(input, deps) {
52376
- const args = buildClipStillArgs(input);
52673
+ return await runStillFfmpeg(buildClipStillArgs(input), null, deps, `${clipStillSeekSeconds(input.durationMs).toFixed(3)} s into the held file`);
52674
+ }
52675
+ /**
52676
+ * One bounded ffmpeg that answers with a JPEG or a named refusal.
52677
+ *
52678
+ * `stdin` carries the elementary stream when the source is the camera, and is
52679
+ * `null` when the source is a path. Shared, so the two cannot drift apart on
52680
+ * the timeout, the kill, or what an empty answer means.
52681
+ */
52682
+ async function runStillFfmpeg(args, stdin, deps, where) {
52377
52683
  let child;
52378
52684
  try {
52379
52685
  child = deps.spawnStill?.([...args]) ?? spawn(deps.ffmpegBinaryPath ?? "ffmpeg", [...args], { stdio: [
52380
- "ignore",
52686
+ stdin === null ? "ignore" : "pipe",
52381
52687
  "pipe",
52382
52688
  "pipe"
52383
52689
  ] });
@@ -52394,6 +52700,10 @@ async function cutClipStill(input, deps) {
52394
52700
  child.stderr?.on("data", (chunk) => {
52395
52701
  stderr += chunk.toString("utf8");
52396
52702
  });
52703
+ if (stdin !== null) {
52704
+ child.stdin?.on("error", () => {});
52705
+ child.stdin?.end(stdin);
52706
+ }
52397
52707
  const timeoutMs = deps.timeoutMs ?? 1e4;
52398
52708
  const exit = await new Promise((resolve) => {
52399
52709
  const timer = setTimeout(() => resolve("timeout"), timeoutMs);
@@ -52416,19 +52726,100 @@ async function cutClipStill(input, deps) {
52416
52726
  };
52417
52727
  }
52418
52728
  const bytes = Buffer.concat(chunks);
52729
+ if (bytes.byteLength > 0) return {
52730
+ kind: "ok",
52731
+ bytes
52732
+ };
52419
52733
  if (exit !== 0) return {
52420
52734
  kind: "refused",
52421
52735
  code: "decode-failed",
52422
52736
  detail: `ffmpeg exited ${String(exit)}: ${stderr.trim().slice(0, 300)}`
52423
52737
  };
52424
- if (bytes.byteLength === 0) return {
52738
+ return {
52425
52739
  kind: "refused",
52426
52740
  code: "no-keyframe",
52427
- detail: `ffmpeg read the clip and produced no frame at ${clipStillSeekSeconds(input.durationMs).toFixed(3)} s`
52741
+ detail: `ffmpeg read ${where} and produced no frame`
52742
+ };
52743
+ }
52744
+ /** Never throws: every dead end is a named refusal. */
52745
+ async function fetchFirstFrame(input, deps) {
52746
+ const openReplay = deps.openReplay ?? openRtspReplay;
52747
+ const want = deps.accessUnits ?? 2;
52748
+ const timeoutMs = deps.timeoutMs ?? 5e3;
52749
+ const startedAt = Date.now();
52750
+ if (deps.signal?.aborted === true) return {
52751
+ kind: "refused",
52752
+ code: "yielded",
52753
+ detail: "the slot was wanted before the open"
52428
52754
  };
52755
+ const units = [];
52756
+ let enough = null;
52757
+ const gotEnough = new Promise((resolve) => {
52758
+ enough = resolve;
52759
+ });
52760
+ let session;
52761
+ try {
52762
+ session = await openReplay({
52763
+ host: input.camera.host,
52764
+ username: input.camera.username,
52765
+ password: input.camera.password,
52766
+ playbackPath: input.row.playbackPath
52767
+ }, { onVideo: (unit) => {
52768
+ if (units.length >= want) return;
52769
+ units.push(unit);
52770
+ if (units.length >= want) enough?.();
52771
+ } }, {
52772
+ logger: deps.logger,
52773
+ deviceId: input.camera.deviceId
52774
+ });
52775
+ } catch (err) {
52776
+ return {
52777
+ kind: "refused",
52778
+ code: "camera-refused",
52779
+ detail: err instanceof Error ? err.message : String(err)
52780
+ };
52781
+ }
52782
+ let yielded = false;
52783
+ const onAbort = () => {
52784
+ yielded = true;
52785
+ enough?.();
52786
+ };
52787
+ deps.signal?.addEventListener("abort", onAbort, { once: true });
52788
+ let timer = setTimeout(() => {
52789
+ timer = null;
52790
+ enough?.();
52791
+ }, timeoutMs);
52792
+ session.ended.then(() => enough?.());
52793
+ await gotEnough;
52794
+ if (timer !== null) clearTimeout(timer);
52795
+ deps.signal?.removeEventListener("abort", onAbort);
52796
+ await session.close();
52797
+ const slotMs = Date.now() - startedAt;
52798
+ if (yielded) return {
52799
+ kind: "refused",
52800
+ code: "yielded",
52801
+ detail: `a playback wanted the slot after ${String(slotMs)} ms`
52802
+ };
52803
+ if (units.length === 0) return {
52804
+ kind: "refused",
52805
+ code: "camera-refused",
52806
+ detail: `the replay delivered no access unit inside ${String(timeoutMs)} ms`
52807
+ };
52808
+ deps.logger.debug("videoclips: took a clip’s first frame off the camera", {
52809
+ tags: { deviceId: input.camera.deviceId },
52810
+ meta: {
52811
+ clipKey: input.row.clipKey,
52812
+ units: units.length,
52813
+ bytes: units.reduce((sum, unit) => sum + unit.bytes.byteLength, 0),
52814
+ codec: session.video.codec,
52815
+ slotMs
52816
+ }
52817
+ });
52429
52818
  return {
52430
52819
  kind: "ok",
52431
- bytes
52820
+ units,
52821
+ codec: session.video.codec,
52822
+ slotMs
52432
52823
  };
52433
52824
  }
52434
52825
  function pathToken(req) {
@@ -52653,6 +53044,9 @@ var ClipStreamRun = class {
52653
53044
  slotFreed = Promise.resolve();
52654
53045
  settle = null;
52655
53046
  bytesOut = 0;
53047
+ /** {@link bytesOut} the last time the audio gate's window elapsed. */
53048
+ bytesOutAtAudioWindow = 0;
53049
+ audioNotHungryLogged = false;
52656
53050
  accessUnits = 0;
52657
53051
  audioFramesAfterMux = 0;
52658
53052
  audioFramesDropped = 0;
@@ -52661,6 +53055,9 @@ var ClipStreamRun = class {
52661
53055
  * row's, which is a projection (D393). */
52662
53056
  deliveredMs = null;
52663
53057
  begun = false;
53058
+ /** ffmpeg's own words, bounded. Kept so EVERY exit can carry them, not just
53059
+ * the one that happened to be holding the closure. */
53060
+ stderr = "";
52664
53061
  startedAt = Date.now();
52665
53062
  constructor(request, deps) {
52666
53063
  this.request = request;
@@ -52788,7 +53185,8 @@ var ClipStreamRun = class {
52788
53185
  });
52789
53186
  if (this.muxedAudio !== null) this.audioGate = createDrainGate({
52790
53187
  timeoutMs: this.deps.drainTimeoutMs,
52791
- onStall: () => this.sever("mux-audio-stalled", "ffmpeg stopped taking audio frames")
53188
+ onStall: () => this.sever("mux-audio-stalled", "ffmpeg stopped taking audio frames"),
53189
+ stillMoving: () => this.muxProducedSinceLastAudioWindow()
52792
53190
  });
52793
53191
  this.peerGate = createDrainGate({
52794
53192
  timeoutMs: this.deps.drainTimeoutMs,
@@ -52803,24 +53201,65 @@ var ClipStreamRun = class {
52803
53201
  audioPipe.on("drain", () => this.audioGate?.drained());
52804
53202
  }
52805
53203
  child.stdout?.on("data", (chunk) => this.onMuxOutput(chunk));
52806
- let stderr = "";
52807
53204
  child.stderr?.on("data", (chunk) => {
52808
- stderr = `${stderr}${chunk.toString()}`.slice(-2e3);
53205
+ this.stderr = `${this.stderr}${chunk.toString()}`.slice(-2e3);
52809
53206
  });
52810
- child.on("close", (code) => this.onMuxClosed(code, stderr));
52811
- this.request.sink.onceDrain(() => this.peerGate?.drained());
53207
+ child.on("close", (code) => this.onMuxClosed(code, this.stderr));
52812
53208
  for (const unit of this.heldVideo) this.writeVideo(unit);
52813
53209
  this.heldVideo = [];
52814
53210
  if (this.muxedAudio !== null) for (const payload of this.heldAudio) this.writeAudio(payload);
52815
53211
  else this.audioFramesDropped += this.heldAudio.length;
52816
53212
  this.heldAudio = [];
52817
53213
  }
53214
+ /**
53215
+ * Has this mux taken frames and produced no MEDIA?
53216
+ *
53217
+ * Checked as units go in, because that is the only place that knows the mux
53218
+ * is being fed. A header and nothing else is not a slow stream, it is a
53219
+ * broken one, and the peer will otherwise sit on it until it gives up with
53220
+ * nothing to show the operator but a blank player.
53221
+ */
53222
+ checkMuxProducedMedia() {
53223
+ if (this.answered || this.mux === null) return;
53224
+ if (this.accessUnits < 64) return;
53225
+ if (this.bytesOut > 65536) return;
53226
+ this.sever("mux-no-media", `ffmpeg took ${String(this.accessUnits)} access units and produced ${String(this.bytesOut)} bytes — a header and no media` + (this.stderr.trim() === "" ? " (ffmpeg said nothing)" : `: ${this.stderr.trim().slice(-300)}`));
53227
+ }
52818
53228
  writeVideo(unit) {
52819
53229
  const stdin = this.mux?.stdin;
52820
53230
  if (stdin === null || stdin === void 0 || stdin.destroyed) return;
52821
53231
  this.accessUnits += 1;
53232
+ this.checkMuxProducedMedia();
53233
+ if (this.answered) return;
52822
53234
  this.videoGate?.wrote(stdin.write(unit.bytes));
52823
53235
  }
53236
+ /**
53237
+ * Did the mux hand the peer anything during the window the audio gate just
53238
+ * waited out?
53239
+ *
53240
+ * The gate's question is "has this hop stopped for good", and on fd 3 the
53241
+ * answer cannot be read from the pipe alone: 64 KiB of µ-law is eight
53242
+ * seconds of sound, so a muxer that is merely AHEAD on audio looks exactly
53243
+ * like one that has died. ffmpeg's own output settles it — bytes on stdout
53244
+ * are proof it is running — and each window is judged on its own, so a
53245
+ * mux that really stops is still cut one window later.
53246
+ */
53247
+ muxProducedSinceLastAudioWindow() {
53248
+ const moved = this.bytesOut > this.bytesOutAtAudioWindow;
53249
+ this.bytesOutAtAudioWindow = this.bytesOut;
53250
+ if (moved && !this.audioNotHungryLogged) {
53251
+ this.audioNotHungryLogged = true;
53252
+ this.deps.logger.info("videoclips: the mux is not taking audio but is still producing", {
53253
+ tags: this.tags,
53254
+ meta: {
53255
+ ...this.meta,
53256
+ bytesOut: this.bytesOut,
53257
+ accessUnits: this.accessUnits
53258
+ }
53259
+ });
53260
+ }
53261
+ return moved;
53262
+ }
52824
53263
  writeAudio(payload) {
52825
53264
  const pipe = writableStdio(this.mux?.stdio[3]);
52826
53265
  if (pipe === null) return;
@@ -52834,7 +53273,14 @@ var ClipStreamRun = class {
52834
53273
  this.request.sink.begin(clipStreamContentTypeFor(this.muxedAudio));
52835
53274
  }
52836
53275
  this.bytesOut += chunk.byteLength;
52837
- this.peerGate?.wrote(this.request.sink.write(chunk));
53276
+ const accepted = this.request.sink.write(chunk);
53277
+ this.peerGate?.wrote(accepted);
53278
+ if (accepted) return;
53279
+ this.mux?.stdout?.pause();
53280
+ this.request.sink.onceDrain(() => {
53281
+ this.peerGate?.drained();
53282
+ this.mux?.stdout?.resume();
53283
+ });
52838
53284
  }
52839
53285
  finishInputs(deliveredMs) {
52840
53286
  if (this.answered) return;
@@ -52916,6 +53362,7 @@ var ClipStreamRun = class {
52916
53362
  ...this.meta,
52917
53363
  branch,
52918
53364
  reason: detail,
53365
+ muxStderr: this.stderr.trim().slice(-500),
52919
53366
  accessUnits: this.accessUnits,
52920
53367
  bytesOut: this.bytesOut,
52921
53368
  elapsedMs: Date.now() - this.startedAt
@@ -53822,7 +54269,7 @@ function createClipService(deps) {
53822
54269
  maxFilesPerDevice: THUMB_MAX_FILES_PER_DEVICE,
53823
54270
  maxBytesPerDevice: THUMB_MAX_BYTES_PER_DEVICE
53824
54271
  });
53825
- const lane = createReplayLane({
54272
+ const lane = deps.lane ?? createReplayLane({
53826
54273
  logger,
53827
54274
  ...deps.replayWaitMs !== void 0 ? { waitMs: deps.replayWaitMs } : {}
53828
54275
  });
@@ -53947,30 +54394,32 @@ function createClipService(deps) {
53947
54394
  detail: "no-catalog-row: list the window that holds this clip first"
53948
54395
  };
53949
54396
  if (await store.pathIfPresent(deviceId, clipKey) === null) {
53950
- const preempt = new AbortController();
53951
- const lease = await lane.acquire(deviceId, purpose, () => preempt.abort());
54397
+ const lease = await lane.acquire(deviceId, purpose);
53952
54398
  if (lease.kind === "busy") return {
53953
54399
  kind: "refused",
53954
54400
  code: "replay-busy",
53955
54401
  detail: lease.detail
53956
54402
  };
54403
+ let fetched;
53957
54404
  try {
53958
- return await prepareClipFile({
54405
+ fetched = await prepareClipFile({
53959
54406
  camera: cameraFor(camera),
53960
54407
  row,
53961
54408
  audio: true
53962
54409
  }, {
53963
54410
  logger,
53964
54411
  store,
53965
- signal: preempt.signal,
53966
54412
  ...deps.ffmpegBinaryPath !== void 0 ? { ffmpegBinaryPath: deps.ffmpegBinaryPath } : {},
53967
- ...deps.openReplay !== void 0 ? { openReplay: deps.openReplay } : {}
54413
+ ...deps.openReplay !== void 0 ? { openReplay: deps.openReplay } : {},
54414
+ ...deps.spawnMux !== void 0 ? { spawnMux: deps.spawnMux } : {}
53968
54415
  });
53969
54416
  } finally {
53970
54417
  lease.release();
53971
54418
  }
54419
+ if (fetched.kind === "ok") await mintPassing(deviceId, clipKey, fetched);
54420
+ return fetched;
53972
54421
  }
53973
- return await prepareClipFile({
54422
+ const cached = await prepareClipFile({
53974
54423
  camera: cameraFor(camera),
53975
54424
  row,
53976
54425
  audio: true
@@ -53978,8 +54427,46 @@ function createClipService(deps) {
53978
54427
  logger,
53979
54428
  store,
53980
54429
  ...deps.ffmpegBinaryPath !== void 0 ? { ffmpegBinaryPath: deps.ffmpegBinaryPath } : {},
53981
- ...deps.openReplay !== void 0 ? { openReplay: deps.openReplay } : {}
54430
+ ...deps.openReplay !== void 0 ? { openReplay: deps.openReplay } : {},
54431
+ ...deps.spawnMux !== void 0 ? { spawnMux: deps.spawnMux } : {}
53982
54432
  });
54433
+ if (cached.kind === "ok") await mintPassing(deviceId, clipKey, cached);
54434
+ return cached;
54435
+ };
54436
+ /**
54437
+ * Mint the still of a clip whose bytes have just been put on this disk.
54438
+ *
54439
+ * Cheap and idempotent: a `stat` says whether one is already held, and the
54440
+ * cut itself is one frame of a local file. It is AWAITED rather than fired
54441
+ * and forgotten, because an unhandled rejection in a detached promise is
54442
+ * exactly the silence D391 forbids — and because a caller that just waited
54443
+ * 30 s for a fetch is not harmed by 1.8 s of decode.
54444
+ *
54445
+ * A failure here NEVER fails the fetch. The caller asked for a clip, not a
54446
+ * picture, and a still that could not be cut is named and left absent.
54447
+ */
54448
+ const mintPassing = async (deviceId, clipKey, file) => {
54449
+ if (await thumbs.has(deviceId, clipKey)) return;
54450
+ try {
54451
+ const minted = await cutHeldStill(deviceId, clipKey, file.path, file.durationMs);
54452
+ if (minted.ok) return;
54453
+ logger.debug("videoclips: no still was cut from a clip that was just fetched", {
54454
+ tags: { deviceId },
54455
+ meta: {
54456
+ clipKey,
54457
+ branch: minted.code,
54458
+ reason: minted.reason
54459
+ }
54460
+ });
54461
+ } catch (err) {
54462
+ logger.warn("videoclips: the passing still mint threw", {
54463
+ tags: { deviceId },
54464
+ meta: {
54465
+ clipKey,
54466
+ error: err instanceof Error ? err.message : String(err)
54467
+ }
54468
+ });
54469
+ }
53983
54470
  };
53984
54471
  /**
53985
54472
  * `fileFor`'s vocabulary, in the one a clip EXPORT answers on.
@@ -54006,19 +54493,84 @@ function createClipService(deps) {
54006
54493
  * about which clip a key means. Its whole job is to turn `fileFor`'s answer
54007
54494
  * into the still vocabulary, and to cut one frame when there is a file.
54008
54495
  */
54496
+ /**
54497
+ * One clip's STILL, at the cheapest source that can give one.
54498
+ *
54499
+ * **Held bytes first, and they are free.** A clip the operator has played or
54500
+ * exported is already on this disk: one frame of local decode, no network.
54501
+ *
54502
+ * **Otherwise the camera's FIRST frame, for ~0.5 s of its playback slot.**
54503
+ * The clip is never FETCHED for a still — that was shipped once and cost
54504
+ * 898 s of camera time to fill one 20-row screen. A first-frame mint holds
54505
+ * the slot for 433–528 ms whatever the clip's length, and it is speculative:
54506
+ * the lane evicts it the moment an operator taps anything (`yielded`), and
54507
+ * an eviction or a busy slot is DEFERRED, because half a second that lost a
54508
+ * race is worth coming back for where twenty seconds was not.
54509
+ *
54510
+ * The midpoint the operator asked for is not reachable: a narrowed
54511
+ * `ContentMgmt/search` window is accepted with 200 and silently served from
54512
+ * the segment head (`clip-first-frame.ts` has the measurement).
54513
+ */
54009
54514
  const mintStill = async (deviceId, clipKey) => {
54010
- const file = await fileFor(deviceId, clipKey, "still");
54011
- if (file.kind === "refused") {
54012
- if (file.code === "replay-busy") return deferStill("queue-full", file.detail, REPLAY_LANE_WAIT_MS);
54013
- if (file.code === "unknown-device") return refuseStill("unknown-device", file.detail);
54014
- if (file.code === "no-catalog-row") return refuseStill("no-catalog-row", file.detail);
54015
- return refuseStill("camera-refused", file.detail);
54515
+ const camera = await deps.resolveCamera(deviceId);
54516
+ if (camera === null) return refuseStill("unknown-device", `device ${String(deviceId)} is not a Hikvision camera`);
54517
+ const row = rowsByKey.get(rowKey(deviceId, clipKey));
54518
+ if (row === void 0) return refuseStill("no-catalog-row", "no-catalog-row: list the window that holds this clip first");
54519
+ const held = await store.pathIfPresent(deviceId, clipKey);
54520
+ if (held !== null) return await cutHeldStill(deviceId, clipKey, held, null);
54521
+ const evict = new AbortController();
54522
+ const lease = await lane.acquire(deviceId, "still", () => evict.abort());
54523
+ if (lease.kind === "busy") return deferStill("queue-full", lease.detail, REPLAY_LANE_WAIT_MS);
54524
+ let frame;
54525
+ try {
54526
+ frame = await fetchFirstFrame({
54527
+ camera: cameraFor(camera),
54528
+ row
54529
+ }, {
54530
+ logger,
54531
+ signal: evict.signal,
54532
+ ...deps.openReplay !== void 0 ? { openReplay: deps.openReplay } : {}
54533
+ });
54534
+ } finally {
54535
+ lease.release();
54536
+ }
54537
+ if (frame.kind === "refused") {
54538
+ if (frame.code === "yielded") return deferStill("queue-full", frame.detail, REPLAY_LANE_WAIT_MS);
54539
+ return refuseStill("camera-refused", frame.detail);
54016
54540
  }
54541
+ const cut = await cutStillFromAccessUnits(frame.units, frame.codec, {
54542
+ logger,
54543
+ ...deps.ffmpegBinaryPath !== void 0 ? { ffmpegBinaryPath: deps.ffmpegBinaryPath } : {},
54544
+ ...deps.spawnStill !== void 0 ? { spawnStill: deps.spawnStill } : {}
54545
+ });
54546
+ if (cut.kind === "refused") return refuseStill(cut.code, cut.detail);
54547
+ await thumbs.put(deviceId, clipKey, cut.bytes);
54548
+ logger.debug("videoclips: a clip still was minted from the camera’s first frame", {
54549
+ tags: { deviceId },
54550
+ meta: {
54551
+ clipKey,
54552
+ bytes: cut.bytes.byteLength,
54553
+ slotMs: frame.slotMs
54554
+ }
54555
+ });
54556
+ return {
54557
+ ok: true,
54558
+ bytes: cut.bytes
54559
+ };
54560
+ };
54561
+ /**
54562
+ * The cut itself, over bytes already on this disk. Touches no camera.
54563
+ *
54564
+ * `measuredMs` is the span the fetch really delivered when one has just run;
54565
+ * `null` falls back to the catalog row, which is the number the operator was
54566
+ * already shown. Zero is refused rather than seeked to (D393/D382).
54567
+ */
54568
+ const cutHeldStill = async (deviceId, clipKey, path, measuredMs) => {
54017
54569
  const row = rowsByKey.get(rowKey(deviceId, clipKey));
54018
- const durationMs = file.durationMs ?? (row === void 0 ? 0 : row.endMs - row.startMs);
54570
+ const durationMs = measuredMs ?? (row === void 0 ? 0 : row.endMs - row.startMs);
54019
54571
  if (durationMs <= 0) return refuseStill("no-keyframe", "this clip has no length to take a midpoint of — nothing measured it and its catalog row spans nothing");
54020
54572
  const cut = await cutClipStill({
54021
- path: file.path,
54573
+ path,
54022
54574
  durationMs
54023
54575
  }, {
54024
54576
  logger,
@@ -54033,7 +54585,7 @@ function createClipService(deps) {
54033
54585
  clipKey,
54034
54586
  bytes: cut.bytes.byteLength,
54035
54587
  durationMs,
54036
- measured: file.durationMs !== null
54588
+ measured: measuredMs !== null
54037
54589
  }
54038
54590
  });
54039
54591
  return {