@camstack/addon-export-alexa 1.2.107 → 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).
@@ -7515,7 +7529,23 @@ var EncodeProfileSchema = object({
7515
7529
  "zerolatency",
7516
7530
  "film",
7517
7531
  "animation"
7518
- ]).optional()
7532
+ ]).optional(),
7533
+ /**
7534
+ * ONE slice per access unit.
7535
+ *
7536
+ * `-tune zerolatency` turns on x264's sliced threads, and a frame then leaves
7537
+ * the encoder as five NAL slices that share one RTP timestamp and carry one
7538
+ * marker bit. A libwebrtc depacketiser sees five frame-starts and one
7539
+ * frame-end per frame: the first pictures render and the video then freezes
7540
+ * for good while the audio, on its own plane, plays on. Measured on this hub
7541
+ * 2026-09-13 against the Echo, and reduced to one slice by this flag alone.
7542
+ *
7543
+ * A NAMED field and not a raw flag, because {@link EgressEncodeSchema} omits
7544
+ * `outputArgs` on purpose: an opaque array is part of the sharing key, so two
7545
+ * consumers meaning the same thing spelled differently would stop sharing one
7546
+ * child. Absent means "whatever the encoder does" — today's behaviour.
7547
+ */
7548
+ singleSlicePerFrame: boolean().optional()
7519
7549
  }),
