@camstack/addon-export-alexa 1.2.107 → 1.2.108

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.
@@ -7515,7 +7515,23 @@ var EncodeProfileSchema = object({
7515
7515
  "zerolatency",
7516
7516
  "film",
7517
7517
  "animation"
7518
- ]).optional()
7518
+ ]).optional(),
7519
+ /**
7520
+ * ONE slice per access unit.
7521
+ *
7522
+ * `-tune zerolatency` turns on x264's sliced threads, and a frame then leaves
7523
+ * the encoder as five NAL slices that share one RTP timestamp and carry one
7524
+ * marker bit. A libwebrtc depacketiser sees five frame-starts and one
7525
+ * frame-end per frame: the first pictures render and the video then freezes
7526
+ * for good while the audio, on its own plane, plays on. Measured on this hub
7527
+ * 2026-09-13 against the Echo, and reduced to one slice by this flag alone.
7528
+ *
7529
+ * A NAMED field and not a raw flag, because {@link EgressEncodeSchema} omits
7530
+ * `outputArgs` on purpose: an opaque array is part of the sharing key, so two
7531
+ * consumers meaning the same thing spelled differently would stop sharing one
7532
+ * child. Absent means "whatever the encoder does" — today's behaviour.
7533
+ */
7534
+ singleSlicePerFrame: boolean().optional()
7519
7535
  }),
