@camstack/addon-provider-reolink 1.2.259 → 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
  /**
@@ -105928,9 +106855,9 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
105928
106855
  */
105929
106856
  EventCategory["DeviceStateChanged"] = "device.state-changed";
105930
106857
  /**
105931
- * A device COMMAND (a vocabulary action, D920/D983) settled in the hub's
105932
- * transition audit (D1022): confirmed, already in place, unconfirmed or
105933
- * failed. Never a device's own change. Payload: `DeviceCommandSettledEvent`
106858
+ * A device COMMAND (a vocabulary action, D920/D983) completed, as the hub's
106859
+ * command audit saw it (D1022, D1084): the call returned (`ok`) or threw
106860
+ * (`failed`). Never a device's own change, and never proof the device obeyed. Payload: `DeviceCommandSettledEvent`
105934
106861
  * (`{deviceId, action, outcome, actor, at}`, no arguments). It feeds
105935
106862
  * the Notification Center `device-command` kind. Telemetry (D8): losing one
105936
106863
  * costs a notification, never state; the audit row is the record.
@@ -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,23 @@ 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;
110007
+ /**
110008
+ * Every switch migration this process added to a declaration so far, by id. The engine replaces
110009
+ * an owner's catalogue on each declare, so a later one (a late kind) carries them all: dropping
110010
+ * an earlier id would read its applied ledger row as a newer database.
110011
+ */
110012
+ switchDeclared = /* @__PURE__ */ new Map();
110013
+ /** The seq each kind's move got, fixed at its first declare so its id and seq never change. */
110014
+ switchSeqs = /* @__PURE__ */ new Map();
110015
+ moveInDeclared = false;
109032
110016
  registrySwitchBound() {
109033
110017
  const api = this.ctx.migrationApi;
109034
110018
  const spec = this.registrySwitchSpec;
@@ -109039,7 +110023,7 @@ var BaseAddon = class {
109039
110023
  return [];
109040
110024
  }
109041
110025
  const date = "2026-11-06";
109042
- const moveIn = spec === null ? [] : migrationSet([registrySwitchToBodyMigration({
110026
+ const moveIn = spec === null || this.moveInDeclared ? [] : migrationSet([registrySwitchToBodyMigration({
109043
110027
  addonId: this.ctx.id,
109044
110028
  date,
109045
110029
  seq: 1e3,
@@ -109049,12 +110033,15 @@ var BaseAddon = class {
109049
110033
  records: switchRecordsOverMigrationApi(a),
109050
110034
  kind: spec.kind
109051
110035
  })).bind(api);
109052
- const moveBack = kinds.flatMap(({ kind }, index) => {
110036
+ if (spec !== null) this.moveInDeclared = true;
110037
+ const moveBack = kinds.flatMap(({ kind }) => {
109053
110038
  this.switchMoved.add(kind.name);
110039
+ const seq = 1001 + this.switchSeqs.size;
110040
+ this.switchSeqs.set(kind.name, seq);
109054
110041
  return migrationSet([bodySwitchToRegistryMigration({
109055
110042
  addonId: this.ctx.id,
109056
110043
  date: "2026-11-19",
109057
- seq: 1001 + index,
110044
+ seq,
109058
110045
  kindName: kind.name,
109059
110046
  ...spec === null ? {} : { followsDate: date }
109060
110047
  })], (a) => bodySwitchPortsOver({
@@ -109080,33 +110067,105 @@ var BaseAddon = class {
109080
110067
  */
109081
110068
  async moveLateInstanceKinds() {
109082
110069
  const late = servedInstanceKindsOf(this.ctx.id).filter((k) => !this.switchMoved.has(k.kind.name));
109083
- 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
+ }
109084
110080
  try {
109085
110081
  const only = late.map((k) => bodySwitchToRegistryId(this.ctx.id, "2026-11-19", k.kind.name));
109086
- await this.runBound(this.lastDeclared, { only });
110082
+ await this.runBound([], { only });
109087
110083
  } catch (err) {
109088
110084
  if (err instanceof AddonMigrationsBlockedError) throw err;
109089
110085
  this.ctx.logger.error("the late instance switch move failed", { meta: { error: errMsg$3(err) } });
109090
110086
  }
109091
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
+ }
109092
110125
  async runBound(declared, options) {
109093
- this.lastDeclared = declared;
110126
+ this.watchAppliedMigrations();
110127
+ const priorIds = new Set([...this.declaredAll.keys(), ...this.switchDeclared.keys()]);
109094
110128
  const added = this.registrySwitchBound();
109095
- const migrations = [...declared, ...added];
109096
- const widened = options?.only === void 0 || added.length === 0 ? options : {
110129
+ for (const m of added) this.switchDeclared.set(m.meta.id, m);
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 ?? {} : {
109097
110134
  ...options,
109098
- only: [...new Set([...options.only, ...added.map((m) => m.meta.id)])]
109099
- };
109100
- const phased = this.retiredMigrationIds.length === 0 ? widened ?? {} : {
109101
- ...widened,
109102
- 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
109103
110149
  };
109104
110150
  const api = this.ctx.api.migrations;
109105
- const report = await runAddonMigrations({
110151
+ const host = {
109106
110152
  declareOwner: (input) => api.declareOwner.mutate(input),
109107
110153
  startMigration: (input) => api.startMigration.mutate(input),
109108
110154
  finishMigration: (input) => api.finishMigration.mutate(input)
109109
- }, 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]);
109110
110169
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
109111
110170
  await this.hydrateSwitches();
109112
110171
  await this.adoptUnrowed();
@@ -110262,6 +111321,7 @@ function method(input, output, options) {
110262
111321
  ...options?.caller !== void 0 ? { caller: options.caller } : {},
110263
111322
  ...options?.actions !== void 0 ? { actions: options.actions } : {},
110264
111323
  ...options?.notOperatorFacing !== void 0 ? { notOperatorFacing: options.notOperatorFacing } : {},
111324
+ ...options?.description !== void 0 ? { description: options.description } : {},
110265
111325
  timeoutMs: options?.timeoutMs
110266
111326
  };
110267
111327
  }
@@ -111877,6 +112937,11 @@ var DeviceType = /* @__PURE__ */ function(DeviceType) {
111877
112937
  * water, cooling, solar), its system modes and its power. One main read-only
111878
112938
  * `heat-pump-status` cap carries all of it; `heat-pump-control` sets it (D1026). */
111879
112939
  DeviceType["HeatPump"] = "heat-pump";
112940
+ /** A road vehicle reached through its maker's connected-car account: odometer, range,
112941
+ * openings, tyre warnings and the 12 V battery in one read-only `vehicle` cap; where it
112942
+ * is in `location`; fuel, fluids and service in `consumables`. Its lock and its cabin
112943
+ * climate are accessory children (`lock-vehicle`, `climate-vehicle`). */
112944
+ DeviceType["Vehicle"] = "vehicle";
111880
112945
  /** A home energy installation (any vendor): solar, grid, house, a metered heat pump
111881
112946
  * and the storage as branches of one bus. One read-only `energy-system` cap carries
111882
112947
  * every value; the storage is a field of it, never the `battery` cap (#513, #522). */
@@ -112119,6 +113184,14 @@ var DeviceRole = /* @__PURE__ */ function(DeviceRole) {
112119
113184
  /** One heating/cooling circuit of a heat pump: a water loop with comfort /
112120
113185
  * eco setpoints and a heat/cool mode, no room sensor. */
112121
113186
  DeviceRole["ClimateHeatPumpCircuit"] = "climate-heat-pump-circuit";
113187
+ /** A car's cabin: pre-conditioning (start / stop, target temperature) through the
113188
+ * maker's connected-car account. An accessory child of a vehicle. */
113189
+ DeviceRole["ClimateVehicle"] = "climate-vehicle";
113190
+ /** A car's central locking, an accessory child of a vehicle. Slow, cloud-held
113191
+ * commands; exports decide by `isVehicleLock`. */
113192
+ DeviceRole["LockVehicle"] = "lock-vehicle";
113193
+ /** A television: power, volume, channel, source and apps. */
113194
+ DeviceRole["MediaPlayerTv"] = "media-player-tv";
112122
113195
  /** Generic motion / occupancy / moving event source. Distinct from
112123
113196
  * the camera accessory PirSensor role: that one is a camera child;
112124
113197
  * this is a standalone HA / 3rd-party motion sensor. */
@@ -112445,6 +113518,16 @@ var BatteryStatusSchema = /* @__PURE__ */ object({
112445
113518
  */
112446
113519
  lastFullRefreshAt: /* @__PURE__ */ number().optional(),
112447
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
+ /**
112448
113531
  * True when the source is a BINARY low-battery indicator (HA
112449
113532
  * `binary_sensor` device_class=battery / `LOW_BAT`) that has no real
112450
113533
  * charge level — `level` is then a coarse stand-in (100 = normal,
@@ -112693,7 +113776,9 @@ var brightnessCapability = {
112693
113776
  deviceNative: true,
112694
113777
  mode: "singleton",
112695
113778
  deviceTypes: [DeviceType.Light],
112696
- methods: { setBrightness: /* @__PURE__ */ method(/* @__PURE__ */ object({
113779
+ methods: {
113780
+ /** Set the light's brightness level from 0 to 100. */
113781
+ setBrightness: /* @__PURE__ */ method(/* @__PURE__ */ object({
112697
113782
  deviceId: /* @__PURE__ */ number().int().nonnegative(),
112698
113783
  level: /* @__PURE__ */ number().min(0).max(100)
112699
113784
  }), /* @__PURE__ */ _void(), {
@@ -112889,7 +113974,9 @@ var dayNightCapability = {
112889
113974
  tab: "image"
112890
113975
  } },
112891
113976
  methods: {
113977
+ /** The camera's day/night modes and current settings. */
112892
113978
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), DayNightOptionsSchema),
113979
+ /** Change the camera's day/night mode, sensitivity or switch delay. */
112893
113980
  setSettings: /* @__PURE__ */ method(/* @__PURE__ */ object({
112894
113981
  deviceId: /* @__PURE__ */ number(),
112895
113982
  settings: DayNightSettingsPatchSchema
@@ -113254,21 +114341,28 @@ var deviceAdoptionCapability = {
113254
114341
  kind: "poll"
113255
114342
  },
113256
114343
  methods: {
114344
+ /** The filters an integration offers to narrow its discovered candidates. */
113257
114345
  listCandidateFilters: /* @__PURE__ */ method(/* @__PURE__ */ object({ integrationId: /* @__PURE__ */ string() }), /* @__PURE__ */ object({ filters: /* @__PURE__ */ array(AdoptionFilterSchema) }), { auth: "admin" }),
114346
+ /** List the devices an integration has discovered and that can be adopted. */
113258
114347
  listCandidates: /* @__PURE__ */ method(ListCandidatesInputSchema, ListCandidatesOutputSchema, { auth: "admin" }),
114348
+ /** Fetch one discovered candidate; null when unknown. */
113259
114349
  getCandidate: /* @__PURE__ */ method(GetCandidateInputSchema, /* @__PURE__ */ DiscoveredChildDeviceSchema.nullable(), { auth: "admin" }),
114350
+ /** Rescan an integration for new candidates and report the adoption status. */
113260
114351
  refresh: /* @__PURE__ */ method(/* @__PURE__ */ object({ integrationId: /* @__PURE__ */ string() }), AdoptionStatusSchema, {
113261
114352
  kind: "mutation",
113262
114353
  auth: "admin"
113263
114354
  }),
114355
+ /** Adopt a discovered candidate as a device. */
113264
114356
  adopt: /* @__PURE__ */ method(AdoptInputSchema, AdoptResultSchema, {
113265
114357
  kind: "mutation",
113266
114358
  auth: "admin"
113267
114359
  }),
114360
+ /** Release an adopted device back to the candidate list. */
113268
114361
  release: /* @__PURE__ */ method(ReleaseInputSchema, /* @__PURE__ */ _void(), {
113269
114362
  kind: "mutation",
113270
114363
  auth: "admin"
113271
114364
  }),
114365
+ /** Re-read an adopted device from the integration and reconcile it. */
113272
114366
  resync: /* @__PURE__ */ method(ResyncInputSchema, ResyncResultSchema, {
113273
114367
  kind: "mutation",
113274
114368
  auth: "admin"
@@ -113632,9 +114726,13 @@ var deviceProviderCapability = {
113632
114726
  scope: "system",
113633
114727
  mode: "collection",
113634
114728
  methods: {
114729
+ /** Start the provider so it begins serving its devices. */
113635
114730
  start: /* @__PURE__ */ method(/* @__PURE__ */ _void(), /* @__PURE__ */ _void(), { kind: "mutation" }),
114731
+ /** Stop the provider. */
113636
114732
  stop: /* @__PURE__ */ method(/* @__PURE__ */ _void(), /* @__PURE__ */ _void(), { kind: "mutation" }),
114733
+ /** The provider's current status. */
113637
114734
  getStatus: /* @__PURE__ */ method(/* @__PURE__ */ _void(), ProviderStatusSchema),
114735
+ /** List the devices the provider serves. */
113638
114736
  getDevices: /* @__PURE__ */ method(/* @__PURE__ */ _void(), /* @__PURE__ */ array(/* @__PURE__ */ object({
113639
114737
  id: /* @__PURE__ */ string(),
113640
114738
  name: /* @__PURE__ */ string(),
@@ -113669,6 +114767,7 @@ var deviceProviderCapability = {
113669
114767
  kind: "mutation",
113670
114768
  timeoutMs: 3 * 6e4
113671
114769
  }),
114770
+ /** Whether the provider can discover devices on the network. */
113672
114771
  supportsDiscovery: /* @__PURE__ */ method(/* @__PURE__ */ object({}), /* @__PURE__ */ boolean()),
113673
114772
  /**
113674
114773
  * Run a network scan. `params` carries optional provider-specific scan
@@ -113714,6 +114813,7 @@ var deviceProviderCapability = {
113714
114813
  getManualCreationType: /* @__PURE__ */ method(/* @__PURE__ */ object({
113715
114814
  /** The integration asked about; a provider whose integrations differ answers per one. */
113716
114815
  integrationId: /* @__PURE__ */ string().optional() }), /* @__PURE__ */ object({ deviceType: /* @__PURE__ */ _enum(DeviceType).nullable() })),
114816
+ /** Adopt a discovered candidate as a device, optionally into an integration instance. */
113717
114817
  adoptDiscoveredDevice: /* @__PURE__ */ method(/* @__PURE__ */ object({
113718
114818
  candidate: DiscoveryCandidateSchema,
113719
114819
  /** The integration the operator adopts into; a provider with several instances needs it. */
@@ -113722,6 +114822,7 @@ integrationId: /* @__PURE__ */ string().optional() }), /* @__PURE__ */ object({
113722
114822
  kind: "mutation",
113723
114823
  auth: "admin"
113724
114824
  }),
114825
+ /** Whether devices can be created by hand through this provider. */
113725
114826
  supportsManualCreation: /* @__PURE__ */ method(/* @__PURE__ */ object({}), /* @__PURE__ */ boolean()),
113726
114827
  /**
113727
114828
  * Fetch the creation form schema for a given DeviceType. Returns
@@ -113734,6 +114835,7 @@ integrationId: /* @__PURE__ */ string().optional() }), /* @__PURE__ */ object({
113734
114835
  /** The integration asked about; a provider whose integrations differ answers per one. */
113735
114836
  integrationId: /* @__PURE__ */ string().optional()
113736
114837
  }), CreationSchemaOutputSchema),
114838
+ /** Create a device of a given type with the given config. */
113737
114839
  createDevice: /* @__PURE__ */ method(/* @__PURE__ */ object({
113738
114840
  type: /* @__PURE__ */ _enum(DeviceType),
113739
114841
  config: /* @__PURE__ */ record(/* @__PURE__ */ string(), /* @__PURE__ */ unknown()),
@@ -113843,11 +114945,13 @@ var deviceStateRefreshCapability = {
113843
114945
  deviceNative: true,
113844
114946
  mode: "singleton",
113845
114947
  methods: {
114948
+ /** Re-read a device's state from the source now. */
113846
114949
  refresh: /* @__PURE__ */ method(DeviceStateRefreshInputSchema, DeviceStateRefreshResultSchema, {
113847
114950
  kind: "mutation",
113848
114951
  auth: "admin",
113849
114952
  notOperatorFacing: NOT_OPERATOR_FACING
113850
114953
  }),
114954
+ /** Re-establish a device's live state subscription. */
113851
114955
  resubscribe: /* @__PURE__ */ method(DeviceStateResubscribeInputSchema, DeviceStateRefreshResultSchema, {
113852
114956
  kind: "mutation",
113853
114957
  auth: "admin",
@@ -114060,7 +115164,10 @@ onPressed: {
114060
115164
  };
114061
115165
  //#endregion
114062
115166
  //#region ../types/dist/esm/capabilities/error.cap.mjs
114063
- /** How loudly a fault wants the operator. Both tiers raise the attention event. */
115167
+ /**
115168
+ * How loudly a fault wants the operator. An `error` raises the attention event;
115169
+ * a `warning` is shown on the device and opens a warning alert, nothing more.
115170
+ */
114064
115171
  var DeviceErrorSeveritySchema = /* @__PURE__ */ _enum(["warning", "error"]);
114065
115172
  /** One fault of a device that can raise several at once. */
114066
115173
  var DeviceFaultSchema = /* @__PURE__ */ object({
@@ -114125,7 +115232,13 @@ listFaultTypes: /* @__PURE__ */ method(ListFaultTypesInputSchema, FaultTypesSche
114125
115232
  status: {
114126
115233
  schema: ErrorStatusSchema,
114127
115234
  kind: "push",
114128
- 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
+ } }
114129
115242
  },
114130
115243
  runtimeState: ErrorStatusSchema,
114131
115244
  /**
@@ -114514,7 +115627,9 @@ var imageSettingsCapability = {
114514
115627
  tab: "image"
114515
115628
  } },
114516
115629
  methods: {
115630
+ /** The camera's picture-adjustment options and current values. */
114517
115631
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), ImageSettingsOptionsSchema),
115632
+ /** Change the camera's picture settings (brightness, contrast, orientation, exposure, ...). */
114518
115633
  setSettings: /* @__PURE__ */ method(/* @__PURE__ */ object({
114519
115634
  deviceId: /* @__PURE__ */ number(),
114520
115635
  settings: ImageSettingsPatchSchema
@@ -114804,6 +115919,7 @@ var integrationInstancesCapability = {
114804
115919
  scope: "system",
114805
115920
  mode: "collection",
114806
115921
  methods: {
115922
+ /** What kind of instances this addon's integration holds and how to configure them. */
114807
115923
  describe: /* @__PURE__ */ method(/* @__PURE__ */ _void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
114808
115924
  /** The form; `id: null` is the create form. */
114809
115925
  instanceFormSchema: /* @__PURE__ */ method(/* @__PURE__ */ object({
@@ -114819,10 +115935,12 @@ var integrationInstancesCapability = {
114819
115935
  /** The discovery candidate the wizard was seeded from (`stableId`), if any. */
114820
115936
  candidateStableId: /* @__PURE__ */ string().min(1).optional()
114821
115937
  }), ConfigSchemaPassthrough, { auth: "admin" }),
115938
+ /** List the integration's instances (accounts, relays, destinations). */
114822
115939
  listInstances: /* @__PURE__ */ method(/* @__PURE__ */ looseObject({}), /* @__PURE__ */ array(IntegrationInstanceSchema).readonly(), {
114823
115940
  auth: "protected",
114824
115941
  caller: "scoped"
114825
115942
  }),
115943
+ /** Fetch one integration instance by id; null when absent. */
114826
115944
  getInstance: /* @__PURE__ */ method(/* @__PURE__ */ object({ id: IntegrationInstanceIdSchema }), /* @__PURE__ */ IntegrationInstanceSchema.nullable(), {
114827
115945
  auth: "protected",
114828
115946
  caller: "scoped"
@@ -114862,6 +115980,7 @@ var integrationInstancesCapability = {
114862
115980
  auth: "protected",
114863
115981
  caller: "scoped"
114864
115982
  }),
115983
+ /** Create or change an integration instance. */
114865
115984
  updateInstance: /* @__PURE__ */ method(IntegrationInstancePatchSchema, /* @__PURE__ */ object({ ok: /* @__PURE__ */ literal(true) }), {
114866
115985
  kind: "mutation",
114867
115986
  auth: "protected",
@@ -114890,6 +116009,7 @@ var integrationInstancesCapability = {
114890
116009
  auth: "protected",
114891
116010
  caller: "scoped"
114892
116011
  }),
116012
+ /** Test an instance's connection with the given values before saving. */
114893
116013
  testInstance: /* @__PURE__ */ optionalMethod(/* @__PURE__ */ object({
114894
116014
  id: /* @__PURE__ */ IntegrationInstanceIdSchema.nullable(),
114895
116015
  values: /* @__PURE__ */ record(/* @__PURE__ */ string(), /* @__PURE__ */ unknown()),
@@ -115007,6 +116127,7 @@ var intercomCapability = {
115007
116127
  auth: "protected",
115008
116128
  notOperatorFacing: "live-stream session plumbing driven by a viewer, never a discrete step"
115009
116129
  }),
116130
+ /** Pass the viewer's SDP answer to an open two-way audio session. */
115010
116131
  handleAnswer: /* @__PURE__ */ method(/* @__PURE__ */ object({
115011
116132
  deviceId: /* @__PURE__ */ number(),
115012
116133
  sessionId: /* @__PURE__ */ string(),
@@ -115677,7 +116798,12 @@ DeviceType.Camera;
115677
116798
  * - `pipeline` — the chosen detector plus the operator's detail steps
115678
116799
  * (faces, plates, classifiers, CLIP…), on varied frames from the bench
115679
116800
  * clip: how many parallel sessions the node carries before latency, drops,
115680
- * CPU, RAM or the event loop give out.
116801
+ * CPU, RAM or the event loop give out;
116802
+ * - `decode` — the node, no accelerator of the inference plane: an encoded
116803
+ * camera-like stream (a profile: resolution, rate, codec) served on the
116804
+ * loopback and decoded by the session decode worker a camera gets, with a
116805
+ * motion pass on its frames: how many concurrent streams keep the profile
116806
+ * frame rate inside the same CPU and RAM limits (D1078).
115681
116807
  */
115682
116808
  /** Defaults and bounds, one place. */
115683
116809
  var NODE_BENCHMARK_DEFAULTS = {
@@ -115696,9 +116822,24 @@ var NODE_BENCHMARK_DEFAULTS = {
115696
116822
  /** Candidate models per device in one run. */
115697
116823
  maxModelsPerDevice: 6
115698
116824
  };
116825
+ /**
116826
+ * The camera-like streams the `decode` measurement ramps, heaviest first: a
116827
+ * 4K H.265 main stream and a 1080p H.264 one, at a camera frame rate.
116828
+ */
116829
+ var NODE_BENCH_DECODE_PROFILES = [{
116830
+ width: 3840,
116831
+ height: 2160,
116832
+ fps: 15,
116833
+ codec: "h265"
116834
+ }, {
116835
+ width: 1920,
116836
+ height: 1080,
116837
+ fps: 15,
116838
+ codec: "h264"
116839
+ }];
115699
116840
  NODE_BENCHMARK_DEFAULTS.maxModelsPerDevice;
115700
116841
  NODE_BENCHMARK_DEFAULTS.fpsPerStream, NODE_BENCHMARK_DEFAULTS.budgetMinutes;
115701
- NODE_BENCHMARK_DEFAULTS.settleSec, NODE_BENCHMARK_DEFAULTS.measureSec;
116842
+ [...NODE_BENCH_DECODE_PROFILES], NODE_BENCHMARK_DEFAULTS.settleSec, NODE_BENCHMARK_DEFAULTS.measureSec;
115702
116843
  /**
115703
116844
  * Per-camera tunable ranges + defaults. Single source of truth used
115704
116845
  * by both the Zod data schema (validation + default fallback) and
@@ -116058,7 +117199,9 @@ var motionTriggerCapability = {
116058
117199
  DeviceType.Siren,
116059
117200
  DeviceType.Switch
116060
117201
  ],
116061
- methods: { setMotionTrigger: /* @__PURE__ */ method(/* @__PURE__ */ object({
117202
+ methods: {
117203
+ /** Turn on or off activating the accessory when the camera detects motion. */
117204
+ setMotionTrigger: /* @__PURE__ */ method(/* @__PURE__ */ object({
116062
117205
  deviceId: /* @__PURE__ */ number().int().nonnegative(),
116063
117206
  enabled: /* @__PURE__ */ boolean()
116064
117207
  }), /* @__PURE__ */ _void(), {
@@ -116177,7 +117320,9 @@ var motionZonesCapability = {
116177
117320
  label: "Motion Zones"
116178
117321
  } },
116179
117322
  methods: {
117323
+ /** The camera's onboard motion zone options and current zone. */
116180
117324
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), MotionZoneOptionsSchema),
117325
+ /** Change the camera's onboard motion zone. */
116181
117326
  setZone: /* @__PURE__ */ method(/* @__PURE__ */ object({
116182
117327
  deviceId: /* @__PURE__ */ number(),
116183
117328
  patch: MotionZonePatchSchema
@@ -116305,7 +117450,9 @@ var nativeObjectDetectionCapability = {
116305
117450
  mode: "singleton",
116306
117451
  deviceTypes: [DeviceType.Camera],
116307
117452
  methods: {
117453
+ /** The object classes the camera's onboard detection supports and its current settings. */
116308
117454
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), NativeObjectDetectionOptionsSchema),
117455
+ /** Change the camera's onboard object detection settings. */
116309
117456
  setSettings: /* @__PURE__ */ method(/* @__PURE__ */ object({
116310
117457
  deviceId: /* @__PURE__ */ number(),
116311
117458
  settings: NativeObjectDetectionSettingsPatchSchema
@@ -116313,6 +117460,7 @@ var nativeObjectDetectionCapability = {
116313
117460
  kind: "mutation",
116314
117461
  auth: "admin"
116315
117462
  }),
117463
+ /** Turn the camera's onboard object detection on or off. */
116316
117464
  setEnabled: /* @__PURE__ */ method(/* @__PURE__ */ object({
116317
117465
  deviceId: /* @__PURE__ */ number(),
116318
117466
  enabled: /* @__PURE__ */ boolean()
@@ -116748,7 +117896,9 @@ var privacyMaskCapability = {
116748
117896
  label: "Privacy Mask"
116749
117897
  } },
116750
117898
  methods: {
117899
+ /** The camera's privacy mask options and current mask. */
116751
117900
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), PrivacyMaskOptionsSchema),
117901
+ /** Change the camera's privacy mask. */
116752
117902
  setMask: /* @__PURE__ */ method(/* @__PURE__ */ object({
116753
117903
  deviceId: /* @__PURE__ */ number(),
116754
117904
  patch: PrivacyMaskPatchSchema
@@ -117039,10 +118189,12 @@ var ptzCapability = {
117039
118189
  order: 0
117040
118190
  } },
117041
118191
  methods: {
118192
+ /** Nudge the camera by a relative pan, tilt or zoom step. */
117042
118193
  move: /* @__PURE__ */ method(/* @__PURE__ */ PtzMoveCommandSchema.extend({ deviceId: /* @__PURE__ */ number() }), /* @__PURE__ */ _void(), {
117043
118194
  kind: "mutation",
117044
118195
  notOperatorFacing: "a relative nudge from the live-view joystick; a fixed place is a preset"
117045
118196
  }),
118197
+ /** Move the camera continuously until stopped. */
117046
118198
  continuousMove: /* @__PURE__ */ method(/* @__PURE__ */ PtzMoveCommandSchema.extend({ deviceId: /* @__PURE__ */ number() }), /* @__PURE__ */ _void(), {
117047
118199
  kind: "mutation",
117048
118200
  notOperatorFacing: "joystick motion held until released — continuous, not a discrete step"
@@ -117061,7 +118213,9 @@ var ptzCapability = {
117061
118213
  icon: "house"
117062
118214
  }]
117063
118215
  }),
118216
+ /** List the camera's PTZ presets. */
117064
118217
  getPresets: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), /* @__PURE__ */ array(PtzPresetSchema)),
118218
+ /** Move the camera to a preset. */
117065
118219
  goToPreset: /* @__PURE__ */ method(/* @__PURE__ */ object({
117066
118220
  deviceId: /* @__PURE__ */ number(),
117067
118221
  presetId: /* @__PURE__ */ string()
@@ -117085,6 +118239,7 @@ var ptzCapability = {
117085
118239
  }]
117086
118240
  }]
117087
118241
  }),
118242
+ /** Save the camera's current position as a named preset. */
117088
118243
  savePreset: /* @__PURE__ */ method(/* @__PURE__ */ object({
117089
118244
  deviceId: /* @__PURE__ */ number(),
117090
118245
  presetId: /* @__PURE__ */ string(),
@@ -117114,6 +118269,7 @@ var ptzCapability = {
117114
118269
  }]
117115
118270
  }]
117116
118271
  }),
118272
+ /** Delete a PTZ preset. */
117117
118273
  deletePreset: /* @__PURE__ */ method(/* @__PURE__ */ object({
117118
118274
  deviceId: /* @__PURE__ */ number(),
117119
118275
  presetId: /* @__PURE__ */ string()
@@ -117121,7 +118277,9 @@ var ptzCapability = {
117121
118277
  kind: "mutation",
117122
118278
  auth: "admin"
117123
118279
  }),
118280
+ /** What the camera's PTZ supports (axes, speeds, presets). */
117124
118281
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), PtzOptionsSchema),
118282
+ /** Stop any PTZ movement. */
117125
118283
  stop: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), /* @__PURE__ */ _void(), {
117126
118284
  kind: "mutation",
117127
118285
  actions: [{
@@ -117482,7 +118640,9 @@ var rebootCapability = {
117482
118640
  DeviceType.Switch,
117483
118641
  DeviceType.Gateway
117484
118642
  ],
117485
- methods: { reboot: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number().int().nonnegative() }), /* @__PURE__ */ object({ success: /* @__PURE__ */ literal(true) }), {
118643
+ methods: {
118644
+ /** Reboot the device. */
118645
+ reboot: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number().int().nonnegative() }), /* @__PURE__ */ object({ success: /* @__PURE__ */ literal(true) }), {
117486
118646
  kind: "mutation",
117487
118647
  auth: "admin",
117488
118648
  actions: [{
@@ -118199,6 +119359,7 @@ var videoclipsCapability = {
118199
119359
  order: 100
118200
119360
  } },
118201
119361
  methods: {
119362
+ /** List a camera's clips in a time window, from every clip source. */
118202
119363
  listClips: /* @__PURE__ */ method(/* @__PURE__ */ object({
118203
119364
  deviceId: /* @__PURE__ */ number(),
118204
119365
  since: /* @__PURE__ */ number(),
@@ -118257,6 +119418,7 @@ var videoclipsCapability = {
118257
119418
  kind: "query",
118258
119419
  auth: "protected"
118259
119420
  }),
119421
+ /** How to play one clip, at the requested quality. */
118260
119422
  getClipPlayback: /* @__PURE__ */ method(/* @__PURE__ */ object({
118261
119423
  deviceId: /* @__PURE__ */ number(),
118262
119424
  clipId: /* @__PURE__ */ string(),
@@ -118871,7 +120033,9 @@ var recordingOnboardCapability = {
118871
120033
  tab: "recording"
118872
120034
  } },
118873
120035
  methods: {
120036
+ /** The camera's onboard recording options and current settings. */
118874
120037
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), RecordingOnboardOptionsSchema),
120038
+ /** Change the camera's onboard recording settings. */
118875
120039
  setSettings: /* @__PURE__ */ method(/* @__PURE__ */ object({
118876
120040
  deviceId: /* @__PURE__ */ number(),
118877
120041
  settings: RecordingOnboardPatchSchema
@@ -119183,6 +120347,7 @@ var snapshotCapability = {
119183
120347
  deviceTypes: [DeviceType.Camera],
119184
120348
  exposesDeviceSettings: true,
119185
120349
  methods: {
120350
+ /** A current snapshot image of a camera, optionally bypassing the cache. */
119186
120351
  getSnapshot: /* @__PURE__ */ method(/* @__PURE__ */ object({
119187
120352
  deviceId: /* @__PURE__ */ number(),
119188
120353
  streamId: /* @__PURE__ */ string().optional(),
@@ -119204,6 +120369,7 @@ var snapshotCapability = {
119204
120369
  */
119205
120370
  force: /* @__PURE__ */ boolean().optional()
119206
120371
  }), /* @__PURE__ */ SnapshotImageSchema.nullable()),
120372
+ /** Drop a camera's cached snapshot. */
119207
120373
  invalidateCache: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), /* @__PURE__ */ _void(), {
119208
120374
  kind: "mutation",
119209
120375
  auth: "admin"
@@ -119455,7 +120621,9 @@ var streamCatalogCapability = {
119455
120621
  deviceNative: true,
119456
120622
  mode: "singleton",
119457
120623
  deviceTypes: [DeviceType.Camera],
119458
- methods: { getCatalog: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number().int().nonnegative() }), /* @__PURE__ */ array(CamStreamDescriptorSchema).readonly()) },
120624
+ methods: {
120625
+ /** List the streams a camera offers. */
120626
+ getCatalog: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number().int().nonnegative() }), /* @__PURE__ */ array(CamStreamDescriptorSchema).readonly()) },
119459
120627
  runtimeState: StreamCatalogStateSchema,
119460
120628
  /**
119461
120629
  * Runtime-state durability: **restored** — see the schema doc. A cold
@@ -119587,7 +120755,9 @@ var streamParamsCapability = {
119587
120755
  tab: "streaming"
119588
120756
  } },
119589
120757
  methods: {
120758
+ /** The camera's stream profiles and their encoding options. */
119590
120759
  getOptions: /* @__PURE__ */ method(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), StreamParamsOptionsSchema),
120760
+ /** Change the encoding settings of one stream profile. */
119591
120761
  setProfile: /* @__PURE__ */ method(/* @__PURE__ */ object({
119592
120762
  deviceId: /* @__PURE__ */ number(),
119593
120763
  profile: StreamProfileSchema,
@@ -119817,6 +120987,7 @@ var switchCapability = {
119817
120987
  DeviceType.Fan
119818
120988
  ],
119819
120989
  methods: {
120990
+ /** Turn the switch on or off. */
119820
120991
  setState: /* @__PURE__ */ method(/* @__PURE__ */ object({
119821
120992
  deviceId: /* @__PURE__ */ number(),
119822
120993
  on: /* @__PURE__ */ boolean()
@@ -119847,12 +121018,15 @@ var switchCapability = {
119847
121018
  offeredWhen: SWITCH_SETTABLE_GATE
119848
121019
  }]
119849
121020
  }),
121021
+ /** The options the switch supports. */
119850
121022
  getOptions: /* @__PURE__ */ optionalMethod(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), SwitchOptionsSchema, { auth: "protected" }),
121023
+ /** Power-cycle the device the switch powers. */
119851
121024
  powerCycle: /* @__PURE__ */ optionalMethod(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), /* @__PURE__ */ _void(), {
119852
121025
  kind: "mutation",
119853
121026
  auth: "protected",
119854
121027
  notOperatorFacing: "a power cycle is the forced restart of the device the switch powers (power-source), never a step of its own"
119855
121028
  }),
121029
+ /** Flip the switch to the opposite state. */
119856
121030
  toggle: /* @__PURE__ */ optionalMethod(/* @__PURE__ */ object({ deviceId: /* @__PURE__ */ number() }), /* @__PURE__ */ _void(), {
119857
121031
  kind: "mutation",
119858
121032
  auth: "protected",
@@ -121181,6 +122355,10 @@ async function declareDeviceIdentifiers(deps, raw, options = {}) {
121181
122355
  }
121182
122356
  }
121183
122357
  //#endregion
122358
+ //#region ../types/dist/esm/notification/alert-episode.mjs
122359
+ /** The category of the alert a device's `error` cap opens for its fault. */
122360
+ var DEVICE_ERROR_ALERT_CATEGORY = "device.error";
122361
+ //#endregion
121184
122362
  //#region ../types/dist/esm/device/device-error-episode.mjs
121185
122363
  /**
121186
122364
  * The edge between two readings, or `null` for no edge.
@@ -121196,6 +122374,75 @@ function deviceErrorEdge(previous, next) {
121196
122374
  if (next.active === false && previous?.active === true) return "resolve";
121197
122375
  return null;
121198
122376
  }
122377
+ /**
122378
+ * The alert severity of a fault tier. `error` is the cap's top tier and asks
122379
+ * for attention (`critical`); `warning` stays a warning.
122380
+ */
122381
+ function deviceErrorAlertSeverity(severity) {
122382
+ return severity === "error" ? "critical" : "warning";
122383
+ }
122384
+ var DEVICE_ERROR_ALERT_IDLE = {
122385
+ neverOpened: false,
122386
+ pending: null,
122387
+ attempts: 0
122388
+ };
122389
+ /**
122390
+ * The alert write a reading asks for.
122391
+ *
122392
+ * - a START opens; a `warning` fault that becomes an `error` opens again (same
122393
+ * alert id and episode, now critical). An error that eases to a warning
122394
+ * writes nothing: its critical alert stays until the fault resolves;
122395
+ * - a RESOLVE closes, except an alert this process knows was never accepted —
122396
+ * that one has nothing to close, and its failed open is dropped;
122397
+ * - with no edge, a failed write is tried again while the reading still asks
122398
+ * for it. An unknown reading asks for nothing (D49).
122399
+ */
122400
+ function planDeviceErrorAlert(delivery, edge, previous, next) {
122401
+ if (edge === "start") return {
122402
+ write: "open",
122403
+ delivery: {
122404
+ neverOpened: true,
122405
+ pending: "open",
122406
+ attempts: 0
122407
+ }
122408
+ };
122409
+ if (edge === "resolve") {
122410
+ if (delivery.neverOpened) return {
122411
+ write: null,
122412
+ delivery: DEVICE_ERROR_ALERT_IDLE
122413
+ };
122414
+ return {
122415
+ write: "close",
122416
+ delivery: {
122417
+ neverOpened: false,
122418
+ pending: "close",
122419
+ attempts: 0
122420
+ }
122421
+ };
122422
+ }
122423
+ if (next.active === true) {
122424
+ if (previous?.active === true && previous.severity === "warning" && next.severity === "error") return {
122425
+ write: "open",
122426
+ delivery: {
122427
+ ...delivery,
122428
+ pending: "open",
122429
+ attempts: 0
122430
+ }
122431
+ };
122432
+ if (delivery.pending === "open") return {
122433
+ write: "open",
122434
+ delivery
122435
+ };
122436
+ }
122437
+ if (next.active === false && delivery.pending === "close") return {
122438
+ write: "close",
122439
+ delivery
122440
+ };
122441
+ return {
122442
+ write: null,
122443
+ delivery
122444
+ };
122445
+ }
121199
122446
  function deviceErrorAlertId(deviceId) {
121200
122447
  return `device-error:${String(deviceId)}`;
121201
122448
  }
@@ -121220,8 +122467,8 @@ function buildDeviceErrorAlert(deviceId, deviceName, status, now) {
121220
122467
  const alertId = deviceErrorAlertId(deviceId);
121221
122468
  return {
121222
122469
  id: alertId,
121223
- category: "device.error",
121224
- severity: "critical",
122470
+ category: DEVICE_ERROR_ALERT_CATEGORY,
122471
+ severity: deviceErrorAlertSeverity(status.severity),
121225
122472
  title: `${deviceName}: ${label}`,
121226
122473
  message: `${deviceName} reports a fault: ${label}.`,
121227
122474
  action: {
@@ -121298,6 +122545,7 @@ var DEVICE_LOCAL_STATE_CAP_NAMES = {
121298
122545
  intercom: "intercom",
121299
122546
  irTransmitter: "ir-transmitter",
121300
122547
  lawnMowerControl: "lawn-mower-control",
122548
+ location: "location",
121301
122549
  lockControl: "lock-control",
121302
122550
  lowPowerSleep: "low-power-sleep",
121303
122551
  mediaPlayer: "media-player",
@@ -121336,6 +122584,7 @@ var DEVICE_LOCAL_STATE_CAP_NAMES = {
121336
122584
  update: "update",
121337
122585
  vacuumControl: "vacuum-control",
121338
122586
  valve: "valve",
122587
+ vehicle: "vehicle",
121339
122588
  vibration: "vibration",
121340
122589
  waterHeater: "water-heater",
121341
122590
  weather: "weather",
@@ -121355,6 +122604,8 @@ var BaseDevice = class {
121355
122604
  statusIsExternal;
121356
122605
  /** The fault catalog the integration declared; `[]` until it does. */
121357
122606
  faultTypes = [];
122607
+ /** What the alerts cap accepted for this device's fault, and the write still owed to it. */
122608
+ errorAlertDelivery = DEVICE_ERROR_ALERT_IDLE;
121358
122609
  name;
121359
122610
  parentDeviceId;
121360
122611
  role;
@@ -121707,51 +122958,81 @@ var BaseDevice = class {
121707
122958
  /**
121708
122959
  * Publish the device's fault. The slice is written; on an EDGE (a fault
121709
122960
  * starts, or one resolves) an attention episode opens or closes through the
121710
- * alerts cap, which the notification center announces as
121711
- * `device-attention-required` / `-resolved`. An unknown reading is never an
121712
- * edge. No rule exists by default: it notifies when the operator makes one.
122961
+ * alerts cap, at the severity of the fault's tier: an `error` fault is a
122962
+ * critical alert, which the notification center announces as
122963
+ * `device-attention-required` / `-resolved`; a `warning` fault is a warning
122964
+ * alert and announces nothing until it becomes an error. An unknown reading
122965
+ * is never an edge. No rule exists by default: it notifies when the operator
122966
+ * makes one.
122967
+ *
122968
+ * An alert write that fails is tried again on the next reading that still
122969
+ * asks for it, `DEVICE_ERROR_ALERT_MAX_ATTEMPTS` times at most.
121713
122970
  */
121714
122971
  async publishError(reading) {
121715
122972
  const previous = this.getCapSlice(errorCapability);
121716
122973
  if (reading.active === null && previous !== null && previous.active !== null) return;
121717
122974
  const now = Date.now();
121718
122975
  const edge = deviceErrorEdge(previous, reading);
121719
- const next = edge === "start" && reading.since === null ? {
122976
+ const next = this.withErrorSince(previous, reading, edge === "start", now);
122977
+ this.setCapSlice(errorCapability, next);
122978
+ const plan = planDeviceErrorAlert(this.errorAlertDelivery, edge, previous, next);
122979
+ this.errorAlertDelivery = plan.delivery;
122980
+ if (plan.write === null) return;
122981
+ await this.writeErrorAlert(plan.write, next, now);
122982
+ }
122983
+ /** A fault keeps the start it was given: stamped on the start, carried while it lasts. */
122984
+ withErrorSince(previous, reading, starts, now) {
122985
+ if (reading.active !== true || reading.since !== null) return reading;
122986
+ if (starts) return {
121720
122987
  ...reading,
121721
122988
  since: now
121722
- } : reading;
121723
- this.setCapSlice(errorCapability, next);
121724
- if (edge === null) return;
121725
- const alerts = this.ctx.api.alerts;
121726
- if (alerts === void 0) {
121727
- this.ctx.logger.warn("device error: attention event skipped — alerts capability missing", {
121728
- tags: { deviceId: this.id },
121729
- meta: { edge }
121730
- });
121731
- return;
121732
- }
122989
+ };
122990
+ return previous?.since == null ? reading : {
122991
+ ...reading,
122992
+ since: previous.since
122993
+ };
122994
+ }
122995
+ /** One attempt at the alert write the plan asked for; a failure stays owed, under the bound. */
122996
+ async writeErrorAlert(write, status, now) {
122997
+ const attempt = this.errorAlertDelivery.attempts + 1;
121733
122998
  try {
121734
- if (edge === "start") await alerts.emit.mutate(buildDeviceErrorAlert(this.id, this.name, next, now));
121735
- else await alerts.update.mutate({
121736
- alertId: deviceErrorAlertId(this.id),
121737
- patch: {
121738
- status: "completed",
121739
- read: true,
121740
- updatedAt: now
121741
- }
121742
- });
121743
- this.ctx.logger.info(`device error: ${edge === "start" ? "raised" : "resolved"}`, {
122999
+ const alerts = this.ctx.api.alerts;
123000
+ if (alerts === void 0) throw new Error("alerts capability missing");
123001
+ if (write === "open") {
123002
+ await alerts.emit.mutate(buildDeviceErrorAlert(this.id, this.name, status, now));
123003
+ this.errorAlertDelivery = DEVICE_ERROR_ALERT_IDLE;
123004
+ } else {
123005
+ await alerts.update.mutate({
123006
+ alertId: deviceErrorAlertId(this.id),
123007
+ patch: {
123008
+ status: "completed",
123009
+ read: true,
123010
+ updatedAt: now
123011
+ }
123012
+ });
123013
+ this.errorAlertDelivery = DEVICE_ERROR_ALERT_IDLE;
123014
+ }
123015
+ this.ctx.logger.info(`device error: ${write === "open" ? "raised" : "resolved"}`, {
121744
123016
  tags: { deviceId: this.id },
121745
123017
  meta: {
121746
- code: next.code,
121747
- label: next.label
123018
+ code: status.code,
123019
+ label: status.label,
123020
+ severity: status.severity,
123021
+ attempt
121748
123022
  }
121749
123023
  });
121750
123024
  } catch (err) {
121751
- this.ctx.logger.warn("device error: attention event failed", {
123025
+ const givenUp = attempt >= 5;
123026
+ this.errorAlertDelivery = {
123027
+ ...this.errorAlertDelivery,
123028
+ pending: givenUp ? null : write,
123029
+ attempts: givenUp ? 0 : attempt
123030
+ };
123031
+ this.ctx.logger.warn(givenUp ? "device error: attention event given up, the alert is not written" : "device error: attention event failed, retried on the next reading", {
121752
123032
  tags: { deviceId: this.id },
121753
123033
  meta: {
121754
- edge,
123034
+ write,
123035
+ attempt,
121755
123036
  error: errMsg$3(err)
121756
123037
  }
121757
123038
  });
@@ -129619,6 +130900,24 @@ var IntercomFailureReport = class {
129619
130900
  /** The process-wide instance every camera in this addon notes into. */
129620
130901
  var intercomFailureReport = new IntercomFailureReport();
129621
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
129622
130921
  //#region src/baichuan-webhook-shared.ts
129623
130922
  /** The data-plane prefix this addon serves the camera push on: `/addon/<addonId>/webhook/<stableId>`. */
129624
130923
  var BAICHUAN_WEBHOOK_PREFIX = "webhook";
@@ -129724,12 +131023,21 @@ function reportsPowerSource(info) {
129724
131023
  * sleep, or while on mains or a panel, reports `0` as a placeholder — device
129725
131024
  * 3628 sat at 100% on its adapter and raised a low-battery notification on
129726
131025
  * every hourly wake. Those zeros are UNMEASURED: the caller keeps the last real
129727
- * level. A `0` from an awake camera running on its cell alone (or of unknown
129728
- * source) is a genuine empty cell and passes, as does every non-zero level.
131026
+ * level.
131027
+ *
131028
+ * The same placeholder also arrives with NO power source to blame (device 3628,
131029
+ * its own Baichuan read): `batteryPercent: 0, chargeStatus: "none",
131030
+ * adapterStatus: "none", voltage: 0, current: 0, temperature: 0`, awake — an
131031
+ * all-zero payload that raised an empty-battery alert; the next read was 99.
131032
+ * A `0` level with a present `voltage` of 0 carries no cell measurement at all,
131033
+ * so it is UNMEASURED too. A `0` from an awake camera on its cell alone with a
131034
+ * real voltage (or a payload without the field) is a genuine empty cell and
131035
+ * passes, as does every non-zero level.
129729
131036
  */
129730
131037
  function isMeasuredCameraBatteryLevel(level, context) {
129731
131038
  if (level !== 0) return true;
129732
131039
  if (context.sleeping) return false;
131040
+ if (context.voltage === 0) return false;
129733
131041
  return context.charging !== "dc" && context.charging !== "solar";
129734
131042
  }
129735
131043
  /** What the cell is doing, from `chargeStatus`. Absent is `'unknown'`, never `'idle'` (D315). */
@@ -129763,6 +131071,12 @@ var BATTERY_REFRESH_MINUTES_KEY = "batteryRefreshMinutes";
129763
131071
  var BATTERY_REFRESH_TICK_MS = 6e4;
129764
131072
  /** The least time between two attempts in one window. */
129765
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;
129766
131080
  /** The one refresh step whose failure does not hold the window open. */
129767
131081
  var SOFT_FAILURE_STEP = "snapshot";
129768
131082
  var MAX_WAKE_LEAD_MS = 5 * 6e4;
@@ -129812,12 +131126,48 @@ function decideBatteryRefresh(input) {
129812
131126
  };
129813
131127
  return { kind: "wake-then-refresh" };
129814
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
+ }
129815
131164
  var BatteryHourlyRefresh = class {
129816
131165
  deps;
129817
131166
  inFlight = null;
129818
131167
  attemptWindow = Number.NEGATIVE_INFINITY;
129819
131168
  attempts = 0;
129820
131169
  lastAttemptAt;
131170
+ hydrated = false;
129821
131171
  constructor(deps) {
129822
131172
  this.deps = deps;
129823
131173
  }
@@ -129842,6 +131192,7 @@ var BatteryHourlyRefresh = class {
129842
131192
  const intervalMs = this.deps.intervalMs();
129843
131193
  const offsetMs = intervalMs > 0 ? staggerOffsetMs(this.deps.deviceId, intervalMs) : 0;
129844
131194
  const window = intervalMs > 0 ? windowIndex(nowMs, intervalMs, offsetMs) : 0;
131195
+ this.hydrateAttempts();
129845
131196
  if (window !== this.attemptWindow) {
129846
131197
  this.attemptWindow = window;
129847
131198
  this.attempts = 0;
@@ -129860,14 +131211,67 @@ var BatteryHourlyRefresh = class {
129860
131211
  this.logSkip(decision.reason, trigger);
129861
131212
  return false;
129862
131213
  }
131214
+ if (this.shouldDeferForStream()) {
131215
+ this.noteStreamDeferred(trigger);
131216
+ return false;
131217
+ }
131218
+ if (this.deps.isStreaming?.() === true) this.logDeferralBoundReached(trigger);
129863
131219
  this.attempts += 1;
129864
131220
  this.lastAttemptAt = nowMs;
131221
+ this.deps.attemptLedger?.write({
131222
+ window,
131223
+ attempts: this.attempts,
131224
+ lastAttemptAt: nowMs
131225
+ });
129865
131226
  const run = this.run(decision.kind, trigger).finally(() => {
129866
131227
  this.inFlight = null;
129867
131228
  });
129868
131229
  this.inFlight = run;
129869
131230
  return run;
129870
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
+ }
129871
131275
  async run(kind, trigger) {
129872
131276
  const { logger, deviceId } = this.deps;
129873
131277
  try {
@@ -132038,6 +133442,7 @@ async function connectReolinkHub(connection) {
132038
133442
  transport: connection.transport,
132039
133443
  ...connection.uid ? { uid: connection.uid } : {}
132040
133444
  });
133445
+ api.setGeneralSessionRecycling({ guard: () => true });
132041
133446
  await api.login();
132042
133447
  return api;
132043
133448
  }
@@ -132143,14 +133548,14 @@ function isSummarySourced(source) {
132143
133548
  function decideSleepCommit(input) {
132144
133549
  const { current, next, source, lastFirstHandCommitAt, nowMs, videoFlowing, wired } = input;
132145
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
+ };
132146
133557
  if (next === true && isSecondHand(source)) {
132147
133558
  const sinceMs = nowMs - lastFirstHandCommitAt;
132148
- if (wired) return {
132149
- kind: "refused",
132150
- reason: "wired",
132151
- windowMs: 0,
132152
- sinceLastChangeMs: sinceMs
132153
- };
132154
133559
  if (videoFlowing) return {
132155
133560
  kind: "refused",
132156
133561
  reason: "video-flowing",
@@ -132182,6 +133587,49 @@ function decideSleepCommit(input) {
132182
133587
  };
132183
133588
  }
132184
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
132185
133633
  //#region src/session-limit.ts
132186
133634
  /**
132187
133635
  * How long the broker lets a Home Hub child's session run before it re-dials on
@@ -132195,15 +133643,25 @@ function decideSleepCommit(input) {
132195
133643
  */
132196
133644
  var HOME_HUB_SESSION_LIMIT_MS = 27 * 6e4;
132197
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
+ /**
132198
133654
  * Stamp the descriptors with the session limit the broker acts on. Only a
132199
- * battery child of a hub gets one: a standalone camera has no such cut, and
132200
- * 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.
132201
133658
  */
132202
133659
  function withSessionLimit(descriptors, input) {
132203
- 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;
132204
133662
  return descriptors.map((d) => ({
132205
133663
  ...d,
132206
- maxSessionMs: HOME_HUB_SESSION_LIMIT_MS
133664
+ maxSessionMs
132207
133665
  }));
132208
133666
  }
132209
133667
  //#endregion
@@ -132429,6 +133887,15 @@ var reolinkAccessoryBaseSchema = object({
132429
133887
  channel: number().int().nonnegative().default(0),
132430
133888
  kind: string()
132431
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
+ }
132432
133899
  //#endregion
132433
133900
  //#region src/accessories/floodlight.ts
132434
133901
  /**
@@ -132478,13 +133945,6 @@ var FloodlightAccessory = class extends BaseDevice {
132478
133945
  * /setMotionTrigger. Read by the parent's align loop via the
132479
133946
  * `ReolinkAccessoryRef.isInCooldown` impl below. */
132480
133947
  lastSetAtMs = 0;
132481
- /** Becomes `true` once both `refreshLightFromFirmware` and
132482
- * `refreshMotionTriggerFromFirmware` have completed at least one
132483
- * successful round-trip. Used by `onProbe` to decide whether the
132484
- * boot-time sleep-gate should force a wake (no cached state) or
132485
- * skip (already-have-state path). Mirrors the Reolink mobile app's
132486
- * one-shot wake-and-fetch on launch. */
132487
- hasFetchedFromFirmware = false;
132488
133948
  constructor(ctx, parent) {
132489
133949
  super(ctx, floodlightAccessorySchema, {
132490
133950
  type: DeviceType.Light,
@@ -132544,7 +134004,6 @@ var FloodlightAccessory = class extends BaseDevice {
132544
134004
  level: brightness,
132545
134005
  lastChangedAt: ts
132546
134006
  });
132547
- this.hasFetchedFromFirmware = true;
132548
134007
  } catch (err) {
132549
134008
  this.ctx.logger.warn("floodlight refresh FAILED — slice stays at cold-start seed", {
132550
134009
  tags: { deviceId: this.id },
@@ -132556,46 +134015,29 @@ var FloodlightAccessory = class extends BaseDevice {
132556
134015
  }
132557
134016
  }
132558
134017
  /**
132559
- * Kernel-driven probe (Phase 4). Runs on every device construction
132560
- * + addon restart. Pulls the actual on/off + brightness +
132561
- * motion-trigger state from the camera so the slices reflect
132562
- * firmware truth instead of the conservative cold-start seeds
132563
- * written in `registerSwitchCap` / `registerBrightnessCap` /
132564
- * `registerMotionTriggerCap`.
132565
- *
132566
- * Sleeping battery cam:
132567
- * 1. **First-time probe (no cached state yet)** — force a one-shot
132568
- * wake + fetch so the operator sees a populated UI at launch.
132569
- * Mirrors the Reolink mobile app: at app launch it wakes the
132570
- * cam once to fetch initial state. Without this, an aggressive
132571
- * sleep timeout (~14s) can return the cam to sleep before the
132572
- * kernel finishes its initial probe pass — the retry chain
132573
- * exhausts and the slices never populate.
132574
- * 2. **Subsequent probes (slices already populated)** — skip. A
132575
- * poll on a sleeping camera returns 400 and drains the
132576
- * battery. The parent's `alignAuxDevicesState('wake')` runs
132577
- * on the next wake transition (simpleEvent push or sleep-poll
132578
- * 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.
132579
134024
  */
132580
134025
  async onProbe() {
132581
- if (this.parent.isBatteryCam?.() === true && this.parent.isSleeping?.() === true) {
132582
- if (this.hasFetchedFromFirmware) {
132583
- this.ctx.logger.debug("floodlight onProbe skipped — parent battery cam is sleeping (have cached state)", { tags: { deviceId: this.id } });
132584
- return;
132585
- }
132586
- this.ctx.logger.info("floodlight onProbe forcing wake — initial probe with no cached state", { tags: { deviceId: this.id } });
132587
- try {
132588
- await (await this.api).wakeUp(this.channel, { waitAfterWakeMs: 2e3 });
132589
- await sleep(1e3);
132590
- } catch (err) {
132591
- this.ctx.logger.warn("floodlight wake before initial probe failed — proceeding anyway", {
132592
- tags: { deviceId: this.id },
132593
- meta: { error: err instanceof Error ? err.message : String(err) }
132594
- });
132595
- }
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;
132596
134029
  }
132597
134030
  await Promise.all([this.refreshLightFromFirmware(), this.refreshMotionTriggerFromFirmware()]);
132598
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
+ }
132599
134041
  /** Refresh motion-trigger from firmware and write the slice. Also
132600
134042
  * mirrors the camera-current `duration` + `detectType` into config
132601
134043
  * so the Settings form shows firmware truth instead of stale
@@ -132617,7 +134059,6 @@ var FloodlightAccessory = class extends BaseDevice {
132617
134059
  lastChangedAt,
132618
134060
  lastFetchedAt: Date.now()
132619
134061
  });
132620
- this.hasFetchedFromFirmware = true;
132621
134062
  const patch = {};
132622
134063
  if (typeof result?.duration === "number" && result.duration > 0) patch["motionLightDurationS"] = result.duration;
132623
134064
  if (typeof result?.detectType === "string") {
@@ -132713,7 +134154,7 @@ var FloodlightAccessory = class extends BaseDevice {
132713
134154
  runtimeState: this.runtimeState,
132714
134155
  cap: motionTriggerCapability,
132715
134156
  ownDeviceId: this.id,
132716
- refresh: () => this.refreshMotionTriggerFromFirmware(),
134157
+ refresh: () => this.revalidateMotionTrigger(),
132717
134158
  staleMs: STALE_MS$1,
132718
134159
  empty: () => ({
132719
134160
  enabled: false,
@@ -132864,12 +134305,6 @@ var PirAccessory = class extends BaseDevice {
132864
134305
  /** Nothing reported: the kernel derives this device's features from its bound caps (#459). */
132865
134306
  features = [];
132866
134307
  lastSetAtMs = 0;
132867
- /** Becomes `true` after the first successful `refreshFromFirmware`
132868
- * round-trip. Used by `onProbe` to decide whether the boot-time
132869
- * sleep-gate should force a wake (no cached state) or skip
132870
- * (already-have-state path). Mirrors the Reolink mobile app's
132871
- * one-shot wake-and-fetch on launch. */
132872
- hasFetchedFromFirmware = false;
132873
134308
  constructor(ctx, parent) {
132874
134309
  super(ctx, pirAccessorySchema, {
132875
134310
  type: DeviceType.Switch,
@@ -132945,7 +134380,6 @@ var PirAccessory = class extends BaseDevice {
132945
134380
  }
132946
134381
  });
132947
134382
  this.refreshSwitchFromExternal(state);
132948
- this.hasFetchedFromFirmware = true;
132949
134383
  } catch (err) {
132950
134384
  this.ctx.logger.warn("pir refresh FAILED — slice stays at cold-start seed", {
132951
134385
  tags: { deviceId: this.id },
@@ -132957,45 +134391,17 @@ var PirAccessory = class extends BaseDevice {
132957
134391
  }
132958
134392
  }
132959
134393
  /**
132960
- * Kernel-driven probe — runs at device construction (addon boot,
132961
- * device add). For battery cams currently asleep we have two
132962
- * cases:
132963
- *
132964
- * 1. **First-time probe (no cached state yet)** — force a one-shot
132965
- * wake + fetch. Mirrors the Reolink mobile app's launch
132966
- * behaviour: the app wakes the cam once at startup so the
132967
- * operator sees a populated UI. Without this, an aggressive
132968
- * sleep timeout (~14s after boot on Argus / battery doorbell
132969
- * firmwares) can put the cam back to sleep before the
132970
- * kernel's initial probe pass completes — the slice never
132971
- * gets populated, the kernel's retry chain exhausts after 5
132972
- * attempts, and the operator sees an empty PIR switch state
132973
- * until they manually wake the cam.
132974
- * 2. **Subsequent probes (slice already populated)** — skip the
132975
- * fetch. A Baichuan poll on a sleeping camera returns 400,
132976
- * drains the battery, and would clobber the cached value
132977
- * anyway. The parent's `alignAuxDevicesState('wake')` path
132978
- * (simpleEvent `awake` push or sleep-poll backstop)
132979
- * refreshes us when the cam wakes naturally.
132980
- *
132981
- * 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.
132982
134400
  */
132983
134401
  async onProbe() {
132984
- if (this.parent.isBatteryCam?.() === true && this.parent.isSleeping?.() === true) {
132985
- if (this.hasFetchedFromFirmware) {
132986
- this.ctx.logger.debug("pir onProbe skipped — parent battery cam is sleeping (have cached state)", { tags: { deviceId: this.id } });
132987
- return;
132988
- }
132989
- this.ctx.logger.info("pir onProbe forcing wake — initial probe with no cached state", { tags: { deviceId: this.id } });
132990
- try {
132991
- await (await this.api).wakeUp(this.channel, { waitAfterWakeMs: 2e3 });
132992
- await sleep(1e3);
132993
- } catch (err) {
132994
- this.ctx.logger.warn("pir wake before initial probe failed — proceeding anyway", {
132995
- tags: { deviceId: this.id },
132996
- meta: { error: err instanceof Error ? err.message : String(err) }
132997
- });
132998
- }
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;
132999
134405
  }
133000
134406
  await this.refreshFromFirmware();
133001
134407
  }
@@ -133223,12 +134629,6 @@ var SirenAccessory = class extends BaseDevice {
133223
134629
  lastSetAtMs = 0;
133224
134630
  /** Clears the `siren` slice when a timed activation runs out. */
133225
134631
  sirenTimer = null;
133226
- /** Becomes `true` after the first successful
133227
- * `refreshMotionTriggerFromFirmware` round-trip. Used by `onProbe`
133228
- * to decide whether the boot-time sleep-gate should force a wake
133229
- * (no cached state) or skip (already-have-state path). Mirrors the
133230
- * Reolink mobile app's one-shot wake-and-fetch on launch. */
133231
- hasFetchedFromFirmware = false;
133232
134632
  constructor(ctx, parent) {
133233
134633
  super(ctx, sirenAccessorySchema, {
133234
134634
  type: DeviceType.Siren,
@@ -133265,42 +134665,26 @@ var SirenAccessory = class extends BaseDevice {
133265
134665
  };
133266
134666
  }
133267
134667
  /**
133268
- * Kernel-driven probe (Phase 4). Runs on every device construction
133269
- * + addon restart. Pulls the actual motion-trigger enable state
133270
- * from the camera so the slice reflects firmware truth. The switch
133271
- * (manual fire) cap is intentionally NOT refreshed — Reolink's
133272
- * `getSiren` returns OFF as soon as the audio task ends.
133273
- *
133274
- * Sleeping battery cam:
133275
- * 1. **First-time probe (no cached state yet)** — force a one-shot
133276
- * wake + fetch so the operator sees a populated UI at launch.
133277
- * Mirrors the Reolink mobile app: at app launch it wakes the
133278
- * cam once to fetch initial state. Without this, an aggressive
133279
- * sleep timeout (~14s) can return the cam to sleep before the
133280
- * kernel finishes its initial probe pass — the retry chain
133281
- * exhausts and the slice never populates.
133282
- * 2. **Subsequent probes (slice already populated)** — skip. A
133283
- * poll on a sleeping camera returns 400 and drains the
133284
- * battery. The parent's `alignAuxDevicesState('wake')` path
133285
- * (simpleEvent `awake` push or sleep-poll backstop) refreshes
133286
- * 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.
133287
134674
  */
133288
134675
  async onProbe() {
133289
- if (this.parent.isBatteryCam?.() === true && this.parent.isSleeping?.() === true) {
133290
- if (this.hasFetchedFromFirmware) {
133291
- this.ctx.logger.debug("siren onProbe skipped — parent battery cam is sleeping (have cached state)", { tags: { deviceId: this.id } });
133292
- return;
133293
- }
133294
- this.ctx.logger.info("siren onProbe forcing wake — initial probe with no cached state", { tags: { deviceId: this.id } });
133295
- try {
133296
- await (await this.api).wakeUp(this.channel, { waitAfterWakeMs: 2e3 });
133297
- await sleep(1e3);
133298
- } catch (err) {
133299
- this.ctx.logger.warn("siren wake before initial probe failed — proceeding anyway", {
133300
- tags: { deviceId: this.id },
133301
- meta: { error: err instanceof Error ? err.message : String(err) }
133302
- });
133303
- }
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;
133304
134688
  }
133305
134689
  await this.refreshMotionTriggerFromFirmware();
133306
134690
  }
@@ -133316,7 +134700,6 @@ var SirenAccessory = class extends BaseDevice {
133316
134700
  lastChangedAt,
133317
134701
  lastFetchedAt: Date.now()
133318
134702
  });
133319
- this.hasFetchedFromFirmware = true;
133320
134703
  const items = audioTask?.typeScheduleList?.item ?? [];
133321
134704
  if (items.length > 0) {
133322
134705
  const recovered = recoverSirenDetectTypeFromItems(items);
@@ -133545,7 +134928,7 @@ var SirenAccessory = class extends BaseDevice {
133545
134928
  runtimeState: this.runtimeState,
133546
134929
  cap: motionTriggerCapability,
133547
134930
  ownDeviceId: this.id,
133548
- refresh: () => this.refreshMotionTriggerFromFirmware(),
134931
+ refresh: () => this.revalidateMotionTrigger(),
133549
134932
  staleMs: STALE_MS,
133550
134933
  empty: () => ({
133551
134934
  enabled: false,
@@ -133869,17 +135252,41 @@ function effectiveProbeFlags(sliceProbed, sliceFlags, deviceCache) {
133869
135252
  ...resolveAccessoryProbeFlags(false, {}, deviceCache)
133870
135253
  };
133871
135254
  }
135255
+ function abilityReadQuality(debug) {
135256
+ return debug?.abilitiesAvailable === true && debug.supportAvailable === true ? "full" : "partial";
135257
+ }
135258
+ /**
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
+ }
133872
135277
  /**
133873
- * The typed answer for `getAccessoryChildren()`. A probe that completed THIS
133874
- * session is a definitive read (`complete`) even while the parent is asleep
133875
- * or offline, so the kernel's reconcile can retire a child whose flag is now
133876
- * false (it still needs a second agreeing probe, D49). Flags restored from
133877
- * `deviceCache` alone, or no probe at all, are `unknown`: they spawn but
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
133878
135284
  * never prune. A legacy bare array was `unknown` whenever the parent was
133879
135285
  * offline, which is how a ghost Floodlight outlived `hasFloodlight:false`.
133880
135286
  */
133881
- function accessoryChildrenAnswerFor(sliceProbed, sliceFlags, specs) {
135287
+ function accessoryChildrenAnswerFor(sliceProbed, sliceFlags, specs, fullReadThisSession) {
133882
135288
  if (!sliceProbed) return accessoryChildrenUnknown("no probe completed this session", specs);
135289
+ if (!fullReadThisSession) return accessoryChildrenUnknown("no full ability read this session", specs);
133883
135290
  if (!ACCESSORY_FLAGS.some(([flag]) => typeof sliceFlags[flag] === "boolean")) return accessoryChildrenUnknown("probe carried no ability flags", specs);
133884
135291
  return {
133885
135292
  kind: "complete",
@@ -135203,8 +136610,17 @@ function createKeepAwakeLoop(deps) {
135203
136610
  let handle = null;
135204
136611
  let failing = false;
135205
136612
  const tick = () => {
136613
+ if (deps.videoFlowing?.() === true) {
136614
+ try {
136615
+ deps.onSkip?.();
136616
+ } catch {}
136617
+ return;
136618
+ }
135206
136619
  deps.wake().then(() => {
135207
136620
  failing = false;
136621
+ try {
136622
+ deps.onSuccess?.();
136623
+ } catch {}
135208
136624
  }).catch((err) => {
135209
136625
  const first = !failing;
135210
136626
  failing = true;
@@ -135995,6 +137411,13 @@ var REOLINK_AUDIO_STREAM_KEYS = [
135995
137411
  "thirdStream"
135996
137412
  ];
135997
137413
  /** Generate a short random hex token for per-stream RTSP-style credentials. */
137414
+ /**
137415
+ * The error a login dialled with replaced settings ends with. A caller still
137416
+ * awaiting it retries through `ensureApi`, which dials with the new settings.
137417
+ */
137418
+ function supersededLoginError(cause) {
137419
+ return new Error("Reolink login superseded by a connection settings change", { cause: cause ?? void 0 });
137420
+ }
135998
137421
  function randomToken(bytes) {
135999
137422
  return (0, node_crypto.randomBytes)(bytes).toString("hex");
136000
137423
  }
@@ -136112,6 +137535,10 @@ function coerceNumber(value) {
136112
137535
  }
136113
137536
  return null;
136114
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;
136115
137542
  /**
136116
137543
  * Baichuan's native PTZ speed scale is 1..63; `runPtz` maps the cap's
136117
137544
  * normalized 0..1 onto it. Named because the autotrack loop has to know the
@@ -136284,6 +137711,9 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
136284
137711
  }
136285
137712
  /** Lazy-connected Baichuan API. Spans the lifetime of every active stream. */
136286
137713
  api = null;
137714
+ /** Why the previous Baichuan session ended; named on the next login's log line. */
137715
+ lastSessionDropReason = null;
137716
+ loginCount = 0;
136287
137717
  /**
136288
137718
  * Stable bound handler for `api.onSimpleEvent` — created ONCE in
136289
137719
  * the class so every `onSimpleEvent` / `offSimpleEvent` call uses
@@ -136383,18 +137813,130 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
136383
137813
  tags: { deviceId: this.id },
136384
137814
  meta: { activeStreams }
136385
137815
  }),
137816
+ onSuccess: () => this.noteKeepAwakeResult(true, null),
137817
+ videoFlowing: () => Date.now() - this.lastVideoFlowAt < KEEP_AWAKE_INTERVAL_MS,
137818
+ onSkip: () => this.noteKeepAwakeSkipped(),
136386
137819
  onFailure: (err, first) => {
137820
+ const error = err instanceof Error ? err.message : String(err);
136387
137821
  (first ? this.ctx.logger.info.bind(this.ctx.logger) : this.ctx.logger.debug.bind(this.ctx.logger))("keep-awake: wake failed", {
136388
137822
  tags: { deviceId: this.id },
136389
- meta: { error: err instanceof Error ? err.message : String(err) }
137823
+ meta: { error }
136390
137824
  });
137825
+ this.noteKeepAwakeResult(false, error);
136391
137826
  }
136392
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
+ }
136393
137917
  syncKeepAwake() {
136394
137918
  this.keepAwake.sync(this.active.size);
136395
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
+ }
136396
137930
  /** Login lock — concurrent demand events must not race the login flow. */
136397
137931
  loginPromise = null;
137932
+ /**
137933
+ * Bumped by `disconnectAll`. A login started under an older generation was
137934
+ * dialled with the OLD settings (e.g. the relay before the operator picked
137935
+ * local-direct): it is closed and discarded instead of becoming `this.api`.
137936
+ */
137937
+ loginGeneration = 0;
137938
+ /** The client a login in flight is dialling, so `disconnectAll` can abort it. */
137939
+ pendingLoginApi = null;
136398
137940
  /** Wall-clock ms of the last video packet the stream server produced; 0 = none yet. */
136399
137941
  lastVideoFlowAt = 0;
136400
137942
  /** True once we've discovered (via getBatteryInfo) that this is a battery cam. */
@@ -136473,6 +138015,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
136473
138015
  batteryUpdateTimer = null;
136474
138016
  /** Set by `removeDevice`: nothing may re-arm a timer on a removed camera. */
136475
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;
136476
138025
  /** Single-flight gate so two interval fires can't overlap. */
136477
138026
  /** Aux accessory references registered by spawned children
136478
138027
  * (siren / floodlight / pir). The parent's centralised align
@@ -137112,9 +138661,18 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137112
138661
  } catch (err) {
137113
138662
  this.ctx.logger.debug("reolink deviceCache snapshot persist failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
137114
138663
  }
137115
- if (slices === void 0 && this.isBattery && this.isEmailPushEligible) await this.refreshCameraEmailConfig().catch((err) => {
137116
- this.ctx.logger.debug("reolink email config probe failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
137117
- });
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
+ }
137118
138676
  }
137119
138677
  /**
137120
138678
  * Admin-only raw-read debug surface (D346): return the library's response
@@ -137228,7 +138786,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137228
138786
  * leave the catalog stale rather than stamping it fresh.
137229
138787
  */
137230
138788
  async wakeForClipCatalogRefresh() {
137231
- 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`);
137232
138790
  }
137233
138791
  /**
137234
138792
  * Wake this camera because the OPERATOR asked for one of its clips — a
@@ -137238,7 +138796,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137238
138796
  * so the service can refuse `wake-timeout` by name.
137239
138797
  */
137240
138798
  async wakeForClipRead(timeoutMs) {
137241
- return this.wakeIfSleeping(timeoutMs);
138799
+ return this.wakeIfSleeping("clip-read", timeoutMs);
137242
138800
  }
137243
138801
  clipTimeZoneWarned = { done: false };
137244
138802
  getClipDeviceRef() {
@@ -137292,7 +138850,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137292
138850
  if (kinds.includes(AccessoryKind.Siren)) push(AccessoryKind.Siren, DeviceType.Siren, ACCESSORY_LABEL[AccessoryKind.Siren]);
137293
138851
  if (kinds.includes(AccessoryKind.Floodlight)) push(AccessoryKind.Floodlight, DeviceType.Light, ACCESSORY_LABEL[AccessoryKind.Floodlight]);
137294
138852
  if (kinds.includes(AccessoryKind.PirSensor)) push(AccessoryKind.PirSensor, DeviceType.Switch, ACCESSORY_LABEL[AccessoryKind.PirSensor]);
137295
- return accessoryChildrenAnswerFor(this.hasProbed(), super.getProbeFlags(), out);
138853
+ return accessoryChildrenAnswerFor(this.hasProbed(), super.getProbeFlags(), out, this.fullAbilityReadThisSession === true);
137296
138854
  }
137297
138855
  /**
137298
138856
  * Resolver injected by the provider (`setEmailPushParamsResolver`) so
@@ -137328,7 +138886,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137328
138886
  * camera. No-op for non-battery or already-awake cams. Best-effort:
137329
138887
  * returns whether the camera is (now) reachable/awake.
137330
138888
  */
137331
- async wakeIfSleeping(timeoutMs = 15e3) {
138889
+ async wakeIfSleeping(caller, timeoutMs = 15e3) {
137332
138890
  if (!this.isBattery || !this.sleeping) return true;
137333
138891
  let api;
137334
138892
  try {
@@ -137339,7 +138897,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137339
138897
  this.markWakeIssued();
137340
138898
  this.ctx.logger.info("proactive action: waking sleeping battery cam", {
137341
138899
  tags: { deviceId: this.id },
137342
- meta: { timeoutMs }
138900
+ meta: {
138901
+ timeoutMs,
138902
+ caller
138903
+ }
137343
138904
  });
137344
138905
  this.ctx.eventBus.emit(createEvent(EventCategory.BatteryOnWakeStarted, this.eventSource(), { deviceId: this.id }));
137345
138906
  const channel = this.getChannel();
@@ -137359,7 +138920,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137359
138920
  } catch (err) {
137360
138921
  this.ctx.logger.warn("proactive action: wake did not complete in time", {
137361
138922
  tags: { deviceId: this.id },
137362
- meta: { error: err instanceof Error ? err.message : String(err) }
138923
+ meta: {
138924
+ caller,
138925
+ error: err instanceof Error ? err.message : String(err)
138926
+ }
137363
138927
  });
137364
138928
  return false;
137365
138929
  }
@@ -137408,7 +138972,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137408
138972
  "vehicle"
137409
138973
  ];
137410
138974
  const attachmentType = this.config.get("emailPushAttachment") ?? "picture";
137411
- await this.wakeIfSleeping();
138975
+ await this.wakeIfSleeping("auto-configure-email-push");
137412
138976
  const api = await this.ensureApi();
137413
138977
  this.ctx.logger.info("email-push: auto-configuring camera", {
137414
138978
  tags: { deviceId: this.id },
@@ -137458,7 +139022,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137458
139022
  if (!this.baichuanWebhookParamsResolver) throw userError("reolink.webhook-not-wired", void 0, "HaCfg Webhook Server is not wired — restart the Reolink addon");
137459
139023
  const params = await this.baichuanWebhookParamsResolver();
137460
139024
  if (!params) throw new Error("The HaCfg webhook cannot be armed for this camera (it is not a standalone battery camera).");
137461
- await this.wakeIfSleeping();
139025
+ await this.wakeIfSleeping("auto-configure-baichuan-webhook");
137462
139026
  const api = await this.ensureApi();
137463
139027
  const supported = await api.probeBaichuanWebhookSupport();
137464
139028
  this.baichuanWebhookSupportedCached = supported;
@@ -137557,7 +139121,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137557
139121
  * Push tab read.
137558
139122
  */
137559
139123
  async refreshCameraEmailConfig() {
137560
- await this.wakeIfSleeping();
139124
+ await this.wakeIfSleeping("refresh-camera-email-config");
137561
139125
  const api = await this.ensureApi();
137562
139126
  const channel = this.getChannel();
137563
139127
  const [email, task] = await Promise.all([api.getEmail(), api.getEmailTask(channel).catch(() => null)]);
@@ -137674,7 +139238,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137674
139238
  await this.autoConfigureBaichuanWebhook();
137675
139239
  });
137676
139240
  this.registerDeviceAction("refresh-settings", deviceCustomAction(unknown(), RefreshSettingsResultSchema, { kind: "mutation" }), async () => {
137677
- const awake = await this.wakeIfSleeping();
139241
+ const awake = await this.wakeIfSleeping("operator-rehydrate");
137678
139242
  const [snapshot, warm] = await Promise.allSettled([this.refreshParentSettingsSnapshot(void 0, "operator"), this.warmCapSlicesOnWake({ force: true })]);
137679
139243
  const warmed = warm.status === "fulfilled" ? warm.value.warmed : 0;
137680
139244
  const capsTotal = this.capWarmers.size;
@@ -137704,6 +139268,12 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137704
139268
  this.registerRecordingOnboardCap();
137705
139269
  this.registerStreamCatalogProvider();
137706
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() {
137707
139277
  const cache = this.config.get("deviceCache");
137708
139278
  if (cache?.deviceType === "battery-cam" || cache?.hasBattery === true) {
137709
139279
  this.isBattery = true;
@@ -137767,7 +139337,8 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137767
139337
  const reported = typeof info.batteryPercent === "number" ? Math.max(0, Math.min(100, Math.round(info.batteryPercent))) : void 0;
137768
139338
  const measured = reported !== void 0 && isMeasuredCameraBatteryLevel(reported, {
137769
139339
  sleeping,
137770
- charging
139340
+ charging,
139341
+ voltage: info.voltage
137771
139342
  });
137772
139343
  if (reported === 0) this.ctx.logger.info("battery read reporting 0", {
137773
139344
  tags: { deviceId: this.id },
@@ -137972,6 +139543,26 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
137972
139543
  return false;
137973
139544
  }
137974
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
+ }
137975
139566
  /**
137976
139567
  * THE single writer of the `battery.sleeping` slice.
137977
139568
  *
@@ -138001,7 +139592,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
138001
139592
  lastFirstHandCommitAt: this.sleepStateChangedAt,
138002
139593
  nowMs: Date.now(),
138003
139594
  videoFlowing: Date.now() - this.lastVideoFlowAt < VIDEO_FLOW_FRESH_MS,
138004
- wired: this.config.get("deviceCache")?.powerSourceSnapshot?.source === "adapter"
139595
+ wired: this.isOnAdapterPower()
138005
139596
  });
138006
139597
  if (decision.kind === "unchanged") return false;
138007
139598
  if (decision.kind === "refused") {
@@ -138124,10 +139715,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
138124
139715
  const now = Date.now();
138125
139716
  const quantised = now - now % ReolinkCamera.CONTACT_WRITE_QUANTUM_MS;
138126
139717
  const previousContact = this.state.battery.lastContactAt ?? 0;
138127
- this.setCapSlice(batteryCapability, {
139718
+ this.setCapSlice(batteryCapability, carryRefreshBookkeeping(this.state.battery, {
138128
139719
  ...mapped,
138129
139720
  lastContactAt: Math.max(previousContact, quantised)
138130
- });
139721
+ }));
138131
139722
  }
138132
139723
  /**
138133
139724
  * Hub-fed battery refresh for an adopted child. The parent's
@@ -138429,7 +140020,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
138429
140020
  * changed.
138430
140021
  */
138431
140022
  async applyEmailConfigPatch(fields) {
138432
- await this.wakeIfSleeping();
140023
+ await this.wakeIfSleeping("apply-email-config-patch");
138433
140024
  const api = await this.ensureApi();
138434
140025
  const channel = this.getChannel();
138435
140026
  const patch = {};
@@ -140978,7 +142569,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
140978
142569
  * session or touches the broker.
140979
142570
  */
140980
142571
  async buildStreamCatalog() {
140981
- if (this.cachedStreamDescriptors?.length) return this.withLiveNativeSdp(this.cachedStreamDescriptors);
142572
+ if (this.cachedStreamDescriptors?.length) return this.withLiveNativeSdp(stampCurrentFeatures(this.cachedStreamDescriptors, this.features));
140982
142573
  const restored = this.restoreStreamCatalogFromLedger();
140983
142574
  if (restored) return this.withLiveNativeSdp(restored);
140984
142575
  if (this.buildStreamCatalogInFlight) return this.withLiveNativeSdp(await this.buildStreamCatalogInFlight);
@@ -141262,7 +142853,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141262
142853
  const stored = this.runtimeState.getCapState(streamCatalogCapability.name);
141263
142854
  const descriptors = stored?.descriptors;
141264
142855
  if (!descriptors || descriptors.length === 0) return null;
141265
- this.cachedStreamDescriptors = [...descriptors];
142856
+ this.cachedStreamDescriptors = stampCurrentFeatures(descriptors, this.features);
141266
142857
  this.ctx.logger.info("stream catalog restored from the durable slice (no camera contact)", {
141267
142858
  tags: { deviceId: this.id },
141268
142859
  meta: {
@@ -141310,7 +142901,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141310
142901
  ...entry.codec !== void 0 ? { codec: entry.codec } : {},
141311
142902
  ...entry.metadata ? { metadata: entry.metadata } : {},
141312
142903
  ...entry.maxSessionMs !== void 0 ? { maxSessionMs: entry.maxSessionMs } : {},
141313
- deviceFeatures: entry.deviceFeatures ?? [...this.features],
142904
+ deviceFeatures: [...this.features],
141314
142905
  autoEligible: entry.autoEligible ?? true
141315
142906
  });
141316
142907
  this.publishedStreamIds.add(entry.camStreamId);
@@ -141347,6 +142938,31 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141347
142938
  * listening; if the lib idle-tore-down between calls we recreate.
141348
142939
  */
141349
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) {
141350
142966
  const parts = parseCamStreamId(camStreamId, this.getChannel());
141351
142967
  if (!parts || parts.kind !== "native") return;
141352
142968
  this.ctx.logger.info("broker requested rfc4571 source refresh — materializing on demand", {
@@ -141380,7 +142996,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141380
142996
  deviceId: this.id,
141381
142997
  camStreamId
141382
142998
  },
141383
- meta: { url: `tcp://${server.host}:${server.port}` }
142999
+ meta: {
143000
+ url: `tcp://${server.host}:${server.port}`,
143001
+ republishCause: "broker-source-refresh (materializeStreamSocket)"
143002
+ }
141384
143003
  });
141385
143004
  }
141386
143005
  async removeDevice() {
@@ -141465,7 +143084,8 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141465
143084
  requireAuth: true,
141466
143085
  deviceId: this.stableId,
141467
143086
  requestedId: camStreamId,
141468
- logger: this.libLoggerAdapter()
143087
+ logger: this.libLoggerAdapter(),
143088
+ resilience: { recoveryGuard: () => this.streamRecoveryVerdict() }
141469
143089
  });
141470
143090
  } catch (err) {
141471
143091
  this.ctx.logger.error("rfc4571: createRfc4571TcpServer failed", {
@@ -141732,17 +143352,21 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141732
143352
  logger: this.ctx.logger,
141733
143353
  now: () => Date.now(),
141734
143354
  isAwake: () => !this.sleeping,
143355
+ isStreaming: () => this.hasActiveStream(),
141735
143356
  intervalMs: () => resolveBatteryRefreshIntervalMs(this.config.get("batteryRefreshMinutes")),
141736
143357
  lastFullRefreshAt: () => this.state.battery.lastFullRefreshAt,
141737
143358
  wake: async () => {
141738
143359
  if (!this.canProactivelyWake("scheduled-refresh")) return false;
141739
143360
  this.markWakeIssued();
141740
- return this.wakeIfSleeping();
143361
+ return this.wakeIfSleeping("scheduled-refresh");
141741
143362
  },
141742
143363
  refreshAll: () => this.refreshEverythingNow(),
141743
143364
  stamp: (at) => {
141744
143365
  this.state.battery.lastFullRefreshAt = at;
141745
- }
143366
+ },
143367
+ attemptLedger: attemptLedgerOverSlice(() => this.state.battery, (fields) => {
143368
+ this.runtimeState.patchCapState(batteryCapability.name, fields);
143369
+ })
141746
143370
  });
141747
143371
  return this.batteryRefresh;
141748
143372
  }
@@ -141936,13 +143560,16 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
141936
143560
  });
141937
143561
  }
141938
143562
  else await this.reprobeAccessoriesIfStale(reason);
141939
- 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) {
141940
143567
  await this.warmCapSlicesOnWake();
141941
143568
  await this.warmSnapshotOnWake();
141942
143569
  await this.alignAuxDevicesState("wake");
141943
143570
  await this.refreshParentSettingsSnapshot();
141944
143571
  }
141945
- await this.refreshClipCatalogOnWake();
143572
+ if (!streamingDefer) await this.refreshClipCatalogOnWake();
141946
143573
  }
141947
143574
  static PING_INTERVAL_MS = 3e4;
141948
143575
  static PING_MAX_FAILURES = 3;
@@ -142271,6 +143898,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
142271
143898
  const entries = [...this.active.values()];
142272
143899
  this.active.clear();
142273
143900
  this.keepAwake.stop();
143901
+ this.loginGeneration += 1;
143902
+ this.loginPromise = null;
143903
+ const pending = this.pendingLoginApi;
143904
+ this.pendingLoginApi = null;
143905
+ if (pending) try {
143906
+ await pending.close({ reason: "login-superseded" });
143907
+ } catch {}
142274
143908
  for (const entry of entries) try {
142275
143909
  await entry.server.close("disconnect-all");
142276
143910
  } catch {}
@@ -143346,7 +144980,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143346
144980
  async applySettingsPatch(patch) {
143347
144981
  if (this.isHubChild()) this.refuseHubChildPatch(patch);
143348
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;
143349
- 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 } });
143350
144984
  const emailFields = {
143351
144985
  emailSmtpServer,
143352
144986
  emailSmtpPort,
@@ -143394,7 +145028,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143394
145028
  if (Object.keys(rest).length === 0 && !hasOsdPatch) return;
143395
145029
  if (Object.keys(rest).length > 0) await this.config.setAll(rest);
143396
145030
  const typedPatch = patch;
143397
- if (typedPatch.host || typedPatch.port || typedPatch.username || typedPatch.password) {
145031
+ if (typedPatch.host || typedPatch.port || typedPatch.username || typedPatch.password || typedPatch.transport || typedPatch.uid || typedPatch.udpDiscoveryMethod) {
143398
145032
  await this.disconnectAll();
143399
145033
  return;
143400
145034
  }
@@ -143806,14 +145440,15 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143806
145440
  * separate auth flow per accessory. `ReolinkAccessory` calls this
143807
145441
  * inside its `applyOn` / `fetchOn` to reach the camera firmware.
143808
145442
  */
143809
- /** Implements `ReolinkAccessoryHost.isBatteryCam` so spawned
143810
- * accessory children skip background polling on a sleeping
143811
- * battery cam (Baichuan polls on a sleeping camera return 400 +
143812
- * drain the battery). Reads from the runtime feature-probe slice
143813
- * populated during `onProbe()`; falls back to false when the probe
143814
- * 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). */
143815
145450
  isBatteryCam() {
143816
- return this.runtimeState.getCapState("feature-probe")?.flags?.["hasBattery"] === true;
145451
+ return this.isBattery;
143817
145452
  }
143818
145453
  /** Implements `ReolinkAccessoryHost.isSleeping`. Reads the canonical
143819
145454
  * source of truth — the `battery.sleeping` runtime-state slice — so
@@ -143828,7 +145463,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143828
145463
  /** Implements `ReolinkAccessoryHost.wakeForWrite`: an accessory's operator
143829
145464
  * write (PIR, ...) wakes a sleeping battery camera first. */
143830
145465
  wakeForWrite() {
143831
- return this.wakeIfSleeping();
145466
+ return this.wakeIfSleeping("write");
143832
145467
  }
143833
145468
  /** Implements `ReolinkAccessoryHost.probeAbility`: the effective probe flag
143834
145469
  * (live slice, else the persisted probe); `undefined` = never probed. */
@@ -143864,7 +145499,9 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143864
145499
  meta: {
143865
145500
  port,
143866
145501
  transport,
143867
- hasUid: Boolean(uid)
145502
+ hasUid: Boolean(uid),
145503
+ loginReason: this.lastSessionDropReason ?? "first-login",
145504
+ loginsSoFar: this.loginCount
143868
145505
  }
143869
145506
  });
143870
145507
  const debugOptions = this.getBaichuanDebugOptions();
@@ -143880,6 +145517,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143880
145517
  debugOptions: debugOptions === void 0 ? null : Object.keys(debugOptions)
143881
145518
  }
143882
145519
  });
145520
+ const generation = this.loginGeneration;
143883
145521
  this.loginPromise = (async () => {
143884
145522
  const api = new ReolinkBaichuanApi({
143885
145523
  host,
@@ -143892,16 +145530,41 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143892
145530
  ...debugOptions ? { debugOptions } : {},
143893
145531
  logger: this.libLoggerAdapter()
143894
145532
  });
145533
+ this.pendingLoginApi = api;
143895
145534
  try {
143896
- await api.login();
145535
+ await loginWithin(() => api.login(), LOGIN_DEADLINE_MS, () => api.close({ reason: "login-deadline" }));
143897
145536
  } catch (err) {
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
+ });
145542
+ this.pendingLoginApi = null;
143898
145543
  this.loginPromise = null;
143899
145544
  if (isConnectivityFailure(err)) this.noteUnreachable(err instanceof Error ? err.message : String(err));
143900
145545
  else if (this.ownsReachability()) this.reachability.noteReachable();
143901
145546
  throw err;
143902
145547
  }
145548
+ if (generation !== this.loginGeneration) {
145549
+ try {
145550
+ await api.close({ reason: "login-superseded" });
145551
+ } catch {}
145552
+ throw supersededLoginError(null);
145553
+ }
145554
+ this.pendingLoginApi = null;
143903
145555
  this.api = api;
143904
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
+ }
143905
145568
  this.reconnectAttempts = 0;
143906
145569
  if (this.ownsReachability()) this.reachability.noteReachable();
143907
145570
  const persistedDeviceType = this.config.get("deviceCache")?.deviceType;
@@ -143918,6 +145581,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
143918
145581
  this.isBattery = false;
143919
145582
  }
143920
145583
  else this.isBattery = false;
145584
+ if (!this.isBattery) api.setGeneralSessionRecycling({ guard: () => true });
143921
145585
  if (this.isBattery) {
143922
145586
  this.startSleepPoll();
143923
145587
  this.startBatteryUpdatePolling();
@@ -144155,11 +145819,13 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144155
145819
  let hasPirSensor;
144156
145820
  let hasAutotrack;
144157
145821
  let capabilitiesRead = false;
145822
+ let readQuality = "partial";
144158
145823
  try {
144159
145824
  channelCount = await api.getChannelCount();
144160
145825
  } catch {}
144161
145826
  try {
144162
- const { capabilities } = await api.getDeviceCapabilities(this.getChannel());
145827
+ const { capabilities, debug } = await api.getDeviceCapabilities(this.getChannel());
145828
+ readQuality = abilityReadQuality(debug);
144163
145829
  hasPtz = capabilities.hasPtz;
144164
145830
  hasIntercom = capabilities.hasIntercom;
144165
145831
  hasDoorbell = capabilities.isDoorbell;
@@ -144180,12 +145846,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144180
145846
  return;
144181
145847
  }
144182
145848
  const prev = this.runtimeState.getCapState("feature-probe");
144183
- const prevFlags = prev?.flags ?? {};
145849
+ const prevFlags = this.getProbeFlags();
144184
145850
  const inferredDeviceType = this.config.get("deviceCache")?.deviceType ?? (this.isBattery ? "battery-cam" : null);
144185
145851
  const persistedModel = this.config.get("deviceCache")?.model ?? null;
144186
- const flags = {
144187
- ...prevFlags,
144188
- hasBattery: hasBattery === true || prevFlags.hasBattery === true || this.isBattery,
145852
+ const readFlags = {
144189
145853
  ...hasPtz !== void 0 ? { hasPtz } : {},
144190
145854
  ...hasIntercom !== void 0 ? { hasIntercom } : {},
144191
145855
  ...hasDoorbell !== void 0 ? { hasDoorbell } : {},
@@ -144194,6 +145858,12 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144194
145858
  ...hasPirSensor !== void 0 ? { hasPirSensor } : {},
144195
145859
  ...hasAutotrack !== void 0 ? { hasAutotrack } : {}
144196
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;
144197
145867
  const now = Date.now();
144198
145868
  const next = {
144199
145869
  flags,
@@ -144210,7 +145880,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144210
145880
  ...inferredDeviceType ? { deviceType: inferredDeviceType } : {},
144211
145881
  ...channelCount !== void 0 ? { channelCount } : {}
144212
145882
  };
144213
- await this.config.setAll({ deviceCache: capabilitiesRead ? withPersistedProbe(identity, flags, now) : identity });
145883
+ await this.config.setAll({ deviceCache: fullRead ? withPersistedProbe(identity, flags, now) : identity });
144214
145884
  } catch (err) {
144215
145885
  this.ctx.logger.debug("deviceCache identity persist failed (non-fatal)", {
144216
145886
  tags: { deviceId: this.id },
@@ -144227,7 +145897,9 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144227
145897
  meta: {
144228
145898
  flags,
144229
145899
  channelCount,
144230
- deviceType: inferredDeviceType
145900
+ deviceType: inferredDeviceType,
145901
+ abilityRead: capabilitiesRead ? readQuality : "failed",
145902
+ ...capabilitiesRead && readQuality === "partial" ? { partialRead: readFlags } : {}
144231
145903
  }
144232
145904
  });
144233
145905
  }
@@ -144288,6 +145960,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144288
145960
  async dropBaichuanSession(reason) {
144289
145961
  const current = this.api;
144290
145962
  this.api = null;
145963
+ if (current) this.lastSessionDropReason = reason;
144291
145964
  if (!current) return;
144292
145965
  try {
144293
145966
  await current.close({ reason });
@@ -144358,6 +146031,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144358
146031
  if (this.reconnectTimer) return;
144359
146032
  if (this.isBattery) {
144360
146033
  this.api = null;
146034
+ this.lastSessionDropReason = `disconnect: ${reason}`;
144361
146035
  this.ctx.logger.debug("Battery cam disconnect — deferring reconnect to next demand", {
144362
146036
  tags: { deviceId: this.id },
144363
146037
  meta: {
@@ -144388,6 +146062,7 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
144388
146062
  }
144389
146063
  });
144390
146064
  this.api = null;
146065
+ this.lastSessionDropReason = `reconnect: ${reason}`;
144391
146066
  if (this.removed) return;
144392
146067
  this.reconnectTimer = setTimeout(() => {
144393
146068
  this.reconnectTimer = null;
@@ -144470,7 +146145,8 @@ var AutodetectCache = class {
144470
146145
  input.username,
144471
146146
  passHash,
144472
146147
  input.uid?.trim() ?? "",
144473
- input.transport
146148
+ input.transport,
146149
+ input.udpDiscoveryMethod ?? ""
144474
146150
  ].join(":");
144475
146151
  }
144476
146152
  /**
@@ -144533,6 +146209,34 @@ var AutodetectCache = class {
144533
146209
  }
144534
146210
  };
144535
146211
  //#endregion
146212
+ //#region src/autodetect-inputs.ts
146213
+ function readString(obj, key) {
146214
+ const v = obj[key];
146215
+ return typeof v === "string" ? v : "";
146216
+ }
146217
+ function readTransportMode(obj) {
146218
+ const v = obj["transport"];
146219
+ return v === "tcp" || v === "udp" || v === "auto" ? v : "auto";
146220
+ }
146221
+ /** `auto` / unknown / absent mean "race every method"; only a real method is kept. */
146222
+ function readDiscoveryMethod(obj) {
146223
+ const parsed = ReolinkUdpDiscoveryMethodSchema.safeParse(obj["udpDiscoveryMethod"]);
146224
+ return parsed.success ? parsed.data : void 0;
146225
+ }
146226
+ function buildAutodetectInputs(form) {
146227
+ const rawUid = readString(form, "uid").trim();
146228
+ const rawPort = form["port"];
146229
+ return {
146230
+ host: readString(form, "host").trim(),
146231
+ username: (readString(form, "username") || "admin").trim(),
146232
+ password: readString(form, "password"),
146233
+ uid: rawUid.length > 0 ? rawUid : void 0,
146234
+ transport: readTransportMode(form),
146235
+ port: typeof rawPort === "number" && Number.isFinite(rawPort) ? rawPort : 9e3,
146236
+ udpDiscoveryMethod: readDiscoveryMethod(form)
146237
+ };
146238
+ }
146239
+ //#endregion
144536
146240
  //#region src/creation-schema.ts
144537
146241
  /**
144538
146242
  * Creation form for Reolink devices.
@@ -144710,6 +146414,28 @@ function buildCreationFormSchema() {
144710
146414
  field: "transport",
144711
146415
  notEquals: "tcp"
144712
146416
  }
146417
+ },
146418
+ {
146419
+ type: "select",
146420
+ key: "udpDiscoveryMethod",
146421
+ label: "UDP discovery",
146422
+ labelKey: "provider-reolink:creation.s_connection.udpDiscoveryMethod.label",
146423
+ default: "auto",
146424
+ description: "Auto races every method and may settle on the Reolink relay. \"Local only\" talks straight to the camera IP and never uses Reolink servers.",
146425
+ descriptionKey: "provider-reolink:creation.s_connection.udpDiscoveryMethod.description",
146426
+ options: [{
146427
+ value: "auto",
146428
+ label: "Auto (may use the Reolink relay)",
146429
+ labelKey: "provider-reolink:creation.s_connection.udpDiscoveryMethod.o_auto.label"
146430
+ }, {
146431
+ value: "local-direct",
146432
+ label: "Local only (direct to the camera IP)",
146433
+ labelKey: "provider-reolink:creation.s_connection.udpDiscoveryMethod.o_local.label"
146434
+ }],
146435
+ showWhen: {
146436
+ field: "transport",
146437
+ notEquals: "tcp"
146438
+ }
144713
146439
  }
144714
146440
  ]
144715
146441
  },
@@ -146415,6 +148141,12 @@ function createWebhookHandler(deps) {
146415
148141
  }
146416
148142
  //#endregion
146417
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
+ });
146418
148150
  /**
146419
148151
  * Adapt a camstack scoped logger to the lib's `Logger` shape (just
146420
148152
  * `log(...)`). Lib lines are prefixed with `[AutoDetect]` /
@@ -146441,28 +148173,6 @@ function getString(obj, key) {
146441
148173
  const v = obj[key];
146442
148174
  return typeof v === "string" ? v : "";
146443
148175
  }
146444
- function getNumber(obj, key, fallback) {
146445
- const v = obj[key];
146446
- return typeof v === "number" && Number.isFinite(v) ? v : fallback;
146447
- }
146448
- function getTransportMode(obj) {
146449
- const v = obj["transport"];
146450
- return v === "tcp" || v === "udp" || v === "auto" ? v : "auto";
146451
- }
146452
- function buildAutodetectInputs(form) {
146453
- const host = getString(form, "host").trim();
146454
- const username = (getString(form, "username") || "admin").trim();
146455
- const password = getString(form, "password");
146456
- const rawUid = getString(form, "uid").trim();
146457
- return {
146458
- host,
146459
- username,
146460
- password,
146461
- uid: rawUid.length > 0 ? rawUid : void 0,
146462
- transport: getTransportMode(form),
146463
- port: getNumber(form, "port", 9e3)
146464
- };
146465
- }
146466
148176
  function buildAutodetectLabels(result) {
146467
148177
  const labels = [];
146468
148178
  const model = result.deviceInfo?.type;
@@ -147005,9 +148715,14 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
147005
148715
  provider: { list: () => intercomFailureReport.list() }
147006
148716
  });
147007
148717
  this.subscribe({ category: EventCategory.StreamBrokerOnRequestStreamSourceRefresh }, (event) => {
147008
- const data = event.data;
147009
- const deviceId = typeof data.deviceId === "number" ? data.deviceId : null;
147010
- 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
+ });
147011
148726
  this.refreshDeviceStreams(deviceId, data.camStreamId).catch((err) => {
147012
148727
  this.ctx.logger.warn("refresh of Reolink stream failed", {
147013
148728
  tags: { deviceId },
@@ -147456,6 +149171,7 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
147456
149171
  username: inputs.username,
147457
149172
  password: inputs.password,
147458
149173
  ...inputs.uid ? { uid: inputs.uid } : {},
149174
+ ...inputs.udpDiscoveryMethod ? { udpDiscoveryMethod: inputs.udpDiscoveryMethod } : {},
147459
149175
  mode: inputs.transport
147460
149176
  });
147461
149177
  } else this.ctx.logger.info("autodetect cache hit — reusing api", {
@@ -147604,6 +149320,7 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
147604
149320
  username: inputs.username,
147605
149321
  password: inputs.password,
147606
149322
  ...inputs.uid ? { uid: inputs.uid } : {},
149323
+ ...inputs.udpDiscoveryMethod ? { udpDiscoveryMethod: inputs.udpDiscoveryMethod } : {},
147607
149324
  mode: inputs.transport,
147608
149325
  logger: buildAutodetectLibLogger(probeLogger)
147609
149326
  });