7520
7550
  audio: union([literal("passthrough"), object({
7521
7551
  codec: _enum([
@@ -7544,6 +7574,28 @@ var EncodeProfileSchema = object({
7544
7574
  outputArgs: array(string()).optional()
7545
7575
  });
7546
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
+ /**
7547
7599
  * The shape every live egress starts from: H.264 Baseline 3.1 at 720p25.
7548
7600
  * Baseline because it is the one profile every consumer in this repo decodes
7549
7601
  * (Echo, iOS, an old browser); 3.1 because that is what the SDPs advertise.
@@ -7591,31 +7643,10 @@ var BASE_LIVE_EGRESS_PROFILE = {
7591
7643
  var ALEXA_EGRESS_PROFILE = {
7592
7644
  ...BASE_LIVE_EGRESS_PROFILE,
7593
7645
  audio: { codec: "opus" },
7594
- /**
7595
- * ONE slice per access unit.
7596
- *
7597
- * `-tune zerolatency` turns on x264's sliced threads, and every access unit
7598
- * came out of this encode as FIVE slices — measured on the hub 2026-09-13 on
7599
- * the exact argv this path spawns, and reduced to one by this single flag.
7600
- *
7601
- * Five slices share one RTP timestamp and carry one marker bit, so a
7602
- * libwebrtc depacketiser sees five frame-starts and one frame-end per frame.
7603
- * The Echo renders the first pictures and then freezes for good, while the
7604
- * audio — a separate plane — plays on. It is the only structural property
7605
- * that survived the elimination: the same freeze reproduced at 2304×1296
7606
- * HEVC with 217 KB keyframes AND at 640×360 H.264 with 67 KB keyframes and a
7607
- * fifth of the bitrate, so source, resolution, bitrate, keyframe burst,
7608
- * hardware decode, parameter sets, drift and bitstream conformance are all
7609
- * out — each ruled out by a measurement, not by elimination.
7610
- *
7611
- * The tune STAYS: it also drops the lookahead and the B-frames, which a live
7612
- * path wants. Only the slicing is unwanted, and this is the flag that says so.
7613
- *
7614
- * Scoped to Alexa deliberately. HomeKit and the browser transcode inherit
7615
- * {@link BASE_LIVE_EGRESS_PROFILE}; whether they want the same shape is a
7616
- * question for their own evidence, and the browser has not been measured.
7617
- */
7618
- outputArgs: ["-x264-params", "sliced-threads=0"]
7646
+ video: {
7647
+ ...BASE_LIVE_EGRESS_PROFILE.video,
7648
+ singleSlicePerFrame: true
7649
+ }
7619
7650
  };
7620
7651
  /**
7621
7652
  * Deep wiring healthcheck — snapshot of active reachability probes across
@@ -9479,6 +9510,47 @@ var LogChannelWindowSchema = object({
9479
9510
  /** `null` = every camera. A non-empty list narrows to those numeric ids. */
9480
9511
  deviceIds: array(number().int()).readonly().nullable()
9481
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
+ */
9482
9554
  function pickPreferredRtspEntry(entries, pref, deviceId, options = {}) {
9483
9555
  if (entries.length === 0) return null;
9484
9556
  const prefix = `${deviceId}/`;
@@ -9508,30 +9580,23 @@ function pickPreferredRtspEntry(entries, pref, deviceId, options = {}) {
9508
9580
  return toPicked(eligible[0]);
9509
9581
  }
9510
9582
  /**
9511
- * Pick the entry whose `resolution` is closest to `target`. Prefer
9512
- * entries ≥ target (downscale is cheap at the consumer; upscale is
9513
- * lossy). Among the rest pick the LARGEST still ≤ target so the
9514
- * consumer gets the best feasible quality. "Closeness" is the
9515
- * `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.
9516
9593
  */
9517
9594
  function pickClosestResolution(entries, target) {
9518
9595
  const targetPixels = target.width * target.height;
9519
- let bestAbove;
9520
- let bestBelow;
9521
- for (const e of entries) {
9522
- if (e.resolution === void 0) continue;
9523
- const pixels = e.resolution.width * e.resolution.height;
9524
- if (pixels >= targetPixels) {
9525
- if (!bestAbove || pixels < bestAbove.pixels) bestAbove = {
9526
- entry: e,
9527
- pixels
9528
- };
9529
- } else if (!bestBelow || pixels > bestBelow.pixels) bestBelow = {
9530
- entry: e,
9531
- pixels
9532
- };
9533
- }
9534
- 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;
9535
9600
  }
9536
9601
  var MODEL_FORMATS = [
9537
9602
  "onnx",
@@ -11745,6 +11810,58 @@ method(ListInputSchema, array(BrokerInfoSchema$1)), method(GetInputSchema, Broke
11745
11810
  auth: "admin"
11746
11811
  }), method(GetStateInputSchema, unknown().nullable()), method(_void(), RegistryStatusSchema);
11747
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());
11748
11865
  /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
11749
11866
  var StreamFormatSchema = _enum([
11750
11867
  "webrtc",
@@ -12141,6 +12258,22 @@ var EgressTranscodeSchema = object({
12141
12258
  camStreamId: string().nullable()
12142
12259
  });
12143
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({
12144
12277
  deviceId: number().int().nonnegative(),
12145
12278
  camStreamId: string().min(1),
12146
12279
  kind: CamStreamKindSchema,
@@ -12395,6 +12528,16 @@ var PickStreamRequirementsSchema = object({
12395
12528
  acceptCodecs: array(StreamCodecSchema).readonly().optional(),
12396
12529
  /** Minimum vertical resolution. Streams shorter than this are dropped. */
12397
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(),
12398
12541
  /** Minimum horizontal resolution. */
12399
12542
  minWidth: number().int().positive().optional(),
12400
12543
  /**
@@ -12411,7 +12554,22 @@ var PickStreamRequirementsSchema = object({
12411
12554
  * transcoded" guard: if the device is already serving the consumer's
12412
12555
  * codec end-to-end, there's nothing to optimise.
12413
12556
  */
12414
- 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()
12415
12573
  }).readonly();
12416
12574
  var PickStreamPreferencesSchema = object({
12417
12575
  /**
@@ -12425,12 +12583,32 @@ var PickStreamPreferencesSchema = object({
12425
12583
  * picks the tallest stream; `'lowest'` picks the shortest (used by
12426
12584
  * memory-constrained consumers / Apple Home guest sessions).
12427
12585
  */
12428
- 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()
12429
12599
  }).readonly();
12430
12600
  var PickedCamStreamSchema = object({
12431
12601
  camStreamId: string(),
12432
12602
  codec: string().optional(),
12433
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(),
12434
12612
  /** One-line explanation of why this stream won — for logs / debug UI. */
12435
12613
  reason: string()
12436
12614
  });
@@ -16503,7 +16681,7 @@ var AlarmArmModeSchema = _enum([
16503
16681
  "vacation",
16504
16682
  "custom_bypass"
16505
16683
  ]);
16506
- object({
16684
+ var AlarmPanelStatusSchema = object({
16507
16685
  /** Current lifecycle state. */
16508
16686
  state: AlarmStateSchema,
16509
16687
  /** Subset of arm modes the panel accepts. UI renders one button per
@@ -16666,6 +16844,8 @@ var NcSystemEventKindSchema = _enum([
16666
16844
  "device-enabled",
16667
16845
  "device-battery-low",
16668
16846
  "device-battery-normal",
16847
+ "device-consumable-low",
16848
+ "device-consumable-normal",
16669
16849
  "stream-online",
16670
16850
  "stream-offline",
16671
16851
  "node-online",
@@ -16684,6 +16864,7 @@ var NcSystemEventKindSchema = _enum([
16684
16864
  "addon-updated",
16685
16865
  "server-updated",
16686
16866
  "export-completed",
16867
+ "backup-completed",
16687
16868
  "camera-online",
16688
16869
  "camera-offline",
16689
16870
  "camera-disabled",
@@ -23941,10 +24122,28 @@ DeviceType.Camera, method(object({ deviceId: number().int().nonnegative() }), ar
23941
24122
  }), boolean()), method(object({
23942
24123
  deviceId: number().int().nonnegative(),
23943
24124
  sessionId: string()
23944
- }), object({ pendingRenegotiation: object({
23945
- target: WebrtcStreamTargetSchema,
23946
- epoch: number()
23947
- }).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
+ }));
23948
24147
  object({
23949
24148
  /** All accessory children of the parent. */
23950
24149
  childDeviceIds: array(number()).readonly(),
@@ -36448,6 +36647,12 @@ Object.freeze({
36448
36647
  addonId: null,
36449
36648
  access: "create"
36450
36649
  },
36650
+ "streamBroker.reportStreamSignal": {
36651
+ capName: "stream-broker",
36652
+ capScope: "system",
36653
+ addonId: null,
36654
+ access: "create"
36655
+ },
36451
36656
  "streamBroker.restartProfile": {
36452
36657
  capName: "stream-broker",
36453
36658
  capScope: "system",
@@ -36532,6 +36737,12 @@ Object.freeze({
36532
36737
  addonId: null,
36533
36738
  access: "create"
36534
36739
  },
36740
+ "streamSignals.listSignals": {
36741
+ capName: "stream-signals",
36742
+ capScope: "device",
36743
+ addonId: null,
36744
+ access: "view"
36745
+ },
36535
36746
  "switch.setState": {
36536
36747
  capName: "switch",
36537
36748
  capScope: "device",
@@ -38904,6 +39115,11 @@ Object.freeze({
38904
39115
  form: "single",
38905
39116
  optional: false
38906
39117
  }],
39118
+ "streamBroker.reportStreamSignal": [{
39119
+ name: "deviceId",
39120
+ form: "single",
39121
+ optional: false
39122
+ }],
38907
39123
  "streamBroker.restartProfile": [{
38908
39124
  name: "deviceId",
38909
39125
  form: "single",
@@ -39734,7 +39950,7 @@ async function acquireAlexaEgress(input) {
39734
39950
  profile: sourceProfile
39735
39951
  },
39736
39952
  encode: ALEXA_EGRESS_PROFILE,
39737
- rateControl: "relaxed",
39953
+ rateControl: "tight",
39738
39954
  publishLocally: true,
39739
39955
  tag: `alexa/${sessionId}`
39740
39956
  });
@@ -39758,6 +39974,7 @@ async function acquireAlexaEgress(input) {
39758
39974
  meta: {
39759
39975
  pipelineKey: transcode.pipelineKey,
39760
39976
  camStreamId,
39977
+ sourceProfile: input.sourceProfile,
39761
39978
  encoder: transcode.encoder,
39762
39979
  decodeHwAccel: transcode.decodeHwAccel ?? "software"
39763
39980
  }
@@ -39791,6 +40008,148 @@ async function releaseAlexaEgress(input) {
39791
40008
  }
39792
40009
  }
39793
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
39794
40153
  //#region src/handlers/types.ts
39795
40154
  /**
39796
40155
  * Zod schemas for the subset of the Alexa Smart Home directive surface
@@ -39852,6 +40211,369 @@ var InitiateSessionWithOfferPayloadSchema = object({
39852
40211
  var SessionDisconnectedPayloadSchema = object({ sessionId: string() });
39853
40212
  var SetModePayloadSchema = object({ mode: string() });
39854
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
40517
+ //#region src/handlers/security-panel-arm-state.ts
40518
+ /**
40519
+ * The panel modes behind each Alexa arm state, PRIMARY first — the mirror of
40520
+ * `MODES_BY_TARGET` in the HomeKit exporter, and for the same reason: one
40521
+ * Alexa state stands for two panel modes, so a panel offering only the
40522
+ * secondary would otherwise be sent a mode it refuses.
40523
+ */
40524
+ var MODES_BY_ARM_STATE = {
40525
+ ARMED_STAY: ["home", "custom_bypass"],
40526
+ ARMED_AWAY: ["away", "vacation"],
40527
+ ARMED_NIGHT: ["night"]
40528
+ };
40529
+ var ARM_STATES = [
40530
+ "ARMED_STAY",
40531
+ "ARMED_AWAY",
40532
+ "ARMED_NIGHT"
40533
+ ];
40534
+ /** The panel's state as Alexa's `armState` property. */
40535
+ function alexaArmStateFor(state) {
40536
+ switch (state) {
40537
+ case "armed_home":
40538
+ case "armed_custom_bypass": return "ARMED_STAY";
40539
+ case "armed_night": return "ARMED_NIGHT";
40540
+ case "armed_away":
40541
+ case "armed_vacation":
40542
+ case "pending":
40543
+ case "triggered": return "ARMED_AWAY";
40544
+ default: return "DISARMED";
40545
+ }
40546
+ }
40547
+ /** `burglaryAlarm`, the only alarm property this cap can honestly fill. */
40548
+ function burglaryAlarmFor(state) {
40549
+ return { value: state === "triggered" ? "ALARM" : "OK" };
40550
+ }
40551
+ /**
40552
+ * The `supportedArmStates` for discovery.
40553
+ *
40554
+ * `DISARMED` is always present: disarming is not one of the panel's arm modes.
40555
+ * An EMPTY `availableModes` is unknown, not "none" — a provider that never
40556
+ * populated the list looks identical to one that accepts nothing, and
40557
+ * publishing a panel that can only be disarmed on that guess takes the
40558
+ * controls off a working alarm. The caller logs it.
40559
+ */
40560
+ function supportedArmStatesFor(availableModes) {
40561
+ return [...availableModes.length === 0 ? ARM_STATES : ARM_STATES.filter((armState) => MODES_BY_ARM_STATE[armState].some((mode) => availableModes.includes(mode))), "DISARMED"];
40562
+ }
40563
+ /**
40564
+ * The arm mode to send for an Alexa arm state, or `null` when there is none.
40565
+ *
40566
+ * `null` is not a shrug: `DISARMED` is the Disarm DIRECTIVE, a different call,
40567
+ * and an arm state the panel accepts no mode for is a directive the handler
40568
+ * refuses with `NOT_READY_FOR_ARM` rather than translating into a guess.
40569
+ */
40570
+ function alarmArmModeForAlexa(armState, availableModes) {
40571
+ if (armState === "DISARMED") return null;
40572
+ const candidates = MODES_BY_ARM_STATE[armState];
40573
+ if (availableModes.length === 0) return candidates[0] ?? null;
40574
+ return candidates.find((mode) => availableModes.includes(mode)) ?? null;
40575
+ }
40576
+ //#endregion
39855
40577
  //#region src/endpoints/builder.ts
39856
40578
  var DEFAULT_RESOLUTIONS = [{
39857
40579
  width: 1920,
@@ -40174,55 +40896,55 @@ function buildPrivacyEndpoint(input) {
40174
40896
  }
40175
40897
  };
40176
40898
  }
40177
- //#endregion
40178
- //#region src/handlers/error-envelope.ts
40179
40899
  /**
40180
- * Shared Alexa `Alexa/ErrorResponse` envelope builder.
40181
- *
40182
- * Lives in its own module so every handler (and the directive router)
40183
- * can emit its own namespace-appropriate error without circular imports.
40184
- */
40185
- object({ event: object({
40186
- header: object({
40187
- namespace: literal("Alexa"),
40188
- name: literal("ErrorResponse"),
40189
- messageId: string(),
40190
- payloadVersion: literal("3")
40191
- }),
40192
- payload: object({
40193
- type: string(),
40194
- message: string()
40195
- })
40196
- }) });
40197
- function errorEnvelope(header, type, message) {
40198
- return { event: {
40199
- header: {
40200
- namespace: "Alexa",
40201
- name: "ErrorResponse",
40202
- messageId: header.messageId,
40203
- payloadVersion: "3"
40900
+ * An `alarm-panel` device as an `Alexa.SecurityPanelController` endpoint.
40901
+ *
40902
+ * It is its OWN endpoint, not a child of a camera: a panel is a standalone
40903
+ * device and has no stream, no doorbell and no PTZ. The `__alarm` suffix on
40904
+ * the endpoint id is a routing tag (see `handlers/endpoint-id.ts`).
40905
+ *
40906
+ * ## What is declared, and what is deliberately not
40907
+ *
40908
+ * - `armState` and `burglaryAlarm` are the two properties this cap can fill
40909
+ * honestly. `fireAlarm` / `carbonMonoxideAlarm` / `waterAlarm` are NOT
40910
+ * declared: `alarm-panel` has no field saying WHICH alarm is sounding, and
40911
+ * declaring a property we would always answer `OK` on is a claim with no
40912
+ * basis behind it. The reasoning is in `security-panel-arm-state.ts`.
40913
+ * - `proactivelyReported: false`. This addon's Event Gateway pushes
40914
+ * ChangeReports for camera motion only; a panel state change is not wired
40915
+ * to it, and promising a report nothing sends is how an endpoint ends up
40916
+ * looking broken. `retrievable: true` — `Alexa/ReportState` answers.
40917
+ * - `supportedAuthorizationTypes` appears only for a panel that requires a
40918
+ * code. Alexa's Disarm directive can carry a PIN; its **Arm directive
40919
+ * cannot**, which is why a PIN-gated arm is refused by the handler with
40920
+ * `AUTHORIZATION_REQUIRED` rather than attempted.
40921
+ */
40922
+ function buildAlarmPanelEndpoint(input) {
40923
+ const configuration = { supportedArmStates: supportedArmStatesFor(input.availableModes).map((value) => ({ value })) };
40924
+ if (input.requiresCode) configuration.supportedAuthorizationTypes = [{ type: "FOUR_DIGIT_PIN" }];
40925
+ const securityPanelController = {
40926
+ type: "AlexaInterface",
40927
+ interface: "Alexa.SecurityPanelController",
40928
+ version: "3",
40929
+ properties: {
40930
+ supported: [{ name: "armState" }, { name: "burglaryAlarm" }],
40931
+ proactivelyReported: false,
40932
+ retrievable: true
40204
40933
  },
40205
- payload: {
40206
- type,
40207
- message
40208
- }
40209
- } };
40934
+ configuration
40935
+ };
40936
+ return {
40937
+ endpointId: `${input.deviceId}__alarm`,
40938
+ manufacturerName: "camstack",
40939
+ description: "CamStack alarm panel",
40940
+ friendlyName: input.friendlyName.trim().length > 0 ? input.friendlyName.trim() : `Alarm ${input.deviceId}`,
40941
+ displayCategories: ["SECURITY_PANEL"],
40942
+ capabilities: [ALEXA_BASE_CAPABILITY, securityPanelController],
40943
+ cookie: { stableId: input.stableId }
40944
+ };
40210
40945
  }
40211
40946
  //#endregion
40212
40947
  //#region src/handlers/discovery.ts
40213
- /**
40214
- * `Alexa.Discovery/Discover` handler — fires when the Alexa app pulls
40215
- * the user's device list. We respond with the operator-curated
40216
- * `exposed-devices.json` list, resolved against the live device
40217
- * registry (so we don't return zombie endpoints for deleted devices).
40218
- *
40219
- * Feature detection is PASSIVE: per exposed device we inspect the
40220
- * `DeviceInfo.features` + bound caps (from `device-manager.getBindings`)
40221
- * and emit only the Alexa capabilities backed by something on our side.
40222
- * Child accessories (siren/floodlight/PIR/…) become SEPARATE endpoints
40223
- * with `endpointId = ${parent}__${child}` so directive handlers can
40224
- * route to the right cap on the right device.
40225
- */
40226
40948
  var discoveryPayloadSchema = DiscoveryDirectiveSchema.shape.payload;
40227
40949
  /** Devices built at once in `handleDiscovery` — latency-bound tRPC reads, so
40228
40950
  * six lanes hide the round-trips without stampeding a booting hub. */
@@ -40236,6 +40958,7 @@ var CAP_SWITCH = "switch";
40236
40958
  var CAP_BRIGHTNESS = "brightness";
40237
40959
  var CAP_BATTERY = "battery";
40238
40960
  var CAP_PRIVACY_MASK = "privacy-mask";
40961
+ var CAP_ALARM_PANEL = "alarm-panel";
40239
40962
  async function handleDiscovery(header, payloadRaw, deps, callerIdentity) {
40240
40963
  if (!discoveryPayloadSchema.safeParse(payloadRaw).success) return errorEnvelope(header, "INVALID_DIRECTIVE", "Discovery payload shape unexpected");
40241
40964
  const exposed = await deps.listExposed();
@@ -40275,6 +40998,7 @@ async function buildEndpointsForExposedDevice(deviceId, deps) {
40275
40998
  return [];
40276
40999
  }
40277
41000
  const parentInfo = await loadBoundDeviceInfo(device, api);
41001
+ if (parentInfo.capNames.includes(CAP_ALARM_PANEL)) return [await buildAlarmPanelEndpointFor(parentInfo, api, deps)];
40278
41002
  const children = await api.deviceManager.getChildren.query({ parentDeviceId: deviceId }).catch((err) => {
40279
41003
  deps.logger.warn("alexa discovery: getChildren failed", {
40280
41004
  tags: { deviceId },
@@ -40354,6 +41078,47 @@ async function buildEndpointsForExposedDevice(deviceId, deps) {
40354
41078
  }
40355
41079
  return out;
40356
41080
  }
41081
+ /**
41082
+ * The panel endpoint, with what the panel says it accepts.
41083
+ *
41084
+ * A `getStatus` that fails leaves `availableModes` empty and `requiresCode`
41085
+ * false, and those are the UNKNOWN readings, not assertions: an empty mode
41086
+ * list makes discovery declare all three arm states (`supportedArmStatesFor`)
41087
+ * rather than publishing a panel that can only be disarmed, and the directive
41088
+ * handler re-reads the panel before it commands anything, so a PIN discovered
41089
+ * later is still honoured. The blind read is logged against the device id.
41090
+ */
41091
+ async function buildAlarmPanelEndpointFor(info, api, deps) {
41092
+ const status = await api.alarmPanel.getStatus.query({ deviceId: info.id }).catch((err) => {
41093
+ deps.logger.warn("alexa discovery: alarmPanel.getStatus failed — declaring every arm state", {
41094
+ tags: { deviceId: info.id },
41095
+ meta: { error: err instanceof Error ? err.message : String(err) }
41096
+ });
41097
+ return null;
41098
+ });
41099
+ const parsed = AlarmPanelStatusSchema.pick({
41100
+ availableModes: true,
41101
+ requiresCode: true
41102
+ }).safeParse(status);
41103
+ if (!parsed.success && status !== null) deps.logger.warn("alexa discovery: panel status did not match the cap schema", { tags: { deviceId: info.id } });
41104
+ const availableModes = parsed.success ? parsed.data.availableModes : [];
41105
+ const requiresCode = parsed.success ? parsed.data.requiresCode : false;
41106
+ deps.logger.info("alexa discovery: built alarm panel endpoint", {
41107
+ tags: { deviceId: info.id },
41108
+ meta: {
41109
+ name: info.name,
41110
+ availableModes: [...availableModes],
41111
+ requiresCode
41112
+ }
41113
+ });
41114
+ return buildAlarmPanelEndpoint({
41115
+ deviceId: info.id,
41116
+ stableId: info.stableId,
41117
+ friendlyName: info.name,
41118
+ availableModes,
41119
+ requiresCode
41120
+ });
41121
+ }
40357
41122
  async function loadBoundDeviceInfo(device, api) {
40358
41123
  const capNames = (await api.deviceManager.getBindings.query({ deviceId: device.id })).entries.map((e) => e.capName);
40359
41124
  return {
@@ -40387,55 +41152,67 @@ function discoveryResponse(header, endpoints) {
40387
41152
  } };
40388
41153
  }
40389
41154
  //#endregion
40390
- //#region src/handlers/endpoint-id.ts
40391
- var SEPARATOR = "__";
40392
- function parseCameraEndpointId(raw) {
40393
- if (!raw.includes(SEPARATOR)) {
40394
- const id = parseNonNegativeInt(raw);
40395
- if (id === null) return {
40396
- kind: "invalid",
40397
- reason: `not a numeric deviceId: ${raw}`
40398
- };
40399
- return {
40400
- kind: "camera",
40401
- deviceId: id
40402
- };
41155
+ //#region src/handlers/brightness-controller.ts
41156
+ var SetBrightnessDirectiveSchema = object({
41157
+ header: object({
41158
+ namespace: literal("Alexa.BrightnessController"),
41159
+ name: literal("SetBrightness")
41160
+ }),
41161
+ endpoint: EndpointRefSchema,
41162
+ payload: object({ brightness: number().min(0).max(100) })
41163
+ });
41164
+ async function handleSetBrightness(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41165
+ const parsed = SetBrightnessDirectiveSchema.safeParse({
41166
+ header: {
41167
+ namespace: header.namespace,
41168
+ name: header.name
41169
+ },
41170
+ endpoint: endpointRaw,
41171
+ payload: payloadRaw ?? {}
41172
+ });
41173
+ if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
41174
+ const endpointId = parsed.data.endpoint.endpointId;
41175
+ const parsedId = parseCameraEndpointId(endpointId);
41176
+ if (parsedId.kind === "autotrack" || parsedId.kind === "privacy" || parsedId.kind === "alarm-panel") return errorEnvelope(header, "INVALID_DIRECTIVE", `BrightnessController is not exposed on the ${parsedId.kind} endpoint`);
41177
+ if (parsedId.kind === "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", "BrightnessController is not exposed on camera endpoints — direct the directive at the dimmable child accessory");
41178
+ if (parsedId.kind === "invalid") return errorEnvelope(header, "INVALID_DIRECTIVE", parsedId.reason);
41179
+ const percentage = parsed.data.payload.brightness;
41180
+ const api = deps.ctx.api;
41181
+ try {
41182
+ await api.brightness.setBrightness.mutate({
41183
+ deviceId: parsedId.childDeviceId,
41184
+ percentage
41185
+ });
41186
+ } catch (err) {
41187
+ const message = err instanceof Error ? err.message : String(err);
41188
+ deps.logger.warn("alexa brightness-controller: setBrightness failed", { meta: {
41189
+ deviceId: parsedId.childDeviceId,
41190
+ percentage,
41191
+ error: message
41192
+ } });
41193
+ return errorEnvelope(header, "INTERNAL_ERROR", `brightness.setBrightness failed: ${message}`);
40403
41194
  }
40404
- const [head, tail, ...rest] = raw.split(SEPARATOR);
40405
- if (head === void 0 || tail === void 0 || rest.length > 0) return {
40406
- kind: "invalid",
40407
- reason: `unexpected segments in endpointId: ${raw}`
40408
- };
40409
- const parent = parseNonNegativeInt(head);
40410
- if (parent === null) return {
40411
- kind: "invalid",
40412
- reason: `parent segment not numeric: ${raw}`
40413
- };
40414
- if (tail === "autotrack") return {
40415
- kind: "autotrack",
40416
- parentDeviceId: parent
40417
- };
40418
- if (tail === "privacy") return {
40419
- kind: "privacy",
40420
- parentDeviceId: parent
40421
- };
40422
- const child = parseNonNegativeInt(tail);
40423
- if (child === null) return {
40424
- kind: "invalid",
40425
- reason: `child segment not numeric and not 'autotrack'/'privacy': ${raw}`
40426
- };
40427
41195
  return {
40428
- kind: "child",
40429
- parentDeviceId: parent,
40430
- childDeviceId: child
41196
+ event: {
41197
+ header: {
41198
+ namespace: "Alexa",
41199
+ name: "Response",
41200
+ messageId: header.messageId,
41201
+ correlationToken: header.correlationToken,
41202
+ payloadVersion: "3"
41203
+ },
41204
+ endpoint: { endpointId },
41205
+ payload: {}
41206
+ },
41207
+ context: { properties: [{
41208
+ namespace: "Alexa.BrightnessController",
41209
+ name: "brightness",
41210
+ value: percentage,
41211
+ timeOfSample: (/* @__PURE__ */ new Date()).toISOString(),
41212
+ uncertaintyInMilliseconds: 500
41213
+ }] }
40431
41214
  };
40432
41215
  }
40433
- function parseNonNegativeInt(s) {
40434
- if (!/^\d+$/.test(s)) return null;
40435
- const n = Number.parseInt(s, 10);
40436
- if (!Number.isFinite(n) || n < 0) return null;
40437
- return n;
40438
- }
40439
41216
  //#endregion
40440
41217
  //#region src/handlers/camera-stream.ts
40441
41218
  /**
@@ -40519,347 +41296,42 @@ async function handleInitializeCameraStreams(header, endpointRaw, payloadRaw, de
40519
41296
  } };
40520
41297
  }
40521
41298
  //#endregion
40522
- //#region src/handlers/rtc-session.ts
40523
- var InitiateSessionWithOfferDirectiveSchema = object({
40524
- endpoint: EndpointRefSchema,
40525
- payload: InitiateSessionWithOfferPayloadSchema
40526
- });
40527
- var SessionDisconnectedDirectiveSchema = object({
40528
- endpoint: EndpointRefSchema,
40529
- payload: SessionDisconnectedPayloadSchema
40530
- });
40531
- /**
40532
- * Live egress handles, keyed by `<deviceId>/<sessionId>`.
40533
- *
40534
- * The primitive's refcount has no lease TTL: a holder that vanishes without
40535
- * releasing leaks a child until the broker restarts (D67). This handler is a
40536
- * holder, so it keeps the one piece of state that lets it not be that holder —
40537
- * the `pipelineKey` its `SessionDisconnected` has to release.
40538
- *
40539
- * A module-level map is right here because the directive handlers are free
40540
- * functions called per directive; the entry is written on a successful acquire
40541
- * and deleted on the release path, both of which are the same tick as the
40542
- * directive that owns it.
40543
- */
40544
- var EGRESS_HANDLES = /* @__PURE__ */ new Map();
40545
- function egressHandleKey(deviceId, sessionId) {
40546
- return `${deviceId}/${sessionId}`;
40547
- }
40548
- var WEBRTC_PROFILE_NAMES = [
40549
- "high",
40550
- "mid",
40551
- "low"
40552
- ];
40553
- function resolveWebrtcTarget(pref) {
40554
- if (pref === "auto") return void 0;
40555
- if (WEBRTC_PROFILE_NAMES.includes(pref)) return {
40556
- kind: "profile",
40557
- profile: pref
40558
- };
40559
- return {
40560
- kind: "cam-stream",
40561
- camStreamId: pref
40562
- };
40563
- }
40564
- async function handleInitiateSessionWithOffer(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
40565
- const parsed = InitiateSessionWithOfferDirectiveSchema.safeParse({
40566
- endpoint: endpointRaw,
40567
- payload: payloadRaw ?? {}
40568
- });
40569
- if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
40570
- const endpoint = parsed.data.endpoint;
40571
- const payload = parsed.data.payload;
40572
- const parsedId = parseCameraEndpointId(endpoint.endpointId);
40573
- if (parsedId.kind !== "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", `endpointId ${endpoint.endpointId} is not a camera`);
40574
- const deviceId = parsedId.deviceId;
40575
- const sessionId = payload.sessionId;
40576
- const log = deps.logger.withTags({
40577
- deviceId,
40578
- sessionId
40579
- });
40580
- const sdpOffer = payload.offer.value;
40581
- if (sdpOffer.length === 0) return errorEnvelope(header, "INVALID_DIRECTIVE", "offer.value is empty");
40582
- const api = deps.ctx.api;
40583
- const exposedEntry = deps.listExposed().find((e) => e.deviceId === deviceId);
40584
- const explicitSourceProfile = exposedEntry?.settings?.sourceProfile;
40585
- const mappedFromPreference = (() => {
40586
- const pref = exposedEntry?.settings?.streamPreference;
40587
- if (pref === "low" || pref === "mid" || pref === "high") return pref;
40588
- })();
40589
- const sourceProfile = explicitSourceProfile ?? mappedFromPreference ?? "high";
40590
- let derivedTarget;
40591
- /**
40592
- * The primitive's release handle, when this session acquired one. Recorded so
40593
- * `SessionDisconnected` can release it: a refcount whose holder disappears is
40594
- * the one gap D67 leaves open, and the least this handler can do is not BE
40595
- * that holder.
40596
- */
40597
- let egressPipelineKey = null;
40598
- const picked = await api.cameraStreams.pickStream.query({
40599
- deviceId,
40600
- requirements: {
40601
- acceptCodecs: ["h264"],
40602
- minHeight: 480,
40603
- excludeDerived: true,
40604
- requireSiblingCodec: ["h265", "hevc"]
40605
- }
40606
- }).catch((err) => {
40607
- log.warn("alexa rtc-session: cameraStreams.pickStream threw — falling back to transcode", { meta: { error: err instanceof Error ? err.message : String(err) } });
40608
- return null;
40609
- });
40610
- if (picked) {
40611
- log.info("alexa rtc-session: bypassing transcode via cameraStreams.pickStream", { meta: {
40612
- sourceProfile,
40613
- selectedCamStreamId: picked.camStreamId,
40614
- reason: picked.reason
40615
- } });
40616
- derivedTarget = {
40617
- kind: "cam-stream",
40618
- camStreamId: picked.camStreamId
40619
- };
40620
- } else try {
40621
- const acquired = await acquireAlexaEgress({
40622
- api,
40623
- deviceId,
40624
- sourceProfile,
40625
- sessionId,
40626
- logger: log
40627
- });
40628
- egressPipelineKey = acquired.pipelineKey;
40629
- EGRESS_HANDLES.set(egressHandleKey(deviceId, sessionId), acquired.pipelineKey);
40630
- derivedTarget = {
40631
- kind: "cam-stream",
40632
- camStreamId: acquired.camStreamId
40633
- };
40634
- } catch (err) {
40635
- log.warn("alexa rtc-session: egress acquire failed, falling back to streamPreference target", { meta: { error: err instanceof Error ? err.message : String(err) } });
40636
- derivedTarget = resolveWebrtcTarget(exposedEntry?.settings?.streamPreference ?? "auto");
40637
- }
40638
- try {
40639
- const result = await api.webrtcSession.handleOffer.mutate({
40640
- deviceId,
40641
- sdpOffer,
40642
- sessionId,
40643
- target: derivedTarget,
40644
- relayOnly: false,
40645
- nonTrickle: true,
40646
- disableTurn: true,
40647
- disableIpv6: true,
40648
- consumerAttribution: {
40649
- kind: "alexa",
40650
- sessionId
40651
- }
40652
- });
40653
- log.info("alexa rtc-session: AnswerGenerated", { meta: {
40654
- returnedSessionId: result.sessionId,
40655
- sdpAnswerLen: result.sdpAnswer.length
40656
- } });
40657
- return { event: {
40658
- header: {
40659
- namespace: "Alexa.RTCSessionController",
40660
- name: "AnswerGeneratedForSession",
40661
- messageId: header.messageId,
40662
- correlationToken: header.correlationToken,
40663
- payloadVersion: "3"
40664
- },
40665
- endpoint: { endpointId: endpoint.endpointId },
40666
- payload: { answer: {
40667
- format: payload.offer.format ?? "SDP",
40668
- value: result.sdpAnswer
40669
- } }
40670
- } };
40671
- } catch (err) {
40672
- const message = err instanceof Error ? err.message : String(err);
40673
- const mSectionSummary = (() => {
40674
- const lines = sdpOffer.split(/\r?\n/);
40675
- const sections = [];
40676
- let current = null;
40677
- for (const raw of lines) {
40678
- const line = raw.trim();
40679
- if (line.startsWith("m=")) {
40680
- if (current) sections.push(current);
40681
- current = {
40682
- mid: null,
40683
- kind: line.split(" ")[0]?.slice(2) ?? "unknown",
40684
- direction: null,
40685
- codecs: []
40686
- };
40687
- } else if (current) {
40688
- if (line.startsWith("a=mid:")) current.mid = line.slice(6);
40689
- else if (/^a=(sendonly|recvonly|sendrecv|inactive)$/.test(line)) current.direction = line.slice(2);
40690
- else if (line.startsWith("a=rtpmap:")) current.codecs.push(line.slice(9));
40691
- }
40692
- }
40693
- if (current) sections.push(current);
40694
- return sections;
40695
- })();
40696
- log.warn("alexa rtc-session: handleOffer failed", { meta: {
40697
- error: message,
40698
- offerLen: sdpOffer.length,
40699
- mSections: mSectionSummary,
40700
- offerSdp: sdpOffer
40701
- } });
40702
- if (egressPipelineKey !== null) {
40703
- EGRESS_HANDLES.delete(egressHandleKey(deviceId, sessionId));
40704
- await releaseAlexaEgress({
40705
- api,
40706
- deviceId,
40707
- pipelineKey: egressPipelineKey,
40708
- logger: log
40709
- });
40710
- }
40711
- return errorEnvelope(header, "INTERNAL_ERROR", `webrtc-session.handleOffer failed: ${message}`);
40712
- }
40713
- }
40714
- async function handleSessionDisconnected(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
40715
- const parsed = SessionDisconnectedDirectiveSchema.safeParse({
40716
- endpoint: endpointRaw,
40717
- payload: payloadRaw ?? {}
40718
- });
40719
- if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
40720
- const endpoint = parsed.data.endpoint;
40721
- const parsedId = parseCameraEndpointId(endpoint.endpointId);
40722
- if (parsedId.kind === "camera") {
40723
- const handleKey = egressHandleKey(parsedId.deviceId, parsed.data.payload.sessionId);
40724
- const pipelineKey = EGRESS_HANDLES.get(handleKey);
40725
- if (pipelineKey !== void 0) {
40726
- EGRESS_HANDLES.delete(handleKey);
40727
- await releaseAlexaEgress({
40728
- api: deps.ctx.api,
40729
- deviceId: parsedId.deviceId,
40730
- pipelineKey,
40731
- logger: deps.logger
40732
- });
40733
- }
40734
- try {
40735
- await deps.ctx.api.webrtcSession.closeSession.mutate({
40736
- deviceId: parsedId.deviceId,
40737
- sessionId: parsed.data.payload.sessionId
40738
- });
40739
- } catch (err) {
40740
- deps.logger.warn("alexa rtc-session: closeSession threw on disconnect (continuing to ack)", {
40741
- tags: {
40742
- deviceId: parsedId.deviceId,
40743
- sessionId: parsed.data.payload.sessionId
40744
- },
40745
- meta: { error: err instanceof Error ? err.message : String(err) }
40746
- });
40747
- }
40748
- }
40749
- const disconnectedDeviceId = parsedId.kind === "camera" ? parsedId.deviceId : void 0;
40750
- deps.logger.info("alexa rtc-session: SessionDisconnected", {
40751
- tags: {
40752
- sessionId: parsed.data.payload.sessionId,
40753
- ...disconnectedDeviceId !== void 0 ? { deviceId: disconnectedDeviceId } : {}
40754
- },
40755
- meta: { endpointId: endpoint.endpointId }
40756
- });
40757
- return { event: {
40758
- header: {
40759
- namespace: "Alexa",
40760
- name: "Response",
40761
- messageId: header.messageId,
40762
- correlationToken: header.correlationToken,
40763
- payloadVersion: "3"
40764
- },
40765
- endpoint: { endpointId: endpoint.endpointId },
40766
- payload: {}
40767
- } };
40768
- }
40769
- //#endregion
40770
- //#region src/handlers/ptz-preset.ts
40771
- /**
40772
- * `Alexa.ModeController/SetMode` handler — dispatches three PTZ instances:
40773
- *
40774
- * `ptz.preset` — preset-recall. Decodes the preset name from the mode
40775
- * value and calls `ptz.goToPreset({deviceId, presetId})`.
40776
- *
40777
- * `ptz.pan` — momentary pan. `ptz.pan.left|right|center` issues a
40778
- * continuousMove pulse stopped on a timer; the dropdown reverts to
40779
- * `center` server-side so subsequent picks re-trigger the move.
40780
- *
40781
- * `ptz.tilt` — momentary tilt. Mirrors ptz.pan with up|down|center.
40782
- */
40783
- var SetModeDirectiveSchema = object({
41299
+ //#region src/handlers/power-controller.ts
41300
+ var PowerDirectiveSchema = object({
40784
41301
  header: object({
40785
- namespace: literal("Alexa.ModeController"),
40786
- name: literal("SetMode"),
40787
- instance: string().optional()
41302
+ namespace: literal("Alexa.PowerController"),
41303
+ name: _enum(["TurnOn", "TurnOff"])
40788
41304
  }),
40789
- endpoint: EndpointRefSchema,
40790
- payload: SetModePayloadSchema
41305
+ endpoint: EndpointRefSchema
40791
41306
  });
40792
- var PTZ_PRESET_MODE_PREFIX = "ptz.preset.";
40793
- var PTZ_DIRECTION_PULSE_MS = 1e3;
40794
- var PTZ_PAN_MOVES = {
40795
- "ptz.pan.left": { pan: -1 },
40796
- "ptz.pan.right": { pan: 1 },
40797
- "ptz.pan.center": {}
40798
- };
40799
- var PTZ_TILT_MOVES = {
40800
- "ptz.tilt.up": { tilt: 1 },
40801
- "ptz.tilt.down": { tilt: -1 },
40802
- "ptz.tilt.center": {}
40803
- };
40804
- async function handleSetMode(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
40805
- const parsed = SetModeDirectiveSchema.safeParse({
41307
+ async function handlePower(header, endpointRaw, deps, _callerIdentity) {
41308
+ const parsed = PowerDirectiveSchema.safeParse({
40806
41309
  header: {
40807
41310
  namespace: header.namespace,
40808
- name: header.name,
40809
- instance: header.instance
41311
+ name: header.name
40810
41312
  },
40811
- endpoint: endpointRaw,
40812
- payload: payloadRaw ?? {}
41313
+ endpoint: endpointRaw
40813
41314
  });
40814
41315
  if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
40815
- const instance = parsed.data.header.instance;
40816
- if (instance !== "ptz.preset" && instance !== "ptz.pan" && instance !== "ptz.tilt") return errorEnvelope(header, "INVALID_DIRECTIVE", `ModeController instance not supported: ${instance ?? "(missing)"}`);
40817
41316
  const endpointId = parsed.data.endpoint.endpointId;
40818
41317
  const parsedId = parseCameraEndpointId(endpointId);
40819
- if (parsedId.kind !== "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", `ModeController only supported on camera endpoints — got ${endpointId}`);
40820
- const mode = parsed.data.payload.mode;
41318
+ const on = parsed.data.header.name === "TurnOn";
40821
41319
  const api = deps.ctx.api;
40822
- if (instance === "ptz.pan" || instance === "ptz.tilt") {
40823
- const move = (instance === "ptz.pan" ? PTZ_PAN_MOVES : PTZ_TILT_MOVES)[mode];
40824
- if (!move) return errorEnvelope(header, "INVALID_DIRECTIVE", `mode '${mode}' is not a valid ${instance} mode`);
40825
- if (Object.keys(move).length === 0) await api.ptz.stop.mutate({ deviceId: parsedId.deviceId }).catch((err) => {
40826
- deps.logger.debug("alexa ptz-mode: stop (center) failed (non-fatal)", { meta: {
40827
- deviceId: parsedId.deviceId,
40828
- instance,
40829
- error: err instanceof Error ? err.message : String(err)
40830
- } });
40831
- });
40832
- else try {
40833
- await api.ptz.continuousMove.mutate({
40834
- deviceId: parsedId.deviceId,
40835
- ...move
40836
- });
40837
- setTimeout(() => {
40838
- api.ptz.stop.mutate({ deviceId: parsedId.deviceId }).catch((err) => {
40839
- deps.logger.debug("alexa ptz-mode: stop after pulse failed (non-fatal)", { meta: {
40840
- deviceId: parsedId.deviceId,
40841
- instance,
40842
- error: err instanceof Error ? err.message : String(err)
40843
- } });
40844
- });
40845
- }, PTZ_DIRECTION_PULSE_MS);
40846
- } catch (err) {
40847
- return errorEnvelope(header, "INTERNAL_ERROR", `ptz.continuousMove failed: ${err instanceof Error ? err.message : String(err)}`);
40848
- }
40849
- return modeSuccessResponse(header, endpointId, instance, instance === "ptz.pan" ? "ptz.pan.center" : "ptz.tilt.center");
40850
- }
40851
- if (!mode.startsWith(PTZ_PRESET_MODE_PREFIX)) return errorEnvelope(header, "INVALID_DIRECTIVE", `mode '${mode}' is not a ptz.preset mode`);
40852
- const presetName = mode.slice(11);
40853
- if (presetName.length === 0) return errorEnvelope(header, "INVALID_DIRECTIVE", "preset name missing after prefix");
40854
- const preset = (await api.ptz.getPresets.query({ deviceId: parsedId.deviceId })).find((p) => p.name === presetName);
40855
- if (!preset) return errorEnvelope(header, "INVALID_DIRECTIVE", `preset '${presetName}' not found on device ${parsedId.deviceId}`);
40856
- await api.ptz.goToPreset.mutate({
40857
- deviceId: parsedId.deviceId,
40858
- presetId: preset.id
41320
+ if (parsedId.kind === "autotrack") await api.ptzAutotrack.setEnabled.mutate({
41321
+ deviceId: parsedId.parentDeviceId,
41322
+ enabled: on
40859
41323
  });
40860
- return modeSuccessResponse(header, endpointId, "ptz.preset", mode);
40861
- }
40862
- function modeSuccessResponse(header, endpointId, instance, mode) {
41324
+ else if (parsedId.kind === "privacy") await api.privacyMask.setMask.mutate({
41325
+ deviceId: parsedId.parentDeviceId,
41326
+ patch: { enabled: on }
41327
+ });
41328
+ else if (parsedId.kind === "child") await api.switch.setState.mutate({
41329
+ deviceId: parsedId.childDeviceId,
41330
+ on
41331
+ });
41332
+ else if (parsedId.kind === "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", "PowerController is not exposed on camera endpoints — direct the directive at the child accessory");
41333
+ else if (parsedId.kind === "alarm-panel") return errorEnvelope(header, "INVALID_DIRECTIVE", "PowerController is not exposed on alarm-panel endpoints — use Alexa.SecurityPanelController");
41334
+ else return errorEnvelope(header, "INVALID_DIRECTIVE", parsedId.reason);
40863
41335
  return {
40864
41336
  event: {
40865
41337
  header: {
@@ -40873,10 +41345,9 @@ function modeSuccessResponse(header, endpointId, instance, mode) {
40873
41345
  payload: {}
40874
41346
  },
40875
41347
  context: { properties: [{
40876
- namespace: "Alexa.ModeController",
40877
- instance,
40878
- name: "mode",
40879
- value: mode,
41348
+ namespace: "Alexa.PowerController",
41349
+ name: "powerState",
41350
+ value: on ? "ON" : "OFF",
40880
41351
  timeOfSample: (/* @__PURE__ */ new Date()).toISOString(),
40881
41352
  uncertaintyInMilliseconds: 500
40882
41353
  }] }
@@ -40976,133 +41447,99 @@ function successResponse(header, endpointId, toggleState, instance) {
40976
41447
  };
40977
41448
  }
40978
41449
  //#endregion
40979
- //#region src/handlers/power-controller.ts
40980
- /**
40981
- * `Alexa.PowerController/{TurnOn,TurnOff}` handler.
40982
- *
40983
- * Routing decodes the endpoint id:
40984
- * - `${parent}__${child}` → call `switch.setState({deviceId: child, on})`
40985
- * - `${parent}__autotrack` → call `ptzAutotrack.setEnabled({deviceId: parent, enabled})`
40986
- * - `${parent}__privacy` → call `privacyMask.setMask({deviceId: parent, patch: { enabled } })`
40987
- * - `${deviceId}` (bare parent camera) → reject with INVALID_DIRECTIVE
40988
- * (we never expose PowerController on the camera itself).
40989
- *
40990
- * Auth: verify the directive's scope token (same as every other
40991
- * controller).
40992
- */
40993
- var PowerDirectiveSchema = object({
40994
- header: object({
40995
- namespace: literal("Alexa.PowerController"),
40996
- name: _enum(["TurnOn", "TurnOff"])
40997
- }),
40998
- endpoint: EndpointRefSchema
40999
- });
41000
- async function handlePower(header, endpointRaw, deps, _callerIdentity) {
41001
- const parsed = PowerDirectiveSchema.safeParse({
41002
- header: {
41003
- namespace: header.namespace,
41004
- name: header.name
41005
- },
41006
- endpoint: endpointRaw
41007
- });
41008
- if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
41009
- const endpointId = parsed.data.endpoint.endpointId;
41010
- const parsedId = parseCameraEndpointId(endpointId);
41011
- const on = parsed.data.header.name === "TurnOn";
41012
- const api = deps.ctx.api;
41013
- if (parsedId.kind === "autotrack") await api.ptzAutotrack.setEnabled.mutate({
41014
- deviceId: parsedId.parentDeviceId,
41015
- enabled: on
41016
- });
41017
- else if (parsedId.kind === "privacy") await api.privacyMask.setMask.mutate({
41018
- deviceId: parsedId.parentDeviceId,
41019
- patch: { enabled: on }
41020
- });
41021
- else if (parsedId.kind === "child") await api.switch.setState.mutate({
41022
- deviceId: parsedId.childDeviceId,
41023
- on
41024
- });
41025
- else if (parsedId.kind === "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", "PowerController is not exposed on camera endpoints — direct the directive at the child accessory");
41026
- else return errorEnvelope(header, "INVALID_DIRECTIVE", parsedId.reason);
41027
- return {
41028
- event: {
41029
- header: {
41030
- namespace: "Alexa",
41031
- name: "Response",
41032
- messageId: header.messageId,
41033
- correlationToken: header.correlationToken,
41034
- payloadVersion: "3"
41035
- },
41036
- endpoint: { endpointId },
41037
- payload: {}
41038
- },
41039
- context: { properties: [{
41040
- namespace: "Alexa.PowerController",
41041
- name: "powerState",
41042
- value: on ? "ON" : "OFF",
41043
- timeOfSample: (/* @__PURE__ */ new Date()).toISOString(),
41044
- uncertaintyInMilliseconds: 500
41045
- }] }
41046
- };
41047
- }
41048
- //#endregion
41049
- //#region src/handlers/brightness-controller.ts
41450
+ //#region src/handlers/ptz-preset.ts
41050
41451
  /**
41051
- * `Alexa.BrightnessController/SetBrightness` handler.
41452
+ * `Alexa.ModeController/SetMode` handler — dispatches three PTZ instances:
41052
41453
  *
41053
- * The Discovery handler declares `Alexa.BrightnessController` only on
41054
- * child accessory endpoints that bind the `brightness` cap (today:
41055
- * Reolink floodlights, Hikvision supplemental lights). Brightness is
41056
- * NEVER exposed on the parent camera endpoint or on the synthetic
41057
- * autotrack endpoint — both reject INVALID_DIRECTIVE here.
41454
+ * `ptz.preset` — preset-recall. Decodes the preset name from the mode
41455
+ * value and calls `ptz.goToPreset({deviceId, presetId})`.
41058
41456
  *
41059
- * Routing:
41060
- * - `${parent}__${child}` → `brightness.setBrightness({deviceId: child, percentage})`
41457
+ * `ptz.pan` — momentary pan. `ptz.pan.left|right|center` issues a
41458
+ * continuousMove pulse stopped on a timer; the dropdown reverts to
41459
+ * `center` server-side so subsequent picks re-trigger the move.
41061
41460
  *
41062
- * Auth: same scope-token verification path as the other controllers.
41063
- * The response carries the `Alexa.BrightnessController.brightness`
41064
- * property echoing the new level so the Echo updates its UI without an
41065
- * extra ReportState round-trip.
41461
+ * `ptz.tilt` — momentary tilt. Mirrors ptz.pan with up|down|center.
41066
41462
  */
41067
- var SetBrightnessDirectiveSchema = object({
41463
+ var SetModeDirectiveSchema = object({
41068
41464
  header: object({
41069
- namespace: literal("Alexa.BrightnessController"),
41070
- name: literal("SetBrightness")
41465
+ namespace: literal("Alexa.ModeController"),
41466
+ name: literal("SetMode"),
41467
+ instance: string().optional()
41071
41468
  }),
41072
41469
  endpoint: EndpointRefSchema,
41073
- payload: object({ brightness: number().min(0).max(100) })
41470
+ payload: SetModePayloadSchema
41074
41471
  });
41075
- async function handleSetBrightness(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41076
- const parsed = SetBrightnessDirectiveSchema.safeParse({
41472
+ var PTZ_PRESET_MODE_PREFIX = "ptz.preset.";
41473
+ var PTZ_DIRECTION_PULSE_MS = 1e3;
41474
+ var PTZ_PAN_MOVES = {
41475
+ "ptz.pan.left": { pan: -1 },
41476
+ "ptz.pan.right": { pan: 1 },
41477
+ "ptz.pan.center": {}
41478
+ };
41479
+ var PTZ_TILT_MOVES = {
41480
+ "ptz.tilt.up": { tilt: 1 },
41481
+ "ptz.tilt.down": { tilt: -1 },
41482
+ "ptz.tilt.center": {}
41483
+ };
41484
+ async function handleSetMode(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41485
+ const parsed = SetModeDirectiveSchema.safeParse({
41077
41486
  header: {
41078
41487
  namespace: header.namespace,
41079
- name: header.name
41488
+ name: header.name,
41489
+ instance: header.instance
41080
41490
  },
41081
41491
  endpoint: endpointRaw,
41082
41492
  payload: payloadRaw ?? {}
41083
41493
  });
41084
41494
  if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
41495
+ const instance = parsed.data.header.instance;
41496
+ if (instance !== "ptz.preset" && instance !== "ptz.pan" && instance !== "ptz.tilt") return errorEnvelope(header, "INVALID_DIRECTIVE", `ModeController instance not supported: ${instance ?? "(missing)"}`);
41085
41497
  const endpointId = parsed.data.endpoint.endpointId;
41086
41498
  const parsedId = parseCameraEndpointId(endpointId);
41087
- if (parsedId.kind === "autotrack" || parsedId.kind === "privacy") return errorEnvelope(header, "INVALID_DIRECTIVE", `BrightnessController is not exposed on the ${parsedId.kind} endpoint`);
41088
- if (parsedId.kind === "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", "BrightnessController is not exposed on camera endpoints — direct the directive at the dimmable child accessory");
41089
- if (parsedId.kind === "invalid") return errorEnvelope(header, "INVALID_DIRECTIVE", parsedId.reason);
41090
- const percentage = parsed.data.payload.brightness;
41499
+ if (parsedId.kind !== "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", `ModeController only supported on camera endpoints — got ${endpointId}`);
41500
+ const mode = parsed.data.payload.mode;
41091
41501
  const api = deps.ctx.api;
41092
- try {
41093
- await api.brightness.setBrightness.mutate({
41094
- deviceId: parsedId.childDeviceId,
41095
- percentage
41502
+ if (instance === "ptz.pan" || instance === "ptz.tilt") {
41503
+ const move = (instance === "ptz.pan" ? PTZ_PAN_MOVES : PTZ_TILT_MOVES)[mode];
41504
+ if (!move) return errorEnvelope(header, "INVALID_DIRECTIVE", `mode '${mode}' is not a valid ${instance} mode`);
41505
+ if (Object.keys(move).length === 0) await api.ptz.stop.mutate({ deviceId: parsedId.deviceId }).catch((err) => {
41506
+ deps.logger.debug("alexa ptz-mode: stop (center) failed (non-fatal)", { meta: {
41507
+ deviceId: parsedId.deviceId,
41508
+ instance,
41509
+ error: err instanceof Error ? err.message : String(err)
41510
+ } });
41096
41511
  });
41097
- } catch (err) {
41098
- const message = err instanceof Error ? err.message : String(err);
41099
- deps.logger.warn("alexa brightness-controller: setBrightness failed", { meta: {
41100
- deviceId: parsedId.childDeviceId,
41101
- percentage,
41102
- error: message
41103
- } });
41104
- return errorEnvelope(header, "INTERNAL_ERROR", `brightness.setBrightness failed: ${message}`);
41512
+ else try {
41513
+ await api.ptz.continuousMove.mutate({
41514
+ deviceId: parsedId.deviceId,
41515
+ ...move
41516
+ });
41517
+ setTimeout(() => {
41518
+ api.ptz.stop.mutate({ deviceId: parsedId.deviceId }).catch((err) => {
41519
+ deps.logger.debug("alexa ptz-mode: stop after pulse failed (non-fatal)", { meta: {
41520
+ deviceId: parsedId.deviceId,
41521
+ instance,
41522
+ error: err instanceof Error ? err.message : String(err)
41523
+ } });
41524
+ });
41525
+ }, PTZ_DIRECTION_PULSE_MS);
41526
+ } catch (err) {
41527
+ return errorEnvelope(header, "INTERNAL_ERROR", `ptz.continuousMove failed: ${err instanceof Error ? err.message : String(err)}`);
41528
+ }
41529
+ return modeSuccessResponse(header, endpointId, instance, instance === "ptz.pan" ? "ptz.pan.center" : "ptz.tilt.center");
41105
41530
  }
41531
+ if (!mode.startsWith(PTZ_PRESET_MODE_PREFIX)) return errorEnvelope(header, "INVALID_DIRECTIVE", `mode '${mode}' is not a ptz.preset mode`);
41532
+ const presetName = mode.slice(11);
41533
+ if (presetName.length === 0) return errorEnvelope(header, "INVALID_DIRECTIVE", "preset name missing after prefix");
41534
+ const preset = (await api.ptz.getPresets.query({ deviceId: parsedId.deviceId })).find((p) => p.name === presetName);
41535
+ if (!preset) return errorEnvelope(header, "INVALID_DIRECTIVE", `preset '${presetName}' not found on device ${parsedId.deviceId}`);
41536
+ await api.ptz.goToPreset.mutate({
41537
+ deviceId: parsedId.deviceId,
41538
+ presetId: preset.id
41539
+ });
41540
+ return modeSuccessResponse(header, endpointId, "ptz.preset", mode);
41541
+ }
41542
+ function modeSuccessResponse(header, endpointId, instance, mode) {
41106
41543
  return {
41107
41544
  event: {
41108
41545
  header: {
@@ -41116,9 +41553,10 @@ async function handleSetBrightness(header, endpointRaw, payloadRaw, deps, _calle
41116
41553
  payload: {}
41117
41554
  },
41118
41555
  context: { properties: [{
41119
- namespace: "Alexa.BrightnessController",
41120
- name: "brightness",
41121
- value: percentage,
41556
+ namespace: "Alexa.ModeController",
41557
+ instance,
41558
+ name: "mode",
41559
+ value: mode,
41122
41560
  timeOfSample: (/* @__PURE__ */ new Date()).toISOString(),
41123
41561
  uncertaintyInMilliseconds: 500
41124
41562
  }] }
@@ -41139,6 +41577,7 @@ async function handleReportState(header, endpointRaw, deps, _callerIdentity) {
41139
41577
  else if (parsed.kind === "privacy") await collectPrivacyProperties(api, parsed.parentDeviceId, properties, nowIso, deps.logger);
41140
41578
  else if (parsed.kind === "autotrack") await collectAutotrackProperties(api, parsed.parentDeviceId, properties, nowIso, deps.logger);
41141
41579
  else if (parsed.kind === "child") await collectChildProperties(api, parsed.childDeviceId, properties, nowIso, deps.logger);
41580
+ else if (parsed.kind === "alarm-panel") await collectAlarmPanelProperties(api, parsed.deviceId, properties, nowIso, deps.logger);
41142
41581
  } catch (err) {
41143
41582
  deps.logger.warn("alexa report-state: collection failed", { meta: {
41144
41583
  endpointId,
@@ -41200,6 +41639,42 @@ async function collectCameraProperties(api, deviceId, properties, timeOfSample,
41200
41639
  uncertaintyInMilliseconds: 0
41201
41640
  });
41202
41641
  }
41642
+ /**
41643
+ * The panel's two declared properties.
41644
+ *
41645
+ * Both are omitted when the panel cannot be read — an `armState` we guessed
41646
+ * would be a claim about whether a house is locked, and Alexa rendering the
41647
+ * endpoint as unavailable is the truthful outcome of a panel nobody reached.
41648
+ * The failure is logged with the device id, never swallowed.
41649
+ */
41650
+ async function collectAlarmPanelProperties(api, deviceId, properties, timeOfSample, logger) {
41651
+ const status = await api.alarmPanel.getStatus.query({ deviceId }).catch((err) => {
41652
+ logger.warn("alexa report-state: alarmPanel.getStatus FAILED — Alexa will show the panel as unavailable", {
41653
+ tags: { deviceId },
41654
+ meta: { error: err instanceof Error ? err.message : String(err) }
41655
+ });
41656
+ return null;
41657
+ });
41658
+ const parsed = AlarmPanelStatusSchema.pick({ state: true }).safeParse(status);
41659
+ if (!parsed.success) {
41660
+ if (status !== null) logger.warn("alexa report-state: panel status did not match the cap schema — omitting", { tags: { deviceId } });
41661
+ return;
41662
+ }
41663
+ properties.push({
41664
+ namespace: "Alexa.SecurityPanelController",
41665
+ name: "armState",
41666
+ value: alexaArmStateFor(parsed.data.state),
41667
+ timeOfSample,
41668
+ uncertaintyInMilliseconds: 0
41669
+ });
41670
+ properties.push({
41671
+ namespace: "Alexa.SecurityPanelController",
41672
+ name: "burglaryAlarm",
41673
+ value: burglaryAlarmFor(parsed.data.state),
41674
+ timeOfSample,
41675
+ uncertaintyInMilliseconds: 0
41676
+ });
41677
+ }
41203
41678
  async function collectPrivacyProperties(api, parentDeviceId, properties, timeOfSample, _logger) {
41204
41679
  const status = await api.privacyMask.getStatus.query({ deviceId: parentDeviceId }).catch(() => null);
41205
41680
  const enabled = Boolean(status?.enabled);
@@ -41253,6 +41728,230 @@ async function collectChildProperties(api, childDeviceId, properties, timeOfSamp
41253
41728
  });
41254
41729
  }
41255
41730
  //#endregion
41731
+ //#region src/handlers/security-panel.ts
41732
+ var ArmPayloadSchema = object({ armState: _enum([
41733
+ "ARMED_STAY",
41734
+ "ARMED_AWAY",
41735
+ "ARMED_NIGHT"
41736
+ ]) });
41737
+ var DisarmPayloadSchema = object({ authorization: object({
41738
+ type: literal("FOUR_DIGIT_PIN"),
41739
+ value: string().min(1)
41740
+ }).optional() });
41741
+ /** The subset of the panel status the directives read. */
41742
+ var PanelReadSchema = AlarmPanelStatusSchema.pick({
41743
+ state: true,
41744
+ availableModes: true,
41745
+ requiresCode: true
41746
+ });
41747
+ /**
41748
+ * `Alexa.SecurityPanelController.ErrorResponse`.
41749
+ *
41750
+ * A namespace of its own, because the four types that matter here
41751
+ * (`AUTHORIZATION_REQUIRED`, `UNAUTHORIZED`, `NOT_READY_FOR_ARM`,
41752
+ * `BYPASS_NEEDED`) are only understood under it — the generic `Alexa`
41753
+ * `ErrorResponse` from `error-envelope.ts` carries none of them, and a PIN
41754
+ * problem reported there is a message the Alexa app cannot act on.
41755
+ */
41756
+ function securityPanelError(header, type, message) {
41757
+ return { event: {
41758
+ header: {
41759
+ namespace: "Alexa.SecurityPanelController",
41760
+ name: "ErrorResponse",
41761
+ messageId: header.messageId,
41762
+ correlationToken: header.correlationToken,
41763
+ payloadVersion: "3"
41764
+ },
41765
+ payload: {
41766
+ type,
41767
+ message
41768
+ }
41769
+ } };
41770
+ }
41771
+ /** Resolve the alarm panel this directive targets, or the refusal to send. */
41772
+ function resolveDeviceId(endpointRaw) {
41773
+ const parsedEndpoint = EndpointRefSchema.safeParse(endpointRaw);
41774
+ if (!parsedEndpoint.success) return { reason: "missing or malformed endpoint" };
41775
+ const parsedId = parseCameraEndpointId(parsedEndpoint.data.endpointId);
41776
+ if (parsedId.kind === "alarm-panel") return { deviceId: parsedId.deviceId };
41777
+ return { reason: `SecurityPanelController is only exposed on alarm-panel endpoints — got '${parsedEndpoint.data.endpointId}'` };
41778
+ }
41779
+ /**
41780
+ * What the panel currently accepts, or `null` when it could not be read.
41781
+ *
41782
+ * `null` is the honest answer and the callers treat it as unknown; nothing
41783
+ * here substitutes a default that would read as "accepts nothing, needs no
41784
+ * PIN".
41785
+ */
41786
+ async function readPanel(api, deviceId, logger, phase) {
41787
+ const raw = await api.alarmPanel.getStatus.query({ deviceId }).catch((err) => {
41788
+ logger.warn("alexa security-panel: alarmPanel.getStatus failed — proceeding without it", {
41789
+ tags: { deviceId },
41790
+ meta: {
41791
+ phase,
41792
+ error: err instanceof Error ? err.message : String(err)
41793
+ }
41794
+ });
41795
+ return null;
41796
+ });
41797
+ const parsed = PanelReadSchema.safeParse(raw);
41798
+ if (!parsed.success) {
41799
+ if (raw !== null) logger.warn("alexa security-panel: panel status did not match the cap schema", {
41800
+ tags: { deviceId },
41801
+ meta: { phase }
41802
+ });
41803
+ return null;
41804
+ }
41805
+ return parsed.data;
41806
+ }
41807
+ /** The `context.properties` block for a panel whose state we re-read. */
41808
+ function panelProperties(facts, fallback) {
41809
+ const timeOfSample = (/* @__PURE__ */ new Date()).toISOString();
41810
+ const parsedState = facts === null ? null : AlarmPanelStatusSchema.shape.state.parse(facts.state);
41811
+ const armState = parsedState === null ? fallback : alexaArmStateFor(parsedState);
41812
+ const burglary = parsedState === null ? { value: "OK" } : burglaryAlarmFor(parsedState);
41813
+ return [{
41814
+ namespace: "Alexa.SecurityPanelController",
41815
+ name: "armState",
41816
+ value: armState,
41817
+ timeOfSample,
41818
+ uncertaintyInMilliseconds: 0
41819
+ }, {
41820
+ namespace: "Alexa.SecurityPanelController",
41821
+ name: "burglaryAlarm",
41822
+ value: burglary,
41823
+ timeOfSample,
41824
+ uncertaintyInMilliseconds: 0
41825
+ }];
41826
+ }
41827
+ async function handleArm(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41828
+ const target = resolveDeviceId(endpointRaw);
41829
+ if (!("deviceId" in target)) return errorEnvelope(header, "INVALID_DIRECTIVE", target.reason);
41830
+ const { deviceId } = target;
41831
+ const payload = ArmPayloadSchema.safeParse(payloadRaw);
41832
+ if (!payload.success) {
41833
+ deps.logger.warn("alexa security-panel: Arm payload is not an arm state Alexa defines", {
41834
+ tags: { deviceId },
41835
+ meta: { error: payload.error.message }
41836
+ });
41837
+ return errorEnvelope(header, "INVALID_DIRECTIVE", `Arm payload unexpected: ${payload.error.message}`);
41838
+ }
41839
+ const requested = payload.data.armState;
41840
+ const api = deps.ctx.api;
41841
+ const facts = await readPanel(api, deviceId, deps.logger, "arm");
41842
+ if (facts?.requiresCode === true) {
41843
+ deps.logger.warn("alexa security-panel: panel requires a PIN and the Arm directive carries none — REFUSED", {
41844
+ tags: { deviceId },
41845
+ meta: { requested }
41846
+ });
41847
+ return securityPanelError(header, "AUTHORIZATION_REQUIRED", "this panel requires a PIN to arm, and Alexa cannot supply one on an Arm directive");
41848
+ }
41849
+ const mode = alarmArmModeForAlexa(requested, facts?.availableModes ?? []);
41850
+ if (mode === null) {
41851
+ deps.logger.warn("alexa security-panel: panel accepts no mode for this arm state — REFUSED", {
41852
+ tags: { deviceId },
41853
+ meta: {
41854
+ requested,
41855
+ availableModes: facts?.availableModes ?? null
41856
+ }
41857
+ });
41858
+ return securityPanelError(header, "NOT_READY_FOR_ARM", `panel does not accept ${requested}`);
41859
+ }
41860
+ try {
41861
+ await api.alarmPanel.arm.mutate({
41862
+ deviceId,
41863
+ mode
41864
+ });
41865
+ } catch (err) {
41866
+ deps.logger.warn("alexa security-panel: arm command failed", {
41867
+ tags: { deviceId },
41868
+ meta: {
41869
+ requested,
41870
+ mode,
41871
+ error: err instanceof Error ? err.message : String(err)
41872
+ }
41873
+ });
41874
+ return securityPanelError(header, "NOT_READY_FOR_ARM", err instanceof Error ? err.message : String(err));
41875
+ }
41876
+ deps.logger.info("alexa security-panel: armed", {
41877
+ tags: { deviceId },
41878
+ meta: {
41879
+ requested,
41880
+ mode
41881
+ }
41882
+ });
41883
+ const after = await readPanel(api, deviceId, deps.logger, "arm-confirm");
41884
+ if (after?.state === "arming") deps.logger.info("alexa security-panel: panel is in its exit delay — reporting DISARMED until it is set", {
41885
+ tags: { deviceId },
41886
+ meta: {
41887
+ requested,
41888
+ mode
41889
+ }
41890
+ });
41891
+ return {
41892
+ event: {
41893
+ header: {
41894
+ namespace: "Alexa.SecurityPanelController",
41895
+ name: "Arm.Response",
41896
+ messageId: header.messageId,
41897
+ correlationToken: header.correlationToken,
41898
+ payloadVersion: "3"
41899
+ },
41900
+ endpoint: { endpointId: `${deviceId}__alarm` },
41901
+ payload: {}
41902
+ },
41903
+ context: { properties: panelProperties(after, requested) }
41904
+ };
41905
+ }
41906
+ async function handleDisarm(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41907
+ const target = resolveDeviceId(endpointRaw);
41908
+ if (!("deviceId" in target)) return errorEnvelope(header, "INVALID_DIRECTIVE", target.reason);
41909
+ const { deviceId } = target;
41910
+ const payload = DisarmPayloadSchema.safeParse(payloadRaw ?? {});
41911
+ if (!payload.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `Disarm payload unexpected: ${payload.error.message}`);
41912
+ const code = payload.data.authorization?.value;
41913
+ const api = deps.ctx.api;
41914
+ if ((await readPanel(api, deviceId, deps.logger, "disarm"))?.requiresCode === true && code === void 0) {
41915
+ deps.logger.warn("alexa security-panel: panel requires a PIN and the Disarm directive carried none — REFUSED", { tags: { deviceId } });
41916
+ return securityPanelError(header, "AUTHORIZATION_REQUIRED", "this panel requires a PIN to disarm");
41917
+ }
41918
+ try {
41919
+ await api.alarmPanel.disarm.mutate(code === void 0 ? { deviceId } : {
41920
+ deviceId,
41921
+ code
41922
+ });
41923
+ } catch (err) {
41924
+ const message = err instanceof Error ? err.message : String(err);
41925
+ deps.logger.warn("alexa security-panel: disarm command failed", {
41926
+ tags: { deviceId },
41927
+ meta: {
41928
+ codeSupplied: code !== void 0,
41929
+ error: message
41930
+ }
41931
+ });
41932
+ return code === void 0 ? errorEnvelope(header, "INTERNAL_ERROR", message) : securityPanelError(header, "UNAUTHORIZED", message);
41933
+ }
41934
+ deps.logger.info("alexa security-panel: disarmed", {
41935
+ tags: { deviceId },
41936
+ meta: { codeSupplied: code !== void 0 }
41937
+ });
41938
+ const after = await readPanel(api, deviceId, deps.logger, "disarm-confirm");
41939
+ return {
41940
+ event: {
41941
+ header: {
41942
+ namespace: "Alexa",
41943
+ name: "Response",
41944
+ messageId: header.messageId,
41945
+ correlationToken: header.correlationToken,
41946
+ payloadVersion: "3"
41947
+ },
41948
+ endpoint: { endpointId: `${deviceId}__alarm` },
41949
+ payload: {}
41950
+ },
41951
+ context: { properties: panelProperties(after, "DISARMED") }
41952
+ };
41953
+ }
41954
+ //#endregion
41256
41955
  //#region src/handlers/stubs.ts
41257
41956
  /**
41258
41957
  * Stub responder for namespaces not yet implemented (CameraStream /
@@ -41332,7 +42031,9 @@ async function dispatchDirective(rawBody, deps, callerIdentity) {
41332
42031
  "Alexa.ModeController/SetMode": "create",
41333
42032
  "Alexa.ToggleController/TurnOn": "create",
41334
42033
  "Alexa.ToggleController/TurnOff": "create",
41335
- "Alexa/ReportState": "view"
42034
+ "Alexa/ReportState": "view",
42035
+ "Alexa.SecurityPanelController/Arm": "create",
42036
+ "Alexa.SecurityPanelController/Disarm": "create"
41336
42037
  };
41337
42038
  try {
41338
42039
  const key = `${header.namespace}/${header.name}`;
@@ -41377,6 +42078,14 @@ async function dispatchDirective(rawBody, deps, callerIdentity) {
41377
42078
  status: 200,
41378
42079
  body: await handlePtzDirection(header, endpoint, deps.ptzDirection, callerIdentity)
41379
42080
  };
42081
+ if (key === "Alexa.SecurityPanelController/Arm") return {
42082
+ status: 200,
42083
+ body: await handleArm(header, endpoint, payload, deps.securityPanel, callerIdentity)
42084
+ };
42085
+ if (key === "Alexa.SecurityPanelController/Disarm") return {
42086
+ status: 200,
42087
+ body: await handleDisarm(header, endpoint, payload, deps.securityPanel, callerIdentity)
42088
+ };
41380
42089
  if (key === "Alexa/ReportState") return {
41381
42090
  status: 200,
41382
42091
  body: await handleReportState(header, endpoint, deps.reportState, callerIdentity)
@@ -42933,7 +43642,13 @@ var DEFAULT_CONFIG = {
42933
43642
  enforceIngressToken: false,
42934
43643
  staleEndpointPurgeInput: ""
42935
43644
  };
42936
- var SUPPORTED_KINDS = ["camera", "doorbell"];
43645
+ /** UI filter for the Export picker. `alarm-panel` publishes an
43646
+ * `Alexa.SecurityPanelController` endpoint (`endpoints/builder.ts`). */
43647
+ var SUPPORTED_KINDS = [
43648
+ "camera",
43649
+ "doorbell",
43650
+ DeviceType.AlarmPanel
43651
+ ];
42937
43652
  var ExportAlexaAddon = class extends BaseAddon {
42938
43653
  lwaGateway = null;
42939
43654
  syncEngine = null;
@@ -43002,6 +43717,10 @@ var ExportAlexaAddon = class extends BaseAddon {
43002
43717
  reportState: {
43003
43718
  ctx: this.ctx,
43004
43719
  logger: this.ctx.logger
43720
+ },
43721
+ securityPanel: {
43722
+ ctx: this.ctx,
43723
+ logger: this.ctx.logger
43005
43724
  }
43006
43725
  },
43007
43726
  lwaTokensCallbackDeps: {
@@ -43056,6 +43775,11 @@ var ExportAlexaAddon = class extends BaseAddon {
43056
43775
  });
43057
43776
  });
43058
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));
43059
43783
  this.ctx.logger.info("export-alexa: initialized", { meta: {
43060
43784
  exposedCount: this.config.exposed.length,
43061
43785
  skillMode: this.config.skillMode,
@@ -43710,6 +44434,37 @@ var ExportAlexaAddon = class extends BaseAddon {
43710
44434
  ]
43711
44435
  }] });
43712
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
+ }
43713
44468
  async buildDeviceSettingsContribution(deviceId) {
43714
44469
  if (!await this.isCameraDevice(deviceId)) return null;
43715
44470
  const entry = this.findEntry(deviceId);
@@ -43717,6 +44472,7 @@ var ExportAlexaAddon = class extends BaseAddon {
43717
44472
  const enabled = entry !== null;
43718
44473
  const enabledKey = `alexa:${deviceId}:enabled`;
43719
44474
  const streamPreferenceKey = `alexa:${deviceId}:streamPreference`;
44475
+ const allowTranscodeKey = `alexa:${deviceId}:allowTranscode`;
43720
44476
  const linkedCount = this.config.linkedAccounts.length;
43721
44477
  return {
43722
44478
  tabs: [{
@@ -43762,6 +44518,19 @@ var ExportAlexaAddon = class extends BaseAddon {
43762
44518
  equals: true
43763
44519
  },
43764
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
43765
44534
  }
43766
44535
  ]
43767
44536
  }]
@@ -43781,26 +44550,17 @@ var ExportAlexaAddon = class extends BaseAddon {
43781
44550
  const idStr = String(deviceId);
43782
44551
  const current = this.findEntry(deviceId);
43783
44552
  const wasEnabled = current !== null;
43784
- const sourceProfileKey = `alexa:${deviceId}:sourceProfile`;
43785
- if (sourceProfileKey in patch) {
43786
- if (!wasEnabled) return { success: true };
43787
- const currentSettings = current?.settings ?? DEFAULT_DEVICE_SETTINGS;
43788
- const sourceProfileRaw = patch[sourceProfileKey];
43789
- const sourceProfile = sourceProfileRaw === "mid" ? "mid" : sourceProfileRaw === "low" ? "low" : "high";
43790
- await this.patchEntrySettings(deviceId, {
43791
- ...currentSettings,
43792
- sourceProfile
43793
- });
43794
- return { success: true };
43795
- }
43796
44553
  const enabledKey = `alexa:${deviceId}:enabled`;
43797
44554
  const streamPreferenceKey = `alexa:${deviceId}:streamPreference`;
44555
+ const allowTranscodeKey = `alexa:${deviceId}:allowTranscode`;
43798
44556
  const enabledValue = enabledKey in patch ? Boolean(patch[enabledKey]) : wasEnabled;
43799
44557
  const streamPreferenceRaw = streamPreferenceKey in patch ? patch[streamPreferenceKey] : current?.settings?.streamPreference;
43800
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;
43801
44560
  const nextSettings = {
43802
44561
  ...current?.settings ?? DEFAULT_DEVICE_SETTINGS,
43803
- streamPreference
44562
+ streamPreference,
44563
+ allowTranscode
43804
44564
  };
43805
44565
  if (!enabledValue) {
43806
44566
  if (wasEnabled) await this.unexposeDevice(idStr);
@@ -43812,13 +44572,22 @@ var ExportAlexaAddon = class extends BaseAddon {
43812
44572
  return { success: true };
43813
44573
  }
43814
44574
  const currentPref = current?.settings?.streamPreference ?? "auto";
44575
+ const currentAllow = current?.settings?.allowTranscode !== false;
43815
44576
  await this.patchEntrySettings(deviceId, nextSettings);
43816
- if (currentPref !== streamPreference) {
43817
- this.ctx.logger.info("export-alexa: streamPreference changed — refreshing exposure", { meta: {
43818
- deviceId,
43819
- from: currentPref,
43820
- to: streamPreference
43821
- } });
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
+ });
43822
44591
  try {
43823
44592
  await this.unexposeDevice(idStr);
43824
44593
  await this.exposeDevice(idStr);