@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.
@@ -7488,7 +7488,23 @@ var EncodeProfileSchema = object({
7488
7488
  "zerolatency",
7489
7489
  "film",
7490
7490
  "animation"
7491
- ]).optional()
7491
+ ]).optional(),
7492
+ /**
7493
+ * ONE slice per access unit.
7494
+ *
7495
+ * `-tune zerolatency` turns on x264's sliced threads, and a frame then leaves
7496
+ * the encoder as five NAL slices that share one RTP timestamp and carry one
7497
+ * marker bit. A libwebrtc depacketiser sees five frame-starts and one
7498
+ * frame-end per frame: the first pictures render and the video then freezes
7499
+ * for good while the audio, on its own plane, plays on. Measured on this hub
7500
+ * 2026-09-13 against the Echo, and reduced to one slice by this flag alone.
7501
+ *
7502
+ * A NAMED field and not a raw flag, because {@link EgressEncodeSchema} omits
7503
+ * `outputArgs` on purpose: an opaque array is part of the sharing key, so two
7504
+ * consumers meaning the same thing spelled differently would stop sharing one
7505
+ * child. Absent means "whatever the encoder does" — today's behaviour.
7506
+ */
7507
+ singleSlicePerFrame: boolean().optional()
7492
7508
  }),
7493
7509
  audio: union([literal("passthrough"), object({
7494
7510
  codec: _enum([
@@ -7564,31 +7580,10 @@ var BASE_LIVE_EGRESS_PROFILE = {
7564
7580
  var ALEXA_EGRESS_PROFILE = {
7565
7581
  ...BASE_LIVE_EGRESS_PROFILE,
7566
7582
  audio: { codec: "opus" },
7567
- /**
7568
- * ONE slice per access unit.
7569
- *
7570
- * `-tune zerolatency` turns on x264's sliced threads, and every access unit
7571
- * came out of this encode as FIVE slices — measured on the hub 2026-09-13 on
7572
- * the exact argv this path spawns, and reduced to one by this single flag.
7573
- *
7574
- * Five slices share one RTP timestamp and carry one marker bit, so a
7575
- * libwebrtc depacketiser sees five frame-starts and one frame-end per frame.
7576
- * The Echo renders the first pictures and then freezes for good, while the
7577
- * audio — a separate plane — plays on. It is the only structural property
7578
- * that survived the elimination: the same freeze reproduced at 2304×1296
7579
- * HEVC with 217 KB keyframes AND at 640×360 H.264 with 67 KB keyframes and a
7580
- * fifth of the bitrate, so source, resolution, bitrate, keyframe burst,
7581
- * hardware decode, parameter sets, drift and bitstream conformance are all
7582
- * out — each ruled out by a measurement, not by elimination.
7583
- *
7584
- * The tune STAYS: it also drops the lookahead and the B-frames, which a live
7585
- * path wants. Only the slicing is unwanted, and this is the flag that says so.
7586
- *
7587
- * Scoped to Alexa deliberately. HomeKit and the browser transcode inherit
7588
- * {@link BASE_LIVE_EGRESS_PROFILE}; whether they want the same shape is a
7589
- * question for their own evidence, and the browser has not been measured.
7590
- */
7591
- outputArgs: ["-x264-params", "sliced-threads=0"]
7583
+ video: {
7584
+ ...BASE_LIVE_EGRESS_PROFILE.video,
7585
+ singleSlicePerFrame: true
7586
+ }
7592
7587
  };
7593
7588
  /**
7594
7589
  * Deep wiring healthcheck — snapshot of active reachability probes across
@@ -16476,7 +16471,7 @@ var AlarmArmModeSchema = _enum([
16476
16471
  "vacation",
16477
16472
  "custom_bypass"
16478
16473
  ]);
16479
- object({
16474
+ var AlarmPanelStatusSchema = object({
16480
16475
  /** Current lifecycle state. */
16481
16476
  state: AlarmStateSchema,
16482
16477
  /** Subset of arm modes the panel accepts. UI renders one button per
@@ -39764,66 +39759,65 @@ async function releaseAlexaEgress(input) {
39764
39759
  }
39765
39760
  }
39766
39761
  //#endregion
39767
- //#region src/handlers/types.ts
39762
+ //#region src/handlers/security-panel-arm-state.ts
39768
39763
  /**
39769
- * Zod schemas for the subset of the Alexa Smart Home directive surface
39770
- * that we actually parse hub-side. The Smart Home Skill API ships
39771
- * thousands of optional fields per namespace — we only validate what
39772
- * we read; everything else passes through as `unknown`.
39764
+ * The panel modes behind each Alexa arm state, PRIMARY first — the mirror of
39765
+ * `MODES_BY_TARGET` in the HomeKit exporter, and for the same reason: one
39766
+ * Alexa state stands for two panel modes, so a panel offering only the
39767
+ * secondary would otherwise be sent a mode it refuses.
39768
+ */
39769
+ var MODES_BY_ARM_STATE = {
39770
+ ARMED_STAY: ["home", "custom_bypass"],
39771
+ ARMED_AWAY: ["away", "vacation"],
39772
+ ARMED_NIGHT: ["night"]
39773
+ };
39774
+ var ARM_STATES = [
39775
+ "ARMED_STAY",
39776
+ "ARMED_AWAY",
39777
+ "ARMED_NIGHT"
39778
+ ];
39779
+ /** The panel's state as Alexa's `armState` property. */
39780
+ function alexaArmStateFor(state) {
39781
+ switch (state) {
39782
+ case "armed_home":
39783
+ case "armed_custom_bypass": return "ARMED_STAY";
39784
+ case "armed_night": return "ARMED_NIGHT";
39785
+ case "armed_away":
39786
+ case "armed_vacation":
39787
+ case "pending":
39788
+ case "triggered": return "ARMED_AWAY";
39789
+ default: return "DISARMED";
39790
+ }
39791
+ }
39792
+ /** `burglaryAlarm`, the only alarm property this cap can honestly fill. */
39793
+ function burglaryAlarmFor(state) {
39794
+ return { value: state === "triggered" ? "ALARM" : "OK" };
39795
+ }
39796
+ /**
39797
+ * The `supportedArmStates` for discovery.
39773
39798
  *
39774
- * Reference: https://developer.amazon.com/en-US/docs/alexa/smarthome/smart-home-skill-api-message-reference.html
39799
+ * `DISARMED` is always present: disarming is not one of the panel's arm modes.
39800
+ * An EMPTY `availableModes` is unknown, not "none" — a provider that never
39801
+ * populated the list looks identical to one that accepts nothing, and
39802
+ * publishing a panel that can only be disarmed on that guess takes the
39803
+ * controls off a working alarm. The caller logs it.
39775
39804
  */
39776
- /** A directive header carries namespace + name + token + correlation id. */
39777
- var DirectiveHeaderSchema = object({
39778
- namespace: string(),
39779
- name: string(),
39780
- payloadVersion: string(),
39781
- messageId: string(),
39782
- correlationToken: string().optional()
39783
- });
39784
- /** Scope carries the bearer token Alexa minted via our OAuth provider. */
39785
- var BearerScopeSchema = object({
39786
- type: literal("BearerToken"),
39787
- token: string()
39788
- });
39789
- /** Endpoint reference inside a directive payload. */
39790
- var EndpointRefSchema = object({
39791
- endpointId: string(),
39792
- scope: BearerScopeSchema.optional(),
39793
- cookie: record(string(), string()).optional()
39794
- });
39795
- var DiscoveryDirectiveSchema = object({
39796
- header: DirectiveHeaderSchema.extend({
39797
- namespace: literal("Alexa.Discovery"),
39798
- name: literal("Discover")
39799
- }),
39800
- payload: object({ scope: BearerScopeSchema })
39801
- });
39802
- /** Envelope wrapping a directive on the Alexa→skill wire. */
39803
- var DirectiveRequestSchema = object({ directive: object({
39804
- header: DirectiveHeaderSchema,
39805
- endpoint: EndpointRefSchema.optional(),
39806
- payload: unknown().optional()
39807
- }) });
39808
- var InitializeCameraStreamsPayloadSchema = object({ cameraStreams: array(object({
39809
- protocol: string(),
39810
- resolution: object({
39811
- width: number(),
39812
- height: number()
39813
- }).optional(),
39814
- authorizationType: string().optional(),
39815
- videoCodec: string().optional(),
39816
- audioCodec: string().optional()
39817
- })).optional() });
39818
- var InitiateSessionWithOfferPayloadSchema = object({
39819
- sessionId: string(),
39820
- offer: object({
39821
- format: string().optional(),
39822
- value: string()
39823
- })
39824
- });
39825
- var SessionDisconnectedPayloadSchema = object({ sessionId: string() });
39826
- var SetModePayloadSchema = object({ mode: string() });
39805
+ function supportedArmStatesFor(availableModes) {
39806
+ return [...availableModes.length === 0 ? ARM_STATES : ARM_STATES.filter((armState) => MODES_BY_ARM_STATE[armState].some((mode) => availableModes.includes(mode))), "DISARMED"];
39807
+ }
39808
+ /**
39809
+ * The arm mode to send for an Alexa arm state, or `null` when there is none.
39810
+ *
39811
+ * `null` is not a shrug: `DISARMED` is the Disarm DIRECTIVE, a different call,
39812
+ * and an arm state the panel accepts no mode for is a directive the handler
39813
+ * refuses with `NOT_READY_FOR_ARM` rather than translating into a guess.
39814
+ */
39815
+ function alarmArmModeForAlexa(armState, availableModes) {
39816
+ if (armState === "DISARMED") return null;
39817
+ const candidates = MODES_BY_ARM_STATE[armState];
39818
+ if (availableModes.length === 0) return candidates[0] ?? null;
39819
+ return candidates.find((mode) => availableModes.includes(mode)) ?? null;
39820
+ }
39827
39821
  //#endregion
39828
39822
  //#region src/endpoints/builder.ts
39829
39823
  var DEFAULT_RESOLUTIONS = [{
@@ -40147,6 +40141,53 @@ function buildPrivacyEndpoint(input) {
40147
40141
  }
40148
40142
  };
40149
40143
  }
40144
+ /**
40145
+ * An `alarm-panel` device as an `Alexa.SecurityPanelController` endpoint.
40146
+ *
40147
+ * It is its OWN endpoint, not a child of a camera: a panel is a standalone
40148
+ * device and has no stream, no doorbell and no PTZ. The `__alarm` suffix on
40149
+ * the endpoint id is a routing tag (see `handlers/endpoint-id.ts`).
40150
+ *
40151
+ * ## What is declared, and what is deliberately not
40152
+ *
40153
+ * - `armState` and `burglaryAlarm` are the two properties this cap can fill
40154
+ * honestly. `fireAlarm` / `carbonMonoxideAlarm` / `waterAlarm` are NOT
40155
+ * declared: `alarm-panel` has no field saying WHICH alarm is sounding, and
40156
+ * declaring a property we would always answer `OK` on is a claim with no
40157
+ * basis behind it. The reasoning is in `security-panel-arm-state.ts`.
40158
+ * - `proactivelyReported: false`. This addon's Event Gateway pushes
40159
+ * ChangeReports for camera motion only; a panel state change is not wired
40160
+ * to it, and promising a report nothing sends is how an endpoint ends up
40161
+ * looking broken. `retrievable: true` — `Alexa/ReportState` answers.
40162
+ * - `supportedAuthorizationTypes` appears only for a panel that requires a
40163
+ * code. Alexa's Disarm directive can carry a PIN; its **Arm directive
40164
+ * cannot**, which is why a PIN-gated arm is refused by the handler with
40165
+ * `AUTHORIZATION_REQUIRED` rather than attempted.
40166
+ */
40167
+ function buildAlarmPanelEndpoint(input) {
40168
+ const configuration = { supportedArmStates: supportedArmStatesFor(input.availableModes).map((value) => ({ value })) };
40169
+ if (input.requiresCode) configuration.supportedAuthorizationTypes = [{ type: "FOUR_DIGIT_PIN" }];
40170
+ const securityPanelController = {
40171
+ type: "AlexaInterface",
40172
+ interface: "Alexa.SecurityPanelController",
40173
+ version: "3",
40174
+ properties: {
40175
+ supported: [{ name: "armState" }, { name: "burglaryAlarm" }],
40176
+ proactivelyReported: false,
40177
+ retrievable: true
40178
+ },
40179
+ configuration
40180
+ };
40181
+ return {
40182
+ endpointId: `${input.deviceId}__alarm`,
40183
+ manufacturerName: "camstack",
40184
+ description: "CamStack alarm panel",
40185
+ friendlyName: input.friendlyName.trim().length > 0 ? input.friendlyName.trim() : `Alarm ${input.deviceId}`,
40186
+ displayCategories: ["SECURITY_PANEL"],
40187
+ capabilities: [ALEXA_BASE_CAPABILITY, securityPanelController],
40188
+ cookie: { stableId: input.stableId }
40189
+ };
40190
+ }
40150
40191
  //#endregion
40151
40192
  //#region src/handlers/error-envelope.ts
40152
40193
  /**
@@ -40182,20 +40223,68 @@ function errorEnvelope(header, type, message) {
40182
40223
  } };
40183
40224
  }
40184
40225
  //#endregion
40185
- //#region src/handlers/discovery.ts
40226
+ //#region src/handlers/types.ts
40186
40227
  /**
40187
- * `Alexa.Discovery/Discover` handler — fires when the Alexa app pulls
40188
- * the user's device list. We respond with the operator-curated
40189
- * `exposed-devices.json` list, resolved against the live device
40190
- * registry (so we don't return zombie endpoints for deleted devices).
40228
+ * Zod schemas for the subset of the Alexa Smart Home directive surface
40229
+ * that we actually parse hub-side. The Smart Home Skill API ships
40230
+ * thousands of optional fields per namespace — we only validate what
40231
+ * we read; everything else passes through as `unknown`.
40191
40232
  *
40192
- * Feature detection is PASSIVE: per exposed device we inspect the
40193
- * `DeviceInfo.features` + bound caps (from `device-manager.getBindings`)
40194
- * and emit only the Alexa capabilities backed by something on our side.
40195
- * Child accessories (siren/floodlight/PIR/…) become SEPARATE endpoints
40196
- * with `endpointId = ${parent}__${child}` so directive handlers can
40197
- * route to the right cap on the right device.
40233
+ * Reference: https://developer.amazon.com/en-US/docs/alexa/smarthome/smart-home-skill-api-message-reference.html
40198
40234
  */
40235
+ /** A directive header carries namespace + name + token + correlation id. */
40236
+ var DirectiveHeaderSchema = object({
40237
+ namespace: string(),
40238
+ name: string(),
40239
+ payloadVersion: string(),
40240
+ messageId: string(),
40241
+ correlationToken: string().optional()
40242
+ });
40243
+ /** Scope carries the bearer token Alexa minted via our OAuth provider. */
40244
+ var BearerScopeSchema = object({
40245
+ type: literal("BearerToken"),
40246
+ token: string()
40247
+ });
40248
+ /** Endpoint reference inside a directive payload. */
40249
+ var EndpointRefSchema = object({
40250
+ endpointId: string(),
40251
+ scope: BearerScopeSchema.optional(),
40252
+ cookie: record(string(), string()).optional()
40253
+ });
40254
+ var DiscoveryDirectiveSchema = object({
40255
+ header: DirectiveHeaderSchema.extend({
40256
+ namespace: literal("Alexa.Discovery"),
40257
+ name: literal("Discover")
40258
+ }),
40259
+ payload: object({ scope: BearerScopeSchema })
40260
+ });
40261
+ /** Envelope wrapping a directive on the Alexa→skill wire. */
40262
+ var DirectiveRequestSchema = object({ directive: object({
40263
+ header: DirectiveHeaderSchema,
40264
+ endpoint: EndpointRefSchema.optional(),
40265
+ payload: unknown().optional()
40266
+ }) });
40267
+ var InitializeCameraStreamsPayloadSchema = object({ cameraStreams: array(object({
40268
+ protocol: string(),
40269
+ resolution: object({
40270
+ width: number(),
40271
+ height: number()
40272
+ }).optional(),
40273
+ authorizationType: string().optional(),
40274
+ videoCodec: string().optional(),
40275
+ audioCodec: string().optional()
40276
+ })).optional() });
40277
+ var InitiateSessionWithOfferPayloadSchema = object({
40278
+ sessionId: string(),
40279
+ offer: object({
40280
+ format: string().optional(),
40281
+ value: string()
40282
+ })
40283
+ });
40284
+ var SessionDisconnectedPayloadSchema = object({ sessionId: string() });
40285
+ var SetModePayloadSchema = object({ mode: string() });
40286
+ //#endregion
40287
+ //#region src/handlers/discovery.ts
40199
40288
  var discoveryPayloadSchema = DiscoveryDirectiveSchema.shape.payload;
40200
40289
  /** Devices built at once in `handleDiscovery` — latency-bound tRPC reads, so
40201
40290
  * six lanes hide the round-trips without stampeding a booting hub. */
@@ -40209,6 +40298,7 @@ var CAP_SWITCH = "switch";
40209
40298
  var CAP_BRIGHTNESS = "brightness";
40210
40299
  var CAP_BATTERY = "battery";
40211
40300
  var CAP_PRIVACY_MASK = "privacy-mask";
40301
+ var CAP_ALARM_PANEL = "alarm-panel";
40212
40302
  async function handleDiscovery(header, payloadRaw, deps, callerIdentity) {
40213
40303
  if (!discoveryPayloadSchema.safeParse(payloadRaw).success) return errorEnvelope(header, "INVALID_DIRECTIVE", "Discovery payload shape unexpected");
40214
40304
  const exposed = await deps.listExposed();
@@ -40248,6 +40338,7 @@ async function buildEndpointsForExposedDevice(deviceId, deps) {
40248
40338
  return [];
40249
40339
  }
40250
40340
  const parentInfo = await loadBoundDeviceInfo(device, api);
40341
+ if (parentInfo.capNames.includes(CAP_ALARM_PANEL)) return [await buildAlarmPanelEndpointFor(parentInfo, api, deps)];
40251
40342
  const children = await api.deviceManager.getChildren.query({ parentDeviceId: deviceId }).catch((err) => {
40252
40343
  deps.logger.warn("alexa discovery: getChildren failed", {
40253
40344
  tags: { deviceId },
@@ -40327,6 +40418,47 @@ async function buildEndpointsForExposedDevice(deviceId, deps) {
40327
40418
  }
40328
40419
  return out;
40329
40420
  }
40421
+ /**
40422
+ * The panel endpoint, with what the panel says it accepts.
40423
+ *
40424
+ * A `getStatus` that fails leaves `availableModes` empty and `requiresCode`
40425
+ * false, and those are the UNKNOWN readings, not assertions: an empty mode
40426
+ * list makes discovery declare all three arm states (`supportedArmStatesFor`)
40427
+ * rather than publishing a panel that can only be disarmed, and the directive
40428
+ * handler re-reads the panel before it commands anything, so a PIN discovered
40429
+ * later is still honoured. The blind read is logged against the device id.
40430
+ */
40431
+ async function buildAlarmPanelEndpointFor(info, api, deps) {
40432
+ const status = await api.alarmPanel.getStatus.query({ deviceId: info.id }).catch((err) => {
40433
+ deps.logger.warn("alexa discovery: alarmPanel.getStatus failed — declaring every arm state", {
40434
+ tags: { deviceId: info.id },
40435
+ meta: { error: err instanceof Error ? err.message : String(err) }
40436
+ });
40437
+ return null;
40438
+ });
40439
+ const parsed = AlarmPanelStatusSchema.pick({
40440
+ availableModes: true,
40441
+ requiresCode: true
40442
+ }).safeParse(status);
40443
+ if (!parsed.success && status !== null) deps.logger.warn("alexa discovery: panel status did not match the cap schema", { tags: { deviceId: info.id } });
40444
+ const availableModes = parsed.success ? parsed.data.availableModes : [];
40445
+ const requiresCode = parsed.success ? parsed.data.requiresCode : false;
40446
+ deps.logger.info("alexa discovery: built alarm panel endpoint", {
40447
+ tags: { deviceId: info.id },
40448
+ meta: {
40449
+ name: info.name,
40450
+ availableModes: [...availableModes],
40451
+ requiresCode
40452
+ }
40453
+ });
40454
+ return buildAlarmPanelEndpoint({
40455
+ deviceId: info.id,
40456
+ stableId: info.stableId,
40457
+ friendlyName: info.name,
40458
+ availableModes,
40459
+ requiresCode
40460
+ });
40461
+ }
40330
40462
  async function loadBoundDeviceInfo(device, api) {
40331
40463
  const capNames = (await api.deviceManager.getBindings.query({ deviceId: device.id })).entries.map((e) => e.capName);
40332
40464
  return {
@@ -40392,10 +40524,14 @@ function parseCameraEndpointId(raw) {
40392
40524
  kind: "privacy",
40393
40525
  parentDeviceId: parent
40394
40526
  };
40527
+ if (tail === "alarm") return {
40528
+ kind: "alarm-panel",
40529
+ deviceId: parent
40530
+ };
40395
40531
  const child = parseNonNegativeInt(tail);
40396
40532
  if (child === null) return {
40397
40533
  kind: "invalid",
40398
- reason: `child segment not numeric and not 'autotrack'/'privacy': ${raw}`
40534
+ reason: `child segment not numeric and not 'autotrack'/'privacy'/'alarm': ${raw}`
40399
40535
  };
40400
40536
  return {
40401
40537
  kind: "child",
@@ -40410,6 +40546,68 @@ function parseNonNegativeInt(s) {
40410
40546
  return n;
40411
40547
  }
40412
40548
  //#endregion
40549
+ //#region src/handlers/brightness-controller.ts
40550
+ var SetBrightnessDirectiveSchema = object({
40551
+ header: object({
40552
+ namespace: literal("Alexa.BrightnessController"),
40553
+ name: literal("SetBrightness")
40554
+ }),
40555
+ endpoint: EndpointRefSchema,
40556
+ payload: object({ brightness: number().min(0).max(100) })
40557
+ });
40558
+ async function handleSetBrightness(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
40559
+ const parsed = SetBrightnessDirectiveSchema.safeParse({
40560
+ header: {
40561
+ namespace: header.namespace,
40562
+ name: header.name
40563
+ },
40564
+ endpoint: endpointRaw,
40565
+ payload: payloadRaw ?? {}
40566
+ });
40567
+ if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
40568
+ const endpointId = parsed.data.endpoint.endpointId;
40569
+ const parsedId = parseCameraEndpointId(endpointId);
40570
+ 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`);
40571
+ if (parsedId.kind === "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", "BrightnessController is not exposed on camera endpoints — direct the directive at the dimmable child accessory");
40572
+ if (parsedId.kind === "invalid") return errorEnvelope(header, "INVALID_DIRECTIVE", parsedId.reason);
40573
+ const percentage = parsed.data.payload.brightness;
40574
+ const api = deps.ctx.api;
40575
+ try {
40576
+ await api.brightness.setBrightness.mutate({
40577
+ deviceId: parsedId.childDeviceId,
40578
+ percentage
40579
+ });
40580
+ } catch (err) {
40581
+ const message = err instanceof Error ? err.message : String(err);
40582
+ deps.logger.warn("alexa brightness-controller: setBrightness failed", { meta: {
40583
+ deviceId: parsedId.childDeviceId,
40584
+ percentage,
40585
+ error: message
40586
+ } });
40587
+ return errorEnvelope(header, "INTERNAL_ERROR", `brightness.setBrightness failed: ${message}`);
40588
+ }
40589
+ return {
40590
+ event: {
40591
+ header: {
40592
+ namespace: "Alexa",
40593
+ name: "Response",
40594
+ messageId: header.messageId,
40595
+ correlationToken: header.correlationToken,
40596
+ payloadVersion: "3"
40597
+ },
40598
+ endpoint: { endpointId },
40599
+ payload: {}
40600
+ },
40601
+ context: { properties: [{
40602
+ namespace: "Alexa.BrightnessController",
40603
+ name: "brightness",
40604
+ value: percentage,
40605
+ timeOfSample: (/* @__PURE__ */ new Date()).toISOString(),
40606
+ uncertaintyInMilliseconds: 500
40607
+ }] }
40608
+ };
40609
+ }
40610
+ //#endregion
40413
40611
  //#region src/handlers/camera-stream.ts
40414
40612
  /**
40415
40613
  * `Alexa.CameraStreamController/InitializeCameraStreams` handler.
@@ -40492,347 +40690,42 @@ async function handleInitializeCameraStreams(header, endpointRaw, payloadRaw, de
40492
40690
  } };
40493
40691
  }
40494
40692
  //#endregion
40495
- //#region src/handlers/rtc-session.ts
40496
- var InitiateSessionWithOfferDirectiveSchema = object({
40497
- endpoint: EndpointRefSchema,
40498
- payload: InitiateSessionWithOfferPayloadSchema
40499
- });
40500
- var SessionDisconnectedDirectiveSchema = object({
40501
- endpoint: EndpointRefSchema,
40502
- payload: SessionDisconnectedPayloadSchema
40503
- });
40504
- /**
40505
- * Live egress handles, keyed by `<deviceId>/<sessionId>`.
40506
- *
40507
- * The primitive's refcount has no lease TTL: a holder that vanishes without
40508
- * releasing leaks a child until the broker restarts (D67). This handler is a
40509
- * holder, so it keeps the one piece of state that lets it not be that holder —
40510
- * the `pipelineKey` its `SessionDisconnected` has to release.
40511
- *
40512
- * A module-level map is right here because the directive handlers are free
40513
- * functions called per directive; the entry is written on a successful acquire
40514
- * and deleted on the release path, both of which are the same tick as the
40515
- * directive that owns it.
40516
- */
40517
- var EGRESS_HANDLES = /* @__PURE__ */ new Map();
40518
- function egressHandleKey(deviceId, sessionId) {
40519
- return `${deviceId}/${sessionId}`;
40520
- }
40521
- var WEBRTC_PROFILE_NAMES = [
40522
- "high",
40523
- "mid",
40524
- "low"
40525
- ];
40526
- function resolveWebrtcTarget(pref) {
40527
- if (pref === "auto") return void 0;
40528
- if (WEBRTC_PROFILE_NAMES.includes(pref)) return {
40529
- kind: "profile",
40530
- profile: pref
40531
- };
40532
- return {
40533
- kind: "cam-stream",
40534
- camStreamId: pref
40535
- };
40536
- }
40537
- async function handleInitiateSessionWithOffer(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
40538
- const parsed = InitiateSessionWithOfferDirectiveSchema.safeParse({
40539
- endpoint: endpointRaw,
40540
- payload: payloadRaw ?? {}
40541
- });
40542
- if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
40543
- const endpoint = parsed.data.endpoint;
40544
- const payload = parsed.data.payload;
40545
- const parsedId = parseCameraEndpointId(endpoint.endpointId);
40546
- if (parsedId.kind !== "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", `endpointId ${endpoint.endpointId} is not a camera`);
40547
- const deviceId = parsedId.deviceId;
40548
- const sessionId = payload.sessionId;
40549
- const log = deps.logger.withTags({
40550
- deviceId,
40551
- sessionId
40552
- });
40553
- const sdpOffer = payload.offer.value;
40554
- if (sdpOffer.length === 0) return errorEnvelope(header, "INVALID_DIRECTIVE", "offer.value is empty");
40555
- const api = deps.ctx.api;
40556
- const exposedEntry = deps.listExposed().find((e) => e.deviceId === deviceId);
40557
- const explicitSourceProfile = exposedEntry?.settings?.sourceProfile;
40558
- const mappedFromPreference = (() => {
40559
- const pref = exposedEntry?.settings?.streamPreference;
40560
- if (pref === "low" || pref === "mid" || pref === "high") return pref;
40561
- })();
40562
- const sourceProfile = explicitSourceProfile ?? mappedFromPreference ?? "high";
40563
- let derivedTarget;
40564
- /**
40565
- * The primitive's release handle, when this session acquired one. Recorded so
40566
- * `SessionDisconnected` can release it: a refcount whose holder disappears is
40567
- * the one gap D67 leaves open, and the least this handler can do is not BE
40568
- * that holder.
40569
- */
40570
- let egressPipelineKey = null;
40571
- const picked = await api.cameraStreams.pickStream.query({
40572
- deviceId,
40573
- requirements: {
40574
- acceptCodecs: ["h264"],
40575
- minHeight: 480,
40576
- excludeDerived: true,
40577
- requireSiblingCodec: ["h265", "hevc"]
40578
- }
40579
- }).catch((err) => {
40580
- log.warn("alexa rtc-session: cameraStreams.pickStream threw — falling back to transcode", { meta: { error: err instanceof Error ? err.message : String(err) } });
40581
- return null;
40582
- });
40583
- if (picked) {
40584
- log.info("alexa rtc-session: bypassing transcode via cameraStreams.pickStream", { meta: {
40585
- sourceProfile,
40586
- selectedCamStreamId: picked.camStreamId,
40587
- reason: picked.reason
40588
- } });
40589
- derivedTarget = {
40590
- kind: "cam-stream",
40591
- camStreamId: picked.camStreamId
40592
- };
40593
- } else try {
40594
- const acquired = await acquireAlexaEgress({
40595
- api,
40596
- deviceId,
40597
- sourceProfile,
40598
- sessionId,
40599
- logger: log
40600
- });
40601
- egressPipelineKey = acquired.pipelineKey;
40602
- EGRESS_HANDLES.set(egressHandleKey(deviceId, sessionId), acquired.pipelineKey);
40603
- derivedTarget = {
40604
- kind: "cam-stream",
40605
- camStreamId: acquired.camStreamId
40606
- };
40607
- } catch (err) {
40608
- log.warn("alexa rtc-session: egress acquire failed, falling back to streamPreference target", { meta: { error: err instanceof Error ? err.message : String(err) } });
40609
- derivedTarget = resolveWebrtcTarget(exposedEntry?.settings?.streamPreference ?? "auto");
40610
- }
40611
- try {
40612
- const result = await api.webrtcSession.handleOffer.mutate({
40613
- deviceId,
40614
- sdpOffer,
40615
- sessionId,
40616
- target: derivedTarget,
40617
- relayOnly: false,
40618
- nonTrickle: true,
40619
- disableTurn: true,
40620
- disableIpv6: true,
40621
- consumerAttribution: {
40622
- kind: "alexa",
40623
- sessionId
40624
- }
40625
- });
40626
- log.info("alexa rtc-session: AnswerGenerated", { meta: {
40627
- returnedSessionId: result.sessionId,
40628
- sdpAnswerLen: result.sdpAnswer.length
40629
- } });
40630
- return { event: {
40631
- header: {
40632
- namespace: "Alexa.RTCSessionController",
40633
- name: "AnswerGeneratedForSession",
40634
- messageId: header.messageId,
40635
- correlationToken: header.correlationToken,
40636
- payloadVersion: "3"
40637
- },
40638
- endpoint: { endpointId: endpoint.endpointId },
40639
- payload: { answer: {
40640
- format: payload.offer.format ?? "SDP",
40641
- value: result.sdpAnswer
40642
- } }
40643
- } };
40644
- } catch (err) {
40645
- const message = err instanceof Error ? err.message : String(err);
40646
- const mSectionSummary = (() => {
40647
- const lines = sdpOffer.split(/\r?\n/);
40648
- const sections = [];
40649
- let current = null;
40650
- for (const raw of lines) {
40651
- const line = raw.trim();
40652
- if (line.startsWith("m=")) {
40653
- if (current) sections.push(current);
40654
- current = {
40655
- mid: null,
40656
- kind: line.split(" ")[0]?.slice(2) ?? "unknown",
40657
- direction: null,
40658
- codecs: []
40659
- };
40660
- } else if (current) {
40661
- if (line.startsWith("a=mid:")) current.mid = line.slice(6);
40662
- else if (/^a=(sendonly|recvonly|sendrecv|inactive)$/.test(line)) current.direction = line.slice(2);
40663
- else if (line.startsWith("a=rtpmap:")) current.codecs.push(line.slice(9));
40664
- }
40665
- }
40666
- if (current) sections.push(current);
40667
- return sections;
40668
- })();
40669
- log.warn("alexa rtc-session: handleOffer failed", { meta: {
40670
- error: message,
40671
- offerLen: sdpOffer.length,
40672
- mSections: mSectionSummary,
40673
- offerSdp: sdpOffer
40674
- } });
40675
- if (egressPipelineKey !== null) {
40676
- EGRESS_HANDLES.delete(egressHandleKey(deviceId, sessionId));
40677
- await releaseAlexaEgress({
40678
- api,
40679
- deviceId,
40680
- pipelineKey: egressPipelineKey,
40681
- logger: log
40682
- });
40683
- }
40684
- return errorEnvelope(header, "INTERNAL_ERROR", `webrtc-session.handleOffer failed: ${message}`);
40685
- }
40686
- }
40687
- async function handleSessionDisconnected(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
40688
- const parsed = SessionDisconnectedDirectiveSchema.safeParse({
40689
- endpoint: endpointRaw,
40690
- payload: payloadRaw ?? {}
40691
- });
40692
- if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
40693
- const endpoint = parsed.data.endpoint;
40694
- const parsedId = parseCameraEndpointId(endpoint.endpointId);
40695
- if (parsedId.kind === "camera") {
40696
- const handleKey = egressHandleKey(parsedId.deviceId, parsed.data.payload.sessionId);
40697
- const pipelineKey = EGRESS_HANDLES.get(handleKey);
40698
- if (pipelineKey !== void 0) {
40699
- EGRESS_HANDLES.delete(handleKey);
40700
- await releaseAlexaEgress({
40701
- api: deps.ctx.api,
40702
- deviceId: parsedId.deviceId,
40703
- pipelineKey,
40704
- logger: deps.logger
40705
- });
40706
- }
40707
- try {
40708
- await deps.ctx.api.webrtcSession.closeSession.mutate({
40709
- deviceId: parsedId.deviceId,
40710
- sessionId: parsed.data.payload.sessionId
40711
- });
40712
- } catch (err) {
40713
- deps.logger.warn("alexa rtc-session: closeSession threw on disconnect (continuing to ack)", {
40714
- tags: {
40715
- deviceId: parsedId.deviceId,
40716
- sessionId: parsed.data.payload.sessionId
40717
- },
40718
- meta: { error: err instanceof Error ? err.message : String(err) }
40719
- });
40720
- }
40721
- }
40722
- const disconnectedDeviceId = parsedId.kind === "camera" ? parsedId.deviceId : void 0;
40723
- deps.logger.info("alexa rtc-session: SessionDisconnected", {
40724
- tags: {
40725
- sessionId: parsed.data.payload.sessionId,
40726
- ...disconnectedDeviceId !== void 0 ? { deviceId: disconnectedDeviceId } : {}
40727
- },
40728
- meta: { endpointId: endpoint.endpointId }
40729
- });
40730
- return { event: {
40731
- header: {
40732
- namespace: "Alexa",
40733
- name: "Response",
40734
- messageId: header.messageId,
40735
- correlationToken: header.correlationToken,
40736
- payloadVersion: "3"
40737
- },
40738
- endpoint: { endpointId: endpoint.endpointId },
40739
- payload: {}
40740
- } };
40741
- }
40742
- //#endregion
40743
- //#region src/handlers/ptz-preset.ts
40744
- /**
40745
- * `Alexa.ModeController/SetMode` handler — dispatches three PTZ instances:
40746
- *
40747
- * `ptz.preset` — preset-recall. Decodes the preset name from the mode
40748
- * value and calls `ptz.goToPreset({deviceId, presetId})`.
40749
- *
40750
- * `ptz.pan` — momentary pan. `ptz.pan.left|right|center` issues a
40751
- * continuousMove pulse stopped on a timer; the dropdown reverts to
40752
- * `center` server-side so subsequent picks re-trigger the move.
40753
- *
40754
- * `ptz.tilt` — momentary tilt. Mirrors ptz.pan with up|down|center.
40755
- */
40756
- var SetModeDirectiveSchema = object({
40693
+ //#region src/handlers/power-controller.ts
40694
+ var PowerDirectiveSchema = object({
40757
40695
  header: object({
40758
- namespace: literal("Alexa.ModeController"),
40759
- name: literal("SetMode"),
40760
- instance: string().optional()
40696
+ namespace: literal("Alexa.PowerController"),
40697
+ name: _enum(["TurnOn", "TurnOff"])
40761
40698
  }),
40762
- endpoint: EndpointRefSchema,
40763
- payload: SetModePayloadSchema
40699
+ endpoint: EndpointRefSchema
40764
40700
  });
40765
- var PTZ_PRESET_MODE_PREFIX = "ptz.preset.";
40766
- var PTZ_DIRECTION_PULSE_MS = 1e3;
40767
- var PTZ_PAN_MOVES = {
40768
- "ptz.pan.left": { pan: -1 },
40769
- "ptz.pan.right": { pan: 1 },
40770
- "ptz.pan.center": {}
40771
- };
40772
- var PTZ_TILT_MOVES = {
40773
- "ptz.tilt.up": { tilt: 1 },
40774
- "ptz.tilt.down": { tilt: -1 },
40775
- "ptz.tilt.center": {}
40776
- };
40777
- async function handleSetMode(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
40778
- const parsed = SetModeDirectiveSchema.safeParse({
40701
+ async function handlePower(header, endpointRaw, deps, _callerIdentity) {
40702
+ const parsed = PowerDirectiveSchema.safeParse({
40779
40703
  header: {
40780
40704
  namespace: header.namespace,
40781
- name: header.name,
40782
- instance: header.instance
40705
+ name: header.name
40783
40706
  },
40784
- endpoint: endpointRaw,
40785
- payload: payloadRaw ?? {}
40707
+ endpoint: endpointRaw
40786
40708
  });
40787
40709
  if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
40788
- const instance = parsed.data.header.instance;
40789
- if (instance !== "ptz.preset" && instance !== "ptz.pan" && instance !== "ptz.tilt") return errorEnvelope(header, "INVALID_DIRECTIVE", `ModeController instance not supported: ${instance ?? "(missing)"}`);
40790
40710
  const endpointId = parsed.data.endpoint.endpointId;
40791
40711
  const parsedId = parseCameraEndpointId(endpointId);
40792
- if (parsedId.kind !== "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", `ModeController only supported on camera endpoints — got ${endpointId}`);
40793
- const mode = parsed.data.payload.mode;
40712
+ const on = parsed.data.header.name === "TurnOn";
40794
40713
  const api = deps.ctx.api;
40795
- if (instance === "ptz.pan" || instance === "ptz.tilt") {
40796
- const move = (instance === "ptz.pan" ? PTZ_PAN_MOVES : PTZ_TILT_MOVES)[mode];
40797
- if (!move) return errorEnvelope(header, "INVALID_DIRECTIVE", `mode '${mode}' is not a valid ${instance} mode`);
40798
- if (Object.keys(move).length === 0) await api.ptz.stop.mutate({ deviceId: parsedId.deviceId }).catch((err) => {
40799
- deps.logger.debug("alexa ptz-mode: stop (center) failed (non-fatal)", { meta: {
40800
- deviceId: parsedId.deviceId,
40801
- instance,
40802
- error: err instanceof Error ? err.message : String(err)
40803
- } });
40804
- });
40805
- else try {
40806
- await api.ptz.continuousMove.mutate({
40807
- deviceId: parsedId.deviceId,
40808
- ...move
40809
- });
40810
- setTimeout(() => {
40811
- api.ptz.stop.mutate({ deviceId: parsedId.deviceId }).catch((err) => {
40812
- deps.logger.debug("alexa ptz-mode: stop after pulse failed (non-fatal)", { meta: {
40813
- deviceId: parsedId.deviceId,
40814
- instance,
40815
- error: err instanceof Error ? err.message : String(err)
40816
- } });
40817
- });
40818
- }, PTZ_DIRECTION_PULSE_MS);
40819
- } catch (err) {
40820
- return errorEnvelope(header, "INTERNAL_ERROR", `ptz.continuousMove failed: ${err instanceof Error ? err.message : String(err)}`);
40821
- }
40822
- return modeSuccessResponse(header, endpointId, instance, instance === "ptz.pan" ? "ptz.pan.center" : "ptz.tilt.center");
40823
- }
40824
- if (!mode.startsWith(PTZ_PRESET_MODE_PREFIX)) return errorEnvelope(header, "INVALID_DIRECTIVE", `mode '${mode}' is not a ptz.preset mode`);
40825
- const presetName = mode.slice(11);
40826
- if (presetName.length === 0) return errorEnvelope(header, "INVALID_DIRECTIVE", "preset name missing after prefix");
40827
- const preset = (await api.ptz.getPresets.query({ deviceId: parsedId.deviceId })).find((p) => p.name === presetName);
40828
- if (!preset) return errorEnvelope(header, "INVALID_DIRECTIVE", `preset '${presetName}' not found on device ${parsedId.deviceId}`);
40829
- await api.ptz.goToPreset.mutate({
40830
- deviceId: parsedId.deviceId,
40831
- presetId: preset.id
40714
+ if (parsedId.kind === "autotrack") await api.ptzAutotrack.setEnabled.mutate({
40715
+ deviceId: parsedId.parentDeviceId,
40716
+ enabled: on
40832
40717
  });
40833
- return modeSuccessResponse(header, endpointId, "ptz.preset", mode);
40834
- }
40835
- function modeSuccessResponse(header, endpointId, instance, mode) {
40718
+ else if (parsedId.kind === "privacy") await api.privacyMask.setMask.mutate({
40719
+ deviceId: parsedId.parentDeviceId,
40720
+ patch: { enabled: on }
40721
+ });
40722
+ else if (parsedId.kind === "child") await api.switch.setState.mutate({
40723
+ deviceId: parsedId.childDeviceId,
40724
+ on
40725
+ });
40726
+ else if (parsedId.kind === "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", "PowerController is not exposed on camera endpoints — direct the directive at the child accessory");
40727
+ else if (parsedId.kind === "alarm-panel") return errorEnvelope(header, "INVALID_DIRECTIVE", "PowerController is not exposed on alarm-panel endpoints — use Alexa.SecurityPanelController");
40728
+ else return errorEnvelope(header, "INVALID_DIRECTIVE", parsedId.reason);
40836
40729
  return {
40837
40730
  event: {
40838
40731
  header: {
@@ -40846,10 +40739,9 @@ function modeSuccessResponse(header, endpointId, instance, mode) {
40846
40739
  payload: {}
40847
40740
  },
40848
40741
  context: { properties: [{
40849
- namespace: "Alexa.ModeController",
40850
- instance,
40851
- name: "mode",
40852
- value: mode,
40742
+ namespace: "Alexa.PowerController",
40743
+ name: "powerState",
40744
+ value: on ? "ON" : "OFF",
40853
40745
  timeOfSample: (/* @__PURE__ */ new Date()).toISOString(),
40854
40746
  uncertaintyInMilliseconds: 500
40855
40747
  }] }
@@ -40949,133 +40841,99 @@ function successResponse(header, endpointId, toggleState, instance) {
40949
40841
  };
40950
40842
  }
40951
40843
  //#endregion
40952
- //#region src/handlers/power-controller.ts
40953
- /**
40954
- * `Alexa.PowerController/{TurnOn,TurnOff}` handler.
40955
- *
40956
- * Routing decodes the endpoint id:
40957
- * - `${parent}__${child}` → call `switch.setState({deviceId: child, on})`
40958
- * - `${parent}__autotrack` → call `ptzAutotrack.setEnabled({deviceId: parent, enabled})`
40959
- * - `${parent}__privacy` → call `privacyMask.setMask({deviceId: parent, patch: { enabled } })`
40960
- * - `${deviceId}` (bare parent camera) → reject with INVALID_DIRECTIVE
40961
- * (we never expose PowerController on the camera itself).
40962
- *
40963
- * Auth: verify the directive's scope token (same as every other
40964
- * controller).
40965
- */
40966
- var PowerDirectiveSchema = object({
40967
- header: object({
40968
- namespace: literal("Alexa.PowerController"),
40969
- name: _enum(["TurnOn", "TurnOff"])
40970
- }),
40971
- endpoint: EndpointRefSchema
40972
- });
40973
- async function handlePower(header, endpointRaw, deps, _callerIdentity) {
40974
- const parsed = PowerDirectiveSchema.safeParse({
40975
- header: {
40976
- namespace: header.namespace,
40977
- name: header.name
40978
- },
40979
- endpoint: endpointRaw
40980
- });
40981
- if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
40982
- const endpointId = parsed.data.endpoint.endpointId;
40983
- const parsedId = parseCameraEndpointId(endpointId);
40984
- const on = parsed.data.header.name === "TurnOn";
40985
- const api = deps.ctx.api;
40986
- if (parsedId.kind === "autotrack") await api.ptzAutotrack.setEnabled.mutate({
40987
- deviceId: parsedId.parentDeviceId,
40988
- enabled: on
40989
- });
40990
- else if (parsedId.kind === "privacy") await api.privacyMask.setMask.mutate({
40991
- deviceId: parsedId.parentDeviceId,
40992
- patch: { enabled: on }
40993
- });
40994
- else if (parsedId.kind === "child") await api.switch.setState.mutate({
40995
- deviceId: parsedId.childDeviceId,
40996
- on
40997
- });
40998
- else if (parsedId.kind === "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", "PowerController is not exposed on camera endpoints — direct the directive at the child accessory");
40999
- else return errorEnvelope(header, "INVALID_DIRECTIVE", parsedId.reason);
41000
- return {
41001
- event: {
41002
- header: {
41003
- namespace: "Alexa",
41004
- name: "Response",
41005
- messageId: header.messageId,
41006
- correlationToken: header.correlationToken,
41007
- payloadVersion: "3"
41008
- },
41009
- endpoint: { endpointId },
41010
- payload: {}
41011
- },
41012
- context: { properties: [{
41013
- namespace: "Alexa.PowerController",
41014
- name: "powerState",
41015
- value: on ? "ON" : "OFF",
41016
- timeOfSample: (/* @__PURE__ */ new Date()).toISOString(),
41017
- uncertaintyInMilliseconds: 500
41018
- }] }
41019
- };
41020
- }
41021
- //#endregion
41022
- //#region src/handlers/brightness-controller.ts
40844
+ //#region src/handlers/ptz-preset.ts
41023
40845
  /**
41024
- * `Alexa.BrightnessController/SetBrightness` handler.
40846
+ * `Alexa.ModeController/SetMode` handler — dispatches three PTZ instances:
41025
40847
  *
41026
- * The Discovery handler declares `Alexa.BrightnessController` only on
41027
- * child accessory endpoints that bind the `brightness` cap (today:
41028
- * Reolink floodlights, Hikvision supplemental lights). Brightness is
41029
- * NEVER exposed on the parent camera endpoint or on the synthetic
41030
- * autotrack endpoint — both reject INVALID_DIRECTIVE here.
40848
+ * `ptz.preset` — preset-recall. Decodes the preset name from the mode
40849
+ * value and calls `ptz.goToPreset({deviceId, presetId})`.
41031
40850
  *
41032
- * Routing:
41033
- * - `${parent}__${child}` → `brightness.setBrightness({deviceId: child, percentage})`
40851
+ * `ptz.pan` — momentary pan. `ptz.pan.left|right|center` issues a
40852
+ * continuousMove pulse stopped on a timer; the dropdown reverts to
40853
+ * `center` server-side so subsequent picks re-trigger the move.
41034
40854
  *
41035
- * Auth: same scope-token verification path as the other controllers.
41036
- * The response carries the `Alexa.BrightnessController.brightness`
41037
- * property echoing the new level so the Echo updates its UI without an
41038
- * extra ReportState round-trip.
40855
+ * `ptz.tilt` — momentary tilt. Mirrors ptz.pan with up|down|center.
41039
40856
  */
41040
- var SetBrightnessDirectiveSchema = object({
40857
+ var SetModeDirectiveSchema = object({
41041
40858
  header: object({
41042
- namespace: literal("Alexa.BrightnessController"),
41043
- name: literal("SetBrightness")
40859
+ namespace: literal("Alexa.ModeController"),
40860
+ name: literal("SetMode"),
40861
+ instance: string().optional()
41044
40862
  }),
41045
40863
  endpoint: EndpointRefSchema,
41046
- payload: object({ brightness: number().min(0).max(100) })
40864
+ payload: SetModePayloadSchema
41047
40865
  });
41048
- async function handleSetBrightness(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41049
- const parsed = SetBrightnessDirectiveSchema.safeParse({
40866
+ var PTZ_PRESET_MODE_PREFIX = "ptz.preset.";
40867
+ var PTZ_DIRECTION_PULSE_MS = 1e3;
40868
+ var PTZ_PAN_MOVES = {
40869
+ "ptz.pan.left": { pan: -1 },
40870
+ "ptz.pan.right": { pan: 1 },
40871
+ "ptz.pan.center": {}
40872
+ };
40873
+ var PTZ_TILT_MOVES = {
40874
+ "ptz.tilt.up": { tilt: 1 },
40875
+ "ptz.tilt.down": { tilt: -1 },
40876
+ "ptz.tilt.center": {}
40877
+ };
40878
+ async function handleSetMode(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
40879
+ const parsed = SetModeDirectiveSchema.safeParse({
41050
40880
  header: {
41051
40881
  namespace: header.namespace,
41052
- name: header.name
40882
+ name: header.name,
40883
+ instance: header.instance
41053
40884
  },
41054
40885
  endpoint: endpointRaw,
41055
40886
  payload: payloadRaw ?? {}
41056
40887
  });
41057
40888
  if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
40889
+ const instance = parsed.data.header.instance;
40890
+ if (instance !== "ptz.preset" && instance !== "ptz.pan" && instance !== "ptz.tilt") return errorEnvelope(header, "INVALID_DIRECTIVE", `ModeController instance not supported: ${instance ?? "(missing)"}`);
41058
40891
  const endpointId = parsed.data.endpoint.endpointId;
41059
40892
  const parsedId = parseCameraEndpointId(endpointId);
41060
- if (parsedId.kind === "autotrack" || parsedId.kind === "privacy") return errorEnvelope(header, "INVALID_DIRECTIVE", `BrightnessController is not exposed on the ${parsedId.kind} endpoint`);
41061
- if (parsedId.kind === "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", "BrightnessController is not exposed on camera endpoints — direct the directive at the dimmable child accessory");
41062
- if (parsedId.kind === "invalid") return errorEnvelope(header, "INVALID_DIRECTIVE", parsedId.reason);
41063
- const percentage = parsed.data.payload.brightness;
40893
+ if (parsedId.kind !== "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", `ModeController only supported on camera endpoints — got ${endpointId}`);
40894
+ const mode = parsed.data.payload.mode;
41064
40895
  const api = deps.ctx.api;
41065
- try {
41066
- await api.brightness.setBrightness.mutate({
41067
- deviceId: parsedId.childDeviceId,
41068
- percentage
40896
+ if (instance === "ptz.pan" || instance === "ptz.tilt") {
40897
+ const move = (instance === "ptz.pan" ? PTZ_PAN_MOVES : PTZ_TILT_MOVES)[mode];
40898
+ if (!move) return errorEnvelope(header, "INVALID_DIRECTIVE", `mode '${mode}' is not a valid ${instance} mode`);
40899
+ if (Object.keys(move).length === 0) await api.ptz.stop.mutate({ deviceId: parsedId.deviceId }).catch((err) => {
40900
+ deps.logger.debug("alexa ptz-mode: stop (center) failed (non-fatal)", { meta: {
40901
+ deviceId: parsedId.deviceId,
40902
+ instance,
40903
+ error: err instanceof Error ? err.message : String(err)
40904
+ } });
41069
40905
  });
41070
- } catch (err) {
41071
- const message = err instanceof Error ? err.message : String(err);
41072
- deps.logger.warn("alexa brightness-controller: setBrightness failed", { meta: {
41073
- deviceId: parsedId.childDeviceId,
41074
- percentage,
41075
- error: message
41076
- } });
41077
- return errorEnvelope(header, "INTERNAL_ERROR", `brightness.setBrightness failed: ${message}`);
40906
+ else try {
40907
+ await api.ptz.continuousMove.mutate({
40908
+ deviceId: parsedId.deviceId,
40909
+ ...move
40910
+ });
40911
+ setTimeout(() => {
40912
+ api.ptz.stop.mutate({ deviceId: parsedId.deviceId }).catch((err) => {
40913
+ deps.logger.debug("alexa ptz-mode: stop after pulse failed (non-fatal)", { meta: {
40914
+ deviceId: parsedId.deviceId,
40915
+ instance,
40916
+ error: err instanceof Error ? err.message : String(err)
40917
+ } });
40918
+ });
40919
+ }, PTZ_DIRECTION_PULSE_MS);
40920
+ } catch (err) {
40921
+ return errorEnvelope(header, "INTERNAL_ERROR", `ptz.continuousMove failed: ${err instanceof Error ? err.message : String(err)}`);
40922
+ }
40923
+ return modeSuccessResponse(header, endpointId, instance, instance === "ptz.pan" ? "ptz.pan.center" : "ptz.tilt.center");
41078
40924
  }
40925
+ if (!mode.startsWith(PTZ_PRESET_MODE_PREFIX)) return errorEnvelope(header, "INVALID_DIRECTIVE", `mode '${mode}' is not a ptz.preset mode`);
40926
+ const presetName = mode.slice(11);
40927
+ if (presetName.length === 0) return errorEnvelope(header, "INVALID_DIRECTIVE", "preset name missing after prefix");
40928
+ const preset = (await api.ptz.getPresets.query({ deviceId: parsedId.deviceId })).find((p) => p.name === presetName);
40929
+ if (!preset) return errorEnvelope(header, "INVALID_DIRECTIVE", `preset '${presetName}' not found on device ${parsedId.deviceId}`);
40930
+ await api.ptz.goToPreset.mutate({
40931
+ deviceId: parsedId.deviceId,
40932
+ presetId: preset.id
40933
+ });
40934
+ return modeSuccessResponse(header, endpointId, "ptz.preset", mode);
40935
+ }
40936
+ function modeSuccessResponse(header, endpointId, instance, mode) {
41079
40937
  return {
41080
40938
  event: {
41081
40939
  header: {
@@ -41089,9 +40947,10 @@ async function handleSetBrightness(header, endpointRaw, payloadRaw, deps, _calle
41089
40947
  payload: {}
41090
40948
  },
41091
40949
  context: { properties: [{
41092
- namespace: "Alexa.BrightnessController",
41093
- name: "brightness",
41094
- value: percentage,
40950
+ namespace: "Alexa.ModeController",
40951
+ instance,
40952
+ name: "mode",
40953
+ value: mode,
41095
40954
  timeOfSample: (/* @__PURE__ */ new Date()).toISOString(),
41096
40955
  uncertaintyInMilliseconds: 500
41097
40956
  }] }
@@ -41112,6 +40971,7 @@ async function handleReportState(header, endpointRaw, deps, _callerIdentity) {
41112
40971
  else if (parsed.kind === "privacy") await collectPrivacyProperties(api, parsed.parentDeviceId, properties, nowIso, deps.logger);
41113
40972
  else if (parsed.kind === "autotrack") await collectAutotrackProperties(api, parsed.parentDeviceId, properties, nowIso, deps.logger);
41114
40973
  else if (parsed.kind === "child") await collectChildProperties(api, parsed.childDeviceId, properties, nowIso, deps.logger);
40974
+ else if (parsed.kind === "alarm-panel") await collectAlarmPanelProperties(api, parsed.deviceId, properties, nowIso, deps.logger);
41115
40975
  } catch (err) {
41116
40976
  deps.logger.warn("alexa report-state: collection failed", { meta: {
41117
40977
  endpointId,
@@ -41173,6 +41033,42 @@ async function collectCameraProperties(api, deviceId, properties, timeOfSample,
41173
41033
  uncertaintyInMilliseconds: 0
41174
41034
  });
41175
41035
  }
41036
+ /**
41037
+ * The panel's two declared properties.
41038
+ *
41039
+ * Both are omitted when the panel cannot be read — an `armState` we guessed
41040
+ * would be a claim about whether a house is locked, and Alexa rendering the
41041
+ * endpoint as unavailable is the truthful outcome of a panel nobody reached.
41042
+ * The failure is logged with the device id, never swallowed.
41043
+ */
41044
+ async function collectAlarmPanelProperties(api, deviceId, properties, timeOfSample, logger) {
41045
+ const status = await api.alarmPanel.getStatus.query({ deviceId }).catch((err) => {
41046
+ logger.warn("alexa report-state: alarmPanel.getStatus FAILED — Alexa will show the panel as unavailable", {
41047
+ tags: { deviceId },
41048
+ meta: { error: err instanceof Error ? err.message : String(err) }
41049
+ });
41050
+ return null;
41051
+ });
41052
+ const parsed = AlarmPanelStatusSchema.pick({ state: true }).safeParse(status);
41053
+ if (!parsed.success) {
41054
+ if (status !== null) logger.warn("alexa report-state: panel status did not match the cap schema — omitting", { tags: { deviceId } });
41055
+ return;
41056
+ }
41057
+ properties.push({
41058
+ namespace: "Alexa.SecurityPanelController",
41059
+ name: "armState",
41060
+ value: alexaArmStateFor(parsed.data.state),
41061
+ timeOfSample,
41062
+ uncertaintyInMilliseconds: 0
41063
+ });
41064
+ properties.push({
41065
+ namespace: "Alexa.SecurityPanelController",
41066
+ name: "burglaryAlarm",
41067
+ value: burglaryAlarmFor(parsed.data.state),
41068
+ timeOfSample,
41069
+ uncertaintyInMilliseconds: 0
41070
+ });
41071
+ }
41176
41072
  async function collectPrivacyProperties(api, parentDeviceId, properties, timeOfSample, _logger) {
41177
41073
  const status = await api.privacyMask.getStatus.query({ deviceId: parentDeviceId }).catch(() => null);
41178
41074
  const enabled = Boolean(status?.enabled);
@@ -41226,6 +41122,478 @@ async function collectChildProperties(api, childDeviceId, properties, timeOfSamp
41226
41122
  });
41227
41123
  }
41228
41124
  //#endregion
41125
+ //#region src/handlers/rtc-session.ts
41126
+ var InitiateSessionWithOfferDirectiveSchema = object({
41127
+ endpoint: EndpointRefSchema,
41128
+ payload: InitiateSessionWithOfferPayloadSchema
41129
+ });
41130
+ var SessionDisconnectedDirectiveSchema = object({
41131
+ endpoint: EndpointRefSchema,
41132
+ payload: SessionDisconnectedPayloadSchema
41133
+ });
41134
+ /**
41135
+ * Live egress handles, keyed by `<deviceId>/<sessionId>`.
41136
+ *
41137
+ * The primitive's refcount has no lease TTL: a holder that vanishes without
41138
+ * releasing leaks a child until the broker restarts (D67). This handler is a
41139
+ * holder, so it keeps the one piece of state that lets it not be that holder —
41140
+ * the `pipelineKey` its `SessionDisconnected` has to release.
41141
+ *
41142
+ * A module-level map is right here because the directive handlers are free
41143
+ * functions called per directive; the entry is written on a successful acquire
41144
+ * and deleted on the release path, both of which are the same tick as the
41145
+ * directive that owns it.
41146
+ */
41147
+ var EGRESS_HANDLES = /* @__PURE__ */ new Map();
41148
+ function egressHandleKey(deviceId, sessionId) {
41149
+ return `${deviceId}/${sessionId}`;
41150
+ }
41151
+ var WEBRTC_PROFILE_NAMES = [
41152
+ "high",
41153
+ "mid",
41154
+ "low"
41155
+ ];
41156
+ function resolveWebrtcTarget(pref) {
41157
+ if (pref === "auto") return void 0;
41158
+ if (WEBRTC_PROFILE_NAMES.includes(pref)) return {
41159
+ kind: "profile",
41160
+ profile: pref
41161
+ };
41162
+ return {
41163
+ kind: "cam-stream",
41164
+ camStreamId: pref
41165
+ };
41166
+ }
41167
+ async function handleInitiateSessionWithOffer(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41168
+ const parsed = InitiateSessionWithOfferDirectiveSchema.safeParse({
41169
+ endpoint: endpointRaw,
41170
+ payload: payloadRaw ?? {}
41171
+ });
41172
+ if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
41173
+ const endpoint = parsed.data.endpoint;
41174
+ const payload = parsed.data.payload;
41175
+ const parsedId = parseCameraEndpointId(endpoint.endpointId);
41176
+ if (parsedId.kind !== "camera") return errorEnvelope(header, "INVALID_DIRECTIVE", `endpointId ${endpoint.endpointId} is not a camera`);
41177
+ const deviceId = parsedId.deviceId;
41178
+ const sessionId = payload.sessionId;
41179
+ const log = deps.logger.withTags({
41180
+ deviceId,
41181
+ sessionId
41182
+ });
41183
+ const sdpOffer = payload.offer.value;
41184
+ if (sdpOffer.length === 0) return errorEnvelope(header, "INVALID_DIRECTIVE", "offer.value is empty");
41185
+ const api = deps.ctx.api;
41186
+ const exposedEntry = deps.listExposed().find((e) => e.deviceId === deviceId);
41187
+ const explicitSourceProfile = exposedEntry?.settings?.sourceProfile;
41188
+ const mappedFromPreference = (() => {
41189
+ const pref = exposedEntry?.settings?.streamPreference;
41190
+ if (pref === "low" || pref === "mid" || pref === "high") return pref;
41191
+ })();
41192
+ const sourceProfile = explicitSourceProfile ?? mappedFromPreference ?? "high";
41193
+ let derivedTarget;
41194
+ /**
41195
+ * The primitive's release handle, when this session acquired one. Recorded so
41196
+ * `SessionDisconnected` can release it: a refcount whose holder disappears is
41197
+ * the one gap D67 leaves open, and the least this handler can do is not BE
41198
+ * that holder.
41199
+ */
41200
+ let egressPipelineKey = null;
41201
+ const picked = await api.cameraStreams.pickStream.query({
41202
+ deviceId,
41203
+ requirements: {
41204
+ acceptCodecs: ["h264"],
41205
+ minHeight: 480,
41206
+ excludeDerived: true,
41207
+ requireSiblingCodec: ["h265", "hevc"]
41208
+ }
41209
+ }).catch((err) => {
41210
+ log.warn("alexa rtc-session: cameraStreams.pickStream threw — falling back to transcode", { meta: { error: err instanceof Error ? err.message : String(err) } });
41211
+ return null;
41212
+ });
41213
+ if (picked) {
41214
+ log.info("alexa rtc-session: bypassing transcode via cameraStreams.pickStream", { meta: {
41215
+ sourceProfile,
41216
+ selectedCamStreamId: picked.camStreamId,
41217
+ reason: picked.reason
41218
+ } });
41219
+ derivedTarget = {
41220
+ kind: "cam-stream",
41221
+ camStreamId: picked.camStreamId
41222
+ };
41223
+ } else try {
41224
+ const acquired = await acquireAlexaEgress({
41225
+ api,
41226
+ deviceId,
41227
+ sourceProfile,
41228
+ sessionId,
41229
+ logger: log
41230
+ });
41231
+ egressPipelineKey = acquired.pipelineKey;
41232
+ EGRESS_HANDLES.set(egressHandleKey(deviceId, sessionId), acquired.pipelineKey);
41233
+ derivedTarget = {
41234
+ kind: "cam-stream",
41235
+ camStreamId: acquired.camStreamId
41236
+ };
41237
+ } catch (err) {
41238
+ log.warn("alexa rtc-session: egress acquire failed, falling back to streamPreference target", { meta: { error: err instanceof Error ? err.message : String(err) } });
41239
+ derivedTarget = resolveWebrtcTarget(exposedEntry?.settings?.streamPreference ?? "auto");
41240
+ }
41241
+ try {
41242
+ const result = await api.webrtcSession.handleOffer.mutate({
41243
+ deviceId,
41244
+ sdpOffer,
41245
+ sessionId,
41246
+ target: derivedTarget,
41247
+ relayOnly: false,
41248
+ nonTrickle: true,
41249
+ disableTurn: true,
41250
+ disableIpv6: true,
41251
+ consumerAttribution: {
41252
+ kind: "alexa",
41253
+ sessionId
41254
+ }
41255
+ });
41256
+ log.info("alexa rtc-session: AnswerGenerated", { meta: {
41257
+ returnedSessionId: result.sessionId,
41258
+ sdpAnswerLen: result.sdpAnswer.length
41259
+ } });
41260
+ return { event: {
41261
+ header: {
41262
+ namespace: "Alexa.RTCSessionController",
41263
+ name: "AnswerGeneratedForSession",
41264
+ messageId: header.messageId,
41265
+ correlationToken: header.correlationToken,
41266
+ payloadVersion: "3"
41267
+ },
41268
+ endpoint: { endpointId: endpoint.endpointId },
41269
+ payload: { answer: {
41270
+ format: payload.offer.format ?? "SDP",
41271
+ value: result.sdpAnswer
41272
+ } }
41273
+ } };
41274
+ } catch (err) {
41275
+ const message = err instanceof Error ? err.message : String(err);
41276
+ const mSectionSummary = (() => {
41277
+ const lines = sdpOffer.split(/\r?\n/);
41278
+ const sections = [];
41279
+ let current = null;
41280
+ for (const raw of lines) {
41281
+ const line = raw.trim();
41282
+ if (line.startsWith("m=")) {
41283
+ if (current) sections.push(current);
41284
+ current = {
41285
+ mid: null,
41286
+ kind: line.split(" ")[0]?.slice(2) ?? "unknown",
41287
+ direction: null,
41288
+ codecs: []
41289
+ };
41290
+ } else if (current) {
41291
+ if (line.startsWith("a=mid:")) current.mid = line.slice(6);
41292
+ else if (/^a=(sendonly|recvonly|sendrecv|inactive)$/.test(line)) current.direction = line.slice(2);
41293
+ else if (line.startsWith("a=rtpmap:")) current.codecs.push(line.slice(9));
41294
+ }
41295
+ }
41296
+ if (current) sections.push(current);
41297
+ return sections;
41298
+ })();
41299
+ log.warn("alexa rtc-session: handleOffer failed", { meta: {
41300
+ error: message,
41301
+ offerLen: sdpOffer.length,
41302
+ mSections: mSectionSummary,
41303
+ offerSdp: sdpOffer
41304
+ } });
41305
+ if (egressPipelineKey !== null) {
41306
+ EGRESS_HANDLES.delete(egressHandleKey(deviceId, sessionId));
41307
+ await releaseAlexaEgress({
41308
+ api,
41309
+ deviceId,
41310
+ pipelineKey: egressPipelineKey,
41311
+ logger: log
41312
+ });
41313
+ }
41314
+ return errorEnvelope(header, "INTERNAL_ERROR", `webrtc-session.handleOffer failed: ${message}`);
41315
+ }
41316
+ }
41317
+ async function handleSessionDisconnected(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41318
+ const parsed = SessionDisconnectedDirectiveSchema.safeParse({
41319
+ endpoint: endpointRaw,
41320
+ payload: payloadRaw ?? {}
41321
+ });
41322
+ if (!parsed.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `payload validation failed: ${parsed.error.message}`);
41323
+ const endpoint = parsed.data.endpoint;
41324
+ const parsedId = parseCameraEndpointId(endpoint.endpointId);
41325
+ if (parsedId.kind === "camera") {
41326
+ const handleKey = egressHandleKey(parsedId.deviceId, parsed.data.payload.sessionId);
41327
+ const pipelineKey = EGRESS_HANDLES.get(handleKey);
41328
+ if (pipelineKey !== void 0) {
41329
+ EGRESS_HANDLES.delete(handleKey);
41330
+ await releaseAlexaEgress({
41331
+ api: deps.ctx.api,
41332
+ deviceId: parsedId.deviceId,
41333
+ pipelineKey,
41334
+ logger: deps.logger
41335
+ });
41336
+ }
41337
+ try {
41338
+ await deps.ctx.api.webrtcSession.closeSession.mutate({
41339
+ deviceId: parsedId.deviceId,
41340
+ sessionId: parsed.data.payload.sessionId
41341
+ });
41342
+ } catch (err) {
41343
+ deps.logger.warn("alexa rtc-session: closeSession threw on disconnect (continuing to ack)", {
41344
+ tags: {
41345
+ deviceId: parsedId.deviceId,
41346
+ sessionId: parsed.data.payload.sessionId
41347
+ },
41348
+ meta: { error: err instanceof Error ? err.message : String(err) }
41349
+ });
41350
+ }
41351
+ }
41352
+ const disconnectedDeviceId = parsedId.kind === "camera" ? parsedId.deviceId : void 0;
41353
+ deps.logger.info("alexa rtc-session: SessionDisconnected", {
41354
+ tags: {
41355
+ sessionId: parsed.data.payload.sessionId,
41356
+ ...disconnectedDeviceId !== void 0 ? { deviceId: disconnectedDeviceId } : {}
41357
+ },
41358
+ meta: { endpointId: endpoint.endpointId }
41359
+ });
41360
+ return { event: {
41361
+ header: {
41362
+ namespace: "Alexa",
41363
+ name: "Response",
41364
+ messageId: header.messageId,
41365
+ correlationToken: header.correlationToken,
41366
+ payloadVersion: "3"
41367
+ },
41368
+ endpoint: { endpointId: endpoint.endpointId },
41369
+ payload: {}
41370
+ } };
41371
+ }
41372
+ //#endregion
41373
+ //#region src/handlers/security-panel.ts
41374
+ var ArmPayloadSchema = object({ armState: _enum([
41375
+ "ARMED_STAY",
41376
+ "ARMED_AWAY",
41377
+ "ARMED_NIGHT"
41378
+ ]) });
41379
+ var DisarmPayloadSchema = object({ authorization: object({
41380
+ type: literal("FOUR_DIGIT_PIN"),
41381
+ value: string().min(1)
41382
+ }).optional() });
41383
+ /** The subset of the panel status the directives read. */
41384
+ var PanelReadSchema = AlarmPanelStatusSchema.pick({
41385
+ state: true,
41386
+ availableModes: true,
41387
+ requiresCode: true
41388
+ });
41389
+ /**
41390
+ * `Alexa.SecurityPanelController.ErrorResponse`.
41391
+ *
41392
+ * A namespace of its own, because the four types that matter here
41393
+ * (`AUTHORIZATION_REQUIRED`, `UNAUTHORIZED`, `NOT_READY_FOR_ARM`,
41394
+ * `BYPASS_NEEDED`) are only understood under it — the generic `Alexa`
41395
+ * `ErrorResponse` from `error-envelope.ts` carries none of them, and a PIN
41396
+ * problem reported there is a message the Alexa app cannot act on.
41397
+ */
41398
+ function securityPanelError(header, type, message) {
41399
+ return { event: {
41400
+ header: {
41401
+ namespace: "Alexa.SecurityPanelController",
41402
+ name: "ErrorResponse",
41403
+ messageId: header.messageId,
41404
+ correlationToken: header.correlationToken,
41405
+ payloadVersion: "3"
41406
+ },
41407
+ payload: {
41408
+ type,
41409
+ message
41410
+ }
41411
+ } };
41412
+ }
41413
+ /** Resolve the alarm panel this directive targets, or the refusal to send. */
41414
+ function resolveDeviceId(endpointRaw) {
41415
+ const parsedEndpoint = EndpointRefSchema.safeParse(endpointRaw);
41416
+ if (!parsedEndpoint.success) return { reason: "missing or malformed endpoint" };
41417
+ const parsedId = parseCameraEndpointId(parsedEndpoint.data.endpointId);
41418
+ if (parsedId.kind === "alarm-panel") return { deviceId: parsedId.deviceId };
41419
+ return { reason: `SecurityPanelController is only exposed on alarm-panel endpoints — got '${parsedEndpoint.data.endpointId}'` };
41420
+ }
41421
+ /**
41422
+ * What the panel currently accepts, or `null` when it could not be read.
41423
+ *
41424
+ * `null` is the honest answer and the callers treat it as unknown; nothing
41425
+ * here substitutes a default that would read as "accepts nothing, needs no
41426
+ * PIN".
41427
+ */
41428
+ async function readPanel(api, deviceId, logger, phase) {
41429
+ const raw = await api.alarmPanel.getStatus.query({ deviceId }).catch((err) => {
41430
+ logger.warn("alexa security-panel: alarmPanel.getStatus failed — proceeding without it", {
41431
+ tags: { deviceId },
41432
+ meta: {
41433
+ phase,
41434
+ error: err instanceof Error ? err.message : String(err)
41435
+ }
41436
+ });
41437
+ return null;
41438
+ });
41439
+ const parsed = PanelReadSchema.safeParse(raw);
41440
+ if (!parsed.success) {
41441
+ if (raw !== null) logger.warn("alexa security-panel: panel status did not match the cap schema", {
41442
+ tags: { deviceId },
41443
+ meta: { phase }
41444
+ });
41445
+ return null;
41446
+ }
41447
+ return parsed.data;
41448
+ }
41449
+ /** The `context.properties` block for a panel whose state we re-read. */
41450
+ function panelProperties(facts, fallback) {
41451
+ const timeOfSample = (/* @__PURE__ */ new Date()).toISOString();
41452
+ const parsedState = facts === null ? null : AlarmPanelStatusSchema.shape.state.parse(facts.state);
41453
+ const armState = parsedState === null ? fallback : alexaArmStateFor(parsedState);
41454
+ const burglary = parsedState === null ? { value: "OK" } : burglaryAlarmFor(parsedState);
41455
+ return [{
41456
+ namespace: "Alexa.SecurityPanelController",
41457
+ name: "armState",
41458
+ value: armState,
41459
+ timeOfSample,
41460
+ uncertaintyInMilliseconds: 0
41461
+ }, {
41462
+ namespace: "Alexa.SecurityPanelController",
41463
+ name: "burglaryAlarm",
41464
+ value: burglary,
41465
+ timeOfSample,
41466
+ uncertaintyInMilliseconds: 0
41467
+ }];
41468
+ }
41469
+ async function handleArm(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41470
+ const target = resolveDeviceId(endpointRaw);
41471
+ if (!("deviceId" in target)) return errorEnvelope(header, "INVALID_DIRECTIVE", target.reason);
41472
+ const { deviceId } = target;
41473
+ const payload = ArmPayloadSchema.safeParse(payloadRaw);
41474
+ if (!payload.success) {
41475
+ deps.logger.warn("alexa security-panel: Arm payload is not an arm state Alexa defines", {
41476
+ tags: { deviceId },
41477
+ meta: { error: payload.error.message }
41478
+ });
41479
+ return errorEnvelope(header, "INVALID_DIRECTIVE", `Arm payload unexpected: ${payload.error.message}`);
41480
+ }
41481
+ const requested = payload.data.armState;
41482
+ const api = deps.ctx.api;
41483
+ const facts = await readPanel(api, deviceId, deps.logger, "arm");
41484
+ if (facts?.requiresCode === true) {
41485
+ deps.logger.warn("alexa security-panel: panel requires a PIN and the Arm directive carries none — REFUSED", {
41486
+ tags: { deviceId },
41487
+ meta: { requested }
41488
+ });
41489
+ return securityPanelError(header, "AUTHORIZATION_REQUIRED", "this panel requires a PIN to arm, and Alexa cannot supply one on an Arm directive");
41490
+ }
41491
+ const mode = alarmArmModeForAlexa(requested, facts?.availableModes ?? []);
41492
+ if (mode === null) {
41493
+ deps.logger.warn("alexa security-panel: panel accepts no mode for this arm state — REFUSED", {
41494
+ tags: { deviceId },
41495
+ meta: {
41496
+ requested,
41497
+ availableModes: facts?.availableModes ?? null
41498
+ }
41499
+ });
41500
+ return securityPanelError(header, "NOT_READY_FOR_ARM", `panel does not accept ${requested}`);
41501
+ }
41502
+ try {
41503
+ await api.alarmPanel.arm.mutate({
41504
+ deviceId,
41505
+ mode
41506
+ });
41507
+ } catch (err) {
41508
+ deps.logger.warn("alexa security-panel: arm command failed", {
41509
+ tags: { deviceId },
41510
+ meta: {
41511
+ requested,
41512
+ mode,
41513
+ error: err instanceof Error ? err.message : String(err)
41514
+ }
41515
+ });
41516
+ return securityPanelError(header, "NOT_READY_FOR_ARM", err instanceof Error ? err.message : String(err));
41517
+ }
41518
+ deps.logger.info("alexa security-panel: armed", {
41519
+ tags: { deviceId },
41520
+ meta: {
41521
+ requested,
41522
+ mode
41523
+ }
41524
+ });
41525
+ const after = await readPanel(api, deviceId, deps.logger, "arm-confirm");
41526
+ if (after?.state === "arming") deps.logger.info("alexa security-panel: panel is in its exit delay — reporting DISARMED until it is set", {
41527
+ tags: { deviceId },
41528
+ meta: {
41529
+ requested,
41530
+ mode
41531
+ }
41532
+ });
41533
+ return {
41534
+ event: {
41535
+ header: {
41536
+ namespace: "Alexa.SecurityPanelController",
41537
+ name: "Arm.Response",
41538
+ messageId: header.messageId,
41539
+ correlationToken: header.correlationToken,
41540
+ payloadVersion: "3"
41541
+ },
41542
+ endpoint: { endpointId: `${deviceId}__alarm` },
41543
+ payload: {}
41544
+ },
41545
+ context: { properties: panelProperties(after, requested) }
41546
+ };
41547
+ }
41548
+ async function handleDisarm(header, endpointRaw, payloadRaw, deps, _callerIdentity) {
41549
+ const target = resolveDeviceId(endpointRaw);
41550
+ if (!("deviceId" in target)) return errorEnvelope(header, "INVALID_DIRECTIVE", target.reason);
41551
+ const { deviceId } = target;
41552
+ const payload = DisarmPayloadSchema.safeParse(payloadRaw ?? {});
41553
+ if (!payload.success) return errorEnvelope(header, "INVALID_DIRECTIVE", `Disarm payload unexpected: ${payload.error.message}`);
41554
+ const code = payload.data.authorization?.value;
41555
+ const api = deps.ctx.api;
41556
+ if ((await readPanel(api, deviceId, deps.logger, "disarm"))?.requiresCode === true && code === void 0) {
41557
+ deps.logger.warn("alexa security-panel: panel requires a PIN and the Disarm directive carried none — REFUSED", { tags: { deviceId } });
41558
+ return securityPanelError(header, "AUTHORIZATION_REQUIRED", "this panel requires a PIN to disarm");
41559
+ }
41560
+ try {
41561
+ await api.alarmPanel.disarm.mutate(code === void 0 ? { deviceId } : {
41562
+ deviceId,
41563
+ code
41564
+ });
41565
+ } catch (err) {
41566
+ const message = err instanceof Error ? err.message : String(err);
41567
+ deps.logger.warn("alexa security-panel: disarm command failed", {
41568
+ tags: { deviceId },
41569
+ meta: {
41570
+ codeSupplied: code !== void 0,
41571
+ error: message
41572
+ }
41573
+ });
41574
+ return code === void 0 ? errorEnvelope(header, "INTERNAL_ERROR", message) : securityPanelError(header, "UNAUTHORIZED", message);
41575
+ }
41576
+ deps.logger.info("alexa security-panel: disarmed", {
41577
+ tags: { deviceId },
41578
+ meta: { codeSupplied: code !== void 0 }
41579
+ });
41580
+ const after = await readPanel(api, deviceId, deps.logger, "disarm-confirm");
41581
+ return {
41582
+ event: {
41583
+ header: {
41584
+ namespace: "Alexa",
41585
+ name: "Response",
41586
+ messageId: header.messageId,
41587
+ correlationToken: header.correlationToken,
41588
+ payloadVersion: "3"
41589
+ },
41590
+ endpoint: { endpointId: `${deviceId}__alarm` },
41591
+ payload: {}
41592
+ },
41593
+ context: { properties: panelProperties(after, "DISARMED") }
41594
+ };
41595
+ }
41596
+ //#endregion
41229
41597
  //#region src/handlers/stubs.ts
41230
41598
  /**
41231
41599
  * Stub responder for namespaces not yet implemented (CameraStream /
@@ -41305,7 +41673,9 @@ async function dispatchDirective(rawBody, deps, callerIdentity) {
41305
41673
  "Alexa.ModeController/SetMode": "create",
41306
41674
  "Alexa.ToggleController/TurnOn": "create",
41307
41675
  "Alexa.ToggleController/TurnOff": "create",
41308
- "Alexa/ReportState": "view"
41676
+ "Alexa/ReportState": "view",
41677
+ "Alexa.SecurityPanelController/Arm": "create",
41678
+ "Alexa.SecurityPanelController/Disarm": "create"
41309
41679
  };
41310
41680
  try {
41311
41681
  const key = `${header.namespace}/${header.name}`;
@@ -41350,6 +41720,14 @@ async function dispatchDirective(rawBody, deps, callerIdentity) {
41350
41720
  status: 200,
41351
41721
  body: await handlePtzDirection(header, endpoint, deps.ptzDirection, callerIdentity)
41352
41722
  };
41723
+ if (key === "Alexa.SecurityPanelController/Arm") return {
41724
+ status: 200,
41725
+ body: await handleArm(header, endpoint, payload, deps.securityPanel, callerIdentity)
41726
+ };
41727
+ if (key === "Alexa.SecurityPanelController/Disarm") return {
41728
+ status: 200,
41729
+ body: await handleDisarm(header, endpoint, payload, deps.securityPanel, callerIdentity)
41730
+ };
41353
41731
  if (key === "Alexa/ReportState") return {
41354
41732
  status: 200,
41355
41733
  body: await handleReportState(header, endpoint, deps.reportState, callerIdentity)
@@ -42906,7 +43284,13 @@ var DEFAULT_CONFIG = {
42906
43284
  enforceIngressToken: false,
42907
43285
  staleEndpointPurgeInput: ""
42908
43286
  };
42909
- var SUPPORTED_KINDS = ["camera", "doorbell"];
43287
+ /** UI filter for the Export picker. `alarm-panel` publishes an
43288
+ * `Alexa.SecurityPanelController` endpoint (`endpoints/builder.ts`). */
43289
+ var SUPPORTED_KINDS = [
43290
+ "camera",
43291
+ "doorbell",
43292
+ DeviceType.AlarmPanel
43293
+ ];
42910
43294
  var ExportAlexaAddon = class extends BaseAddon {
42911
43295
  lwaGateway = null;
42912
43296
  syncEngine = null;
@@ -42975,6 +43359,10 @@ var ExportAlexaAddon = class extends BaseAddon {
42975
43359
  reportState: {
42976
43360
  ctx: this.ctx,
42977
43361
  logger: this.ctx.logger
43362
+ },
43363
+ securityPanel: {
43364
+ ctx: this.ctx,
43365
+ logger: this.ctx.logger
42978
43366
  }
42979
43367
  },
42980
43368
  lwaTokensCallbackDeps: {