7520
7536
  audio: union([literal("passthrough"), object({
7521
7537
  codec: _enum([
@@ -7591,31 +7607,10 @@ var BASE_LIVE_EGRESS_PROFILE = {
7591
7607
  var ALEXA_EGRESS_PROFILE = {
7592
7608
  ...BASE_LIVE_EGRESS_PROFILE,
7593
7609
  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"]
7610
+ video: {
7611
+ ...BASE_LIVE_EGRESS_PROFILE.video,
7612
+ singleSlicePerFrame: true
7613
+ }
7619
7614
  };
7620
7615
  /**
7621
7616
  * Deep wiring healthcheck — snapshot of active reachability probes across
@@ -16503,7 +16498,7 @@ var AlarmArmModeSchema = _enum([
16503
16498
  "vacation",
16504
16499
  "custom_bypass"
16505
16500
  ]);
16506
- object({
16501
+ var AlarmPanelStatusSchema = object({
16507
16502
  /** Current lifecycle state. */
16508
16503
  state: AlarmStateSchema,
16509
16504
  /** Subset of arm modes the panel accepts. UI renders one button per
@@ -39791,66 +39786,65 @@ async function releaseAlexaEgress(input) {
39791
39786
  }
39792
39787
  }
39793
39788
  //#endregion
39794
- //#region src/handlers/types.ts
39789
+ //#region src/handlers/security-panel-arm-state.ts
39795
39790
  /**
39796
- * Zod schemas for the subset of the Alexa Smart Home directive surface
39797
- * that we actually parse hub-side. The Smart Home Skill API ships
39798
- * thousands of optional fields per namespace — we only validate what
39799
- * we read; everything else passes through as `unknown`.
39791
+ * The panel modes behind each Alexa arm state, PRIMARY first — the mirror of
39792
+ * `MODES_BY_TARGET` in the HomeKit exporter, and for the same reason: one
39793
+ * Alexa state stands for two panel modes, so a panel offering only the
39794
+ * secondary would otherwise be sent a mode it refuses.
39795
+ */
39796
+ var MODES_BY_ARM_STATE = {
39797
+ ARMED_STAY: ["home", "custom_bypass"],
39798
+ ARMED_AWAY: ["away", "vacation"],
39799
+ ARMED_NIGHT: ["night"]
39800
+ };
39801
+ var ARM_STATES = [
39802
+ "ARMED_STAY",
39803
+ "ARMED_AWAY",
39804
+ "ARMED_NIGHT"
39805
+ ];
39806
+ /** The panel's state as Alexa's `armState` property. */
39807
+ function alexaArmStateFor(state) {
39808
+ switch (state) {
39809
+ case "armed_home":
39810
+ case "armed_custom_bypass": return "ARMED_STAY";
39811
+ case "armed_night": return "ARMED_NIGHT";
39812
+ case "armed_away":
39813
+ case "armed_vacation":
39814
+ case "pending":
39815
+ case "triggered": return "ARMED_AWAY";
39816
+ default: return "DISARMED";
39817
+ }
39818
+ }
39819
+ /** `burglaryAlarm`, the only alarm property this cap can honestly fill. */
39820
+ function burglaryAlarmFor(state) {
39821
+ return { value: state === "triggered" ? "ALARM" : "OK" };
39822
+ }
39823
+ /**
39824
+ * The `supportedArmStates` for discovery.
39800
39825
  *
39801
- * Reference: https://developer.amazon.com/en-US/docs/alexa/smarthome/smart-home-skill-api-message-reference.html
39826
+ * `DISARMED` is always present: disarming is not one of the panel's arm modes.
39827
+ * An EMPTY `availableModes` is unknown, not "none" — a provider that never
39828
+ * populated the list looks identical to one that accepts nothing, and
39829
+ * publishing a panel that can only be disarmed on that guess takes the
39830
+ * controls off a working alarm. The caller logs it.
39802
39831
  */
39803
- /** A directive header carries namespace + name + token + correlation id. */
39804
- var DirectiveHeaderSchema = object({
39805
- namespace: string(),
39806
- name: string(),
39807
- payloadVersion: string(),
39808
- messageId: string(),
39809
- correlationToken: string().optional()
39810
- });
39811
- /** Scope carries the bearer token Alexa minted via our OAuth provider. */
39812
- var BearerScopeSchema = object({
39813
- type: literal("BearerToken"),
39814
- token: string()
39815
- });
39816
- /** Endpoint reference inside a directive payload. */
39817
- var EndpointRefSchema = object({
39818
- endpointId: string(),
39819
- scope: BearerScopeSchema.optional(),
39820
- cookie: record(string(), string()).optional()
39821
- });
39822
- var DiscoveryDirectiveSchema = object({
39823
- header: DirectiveHeaderSchema.extend({
39824
- namespace: literal("Alexa.Discovery"),
39825
- name: literal("Discover")
39826
- }),
39827
- payload: object({ scope: BearerScopeSchema })
39828
- });
39829
- /** Envelope wrapping a directive on the Alexa→skill wire. */
39830
- var DirectiveRequestSchema = object({ directive: object({
39831
- header: DirectiveHeaderSchema,
39832
- endpoint: EndpointRefSchema.optional(),
39833
- payload: unknown().optional()
39834
- }) });
39835
- var InitializeCameraStreamsPayloadSchema = object({ cameraStreams: array(object({
39836
- protocol: string(),
39837
- resolution: object({
39838
- width: number(),
39839
- height: number()
39840
- }).optional(),
39841
- authorizationType: string().optional(),
39842
- videoCodec: string().optional(),
39843
- audioCodec: string().optional()
39844
- })).optional() });
39845
- var InitiateSessionWithOfferPayloadSchema = object({
39846
- sessionId: string(),
39847
- offer: object({
39848
- format: string().optional(),
39849
- value: string()
39850
- })
39851
- });
39852
- var SessionDisconnectedPayloadSchema = object({ sessionId: string() });
39853
- var SetModePayloadSchema = object({ mode: string() });
39832
+ function supportedArmStatesFor(availableModes) {
39833
+ return [...availableModes.length === 0 ? ARM_STATES : ARM_STATES.filter((armState) => MODES_BY_ARM_STATE[armState].some((mode) => availableModes.includes(mode))), "DISARMED"];
39834
+ }
39835
+ /**
39836
+ * The arm mode to send for an Alexa arm state, or `null` when there is none.
39837
+ *
39838
+ * `null` is not a shrug: `DISARMED` is the Disarm DIRECTIVE, a different call,
39839
+ * and an arm state the panel accepts no mode for is a directive the handler
39840
+ * refuses with `NOT_READY_FOR_ARM` rather than translating into a guess.
39841
+ */
39842
+ function alarmArmModeForAlexa(armState, availableModes) {
39843
+ if (armState === "DISARMED") return null;
39844
+ const candidates = MODES_BY_ARM_STATE[armState];
39845
+ if (availableModes.length === 0) return candidates[0] ?? null;
39846
+ return candidates.find((mode) => availableModes.includes(mode)) ?? null;
39847
+ }
39854
39848
  //#endregion
39855
39849
  //#region src/endpoints/builder.ts
39856
39850
  var DEFAULT_RESOLUTIONS = [{
@@ -40174,6 +40168,53 @@ function buildPrivacyEndpoint(input) {
40174
40168
  }
40175
40169
  };
40176
40170
  }
40171
+ /**
40172
+ * An `alarm-panel` device as an `Alexa.SecurityPanelController` endpoint.
40173
+ *
40174
+ * It is its OWN endpoint, not a child of a camera: a panel is a standalone
40175
+ * device and has no stream, no doorbell and no PTZ. The `__alarm` suffix on
40176
+ * the endpoint id is a routing tag (see `handlers/endpoint-id.ts`).
40177
+ *
40178
+ * ## What is declared, and what is deliberately not
40179
+ *
40180
+ * - `armState` and `burglaryAlarm` are the two properties this cap can fill
40181
+ * honestly. `fireAlarm` / `carbonMonoxideAlarm` / `waterAlarm` are NOT
40182
+ * declared: `alarm-panel` has no field saying WHICH alarm is sounding, and
40183
+ * declaring a property we would always answer `OK` on is a claim with no
40184
+ * basis behind it. The reasoning is in `security-panel-arm-state.ts`.
40185
+ * - `proactivelyReported: false`. This addon's Event Gateway pushes
40186
+ * ChangeReports for camera motion only; a panel state change is not wired
40187
+ * to it, and promising a report nothing sends is how an endpoint ends up
40188
+ * looking broken. `retrievable: true` — `Alexa/ReportState` answers.
40189
+ * - `supportedAuthorizationTypes` appears only for a panel that requires a
40190
+ * code. Alexa's Disarm directive can carry a PIN; its **Arm directive
40191
+ * cannot**, which is why a PIN-gated arm is refused by the handler with
40192
+ * `AUTHORIZATION_REQUIRED` rather than attempted.
40193
+ */
40194
+ function buildAlarmPanelEndpoint(input) {
40195
+ const configuration = { supportedArmStates: supportedArmStatesFor(input.availableModes).map((value) => ({ value })) };
40196
+ if (input.requiresCode) configuration.supportedAuthorizationTypes = [{ type: "FOUR_DIGIT_PIN" }];
40197
+ const securityPanelController = {
40198
+ type: "AlexaInterface",
40199
+ interface: "Alexa.SecurityPanelController",
40200
+ version: "3",
40201
+ properties: {
40202
+ supported: [{ name: "armState" }, { name: "burglaryAlarm" }],
40203
+ proactivelyReported: false,
40204
+ retrievable: true
40205
+ },
40206
+ configuration
40207
+ };
40208
+ return {
40209
+ endpointId: `${input.deviceId}__alarm`,
40210
+ manufacturerName: "camstack",
40211
+ description: "CamStack alarm panel",
40212
+ friendlyName: input.friendlyName.trim().length > 0 ? input.friendlyName.trim() : `Alarm ${input.deviceId}`,
40213
+ displayCategories: ["SECURITY_PANEL"],
40214
+ capabilities: [ALEXA_BASE_CAPABILITY, securityPanelController],
40215
+ cookie: { stableId: input.stableId }
40216
+ };
40217
+ }
40177
40218
  //#endregion
40178
40219
  //#region src/handlers/error-envelope.ts
40179
40220
  /**
@@ -40209,20 +40250,68 @@ function errorEnvelope(header, type, message) {
40209
40250
  } };
40210
40251
  }
40211
40252
  //#endregion
40212
- //#region src/handlers/discovery.ts
40253
+ //#region src/handlers/types.ts
40213
40254
  /**
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).
40255
+ * Zod schemas for the subset of the Alexa Smart Home directive surface
40256
+ * that we actually parse hub-side. The Smart Home Skill API ships
40257
+ * thousands of optional fields per namespace — we only validate what
40258
+ * we read; everything else passes through as `unknown`.
40218
40259
  *
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.
40260
+ * Reference: https://developer.amazon.com/en-US/docs/alexa/smarthome/smart-home-skill-api-message-reference.html
40225
40261
  */
40262
+ /** A directive header carries namespace + name + token + correlation id. */
40263
+ var DirectiveHeaderSchema = object({
40264
+ namespace: string(),
40265
+ name: string(),
40266
+ payloadVersion: string(),
40267
+ messageId: string(),
40268
+ correlationToken: string().optional()
40269
+ });
40270
+ /** Scope carries the bearer token Alexa minted via our OAuth provider. */
40271
+ var BearerScopeSchema = object({
40272
+ type: literal("BearerToken"),
40273
+ token: string()
40274
+ });
40275
+ /** Endpoint reference inside a directive payload. */
40276
+ var EndpointRefSchema = object({
40277
+ endpointId: string(),
40278
+ scope: BearerScopeSchema.optional(),
40279
+ cookie: record(string(), string()).optional()
40280
+ });
40281
+ var DiscoveryDirectiveSchema = object({
40282
+ header: DirectiveHeaderSchema.extend({
40283
+ namespace: literal("Alexa.Discovery"),
40284
+ name: literal("Discover")
40285
+ }),
40286
+ payload: object({ scope: BearerScopeSchema })
40287
+ });
40288
+ /** Envelope wrapping a directive on the Alexa→skill wire. */
40289
+ var DirectiveRequestSchema = object({ directive: object({
40290
+ header: DirectiveHeaderSchema,
40291
+ endpoint: EndpointRefSchema.optional(),
40292
+ payload: unknown().optional()
40293
+ }) });
40294
+ var InitializeCameraStreamsPayloadSchema = object({ cameraStreams: array(object({
40295
+ protocol: string(),
40296
+ resolution: object({
40297
+ width: number(),
40298
+ height: number()
40299
+ }).optional(),
40300
+ authorizationType: string().optional(),
40301
+ videoCodec: string().optional(),
40302
+ audioCodec: string().optional()
40303
+ })).optional() });
40304
+ var InitiateSessionWithOfferPayloadSchema = object({
40305
+ sessionId: string(),
40306
+ offer: object({
40307
+ format: string().optional(),
40308
+ value: string()
40309
+ })
40310
+ });
40311
+ var SessionDisconnectedPayloadSchema = object({ sessionId: string() });
40312
+ var SetModePayloadSchema = object({ mode: string() });
40313
+ //#endregion
40314
+ //#region src/handlers/discovery.ts
40226
40315
  var discoveryPayloadSchema = DiscoveryDirectiveSchema.shape.payload;
40227
40316
  /** Devices built at once in `handleDiscovery` — latency-bound tRPC reads, so
40228
40317
  * six lanes hide the round-trips without stampeding a booting hub. */
@@ -40236,6 +40325,7 @@ var CAP_SWITCH = "switch";
40236
40325
  var CAP_BRIGHTNESS = "brightness";
40237
40326
  var CAP_BATTERY = "battery";
40238
40327
  var CAP_PRIVACY_MASK = "privacy-mask";
40328
+ var CAP_ALARM_PANEL = "alarm-panel";
40239
40329
  async function handleDiscovery(header, payloadRaw, deps, callerIdentity) {
40240
40330
  if (!discoveryPayloadSchema.safeParse(payloadRaw).success) return errorEnvelope(header, "INVALID_DIRECTIVE", "Discovery payload shape unexpected");
40241
40331
  const exposed = await deps.listExposed();
@@ -40275,6 +40365,7 @@ async function buildEndpointsForExposedDevice(deviceId, deps) {
40275
40365
  return [];
40276
40366
  }
40277
40367
  const parentInfo = await loadBoundDeviceInfo(device, api);
40368
+ if (parentInfo.capNames.includes(CAP_ALARM_PANEL)) return [await buildAlarmPanelEndpointFor(parentInfo, api, deps)];
40278
40369
  const children = await api.deviceManager.getChildren.query({ parentDeviceId: deviceId }).catch((err) => {
40279
40370
  deps.logger.warn("alexa discovery: getChildren failed", {
40280
40371
  tags: { deviceId },
@@ -40354,6 +40445,47 @@ async function buildEndpointsForExposedDevice(deviceId, deps) {
40354
40445
  }
40355
40446
  return out;
40356
40447
  }
40448
+ /**
40449
+ * The panel endpoint, with what the panel says it accepts.
40450
+ *
40451
+ * A `getStatus` that fails leaves `availableModes` empty and `requiresCode`
40452
+ * false, and those are the UNKNOWN readings, not assertions: an empty mode
40453
+ * list makes discovery declare all three arm states (`supportedArmStatesFor`)
40454
+ * rather than publishing a panel that can only be disarmed, and the directive
40455
+ * handler re-reads the panel before it commands anything, so a PIN discovered
40456
+ * later is still honoured. The blind read is logged against the device id.
40457
+ */
40458
+ async function buildAlarmPanelEndpointFor(info, api, deps) {
40459
+ const status = await api.alarmPanel.getStatus.query({ deviceId: info.id }).catch((err) => {
40460
+ deps.logger.warn("alexa discovery: alarmPanel.getStatus failed — declaring every arm state", {
40461
+ tags: { deviceId: info.id },
40462
+ meta: { error: err instanceof Error ? err.message : String(err) }
40463
+ });
40464
+ return null;
40465
+ });
40466
+ const parsed = AlarmPanelStatusSchema.pick({
40467
+ availableModes: true,
40468
+ requiresCode: true
40469
+ }).safeParse(status);
40470
+ if (!parsed.success && status !== null) deps.logger.warn("alexa discovery: panel status did not match the cap schema", { tags: { deviceId: info.id } });
40471
+ const availableModes = parsed.success ? parsed.data.availableModes : [];
40472
+ const requiresCode = parsed.success ? parsed.data.requiresCode : false;
40473
+ deps.logger.info("alexa discovery: built alarm panel endpoint", {
40474
+ tags: { deviceId: info.id },
40475
+ meta: {
40476
+ name: info.name,
40477
+ availableModes: [...availableModes],
40478
+ requiresCode
40479
+ }
40480
+ });
40481
+ return buildAlarmPanelEndpoint({
40482
+ deviceId: info.id,
40483
+ stableId: info.stableId,
40484
+ friendlyName: info.name,
40485
+ availableModes,
40486
+ requiresCode
40487
+ });
40488
+ }
40357
40489
  async function loadBoundDeviceInfo(device, api) {
40358
40490
  const capNames = (await api.deviceManager.getBindings.query({ deviceId: device.id })).entries.map((e) => e.capName);
40359
40491
  return {
@@ -40419,10 +40551,14 @@ function parseCameraEndpointId(raw) {
40419
40551
  kind: "privacy",
40420
40552
  parentDeviceId: parent
40421
40553
  };
40554
+ if (tail === "alarm") return {
40555
+ kind: "alarm-panel",
40556
+ deviceId: parent
40557
+ };
40422
40558
  const child = parseNonNegativeInt(tail);
40423
40559
  if (child === null) return {
40424
40560
  kind: "invalid",
40425
- reason: `child segment not numeric and not 'autotrack'/'privacy': ${raw}`
40561
+ reason: `child segment not numeric and not 'autotrack'/'privacy'/'alarm': ${raw}`
40426
40562
  };
40427
40563
  return {
40428
40564
  kind: "child",
@@ -40437,6 +40573,68 @@ function parseNonNegativeInt(s) {
40437
40573
  return n;
40438
40574
  }
40439
40575
  //#endregion
40576
+ //#region src/handlers/brightness-controller.ts
40577
+ var SetBrightnessDirectiveSchema = object({
40578
+ header: object({
40579
+ namespace: literal("Alexa.BrightnessController"),
40580
+ name: literal("SetBrightness")
40581
+ }),
40582
+ endpoint: EndpointRefSchema,
40583
+ payload: object({ brightness: number().min(0).max(100) })
40584
+ });
40585
+ async function handleSetBrightness(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
40586
+ const parsed = SetBrightnessDirectiveSchema.safeParse({
40587
+ header: {
40588
+ namespace: header.namespace,
40589
+ name: header.name
40590
+ },
40591
+ endpoint: endpointRaw,
40592
+ payload: payloadRaw ?? {}
40593
+ });
40594
+ if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
40595
+ const endpointId = parsed.data.endpoint.endpointId;
40596
+ const parsedId = parseCameraEndpointId(endpointId);
40597
+ 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`);
40598
+ if (parsedId.kind === "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", "BrightnessController is not exposed on camera endpoints — direct the directive at the dimmable child accessory");
40599
+ if (parsedId.kind === "invalid") return errorEnvelope(header, "INVALID_DIRECTIVE", parsedId.reason);
40600
+ const percentage = parsed.data.payload.brightness;
40601
+ const api = deps.ctx.api;
40602
+ try {
40603
+ await api.brightness.setBrightness.mutate({
40604
+ deviceId: parsedId.childDeviceId,
40605
+ percentage
40606
+ });
40607
+ } catch (err) {
40608
+ const message = err instanceof Error ? err.message : String(err);
40609
+ deps.logger.warn("alexa brightness-controller: setBrightness failed", { meta: {
40610
+ deviceId: parsedId.childDeviceId,
40611
+ percentage,
40612
+ error: message
40613
+ } });
40614
+ return errorEnvelope(header, "INTERNAL_ERROR", `brightness.setBrightness failed: ${message}`);
40615
+ }
40616
+ return {
40617
+ event: {
40618
+ header: {
40619
+ namespace: "Alexa",
40620
+ name: "Response",
40621
+ messageId: header.messageId,
40622
+ correlationToken: header.correlationToken,
40623
+ payloadVersion: "3"
40624
+ },
40625
+ endpoint: { endpointId },
40626
+ payload: {}
40627
+ },
40628
+ context: { properties: [{
40629
+ namespace: "Alexa.BrightnessController",
40630
+ name: "brightness",
40631
+ value: percentage,
40632
+ timeOfSample: (/* @__PURE__ */ new Date()).toISOString(),
40633
+ uncertaintyInMilliseconds: 500
40634
+ }] }
40635
+ };
40636
+ }
40637
+ //#endregion
40440
40638
  //#region src/handlers/camera-stream.ts
40441
40639
  /**
40442
40640
  * `Alexa.CameraStreamController/InitializeCameraStreams` handler.
@@ -40519,347 +40717,42 @@ async function handleInitializeCameraStreams(header, endpointRaw, payloadRaw, de
40519
40717
  } };
40520
40718
  }
40521
40719
  //#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({
40720
+ //#region src/handlers/power-controller.ts
40721
+ var PowerDirectiveSchema = object({
40784
40722
  header: object({
40785
- namespace: literal("Alexa.ModeController"),
40786
- name: literal("SetMode"),
40787
- instance: string().optional()
40723
+ namespace: literal("Alexa.PowerController"),
40724
+ name: _enum(["TurnOn", "TurnOff"])
40788
40725
  }),
40789
- endpoint: EndpointRefSchema,
40790
- payload: SetModePayloadSchema
40726
+ endpoint: EndpointRefSchema
40791
40727
  });
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({
40728
+ async function handlePower(header, endpointRaw, deps, _callerIdentity) {
40729
+ const parsed = PowerDirectiveSchema.safeParse({
40806
40730
  header: {
40807
40731
  namespace: header.namespace,
40808
- name: header.name,
40809
- instance: header.instance
40732
+ name: header.name
40810
40733
  },
40811
- endpoint: endpointRaw,
40812
- payload: payloadRaw ?? {}
40734
+ endpoint: endpointRaw
40813
40735
  });
40814
40736
  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
40737
  const endpointId = parsed.data.endpoint.endpointId;
40818
40738
  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;
40739
+ const on = parsed.data.header.name === "TurnOn";
40821
40740
  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
40741
+ if (parsedId.kind === "autotrack") await api.ptzAutotrack.setEnabled.mutate({
40742
+ deviceId: parsedId.parentDeviceId,
40743
+ enabled: on
40859
40744
  });
40860
- return modeSuccessResponse(header, endpointId, "ptz.preset", mode);
40861
- }
40862
- function modeSuccessResponse(header, endpointId, instance, mode) {
40745
+ else if (parsedId.kind === "privacy") await api.privacyMask.setMask.mutate({
40746
+ deviceId: parsedId.parentDeviceId,
40747
+ patch: { enabled: on }
40748
+ });
40749
+ else if (parsedId.kind === "child") await api.switch.setState.mutate({
40750
+ deviceId: parsedId.childDeviceId,
40751
+ on
40752
+ });
40753
+ else if (parsedId.kind === "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", "PowerController is not exposed on camera endpoints — direct the directive at the child accessory");
40754
+ else if (parsedId.kind === "alarm-panel") return errorEnvelope(header, "INVALID_DIRECTIVE", "PowerController is not exposed on alarm-panel endpoints — use Alexa.SecurityPanelController");
40755
+ else return errorEnvelope(header, "INVALID_DIRECTIVE", parsedId.reason);
40863
40756
  return {
40864
40757
  event: {
40865
40758
  header: {
@@ -40873,10 +40766,9 @@ function modeSuccessResponse(header, endpointId, instance, mode) {
40873
40766
  payload: {}
40874
40767
  },
40875
40768
  context: { properties: [{
40876
- namespace: "Alexa.ModeController",
40877
- instance,
40878
- name: "mode",
40879
- value: mode,
40769
+ namespace: "Alexa.PowerController",
40770
+ name: "powerState",
40771
+ value: on ? "ON" : "OFF",
40880
40772
  timeOfSample: (/* @__PURE__ */ new Date()).toISOString(),
40881
40773
  uncertaintyInMilliseconds: 500
40882
40774
  }] }
@@ -40976,133 +40868,99 @@ function successResponse(header, endpointId, toggleState, instance) {
40976
40868
  };
40977
40869
  }
40978
40870
  //#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
40871
+ //#region src/handlers/ptz-preset.ts
41050
40872
  /**
41051
- * `Alexa.BrightnessController/SetBrightness` handler.
40873
+ * `Alexa.ModeController/SetMode` handler — dispatches three PTZ instances:
41052
40874
  *
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.
40875
+ * `ptz.preset` — preset-recall. Decodes the preset name from the mode
40876
+ * value and calls `ptz.goToPreset({deviceId, presetId})`.
41058
40877
  *
41059
- * Routing:
41060
- * - `${parent}__${child}` → `brightness.setBrightness({deviceId: child, percentage})`
40878
+ * `ptz.pan` — momentary pan. `ptz.pan.left|right|center` issues a
40879
+ * continuousMove pulse stopped on a timer; the dropdown reverts to
40880
+ * `center` server-side so subsequent picks re-trigger the move.
41061
40881
  *
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.
40882
+ * `ptz.tilt` — momentary tilt. Mirrors ptz.pan with up|down|center.
41066
40883
  */
41067
- var SetBrightnessDirectiveSchema = object({
40884
+ var SetModeDirectiveSchema = object({
41068
40885
  header: object({
41069
- namespace: literal("Alexa.BrightnessController"),
41070
- name: literal("SetBrightness")
40886
+ namespace: literal("Alexa.ModeController"),
40887
+ name: literal("SetMode"),
40888
+ instance: string().optional()
41071
40889
  }),
41072
40890
  endpoint: EndpointRefSchema,
41073
- payload: object({ brightness: number().min(0).max(100) })
40891
+ payload: SetModePayloadSchema
41074
40892
  });
41075
- async function handleSetBrightness(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41076
- const parsed = SetBrightnessDirectiveSchema.safeParse({
40893
+ var PTZ_PRESET_MODE_PREFIX = "ptz.preset.";
40894
+ var PTZ_DIRECTION_PULSE_MS = 1e3;
40895
+ var PTZ_PAN_MOVES = {
40896
+ "ptz.pan.left": { pan: -1 },
40897
+ "ptz.pan.right": { pan: 1 },
40898
+ "ptz.pan.center": {}
40899
+ };
40900
+ var PTZ_TILT_MOVES = {
40901
+ "ptz.tilt.up": { tilt: 1 },
40902
+ "ptz.tilt.down": { tilt: -1 },
40903
+ "ptz.tilt.center": {}
40904
+ };
40905
+ async function handleSetMode(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
40906
+ const parsed = SetModeDirectiveSchema.safeParse({
41077
40907
  header: {
41078
40908
  namespace: header.namespace,
41079
- name: header.name
40909
+ name: header.name,
40910
+ instance: header.instance
41080
40911
  },
41081
40912
  endpoint: endpointRaw,
41082
40913
  payload: payloadRaw ?? {}
41083
40914
  });
41084
40915
  if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
40916
+ const instance = parsed.data.header.instance;
40917
+ if (instance !== "ptz.preset" && instance !== "ptz.pan" && instance !== "ptz.tilt") return errorEnvelope(header, "INVALID_DIRECTIVE", `ModeController instance not supported: ${instance ?? "(missing)"}`);
41085
40918
  const endpointId = parsed.data.endpoint.endpointId;
41086
40919
  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;
40920
+ if (parsedId.kind !== "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", `ModeController only supported on camera endpoints — got ${endpointId}`);
40921
+ const mode = parsed.data.payload.mode;
41091
40922
  const api = deps.ctx.api;
41092
- try {
41093
- await api.brightness.setBrightness.mutate({
41094
- deviceId: parsedId.childDeviceId,
41095
- percentage
40923
+ if (instance === "ptz.pan" || instance === "ptz.tilt") {
40924
+ const move = (instance === "ptz.pan" ? PTZ_PAN_MOVES : PTZ_TILT_MOVES)[mode];
40925
+ if (!move) return errorEnvelope(header, "INVALID_DIRECTIVE", `mode '${mode}' is not a valid ${instance} mode`);
40926
+ if (Object.keys(move).length === 0) await api.ptz.stop.mutate({ deviceId: parsedId.deviceId }).catch((err) => {
40927
+ deps.logger.debug("alexa ptz-mode: stop (center) failed (non-fatal)", { meta: {
40928
+ deviceId: parsedId.deviceId,
40929
+ instance,
40930
+ error: err instanceof Error ? err.message : String(err)
40931
+ } });
41096
40932
  });
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}`);
40933
+ else try {
40934
+ await api.ptz.continuousMove.mutate({
40935
+ deviceId: parsedId.deviceId,
40936
+ ...move
40937
+ });
40938
+ setTimeout(() => {
40939
+ api.ptz.stop.mutate({ deviceId: parsedId.deviceId }).catch((err) => {
40940
+ deps.logger.debug("alexa ptz-mode: stop after pulse failed (non-fatal)", { meta: {
40941
+ deviceId: parsedId.deviceId,
40942
+ instance,
40943
+ error: err instanceof Error ? err.message : String(err)
40944
+ } });
40945
+ });
40946
+ }, PTZ_DIRECTION_PULSE_MS);
40947
+ } catch (err) {
40948
+ return errorEnvelope(header, "INTERNAL_ERROR", `ptz.continuousMove failed: ${err instanceof Error ? err.message : String(err)}`);
40949
+ }
40950
+ return modeSuccessResponse(header, endpointId, instance, instance === "ptz.pan" ? "ptz.pan.center" : "ptz.tilt.center");
41105
40951
  }
40952
+ if (!mode.startsWith(PTZ_PRESET_MODE_PREFIX)) return errorEnvelope(header, "INVALID_DIRECTIVE", `mode '${mode}' is not a ptz.preset mode`);
40953
+ const presetName = mode.slice(11);
40954
+ if (presetName.length === 0) return errorEnvelope(header, "INVALID_DIRECTIVE", "preset name missing after prefix");
40955
+ const preset = (await api.ptz.getPresets.query({ deviceId: parsedId.deviceId })).find((p) => p.name === presetName);
40956
+ if (!preset) return errorEnvelope(header, "INVALID_DIRECTIVE", `preset '${presetName}' not found on device ${parsedId.deviceId}`);
40957
+ await api.ptz.goToPreset.mutate({
40958
+ deviceId: parsedId.deviceId,
40959
+ presetId: preset.id
40960
+ });
40961
+ return modeSuccessResponse(header, endpointId, "ptz.preset", mode);
40962
+ }
40963
+ function modeSuccessResponse(header, endpointId, instance, mode) {
41106
40964
  return {
41107
40965
  event: {
41108
40966
  header: {
@@ -41116,9 +40974,10 @@ async function handleSetBrightness(header, endpointRaw, payloadRaw, deps, _calle
41116
40974
  payload: {}
41117
40975
  },
41118
40976
  context: { properties: [{
41119
- namespace: "Alexa.BrightnessController",
41120
- name: "brightness",
41121
- value: percentage,
40977
+ namespace: "Alexa.ModeController",
40978
+ instance,
40979
+ name: "mode",
40980
+ value: mode,
41122
40981
  timeOfSample: (/* @__PURE__ */ new Date()).toISOString(),
41123
40982
  uncertaintyInMilliseconds: 500
41124
40983
  }] }
@@ -41139,6 +40998,7 @@ async function handleReportState(header, endpointRaw, deps, _callerIdentity) {
41139
40998
  else if (parsed.kind === "privacy") await collectPrivacyProperties(api, parsed.parentDeviceId, properties, nowIso, deps.logger);
41140
40999
  else if (parsed.kind === "autotrack") await collectAutotrackProperties(api, parsed.parentDeviceId, properties, nowIso, deps.logger);
41141
41000
  else if (parsed.kind === "child") await collectChildProperties(api, parsed.childDeviceId, properties, nowIso, deps.logger);
41001
+ else if (parsed.kind === "alarm-panel") await collectAlarmPanelProperties(api, parsed.deviceId, properties, nowIso, deps.logger);
41142
41002
  } catch (err) {
41143
41003
  deps.logger.warn("alexa report-state: collection failed", { meta: {
41144
41004
  endpointId,
@@ -41200,6 +41060,42 @@ async function collectCameraProperties(api, deviceId, properties, timeOfSample,
41200
41060
  uncertaintyInMilliseconds: 0
41201
41061
  });
41202
41062
  }
41063
+ /**
41064
+ * The panel's two declared properties.
41065
+ *
41066
+ * Both are omitted when the panel cannot be read — an `armState` we guessed
41067
+ * would be a claim about whether a house is locked, and Alexa rendering the
41068
+ * endpoint as unavailable is the truthful outcome of a panel nobody reached.
41069
+ * The failure is logged with the device id, never swallowed.
41070
+ */
41071
+ async function collectAlarmPanelProperties(api, deviceId, properties, timeOfSample, logger) {
41072
+ const status = await api.alarmPanel.getStatus.query({ deviceId }).catch((err) => {
41073
+ logger.warn("alexa report-state: alarmPanel.getStatus FAILED — Alexa will show the panel as unavailable", {
41074
+ tags: { deviceId },
41075
+ meta: { error: err instanceof Error ? err.message : String(err) }
41076
+ });
41077
+ return null;
41078
+ });
41079
+ const parsed = AlarmPanelStatusSchema.pick({ state: true }).safeParse(status);
41080
+ if (!parsed.success) {
41081
+ if (status !== null) logger.warn("alexa report-state: panel status did not match the cap schema — omitting", { tags: { deviceId } });
41082
+ return;
41083
+ }
41084
+ properties.push({
41085
+ namespace: "Alexa.SecurityPanelController",
41086
+ name: "armState",
41087
+ value: alexaArmStateFor(parsed.data.state),
41088
+ timeOfSample,
41089
+ uncertaintyInMilliseconds: 0
41090
+ });
41091
+ properties.push({
41092
+ namespace: "Alexa.SecurityPanelController",
41093
+ name: "burglaryAlarm",
41094
+ value: burglaryAlarmFor(parsed.data.state),
41095
+ timeOfSample,
41096
+ uncertaintyInMilliseconds: 0
41097
+ });
41098
+ }
41203
41099
  async function collectPrivacyProperties(api, parentDeviceId, properties, timeOfSample, _logger) {
41204
41100
  const status = await api.privacyMask.getStatus.query({ deviceId: parentDeviceId }).catch(() => null);
41205
41101
  const enabled = Boolean(status?.enabled);
@@ -41253,6 +41149,478 @@ async function collectChildProperties(api, childDeviceId, properties, timeOfSamp
41253
41149
  });
41254
41150
  }
41255
41151
  //#endregion
41152
+ //#region src/handlers/rtc-session.ts
41153
+ var InitiateSessionWithOfferDirectiveSchema = object({
41154
+ endpoint: EndpointRefSchema,
41155
+ payload: InitiateSessionWithOfferPayloadSchema
41156
+ });
41157
+ var SessionDisconnectedDirectiveSchema = object({
41158
+ endpoint: EndpointRefSchema,
41159
+ payload: SessionDisconnectedPayloadSchema
41160
+ });
41161
+ /**
41162
+ * Live egress handles, keyed by `<deviceId>/<sessionId>`.
41163
+ *
41164
+ * The primitive's refcount has no lease TTL: a holder that vanishes without
41165
+ * releasing leaks a child until the broker restarts (D67). This handler is a
41166
+ * holder, so it keeps the one piece of state that lets it not be that holder —
41167
+ * the `pipelineKey` its `SessionDisconnected` has to release.
41168
+ *
41169
+ * A module-level map is right here because the directive handlers are free
41170
+ * functions called per directive; the entry is written on a successful acquire
41171
+ * and deleted on the release path, both of which are the same tick as the
41172
+ * directive that owns it.
41173
+ */
41174
+ var EGRESS_HANDLES = /* @__PURE__ */ new Map();
41175
+ function egressHandleKey(deviceId, sessionId) {
41176
+ return `${deviceId}/${sessionId}`;
41177
+ }
41178
+ var WEBRTC_PROFILE_NAMES = [
41179
+ "high",
41180
+ "mid",
41181
+ "low"
41182
+ ];
41183
+ function resolveWebrtcTarget(pref) {
41184
+ if (pref === "auto") return void 0;
41185
+ if (WEBRTC_PROFILE_NAMES.includes(pref)) return {
41186
+ kind: "profile",
41187
+ profile: pref
41188
+ };
41189
+ return {
41190
+ kind: "cam-stream",
41191
+ camStreamId: pref
41192
+ };
41193
+ }
41194
+ async function handleInitiateSessionWithOffer(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41195
+ const parsed = InitiateSessionWithOfferDirectiveSchema.safeParse({
41196
+ endpoint: endpointRaw,
41197
+ payload: payloadRaw ?? {}
41198
+ });
41199
+ if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
41200
+ const endpoint = parsed.data.endpoint;
41201
+ const payload = parsed.data.payload;
41202
+ const parsedId = parseCameraEndpointId(endpoint.endpointId);
41203
+ if (parsedId.kind !== "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", `endpointId ${endpoint.endpointId} is not a camera`);
41204
+ const deviceId = parsedId.deviceId;
41205
+ const sessionId = payload.sessionId;
41206
+ const log = deps.logger.withTags({
41207
+ deviceId,
41208
+ sessionId
41209
+ });
41210
+ const sdpOffer = payload.offer.value;
41211
+ if (sdpOffer.length === 0) return errorEnvelope(header, "INVALID_DIRECTIVE", "offer.value is empty");
41212
+ const api = deps.ctx.api;
41213
+ const exposedEntry = deps.listExposed().find((e) => e.deviceId === deviceId);
41214
+ const explicitSourceProfile = exposedEntry?.settings?.sourceProfile;
41215
+ const mappedFromPreference = (() => {
41216
+ const pref = exposedEntry?.settings?.streamPreference;
41217
+ if (pref === "low" || pref === "mid" || pref === "high") return pref;
41218
+ })();
41219
+ const sourceProfile = explicitSourceProfile ?? mappedFromPreference ?? "high";
41220
+ let derivedTarget;
41221
+ /**
41222
+ * The primitive's release handle, when this session acquired one. Recorded so
41223
+ * `SessionDisconnected` can release it: a refcount whose holder disappears is
41224
+ * the one gap D67 leaves open, and the least this handler can do is not BE
41225
+ * that holder.
41226
+ */
41227
+ let egressPipelineKey = null;
41228
+ const picked = await api.cameraStreams.pickStream.query({
41229
+ deviceId,
41230
+ requirements: {
41231
+ acceptCodecs: ["h264"],
41232
+ minHeight: 480,
41233
+ excludeDerived: true,
41234
+ requireSiblingCodec: ["h265", "hevc"]
41235
+ }
41236
+ }).catch((err) => {
41237
+ log.warn("alexa rtc-session: cameraStreams.pickStream threw — falling back to transcode", { meta: { error: err instanceof Error ? err.message : String(err) } });
41238
+ return null;
41239
+ });
41240
+ if (picked) {
41241
+ log.info("alexa rtc-session: bypassing transcode via cameraStreams.pickStream", { meta: {
41242
+ sourceProfile,
41243
+ selectedCamStreamId: picked.camStreamId,
41244
+ reason: picked.reason
41245
+ } });
41246
+ derivedTarget = {
41247
+ kind: "cam-stream",
41248
+ camStreamId: picked.camStreamId
41249
+ };
41250
+ } else try {
41251
+ const acquired = await acquireAlexaEgress({
41252
+ api,
41253
+ deviceId,
41254
+ sourceProfile,
41255
+ sessionId,
41256
+ logger: log
41257
+ });
41258
+ egressPipelineKey = acquired.pipelineKey;
41259
+ EGRESS_HANDLES.set(egressHandleKey(deviceId, sessionId), acquired.pipelineKey);
41260
+ derivedTarget = {
41261
+ kind: "cam-stream",
41262
+ camStreamId: acquired.camStreamId
41263
+ };
41264
+ } catch (err) {
41265
+ log.warn("alexa rtc-session: egress acquire failed, falling back to streamPreference target", { meta: { error: err instanceof Error ? err.message : String(err) } });
41266
+ derivedTarget = resolveWebrtcTarget(exposedEntry?.settings?.streamPreference ?? "auto");
41267
+ }
41268
+ try {
41269
+ const result = await api.webrtcSession.handleOffer.mutate({
41270
+ deviceId,
41271
+ sdpOffer,
41272
+ sessionId,
41273
+ target: derivedTarget,
41274
+ relayOnly: false,
41275
+ nonTrickle: true,
41276
+ disableTurn: true,
41277
+ disableIpv6: true,
41278
+ consumerAttribution: {
41279
+ kind: "alexa",
41280
+ sessionId
41281
+ }
41282
+ });
41283
+ log.info("alexa rtc-session: AnswerGenerated", { meta: {
41284
+ returnedSessionId: result.sessionId,
41285
+ sdpAnswerLen: result.sdpAnswer.length
41286
+ } });
41287
+ return { event: {
41288
+ header: {
41289
+ namespace: "Alexa.RTCSessionController",
41290
+ name: "AnswerGeneratedForSession",
41291
+ messageId: header.messageId,
41292
+ correlationToken: header.correlationToken,
41293
+ payloadVersion: "3"
41294
+ },
41295
+ endpoint: { endpointId: endpoint.endpointId },
41296
+ payload: { answer: {
41297
+ format: payload.offer.format ?? "SDP",
41298
+ value: result.sdpAnswer
41299
+ } }
41300
+ } };
41301
+ } catch (err) {
41302
+ const message = err instanceof Error ? err.message : String(err);
41303
+ const mSectionSummary = (() => {
41304
+ const lines = sdpOffer.split(/\r?\n/);
41305
+ const sections = [];
41306
+ let current = null;
41307
+ for (const raw of lines) {
41308
+ const line = raw.trim();
41309
+ if (line.startsWith("m=")) {
41310
+ if (current) sections.push(current);
41311
+ current = {
41312
+ mid: null,
41313
+ kind: line.split(" ")[0]?.slice(2) ?? "unknown",
41314
+ direction: null,
41315
+ codecs: []
41316
+ };
41317
+ } else if (current) {
41318
+ if (line.startsWith("a=mid:")) current.mid = line.slice(6);
41319
+ else if (/^a=(sendonly|recvonly|sendrecv|inactive)$/.test(line)) current.direction = line.slice(2);
41320
+ else if (line.startsWith("a=rtpmap:")) current.codecs.push(line.slice(9));
41321
+ }
41322
+ }
41323
+ if (current) sections.push(current);
41324
+ return sections;
41325
+ })();
41326
+ log.warn("alexa rtc-session: handleOffer failed", { meta: {
41327
+ error: message,
41328
+ offerLen: sdpOffer.length,
41329
+ mSections: mSectionSummary,
41330
+ offerSdp: sdpOffer
41331
+ } });
41332
+ if (egressPipelineKey !== null) {
41333
+ EGRESS_HANDLES.delete(egressHandleKey(deviceId, sessionId));
41334
+ await releaseAlexaEgress({
41335
+ api,
41336
+ deviceId,
41337
+ pipelineKey: egressPipelineKey,
41338
+ logger: log
41339
+ });
41340
+ }
41341
+ return errorEnvelope(header, "INTERNAL_ERROR", `webrtc-session.handleOffer failed: ${message}`);
41342
+ }
41343
+ }
41344
+ async function handleSessionDisconnected(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41345
+ const parsed = SessionDisconnectedDirectiveSchema.safeParse({
41346
+ endpoint: endpointRaw,
41347
+ payload: payloadRaw ?? {}
41348
+ });
41349
+ if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
41350
+ const endpoint = parsed.data.endpoint;
41351
+ const parsedId = parseCameraEndpointId(endpoint.endpointId);
41352
+ if (parsedId.kind === "camera") {
41353
+ const handleKey = egressHandleKey(parsedId.deviceId, parsed.data.payload.sessionId);
41354
+ const pipelineKey = EGRESS_HANDLES.get(handleKey);
41355
+ if (pipelineKey !== void 0) {
41356
+ EGRESS_HANDLES.delete(handleKey);
41357
+ await releaseAlexaEgress({
41358
+ api: deps.ctx.api,
41359
+ deviceId: parsedId.deviceId,
41360
+ pipelineKey,
41361
+ logger: deps.logger
41362
+ });
41363
+ }
41364
+ try {
41365
+ await deps.ctx.api.webrtcSession.closeSession.mutate({
41366
+ deviceId: parsedId.deviceId,
41367
+ sessionId: parsed.data.payload.sessionId
41368
+ });
41369
+ } catch (err) {
41370
+ deps.logger.warn("alexa rtc-session: closeSession threw on disconnect (continuing to ack)", {
41371
+ tags: {
41372
+ deviceId: parsedId.deviceId,
41373
+ sessionId: parsed.data.payload.sessionId
41374
+ },
41375
+ meta: { error: err instanceof Error ? err.message : String(err) }
41376
+ });
41377
+ }
41378
+ }
41379
+ const disconnectedDeviceId = parsedId.kind === "camera" ? parsedId.deviceId : void 0;
41380
+ deps.logger.info("alexa rtc-session: SessionDisconnected", {
41381
+ tags: {
41382
+ sessionId: parsed.data.payload.sessionId,
41383
+ ...disconnectedDeviceId !== void 0 ? { deviceId: disconnectedDeviceId } : {}
41384
+ },
41385
+ meta: { endpointId: endpoint.endpointId }
41386
+ });
41387
+ return { event: {
41388
+ header: {
41389
+ namespace: "Alexa",
41390
+ name: "Response",
41391
+ messageId: header.messageId,
41392
+ correlationToken: header.correlationToken,
41393
+ payloadVersion: "3"
41394
+ },
41395
+ endpoint: { endpointId: endpoint.endpointId },
41396
+ payload: {}
41397
+ } };
41398
+ }
41399
+ //#endregion
41400
+ //#region src/handlers/security-panel.ts
41401
+ var ArmPayloadSchema = object({ armState: _enum([
41402
+ "ARMED_STAY",
41403
+ "ARMED_AWAY",
41404
+ "ARMED_NIGHT"
41405
+ ]) });
41406
+ var DisarmPayloadSchema = object({ authorization: object({
41407
+ type: literal("FOUR_DIGIT_PIN"),
41408
+ value: string().min(1)
41409
+ }).optional() });
41410
+ /** The subset of the panel status the directives read. */
41411
+ var PanelReadSchema = AlarmPanelStatusSchema.pick({
41412
+ state: true,
41413
+ availableModes: true,
41414
+ requiresCode: true
41415
+ });
41416
+ /**
41417
+ * `Alexa.SecurityPanelController.ErrorResponse`.
41418
+ *
41419
+ * A namespace of its own, because the four types that matter here
41420
+ * (`AUTHORIZATION_REQUIRED`, `UNAUTHORIZED`, `NOT_READY_FOR_ARM`,
41421
+ * `BYPASS_NEEDED`) are only understood under it — the generic `Alexa`
41422
+ * `ErrorResponse` from `error-envelope.ts` carries none of them, and a PIN
41423
+ * problem reported there is a message the Alexa app cannot act on.
41424
+ */
41425
+ function securityPanelError(header, type, message) {
41426
+ return { event: {
41427
+ header: {
41428
+ namespace: "Alexa.SecurityPanelController",
41429
+ name: "ErrorResponse",
41430
+ messageId: header.messageId,
41431
+ correlationToken: header.correlationToken,
41432
+ payloadVersion: "3"
41433
+ },
41434
+ payload: {
41435
+ type,
41436
+ message
41437
+ }
41438
+ } };
41439
+ }
41440
+ /** Resolve the alarm panel this directive targets, or the refusal to send. */
41441
+ function resolveDeviceId(endpointRaw) {
41442
+ const parsedEndpoint = EndpointRefSchema.safeParse(endpointRaw);
41443
+ if (!parsedEndpoint.success) return { reason: "missing or malformed endpoint" };
41444
+ const parsedId = parseCameraEndpointId(parsedEndpoint.data.endpointId);
41445
+ if (parsedId.kind === "alarm-panel") return { deviceId: parsedId.deviceId };
41446
+ return { reason: `SecurityPanelController is only exposed on alarm-panel endpoints — got '${parsedEndpoint.data.endpointId}'` };
41447
+ }
41448
+ /**
41449
+ * What the panel currently accepts, or `null` when it could not be read.
41450
+ *
41451
+ * `null` is the honest answer and the callers treat it as unknown; nothing
41452
+ * here substitutes a default that would read as "accepts nothing, needs no
41453
+ * PIN".
41454
+ */
41455
+ async function readPanel(api, deviceId, logger, phase) {
41456
+ const raw = await api.alarmPanel.getStatus.query({ deviceId }).catch((err) => {
41457
+ logger.warn("alexa security-panel: alarmPanel.getStatus failed — proceeding without it", {
41458
+ tags: { deviceId },
41459
+ meta: {
41460
+ phase,
41461
+ error: err instanceof Error ? err.message : String(err)
41462
+ }
41463
+ });
41464
+ return null;
41465
+ });
41466
+ const parsed = PanelReadSchema.safeParse(raw);
41467
+ if (!parsed.success) {
41468
+ if (raw !== null) logger.warn("alexa security-panel: panel status did not match the cap schema", {
41469
+ tags: { deviceId },
41470
+ meta: { phase }
41471
+ });
41472
+ return null;
41473
+ }
41474
+ return parsed.data;
41475
+ }
41476
+ /** The `context.properties` block for a panel whose state we re-read. */
41477
+ function panelProperties(facts, fallback) {
41478
+ const timeOfSample = (/* @__PURE__ */ new Date()).toISOString();
41479
+ const parsedState = facts === null ? null : AlarmPanelStatusSchema.shape.state.parse(facts.state);
41480
+ const armState = parsedState === null ? fallback : alexaArmStateFor(parsedState);
41481
+ const burglary = parsedState === null ? { value: "OK" } : burglaryAlarmFor(parsedState);
41482
+ return [{
41483
+ namespace: "Alexa.SecurityPanelController",
41484
+ name: "armState",
41485
+ value: armState,
41486
+ timeOfSample,
41487
+ uncertaintyInMilliseconds: 0
41488
+ }, {
41489
+ namespace: "Alexa.SecurityPanelController",
41490
+ name: "burglaryAlarm",
41491
+ value: burglary,
41492
+ timeOfSample,
41493
+ uncertaintyInMilliseconds: 0
41494
+ }];
41495
+ }
41496
+ async function handleArm(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41497
+ const target = resolveDeviceId(endpointRaw);
41498
+ if (!("deviceId" in target)) return errorEnvelope(header, "INVALID_DIRECTIVE", target.reason);
41499
+ const { deviceId } = target;
41500
+ const payload = ArmPayloadSchema.safeParse(payloadRaw);
41501
+ if (!payload.success) {
41502
+ deps.logger.warn("alexa security-panel: Arm payload is not an arm state Alexa defines", {
41503
+ tags: { deviceId },
41504
+ meta: { error: payload.error.message }
41505
+ });
41506
+ return errorEnvelope(header, "INVALID_DIRECTIVE", `Arm payload unexpected: ${payload.error.message}`);
41507
+ }
41508
+ const requested = payload.data.armState;
41509
+ const api = deps.ctx.api;
41510
+ const facts = await readPanel(api, deviceId, deps.logger, "arm");
41511
+ if (facts?.requiresCode === true) {
41512
+ deps.logger.warn("alexa security-panel: panel requires a PIN and the Arm directive carries none — REFUSED", {
41513
+ tags: { deviceId },
41514
+ meta: { requested }
41515
+ });
41516
+ return securityPanelError(header, "AUTHORIZATION_REQUIRED", "this panel requires a PIN to arm, and Alexa cannot supply one on an Arm directive");
41517
+ }
41518
+ const mode = alarmArmModeForAlexa(requested, facts?.availableModes ?? []);
41519
+ if (mode === null) {
41520
+ deps.logger.warn("alexa security-panel: panel accepts no mode for this arm state — REFUSED", {
41521
+ tags: { deviceId },
41522
+ meta: {
41523
+ requested,
41524
+ availableModes: facts?.availableModes ?? null
41525
+ }
41526
+ });
41527
+ return securityPanelError(header, "NOT_READY_FOR_ARM", `panel does not accept ${requested}`);
41528
+ }
41529
+ try {
41530
+ await api.alarmPanel.arm.mutate({
41531
+ deviceId,
41532
+ mode
41533
+ });
41534
+ } catch (err) {
41535
+ deps.logger.warn("alexa security-panel: arm command failed", {
41536
+ tags: { deviceId },
41537
+ meta: {
41538
+ requested,
41539
+ mode,
41540
+ error: err instanceof Error ? err.message : String(err)
41541
+ }
41542
+ });
41543
+ return securityPanelError(header, "NOT_READY_FOR_ARM", err instanceof Error ? err.message : String(err));
41544
+ }
41545
+ deps.logger.info("alexa security-panel: armed", {
41546
+ tags: { deviceId },
41547
+ meta: {
41548
+ requested,
41549
+ mode
41550
+ }
41551
+ });
41552
+ const after = await readPanel(api, deviceId, deps.logger, "arm-confirm");
41553
+ if (after?.state === "arming") deps.logger.info("alexa security-panel: panel is in its exit delay — reporting DISARMED until it is set", {
41554
+ tags: { deviceId },
41555
+ meta: {
41556
+ requested,
41557
+ mode
41558
+ }
41559
+ });
41560
+ return {
41561
+ event: {
41562
+ header: {
41563
+ namespace: "Alexa.SecurityPanelController",
41564
+ name: "Arm.Response",
41565
+ messageId: header.messageId,
41566
+ correlationToken: header.correlationToken,
41567
+ payloadVersion: "3"
41568
+ },
41569
+ endpoint: { endpointId: `${deviceId}__alarm` },
41570
+ payload: {}
41571
+ },
41572
+ context: { properties: panelProperties(after, requested) }
41573
+ };
41574
+ }
41575
+ async function handleDisarm(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41576
+ const target = resolveDeviceId(endpointRaw);
41577
+ if (!("deviceId" in target)) return errorEnvelope(header, "INVALID_DIRECTIVE", target.reason);
41578
+ const { deviceId } = target;
41579
+ const payload = DisarmPayloadSchema.safeParse(payloadRaw ?? {});
41580
+ if (!payload.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `Disarm payload unexpected: ${payload.error.message}`);
41581
+ const code = payload.data.authorization?.value;
41582
+ const api = deps.ctx.api;
41583
+ if ((await readPanel(api, deviceId, deps.logger, "disarm"))?.requiresCode === true && code === void 0) {
41584
+ deps.logger.warn("alexa security-panel: panel requires a PIN and the Disarm directive carried none — REFUSED", { tags: { deviceId } });
41585
+ return securityPanelError(header, "AUTHORIZATION_REQUIRED", "this panel requires a PIN to disarm");
41586
+ }
41587
+ try {
41588
+ await api.alarmPanel.disarm.mutate(code === void 0 ? { deviceId } : {
41589
+ deviceId,
41590
+ code
41591
+ });
41592
+ } catch (err) {
41593
+ const message = err instanceof Error ? err.message : String(err);
41594
+ deps.logger.warn("alexa security-panel: disarm command failed", {
41595
+ tags: { deviceId },
41596
+ meta: {
41597
+ codeSupplied: code !== void 0,
41598
+ error: message
41599
+ }
41600
+ });
41601
+ return code === void 0 ? errorEnvelope(header, "INTERNAL_ERROR", message) : securityPanelError(header, "UNAUTHORIZED", message);
41602
+ }
41603
+ deps.logger.info("alexa security-panel: disarmed", {
41604
+ tags: { deviceId },
41605
+ meta: { codeSupplied: code !== void 0 }
41606
+ });
41607
+ const after = await readPanel(api, deviceId, deps.logger, "disarm-confirm");
41608
+ return {
41609
+ event: {
41610
+ header: {
41611
+ namespace: "Alexa",
41612
+ name: "Response",
41613
+ messageId: header.messageId,
41614
+ correlationToken: header.correlationToken,
41615
+ payloadVersion: "3"
41616
+ },
41617
+ endpoint: { endpointId: `${deviceId}__alarm` },
41618
+ payload: {}
41619
+ },
41620
+ context: { properties: panelProperties(after, "DISARMED") }
41621
+ };
41622
+ }
41623
+ //#endregion
41256
41624
  //#region src/handlers/stubs.ts
41257
41625
  /**
41258
41626
  * Stub responder for namespaces not yet implemented (CameraStream /
@@ -41332,7 +41700,9 @@ async function dispatchDirective(rawBody, deps, callerIdentity) {
41332
41700
  "Alexa.ModeController/SetMode": "create",
41333
41701
  "Alexa.ToggleController/TurnOn": "create",
41334
41702
  "Alexa.ToggleController/TurnOff": "create",
41335
- "Alexa/ReportState": "view"
41703
+ "Alexa/ReportState": "view",
41704
+ "Alexa.SecurityPanelController/Arm": "create",
41705
+ "Alexa.SecurityPanelController/Disarm": "create"
41336
41706
  };
41337
41707
  try {
41338
41708
  const key = `${header.namespace}/${header.name}`;
@@ -41377,6 +41747,14 @@ async function dispatchDirective(rawBody, deps, callerIdentity) {
41377
41747
  status: 200,
41378
41748
  body: await handlePtzDirection(header, endpoint, deps.ptzDirection, callerIdentity)
41379
41749
  };
41750
+ if (key === "Alexa.SecurityPanelController/Arm") return {
41751
+ status: 200,
41752
+ body: await handleArm(header, endpoint, payload, deps.securityPanel, callerIdentity)
41753
+ };
41754
+ if (key === "Alexa.SecurityPanelController/Disarm") return {
41755
+ status: 200,
41756
+ body: await handleDisarm(header, endpoint, payload, deps.securityPanel, callerIdentity)
41757
+ };
41380
41758
  if (key === "Alexa/ReportState") return {
41381
41759
  status: 200,
41382
41760
  body: await handleReportState(header, endpoint, deps.reportState, callerIdentity)
@@ -42933,7 +43311,13 @@ var DEFAULT_CONFIG = {
42933
43311
  enforceIngressToken: false,
42934
43312
  staleEndpointPurgeInput: ""
42935
43313
  };
42936
- var SUPPORTED_KINDS = ["camera", "doorbell"];
43314
+ /** UI filter for the Export picker. `alarm-panel` publishes an
43315
+ * `Alexa.SecurityPanelController` endpoint (`endpoints/builder.ts`). */
43316
+ var SUPPORTED_KINDS = [
43317
+ "camera",
43318
+ "doorbell",
43319
+ DeviceType.AlarmPanel
43320
+ ];
42937
43321
  var ExportAlexaAddon = class extends BaseAddon {
42938
43322
  lwaGateway = null;
42939
43323
  syncEngine = null;
@@ -43002,6 +43386,10 @@ var ExportAlexaAddon = class extends BaseAddon {
43002
43386
  reportState: {
43003
43387
  ctx: this.ctx,
43004
43388
  logger: this.ctx.logger
43389
+ },
43390
+ securityPanel: {
43391
+ ctx: this.ctx,
43392
+ logger: this.ctx.logger
43005
43393
  }
43006
43394
  },
43007
43395
  lwaTokensCallbackDeps: {