@camstack/addon-provider-homeassistant 1.2.41 → 1.2.43

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.
@@ -3,7 +3,7 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  //#endregion
6
- const require_dist = require("../dist-t-5RdKBJ.js");
6
+ const require_dist = require("../dist-DiprHh6i.js");
7
7
  let node_crypto = require("node:crypto");
8
8
  //#region src/ha-export/topics.ts
9
9
  /**
@@ -1257,9 +1257,14 @@ function cameraSpecs(device) {
1257
1257
  }),
1258
1258
  (
1259
1259
  /**
1260
- * What was heard, and how loud. Fed by `pipeline.audio-inference-result`
1261
- * the event this addon did not subscribe to at all, which is why
1262
- * `audio_detected` below has effectively never moved.
1260
+ * What was heard, and how loud. Both fed by `pipeline.audio-inference-result`
1261
+ * via `projectAudioWindow` which is also where `audio_detected` (the
1262
+ * `audio` row of the macro loop below) gets its value now. Until this was
1263
+ * fixed, `audio_detected` was fed only by the track lifecycle, which
1264
+ * almost never carries an audio macro, so the entity existed and
1265
+ * effectively never moved: a comment right here used to claim this window
1266
+ * was already its source, and it was not — an avanzo that described the
1267
+ * right design while being false.
1263
1268
  *
1264
1269
  * `audio_last_sound`, NOT `audio_last_label`: `<macro>_last_label` is the
1265
1270
  * TRACK path's naming, reserved for the macros that carry an
@@ -1338,8 +1343,10 @@ function cameraSpecs(device) {
1338
1343
  enabledByDefault: false
1339
1344
  });
1340
1345
  /**
1341
- * One HA switch per AVAILABLE camera switch, rendered from
1342
- * `getCameraSwitches` and commanded back through `setCameraSwitch`.
1346
+ * One HA switch per AVAILABLE camera function, rendered from
1347
+ * `deriveCameraFunctions` and commanded back through
1348
+ * `resolveCameraFunctionWrite` + `applyCameraFunctionWrite` — each straight
1349
+ * onto the authority that already owns it (D62, D113 phase 4).
1343
1350
  *
1344
1351
  * The export never writes an authority itself: a second knob that can
1345
1352
  * disagree with the admin UI is worse than no knob (D62). An
@@ -1435,6 +1442,30 @@ function cameraSpecs(device) {
1435
1442
  entityCategory: "diagnostic",
1436
1443
  enabledByDefault: false
1437
1444
  });
1445
+ /**
1446
+ * `status` — the entity D62 exists for outside this repo. A camera an
1447
+ * operator switched off must never paint the same picture in Home
1448
+ * Assistant as one that is genuinely broken (`projectCameraStatus`).
1449
+ *
1450
+ * No `device_class`: HA's `enum` device class demands `options`, and a
1451
+ * `select` here would be a control that cannot be written — the dead
1452
+ * control this whole export refuses to ship.
1453
+ */
1454
+ specs.push({
1455
+ entity: "status",
1456
+ platform: "sensor",
1457
+ label: "Status",
1458
+ icon: "mdi:cctv",
1459
+ enabledByDefault: true
1460
+ });
1461
+ /** «Is it recording right now?» — `CameraStatus.recording.active`. */
1462
+ specs.push({
1463
+ entity: "recording_active",
1464
+ platform: "binary_sensor",
1465
+ label: "Recording",
1466
+ deviceClass: "running",
1467
+ enabledByDefault: true
1468
+ });
1438
1469
  specs.push({
1439
1470
  entity: "snooze",
1440
1471
  platform: "select",
@@ -2692,7 +2723,7 @@ var CAPS_NOT_EXPORTED = [
2692
2723
  },
2693
2724
  {
2694
2725
  cap: "privacy-mask",
2695
- reason: "Rendered as a camera switch through getCameraSwitches, never written directly (D62)."
2726
+ reason: "Rendered as two camera function switches (privacy-mask, device-audio) through deriveCameraFunctions, never written directly (D62, D113 phase 4)."
2696
2727
  },
2697
2728
  {
2698
2729
  cap: "zone-analytics",
@@ -2948,17 +2979,8 @@ function buildDevicePlan(device, options = UNNEGOTIATED_PLAN_OPTIONS) {
2948
2979
  * refusal carries a named reason so the log line says which of those it
2949
2980
  * was.
2950
2981
  */
2951
- /** The camera switch ids, keyed by the entity slug the catalog emits. */
2952
- var CAMERA_SWITCH_BY_SLUG = Object.fromEntries([
2953
- "stream-broker",
2954
- "object-detection",
2955
- "privacy-mask",
2956
- "device-audio",
2957
- "broker-audio",
2958
- "audio-analysis",
2959
- "recording",
2960
- "notifications"
2961
- ].map((id) => [toSlug(id), id]));
2982
+ /** The camera function ids, keyed by the entity slug the catalog emits. */
2983
+ var CAMERA_SWITCH_BY_SLUG = Object.fromEntries(require_dist.CAMERA_SWITCH_ORDER.map((id) => [toSlug(id), id]));
2962
2984
  var PTZ_DIRECTION_BY_ENTITY = Object.fromEntries(PTZ_BUTTONS.map((entity) => [entity, entity.slice(4)]));
2963
2985
  function parseBool(value) {
2964
2986
  const lower = value.trim().toLowerCase();
@@ -3543,7 +3565,7 @@ function resolveCommand(target, entity, value) {
3543
3565
  return {
3544
3566
  ok: true,
3545
3567
  command: {
3546
- kind: "camera-switch",
3568
+ kind: "camera-function",
3547
3569
  deviceId: target.deviceId,
3548
3570
  switchId,
3549
3571
  enabled
@@ -3703,7 +3725,7 @@ function build(builder, deviceId, value, capName) {
3703
3725
  */
3704
3726
  function isCameraCommand(command) {
3705
3727
  switch (command.kind) {
3706
- case "camera-switch":
3728
+ case "camera-function":
3707
3729
  case "reboot":
3708
3730
  case "ptz-move":
3709
3731
  case "ptz-preset":
@@ -3942,6 +3964,187 @@ async function call(slice, capName, make) {
3942
3964
  }
3943
3965
  return { ok: true };
3944
3966
  }
3967
+ //#endregion
3968
+ //#region src/ha-export/camera-function-writes.ts
3969
+ /**
3970
+ * Esegue la SCRITTURA di una funzione camera sull'autorità che la possiede.
3971
+ *
3972
+ * `deriveCameraFunctions`/`resolveCameraFunctionWrite` (`camera-functions.ts`)
3973
+ * decidono; questo modulo agisce. È il file che
3974
+ * `scripts/check-switch-successor-surfaces.ts` punta come successore della
3975
+ * coppia deprecata `getCameraSwitches` / `setCameraSwitch` (D113 fase 4).
3976
+ */
3977
+ async function applyCameraFunctionWrite(api, deviceId, write, sourceNodeId) {
3978
+ switch (write.kind) {
3979
+ case "device-disabled":
3980
+ await api.deviceManager.setDisabled.mutate({
3981
+ deviceId,
3982
+ disabled: write.disabled
3983
+ });
3984
+ return;
3985
+ case "wrapper-binding":
3986
+ await api.deviceManager.setWrapperActive.mutate({
3987
+ deviceId,
3988
+ capName: write.capName,
3989
+ wrapperAddonId: write.wrapperAddonId,
3990
+ active: write.active
3991
+ });
3992
+ return;
3993
+ case "recording-enabled": {
3994
+ const config = await api.recording.getDeviceConfig.query({ deviceId });
3995
+ await api.recording.setDeviceConfig.mutate({
3996
+ deviceId,
3997
+ config: {
3998
+ ...config,
3999
+ enabled: write.enabled
4000
+ }
4001
+ });
4002
+ return;
4003
+ }
4004
+ case "notification-mute":
4005
+ await api.notificationRules.setDeviceMuted.mutate({
4006
+ deviceId,
4007
+ muted: write.muted
4008
+ });
4009
+ return;
4010
+ case "camera-mask":
4011
+ await api.privacyMask.setMask.mutate({
4012
+ deviceId,
4013
+ patch: { enabled: write.enabled }
4014
+ });
4015
+ return;
4016
+ case "camera-audio":
4017
+ await api.privacyMask.setAudioEnabled.mutate({
4018
+ deviceId,
4019
+ enabled: write.enabled
4020
+ });
4021
+ return;
4022
+ case "broker-audio-mute":
4023
+ if (sourceNodeId === null) throw new Error(`refusing an unrouted broker audio write for device ${String(deviceId)}: no source node`);
4024
+ await api.streamBroker.setDeviceAudioMute.mutate({
4025
+ deviceId,
4026
+ muted: write.muted
4027
+ }, require_dist.nodePin(sourceNodeId));
4028
+ return;
4029
+ }
4030
+ }
4031
+ //#endregion
4032
+ //#region src/ha-export/camera-functions.ts
4033
+ var DETECTION_CAP = "detection-pipeline";
4034
+ var AUDIO_ANALYSIS_CAP = "audio-analysis";
4035
+ /** Ordine di resa: raggio d'azione più ampio prima, sorgente prima del consumatore. */
4036
+ var ORDER = [
4037
+ "stream-broker",
4038
+ "object-detection",
4039
+ "privacy-mask",
4040
+ "device-audio",
4041
+ "broker-audio",
4042
+ "audio-analysis",
4043
+ "recording",
4044
+ "notifications"
4045
+ ];
4046
+ var LABELS = {
4047
+ "stream-broker": "Camera",
4048
+ "object-detection": "Object detection & tracking",
4049
+ "privacy-mask": "Privacy mask",
4050
+ "device-audio": "Camera microphone",
4051
+ "broker-audio": "Audio distribution",
4052
+ "audio-analysis": "Audio detection & classification",
4053
+ recording: "Recording",
4054
+ notifications: "Notifications"
4055
+ };
4056
+ var UNAVAILABLE = {
4057
+ available: false,
4058
+ enabled: true
4059
+ };
4060
+ function resolveWrapper(capName, reads) {
4061
+ if (reads.bindableCapNames === null || reads.wrappedCapNames === null) return UNAVAILABLE;
4062
+ if (!reads.bindableCapNames.includes(capName)) return UNAVAILABLE;
4063
+ if (reads.wrapperAddonIdByCap.get(capName) === void 0) return UNAVAILABLE;
4064
+ return {
4065
+ available: true,
4066
+ enabled: reads.wrappedCapNames.includes(capName)
4067
+ };
4068
+ }
4069
+ function resolveOne(id, reads) {
4070
+ switch (id) {
4071
+ case "stream-broker": return reads.deviceDisabled === null ? UNAVAILABLE : {
4072
+ available: true,
4073
+ enabled: !reads.deviceDisabled
4074
+ };
4075
+ case "object-detection": return resolveWrapper(DETECTION_CAP, reads);
4076
+ case "audio-analysis": return resolveWrapper(AUDIO_ANALYSIS_CAP, reads);
4077
+ case "recording": return reads.recordingEnabled === null ? UNAVAILABLE : {
4078
+ available: true,
4079
+ enabled: reads.recordingEnabled
4080
+ };
4081
+ case "notifications": return reads.notificationsMuted === null ? UNAVAILABLE : {
4082
+ available: true,
4083
+ enabled: !reads.notificationsMuted
4084
+ };
4085
+ case "privacy-mask": return reads.privacy === null ? UNAVAILABLE : {
4086
+ available: true,
4087
+ enabled: reads.privacy.maskEnabled
4088
+ };
4089
+ case "device-audio": return reads.privacy === null || reads.privacy.audioEnabled === null ? UNAVAILABLE : {
4090
+ available: true,
4091
+ enabled: reads.privacy.audioEnabled
4092
+ };
4093
+ case "broker-audio": return reads.brokerAudioMuted === null ? UNAVAILABLE : {
4094
+ available: true,
4095
+ enabled: !reads.brokerAudioMuted
4096
+ };
4097
+ }
4098
+ }
4099
+ function deriveCameraFunctions(reads) {
4100
+ return ORDER.map((id) => ({
4101
+ id,
4102
+ label: LABELS[id],
4103
+ ...resolveOne(id, reads)
4104
+ }));
4105
+ }
4106
+ /** `null` = non disponibile: la scrittura va RIFIUTATA, non approssimata. */
4107
+ function resolveCameraFunctionWrite(id, on, reads) {
4108
+ if (!resolveOne(id, reads).available) return null;
4109
+ switch (id) {
4110
+ case "stream-broker": return {
4111
+ kind: "device-disabled",
4112
+ disabled: !on
4113
+ };
4114
+ case "object-detection":
4115
+ case "audio-analysis": {
4116
+ const capName = id === "object-detection" ? DETECTION_CAP : AUDIO_ANALYSIS_CAP;
4117
+ const wrapperAddonId = reads.wrapperAddonIdByCap.get(capName);
4118
+ if (wrapperAddonId === void 0) return null;
4119
+ return {
4120
+ kind: "wrapper-binding",
4121
+ capName,
4122
+ wrapperAddonId,
4123
+ active: on
4124
+ };
4125
+ }
4126
+ case "recording": return {
4127
+ kind: "recording-enabled",
4128
+ enabled: on
4129
+ };
4130
+ case "notifications": return {
4131
+ kind: "notification-mute",
4132
+ muted: !on
4133
+ };
4134
+ case "privacy-mask": return {
4135
+ kind: "camera-mask",
4136
+ enabled: on
4137
+ };
4138
+ case "device-audio": return {
4139
+ kind: "camera-audio",
4140
+ enabled: on
4141
+ };
4142
+ case "broker-audio": return {
4143
+ kind: "broker-audio-mute",
4144
+ muted: !on
4145
+ };
4146
+ }
4147
+ }
3945
4148
  /**
3946
4149
  * The ONE derivation of "a signed, expiring URL".
3947
4150
  *
@@ -4687,16 +4890,18 @@ function projectBatterySlice(deviceKey, slice) {
4687
4890
  }
4688
4891
  /**
4689
4892
  * The per-camera function switches, mirrored 1:1 from
4690
- * `pipelineOrchestrator.getCameraSwitches`.
4893
+ * `deriveCameraFunctions` (`camera-functions.ts`) — the pure derivation over
4894
+ * the AUTHORITIES that own each function, replacing the deprecated
4895
+ * `pipelineOrchestrator.getCameraSwitches` group (D113 phase 4).
4691
4896
  *
4692
- * An UNAVAILABLE switch publishes nothing, because `enabled` is
4897
+ * An UNAVAILABLE function publishes nothing, because `enabled` is
4693
4898
  * meaningless when `available` is false — a source that did not answer
4694
4899
  * must never become a control rendered `on`.
4695
4900
  */
4696
- function projectCameraSwitches(deviceKey, switches) {
4697
- return switches.filter((sw) => sw.available).map((sw) => ({
4698
- topic: stateTopic(deviceKey, toSlug(sw.id)),
4699
- value: bool(sw.enabled)
4901
+ function projectCameraFunctions(deviceKey, functions) {
4902
+ return functions.filter((fn) => fn.available).map((fn) => ({
4903
+ topic: stateTopic(deviceKey, toSlug(fn.id)),
4904
+ value: bool(fn.enabled)
4700
4905
  }));
4701
4906
  }
4702
4907
  /**
@@ -4762,12 +4967,88 @@ function projectAudioWindow(deviceKey, input) {
4762
4967
  value: String(Math.round(input.rms * 1e4) / 1e4)
4763
4968
  });
4764
4969
  const best = input.detections.reduce((top, d) => top === null || d.confidence > top.confidence ? d : top, null);
4970
+ /**
4971
+ * `audio_detected` — the source it never had. The catalog's comment used
4972
+ * to claim this window was already feeding it; it was not (grep found no
4973
+ * publisher), and that comment was a leftover describing the right design
4974
+ * while being false. This window is the fix: it raises on any window that
4975
+ * carries a classification and lowers on a quiet one, WITHOUT clearing
4976
+ * `audio_last_sound` — "what was that noise" is asked after the noise has
4977
+ * stopped.
4978
+ */
4979
+ values.push({
4980
+ topic: stateTopic(deviceKey, "audio_detected"),
4981
+ value: bool(best !== null)
4982
+ });
4765
4983
  if (best !== null) values.push({
4766
4984
  topic: stateTopic(deviceKey, "audio_last_sound"),
4767
4985
  value: best.className
4768
4986
  });
4769
4987
  return values;
4770
4988
  }
4989
+ /** Inverse of `SNOOZE_MINUTES` — a minute count back to the option label. */
4990
+ var SNOOZE_OPTION_BY_MINUTES = new Map(Object.entries(SNOOZE_MINUTES).map(([option, minutes]) => [minutes, option]));
4991
+ /**
4992
+ * The `snooze` select's STATE. The authority is
4993
+ * `notificationRules.listSnoozes`, which carries `startedAt`/`expiresAt` but
4994
+ * not the preset label an operator picked — there is nowhere to store that
4995
+ * label, and there must not be: it is reconstructed from the two timestamps
4996
+ * every time, so it can never drift from the authority.
4997
+ *
4998
+ * No active snooze publishes `Off`, never silence: Home Assistant reads a
4999
+ * missing state update as "the last value still holds", so a select gone
5000
+ * quiet after a snooze expires would keep showing the expired duration
5001
+ * forever.
5002
+ *
5003
+ * A duration the select's closed vocabulary cannot express — a snooze the
5004
+ * viewer created with an arbitrary minute count — publishes NOTHING.
5005
+ * Rounding it to the nearest preset would let Home Assistant re-send a
5006
+ * duration the operator never chose; `unknown` is the honest state.
5007
+ */
5008
+ function projectSnooze(deviceKey, window) {
5009
+ if (window === null) return [{
5010
+ topic: stateTopic(deviceKey, "snooze"),
5011
+ value: "Off"
5012
+ }];
5013
+ const minutes = Math.round((window.expiresAt - window.startedAt) / 6e4);
5014
+ const option = SNOOZE_OPTION_BY_MINUTES.get(minutes);
5015
+ if (option === void 0) return [];
5016
+ return [{
5017
+ topic: stateTopic(deviceKey, "snooze"),
5018
+ value: option
5019
+ }];
5020
+ }
5021
+ /**
5022
+ * `status` — the entity D62 exists for. A camera an operator switched off and
5023
+ * a camera that is genuinely broken must never paint the same picture in Home
5024
+ * Assistant: this is what tells the two apart.
5025
+ *
5026
+ * Order matters: the `switches` stage failing to answer makes the WHOLE
5027
+ * badge unknown, because an empty `switchedOff` is only a positive claim when
5028
+ * `degraded` does not name `switches` — reporting `ok` here would be the D62
5029
+ * failure landing inside the very field written to prevent it.
5030
+ */
5031
+ function projectCameraStatus(deviceKey, input) {
5032
+ const values = [{
5033
+ topic: stateTopic(deviceKey, "status"),
5034
+ value: cameraStatusToken(input)
5035
+ }];
5036
+ if (input.recording !== null) values.push({
5037
+ topic: stateTopic(deviceKey, "recording_active"),
5038
+ value: bool(input.recording.active)
5039
+ });
5040
+ else if (!input.degradedStages.includes("recording")) values.push({
5041
+ topic: stateTopic(deviceKey, "recording_active"),
5042
+ value: bool(false)
5043
+ });
5044
+ return values;
5045
+ }
5046
+ function cameraStatusToken(input) {
5047
+ if (input.degradedStages.includes("switches")) return "unknown";
5048
+ if (input.switchedOff.length > 0) return "switched_off";
5049
+ if (input.degradedStages.length > 0) return "degraded";
5050
+ return "ok";
5051
+ }
4771
5052
  //#endregion
4772
5053
  //#region src/ha-export/synthetic-devices.ts
4773
5054
  /**
@@ -4808,6 +5089,25 @@ function isSyntheticDeviceKey(deviceKey) {
4808
5089
  return SYNTHETIC_STABLE_IDS.some((id) => deviceKeyFor(id) === deviceKey);
4809
5090
  }
4810
5091
  /**
5092
+ * Pure derivation of the three alert entities (Task D1) — the conditions
5093
+ * nobody said, surfaced from `alerts.list`.
5094
+ *
5095
+ * Counts and raises the badge ONLY on `status: 'active'` alerts whose
5096
+ * `severity` is `warning` or `error`. `info` moves neither: a badge that
5097
+ * lights up on `info` teaches an operator to ignore it, which is how the
5098
+ * 2026-08-08 four-hour blackout produced not one visible alert despite the
5099
+ * liveness monitor's findings running the whole time.
5100
+ */
5101
+ function deriveAlertSummary(alerts) {
5102
+ const relevant = alerts.filter((a) => a.status === "active" && (a.severity === "warning" || a.severity === "error"));
5103
+ const last = relevant.reduce((top, a) => top === null || a.updatedAt > top.updatedAt ? a : top, null);
5104
+ return {
5105
+ active: relevant.length > 0,
5106
+ count: relevant.length,
5107
+ lastTitle: last?.title ?? null
5108
+ };
5109
+ }
5110
+ /**
4811
5111
  * Everything a synthetic device exports arrives ENABLED.
4812
5112
  *
4813
5113
  * The pressure valve exists for the camera fan-out — three zones is ~73
@@ -4880,6 +5180,21 @@ function notificationCenterSpecs(input) {
4880
5180
  icon: "mdi:counter",
4881
5181
  entityCategory: "diagnostic"
4882
5182
  },
5183
+ (
5184
+ /**
5185
+ * The GLOBAL snooze, as a control (Task D4) — the half `snoozed` (above)
5186
+ * never had. Its state is NOT projected here: `ha-export.addon.ts` pushes
5187
+ * it through the SAME `projectSnooze` a camera's snooze uses, so the rule
5188
+ * lives in one place — two expressions of it in two files is how
5189
+ * `audio_detected` went mute for a year.
5190
+ */
5191
+ {
5192
+ entity: "snooze",
5193
+ platform: "select",
5194
+ label: "Snooze all notifications",
5195
+ writable: true,
5196
+ options: SNOOZE_OPTIONS
5197
+ }),
4883
5198
  ...input.rules.map((rule) => ({
4884
5199
  entity: ruleEntity(rule.id),
4885
5200
  platform: "switch",
@@ -4941,6 +5256,56 @@ function serverSpecs(input) {
4941
5256
  deviceClass: "update",
4942
5257
  entityCategory: "diagnostic"
4943
5258
  },
5259
+ (
5260
+ /**
5261
+ * The conditions nobody said (Task D1) — `alerts.list`'s active,
5262
+ * warning-or-error findings. `info` never raises `alerts_active` or
5263
+ * inflates the count: a badge that lights up on `info` teaches an
5264
+ * operator to ignore it, which is how the four-hour blackout stayed
5265
+ * quiet through every liveness finding it produced.
5266
+ */
5267
+ {
5268
+ entity: "alerts_active",
5269
+ platform: "binary_sensor",
5270
+ label: "Alerts active",
5271
+ deviceClass: "problem"
5272
+ }),
5273
+ {
5274
+ entity: "alerts_active_count",
5275
+ platform: "sensor",
5276
+ label: "Active alerts",
5277
+ icon: "mdi:alert"
5278
+ },
5279
+ {
5280
+ entity: "alerts_last_title",
5281
+ platform: "sensor",
5282
+ label: "Last active alert",
5283
+ icon: "mdi:alert-circle-outline",
5284
+ entityCategory: "diagnostic"
5285
+ },
5286
+ (
5287
+ /** The oldest footage across the whole cluster (Task D2). */
5288
+ {
5289
+ entity: "oldest_footage",
5290
+ platform: "sensor",
5291
+ label: "Oldest footage",
5292
+ deviceClass: "timestamp",
5293
+ entityCategory: "diagnostic"
5294
+ }),
5295
+ (
5296
+ /**
5297
+ * The seed-vs-contract verdict (Task D3, D3's `image_contract`) — the
5298
+ * 2026-08-02 guasto, where `runningVersion` was current while the
5299
+ * container image was weeks old from a renamed repository nothing
5300
+ * rebuilt. Hub only: it describes THIS process's own image.
5301
+ */
5302
+ {
5303
+ entity: "image_contract",
5304
+ platform: "sensor",
5305
+ label: "Image contract",
5306
+ icon: "mdi:package-variant-closed-check",
5307
+ entityCategory: "diagnostic"
5308
+ }),
4944
5309
  ...input.nodes.flatMap((node) => {
4945
5310
  const slug = toSlug(node.id);
4946
5311
  return [
@@ -4969,7 +5334,38 @@ function serverSpecs(input) {
4969
5334
  platform: "sensor",
4970
5335
  label: `${node.name} uptime`,
4971
5336
  deviceClass: "timestamp"
4972
- }
5337
+ },
5338
+ (
5339
+ /** The disk (Task D2) — every node, hub included: every node records. */
5340
+ {
5341
+ entity: `${slug}_footage_used_bytes`,
5342
+ platform: "sensor",
5343
+ label: `${node.name} footage used`,
5344
+ deviceClass: "data_size",
5345
+ unit: "B",
5346
+ entityCategory: "diagnostic"
5347
+ }),
5348
+ {
5349
+ entity: `${slug}_footage_free_percent`,
5350
+ platform: "sensor",
5351
+ label: `${node.name} footage free`,
5352
+ unit: "%",
5353
+ icon: "mdi:harddisk",
5354
+ entityCategory: "diagnostic"
5355
+ },
5356
+ ...node.isHub ? [] : [{
5357
+ entity: `${slug}_version`,
5358
+ platform: "sensor",
5359
+ label: `${node.name} version`,
5360
+ icon: "mdi:tag",
5361
+ entityCategory: "diagnostic"
5362
+ }, {
5363
+ entity: `${slug}_update_available`,
5364
+ platform: "binary_sensor",
5365
+ label: `${node.name} update available`,
5366
+ deviceClass: "update",
5367
+ entityCategory: "diagnostic"
5368
+ }]
4973
5369
  ];
4974
5370
  })
4975
5371
  ];
@@ -5034,8 +5430,28 @@ function projectSynthetic(input, nowMs) {
5034
5430
  {
5035
5431
  topic: stateTopic(srv, "update_available"),
5036
5432
  value: String(input.updateAvailable)
5433
+ },
5434
+ {
5435
+ topic: stateTopic(srv, "alerts_active"),
5436
+ value: String(input.alertsActive)
5437
+ },
5438
+ {
5439
+ topic: stateTopic(srv, "alerts_active_count"),
5440
+ value: String(input.alertsActiveCount)
5037
5441
  }
5038
5442
  ];
5443
+ if (input.alertsLastTitle !== null) values.push({
5444
+ topic: stateTopic(srv, "alerts_last_title"),
5445
+ value: input.alertsLastTitle
5446
+ });
5447
+ if (input.oldestFootageMs !== null) values.push({
5448
+ topic: stateTopic(srv, "oldest_footage"),
5449
+ value: new Date(input.oldestFootageMs).toISOString()
5450
+ });
5451
+ if (input.imageContractState !== null) values.push({
5452
+ topic: stateTopic(srv, "image_contract"),
5453
+ value: input.imageContractState
5454
+ });
5039
5455
  for (const node of input.nodes) {
5040
5456
  const slug = toSlug(node.id);
5041
5457
  values.push({
@@ -5052,6 +5468,24 @@ function projectSynthetic(input, nowMs) {
5052
5468
  topic: stateTopic(srv, `${slug}_uptime`),
5053
5469
  value: (/* @__PURE__ */ new Date(nowMs - node.uptime * 1e3)).toISOString()
5054
5470
  });
5471
+ if (node.footageUsedBytes !== null) values.push({
5472
+ topic: stateTopic(srv, `${slug}_footage_used_bytes`),
5473
+ value: String(node.footageUsedBytes)
5474
+ });
5475
+ if (node.footageFreePercent !== null) values.push({
5476
+ topic: stateTopic(srv, `${slug}_footage_free_percent`),
5477
+ value: String(Math.round(node.footageFreePercent * 10) / 10)
5478
+ });
5479
+ if (!node.isHub) {
5480
+ if (node.rootPackageVersion !== null) values.push({
5481
+ topic: stateTopic(srv, `${slug}_version`),
5482
+ value: node.rootPackageVersion
5483
+ });
5484
+ if (node.updateAvailable !== null) values.push({
5485
+ topic: stateTopic(srv, `${slug}_update_available`),
5486
+ value: String(node.updateAvailable)
5487
+ });
5488
+ }
5055
5489
  }
5056
5490
  return values;
5057
5491
  }
@@ -5190,6 +5624,17 @@ var HaExportAddon = class extends require_dist.BaseAddon {
5190
5624
  */
5191
5625
  syntheticRules = [];
5192
5626
  /**
5627
+ * `pipelineOrchestrator.getCameraStatuses`, keyed by deviceId — ONE call
5628
+ * per reconcile pass for every exported camera (Task C3), never per
5629
+ * device: the input is optional and omitting it means "the whole fleet",
5630
+ * which is exactly the path this repo just finished removing from hot
5631
+ * loops. Feeds `status` / `recording_active` (Traccia C) and
5632
+ * `broker-audio`'s node pin (Traccia A2). Cleared to empty on a failed
5633
+ * read — never stale data from a previous pass, which would be a status
5634
+ * silently wrong rather than absent.
5635
+ */
5636
+ cameraStatusByDeviceId = /* @__PURE__ */ new Map();
5637
+ /**
5193
5638
  * A link that returned repairs NOW, not at the next periodic pass.
5194
5639
  *
5195
5640
  * `PushClient` drops its dedup cache the moment Home Assistant answers
@@ -5689,6 +6134,39 @@ var HaExportAddon = class extends require_dist.BaseAddon {
5689
6134
  const devices = await this.ctx.api.deviceManager.listAll.query({});
5690
6135
  const snapshots = await this.ctx.api.deviceState.getAllSnapshots.query({});
5691
6136
  const byId = new Map(devices.map((device) => [device.id, device]));
6137
+ /**
6138
+ * The exported cameras' `CameraStatus`, ONE call for every one of them
6139
+ * (Task C3). Computed BEFORE the per-device loop: `status`,
6140
+ * `recording_active` and `broker-audio`'s node pin all read from it, and
6141
+ * asking per camera would be the fan-out this repo just finished
6142
+ * removing from a 300 s poll.
6143
+ */
6144
+ const exposedIds = exposedDeviceIds(this.config.membership, enabled);
6145
+ const cameraDeviceIds = [];
6146
+ for (const idStr of exposedIds) {
6147
+ const numericId = Number(idStr);
6148
+ if (!Number.isFinite(numericId)) continue;
6149
+ const candidate = byId.get(numericId);
6150
+ if (candidate !== void 0 && candidate.type === "camera" && candidate.addonId !== "provider-homeassistant") cameraDeviceIds.push(numericId);
6151
+ }
6152
+ this.cameraStatusByDeviceId = await this.readCameraStatuses(cameraDeviceIds);
6153
+ /** `notificationRules.listDeviceMutes` — once per pass, a flat list. */
6154
+ const mutedDeviceIds = await this.ctx.api.notificationRules.listDeviceMutes.query({}).then((r) => r.mutedDeviceIds).catch((err) => {
6155
+ this.ctx.logger.warn("ha-export: could not read notification mutes, camera functions degrade", { meta: { error: errMsg(err) } });
6156
+ return null;
6157
+ });
6158
+ /** `deviceManager.listBindableCapsForDeviceType` — once per TYPE, not per device. */
6159
+ const bindableCapsByType = /* @__PURE__ */ new Map();
6160
+ /**
6161
+ * `notificationRules.listSnoozes` — ONE read for the whole pass, shared
6162
+ * by every camera's `snooze` select (Task B1) and the synthetic
6163
+ * `snooze` select on *Notification Center* (Task D4): two expressions
6164
+ * of the same read is how `audio_detected` went mute for a year.
6165
+ */
6166
+ const snoozes = await this.ctx.api.notificationRules.listSnoozes.query({}).then((r) => r.snoozes).catch((err) => {
6167
+ this.ctx.logger.warn("ha-export: could not read snoozes, snooze selects go unknown", { meta: { error: errMsg(err) } });
6168
+ return [];
6169
+ });
5692
6170
  const exported = /* @__PURE__ */ new Map();
5693
6171
  const keyByDeviceId = /* @__PURE__ */ new Map();
5694
6172
  const allCaps = /* @__PURE__ */ new Set();
@@ -5714,7 +6192,24 @@ var HaExportAddon = class extends require_dist.BaseAddon {
5714
6192
  this.ctx.logger.warn("ha-export: refusing to export a device imported from Home Assistant", { tags: { deviceId: numericId } });
5715
6193
  continue;
5716
6194
  }
5717
- const catalogDevice = await this.buildCatalogDevice(device, snapshots[String(numericId)]);
6195
+ /**
6196
+ * ONE collection of the eight function authorities per camera per
6197
+ * pass (Task A1/A3) — reused below by the announce (the switch
6198
+ * catalog, via `buildCatalogDevice`) AND by the state push
6199
+ * (`currentStateFor`, off `ExportedDevice.cameraFunctions`). The two
6200
+ * used to call the deprecated `getCameraSwitches` separately for the
6201
+ * same answer.
6202
+ */
6203
+ const cameraFunctions = device.type === "camera" ? deriveCameraFunctions(await this.readCameraFunctions({
6204
+ deviceId: numericId,
6205
+ deviceType: device.type,
6206
+ deviceDisabled: device.disabled,
6207
+ privacySlice: toSnapshot(snapshots[String(numericId)])["privacy-mask"],
6208
+ sourceNodeId: this.cameraStatusByDeviceId.get(numericId)?.assignment.sourceNodeId ?? null,
6209
+ bindableCapsByType,
6210
+ mutedDeviceIds
6211
+ })) : null;
6212
+ const catalogDevice = await this.buildCatalogDevice(device, snapshots[String(numericId)], cameraFunctions);
5718
6213
  for (const cap of catalogDevice.boundCaps) allCaps.add(cap);
5719
6214
  const brokerIds = brokersExposing(this.config.membership, deviceIdStr).filter((id) => enabled.includes(id));
5720
6215
  /**
@@ -5734,7 +6229,8 @@ var HaExportAddon = class extends require_dist.BaseAddon {
5734
6229
  boundCaps: catalogDevice.boundCaps
5735
6230
  },
5736
6231
  brokerIds,
5737
- streams: catalogDevice.streams ?? []
6232
+ streams: catalogDevice.streams ?? [],
6233
+ cameraFunctions
5738
6234
  });
5739
6235
  keyByDeviceId.set(numericId, plan.deviceKey);
5740
6236
  entityCount += Object.keys(plan.cmps).length;
@@ -5763,7 +6259,7 @@ var HaExportAddon = class extends require_dist.BaseAddon {
5763
6259
  * `brokerIds` is every enabled broker, because they belong to the server
5764
6260
  * and not to a membership the operator picks per camera.
5765
6261
  */
5766
- const synthetic = await this.buildSynthetic();
6262
+ const synthetic = await this.buildSynthetic(snoozes);
5767
6263
  if (synthetic !== null) for (const plan of syntheticPlans(synthetic)) {
5768
6264
  exported.set(plan.deviceKey, {
5769
6265
  plan,
@@ -5774,7 +6270,8 @@ var HaExportAddon = class extends require_dist.BaseAddon {
5774
6270
  boundCaps: []
5775
6271
  },
5776
6272
  brokerIds: [...enabled],
5777
- streams: []
6273
+ streams: [],
6274
+ cameraFunctions: null
5778
6275
  });
5779
6276
  entityCount += Object.keys(plan.cmps).length;
5780
6277
  }
@@ -5802,8 +6299,16 @@ var HaExportAddon = class extends require_dist.BaseAddon {
5802
6299
  }
5803
6300
  });
5804
6301
  await this.announce(exported);
5805
- await this.pushFullState(exported, snapshots);
5806
- if (synthetic !== null) await this.pushSynthetic(projectSynthetic(synthetic, Date.now()), [...enabled]);
6302
+ await this.pushFullState(exported, snapshots, snoozes);
6303
+ if (synthetic !== null) {
6304
+ /**
6305
+ * The global snooze's STATE (Task D4) rides the SAME `projectSnooze`
6306
+ * a camera's `snooze` select uses, over the SAME `snoozes` read this
6307
+ * pass already made — one expression of the rule, not two.
6308
+ */
6309
+ const ncKey = deviceKeyFor(NOTIFICATION_CENTER_STABLE_ID);
6310
+ await this.pushSynthetic([...projectSynthetic(synthetic, Date.now()), ...projectSnooze(ncKey, latestGlobalSnoozeWindow(snoozes))], [...enabled]);
6311
+ }
5807
6312
  this.ctx.logger.info("ha-export: reconciled", { meta: {
5808
6313
  reason,
5809
6314
  brokers: enabled.length,
@@ -5837,7 +6342,7 @@ var HaExportAddon = class extends require_dist.BaseAddon {
5837
6342
  * Returns `null` only when NOTHING answered, so the devices are not
5838
6343
  * announced empty on a hub that is still booting.
5839
6344
  */
5840
- async buildSynthetic() {
6345
+ async buildSynthetic(snoozes) {
5841
6346
  const rules = await this.ctx.api.notificationRules.listRules.query({}).then((r) => r.rules.map((rule) => ({
5842
6347
  id: rule.id,
5843
6348
  name: rule.name,
@@ -5846,15 +6351,9 @@ var HaExportAddon = class extends require_dist.BaseAddon {
5846
6351
  this.ctx.logger.warn("ha-export: could not read notification rules", { meta: { error: errMsg(err) } });
5847
6352
  return null;
5848
6353
  });
5849
- const snoozes = await this.ctx.api.notificationRules.listSnoozes.query({}).then((r) => r.snoozes.length > 0).catch(() => null);
5850
- const nodes = await this.ctx.api.nodes.topology.query().then((list) => list.map((node) => ({
5851
- id: node.id,
5852
- name: node.name,
5853
- online: node.isOnline,
5854
- cpuPercent: node.cpuPercent,
5855
- memoryPercent: node.memoryPercent,
5856
- uptime: node.uptime
5857
- }))).catch((err) => {
6354
+ /** Reuses the ONE `listSnoozes` read the pass already made (Task B1/D4). */
6355
+ const anySnoozed = snoozes.length > 0;
6356
+ const topology = await this.ctx.api.nodes.topology.query().catch((err) => {
5858
6357
  this.ctx.logger.warn("ha-export: could not read the cluster topology", { meta: { error: errMsg(err) } });
5859
6358
  return null;
5860
6359
  });
@@ -5869,16 +6368,92 @@ var HaExportAddon = class extends require_dist.BaseAddon {
5869
6368
  };
5870
6369
  }).catch(() => null);
5871
6370
  const server = await this.ctx.api.serverManagement.getServerPackageStatus.query().catch(() => null);
5872
- if (rules === null && nodes === null && addons === null && server === null) return null;
6371
+ const alerts = await this.readActiveAlerts();
6372
+ if (rules === null && topology === null && addons === null && server === null) return null;
5873
6373
  this.syntheticRules = rules ?? this.syntheticRules;
6374
+ const { nodes, oldestFootageMs } = await this.buildSyntheticNodes(topology ?? []);
5874
6375
  return {
5875
6376
  rules: rules ?? this.syntheticRules,
5876
- snoozed: snoozes ?? false,
5877
- nodes: nodes ?? [],
6377
+ snoozed: anySnoozed,
6378
+ nodes,
5878
6379
  addonsRunning: addons?.running ?? 0,
5879
6380
  addonsFailed: addons?.failed ?? 0,
5880
6381
  serverVersion: server?.runningVersion ?? server?.activeVersion ?? "unknown",
5881
- updateAvailable: server?.updateAvailable ?? false
6382
+ updateAvailable: server?.updateAvailable ?? false,
6383
+ alertsActive: alerts.active,
6384
+ alertsActiveCount: alerts.count,
6385
+ alertsLastTitle: alerts.lastTitle,
6386
+ oldestFootageMs,
6387
+ imageContractState: server?.imageContract?.state ?? null
6388
+ };
6389
+ }
6390
+ /**
6391
+ * `alerts.list` — the conditions nobody said (Task D1). Best-effort: a
6392
+ * failed read yields "nothing active", not a fabricated absence dressed up
6393
+ * as a clean one — this addon logs the drop rather than pretending the
6394
+ * cluster is quiet. The derivation itself is pure — see
6395
+ * `deriveAlertSummary` in `synthetic-devices.ts`, which is what is tested.
6396
+ */
6397
+ async readActiveAlerts() {
6398
+ try {
6399
+ return deriveAlertSummary(await this.ctx.api.alerts.list.query({
6400
+ unreadOnly: false,
6401
+ limit: 50
6402
+ }));
6403
+ } catch (err) {
6404
+ this.ctx.logger.warn("ha-export: could not read alerts, the alert entities go quiet", { meta: { error: errMsg(err) } });
6405
+ return {
6406
+ active: false,
6407
+ count: 0,
6408
+ lastTitle: null
6409
+ };
6410
+ }
6411
+ }
6412
+ /**
6413
+ * Per-node disk usage (Task D2) and per-AGENT package status (Task D3),
6414
+ * fanned out from the topology this pass already read. Bounded per node —
6415
+ * one unreachable node degrades its own two rows, never the others'.
6416
+ */
6417
+ async buildSyntheticNodes(topology) {
6418
+ let oldestFootageMs = null;
6419
+ return {
6420
+ nodes: await Promise.all(topology.map(async (node) => {
6421
+ const disk = await this.ctx.api.recording.getStorageUsage.query({}, require_dist.nodePin(node.id)).catch((err) => {
6422
+ this.ctx.logger.warn("ha-export: could not read storage usage for a node, its disk entities go unknown", { meta: {
6423
+ nodeId: node.id,
6424
+ error: errMsg(err)
6425
+ } });
6426
+ return null;
6427
+ });
6428
+ const freePercents = (disk?.locations ?? []).filter((loc) => loc.availableBytes !== null && loc.totalBytes !== null && loc.totalBytes > 0).map((loc) => loc.availableBytes / loc.totalBytes * 100);
6429
+ const footageFreePercent = freePercents.length > 0 ? Math.min(...freePercents) : null;
6430
+ for (const device of disk?.devices ?? []) {
6431
+ const oldest = device.oldestMs;
6432
+ if (oldest === null || oldest === void 0) continue;
6433
+ if (oldestFootageMs === null || oldest < oldestFootageMs) oldestFootageMs = oldest;
6434
+ }
6435
+ const packageStatus = node.isHub ? null : await this.ctx.api.serverManagement.getServerPackageStatus.query({ nodeId: node.id }).catch((err) => {
6436
+ this.ctx.logger.warn("ha-export: could not read package status for an agent node, its update entities go unknown", { meta: {
6437
+ nodeId: node.id,
6438
+ error: errMsg(err)
6439
+ } });
6440
+ return null;
6441
+ });
6442
+ return {
6443
+ id: node.id,
6444
+ name: node.name,
6445
+ online: node.isOnline,
6446
+ cpuPercent: node.cpuPercent,
6447
+ memoryPercent: node.memoryPercent,
6448
+ uptime: node.uptime,
6449
+ isHub: node.isHub,
6450
+ footageUsedBytes: disk?.totalUsedBytes ?? null,
6451
+ footageFreePercent,
6452
+ rootPackageVersion: node.rootPackage?.version ?? null,
6453
+ updateAvailable: packageStatus?.updateAvailable ?? null
6454
+ };
6455
+ })),
6456
+ oldestFootageMs
5882
6457
  };
5883
6458
  }
5884
6459
  /** Push the synthetic values to every enabled broker. */
@@ -5906,9 +6481,9 @@ var HaExportAddon = class extends require_dist.BaseAddon {
5906
6481
  }
5907
6482
  }
5908
6483
  }
5909
- async pushFullState(exported, snapshots) {
6484
+ async pushFullState(exported, snapshots, snoozes) {
5910
6485
  for (const entry of exported.values()) try {
5911
- const values = await this.currentStateFor(entry, snapshots[String(entry.deviceId)]);
6486
+ const values = await this.currentStateFor(entry, snapshots[String(entry.deviceId)], snoozes);
5912
6487
  this.push(entry.deviceId, values);
5913
6488
  } catch (err) {
5914
6489
  this.ctx.logger.warn("ha-export: could not read current state for a device", {
@@ -5919,7 +6494,7 @@ var HaExportAddon = class extends require_dist.BaseAddon {
5919
6494
  for (const link of this.links.values()) await link.client.flush();
5920
6495
  }
5921
6496
  /** Everything readable without waiting for an event. */
5922
- async currentStateFor(entry, snapshotRaw) {
6497
+ async currentStateFor(entry, snapshotRaw, snoozes) {
5923
6498
  const key = entry.plan.deviceKey;
5924
6499
  const values = [];
5925
6500
  const snapshot = toSnapshot(snapshotRaw);
@@ -5989,13 +6564,26 @@ var HaExportAddon = class extends require_dist.BaseAddon {
5989
6564
  * video itself. The url this block used to publish was read by
5990
6565
  * nobody — see `camera-entities.ts`.
5991
6566
  */
5992
- const group = await this.ctx.api.pipelineOrchestrator.getCameraSwitches.query({ deviceId: entry.deviceId });
5993
- values.push(...projectCameraSwitches(key, group.switches.map((sw) => ({
5994
- id: sw.id,
5995
- label: sw.label,
5996
- available: sw.available,
5997
- enabled: sw.enabled
5998
- }))));
6567
+ values.push(...projectCameraFunctions(key, entry.cameraFunctions ?? []));
6568
+ /**
6569
+ * `status` / `recording_active` (Traccia C) — off the SAME
6570
+ * `CameraStatus` `runReconcile` already read once for the whole pass
6571
+ * (Task C3). A camera the batch read did not cover (the call failed
6572
+ * entirely, or a camera added mid-pass) publishes NEITHER: an invented
6573
+ * `ok` is the D62 failure this entity exists to prevent.
6574
+ */
6575
+ const cameraStatus = this.cameraStatusByDeviceId.get(entry.deviceId);
6576
+ if (cameraStatus !== void 0) values.push(...projectCameraStatus(key, toCameraStatusInput(cameraStatus)));
6577
+ /**
6578
+ * `snooze` (Task B1) — reconstructed from `notificationRules.listSnoozes`,
6579
+ * never stored: the select's state is the SAME authority the write path
6580
+ * (`applySnooze`) already uses.
6581
+ */
6582
+ const snoozeValues = projectSnooze(key, latestDeviceSnoozeWindow(snoozes, entry.deviceId));
6583
+ if (snoozeValues.length === 0) {
6584
+ if (snoozes.filter((s) => s.scope === "device" && s.deviceId === entry.deviceId).length > 0) this.ctx.logger.debug("ha-export: an active snooze has a duration the select cannot express, publishing nothing", { tags: { deviceId: entry.deviceId } });
6585
+ }
6586
+ values.push(...snoozeValues);
5999
6587
  const occupancy = await this.ctx.api.zoneAnalytics.getCurrentSnapshot.query({ deviceId: entry.deviceId });
6000
6588
  if (occupancy !== null) values.push(...projectZoneOccupancy(key, {
6001
6589
  zones: occupancy.zones.map((zone) => ({
@@ -6011,11 +6599,20 @@ var HaExportAddon = class extends require_dist.BaseAddon {
6011
6599
  }
6012
6600
  return values;
6013
6601
  }
6014
- async buildCatalogDevice(device, snapshotRaw) {
6602
+ async buildCatalogDevice(device, snapshotRaw, cameraFunctions) {
6015
6603
  const snapshot = toSnapshot(snapshotRaw);
6016
6604
  const boundCaps = await this.loadBoundCaps(device.id);
6017
6605
  const zones = device.type === "camera" ? await this.loadZones(device.id) : [];
6018
- const switches = device.type === "camera" ? await this.loadSwitches(device.id) : [];
6606
+ /**
6607
+ * Every camera function, available or not — `entity-catalog.ts` is the
6608
+ * one place that filters to `available`, exactly as it did for
6609
+ * `getCameraSwitches`'s answer.
6610
+ */
6611
+ const switches = (cameraFunctions ?? []).map((fn) => ({
6612
+ id: fn.id,
6613
+ label: fn.label,
6614
+ available: fn.available
6615
+ }));
6019
6616
  const ptzPresets = device.type === "camera" && boundCaps.includes("ptz") ? await this.loadPresets(device.id) : [];
6020
6617
  const streams = device.type === "camera" && boundCaps.includes("webrtc-session") ? await this.loadStreamChoices(device.id) : [];
6021
6618
  const manufacturer = readString(device.metadata ?? {}, "manufacturer");
@@ -6101,25 +6698,118 @@ var HaExportAddon = class extends require_dist.BaseAddon {
6101
6698
  return [];
6102
6699
  }
6103
6700
  }
6104
- async loadSwitches(deviceId) {
6701
+ /**
6702
+ * `pipelineOrchestrator.getCameraStatuses`, for every exported camera in
6703
+ * ONE call (Task C3). Best-effort for the WHOLE batch: a failure here means
6704
+ * `status`, `recording_active` and every `broker-audio` control degrade for
6705
+ * this pass — never a value invented from a previous pass's answer.
6706
+ */
6707
+ async readCameraStatuses(deviceIds) {
6708
+ if (deviceIds.length === 0) return /* @__PURE__ */ new Map();
6709
+ const startedAt = Date.now();
6105
6710
  try {
6106
- return (await this.ctx.api.pipelineOrchestrator.getCameraSwitches.query({ deviceId })).switches.map((sw) => ({
6107
- id: sw.id,
6108
- label: sw.label,
6109
- available: sw.available
6110
- }));
6711
+ const statuses = await this.ctx.api.pipelineOrchestrator.getCameraStatuses.query({ deviceIds: [...deviceIds] });
6712
+ this.ctx.logger.debug("ha-export: read camera statuses for the pass", { meta: {
6713
+ cameraStatusMs: Date.now() - startedAt,
6714
+ cameras: deviceIds.length
6715
+ } });
6716
+ return new Map(statuses.map((status) => [status.deviceId, status]));
6111
6717
  } catch (err) {
6112
- /**
6113
- * A source that did not answer produces NO control, never one
6114
- * defaulted to on. This is the rule `CameraSwitch.available`
6115
- * exists to enforce, and it has to survive the read failing.
6116
- */
6117
- this.ctx.logger.warn("ha-export: could not read camera switches, exporting no controls", {
6718
+ this.ctx.logger.warn("ha-export: could not read camera statuses — status, recording_active and broker-audio degrade for every exported camera this pass", { meta: {
6719
+ error: errMsg(err),
6720
+ cameras: deviceIds.length
6721
+ } });
6722
+ return /* @__PURE__ */ new Map();
6723
+ }
6724
+ }
6725
+ /**
6726
+ * The eight per-camera function authorities (Task A1), assembled into
6727
+ * {@link CameraFunctionReads}. Every source degrades INDEPENDENTLY with a
6728
+ * WARN carrying `tags: { deviceId }` — a dropped authority must never look
6729
+ * like "this function does not exist" (D62).
6730
+ *
6731
+ * `bindableCapsByType`/`mutedDeviceIds` are the reconcile pass's shared
6732
+ * caches when the caller has them (a per-TYPE lookup and a flat list read
6733
+ * once for the whole pass); omitted, each is read fresh — the one-off
6734
+ * command path (`dispatch`) has no pass to share.
6735
+ */
6736
+ async readCameraFunctions(input) {
6737
+ const { deviceId, deviceType, deviceDisabled, privacySlice, sourceNodeId } = input;
6738
+ const bindableCache = input.bindableCapsByType;
6739
+ let bindableCapNames = bindableCache?.get(deviceType);
6740
+ if (bindableCache === void 0 || bindableCapNames === void 0) {
6741
+ bindableCapNames = await this.ctx.api.deviceManager.listBindableCapsForDeviceType.query({ deviceType }).then((entries) => entries.filter((e) => e.wrappers.length > 0).map((e) => e.capName)).catch((err) => {
6742
+ this.ctx.logger.warn("ha-export: could not read bindable caps for a device type, camera functions degrade", {
6743
+ tags: { deviceId },
6744
+ meta: {
6745
+ deviceType,
6746
+ error: errMsg(err)
6747
+ }
6748
+ });
6749
+ return null;
6750
+ });
6751
+ bindableCache?.set(deviceType, bindableCapNames);
6752
+ }
6753
+ const wrapperAddonIdByCap = /* @__PURE__ */ new Map();
6754
+ const wrappedCapNames = await this.ctx.api.deviceManager.getBindings.query({ deviceId }).then((bindings) => {
6755
+ const active = [];
6756
+ for (const entry of bindings.entries) {
6757
+ if (entry.kind !== "wrapped") continue;
6758
+ active.push(entry.capName);
6759
+ if (entry.providerAddonId !== "") wrapperAddonIdByCap.set(entry.capName, entry.providerAddonId);
6760
+ }
6761
+ return active;
6762
+ }).catch((err) => {
6763
+ this.ctx.logger.warn("ha-export: could not read bindings, camera functions degrade", {
6118
6764
  tags: { deviceId },
6119
6765
  meta: { error: errMsg(err) }
6120
6766
  });
6121
- return [];
6122
- }
6767
+ return null;
6768
+ });
6769
+ const recordingEnabled = await this.ctx.api.recording.getDeviceConfig.query({ deviceId }).then((config) => config.enabled).catch((err) => {
6770
+ this.ctx.logger.warn("ha-export: could not read recording config, the recording function degrades", {
6771
+ tags: { deviceId },
6772
+ meta: { error: errMsg(err) }
6773
+ });
6774
+ return null;
6775
+ });
6776
+ const mutedDeviceIds = input.mutedDeviceIds !== void 0 ? input.mutedDeviceIds : await this.ctx.api.notificationRules.listDeviceMutes.query({}).then((r) => r.mutedDeviceIds).catch((err) => {
6777
+ this.ctx.logger.warn("ha-export: could not read notification mutes, the notifications function degrades", {
6778
+ tags: { deviceId },
6779
+ meta: { error: errMsg(err) }
6780
+ });
6781
+ return null;
6782
+ });
6783
+ const notificationsMuted = mutedDeviceIds === null ? null : mutedDeviceIds.includes(deviceId);
6784
+ /**
6785
+ * The `privacy-mask` slice already in the snapshot this pass downloaded
6786
+ * (D224: a camera fact's freshness lives in the provider that owns it) —
6787
+ * zero new dialers to the camera.
6788
+ */
6789
+ const privacy = privacySlice === void 0 ? null : {
6790
+ maskEnabled: privacySlice["enabled"] === true,
6791
+ audioEnabled: typeof privacySlice["audioEnabled"] === "boolean" ? privacySlice["audioEnabled"] : null
6792
+ };
6793
+ const brokerAudioMuted = sourceNodeId === null ? null : await this.ctx.api.streamBroker.getDeviceAudioMute.query({ deviceId }, require_dist.nodePin(sourceNodeId)).then((r) => r.muted).catch((err) => {
6794
+ this.ctx.logger.warn("ha-export: could not read broker audio mute, the broker-audio function degrades", {
6795
+ tags: { deviceId },
6796
+ meta: {
6797
+ sourceNodeId,
6798
+ error: errMsg(err)
6799
+ }
6800
+ });
6801
+ return null;
6802
+ });
6803
+ return {
6804
+ deviceDisabled,
6805
+ bindableCapNames,
6806
+ wrappedCapNames,
6807
+ wrapperAddonIdByCap,
6808
+ recordingEnabled,
6809
+ notificationsMuted,
6810
+ privacy,
6811
+ brokerAudioMuted
6812
+ };
6123
6813
  }
6124
6814
  async loadPresets(deviceId) {
6125
6815
  try {
@@ -6372,6 +7062,38 @@ var HaExportAddon = class extends require_dist.BaseAddon {
6372
7062
  * disagree with the admin UI is worse than no knob (D62).
6373
7063
  */
6374
7064
  if (isSyntheticDeviceKey(parsed.deviceKey)) {
7065
+ /**
7066
+ * The global snooze select (Task D4) — the OTHER control this branch
7067
+ * routes, alongside the per-rule switches below. Same rule as the
7068
+ * camera's own snooze (`applySnooze`): the export writes
7069
+ * `createSnooze`/`cancelSnooze` directly, `scope: 'all'`, never a
7070
+ * store of its own.
7071
+ */
7072
+ if (parsed.deviceKey === deviceKeyFor("synthetic-notification-center") && parsed.entity === "snooze") {
7073
+ if (!SNOOZE_OPTIONS.includes(value)) {
7074
+ this.ctx.logger.warn("ha-export: dropping a global snooze command, unknown option", { meta: {
7075
+ topic,
7076
+ value
7077
+ } });
7078
+ reply.status(422);
7079
+ reply.send({ error: "unroutable command" });
7080
+ return;
7081
+ }
7082
+ const minutes = SNOOZE_MINUTES[value] ?? null;
7083
+ try {
7084
+ await this.applyGlobalSnooze(minutes);
7085
+ reply.status(200);
7086
+ reply.send({});
7087
+ } catch (err) {
7088
+ this.ctx.logger.warn("ha-export: could not apply the global snooze from Home Assistant", { meta: {
7089
+ minutes,
7090
+ error: errMsg(err)
7091
+ } });
7092
+ reply.status(422);
7093
+ reply.send({ error: "command not applied" });
7094
+ }
7095
+ return;
7096
+ }
6375
7097
  const ruleId = ruleIdFromEntity(parsed.entity, this.syntheticRules);
6376
7098
  if (ruleId === null) {
6377
7099
  this.ctx.logger.warn("ha-export: dropping a synthetic command with no authority behind it", { meta: {
@@ -6457,20 +7179,62 @@ var HaExportAddon = class extends require_dist.BaseAddon {
6457
7179
  return false;
6458
7180
  }
6459
7181
  switch (command.kind) {
6460
- case "camera-switch": {
7182
+ case "camera-function": {
6461
7183
  const parsed = require_dist.CameraSwitchIdSchema.safeParse(command.switchId);
6462
7184
  if (!parsed.success) {
6463
- this.ctx.logger.warn("ha-export: dropping a command for an unknown camera switch", {
7185
+ this.ctx.logger.warn("ha-export: dropping a command for an unknown camera function", {
6464
7186
  tags: { deviceId: command.deviceId },
6465
7187
  meta: { switchId: command.switchId }
6466
7188
  });
6467
7189
  return false;
6468
7190
  }
6469
- await this.ctx.api.pipelineOrchestrator.setCameraSwitch.mutate({
7191
+ /**
7192
+ * A FRESH read for this one device — the pass-level caches are up to
7193
+ * `reconcileIntervalSec` old, and an availability decision that
7194
+ * writes belongs to the moment of the command, not the last poll.
7195
+ */
7196
+ const device = await this.ctx.api.deviceManager.getDevice.query({ deviceId: command.deviceId });
7197
+ if (device === null) {
7198
+ this.ctx.logger.warn("ha-export: dropping a camera-function command, the device is not in the registry", { tags: { deviceId: command.deviceId } });
7199
+ return false;
7200
+ }
7201
+ const privacySlice = await this.ctx.api.deviceState.getCapSlice.query({
6470
7202
  deviceId: command.deviceId,
6471
- switchId: parsed.data,
6472
- enabled: command.enabled
7203
+ capName: "privacy-mask"
7204
+ }).catch((err) => {
7205
+ this.ctx.logger.warn("ha-export: could not read the privacy slice for a camera-function command", {
7206
+ tags: { deviceId: command.deviceId },
7207
+ meta: { error: errMsg(err) }
7208
+ });
7209
+ return null;
6473
7210
  });
7211
+ /**
7212
+ * The source node comes from the last reconcile's `CameraStatus`
7213
+ * batch (Task C3) rather than a fresh per-command call: it changes
7214
+ * rarely, and only `broker-audio` needs it — a stale pin degrades
7215
+ * that ONE function for this command, not the other seven.
7216
+ */
7217
+ const sourceNodeId = this.cameraStatusByDeviceId.get(command.deviceId)?.assignment.sourceNodeId ?? null;
7218
+ const reads = await this.readCameraFunctions({
7219
+ deviceId: command.deviceId,
7220
+ deviceType: device.type,
7221
+ deviceDisabled: device.disabled,
7222
+ privacySlice: privacySlice ?? void 0,
7223
+ sourceNodeId
7224
+ });
7225
+ const write = resolveCameraFunctionWrite(parsed.data, command.enabled, reads);
7226
+ if (write === null) {
7227
+ /**
7228
+ * Refused, never approximated. No optimistic ack: the next
7229
+ * reconcile corrects Home Assistant's toggle back to reality.
7230
+ */
7231
+ this.ctx.logger.warn("ha-export: dropping a camera-function command, the function is not available", {
7232
+ tags: { deviceId: command.deviceId },
7233
+ meta: { switchId: parsed.data }
7234
+ });
7235
+ return false;
7236
+ }
7237
+ await applyCameraFunctionWrite(this.ctx.api, command.deviceId, write, sourceNodeId);
6474
7238
  return true;
6475
7239
  }
6476
7240
  case "reboot": {
@@ -6534,19 +7298,69 @@ var HaExportAddon = class extends require_dist.BaseAddon {
6534
7298
  tags: { deviceId },
6535
7299
  meta: { cancelled: mine.length }
6536
7300
  });
6537
- return true;
7301
+ } else {
7302
+ await this.ctx.api.notificationRules.createSnooze.mutate({ snooze: {
7303
+ scope: "device",
7304
+ deviceId,
7305
+ durationMinutes: minutes
7306
+ } });
7307
+ this.ctx.logger.info("ha-export: snoozed from Home Assistant", {
7308
+ tags: { deviceId },
7309
+ meta: { minutes }
7310
+ });
6538
7311
  }
6539
- await this.ctx.api.notificationRules.createSnooze.mutate({ snooze: {
6540
- scope: "device",
6541
- deviceId,
6542
- durationMinutes: minutes
6543
- } });
6544
- this.ctx.logger.info("ha-export: snoozed from Home Assistant", {
6545
- tags: { deviceId },
6546
- meta: { minutes }
6547
- });
7312
+ /**
7313
+ * Republish right away — the select is otherwise stale for up to
7314
+ * `reconcileIntervalSec` after a write Home Assistant itself made
7315
+ * (Task B1 passo 4).
7316
+ */
7317
+ await this.republishSnooze(deviceId);
6548
7318
  return true;
6549
7319
  }
7320
+ /** Push `snooze`'s current state for one camera, outside the reconcile cadence. */
7321
+ async republishSnooze(deviceId) {
7322
+ const key = this.keyByDeviceId.get(deviceId);
7323
+ if (key === void 0) return;
7324
+ try {
7325
+ const { snoozes } = await this.ctx.api.notificationRules.listSnoozes.query({});
7326
+ this.push(deviceId, projectSnooze(key, latestDeviceSnoozeWindow(snoozes, deviceId)));
7327
+ } catch (err) {
7328
+ this.ctx.logger.warn("ha-export: could not republish snooze after a write from Home Assistant", {
7329
+ tags: { deviceId },
7330
+ meta: { error: errMsg(err) }
7331
+ });
7332
+ }
7333
+ }
7334
+ /**
7335
+ * The global `select` on *Notification Center* (Task D4) — `scope: 'all'`,
7336
+ * the same authority `applySnooze` already writes for a camera. `Off`
7337
+ * cancels every global snooze, exactly as a camera's `Off` cancels its own.
7338
+ */
7339
+ async applyGlobalSnooze(minutes) {
7340
+ if (minutes === null) {
7341
+ const { snoozes } = await this.ctx.api.notificationRules.listSnoozes.query({});
7342
+ const mine = snoozes.filter((snooze) => snooze.scope === "all");
7343
+ for (const snooze of mine) await this.ctx.api.notificationRules.cancelSnooze.mutate({ snoozeId: snooze.id });
7344
+ this.ctx.logger.info("ha-export: cancelled the global snooze from Home Assistant", { meta: { cancelled: mine.length } });
7345
+ } else {
7346
+ await this.ctx.api.notificationRules.createSnooze.mutate({ snooze: {
7347
+ scope: "all",
7348
+ durationMinutes: minutes
7349
+ } });
7350
+ this.ctx.logger.info("ha-export: snoozed globally from Home Assistant", { meta: { minutes } });
7351
+ }
7352
+ await this.republishGlobalSnooze();
7353
+ }
7354
+ /** Push the global `snooze` select's current state, outside the reconcile cadence. */
7355
+ async republishGlobalSnooze() {
7356
+ try {
7357
+ const { snoozes } = await this.ctx.api.notificationRules.listSnoozes.query({});
7358
+ const ncKey = deviceKeyFor(NOTIFICATION_CENTER_STABLE_ID);
7359
+ await this.pushSynthetic(projectSnooze(ncKey, latestGlobalSnoozeWindow(snoozes)), this.enabledBrokerIds());
7360
+ } catch (err) {
7361
+ this.ctx.logger.warn("ha-export: could not republish the global snooze after a write from Home Assistant", { meta: { error: errMsg(err) } });
7362
+ }
7363
+ }
6550
7364
  /**
6551
7365
  * A public, signed, expiring route Home Assistant can fetch bytes from.
6552
7366
  *
@@ -6939,6 +7753,37 @@ function toSnapshot(raw) {
6939
7753
  for (const [cap, slice] of Object.entries(raw)) if (slice !== null && typeof slice === "object") out[cap] = { ...slice };
6940
7754
  return out;
6941
7755
  }
7756
+ /** `CameraStatus` → the narrower shape `projectCameraStatus` needs. */
7757
+ function toCameraStatusInput(status) {
7758
+ return {
7759
+ switchedOff: status.switchedOff,
7760
+ degradedStages: status.degraded.map((d) => d.stage),
7761
+ recording: status.recording === null ? null : { active: status.recording.active }
7762
+ };
7763
+ }
7764
+ /**
7765
+ * The ACTIVE window for one scope, from a flat `listSnoozes` answer.
7766
+ *
7767
+ * "Active" is `expiresAt` in the future — `listSnoozes` never sweeps expired
7768
+ * rows (expiry is a comparison, not a job), so a reader that skipped this
7769
+ * would keep publishing a duration that ended hours ago. When several windows
7770
+ * match, the one expiring LATEST wins: that is the duration still in effect.
7771
+ */
7772
+ function latestSnoozeWindow(snoozes, matches, now) {
7773
+ const latest = snoozes.filter((s) => matches(s) && s.expiresAt > now).reduce((top, s) => top === null || s.expiresAt > top.expiresAt ? s : top, null);
7774
+ return latest === null ? null : {
7775
+ startedAt: latest.startedAt,
7776
+ expiresAt: latest.expiresAt
7777
+ };
7778
+ }
7779
+ /** The camera's own `scope: 'device'` snoozes (Task B1). */
7780
+ function latestDeviceSnoozeWindow(snoozes, deviceId) {
7781
+ return latestSnoozeWindow(snoozes, (s) => s.scope === "device" && s.deviceId === deviceId, Date.now());
7782
+ }
7783
+ /** The global `scope: 'all'` snooze (Task D4). */
7784
+ function latestGlobalSnoozeWindow(snoozes) {
7785
+ return latestSnoozeWindow(snoozes, (s) => s.scope === "all", Date.now());
7786
+ }
6942
7787
  function toCountRecord(raw) {
6943
7788
  if (raw === null || typeof raw !== "object") return {};
6944
7789
  const out = {};