@camstack/addon-provider-reolink 1.2.260 → 1.2.261

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/addon.js CHANGED
@@ -29165,7 +29165,7 @@ var require_lz4 = /* @__PURE__ */ require_chunk.__commonJSMin(((exports) => {
29165
29165
  };
29166
29166
  }));
29167
29167
  //#endregion
29168
- //#region node_modules/@apocaliss92/nodelink-js/dist/chunk-2XVZ5ZZL.js
29168
+ //#region node_modules/@apocaliss92/nodelink-js/dist/chunk-MC2CLGY2.js
29169
29169
  var import_fxp = require_fxp();
29170
29170
  var import_lz4 = /* @__PURE__ */ require_chunk.__toESM(require_lz4(), 1);
29171
29171
  function bcHeaderLen(messageClass, buf, bodyLen) {
@@ -29998,6 +29998,21 @@ var BcUdpStream = class extends events.EventEmitter {
29998
29998
  lastAcceptAtMs;
29999
29999
  ackScheduled = false;
30000
30000
  ackLatency = new AckLatency();
30001
+ /** When the data phase started (timers armed); the session's age base. */
30002
+ connectedAtMs;
30003
+ /** Last datagram of any kind received from the camera. */
30004
+ lastRxAtMs;
30005
+ /** Last DATA packet received from the camera, and its packet id. */
30006
+ lastDataRxAtMs;
30007
+ lastDataRxPacketId;
30008
+ /** Last ACK from the camera (acknowledging OUR packets), and its id. */
30009
+ lastAckRxAtMs;
30010
+ lastAckRxPacketId;
30011
+ /** Set when the camera sent D2C_DISC (it, not us, ended the session). */
30012
+ discFromCameraAtMs;
30013
+ /** One log per stall; re-armed when the stalled condition clears. */
30014
+ ackWindowStallLogged = false;
30015
+ rxSilenceStallLogged = false;
30001
30016
  lastAckPacket = Buffer.alloc(0);
30002
30017
  ackSentCount = 0;
30003
30018
  pendingData = [];
@@ -30787,6 +30802,9 @@ var BcUdpStream = class extends events.EventEmitter {
30787
30802
  }
30788
30803
  startTimers() {
30789
30804
  if (!this.sock || !this.remote || this.clientId == null || this.cameraId == null) throw new Error("BCUDP not ready");
30805
+ this.connectedAtMs = Date.now();
30806
+ this.ackWindowStallLogged = false;
30807
+ this.rxSilenceStallLogged = false;
30790
30808
  this.updateAckPacket();
30791
30809
  this.sendHeartbeat();
30792
30810
  this.ackTimer = (0, timers.setInterval)(() => {
@@ -30799,6 +30817,7 @@ var BcUdpStream = class extends events.EventEmitter {
30799
30817
  this.resendTimer = (0, timers.setInterval)(() => {
30800
30818
  try {
30801
30819
  this.resendOutstanding();
30820
+ this.checkStalls(Date.now());
30802
30821
  } catch (e) {
30803
30822
  this.emit("error", e instanceof Error ? e : new Error(String(e)));
30804
30823
  }
@@ -30884,6 +30903,49 @@ var BcUdpStream = class extends events.EventEmitter {
30884
30903
  this.emit("debug", "ack_scheduled", { reason });
30885
30904
  }
30886
30905
  }
30906
+ /**
30907
+ * Snapshot of the session's health, for the disconnect log of the owner.
30908
+ * Packet ids are the camera's (rx) and ours acknowledged by the camera (ack).
30909
+ */
30910
+ getSessionDiagnostics(now = Date.now()) {
30911
+ let oldestUnackedAgeMs;
30912
+ for (const entry of this.sent.values()) {
30913
+ const age = now - entry.ts;
30914
+ if (oldestUnackedAgeMs === void 0 || age > oldestUnackedAgeMs) oldestUnackedAgeMs = age;
30915
+ }
30916
+ return {
30917
+ sessionAgeMs: this.connectedAtMs !== void 0 ? now - this.connectedAtMs : void 0,
30918
+ lastRxAgoMs: this.lastRxAtMs !== void 0 ? now - this.lastRxAtMs : void 0,
30919
+ lastDataRxPacketId: this.lastDataRxPacketId,
30920
+ lastDataRxAgoMs: this.lastDataRxAtMs !== void 0 ? now - this.lastDataRxAtMs : void 0,
30921
+ lastAckRxPacketId: this.lastAckRxPacketId,
30922
+ lastAckRxAgoMs: this.lastAckRxAtMs !== void 0 ? now - this.lastAckRxAtMs : void 0,
30923
+ unackedPackets: this.sent.size,
30924
+ ...oldestUnackedAgeMs !== void 0 ? { oldestUnackedAgeMs } : {},
30925
+ discFromCamera: this.discFromCameraAtMs !== void 0
30926
+ };
30927
+ }
30928
+ /**
30929
+ * Logs (once per stall) when the camera stops acknowledging our packets or
30930
+ * stops sending anything at all, with the session's age. Runs on the 500 ms
30931
+ * resend tick; purely diagnostic, it never closes the session.
30932
+ */
30933
+ checkStalls(now) {
30934
+ const age = this.connectedAtMs !== void 0 ? now - this.connectedAtMs : void 0;
30935
+ const diag = this.getSessionDiagnostics(now);
30936
+ const ackStalled = diag.oldestUnackedAgeMs !== void 0 && diag.oldestUnackedAgeMs >= 5e3;
30937
+ if (ackStalled && !this.ackWindowStallLogged) {
30938
+ this.ackWindowStallLogged = true;
30939
+ this.discoveryLogger?.warn?.(`[BcUdpStream] ack window stalled: ${diag.unackedPackets} packet(s) unacked, oldest ${diag.oldestUnackedAgeMs}ms, lastAckRxPacketId=${diag.lastAckRxPacketId ?? "none"} sessionAgeMs=${age}`);
30940
+ this.emit("debug", "ack_window_stall", { ...diag });
30941
+ } else if (!ackStalled) this.ackWindowStallLogged = false;
30942
+ const rxSilent = ackStalled && diag.lastRxAgoMs !== void 0 && diag.lastRxAgoMs >= 5e3;
30943
+ if (rxSilent && !this.rxSilenceStallLogged) {
30944
+ this.rxSilenceStallLogged = true;
30945
+ this.discoveryLogger?.warn?.(`[BcUdpStream] camera silent while requests are outstanding: nothing received for ${diag.lastRxAgoMs}ms lastDataRxPacketId=${diag.lastDataRxPacketId ?? "none"} lastAckRxPacketId=${diag.lastAckRxPacketId ?? "none"} sessionAgeMs=${age}`);
30946
+ this.emit("debug", "rx_silence_stall", { ...diag });
30947
+ } else if (!rxSilent) this.rxSilenceStallLogged = false;
30948
+ }
30887
30949
  resendOutstanding() {
30888
30950
  if (!this.sock || !this.remote) return;
30889
30951
  for (const [, entry] of this.sent) this.sock.send(entry.buf, this.remote.port, this.remote.host);
@@ -30939,9 +31001,12 @@ var BcUdpStream = class extends events.EventEmitter {
30939
31001
  }
30940
31002
  };
30941
31003
  if (!this.remote) updateRemote("first_packet");
31004
+ this.lastRxAtMs = Date.now();
30942
31005
  if (p.kind === "ack") {
30943
31006
  if (this.clientId != null && p.connectionId === this.clientId) {
30944
31007
  updateRemote("ack");
31008
+ this.lastAckRxAtMs = Date.now();
31009
+ this.lastAckRxPacketId = p.packetId;
30945
31010
  this.handleAckFromCamera(p.packetId, p.payload);
30946
31011
  }
30947
31012
  return;
@@ -30949,6 +31014,8 @@ var BcUdpStream = class extends events.EventEmitter {
30949
31014
  if (p.kind === "data") {
30950
31015
  if (this.clientId != null && p.connectionId === this.clientId) {
30951
31016
  updateRemote("data");
31017
+ this.lastDataRxAtMs = Date.now();
31018
+ this.lastDataRxPacketId = p.packetId;
30952
31019
  if (p.packetId >= this.packetsWant) {
30953
31020
  this.received.set(p.packetId, p.payload);
30954
31021
  this.flushReceived();
@@ -31040,6 +31107,7 @@ var BcUdpStream = class extends events.EventEmitter {
31040
31107
  rhost,
31041
31108
  rport
31042
31109
  });
31110
+ this.discFromCameraAtMs = Date.now();
31043
31111
  this.emit("error", /* @__PURE__ */ new Error(`BCUDP disconnected by camera (D2C_DISC${this.sid != null ? ` sid=${this.sid}` : ""})`));
31044
31112
  this.close();
31045
31113
  return;
@@ -31253,6 +31321,20 @@ var BaichuanClient = class _BaichuanClient extends events.EventEmitter {
31253
31321
  msgNum = 0;
31254
31322
  loggedIn = false;
31255
31323
  subscribed = false;
31324
+ /**
31325
+ * Consecutive request timeouts with no received frame in between, after
31326
+ * which the session is declared stalled (`sessionStalled`). 3 because one
31327
+ * timeout is a lost packet or a slow command, two happen on a lossy radio
31328
+ * link, but three with total receive silence (see
31329
+ * {@link BaichuanClient.SESSION_STALL_MIN_SILENCE_MS}) is a dead session.
31330
+ */
31331
+ static SESSION_STALL_TIMEOUTS = 3;
31332
+ /** Receive silence required on top of the timeout count (ignored-command guard). */
31333
+ static SESSION_STALL_MIN_SILENCE_MS = 2e4;
31334
+ consecutiveRequestTimeouts = 0;
31335
+ sessionStalledEmitted = false;
31336
+ /** When the current socket session was opened (age base for diagnostics). */
31337
+ sessionStartedAtMs;
31256
31338
  keepAliveTimer;
31257
31339
  keepAlivePingInFlight = false;
31258
31340
  consecutiveKeepalivePingFailures = 0;
@@ -31325,6 +31407,68 @@ var BaichuanClient = class _BaichuanClient extends events.EventEmitter {
31325
31407
  newSocketSessionId(transport) {
31326
31408
  return `${transport}-${(0, crypto$1.randomUUID)().split("-")[0] ?? (0, crypto$1.randomUUID)().slice(0, 8)}`;
31327
31409
  }
31410
+ /**
31411
+ * Re-emit a socket error to consumers. EventEmitter throws when an `error`
31412
+ * event has no listener, and the constructor's safety listener is gone once
31413
+ * a caller runs `removeAllListeners()` on a client it is discarding. A late
31414
+ * reset on that discarded socket must stay a log line, never a thrown
31415
+ * exception out of the socket's event handler.
31416
+ */
31417
+ emitSocketError(err) {
31418
+ if (this.listenerCount("error") === 0) {
31419
+ this.logFixed("error_no_listener", {
31420
+ message: err?.message ?? String(err),
31421
+ code: err?.code
31422
+ });
31423
+ return;
31424
+ }
31425
+ this.emit("error", err);
31426
+ }
31427
+ /**
31428
+ * Fields appended to the `disconnected` line so a session that dies on a
31429
+ * schedule (e.g. every ~30 min) can be told apart from a camera that ends it
31430
+ * (`discFromCamera=true`) and from silent loss (`lastRxAgoMs` large).
31431
+ */
31432
+ describeSessionForDisconnect(udp) {
31433
+ const now = Date.now();
31434
+ const parts = [];
31435
+ const age = this.sessionStartedAtMs !== void 0 ? now - this.sessionStartedAtMs : udp?.sessionAgeMs;
31436
+ if (age !== void 0) parts.push(`sessionAgeMs=${age}`);
31437
+ if (this.lastRxAtMs) parts.push(`lastRxAgoMs=${now - this.lastRxAtMs}`);
31438
+ if (udp) {
31439
+ parts.push(`lastRxPktId=${udp.lastDataRxPacketId ?? "none"}`);
31440
+ parts.push(`lastAckPktId=${udp.lastAckRxPacketId ?? "none"}`);
31441
+ parts.push(`unackedPkts=${udp.unackedPackets}`);
31442
+ parts.push(`discFromCamera=${udp.discFromCamera}`);
31443
+ }
31444
+ if (this.consecutiveRequestTimeouts > 0) parts.push(`consecutiveTimeouts=${this.consecutiveRequestTimeouts}`);
31445
+ return parts;
31446
+ }
31447
+ resetStallTracking() {
31448
+ this.consecutiveRequestTimeouts = 0;
31449
+ this.sessionStalledEmitted = false;
31450
+ }
31451
+ /**
31452
+ * Called by every request path when its reply did not arrive in time.
31453
+ * Emits `sessionStalled` once per session when the run of timeouts is long
31454
+ * enough AND the session has received nothing for a while.
31455
+ */
31456
+ noteRequestTimeout() {
31457
+ this.consecutiveRequestTimeouts++;
31458
+ if (this.sessionStalledEmitted) return;
31459
+ if (this.consecutiveRequestTimeouts < _BaichuanClient.SESSION_STALL_TIMEOUTS) return;
31460
+ const now = Date.now();
31461
+ const lastRxAgo = this.lastRxAtMs ? now - this.lastRxAtMs : void 0;
31462
+ if (lastRxAgo !== void 0 && lastRxAgo < _BaichuanClient.SESSION_STALL_MIN_SILENCE_MS) return;
31463
+ this.sessionStalledEmitted = true;
31464
+ this.emit("sessionStalled", {
31465
+ consecutiveTimeouts: this.consecutiveRequestTimeouts,
31466
+ sessionAgeMs: this.sessionStartedAtMs !== void 0 ? now - this.sessionStartedAtMs : void 0,
31467
+ lastRxAgoMs: lastRxAgo,
31468
+ lastRxCmdId: this.lastRxInfo?.cmdId,
31469
+ transport: this.transport
31470
+ });
31471
+ }
31328
31472
  logFixed(event, data) {
31329
31473
  const msg = `[BaichuanClient] ${event}`;
31330
31474
  const l = this.logger;
@@ -31941,6 +32085,8 @@ var BaichuanClient = class _BaichuanClient extends events.EventEmitter {
31941
32085
  this.socketClosed = false;
31942
32086
  this.consecutiveKeepalivePingFailures = 0;
31943
32087
  this.socketSessionId = this.newSocketSessionId("tcp");
32088
+ this.sessionStartedAtMs = Date.now();
32089
+ this.resetStallTracking();
31944
32090
  try {
31945
32091
  sock.setKeepAlive(true, 3e4);
31946
32092
  } catch (e) {
@@ -31975,6 +32121,7 @@ var BaichuanClient = class _BaichuanClient extends events.EventEmitter {
31975
32121
  if (tcpPort != null) tcpDisconnectParts.push(`port=${tcpPort}`);
31976
32122
  if (this.lastRxInfo?.cmdId != null) tcpDisconnectParts.push(`lastRxCmdId=${this.lastRxInfo.cmdId}`);
31977
32123
  if (this.lastTxInfo?.cmdId != null) tcpDisconnectParts.push(`lastTxCmdId=${this.lastTxInfo.cmdId}`);
32124
+ tcpDisconnectParts.push(...this.describeSessionForDisconnect(void 0));
31978
32125
  this.logFixed("disconnected", tcpDisconnectParts.join(" "));
31979
32126
  this.socketSessionId = void 0;
31980
32127
  this.loggedIn = false;
@@ -31995,7 +32142,7 @@ var BaichuanClient = class _BaichuanClient extends events.EventEmitter {
31995
32142
  message: err?.message ?? String(err),
31996
32143
  code
31997
32144
  } });
31998
- this.emit("error", err);
32145
+ this.emitSocketError(err);
31999
32146
  });
32000
32147
  await new Promise((resolve, reject) => {
32001
32148
  let settled = false;
@@ -32064,6 +32211,8 @@ var BaichuanClient = class _BaichuanClient extends events.EventEmitter {
32064
32211
  this.transport = "udp";
32065
32212
  this.socketClosed = false;
32066
32213
  this.socketSessionId = this.newSocketSessionId("udp");
32214
+ this.sessionStartedAtMs = Date.now();
32215
+ this.resetStallTracking();
32067
32216
  sock.on("data", (chunk) => {
32068
32217
  const frames = this.parser.push(chunk);
32069
32218
  for (const f of frames) this.handleFrame(f);
@@ -32071,6 +32220,7 @@ var BaichuanClient = class _BaichuanClient extends events.EventEmitter {
32071
32220
  sock.on("close", () => {
32072
32221
  this.logSocketState("udp_close_event", { udpConnected: sock.isConnected?.() });
32073
32222
  const sid2 = this.socketSessionId;
32223
+ const udpDiag = sock.getSessionDiagnostics?.();
32074
32224
  if (sock === this.udpSocket) this.udpSocket = void 0;
32075
32225
  if (sock.removeAllListeners) sock.removeAllListeners();
32076
32226
  this.stopKeepAlive();
@@ -32094,6 +32244,7 @@ var BaichuanClient = class _BaichuanClient extends events.EventEmitter {
32094
32244
  }
32095
32245
  if (this.lastRxInfo?.cmdId != null) udpDisconnectParts.push(`lastRxCmdId=${this.lastRxInfo.cmdId}`);
32096
32246
  if (this.lastTxInfo?.cmdId != null) udpDisconnectParts.push(`lastTxCmdId=${this.lastTxInfo.cmdId}`);
32247
+ udpDisconnectParts.push(...this.describeSessionForDisconnect(udpDiag));
32097
32248
  this.logFixed("disconnected", udpDisconnectParts.join(" "));
32098
32249
  this.socketSessionId = void 0;
32099
32250
  this.loggedIn = false;
@@ -32303,6 +32454,7 @@ var BaichuanClient = class _BaichuanClient extends events.EventEmitter {
32303
32454
  handleFrame(frame) {
32304
32455
  const now = Date.now();
32305
32456
  this.lastRxAtMs = now;
32457
+ this.consecutiveRequestTimeouts = 0;
32306
32458
  this.lastRxInfo = {
32307
32459
  atMs: now,
32308
32460
  cmdId: frame.header.cmdId,
@@ -32961,6 +33113,7 @@ var BaichuanClient = class _BaichuanClient extends events.EventEmitter {
32961
33113
  const framePromise = new Promise((resolve, reject) => {
32962
33114
  const t = setTimeout(() => {
32963
33115
  this.pending.delete(pendingKey);
33116
+ this.noteRequestTimeout();
32964
33117
  reject(/* @__PURE__ */ new Error(`Baichuan timeout cmdId=${cmdId} msgNum=${msgNum}`));
32965
33118
  }, remainingMs);
32966
33119
  this.pending.set(pendingKey, {
@@ -33048,6 +33201,7 @@ var BaichuanClient = class _BaichuanClient extends events.EventEmitter {
33048
33201
  const framePromise = new Promise((resolve, reject) => {
33049
33202
  const t = setTimeout(() => {
33050
33203
  this.pending.delete(pendingKey);
33204
+ this.noteRequestTimeout();
33051
33205
  reject(/* @__PURE__ */ new Error(`Baichuan timeout cmdId=${cmdId} msgNum=${msgNum}`));
33052
33206
  }, remainingMs);
33053
33207
  this.pending.set(pendingKey, {
@@ -33143,6 +33297,7 @@ var BaichuanClient = class _BaichuanClient extends events.EventEmitter {
33143
33297
  const framePromise = new Promise((resolve, reject) => {
33144
33298
  const t = setTimeout(() => {
33145
33299
  this.pending.delete(pendingKey);
33300
+ this.noteRequestTimeout();
33146
33301
  reject(/* @__PURE__ */ new Error(`Baichuan timeout cmdId=${cmdId} msgNum=${msgNum}`));
33147
33302
  }, timeoutMs);
33148
33303
  this.pending.set(pendingKey, {
@@ -34414,13 +34569,13 @@ var ContinuousVideoStream = class extends events.EventEmitter {
34414
34569
  this.starting = true;
34415
34570
  try {
34416
34571
  this.stopIdleLoop();
34417
- const stream$8 = await this.opts.createLiveStream();
34418
- this.live = stream$8;
34419
- stream$8.on("videoAccessUnit", this.onLiveAccessUnit);
34420
- stream$8.on("additionalHeader", this.onAdditionalHeader);
34421
- stream$8.on("audioFrame", this.onAudioFrame);
34422
- stream$8.on("error", this.onLiveError);
34423
- await stream$8.start().catch((e) => this.emit("error", e));
34572
+ const stream$11 = await this.opts.createLiveStream();
34573
+ this.live = stream$11;
34574
+ stream$11.on("videoAccessUnit", this.onLiveAccessUnit);
34575
+ stream$11.on("additionalHeader", this.onAdditionalHeader);
34576
+ stream$11.on("audioFrame", this.onAudioFrame);
34577
+ stream$11.on("error", this.onLiveError);
34578
+ await stream$11.start().catch((e) => this.emit("error", e));
34424
34579
  } finally {
34425
34580
  this.starting = false;
34426
34581
  }
@@ -34809,12 +34964,12 @@ async function resolveProfileStreamMetadata(cached, profile, fetchMetadata, hook
34809
34964
  cacheable: false
34810
34965
  };
34811
34966
  try {
34812
- const stream$9 = (await fetchMetadata()).streams.find((s) => s.profile === profile);
34813
- if (stream$9) {
34967
+ const stream$12 = (await fetchMetadata()).streams.find((s) => s.profile === profile);
34968
+ if (stream$12) {
34814
34969
  const metadata = {
34815
- frameRate: stream$9.frameRate || FALLBACK_FRAME_RATE,
34816
- ...stream$9.width === void 0 ? {} : { width: stream$9.width },
34817
- ...stream$9.height === void 0 ? {} : { height: stream$9.height }
34970
+ frameRate: stream$12.frameRate || FALLBACK_FRAME_RATE,
34971
+ ...stream$12.width === void 0 ? {} : { width: stream$12.width },
34972
+ ...stream$12.height === void 0 ? {} : { height: stream$12.height }
34818
34973
  };
34819
34974
  hooks?.onDebug?.(`Fetched metadata for profile ${profile}: ${metadata.frameRate} fps`);
34820
34975
  return {
@@ -35228,14 +35383,14 @@ var BaichuanRtspServer = class _BaichuanRtspServer extends events.EventEmitter {
35228
35383
  if (this.active) throw new Error("RTSP server is already active");
35229
35384
  if (this.lazyMetadata) this.logger.info(`[BaichuanRtspServer] lazy metadata: skipping initial getStreamMetadata; will fetch on first DESCRIBE`);
35230
35385
  else try {
35231
- const stream$10 = (await this.api.getStreamMetadata(this.channel)).streams.find((s) => s.profile === this.profile);
35232
- if (stream$10) {
35386
+ const stream$13 = (await this.api.getStreamMetadata(this.channel)).streams.find((s) => s.profile === this.profile);
35387
+ if (stream$13) {
35233
35388
  this.streamMetadata = {
35234
- frameRate: stream$10.frameRate || 25,
35235
- width: stream$10.width,
35236
- height: stream$10.height
35389
+ frameRate: stream$13.frameRate || 25,
35390
+ width: stream$13.width,
35391
+ height: stream$13.height
35237
35392
  };
35238
- const enc = String(stream$10.videoEncType ?? "").trim().toLowerCase();
35393
+ const enc = String(stream$13.videoEncType ?? "").trim().toLowerCase();
35239
35394
  const metaVideoType = enc.includes("265") || enc.includes("hevc") ? "H265" : "H264";
35240
35395
  this.setFlowVideoType(metaVideoType, "metadata");
35241
35396
  }
@@ -39889,7 +40044,7 @@ function buildEncOptions(list, channel) {
39889
40044
  }
39890
40045
  function aggregateByType(list, type) {
39891
40046
  const seen = /* @__PURE__ */ new Map();
39892
- for (const stream$11 of list.streams) for (const eb of stream$11.encodeTables) {
40047
+ for (const stream$14 of list.streams) for (const eb of stream$14.encodeTables) {
39893
40048
  if (eb.type !== type) continue;
39894
40049
  const mapped = mapEncodeTable(eb);
39895
40050
  if (!mapped) continue;
@@ -41166,6 +41321,124 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
41166
41321
  }
41167
41322
  }
41168
41323
  /**
41324
+ * Consumer decision on recycling a stalled general session. `true` asserts
41325
+ * the camera is awake and always on (a recycle logs in, which wakes a
41326
+ * sleeper); `false` forbids it. Without a guard only a camera KNOWN to be
41327
+ * awake, or one with no battery signal at all (wired TCP), is recycled.
41328
+ */
41329
+ generalRecycleGuard;
41330
+ /** `false` disables recycling entirely (default: enabled). */
41331
+ generalRecycleEnabled = true;
41332
+ generalRecycling = false;
41333
+ /** Minimum time between two recycles: a camera that logs in but never answers must not loop. */
41334
+ generalRecycleMinIntervalMs = 5 * 6e4;
41335
+ /** Recycles allowed in any rolling hour. */
41336
+ generalRecycleMaxPerHour = 6;
41337
+ generalRecycleAtMs = [];
41338
+ /**
41339
+ * Configure recycling of a general session that stays silently dead.
41340
+ *
41341
+ * Without a `guard`, a camera is recycled only when known awake, or when it
41342
+ * shows no battery signal. That signal is a received battery push or a BCUDP
41343
+ * transport, so a TCP battery camera that has not pushed battery info yet
41344
+ * looks wired and CAN be woken by the login. Consumers that know battery
41345
+ * status should pass a `guard` (`true` = always on, `false` = never).
41346
+ */
41347
+ setGeneralSessionRecycling(opts) {
41348
+ if (opts.enabled !== void 0) this.generalRecycleEnabled = opts.enabled;
41349
+ if ("guard" in opts) this.generalRecycleGuard = opts.guard;
41350
+ if (opts.minIntervalMs !== void 0) this.generalRecycleMinIntervalMs = Math.max(0, opts.minIntervalMs);
41351
+ if (opts.maxPerHour !== void 0) this.generalRecycleMaxPerHour = Math.max(0, opts.maxPerHour);
41352
+ }
41353
+ /**
41354
+ * Whether a recycle may log in without waking a sleeping camera. The sleep
41355
+ * state is only known once inference ran (UDP) or a probe answered, so an
41356
+ * unknown state on a camera that may be battery-powered is a refusal.
41357
+ */
41358
+ generalRecycleSleepVerdict() {
41359
+ if (this.generalRecycleGuard) {
41360
+ let v = false;
41361
+ try {
41362
+ v = this.generalRecycleGuard();
41363
+ } catch {
41364
+ v = false;
41365
+ }
41366
+ return {
41367
+ ok: v,
41368
+ why: v ? "guard allows" : "consumer guard refuses"
41369
+ };
41370
+ }
41371
+ const states = Array.from(this.udpLastInferredSleepStateByChannel.values());
41372
+ if (states.includes("sleeping")) return {
41373
+ ok: false,
41374
+ why: "camera is asleep"
41375
+ };
41376
+ const probe = this.lastSleepProbe;
41377
+ if (probe && Date.now() - probe.atMs < 12e4) {
41378
+ if (probe.status.state === "sleeping") return {
41379
+ ok: false,
41380
+ why: "camera is asleep"
41381
+ };
41382
+ if (probe.status.state === "awake") return {
41383
+ ok: true,
41384
+ why: "awake"
41385
+ };
41386
+ }
41387
+ if (states.length > 0 && states.every((x) => x === "awake")) return {
41388
+ ok: true,
41389
+ why: "awake"
41390
+ };
41391
+ if (this.lastBatteryPushKey.size > 0 || this.client?.getTransport?.() === "udp") return {
41392
+ ok: false,
41393
+ why: "sleep state unknown on a camera that may be battery-powered"
41394
+ };
41395
+ return {
41396
+ ok: true,
41397
+ why: "no battery signal"
41398
+ };
41399
+ }
41400
+ /**
41401
+ * Tear down a general session the client declared stalled and open a new one.
41402
+ * `client` is the one that raised the event: a late event from an already
41403
+ * replaced client is ignored.
41404
+ */
41405
+ async recycleStalledGeneralSession(client, info) {
41406
+ if (this._closed || !this.generalRecycleEnabled || this.generalRecycling) return;
41407
+ if (this.socketPool.get("general")?.client !== client) return;
41408
+ const verdict2 = this.generalRecycleSleepVerdict();
41409
+ if (!verdict2.ok) {
41410
+ this.logger.warn?.(`[ReolinkBaichuanApi] general session stalled (${info.consecutiveTimeouts} consecutive timeouts, age=${info.sessionAgeMs}ms) but not recycled: ${verdict2.why}`);
41411
+ return;
41412
+ }
41413
+ const now = Date.now();
41414
+ while (this.generalRecycleAtMs.length > 0 && now - this.generalRecycleAtMs[0] >= 36e5) this.generalRecycleAtMs.shift();
41415
+ const last = this.generalRecycleAtMs[this.generalRecycleAtMs.length - 1];
41416
+ if (last !== void 0 && now - last < this.generalRecycleMinIntervalMs) {
41417
+ this.logger.warn?.(`[ReolinkBaichuanApi] general session stalled again ${now - last}ms after the last recycle; not recycling before ${this.generalRecycleMinIntervalMs}ms`);
41418
+ return;
41419
+ }
41420
+ if (this.generalRecycleAtMs.length >= this.generalRecycleMaxPerHour) {
41421
+ this.logger.warn?.(`[ReolinkBaichuanApi] general session recycle bound hit (${this.generalRecycleAtMs.length} in the last hour); giving up on recycling until it clears`);
41422
+ return;
41423
+ }
41424
+ this.generalRecycleAtMs.push(now);
41425
+ this.generalRecycling = true;
41426
+ try {
41427
+ this.logger.warn?.(`[ReolinkBaichuanApi] recycling general session: ${info.consecutiveTimeouts} consecutive command timeouts, nothing received for ${info.lastRxAgoMs ?? "?"}ms, session age=${info.sessionAgeMs ?? "?"}ms`);
41428
+ if (!this._ensureConnectedPromise) this._ensureConnectedPromise = this.reconnectGeneralSocket();
41429
+ try {
41430
+ await this._ensureConnectedPromise;
41431
+ } finally {
41432
+ this._ensureConnectedPromise = void 0;
41433
+ }
41434
+ this.logger.warn?.(`[ReolinkBaichuanApi] general session recycled (previous age=${info.sessionAgeMs ?? "?"}ms)`);
41435
+ } catch (e) {
41436
+ this.logger.warn?.(`[ReolinkBaichuanApi] recycling the general session failed: ${e instanceof Error ? e.message : String(e)}`);
41437
+ } finally {
41438
+ this.generalRecycling = false;
41439
+ }
41440
+ }
41441
+ /**
41169
41442
  * Internal: destroy the current general socket (if any), create a new one,
41170
41443
  * login, and re-attach all listeners.
41171
41444
  */
@@ -41173,6 +41446,12 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
41173
41446
  const oldEntry = this.socketPool.get("general");
41174
41447
  if (oldEntry) {
41175
41448
  oldEntry.client.removeAllListeners();
41449
+ oldEntry.client.on("error", (err) => {
41450
+ (this.logger.debug ?? this.logger.log)?.call(this.logger, "general socket (discarded) late error", {
41451
+ message: err?.message ?? String(err),
41452
+ code: err?.code
41453
+ });
41454
+ });
41176
41455
  if (oldEntry.idleCloseTimer) clearTimeout(oldEntry.idleCloseTimer);
41177
41456
  if (oldEntry.generalPermitRelease) try {
41178
41457
  oldEntry.generalPermitRelease();
@@ -41233,6 +41512,9 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
41233
41512
  this.logger?.debug?.(`[ReolinkBaichuanApi] general error handler threw: ${e}`);
41234
41513
  }
41235
41514
  });
41515
+ client.on("sessionStalled", (info) => {
41516
+ this.recycleStalledGeneralSession(client, info);
41517
+ });
41236
41518
  client.on("event", (event) => {
41237
41519
  const mapped = mapToSimpleEvent(event);
41238
41520
  if (!mapped) return;
@@ -41881,6 +42163,8 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
41881
42163
  resolveSocketTag(sessionKey) {
41882
42164
  const replayMatch = sessionKey.match(/^replay:([^:]+)(?::ch(\d+))?/);
41883
42165
  if (replayMatch) return `replay:${replayMatch[1]}:ch${replayMatch[2] ?? "0"}`;
42166
+ const renewMatch = sessionKey.match(/^(.*)#renew(\d+)$/);
42167
+ if (renewMatch && renewMatch[1]) return `${this.resolveSocketTag(renewMatch[1])}:renew${renewMatch[2]}`;
41884
42168
  const liveMatch = sessionKey.match(/^live:[^:]+:ch(\d+):(\w+)$/);
41885
42169
  if (liveMatch && liveMatch[1] && liveMatch[2]) {
41886
42170
  const channel = parseInt(liveMatch[1], 10);
@@ -42189,8 +42473,27 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
42189
42473
  */
42190
42474
  async createDedicatedSession(sessionKey, logger) {
42191
42475
  const tag2 = this.resolveSocketTag(sessionKey);
42192
- (logger ?? this.logger)?.debug?.(`[SocketPool] createDedicatedSession sessionKey=${sessionKey} \u2192 tag=${tag2}`);
42193
- return await this.acquirePooledSocket(tag2, logger);
42476
+ const log = logger ?? this.logger;
42477
+ log?.debug?.(`[SocketPool] createDedicatedSession sessionKey=${sessionKey} \u2192 tag=${tag2}`);
42478
+ const acquired = await this.acquirePooledSocket(tag2, logger);
42479
+ const stillHoldsPooledSocket = () => this.socketPool.get(tag2)?.client === acquired.client;
42480
+ let settled = false;
42481
+ return {
42482
+ client: acquired.client,
42483
+ release: async () => {
42484
+ if (settled) return;
42485
+ settled = true;
42486
+ if (!stillHoldsPooledSocket()) return;
42487
+ await acquired.release();
42488
+ },
42489
+ invalidate: async (reason) => {
42490
+ if (settled) return;
42491
+ settled = true;
42492
+ if (!stillHoldsPooledSocket()) return;
42493
+ log?.warn?.(`[SocketPool] Discarding socket for tag=${tag2} (sessionKey=${sessionKey}): ${reason}`);
42494
+ await this.forceClosePooledSocket(tag2, logger);
42495
+ }
42496
+ };
42194
42497
  }
42195
42498
  /**
42196
42499
  * @deprecated Use forceClosePooledSocket via createDedicatedSession instead.
@@ -42854,7 +43157,7 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
42854
43157
  const { BaichuanVideoStream: BaichuanVideoStream2 } = await Promise.resolve().then(() => require("./BaichuanVideoStream-H3LAUNQR-DOjU7TyZ.js"));
42855
43158
  const sessionKey = `live:object-detections:ch${entry.channel}:${entry.profile}`;
42856
43159
  const dedicated = await this.createDedicatedSession(sessionKey);
42857
- const stream$12 = new BaichuanVideoStream2({
43160
+ const stream$15 = new BaichuanVideoStream2({
42858
43161
  client: dedicated.client,
42859
43162
  api: this,
42860
43163
  channel: entry.channel,
@@ -42863,14 +43166,14 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
42863
43166
  });
42864
43167
  this.ensureObjectDetectionInternalListener();
42865
43168
  try {
42866
- await stream$12.start();
43169
+ await stream$15.start();
42867
43170
  } catch (e) {
42868
43171
  await dedicated.release().catch(() => {});
42869
43172
  this.maybeDropObjectDetectionInternalListener();
42870
43173
  throw e;
42871
43174
  }
42872
43175
  entry.stream = {
42873
- stop: () => stream$12.stop(),
43176
+ stop: () => stream$15.stop(),
42874
43177
  release: () => dedicated.release()
42875
43178
  };
42876
43179
  this.logger.debug?.(`[ReolinkBaichuanApi] onObjectDetections: substream started (key=${sessionKey})`);
@@ -42907,7 +43210,7 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
42907
43210
  * its `additionalHeader` event. Returns a teardown function the stream calls
42908
43211
  * on stop. Not intended for direct use by consumers.
42909
43212
  */
42910
- _registerVideoStreamForDetection(stream$13, context) {
43213
+ _registerVideoStreamForDetection(stream$16, context) {
42911
43214
  const listener = (info) => {
42912
43215
  if (this.detectionEventListeners.size === 0) return;
42913
43216
  const decoded = decodeDetectionHeader(info.raw, info.frameType);
@@ -42923,12 +43226,12 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
42923
43226
  };
42924
43227
  this.dispatchDetectionEvent(event);
42925
43228
  };
42926
- stream$13.on("additionalHeader", listener);
43229
+ stream$16.on("additionalHeader", listener);
42927
43230
  const teardown = () => {
42928
- stream$13.off("additionalHeader", listener);
42929
- this.detectionEventStreamHooks.delete(stream$13);
43231
+ stream$16.off("additionalHeader", listener);
43232
+ this.detectionEventStreamHooks.delete(stream$16);
42930
43233
  };
42931
- this.detectionEventStreamHooks.set(stream$13, teardown);
43234
+ this.detectionEventStreamHooks.set(stream$16, teardown);
42932
43235
  return teardown;
42933
43236
  }
42934
43237
  dispatchDetectionEvent(evt) {
@@ -44777,7 +45080,7 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
44777
45080
  });
44778
45081
  const msgNum = 0;
44779
45082
  dedicatedClient.subscribeVideoStream(5, msgNum);
44780
- const stream$14 = new require_chunk_LXENEW4N.BaichuanVideoStream({
45083
+ const stream$17 = new require_chunk_LXENEW4N.BaichuanVideoStream({
44781
45084
  client: dedicatedClient,
44782
45085
  channel,
44783
45086
  profile: streamType === "subStream" ? "sub" : "main",
@@ -44789,7 +45092,7 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
44789
45092
  });
44790
45093
  let started = false;
44791
45094
  try {
44792
- await stream$14.start();
45095
+ await stream$17.start();
44793
45096
  const sessionCounter = dedicatedClient.reserveNextMsgNum();
44794
45097
  const frame = await dedicatedClient.sendFrame({
44795
45098
  cmdId: 5,
@@ -44805,7 +45108,7 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
44805
45108
  started = true;
44806
45109
  } catch (e) {
44807
45110
  try {
44808
- await stream$14.stop();
45111
+ await stream$17.stop();
44809
45112
  } catch {}
44810
45113
  try {
44811
45114
  dedicatedClient.unsubscribeVideoStream(5, msgNum);
@@ -44837,7 +45140,7 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
44837
45140
  try {
44838
45141
  dedicatedClient.unsubscribeVideoStream(5, msgNum);
44839
45142
  } catch {}
44840
- await stream$14.stop();
45143
+ await stream$17.stop();
44841
45144
  await releaseDedicatedClient();
44842
45145
  };
44843
45146
  const autoTeardown = (reason) => {
@@ -44845,13 +45148,13 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
44845
45148
  logger?.debug?.(`[DedicatedClient] Auto-teardown for ${sessionKey}: ${reason}`);
44846
45149
  stop();
44847
45150
  };
44848
- stream$14.once("close", () => autoTeardown("stream closed"));
44849
- stream$14.once("error", (e) => autoTeardown(`stream error: ${e?.message || e}`));
45151
+ stream$17.once("close", () => autoTeardown("stream closed"));
45152
+ stream$17.once("error", (e) => autoTeardown(`stream error: ${e?.message || e}`));
44850
45153
  dedicatedClient.once("error", (e) => autoTeardown(`client error: ${e?.message || e}`));
44851
45154
  dedicatedClient.once("close", () => autoTeardown("client closed"));
44852
45155
  return {
44853
45156
  msgNum,
44854
- stream: stream$14,
45157
+ stream: stream$17,
44855
45158
  stop
44856
45159
  };
44857
45160
  }
@@ -44886,7 +45189,7 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
44886
45189
  });
44887
45190
  const msgNum = 0;
44888
45191
  dedicatedClient.subscribeVideoStream(5, msgNum);
44889
- const stream$15 = new require_chunk_LXENEW4N.BaichuanVideoStream({
45192
+ const stream$18 = new require_chunk_LXENEW4N.BaichuanVideoStream({
44890
45193
  client: dedicatedClient,
44891
45194
  channel,
44892
45195
  profile: streamType === "subStream" ? "sub" : "main",
@@ -44898,7 +45201,7 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
44898
45201
  });
44899
45202
  let started = false;
44900
45203
  try {
44901
- await stream$15.start();
45204
+ await stream$18.start();
44902
45205
  const channelIdOverride = headerChannelIdOverride != null ? headerChannelIdOverride ?? 82 : dedicatedClient.reserveNextMsgNum();
44903
45206
  const frame = await dedicatedClient.sendFrame({
44904
45207
  cmdId: 5,
@@ -44915,7 +45218,7 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
44915
45218
  started = true;
44916
45219
  } catch (e) {
44917
45220
  try {
44918
- await stream$15.stop();
45221
+ await stream$18.stop();
44919
45222
  } catch {}
44920
45223
  try {
44921
45224
  dedicatedClient.unsubscribeVideoStream(5, msgNum);
@@ -44947,7 +45250,7 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
44947
45250
  try {
44948
45251
  dedicatedClient.unsubscribeVideoStream(5, msgNum);
44949
45252
  } catch {}
44950
- await stream$15.stop();
45253
+ await stream$18.stop();
44951
45254
  await releaseDedicatedClient();
44952
45255
  };
44953
45256
  const autoTeardown = (reason) => {
@@ -44955,13 +45258,13 @@ var ReolinkBaichuanApi = class _ReolinkBaichuanApi {
44955
45258
  logger?.debug?.(`[DedicatedClient] Auto-teardown for ${sessionKey}: ${reason}`);
44956
45259
  stop();
44957
45260
  };
44958
- stream$15.once("close", () => autoTeardown("stream closed"));
44959
- stream$15.once("error", (e) => autoTeardown(`stream error: ${e?.message || e}`));
45261
+ stream$18.once("close", () => autoTeardown("stream closed"));
45262
+ stream$18.once("error", (e) => autoTeardown(`stream error: ${e?.message || e}`));
44960
45263
  dedicatedClient.once("error", (e) => autoTeardown(`client error: ${e?.message || e}`));
44961
45264
  dedicatedClient.once("close", () => autoTeardown("client closed"));
44962
45265
  return {
44963
45266
  msgNum,
44964
- stream: stream$15,
45267
+ stream: stream$18,
44965
45268
  stop
44966
45269
  };
44967
45270
  }
@@ -46281,7 +46584,7 @@ ${stderr}`));
46281
46584
  const dedupKey = `thumbnail:${channel}:${params.fileName}`;
46282
46585
  return this.enqueueReplayOperation(async () => {
46283
46586
  this.logger?.debug?.(`[getRecordingThumbnail] Extracting thumbnail via streaming: channel=${channel}, file=${params.fileName}, streamType=${streamType}`);
46284
- const { stream: stream$16, stop } = await this.startRecordingReplayStream({
46587
+ const { stream: stream$19, stop } = await this.startRecordingReplayStream({
46285
46588
  channel,
46286
46589
  fileName: params.fileName,
46287
46590
  timeoutMs
@@ -46350,21 +46653,21 @@ ${stderr}`));
46350
46653
  return;
46351
46654
  }
46352
46655
  clearTimeout(timeout);
46353
- stream$16.off("videoAccessUnit", onFrame);
46656
+ stream$19.off("videoAccessUnit", onFrame);
46354
46657
  resolve({
46355
46658
  data: au.data,
46356
46659
  videoType: au.videoType
46357
46660
  });
46358
46661
  };
46359
- stream$16.on("videoAccessUnit", onFrame);
46360
- stream$16.once("error", (err) => {
46662
+ stream$19.on("videoAccessUnit", onFrame);
46663
+ stream$19.once("error", (err) => {
46361
46664
  clearTimeout(timeout);
46362
- stream$16.off("videoAccessUnit", onFrame);
46665
+ stream$19.off("videoAccessUnit", onFrame);
46363
46666
  reject(err);
46364
46667
  });
46365
- stream$16.once("close", () => {
46668
+ stream$19.once("close", () => {
46366
46669
  clearTimeout(timeout);
46367
- stream$16.off("videoAccessUnit", onFrame);
46670
+ stream$19.off("videoAccessUnit", onFrame);
46368
46671
  reject(/* @__PURE__ */ new Error("Stream closed before keyframe received"));
46369
46672
  });
46370
46673
  });
@@ -46444,7 +46747,7 @@ ${stderr}`));
46444
46747
  const maxDurationMs = params.maxDurationMs ?? 3e5;
46445
46748
  const idleTimeoutMs = params.idleTimeoutMs ?? 1e4;
46446
46749
  this.logger?.info?.(`[getRecordingVideoViaStreaming] Starting stream: channel=${channel}, file=${params.fileName}`);
46447
- const { stream: stream$17, stop } = await this.startRecordingReplayStream({
46750
+ const { stream: stream$20, stop } = await this.startRecordingReplayStream({
46448
46751
  channel,
46449
46752
  fileName: params.fileName,
46450
46753
  timeoutMs: 3e4
@@ -46462,18 +46765,18 @@ ${stderr}`));
46462
46765
  clearInterval(checkInterval);
46463
46766
  resolve();
46464
46767
  };
46465
- stream$17.on("videoAccessUnit", (frame) => {
46768
+ stream$20.on("videoAccessUnit", (frame) => {
46466
46769
  lastFrameAt = Date.now();
46467
46770
  videoFrames.push(frame.data);
46468
46771
  videoCodec = frame.videoType;
46469
46772
  if (frame.isKeyframe) keyframes++;
46470
46773
  if (videoFrames.length % 100 === 0) this.logger?.debug?.(`[getRecordingVideoViaStreaming] Collected ${videoFrames.length} frames (${keyframes} keyframes)`);
46471
46774
  });
46472
- stream$17.on("close", () => {
46775
+ stream$20.on("close", () => {
46473
46776
  this.logger?.info?.(`[getRecordingVideoViaStreaming] Stream closed after ${videoFrames.length} frames`);
46474
46777
  finish();
46475
46778
  });
46476
- stream$17.on("error", (err) => {
46779
+ stream$20.on("error", (err) => {
46477
46780
  this.logger?.warn?.(`[getRecordingVideoViaStreaming] Stream error: ${err.message}`);
46478
46781
  finish();
46479
46782
  });
@@ -48010,6 +48313,7 @@ ${stderr}`));
48010
48313
  if (n !== void 0) modifiedXml = modifiedXml.replace(/<reduceFalseAlarm>[^<]*<\/reduceFalseAlarm>/, `<reduceFalseAlarm>${n}</reduceFalseAlarm>`);
48011
48314
  }
48012
48315
  if (params.interval !== void 0) modifiedXml = modifiedXml.replace(/<interval>[^<]*<\/interval>/, `<interval>${params.interval}</interval>`);
48316
+ modifiedXml = modifiedXml.replace(/<maxAlarmTime>\s*([^<]*?)\s*<\/maxAlarmTime>/, (match, raw) => /^\d+$/.test(raw) && Number.isSafeInteger(Number(raw)) ? match : "");
48013
48317
  await this.sendXml({
48014
48318
  cmdId: 213,
48015
48319
  channel: ch,
@@ -48821,8 +49125,8 @@ ${xml}`);
48821
49125
  options = typeof profileOrOptions === "object" && profileOrOptions !== null ? profileOrOptions : void 0;
48822
49126
  }
48823
49127
  try {
48824
- const stream$18 = (await this.getStreamMetadata(ch)).streams.find((s) => s.profile === profile);
48825
- if (stream$18?.videoEncType) stream$18.videoEncType;
49128
+ const stream$21 = (await this.getStreamMetadata(ch)).streams.find((s) => s.profile === profile);
49129
+ if (stream$21?.videoEncType) stream$21.videoEncType;
48826
49130
  } catch (error) {
48827
49131
  this.logger.warn(`[ReolinkBaichuanApi] Could not fetch stream metadata, will auto-detect codec: ${error instanceof Error ? error.message : error}`);
48828
49132
  }
@@ -50299,9 +50603,9 @@ ${xml}`);
50299
50603
  const built = buildEncOptions(await this.getStreamInfoList(channel, options), channel);
50300
50604
  try {
50301
50605
  const compression = (await this.getEnc(channel, options)).body?.Compression;
50302
- const mergeGop = (target, stream$19) => {
50303
- if (!target || !stream$19) return;
50304
- const g = stream$19.gop;
50606
+ const mergeGop = (target, stream$22) => {
50607
+ if (!target || !stream$22) return;
50608
+ const g = stream$22.gop;
50305
50609
  if (!g) return;
50306
50610
  target.gopRange = {
50307
50611
  ...g.cur !== void 0 ? { cur: g.cur } : {},
@@ -51287,7 +51591,7 @@ ${scheduleItems}
51287
51591
  const { result: replayResult, release: releaseQueueSlot, abortSignal } = await this.enqueueStreamingReplayOperation(async () => {
51288
51592
  return await this.startRecordingReplayStream(startParams);
51289
51593
  });
51290
- const { stream: stream$20, stop: stopReplay } = replayResult;
51594
+ const { stream: stream$23, stop: stopReplay } = replayResult;
51291
51595
  const input = new stream.PassThrough();
51292
51596
  const output = new stream.PassThrough();
51293
51597
  const H264_AUD = Buffer.from([
@@ -51394,7 +51698,7 @@ ${scheduleItems}
51394
51698
  logger?.debug?.(`[createRecordingReplayMp4Stream] Stopping stream, frames=${frameCount}`);
51395
51699
  const cleanupPromises = [];
51396
51700
  cleanupPromises.push(stopReplay().catch(() => {}));
51397
- cleanupPromises.push(stream$20.stop().catch(() => {}));
51701
+ cleanupPromises.push(stream$23.stop().catch(() => {}));
51398
51702
  try {
51399
51703
  input.end();
51400
51704
  } catch {}
@@ -51420,17 +51724,17 @@ ${scheduleItems}
51420
51724
  clearTimeout(timer);
51421
51725
  stopAll();
51422
51726
  });
51423
- stream$20.on("error", (e) => {
51727
+ stream$23.on("error", (e) => {
51424
51728
  logger?.error?.(`[createRecordingReplayMp4Stream] Stream error: ${e.message}`);
51425
51729
  output.destroy(e);
51426
51730
  stopAll();
51427
51731
  });
51428
- stream$20.on("close", () => {
51732
+ stream$23.on("close", () => {
51429
51733
  logger?.debug?.(`[createRecordingReplayMp4Stream] Stream closed, frames=${frameCount}`);
51430
51734
  clearTimeout(timer);
51431
51735
  stopAll();
51432
51736
  });
51433
- stream$20.on("videoAccessUnit", ({ data, videoType, isKeyframe, microseconds }) => {
51737
+ stream$23.on("videoAccessUnit", ({ data, videoType, isKeyframe, microseconds }) => {
51434
51738
  if (ended) return;
51435
51739
  startFfmpeg(videoType);
51436
51740
  frameCount++;
@@ -51654,7 +51958,7 @@ ${scheduleItems}
51654
51958
  const { result: replayResult, release: releaseQueueSlot, abortSignal } = await this.enqueueStreamingReplayOperation(async () => {
51655
51959
  return await this.startRecordingReplayStream(startParams);
51656
51960
  });
51657
- const { stream: stream$21, stop: stopReplay } = replayResult;
51961
+ const { stream: stream$24, stop: stopReplay } = replayResult;
51658
51962
  const input = new stream.PassThrough();
51659
51963
  Buffer.from([
51660
51964
  0,
@@ -51785,7 +52089,7 @@ ${scheduleItems}
51785
52089
  logger?.debug?.(`[createRecordingReplayHlsSession] Stopping, frames=${frameCount}`);
51786
52090
  const cleanupPromises = [];
51787
52091
  cleanupPromises.push(stopReplay().catch(() => {}));
51788
- cleanupPromises.push(stream$21.stop().catch(() => {}));
52092
+ cleanupPromises.push(stream$24.stop().catch(() => {}));
51789
52093
  try {
51790
52094
  input.end();
51791
52095
  } catch {}
@@ -51811,19 +52115,19 @@ ${scheduleItems}
51811
52115
  stopAll();
51812
52116
  }
51813
52117
  }, { once: true });
51814
- stream$21.on("error", (e) => {
52118
+ stream$24.on("error", (e) => {
51815
52119
  logger?.error?.(`[createRecordingReplayHlsSession] Stream error: ${e.message}`);
51816
52120
  clearTimeout(timer);
51817
52121
  stopAll();
51818
52122
  });
51819
- stream$21.on("close", () => {
52123
+ stream$24.on("close", () => {
51820
52124
  logger?.debug?.(`[createRecordingReplayHlsSession] Stream closed, frames=${frameCount}`);
51821
52125
  clearTimeout(timer);
51822
52126
  try {
51823
52127
  input.end();
51824
52128
  } catch {}
51825
52129
  });
51826
- stream$21.on("videoAccessUnit", ({ data, videoType, isKeyframe, microseconds }) => {
52130
+ stream$24.on("videoAccessUnit", ({ data, videoType, isKeyframe, microseconds }) => {
51827
52131
  if (ended) return;
51828
52132
  startFfmpeg(videoType);
51829
52133
  frameCount++;
@@ -98742,20 +99046,20 @@ var Rfc4571Muxer = class _Rfc4571Muxer {
98742
99046
  state.untrustedDeltaCount++;
98743
99047
  if (now - state.lastUntrustedDeltaLogMs < intervalMs) return;
98744
99048
  state.lastUntrustedDeltaLogMs = now;
98745
- this.logger.warn(`[rfc4571] video timing: ${message} (untrustedDeltaCount=${state.untrustedDeltaCount})`);
99049
+ this.logger?.warn?.(`[rfc4571] video timing: ${message} (untrustedDeltaCount=${state.untrustedDeltaCount})`);
98746
99050
  return;
98747
99051
  }
98748
99052
  if (kind === "wrap") {
98749
99053
  state.wrapCount++;
98750
99054
  if (now - state.lastWrapLogMs < intervalMs) return;
98751
99055
  state.lastWrapLogMs = now;
98752
- this.logger.warn(`[rfc4571] video timing: ${message} (wrapCount=${state.wrapCount})`);
99056
+ this.logger?.warn?.(`[rfc4571] video timing: ${message} (wrapCount=${state.wrapCount})`);
98753
99057
  return;
98754
99058
  }
98755
99059
  state.resetCount++;
98756
99060
  if (now - state.lastResetLogMs < intervalMs) return;
98757
99061
  state.lastResetLogMs = now;
98758
- this.logger.warn(`[rfc4571] video timing: ${message} (resetCount=${state.resetCount})`);
99062
+ this.logger?.warn?.(`[rfc4571] video timing: ${message} (resetCount=${state.resetCount})`);
98759
99063
  }
98760
99064
  advanceVideoTimestampFallback() {
98761
99065
  this.videoRtp.advanceTimestamp(this.fallbackVideoIncrement);
@@ -98964,6 +99268,547 @@ var Rfc4571Muxer = class _Rfc4571Muxer {
98964
99268
  if (isKeyframeLike) for (const c of this.clients) c.needsKeyframe = false;
98965
99269
  }
98966
99270
  };
99271
+ var RESILIENT_STREAM_DEFAULTS = {
99272
+ silenceMs: 1e4,
99273
+ startTimeoutMs: 15e3,
99274
+ maxRecoveryMs: 10 * 6e4,
99275
+ retryDelayMs: 1e3,
99276
+ maxRetryDelayMs: 15e3,
99277
+ renewKeyframeTimeoutMs: 15e3,
99278
+ renewRetryDelayMs: 3e4,
99279
+ maxRenewAttempts: 2
99280
+ };
99281
+ var UDP_SESSION_RENEW_AFTER_MS = 27 * 6e4;
99282
+ var transportLastVideoAt = /* @__PURE__ */ new WeakMap();
99283
+ var ResilientVideoStream = class extends events.EventEmitter {
99284
+ constructor(opts) {
99285
+ super();
99286
+ this.opts = opts;
99287
+ const d = RESILIENT_STREAM_DEFAULTS;
99288
+ this.silenceMs = Math.max(0, opts.silenceMs ?? d.silenceMs);
99289
+ this.startTimeoutMs = Math.max(1, opts.startTimeoutMs ?? d.startTimeoutMs);
99290
+ this.maxRecoveryMs = Math.max(0, opts.maxRecoveryMs ?? d.maxRecoveryMs);
99291
+ this.retryDelayMs = Math.max(1, opts.retryDelayMs ?? d.retryDelayMs);
99292
+ this.maxRetryDelayMs = Math.max(this.retryDelayMs, opts.maxRetryDelayMs ?? d.maxRetryDelayMs);
99293
+ this.renewAfterMs = Math.max(0, opts.renewAfterMs ?? 0);
99294
+ this.renewKeyframeTimeoutMs = Math.max(1, opts.renewKeyframeTimeoutMs ?? d.renewKeyframeTimeoutMs);
99295
+ this.renewRetryDelayMs = Math.max(1, opts.renewRetryDelayMs ?? d.renewRetryDelayMs);
99296
+ this.maxRenewAttempts = Math.max(1, opts.maxRenewAttempts ?? d.maxRenewAttempts);
99297
+ this.logger = opts.logger;
99298
+ this.prefix = `[ResilientVideoStream${opts.label ? ` ${opts.label}` : ""}]`;
99299
+ }
99300
+ silenceMs;
99301
+ startTimeoutMs;
99302
+ maxRecoveryMs;
99303
+ retryDelayMs;
99304
+ maxRetryDelayMs;
99305
+ logger;
99306
+ prefix;
99307
+ session = null;
99308
+ stopped = false;
99309
+ started = false;
99310
+ /** Set while the source is lost; cleared by the first video frame after it. */
99311
+ outage = null;
99312
+ /** True while a recovery attempt (teardown + reopen) is in flight. */
99313
+ reopening = false;
99314
+ lastMediaAt = 0;
99315
+ /** Last video from the current session only (0 until it delivers). */
99316
+ lastVideoAt = 0;
99317
+ silenceTimer = null;
99318
+ retryTimer = null;
99319
+ recoveries = 0;
99320
+ renewAfterMs;
99321
+ renewKeyframeTimeoutMs;
99322
+ renewRetryDelayMs;
99323
+ maxRenewAttempts;
99324
+ /** When the live session was opened (its age base). */
99325
+ sessionOpenedAt = 0;
99326
+ renewTimer = null;
99327
+ renewing = false;
99328
+ renewalCount = 0;
99329
+ renewFailures = 0;
99330
+ /** After failed renewals: reopen proactively at the next keyframe. */
99331
+ renewFallbackArmed = false;
99332
+ candidate = null;
99333
+ /**
99334
+ * Added to every `microseconds` the consumer sees, so a renewed session
99335
+ * (its own camera clock) continues the previous one instead of jumping.
99336
+ */
99337
+ tsOffsetUs = 0;
99338
+ /** Last `microseconds` handed to the consumer, and the last frame spacing. */
99339
+ lastEmittedUs;
99340
+ lastFrameDeltaUs = 4e4;
99341
+ /** Number of outages this stream has recovered from. */
99342
+ getRecoveryCount() {
99343
+ return this.recoveries;
99344
+ }
99345
+ isRecovering() {
99346
+ return this.outage !== null;
99347
+ }
99348
+ consumePendingStartupError() {
99349
+ return this.session?.stream.consumePendingStartupError?.();
99350
+ }
99351
+ /**
99352
+ * Opens the first session. A failure here is the caller's: nothing was
99353
+ * delivered yet, so there is no stream to keep alive.
99354
+ */
99355
+ async start() {
99356
+ if (this.stopped) throw new Error("ResilientVideoStream is stopped");
99357
+ if (this.started) return;
99358
+ await this.openAndStart();
99359
+ if (this.stopped) return;
99360
+ this.started = true;
99361
+ this.lastMediaAt = Date.now();
99362
+ this.startSilenceWatch();
99363
+ }
99364
+ async stop() {
99365
+ if (this.stopped) return;
99366
+ this.stopped = true;
99367
+ this.stopSilenceWatch();
99368
+ this.clearRenewTimer();
99369
+ await this.abandonCandidate("stopped");
99370
+ if (this.retryTimer) {
99371
+ clearTimeout(this.retryTimer);
99372
+ this.retryTimer = null;
99373
+ }
99374
+ await this.dropSession(false, "stopped");
99375
+ this.emit("close");
99376
+ }
99377
+ async openAndStart(purpose = "initial") {
99378
+ const session = await this.opts.openSession({ purpose });
99379
+ if (this.stopped) {
99380
+ await session.release().catch(() => {});
99381
+ throw new Error("ResilientVideoStream stopped while opening a session");
99382
+ }
99383
+ this.session = session;
99384
+ this.lastVideoAt = 0;
99385
+ this.tsOffsetUs = 0;
99386
+ this.lastEmittedUs = void 0;
99387
+ this.attach(session.stream);
99388
+ try {
99389
+ await this.startWithDeadline(session.stream);
99390
+ } catch (e) {
99391
+ await this.dropSession(true, `start failed: ${errorMessage$1(e)}`);
99392
+ throw e;
99393
+ }
99394
+ this.sessionOpenedAt = Date.now();
99395
+ this.renewFallbackArmed = false;
99396
+ this.renewFailures = 0;
99397
+ this.scheduleRenewal(this.renewAfterMs);
99398
+ }
99399
+ async startWithDeadline(stream$3) {
99400
+ let timer;
99401
+ const startPromise = stream$3.start();
99402
+ const deadline = new Promise((_, reject) => {
99403
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`stream start not answered in ${this.startTimeoutMs}ms`)), this.startTimeoutMs);
99404
+ });
99405
+ try {
99406
+ await Promise.race([startPromise, deadline]);
99407
+ } catch (e) {
99408
+ startPromise.catch(() => {});
99409
+ throw e;
99410
+ } finally {
99411
+ if (timer) clearTimeout(timer);
99412
+ }
99413
+ }
99414
+ attach(stream$4) {
99415
+ stream$4.on("videoAccessUnit", this.onAccessUnit);
99416
+ stream$4.on("additionalHeader", this.onAdditionalHeader);
99417
+ stream$4.on("audioFrame", this.onAudioFrame);
99418
+ stream$4.on("error", this.onInnerError);
99419
+ stream$4.on("close", this.onInnerClose);
99420
+ }
99421
+ detach(stream$5) {
99422
+ stream$5.off("videoAccessUnit", this.onAccessUnit);
99423
+ stream$5.off("additionalHeader", this.onAdditionalHeader);
99424
+ stream$5.off("audioFrame", this.onAudioFrame);
99425
+ stream$5.off("error", this.onInnerError);
99426
+ stream$5.off("close", this.onInnerClose);
99427
+ }
99428
+ /** Detaches and stops the current inner stream, then returns its session. */
99429
+ async dropSession(invalidate, reason, forceDiscard = false) {
99430
+ const session = this.session;
99431
+ if (!session) return;
99432
+ this.session = null;
99433
+ this.detach(session.stream);
99434
+ const discard = invalidate && (forceDiscard || !this.siblingStillFlowing(session));
99435
+ if (invalidate && !discard) this.logger?.warn?.(`${this.prefix} the transport still carries another stream; keeping it and asking again on it`);
99436
+ await session.stream.stop().catch(() => {});
99437
+ if (discard) await session.invalidate(reason).catch(() => {});
99438
+ else await session.release().catch(() => {});
99439
+ }
99440
+ /**
99441
+ * A transport that delivered video to another stream after this one last
99442
+ * saw any is alive: only this stream's request is stuck, and closing the
99443
+ * transport would cut the stream that works.
99444
+ */
99445
+ siblingStillFlowing(session) {
99446
+ if (!session.transport) return false;
99447
+ const transportAt = transportLastVideoAt.get(session.transport);
99448
+ if (transportAt === void 0) return false;
99449
+ const window = this.silenceMs > 0 ? this.silenceMs : 1e4;
99450
+ return transportAt > this.lastVideoAt && Date.now() - transportAt < window;
99451
+ }
99452
+ startSilenceWatch() {
99453
+ if (this.silenceMs <= 0 || this.silenceTimer) return;
99454
+ const tickMs = Math.max(50, Math.min(1e3, Math.floor(this.silenceMs / 4)));
99455
+ this.silenceTimer = setInterval(() => {
99456
+ if (this.stopped || this.reopening || this.retryTimer) return;
99457
+ const silentFor = Date.now() - this.lastMediaAt;
99458
+ if (silentFor < this.silenceMs) return;
99459
+ this.sourceLost(`no media for ${silentFor}ms`);
99460
+ }, tickMs);
99461
+ this.silenceTimer.unref?.();
99462
+ }
99463
+ stopSilenceWatch() {
99464
+ if (!this.silenceTimer) return;
99465
+ clearInterval(this.silenceTimer);
99466
+ this.silenceTimer = null;
99467
+ }
99468
+ /**
99469
+ * The guard's verdict, with a throw read as a refusal: not knowing whether
99470
+ * the camera sleeps is not permission to wake it.
99471
+ */
99472
+ recoveryVerdict() {
99473
+ const guard = this.opts.recoveryGuard;
99474
+ if (!guard) return { allowed: true };
99475
+ try {
99476
+ return guard();
99477
+ } catch (e) {
99478
+ return {
99479
+ allowed: false,
99480
+ reason: `sleep state unknown (${errorMessage$1(e)})`
99481
+ };
99482
+ }
99483
+ }
99484
+ /** Ends the stream without reopening: the camera must not be woken by us. */
99485
+ async refuseRecovery(lost, refusal) {
99486
+ if (this.stopped) return;
99487
+ this.stopped = true;
99488
+ this.stopSilenceWatch();
99489
+ this.clearRenewTimer();
99490
+ await this.abandonCandidate("recovery refused");
99491
+ if (this.retryTimer) {
99492
+ clearTimeout(this.retryTimer);
99493
+ this.retryTimer = null;
99494
+ }
99495
+ this.logger?.warn?.(`${this.prefix} source lost (${lost}); not recovering: ${refusal}`);
99496
+ await this.dropSession(true, lost);
99497
+ const err = /* @__PURE__ */ new Error(`${this.prefix} source lost (${lost}); recovery refused: ${refusal}`);
99498
+ if (this.listenerCount("error") > 0) this.emit("error", err);
99499
+ this.emit("close");
99500
+ }
99501
+ /** Entry point for every way the source can be lost. */
99502
+ sourceLost(reason) {
99503
+ if (this.stopped || !this.started) return;
99504
+ if (this.reopening || this.retryTimer) return;
99505
+ this.clearRenewTimer();
99506
+ this.abandonCandidate(`source lost (${reason})`);
99507
+ const verdict = this.recoveryVerdict();
99508
+ if (!verdict.allowed) {
99509
+ this.refuseRecovery(reason, verdict.reason);
99510
+ return;
99511
+ }
99512
+ if (!this.outage) {
99513
+ this.outage = {
99514
+ reason,
99515
+ lostAt: Date.now(),
99516
+ attempts: 0
99517
+ };
99518
+ this.logger?.warn?.(`${this.prefix} source lost (${reason}); recovering on a new session`);
99519
+ this.emit("recovering", { reason });
99520
+ } else this.logger?.warn?.(`${this.prefix} still no video after attempt ${this.outage.attempts} (${reason}); retrying`);
99521
+ const delay = this.outage.attempts > 0 ? this.backoffDelay(this.outage.attempts) : 0;
99522
+ if (delay === 0) {
99523
+ this.reopen(reason);
99524
+ return;
99525
+ }
99526
+ this.logger?.warn?.(`${this.prefix} next attempt in ${delay}ms (silence after attempt ${this.outage.attempts})`);
99527
+ this.dropSession(true, reason);
99528
+ this.scheduleReopen(reason, delay);
99529
+ }
99530
+ backoffDelay(attempts) {
99531
+ return Math.min(this.maxRetryDelayMs, this.retryDelayMs * 2 ** Math.min(Math.max(attempts - 1, 0), 10));
99532
+ }
99533
+ scheduleReopen(reason, delay) {
99534
+ this.retryTimer = setTimeout(() => {
99535
+ this.retryTimer = null;
99536
+ this.reopen(reason);
99537
+ }, delay);
99538
+ this.retryTimer.unref?.();
99539
+ }
99540
+ async reopen(reason, forceDiscard = false) {
99541
+ const outage = this.outage;
99542
+ if (!outage || this.stopped || this.reopening) return;
99543
+ this.reopening = true;
99544
+ try {
99545
+ await this.dropSession(true, reason, forceDiscard);
99546
+ if (this.stopped) return;
99547
+ if (Date.now() - outage.lostAt >= this.maxRecoveryMs) {
99548
+ this.giveUp(outage);
99549
+ return;
99550
+ }
99551
+ const verdict = this.recoveryVerdict();
99552
+ if (!verdict.allowed) {
99553
+ this.reopening = false;
99554
+ await this.refuseRecovery(reason, verdict.reason);
99555
+ return;
99556
+ }
99557
+ outage.attempts++;
99558
+ try {
99559
+ await this.openAndStart("recovery");
99560
+ this.lastMediaAt = Date.now();
99561
+ this.logger?.debug?.(`${this.prefix} attempt ${outage.attempts}: stream re-requested, waiting for video`);
99562
+ } catch (e) {
99563
+ if (this.stopped) return;
99564
+ const delay = this.backoffDelay(outage.attempts);
99565
+ this.logger?.warn?.(`${this.prefix} attempt ${outage.attempts} failed (${errorMessage$1(e)}); next in ${delay}ms`);
99566
+ this.scheduleReopen(reason, delay);
99567
+ }
99568
+ } finally {
99569
+ this.reopening = false;
99570
+ }
99571
+ }
99572
+ clearRenewTimer() {
99573
+ if (!this.renewTimer) return;
99574
+ clearTimeout(this.renewTimer);
99575
+ this.renewTimer = null;
99576
+ }
99577
+ /** Arms the renewal for when the live session reaches `renewAfterMs`. */
99578
+ scheduleRenewal(delayMs) {
99579
+ this.clearRenewTimer();
99580
+ if (this.renewAfterMs <= 0 || this.stopped) return;
99581
+ this.renewTimer = setTimeout(() => {
99582
+ this.renewTimer = null;
99583
+ this.renewSession();
99584
+ }, Math.max(0, delayMs));
99585
+ this.renewTimer.unref?.();
99586
+ }
99587
+ async renewSession() {
99588
+ if (this.stopped || !this.started) return;
99589
+ if (this.renewing || this.candidate) return;
99590
+ if (this.reopening || this.retryTimer || this.outage) return;
99591
+ const verdict = this.recoveryVerdict();
99592
+ if (!verdict.allowed) {
99593
+ const retry = this.withinRenewWindow();
99594
+ this.logger?.warn?.(`${this.prefix} session renewal refused: ${verdict.reason}${retry ? `; asking again in ${this.renewRetryDelayMs}ms` : "; past the renewal window, leaving it to recovery"}`);
99595
+ if (retry) this.scheduleRenewal(this.renewRetryDelayMs);
99596
+ return;
99597
+ }
99598
+ const age = Date.now() - this.sessionOpenedAt;
99599
+ this.renewing = true;
99600
+ this.logger?.info?.(`${this.prefix} renewing session at age=${age}ms (make-before-break)`);
99601
+ const renewalId = this.renewalCount++ % 2;
99602
+ let session;
99603
+ try {
99604
+ session = await this.opts.openSession({
99605
+ purpose: "renewal",
99606
+ renewalId
99607
+ });
99608
+ } catch (e) {
99609
+ this.renewing = false;
99610
+ this.renewalFailed(`could not open a second session: ${errorMessage$1(e)}`);
99611
+ return;
99612
+ }
99613
+ if (this.stopped || this.outage) {
99614
+ this.renewing = false;
99615
+ await session.invalidate("renewal no longer needed").catch(() => {});
99616
+ return;
99617
+ }
99618
+ const cand = {
99619
+ session,
99620
+ openedAt: Date.now(),
99621
+ header: void 0,
99622
+ onAccessUnit: (...args) => this.onCandidateAccessUnit(cand, args[0]),
99623
+ onHeader: (...args) => {
99624
+ cand.header = args;
99625
+ },
99626
+ onFail: (...args) => {
99627
+ this.abandonCandidate(`renewal session failed: ${errorMessage$1(args[0])}`).then(() => this.renewalFailed(`renewal session failed: ${errorMessage$1(args[0])}`));
99628
+ },
99629
+ deadline: null
99630
+ };
99631
+ this.candidate = cand;
99632
+ session.stream.on("videoAccessUnit", cand.onAccessUnit);
99633
+ session.stream.on("additionalHeader", cand.onHeader);
99634
+ session.stream.on("error", cand.onFail);
99635
+ session.stream.on("close", cand.onFail);
99636
+ try {
99637
+ await this.startWithDeadline(session.stream);
99638
+ } catch (e) {
99639
+ this.renewing = false;
99640
+ if (this.candidate !== cand) return;
99641
+ await this.abandonCandidate("start failed");
99642
+ this.renewalFailed(`second session did not start: ${errorMessage$1(e)}`);
99643
+ return;
99644
+ }
99645
+ this.renewing = false;
99646
+ if (this.candidate !== cand) return;
99647
+ cand.deadline = setTimeout(() => {
99648
+ cand.deadline = null;
99649
+ this.abandonCandidate("no keyframe in time").then(() => this.renewalFailed(`second session delivered no keyframe in ${this.renewKeyframeTimeoutMs}ms`));
99650
+ }, this.renewKeyframeTimeoutMs);
99651
+ cand.deadline.unref?.();
99652
+ }
99653
+ /** First keyframe of the candidate: switch the consumer over, then close the old one. */
99654
+ onCandidateAccessUnit(cand, au) {
99655
+ if (this.candidate !== cand || !au.isKeyframe) return;
99656
+ const old = this.session;
99657
+ this.candidate = null;
99658
+ if (cand.deadline) clearTimeout(cand.deadline);
99659
+ cand.deadline = null;
99660
+ this.detachCandidate(cand);
99661
+ if (this.stopped) {
99662
+ cand.session.invalidate("stopped").catch(() => {});
99663
+ return;
99664
+ }
99665
+ const previousAgeMs = Date.now() - this.sessionOpenedAt;
99666
+ if (old) this.detach(old.stream);
99667
+ this.session = cand.session;
99668
+ this.sessionOpenedAt = cand.openedAt;
99669
+ this.lastVideoAt = 0;
99670
+ this.renewFailures = 0;
99671
+ this.attach(cand.session.stream);
99672
+ if (this.lastEmittedUs !== void 0) this.tsOffsetUs = this.lastEmittedUs + this.lastFrameDeltaUs - au.microseconds | 0;
99673
+ if (cand.header) this.emit("additionalHeader", this.rebaseHeader(cand.header[0]));
99674
+ this.onAccessUnit(au);
99675
+ this.scheduleRenewal(this.renewAfterMs);
99676
+ this.logger?.info?.(`${this.prefix} switched to the renewed session (previous age=${previousAgeMs}ms); closing the old one`);
99677
+ this.emit("renewed", { previousAgeMs });
99678
+ if (old) (async () => {
99679
+ await old.stream.stop().catch(() => {});
99680
+ await old.invalidate("session renewed").catch(() => {});
99681
+ })();
99682
+ }
99683
+ detachCandidate(cand) {
99684
+ cand.session.stream.off("videoAccessUnit", cand.onAccessUnit);
99685
+ cand.session.stream.off("additionalHeader", cand.onHeader);
99686
+ cand.session.stream.off("error", cand.onFail);
99687
+ cand.session.stream.off("close", cand.onFail);
99688
+ }
99689
+ /** Discards a candidate that never took over. The live session is untouched. */
99690
+ async abandonCandidate(reason) {
99691
+ const cand = this.candidate;
99692
+ if (!cand) return;
99693
+ this.candidate = null;
99694
+ if (cand.deadline) clearTimeout(cand.deadline);
99695
+ cand.deadline = null;
99696
+ this.detachCandidate(cand);
99697
+ await cand.session.stream.stop().catch(() => {});
99698
+ await cand.session.invalidate(reason).catch(() => {});
99699
+ }
99700
+ renewalFailed(why) {
99701
+ if (this.stopped) return;
99702
+ this.renewFailures++;
99703
+ if (this.renewFailures >= this.maxRenewAttempts) {
99704
+ this.logger?.warn?.(`${this.prefix} session renewal failed ${this.renewFailures}x (${why}); falling back to a proactive reopen at the next keyframe`);
99705
+ this.renewFallbackArmed = true;
99706
+ return;
99707
+ }
99708
+ this.logger?.warn?.(`${this.prefix} session renewal failed (${why}); retrying in ${this.renewRetryDelayMs}ms`);
99709
+ this.scheduleRenewal(this.renewRetryDelayMs);
99710
+ }
99711
+ /**
99712
+ * Renewal is pointless once the session is well past the age at which the
99713
+ * camera ends it (~30 min against a 27 min default): +3 min of margin.
99714
+ */
99715
+ withinRenewWindow() {
99716
+ return Date.now() - this.sessionOpenedAt < this.renewAfterMs + 18e4;
99717
+ }
99718
+ /** Planned break-before-make renewal, entered right after a keyframe. */
99719
+ proactiveReopen() {
99720
+ if (this.stopped || this.reopening || this.outage || this.retryTimer) return;
99721
+ if (!this.recoveryVerdict().allowed) {
99722
+ this.renewFallbackArmed = this.withinRenewWindow();
99723
+ return;
99724
+ }
99725
+ const reason = `proactive session renewal at age=${Date.now() - this.sessionOpenedAt}ms`;
99726
+ this.outage = {
99727
+ reason,
99728
+ lostAt: Date.now(),
99729
+ attempts: 0
99730
+ };
99731
+ this.logger?.warn?.(`${this.prefix} ${reason}; reopening on a new session`);
99732
+ this.emit("recovering", { reason });
99733
+ this.reopen(reason, true);
99734
+ }
99735
+ giveUp(outage) {
99736
+ const err = /* @__PURE__ */ new Error(`${this.prefix} source not recovered after ${Date.now() - outage.lostAt}ms and ${outage.attempts} attempt(s) (${outage.reason})`);
99737
+ this.logger?.warn?.(err.message);
99738
+ this.stopped = true;
99739
+ this.stopSilenceWatch();
99740
+ this.clearRenewTimer();
99741
+ this.abandonCandidate("gave up");
99742
+ if (this.listenerCount("error") > 0) this.emit("error", err);
99743
+ this.emit("close");
99744
+ }
99745
+ onAccessUnit = (...args) => {
99746
+ const au = this.rebase(args[0]);
99747
+ this.lastMediaAt = Date.now();
99748
+ this.lastVideoAt = this.lastMediaAt;
99749
+ const transport = this.session?.transport;
99750
+ if (transport) transportLastVideoAt.set(transport, this.lastMediaAt);
99751
+ const outage = this.outage;
99752
+ if (outage) {
99753
+ if (!au.isKeyframe) return;
99754
+ this.outage = null;
99755
+ this.recoveries++;
99756
+ const info = {
99757
+ reason: outage.reason,
99758
+ outageMs: Date.now() - outage.lostAt,
99759
+ attempts: outage.attempts
99760
+ };
99761
+ (this.logger?.info ?? this.logger?.log)?.call(this.logger, `${this.prefix} recovered after ${info.outageMs}ms attempts=${info.attempts} (${info.reason})`);
99762
+ this.emit("recovered", info);
99763
+ }
99764
+ this.trackEmittedUs(au.microseconds);
99765
+ this.emit("videoAccessUnit", au);
99766
+ if (this.renewFallbackArmed && au.isKeyframe && !this.outage) {
99767
+ this.renewFallbackArmed = false;
99768
+ this.proactiveReopen();
99769
+ }
99770
+ };
99771
+ onAdditionalHeader = (...args) => {
99772
+ this.emit("additionalHeader", this.rebaseHeader(args[0]));
99773
+ };
99774
+ rebase(au) {
99775
+ if (this.tsOffsetUs === 0) return au;
99776
+ return {
99777
+ ...au,
99778
+ microseconds: au.microseconds + this.tsOffsetUs >>> 0
99779
+ };
99780
+ }
99781
+ rebaseHeader(h) {
99782
+ if (this.tsOffsetUs === 0 || typeof h !== "object" || h === null) return h;
99783
+ const us = h.microseconds;
99784
+ if (typeof us !== "number") return h;
99785
+ return {
99786
+ ...h,
99787
+ microseconds: us + this.tsOffsetUs >>> 0
99788
+ };
99789
+ }
99790
+ trackEmittedUs(us) {
99791
+ if (this.lastEmittedUs !== void 0) {
99792
+ const d = us - this.lastEmittedUs >>> 0;
99793
+ if (d >= 1e3 && d <= 1e6) this.lastFrameDeltaUs = d;
99794
+ }
99795
+ this.lastEmittedUs = us;
99796
+ }
99797
+ onAudioFrame = (...args) => {
99798
+ if (this.outage) return;
99799
+ this.emit("audioFrame", args[0]);
99800
+ };
99801
+ onInnerError = (...args) => {
99802
+ this.sourceLost(`stream error: ${errorMessage$1(args[0])}`);
99803
+ };
99804
+ onInnerClose = () => {
99805
+ this.sourceLost("stream closed by the camera or the transport");
99806
+ };
99807
+ };
99808
+ function errorMessage$1(e) {
99809
+ if (e instanceof Error) return e.message;
99810
+ return String(e);
99811
+ }
98967
99812
  function calculateOverlayPosition(position, mainWidth, mainHeight, pipWidth, pipHeight, margin) {
98968
99813
  const pipW = Math.floor(pipWidth);
98969
99814
  const pipH = Math.floor(pipHeight);
@@ -99715,6 +100560,17 @@ var CompositeStream = class extends events.EventEmitter {
99715
100560
  return this.active;
99716
100561
  }
99717
100562
  };
100563
+ var STREAM_METADATA_DEADLINE_MS = 5e3;
100564
+ function withDeadline(work, deadlineMs, what) {
100565
+ let timer;
100566
+ const deadline = new Promise((_, reject) => {
100567
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`${what} not answered in ${deadlineMs}ms`)), deadlineMs);
100568
+ });
100569
+ work.catch(() => {});
100570
+ return Promise.race([work, deadline]).finally(() => {
100571
+ if (timer) clearTimeout(timer);
100572
+ });
100573
+ }
99718
100574
  async function createRfc4571TcpServer(options) {
99719
100575
  const sharedProcessId = typeof process !== "undefined" && typeof process.pid === "number" ? process.pid : "n/a";
99720
100576
  const sharedInstanceId = (() => {
@@ -99878,7 +100734,10 @@ async function createRfc4571TcpServerInternal(options) {
99878
100734
  apisToClose.add(baseApi);
99879
100735
  if (resolvedCompositeApis?.widerApi) apisToClose.add(resolvedCompositeApis.widerApi);
99880
100736
  if (resolvedCompositeApis?.teleApi) apisToClose.add(resolvedCompositeApis.teleApi);
99881
- const uptimeRestartMs = Boolean(options.alwaysOn?.enabled) && !isComposite ? 0 : uptimeRestartMsOpt ?? (isComposite ? 6e4 : 1e4);
100737
+ const alwaysOnEnabled = Boolean(options.alwaysOn?.enabled) && !isComposite;
100738
+ const resilienceEnabled = !isComposite && !alwaysOnEnabled && Boolean(options.deviceId) && options.resilience?.enabled !== false;
100739
+ const sourceSilenceMs = options.resilience?.silenceMs ?? uptimeRestartMsOpt ?? 1e4;
100740
+ const uptimeRestartMs = alwaysOnEnabled || resilienceEnabled ? 0 : uptimeRestartMsOpt ?? (isComposite ? 6e4 : 1e4);
99882
100741
  const variantSuffix = variant && variant !== "default" ? ` variant=${variant}` : "";
99883
100742
  const logPrefix = isComposite ? `[native-rfc4571 composite profile=${profile}${variantSuffix}${requestedId ? ` id=${requestedId}` : ""}]` : `[native-rfc4571 ch=${channel} profile=${profile}${variantSuffix}]`;
99884
100743
  const log = (message) => {
@@ -99995,8 +100854,8 @@ async function createRfc4571TcpServerInternal(options) {
99995
100854
  const ch = channel;
99996
100855
  const deviceId = options.deviceId;
99997
100856
  let streamClient;
100857
+ const sessionKey = `live:${deviceId}:ch${ch}:${profile}${variant && variant !== "default" ? `:${variant}` : ""}`;
99998
100858
  if (deviceId) {
99999
- const sessionKey = `live:${deviceId}:ch${ch}:${profile}${variant && variant !== "default" ? `:${variant}` : ""}`;
100000
100859
  dedicatedSession = await baseApi.createDedicatedSession(sessionKey, logger);
100001
100860
  streamClient = dedicatedSession.client;
100002
100861
  logSessionsSummary(`dedicated session created: ${sessionKey}`);
@@ -100028,6 +100887,53 @@ async function createRfc4571TcpServerInternal(options) {
100028
100887
  await alwaysOnController.start();
100029
100888
  videoStream = cvs;
100030
100889
  log(`always-on stream started (ch=${ch} profile=${profile}${deviceId ? ` dedicated=${deviceId}` : ""})`);
100890
+ } else if (resilienceEnabled && dedicatedSession) {
100891
+ let firstSession = dedicatedSession;
100892
+ const resilient = new ResilientVideoStream({
100893
+ label: `ch=${ch} profile=${profile}`,
100894
+ silenceMs: sourceSilenceMs,
100895
+ renewAfterMs: resolveRenewAfterMs(options.resilience, baseApi.client.getTransport?.()),
100896
+ recoveryGuard: resolveRecoveryGuard(options.resilience, () => baseApi.client.getTransport?.()),
100897
+ ...options.resilience?.maxRecoveryMs !== void 0 ? { maxRecoveryMs: options.resilience.maxRecoveryMs } : {},
100898
+ logger,
100899
+ openSession: async (ctx) => {
100900
+ const key = ctx?.purpose === "renewal" ? `${sessionKey}#renew${ctx.renewalId ?? 0}` : sessionKey;
100901
+ const session = firstSession ?? await baseApi.createDedicatedSession(key, logger);
100902
+ firstSession = void 0;
100903
+ return {
100904
+ stream: new require_chunk_LXENEW4N.BaichuanVideoStream({
100905
+ client: session.client,
100906
+ api: baseApi,
100907
+ channel: ch,
100908
+ profile,
100909
+ variant,
100910
+ logger
100911
+ }),
100912
+ release: session.release,
100913
+ invalidate: session.invalidate,
100914
+ transport: session.client
100915
+ };
100916
+ }
100917
+ });
100918
+ let releaseRecoveryPermit;
100919
+ const dropRecoveryPermit = () => {
100920
+ const release = releaseRecoveryPermit;
100921
+ releaseRecoveryPermit = void 0;
100922
+ try {
100923
+ release?.();
100924
+ } catch {}
100925
+ };
100926
+ resilient.on("recovering", () => {
100927
+ dropRecoveryPermit();
100928
+ try {
100929
+ releaseRecoveryPermit = baseApi.client.acquirePermit?.(options.resilience?.maxRecoveryMs ?? RESILIENT_STREAM_DEFAULTS.maxRecoveryMs, `stream-recovery:${sessionKey}`);
100930
+ } catch {}
100931
+ });
100932
+ resilient.on("recovered", dropRecoveryPermit);
100933
+ resilient.on("close", dropRecoveryPermit);
100934
+ await resilient.start();
100935
+ videoStream = resilient;
100936
+ log(`stream started (ch=${ch} profile=${profile} dedicated=${deviceId} self-healing silenceMs=${sourceSilenceMs})`);
100031
100937
  } else {
100032
100938
  const live = await createLiveStream();
100033
100939
  await live.start();
@@ -100159,8 +101065,10 @@ async function createRfc4571TcpServerInternal(options) {
100159
101065
  }
100160
101066
  throw e;
100161
101067
  }
101068
+ log(`keyframe received (video=${keyframe.videoType})`);
100162
101069
  if (expectedVideoType && keyframe.videoType !== expectedVideoType) log(`expectedVideoType mismatch (expected=${expectedVideoType} actual=${keyframe.videoType})`);
100163
101070
  let fps = 25;
101071
+ const metadataStartedAt = Date.now();
100164
101072
  try {
100165
101073
  if (isComposite) {
100166
101074
  const widerChannel = compositeOptions?.widerChannel ?? 0;
@@ -100174,16 +101082,18 @@ async function createRfc4571TcpServerInternal(options) {
100174
101082
  widerMainIsH264 = (typeof main?.videoEncType === "string" ? main.videoEncType.toLowerCase() : "").includes("264");
100175
101083
  } catch {}
100176
101084
  const widerProfile = requested?.widerProfile ?? (effectiveTeleProfile === "ext" ? "ext" : effectiveTeleProfile === "main" && widerMainIsH264 ? "main" : "sub");
100177
- const stream$3 = streams.find((s) => s?.profile === widerProfile);
100178
- const fr = Number(stream$3?.frameRate);
101085
+ const stream$6 = streams.find((s) => s?.profile === widerProfile);
101086
+ const fr = Number(stream$6?.frameRate);
100179
101087
  if (Number.isFinite(fr) && fr > 0) fps = fr;
100180
101088
  } else {
100181
- const metadata = await baseApi.getStreamMetadata(channel);
100182
- const stream$4 = (Array.isArray(metadata) ? metadata : Array.isArray(metadata?.streams) ? metadata.streams : []).find((s) => s?.profile === profile);
100183
- const fr = Number(stream$4?.frameRate);
101089
+ const metadata = await withDeadline(baseApi.getStreamMetadata(channel), STREAM_METADATA_DEADLINE_MS, "stream metadata");
101090
+ const stream$7 = (Array.isArray(metadata) ? metadata : Array.isArray(metadata?.streams) ? metadata.streams : []).find((s) => s?.profile === profile);
101091
+ const fr = Number(stream$7?.frameRate);
100184
101092
  if (Number.isFinite(fr) && fr > 0) fps = fr;
100185
101093
  }
100186
- } catch {}
101094
+ } catch (e) {
101095
+ log(`stream metadata unavailable after ${Date.now() - metadataStartedAt}ms, keeping fps=${fps} (${e instanceof Error ? e.message : String(e)})`);
101096
+ }
100187
101097
  let audio;
100188
101098
  const tryPrimeAudio = async () => {
100189
101099
  return await new Promise((resolve) => {
@@ -100527,6 +101437,21 @@ async function createRfc4571TcpServerInternal(options) {
100527
101437
  close
100528
101438
  };
100529
101439
  }
101440
+ var SLEEPER_REFUSAL = {
101441
+ allowed: false,
101442
+ reason: "the camera sleeps: a new session would wake it, so dialling again is the caller's decision"
101443
+ };
101444
+ var ALWAYS_RECOVER = { allowed: true };
101445
+ function resolveRenewAfterMs(resilience, transport) {
101446
+ if (resilience?.renewAfterMs !== void 0) return resilience.renewAfterMs;
101447
+ return transport === "udp" ? UDP_SESSION_RENEW_AFTER_MS : 0;
101448
+ }
101449
+ function resolveRecoveryGuard(resilience, transport) {
101450
+ if (resilience?.recoveryGuard) return resilience.recoveryGuard;
101451
+ if (resilience?.sleeps === true) return () => SLEEPER_REFUSAL;
101452
+ if (resilience?.sleeps === false) return () => ALWAYS_RECOVER;
101453
+ return () => transport() === "udp" ? SLEEPER_REFUSAL : ALWAYS_RECOVER;
101454
+ }
100530
101455
  Buffer.from([
100531
101456
  0,
100532
101457
  0,
@@ -105896,7 +106821,9 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
105896
106821
  * only way to keep the broker dialable. Camera providers (Reolink
105897
106822
  * Baichuan native, …) subscribe and respond by re-running their publish
105898
106823
  * pipeline.
105899
- * Payload: `{ deviceId, camStreamId, brokerId }`.
106824
+ * Payload: `{ deviceId, camStreamId, brokerId, reason? }`. `reason` is
106825
+ * `'source-silent'` when a no-packet watchdog asked: a still-listening cached
106826
+ * server is then the dead one and must be recreated.
105900
106827
  */
105901
106828
  EventCategory["StreamBrokerOnRequestStreamSourceRefresh"] = "stream-broker.onRequestStreamSourceRefresh";
105902
106829
  /**
@@ -106701,7 +107628,8 @@ function typeOf(field) {
106701
107628
  case "timezone":
106702
107629
  case "datetime": return "string";
106703
107630
  case "number":
106704
- case "slider": return "number";
107631
+ case "slider":
107632
+ case "duration": return "number";
106705
107633
  case "boolean": return "boolean";
106706
107634
  default: return "other";
106707
107635
  }
@@ -106799,12 +107727,41 @@ async function guarded(work) {
106799
107727
  };
106800
107728
  }
106801
107729
  }
107730
+ var WAITING_REASON = /^dependency-(?:pending|blocked):(.+)$/;
107731
+ /**
107732
+ * What an owner keeps between runs: the steps blocked only on a predecessor not yet applied.
107733
+ * The engine announces every applied id (`migration.applied`); {@link releasedBy} says which
107734
+ * waiting steps that frees, so the owner runs them again without a restart or a timer.
107735
+ */
107736
+ var MigrationDependencyWaits = class {
107737
+ waiting = /* @__PURE__ */ new Map();
107738
+ /** Replace what is waiting for the ids this run judged (a step that moved on stops waiting). */
107739
+ record(report, judged) {
107740
+ for (const id of judged) this.waiting.delete(id);
107741
+ for (const entry of report.awaiting) this.waiting.set(entry.id, entry.on);
107742
+ }
107743
+ /** Waiting steps whose predecessor is among `applied`; they stop waiting (the rerun re-records). */
107744
+ releasedBy(applied) {
107745
+ const freed = [...this.waiting].filter(([, on]) => applied.includes(on)).map(([id]) => id);
107746
+ for (const id of freed) this.waiting.delete(id);
107747
+ return freed;
107748
+ }
107749
+ get size() {
107750
+ return this.waiting.size;
107751
+ }
107752
+ };
107753
+ /** The ids a `migration.applied` event carries; anything else yields none. */
107754
+ function appliedIdsOf(data) {
107755
+ if (typeof data !== "object" || data === null || !("ids" in data) || !Array.isArray(data.ids)) return [];
107756
+ return data.ids.filter((id) => typeof id === "string");
107757
+ }
106802
107758
  var NOT_RUN = {
106803
107759
  declared: false,
106804
107760
  snapshot: null,
106805
107761
  applied: [],
106806
107762
  failed: [],
106807
107763
  blocked: [],
107764
+ awaiting: [],
106808
107765
  skipped: [],
106809
107766
  blockOwner: []
106810
107767
  };
@@ -106824,7 +107781,8 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
106824
107781
  declaration = await host.declareOwner({
106825
107782
  owner,
106826
107783
  metas: migrations.map((m) => m.meta),
106827
- ...options.retired === void 0 ? {} : { retired: [...options.retired] }
107784
+ ...options.retired === void 0 ? {} : { retired: [...options.retired] },
107785
+ ...options.complete === void 0 ? {} : { complete: options.complete }
106828
107786
  });
106829
107787
  } catch (err) {
106830
107788
  log.error("the migration engine refused or could not take this addon catalogue — none ran", { meta: { error: errMsg$3(err) } });
@@ -106836,6 +107794,7 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
106836
107794
  const applied = [];
106837
107795
  const failed = [];
106838
107796
  const blocked = [];
107797
+ const awaiting = [];
106839
107798
  const skipped = [];
106840
107799
  const settle = (id, status) => {
106841
107800
  if (status === "applied") applied.push(id);
@@ -106845,10 +107804,12 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
106845
107804
  };
106846
107805
  const selected = options.only === void 0 ? null : new Set(options.only);
106847
107806
  const deferred = /* @__PURE__ */ new Set();
107807
+ const settledEarlier = new Set(options.settledEarlier ?? []);
106848
107808
  const deferredBy = (reason) => {
106849
107809
  if (selected === null || reason === null) return null;
106850
107810
  const dep = /^dependency-(?:pending|blocked):(.+)$/.exec(reason)?.[1];
106851
107811
  if (dep === void 0 || !byId.has(dep)) return null;
107812
+ if (settledEarlier.has(dep)) return null;
106852
107813
  return !selected.has(dep) || deferred.has(dep) ? dep : null;
106853
107814
  };
106854
107815
  for (const step of declaration.steps) {
@@ -106882,6 +107843,11 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
106882
107843
  reason: gate.reason
106883
107844
  }
106884
107845
  });
107846
+ const on = WAITING_REASON.exec(gate.reason ?? "")?.[1];
107847
+ if (on !== void 0) awaiting.push({
107848
+ id: step.id,
107849
+ on
107850
+ });
106885
107851
  settle(step.id, gate.state === "pending" ? "blocked" : gate.state);
106886
107852
  continue;
106887
107853
  }
@@ -106914,6 +107880,7 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
106914
107880
  applied,
106915
107881
  failed,
106916
107882
  blocked,
107883
+ awaiting,
106917
107884
  skipped,
106918
107885
  blockOwner
106919
107886
  };
@@ -108981,6 +109948,7 @@ var BaseAddon = class {
108981
109948
  });
108982
109949
  await this.hydrateSwitches();
108983
109950
  const result = await this.onInitialize();
109951
+ this.catalogueOpen = false;
108984
109952
  await this.moveLateInstanceKinds();
108985
109953
  await this.adoptUnrowed();
108986
109954
  if (this.switchesHydrated) {
@@ -109028,7 +109996,14 @@ var BaseAddon = class {
109028
109996
  registrySwitchSpec = null;
109029
109997
  /** The instance kinds whose switch move this process already ran (or tried), by record kind name. */
109030
109998
  switchMoved = /* @__PURE__ */ new Set();
109031
- lastDeclared = [];
109999
+ /**
110000
+ * Every migration any `runMigrations` call of this process declared, by id. The engine replaces
110001
+ * an owner's catalogue on each declare, so each call carries the union, phased to its own ids.
110002
+ */
110003
+ declaredAll = /* @__PURE__ */ new Map();
110004
+ /** True until `initialize` has run `onInitialize`: more kinds and calls may still declare. */
110005
+ catalogueOpen = true;
110006
+ declaredIncomplete = false;
109032
110007
  /**
109033
110008
  * Every switch migration this process added to a declaration so far, by id. The engine replaces
109034
110009
  * an owner's catalogue on each declare, so a later one (a late kind) carries them all: dropping
@@ -109092,34 +110067,105 @@ var BaseAddon = class {
109092
110067
  */
109093
110068
  async moveLateInstanceKinds() {
109094
110069
  const late = servedInstanceKindsOf(this.ctx.id).filter((k) => !this.switchMoved.has(k.kind.name));
109095
- if (late.length === 0) return;
110070
+ if (late.length === 0) {
110071
+ if (!this.declaredIncomplete) return;
110072
+ try {
110073
+ await this.runBound([], { only: [] });
110074
+ } catch (err) {
110075
+ if (err instanceof AddonMigrationsBlockedError) throw err;
110076
+ this.ctx.logger.error("the closing migration declare failed", { meta: { error: errMsg$3(err) } });
110077
+ }
110078
+ return;
110079
+ }
109096
110080
  try {
109097
110081
  const only = late.map((k) => bodySwitchToRegistryId(this.ctx.id, "2026-11-19", k.kind.name));
109098
- await this.runBound(this.lastDeclared, { only });
110082
+ await this.runBound([], { only });
109099
110083
  } catch (err) {
109100
110084
  if (err instanceof AddonMigrationsBlockedError) throw err;
109101
110085
  this.ctx.logger.error("the late instance switch move failed", { meta: { error: errMsg$3(err) } });
109102
110086
  }
109103
110087
  }
110088
+ /** Steps blocked only on another owner's step that has not applied yet (run again when it does). */
110089
+ migrationWaits = new MigrationDependencyWaits();
110090
+ migrationWatch = false;
110091
+ /** Every id announced applied since the subscription: closes the in-flight-run window. */
110092
+ migrationAppliedSeen = /* @__PURE__ */ new Set();
110093
+ migrationRerunTail = Promise.resolve();
110094
+ /**
110095
+ * The engine announces every applied step (`migration.applied`). Subscribed BEFORE the first
110096
+ * declare, so a predecessor that lands between this owner's read and its subscription is not
110097
+ * missed; a step the engine blocked on one runs when that predecessor applies, with no restart.
110098
+ */
110099
+ watchAppliedMigrations() {
110100
+ if (this.migrationWatch) return;
110101
+ this.migrationWatch = true;
110102
+ this.subscribe({ category: EventCategory.MigrationApplied }, (event) => {
110103
+ const ids = appliedIdsOf(event.data);
110104
+ for (const id of ids) this.migrationAppliedSeen.add(id);
110105
+ this.releaseBlockedMigrations(ids);
110106
+ });
110107
+ }
110108
+ /**
110109
+ * Run again the waiting steps whose predecessor is among `applied`. The event is a hint (D8):
110110
+ * a dropped one leaves the step blocked until this addon's next boot, which reads the ledger.
110111
+ */
110112
+ releaseBlockedMigrations(applied) {
110113
+ const freed = this.migrationWaits.releasedBy(applied);
110114
+ if (freed.length === 0) return;
110115
+ this.migrationRerunTail = this.migrationRerunTail.catch(() => void 0).then(async () => {
110116
+ this.ctx.logger.info("a migration predecessor applied — running the blocked steps", { meta: { ids: freed } });
110117
+ await this.runBound([], { only: freed });
110118
+ }).then(() => void 0, (err) => {
110119
+ this.ctx.logger.error("the blocked migration steps could not run again", { meta: {
110120
+ ids: freed,
110121
+ error: errMsg$3(err)
110122
+ } });
110123
+ });
110124
+ }
109104
110125
  async runBound(declared, options) {
109105
- this.lastDeclared = declared;
110126
+ this.watchAppliedMigrations();
110127
+ const priorIds = new Set([...this.declaredAll.keys(), ...this.switchDeclared.keys()]);
109106
110128
  const added = this.registrySwitchBound();
109107
110129
  for (const m of added) this.switchDeclared.set(m.meta.id, m);
109108
- const migrations = [...declared, ...[...this.switchDeclared.values()].filter((m) => !declared.some((d) => d.meta.id === m.meta.id))];
109109
- const widened = options?.only === void 0 || added.length === 0 ? options : {
110130
+ for (const m of declared) this.declaredAll.set(m.meta.id, m);
110131
+ const migrations = [...this.declaredAll.values(), ...[...this.switchDeclared.values()].filter((m) => !this.declaredAll.has(m.meta.id))];
110132
+ const settledEarlier = [...priorIds].filter((id) => !declared.some((d) => d.meta.id === id));
110133
+ const own = settledEarlier.length === 0 ? options ?? {} : {
109110
110134
  ...options,
109111
- only: [...new Set([...options.only, ...added.map((m) => m.meta.id)])]
109112
- };
109113
- const phased = this.retiredMigrationIds.length === 0 ? widened ?? {} : {
109114
- ...widened,
109115
- retired: this.retiredMigrationIds
110135
+ ...options?.only === void 0 ? { only: declared.map((m) => m.meta.id) } : {},
110136
+ settledEarlier
110137
+ };
110138
+ const widened = own?.only === void 0 || added.length === 0 ? own : {
110139
+ ...own,
110140
+ only: [...new Set([...own.only, ...added.map((m) => m.meta.id)])]
110141
+ };
110142
+ if (this.catalogueOpen) this.declaredIncomplete = true;
110143
+ const declare = {
110144
+ ...this.retiredMigrationIds.length === 0 ? widened ?? {} : {
110145
+ ...widened,
110146
+ retired: this.retiredMigrationIds
110147
+ },
110148
+ complete: !this.catalogueOpen
109116
110149
  };
109117
110150
  const api = this.ctx.api.migrations;
109118
- const report = await runAddonMigrations({
110151
+ const host = {
109119
110152
  declareOwner: (input) => api.declareOwner.mutate(input),
109120
110153
  startMigration: (input) => api.startMigration.mutate(input),
109121
110154
  finishMigration: (input) => api.finishMigration.mutate(input)
109122
- }, migrations, this.ctx.logger, phased);
110155
+ };
110156
+ const report = await runAddonMigrations(host, migrations, this.ctx.logger, declare);
110157
+ if (declare.complete === false && !this.catalogueOpen) await runAddonMigrations(host, [...new Map([...this.declaredAll, ...this.switchDeclared]).values()], this.ctx.logger, {
110158
+ ...this.retiredMigrationIds.length === 0 ? {} : { retired: this.retiredMigrationIds },
110159
+ only: [],
110160
+ complete: true
110161
+ });
110162
+ this.migrationWaits.record(report, [
110163
+ ...report.applied,
110164
+ ...report.failed,
110165
+ ...report.blocked,
110166
+ ...report.skipped
110167
+ ]);
110168
+ this.releaseBlockedMigrations([...this.migrationAppliedSeen]);
109123
110169
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
109124
110170
  await this.hydrateSwitches();
109125
110171
  await this.adoptUnrowed();
@@ -112472,6 +113518,16 @@ var BatteryStatusSchema = /* @__PURE__ */ object({
112472
113518
  */
112473
113519
  lastFullRefreshAt: /* @__PURE__ */ number().optional(),
112474
113520
  /**
113521
+ * The scheduled refresh's attempt bookkeeping for the window it last tried
113522
+ * (window index, attempts spent, ms epoch of the last attempt; `0` = none).
113523
+ * Persisted beside `lastFullRefreshAt` so a restart neither forgets a wake
113524
+ * the window already spent nor repeats it (#666). Written only by the
113525
+ * provider's refresh controller.
113526
+ */
113527
+ refreshAttemptWindow: /* @__PURE__ */ number().optional(),
113528
+ refreshAttempts: /* @__PURE__ */ number().optional(),
113529
+ refreshLastAttemptAt: /* @__PURE__ */ number().optional(),
113530
+ /**
112475
113531
  * True when the source is a BINARY low-battery indicator (HA
112476
113532
  * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
112477
113533
  * charge level — `level` is then a coarse stand-in (100 = normal,
@@ -114176,7 +115232,13 @@ listFaultTypes: /* @__PURE__ */ method(ListFaultTypesInputSchema, FaultTypesSche
114176
115232
  status: {
114177
115233
  schema: ErrorStatusSchema,
114178
115234
  kind: "push",
114179
- empty: ERROR_STATUS_COLD
115235
+ empty: ERROR_STATUS_COLD,
115236
+ fieldEnums: { code: {
115237
+ from: "method",
115238
+ method: "listFaultTypes",
115239
+ listKey: "types",
115240
+ valueKey: "code"
115241
+ } }
114180
115242
  },
114181
115243
  runtimeState: ErrorStatusSchema,
114182
115244
  /**
@@ -129838,6 +130900,24 @@ var IntercomFailureReport = class {
129838
130900
  /** The process-wide instance every camera in this addon notes into. */
129839
130901
  var intercomFailureReport = new IntercomFailureReport();
129840
130902
  //#endregion
130903
+ //#region src/stamp-current-features.ts
130904
+ /**
130905
+ * Stamp the camera's CURRENT feature list on every descriptor.
130906
+ *
130907
+ * A descriptor restored from the durable catalog slice carries the
130908
+ * `deviceFeatures` of whichever provider build wrote it (a pre-#459 build wrote
130909
+ * `battery-operated` without `sleeps`). Trusting that list made the broker open
130910
+ * a default prebuffer hold on a battery camera and keep it awake forever. The
130911
+ * features are a property of the camera NOW, never of the stored catalog, so a
130912
+ * stored list is never read.
130913
+ */
130914
+ function stampCurrentFeatures(descriptors, features) {
130915
+ return descriptors.map((d) => ({
130916
+ ...d,
130917
+ deviceFeatures: [...features]
130918
+ }));
130919
+ }
130920
+ //#endregion
129841
130921
  //#region src/baichuan-webhook-shared.ts
129842
130922
  /** The data-plane prefix this addon serves the camera push on: `/addon/<addonId>/webhook/<stableId>`. */
129843
130923
  var BAICHUAN_WEBHOOK_PREFIX = "webhook";
@@ -129991,6 +131071,12 @@ var BATTERY_REFRESH_MINUTES_KEY = "batteryRefreshMinutes";
129991
131071
  var BATTERY_REFRESH_TICK_MS = 6e4;
129992
131072
  /** The least time between two attempts in one window. */
129993
131073
  var RETRY_BACKOFF_MS = 10 * 6e4;
131074
+ /**
131075
+ * How old the last full refresh may grow while a stream is open before the
131076
+ * control burst runs under that stream anyway. A camera that streams 24/7
131077
+ * would otherwise never refresh battery, accessories or settings.
131078
+ */
131079
+ var STREAM_DEFER_MAX_AGE_MS = 240 * 6e4;
129994
131080
  /** The one refresh step whose failure does not hold the window open. */
129995
131081
  var SOFT_FAILURE_STEP = "snapshot";
129996
131082
  var MAX_WAKE_LEAD_MS = 5 * 6e4;
@@ -130040,12 +131126,48 @@ function decideBatteryRefresh(input) {
130040
131126
  };
130041
131127
  return { kind: "wake-then-refresh" };
130042
131128
  }
131129
+ /**
131130
+ * A FULL-slice write replaces the slice, so every writer that composes its own
131131
+ * value must carry the scheduled refresh's bookkeeping over from the slice it
131132
+ * replaces. Dropping it makes a restart read "never refreshed" and owe the
131133
+ * camera a wake (#666: the stamp read back `null` after any battery read that
131134
+ * followed it).
131135
+ */
131136
+ function carryRefreshBookkeeping(previous, next) {
131137
+ return {
131138
+ ...next,
131139
+ ...previous.lastFullRefreshAt !== void 0 ? { lastFullRefreshAt: previous.lastFullRefreshAt } : {},
131140
+ ...previous.refreshAttemptWindow !== void 0 ? { refreshAttemptWindow: previous.refreshAttemptWindow } : {},
131141
+ ...previous.refreshAttempts !== void 0 ? { refreshAttempts: previous.refreshAttempts } : {},
131142
+ ...previous.refreshLastAttemptAt !== void 0 ? { refreshLastAttemptAt: previous.refreshLastAttemptAt } : {}
131143
+ };
131144
+ }
131145
+ /** The ledger over the slice's flat fields; `write` receives the patch to persist. */
131146
+ function attemptLedgerOverSlice(readSlice, writeFields) {
131147
+ return {
131148
+ read: () => {
131149
+ const s = readSlice();
131150
+ if (typeof s.refreshAttemptWindow !== "number" || typeof s.refreshAttempts !== "number") return;
131151
+ return {
131152
+ window: s.refreshAttemptWindow,
131153
+ attempts: s.refreshAttempts,
131154
+ lastAttemptAt: s.refreshLastAttemptAt
131155
+ };
131156
+ },
131157
+ write: (r) => writeFields({
131158
+ refreshAttemptWindow: r.window,
131159
+ refreshAttempts: r.attempts,
131160
+ refreshLastAttemptAt: r.lastAttemptAt ?? 0
131161
+ })
131162
+ };
131163
+ }
130043
131164
  var BatteryHourlyRefresh = class {
130044
131165
  deps;
130045
131166
  inFlight = null;
130046
131167
  attemptWindow = Number.NEGATIVE_INFINITY;
130047
131168
  attempts = 0;
130048
131169
  lastAttemptAt;
131170
+ hydrated = false;
130049
131171
  constructor(deps) {
130050
131172
  this.deps = deps;
130051
131173
  }
@@ -130070,6 +131192,7 @@ var BatteryHourlyRefresh = class {
130070
131192
  const intervalMs = this.deps.intervalMs();
130071
131193
  const offsetMs = intervalMs > 0 ? staggerOffsetMs(this.deps.deviceId, intervalMs) : 0;
130072
131194
  const window = intervalMs > 0 ? windowIndex(nowMs, intervalMs, offsetMs) : 0;
131195
+ this.hydrateAttempts();
130073
131196
  if (window !== this.attemptWindow) {
130074
131197
  this.attemptWindow = window;
130075
131198
  this.attempts = 0;
@@ -130088,14 +131211,67 @@ var BatteryHourlyRefresh = class {
130088
131211
  this.logSkip(decision.reason, trigger);
130089
131212
  return false;
130090
131213
  }
131214
+ if (this.shouldDeferForStream()) {
131215
+ this.noteStreamDeferred(trigger);
131216
+ return false;
131217
+ }
131218
+ if (this.deps.isStreaming?.() === true) this.logDeferralBoundReached(trigger);
130091
131219
  this.attempts += 1;
130092
131220
  this.lastAttemptAt = nowMs;
131221
+ this.deps.attemptLedger?.write({
131222
+ window,
131223
+ attempts: this.attempts,
131224
+ lastAttemptAt: nowMs
131225
+ });
130093
131226
  const run = this.run(decision.kind, trigger).finally(() => {
130094
131227
  this.inFlight = null;
130095
131228
  });
130096
131229
  this.inFlight = run;
130097
131230
  return run;
130098
131231
  }
131232
+ /** Once, at the first decision: take the persisted bookkeeping of the window a restart interrupted. */
131233
+ hydrateAttempts() {
131234
+ if (this.hydrated) return;
131235
+ this.hydrated = true;
131236
+ const stored = this.deps.attemptLedger?.read();
131237
+ if (stored === void 0) return;
131238
+ this.attemptWindow = stored.window;
131239
+ this.attempts = stored.attempts;
131240
+ this.lastAttemptAt = typeof stored.lastAttemptAt === "number" && stored.lastAttemptAt > 0 ? stored.lastAttemptAt : void 0;
131241
+ }
131242
+ /**
131243
+ * A stream is open AND the last full refresh is younger than
131244
+ * {@link STREAM_DEFER_MAX_AGE_MS}: the control burst waits. Past that age (or
131245
+ * with no refresh on record) it runs under the stream — the deferral is bounded.
131246
+ */
131247
+ shouldDeferForStream() {
131248
+ if (this.deps.isStreaming?.() !== true) return false;
131249
+ const last = this.deps.lastFullRefreshAt();
131250
+ if (typeof last !== "number" || last <= 0) return false;
131251
+ return this.deps.now() - last < STREAM_DEFER_MAX_AGE_MS;
131252
+ }
131253
+ logDeferralBoundReached(what) {
131254
+ this.deps.logger.info("battery control burst: deferral bound reached — refreshing under an active stream", {
131255
+ tags: { deviceId: this.deps.deviceId },
131256
+ meta: {
131257
+ what,
131258
+ maxAgeMs: STREAM_DEFER_MAX_AGE_MS
131259
+ }
131260
+ });
131261
+ }
131262
+ streamDeferLoggedWindow = Number.NEGATIVE_INFINITY;
131263
+ /** Say once per window that a due control burst was held back for a stream. */
131264
+ noteStreamDeferred(what) {
131265
+ const intervalMs = this.deps.intervalMs();
131266
+ const offsetMs = intervalMs > 0 ? staggerOffsetMs(this.deps.deviceId, intervalMs) : 0;
131267
+ const window = intervalMs > 0 ? windowIndex(this.deps.now(), intervalMs, offsetMs) : 0;
131268
+ if (window === this.streamDeferLoggedWindow) return;
131269
+ this.streamDeferLoggedWindow = window;
131270
+ this.deps.logger.info("battery control burst deferred — a stream is active", {
131271
+ tags: { deviceId: this.deps.deviceId },
131272
+ meta: { what }
131273
+ });
131274
+ }
130099
131275
  async run(kind, trigger) {
130100
131276
  const { logger, deviceId } = this.deps;
130101
131277
  try {
@@ -132266,6 +133442,7 @@ async function connectReolinkHub(connection) {
132266
133442
  transport: connection.transport,
132267
133443
  ...connection.uid ? { uid: connection.uid } : {}
132268
133444
  });
133445
+ api.setGeneralSessionRecycling({ guard: () => true });
132269
133446
  await api.login();
132270
133447
  return api;
132271
133448
  }
@@ -132371,14 +133548,14 @@ function isSummarySourced(source) {
132371
133548
  function decideSleepCommit(input) {
132372
133549
  const { current, next, source, lastFirstHandCommitAt, nowMs, videoFlowing, wired } = input;
132373
133550
  if (current === next) return { kind: "unchanged" };
133551
+ if (next === true && wired) return {
133552
+ kind: "refused",
133553
+ reason: "wired",
133554
+ windowMs: 0,
133555
+ sinceLastChangeMs: nowMs - lastFirstHandCommitAt
133556
+ };
132374
133557
  if (next === true && isSecondHand(source)) {
132375
133558
  const sinceMs = nowMs - lastFirstHandCommitAt;
132376
- if (wired) return {
132377
- kind: "refused",
132378
- reason: "wired",
132379
- windowMs: 0,
132380
- sinceLastChangeMs: sinceMs
132381
- };
132382
133559
  if (videoFlowing) return {
132383
133560
  kind: "refused",
132384
133561
  reason: "video-flowing",
@@ -132410,6 +133587,49 @@ function decideSleepCommit(input) {
132410
133587
  };
132411
133588
  }
132412
133589
  //#endregion
133590
+ //#region src/login-deadline.ts
133591
+ /**
133592
+ * A login the camera abandons must not wedge the provider.
133593
+ *
133594
+ * `ensureApi` is single-flight: every caller joins the pending `loginPromise`.
133595
+ * A camera that accepts the connection and then never answers left that
133596
+ * promise pending forever, so every later demand joined a login that could
133597
+ * not finish and the provider stayed dark until a restart.
133598
+ */
133599
+ /** Longest a Baichuan login may take before it is abandoned (a battery wake included). */
133600
+ var LOGIN_DEADLINE_MS = 6e4;
133601
+ var LoginDeadlineError = class extends Error {
133602
+ deadlineMs;
133603
+ constructor(deadlineMs) {
133604
+ super(`Baichuan login did not finish within ${deadlineMs} ms`);
133605
+ this.deadlineMs = deadlineMs;
133606
+ this.name = "LoginDeadlineError";
133607
+ }
133608
+ };
133609
+ /**
133610
+ * Run `login`, bounded. On expiry `onExpire` closes the pending client, then
133611
+ * the call rejects with {@link LoginDeadlineError}; a late settle of `login` is
133612
+ * swallowed (the client it belonged to is closed).
133613
+ */
133614
+ async function loginWithin(login, deadlineMs, onExpire) {
133615
+ let timer;
133616
+ let didExpire = false;
133617
+ const expired = new Promise((_, reject) => {
133618
+ timer = setTimeout(() => {
133619
+ didExpire = true;
133620
+ Promise.resolve().then(onExpire).catch(() => void 0).then(() => reject(new LoginDeadlineError(deadlineMs)));
133621
+ }, deadlineMs);
133622
+ });
133623
+ const run = login();
133624
+ run.catch(() => void 0);
133625
+ try {
133626
+ await Promise.race([run, expired]);
133627
+ if (didExpire) throw new LoginDeadlineError(deadlineMs);
133628
+ } finally {
133629
+ if (timer !== void 0) clearTimeout(timer);
133630
+ }
133631
+ }
133632
+ //#endregion
132413
133633
  //#region src/session-limit.ts
132414
133634
  /**
132415
133635
  * How long the broker lets a Home Hub child's session run before it re-dials on
@@ -132423,15 +133643,25 @@ function decideSleepCommit(input) {
132423
133643
  */
132424
133644
  var HOME_HUB_SESSION_LIMIT_MS = 27 * 6e4;
132425
133645
  /**
133646
+ * The same cut on a STANDALONE battery camera: four consecutive live sessions
133647
+ * ended at 1799-1806 s (2026-11-23), so the firmware limits a session to about
133648
+ * 30 min there too. Declared two minutes under it so the broker's planned
133649
+ * re-dial wins the race against the camera's cut and the recording rolls over
133650
+ * at a time of our choosing, not as a hole.
133651
+ */
133652
+ var STANDALONE_BATTERY_SESSION_LIMIT_MS = 28 * 6e4;
133653
+ /**
132426
133654
  * Stamp the descriptors with the session limit the broker acts on. Only a
132427
- * battery child of a hub gets one: a standalone camera has no such cut, and
132428
- * declaring one there would re-dial a healthy stream for nothing.
133655
+ * battery camera gets one (a hub child at 27 min, a standalone one at 28 min):
133656
+ * a mains-powered camera or a wired hub child has no such cut, and declaring
133657
+ * one there would re-dial a healthy stream for nothing.
132429
133658
  */
132430
133659
  function withSessionLimit(descriptors, input) {
132431
- if (!input.isHubChild || !input.isBattery) return [...descriptors];
133660
+ if (!input.isBattery) return [...descriptors];
133661
+ const maxSessionMs = input.isHubChild ? HOME_HUB_SESSION_LIMIT_MS : STANDALONE_BATTERY_SESSION_LIMIT_MS;
132432
133662
  return descriptors.map((d) => ({
132433
133663
  ...d,
132434
- maxSessionMs: HOME_HUB_SESSION_LIMIT_MS
133664
+ maxSessionMs
132435
133665
  }));
132436
133666
  }
132437
133667
  //#endregion
@@ -132657,6 +133887,15 @@ var reolinkAccessoryBaseSchema = object({
132657
133887
  channel: number().int().nonnegative().default(0),
132658
133888
  kind: string()
132659
133889
  });
133890
+ /**
133891
+ * True when the parent is a battery camera that is asleep right now. The one
133892
+ * question every accessory probe / revalidation asks BEFORE it reaches
133893
+ * `ensureApi()`: on a sleeping battery camera the login itself is the wake.
133894
+ * It reads the parent's own `isBattery` + `sleeping` (no second copy).
133895
+ */
133896
+ function isParentSleepingBattery(parent) {
133897
+ return parent.isBatteryCam?.() === true && parent.isSleeping?.() === true;
133898
+ }
132660
133899
  //#endregion
132661
133900
  //#region src/accessories/floodlight.ts
132662
133901
  /**
@@ -132706,13 +133945,6 @@ var FloodlightAccessory = class extends BaseDevice {
132706
133945
  * /setMotionTrigger. Read by the parent's align loop via the
132707
133946
  * `ReolinkAccessoryRef.isInCooldown` impl below. */
132708
133947
  lastSetAtMs = 0;
132709
- /** Becomes `true` once both `refreshLightFromFirmware` and
132710
- * `refreshMotionTriggerFromFirmware` have completed at least one
132711
- * successful round-trip. Used by `onProbe` to decide whether the
132712
- * boot-time sleep-gate should force a wake (no cached state) or
132713
- * skip (already-have-state path). Mirrors the Reolink mobile app's
132714
- * one-shot wake-and-fetch on launch. */
132715
- hasFetchedFromFirmware = false;
132716
133948
  constructor(ctx, parent) {
132717
133949
  super(ctx, floodlightAccessorySchema, {
132718
133950
  type: DeviceType.Light,
@@ -132772,7 +134004,6 @@ var FloodlightAccessory = class extends BaseDevice {
132772
134004
  level: brightness,
132773
134005
  lastChangedAt: ts
132774
134006
  });
132775
- this.hasFetchedFromFirmware = true;
132776
134007
  } catch (err) {
132777
134008
  this.ctx.logger.warn("floodlight refresh FAILED — slice stays at cold-start seed", {
132778
134009
  tags: { deviceId: this.id },
@@ -132784,46 +134015,29 @@ var FloodlightAccessory = class extends BaseDevice {
132784
134015
  }
132785
134016
  }
132786
134017
  /**
132787
- * Kernel-driven probe (Phase 4). Runs on every device construction
132788
- * + addon restart. Pulls the actual on/off + brightness +
132789
- * motion-trigger state from the camera so the slices reflect
132790
- * firmware truth instead of the conservative cold-start seeds
132791
- * written in `registerSwitchCap` / `registerBrightnessCap` /
132792
- * `registerMotionTriggerCap`.
132793
- *
132794
- * Sleeping battery cam:
132795
- * 1. **First-time probe (no cached state yet)** — force a one-shot
132796
- * wake + fetch so the operator sees a populated UI at launch.
132797
- * Mirrors the Reolink mobile app: at app launch it wakes the
132798
- * cam once to fetch initial state. Without this, an aggressive
132799
- * sleep timeout (~14s) can return the cam to sleep before the
132800
- * kernel finishes its initial probe pass — the retry chain
132801
- * exhausts and the slices never populate.
132802
- * 2. **Subsequent probes (slices already populated)** — skip. A
132803
- * poll on a sleeping camera returns 400 and drains the
132804
- * battery. The parent's `alignAuxDevicesState('wake')` runs
132805
- * on the next wake transition (simpleEvent push or sleep-poll
132806
- * backstop) and refreshes both slices then.
134018
+ * Kernel-driven probe. On a sleeping battery camera it does nothing: no
134019
+ * login, no wake (the login IS the wake, #666), not even for an accessory
134020
+ * with no cached state. The persisted slices stand in, and the parent's
134021
+ * `alignAuxDevicesState('wake')` (the wake transition, or the scheduled
134022
+ * window's authorised wake) refreshes this accessory the next time the
134023
+ * camera is up for its own reasons.
132807
134024
  */
132808
134025
  async onProbe() {
132809
- if (this.parent.isBatteryCam?.() === true && this.parent.isSleeping?.() === true) {
132810
- if (this.hasFetchedFromFirmware) {
132811
- this.ctx.logger.debug("floodlight onProbe skipped — parent battery cam is sleeping (have cached state)", { tags: { deviceId: this.id } });
132812
- return;
132813
- }
132814
- this.ctx.logger.info("floodlight onProbe forcing wake — initial probe with no cached state", { tags: { deviceId: this.id } });
132815
- try {
132816
- await (await this.api).wakeUp(this.channel, { waitAfterWakeMs: 2e3 });
132817
- await sleep(1e3);
132818
- } catch (err) {
132819
- this.ctx.logger.warn("floodlight wake before initial probe failed — proceeding anyway", {
132820
- tags: { deviceId: this.id },
132821
- meta: { error: err instanceof Error ? err.message : String(err) }
132822
- });
132823
- }
134026
+ if (isParentSleepingBattery(this.parent)) {
134027
+ this.ctx.logger.info("floodlight onProbe skipped — parent battery cam is sleeping (serving persisted state)", { tags: { deviceId: this.id } });
134028
+ return;
132824
134029
  }
132825
134030
  await Promise.all([this.refreshLightFromFirmware(), this.refreshMotionTriggerFromFirmware()]);
132826
134031
  }
134032
+ /** The cap read's revalidation: never logs in to a sleeping battery camera
134033
+ * (#666) — the read is served from the persisted slice. */
134034
+ async revalidateMotionTrigger() {
134035
+ if (isParentSleepingBattery(this.parent)) {
134036
+ this.ctx.logger.debug("floodlight motion-trigger revalidation skipped — parent battery cam is sleeping", { tags: { deviceId: this.id } });
134037
+ return;
134038
+ }
134039
+ await this.refreshMotionTriggerFromFirmware();
134040
+ }
132827
134041
  /** Refresh motion-trigger from firmware and write the slice. Also
132828
134042
  * mirrors the camera-current `duration` + `detectType` into config
132829
134043
  * so the Settings form shows firmware truth instead of stale
@@ -132845,7 +134059,6 @@ var FloodlightAccessory = class extends BaseDevice {
132845
134059
  lastChangedAt,
132846
134060
  lastFetchedAt: Date.now()
132847
134061
  });
132848
- this.hasFetchedFromFirmware = true;
132849
134062
  const patch = {};
132850
134063
  if (typeof result?.duration === "number" && result.duration > 0) patch["motionLightDurationS"] = result.duration;
132851
134064
  if (typeof result?.detectType === "string") {
@@ -132941,7 +134154,7 @@ var FloodlightAccessory = class extends BaseDevice {
132941
134154
  runtimeState: this.runtimeState,
132942
134155
  cap: motionTriggerCapability,
132943
134156
  ownDeviceId: this.id,
132944
- refresh: () => this.refreshMotionTriggerFromFirmware(),
134157
+ refresh: () => this.revalidateMotionTrigger(),
132945
134158
  staleMs: STALE_MS$1,
132946
134159
  empty: () => ({
132947
134160
  enabled: false,
@@ -133092,12 +134305,6 @@ var PirAccessory = class extends BaseDevice {
133092
134305
  /** Nothing reported: the kernel derives this device's features from its bound caps (#459). */
133093
134306
  features = [];
133094
134307
  lastSetAtMs = 0;
133095
- /** Becomes `true` after the first successful `refreshFromFirmware`
133096
- * round-trip. Used by `onProbe` to decide whether the boot-time
133097
- * sleep-gate should force a wake (no cached state) or skip
133098
- * (already-have-state path). Mirrors the Reolink mobile app's
133099
- * one-shot wake-and-fetch on launch. */
133100
- hasFetchedFromFirmware = false;
133101
134308
  constructor(ctx, parent) {
133102
134309
  super(ctx, pirAccessorySchema, {
133103
134310
  type: DeviceType.Switch,
@@ -133173,7 +134380,6 @@ var PirAccessory = class extends BaseDevice {
133173
134380
  }
133174
134381
  });
133175
134382
  this.refreshSwitchFromExternal(state);
133176
- this.hasFetchedFromFirmware = true;
133177
134383
  } catch (err) {
133178
134384
  this.ctx.logger.warn("pir refresh FAILED — slice stays at cold-start seed", {
133179
134385
  tags: { deviceId: this.id },
@@ -133185,45 +134391,17 @@ var PirAccessory = class extends BaseDevice {
133185
134391
  }
133186
134392
  }
133187
134393
  /**
133188
- * Kernel-driven probe — runs at device construction (addon boot,
133189
- * device add). For battery cams currently asleep we have two
133190
- * cases:
133191
- *
133192
- * 1. **First-time probe (no cached state yet)** — force a one-shot
133193
- * wake + fetch. Mirrors the Reolink mobile app's launch
133194
- * behaviour: the app wakes the cam once at startup so the
133195
- * operator sees a populated UI. Without this, an aggressive
133196
- * sleep timeout (~14s after boot on Argus / battery doorbell
133197
- * firmwares) can put the cam back to sleep before the
133198
- * kernel's initial probe pass completes — the slice never
133199
- * gets populated, the kernel's retry chain exhausts after 5
133200
- * attempts, and the operator sees an empty PIR switch state
133201
- * until they manually wake the cam.
133202
- * 2. **Subsequent probes (slice already populated)** — skip the
133203
- * fetch. A Baichuan poll on a sleeping camera returns 400,
133204
- * drains the battery, and would clobber the cached value
133205
- * anyway. The parent's `alignAuxDevicesState('wake')` path
133206
- * (simpleEvent `awake` push or sleep-poll backstop)
133207
- * refreshes us when the cam wakes naturally.
133208
- *
133209
- * Wired cams + already-awake battery cams take the normal path.
134394
+ * Kernel-driven probe. On a sleeping battery camera it does nothing: no
134395
+ * login, no wake (the login IS the wake, #666), not even for an accessory
134396
+ * with no cached state. The persisted slices stand in, and the parent's
134397
+ * `alignAuxDevicesState('wake')` (the wake transition, or the scheduled
134398
+ * window's authorised wake) refreshes this accessory the next time the
134399
+ * camera is up for its own reasons.
133210
134400
  */
133211
134401
  async onProbe() {
133212
- if (this.parent.isBatteryCam?.() === true && this.parent.isSleeping?.() === true) {
133213
- if (this.hasFetchedFromFirmware) {
133214
- this.ctx.logger.debug("pir onProbe skipped — parent battery cam is sleeping (have cached state)", { tags: { deviceId: this.id } });
133215
- return;
133216
- }
133217
- this.ctx.logger.info("pir onProbe forcing wake — initial probe with no cached state", { tags: { deviceId: this.id } });
133218
- try {
133219
- await (await this.api).wakeUp(this.channel, { waitAfterWakeMs: 2e3 });
133220
- await sleep(1e3);
133221
- } catch (err) {
133222
- this.ctx.logger.warn("pir wake before initial probe failed — proceeding anyway", {
133223
- tags: { deviceId: this.id },
133224
- meta: { error: err instanceof Error ? err.message : String(err) }
133225
- });
133226
- }
134402
+ if (isParentSleepingBattery(this.parent)) {
134403
+ this.ctx.logger.info("pir onProbe skipped — parent battery cam is sleeping (serving persisted state)", { tags: { deviceId: this.id } });
134404
+ return;
133227
134405
  }
133228
134406
  await this.refreshFromFirmware();
133229
134407
  }
@@ -133451,12 +134629,6 @@ var SirenAccessory = class extends BaseDevice {
133451
134629
  lastSetAtMs = 0;
133452
134630
  /** Clears the `siren` slice when a timed activation runs out. */
133453
134631
  sirenTimer = null;
133454
- /** Becomes `true` after the first successful
133455
- * `refreshMotionTriggerFromFirmware` round-trip. Used by `onProbe`
133456
- * to decide whether the boot-time sleep-gate should force a wake
133457
- * (no cached state) or skip (already-have-state path). Mirrors the
133458
- * Reolink mobile app's one-shot wake-and-fetch on launch. */
133459
- hasFetchedFromFirmware = false;
133460
134632
  constructor(ctx, parent) {
133461
134633
  super(ctx, sirenAccessorySchema, {
133462
134634
  type: DeviceType.Siren,
@@ -133493,42 +134665,26 @@ var SirenAccessory = class extends BaseDevice {
133493
134665
  };
133494
134666
  }
133495
134667
  /**
133496
- * Kernel-driven probe (Phase 4). Runs on every device construction
133497
- * + addon restart. Pulls the actual motion-trigger enable state
133498
- * from the camera so the slice reflects firmware truth. The switch
133499
- * (manual fire) cap is intentionally NOT refreshed — Reolink's
133500
- * `getSiren` returns OFF as soon as the audio task ends.
133501
- *
133502
- * Sleeping battery cam:
133503
- * 1. **First-time probe (no cached state yet)** — force a one-shot
133504
- * wake + fetch so the operator sees a populated UI at launch.
133505
- * Mirrors the Reolink mobile app: at app launch it wakes the
133506
- * cam once to fetch initial state. Without this, an aggressive
133507
- * sleep timeout (~14s) can return the cam to sleep before the
133508
- * kernel finishes its initial probe pass — the retry chain
133509
- * exhausts and the slice never populates.
133510
- * 2. **Subsequent probes (slice already populated)** — skip. A
133511
- * poll on a sleeping camera returns 400 and drains the
133512
- * battery. The parent's `alignAuxDevicesState('wake')` path
133513
- * (simpleEvent `awake` push or sleep-poll backstop) refreshes
133514
- * us when the cam wakes naturally.
134668
+ * Kernel-driven probe. On a sleeping battery camera it does nothing: no
134669
+ * login, no wake (the login IS the wake, #666), not even for an accessory
134670
+ * with no cached state. The persisted slices stand in, and the parent's
134671
+ * `alignAuxDevicesState('wake')` (the wake transition, or the scheduled
134672
+ * window's authorised wake) refreshes this accessory the next time the
134673
+ * camera is up for its own reasons.
133515
134674
  */
133516
134675
  async onProbe() {
133517
- if (this.parent.isBatteryCam?.() === true && this.parent.isSleeping?.() === true) {
133518
- if (this.hasFetchedFromFirmware) {
133519
- this.ctx.logger.debug("siren onProbe skipped — parent battery cam is sleeping (have cached state)", { tags: { deviceId: this.id } });
133520
- return;
133521
- }
133522
- this.ctx.logger.info("siren onProbe forcing wake — initial probe with no cached state", { tags: { deviceId: this.id } });
133523
- try {
133524
- await (await this.api).wakeUp(this.channel, { waitAfterWakeMs: 2e3 });
133525
- await sleep(1e3);
133526
- } catch (err) {
133527
- this.ctx.logger.warn("siren wake before initial probe failed — proceeding anyway", {
133528
- tags: { deviceId: this.id },
133529
- meta: { error: err instanceof Error ? err.message : String(err) }
133530
- });
133531
- }
134676
+ if (isParentSleepingBattery(this.parent)) {
134677
+ this.ctx.logger.info("siren onProbe skipped — parent battery cam is sleeping (serving persisted state)", { tags: { deviceId: this.id } });
134678
+ return;
134679
+ }
134680
+ await this.refreshMotionTriggerFromFirmware();
134681
+ }
134682
+ /** The cap read's revalidation: never logs in to a sleeping battery camera
134683
+ * (#666) — the read is served from the persisted slice. */
134684
+ async revalidateMotionTrigger() {
134685
+ if (isParentSleepingBattery(this.parent)) {
134686
+ this.ctx.logger.debug("siren motion-trigger revalidation skipped — parent battery cam is sleeping", { tags: { deviceId: this.id } });
134687
+ return;
133532
134688
  }
133533
134689
  await this.refreshMotionTriggerFromFirmware();
133534
134690
  }
@@ -133544,7 +134700,6 @@ var SirenAccessory = class extends BaseDevice {
133544
134700
  lastChangedAt,
133545
134701
  lastFetchedAt: Date.now()
133546
134702
  });
133547
- this.hasFetchedFromFirmware = true;
133548
134703
  const items = audioTask?.typeScheduleList?.item ?? [];
133549
134704
  if (items.length > 0) {
133550
134705
  const recovered = recoverSirenDetectTypeFromItems(items);
@@ -133773,7 +134928,7 @@ var SirenAccessory = class extends BaseDevice {
133773
134928
  runtimeState: this.runtimeState,
133774
134929
  cap: motionTriggerCapability,
133775
134930
  ownDeviceId: this.id,
133776
- refresh: () => this.refreshMotionTriggerFromFirmware(),
134931
+ refresh: () => this.revalidateMotionTrigger(),
133777
134932
  staleMs: STALE_MS,
133778
134933
  empty: () => ({
133779
134934
  enabled: false,
@@ -134097,17 +135252,41 @@ function effectiveProbeFlags(sliceProbed, sliceFlags, deviceCache) {
134097
135252
  ...resolveAccessoryProbeFlags(false, {}, deviceCache)
134098
135253
  };
134099
135254
  }
135255
+ function abilityReadQuality(debug) {
135256
+ return debug?.abilitiesAvailable === true && debug.supportAvailable === true ? "full" : "partial";
135257
+ }
134100
135258
  /**
134101
- * The typed answer for `getAccessoryChildren()`. A probe that completed THIS
134102
- * session is a definitive read (`complete`) even while the parent is asleep
134103
- * or offline, so the kernel's reconcile can retire a child whose flag is now
134104
- * false (it still needs a second agreeing probe, D49). Flags restored from
134105
- * `deviceCache` alone, or no probe at all, are `unknown`: they spawn but
135259
+ * Fold one ability read into the flags already known. A `full` read is
135260
+ * authoritative, `false` included. A `partial` read is not evidence of
135261
+ * absence (D49): it may add a flag it positively saw, never retract one —
135262
+ * two degraded probes in a row on camera 3628 pruned its Siren child and the
135263
+ * next full probe re-created it under a new id. Returns a new object.
135264
+ */
135265
+ function mergeAbilityRead(previous, read, quality) {
135266
+ const taken = {};
135267
+ for (const key of FLAG_KEYS) {
135268
+ const value = read[key];
135269
+ if (value === void 0) continue;
135270
+ if (quality === "full" || value) taken[key] = value;
135271
+ }
135272
+ return {
135273
+ ...previous,
135274
+ ...taken
135275
+ };
135276
+ }
135277
+ /**
135278
+ * The typed answer for `getAccessoryChildren()`. A FULL ability read that
135279
+ * landed THIS session is a definitive read (`complete`) even while the parent
135280
+ * is asleep or offline, so the kernel's reconcile can retire a child whose
135281
+ * flag is now false (it still needs a second agreeing probe, D49). Flags
135282
+ * restored from `deviceCache` alone, a slice rehydrated from an earlier
135283
+ * session, partial reads, or no probe at all, are `unknown`: they spawn but
134106
135284
  * never prune. A legacy bare array was `unknown` whenever the parent was
134107
135285
  * offline, which is how a ghost Floodlight outlived `hasFloodlight:false`.
134108
135286
  */
134109
- function accessoryChildrenAnswerFor(sliceProbed, sliceFlags, specs) {
135287
+ function accessoryChildrenAnswerFor(sliceProbed, sliceFlags, specs, fullReadThisSession) {
134110
135288
  if (!sliceProbed) return accessoryChildrenUnknown("no probe completed this session", specs);
135289
+ if (!fullReadThisSession) return accessoryChildrenUnknown("no full ability read this session", specs);
134111
135290
  if (!ACCESSORY_FLAGS.some(([flag]) => typeof sliceFlags[flag] === "boolean")) return accessoryChildrenUnknown("probe carried no ability flags", specs);
134112
135291
  return {
134113
135292
  kind: "complete",
@@ -135431,8 +136610,17 @@ function createKeepAwakeLoop(deps) {
135431
136610
  let handle = null;
135432
136611
  let failing = false;
135433
136612
  const tick = () => {
136613
+ if (deps.videoFlowing?.() === true) {
136614
+ try {
136615
+ deps.onSkip?.();
136616
+ } catch {}
136617
+ return;
136618
+ }
135434
136619
  deps.wake().then(() => {
135435
136620
  failing = false;
136621
+ try {
136622
+ deps.onSuccess?.();
136623
+ } catch {}
135436
136624
  }).catch((err) => {
135437
136625
  const first = !failing;
135438
136626
  failing = true;
@@ -136347,6 +137535,10 @@ function coerceNumber(value) {
136347
137535
  }
136348
137536
  return null;
136349
137537
  }
137538
+ /** One successful wake in this many is logged at debug. */
137539
+ var KEEP_AWAKE_SUCCESS_LOG_EVERY = 15;
137540
+ /** A joiner of a materialize run older than this is logged (a stuck run reads as silence otherwise). */
137541
+ var MATERIALIZE_JOIN_LOG_AFTER_MS = 2e4;
136350
137542
  /**
136351
137543
  * Baichuan's native PTZ speed scale is 1..63; `runPtz` maps the cap's
136352
137544
  * normalized 0..1 onto it. Named because the autotrack loop has to know the
@@ -136519,6 +137711,9 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
136519
137711
  }
136520
137712
  /** Lazy-connected Baichuan API. Spans the lifetime of every active stream. */
136521
137713
  api = null;
137714
+ /** Why the previous Baichuan session ended; named on the next login's log line. */
137715
+ lastSessionDropReason = null;
137716
+ loginCount = 0;
136522
137717
  /**
136523
137718
  * Stable bound handler for `api.onSimpleEvent` — created ONCE in
136524
137719
  * the class so every `onSimpleEvent` / `offSimpleEvent` call uses
@@ -136618,16 +137813,120 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
136618
137813
  tags: { deviceId: this.id },
136619
137814
  meta: { activeStreams }
136620
137815
  }),
137816
+ onSuccess: () => this.noteKeepAwakeResult(true, null),
137817
+ videoFlowing: () => Date.now() - this.lastVideoFlowAt < KEEP_AWAKE_INTERVAL_MS,
137818
+ onSkip: () => this.noteKeepAwakeSkipped(),
136621
137819
  onFailure: (err, first) => {
137820
+ const error = err instanceof Error ? err.message : String(err);
136622
137821
  (first ? this.ctx.logger.info.bind(this.ctx.logger) : this.ctx.logger.debug.bind(this.ctx.logger))("keep-awake: wake failed", {
136623
137822
  tags: { deviceId: this.id },
136624
- meta: { error: err instanceof Error ? err.message : String(err) }
137823
+ meta: { error }
136625
137824
  });
137825
+ this.noteKeepAwakeResult(false, error);
136626
137826
  }
136627
137827
  });
137828
+ /** Wake counters for the current hour, plus the last broker packet count per stream. */
137829
+ keepAwakeStats = {
137830
+ windowStartedAt: 0,
137831
+ issued: 0,
137832
+ succeeded: 0,
137833
+ failed: 0,
137834
+ skipped: 0
137835
+ };
137836
+ keepAwakePacketCount = /* @__PURE__ */ new Map();
137837
+ /** A tick skipped because video was flowing: counted, never logged per tick. */
137838
+ noteKeepAwakeSkipped() {
137839
+ const stats = this.keepAwakeStats;
137840
+ if (stats.windowStartedAt === 0) stats.windowStartedAt = Date.now();
137841
+ stats.skipped += 1;
137842
+ this.flushKeepAwakeSummary(Date.now());
137843
+ }
137844
+ /**
137845
+ * Make the keep-awake loop observable: a sampled debug line for successes, an
137846
+ * hourly info summary, and — on a failure — whether the broker is still
137847
+ * receiving video (a failed wake with flowing video is not a dead camera).
137848
+ */
137849
+ noteKeepAwakeResult(ok, error) {
137850
+ const now = Date.now();
137851
+ const stats = this.keepAwakeStats;
137852
+ if (stats.windowStartedAt === 0) stats.windowStartedAt = now;
137853
+ stats.issued += 1;
137854
+ if (ok) stats.succeeded += 1;
137855
+ else stats.failed += 1;
137856
+ if (ok && stats.succeeded % KEEP_AWAKE_SUCCESS_LOG_EVERY === 1) this.ctx.logger.debug("keep-awake: wake ok", {
137857
+ tags: { deviceId: this.id },
137858
+ meta: {
137859
+ succeeded: stats.succeeded,
137860
+ issued: stats.issued,
137861
+ sampledEvery: KEEP_AWAKE_SUCCESS_LOG_EVERY
137862
+ }
137863
+ });
137864
+ this.flushKeepAwakeSummary(now);
137865
+ if (!ok) this.logVideoFlowAfterWakeFailure(error ?? "unknown");
137866
+ }
137867
+ /** The hourly info summary; resets the window. */
137868
+ flushKeepAwakeSummary(now) {
137869
+ const stats = this.keepAwakeStats;
137870
+ if (now - stats.windowStartedAt < 60 * 6e4) return;
137871
+ this.ctx.logger.info("keep-awake: hourly summary", {
137872
+ tags: { deviceId: this.id },
137873
+ meta: {
137874
+ issued: stats.issued,
137875
+ succeeded: stats.succeeded,
137876
+ failed: stats.failed,
137877
+ skippedVideoFlowing: stats.skipped,
137878
+ windowMs: now - stats.windowStartedAt
137879
+ }
137880
+ });
137881
+ this.keepAwakeStats = {
137882
+ windowStartedAt: now,
137883
+ issued: 0,
137884
+ succeeded: 0,
137885
+ failed: 0,
137886
+ skipped: 0
137887
+ };
137888
+ }
137889
+ async logVideoFlowAfterWakeFailure(error) {
137890
+ for (const camStreamId of [...this.active.keys()]) try {
137891
+ const stats = await this.ctx.api.streamBroker.getBrokerStats.query({ brokerId: `${this.id}/${camStreamId}` });
137892
+ const previous = this.keepAwakePacketCount.get(camStreamId);
137893
+ this.keepAwakePacketCount.set(camStreamId, stats.packetCount);
137894
+ if (previous !== void 0 ? stats.packetCount > previous : stats.inputFps > 0) this.ctx.logger.info("keep-awake: wake failed but the broker still receives video", {
137895
+ tags: {
137896
+ deviceId: this.id,
137897
+ camStreamId
137898
+ },
137899
+ meta: {
137900
+ error,
137901
+ inputFps: stats.inputFps,
137902
+ packetCount: stats.packetCount,
137903
+ packetsSinceLastFailedWake: previous === void 0 ? null : stats.packetCount - previous,
137904
+ brokerStatus: stats.status
137905
+ }
137906
+ });
137907
+ } catch (err) {
137908
+ this.ctx.logger.debug("keep-awake: broker stats unavailable for the video-flow check", {
137909
+ tags: {
137910
+ deviceId: this.id,
137911
+ camStreamId
137912
+ },
137913
+ meta: { error: err instanceof Error ? err.message : String(err) }
137914
+ });
137915
+ }
137916
+ }
136628
137917
  syncKeepAwake() {
136629
137918
  this.keepAwake.sync(this.active.size);
136630
137919
  }
137920
+ /**
137921
+ * A broker stream of this camera is open (a listening rfc4571 server in
137922
+ * `this.active`) — in-memory only, never a read (D49). The scheduled battery
137923
+ * refresh and the wake warm-up use it to keep their control burst off a
137924
+ * session that is carrying video: the firmware pauses video while the
137925
+ * control channel is busy.
137926
+ */
137927
+ hasActiveStream() {
137928
+ return this.active.size > 0;
137929
+ }
136631
137930
  /** Login lock — concurrent demand events must not race the login flow. */
136632
137931
  loginPromise = null;
136633
137932
  /**
@@ -136716,6 +138015,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
136716
138015
  batteryUpdateTimer = null;
136717
138016
  /** Set by `removeDevice`: nothing may re-arm a timer on a removed camera. */
136718
138017
  removed = false;
138018
+ /**
138019
+ * True once a FULL ability read (SupportInfo and AbilityInfo both answered)
138020
+ * landed this session. Until then the accessory answer is `unknown` and can
138021
+ * never prune a child: a rehydrated slice or a partial read is not a list
138022
+ * (D49). Read defensively — the base constructor may ask before field init.
138023
+ */
138024
+ fullAbilityReadThisSession = false;
136719
138025
  /** Single-flight gate so two interval fires can't overlap. */
136720
138026
  /** Aux accessory references registered by spawned children
136721
138027
  * (siren / floodlight / pir). The parent's centralised align
@@ -137355,9 +138661,18 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137355
138661
  } catch (err) {
137356
138662
  this.ctx.logger.debug("reolink deviceCache snapshot persist failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
137357
138663
  }
137358
- if (slices === void 0 && this.isBattery && this.isEmailPushEligible) await this.refreshCameraEmailConfig().catch((err) => {
137359
- this.ctx.logger.debug("reolink email config probe failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
137360
- });
138664
+ if (slices === void 0 && this.isBattery && this.isEmailPushEligible) {
138665
+ if (this.sleeping) {
138666
+ this.ctx.logger.info("reolink email config read skipped — the camera fell asleep during the refresh", {
138667
+ tags: { deviceId: this.id },
138668
+ meta: { reason }
138669
+ });
138670
+ return;
138671
+ }
138672
+ await this.refreshCameraEmailConfig().catch((err) => {
138673
+ this.ctx.logger.debug("reolink email config probe failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
138674
+ });
138675
+ }
137361
138676
  }
137362
138677
  /**
137363
138678
  * Admin-only raw-read debug surface (D346): return the library's response
@@ -137471,7 +138786,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137471
138786
  * leave the catalog stale rather than stamping it fresh.
137472
138787
  */
137473
138788
  async wakeForClipCatalogRefresh() {
137474
- if (!await this.wakeIfSleeping()) throw new Error(`ReolinkCamera ${this.id}: the authorised clip-refresh wake did not bring the camera up`);
138789
+ if (!await this.wakeIfSleeping("clip-catalog-refresh")) throw new Error(`ReolinkCamera ${this.id}: the authorised clip-refresh wake did not bring the camera up`);
137475
138790
  }
137476
138791
  /**
137477
138792
  * Wake this camera because the OPERATOR asked for one of its clips — a
@@ -137481,7 +138796,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137481
138796
  * so the service can refuse `wake-timeout` by name.
137482
138797
  */
137483
138798
  async wakeForClipRead(timeoutMs) {
137484
- return this.wakeIfSleeping(timeoutMs);
138799
+ return this.wakeIfSleeping("clip-read", timeoutMs);
137485
138800
  }
137486
138801
  clipTimeZoneWarned = { done: false };
137487
138802
  getClipDeviceRef() {
@@ -137535,7 +138850,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137535
138850
  if (kinds.includes(AccessoryKind.Siren)) push(AccessoryKind.Siren, DeviceType.Siren, ACCESSORY_LABEL[AccessoryKind.Siren]);
137536
138851
  if (kinds.includes(AccessoryKind.Floodlight)) push(AccessoryKind.Floodlight, DeviceType.Light, ACCESSORY_LABEL[AccessoryKind.Floodlight]);
137537
138852
  if (kinds.includes(AccessoryKind.PirSensor)) push(AccessoryKind.PirSensor, DeviceType.Switch, ACCESSORY_LABEL[AccessoryKind.PirSensor]);
137538
- return accessoryChildrenAnswerFor(this.hasProbed(), super.getProbeFlags(), out);
138853
+ return accessoryChildrenAnswerFor(this.hasProbed(), super.getProbeFlags(), out, this.fullAbilityReadThisSession === true);
137539
138854
  }
137540
138855
  /**
137541
138856
  * Resolver injected by the provider (`setEmailPushParamsResolver`) so
@@ -137571,7 +138886,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137571
138886
  * camera. No-op for non-battery or already-awake cams. Best-effort:
137572
138887
  * returns whether the camera is (now) reachable/awake.
137573
138888
  */
137574
- async wakeIfSleeping(timeoutMs = 15e3) {
138889
+ async wakeIfSleeping(caller, timeoutMs = 15e3) {
137575
138890
  if (!this.isBattery || !this.sleeping) return true;
137576
138891
  let api;
137577
138892
  try {
@@ -137582,7 +138897,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137582
138897
  this.markWakeIssued();
137583
138898
  this.ctx.logger.info("proactive action: waking sleeping battery cam", {
137584
138899
  tags: { deviceId: this.id },
137585
- meta: { timeoutMs }
138900
+ meta: {
138901
+ timeoutMs,
138902
+ caller
138903
+ }
137586
138904
  });
137587
138905
  this.ctx.eventBus.emit(createEvent(EventCategory.BatteryOnWakeStarted, this.eventSource(), { deviceId: this.id }));
137588
138906
  const channel = this.getChannel();
@@ -137602,7 +138920,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137602
138920
  } catch (err) {
137603
138921
  this.ctx.logger.warn("proactive action: wake did not complete in time", {
137604
138922
  tags: { deviceId: this.id },
137605
- meta: { error: err instanceof Error ? err.message : String(err) }
138923
+ meta: {
138924
+ caller,
138925
+ error: err instanceof Error ? err.message : String(err)
138926
+ }
137606
138927
  });
137607
138928
  return false;
137608
138929
  }
@@ -137651,7 +138972,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137651
138972
  "vehicle"
137652
138973
  ];
137653
138974
  const attachmentType = this.config.get("emailPushAttachment") ?? "picture";
137654
- await this.wakeIfSleeping();
138975
+ await this.wakeIfSleeping("auto-configure-email-push");
137655
138976
  const api = await this.ensureApi();
137656
138977
  this.ctx.logger.info("email-push: auto-configuring camera", {
137657
138978
  tags: { deviceId: this.id },
@@ -137701,7 +139022,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137701
139022
  if (!this.baichuanWebhookParamsResolver) throw userError("reolink.webhook-not-wired", void 0, "HaCfg Webhook Server is not wired — restart the Reolink addon");
137702
139023
  const params = await this.baichuanWebhookParamsResolver();
137703
139024
  if (!params) throw new Error("The HaCfg webhook cannot be armed for this camera (it is not a standalone battery camera).");
137704
- await this.wakeIfSleeping();
139025
+ await this.wakeIfSleeping("auto-configure-baichuan-webhook");
137705
139026
  const api = await this.ensureApi();
137706
139027
  const supported = await api.probeBaichuanWebhookSupport();
137707
139028
  this.baichuanWebhookSupportedCached = supported;
@@ -137800,7 +139121,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137800
139121
  * Push tab read.
137801
139122
  */
137802
139123
  async refreshCameraEmailConfig() {
137803
- await this.wakeIfSleeping();
139124
+ await this.wakeIfSleeping("refresh-camera-email-config");
137804
139125
  const api = await this.ensureApi();
137805
139126
  const channel = this.getChannel();
137806
139127
  const [email, task] = await Promise.all([api.getEmail(), api.getEmailTask(channel).catch(() => null)]);
@@ -137917,7 +139238,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137917
139238
  await this.autoConfigureBaichuanWebhook();
137918
139239
  });
137919
139240
  this.registerDeviceAction("refresh-settings", deviceCustomAction(unknown(), RefreshSettingsResultSchema, { kind: "mutation" }), async () => {
137920
- const awake = await this.wakeIfSleeping();
139241
+ const awake = await this.wakeIfSleeping("operator-rehydrate");
137921
139242
  const [snapshot, warm] = await Promise.allSettled([this.refreshParentSettingsSnapshot(void 0, "operator"), this.warmCapSlicesOnWake({ force: true })]);
137922
139243
  const warmed = warm.status === "fulfilled" ? warm.value.warmed : 0;
137923
139244
  const capsTotal = this.capWarmers.size;
@@ -137947,6 +139268,12 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137947
139268
  this.registerRecordingOnboardCap();
137948
139269
  this.registerStreamCatalogProvider();
137949
139270
  this.registerNativeObjectDetectionCap();
139271
+ this.adoptBatteryFromDeviceCache();
139272
+ }
139273
+ /** Sets `isBattery` from the persisted `deviceCache` and, for a battery
139274
+ * camera, registers its battery cap and arms the refresh timer. Called from
139275
+ * cap registration; `isBatteryCam()` answers from the flag it sets. */
139276
+ adoptBatteryFromDeviceCache() {
137950
139277
  const cache = this.config.get("deviceCache");
137951
139278
  if (cache?.deviceType === "battery-cam" || cache?.hasBattery === true) {
137952
139279
  this.isBattery = true;
@@ -138216,6 +139543,26 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
138216
139543
  return false;
138217
139544
  }
138218
139545
  }
139546
+ /** A battery camera running on its adapter is wired: it never sleeps. */
139547
+ isOnAdapterPower() {
139548
+ return this.config.get("deviceCache")?.powerSourceSnapshot?.source === "adapter";
139549
+ }
139550
+ /**
139551
+ * Whether a silent stream source may be a camera gone to sleep. A battery
139552
+ * camera whose power source is not known yet (no snapshot, or `unknown`)
139553
+ * counts as sleeping — refusing one recovery is cheap, waking a sleeper
139554
+ * drains it; a camera with no battery feature is never refused.
139555
+ */
139556
+ streamSourceMaySleep() {
139557
+ return reolinkCameraSleeps(this.featureInputs()) && !this.isOnAdapterPower();
139558
+ }
139559
+ /** Asked by the lib before EVERY recovery of a silent source: read live, never frozen at creation. */
139560
+ streamRecoveryVerdict() {
139561
+ return this.streamSourceMaySleep() ? {
139562
+ allowed: false,
139563
+ reason: "the camera may be asleep: a new session would wake it, so the next consumer decides"
139564
+ } : { allowed: true };
139565
+ }
138219
139566
  /**
138220
139567
  * THE single writer of the `battery.sleeping` slice.
138221
139568
  *
@@ -138245,7 +139592,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
138245
139592
  lastFirstHandCommitAt: this.sleepStateChangedAt,
138246
139593
  nowMs: Date.now(),
138247
139594
  videoFlowing: Date.now() - this.lastVideoFlowAt < VIDEO_FLOW_FRESH_MS,
138248
- wired: this.config.get("deviceCache")?.powerSourceSnapshot?.source === "adapter"
139595
+ wired: this.isOnAdapterPower()
138249
139596
  });
138250
139597
  if (decision.kind === "unchanged") return false;
138251
139598
  if (decision.kind === "refused") {
@@ -138368,10 +139715,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
138368
139715
  const now = Date.now();
138369
139716
  const quantised = now - now % ReolinkCamera.CONTACT_WRITE_QUANTUM_MS;
138370
139717
  const previousContact = this.state.battery.lastContactAt ?? 0;
138371
- this.setCapSlice(batteryCapability, {
139718
+ this.setCapSlice(batteryCapability, carryRefreshBookkeeping(this.state.battery, {
138372
139719
  ...mapped,
138373
139720
  lastContactAt: Math.max(previousContact, quantised)
138374
- });
139721
+ }));
138375
139722
  }
138376
139723
  /**
138377
139724
  * Hub-fed battery refresh for an adopted child. The parent's
@@ -138673,7 +140020,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
138673
140020
  * changed.
138674
140021
  */
138675
140022
  async applyEmailConfigPatch(fields) {
138676
- await this.wakeIfSleeping();
140023
+ await this.wakeIfSleeping("apply-email-config-patch");
138677
140024
  const api = await this.ensureApi();
138678
140025
  const channel = this.getChannel();
138679
140026
  const patch = {};
@@ -141222,7 +142569,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141222
142569
  * session or touches the broker.
141223
142570
  */
141224
142571
  async buildStreamCatalog() {
141225
- if (this.cachedStreamDescriptors?.length) return this.withLiveNativeSdp(this.cachedStreamDescriptors);
142572
+ if (this.cachedStreamDescriptors?.length) return this.withLiveNativeSdp(stampCurrentFeatures(this.cachedStreamDescriptors, this.features));
141226
142573
  const restored = this.restoreStreamCatalogFromLedger();
141227
142574
  if (restored) return this.withLiveNativeSdp(restored);
141228
142575
  if (this.buildStreamCatalogInFlight) return this.withLiveNativeSdp(await this.buildStreamCatalogInFlight);
@@ -141506,7 +142853,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141506
142853
  const stored = this.runtimeState.getCapState(streamCatalogCapability.name);
141507
142854
  const descriptors = stored?.descriptors;
141508
142855
  if (!descriptors || descriptors.length === 0) return null;
141509
- this.cachedStreamDescriptors = [...descriptors];
142856
+ this.cachedStreamDescriptors = stampCurrentFeatures(descriptors, this.features);
141510
142857
  this.ctx.logger.info("stream catalog restored from the durable slice (no camera contact)", {
141511
142858
  tags: { deviceId: this.id },
141512
142859
  meta: {
@@ -141554,7 +142901,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141554
142901
  ...entry.codec !== void 0 ? { codec: entry.codec } : {},
141555
142902
  ...entry.metadata ? { metadata: entry.metadata } : {},
141556
142903
  ...entry.maxSessionMs !== void 0 ? { maxSessionMs: entry.maxSessionMs } : {},
141557
- deviceFeatures: entry.deviceFeatures ?? [...this.features],
142904
+ deviceFeatures: [...this.features],
141558
142905
  autoEligible: entry.autoEligible ?? true
141559
142906
  });
141560
142907
  this.publishedStreamIds.add(entry.camStreamId);
@@ -141591,6 +142938,31 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141591
142938
  * listening; if the lib idle-tore-down between calls we recreate.
141592
142939
  */
141593
142940
  async materializeStreamSocket(camStreamId) {
142941
+ const inFlight = this.materializeInFlight.get(camStreamId);
142942
+ if (inFlight) {
142943
+ const ageMs = Date.now() - (this.materializeStartedAt.get(camStreamId) ?? Date.now());
142944
+ if (ageMs >= MATERIALIZE_JOIN_LOG_AFTER_MS) this.ctx.logger.warn("materializeStreamSocket: joining a run still in flight", {
142945
+ tags: {
142946
+ deviceId: this.id,
142947
+ camStreamId
142948
+ },
142949
+ meta: { inFlightMs: ageMs }
142950
+ });
142951
+ return inFlight;
142952
+ }
142953
+ this.materializeStartedAt.set(camStreamId, Date.now());
142954
+ const run = this.runMaterializeStreamSocket(camStreamId).finally(() => {
142955
+ this.materializeStartedAt.delete(camStreamId);
142956
+ if (this.materializeInFlight.get(camStreamId) === run) this.materializeInFlight.delete(camStreamId);
142957
+ });
142958
+ this.materializeInFlight.set(camStreamId, run);
142959
+ return run;
142960
+ }
142961
+ /** In-flight `materializeStreamSocket` runs, per camStreamId. */
142962
+ materializeInFlight = /* @__PURE__ */ new Map();
142963
+ /** When each in-flight run started, to say how long a joiner waited on it. */
142964
+ materializeStartedAt = /* @__PURE__ */ new Map();
142965
+ async runMaterializeStreamSocket(camStreamId) {
141594
142966
  const parts = parseCamStreamId(camStreamId, this.getChannel());
141595
142967
  if (!parts || parts.kind !== "native") return;
141596
142968
  this.ctx.logger.info("broker requested rfc4571 source refresh — materializing on demand", {
@@ -141624,7 +142996,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141624
142996
  deviceId: this.id,
141625
142997
  camStreamId
141626
142998
  },
141627
- meta: { url: `tcp://${server.host}:${server.port}` }
142999
+ meta: {
143000
+ url: `tcp://${server.host}:${server.port}`,
143001
+ republishCause: "broker-source-refresh (materializeStreamSocket)"
143002
+ }
141628
143003
  });
141629
143004
  }
141630
143005
  async removeDevice() {
@@ -141709,7 +143084,8 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141709
143084
  requireAuth: true,
141710
143085
  deviceId: this.stableId,
141711
143086
  requestedId: camStreamId,
141712
- logger: this.libLoggerAdapter()
143087
+ logger: this.libLoggerAdapter(),
143088
+ resilience: { recoveryGuard: () => this.streamRecoveryVerdict() }
141713
143089
  });
141714
143090
  } catch (err) {
141715
143091
  this.ctx.logger.error("rfc4571: createRfc4571TcpServer failed", {
@@ -141976,17 +143352,21 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141976
143352
  logger: this.ctx.logger,
141977
143353
  now: () => Date.now(),
141978
143354
  isAwake: () => !this.sleeping,
143355
+ isStreaming: () => this.hasActiveStream(),
141979
143356
  intervalMs: () => resolveBatteryRefreshIntervalMs(this.config.get("batteryRefreshMinutes")),
141980
143357
  lastFullRefreshAt: () => this.state.battery.lastFullRefreshAt,
141981
143358
  wake: async () => {
141982
143359
  if (!this.canProactivelyWake("scheduled-refresh")) return false;
141983
143360
  this.markWakeIssued();
141984
- return this.wakeIfSleeping();
143361
+ return this.wakeIfSleeping("scheduled-refresh");
141985
143362
  },
141986
143363
  refreshAll: () => this.refreshEverythingNow(),
141987
143364
  stamp: (at) => {
141988
143365
  this.state.battery.lastFullRefreshAt = at;
141989
- }
143366
+ },
143367
+ attemptLedger: attemptLedgerOverSlice(() => this.state.battery, (fields) => {
143368
+ this.runtimeState.patchCapState(batteryCapability.name, fields);
143369
+ })
141990
143370
  });
141991
143371
  return this.batteryRefresh;
141992
143372
  }
@@ -142180,13 +143560,16 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
142180
143560
  });
142181
143561
  }
142182
143562
  else await this.reprobeAccessoriesIfStale(reason);
142183
- if (!(this.isBattery ? await this.getBatteryRefresh().noteAwake().catch(() => false) : false)) {
143563
+ const scheduledRefreshCovered = this.isBattery ? await this.getBatteryRefresh().noteAwake().catch(() => false) : false;
143564
+ const streamingDefer = this.isBattery && this.getBatteryRefresh().shouldDeferForStream();
143565
+ if (streamingDefer) this.getBatteryRefresh().noteStreamDeferred("wake-warm-up");
143566
+ if (!scheduledRefreshCovered && !streamingDefer) {
142184
143567
  await this.warmCapSlicesOnWake();
142185
143568
  await this.warmSnapshotOnWake();
142186
143569
  await this.alignAuxDevicesState("wake");
142187
143570
  await this.refreshParentSettingsSnapshot();
142188
143571
  }
142189
- await this.refreshClipCatalogOnWake();
143572
+ if (!streamingDefer) await this.refreshClipCatalogOnWake();
142190
143573
  }
142191
143574
  static PING_INTERVAL_MS = 3e4;
142192
143575
  static PING_MAX_FAILURES = 3;
@@ -143597,7 +144980,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143597
144980
  async applySettingsPatch(patch) {
143598
144981
  if (this.isHubChild()) this.refuseHubChildPatch(patch);
143599
144982
  const { emailSmtpServer, emailSmtpPort, emailUserName, emailPassword, emailSsl, emailRecipient1, emailRecipient2, emailRecipient3, emailSendNickname, emailScheduleEnabled, osdChannelEnabled, osdChannelName, osdChannelPosition, osdTimeEnabled, osdTimePosition, osdWatermark, hubName: _hubName, [POWER_SOURCE_SETTING_KEY]: powerSource, ...rest } = patch;
143600
- if ((osdChannelEnabled !== void 0 || osdChannelName !== void 0 || osdChannelPosition !== void 0 || osdTimeEnabled !== void 0 || osdTimePosition !== void 0 || osdWatermark !== void 0 || emailSmtpServer !== void 0 || emailRecipient1 !== void 0 || powerSource !== void 0) && !await this.wakeIfSleeping()) this.ctx.logger.warn("settings write: battery cam did not wake — writing anyway", { tags: { deviceId: this.id } });
144983
+ if ((osdChannelEnabled !== void 0 || osdChannelName !== void 0 || osdChannelPosition !== void 0 || osdTimeEnabled !== void 0 || osdTimePosition !== void 0 || osdWatermark !== void 0 || emailSmtpServer !== void 0 || emailRecipient1 !== void 0 || powerSource !== void 0) && !await this.wakeIfSleeping("settings-write")) this.ctx.logger.warn("settings write: battery cam did not wake — writing anyway", { tags: { deviceId: this.id } });
143601
144984
  const emailFields = {
143602
144985
  emailSmtpServer,
143603
144986
  emailSmtpPort,
@@ -144057,14 +145440,15 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144057
145440
  * separate auth flow per accessory. `ReolinkAccessory` calls this
144058
145441
  * inside its `applyOn` / `fetchOn` to reach the camera firmware.
144059
145442
  */
144060
- /** Implements `ReolinkAccessoryHost.isBatteryCam` so spawned
144061
- * accessory children skip background polling on a sleeping
144062
- * battery cam (Baichuan polls on a sleeping camera return 400 +
144063
- * drain the battery). Reads from the runtime feature-probe slice
144064
- * populated during `onProbe()`; falls back to false when the probe
144065
- * hasn't completed yet. */
145443
+ /** Implements `ReolinkAccessoryHost.isBatteryCam`: returns `this.isBattery`,
145444
+ * the same flag the parent's own sleep gates read. That flag is set during
145445
+ * cap registration from the persisted `deviceCache`
145446
+ * (`deviceType === 'battery-cam' || hasBattery`) and again at login. It is
145447
+ * NOT read from the `feature-probe` slice: a battery camera asleep at boot
145448
+ * never seeds that slice, so every accessory probed straight through its
145449
+ * sleep gate and woke the camera (#666, device 640). */
144066
145450
  isBatteryCam() {
144067
- return this.runtimeState.getCapState("feature-probe")?.flags?.["hasBattery"] === true;
145451
+ return this.isBattery;
144068
145452
  }
144069
145453
  /** Implements `ReolinkAccessoryHost.isSleeping`. Reads the canonical
144070
145454
  * source of truth — the `battery.sleeping` runtime-state slice — so
@@ -144079,7 +145463,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144079
145463
  /** Implements `ReolinkAccessoryHost.wakeForWrite`: an accessory's operator
144080
145464
  * write (PIR, ...) wakes a sleeping battery camera first. */
144081
145465
  wakeForWrite() {
144082
- return this.wakeIfSleeping();
145466
+ return this.wakeIfSleeping("write");
144083
145467
  }
144084
145468
  /** Implements `ReolinkAccessoryHost.probeAbility`: the effective probe flag
144085
145469
  * (live slice, else the persisted probe); `undefined` = never probed. */
@@ -144115,7 +145499,9 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144115
145499
  meta: {
144116
145500
  port,
144117
145501
  transport,
144118
- hasUid: Boolean(uid)
145502
+ hasUid: Boolean(uid),
145503
+ loginReason: this.lastSessionDropReason ?? "first-login",
145504
+ loginsSoFar: this.loginCount
144119
145505
  }
144120
145506
  });
144121
145507
  const debugOptions = this.getBaichuanDebugOptions();
@@ -144146,9 +145532,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144146
145532
  });
144147
145533
  this.pendingLoginApi = api;
144148
145534
  try {
144149
- await api.login();
145535
+ await loginWithin(() => api.login(), LOGIN_DEADLINE_MS, () => api.close({ reason: "login-deadline" }));
144150
145536
  } catch (err) {
144151
145537
  if (generation !== this.loginGeneration) throw supersededLoginError(err);
145538
+ if (err instanceof LoginDeadlineError) this.ctx.logger.warn("Baichuan login abandoned — camera did not answer in time", {
145539
+ tags: { deviceId: this.id },
145540
+ meta: { deadlineMs: err.deadlineMs }
145541
+ });
144152
145542
  this.pendingLoginApi = null;
144153
145543
  this.loginPromise = null;
144154
145544
  if (isConnectivityFailure(err)) this.noteUnreachable(err instanceof Error ? err.message : String(err));
@@ -144164,6 +145554,17 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144164
145554
  this.pendingLoginApi = null;
144165
145555
  this.api = api;
144166
145556
  this.loginPromise = null;
145557
+ this.loginCount += 1;
145558
+ if (this.lastSessionDropReason !== null) {
145559
+ this.ctx.logger.info("Baichuan session re-logged-in", {
145560
+ tags: { deviceId: this.id },
145561
+ meta: {
145562
+ reason: this.lastSessionDropReason,
145563
+ loginCount: this.loginCount
145564
+ }
145565
+ });
145566
+ this.lastSessionDropReason = null;
145567
+ }
144167
145568
  this.reconnectAttempts = 0;
144168
145569
  if (this.ownsReachability()) this.reachability.noteReachable();
144169
145570
  const persistedDeviceType = this.config.get("deviceCache")?.deviceType;
@@ -144180,6 +145581,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144180
145581
  this.isBattery = false;
144181
145582
  }
144182
145583
  else this.isBattery = false;
145584
+ if (!this.isBattery) api.setGeneralSessionRecycling({ guard: () => true });
144183
145585
  if (this.isBattery) {
144184
145586
  this.startSleepPoll();
144185
145587
  this.startBatteryUpdatePolling();
@@ -144417,11 +145819,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144417
145819
  let hasPirSensor;
144418
145820
  let hasAutotrack;
144419
145821
  let capabilitiesRead = false;
145822
+ let readQuality = "partial";
144420
145823
  try {
144421
145824
  channelCount = await api.getChannelCount();
144422
145825
  } catch {}
144423
145826
  try {
144424
- const { capabilities } = await api.getDeviceCapabilities(this.getChannel());
145827
+ const { capabilities, debug } = await api.getDeviceCapabilities(this.getChannel());
145828
+ readQuality = abilityReadQuality(debug);
144425
145829
  hasPtz = capabilities.hasPtz;
144426
145830
  hasIntercom = capabilities.hasIntercom;
144427
145831
  hasDoorbell = capabilities.isDoorbell;
@@ -144442,12 +145846,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144442
145846
  return;
144443
145847
  }
144444
145848
  const prev = this.runtimeState.getCapState("feature-probe");
144445
- const prevFlags = prev?.flags ?? {};
145849
+ const prevFlags = this.getProbeFlags();
144446
145850
  const inferredDeviceType = this.config.get("deviceCache")?.deviceType ?? (this.isBattery ? "battery-cam" : null);
144447
145851
  const persistedModel = this.config.get("deviceCache")?.model ?? null;
144448
- const flags = {
144449
- ...prevFlags,
144450
- hasBattery: hasBattery === true || prevFlags.hasBattery === true || this.isBattery,
145852
+ const readFlags = {
144451
145853
  ...hasPtz !== void 0 ? { hasPtz } : {},
144452
145854
  ...hasIntercom !== void 0 ? { hasIntercom } : {},
144453
145855
  ...hasDoorbell !== void 0 ? { hasDoorbell } : {},
@@ -144456,6 +145858,12 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144456
145858
  ...hasPirSensor !== void 0 ? { hasPirSensor } : {},
144457
145859
  ...hasAutotrack !== void 0 ? { hasAutotrack } : {}
144458
145860
  };
145861
+ const flags = {
145862
+ ...mergeAbilityRead(prevFlags, readFlags, readQuality),
145863
+ hasBattery: hasBattery === true || prevFlags.hasBattery === true || this.isBattery
145864
+ };
145865
+ const fullRead = capabilitiesRead && readQuality === "full";
145866
+ if (fullRead) this.fullAbilityReadThisSession = true;
144459
145867
  const now = Date.now();
144460
145868
  const next = {
144461
145869
  flags,
@@ -144472,7 +145880,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144472
145880
  ...inferredDeviceType ? { deviceType: inferredDeviceType } : {},
144473
145881
  ...channelCount !== void 0 ? { channelCount } : {}
144474
145882
  };
144475
- await this.config.setAll({ deviceCache: capabilitiesRead ? withPersistedProbe(identity, flags, now) : identity });
145883
+ await this.config.setAll({ deviceCache: fullRead ? withPersistedProbe(identity, flags, now) : identity });
144476
145884
  } catch (err) {
144477
145885
  this.ctx.logger.debug("deviceCache identity persist failed (non-fatal)", {
144478
145886
  tags: { deviceId: this.id },
@@ -144489,7 +145897,9 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144489
145897
  meta: {
144490
145898
  flags,
144491
145899
  channelCount,
144492
- deviceType: inferredDeviceType
145900
+ deviceType: inferredDeviceType,
145901
+ abilityRead: capabilitiesRead ? readQuality : "failed",
145902
+ ...capabilitiesRead && readQuality === "partial" ? { partialRead: readFlags } : {}
144493
145903
  }
144494
145904
  });
144495
145905
  }
@@ -144550,6 +145960,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144550
145960
  async dropBaichuanSession(reason) {
144551
145961
  const current = this.api;
144552
145962
  this.api = null;
145963
+ if (current) this.lastSessionDropReason = reason;
144553
145964
  if (!current) return;
144554
145965
  try {
144555
145966
  await current.close({ reason });
@@ -144620,6 +146031,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144620
146031
  if (this.reconnectTimer) return;
144621
146032
  if (this.isBattery) {
144622
146033
  this.api = null;
146034
+ this.lastSessionDropReason = `disconnect: ${reason}`;
144623
146035
  this.ctx.logger.debug("Battery cam disconnect — deferring reconnect to next demand", {
144624
146036
  tags: { deviceId: this.id },
144625
146037
  meta: {
@@ -144650,6 +146062,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144650
146062
  }
144651
146063
  });
144652
146064
  this.api = null;
146065
+ this.lastSessionDropReason = `reconnect: ${reason}`;
144653
146066
  if (this.removed) return;
144654
146067
  this.reconnectTimer = setTimeout(() => {
144655
146068
  this.reconnectTimer = null;
@@ -146728,6 +148141,12 @@ function createWebhookHandler(deps) {
146728
148141
  }
146729
148142
  //#endregion
146730
148143
  //#region src/addon.ts
148144
+ /** The broker's source-refresh request; a `reason` it adds is ignored (the library heals a silent source itself). */
148145
+ var sourceRefreshPayload = object({
148146
+ deviceId: number(),
148147
+ camStreamId: string().optional(),
148148
+ reason: string().optional()
148149
+ });
146731
148150
  /**
146732
148151
  * Adapt a camstack scoped logger to the lib's `Logger` shape (just
146733
148152
  * `log(...)`). Lib lines are prefixed with `[AutoDetect]` /
@@ -147296,9 +148715,14 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
147296
148715
  provider: { list: () => intercomFailureReport.list() }
147297
148716
  });
147298
148717
  this.subscribe({ category: EventCategory.StreamBrokerOnRequestStreamSourceRefresh }, (event) => {
147299
- const data = event.data;
147300
- const deviceId = typeof data.deviceId === "number" ? data.deviceId : null;
147301
- if (deviceId === null) return;
148718
+ const parsed = sourceRefreshPayload.safeParse(event.data);
148719
+ if (!parsed.success) return;
148720
+ const data = parsed.data;
148721
+ const deviceId = data.deviceId;
148722
+ if (data.reason === "source-silent") this.ctx.logger.debug("stream source refresh reason source-silent is advisory — the library heals a silent source itself", {
148723
+ tags: { deviceId },
148724
+ meta: { camStreamId: data.camStreamId ?? null }
148725
+ });
147302
148726
  this.refreshDeviceStreams(deviceId, data.camStreamId).catch((err) => {
147303
148727
  this.ctx.logger.warn("refresh of Reolink stream failed", {
147304
148728
  tags: { deviceId },