iobroker.assistant 1.4.11 → 1.4.13

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.
@@ -122,6 +122,14 @@ class SpeechDetector {
122
122
  get sawSpeech() {
123
123
  return this.speechSeen;
124
124
  }
125
+ /** Something is being heard right now: speech, or a sound that may become speech. */
126
+ get hearing() {
127
+ return this.speechSeen || this.candidateMs >= 0;
128
+ }
129
+ /** Milliseconds of audio analysed so far (the skipped start included). */
130
+ get analysedMs() {
131
+ return this.elapsedMs;
132
+ }
125
133
  /** Tracked room level (adaptive mode), for logging. 0 before the first analysed frame. */
126
134
  get noiseFloor() {
127
135
  return this.floor ?? 0;
@@ -1 +1 @@
1
- {"version":3,"file":"vad.js","sourceRoot":"","sources":["../../../src/lib/voice/vad.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;;;AASH,kBAWC;AAZD,kFAAkF;AAClF,SAAgB,GAAG,CAAC,GAAU;IAC1B,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC3C,IAAI,CAAC,OAAO,EAAE,CAAC;QACX,OAAO,CAAC,CAAC;IACb,CAAC;IACD,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,EAAE,EAAE,CAAC;QAC/B,MAAM,KAAK,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;QACrC,GAAG,IAAI,KAAK,GAAG,KAAK,CAAC;IACzB,CAAC;IACD,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,OAAO,CAAC,CAAC;AACpC,CAAC;AAuFD;;;;GAIG;AACH,MAAM,UAAU,GAAG,IAAI,CAAC;AAExB,MAAa,cAAc;IACN,UAAU,CAAS;IACnB,OAAO,CA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,CAAC,CAAC;gBAClB,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,OAAO,CAAC;YAClC,CAAC;YAED,IAAI,CAAC,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC,cAAc,GAAG,CAAC,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;gBACvF,OAAO,KAAK,WAAW,CAAC;YAC5B,CAAC;YACD,IAAI,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;gBAC7B,OAAO,KAAK,SAAS,CAAC;YAC1B,CAAC;QACL,CAAC;QACD,OAAO,OAAO,CAAC;IACnB,CAAC;CACJ;AAtOD,wCAsOC","sourcesContent":["/**\n * End-of-speech detection for satellites that stream microphone audio until they are told to stop.\n *\n * The Hannah/UDP protocol has the satellite decide when an utterance ended (`audio_end`), and Wyoming\n * clients send `audio-stop` themselves. ESPHome voice satellites do neither: they keep streaming until\n * the server sends `STT_VAD_END`/`STT_END`, so the decision has to happen here.\n *\n * This is a plain energy gate, not a neural VAD — good enough to close an utterance, and it costs\n * nothing per frame. Speech must first rise above `startLevel`; after that, `silenceMs` worth of frames\n * below `endLevel` ends it. `maxMs` is the hard stop for rooms that are simply loud.\n *\n * Fixed thresholds only work when the microphone level is known, and on a real satellite it is not.\n * Measured on a ThirdReality Voice & Music Assistant: the device plays a wake-acknowledgement chirp\n * into its own microphone that peaks at full scale (RMS ~16000, clipped), while the speech that follows\n * arrives at RMS 358–469 — below the 700 default for `startLevel` and right on the 400 for `endLevel`.\n * That breaks the gate twice over: `sawSpeech` is satisfied by the chirp rather than by any voice, so\n * the \"nothing but speech-free audio\" guard never fires, and half the real speech frames count as\n * silence, so the utterance can be cut off mid-sentence.\n *\n * Hence two opt-in knobs, both enabled by the ESPHome transport:\n *\n * - `skipMs` drops the leading chirp from the *analysis* only. What reaches STT is cut later, from where\n * speech was detected minus a margin (`speechAudio.ts`) — a fast speaker may already be talking.\n * - `adaptive` derives the thresholds from a tracked noise floor instead of fixed levels. The floor\n * follows the quietest frame seen (instant down, very slow up), so it settles on room noise even when\n * someone starts talking immediately — which a mean or median over a calibration window would not.\n *\n * And one for longer requests: `longSilenceMs` after `longAfterMs` of speech. In a quiet room the silence\n * threshold sits at its minimum, and a voice a few metres away dips below it between syllables — on a\n * ThirdReality speaker a whole \"Мессенджер\" (0.7 s) stayed under 150. A pause for thought on top of that\n * ended a long request mid-sentence, while short commands should keep closing quickly.\n */\n\n/**\n * A buffer that may be a view onto any `ArrayBufferLike` — what `Buffer.subarray()` and\n * `Buffer.concat()` hand back. Plain `Buffer` (= `Buffer<ArrayBuffer>`) assigns to it, not the reverse.\n */\nexport type Bytes = Buffer<ArrayBufferLike>;\n\n/** Root-mean-square amplitude (0…32767) of a mono 16-bit signed LE PCM buffer. */\nexport function rms(pcm: Bytes): number {\n const samples = Math.floor(pcm.length / 2);\n if (!samples) {\n return 0;\n }\n let sum = 0;\n for (let i = 0; i < samples; i++) {\n const value = pcm.readInt16LE(i * 2);\n sum += value * value;\n }\n return Math.sqrt(sum / samples);\n}\n\nexport interface SpeechDetectorOptions {\n /** Sample rate of the incoming PCM (ESPHome satellites always capture at 16 kHz). */\n sampleRate?: number;\n /** Analysis window; 30 ms is the usual compromise between latency and stability. */\n frameMs?: number;\n /** RMS above which we consider speech to have started. Ignored when `adaptive` is on. */\n startLevel?: number;\n /** RMS below which a frame counts as silence. Ignored when `adaptive` is on. */\n endLevel?: number;\n /** Silence after speech that ends the utterance. */\n silenceMs?: number;\n /**\n * Silence that ends the utterance once the speaker has talked for {@link longAfterMs} (0 = always\n * {@link silenceMs}). Somebody dictating a longer request pauses to think, and a short command should\n * still close fast.\n */\n longSilenceMs?: number;\n /** Speech (from its start to the pause) after which {@link longSilenceMs} applies; 0 = never. */\n longAfterMs?: number;\n /**\n * Sound above the silence threshold needed before a crossing of the speech threshold counts as speech; 0 = the\n * first loud frame does. A click or a knock is over in 100 ms, the shortest \"да\" takes about 250.\n */\n minSpeechMs?: number;\n /** A candidate start that falls quiet this long before reaching {@link minSpeechMs} is forgotten. */\n speechGapMs?: number;\n /** Hard cap on one utterance, in case the room never falls quiet. */\n maxMs?: number;\n /**\n * Give up when no speech has started this long after the stream began (the skipped lead-in included);\n * 0 = only {@link maxMs}. A false wake would otherwise keep the microphone open for the whole `maxMs`.\n */\n startTimeoutMs?: number;\n /**\n * Leading audio to leave out of the analysis — for devices that chirp into their own microphone\n * when the wake word fires. The audio itself is untouched; this only stops the chirp from being\n * mistaken for speech and from poisoning the noise floor.\n */\n skipMs?: number;\n /** Derive the thresholds from the tracked noise floor instead of using fixed levels. */\n adaptive?: boolean;\n /** Adaptive mode: `startLevel` is at least this, however quiet the room is. */\n minStartLevel?: number;\n /** Adaptive mode: `endLevel` is at least this. */\n minEndLevel?: number;\n /** Adaptive mode: speech threshold as a multiple of the noise floor. */\n startFactor?: number;\n /** Adaptive mode: silence threshold as a multiple of the noise floor. */\n endFactor?: number;\n /** Adaptive mode: settle the noise floor this long before speech may be declared. */\n warmupMs?: number;\n}\n\n/** Why an utterance ended: the speaker stopped, we hit the hard cap, or nobody started speaking at all. */\nexport type SpeechEnd = 'speech-end' | 'timeout' | 'no-speech';\n\n/**\n * Why a recording ended, from the transport's view: what the detector said, the device ending the stream\n * ('stream'), the device going quiet without ending it ('stall'), or the transport's last-resort timer.\n */\nexport type CaptureEnd = SpeechEnd | 'stream' | 'stall' | 'pipeline-timeout';\n\n/** What the detector made of one recording — for the request trace and the diagnosis recordings. */\nexport interface VadReport {\n /** Loudest frame, the wake chirp included. */\n peak: number;\n /** Loudest frame after the skipped lead-in. */\n analysedPeak: number;\n noiseFloor: number;\n startLevel: number;\n endLevel: number;\n /** Where speech began, in ms from the start of the recording; absent when it never did. */\n speechStartMs?: number;\n /** Why the recording ended. */\n end?: CaptureEnd;\n /** Sound above the silence threshold since speech started, in ms. */\n voicedMs?: number;\n /** Silence that was needed to end it at that point (longer once the speaker talked for a while). */\n silenceMs?: number;\n /** RMS per 100 ms of the whole recording. */\n levels?: number[];\n /** What went to speech recognition: the recording cut to the speech, and the gain applied to it. */\n stt?: { fromMs: number; toMs: number; gain: number };\n}\n\n/**\n * How fast the tracked noise floor may follow a *rising* ambient level, per analysed frame (30 ms).\n * Fast enough that a genuinely noisy room is matched within about a second, slow enough that a voice\n * cannot pull the floor up to its own level before it has been recognised as speech.\n */\nconst NOISE_RISE = 0.02;\n\nexport class SpeechDetector {\n private readonly frameBytes: number;\n private readonly frameMs: number;\n private readonly fixedStart: number;\n private readonly fixedEnd: number;\n private readonly silenceMs: number;\n private readonly longSilenceMs: number;\n private readonly longAfterMs: number;\n private readonly minSpeechMs: number;\n private readonly speechGapMs: number;\n private readonly maxMs: number;\n private readonly startTimeoutMs: number;\n private readonly skipMs: number;\n private readonly adaptive: boolean;\n private readonly minStartLevel: number;\n private readonly minEndLevel: number;\n private readonly startFactor: number;\n private readonly endFactor: number;\n private readonly warmupMs: number;\n\n private pending: Bytes = Buffer.alloc(0);\n private speechSeen = false;\n private silentMs = 0;\n /** Tracked room level in adaptive mode; null until the first analysed frame. */\n private floor: number | null = null;\n /** Audio seen so far *including* the skipped lead-in, in milliseconds. */\n private elapsedMs = 0;\n /** Start of the frame that crossed {@link startLevel}, in ms from the start of the recording; -1 = not yet. */\n speechStartMs = -1;\n /** A crossing of {@link startLevel} that has not yet lasted {@link minSpeechMs}: its start, -1 = none. */\n private candidateMs = -1;\n /** Quiet since the last loud frame of the candidate. */\n private candidateQuietMs = 0;\n /** Sound above {@link endLevel} since the candidate (and then the speech) started, in ms. */\n voicedMs = 0;\n /** The longest sound that crossed {@link startLevel}, in ms — also one too short to count as speech. */\n longestSoundMs = 0;\n /** Audio analysed so far, in milliseconds (exposed for logging). */\n totalMs = 0;\n /** Loudest frame seen so far (exposed for logging — the usual clue when a mic is mis-configured). */\n peak = 0;\n /**\n * Loudest frame after the skipped lead-in, i.e. without the wake chirp. Compared with {@link startLevel}\n * it tells whether a dropped utterance was silence or a voice that was simply too quiet for the gate.\n */\n analysedPeak = 0;\n\n constructor({\n sampleRate = 16000,\n frameMs = 30,\n startLevel = 700,\n endLevel = 400,\n silenceMs = 900,\n longSilenceMs = 0,\n longAfterMs = 0,\n minSpeechMs = 0,\n speechGapMs = 300,\n maxMs = 12000,\n startTimeoutMs = 0,\n skipMs = 0,\n adaptive = false,\n minStartLevel = 250,\n minEndLevel = 150,\n startFactor = 3.5,\n endFactor = 2,\n warmupMs = 150,\n }: SpeechDetectorOptions = {}) {\n this.frameBytes = Math.round((sampleRate * frameMs) / 1000) * 2;\n this.frameMs = frameMs;\n this.fixedStart = startLevel;\n this.fixedEnd = endLevel;\n this.silenceMs = silenceMs;\n this.longSilenceMs = longSilenceMs;\n this.longAfterMs = longAfterMs;\n this.minSpeechMs = minSpeechMs;\n this.speechGapMs = speechGapMs;\n this.maxMs = maxMs;\n this.startTimeoutMs = startTimeoutMs;\n this.skipMs = skipMs;\n this.adaptive = adaptive;\n this.minStartLevel = minStartLevel;\n this.minEndLevel = minEndLevel;\n this.startFactor = startFactor;\n this.endFactor = endFactor;\n this.warmupMs = warmupMs;\n }\n\n /** True once any frame crossed {@link startLevel} — an utterance that never did is room noise. */\n get sawSpeech(): boolean {\n return this.speechSeen;\n }\n\n /** Tracked room level (adaptive mode), for logging. 0 before the first analysed frame. */\n get noiseFloor(): number {\n return this.floor ?? 0;\n }\n\n /** Current speech threshold — fixed, or derived from the noise floor in adaptive mode. */\n get startLevel(): number {\n return this.adaptive ? Math.max(this.minStartLevel, (this.floor ?? 0) * this.startFactor) : this.fixedStart;\n }\n\n /** Current silence threshold. Never above {@link startLevel}, so the gate keeps its hysteresis. */\n get endLevel(): number {\n if (!this.adaptive) {\n return this.fixedEnd;\n }\n return Math.min(this.startLevel, Math.max(this.minEndLevel, (this.floor ?? 0) * this.endFactor));\n }\n\n /**\n * Silence that ends the utterance right now: {@link silenceMs}, or {@link longSilenceMs} once the speaker\n * has talked for {@link longAfterMs} before the current pause.\n */\n get requiredSilenceMs(): number {\n if (!this.speechSeen || !this.longAfterMs || this.longSilenceMs <= this.silenceMs) {\n return this.silenceMs;\n }\n const spokenMs = this.elapsedMs - this.silentMs - this.speechStartMs;\n return spokenMs >= this.longAfterMs ? this.longSilenceMs : this.silenceMs;\n }\n\n /** The detector's view of the recording so far. */\n report(): VadReport {\n return {\n peak: Math.round(this.peak),\n analysedPeak: Math.round(this.analysedPeak),\n noiseFloor: Math.round(this.noiseFloor),\n startLevel: Math.round(this.startLevel),\n endLevel: Math.round(this.endLevel),\n speechStartMs: this.speechSeen ? this.speechStartMs : undefined,\n voicedMs: this.speechSeen ? this.voicedMs : undefined,\n silenceMs: this.requiredSilenceMs,\n };\n }\n\n /** Feed one audio chunk (any size). Returns why the utterance ended, or null to keep listening. */\n push(chunk: Bytes): SpeechEnd | null {\n this.pending = this.pending.length ? Buffer.concat([this.pending, chunk]) : chunk;\n let verdict: SpeechEnd | null = null;\n\n while (this.pending.length >= this.frameBytes) {\n const frame = this.pending.subarray(0, this.frameBytes);\n this.pending = this.pending.subarray(this.frameBytes);\n this.elapsedMs += this.frameMs;\n\n const level = rms(frame);\n if (level > this.peak) {\n this.peak = level;\n }\n\n // The device's own wake chirp: loud, clipped, and not speech. Leaving it out of the\n // analysis is what makes `sawSpeech` mean anything, and keeps the noise floor honest.\n if (this.elapsedMs <= this.skipMs) {\n continue;\n }\n this.totalMs += this.frameMs;\n if (level > this.analysedPeak) {\n this.analysedPeak = level;\n }\n\n if (this.adaptive) {\n // Three rules, each there to defeat a specific way of getting this wrong:\n // - start at zero, i.e. maximally sensitive. Seeding from the first frame instead\n // lets someone who talks straight after the wake word install their own voice as\n // the room's noise floor, which shuts the gate for good — the same trap an average\n // or median over a calibration window falls into.\n // - fall instantly, so a room that went quiet is believed at once.\n // - rise slowly, and not at all once speech has been recognised: otherwise a long\n // utterance drags the floor, and with it `endLevel`, up to its own level and cuts\n // itself off mid-sentence. Falling stays on, so the pauses between words still count.\n this.floor =\n this.floor === null\n ? 0\n : level < this.floor\n ? level\n : this.speechSeen || this.candidateMs >= 0\n ? this.floor\n : this.floor + (level - this.floor) * NOISE_RISE;\n if (this.totalMs < this.warmupMs) {\n continue; // let the floor settle before anything may count as speech\n }\n }\n\n if (!this.speechSeen) {\n // A loud frame opens a candidate; it becomes speech once it has lasted `minSpeechMs`, and is\n // forgotten when it falls quiet for `speechGapMs` before that — a click is not a request.\n if (this.candidateMs < 0) {\n if (level >= this.startLevel) {\n this.candidateMs = this.elapsedMs - this.frameMs;\n this.candidateQuietMs = 0;\n this.voicedMs = this.frameMs;\n this.longestSoundMs = Math.max(this.longestSoundMs, this.voicedMs);\n }\n } else if (level >= this.endLevel) {\n this.voicedMs += this.frameMs;\n this.candidateQuietMs = 0;\n this.longestSoundMs = Math.max(this.longestSoundMs, this.voicedMs);\n } else {\n this.candidateQuietMs += this.frameMs;\n if (this.candidateQuietMs >= this.speechGapMs) {\n this.candidateMs = -1;\n this.voicedMs = 0;\n }\n }\n if (this.candidateMs >= 0 && this.voicedMs >= this.minSpeechMs) {\n this.speechSeen = true;\n this.speechStartMs = this.candidateMs;\n // A gap inside the candidate already counts towards the end of the utterance.\n this.silentMs = this.candidateQuietMs;\n }\n } else if (level < this.endLevel) {\n this.silentMs += this.frameMs;\n if (this.silentMs >= this.requiredSilenceMs) {\n verdict ||= 'speech-end';\n }\n } else {\n this.silentMs = 0;\n this.voicedMs += this.frameMs;\n }\n\n if (!this.speechSeen && this.startTimeoutMs > 0 && this.elapsedMs >= this.startTimeoutMs) {\n verdict ||= 'no-speech';\n }\n if (this.totalMs >= this.maxMs) {\n verdict ||= 'timeout';\n }\n }\n return verdict;\n }\n}\n"]}
1
+ {"version":3,"file":"vad.js","sourceRoot":"","sources":["../../../src/lib/voice/vad.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;;;AASH,kBAWC;AAZD,kFAAkF;AAClF,SAAgB,GAAG,CAAC,GAAU;IAC1B,MAAM,OAAO,GAAG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satellites that stream microphone audio until they are told to stop.\n *\n * The Hannah/UDP protocol has the satellite decide when an utterance ended (`audio_end`), and Wyoming\n * clients send `audio-stop` themselves. ESPHome voice satellites do neither: they keep streaming until\n * the server sends `STT_VAD_END`/`STT_END`, so the decision has to happen here.\n *\n * This is a plain energy gate, not a neural VAD — good enough to close an utterance, and it costs\n * nothing per frame. Speech must first rise above `startLevel`; after that, `silenceMs` worth of frames\n * below `endLevel` ends it. `maxMs` is the hard stop for rooms that are simply loud.\n *\n * Fixed thresholds only work when the microphone level is known, and on a real satellite it is not.\n * Measured on a ThirdReality Voice & Music Assistant: the device plays a wake-acknowledgement chirp\n * into its own microphone that peaks at full scale (RMS ~16000, clipped), while the speech that follows\n * arrives at RMS 358–469 — below the 700 default for `startLevel` and right on the 400 for `endLevel`.\n * That breaks the gate twice over: `sawSpeech` is satisfied by the chirp rather than by any voice, so\n * the \"nothing but speech-free audio\" guard never fires, and half the real speech frames count as\n * silence, so the utterance can be cut off mid-sentence.\n *\n * Hence two opt-in knobs, both enabled by the ESPHome transport:\n *\n * - `skipMs` drops the leading chirp from the *analysis* only. What reaches STT is cut later, from where\n * speech was detected minus a margin (`speechAudio.ts`) — a fast speaker may already be talking.\n * - `adaptive` derives the thresholds from a tracked noise floor instead of fixed levels. The floor\n * follows the quietest frame seen (instant down, very slow up), so it settles on room noise even when\n * someone starts talking immediately — which a mean or median over a calibration window would not.\n *\n * And one for longer requests: `longSilenceMs` after `longAfterMs` of speech. In a quiet room the silence\n * threshold sits at its minimum, and a voice a few metres away dips below it between syllables — on a\n * ThirdReality speaker a whole \"Мессенджер\" (0.7 s) stayed under 150. A pause for thought on top of that\n * ended a long request mid-sentence, while short commands should keep closing quickly.\n */\n\n/**\n * A buffer that may be a view onto any `ArrayBufferLike` — what `Buffer.subarray()` and\n * `Buffer.concat()` hand back. Plain `Buffer` (= `Buffer<ArrayBuffer>`) assigns to it, not the reverse.\n */\nexport type Bytes = Buffer<ArrayBufferLike>;\n\n/** Root-mean-square amplitude (0…32767) of a mono 16-bit signed LE PCM buffer. */\nexport function rms(pcm: Bytes): number {\n const samples = Math.floor(pcm.length / 2);\n if (!samples) {\n return 0;\n }\n let sum = 0;\n for (let i = 0; i < samples; i++) {\n const value = pcm.readInt16LE(i * 2);\n sum += value * value;\n }\n return Math.sqrt(sum / samples);\n}\n\nexport interface SpeechDetectorOptions {\n /** Sample rate of the incoming PCM (ESPHome satellites always capture at 16 kHz). */\n sampleRate?: number;\n /** Analysis window; 30 ms is the usual compromise between latency and stability. */\n frameMs?: number;\n /** RMS above which we consider speech to have started. Ignored when `adaptive` is on. */\n startLevel?: number;\n /** RMS below which a frame counts as silence. Ignored when `adaptive` is on. */\n endLevel?: number;\n /** Silence after speech that ends the utterance. */\n silenceMs?: number;\n /**\n * Silence that ends the utterance once the speaker has talked for {@link longAfterMs} (0 = always\n * {@link silenceMs}). Somebody dictating a longer request pauses to think, and a short command should\n * still close fast.\n */\n longSilenceMs?: number;\n /** Speech (from its start to the pause) after which {@link longSilenceMs} applies; 0 = never. */\n longAfterMs?: number;\n /**\n * Sound above the silence threshold needed before a crossing of the speech threshold counts as speech; 0 = the\n * first loud frame does. A click or a knock is over in 100 ms, the shortest \"да\" takes about 250.\n */\n minSpeechMs?: number;\n /** A candidate start that falls quiet this long before reaching {@link minSpeechMs} is forgotten. */\n speechGapMs?: number;\n /** Hard cap on one utterance, in case the room never falls quiet. */\n maxMs?: number;\n /**\n * Give up when no speech has started this long after the stream began (the skipped lead-in included);\n * 0 = only {@link maxMs}. A false wake would otherwise keep the microphone open for the whole `maxMs`.\n */\n startTimeoutMs?: number;\n /**\n * Leading audio to leave out of the analysis — for devices that chirp into their own microphone\n * when the wake word fires. The audio itself is untouched; this only stops the chirp from being\n * mistaken for speech and from poisoning the noise floor.\n */\n skipMs?: number;\n /** Derive the thresholds from the tracked noise floor instead of using fixed levels. */\n adaptive?: boolean;\n /** Adaptive mode: `startLevel` is at least this, however quiet the room is. */\n minStartLevel?: number;\n /** Adaptive mode: `endLevel` is at least this. */\n minEndLevel?: number;\n /** Adaptive mode: speech threshold as a multiple of the noise floor. */\n startFactor?: number;\n /** Adaptive mode: silence threshold as a multiple of the noise floor. */\n endFactor?: number;\n /** Adaptive mode: settle the noise floor this long before speech may be declared. */\n warmupMs?: number;\n}\n\n/** Why an utterance ended: the speaker stopped, we hit the hard cap, or nobody started speaking at all. */\nexport type SpeechEnd = 'speech-end' | 'timeout' | 'no-speech';\n\n/**\n * Why a recording ended, from the transport's view: what the detector said, the device ending the stream\n * ('stream'), the device going quiet without ending it ('stall'), or the transport's last-resort timer.\n */\nexport type CaptureEnd = SpeechEnd | 'stream' | 'stall' | 'pipeline-timeout';\n\n/** What the detector made of one recording — for the request trace and the diagnosis recordings. */\nexport interface VadReport {\n /** Loudest frame, the wake chirp included. */\n peak: number;\n /** Loudest frame after the skipped lead-in. */\n analysedPeak: number;\n noiseFloor: number;\n startLevel: number;\n endLevel: number;\n /** Where speech began, in ms from the start of the recording; absent when it never did. */\n speechStartMs?: number;\n /** Why the recording ended. */\n end?: CaptureEnd;\n /** Sound above the silence threshold since speech started, in ms. */\n voicedMs?: number;\n /** Silence that was needed to end it at that point (longer once the speaker talked for a while). */\n silenceMs?: number;\n /** RMS per 100 ms of the whole recording. */\n levels?: number[];\n /** What went to speech recognition: the recording cut to the speech, and the gain applied to it. */\n stt?: { fromMs: number; toMs: number; gain: number };\n}\n\n/**\n * How fast the tracked noise floor may follow a *rising* ambient level, per analysed frame (30 ms).\n * Fast enough that a genuinely noisy room is matched within about a second, slow enough that a voice\n * cannot pull the floor up to its own level before it has been recognised as speech.\n */\nconst NOISE_RISE = 0.02;\n\nexport class SpeechDetector {\n private readonly frameBytes: number;\n private readonly frameMs: number;\n private readonly fixedStart: number;\n private readonly fixedEnd: number;\n private readonly silenceMs: number;\n private readonly longSilenceMs: number;\n private readonly longAfterMs: number;\n private readonly minSpeechMs: number;\n private readonly speechGapMs: number;\n private readonly maxMs: number;\n private readonly startTimeoutMs: number;\n private readonly skipMs: number;\n private readonly adaptive: boolean;\n private readonly minStartLevel: number;\n private readonly minEndLevel: number;\n private readonly startFactor: number;\n private readonly endFactor: number;\n private readonly warmupMs: number;\n\n private pending: Bytes = Buffer.alloc(0);\n private speechSeen = false;\n private silentMs = 0;\n /** Tracked room level in adaptive mode; null until the first analysed frame. */\n private floor: number | null = null;\n /** Audio seen so far *including* the skipped lead-in, in milliseconds. */\n private elapsedMs = 0;\n /** Start of the frame that crossed {@link startLevel}, in ms from the start of the recording; -1 = not yet. */\n speechStartMs = -1;\n /** A crossing of {@link startLevel} that has not yet lasted {@link minSpeechMs}: its start, -1 = none. */\n private candidateMs = -1;\n /** Quiet since the last loud frame of the candidate. */\n private candidateQuietMs = 0;\n /** Sound above {@link endLevel} since the candidate (and then the speech) started, in ms. */\n voicedMs = 0;\n /** The longest sound that crossed {@link startLevel}, in ms — also one too short to count as speech. */\n longestSoundMs = 0;\n /** Audio analysed so far, in milliseconds (exposed for logging). */\n totalMs = 0;\n /** Loudest frame seen so far (exposed for logging — the usual clue when a mic is mis-configured). */\n peak = 0;\n /**\n * Loudest frame after the skipped lead-in, i.e. without the wake chirp. Compared with {@link startLevel}\n * it tells whether a dropped utterance was silence or a voice that was simply too quiet for the gate.\n */\n analysedPeak = 0;\n\n constructor({\n sampleRate = 16000,\n frameMs = 30,\n startLevel = 700,\n endLevel = 400,\n silenceMs = 900,\n longSilenceMs = 0,\n longAfterMs = 0,\n minSpeechMs = 0,\n speechGapMs = 300,\n maxMs = 12000,\n startTimeoutMs = 0,\n skipMs = 0,\n adaptive = false,\n minStartLevel = 250,\n minEndLevel = 150,\n startFactor = 3.5,\n endFactor = 2,\n warmupMs = 150,\n }: SpeechDetectorOptions = {}) {\n this.frameBytes = Math.round((sampleRate * frameMs) / 1000) * 2;\n this.frameMs = frameMs;\n this.fixedStart = startLevel;\n this.fixedEnd = endLevel;\n this.silenceMs = silenceMs;\n this.longSilenceMs = longSilenceMs;\n this.longAfterMs = longAfterMs;\n this.minSpeechMs = minSpeechMs;\n this.speechGapMs = speechGapMs;\n this.maxMs = maxMs;\n this.startTimeoutMs = startTimeoutMs;\n this.skipMs = skipMs;\n this.adaptive = adaptive;\n this.minStartLevel = minStartLevel;\n this.minEndLevel = minEndLevel;\n this.startFactor = startFactor;\n this.endFactor = endFactor;\n this.warmupMs = warmupMs;\n }\n\n /** True once any frame crossed {@link startLevel} — an utterance that never did is room noise. */\n get sawSpeech(): boolean {\n return this.speechSeen;\n }\n\n /** Something is being heard right now: speech, or a sound that may become speech. */\n get hearing(): boolean {\n return this.speechSeen || this.candidateMs >= 0;\n }\n\n /** Milliseconds of audio analysed so far (the skipped start included). */\n get analysedMs(): number {\n return this.elapsedMs;\n }\n\n /** Tracked room level (adaptive mode), for logging. 0 before the first analysed frame. */\n get noiseFloor(): number {\n return this.floor ?? 0;\n }\n\n /** Current speech threshold — fixed, or derived from the noise floor in adaptive mode. */\n get startLevel(): number {\n return this.adaptive ? Math.max(this.minStartLevel, (this.floor ?? 0) * this.startFactor) : this.fixedStart;\n }\n\n /** Current silence threshold. Never above {@link startLevel}, so the gate keeps its hysteresis. */\n get endLevel(): number {\n if (!this.adaptive) {\n return this.fixedEnd;\n }\n return Math.min(this.startLevel, Math.max(this.minEndLevel, (this.floor ?? 0) * this.endFactor));\n }\n\n /**\n * Silence that ends the utterance right now: {@link silenceMs}, or {@link longSilenceMs} once the speaker\n * has talked for {@link longAfterMs} before the current pause.\n */\n get requiredSilenceMs(): number {\n if (!this.speechSeen || !this.longAfterMs || this.longSilenceMs <= this.silenceMs) {\n return this.silenceMs;\n }\n const spokenMs = this.elapsedMs - this.silentMs - this.speechStartMs;\n return spokenMs >= this.longAfterMs ? this.longSilenceMs : this.silenceMs;\n }\n\n /** The detector's view of the recording so far. */\n report(): VadReport {\n return {\n peak: Math.round(this.peak),\n analysedPeak: Math.round(this.analysedPeak),\n noiseFloor: Math.round(this.noiseFloor),\n startLevel: Math.round(this.startLevel),\n endLevel: Math.round(this.endLevel),\n speechStartMs: this.speechSeen ? this.speechStartMs : undefined,\n voicedMs: this.speechSeen ? this.voicedMs : undefined,\n silenceMs: this.requiredSilenceMs,\n };\n }\n\n /** Feed one audio chunk (any size). Returns why the utterance ended, or null to keep listening. */\n push(chunk: Bytes): SpeechEnd | null {\n this.pending = this.pending.length ? Buffer.concat([this.pending, chunk]) : chunk;\n let verdict: SpeechEnd | null = null;\n\n while (this.pending.length >= this.frameBytes) {\n const frame = this.pending.subarray(0, this.frameBytes);\n this.pending = this.pending.subarray(this.frameBytes);\n this.elapsedMs += this.frameMs;\n\n const level = rms(frame);\n if (level > this.peak) {\n this.peak = level;\n }\n\n // The device's own wake chirp: loud, clipped, and not speech. Leaving it out of the\n // analysis is what makes `sawSpeech` mean anything, and keeps the noise floor honest.\n if (this.elapsedMs <= this.skipMs) {\n continue;\n }\n this.totalMs += this.frameMs;\n if (level > this.analysedPeak) {\n this.analysedPeak = level;\n }\n\n if (this.adaptive) {\n // Three rules, each there to defeat a specific way of getting this wrong:\n // - start at zero, i.e. maximally sensitive. Seeding from the first frame instead\n // lets someone who talks straight after the wake word install their own voice as\n // the room's noise floor, which shuts the gate for good — the same trap an average\n // or median over a calibration window falls into.\n // - fall instantly, so a room that went quiet is believed at once.\n // - rise slowly, and not at all once speech has been recognised: otherwise a long\n // utterance drags the floor, and with it `endLevel`, up to its own level and cuts\n // itself off mid-sentence. Falling stays on, so the pauses between words still count.\n this.floor =\n this.floor === null\n ? 0\n : level < this.floor\n ? level\n : this.speechSeen || this.candidateMs >= 0\n ? this.floor\n : this.floor + (level - this.floor) * NOISE_RISE;\n if (this.totalMs < this.warmupMs) {\n continue; // let the floor settle before anything may count as speech\n }\n }\n\n if (!this.speechSeen) {\n // A loud frame opens a candidate; it becomes speech once it has lasted `minSpeechMs`, and is\n // forgotten when it falls quiet for `speechGapMs` before that — a click is not a request.\n if (this.candidateMs < 0) {\n if (level >= this.startLevel) {\n this.candidateMs = this.elapsedMs - this.frameMs;\n this.candidateQuietMs = 0;\n this.voicedMs = this.frameMs;\n this.longestSoundMs = Math.max(this.longestSoundMs, this.voicedMs);\n }\n } else if (level >= this.endLevel) {\n this.voicedMs += this.frameMs;\n this.candidateQuietMs = 0;\n this.longestSoundMs = Math.max(this.longestSoundMs, this.voicedMs);\n } else {\n this.candidateQuietMs += this.frameMs;\n if (this.candidateQuietMs >= this.speechGapMs) {\n this.candidateMs = -1;\n this.voicedMs = 0;\n }\n }\n if (this.candidateMs >= 0 && this.voicedMs >= this.minSpeechMs) {\n this.speechSeen = true;\n this.speechStartMs = this.candidateMs;\n // A gap inside the candidate already counts towards the end of the utterance.\n this.silentMs = this.candidateQuietMs;\n }\n } else if (level < this.endLevel) {\n this.silentMs += this.frameMs;\n if (this.silentMs >= this.requiredSilenceMs) {\n verdict ||= 'speech-end';\n }\n } else {\n this.silentMs = 0;\n this.voicedMs += this.frameMs;\n }\n\n if (!this.speechSeen && this.startTimeoutMs > 0 && this.elapsedMs >= this.startTimeoutMs) {\n verdict ||= 'no-speech';\n }\n if (this.totalMs >= this.maxMs) {\n verdict ||= 'timeout';\n }\n }\n return verdict;\n }\n}\n"]}
package/build/main.js CHANGED
@@ -703,6 +703,12 @@ class Assistant extends adapter_core_1.Adapter {
703
703
  this.updateSatelliteControl(device, room, entity).catch(e => this.log.debug(`satellite control update failed: ${e.message}`));
704
704
  },
705
705
  expectsFollowUp: (answer, device) => this.followUpFor(device, answer),
706
+ onDialog: (device, room, on) => {
707
+ const id = this.knownSatelliteId(device, room);
708
+ if (id) {
709
+ this.setStateAsync(`satellites.${id}.dialog`, { val: on, ack: true }).catch(() => { });
710
+ }
711
+ },
706
712
  onDiscarded: cfg.esphomeSaveCaptures ? capture => this.keepCapture(capture) : undefined,
707
713
  externalWakeWords: () => [...this.customWakeWords.values()].map(w => ({
708
714
  id: w.id,
@@ -1166,6 +1172,20 @@ class Assistant extends adapter_core_1.Adapter {
1166
1172
  return;
1167
1173
  }
1168
1174
  this.satEsphomeMarked.set(id, address);
1175
+ await this.setObjectNotExistsAsync(`satellites.${id}.dialog`, {
1176
+ type: 'state',
1177
+ common: {
1178
+ name: 'Dialog mode: listens again after every answer, without the wake word',
1179
+ type: 'boolean',
1180
+ role: 'switch.mode',
1181
+ read: true,
1182
+ write: true,
1183
+ def: false,
1184
+ },
1185
+ native: {},
1186
+ });
1187
+ this.subscribeStates(`satellites.${id}.dialog`);
1188
+ await this.setStateAsync(`satellites.${id}.dialog`, { val: !!this.esphome?.dialog(device), ack: true });
1169
1189
  const obj = await this.getObjectAsync(`satellites.${id}`);
1170
1190
  if (obj?.native?.esphome !== address) {
1171
1191
  await this.extendObjectAsync(`satellites.${id}`, { native: { esphome: address } });
@@ -1852,6 +1872,57 @@ class Assistant extends adapter_core_1.Adapter {
1852
1872
  }
1853
1873
  }
1854
1874
  }
1875
+ /**
1876
+ * Apply a write to `satellites.<id>.dialog`. Switched on while the satellite is idle, it plays the confirmation
1877
+ * tone and opens its microphone after it.
1878
+ */
1879
+ async setSatelliteDialog(satId, on) {
1880
+ const device = this.satDeviceById.get(satId) || satId;
1881
+ const tone = (0, tone_1.confirmationTone)();
1882
+ if (this.esphome?.setDialog(device, on, on ? tone : undefined)) {
1883
+ await this.setStateAsync(`satellites.${satId}.dialog`, { val: on, ack: true });
1884
+ return;
1885
+ }
1886
+ this.log.warn(`Cannot switch the dialog mode of ${device}: it is not a connected ESPHome satellite.`);
1887
+ await this.setStateAsync(`satellites.${satId}.dialog`, { val: !!this.esphome?.dialog(device), ack: true });
1888
+ }
1889
+ /**
1890
+ * "Dialogmodus an/aus" said to a satellite — or, in dialog mode, a bare "stop". The reply to "on" is the first turn
1891
+ * of the dialog already: the satellite listens again after it. null when the request is no such command.
1892
+ */
1893
+ switchDialog(question, source) {
1894
+ let wanted = (0, nlu_1.dialogCommand)(question);
1895
+ const inDialog = !!this.esphome?.dialog(source);
1896
+ if (!wanted && inDialog && (0, nlu_1.isStopCommand)(question) && question.trim().split(/\s+/).length <= 2) {
1897
+ wanted = 'off';
1898
+ }
1899
+ if (!wanted) {
1900
+ return null;
1901
+ }
1902
+ const on = wanted === 'on';
1903
+ const lang = this.answerLanguage();
1904
+ const pick = (ru, de, en) => (lang === 'ru' ? ru : lang === 'de' ? de : en);
1905
+ let text;
1906
+ let done = false;
1907
+ if (this.esphome?.setDialog(source, on)) {
1908
+ done = true;
1909
+ text = on
1910
+ ? pick('Режим диалога включён. Говорите без слова активации, «выключи режим диалога» его завершит.', 'Dialogmodus an. Sprich einfach weiter, „Dialogmodus aus“ beendet ihn.', 'Dialog mode on. Just keep talking; "dialog mode off" ends it.')
1911
+ : pick('Режим диалога выключен.', 'Dialogmodus aus.', 'Dialog mode off.');
1912
+ }
1913
+ else if (source === 'chat') {
1914
+ text = pick('В чате для этого есть кнопка «Диалог» слева от поля ввода.', 'Im Chat gibt es dafür den Dialog-Knopf links neben dem Eingabefeld.', 'In the chat, use the dialog button left of the input field.');
1915
+ }
1916
+ else {
1917
+ text = pick('Режим диалога есть только у спутников ESPHome.', 'Den Dialogmodus gibt es nur an ESPHome-Satelliten.', 'The dialog mode is only available on ESPHome satellites.');
1918
+ }
1919
+ this.journal?.note({ tier: 'nlu', detail: `dialog ${wanted}` });
1920
+ this.journal?.step({
1921
+ stage: 'nlu',
1922
+ title: done ? `Dialog mode ${wanted} for ${source}` : `Dialog mode ${wanted}: not possible for ${source}`,
1923
+ });
1924
+ return text;
1925
+ }
1855
1926
  /**
1856
1927
  * Record which ioBroker host a satellite runs on, resolved from the sender instance object
1857
1928
  * (`system.adapter.<from>.common.host`). Only meaningful for ioBroker-native satellites; UDP/ESP ones
@@ -2385,6 +2456,12 @@ class Assistant extends adapter_core_1.Adapter {
2385
2456
  await this.announceToSatellites(String(state.val ?? ''), satTts[1]); // satTts[1] = satellite state id
2386
2457
  return;
2387
2458
  }
2459
+ // Dialog mode of an ESPHome satellite: it listens again after every answer, without the wake word.
2460
+ const satDialog = id.match(/\.satellites\.([^.]+)\.dialog$/);
2461
+ if (satDialog) {
2462
+ await this.setSatelliteDialog(satDialog[1], !!state.val);
2463
+ return;
2464
+ }
2388
2465
  // Pick which wake words listen on an ESPHome satellite (comma-separated ids).
2389
2466
  const satWake = id.match(/\.satellites\.([^.]+)\.wakeWords$/);
2390
2467
  if (satWake) {
@@ -3280,7 +3357,7 @@ class Assistant extends adapter_core_1.Adapter {
3280
3357
  return;
3281
3358
  }
3282
3359
  const shown = (0, media_1.historyText)(question, attachments.images.length, !!attachments.video);
3283
- this.log.info(`${heard ? 'Voice Q' : 'Q'} (${obj.command} from ${caller}): ${shown}${attachments.video ? ` (video ${attachments.video.adapter}/${attachments.video.path})` : ''}`);
3360
+ this.log.info(`${heard ? 'Voice Q' : 'Q'} (${obj.command} from ${caller}): ${shown}${attachments.video ? ` (video ${(0, media_1.videoLocation)(attachments.video)})` : ''}`);
3284
3361
  this.setStateAsync('text.request', { val: shown, ack: true }).catch(() => { });
3285
3362
  this.setQuerySource(source);
3286
3363
  try {
@@ -3412,7 +3489,7 @@ class Assistant extends adapter_core_1.Adapter {
3412
3489
  const kb = (base64) => Math.round((base64.length * 3) / 4 / 1024);
3413
3490
  const parts = [
3414
3491
  images.length ? `${images.length} picture(s), ${images.reduce((n, i) => n + kb(i.data), 0)} KB` : '',
3415
- video ? `video ${video.adapter}/${video.path}` : '',
3492
+ video ? `video ${(0, media_1.videoLocation)(video)}` : '',
3416
3493
  ].filter(Boolean);
3417
3494
  this.journal?.step({
3418
3495
  stage: 'request',
@@ -3516,6 +3593,20 @@ class Assistant extends adapter_core_1.Adapter {
3516
3593
  }
3517
3594
  return 'If the request was only a command to switch devices on or off or to set them to a value, and everything worked, answer with the control marker [[DONE]] alone (a short beep plays instead of a sentence). For questions, errors or when you have something to tell, answer normally.';
3518
3595
  }
3596
+ /**
3597
+ * System-prompt instruction to answer in the language of the question: the system prompt, the device names and
3598
+ * the time/weather lines are in the configured language, and the model followed them instead of the question.
3599
+ */
3600
+ languageHint() {
3601
+ const lang = String(this.config.voiceLanguage || this.language || 'en');
3602
+ if (lang === 'ru') {
3603
+ return 'Всегда отвечай на том языке, на котором задан вопрос, даже если эти инструкции, имена устройств или данные на другом языке.';
3604
+ }
3605
+ if (lang === 'de') {
3606
+ return 'Antworte immer in der Sprache, in der die Frage gestellt wurde, auch wenn diese Anweisungen, die Gerätenamen oder die Daten in einer anderen Sprache sind.';
3607
+ }
3608
+ return 'Always answer in the language the question was asked in, even if these instructions, the device names or the data are in another language.';
3609
+ }
3519
3610
  /**
3520
3611
  * Length instruction for a request that came in by voice: the answer is cut at `ttsMaxChars` before it is
3521
3612
  * spoken, so the model is asked to stay within it. Empty for text requests (chat, Telegram, scripts) and
@@ -3717,7 +3808,7 @@ class Assistant extends adapter_core_1.Adapter {
3717
3808
  const { images, video } = this.attachments();
3718
3809
  if (!question.trim() && video) {
3719
3810
  // A video without a question: nothing looks at videos yet
3720
- this.log.info(`Video from '${source}' (${video.adapter}/${video.path}) not looked at: not supported yet.`);
3811
+ this.log.info(`Video from '${source}' (${(0, media_1.videoLocation)(video)}) not looked at: not supported yet.`);
3721
3812
  this.journal?.note({ tier: 'none' });
3722
3813
  this.journal?.step({ stage: 'none', title: 'A video without a question: videos are not looked at yet' });
3723
3814
  return (0, media_1.videoNotSupportedText)(this.answerLanguage());
@@ -3748,6 +3839,11 @@ class Assistant extends adapter_core_1.Adapter {
3748
3839
  return '';
3749
3840
  }
3750
3841
  }
3842
+ // "Dialogmodus an/aus": before the tiers, which would take it for a device ("Modus") or ask the cloud model
3843
+ const dialog = this.switchDialog(question, source);
3844
+ if (dialog !== null) {
3845
+ return dialog;
3846
+ }
3751
3847
  if (images.length && !this.agent && !this.piAgent) {
3752
3848
  this.log.info(`Pictures from '${source}' not looked at: no cloud model is configured.`);
3753
3849
  this.journal?.note({ tier: 'none' });
@@ -3834,7 +3930,7 @@ class Assistant extends adapter_core_1.Adapter {
3834
3930
  // Only ask the model to emit the follow-up marker when satellites can actually re-open the mic.
3835
3931
  const followUp = this.config.voiceEnabled ? this.followUpHint() : '';
3836
3932
  const done = this.doneHint();
3837
- const parts = [this.config.systemPrompt || '', followUp, done, mem, ctx].filter(Boolean);
3933
+ const parts = [this.config.systemPrompt || '', this.languageHint(), followUp, done, mem, ctx].filter(Boolean);
3838
3934
  const sys = parts.length ? parts.join('\n\n') : undefined;
3839
3935
  this.log.info(`Cloud LLM [${this.agent.model || 'auto'}] (source='${source}', context=${history.length} turn(s)${mem ? ', memory' : ''}${weather ? ', weather' : ''}${this.presence?.configured ? ', presence' : ''}) — running tool loop…`);
3840
3936
  // Prepend the current date/time (and the weather line, if a source is configured) to the user turn —
@@ -3867,7 +3963,7 @@ class Assistant extends adapter_core_1.Adapter {
3867
3963
  time,
3868
3964
  weather: weather || undefined,
3869
3965
  images: images.length || undefined,
3870
- video: video ? `${video.adapter}/${video.path}` : undefined,
3966
+ video: video ? (0, media_1.videoLocation)(video) : undefined,
3871
3967
  },
3872
3968
  });
3873
3969
  try {
@@ -3900,7 +3996,7 @@ class Assistant extends adapter_core_1.Adapter {
3900
3996
  const followUp = this.config.voiceEnabled ? this.followUpHint() : '';
3901
3997
  // The device list maps names to state ids, so pi-agent can act without searching first. It is the
3902
3998
  // first to go when the instructions get too long — pi-agent can still search.
3903
- const { text: instructions, dropped } = (0, piAgent_1.composeInstructions)([this.config.systemPrompt || '', followUp, this.doneHint(), this.spokenLengthHint()], [this.buildMemoryContext(), await this.buildDeviceContext()]);
3999
+ const { text: instructions, dropped } = (0, piAgent_1.composeInstructions)([this.config.systemPrompt || '', this.languageHint(), followUp, this.doneHint(), this.spokenLengthHint()], [this.buildMemoryContext(), await this.buildDeviceContext()]);
3904
4000
  if (dropped) {
3905
4001
  this.log.debug(`pi-agent: ${dropped} context block(s) left out, the instructions would be too long.`);
3906
4002
  }
@@ -4026,7 +4122,7 @@ class Assistant extends adapter_core_1.Adapter {
4026
4122
  continue; // hidden from the LLM
4027
4123
  }
4028
4124
  const room = d.room ? `${d.room}, ` : '';
4029
- lines.push(`- ${d.name} (${room}${d.type}): ${ids.join(', ')}`);
4125
+ lines.push(`- ${d.name} (${room}${d.type}): ${this.describeControls(d)}`);
4030
4126
  }
4031
4127
  const lang = String(this.config.voiceLanguage || this.language || 'en');
4032
4128
  lines.push(...this.satelliteVolumeLines(lang));
@@ -4034,12 +4130,35 @@ class Assistant extends adapter_core_1.Adapter {
4034
4130
  return '';
4035
4131
  }
4036
4132
  const header = lang === 'ru'
4037
- ? 'Известные устройства — «имя (комната, тип): stateId». Используй эти stateId напрямую с set_state/get_states; вызывай list_devices только если нужного устройства здесь нет.'
4133
+ ? 'Известные устройства — «имя (комната, тип): элемент stateId [вид]; …». Используй эти stateId напрямую с set_state/get_states; вызывай list_devices только если нужного устройства здесь нет. Если у устройства есть выключатель [on/off] и уровень [number], то «включи» — это выключатель = true (уровень — только если его назвали): один уровень устройство не включает.'
4038
4134
  : lang === 'de'
4039
- ? 'Bekannte Geräte — "Name (Raum, Typ): stateId". Nutze diese stateIds direkt mit set_state/get_states; rufe list_devices nur, wenn ein Gerät hier fehlt.'
4040
- : 'Known devices — "name (room, type): stateId". Use these stateIds directly with set_state/get_states; only call list_devices if a needed device is missing here.';
4135
+ ? 'Bekannte Geräte — "Name (Raum, Typ): Element stateId [Art]; …". Nutze diese stateIds direkt mit set_state/get_states; rufe list_devices nur, wenn ein Gerät hier fehlt. Hat ein Gerät einen Schalter [on/off] und einen Level [number], heißt "einschalten" Schalter = true (den Level nur, wenn er genannt wurde): der Level allein schaltet das Gerät nicht ein.'
4136
+ : 'Known devices — "name (room, type): element stateId [kind]; …". Use these stateIds directly with set_state/get_states; only call list_devices if a needed device is missing here. If a device has a switch [on/off] and a level [number], "turn on" means switch = true (the level only if one was asked for): the level alone does not switch the device on.';
4041
4137
  return `${header}\n${lines.join('\n')}`;
4042
4138
  }
4139
+ /**
4140
+ * The controls of a device for the LLM: element, state id and what it is. A bare list of ids did not tell the
4141
+ * level from the switch next to it, and the model set only the level of a light, so it stayed off.
4142
+ */
4143
+ describeControls(d) {
4144
+ const seen = new Set();
4145
+ const parts = [];
4146
+ for (const [key, id] of Object.entries(d.controls)) {
4147
+ if (seen.has(id)) {
4148
+ continue;
4149
+ }
4150
+ seen.add(id);
4151
+ const kind = d.writable[key] === false
4152
+ ? 'read-only'
4153
+ : d.types[key] === 'boolean'
4154
+ ? 'on/off'
4155
+ : d.types[key] === 'number'
4156
+ ? 'number'
4157
+ : '';
4158
+ parts.push(kind ? `${key} ${id} [${kind}]` : `${key} ${id}`);
4159
+ }
4160
+ return parts.join('; ');
4161
+ }
4043
4162
  /**
4044
4163
  * The playback volume of every voice satellite as a line of the device list. Without it, "Lautstärke auf 50
4045
4164
  * Prozent" that the rules miss reaches the LLM (or pi-agent) with only the media devices of the room in view, and
@@ -5518,6 +5637,9 @@ class Assistant extends adapter_core_1.Adapter {
5518
5637
  * because a confirmation nobody hears is worse than one that costs a TTS call.
5519
5638
  */
5520
5639
  async playConfirmationTone(source) {
5640
+ if (this.esphome?.dialog(source)) {
5641
+ return true; // in dialog mode the satellite plays it as the reply and listens again after it
5642
+ }
5521
5643
  const target = this.announceTargetForSource(source);
5522
5644
  if (!target) {
5523
5645
  return false; // chat/telegram/unknown origin: there is no speaker to beep on