@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.
@@ -1,5 +1,5 @@
1
1
  import * as crypto$1 from "node:crypto";
2
- //#region ../types/dist/event-category-ZyX6jcse.mjs
2
+ //#region ../types/dist/event-category-BVDXG4tB.mjs
3
3
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
4
4
  EventCategory["SystemBoot"] = "system.boot";
5
5
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -616,6 +616,20 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
616
616
  * pull-reconcile from the provider's `getStatus` on reconnect. */
617
617
  EventCategory["MeshNetworkChanged"] = "network.mesh.changed";
618
618
  EventCategory["BackupCompleted"] = "backup.completed";
619
+ /**
620
+ * A whole backup RUN finished — every destination attempted, win or lose.
621
+ *
622
+ * `backup.completed` fires once per DESTINATION, which is the right grain for
623
+ * a progress UI and the wrong one for a notification: an operator with three
624
+ * destinations would be told three times. And a run where two of three
625
+ * destinations succeeded is not a clean success — a single "backup
626
+ * completed" that hid the failed one would be a lie, so the count of each is
627
+ * carried here and the message says both.
628
+ *
629
+ * Emitted by the backup orchestrator only after the destination loop, so a
630
+ * run that dies during the BUILD phase produces no completion at all.
631
+ */
632
+ EventCategory["BackupRunCompleted"] = "backup.run-completed";
619
633
  EventCategory["BackupRestored"] = "backup.restored";
620
634
  EventCategory["NotificationDispatched"] = "notification.dispatched";
621
635
  EventCategory["NotificationFailed"] = "notification.failed";
@@ -5346,7 +5360,7 @@ var ZodIssueCode = {
5346
5360
  var ZodFirstPartyTypeKind;
5347
5361
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5348
5362
  //#endregion
5349
- //#region ../types/dist/sleep-DBKu2-U5.mjs
5363
+ //#region ../types/dist/sleep-DEuj7E3j.mjs
5350
5364
  /**
5351
5365
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5352
5366
  * window to float samples (D455).
@@ -7533,6 +7547,28 @@ var EncodeProfileSchema = object({
7533
7547
  outputArgs: array(string()).optional()
7534
7548
  });
7535
7549
  /**
7550
+ * THE target rule: which of two sizes serves a consumer better.
7551
+ *
7552
+ * "Prefer at or above the target so the consumer downscales instead of
7553
+ * upscaling; among those the SMALLEST, because the extra pixels are thrown
7554
+ * away and the decode is not; among the rest the LARGEST, because it is the
7555
+ * closest we can get." One sentence, and until now it was written twice — once
7556
+ * here in lines, once in `stream-selection.ts` in pixels, for the same two
7557
+ * exporters. The two agreed, which is luck, not a property.
7558
+ *
7559
+ * The `size` is whatever measure the caller ranks by: the cap ranks by LINES
7560
+ * (a consumer's requirement is stated in p), the RTSP picker by PIXELS (it
7561
+ * compares entries of possibly different aspect). The rule is the same either
7562
+ * way and the measure is the caller's business.
7563
+ *
7564
+ * Returns a sort delta: negative when `a` should come first.
7565
+ */
7566
+ function compareToTarget(a, b, target) {
7567
+ const aReaches = a >= target;
7568
+ if (aReaches !== b >= target) return aReaches ? -1 : 1;
7569
+ return aReaches ? a - b : b - a;
7570
+ }
7571
+ /**
7536
7572
  * The shape every live egress starts from: H.264 Baseline 3.1 at 720p25.
7537
7573
  * Baseline because it is the one profile every consumer in this repo decodes
7538
7574
  * (Echo, iOS, an old browser); 3.1 because that is what the SDPs advertise.
@@ -9447,6 +9483,47 @@ var LogChannelWindowSchema = object({
9447
9483
  /** `null` = every camera. A non-empty list narrows to those numeric ids. */
9448
9484
  deviceIds: array(number().int()).readonly().nullable()
9449
9485
  });
