@camstack/addon-export-alexa 1.2.108 → 1.2.109

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.
@@ -26,7 +26,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
26
26
  //#endregion
27
27
  let node_crypto = require("node:crypto");
28
28
  node_crypto = __toESM(node_crypto);
29
- //#region ../types/dist/event-category-ZyX6jcse.mjs
29
+ //#region ../types/dist/event-category-BVDXG4tB.mjs
30
30
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
31
31
  EventCategory["SystemBoot"] = "system.boot";
32
32
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -643,6 +643,20 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
643
643
  * pull-reconcile from the provider's `getStatus` on reconnect. */
644
644
  EventCategory["MeshNetworkChanged"] = "network.mesh.changed";
645
645
  EventCategory["BackupCompleted"] = "backup.completed";
646
+ /**
647
+ * A whole backup RUN finished — every destination attempted, win or lose.
648
+ *
649
+ * `backup.completed` fires once per DESTINATION, which is the right grain for
650
+ * a progress UI and the wrong one for a notification: an operator with three
651
+ * destinations would be told three times. And a run where two of three
652
+ * destinations succeeded is not a clean success — a single "backup
653
+ * completed" that hid the failed one would be a lie, so the count of each is
654
+ * carried here and the message says both.
655
+ *
656
+ * Emitted by the backup orchestrator only after the destination loop, so a
657
+ * run that dies during the BUILD phase produces no completion at all.
658
+ */
659
+ EventCategory["BackupRunCompleted"] = "backup.run-completed";
646
660
  EventCategory["BackupRestored"] = "backup.restored";
647
661
  EventCategory["NotificationDispatched"] = "notification.dispatched";
648
662
  EventCategory["NotificationFailed"] = "notification.failed";
@@ -5373,7 +5387,7 @@ var ZodIssueCode = {
5373
5387
  var ZodFirstPartyTypeKind;
5374
5388
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5375
5389
  //#endregion
5376
- //#region ../types/dist/sleep-DBKu2-U5.mjs
5390
+ //#region ../types/dist/sleep-DEuj7E3j.mjs
5377
5391
  /**
5378
5392
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5379
5393
  * window to float samples (D455).
@@ -7560,6 +7574,28 @@ var EncodeProfileSchema = object({
7560
7574
  outputArgs: array(string()).optional()
7561
7575
  });
7562
7576
  /**
7577
+ * THE target rule: which of two sizes serves a consumer better.
7578
+ *
7579
+ * "Prefer at or above the target so the consumer downscales instead of
7580
+ * upscaling; among those the SMALLEST, because the extra pixels are thrown
7581
+ * away and the decode is not; among the rest the LARGEST, because it is the
7582
+ * closest we can get." One sentence, and until now it was written twice — once
7583
+ * here in lines, once in `stream-selection.ts` in pixels, for the same two
7584
+ * exporters. The two agreed, which is luck, not a property.
7585
+ *
7586
+ * The `size` is whatever measure the caller ranks by: the cap ranks by LINES
7587
+ * (a consumer's requirement is stated in p), the RTSP picker by PIXELS (it
7588
+ * compares entries of possibly different aspect). The rule is the same either
7589
+ * way and the measure is the caller's business.
7590
+ *
7591
+ * Returns a sort delta: negative when `a` should come first.
7592
+ */
7593
+ function compareToTarget(a, b, target) {
7594
+ const aReaches = a >= target;
7595
+ if (aReaches !== b >= target) return aReaches ? -1 : 1;
7596
+ return aReaches ? a - b : b - a;
7597
+ }
7598
+ /**
7563
7599
  * The shape every live egress starts from: H.264 Baseline 3.1 at 720p25.
7564
7600
  * Baseline because it is the one profile every consumer in this repo decodes
7565
7601
  * (Echo, iOS, an old browser); 3.1 because that is what the SDPs advertise.
@@ -9474,6 +9510,47 @@ var LogChannelWindowSchema = object({
9474
9510
  /** `null` = every camera. A non-empty list narrows to those numeric ids. */
9475
9511
  deviceIds: array(number().int()).readonly().nullable()
9476
9512
  });