9486
+ /**
9487
+ * Shared stream-selection picker for export addons.
9488
+ *
9489
+ * Both `addon-export-alexa` and `addon-export-hap` resolve the
9490
+ * operator's `streamPreference` setting against the broker's RTSP
9491
+ * entries before dialling a camera. Each addon used to roll its own:
9492
+ * Alexa had `pickPreferredRtspEntry` under `handlers/`, HAP had an
9493
+ * inline `"prefer /mid, then /high, then first"` chain inside its
9494
+ * camera-streams mapper. The chains drifted (Alexa honoured
9495
+ * `streamPreference`, HAP didn't; only Alexa got the smart
9496
+ * resolution-targeted auto-pick) and the cross-addon import rule
9497
+ * blocks deduping in either direction.
9498
+ *
9499
+ * Lifting the picker into `@camstack/types` lets every exporter call
9500
+ * the same code path with the consumer's target resolution baked into
9501
+ * the call site — Alexa passes 1280×720, HomeKit passes 1920×1080,
9502
+ * the picker handles the rest.
9503
+ *
9504
+ * Selection algorithm:
9505
+ * - pref === '<profile>' → profile-keyed entries (from
9506
+ * `getProfileRtspEntries`) match on `e.profile`;
9507
+ * legacy raw entries match on the brokerId
9508
+ * suffix (`brokerId` ENDS WITH `/${pref}`, shape
9509
+ * `${deviceId}/${camStreamId}`). Addons store the
9510
+ * bare profile/camStream id in their
9511
+ * `ExportDeviceSettings.streamPreference`. Falls
9512
+ * back to 'auto' when no enabled entry matches
9513
+ * either way.
9514
+ * - pref === 'auto' → when `targetResolution` is given, pick the
9515
+ * entry whose source resolution is closest to
9516
+ * it (prefer ≥ target so the consumer
9517
+ * downscales instead of upscaling). Without a
9518
+ * target, fall back to first-enabled. If no
9519
+ * entry advertises a resolution at all
9520
+ * (broker hasn't probed yet), also fall back
9521
+ * to first-enabled so cold start still serves.
9522
+ *
9523
+ * Returns `null` when nothing is publishable — callers fold that into
9524
+ * the consumer's "no stream" error (Alexa: STREAM_TYPE_UNSUPPORTED;
9525
+ * HAP: a thrown error inside `startFfmpegForSession`).
9526
+ */
9450
9527
  function pickPreferredRtspEntry(entries, pref, deviceId, options = {}) {
9451
9528
  if (entries.length === 0) return null;
9452
9529
  const prefix = `${deviceId}/`;
@@ -9476,30 +9553,23 @@ function pickPreferredRtspEntry(entries, pref, deviceId, options = {}) {
9476
9553
  return toPicked(eligible[0]);
9477
9554
  }
9478
9555
  /**
9479
- * Pick the entry whose `resolution` is closest to `target`. Prefer
9480
- * entries ≥ target (downscale is cheap at the consumer; upscale is
9481
- * lossy). Among the rest pick the LARGEST still ≤ target so the
9482
- * consumer gets the best feasible quality. "Closeness" is the
9483
- * `width × height` pixel delta.
9556
+ * Pick the entry whose `resolution` is closest to `target`, by the ONE target
9557
+ * rule ({@link compareToTarget}): prefer at or above the target so the consumer
9558
+ * downscales instead of upscaling; among those the smallest; among the rest the
9559
+ * largest.
9560
+ *
9561
+ * This function used to implement that rule itself, in pixels, while
9562
+ * `rankStreams` implemented it again in lines — the same sentence written twice
9563
+ * for the same two exporters, agreeing by luck rather than by construction.
9564
+ * Only the MEASURE is this picker's own: it compares whole pixel counts because
9565
+ * its entries can differ in aspect, where the cap's requirement is stated in p.
9484
9566
  */
9485
9567
  function pickClosestResolution(entries, target) {
9486
9568
  const targetPixels = target.width * target.height;
9487
- let bestAbove;
9488
- let bestBelow;
9489
- for (const e of entries) {
9490
- if (e.resolution === void 0) continue;
9491
- const pixels = e.resolution.width * e.resolution.height;
9492
- if (pixels >= targetPixels) {
9493
- if (!bestAbove || pixels < bestAbove.pixels) bestAbove = {
9494
- entry: e,
9495
- pixels
9496
- };
9497
- } else if (!bestBelow || pixels > bestBelow.pixels) bestBelow = {
9498
- entry: e,
9499
- pixels
9500
- };
9501
- }
9502
- return bestAbove?.entry ?? bestBelow?.entry;
9569
+ return [...entries.flatMap((entry) => entry.resolution === void 0 ? [] : [{
9570
+ entry,
9571
+ pixels: entry.resolution.width * entry.resolution.height
9572
+ }])].sort((a, b) => compareToTarget(a.pixels, b.pixels, targetPixels))[0]?.entry;
9503
9573
  }
9504
9574
  var MODEL_FORMATS = [
9505
9575
  "onnx",
@@ -11713,6 +11783,58 @@ method(ListInputSchema, array(BrokerInfoSchema$1)), method(GetInputSchema, Broke
11713
11783
  auth: "admin"
11714
11784
  }), method(GetStateInputSchema, unknown().nullable()), method(_void(), RegistryStatusSchema);
11715
11785
  DeviceType.Camera;
11786
+ /**
11787
+ * The signals a device can emit to WAKE its own stream.
11788
+ *
11789
+ * A camera whose stream is built on demand sleeps until something asks for it,
11790
+ * and "something" cannot be a consumer that is merely attached — a Frigate-style
11791
+ * puller holds a session open for ever, and treating that as demand would keep
11792
+ * a battery camera awake for ever, which is the whole thing the battery is for
11793
+ * (D173). So the wake has to come from the CAMERA: an event it noticed by
11794
+ * itself, with no stream running.
11795
+ *
11796
+ * ## The vocabulary is the PROVIDER'S, not ours
11797
+ *
11798
+ * Like `consumables`, this cap declares no vocabulary of its own. A provider
11799
+ * names each signal with a `code` it chooses and a `label` an operator reads.
11800
+ * Reolink offers motion and camera-native detection; another provider may offer
11801
+ * a tamper, a doorbell press, a PIR, or something no camera in this fleet has
11802
+ * yet. A fixed enum here would mean every new signal is a framework release.
11803
+ *
11804
+ * It is deliberately NOT derived from the caps a device already binds. Whether
11805
+ * a camera CAN push firmware motion is expressed by `motionSources` containing
11806
+ * `'onboard'`, and whether it does AI on-camera by the `native-object-detection`
11807
+ * binding — but both answer "what drives the detection pipeline", which is a
11808
+ * different question from "what may wake a sleeping stream". A camera can do
11809
+ * the first and not be trusted with the second, and the operator picks per
11810
+ * camera. Two questions, two authorities.
11811
+ *
11812
+ * ## Availability is not permission
11813
+ *
11814
+ * `listSignals` says what the device CAN emit. Whether a given signal actually
11815
+ * wakes the stream is the operator's per-camera choice, held by the broker
11816
+ * alongside the cooldown — see the stream-broker cap's wake settings. A
11817
+ * provider declaring a signal is not a provider enabling it.
11818
+ */
11819
+ /** One signal a device can emit. */
11820
+ var StreamSignalSchema = object({
11821
+ /** Stable id chosen by the provider, e.g. `'motion'`, `'person'`, `'tamper'`. */
11822
+ code: string().min(1),
11823
+ /** What an operator reads in the picker. The provider's own wording. */
11824
+ label: string().min(1),
11825
+ /**
11826
+ * Whether the provider recommends this signal ON when a camera is first set
11827
+ * up. A provider knows which of its signals are cheap and reliable; an
11828
+ * operator should not have to discover that by trial. Reolink recommends
11829
+ * both of its own.
11830
+ */
11831
+ recommended: boolean()
11832
+ });
11833
+ object({
11834
+ signals: array(StreamSignalSchema),
11835
+ lastFetchedAt: number()
11836
+ });
11837
+ Object.values(DeviceType), method(_void(), array(StreamSignalSchema).readonly());
11716
11838
  /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
11717
11839
  var StreamFormatSchema = _enum([
11718
11840
  "webrtc",
@@ -12109,6 +12231,22 @@ var EgressTranscodeSchema = object({
12109
12231
  camStreamId: string().nullable()
12110
12232
  });
12111
12233
  method(object({
12234
+ deviceId: number().int().nonnegative(),
12235
+ /** The provider's signal code. */
12236
+ code: string().min(1),
12237
+ /** Ms epoch. Absent ⇒ now. */
12238
+ at: number().optional()
12239
+ }), object({
12240
+ /** Whether the broker acted on it, and if not, why. */
12241
+ accepted: boolean(),
12242
+ reason: _enum([
12243
+ "woke",
12244
+ "hold-extended",
12245
+ "not-enabled",
12246
+ "no-consumer",
12247
+ "unknown-code"
12248
+ ])
12249
+ }), { kind: "mutation" }), method(object({
12112
12250
  deviceId: number().int().nonnegative(),
12113
12251
  camStreamId: string().min(1),
12114
12252
  kind: CamStreamKindSchema,
@@ -12363,6 +12501,16 @@ var PickStreamRequirementsSchema = object({
12363
12501
  acceptCodecs: array(StreamCodecSchema).readonly().optional(),
12364
12502
  /** Minimum vertical resolution. Streams shorter than this are dropped. */
12365
12503
  minHeight: number().int().positive().optional(),
12504
+ /**
12505
+ * Maximum vertical resolution. Streams TALLER than this are dropped.
12506
+ *
12507
+ * A consumer can have a ceiling as real as its floor: Alexa documents
12508
+ * 480p to 1080p, and a 4K stream is as unusable to an Echo as a 360p one.
12509
+ * Without this the ceiling had to be re-implemented by every caller — and
12510
+ * one caller implementing it privately is how a second scoring authority
12511
+ * gets born.
12512
+ */
12513
+ maxHeight: number().int().positive().optional(),
12366
12514
  /** Minimum horizontal resolution. */
12367
12515
  minWidth: number().int().positive().optional(),
12368
12516
  /**
@@ -12379,7 +12527,22 @@ var PickStreamRequirementsSchema = object({
12379
12527
  * transcoded" guard: if the device is already serving the consumer's
12380
12528
  * codec end-to-end, there's nothing to optimise.
12381
12529
  */
12382
- requireSiblingCodec: array(StreamCodecSchema).readonly().optional()
12530
+ requireSiblingCodec: array(StreamCodecSchema).readonly().optional(),
12531
+ /**
12532
+ * Whether a stream the consumer CANNOT decode may still be picked, on the
12533
+ * understanding that it will be transcoded.
12534
+ *
12535
+ * Default `false` — today's behaviour, and the right one for a bypass
12536
+ * question ("is there a stream I can forward untouched?"). Set `true` to
12537
+ * ask the larger question: "what is the best stream for me, transcoding if
12538
+ * I must?" A stream that satisfies `acceptCodecs` always outranks one that
12539
+ * does not, so a passthrough is never lost to a transcode; the answer says
12540
+ * which it is in {@link PickedCamStreamSchema.transcodes}.
12541
+ *
12542
+ * This is what lets one picker serve both the bypass and the full source
12543
+ * choice, instead of a consumer scoring privately when the bypass misses.
12544
+ */
12545
+ allowTranscode: boolean().optional()
12383
12546
  }).readonly();
12384
12547
  var PickStreamPreferencesSchema = object({
12385
12548
  /**
@@ -12393,12 +12556,32 @@ var PickStreamPreferencesSchema = object({
12393
12556
  * picks the tallest stream; `'lowest'` picks the shortest (used by
12394
12557
  * memory-constrained consumers / Apple Home guest sessions).
12395
12558
  */
12396
- resolutionPreference: _enum(["highest", "lowest"]).optional()
12559
+ resolutionPreference: _enum(["highest", "lowest"]).optional(),
12560
+ /**
12561
+ * The height the consumer actually wants to DELIVER.
12562
+ *
12563
+ * Not a constraint — an ordering. With it set, the SMALLEST stream at or
12564
+ * above the target wins, and only if nothing reaches it does the tallest
12565
+ * take over. Pulling 1296 lines to draw 720 on a 1280x800 Echo panel costs
12566
+ * a decode and buys nothing, and `resolutionPreference: 'highest'` cannot
12567
+ * express that: it says "as big as possible", which is a different wish.
12568
+ *
12569
+ * Ignored when absent, so every existing caller keeps its ordering.
12570
+ */
12571
+ targetHeight: number().int().positive().optional()
12397
12572
  }).readonly();
12398
12573
  var PickedCamStreamSchema = object({
12399
12574
  camStreamId: string(),
12400
12575
  codec: string().optional(),
12401
12576
  resolution: CamStreamResolutionSchema.optional(),
12577
+ /**
12578
+ * Whether serving this stream requires a decode + re-encode.
12579
+ *
12580
+ * `false` is a stream the consumer can take as it stands. Only ever `true`
12581
+ * when the caller asked for it with `allowTranscode`, so a caller that did
12582
+ * not ask cannot be handed a cost it never agreed to pay.
12583
+ */
12584
+ transcodes: boolean(),
12402
12585
  /** One-line explanation of why this stream won — for logs / debug UI. */
12403
12586
  reason: string()
12404
12587
  });
@@ -16634,6 +16817,8 @@ var NcSystemEventKindSchema = _enum([
16634
16817
  "device-enabled",
16635
16818
  "device-battery-low",
16636
16819
  "device-battery-normal",
16820
+ "device-consumable-low",
16821
+ "device-consumable-normal",
16637
16822
  "stream-online",
16638
16823
  "stream-offline",
16639
16824
  "node-online",
@@ -16652,6 +16837,7 @@ var NcSystemEventKindSchema = _enum([
16652
16837
  "addon-updated",
16653
16838
  "server-updated",
16654
16839
  "export-completed",
16840
+ "backup-completed",
16655
16841
  "camera-online",
16656
16842
  "camera-offline",
16657
16843
  "camera-disabled",
@@ -23909,10 +24095,28 @@ DeviceType.Camera, method(object({ deviceId: number().int().nonnegative() }), ar
23909
24095
  }), boolean()), method(object({
23910
24096
  deviceId: number().int().nonnegative(),
23911
24097
  sessionId: string()
23912
- }), object({ pendingRenegotiation: object({
23913
- target: WebrtcStreamTargetSchema,
23914
- epoch: number()
23915
- }).nullable() }));
24098
+ }), object({
24099
+ pendingRenegotiation: object({
24100
+ target: WebrtcStreamTargetSchema,
24101
+ epoch: number()
24102
+ }).nullable(),
24103
+ /**
24104
+ * Whether the session still EXISTS.
24105
+ *
24106
+ * A consumer that holds a resource for the life of a session needs to
24107
+ * be able to ask, because a session does not always end the way it
24108
+ * began. Measured on this hub 2026-09-13: an Echo that got stuck never
24109
+ * sent `SessionDisconnected`, so the Alexa exporter's
24110
+ * `releaseEgressTranscode` never ran, and a 2304x1296 HEVC to 720p
24111
+ * H.264 transcode kept running for NOBODY for more than twenty
24112
+ * minutes. The WebRTC session had logged `WebRTC session closed`
24113
+ * minutes earlier — the broker knew; the holder had no way to ask.
24114
+ *
24115
+ * `false` for a session id the provider has never heard of, which is
24116
+ * the same answer as "it ended": either way nothing is holding it up.
24117
+ */
24118
+ alive: boolean()
24119
+ }));
23916
24120
  object({
23917
24121
  /** All accessory children of the parent. */
23918
24122
  childDeviceIds: array(number()).readonly(),
@@ -36416,6 +36620,12 @@ Object.freeze({
36416
36620
  addonId: null,
36417
36621
  access: "create"
36418
36622
  },
36623
+ "streamBroker.reportStreamSignal": {
36624
+ capName: "stream-broker",
36625
+ capScope: "system",
36626
+ addonId: null,
36627
+ access: "create"
36628
+ },
36419
36629
  "streamBroker.restartProfile": {
36420
36630
  capName: "stream-broker",
36421
36631
  capScope: "system",
@@ -36500,6 +36710,12 @@ Object.freeze({
36500
36710
  addonId: null,
36501
36711
  access: "create"
36502
36712
  },
36713
+ "streamSignals.listSignals": {
36714
+ capName: "stream-signals",
36715
+ capScope: "device",
36716
+ addonId: null,
36717
+ access: "view"
36718
+ },
36503
36719
  "switch.setState": {
36504
36720
  capName: "switch",
36505
36721
  capScope: "device",
@@ -38872,6 +39088,11 @@ Object.freeze({
38872
39088
  form: "single",
38873
39089
  optional: false
38874
39090
  }],
39091
+ "streamBroker.reportStreamSignal": [{
39092
+ name: "deviceId",
39093
+ form: "single",
39094
+ optional: false
39095
+ }],
38875
39096
  "streamBroker.restartProfile": [{
38876
39097
  name: "deviceId",
38877
39098
  form: "single",
@@ -39702,7 +39923,7 @@ async function acquireAlexaEgress(input) {
39702
39923
  profile: sourceProfile
39703
39924
  },
39704
39925
  encode: ALEXA_EGRESS_PROFILE,
39705
- rateControl: "relaxed",
39926
+ rateControl: "tight",
39706
39927
  publishLocally: true,
39707
39928
  tag: `alexa/${sessionId}`
39708
39929
  });
@@ -39726,6 +39947,7 @@ async function acquireAlexaEgress(input) {
39726
39947
  meta: {
39727
39948
  pipelineKey: transcode.pipelineKey,
39728
39949
  camStreamId,
39950
+ sourceProfile: input.sourceProfile,
39729
39951
  encoder: transcode.encoder,
39730
39952
  decodeHwAccel: transcode.decodeHwAccel ?? "software"
39731
39953
  }
@@ -39759,6 +39981,512 @@ async function releaseAlexaEgress(input) {
39759
39981
  }
39760
39982
  }
39761
39983
  //#endregion
39984
+ //#region src/egress/egress-handle-reaper.ts
39985
+ /**
39986
+ * Which handles should be released now.
39987
+ *
39988
+ * A session the broker says is GONE is reclaimed. A session it could not be
39989
+ * asked about is KEPT — a read that failed is not evidence of death, and
39990
+ * releasing a live session's transcode would black out a working stream to
39991
+ * save a process (D393, read in the direction that destroys work).
39992
+ */
39993
+ async function reapDeadEgressHandles(input) {
39994
+ const dead = [];
39995
+ for (const handle of input.held) if (await input.isAlive(handle) === false) dead.push(handle);
39996
+ return dead;
39997
+ }
39998
+ /** How often the sweep runs. Well under the minute Amazon requires a session
39999
+ * to survive, so a genuinely dead one is not transcoding for long. */
40000
+ var EGRESS_REAP_INTERVAL_MS = 3e4;
40001
+ function logReaped(logger, handle) {
40002
+ logger?.warn("alexa egress: session is GONE — reclaiming the transcode it still held", {
40003
+ tags: { deviceId: handle.deviceId },
40004
+ meta: {
40005
+ sessionId: handle.sessionId,
40006
+ pipelineKey: handle.pipelineKey,
40007
+ reason: "no SessionDisconnected directive"
40008
+ }
40009
+ });
40010
+ }
40011
+ //#endregion
40012
+ //#region src/egress/alexa-source-pick.ts
40013
+ /** Amazon's documented ceiling. */
40014
+ var ALEXA_MAX_LINES = 1080;
40015
+ /**
40016
+ * Which profile slot serves `camStreamId`, or `null` when none does — a read
40017
+ * that failed is `null` too, and the caller keeps its previous behaviour
40018
+ * rather than guessing a slot from an error (D393).
40019
+ */
40020
+ async function profileForCamStream(input) {
40021
+ try {
40022
+ const slots = await input.api.streamBroker.listAllProfileSlots.query();
40023
+ for (const slot of slots) {
40024
+ if (slot.deviceId !== input.deviceId) continue;
40025
+ if (slot.sourceCamStreamId !== input.camStreamId) continue;
40026
+ if (slot.profile === "high" || slot.profile === "mid" || slot.profile === "low") return slot.profile;
40027
+ }
40028
+ return null;
40029
+ } catch (err) {
40030
+ input.logger?.warn("alexa rtc-session: could not read the profile slots", {
40031
+ tags: { deviceId: input.deviceId },
40032
+ meta: { error: errMsg(err) }
40033
+ });
40034
+ return null;
40035
+ }
40036
+ }
40037
+ //#endregion
40038
+ //#region src/handlers/endpoint-id.ts
40039
+ var SEPARATOR = "__";
40040
+ function parseCameraEndpointId(raw) {
40041
+ if (!raw.includes(SEPARATOR)) {
40042
+ const id = parseNonNegativeInt(raw);
40043
+ if (id === null) return {
40044
+ kind: "invalid",
40045
+ reason: `not a numeric deviceId: ${raw}`
40046
+ };
40047
+ return {
40048
+ kind: "camera",
40049
+ deviceId: id
40050
+ };
40051
+ }
40052
+ const [head, tail, ...rest] = raw.split(SEPARATOR);
40053
+ if (head === void 0 || tail === void 0 || rest.length > 0) return {
40054
+ kind: "invalid",
40055
+ reason: `unexpected segments in endpointId: ${raw}`
40056
+ };
40057
+ const parent = parseNonNegativeInt(head);
40058
+ if (parent === null) return {
40059
+ kind: "invalid",
40060
+ reason: `parent segment not numeric: ${raw}`
40061
+ };
40062
+ if (tail === "autotrack") return {
40063
+ kind: "autotrack",
40064
+ parentDeviceId: parent
40065
+ };
40066
+ if (tail === "privacy") return {
40067
+ kind: "privacy",
40068
+ parentDeviceId: parent
40069
+ };
40070
+ if (tail === "alarm") return {
40071
+ kind: "alarm-panel",
40072
+ deviceId: parent
40073
+ };
40074
+ const child = parseNonNegativeInt(tail);
40075
+ if (child === null) return {
40076
+ kind: "invalid",
40077
+ reason: `child segment not numeric and not 'autotrack'/'privacy'/'alarm': ${raw}`
40078
+ };
40079
+ return {
40080
+ kind: "child",
40081
+ parentDeviceId: parent,
40082
+ childDeviceId: child
40083
+ };
40084
+ }
40085
+ function parseNonNegativeInt(s) {
40086
+ if (!/^\d+$/.test(s)) return null;
40087
+ const n = Number.parseInt(s, 10);
40088
+ if (!Number.isFinite(n) || n < 0) return null;
40089
+ return n;
40090
+ }
40091
+ //#endregion
40092
+ //#region src/handlers/error-envelope.ts
40093
+ /**
40094
+ * Shared Alexa `Alexa/ErrorResponse` envelope builder.
40095
+ *
40096
+ * Lives in its own module so every handler (and the directive router)
40097
+ * can emit its own namespace-appropriate error without circular imports.
40098
+ */
40099
+ object({ event: object({
40100
+ header: object({
40101
+ namespace: literal("Alexa"),
40102
+ name: literal("ErrorResponse"),
40103
+ messageId: string(),
40104
+ payloadVersion: literal("3")
40105
+ }),
40106
+ payload: object({
40107
+ type: string(),
40108
+ message: string()
40109
+ })
40110
+ }) });
40111
+ function errorEnvelope(header, type, message) {
40112
+ return { event: {
40113
+ header: {
40114
+ namespace: "Alexa",
40115
+ name: "ErrorResponse",
40116
+ messageId: header.messageId,
40117
+ payloadVersion: "3"
40118
+ },
40119
+ payload: {
40120
+ type,
40121
+ message
40122
+ }
40123
+ } };
40124
+ }
40125
+ //#endregion
40126
+ //#region src/handlers/types.ts
40127
+ /**
40128
+ * Zod schemas for the subset of the Alexa Smart Home directive surface
40129
+ * that we actually parse hub-side. The Smart Home Skill API ships
40130
+ * thousands of optional fields per namespace — we only validate what
40131
+ * we read; everything else passes through as `unknown`.
40132
+ *
40133
+ * Reference: https://developer.amazon.com/en-US/docs/alexa/smarthome/smart-home-skill-api-message-reference.html
40134
+ */
40135
+ /** A directive header carries namespace + name + token + correlation id. */
40136
+ var DirectiveHeaderSchema = object({
40137
+ namespace: string(),
40138
+ name: string(),
40139
+ payloadVersion: string(),
40140
+ messageId: string(),
40141
+ correlationToken: string().optional()
40142
+ });
40143
+ /** Scope carries the bearer token Alexa minted via our OAuth provider. */
40144
+ var BearerScopeSchema = object({
40145
+ type: literal("BearerToken"),
40146
+ token: string()
40147
+ });
40148
+ /** Endpoint reference inside a directive payload. */
40149
+ var EndpointRefSchema = object({
40150
+ endpointId: string(),
40151
+ scope: BearerScopeSchema.optional(),
40152
+ cookie: record(string(), string()).optional()
40153
+ });
40154
+ var DiscoveryDirectiveSchema = object({
40155
+ header: DirectiveHeaderSchema.extend({
40156
+ namespace: literal("Alexa.Discovery"),
40157
+ name: literal("Discover")
40158
+ }),
40159
+ payload: object({ scope: BearerScopeSchema })
40160
+ });
40161
+ /** Envelope wrapping a directive on the Alexa→skill wire. */
40162
+ var DirectiveRequestSchema = object({ directive: object({
40163
+ header: DirectiveHeaderSchema,
40164
+ endpoint: EndpointRefSchema.optional(),
40165
+ payload: unknown().optional()
40166
+ }) });
40167
+ var InitializeCameraStreamsPayloadSchema = object({ cameraStreams: array(object({
40168
+ protocol: string(),
40169
+ resolution: object({
40170
+ width: number(),
40171
+ height: number()
40172
+ }).optional(),
40173
+ authorizationType: string().optional(),
40174
+ videoCodec: string().optional(),
40175
+ audioCodec: string().optional()
40176
+ })).optional() });
40177
+ var InitiateSessionWithOfferPayloadSchema = object({
40178
+ sessionId: string(),
40179
+ offer: object({
40180
+ format: string().optional(),
40181
+ value: string()
40182
+ })
40183
+ });
40184
+ var SessionDisconnectedPayloadSchema = object({ sessionId: string() });
40185
+ var SetModePayloadSchema = object({ mode: string() });
40186
+ //#endregion
40187
+ //#region src/handlers/rtc-session.ts
40188
+ var InitiateSessionWithOfferDirectiveSchema = object({
40189
+ endpoint: EndpointRefSchema,
40190
+ payload: InitiateSessionWithOfferPayloadSchema
40191
+ });
40192
+ var SessionDisconnectedDirectiveSchema = object({
40193
+ endpoint: EndpointRefSchema,
40194
+ payload: SessionDisconnectedPayloadSchema
40195
+ });
40196
+ /**
40197
+ * Live egress handles, keyed by `<deviceId>/<sessionId>`.
40198
+ *
40199
+ * The primitive's refcount has no lease TTL: a holder that vanishes without
40200
+ * releasing leaks a child until the broker restarts (D67). This handler is a
40201
+ * holder, so it keeps the one piece of state that lets it not be that holder —
40202
+ * the `pipelineKey` its `SessionDisconnected` has to release.
40203
+ *
40204
+ * A module-level map is right here because the directive handlers are free
40205
+ * functions called per directive; the entry is written on a successful acquire
40206
+ * and deleted on the release path, both of which are the same tick as the
40207
+ * directive that owns it.
40208
+ */
40209
+ var EGRESS_HANDLES = /* @__PURE__ */ new Map();
40210
+ function egressHandleKey(deviceId, sessionId) {
40211
+ return `${deviceId}/${sessionId}`;
40212
+ }
40213
+ /** Every handle currently held, for the sweep. */
40214
+ function heldEgressHandles() {
40215
+ const held = [];
40216
+ for (const [key, pipelineKey] of EGRESS_HANDLES) {
40217
+ const slash = key.indexOf("/");
40218
+ if (slash <= 0) continue;
40219
+ const deviceId = Number.parseInt(key.slice(0, slash), 10);
40220
+ if (!Number.isFinite(deviceId)) continue;
40221
+ held.push({
40222
+ deviceId,
40223
+ sessionId: key.slice(slash + 1),
40224
+ pipelineKey
40225
+ });
40226
+ }
40227
+ return held;
40228
+ }
40229
+ /** Drop a handle the sweep reclaimed, so it is not reaped twice. */
40230
+ function forgetEgressHandle(handle) {
40231
+ EGRESS_HANDLES.delete(egressHandleKey(handle.deviceId, handle.sessionId));
40232
+ }
40233
+ var WEBRTC_PROFILE_NAMES = [
40234
+ "high",
40235
+ "mid",
40236
+ "low"
40237
+ ];
40238
+ function resolveWebrtcTarget(pref) {
40239
+ if (pref === "auto") return void 0;
40240
+ if (WEBRTC_PROFILE_NAMES.includes(pref)) return {
40241
+ kind: "profile",
40242
+ profile: pref
40243
+ };
40244
+ return {
40245
+ kind: "cam-stream",
40246
+ camStreamId: pref
40247
+ };
40248
+ }
40249
+ async function handleInitiateSessionWithOffer(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
40250
+ const parsed = InitiateSessionWithOfferDirectiveSchema.safeParse({
40251
+ endpoint: endpointRaw,
40252
+ payload: payloadRaw ?? {}
40253
+ });
40254
+ if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
40255
+ const endpoint = parsed.data.endpoint;
40256
+ const payload = parsed.data.payload;
40257
+ const parsedId = parseCameraEndpointId(endpoint.endpointId);
40258
+ if (parsedId.kind !== "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", `endpointId ${endpoint.endpointId} is not a camera`);
40259
+ const deviceId = parsedId.deviceId;
40260
+ const sessionId = payload.sessionId;
40261
+ const log = deps.logger.withTags({
40262
+ deviceId,
40263
+ sessionId
40264
+ });
40265
+ const sdpOffer = payload.offer.value;
40266
+ if (sdpOffer.length === 0) return errorEnvelope(header, "INVALID_DIRECTIVE", "offer.value is empty");
40267
+ const api = deps.ctx.api;
40268
+ const exposedEntry = deps.listExposed().find((e) => e.deviceId === deviceId);
40269
+ const pinnedProfile = (() => {
40270
+ const pref = exposedEntry?.settings?.streamPreference;
40271
+ if (pref === "low" || pref === "mid" || pref === "high") return pref;
40272
+ })();
40273
+ const allowTranscode = exposedEntry?.settings?.allowTranscode !== false;
40274
+ const scored = pinnedProfile === void 0 ? await api.cameraStreams.pickStream.query({
40275
+ deviceId,
40276
+ requirements: {
40277
+ acceptCodecs: ["h264"],
40278
+ minHeight: 480,
40279
+ maxHeight: ALEXA_MAX_LINES,
40280
+ excludeDerived: true,
40281
+ allowTranscode
40282
+ },
40283
+ preferences: { targetHeight: 720 }
40284
+ }).catch((err) => {
40285
+ log.warn("alexa rtc-session: pickStream threw — falling back to the high slot", {
40286
+ tags: { deviceId },
40287
+ meta: { error: err instanceof Error ? err.message : String(err) }
40288
+ });
40289
+ return null;
40290
+ }) : null;
40291
+ const scoredProfile = scored === null ? null : await profileForCamStream({
40292
+ api,
40293
+ deviceId,
40294
+ camStreamId: scored.camStreamId,
40295
+ logger: log
40296
+ });
40297
+ const sourceProfile = pinnedProfile ?? scoredProfile ?? "high";
40298
+ if (pinnedProfile === void 0) log.info("alexa rtc-session: source scored against the Echo requirements", {
40299
+ tags: { deviceId },
40300
+ meta: {
40301
+ chosen: sourceProfile,
40302
+ scored: scored === null ? "none-eligible" : scored.reason,
40303
+ camStreamId: scored?.camStreamId ?? null,
40304
+ slot: scoredProfile ?? (scored === null ? null : "no-slot"),
40305
+ height: scored?.resolution?.height ?? null,
40306
+ transcodes: scored?.transcodes ?? null,
40307
+ allowTranscode
40308
+ }
40309
+ });
40310
+ let derivedTarget;
40311
+ /**
40312
+ * The primitive's release handle, when this session acquired one. Recorded so
40313
+ * `SessionDisconnected` can release it: a refcount whose holder disappears is
40314
+ * the one gap D67 leaves open, and the least this handler can do is not BE
40315
+ * that holder.
40316
+ */
40317
+ let egressPipelineKey = null;
40318
+ const picked = await api.cameraStreams.pickStream.query({
40319
+ deviceId,
40320
+ requirements: {
40321
+ acceptCodecs: ["h264"],
40322
+ minHeight: 480,
40323
+ excludeDerived: true,
40324
+ requireSiblingCodec: ["h265", "hevc"]
40325
+ }
40326
+ }).catch((err) => {
40327
+ log.warn("alexa rtc-session: cameraStreams.pickStream threw — falling back to transcode", { meta: { error: err instanceof Error ? err.message : String(err) } });
40328
+ return null;
40329
+ });
40330
+ if (picked) {
40331
+ log.info("alexa rtc-session: bypassing transcode via cameraStreams.pickStream", { meta: {
40332
+ sourceProfile,
40333
+ selectedCamStreamId: picked.camStreamId,
40334
+ reason: picked.reason
40335
+ } });
40336
+ derivedTarget = {
40337
+ kind: "cam-stream",
40338
+ camStreamId: picked.camStreamId
40339
+ };
40340
+ } else try {
40341
+ const acquired = await acquireAlexaEgress({
40342
+ api,
40343
+ deviceId,
40344
+ sourceProfile,
40345
+ sessionId,
40346
+ logger: log
40347
+ });
40348
+ egressPipelineKey = acquired.pipelineKey;
40349
+ EGRESS_HANDLES.set(egressHandleKey(deviceId, sessionId), acquired.pipelineKey);
40350
+ derivedTarget = {
40351
+ kind: "cam-stream",
40352
+ camStreamId: acquired.camStreamId
40353
+ };
40354
+ } catch (err) {
40355
+ log.warn("alexa rtc-session: egress acquire failed, falling back to streamPreference target", { meta: { error: err instanceof Error ? err.message : String(err) } });
40356
+ derivedTarget = resolveWebrtcTarget(exposedEntry?.settings?.streamPreference ?? "auto");
40357
+ }
40358
+ try {
40359
+ const result = await api.webrtcSession.handleOffer.mutate({
40360
+ deviceId,
40361
+ sdpOffer,
40362
+ sessionId,
40363
+ target: derivedTarget,
40364
+ relayOnly: false,
40365
+ nonTrickle: true,
40366
+ disableTurn: true,
40367
+ disableIpv6: true,
40368
+ consumerAttribution: {
40369
+ kind: "alexa",
40370
+ sessionId
40371
+ }
40372
+ });
40373
+ log.info("alexa rtc-session: AnswerGenerated", { meta: {
40374
+ returnedSessionId: result.sessionId,
40375
+ sdpAnswerLen: result.sdpAnswer.length
40376
+ } });
40377
+ return { event: {
40378
+ header: {
40379
+ namespace: "Alexa.RTCSessionController",
40380
+ name: "AnswerGeneratedForSession",
40381
+ messageId: header.messageId,
40382
+ correlationToken: header.correlationToken,
40383
+ payloadVersion: "3"
40384
+ },
40385
+ endpoint: { endpointId: endpoint.endpointId },
40386
+ payload: { answer: {
40387
+ format: payload.offer.format ?? "SDP",
40388
+ value: result.sdpAnswer
40389
+ } }
40390
+ } };
40391
+ } catch (err) {
40392
+ const message = err instanceof Error ? err.message : String(err);
40393
+ const mSectionSummary = (() => {
40394
+ const lines = sdpOffer.split(/\r?\n/);
40395
+ const sections = [];
40396
+ let current = null;
40397
+ for (const raw of lines) {
40398
+ const line = raw.trim();
40399
+ if (line.startsWith("m=")) {
40400
+ if (current) sections.push(current);
40401
+ current = {
40402
+ mid: null,
40403
+ kind: line.split(" ")[0]?.slice(2) ?? "unknown",
40404
+ direction: null,
40405
+ codecs: []
40406
+ };
40407
+ } else if (current) {
40408
+ if (line.startsWith("a=mid:")) current.mid = line.slice(6);
40409
+ else if (/^a=(sendonly|recvonly|sendrecv|inactive)$/.test(line)) current.direction = line.slice(2);
40410
+ else if (line.startsWith("a=rtpmap:")) current.codecs.push(line.slice(9));
40411
+ }
40412
+ }
40413
+ if (current) sections.push(current);
40414
+ return sections;
40415
+ })();
40416
+ log.warn("alexa rtc-session: handleOffer failed", { meta: {
40417
+ error: message,
40418
+ offerLen: sdpOffer.length,
40419
+ mSections: mSectionSummary,
40420
+ offerSdp: sdpOffer
40421
+ } });
40422
+ if (egressPipelineKey !== null) {
40423
+ EGRESS_HANDLES.delete(egressHandleKey(deviceId, sessionId));
40424
+ await releaseAlexaEgress({
40425
+ api,
40426
+ deviceId,
40427
+ pipelineKey: egressPipelineKey,
40428
+ logger: log
40429
+ });
40430
+ }
40431
+ return errorEnvelope(header, "INTERNAL_ERROR", `webrtc-session.handleOffer failed: ${message}`);
40432
+ }
40433
+ }
40434
+ async function handleSessionDisconnected(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
40435
+ const parsed = SessionDisconnectedDirectiveSchema.safeParse({
40436
+ endpoint: endpointRaw,
40437
+ payload: payloadRaw ?? {}
40438
+ });
40439
+ if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
40440
+ const endpoint = parsed.data.endpoint;
40441
+ const parsedId = parseCameraEndpointId(endpoint.endpointId);
40442
+ if (parsedId.kind === "camera") {
40443
+ const handleKey = egressHandleKey(parsedId.deviceId, parsed.data.payload.sessionId);
40444
+ const pipelineKey = EGRESS_HANDLES.get(handleKey);
40445
+ if (pipelineKey !== void 0) {
40446
+ EGRESS_HANDLES.delete(handleKey);
40447
+ await releaseAlexaEgress({
40448
+ api: deps.ctx.api,
40449
+ deviceId: parsedId.deviceId,
40450
+ pipelineKey,
40451
+ logger: deps.logger
40452
+ });
40453
+ }
40454
+ try {
40455
+ await deps.ctx.api.webrtcSession.closeSession.mutate({
40456
+ deviceId: parsedId.deviceId,
40457
+ sessionId: parsed.data.payload.sessionId
40458
+ });
40459
+ } catch (err) {
40460
+ deps.logger.warn("alexa rtc-session: closeSession threw on disconnect (continuing to ack)", {
40461
+ tags: {
40462
+ deviceId: parsedId.deviceId,
40463
+ sessionId: parsed.data.payload.sessionId
40464
+ },
40465
+ meta: { error: err instanceof Error ? err.message : String(err) }
40466
+ });
40467
+ }
40468
+ }
40469
+ const disconnectedDeviceId = parsedId.kind === "camera" ? parsedId.deviceId : void 0;
40470
+ deps.logger.info("alexa rtc-session: SessionDisconnected", {
40471
+ tags: {
40472
+ sessionId: parsed.data.payload.sessionId,
40473
+ ...disconnectedDeviceId !== void 0 ? { deviceId: disconnectedDeviceId } : {}
40474
+ },
40475
+ meta: { endpointId: endpoint.endpointId }
40476
+ });
40477
+ return { event: {
40478
+ header: {
40479
+ namespace: "Alexa",
40480
+ name: "Response",
40481
+ messageId: header.messageId,
40482
+ correlationToken: header.correlationToken,
40483
+ payloadVersion: "3"
40484
+ },
40485
+ endpoint: { endpointId: endpoint.endpointId },
40486
+ payload: {}
40487
+ } };
40488
+ }
40489
+ //#endregion
39762
40490
  //#region src/handlers/security-panel-arm-state.ts
39763
40491
  /**
39764
40492
  * The panel modes behind each Alexa arm state, PRIMARY first — the mirror of
@@ -40189,101 +40917,6 @@ function buildAlarmPanelEndpoint(input) {
40189
40917
  };
40190
40918
  }
40191
40919
  //#endregion
40192
- //#region src/handlers/error-envelope.ts
40193
- /**
40194
- * Shared Alexa `Alexa/ErrorResponse` envelope builder.
40195
- *
40196
- * Lives in its own module so every handler (and the directive router)
40197
- * can emit its own namespace-appropriate error without circular imports.
40198
- */
40199
- object({ event: object({
40200
- header: object({
40201
- namespace: literal("Alexa"),
40202
- name: literal("ErrorResponse"),
40203
- messageId: string(),
40204
- payloadVersion: literal("3")
40205
- }),
40206
- payload: object({
40207
- type: string(),
40208
- message: string()
40209
- })
40210
- }) });
40211
- function errorEnvelope(header, type, message) {
40212
- return { event: {
40213
- header: {
40214
- namespace: "Alexa",
40215
- name: "ErrorResponse",
40216
- messageId: header.messageId,
40217
- payloadVersion: "3"
40218
- },
40219
- payload: {
40220
- type,
40221
- message
40222
- }
40223
- } };
40224
- }
40225
- //#endregion
40226
- //#region src/handlers/types.ts
40227
- /**
40228
- * Zod schemas for the subset of the Alexa Smart Home directive surface
40229
- * that we actually parse hub-side. The Smart Home Skill API ships
40230
- * thousands of optional fields per namespace — we only validate what
40231
- * we read; everything else passes through as `unknown`.
40232
- *
40233
- * Reference: https://developer.amazon.com/en-US/docs/alexa/smarthome/smart-home-skill-api-message-reference.html
40234
- */
40235
- /** A directive header carries namespace + name + token + correlation id. */
40236
- var DirectiveHeaderSchema = object({
40237
- namespace: string(),
40238
- name: string(),
40239
- payloadVersion: string(),
40240
- messageId: string(),
40241
- correlationToken: string().optional()
40242
- });
40243
- /** Scope carries the bearer token Alexa minted via our OAuth provider. */
40244
- var BearerScopeSchema = object({
40245
- type: literal("BearerToken"),
40246
- token: string()
40247
- });
40248
- /** Endpoint reference inside a directive payload. */
40249
- var EndpointRefSchema = object({
40250
- endpointId: string(),
40251
- scope: BearerScopeSchema.optional(),
40252
- cookie: record(string(), string()).optional()
40253
- });
40254
- var DiscoveryDirectiveSchema = object({
40255
- header: DirectiveHeaderSchema.extend({
40256
- namespace: literal("Alexa.Discovery"),
40257
- name: literal("Discover")
40258
- }),
40259
- payload: object({ scope: BearerScopeSchema })
40260
- });
40261
- /** Envelope wrapping a directive on the Alexa→skill wire. */
40262
- var DirectiveRequestSchema = object({ directive: object({
40263
- header: DirectiveHeaderSchema,
40264
- endpoint: EndpointRefSchema.optional(),
40265
- payload: unknown().optional()
40266
- }) });
40267
- var InitializeCameraStreamsPayloadSchema = object({ cameraStreams: array(object({
40268
- protocol: string(),
40269
- resolution: object({
40270
- width: number(),
40271
- height: number()
40272
- }).optional(),
40273
- authorizationType: string().optional(),
40274
- videoCodec: string().optional(),
40275
- audioCodec: string().optional()
40276
- })).optional() });
40277
- var InitiateSessionWithOfferPayloadSchema = object({
40278
- sessionId: string(),
40279
- offer: object({
40280
- format: string().optional(),
40281
- value: string()
40282
- })
40283
- });
40284
- var SessionDisconnectedPayloadSchema = object({ sessionId: string() });
40285
- var SetModePayloadSchema = object({ mode: string() });
40286
- //#endregion
40287
40920
  //#region src/handlers/discovery.ts
40288
40921
  var discoveryPayloadSchema = DiscoveryDirectiveSchema.shape.payload;
40289
40922
  /** Devices built at once in `handleDiscovery` — latency-bound tRPC reads, so
@@ -40492,60 +41125,6 @@ function discoveryResponse(header, endpoints) {
40492
41125
  } };
40493
41126
  }
40494
41127
  //#endregion
40495
- //#region src/handlers/endpoint-id.ts
40496
- var SEPARATOR = "__";
40497
- function parseCameraEndpointId(raw) {
40498
- if (!raw.includes(SEPARATOR)) {
40499
- const id = parseNonNegativeInt(raw);
40500
- if (id === null) return {
40501
- kind: "invalid",
40502
- reason: `not a numeric deviceId: ${raw}`
40503
- };
40504
- return {
40505
- kind: "camera",
40506
- deviceId: id
40507
- };
40508
- }
40509
- const [head, tail, ...rest] = raw.split(SEPARATOR);
40510
- if (head === void 0 || tail === void 0 || rest.length > 0) return {
40511
- kind: "invalid",
40512
- reason: `unexpected segments in endpointId: ${raw}`
40513
- };
40514
- const parent = parseNonNegativeInt(head);
40515
- if (parent === null) return {
40516
- kind: "invalid",
40517
- reason: `parent segment not numeric: ${raw}`
40518
- };
40519
- if (tail === "autotrack") return {
40520
- kind: "autotrack",
40521
- parentDeviceId: parent
40522
- };
40523
- if (tail === "privacy") return {
40524
- kind: "privacy",
40525
- parentDeviceId: parent
40526
- };
40527
- if (tail === "alarm") return {
40528
- kind: "alarm-panel",
40529
- deviceId: parent
40530
- };
40531
- const child = parseNonNegativeInt(tail);
40532
- if (child === null) return {
40533
- kind: "invalid",
40534
- reason: `child segment not numeric and not 'autotrack'/'privacy'/'alarm': ${raw}`
40535
- };
40536
- return {
40537
- kind: "child",
40538
- parentDeviceId: parent,
40539
- childDeviceId: child
40540
- };
40541
- }
40542
- function parseNonNegativeInt(s) {
40543
- if (!/^\d+$/.test(s)) return null;
40544
- const n = Number.parseInt(s, 10);
40545
- if (!Number.isFinite(n) || n < 0) return null;
40546
- return n;
40547
- }
40548
- //#endregion
40549
41128
  //#region src/handlers/brightness-controller.ts
40550
41129
  var SetBrightnessDirectiveSchema = object({
40551
41130
  header: object({
@@ -41122,254 +41701,6 @@ async function collectChildProperties(api, childDeviceId, properties, timeOfSamp
41122
41701
  });
41123
41702
  }
41124
41703
  //#endregion
41125
- //#region src/handlers/rtc-session.ts
41126
- var InitiateSessionWithOfferDirectiveSchema = object({
41127
- endpoint: EndpointRefSchema,
41128
- payload: InitiateSessionWithOfferPayloadSchema
41129
- });
41130
- var SessionDisconnectedDirectiveSchema = object({
41131
- endpoint: EndpointRefSchema,
41132
- payload: SessionDisconnectedPayloadSchema
41133
- });
41134
- /**
41135
- * Live egress handles, keyed by `<deviceId>/<sessionId>`.
41136
- *
41137
- * The primitive's refcount has no lease TTL: a holder that vanishes without
41138
- * releasing leaks a child until the broker restarts (D67). This handler is a
41139
- * holder, so it keeps the one piece of state that lets it not be that holder —
41140
- * the `pipelineKey` its `SessionDisconnected` has to release.
41141
- *
41142
- * A module-level map is right here because the directive handlers are free
41143
- * functions called per directive; the entry is written on a successful acquire
41144
- * and deleted on the release path, both of which are the same tick as the
41145
- * directive that owns it.
41146
- */
41147
- var EGRESS_HANDLES = /* @__PURE__ */ new Map();
41148
- function egressHandleKey(deviceId, sessionId) {
41149
- return `${deviceId}/${sessionId}`;
41150
- }
41151
- var WEBRTC_PROFILE_NAMES = [
41152
- "high",
41153
- "mid",
41154
- "low"
41155
- ];
41156
- function resolveWebrtcTarget(pref) {
41157
- if (pref === "auto") return void 0;
41158
- if (WEBRTC_PROFILE_NAMES.includes(pref)) return {
41159
- kind: "profile",
41160
- profile: pref
41161
- };
41162
- return {
41163
- kind: "cam-stream",
41164
- camStreamId: pref
41165
- };
41166
- }
41167
- async function handleInitiateSessionWithOffer(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41168
- const parsed = InitiateSessionWithOfferDirectiveSchema.safeParse({
41169
- endpoint: endpointRaw,
41170
- payload: payloadRaw ?? {}
41171
- });
41172
- if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
41173
- const endpoint = parsed.data.endpoint;
41174
- const payload = parsed.data.payload;
41175
- const parsedId = parseCameraEndpointId(endpoint.endpointId);
41176
- if (parsedId.kind !== "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", `endpointId ${endpoint.endpointId} is not a camera`);
41177
- const deviceId = parsedId.deviceId;
41178
- const sessionId = payload.sessionId;
41179
- const log = deps.logger.withTags({
41180
- deviceId,
41181
- sessionId
41182
- });
41183
- const sdpOffer = payload.offer.value;
41184
- if (sdpOffer.length === 0) return errorEnvelope(header, "INVALID_DIRECTIVE", "offer.value is empty");
41185
- const api = deps.ctx.api;
41186
- const exposedEntry = deps.listExposed().find((e) => e.deviceId === deviceId);
41187
- const explicitSourceProfile = exposedEntry?.settings?.sourceProfile;
41188
- const mappedFromPreference = (() => {
41189
- const pref = exposedEntry?.settings?.streamPreference;
41190
- if (pref === "low" || pref === "mid" || pref === "high") return pref;
41191
- })();
41192
- const sourceProfile = explicitSourceProfile ?? mappedFromPreference ?? "high";
41193
- let derivedTarget;
41194
- /**
41195
- * The primitive's release handle, when this session acquired one. Recorded so
41196
- * `SessionDisconnected` can release it: a refcount whose holder disappears is
41197
- * the one gap D67 leaves open, and the least this handler can do is not BE
41198
- * that holder.
41199
- */
41200
- let egressPipelineKey = null;
41201
- const picked = await api.cameraStreams.pickStream.query({
41202
- deviceId,
41203
- requirements: {
41204
- acceptCodecs: ["h264"],
41205
- minHeight: 480,
41206
- excludeDerived: true,
41207
- requireSiblingCodec: ["h265", "hevc"]
41208
- }
41209
- }).catch((err) => {
41210
- log.warn("alexa rtc-session: cameraStreams.pickStream threw — falling back to transcode", { meta: { error: err instanceof Error ? err.message : String(err) } });
41211
- return null;
41212
- });
41213
- if (picked) {
41214
- log.info("alexa rtc-session: bypassing transcode via cameraStreams.pickStream", { meta: {
41215
- sourceProfile,
41216
- selectedCamStreamId: picked.camStreamId,
41217
- reason: picked.reason
41218
- } });
41219
- derivedTarget = {
41220
- kind: "cam-stream",
41221
- camStreamId: picked.camStreamId
41222
- };
41223
- } else try {
41224
- const acquired = await acquireAlexaEgress({
41225
- api,
41226
- deviceId,
41227
- sourceProfile,
41228
- sessionId,
41229
- logger: log
41230
- });
41231
- egressPipelineKey = acquired.pipelineKey;
41232
- EGRESS_HANDLES.set(egressHandleKey(deviceId, sessionId), acquired.pipelineKey);
41233
- derivedTarget = {
41234
- kind: "cam-stream",
41235
- camStreamId: acquired.camStreamId
41236
- };
41237
- } catch (err) {
41238
- log.warn("alexa rtc-session: egress acquire failed, falling back to streamPreference target", { meta: { error: err instanceof Error ? err.message : String(err) } });
41239
- derivedTarget = resolveWebrtcTarget(exposedEntry?.settings?.streamPreference ?? "auto");
41240
- }
41241
- try {
41242
- const result = await api.webrtcSession.handleOffer.mutate({
41243
- deviceId,
41244
- sdpOffer,
41245
- sessionId,
41246
- target: derivedTarget,
41247
- relayOnly: false,
41248
- nonTrickle: true,
41249
- disableTurn: true,
41250
- disableIpv6: true,
41251
- consumerAttribution: {
41252
- kind: "alexa",
41253
- sessionId
41254
- }
41255
- });
41256
- log.info("alexa rtc-session: AnswerGenerated", { meta: {
41257
- returnedSessionId: result.sessionId,
41258
- sdpAnswerLen: result.sdpAnswer.length
41259
- } });
41260
- return { event: {
41261
- header: {
41262
- namespace: "Alexa.RTCSessionController",
41263
- name: "AnswerGeneratedForSession",
41264
- messageId: header.messageId,
41265
- correlationToken: header.correlationToken,
41266
- payloadVersion: "3"
41267
- },
41268
- endpoint: { endpointId: endpoint.endpointId },
41269
- payload: { answer: {
41270
- format: payload.offer.format ?? "SDP",
41271
- value: result.sdpAnswer
41272
- } }
41273
- } };
41274
- } catch (err) {
41275
- const message = err instanceof Error ? err.message : String(err);
41276
- const mSectionSummary = (() => {
41277
- const lines = sdpOffer.split(/\r?\n/);
41278
- const sections = [];
41279
- let current = null;
41280
- for (const raw of lines) {
41281
- const line = raw.trim();
41282
- if (line.startsWith("m=")) {
41283
- if (current) sections.push(current);
41284
- current = {
41285
- mid: null,
41286
- kind: line.split(" ")[0]?.slice(2) ?? "unknown",
41287
- direction: null,
41288
- codecs: []
41289
- };
41290
- } else if (current) {
41291
- if (line.startsWith("a=mid:")) current.mid = line.slice(6);
41292
- else if (/^a=(sendonly|recvonly|sendrecv|inactive)$/.test(line)) current.direction = line.slice(2);
41293
- else if (line.startsWith("a=rtpmap:")) current.codecs.push(line.slice(9));
41294
- }
41295
- }
41296
- if (current) sections.push(current);
41297
- return sections;
41298
- })();
41299
- log.warn("alexa rtc-session: handleOffer failed", { meta: {
41300
- error: message,
41301
- offerLen: sdpOffer.length,
41302
- mSections: mSectionSummary,
41303
- offerSdp: sdpOffer
41304
- } });
41305
- if (egressPipelineKey !== null) {
41306
- EGRESS_HANDLES.delete(egressHandleKey(deviceId, sessionId));
41307
- await releaseAlexaEgress({
41308
- api,
41309
- deviceId,
41310
- pipelineKey: egressPipelineKey,
41311
- logger: log
41312
- });
41313
- }
41314
- return errorEnvelope(header, "INTERNAL_ERROR", `webrtc-session.handleOffer failed: ${message}`);
41315
- }
41316
- }
41317
- async function handleSessionDisconnected(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41318
- const parsed = SessionDisconnectedDirectiveSchema.safeParse({
41319
- endpoint: endpointRaw,
41320
- payload: payloadRaw ?? {}
41321
- });
41322
- if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
41323
- const endpoint = parsed.data.endpoint;
41324
- const parsedId = parseCameraEndpointId(endpoint.endpointId);
41325
- if (parsedId.kind === "camera") {
41326
- const handleKey = egressHandleKey(parsedId.deviceId, parsed.data.payload.sessionId);
41327
- const pipelineKey = EGRESS_HANDLES.get(handleKey);
41328
- if (pipelineKey !== void 0) {
41329
- EGRESS_HANDLES.delete(handleKey);
41330
- await releaseAlexaEgress({
41331
- api: deps.ctx.api,
41332
- deviceId: parsedId.deviceId,
41333
- pipelineKey,
41334
- logger: deps.logger
41335
- });
41336
- }
41337
- try {
41338
- await deps.ctx.api.webrtcSession.closeSession.mutate({
41339
- deviceId: parsedId.deviceId,
41340
- sessionId: parsed.data.payload.sessionId
41341
- });
41342
- } catch (err) {
41343
- deps.logger.warn("alexa rtc-session: closeSession threw on disconnect (continuing to ack)", {
41344
- tags: {
41345
- deviceId: parsedId.deviceId,
41346
- sessionId: parsed.data.payload.sessionId
41347
- },
41348
- meta: { error: err instanceof Error ? err.message : String(err) }
41349
- });
41350
- }
41351
- }
41352
- const disconnectedDeviceId = parsedId.kind === "camera" ? parsedId.deviceId : void 0;
41353
- deps.logger.info("alexa rtc-session: SessionDisconnected", {
41354
- tags: {
41355
- sessionId: parsed.data.payload.sessionId,
41356
- ...disconnectedDeviceId !== void 0 ? { deviceId: disconnectedDeviceId } : {}
41357
- },
41358
- meta: { endpointId: endpoint.endpointId }
41359
- });
41360
- return { event: {
41361
- header: {
41362
- namespace: "Alexa",
41363
- name: "Response",
41364
- messageId: header.messageId,
41365
- correlationToken: header.correlationToken,
41366
- payloadVersion: "3"
41367
- },
41368
- endpoint: { endpointId: endpoint.endpointId },
41369
- payload: {}
41370
- } };
41371
- }
41372
- //#endregion
41373
41704
  //#region src/handlers/security-panel.ts
41374
41705
  var ArmPayloadSchema = object({ armState: _enum([
41375
41706
  "ARMED_STAY",
@@ -43417,6 +43748,11 @@ var ExportAlexaAddon = class extends BaseAddon {
43417
43748
  });
43418
43749
  });
43419
43750
  this.ctx.addDisposer(async () => offTunnelStarted());
43751
+ const reaper = setInterval(() => {
43752
+ this.reapDeadEgressHandles();
43753
+ }, EGRESS_REAP_INTERVAL_MS);
43754
+ reaper.unref?.();
43755
+ this.ctx.addDisposer(async () => clearInterval(reaper));
43420
43756
  this.ctx.logger.info("export-alexa: initialized", { meta: {
43421
43757
  exposedCount: this.config.exposed.length,
43422
43758
  skillMode: this.config.skillMode,
@@ -44071,6 +44407,37 @@ var ExportAlexaAddon = class extends BaseAddon {
44071
44407
  ]
44072
44408
  }] });
44073
44409
  }
44410
+ /**
44411
+ * One sweep: ask the broker which held sessions are still alive, and release
44412
+ * the transcodes the dead ones are still holding.
44413
+ */
44414
+ async reapDeadEgressHandles() {
44415
+ const held = heldEgressHandles();
44416
+ if (held.length === 0) return;
44417
+ const dead = await reapDeadEgressHandles({
44418
+ held,
44419
+ isAlive: async (handle) => {
44420
+ try {
44421
+ return (await this.ctx.api.webrtcSession.getSessionState.query({
44422
+ deviceId: handle.deviceId,
44423
+ sessionId: handle.sessionId
44424
+ })).alive;
44425
+ } catch {
44426
+ return null;
44427
+ }
44428
+ }
44429
+ });
44430
+ for (const handle of dead) {
44431
+ logReaped(this.ctx.logger, handle);
44432
+ forgetEgressHandle(handle);
44433
+ await releaseAlexaEgress({
44434
+ api: this.ctx.api,
44435
+ deviceId: handle.deviceId,
44436
+ pipelineKey: handle.pipelineKey,
44437
+ logger: this.ctx.logger
44438
+ }).catch(() => {});
44439
+ }
44440
+ }
44074
44441
  async buildDeviceSettingsContribution(deviceId) {
44075
44442
  if (!await this.isCameraDevice(deviceId)) return null;
44076
44443
  const entry = this.findEntry(deviceId);
@@ -44078,6 +44445,7 @@ var ExportAlexaAddon = class extends BaseAddon {
44078
44445
  const enabled = entry !== null;
44079
44446
  const enabledKey = `alexa:${deviceId}:enabled`;
44080
44447
  const streamPreferenceKey = `alexa:${deviceId}:streamPreference`;
44448
+ const allowTranscodeKey = `alexa:${deviceId}:allowTranscode`;
44081
44449
  const linkedCount = this.config.linkedAccounts.length;
44082
44450
  return {
44083
44451
  tabs: [{
@@ -44123,6 +44491,19 @@ var ExportAlexaAddon = class extends BaseAddon {
44123
44491
  equals: true
44124
44492
  },
44125
44493
  immediate: true
44494
+ },
44495
+ {
44496
+ type: "boolean",
44497
+ key: allowTranscodeKey,
44498
+ label: "Allow transcoding for Alexa",
44499
+ 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.",
44500
+ style: "switch",
44501
+ value: settings.allowTranscode !== false,
44502
+ showWhen: {
44503
+ field: enabledKey,
44504
+ equals: true
44505
+ },
44506
+ immediate: true
44126
44507
  }
44127
44508
  ]
44128
44509
  }]
@@ -44142,26 +44523,17 @@ var ExportAlexaAddon = class extends BaseAddon {
44142
44523
  const idStr = String(deviceId);
44143
44524
  const current = this.findEntry(deviceId);
44144
44525
  const wasEnabled = current !== null;
44145
- const sourceProfileKey = `alexa:${deviceId}:sourceProfile`;
44146
- if (sourceProfileKey in patch) {
44147
- if (!wasEnabled) return { success: true };
44148
- const currentSettings = current?.settings ?? DEFAULT_DEVICE_SETTINGS;
44149
- const sourceProfileRaw = patch[sourceProfileKey];
44150
- const sourceProfile = sourceProfileRaw === "mid" ? "mid" : sourceProfileRaw === "low" ? "low" : "high";
44151
- await this.patchEntrySettings(deviceId, {
44152
- ...currentSettings,
44153
- sourceProfile
44154
- });
44155
- return { success: true };
44156
- }
44157
44526
  const enabledKey = `alexa:${deviceId}:enabled`;
44158
44527
  const streamPreferenceKey = `alexa:${deviceId}:streamPreference`;
44528
+ const allowTranscodeKey = `alexa:${deviceId}:allowTranscode`;
44159
44529
  const enabledValue = enabledKey in patch ? Boolean(patch[enabledKey]) : wasEnabled;
44160
44530
  const streamPreferenceRaw = streamPreferenceKey in patch ? patch[streamPreferenceKey] : current?.settings?.streamPreference;
44161
44531
  const streamPreference = typeof streamPreferenceRaw === "string" && streamPreferenceRaw.trim().length > 0 ? streamPreferenceRaw : "auto";
44532
+ const allowTranscode = allowTranscodeKey in patch ? Boolean(patch[allowTranscodeKey]) : current?.settings?.allowTranscode !== false;
44162
44533
  const nextSettings = {
44163
44534
  ...current?.settings ?? DEFAULT_DEVICE_SETTINGS,
44164
- streamPreference
44535
+ streamPreference,
44536
+ allowTranscode
44165
44537
  };
44166
44538
  if (!enabledValue) {
44167
44539
  if (wasEnabled) await this.unexposeDevice(idStr);
@@ -44173,13 +44545,22 @@ var ExportAlexaAddon = class extends BaseAddon {
44173
44545
  return { success: true };
44174
44546
  }
44175
44547
  const currentPref = current?.settings?.streamPreference ?? "auto";
44548
+ const currentAllow = current?.settings?.allowTranscode !== false;
44176
44549
  await this.patchEntrySettings(deviceId, nextSettings);
44177
- if (currentPref !== streamPreference) {
44178
- this.ctx.logger.info("export-alexa: streamPreference changed — refreshing exposure", { meta: {
44179
- deviceId,
44180
- from: currentPref,
44181
- to: streamPreference
44182
- } });
44550
+ if (currentPref !== streamPreference || currentAllow !== allowTranscode) {
44551
+ this.ctx.logger.info("export-alexa: source settings changed — refreshing exposure", {
44552
+ tags: { deviceId },
44553
+ meta: {
44554
+ streamPreference: {
44555
+ from: currentPref,
44556
+ to: streamPreference
44557
+ },
44558
+ allowTranscode: {
44559
+ from: currentAllow,
44560
+ to: allowTranscode
44561
+ }
44562
+ }
44563
+ });
44183
44564
  try {
44184
44565
  await this.unexposeDevice(idStr);
44185
44566
  await this.exposeDevice(idStr);