9513
+ /**
9514
+ * Shared stream-selection picker for export addons.
9515
+ *
9516
+ * Both `addon-export-alexa` and `addon-export-hap` resolve the
9517
+ * operator's `streamPreference` setting against the broker's RTSP
9518
+ * entries before dialling a camera. Each addon used to roll its own:
9519
+ * Alexa had `pickPreferredRtspEntry` under `handlers/`, HAP had an
9520
+ * inline `"prefer /mid, then /high, then first"` chain inside its
9521
+ * camera-streams mapper. The chains drifted (Alexa honoured
9522
+ * `streamPreference`, HAP didn't; only Alexa got the smart
9523
+ * resolution-targeted auto-pick) and the cross-addon import rule
9524
+ * blocks deduping in either direction.
9525
+ *
9526
+ * Lifting the picker into `@camstack/types` lets every exporter call
9527
+ * the same code path with the consumer's target resolution baked into
9528
+ * the call site — Alexa passes 1280×720, HomeKit passes 1920×1080,
9529
+ * the picker handles the rest.
9530
+ *
9531
+ * Selection algorithm:
9532
+ * - pref === '<profile>' → profile-keyed entries (from
9533
+ * `getProfileRtspEntries`) match on `e.profile`;
9534
+ * legacy raw entries match on the brokerId
9535
+ * suffix (`brokerId` ENDS WITH `/${pref}`, shape
9536
+ * `${deviceId}/${camStreamId}`). Addons store the
9537
+ * bare profile/camStream id in their
9538
+ * `ExportDeviceSettings.streamPreference`. Falls
9539
+ * back to 'auto' when no enabled entry matches
9540
+ * either way.
9541
+ * - pref === 'auto' → when `targetResolution` is given, pick the
9542
+ * entry whose source resolution is closest to
9543
+ * it (prefer ≥ target so the consumer
9544
+ * downscales instead of upscaling). Without a
9545
+ * target, fall back to first-enabled. If no
9546
+ * entry advertises a resolution at all
9547
+ * (broker hasn't probed yet), also fall back
9548
+ * to first-enabled so cold start still serves.
9549
+ *
9550
+ * Returns `null` when nothing is publishable — callers fold that into
9551
+ * the consumer's "no stream" error (Alexa: STREAM_TYPE_UNSUPPORTED;
9552
+ * HAP: a thrown error inside `startFfmpegForSession`).
9553
+ */
9477
9554
  function pickPreferredRtspEntry(entries, pref, deviceId, options = {}) {
9478
9555
  if (entries.length === 0) return null;
9479
9556
  const prefix = `${deviceId}/`;
@@ -9503,30 +9580,23 @@ function pickPreferredRtspEntry(entries, pref, deviceId, options = {}) {
9503
9580
  return toPicked(eligible[0]);
9504
9581
  }
9505
9582
  /**
9506
- * Pick the entry whose `resolution` is closest to `target`. Prefer
9507
- * entries ≥ target (downscale is cheap at the consumer; upscale is
9508
- * lossy). Among the rest pick the LARGEST still ≤ target so the
9509
- * consumer gets the best feasible quality. "Closeness" is the
9510
- * `width × height` pixel delta.
9583
+ * Pick the entry whose `resolution` is closest to `target`, by the ONE target
9584
+ * rule ({@link compareToTarget}): prefer at or above the target so the consumer
9585
+ * downscales instead of upscaling; among those the smallest; among the rest the
9586
+ * largest.
9587
+ *
9588
+ * This function used to implement that rule itself, in pixels, while
9589
+ * `rankStreams` implemented it again in lines — the same sentence written twice
9590
+ * for the same two exporters, agreeing by luck rather than by construction.
9591
+ * Only the MEASURE is this picker's own: it compares whole pixel counts because
9592
+ * its entries can differ in aspect, where the cap's requirement is stated in p.
9511
9593
  */
9512
9594
  function pickClosestResolution(entries, target) {
9513
9595
  const targetPixels = target.width * target.height;
9514
- let bestAbove;
9515
- let bestBelow;
9516
- for (const e of entries) {
9517
- if (e.resolution === void 0) continue;
9518
- const pixels = e.resolution.width * e.resolution.height;
9519
- if (pixels >= targetPixels) {
9520
- if (!bestAbove || pixels < bestAbove.pixels) bestAbove = {
9521
- entry: e,
9522
- pixels
9523
- };
9524
- } else if (!bestBelow || pixels > bestBelow.pixels) bestBelow = {
9525
- entry: e,
9526
- pixels
9527
- };
9528
- }
9529
- return bestAbove?.entry ?? bestBelow?.entry;
9596
+ return [...entries.flatMap((entry) => entry.resolution === void 0 ? [] : [{
9597
+ entry,
9598
+ pixels: entry.resolution.width * entry.resolution.height
9599
+ }])].sort((a, b) => compareToTarget(a.pixels, b.pixels, targetPixels))[0]?.entry;
9530
9600
  }
9531
9601
  var MODEL_FORMATS = [
9532
9602
  "onnx",
@@ -11740,6 +11810,58 @@ method(ListInputSchema, array(BrokerInfoSchema$1)), method(GetInputSchema, Broke
11740
11810
  auth: "admin"
11741
11811
  }), method(GetStateInputSchema, unknown().nullable()), method(_void(), RegistryStatusSchema);
11742
11812
  DeviceType.Camera;
11813
+ /**
11814
+ * The signals a device can emit to WAKE its own stream.
11815
+ *
11816
+ * A camera whose stream is built on demand sleeps until something asks for it,
11817
+ * and "something" cannot be a consumer that is merely attached — a Frigate-style
11818
+ * puller holds a session open for ever, and treating that as demand would keep
11819
+ * a battery camera awake for ever, which is the whole thing the battery is for
11820
+ * (D173). So the wake has to come from the CAMERA: an event it noticed by
11821
+ * itself, with no stream running.
11822
+ *
11823
+ * ## The vocabulary is the PROVIDER'S, not ours
11824
+ *
11825
+ * Like `consumables`, this cap declares no vocabulary of its own. A provider
11826
+ * names each signal with a `code` it chooses and a `label` an operator reads.
11827
+ * Reolink offers motion and camera-native detection; another provider may offer
11828
+ * a tamper, a doorbell press, a PIR, or something no camera in this fleet has
11829
+ * yet. A fixed enum here would mean every new signal is a framework release.
11830
+ *
11831
+ * It is deliberately NOT derived from the caps a device already binds. Whether
11832
+ * a camera CAN push firmware motion is expressed by `motionSources` containing
11833
+ * `'onboard'`, and whether it does AI on-camera by the `native-object-detection`
11834
+ * binding — but both answer "what drives the detection pipeline", which is a
11835
+ * different question from "what may wake a sleeping stream". A camera can do
11836
+ * the first and not be trusted with the second, and the operator picks per
11837
+ * camera. Two questions, two authorities.
11838
+ *
11839
+ * ## Availability is not permission
11840
+ *
11841
+ * `listSignals` says what the device CAN emit. Whether a given signal actually
11842
+ * wakes the stream is the operator's per-camera choice, held by the broker
11843
+ * alongside the cooldown — see the stream-broker cap's wake settings. A
11844
+ * provider declaring a signal is not a provider enabling it.
11845
+ */
11846
+ /** One signal a device can emit. */
11847
+ var StreamSignalSchema = object({
11848
+ /** Stable id chosen by the provider, e.g. `'motion'`, `'person'`, `'tamper'`. */
11849
+ code: string().min(1),
11850
+ /** What an operator reads in the picker. The provider's own wording. */
11851
+ label: string().min(1),
11852
+ /**
11853
+ * Whether the provider recommends this signal ON when a camera is first set
11854
+ * up. A provider knows which of its signals are cheap and reliable; an
11855
+ * operator should not have to discover that by trial. Reolink recommends
11856
+ * both of its own.
11857
+ */
11858
+ recommended: boolean()
11859
+ });
11860
+ object({
11861
+ signals: array(StreamSignalSchema),
11862
+ lastFetchedAt: number()
11863
+ });
11864
+ Object.values(DeviceType), method(_void(), array(StreamSignalSchema).readonly());
11743
11865
  /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
11744
11866
  var StreamFormatSchema = _enum([
11745
11867
  "webrtc",
@@ -12136,6 +12258,22 @@ var EgressTranscodeSchema = object({
12136
12258
  camStreamId: string().nullable()
12137
12259
  });
12138
12260
  method(object({
12261
+ deviceId: number().int().nonnegative(),
12262
+ /** The provider's signal code. */
12263
+ code: string().min(1),
12264
+ /** Ms epoch. Absent ⇒ now. */
12265
+ at: number().optional()
12266
+ }), object({
12267
+ /** Whether the broker acted on it, and if not, why. */
12268
+ accepted: boolean(),
12269
+ reason: _enum([
12270
+ "woke",
12271
+ "hold-extended",
12272
+ "not-enabled",
12273
+ "no-consumer",
12274
+ "unknown-code"
12275
+ ])
12276
+ }), { kind: "mutation" }), method(object({
12139
12277
  deviceId: number().int().nonnegative(),
12140
12278
  camStreamId: string().min(1),
12141
12279
  kind: CamStreamKindSchema,
@@ -12390,6 +12528,16 @@ var PickStreamRequirementsSchema = object({
12390
12528
  acceptCodecs: array(StreamCodecSchema).readonly().optional(),
12391
12529
  /** Minimum vertical resolution. Streams shorter than this are dropped. */
12392
12530
  minHeight: number().int().positive().optional(),
12531
+ /**
12532
+ * Maximum vertical resolution. Streams TALLER than this are dropped.
12533
+ *
12534
+ * A consumer can have a ceiling as real as its floor: Alexa documents
12535
+ * 480p to 1080p, and a 4K stream is as unusable to an Echo as a 360p one.
12536
+ * Without this the ceiling had to be re-implemented by every caller — and
12537
+ * one caller implementing it privately is how a second scoring authority
12538
+ * gets born.
12539
+ */
12540
+ maxHeight: number().int().positive().optional(),
12393
12541
  /** Minimum horizontal resolution. */
12394
12542
  minWidth: number().int().positive().optional(),
12395
12543
  /**
@@ -12406,7 +12554,22 @@ var PickStreamRequirementsSchema = object({
12406
12554
  * transcoded" guard: if the device is already serving the consumer's
12407
12555
  * codec end-to-end, there's nothing to optimise.
12408
12556
  */
12409
- requireSiblingCodec: array(StreamCodecSchema).readonly().optional()
12557
+ requireSiblingCodec: array(StreamCodecSchema).readonly().optional(),
12558
+ /**
12559
+ * Whether a stream the consumer CANNOT decode may still be picked, on the
12560
+ * understanding that it will be transcoded.
12561
+ *
12562
+ * Default `false` — today's behaviour, and the right one for a bypass
12563
+ * question ("is there a stream I can forward untouched?"). Set `true` to
12564
+ * ask the larger question: "what is the best stream for me, transcoding if
12565
+ * I must?" A stream that satisfies `acceptCodecs` always outranks one that
12566
+ * does not, so a passthrough is never lost to a transcode; the answer says
12567
+ * which it is in {@link PickedCamStreamSchema.transcodes}.
12568
+ *
12569
+ * This is what lets one picker serve both the bypass and the full source
12570
+ * choice, instead of a consumer scoring privately when the bypass misses.
12571
+ */
12572
+ allowTranscode: boolean().optional()
12410
12573
  }).readonly();
12411
12574
  var PickStreamPreferencesSchema = object({
12412
12575
  /**
@@ -12420,12 +12583,32 @@ var PickStreamPreferencesSchema = object({
12420
12583
  * picks the tallest stream; `'lowest'` picks the shortest (used by
12421
12584
  * memory-constrained consumers / Apple Home guest sessions).
12422
12585
  */
12423
- resolutionPreference: _enum(["highest", "lowest"]).optional()
12586
+ resolutionPreference: _enum(["highest", "lowest"]).optional(),
12587
+ /**
12588
+ * The height the consumer actually wants to DELIVER.
12589
+ *
12590
+ * Not a constraint — an ordering. With it set, the SMALLEST stream at or
12591
+ * above the target wins, and only if nothing reaches it does the tallest
12592
+ * take over. Pulling 1296 lines to draw 720 on a 1280x800 Echo panel costs
12593
+ * a decode and buys nothing, and `resolutionPreference: 'highest'` cannot
12594
+ * express that: it says "as big as possible", which is a different wish.
12595
+ *
12596
+ * Ignored when absent, so every existing caller keeps its ordering.
12597
+ */
12598
+ targetHeight: number().int().positive().optional()
12424
12599
  }).readonly();
12425
12600
  var PickedCamStreamSchema = object({
12426
12601
  camStreamId: string(),
12427
12602
  codec: string().optional(),
12428
12603
  resolution: CamStreamResolutionSchema.optional(),
12604
+ /**
12605
+ * Whether serving this stream requires a decode + re-encode.
12606
+ *
12607
+ * `false` is a stream the consumer can take as it stands. Only ever `true`
12608
+ * when the caller asked for it with `allowTranscode`, so a caller that did
12609
+ * not ask cannot be handed a cost it never agreed to pay.
12610
+ */
12611
+ transcodes: boolean(),
12429
12612
  /** One-line explanation of why this stream won — for logs / debug UI. */
12430
12613
  reason: string()
12431
12614
  });
@@ -16661,6 +16844,8 @@ var NcSystemEventKindSchema = _enum([
16661
16844
  "device-enabled",
16662
16845
  "device-battery-low",
16663
16846
  "device-battery-normal",
16847
+ "device-consumable-low",
16848
+ "device-consumable-normal",
16664
16849
  "stream-online",
16665
16850
  "stream-offline",
16666
16851
  "node-online",
@@ -16679,6 +16864,7 @@ var NcSystemEventKindSchema = _enum([
16679
16864
  "addon-updated",
16680
16865
  "server-updated",
16681
16866
  "export-completed",
16867
+ "backup-completed",
16682
16868
  "camera-online",
16683
16869
  "camera-offline",
16684
16870
  "camera-disabled",
@@ -23936,10 +24122,28 @@ DeviceType.Camera, method(object({ deviceId: number().int().nonnegative() }), ar
23936
24122
  }), boolean()), method(object({
23937
24123
  deviceId: number().int().nonnegative(),
23938
24124
  sessionId: string()
23939
- }), object({ pendingRenegotiation: object({
23940
- target: WebrtcStreamTargetSchema,
23941
- epoch: number()
23942
- }).nullable() }));
24125
+ }), object({
24126
+ pendingRenegotiation: object({
24127
+ target: WebrtcStreamTargetSchema,
24128
+ epoch: number()
24129
+ }).nullable(),
24130
+ /**
24131
+ * Whether the session still EXISTS.
24132
+ *
24133
+ * A consumer that holds a resource for the life of a session needs to
24134
+ * be able to ask, because a session does not always end the way it
24135
+ * began. Measured on this hub 2026-09-13: an Echo that got stuck never
24136
+ * sent `SessionDisconnected`, so the Alexa exporter's
24137
+ * `releaseEgressTranscode` never ran, and a 2304x1296 HEVC to 720p
24138
+ * H.264 transcode kept running for NOBODY for more than twenty
24139
+ * minutes. The WebRTC session had logged `WebRTC session closed`
24140
+ * minutes earlier — the broker knew; the holder had no way to ask.
24141
+ *
24142
+ * `false` for a session id the provider has never heard of, which is
24143
+ * the same answer as "it ended": either way nothing is holding it up.
24144
+ */
24145
+ alive: boolean()
24146
+ }));
23943
24147
  object({
23944
24148
  /** All accessory children of the parent. */
23945
24149
  childDeviceIds: array(number()).readonly(),
@@ -36443,6 +36647,12 @@ Object.freeze({
36443
36647
  addonId: null,
36444
36648
  access: "create"
36445
36649
  },
36650
+ "streamBroker.reportStreamSignal": {
36651
+ capName: "stream-broker",
36652
+ capScope: "system",
36653
+ addonId: null,
36654
+ access: "create"
36655
+ },
36446
36656
  "streamBroker.restartProfile": {
36447
36657
  capName: "stream-broker",
36448
36658
  capScope: "system",
@@ -36527,6 +36737,12 @@ Object.freeze({
36527
36737
  addonId: null,
36528
36738
  access: "create"
36529
36739
  },
36740
+ "streamSignals.listSignals": {
36741
+ capName: "stream-signals",
36742
+ capScope: "device",
36743
+ addonId: null,
36744
+ access: "view"
36745
+ },
36530
36746
  "switch.setState": {
36531
36747
  capName: "switch",
36532
36748
  capScope: "device",
@@ -38899,6 +39115,11 @@ Object.freeze({
38899
39115
  form: "single",
38900
39116
  optional: false
38901
39117
  }],
39118
+ "streamBroker.reportStreamSignal": [{
39119
+ name: "deviceId",
39120
+ form: "single",
39121
+ optional: false
39122
+ }],
38902
39123
  "streamBroker.restartProfile": [{
38903
39124
  name: "deviceId",
38904
39125
  form: "single",
@@ -39729,7 +39950,7 @@ async function acquireAlexaEgress(input) {
39729
39950
  profile: sourceProfile
39730
39951
  },
39731
39952
  encode: ALEXA_EGRESS_PROFILE,
39732
- rateControl: "relaxed",
39953
+ rateControl: "tight",
39733
39954
  publishLocally: true,
39734
39955
  tag: `alexa/${sessionId}`
39735
39956
  });
@@ -39753,6 +39974,7 @@ async function acquireAlexaEgress(input) {
39753
39974
  meta: {
39754
39975
  pipelineKey: transcode.pipelineKey,
39755
39976
  camStreamId,
39977
+ sourceProfile: input.sourceProfile,
39756
39978
  encoder: transcode.encoder,
39757
39979
  decodeHwAccel: transcode.decodeHwAccel ?? "software"
39758
39980
  }
@@ -39786,6 +40008,512 @@ async function releaseAlexaEgress(input) {
39786
40008
  }
39787
40009
  }
39788
40010
  //#endregion
40011
+ //#region src/egress/egress-handle-reaper.ts
40012
+ /**
40013
+ * Which handles should be released now.
40014
+ *
40015
+ * A session the broker says is GONE is reclaimed. A session it could not be
40016
+ * asked about is KEPT — a read that failed is not evidence of death, and
40017
+ * releasing a live session's transcode would black out a working stream to
40018
+ * save a process (D393, read in the direction that destroys work).
40019
+ */
40020
+ async function reapDeadEgressHandles(input) {
40021
+ const dead = [];
40022
+ for (const handle of input.held) if (await input.isAlive(handle) === false) dead.push(handle);
40023
+ return dead;
40024
+ }
40025
+ /** How often the sweep runs. Well under the minute Amazon requires a session
40026
+ * to survive, so a genuinely dead one is not transcoding for long. */
40027
+ var EGRESS_REAP_INTERVAL_MS = 3e4;
40028
+ function logReaped(logger, handle) {
40029
+ logger?.warn("alexa egress: session is GONE — reclaiming the transcode it still held", {
40030
+ tags: { deviceId: handle.deviceId },
40031
+ meta: {
40032
+ sessionId: handle.sessionId,
40033
+ pipelineKey: handle.pipelineKey,
40034
+ reason: "no SessionDisconnected directive"
40035
+ }
40036
+ });
40037
+ }
40038
+ //#endregion
40039
+ //#region src/egress/alexa-source-pick.ts
40040
+ /** Amazon's documented ceiling. */
40041
+ var ALEXA_MAX_LINES = 1080;
40042
+ /**
40043
+ * Which profile slot serves `camStreamId`, or `null` when none does — a read
40044
+ * that failed is `null` too, and the caller keeps its previous behaviour
40045
+ * rather than guessing a slot from an error (D393).
40046
+ */
40047
+ async function profileForCamStream(input) {
40048
+ try {
40049
+ const slots = await input.api.streamBroker.listAllProfileSlots.query();
40050
+ for (const slot of slots) {
40051
+ if (slot.deviceId !== input.deviceId) continue;
40052
+ if (slot.sourceCamStreamId !== input.camStreamId) continue;
40053
+ if (slot.profile === "high" || slot.profile === "mid" || slot.profile === "low") return slot.profile;
40054
+ }
40055
+ return null;
40056
+ } catch (err) {
40057
+ input.logger?.warn("alexa rtc-session: could not read the profile slots", {
40058
+ tags: { deviceId: input.deviceId },
40059
+ meta: { error: errMsg(err) }
40060
+ });
40061
+ return null;
40062
+ }
40063
+ }
40064
+ //#endregion
40065
+ //#region src/handlers/endpoint-id.ts
40066
+ var SEPARATOR = "__";
40067
+ function parseCameraEndpointId(raw) {
40068
+ if (!raw.includes(SEPARATOR)) {
40069
+ const id = parseNonNegativeInt(raw);
40070
+ if (id === null) return {
40071
+ kind: "invalid",
40072
+ reason: `not a numeric deviceId: ${raw}`
40073
+ };
40074
+ return {
40075
+ kind: "camera",
40076
+ deviceId: id
40077
+ };
40078
+ }
40079
+ const [head, tail, ...rest] = raw.split(SEPARATOR);
40080
+ if (head === void 0 || tail === void 0 || rest.length > 0) return {
40081
+ kind: "invalid",
40082
+ reason: `unexpected segments in endpointId: ${raw}`
40083
+ };
40084
+ const parent = parseNonNegativeInt(head);
40085
+ if (parent === null) return {
40086
+ kind: "invalid",
40087
+ reason: `parent segment not numeric: ${raw}`
40088
+ };
40089
+ if (tail === "autotrack") return {
40090
+ kind: "autotrack",
40091
+ parentDeviceId: parent
40092
+ };
40093
+ if (tail === "privacy") return {
40094
+ kind: "privacy",
40095
+ parentDeviceId: parent
40096
+ };
40097
+ if (tail === "alarm") return {
40098
+ kind: "alarm-panel",
40099
+ deviceId: parent
40100
+ };
40101
+ const child = parseNonNegativeInt(tail);
40102
+ if (child === null) return {
40103
+ kind: "invalid",
40104
+ reason: `child segment not numeric and not 'autotrack'/'privacy'/'alarm': ${raw}`
40105
+ };
40106
+ return {
40107
+ kind: "child",
40108
+ parentDeviceId: parent,
40109
+ childDeviceId: child
40110
+ };
40111
+ }
40112
+ function parseNonNegativeInt(s) {
40113
+ if (!/^\d+$/.test(s)) return null;
40114
+ const n = Number.parseInt(s, 10);
40115
+ if (!Number.isFinite(n) || n < 0) return null;
40116
+ return n;
40117
+ }
40118
+ //#endregion
40119
+ //#region src/handlers/error-envelope.ts
40120
+ /**
40121
+ * Shared Alexa `Alexa/ErrorResponse` envelope builder.
40122
+ *
40123
+ * Lives in its own module so every handler (and the directive router)
40124
+ * can emit its own namespace-appropriate error without circular imports.
40125
+ */
40126
+ object({ event: object({
40127
+ header: object({
40128
+ namespace: literal("Alexa"),
40129
+ name: literal("ErrorResponse"),
40130
+ messageId: string(),
40131
+ payloadVersion: literal("3")
40132
+ }),
40133
+ payload: object({
40134
+ type: string(),
40135
+ message: string()
40136
+ })
40137
+ }) });
40138
+ function errorEnvelope(header, type, message) {
40139
+ return { event: {
40140
+ header: {
40141
+ namespace: "Alexa",
40142
+ name: "ErrorResponse",
40143
+ messageId: header.messageId,
40144
+ payloadVersion: "3"
40145
+ },
40146
+ payload: {
40147
+ type,
40148
+ message
40149
+ }
40150
+ } };
40151
+ }
40152
+ //#endregion
40153
+ //#region src/handlers/types.ts
40154
+ /**
40155
+ * Zod schemas for the subset of the Alexa Smart Home directive surface
40156
+ * that we actually parse hub-side. The Smart Home Skill API ships
40157
+ * thousands of optional fields per namespace — we only validate what
40158
+ * we read; everything else passes through as `unknown`.
40159
+ *
40160
+ * Reference: https://developer.amazon.com/en-US/docs/alexa/smarthome/smart-home-skill-api-message-reference.html
40161
+ */
40162
+ /** A directive header carries namespace + name + token + correlation id. */
40163
+ var DirectiveHeaderSchema = object({
40164
+ namespace: string(),
40165
+ name: string(),
40166
+ payloadVersion: string(),
40167
+ messageId: string(),
40168
+ correlationToken: string().optional()
40169
+ });
40170
+ /** Scope carries the bearer token Alexa minted via our OAuth provider. */
40171
+ var BearerScopeSchema = object({
40172
+ type: literal("BearerToken"),
40173
+ token: string()
40174
+ });
40175
+ /** Endpoint reference inside a directive payload. */
40176
+ var EndpointRefSchema = object({
40177
+ endpointId: string(),
40178
+ scope: BearerScopeSchema.optional(),
40179
+ cookie: record(string(), string()).optional()
40180
+ });
40181
+ var DiscoveryDirectiveSchema = object({
40182
+ header: DirectiveHeaderSchema.extend({
40183
+ namespace: literal("Alexa.Discovery"),
40184
+ name: literal("Discover")
40185
+ }),
40186
+ payload: object({ scope: BearerScopeSchema })
40187
+ });
40188
+ /** Envelope wrapping a directive on the Alexa→skill wire. */
40189
+ var DirectiveRequestSchema = object({ directive: object({
40190
+ header: DirectiveHeaderSchema,
40191
+ endpoint: EndpointRefSchema.optional(),
40192
+ payload: unknown().optional()
40193
+ }) });
40194
+ var InitializeCameraStreamsPayloadSchema = object({ cameraStreams: array(object({
40195
+ protocol: string(),
40196
+ resolution: object({
40197
+ width: number(),
40198
+ height: number()
40199
+ }).optional(),
40200
+ authorizationType: string().optional(),
40201
+ videoCodec: string().optional(),
40202
+ audioCodec: string().optional()
40203
+ })).optional() });
40204
+ var InitiateSessionWithOfferPayloadSchema = object({
40205
+ sessionId: string(),
40206
+ offer: object({
40207
+ format: string().optional(),
40208
+ value: string()
40209
+ })
40210
+ });
40211
+ var SessionDisconnectedPayloadSchema = object({ sessionId: string() });
40212
+ var SetModePayloadSchema = object({ mode: string() });
40213
+ //#endregion
40214
+ //#region src/handlers/rtc-session.ts
40215
+ var InitiateSessionWithOfferDirectiveSchema = object({
40216
+ endpoint: EndpointRefSchema,
40217
+ payload: InitiateSessionWithOfferPayloadSchema
40218
+ });
40219
+ var SessionDisconnectedDirectiveSchema = object({
40220
+ endpoint: EndpointRefSchema,
40221
+ payload: SessionDisconnectedPayloadSchema
40222
+ });
40223
+ /**
40224
+ * Live egress handles, keyed by `<deviceId>/<sessionId>`.
40225
+ *
40226
+ * The primitive's refcount has no lease TTL: a holder that vanishes without
40227
+ * releasing leaks a child until the broker restarts (D67). This handler is a
40228
+ * holder, so it keeps the one piece of state that lets it not be that holder —
40229
+ * the `pipelineKey` its `SessionDisconnected` has to release.
40230
+ *
40231
+ * A module-level map is right here because the directive handlers are free
40232
+ * functions called per directive; the entry is written on a successful acquire
40233
+ * and deleted on the release path, both of which are the same tick as the
40234
+ * directive that owns it.
40235
+ */
40236
+ var EGRESS_HANDLES = /* @__PURE__ */ new Map();
40237
+ function egressHandleKey(deviceId, sessionId) {
40238
+ return `${deviceId}/${sessionId}`;
40239
+ }
40240
+ /** Every handle currently held, for the sweep. */
40241
+ function heldEgressHandles() {
40242
+ const held = [];
40243
+ for (const [key, pipelineKey] of EGRESS_HANDLES) {
40244
+ const slash = key.indexOf("/");
40245
+ if (slash <= 0) continue;
40246
+ const deviceId = Number.parseInt(key.slice(0, slash), 10);
40247
+ if (!Number.isFinite(deviceId)) continue;
40248
+ held.push({
40249
+ deviceId,
40250
+ sessionId: key.slice(slash + 1),
40251
+ pipelineKey
40252
+ });
40253
+ }
40254
+ return held;
40255
+ }
40256
+ /** Drop a handle the sweep reclaimed, so it is not reaped twice. */
40257
+ function forgetEgressHandle(handle) {
40258
+ EGRESS_HANDLES.delete(egressHandleKey(handle.deviceId, handle.sessionId));
40259
+ }
40260
+ var WEBRTC_PROFILE_NAMES = [
40261
+ "high",
40262
+ "mid",
40263
+ "low"
40264
+ ];
40265
+ function resolveWebrtcTarget(pref) {
40266
+ if (pref === "auto") return void 0;
40267
+ if (WEBRTC_PROFILE_NAMES.includes(pref)) return {
40268
+ kind: "profile",
40269
+ profile: pref
40270
+ };
40271
+ return {
40272
+ kind: "cam-stream",
40273
+ camStreamId: pref
40274
+ };
40275
+ }
40276
+ async function handleInitiateSessionWithOffer(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
40277
+ const parsed = InitiateSessionWithOfferDirectiveSchema.safeParse({
40278
+ endpoint: endpointRaw,
40279
+ payload: payloadRaw ?? {}
40280
+ });
40281
+ if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
40282
+ const endpoint = parsed.data.endpoint;
40283
+ const payload = parsed.data.payload;
40284
+ const parsedId = parseCameraEndpointId(endpoint.endpointId);
40285
+ if (parsedId.kind !== "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", `endpointId ${endpoint.endpointId} is not a camera`);
40286
+ const deviceId = parsedId.deviceId;
40287
+ const sessionId = payload.sessionId;
40288
+ const log = deps.logger.withTags({
40289
+ deviceId,
40290
+ sessionId
40291
+ });
40292
+ const sdpOffer = payload.offer.value;
40293
+ if (sdpOffer.length === 0) return errorEnvelope(header, "INVALID_DIRECTIVE", "offer.value is empty");
40294
+ const api = deps.ctx.api;
40295
+ const exposedEntry = deps.listExposed().find((e) => e.deviceId === deviceId);
40296
+ const pinnedProfile = (() => {
40297
+ const pref = exposedEntry?.settings?.streamPreference;
40298
+ if (pref === "low" || pref === "mid" || pref === "high") return pref;
40299
+ })();
40300
+ const allowTranscode = exposedEntry?.settings?.allowTranscode !== false;
40301
+ const scored = pinnedProfile === void 0 ? await api.cameraStreams.pickStream.query({
40302
+ deviceId,
40303
+ requirements: {
40304
+ acceptCodecs: ["h264"],
40305
+ minHeight: 480,
40306
+ maxHeight: ALEXA_MAX_LINES,
40307
+ excludeDerived: true,
40308
+ allowTranscode
40309
+ },
40310
+ preferences: { targetHeight: 720 }
40311
+ }).catch((err) => {
40312
+ log.warn("alexa rtc-session: pickStream threw — falling back to the high slot", {
40313
+ tags: { deviceId },
40314
+ meta: { error: err instanceof Error ? err.message : String(err) }
40315
+ });
40316
+ return null;
40317
+ }) : null;
40318
+ const scoredProfile = scored === null ? null : await profileForCamStream({
40319
+ api,
40320
+ deviceId,
40321
+ camStreamId: scored.camStreamId,
40322
+ logger: log
40323
+ });
40324
+ const sourceProfile = pinnedProfile ?? scoredProfile ?? "high";
40325
+ if (pinnedProfile === void 0) log.info("alexa rtc-session: source scored against the Echo requirements", {
40326
+ tags: { deviceId },
40327
+ meta: {
40328
+ chosen: sourceProfile,
40329
+ scored: scored === null ? "none-eligible" : scored.reason,
40330
+ camStreamId: scored?.camStreamId ?? null,
40331
+ slot: scoredProfile ?? (scored === null ? null : "no-slot"),
40332
+ height: scored?.resolution?.height ?? null,
40333
+ transcodes: scored?.transcodes ?? null,
40334
+ allowTranscode
40335
+ }
40336
+ });
40337
+ let derivedTarget;
40338
+ /**
40339
+ * The primitive's release handle, when this session acquired one. Recorded so
40340
+ * `SessionDisconnected` can release it: a refcount whose holder disappears is
40341
+ * the one gap D67 leaves open, and the least this handler can do is not BE
40342
+ * that holder.
40343
+ */
40344
+ let egressPipelineKey = null;
40345
+ const picked = await api.cameraStreams.pickStream.query({
40346
+ deviceId,
40347
+ requirements: {
40348
+ acceptCodecs: ["h264"],
40349
+ minHeight: 480,
40350
+ excludeDerived: true,
40351
+ requireSiblingCodec: ["h265", "hevc"]
40352
+ }
40353
+ }).catch((err) => {
40354
+ log.warn("alexa rtc-session: cameraStreams.pickStream threw — falling back to transcode", { meta: { error: err instanceof Error ? err.message : String(err) } });
40355
+ return null;
40356
+ });
40357
+ if (picked) {
40358
+ log.info("alexa rtc-session: bypassing transcode via cameraStreams.pickStream", { meta: {
40359
+ sourceProfile,
40360
+ selectedCamStreamId: picked.camStreamId,
40361
+ reason: picked.reason
40362
+ } });
40363
+ derivedTarget = {
40364
+ kind: "cam-stream",
40365
+ camStreamId: picked.camStreamId
40366
+ };
40367
+ } else try {
40368
+ const acquired = await acquireAlexaEgress({
40369
+ api,
40370
+ deviceId,
40371
+ sourceProfile,
40372
+ sessionId,
40373
+ logger: log
40374
+ });
40375
+ egressPipelineKey = acquired.pipelineKey;
40376
+ EGRESS_HANDLES.set(egressHandleKey(deviceId, sessionId), acquired.pipelineKey);
40377
+ derivedTarget = {
40378
+ kind: "cam-stream",
40379
+ camStreamId: acquired.camStreamId
40380
+ };
40381
+ } catch (err) {
40382
+ log.warn("alexa rtc-session: egress acquire failed, falling back to streamPreference target", { meta: { error: err instanceof Error ? err.message : String(err) } });
40383
+ derivedTarget = resolveWebrtcTarget(exposedEntry?.settings?.streamPreference ?? "auto");
40384
+ }
40385
+ try {
40386
+ const result = await api.webrtcSession.handleOffer.mutate({
40387
+ deviceId,
40388
+ sdpOffer,
40389
+ sessionId,
40390
+ target: derivedTarget,
40391
+ relayOnly: false,
40392
+ nonTrickle: true,
40393
+ disableTurn: true,
40394
+ disableIpv6: true,
40395
+ consumerAttribution: {
40396
+ kind: "alexa",
40397
+ sessionId
40398
+ }
40399
+ });
40400
+ log.info("alexa rtc-session: AnswerGenerated", { meta: {
40401
+ returnedSessionId: result.sessionId,
40402
+ sdpAnswerLen: result.sdpAnswer.length
40403
+ } });
40404
+ return { event: {
40405
+ header: {
40406
+ namespace: "Alexa.RTCSessionController",
40407
+ name: "AnswerGeneratedForSession",
40408
+ messageId: header.messageId,
40409
+ correlationToken: header.correlationToken,
40410
+ payloadVersion: "3"
40411
+ },
40412
+ endpoint: { endpointId: endpoint.endpointId },
40413
+ payload: { answer: {
40414
+ format: payload.offer.format ?? "SDP",
40415
+ value: result.sdpAnswer
40416
+ } }
40417
+ } };
40418
+ } catch (err) {
40419
+ const message = err instanceof Error ? err.message : String(err);
40420
+ const mSectionSummary = (() => {
40421
+ const lines = sdpOffer.split(/\r?\n/);
40422
+ const sections = [];
40423
+ let current = null;
40424
+ for (const raw of lines) {
40425
+ const line = raw.trim();
40426
+ if (line.startsWith("m=")) {
40427
+ if (current) sections.push(current);
40428
+ current = {
40429
+ mid: null,
40430
+ kind: line.split(" ")[0]?.slice(2) ?? "unknown",
40431
+ direction: null,
40432
+ codecs: []
40433
+ };
40434
+ } else if (current) {
40435
+ if (line.startsWith("a=mid:")) current.mid = line.slice(6);
40436
+ else if (/^a=(sendonly|recvonly|sendrecv|inactive)$/.test(line)) current.direction = line.slice(2);
40437
+ else if (line.startsWith("a=rtpmap:")) current.codecs.push(line.slice(9));
40438
+ }
40439
+ }
40440
+ if (current) sections.push(current);
40441
+ return sections;
40442
+ })();
40443
+ log.warn("alexa rtc-session: handleOffer failed", { meta: {
40444
+ error: message,
40445
+ offerLen: sdpOffer.length,
40446
+ mSections: mSectionSummary,
40447
+ offerSdp: sdpOffer
40448
+ } });
40449
+ if (egressPipelineKey !== null) {
40450
+ EGRESS_HANDLES.delete(egressHandleKey(deviceId, sessionId));
40451
+ await releaseAlexaEgress({
40452
+ api,
40453
+ deviceId,
40454
+ pipelineKey: egressPipelineKey,
40455
+ logger: log
40456
+ });
40457
+ }
40458
+ return errorEnvelope(header, "INTERNAL_ERROR", `webrtc-session.handleOffer failed: ${message}`);
40459
+ }
40460
+ }
40461
+ async function handleSessionDisconnected(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
40462
+ const parsed = SessionDisconnectedDirectiveSchema.safeParse({
40463
+ endpoint: endpointRaw,
40464
+ payload: payloadRaw ?? {}
40465
+ });
40466
+ if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
40467
+ const endpoint = parsed.data.endpoint;
40468
+ const parsedId = parseCameraEndpointId(endpoint.endpointId);
40469
+ if (parsedId.kind === "camera") {
40470
+ const handleKey = egressHandleKey(parsedId.deviceId, parsed.data.payload.sessionId);
40471
+ const pipelineKey = EGRESS_HANDLES.get(handleKey);
40472
+ if (pipelineKey !== void 0) {
40473
+ EGRESS_HANDLES.delete(handleKey);
40474
+ await releaseAlexaEgress({
40475
+ api: deps.ctx.api,
40476
+ deviceId: parsedId.deviceId,
40477
+ pipelineKey,
40478
+ logger: deps.logger
40479
+ });
40480
+ }
40481
+ try {
40482
+ await deps.ctx.api.webrtcSession.closeSession.mutate({
40483
+ deviceId: parsedId.deviceId,
40484
+ sessionId: parsed.data.payload.sessionId
40485
+ });
40486
+ } catch (err) {
40487
+ deps.logger.warn("alexa rtc-session: closeSession threw on disconnect (continuing to ack)", {
40488
+ tags: {
40489
+ deviceId: parsedId.deviceId,
40490
+ sessionId: parsed.data.payload.sessionId
40491
+ },
40492
+ meta: { error: err instanceof Error ? err.message : String(err) }
40493
+ });
40494
+ }
40495
+ }
40496
+ const disconnectedDeviceId = parsedId.kind === "camera" ? parsedId.deviceId : void 0;
40497
+ deps.logger.info("alexa rtc-session: SessionDisconnected", {
40498
+ tags: {
40499
+ sessionId: parsed.data.payload.sessionId,
40500
+ ...disconnectedDeviceId !== void 0 ? { deviceId: disconnectedDeviceId } : {}
40501
+ },
40502
+ meta: { endpointId: endpoint.endpointId }
40503
+ });
40504
+ return { event: {
40505
+ header: {
40506
+ namespace: "Alexa",
40507
+ name: "Response",
40508
+ messageId: header.messageId,
40509
+ correlationToken: header.correlationToken,
40510
+ payloadVersion: "3"
40511
+ },
40512
+ endpoint: { endpointId: endpoint.endpointId },
40513
+ payload: {}
40514
+ } };
40515
+ }
40516
+ //#endregion
39789
40517
  //#region src/handlers/security-panel-arm-state.ts
39790
40518
  /**
39791
40519
  * The panel modes behind each Alexa arm state, PRIMARY first — the mirror of
@@ -40216,101 +40944,6 @@ function buildAlarmPanelEndpoint(input) {
40216
40944
  };
40217
40945
  }
40218
40946
  //#endregion
40219
- //#region src/handlers/error-envelope.ts
40220
- /**
40221
- * Shared Alexa `Alexa/ErrorResponse` envelope builder.
40222
- *
40223
- * Lives in its own module so every handler (and the directive router)
40224
- * can emit its own namespace-appropriate error without circular imports.
40225
- */
40226
- object({ event: object({
40227
- header: object({
40228
- namespace: literal("Alexa"),
40229
- name: literal("ErrorResponse"),
40230
- messageId: string(),
40231
- payloadVersion: literal("3")
40232
- }),
40233
- payload: object({
40234
- type: string(),
40235
- message: string()
40236
- })
40237
- }) });
40238
- function errorEnvelope(header, type, message) {
40239
- return { event: {
40240
- header: {
40241
- namespace: "Alexa",
40242
- name: "ErrorResponse",
40243
- messageId: header.messageId,
40244
- payloadVersion: "3"
40245
- },
40246
- payload: {
40247
- type,
40248
- message
40249
- }
40250
- } };
40251
- }
40252
- //#endregion
40253
- //#region src/handlers/types.ts
40254
- /**
40255
- * Zod schemas for the subset of the Alexa Smart Home directive surface
40256
- * that we actually parse hub-side. The Smart Home Skill API ships
40257
- * thousands of optional fields per namespace — we only validate what
40258
- * we read; everything else passes through as `unknown`.
40259
- *
40260
- * Reference: https://developer.amazon.com/en-US/docs/alexa/smarthome/smart-home-skill-api-message-reference.html
40261
- */
40262
- /** A directive header carries namespace + name + token + correlation id. */
40263
- var DirectiveHeaderSchema = object({
40264
- namespace: string(),
40265
- name: string(),
40266
- payloadVersion: string(),
40267
- messageId: string(),
40268
- correlationToken: string().optional()
40269
- });
40270
- /** Scope carries the bearer token Alexa minted via our OAuth provider. */
40271
- var BearerScopeSchema = object({
40272
- type: literal("BearerToken"),
40273
- token: string()
40274
- });
40275
- /** Endpoint reference inside a directive payload. */
40276
- var EndpointRefSchema = object({
40277
- endpointId: string(),
40278
- scope: BearerScopeSchema.optional(),
40279
- cookie: record(string(), string()).optional()
40280
- });
40281
- var DiscoveryDirectiveSchema = object({
40282
- header: DirectiveHeaderSchema.extend({
40283
- namespace: literal("Alexa.Discovery"),
40284
- name: literal("Discover")
40285
- }),
40286
- payload: object({ scope: BearerScopeSchema })
40287
- });
40288
- /** Envelope wrapping a directive on the Alexa→skill wire. */
40289
- var DirectiveRequestSchema = object({ directive: object({
40290
- header: DirectiveHeaderSchema,
40291
- endpoint: EndpointRefSchema.optional(),
40292
- payload: unknown().optional()
40293
- }) });
40294
- var InitializeCameraStreamsPayloadSchema = object({ cameraStreams: array(object({
40295
- protocol: string(),
40296
- resolution: object({
40297
- width: number(),
40298
- height: number()
40299
- }).optional(),
40300
- authorizationType: string().optional(),
40301
- videoCodec: string().optional(),
40302
- audioCodec: string().optional()
40303
- })).optional() });
40304
- var InitiateSessionWithOfferPayloadSchema = object({
40305
- sessionId: string(),
40306
- offer: object({
40307
- format: string().optional(),
40308
- value: string()
40309
- })
40310
- });
40311
- var SessionDisconnectedPayloadSchema = object({ sessionId: string() });
40312
- var SetModePayloadSchema = object({ mode: string() });
40313
- //#endregion
40314
40947
  //#region src/handlers/discovery.ts
40315
40948
  var discoveryPayloadSchema = DiscoveryDirectiveSchema.shape.payload;
40316
40949
  /** Devices built at once in `handleDiscovery` — latency-bound tRPC reads, so
@@ -40519,60 +41152,6 @@ function discoveryResponse(header, endpoints) {
40519
41152
  } };
40520
41153
  }
40521
41154
  //#endregion
40522
- //#region src/handlers/endpoint-id.ts
40523
- var SEPARATOR = "__";
40524
- function parseCameraEndpointId(raw) {
40525
- if (!raw.includes(SEPARATOR)) {
40526
- const id = parseNonNegativeInt(raw);
40527
- if (id === null) return {
40528
- kind: "invalid",
40529
- reason: `not a numeric deviceId: ${raw}`
40530
- };
40531
- return {
40532
- kind: "camera",
40533
- deviceId: id
40534
- };
40535
- }
40536
- const [head, tail, ...rest] = raw.split(SEPARATOR);
40537
- if (head === void 0 || tail === void 0 || rest.length > 0) return {
40538
- kind: "invalid",
40539
- reason: `unexpected segments in endpointId: ${raw}`
40540
- };
40541
- const parent = parseNonNegativeInt(head);
40542
- if (parent === null) return {
40543
- kind: "invalid",
40544
- reason: `parent segment not numeric: ${raw}`
40545
- };
40546
- if (tail === "autotrack") return {
40547
- kind: "autotrack",
40548
- parentDeviceId: parent
40549
- };
40550
- if (tail === "privacy") return {
40551
- kind: "privacy",
40552
- parentDeviceId: parent
40553
- };
40554
- if (tail === "alarm") return {
40555
- kind: "alarm-panel",
40556
- deviceId: parent
40557
- };
40558
- const child = parseNonNegativeInt(tail);
40559
- if (child === null) return {
40560
- kind: "invalid",
40561
- reason: `child segment not numeric and not 'autotrack'/'privacy'/'alarm': ${raw}`
40562
- };
40563
- return {
40564
- kind: "child",
40565
- parentDeviceId: parent,
40566
- childDeviceId: child
40567
- };
40568
- }
40569
- function parseNonNegativeInt(s) {
40570
- if (!/^\d+$/.test(s)) return null;
40571
- const n = Number.parseInt(s, 10);
40572
- if (!Number.isFinite(n) || n < 0) return null;
40573
- return n;
40574
- }
40575
- //#endregion
40576
41155
  //#region src/handlers/brightness-controller.ts
40577
41156
  var SetBrightnessDirectiveSchema = object({
40578
41157
  header: object({
@@ -41149,254 +41728,6 @@ async function collectChildProperties(api, childDeviceId, properties, timeOfSamp
41149
41728
  });
41150
41729
  }
41151
41730
  //#endregion
41152
- //#region src/handlers/rtc-session.ts
41153
- var InitiateSessionWithOfferDirectiveSchema = object({
41154
- endpoint: EndpointRefSchema,
41155
- payload: InitiateSessionWithOfferPayloadSchema
41156
- });
41157
- var SessionDisconnectedDirectiveSchema = object({
41158
- endpoint: EndpointRefSchema,
41159
- payload: SessionDisconnectedPayloadSchema
41160
- });
41161
- /**
41162
- * Live egress handles, keyed by `<deviceId>/<sessionId>`.
41163
- *
41164
- * The primitive's refcount has no lease TTL: a holder that vanishes without
41165
- * releasing leaks a child until the broker restarts (D67). This handler is a
41166
- * holder, so it keeps the one piece of state that lets it not be that holder —
41167
- * the `pipelineKey` its `SessionDisconnected` has to release.
41168
- *
41169
- * A module-level map is right here because the directive handlers are free
41170
- * functions called per directive; the entry is written on a successful acquire
41171
- * and deleted on the release path, both of which are the same tick as the
41172
- * directive that owns it.
41173
- */
41174
- var EGRESS_HANDLES = /* @__PURE__ */ new Map();
41175
- function egressHandleKey(deviceId, sessionId) {
41176
- return `${deviceId}/${sessionId}`;
41177
- }
41178
- var WEBRTC_PROFILE_NAMES = [
41179
- "high",
41180
- "mid",
41181
- "low"
41182
- ];
41183
- function resolveWebrtcTarget(pref) {
41184
- if (pref === "auto") return void 0;
41185
- if (WEBRTC_PROFILE_NAMES.includes(pref)) return {
41186
- kind: "profile",
41187
- profile: pref
41188
- };
41189
- return {
41190
- kind: "cam-stream",
41191
- camStreamId: pref
41192
- };
41193
- }
41194
- async function handleInitiateSessionWithOffer(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41195
- const parsed = InitiateSessionWithOfferDirectiveSchema.safeParse({
41196
- endpoint: endpointRaw,
41197
- payload: payloadRaw ?? {}
41198
- });
41199
- if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
41200
- const endpoint = parsed.data.endpoint;
41201
- const payload = parsed.data.payload;
41202
- const parsedId = parseCameraEndpointId(endpoint.endpointId);
41203
- if (parsedId.kind !== "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", `endpointId ${endpoint.endpointId} is not a camera`);
41204
- const deviceId = parsedId.deviceId;
41205
- const sessionId = payload.sessionId;
41206
- const log = deps.logger.withTags({
41207
- deviceId,
41208
- sessionId
41209
- });
41210
- const sdpOffer = payload.offer.value;
41211
- if (sdpOffer.length === 0) return errorEnvelope(header, "INVALID_DIRECTIVE", "offer.value is empty");
41212
- const api = deps.ctx.api;
41213
- const exposedEntry = deps.listExposed().find((e) => e.deviceId === deviceId);
41214
- const explicitSourceProfile = exposedEntry?.settings?.sourceProfile;
41215
- const mappedFromPreference = (() => {
41216
- const pref = exposedEntry?.settings?.streamPreference;
41217
- if (pref === "low" || pref === "mid" || pref === "high") return pref;
41218
- })();
41219
- const sourceProfile = explicitSourceProfile ?? mappedFromPreference ?? "high";
41220
- let derivedTarget;
41221
- /**
41222
- * The primitive's release handle, when this session acquired one. Recorded so
41223
- * `SessionDisconnected` can release it: a refcount whose holder disappears is
41224
- * the one gap D67 leaves open, and the least this handler can do is not BE
41225
- * that holder.
41226
- */
41227
- let egressPipelineKey = null;
41228
- const picked = await api.cameraStreams.pickStream.query({
41229
- deviceId,
41230
- requirements: {
41231
- acceptCodecs: ["h264"],
41232
- minHeight: 480,
41233
- excludeDerived: true,
41234
- requireSiblingCodec: ["h265", "hevc"]
41235
- }
41236
- }).catch((err) => {
41237
- log.warn("alexa rtc-session: cameraStreams.pickStream threw — falling back to transcode", { meta: { error: err instanceof Error ? err.message : String(err) } });
41238
- return null;
41239
- });
41240
- if (picked) {
41241
- log.info("alexa rtc-session: bypassing transcode via cameraStreams.pickStream", { meta: {
41242
- sourceProfile,
41243
- selectedCamStreamId: picked.camStreamId,
41244
- reason: picked.reason
41245
- } });
41246
- derivedTarget = {
41247
- kind: "cam-stream",
41248
- camStreamId: picked.camStreamId
41249
- };
41250
- } else try {
41251
- const acquired = await acquireAlexaEgress({
41252
- api,
41253
- deviceId,
41254
- sourceProfile,
41255
- sessionId,
41256
- logger: log
41257
- });
41258
- egressPipelineKey = acquired.pipelineKey;
41259
- EGRESS_HANDLES.set(egressHandleKey(deviceId, sessionId), acquired.pipelineKey);
41260
- derivedTarget = {
41261
- kind: "cam-stream",
41262
- camStreamId: acquired.camStreamId
41263
- };
41264
- } catch (err) {
41265
- log.warn("alexa rtc-session: egress acquire failed, falling back to streamPreference target", { meta: { error: err instanceof Error ? err.message : String(err) } });
41266
- derivedTarget = resolveWebrtcTarget(exposedEntry?.settings?.streamPreference ?? "auto");
41267
- }
41268
- try {
41269
- const result = await api.webrtcSession.handleOffer.mutate({
41270
- deviceId,
41271
- sdpOffer,
41272
- sessionId,
41273
- target: derivedTarget,
41274
- relayOnly: false,
41275
- nonTrickle: true,
41276
- disableTurn: true,
41277
- disableIpv6: true,
41278
- consumerAttribution: {
41279
- kind: "alexa",
41280
- sessionId
41281
- }
41282
- });
41283
- log.info("alexa rtc-session: AnswerGenerated", { meta: {
41284
- returnedSessionId: result.sessionId,
41285
- sdpAnswerLen: result.sdpAnswer.length
41286
- } });
41287
- return { event: {
41288
- header: {
41289
- namespace: "Alexa.RTCSessionController",
41290
- name: "AnswerGeneratedForSession",
41291
- messageId: header.messageId,
41292
- correlationToken: header.correlationToken,
41293
- payloadVersion: "3"
41294
- },
41295
- endpoint: { endpointId: endpoint.endpointId },
41296
- payload: { answer: {
41297
- format: payload.offer.format ?? "SDP",
41298
- value: result.sdpAnswer
41299
- } }
41300
- } };
41301
- } catch (err) {
41302
- const message = err instanceof Error ? err.message : String(err);
41303
- const mSectionSummary = (() => {
41304
- const lines = sdpOffer.split(/\r?\n/);
41305
- const sections = [];
41306
- let current = null;
41307
- for (const raw of lines) {
41308
- const line = raw.trim();
41309
- if (line.startsWith("m=")) {
41310
- if (current) sections.push(current);
41311
- current = {
41312
- mid: null,
41313
- kind: line.split(" ")[0]?.slice(2) ?? "unknown",
41314
- direction: null,
41315
- codecs: []
41316
- };
41317
- } else if (current) {
41318
- if (line.startsWith("a=mid:")) current.mid = line.slice(6);
41319
- else if (/^a=(sendonly|recvonly|sendrecv|inactive)$/.test(line)) current.direction = line.slice(2);
41320
- else if (line.startsWith("a=rtpmap:")) current.codecs.push(line.slice(9));
41321
- }
41322
- }
41323
- if (current) sections.push(current);
41324
- return sections;
41325
- })();
41326
- log.warn("alexa rtc-session: handleOffer failed", { meta: {
41327
- error: message,
41328
- offerLen: sdpOffer.length,
41329
- mSections: mSectionSummary,
41330
- offerSdp: sdpOffer
41331
- } });
41332
- if (egressPipelineKey !== null) {
41333
- EGRESS_HANDLES.delete(egressHandleKey(deviceId, sessionId));
41334
- await releaseAlexaEgress({
41335
- api,
41336
- deviceId,
41337
- pipelineKey: egressPipelineKey,
41338
- logger: log
41339
- });
41340
- }
41341
- return errorEnvelope(header, "INTERNAL_ERROR", `webrtc-session.handleOffer failed: ${message}`);
41342
- }
41343
- }
41344
- async function handleSessionDisconnected(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41345
- const parsed = SessionDisconnectedDirectiveSchema.safeParse({
41346
- endpoint: endpointRaw,
41347
- payload: payloadRaw ?? {}
41348
- });
41349
- if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
41350
- const endpoint = parsed.data.endpoint;
41351
- const parsedId = parseCameraEndpointId(endpoint.endpointId);
41352
- if (parsedId.kind === "camera") {
41353
- const handleKey = egressHandleKey(parsedId.deviceId, parsed.data.payload.sessionId);
41354
- const pipelineKey = EGRESS_HANDLES.get(handleKey);
41355
- if (pipelineKey !== void 0) {
41356
- EGRESS_HANDLES.delete(handleKey);
41357
- await releaseAlexaEgress({
41358
- api: deps.ctx.api,
41359
- deviceId: parsedId.deviceId,
41360
- pipelineKey,
41361
- logger: deps.logger
41362
- });
41363
- }
41364
- try {
41365
- await deps.ctx.api.webrtcSession.closeSession.mutate({
41366
- deviceId: parsedId.deviceId,
41367
- sessionId: parsed.data.payload.sessionId
41368
- });
41369
- } catch (err) {
41370
- deps.logger.warn("alexa rtc-session: closeSession threw on disconnect (continuing to ack)", {
41371
- tags: {
41372
- deviceId: parsedId.deviceId,
41373
- sessionId: parsed.data.payload.sessionId
41374
- },
41375
- meta: { error: err instanceof Error ? err.message : String(err) }
41376
- });
41377
- }
41378
- }
41379
- const disconnectedDeviceId = parsedId.kind === "camera" ? parsedId.deviceId : void 0;
41380
- deps.logger.info("alexa rtc-session: SessionDisconnected", {
41381
- tags: {
41382
- sessionId: parsed.data.payload.sessionId,
41383
- ...disconnectedDeviceId !== void 0 ? { deviceId: disconnectedDeviceId } : {}
41384
- },
41385
- meta: { endpointId: endpoint.endpointId }
41386
- });
41387
- return { event: {
41388
- header: {
41389
- namespace: "Alexa",
41390
- name: "Response",
41391
- messageId: header.messageId,
41392
- correlationToken: header.correlationToken,
41393
- payloadVersion: "3"
41394
- },
41395
- endpoint: { endpointId: endpoint.endpointId },
41396
- payload: {}
41397
- } };
41398
- }
41399
- //#endregion
41400
41731
  //#region src/handlers/security-panel.ts
41401
41732
  var ArmPayloadSchema = object({ armState: _enum([
41402
41733
  "ARMED_STAY",
@@ -43444,6 +43775,11 @@ var ExportAlexaAddon = class extends BaseAddon {
43444
43775
  });
43445
43776
  });
43446
43777
  this.ctx.addDisposer(async () => offTunnelStarted());
43778
+ const reaper = setInterval(() => {
43779
+ this.reapDeadEgressHandles();
43780
+ }, EGRESS_REAP_INTERVAL_MS);
43781
+ reaper.unref?.();
43782
+ this.ctx.addDisposer(async () => clearInterval(reaper));
43447
43783
  this.ctx.logger.info("export-alexa: initialized", { meta: {
43448
43784
  exposedCount: this.config.exposed.length,
43449
43785
  skillMode: this.config.skillMode,
@@ -44098,6 +44434,37 @@ var ExportAlexaAddon = class extends BaseAddon {
44098
44434
  ]
44099
44435
  }] });
44100
44436
  }
44437
+ /**
44438
+ * One sweep: ask the broker which held sessions are still alive, and release
44439
+ * the transcodes the dead ones are still holding.
44440
+ */
44441
+ async reapDeadEgressHandles() {
44442
+ const held = heldEgressHandles();
44443
+ if (held.length === 0) return;
44444
+ const dead = await reapDeadEgressHandles({
44445
+ held,
44446
+ isAlive: async (handle) => {
44447
+ try {
44448
+ return (await this.ctx.api.webrtcSession.getSessionState.query({
44449
+ deviceId: handle.deviceId,
44450
+ sessionId: handle.sessionId
44451
+ })).alive;
44452
+ } catch {
44453
+ return null;
44454
+ }
44455
+ }
44456
+ });
44457
+ for (const handle of dead) {
44458
+ logReaped(this.ctx.logger, handle);
44459
+ forgetEgressHandle(handle);
44460
+ await releaseAlexaEgress({
44461
+ api: this.ctx.api,
44462
+ deviceId: handle.deviceId,
44463
+ pipelineKey: handle.pipelineKey,
44464
+ logger: this.ctx.logger
44465
+ }).catch(() => {});
44466
+ }
44467
+ }
44101
44468
  async buildDeviceSettingsContribution(deviceId) {
44102
44469
  if (!await this.isCameraDevice(deviceId)) return null;
44103
44470
  const entry = this.findEntry(deviceId);
@@ -44105,6 +44472,7 @@ var ExportAlexaAddon = class extends BaseAddon {
44105
44472
  const enabled = entry !== null;
44106
44473
  const enabledKey = `alexa:${deviceId}:enabled`;
44107
44474
  const streamPreferenceKey = `alexa:${deviceId}:streamPreference`;
44475
+ const allowTranscodeKey = `alexa:${deviceId}:allowTranscode`;
44108
44476
  const linkedCount = this.config.linkedAccounts.length;
44109
44477
  return {
44110
44478
  tabs: [{
@@ -44150,6 +44518,19 @@ var ExportAlexaAddon = class extends BaseAddon {
44150
44518
  equals: true
44151
44519
  },
44152
44520
  immediate: true
44521
+ },
44522
+ {
44523
+ type: "boolean",
44524
+ key: allowTranscodeKey,
44525
+ label: "Allow transcoding for Alexa",
44526
+ description: "Let the hub re-encode this camera for the Echo when no stream is directly usable. Off means only a stream Alexa can take as-is (H.264, 480p-1080p) is offered — cheaper, but a camera that publishes only H.265, or only a small sub-stream, will not be streamable to Alexa at all.",
44527
+ style: "switch",
44528
+ value: settings.allowTranscode !== false,
44529
+ showWhen: {
44530
+ field: enabledKey,
44531
+ equals: true
44532
+ },
44533
+ immediate: true
44153
44534
  }
44154
44535
  ]
44155
44536
  }]
@@ -44169,26 +44550,17 @@ var ExportAlexaAddon = class extends BaseAddon {
44169
44550
  const idStr = String(deviceId);
44170
44551
  const current = this.findEntry(deviceId);
44171
44552
  const wasEnabled = current !== null;
44172
- const sourceProfileKey = `alexa:${deviceId}:sourceProfile`;
44173
- if (sourceProfileKey in patch) {
44174
- if (!wasEnabled) return { success: true };
44175
- const currentSettings = current?.settings ?? DEFAULT_DEVICE_SETTINGS;
44176
- const sourceProfileRaw = patch[sourceProfileKey];
44177
- const sourceProfile = sourceProfileRaw === "mid" ? "mid" : sourceProfileRaw === "low" ? "low" : "high";
44178
- await this.patchEntrySettings(deviceId, {
44179
- ...currentSettings,
44180
- sourceProfile
44181
- });
44182
- return { success: true };
44183
- }
44184
44553
  const enabledKey = `alexa:${deviceId}:enabled`;
44185
44554
  const streamPreferenceKey = `alexa:${deviceId}:streamPreference`;
44555
+ const allowTranscodeKey = `alexa:${deviceId}:allowTranscode`;
44186
44556
  const enabledValue = enabledKey in patch ? Boolean(patch[enabledKey]) : wasEnabled;
44187
44557
  const streamPreferenceRaw = streamPreferenceKey in patch ? patch[streamPreferenceKey] : current?.settings?.streamPreference;
44188
44558
  const streamPreference = typeof streamPreferenceRaw === "string" && streamPreferenceRaw.trim().length > 0 ? streamPreferenceRaw : "auto";
44559
+ const allowTranscode = allowTranscodeKey in patch ? Boolean(patch[allowTranscodeKey]) : current?.settings?.allowTranscode !== false;
44189
44560
  const nextSettings = {
44190
44561
  ...current?.settings ?? DEFAULT_DEVICE_SETTINGS,
44191
- streamPreference
44562
+ streamPreference,
44563
+ allowTranscode
44192
44564
  };
44193
44565
  if (!enabledValue) {
44194
44566
  if (wasEnabled) await this.unexposeDevice(idStr);
@@ -44200,13 +44572,22 @@ var ExportAlexaAddon = class extends BaseAddon {
44200
44572
  return { success: true };
44201
44573
  }
44202
44574
  const currentPref = current?.settings?.streamPreference ?? "auto";
44575
+ const currentAllow = current?.settings?.allowTranscode !== false;
44203
44576
  await this.patchEntrySettings(deviceId, nextSettings);
44204
- if (currentPref !== streamPreference) {
44205
- this.ctx.logger.info("export-alexa: streamPreference changed — refreshing exposure", { meta: {
44206
- deviceId,
44207
- from: currentPref,
44208
- to: streamPreference
44209
- } });
44577
+ if (currentPref !== streamPreference || currentAllow !== allowTranscode) {
44578
+ this.ctx.logger.info("export-alexa: source settings changed — refreshing exposure", {
44579
+ tags: { deviceId },
44580
+ meta: {
44581
+ streamPreference: {
44582
+ from: currentPref,
44583
+ to: streamPreference
44584
+ },
44585
+ allowTranscode: {
44586
+ from: currentAllow,
44587
+ to: allowTranscode
44588
+ }
44589
+ }
44590
+ });
44210
44591
  try {
44211
44592
  await this.unexposeDevice(idStr);
44212
44593
  await this.exposeDevice(idStr);