iobroker.assistant 1.4.1 → 1.4.3
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.
- package/README.md +9 -0
- package/admin/i18n/de.json +2 -2
- package/admin/i18n/en.json +2 -2
- package/admin/i18n/es.json +2 -2
- package/admin/i18n/fr.json +2 -2
- package/admin/i18n/it.json +2 -2
- package/admin/i18n/nl.json +2 -2
- package/admin/i18n/pl.json +2 -2
- package/admin/i18n/pt.json +2 -2
- package/admin/i18n/ru.json +2 -2
- package/admin/i18n/uk.json +2 -2
- package/admin/i18n/zh-cn.json +2 -2
- package/admin/jsonConfig.json +2 -2
- package/build/lib/journal.js.map +1 -1
- package/build/lib/voice/captures.js.map +1 -1
- package/build/lib/voice/esphome.js +36 -24
- package/build/lib/voice/esphome.js.map +1 -1
- package/build/lib/voice/fallback.js +18 -3
- package/build/lib/voice/fallback.js.map +1 -1
- package/build/lib/voice/speechAudio.js +97 -0
- package/build/lib/voice/speechAudio.js.map +1 -0
- package/build/lib/voice/vad.js +39 -4
- package/build/lib/voice/vad.js.map +1 -1
- package/build/main.js +36 -2
- package/build/main.js.map +1 -1
- package/io-package.json +27 -27
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -235,6 +235,15 @@ train it twice.
|
|
|
235
235
|
Placeholder for the next version (at the beginning of the line):
|
|
236
236
|
### **WORK IN PROGRESS**
|
|
237
237
|
-->
|
|
238
|
+
### 1.4.3 (2026-11-03)
|
|
239
|
+
* (@GermanBluefox) An empty question sent with `sendTo('ask')` is rejected (`{error: 'empty question'}`) instead of going to the model with nothing but the time context, and the log names the sender once a minute. A script that asked on every answer looped about once a second and used pi-agent tokens. The log line of every `ask` now names the sender
|
|
240
|
+
|
|
241
|
+
### 1.4.2 (2026-11-03)
|
|
242
|
+
* (@GermanBluefox) ESPHome satellites: after 2.5 seconds of speech a pause may be half as long again before the request ends, so a pause for thought no longer cuts off a longer request. Short commands close as fast as before
|
|
243
|
+
* (@GermanBluefox) ESPHome satellites: speech recognition gets the recording without the device's chirp or beep and without the silence around the speech, and quiet speech is amplified (up to ×10). Whisper made "Продолжение следует..." of the beep and the silence
|
|
244
|
+
* (@GermanBluefox) The speech-to-text fallback also steps in when the first engine returns no text for speech
|
|
245
|
+
* (@GermanBluefox) Request details: the speech recognition step shows the level profile of the recording (RMS per 100 ms), where speech started, why the recording ended and what went to the recognition
|
|
246
|
+
|
|
238
247
|
### 1.4.1 (2026-11-03)
|
|
239
248
|
* (@GermanBluefox) Satellite settings: compound controls show their name ("Firmware Update") instead of the object id ("thirdreality_firmware_update"), and values of ESPHome devices no longer carry float noise (0.5 instead of 0.5000000237487257, step 0.001 instead of 0.0010000000474974513). Existing number controls get the cleaned range on the next connect
|
|
240
249
|
* (@GermanBluefox) Satellite settings, firmware update: the install button only appears when another version is available, and a running update shows its progress as a bar
|
package/admin/i18n/de.json
CHANGED
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
"Longest spoken answer (characters)": "Längste gesprochene Antwort (Zeichen)",
|
|
158
158
|
"A longer answer is cut at the last sentence end before this limit. 400 characters are about 25–30 seconds of speech. 0 = no limit.": "Eine längere Antwort wird am letzten Satzende vor dieser Grenze abgeschnitten. 400 Zeichen sind etwa 25–30 Sekunden Sprache. 0 = keine Grenze.",
|
|
159
159
|
"Text-to-speech provider": "Sprachausgabe-Anbieter",
|
|
160
|
-
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long.": "Diese Geräte streamen, bis der Server sie stoppt — der Adapter entscheidet also, wann du aufgehört hast zu sprechen. Erhöhen, wenn die Antwort dir ins Wort fällt; verringern, wenn der Assistent zu lange wartet.",
|
|
160
|
+
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long. After 2.5 seconds of speech half as much again is allowed, so a pause for thought does not end a longer request.": "Diese Geräte streamen, bis der Server sie stoppt — der Adapter entscheidet also, wann du aufgehört hast zu sprechen. Erhöhen, wenn die Antwort dir ins Wort fällt; verringern, wenn der Assistent zu lange wartet. Nach 2,5 Sekunden Sprechen gilt das Anderthalbfache, damit eine Denkpause eine längere Anfrage nicht beendet.",
|
|
161
161
|
"ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. These devices listen on TCP 6053 and the adapter dials them, so no port is opened for the audio itself — only the media server below, which they fetch the spoken reply from.": "ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. Diese Geräte lauschen auf TCP 6053 und der Adapter baut die Verbindung zu ihnen auf — für das Audio selbst wird also kein Port geöffnet, nur der Medien-Server unten, von dem sie die gesprochene Antwort abholen.",
|
|
162
162
|
"Timer sound (mp3/wav, optional)": "Timer-Sound (mp3/wav, optional)",
|
|
163
163
|
"Triggers": "Trigger",
|
|
@@ -170,7 +170,7 @@
|
|
|
170
170
|
"Every question the rules do not understand goes to the local model before the cloud. Saves cloud calls, but on a Raspberry Pi it adds 10–25 seconds to such questions.": "Jede Frage, die die Regeln nicht verstehen, geht vor der Cloud an das lokale Modell. Spart Cloud-Aufrufe, kostet auf einem Raspberry Pi aber 10–25 Sekunden pro solcher Frage.",
|
|
171
171
|
"Local model timeout (s)": "Zeitlimit lokales Modell (s)",
|
|
172
172
|
"After this time the local model is stopped and the question goes on to the cloud.": "Nach dieser Zeit wird das lokale Modell abgebrochen und die Frage geht an die Cloud weiter.",
|
|
173
|
-
"Used when the provider above fails (outage, expired key, empty quota). A local engine keeps voice working without the internet.": "Wird genutzt, wenn der Anbieter oben ausfällt (Störung, abgelaufener Key, leeres Guthaben). Eine lokale Engine hält die Sprachsteuerung ohne Internet am Leben.",
|
|
173
|
+
"Used when the provider above fails (outage, expired key, empty quota) or returns no text for speech. A local engine keeps voice working without the internet.": "Wird genutzt, wenn der Anbieter oben ausfällt (Störung, abgelaufener Key, leeres Guthaben) oder für Sprache keinen Text liefert. Eine lokale Engine hält die Sprachsteuerung ohne Internet am Leben.",
|
|
174
174
|
"Used when the provider above fails. Piper keeps the assistant speaking without the internet.": "Wird genutzt, wenn der Anbieter oben ausfällt. Piper lässt den Assistenten ohne Internet weitersprechen.",
|
|
175
175
|
"Verify device feedback": "Geräte-Rückmeldung prüfen",
|
|
176
176
|
"Voice": "Sprache",
|
package/admin/i18n/en.json
CHANGED
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
"Longest spoken answer (characters)": "Longest spoken answer (characters)",
|
|
158
158
|
"A longer answer is cut at the last sentence end before this limit. 400 characters are about 25–30 seconds of speech. 0 = no limit.": "A longer answer is cut at the last sentence end before this limit. 400 characters are about 25–30 seconds of speech. 0 = no limit.",
|
|
159
159
|
"Text-to-speech provider": "Text-to-speech provider",
|
|
160
|
-
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long.": "These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long.",
|
|
160
|
+
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long. After 2.5 seconds of speech half as much again is allowed, so a pause for thought does not end a longer request.": "These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long. After 2.5 seconds of speech half as much again is allowed, so a pause for thought does not end a longer request.",
|
|
161
161
|
"ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. These devices listen on TCP 6053 and the adapter dials them, so no port is opened for the audio itself — only the media server below, which they fetch the spoken reply from.": "ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. These devices listen on TCP 6053 and the adapter dials them, so no port is opened for the audio itself — only the media server below, which they fetch the spoken reply from.",
|
|
162
162
|
"Timer sound (mp3/wav, optional)": "Timer sound (mp3/wav, optional)",
|
|
163
163
|
"Triggers": "Triggers",
|
|
@@ -170,7 +170,7 @@
|
|
|
170
170
|
"Every question the rules do not understand goes to the local model before the cloud. Saves cloud calls, but on a Raspberry Pi it adds 10–25 seconds to such questions.": "Every question the rules do not understand goes to the local model before the cloud. Saves cloud calls, but on a Raspberry Pi it adds 10–25 seconds to such questions.",
|
|
171
171
|
"Local model timeout (s)": "Local model timeout (s)",
|
|
172
172
|
"After this time the local model is stopped and the question goes on to the cloud.": "After this time the local model is stopped and the question goes on to the cloud.",
|
|
173
|
-
"Used when the provider above fails (outage, expired key, empty quota). A local engine keeps voice working without the internet.": "Used when the provider above fails (outage, expired key, empty quota). A local engine keeps voice working without the internet.",
|
|
173
|
+
"Used when the provider above fails (outage, expired key, empty quota) or returns no text for speech. A local engine keeps voice working without the internet.": "Used when the provider above fails (outage, expired key, empty quota) or returns no text for speech. A local engine keeps voice working without the internet.",
|
|
174
174
|
"Used when the provider above fails. Piper keeps the assistant speaking without the internet.": "Used when the provider above fails. Piper keeps the assistant speaking without the internet.",
|
|
175
175
|
"Verify device feedback": "Verify device feedback",
|
|
176
176
|
"Voice": "Voice",
|
package/admin/i18n/es.json
CHANGED
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
"Longest spoken answer (characters)": "Respuesta hablada más larga (caracteres)",
|
|
158
158
|
"A longer answer is cut at the last sentence end before this limit. 400 characters are about 25–30 seconds of speech. 0 = no limit.": "Una respuesta más larga se corta en el último final de frase antes de este límite. 400 caracteres son unos 25–30 segundos de voz. 0 = sin límite.",
|
|
159
159
|
"Text-to-speech provider": "Proveedor de conversión de texto a voz",
|
|
160
|
-
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long.": "Estos dispositivos transmiten hasta que el servidor los detiene, así que el adaptador decide cuándo has dejado de hablar.
|
|
160
|
+
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long. After 2.5 seconds of speech half as much again is allowed, so a pause for thought does not end a longer request.": "Estos dispositivos transmiten hasta que el servidor los detiene, así que el adaptador decide cuándo has dejado de hablar. Auméntalo si la respuesta te interrumpe; redúcelo si el asistente espera demasiado. Tras 2,5 segundos de habla se permite una pausa una vez y media más larga, para que una pausa para pensar no termine una petición larga.",
|
|
161
161
|
"ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. These devices listen on TCP 6053 and the adapter dials them, so no port is opened for the audio itself — only the media server below, which they fetch the spoken reply from.": "ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. Estos dispositivos escuchan en TCP 6053 y es el adaptador quien los llama, así que no se abre ningún puerto para el audio en sí, solo el servidor multimedia de abajo, del que descargan la respuesta hablada.",
|
|
162
162
|
"Timer sound (mp3/wav, optional)": "Sonido del temporizador (mp3/wav, opcional)",
|
|
163
163
|
"Triggers": "Disparadores",
|
|
@@ -170,7 +170,7 @@
|
|
|
170
170
|
"Every question the rules do not understand goes to the local model before the cloud. Saves cloud calls, but on a Raspberry Pi it adds 10–25 seconds to such questions.": "Cada pregunta que las reglas no entienden va al modelo local antes que a la nube. Ahorra llamadas a la nube, pero en una Raspberry Pi añade 10–25 segundos a esas preguntas.",
|
|
171
171
|
"Local model timeout (s)": "Tiempo límite del modelo local (s)",
|
|
172
172
|
"After this time the local model is stopped and the question goes on to the cloud.": "Pasado este tiempo, el modelo local se detiene y la pregunta pasa a la nube.",
|
|
173
|
-
"Used when the provider above fails (outage, expired key, empty quota). A local engine keeps voice working without the internet.": "Se usa cuando
|
|
173
|
+
"Used when the provider above fails (outage, expired key, empty quota) or returns no text for speech. A local engine keeps voice working without the internet.": "Se usa cuando el proveedor de arriba falla (caída, clave caducada, cuota agotada) o no devuelve texto para el habla. Un motor local mantiene la voz funcionando sin internet.",
|
|
174
174
|
"Used when the provider above fails. Piper keeps the assistant speaking without the internet.": "Se usa cuando falla el proveedor de arriba. Piper mantiene al asistente hablando sin internet.",
|
|
175
175
|
"Verify device feedback": "Verificar la respuesta del dispositivo",
|
|
176
176
|
"Voice": "Voz",
|
package/admin/i18n/fr.json
CHANGED
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
"Longest spoken answer (characters)": "Réponse parlée la plus longue (caractères)",
|
|
158
158
|
"A longer answer is cut at the last sentence end before this limit. 400 characters are about 25–30 seconds of speech. 0 = no limit.": "Une réponse plus longue est coupée à la dernière fin de phrase avant cette limite. 400 caractères correspondent à environ 25 à 30 secondes de parole. 0 = aucune limite.",
|
|
159
159
|
"Text-to-speech provider": "fournisseur de synthèse vocale",
|
|
160
|
-
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long.": "Ces appareils
|
|
160
|
+
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long. After 2.5 seconds of speech half as much again is allowed, so a pause for thought does not end a longer request.": "Ces appareils diffusent jusqu'à ce que le serveur les arrête : c'est donc l'adaptateur qui décide quand vous avez fini de parler. Augmentez la valeur si la réponse vous coupe la parole, diminuez-la si l'assistant attend trop longtemps. Après 2,5 secondes de parole, une pause une fois et demie plus longue est admise, pour qu'une pause de réflexion ne termine pas une demande longue.",
|
|
161
161
|
"ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. These devices listen on TCP 6053 and the adapter dials them, so no port is opened for the audio itself — only the media server below, which they fetch the spoken reply from.": "ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. Ces appareils écoutent sur le TCP 6053 et c’est l’adaptateur qui les appelle : aucun port n’est donc ouvert pour l’audio lui-même, seulement le serveur multimédia ci-dessous, d’où ils récupèrent la réponse parlée.",
|
|
162
162
|
"Timer sound (mp3/wav, optional)": "Son de minuterie (mp3/wav, optionnel)",
|
|
163
163
|
"Triggers": "Déclencheurs",
|
|
@@ -170,7 +170,7 @@
|
|
|
170
170
|
"Every question the rules do not understand goes to the local model before the cloud. Saves cloud calls, but on a Raspberry Pi it adds 10–25 seconds to such questions.": "Chaque question que les règles ne comprennent pas va au modèle local avant le cloud. Économise des appels au cloud, mais ajoute 10 à 25 secondes à ces questions sur un Raspberry Pi.",
|
|
171
171
|
"Local model timeout (s)": "Délai du modèle local (s)",
|
|
172
172
|
"After this time the local model is stopped and the question goes on to the cloud.": "Passé ce délai, le modèle local est arrêté et la question est transmise au cloud.",
|
|
173
|
-
"Used when the provider above fails (outage, expired key, empty quota). A local engine keeps voice working without the internet.": "Utilisé lorsque le fournisseur ci-dessus échoue (panne, clé expirée, quota épuisé). Un moteur local
|
|
173
|
+
"Used when the provider above fails (outage, expired key, empty quota) or returns no text for speech. A local engine keeps voice working without the internet.": "Utilisé lorsque le fournisseur ci-dessus échoue (panne, clé expirée, quota épuisé) ou ne renvoie aucun texte pour de la parole. Un moteur local maintient la voix sans internet.",
|
|
174
174
|
"Used when the provider above fails. Piper keeps the assistant speaking without the internet.": "Utilisé lorsque le fournisseur ci-dessus échoue. Piper permet à l'assistant de continuer à parler sans Internet.",
|
|
175
175
|
"Verify device feedback": "Vérifier le retour de l'appareil",
|
|
176
176
|
"Voice": "Voix",
|
package/admin/i18n/it.json
CHANGED
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
"Longest spoken answer (characters)": "Risposta parlata più lunga (caratteri)",
|
|
158
158
|
"A longer answer is cut at the last sentence end before this limit. 400 characters are about 25–30 seconds of speech. 0 = no limit.": "Una risposta più lunga viene tagliata all'ultima fine di frase prima di questo limite. 400 caratteri sono circa 25–30 secondi di parlato. 0 = nessun limite.",
|
|
159
159
|
"Text-to-speech provider": "Fornitore di sintesi vocale",
|
|
160
|
-
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long.": "Questi dispositivi trasmettono finché il server non li ferma, quindi è l
|
|
160
|
+
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long. After 2.5 seconds of speech half as much again is allowed, so a pause for thought does not end a longer request.": "Questi dispositivi trasmettono finché il server non li ferma, quindi è l'adattatore a decidere quando hai finito di parlare. Aumentalo se la risposta ti interrompe, riducilo se l'assistente aspetta troppo. Dopo 2,5 secondi di parlato è ammessa una pausa una volta e mezza più lunga, così una pausa per riflettere non chiude una richiesta lunga.",
|
|
161
161
|
"ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. These devices listen on TCP 6053 and the adapter dials them, so no port is opened for the audio itself — only the media server below, which they fetch the spoken reply from.": "ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. Questi dispositivi ascoltano sulla TCP 6053 ed è l’adapter a contattarli, quindi per l’audio non viene aperta alcuna porta: solo il media server qui sotto, da cui scaricano la risposta parlata.",
|
|
162
162
|
"Timer sound (mp3/wav, optional)": "Suono del timer (mp3/wav, facoltativo)",
|
|
163
163
|
"Triggers": "Trigger",
|
|
@@ -170,7 +170,7 @@
|
|
|
170
170
|
"Every question the rules do not understand goes to the local model before the cloud. Saves cloud calls, but on a Raspberry Pi it adds 10–25 seconds to such questions.": "Ogni domanda che le regole non capiscono va al modello locale prima che al cloud. Risparmia chiamate al cloud, ma su un Raspberry Pi aggiunge 10–25 secondi a queste domande.",
|
|
171
171
|
"Local model timeout (s)": "Timeout del modello locale (s)",
|
|
172
172
|
"After this time the local model is stopped and the question goes on to the cloud.": "Trascorso questo tempo il modello locale viene interrotto e la domanda passa al cloud.",
|
|
173
|
-
"Used when the provider above fails (outage, expired key, empty quota). A local engine keeps voice working without the internet.": "Usato quando il
|
|
173
|
+
"Used when the provider above fails (outage, expired key, empty quota) or returns no text for speech. A local engine keeps voice working without the internet.": "Usato quando il fornitore sopra non funziona (guasto, chiave scaduta, quota esaurita) o non restituisce testo per il parlato. Un motore locale mantiene la voce attiva senza internet.",
|
|
174
174
|
"Used when the provider above fails. Piper keeps the assistant speaking without the internet.": "Usato quando il provider sopra non funziona. Piper fa parlare l'assistente anche senza internet.",
|
|
175
175
|
"Verify device feedback": "Verifica il riscontro del dispositivo",
|
|
176
176
|
"Voice": "Voce",
|
package/admin/i18n/nl.json
CHANGED
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
"Longest spoken answer (characters)": "Langste gesproken antwoord (tekens)",
|
|
158
158
|
"A longer answer is cut at the last sentence end before this limit. 400 characters are about 25–30 seconds of speech. 0 = no limit.": "Een langer antwoord wordt afgekapt bij het laatste zinseinde vóór deze grens. 400 tekens zijn ongeveer 25–30 seconden spraak. 0 = geen grens.",
|
|
159
159
|
"Text-to-speech provider": "Tekst-naar-spraak-aanbieder",
|
|
160
|
-
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long.": "Deze apparaten streamen tot de server ze stopt, dus de adapter
|
|
160
|
+
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long. After 2.5 seconds of speech half as much again is allowed, so a pause for thought does not end a longer request.": "Deze apparaten streamen tot de server ze stopt, dus de adapter beslist wanneer je klaar bent met praten. Verhoog de waarde als het antwoord je onderbreekt, verlaag haar als de assistent te lang wacht. Na 2,5 seconden spraak is een anderhalf keer zo lange pauze toegestaan, zodat een denkpauze een langer verzoek niet beëindigt.",
|
|
161
161
|
"ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. These devices listen on TCP 6053 and the adapter dials them, so no port is opened for the audio itself — only the media server below, which they fetch the spoken reply from.": "ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. Deze apparaten luisteren op TCP 6053 en de adapter belt ze zelf aan, dus voor de audio zelf wordt geen poort geopend — alleen de mediaserver hieronder, waar ze het gesproken antwoord ophalen.",
|
|
162
162
|
"Timer sound (mp3/wav, optional)": "Timergeluid (mp3/wav, optioneel)",
|
|
163
163
|
"Triggers": "Triggers",
|
|
@@ -170,7 +170,7 @@
|
|
|
170
170
|
"Every question the rules do not understand goes to the local model before the cloud. Saves cloud calls, but on a Raspberry Pi it adds 10–25 seconds to such questions.": "Elke vraag die de regels niet begrijpen gaat eerst naar het lokale model en dan naar de cloud. Bespaart cloudaanroepen, maar kost op een Raspberry Pi 10–25 seconden extra per zo’n vraag.",
|
|
171
171
|
"Local model timeout (s)": "Time-out lokaal model (s)",
|
|
172
172
|
"After this time the local model is stopped and the question goes on to the cloud.": "Na deze tijd wordt het lokale model gestopt en gaat de vraag door naar de cloud.",
|
|
173
|
-
"Used when the provider above fails (outage, expired key, empty quota). A local engine keeps voice working without the internet.": "
|
|
173
|
+
"Used when the provider above fails (outage, expired key, empty quota) or returns no text for speech. A local engine keeps voice working without the internet.": "Gebruikt als de bovenstaande provider faalt (storing, verlopen sleutel, leeg tegoed) of voor spraak geen tekst teruggeeft. Een lokale engine houdt spraak werkend zonder internet.",
|
|
174
174
|
"Used when the provider above fails. Piper keeps the assistant speaking without the internet.": "Wordt gebruikt als de bovenstaande provider faalt. Met Piper blijft de assistent spreken zonder internet.",
|
|
175
175
|
"Verify device feedback": "Terugmelding van apparaat controleren",
|
|
176
176
|
"Voice": "Stem",
|
package/admin/i18n/pl.json
CHANGED
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
"Longest spoken answer (characters)": "Najdłuższa wypowiadana odpowiedź (znaki)",
|
|
158
158
|
"A longer answer is cut at the last sentence end before this limit. 400 characters are about 25–30 seconds of speech. 0 = no limit.": "Dłuższa odpowiedź jest obcinana na ostatnim końcu zdania przed tym limitem. 400 znaków to około 25–30 sekund mowy. 0 = bez limitu.",
|
|
159
159
|
"Text-to-speech provider": "Dostawca tekstu na mowę",
|
|
160
|
-
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long.": "Te urządzenia
|
|
160
|
+
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long. After 2.5 seconds of speech half as much again is allowed, so a pause for thought does not end a longer request.": "Te urządzenia przesyłają dźwięk, dopóki serwer ich nie zatrzyma, więc to adapter decyduje, kiedy skończyłeś mówić. Zwiększ wartość, jeśli odpowiedź ci przerywa, zmniejsz, jeśli asystent czeka zbyt długo. Po 2,5 sekundy mowy dozwolona jest półtora raza dłuższa pauza, aby pauza do namysłu nie kończyła dłuższego polecenia.",
|
|
161
161
|
"ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. These devices listen on TCP 6053 and the adapter dials them, so no port is opened for the audio itself — only the media server below, which they fetch the spoken reply from.": "ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. Te urządzenia nasłuchują na TCP 6053 i to adapter nawiązuje z nimi połączenie, więc dla samego dźwięku nie jest otwierany żaden port — tylko serwer multimediów poniżej, z którego pobierają wypowiedzianą odpowiedź.",
|
|
162
162
|
"Timer sound (mp3/wav, optional)": "Dźwięk timera (mp3/wav, opcjonalnie)",
|
|
163
163
|
"Triggers": "Wyzwalacze",
|
|
@@ -170,7 +170,7 @@
|
|
|
170
170
|
"Every question the rules do not understand goes to the local model before the cloud. Saves cloud calls, but on a Raspberry Pi it adds 10–25 seconds to such questions.": "Każde pytanie, którego nie rozumieją reguły, trafia do modelu lokalnego przed chmurą. Oszczędza wywołania chmury, ale na Raspberry Pi wydłuża takie pytania o 10–25 sekund.",
|
|
171
171
|
"Local model timeout (s)": "Limit czasu modelu lokalnego (s)",
|
|
172
172
|
"After this time the local model is stopped and the question goes on to the cloud.": "Po tym czasie model lokalny jest zatrzymywany, a pytanie trafia do chmury.",
|
|
173
|
-
"Used when the provider above fails (outage, expired key, empty quota). A local engine keeps voice working without the internet.": "
|
|
173
|
+
"Used when the provider above fails (outage, expired key, empty quota) or returns no text for speech. A local engine keeps voice working without the internet.": "Używany, gdy powyższy dostawca zawiedzie (awaria, wygasły klucz, wyczerpany limit) lub nie zwróci tekstu dla mowy. Lokalny silnik utrzymuje sterowanie głosem bez internetu.",
|
|
174
174
|
"Used when the provider above fails. Piper keeps the assistant speaking without the internet.": "Używane, gdy powyższy dostawca zawiedzie. Piper pozwala asystentowi mówić bez internetu.",
|
|
175
175
|
"Verify device feedback": "Sprawdzaj potwierdzenie z urządzenia",
|
|
176
176
|
"Voice": "Głos",
|
package/admin/i18n/pt.json
CHANGED
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
"Longest spoken answer (characters)": "Resposta falada mais longa (caracteres)",
|
|
158
158
|
"A longer answer is cut at the last sentence end before this limit. 400 characters are about 25–30 seconds of speech. 0 = no limit.": "Uma resposta mais longa é cortada no último fim de frase antes deste limite. 400 caracteres são cerca de 25–30 segundos de fala. 0 = sem limite.",
|
|
159
159
|
"Text-to-speech provider": "provedor de texto para voz",
|
|
160
|
-
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long.": "Estes dispositivos transmitem até o servidor os parar, por isso é o adaptador que decide quando
|
|
160
|
+
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long. After 2.5 seconds of speech half as much again is allowed, so a pause for thought does not end a longer request.": "Estes dispositivos transmitem até o servidor os parar, por isso é o adaptador que decide quando você parou de falar. Aumente se a resposta o interromper; diminua se o assistente esperar demasiado. Após 2,5 segundos de fala é permitida uma pausa uma vez e meia mais longa, para que uma pausa para pensar não termine um pedido longo.",
|
|
161
161
|
"ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. These devices listen on TCP 6053 and the adapter dials them, so no port is opened for the audio itself — only the media server below, which they fetch the spoken reply from.": "ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. Estes dispositivos escutam na TCP 6053 e é o adaptador que os contacta, por isso não é aberta nenhuma porta para o áudio em si — apenas o servidor de media abaixo, de onde eles buscam a resposta falada.",
|
|
162
162
|
"Timer sound (mp3/wav, optional)": "Som do temporizador (mp3/wav, opcional)",
|
|
163
163
|
"Triggers": "Gatilhos",
|
|
@@ -170,7 +170,7 @@
|
|
|
170
170
|
"Every question the rules do not understand goes to the local model before the cloud. Saves cloud calls, but on a Raspberry Pi it adds 10–25 seconds to such questions.": "Cada pergunta que as regras não entendem vai ao modelo local antes da nuvem. Poupa chamadas à nuvem, mas num Raspberry Pi acrescenta 10–25 segundos a essas perguntas.",
|
|
171
171
|
"Local model timeout (s)": "Tempo limite do modelo local (s)",
|
|
172
172
|
"After this time the local model is stopped and the question goes on to the cloud.": "Após este tempo o modelo local é interrompido e a pergunta segue para a nuvem.",
|
|
173
|
-
"Used when the provider above fails (outage, expired key, empty quota). A local engine keeps voice working without the internet.": "Usado quando o
|
|
173
|
+
"Used when the provider above fails (outage, expired key, empty quota) or returns no text for speech. A local engine keeps voice working without the internet.": "Usado quando o fornecedor acima falha (falha, chave expirada, quota esgotada) ou não devolve texto para a fala. Um motor local mantém a voz a funcionar sem internet.",
|
|
174
174
|
"Used when the provider above fails. Piper keeps the assistant speaking without the internet.": "Usado quando o provedor acima falha. O Piper mantém o assistente falando sem internet.",
|
|
175
175
|
"Verify device feedback": "Verificar a resposta do dispositivo",
|
|
176
176
|
"Voice": "Voz",
|
package/admin/i18n/ru.json
CHANGED
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
"Longest spoken answer (characters)": "Самый длинный произносимый ответ (символов)",
|
|
158
158
|
"A longer answer is cut at the last sentence end before this limit. 400 characters are about 25–30 seconds of speech. 0 = no limit.": "Более длинный ответ обрезается по последнему концу предложения перед этим пределом. 400 символов — это примерно 25–30 секунд речи. 0 = без ограничения.",
|
|
159
159
|
"Text-to-speech provider": "Поставщик услуг преобразования текста в речь",
|
|
160
|
-
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long.": "Эти устройства передают
|
|
160
|
+
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long. After 2.5 seconds of speech half as much again is allowed, so a pause for thought does not end a longer request.": "Эти устройства передают звук, пока сервер их не остановит, поэтому адаптер сам решает, когда вы закончили говорить. Увеличьте значение, если ответ перебивает вас, уменьшите, если ассистент ждёт слишком долго. После 2,5 секунды речи допускается пауза в полтора раза длиннее, чтобы пауза на раздумье не обрывала длинный запрос.",
|
|
161
161
|
"ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. These devices listen on TCP 6053 and the adapter dials them, so no port is opened for the audio itself — only the media server below, which they fetch the spoken reply from.": "ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. Эти устройства слушают TCP 6053, и адаптер подключается к ним сам — поэтому для самого звука порт не открывается, только медиасервер ниже, с которого они забирают произнесённый ответ.",
|
|
162
162
|
"Timer sound (mp3/wav, optional)": "Звук таймера (mp3/wav, по желанию)",
|
|
163
163
|
"Triggers": "Триггеры",
|
|
@@ -170,7 +170,7 @@
|
|
|
170
170
|
"Every question the rules do not understand goes to the local model before the cloud. Saves cloud calls, but on a Raspberry Pi it adds 10–25 seconds to such questions.": "Каждый вопрос, который не поняли правила, сначала идёт к локальной модели, потом в облако. Экономит облачные запросы, но на Raspberry Pi добавляет к таким вопросам 10–25 секунд.",
|
|
171
171
|
"Local model timeout (s)": "Тайм-аут локальной модели (с)",
|
|
172
172
|
"After this time the local model is stopped and the question goes on to the cloud.": "По истечении этого времени локальная модель останавливается, и вопрос передаётся в облако.",
|
|
173
|
-
"Used when the provider above fails (outage, expired key, empty quota). A local engine keeps voice working without the internet.": "Используется, если указанный выше провайдер не работает (сбой, истёкший ключ, исчерпанная квота)
|
|
173
|
+
"Used when the provider above fails (outage, expired key, empty quota) or returns no text for speech. A local engine keeps voice working without the internet.": "Используется, если указанный выше провайдер не работает (сбой, истёкший ключ, исчерпанная квота) или не распознал речь. Локальный движок сохраняет голосовое управление без интернета.",
|
|
174
174
|
"Used when the provider above fails. Piper keeps the assistant speaking without the internet.": "Используется, если указанный выше провайдер не работает. Piper позволяет ассистенту говорить без интернета.",
|
|
175
175
|
"Verify device feedback": "Проверять ответ устройства",
|
|
176
176
|
"Voice": "Голос",
|
package/admin/i18n/uk.json
CHANGED
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
"Longest spoken answer (characters)": "Найдовша вимовлена відповідь (символів)",
|
|
158
158
|
"A longer answer is cut at the last sentence end before this limit. 400 characters are about 25–30 seconds of speech. 0 = no limit.": "Довша відповідь обрізається за останнім кінцем речення перед цією межею. 400 символів — це приблизно 25–30 секунд мовлення. 0 = без обмеження.",
|
|
159
159
|
"Text-to-speech provider": "Постачальник перетворення тексту в мовлення",
|
|
160
|
-
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long.": "Ці пристрої передають
|
|
160
|
+
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long. After 2.5 seconds of speech half as much again is allowed, so a pause for thought does not end a longer request.": "Ці пристрої передають звук, доки сервер їх не зупинить, тому адаптер сам вирішує, коли ви закінчили говорити. Збільште значення, якщо відповідь перебиває вас, зменште, якщо асистент чекає надто довго. Після 2,5 секунди мовлення допускається пауза в півтора раза довша, щоб пауза на роздуми не обривала довгий запит.",
|
|
161
161
|
"ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. These devices listen on TCP 6053 and the adapter dials them, so no port is opened for the audio itself — only the media server below, which they fetch the spoken reply from.": "ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. Ці пристрої слухають на TCP 6053, і адаптер підключається до них сам — тож для самого звуку порт не відкривається, лише медіасервер нижче, з якого вони забирають озвучену відповідь.",
|
|
162
162
|
"Timer sound (mp3/wav, optional)": "Звук таймера (mp3/wav, необов'язково)",
|
|
163
163
|
"Triggers": "Тригери",
|
|
@@ -170,7 +170,7 @@
|
|
|
170
170
|
"Every question the rules do not understand goes to the local model before the cloud. Saves cloud calls, but on a Raspberry Pi it adds 10–25 seconds to such questions.": "Кожне запитання, яке не зрозуміли правила, спочатку йде до локальної моделі, потім у хмару. Заощаджує хмарні запити, але на Raspberry Pi додає до таких запитань 10–25 секунд.",
|
|
171
171
|
"Local model timeout (s)": "Тайм-аут локальної моделі (с)",
|
|
172
172
|
"After this time the local model is stopped and the question goes on to the cloud.": "Після цього часу локальна модель зупиняється, і запитання передається в хмару.",
|
|
173
|
-
"Used when the provider above fails (outage, expired key, empty quota). A local engine keeps voice working without the internet.": "Використовується, якщо вказаний вище провайдер не працює (збій, прострочений ключ, вичерпана квота)
|
|
173
|
+
"Used when the provider above fails (outage, expired key, empty quota) or returns no text for speech. A local engine keeps voice working without the internet.": "Використовується, якщо вказаний вище провайдер не працює (збій, прострочений ключ, вичерпана квота) або не розпізнав мовлення. Локальний рушій зберігає голосове керування без інтернету.",
|
|
174
174
|
"Used when the provider above fails. Piper keeps the assistant speaking without the internet.": "Використовується, якщо вказаний вище провайдер не працює. Piper дає асистентові змогу говорити без інтернету.",
|
|
175
175
|
"Verify device feedback": "Перевіряти відповідь пристрою",
|
|
176
176
|
"Voice": "Голос",
|
package/admin/i18n/zh-cn.json
CHANGED
|
@@ -157,7 +157,7 @@
|
|
|
157
157
|
"Longest spoken answer (characters)": "最长语音回答(字符)",
|
|
158
158
|
"A longer answer is cut at the last sentence end before this limit. 400 characters are about 25–30 seconds of speech. 0 = no limit.": "更长的回答会在此上限之前的最后一个句末处截断。400 个字符约为 25–30 秒语音。0 = 不限制。",
|
|
159
159
|
"Text-to-speech provider": "文本转语音服务提供商",
|
|
160
|
-
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long.": "
|
|
160
|
+
"These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long. After 2.5 seconds of speech half as much again is allowed, so a pause for thought does not end a longer request.": "这些设备会一直传输音频,直到服务器让它们停止,因此由适配器判断您何时说完。如果回复打断了您,请调高;如果助手等待太久,请调低。说话超过 2.5 秒后,允许的停顿延长为 1.5 倍,这样思考时的停顿不会提前结束较长的请求。",
|
|
161
161
|
"ThirdReality Voice & Music Assistant, Home Assistant Voice PE, linux-voice-assistant. These devices listen on TCP 6053 and the adapter dials them, so no port is opened for the audio itself — only the media server below, which they fetch the spoken reply from.": "ThirdReality Voice & Music Assistant、Home Assistant Voice PE、linux-voice-assistant。这些设备在 TCP 6053 上监听,由适配器主动连接它们,因此音频本身不会占用端口——只有下面的媒体服务器,设备会从那里获取语音回复。",
|
|
162
162
|
"Timer sound (mp3/wav, optional)": "定时器声音(mp3/wav格式,可选)",
|
|
163
163
|
"Triggers": "触发器",
|
|
@@ -170,7 +170,7 @@
|
|
|
170
170
|
"Every question the rules do not understand goes to the local model before the cloud. Saves cloud calls, but on a Raspberry Pi it adds 10–25 seconds to such questions.": "规则无法理解的每个问题都会先交给本地模型,再交给云端。可节省云端调用,但在树莓派上每个此类问题会多花 10–25 秒。",
|
|
171
171
|
"Local model timeout (s)": "本地模型超时(秒)",
|
|
172
172
|
"After this time the local model is stopped and the question goes on to the cloud.": "超过此时间后本地模型将被停止,问题转交给云端。",
|
|
173
|
-
"Used when the provider above fails (outage, expired key, empty quota). A local engine keeps voice working without the internet.": "
|
|
173
|
+
"Used when the provider above fails (outage, expired key, empty quota) or returns no text for speech. A local engine keeps voice working without the internet.": "当上面的提供商出现故障(服务中断、密钥过期、额度用完)或对语音未返回文字时使用。本地引擎可在没有互联网时保持语音功能。",
|
|
174
174
|
"Used when the provider above fails. Piper keeps the assistant speaking without the internet.": "当上方的服务商不可用时使用。Piper 可让助手在没有互联网时继续说话。",
|
|
175
175
|
"Verify device feedback": "验证设备反馈",
|
|
176
176
|
"Voice": "嗓音",
|
package/admin/jsonConfig.json
CHANGED
|
@@ -937,7 +937,7 @@
|
|
|
937
937
|
"esphomeSilenceMs": {
|
|
938
938
|
"type": "number",
|
|
939
939
|
"label": "End of speech after (ms of silence)",
|
|
940
|
-
"help": "These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long.",
|
|
940
|
+
"help": "These devices stream until the server stops them, so the adapter decides when you stopped talking. Raise it if replies cut you off, lower it if the assistant waits too long. After 2.5 seconds of speech half as much again is allowed, so a pause for thought does not end a longer request.",
|
|
941
941
|
"default": 900,
|
|
942
942
|
"min": 200,
|
|
943
943
|
"max": 5000,
|
|
@@ -1060,7 +1060,7 @@
|
|
|
1060
1060
|
"newLine": true,
|
|
1061
1061
|
"type": "select",
|
|
1062
1062
|
"label": "Speech-to-text fallback",
|
|
1063
|
-
"help": "Used when the provider above fails (outage, expired key, empty quota). A local engine keeps voice working without the internet.",
|
|
1063
|
+
"help": "Used when the provider above fails (outage, expired key, empty quota) or returns no text for speech. A local engine keeps voice working without the internet.",
|
|
1064
1064
|
"options": [
|
|
1065
1065
|
{ "label": "None", "value": "" },
|
|
1066
1066
|
{ "label": "OpenAI (Whisper)", "value": "openai" },
|
package/build/lib/journal.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"journal.js","sourceRoot":"","sources":["../../src/lib/journal.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmKA,kCAEC;AAMD,4BAuBC;AAGD,8BAeC;AAGD,gDAcC;AArOD;;;;;;;;;;;;;;;;;GAiBG;AACH,uDAAqD;AACrD,qCAAyC;AACzC,gDAAkC;AA6HlC,wGAAwG;AACxG,MAAM,WAAW,GAAG,IAAI,CAAC;AACzB,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,MAAM,YAAY,GAAG,GAAG,CAAC;AACzB,4CAA4C;AAC/B,QAAA,UAAU,GAAG,GAAG,CAAC;AAC9B,oFAAoF;AACpF,MAAM,aAAa,GAAG,EAAE,CAAC;AACzB,oFAAoF;AACpF,MAAM,SAAS,GAAG,GAAG,CAAC;AACtB,sFAAsF;AACtF,MAAM,iBAAiB,GAAG,OAAO,CAAC;AAClC,2EAA2E;AAC3E,MAAM,gBAAgB,GAAG,OAAO,CAAC;AACjC,4FAA4F;AAC5F,MAAM,KAAK,GAAG,cAAc,CAAC;AAE7B,0DAA0D;AAC1D,SAAgB,WAAW,CAAC,IAAY;IACpC,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,eAAe,CAAC,CAAC;AAC1D,CAAC;AAED;;;GAGG;AACH,S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AAI,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBACtB,IAAI,KAAK,EAAE,CAAC;oBACR,MAAM,kBAAE,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;gBAC9F,CAAC;YACL,CAAC;YACD,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,kBAAU,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;YACrE,KAAK,MAAM,IAAI,IAAI,MAAM,kBAAE,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACjD,IAAI,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;oBACzD,MAAM,kBAAE,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;gBACjE,CAAC;YACL,CAAC;QACL,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACT,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,sCAAuC,CAAW,CAAC,OAAO,EAAE,CAAC,CAAC;QACrF,CAAC;IACL,CAAC;CACJ;AA9aD,0BA8aC","sourcesContent":["/**\n * Conversation journal: one entry per request the assistant answered — where it came from (chat, script,\n * Telegram, which satellite, which wake word), which tier answered it (routine, rule-based NLU, local\n * model, cloud model), which tools the model called and which state ids were read or written along the\n * way. The admin chat shows it live, so one can check what a satellite heard and what was done about it.\n *\n * Tools and state accesses happen deep inside the pipeline (NLU executor, LLM tool loop, routine\n * executor). Instead of threading an entry object through all of them, the entry rides along in an\n * {@link AsyncLocalStorage}: {@link Journal.run} opens it, and {@link Journal.note}/{@link Journal.tool}/\n * {@link Journal.stateAccess} write to whatever entry the current call chain belongs to — and do nothing\n * outside of one (a trigger writing a state is not a conversation).\n *\n * Besides the entry, every request keeps a **trace**: the steps of its processing with their timing and\n * whatever explains them — the NLU's parse, the full prompt and every round of the model, tool arguments\n * and results in full, speech recognition and synthesis. Traces are too big to ride along in `journal.last`\n * and in `journal.json`, so the chat fetches one when a request is opened ({@link Journal.trace}); each is\n * kept in a file of its own and only for the newest {@link MAX_TRACES} requests.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\n\n/** How a request reached us. */\nexport type JournalTransport = 'chat' | 'script' | 'state' | 'telegram' | 'esphome' | 'udp' | 'native' | 'wyoming';\n\n/** Which stage of the pipeline produced the answer. */\nexport type JournalTier =\n | 'stop' // stop word silenced a ringing timer/alarm\n | 'askReply' // the utterance answered an open `askUser` question\n | 'routine'\n | 'nlu'\n | 'localLlm'\n | 'cloud'\n | 'none'; // nothing local understood it and there is no cloud provider\n\n/** Tokens a model call used (summed over the rounds of a request in {@link JournalEntry.tokens}). */\nexport interface JournalTokens {\n input: number;\n output: number;\n /** Prompt tokens served from the provider's prompt cache. */\n cacheRead?: number;\n /** Prompt tokens written to the provider's prompt cache (Anthropic). */\n cacheWrite?: number;\n}\n\n/** One step of how a request was processed — what the debug view of the admin chat shows. */\nexport interface JournalStep {\n /** Start of the step in ms after the request started (negative for speech recognition, which comes first). */\n t: number;\n /** Duration, for steps that took time. */\n ms?: number;\n /** Pipeline stage: request, stt, context, stop, askReply, routine, youtube, nlu, localLlm, cloud, tool, state, answer, tts, error. */\n stage: string;\n title: string;\n level?: 'warn' | 'error';\n tokens?: JournalTokens;\n /** Whatever explains the step (prompts, model responses, parse results) — a JSON snapshot. */\n data?: unknown;\n}\n\n/** What a caller records; the journal adds the timing. */\nexport type JournalStepInput = Omit<JournalStep, 't'>;\n\n/** Hook for library code that should not know the journal (the LLM agent). */\nexport type TraceFn = (step: JournalStepInput) => void;\n\nexport interface JournalTool {\n name: string;\n args: Record<string, unknown>;\n ms: number;\n /** Result, JSON, shortened. */\n result?: string;\n error?: string;\n}\n\nexport interface JournalEntry {\n id: string;\n /** Start of the answer, ms. */\n ts: number;\n /** False while the answer is still being produced. */\n done: boolean;\n /** Time to produce the answer (without STT/TTS). */\n ms?: number;\n source: string;\n transport: JournalTransport;\n satellite?: string;\n room?: string;\n /** Wake word the satellite reported; '' = the mic was re-opened for a follow-up, absent = unknown. */\n wakeWord?: string;\n /** Speech recognition time, for voice requests. */\n sttMs?: number;\n /** Length of the recorded utterance. */\n audioMs?: number;\n /** Speech synthesis time of the reply (voice requests, filled in after the answer). */\n ttsMs?: number;\n /** Length of the spoken reply. */\n replyAudioMs?: number;\n question: string;\n answer?: string;\n error?: string;\n tier?: JournalTier;\n /** Model name, routine name or NLU actions — whatever explains the tier. */\n detail?: string;\n tools: JournalTool[];\n /** State ids read to produce the answer. */\n read: string[];\n /** States written to produce the answer. */\n written: { id: string; value: unknown }[];\n /** The reply asks back, so a satellite re-opened its mic. */\n followUp?: boolean;\n /** Tokens of all model calls, when a cloud model answered. */\n tokens?: JournalTokens;\n}\n\n/** What the caller knows about a request before the pipeline starts. */\nexport interface JournalOrigin {\n transport?: JournalTransport;\n satellite?: string;\n room?: string;\n wakeWord?: string;\n sttMs?: number;\n audioMs?: number;\n /** Voice activity detection of the utterance (ESPHome) — trace only. */\n vad?: { peak: number; noiseFloor: number; startLevel: number; endLevel: number };\n}\n\n/** What a transport reports after it synthesised the reply. */\nexport interface JournalSpeech {\n ms: number;\n audioMs: number;\n provider: string;\n fallback?: string;\n voice?: string;\n}\n\nexport interface JournalOptions {\n /** Retention in hours; 0 disables the journal entirely. */\n hours: number;\n /** File the journal is kept in across restarts ('' = memory only). */\n file: string;\n /** Called with every new or updated entry (drives the `journal.last` state the chat listens to). */\n onChange?: (entry: JournalEntry) => void;\n log: ioBroker.Logger;\n}\n\n/** Hard cap independent of the retention — a script asking every few seconds must not fill the disk. */\nconst MAX_ENTRIES = 3000;\nconst SAVE_DELAY_MS = 5000;\nconst RESULT_CHARS = 300;\n/** Requests whose trace is kept on disk. */\nexport const MAX_TRACES = 200;\n/** Traces held in memory (the newest ones — the ones somebody is about to open). */\nconst MEMORY_TRACES = 30;\n/** Steps per request; a tool loop gone wild must not grow one trace without end. */\nconst MAX_STEPS = 400;\n/** Longer strings are cut — enough for a system prompt with a few hundred devices. */\nconst STEP_STRING_CHARS = 100_000;\n/** A reply is matched to its synthesis only this long after the answer. */\nconst SPEECH_WINDOW_MS = 120_000;\n/** Entry ids as {@link Journal.run} makes them — checked before one becomes a file name. */\nconst ID_RE = /^[a-z0-9-]+$/;\n\n/** Directory the traces of a journal file are kept in. */\nexport function traceDirFor(file: string): string {\n return path.join(path.dirname(file), 'journal-trace');\n}\n\n/**\n * JSON snapshot of a step's data — taken when it is recorded, because the objects go on changing (the\n * model's message list grows, cache markers move). Long strings are cut and buffers summarised.\n */\nexport function snapshot(value: unknown): unknown {\n if (value === undefined) {\n return undefined;\n }\n try {\n const text = JSON.stringify(value, (_key, v: unknown) => {\n if (typeof v === 'string' && v.length > STEP_STRING_CHARS) {\n return `${v.slice(0, STEP_STRING_CHARS)}… [+${v.length - STEP_STRING_CHARS} chars]`;\n }\n if (typeof v === 'bigint') {\n return v.toString();\n }\n // Buffer.toJSON() has already run when the replacer sees it.\n const b = v as { type?: unknown; data?: unknown } | null;\n if (b && typeof b === 'object' && b.type === 'Buffer' && Array.isArray(b.data)) {\n return `<${b.data.length} bytes>`;\n }\n return v;\n });\n return text === undefined ? undefined : JSON.parse(text);\n } catch (e) {\n return `<not serializable: ${(e as Error).message}>`;\n }\n}\n\n/** Everything an error carries that helps — an API error's status and body, the stack. */\nexport function errorInfo(e: unknown): Record<string, unknown> {\n if (!(e instanceof Error)) {\n return { message: String(e) };\n }\n const info: Record<string, unknown> = { name: e.name, message: e.message };\n for (const key of ['status', 'code', 'type', 'param', 'error', 'request_id', 'requestID']) {\n const v = (e as unknown as Record<string, unknown>)[key];\n if (v !== undefined && v !== null) {\n info[key] = v;\n }\n }\n if (e.stack) {\n info.stack = e.stack;\n }\n return info;\n}\n\n/** Derive the transport from a request source when the caller did not say. */\nexport function transportForSource(source: string): JournalTransport {\n if (source === 'chat') {\n return 'chat';\n }\n if (source === '') {\n return 'state';\n }\n if (source === 'wyoming') {\n return 'wyoming';\n }\n if (source.startsWith('telegram:')) {\n return 'telegram';\n }\n return 'script';\n}\n\nexport class Journal {\n private entries: JournalEntry[] = [];\n private readonly store = new AsyncLocalStorage<JournalEntry>();\n private saveTimer: NodeJS.Timeout | null = null;\n private counter = 0;\n /** Steps of the newest requests; older ones are read back from their file. */\n private readonly traces = new Map<string, JournalStep[]>();\n /** Traces changed since they were last written. */\n private readonly dirty = new Set<string>();\n /** LLM tool calls in progress per request: a state access inside one belongs to that tool's step. */\n private readonly toolDepth = new WeakMap<JournalEntry, number>();\n private readonly traceDir: string;\n\n constructor(private readonly opts: JournalOptions) {\n this.traceDir = opts.file ? traceDirFor(opts.file) : '';\n }\n\n get enabled(): boolean {\n return this.opts.hours > 0;\n }\n\n /** Load the entries of the last run (silently starts empty when there are none). */\n async load(): Promise<void> {\n if (!this.enabled || !this.opts.file) {\n return;\n }\n try {\n const raw = JSON.parse(await fs.readFile(this.opts.file, 'utf8')) as unknown;\n if (Array.isArray(raw)) {\n // An entry still open at shutdown never got its answer.\n this.entries = (raw as JournalEntry[])\n .filter(e => e && typeof e.id === 'string' && typeof e.ts === 'number')\n .map(e => (e.done ? e : { ...e, done: true, error: e.error || 'interrupted' }));\n this.prune();\n }\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {\n this.opts.log.warn(`Journal could not be read: ${(e as Error).message}`);\n }\n }\n }\n\n /** Entries newer than `since` (ms), oldest first. */\n list(since = 0): JournalEntry[] {\n this.prune();\n return this.entries.filter(e => e.ts > since);\n }\n\n clear(): void {\n this.entries = [];\n this.traces.clear();\n this.dirty.clear();\n this.scheduleSave();\n }\n\n /** The entry of a request (the chat asks for it together with its trace). */\n get(id: string): JournalEntry | undefined {\n return this.entries.find(e => e.id === id);\n }\n\n /** The processing steps of a request, or null when none were kept (too old, or from an older version). */\n async trace(id: string): Promise<JournalStep[] | null> {\n if (!ID_RE.test(id) || !this.get(id)) {\n return null;\n }\n const steps = this.traces.get(id);\n if (steps) {\n return steps;\n }\n if (!this.traceDir) {\n return null;\n }\n try {\n const raw = JSON.parse(await fs.readFile(path.join(this.traceDir, `${id}.json`), 'utf8')) as {\n steps?: unknown;\n };\n return Array.isArray(raw?.steps) ? (raw.steps as JournalStep[]) : null;\n } catch {\n return null;\n }\n }\n\n /**\n * Run `fn` as one journalled request. The entry is published once when the request starts (so the\n * chat shows the question while the answer is still being worked out) and once when it is finished.\n */\n async run(question: string, source: string, origin: JournalOrigin, fn: () => Promise<string>): Promise<string> {\n if (!this.enabled) {\n return fn();\n }\n const entry: JournalEntry = {\n id: `${Date.now().toString(36)}-${(this.counter++).toString(36)}`,\n ts: Date.now(),\n done: false,\n source,\n transport: origin.transport || transportForSource(source),\n question,\n tools: [],\n read: [],\n written: [],\n };\n for (const key of ['satellite', 'room', 'wakeWord', 'sttMs', 'audioMs'] as const) {\n if (origin[key] !== undefined && origin[key] !== '') {\n (entry as unknown as Record<string, unknown>)[key] = origin[key];\n }\n }\n // A satellite that re-opened its mic reports no wake word — say so instead of \"unknown\".\n if (origin.wakeWord === '') {\n entry.wakeWord = '';\n }\n this.entries.push(entry);\n this.traces.set(entry.id, []);\n this.addStep(entry, {\n stage: 'request',\n title: `Request from ${source || entry.transport} (${entry.transport})`,\n data: { question, source, origin },\n });\n this.publish(entry);\n try {\n const answer = await this.store.run(entry, fn);\n entry.answer = answer;\n return answer;\n } catch (e) {\n entry.error = (e as Error).message;\n this.addStep(entry, { stage: 'error', level: 'error', title: entry.error, data: errorInfo(e) });\n throw e;\n } finally {\n entry.done = true;\n entry.ms = Date.now() - entry.ts;\n this.dirty.add(entry.id);\n this.publish(entry);\n this.prune();\n this.scheduleSave();\n }\n }\n\n /** Add a step to the current request's trace (nothing outside of one). */\n step(input: JournalStepInput): void {\n const entry = this.store.getStore();\n if (entry) {\n this.addStep(entry, input);\n }\n }\n\n /**\n * Run an LLM tool as part of the current request: the call lands in the entry's tool list and, with the\n * full arguments and result, in the trace.\n */\n async toolCall<T>(name: string, args: Record<string, unknown>, fn: () => Promise<T>): Promise<T> {\n const entry = this.store.getStore();\n if (!entry) {\n return fn();\n }\n this.toolDepth.set(entry, (this.toolDepth.get(entry) || 0) + 1);\n const start = Date.now();\n try {\n const result = await fn();\n const ms = Date.now() - start;\n this.addStep(entry, { stage: 'tool', title: `Tool ${name}`, ms, data: { args, result } });\n this.tool(name, args, ms, result);\n return result;\n } catch (e) {\n const ms = Date.now() - start;\n const message = (e as Error).message;\n this.addStep(entry, {\n stage: 'tool',\n level: 'error',\n title: `Tool ${name} failed: ${message}`,\n ms,\n data: { args, error: errorInfo(e) },\n });\n this.tool(name, args, ms, undefined, message);\n throw e;\n } finally {\n this.toolDepth.set(entry, (this.toolDepth.get(entry) || 1) - 1);\n }\n }\n\n /**\n * Run a state call (MCP `get_states`/`set_state`/…) as part of the current request: the ids land in the\n * entry's read/written lists, and — unless an LLM tool made the call, whose step already shows it — the\n * call with its result in the trace.\n */\n async stateCall<T>(name: string, args: Record<string, unknown> | undefined, fn: () => Promise<T>): Promise<T> {\n const entry = this.store.getStore();\n if (!entry) {\n return fn();\n }\n this.stateAccess(name, args);\n if (this.toolDepth.get(entry)) {\n return fn();\n }\n const start = Date.now();\n try {\n const result = await fn();\n this.addStep(entry, { stage: 'state', title: name, ms: Date.now() - start, data: { args, result } });\n return result;\n } catch (e) {\n this.addStep(entry, {\n stage: 'state',\n level: 'error',\n title: `${name} failed: ${(e as Error).message}`,\n ms: Date.now() - start,\n data: { args, error: errorInfo(e) },\n });\n throw e;\n }\n }\n\n /**\n * A transport synthesised the reply to the latest request of `source`. That happens after the answer,\n * outside of the request, so the entry is found by its source.\n */\n spoken(source: string, speech: JournalSpeech): void {\n const now = Date.now();\n for (let i = this.entries.length - 1; i >= 0; i--) {\n const entry = this.entries[i];\n if (entry.source !== source) {\n continue;\n }\n if (!entry.done || entry.ttsMs !== undefined || now - entry.ts - (entry.ms || 0) > SPEECH_WINDOW_MS) {\n return;\n }\n entry.ttsMs = speech.ms;\n entry.replyAudioMs = Math.round(speech.audioMs);\n const voice = speech.voice ? ` (${speech.voice})` : '';\n this.addStep(entry, {\n stage: 'tts',\n title: `Speech synthesis: ${speech.provider}${voice}, ${(speech.audioMs / 1000).toFixed(1)} s of audio`,\n ms: speech.ms,\n data: speech,\n });\n this.dirty.add(entry.id);\n this.publish(entry);\n this.scheduleSave();\n return;\n }\n }\n\n private addStep(entry: JournalEntry, input: JournalStepInput): void {\n const steps = this.traces.get(entry.id);\n if (!steps || steps.length > MAX_STEPS) {\n return;\n }\n if (steps.length === MAX_STEPS) {\n steps.push({\n t: Date.now() - entry.ts,\n stage: 'error',\n level: 'warn',\n title: `More than ${MAX_STEPS} steps — the rest is not recorded`,\n });\n return;\n }\n const step: JournalStep = {\n t: Date.now() - entry.ts - (input.ms || 0),\n stage: input.stage,\n title: input.title,\n };\n if (input.ms !== undefined) {\n step.ms = input.ms;\n }\n if (input.level) {\n step.level = input.level;\n }\n if (input.tokens) {\n step.tokens = input.tokens;\n const sum = (entry.tokens ||= { input: 0, output: 0 });\n sum.input += input.tokens.input || 0;\n sum.output += input.tokens.output || 0;\n if (input.tokens.cacheRead) {\n sum.cacheRead = (sum.cacheRead || 0) + input.tokens.cacheRead;\n }\n if (input.tokens.cacheWrite) {\n sum.cacheWrite = (sum.cacheWrite || 0) + input.tokens.cacheWrite;\n }\n }\n if (input.data !== undefined) {\n step.data = snapshot(input.data);\n }\n steps.push(step);\n }\n\n /** Fill in fields of the current request's entry (tier, detail, followUp …). */\n note(fields: Partial<Pick<JournalEntry, 'tier' | 'detail' | 'followUp'>>): void {\n const entry = this.store.getStore();\n if (entry) {\n Object.assign(entry, fields);\n }\n }\n\n /** Record a tool call the model made for the current request. */\n tool(name: string, args: Record<string, unknown>, ms: number, result: unknown, error?: string): void {\n const entry = this.store.getStore();\n if (!entry) {\n return;\n }\n const item: JournalTool = { name, args: args || {}, ms };\n if (error) {\n item.error = error;\n } else {\n let text: string;\n try {\n text = typeof result === 'string' ? result : JSON.stringify(result);\n } catch {\n text = String(result);\n }\n item.result = text.length > RESULT_CHARS ? `${text.slice(0, RESULT_CHARS)}…` : text;\n }\n entry.tools.push(item);\n // Live view: show each tool call as it happens, a cloud round can take seconds.\n this.publish(entry);\n }\n\n /** Record which states a call reads or writes (MCP `get_states`/`set_state`/`set_states`, routines). */\n stateAccess(tool: string, args: Record<string, unknown> | undefined): void {\n const entry = this.store.getStore();\n if (!entry || !args) {\n return;\n }\n if (tool === 'get_states' && Array.isArray(args.ids)) {\n for (const id of args.ids) {\n if (typeof id === 'string' && !entry.read.includes(id)) {\n entry.read.push(id);\n }\n }\n } else if (tool === 'get_state' && typeof args.id === 'string') {\n if (!entry.read.includes(args.id)) {\n entry.read.push(args.id);\n }\n } else if (tool === 'set_state' && typeof args.id === 'string') {\n entry.written.push({ id: args.id, value: args.value });\n } else if (tool === 'set_states' && Array.isArray(args.states)) {\n for (const s of args.states as { id?: unknown; value?: unknown }[]) {\n if (typeof s?.id === 'string') {\n entry.written.push({ id: s.id, value: s.value });\n }\n }\n }\n }\n\n /** Write pending changes now (on unload). */\n async flush(): Promise<void> {\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n await this.save();\n }\n\n private publish(entry: JournalEntry): void {\n try {\n this.opts.onChange?.(entry);\n } catch {\n // a listener must never break the answer\n }\n }\n\n private prune(): void {\n const cutoff = Date.now() - this.opts.hours * 3600_000;\n let start = 0;\n while (start < this.entries.length && this.entries[start].ts < cutoff) {\n start++;\n }\n start = Math.max(start, this.entries.length - MAX_ENTRIES);\n if (start > 0) {\n for (const e of this.entries.slice(0, start)) {\n this.traces.delete(e.id);\n this.dirty.delete(e.id);\n }\n this.entries = this.entries.slice(start);\n }\n // Without a file the memory is all there is: keep as many as would be on disk.\n const keep = this.traceDir ? MEMORY_TRACES : MAX_TRACES;\n for (const id of this.traces.keys()) {\n if (this.traces.size <= keep) {\n break;\n }\n // Not written yet, or still being answered: needed until it is on disk.\n if ((!this.traceDir || !this.dirty.has(id)) && this.get(id)?.done !== false) {\n this.traces.delete(id);\n }\n }\n }\n\n private scheduleSave(): void {\n if (!this.opts.file || this.saveTimer) {\n return;\n }\n this.saveTimer = setTimeout(() => {\n this.saveTimer = null;\n void this.save();\n }, SAVE_DELAY_MS);\n this.saveTimer.unref?.();\n }\n\n private async save(): Promise<void> {\n if (!this.opts.file) {\n return;\n }\n try {\n await fs.mkdir(path.dirname(this.opts.file), { recursive: true });\n await fs.writeFile(this.opts.file, JSON.stringify(this.entries.filter(e => e.done)));\n } catch (e) {\n this.opts.log.warn(`Journal could not be saved: ${(e as Error).message}`);\n }\n await this.saveTraces();\n this.prune();\n }\n\n /** Write the traces that changed, and delete the files of requests that are no longer kept. */\n private async saveTraces(): Promise<void> {\n try {\n await fs.mkdir(this.traceDir, { recursive: true });\n for (const id of [...this.dirty]) {\n const steps = this.traces.get(id);\n this.dirty.delete(id);\n if (steps) {\n await fs.writeFile(path.join(this.traceDir, `${id}.json`), JSON.stringify({ id, steps }));\n }\n }\n const keep = new Set(this.entries.slice(-MAX_TRACES).map(e => e.id));\n for (const name of await fs.readdir(this.traceDir)) {\n if (name.endsWith('.json') && !keep.has(name.slice(0, -5))) {\n await fs.rm(path.join(this.traceDir, name), { force: true });\n }\n }\n } catch (e) {\n this.opts.log.warn(`Journal traces could not be saved: ${(e as Error).message}`);\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,OAAO,CAAC,KAAK,CAAC,CAAC,kBAAU,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;YACrE,KAAK,MAAM,IAAI,IAAI,MAAM,kBAAE,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACjD,IAAI,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;oBACzD,MAAM,kBAAE,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;gBACjE,CAAC;YACL,CAAC;QACL,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACT,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,sCAAuC,CAAW,CAAC,OAAO,EAAE,CAAC,CAAC;QACrF,CAAC;IACL,CAAC;CACJ;AA9aD,0BA8aC","sourcesContent":["/**\n * Conversation journal: one entry per request the assistant answered — where it came from (chat, script,\n * Telegram, which satellite, which wake word), which tier answered it (routine, rule-based NLU, local\n * model, cloud model), which tools the model called and which state ids were read or written along the\n * way. The admin chat shows it live, so one can check what a satellite heard and what was done about it.\n *\n * Tools and state accesses happen deep inside the pipeline (NLU executor, LLM tool loop, routine\n * executor). Instead of threading an entry object through all of them, the entry rides along in an\n * {@link AsyncLocalStorage}: {@link Journal.run} opens it, and {@link Journal.note}/{@link Journal.tool}/\n * {@link Journal.stateAccess} write to whatever entry the current call chain belongs to — and do nothing\n * outside of one (a trigger writing a state is not a conversation).\n *\n * Besides the entry, every request keeps a **trace**: the steps of its processing with their timing and\n * whatever explains them — the NLU's parse, the full prompt and every round of the model, tool arguments\n * and results in full, speech recognition and synthesis. Traces are too big to ride along in `journal.last`\n * and in `journal.json`, so the chat fetches one when a request is opened ({@link Journal.trace}); each is\n * kept in a file of its own and only for the newest {@link MAX_TRACES} requests.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport type { VadReport } from './voice/vad';\n\n/** How a request reached us. */\nexport type JournalTransport = 'chat' | 'script' | 'state' | 'telegram' | 'esphome' | 'udp' | 'native' | 'wyoming';\n\n/** Which stage of the pipeline produced the answer. */\nexport type JournalTier =\n | 'stop' // stop word silenced a ringing timer/alarm\n | 'askReply' // the utterance answered an open `askUser` question\n | 'routine'\n | 'nlu'\n | 'localLlm'\n | 'cloud'\n | 'none'; // nothing local understood it and there is no cloud provider\n\n/** Tokens a model call used (summed over the rounds of a request in {@link JournalEntry.tokens}). */\nexport interface JournalTokens {\n input: number;\n output: number;\n /** Prompt tokens served from the provider's prompt cache. */\n cacheRead?: number;\n /** Prompt tokens written to the provider's prompt cache (Anthropic). */\n cacheWrite?: number;\n}\n\n/** One step of how a request was processed — what the debug view of the admin chat shows. */\nexport interface JournalStep {\n /** Start of the step in ms after the request started (negative for speech recognition, which comes first). */\n t: number;\n /** Duration, for steps that took time. */\n ms?: number;\n /** Pipeline stage: request, stt, context, stop, askReply, routine, youtube, nlu, localLlm, cloud, tool, state, answer, tts, error. */\n stage: string;\n title: string;\n level?: 'warn' | 'error';\n tokens?: JournalTokens;\n /** Whatever explains the step (prompts, model responses, parse results) — a JSON snapshot. */\n data?: unknown;\n}\n\n/** What a caller records; the journal adds the timing. */\nexport type JournalStepInput = Omit<JournalStep, 't'>;\n\n/** Hook for library code that should not know the journal (the LLM agent). */\nexport type TraceFn = (step: JournalStepInput) => void;\n\nexport interface JournalTool {\n name: string;\n args: Record<string, unknown>;\n ms: number;\n /** Result, JSON, shortened. */\n result?: string;\n error?: string;\n}\n\nexport interface JournalEntry {\n id: string;\n /** Start of the answer, ms. */\n ts: number;\n /** False while the answer is still being produced. */\n done: boolean;\n /** Time to produce the answer (without STT/TTS). */\n ms?: number;\n source: string;\n transport: JournalTransport;\n satellite?: string;\n room?: string;\n /** Wake word the satellite reported; '' = the mic was re-opened for a follow-up, absent = unknown. */\n wakeWord?: string;\n /** Speech recognition time, for voice requests. */\n sttMs?: number;\n /** Length of the recorded utterance. */\n audioMs?: number;\n /** Speech synthesis time of the reply (voice requests, filled in after the answer). */\n ttsMs?: number;\n /** Length of the spoken reply. */\n replyAudioMs?: number;\n question: string;\n answer?: string;\n error?: string;\n tier?: JournalTier;\n /** Model name, routine name or NLU actions — whatever explains the tier. */\n detail?: string;\n tools: JournalTool[];\n /** State ids read to produce the answer. */\n read: string[];\n /** States written to produce the answer. */\n written: { id: string; value: unknown }[];\n /** The reply asks back, so a satellite re-opened its mic. */\n followUp?: boolean;\n /** Tokens of all model calls, when a cloud model answered. */\n tokens?: JournalTokens;\n}\n\n/** What the caller knows about a request before the pipeline starts. */\nexport interface JournalOrigin {\n transport?: JournalTransport;\n satellite?: string;\n room?: string;\n wakeWord?: string;\n sttMs?: number;\n audioMs?: number;\n /** Voice activity detection of the utterance (ESPHome) — trace only. */\n vad?: VadReport;\n}\n\n/** What a transport reports after it synthesised the reply. */\nexport interface JournalSpeech {\n ms: number;\n audioMs: number;\n provider: string;\n fallback?: string;\n voice?: string;\n}\n\nexport interface JournalOptions {\n /** Retention in hours; 0 disables the journal entirely. */\n hours: number;\n /** File the journal is kept in across restarts ('' = memory only). */\n file: string;\n /** Called with every new or updated entry (drives the `journal.last` state the chat listens to). */\n onChange?: (entry: JournalEntry) => void;\n log: ioBroker.Logger;\n}\n\n/** Hard cap independent of the retention — a script asking every few seconds must not fill the disk. */\nconst MAX_ENTRIES = 3000;\nconst SAVE_DELAY_MS = 5000;\nconst RESULT_CHARS = 300;\n/** Requests whose trace is kept on disk. */\nexport const MAX_TRACES = 200;\n/** Traces held in memory (the newest ones — the ones somebody is about to open). */\nconst MEMORY_TRACES = 30;\n/** Steps per request; a tool loop gone wild must not grow one trace without end. */\nconst MAX_STEPS = 400;\n/** Longer strings are cut — enough for a system prompt with a few hundred devices. */\nconst STEP_STRING_CHARS = 100_000;\n/** A reply is matched to its synthesis only this long after the answer. */\nconst SPEECH_WINDOW_MS = 120_000;\n/** Entry ids as {@link Journal.run} makes them — checked before one becomes a file name. */\nconst ID_RE = /^[a-z0-9-]+$/;\n\n/** Directory the traces of a journal file are kept in. */\nexport function traceDirFor(file: string): string {\n return path.join(path.dirname(file), 'journal-trace');\n}\n\n/**\n * JSON snapshot of a step's data — taken when it is recorded, because the objects go on changing (the\n * model's message list grows, cache markers move). Long strings are cut and buffers summarised.\n */\nexport function snapshot(value: unknown): unknown {\n if (value === undefined) {\n return undefined;\n }\n try {\n const text = JSON.stringify(value, (_key, v: unknown) => {\n if (typeof v === 'string' && v.length > STEP_STRING_CHARS) {\n return `${v.slice(0, STEP_STRING_CHARS)}… [+${v.length - STEP_STRING_CHARS} chars]`;\n }\n if (typeof v === 'bigint') {\n return v.toString();\n }\n // Buffer.toJSON() has already run when the replacer sees it.\n const b = v as { type?: unknown; data?: unknown } | null;\n if (b && typeof b === 'object' && b.type === 'Buffer' && Array.isArray(b.data)) {\n return `<${b.data.length} bytes>`;\n }\n return v;\n });\n return text === undefined ? undefined : JSON.parse(text);\n } catch (e) {\n return `<not serializable: ${(e as Error).message}>`;\n }\n}\n\n/** Everything an error carries that helps — an API error's status and body, the stack. */\nexport function errorInfo(e: unknown): Record<string, unknown> {\n if (!(e instanceof Error)) {\n return { message: String(e) };\n }\n const info: Record<string, unknown> = { name: e.name, message: e.message };\n for (const key of ['status', 'code', 'type', 'param', 'error', 'request_id', 'requestID']) {\n const v = (e as unknown as Record<string, unknown>)[key];\n if (v !== undefined && v !== null) {\n info[key] = v;\n }\n }\n if (e.stack) {\n info.stack = e.stack;\n }\n return info;\n}\n\n/** Derive the transport from a request source when the caller did not say. */\nexport function transportForSource(source: string): JournalTransport {\n if (source === 'chat') {\n return 'chat';\n }\n if (source === '') {\n return 'state';\n }\n if (source === 'wyoming') {\n return 'wyoming';\n }\n if (source.startsWith('telegram:')) {\n return 'telegram';\n }\n return 'script';\n}\n\nexport class Journal {\n private entries: JournalEntry[] = [];\n private readonly store = new AsyncLocalStorage<JournalEntry>();\n private saveTimer: NodeJS.Timeout | null = null;\n private counter = 0;\n /** Steps of the newest requests; older ones are read back from their file. */\n private readonly traces = new Map<string, JournalStep[]>();\n /** Traces changed since they were last written. */\n private readonly dirty = new Set<string>();\n /** LLM tool calls in progress per request: a state access inside one belongs to that tool's step. */\n private readonly toolDepth = new WeakMap<JournalEntry, number>();\n private readonly traceDir: string;\n\n constructor(private readonly opts: JournalOptions) {\n this.traceDir = opts.file ? traceDirFor(opts.file) : '';\n }\n\n get enabled(): boolean {\n return this.opts.hours > 0;\n }\n\n /** Load the entries of the last run (silently starts empty when there are none). */\n async load(): Promise<void> {\n if (!this.enabled || !this.opts.file) {\n return;\n }\n try {\n const raw = JSON.parse(await fs.readFile(this.opts.file, 'utf8')) as unknown;\n if (Array.isArray(raw)) {\n // An entry still open at shutdown never got its answer.\n this.entries = (raw as JournalEntry[])\n .filter(e => e && typeof e.id === 'string' && typeof e.ts === 'number')\n .map(e => (e.done ? e : { ...e, done: true, error: e.error || 'interrupted' }));\n this.prune();\n }\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {\n this.opts.log.warn(`Journal could not be read: ${(e as Error).message}`);\n }\n }\n }\n\n /** Entries newer than `since` (ms), oldest first. */\n list(since = 0): JournalEntry[] {\n this.prune();\n return this.entries.filter(e => e.ts > since);\n }\n\n clear(): void {\n this.entries = [];\n this.traces.clear();\n this.dirty.clear();\n this.scheduleSave();\n }\n\n /** The entry of a request (the chat asks for it together with its trace). */\n get(id: string): JournalEntry | undefined {\n return this.entries.find(e => e.id === id);\n }\n\n /** The processing steps of a request, or null when none were kept (too old, or from an older version). */\n async trace(id: string): Promise<JournalStep[] | null> {\n if (!ID_RE.test(id) || !this.get(id)) {\n return null;\n }\n const steps = this.traces.get(id);\n if (steps) {\n return steps;\n }\n if (!this.traceDir) {\n return null;\n }\n try {\n const raw = JSON.parse(await fs.readFile(path.join(this.traceDir, `${id}.json`), 'utf8')) as {\n steps?: unknown;\n };\n return Array.isArray(raw?.steps) ? (raw.steps as JournalStep[]) : null;\n } catch {\n return null;\n }\n }\n\n /**\n * Run `fn` as one journalled request. The entry is published once when the request starts (so the\n * chat shows the question while the answer is still being worked out) and once when it is finished.\n */\n async run(question: string, source: string, origin: JournalOrigin, fn: () => Promise<string>): Promise<string> {\n if (!this.enabled) {\n return fn();\n }\n const entry: JournalEntry = {\n id: `${Date.now().toString(36)}-${(this.counter++).toString(36)}`,\n ts: Date.now(),\n done: false,\n source,\n transport: origin.transport || transportForSource(source),\n question,\n tools: [],\n read: [],\n written: [],\n };\n for (const key of ['satellite', 'room', 'wakeWord', 'sttMs', 'audioMs'] as const) {\n if (origin[key] !== undefined && origin[key] !== '') {\n (entry as unknown as Record<string, unknown>)[key] = origin[key];\n }\n }\n // A satellite that re-opened its mic reports no wake word — say so instead of \"unknown\".\n if (origin.wakeWord === '') {\n entry.wakeWord = '';\n }\n this.entries.push(entry);\n this.traces.set(entry.id, []);\n this.addStep(entry, {\n stage: 'request',\n title: `Request from ${source || entry.transport} (${entry.transport})`,\n data: { question, source, origin },\n });\n this.publish(entry);\n try {\n const answer = await this.store.run(entry, fn);\n entry.answer = answer;\n return answer;\n } catch (e) {\n entry.error = (e as Error).message;\n this.addStep(entry, { stage: 'error', level: 'error', title: entry.error, data: errorInfo(e) });\n throw e;\n } finally {\n entry.done = true;\n entry.ms = Date.now() - entry.ts;\n this.dirty.add(entry.id);\n this.publish(entry);\n this.prune();\n this.scheduleSave();\n }\n }\n\n /** Add a step to the current request's trace (nothing outside of one). */\n step(input: JournalStepInput): void {\n const entry = this.store.getStore();\n if (entry) {\n this.addStep(entry, input);\n }\n }\n\n /**\n * Run an LLM tool as part of the current request: the call lands in the entry's tool list and, with the\n * full arguments and result, in the trace.\n */\n async toolCall<T>(name: string, args: Record<string, unknown>, fn: () => Promise<T>): Promise<T> {\n const entry = this.store.getStore();\n if (!entry) {\n return fn();\n }\n this.toolDepth.set(entry, (this.toolDepth.get(entry) || 0) + 1);\n const start = Date.now();\n try {\n const result = await fn();\n const ms = Date.now() - start;\n this.addStep(entry, { stage: 'tool', title: `Tool ${name}`, ms, data: { args, result } });\n this.tool(name, args, ms, result);\n return result;\n } catch (e) {\n const ms = Date.now() - start;\n const message = (e as Error).message;\n this.addStep(entry, {\n stage: 'tool',\n level: 'error',\n title: `Tool ${name} failed: ${message}`,\n ms,\n data: { args, error: errorInfo(e) },\n });\n this.tool(name, args, ms, undefined, message);\n throw e;\n } finally {\n this.toolDepth.set(entry, (this.toolDepth.get(entry) || 1) - 1);\n }\n }\n\n /**\n * Run a state call (MCP `get_states`/`set_state`/…) as part of the current request: the ids land in the\n * entry's read/written lists, and — unless an LLM tool made the call, whose step already shows it — the\n * call with its result in the trace.\n */\n async stateCall<T>(name: string, args: Record<string, unknown> | undefined, fn: () => Promise<T>): Promise<T> {\n const entry = this.store.getStore();\n if (!entry) {\n return fn();\n }\n this.stateAccess(name, args);\n if (this.toolDepth.get(entry)) {\n return fn();\n }\n const start = Date.now();\n try {\n const result = await fn();\n this.addStep(entry, { stage: 'state', title: name, ms: Date.now() - start, data: { args, result } });\n return result;\n } catch (e) {\n this.addStep(entry, {\n stage: 'state',\n level: 'error',\n title: `${name} failed: ${(e as Error).message}`,\n ms: Date.now() - start,\n data: { args, error: errorInfo(e) },\n });\n throw e;\n }\n }\n\n /**\n * A transport synthesised the reply to the latest request of `source`. That happens after the answer,\n * outside of the request, so the entry is found by its source.\n */\n spoken(source: string, speech: JournalSpeech): void {\n const now = Date.now();\n for (let i = this.entries.length - 1; i >= 0; i--) {\n const entry = this.entries[i];\n if (entry.source !== source) {\n continue;\n }\n if (!entry.done || entry.ttsMs !== undefined || now - entry.ts - (entry.ms || 0) > SPEECH_WINDOW_MS) {\n return;\n }\n entry.ttsMs = speech.ms;\n entry.replyAudioMs = Math.round(speech.audioMs);\n const voice = speech.voice ? ` (${speech.voice})` : '';\n this.addStep(entry, {\n stage: 'tts',\n title: `Speech synthesis: ${speech.provider}${voice}, ${(speech.audioMs / 1000).toFixed(1)} s of audio`,\n ms: speech.ms,\n data: speech,\n });\n this.dirty.add(entry.id);\n this.publish(entry);\n this.scheduleSave();\n return;\n }\n }\n\n private addStep(entry: JournalEntry, input: JournalStepInput): void {\n const steps = this.traces.get(entry.id);\n if (!steps || steps.length > MAX_STEPS) {\n return;\n }\n if (steps.length === MAX_STEPS) {\n steps.push({\n t: Date.now() - entry.ts,\n stage: 'error',\n level: 'warn',\n title: `More than ${MAX_STEPS} steps — the rest is not recorded`,\n });\n return;\n }\n const step: JournalStep = {\n t: Date.now() - entry.ts - (input.ms || 0),\n stage: input.stage,\n title: input.title,\n };\n if (input.ms !== undefined) {\n step.ms = input.ms;\n }\n if (input.level) {\n step.level = input.level;\n }\n if (input.tokens) {\n step.tokens = input.tokens;\n const sum = (entry.tokens ||= { input: 0, output: 0 });\n sum.input += input.tokens.input || 0;\n sum.output += input.tokens.output || 0;\n if (input.tokens.cacheRead) {\n sum.cacheRead = (sum.cacheRead || 0) + input.tokens.cacheRead;\n }\n if (input.tokens.cacheWrite) {\n sum.cacheWrite = (sum.cacheWrite || 0) + input.tokens.cacheWrite;\n }\n }\n if (input.data !== undefined) {\n step.data = snapshot(input.data);\n }\n steps.push(step);\n }\n\n /** Fill in fields of the current request's entry (tier, detail, followUp …). */\n note(fields: Partial<Pick<JournalEntry, 'tier' | 'detail' | 'followUp'>>): void {\n const entry = this.store.getStore();\n if (entry) {\n Object.assign(entry, fields);\n }\n }\n\n /** Record a tool call the model made for the current request. */\n tool(name: string, args: Record<string, unknown>, ms: number, result: unknown, error?: string): void {\n const entry = this.store.getStore();\n if (!entry) {\n return;\n }\n const item: JournalTool = { name, args: args || {}, ms };\n if (error) {\n item.error = error;\n } else {\n let text: string;\n try {\n text = typeof result === 'string' ? result : JSON.stringify(result);\n } catch {\n text = String(result);\n }\n item.result = text.length > RESULT_CHARS ? `${text.slice(0, RESULT_CHARS)}…` : text;\n }\n entry.tools.push(item);\n // Live view: show each tool call as it happens, a cloud round can take seconds.\n this.publish(entry);\n }\n\n /** Record which states a call reads or writes (MCP `get_states`/`set_state`/`set_states`, routines). */\n stateAccess(tool: string, args: Record<string, unknown> | undefined): void {\n const entry = this.store.getStore();\n if (!entry || !args) {\n return;\n }\n if (tool === 'get_states' && Array.isArray(args.ids)) {\n for (const id of args.ids) {\n if (typeof id === 'string' && !entry.read.includes(id)) {\n entry.read.push(id);\n }\n }\n } else if (tool === 'get_state' && typeof args.id === 'string') {\n if (!entry.read.includes(args.id)) {\n entry.read.push(args.id);\n }\n } else if (tool === 'set_state' && typeof args.id === 'string') {\n entry.written.push({ id: args.id, value: args.value });\n } else if (tool === 'set_states' && Array.isArray(args.states)) {\n for (const s of args.states as { id?: unknown; value?: unknown }[]) {\n if (typeof s?.id === 'string') {\n entry.written.push({ id: s.id, value: s.value });\n }\n }\n }\n }\n\n /** Write pending changes now (on unload). */\n async flush(): Promise<void> {\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n await this.save();\n }\n\n private publish(entry: JournalEntry): void {\n try {\n this.opts.onChange?.(entry);\n } catch {\n // a listener must never break the answer\n }\n }\n\n private prune(): void {\n const cutoff = Date.now() - this.opts.hours * 3600_000;\n let start = 0;\n while (start < this.entries.length && this.entries[start].ts < cutoff) {\n start++;\n }\n start = Math.max(start, this.entries.length - MAX_ENTRIES);\n if (start > 0) {\n for (const e of this.entries.slice(0, start)) {\n this.traces.delete(e.id);\n this.dirty.delete(e.id);\n }\n this.entries = this.entries.slice(start);\n }\n // Without a file the memory is all there is: keep as many as would be on disk.\n const keep = this.traceDir ? MEMORY_TRACES : MAX_TRACES;\n for (const id of this.traces.keys()) {\n if (this.traces.size <= keep) {\n break;\n }\n // Not written yet, or still being answered: needed until it is on disk.\n if ((!this.traceDir || !this.dirty.has(id)) && this.get(id)?.done !== false) {\n this.traces.delete(id);\n }\n }\n }\n\n private scheduleSave(): void {\n if (!this.opts.file || this.saveTimer) {\n return;\n }\n this.saveTimer = setTimeout(() => {\n this.saveTimer = null;\n void this.save();\n }, SAVE_DELAY_MS);\n this.saveTimer.unref?.();\n }\n\n private async save(): Promise<void> {\n if (!this.opts.file) {\n return;\n }\n try {\n await fs.mkdir(path.dirname(this.opts.file), { recursive: true });\n await fs.writeFile(this.opts.file, JSON.stringify(this.entries.filter(e => e.done)));\n } catch (e) {\n this.opts.log.warn(`Journal could not be saved: ${(e as Error).message}`);\n }\n await this.saveTraces();\n this.prune();\n }\n\n /** Write the traces that changed, and delete the files of requests that are no longer kept. */\n private async saveTraces(): Promise<void> {\n try {\n await fs.mkdir(this.traceDir, { recursive: true });\n for (const id of [...this.dirty]) {\n const steps = this.traces.get(id);\n this.dirty.delete(id);\n if (steps) {\n await fs.writeFile(path.join(this.traceDir, `${id}.json`), JSON.stringify({ id, steps }));\n }\n }\n const keep = new Set(this.entries.slice(-MAX_TRACES).map(e => e.id));\n for (const name of await fs.readdir(this.traceDir)) {\n if (name.endsWith('.json') && !keep.has(name.slice(0, -5))) {\n await fs.rm(path.join(this.traceDir, name), { force: true });\n }\n }\n } catch (e) {\n this.opts.log.warn(`Journal traces could not be saved: ${(e as Error).message}`);\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"captures.js","sourceRoot":"","sources":["../../../src/lib/voice/captures.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;AAwCH,oCAOC;AAMD,0CAOC;AA1DD,+BAAiC;AACjC,+
|
|
1
|
+
{"version":3,"file":"captures.js","sourceRoot":"","sources":["../../../src/lib/voice/captures.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;AAwCH,oCAOC;AAMD,0CAOC;AA1DD,+BAAiC;AACjC,+BAAwD;A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CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QAClF,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;YACtE,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC,KAAK,IAAI,CAAC,EAAE,CAAC;gBAC5E,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,mBAAW,IAAI,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;YAC7E,CAAC;QACL,CAAC;IACL,CAAC;CACJ;AA7CD,oCA6CC","sourcesContent":["/**\n * Diagnosis recordings: microphone audio that a satellite captured but that never became a request — dropped as\n * silence, or returned empty by the speech recognition. Without the audio there is no telling whether a false\n * wake heard the TV, a quiet microphone missed a voice, or the recognition failed on real speech.\n *\n * Each recording is a WAV plus a JSON with what the voice activity detection made of it and a level profile (RMS\n * per 100 ms), so the levels can be read without an audio editor. Only the newest {@link MAX_CAPTURES} are kept.\n * The store does not care where files go; the adapter hands it its file storage (Admin → Files).\n */\n\nimport { pcmToWav } from './stt';\nimport { rms, type Bytes, type VadReport } from './vad';\n\n/** Why a recording was dropped. */\nexport type DiscardReason =\n /** nobody started speaking before the start timeout */\n | 'no-speech'\n /** sound, but never loud enough for the speech threshold */\n | 'silence'\n /** speech by level, but the recognition returned no text */\n | 'empty-stt';\n\nexport interface DiscardedCapture {\n device: string;\n room: string;\n /** Wake word that opened the mic; '' = re-opened for a follow-up. */\n wakeWord: string;\n reason: DiscardReason;\n pcm: Bytes;\n sampleRate: number;\n vad: VadReport;\n}\n\n/** File operations, relative to the store's root (the adapter's file storage). */\nexport interface CaptureFiles {\n write(path: string, data: Buffer | string): Promise<void>;\n /** File names in `dir`; empty (not an error) when it does not exist yet. */\n list(dir: string): Promise<string[]>;\n remove(path: string): Promise<void>;\n}\n\nexport const CAPTURE_DIR = 'captures';\n/** ~400 KB per 12 s recording at 16 kHz, so at most ~20 MB. */\nexport const MAX_CAPTURES = 50;\n/** Resolution of the level profile in the JSON. */\nexport const LEVEL_STEP_MS = 100;\n\n/** RMS per `stepMs` of mono 16-bit PCM, rounded. */\nexport function levelProfile(pcm: Bytes, sampleRate: number, stepMs = LEVEL_STEP_MS): number[] {\n const step = Math.max(2, Math.round((sampleRate * stepMs) / 1000) * 2);\n const levels: number[] = [];\n for (let offset = 0; offset < pcm.length; offset += step) {\n levels.push(Math.round(rms(pcm.subarray(offset, Math.min(pcm.length, offset + step)))));\n }\n return levels;\n}\n\n/**\n * `2026-11-03_08-33-36-123_<device>_<reason>` in local time: sorts chronologically by name, which is what\n * pruning relies on, and reads well in the Admin file list.\n */\nexport function captureBaseName(date: Date, device: string, reason: DiscardReason): string {\n const pad = (n: number, len = 2): string => String(n).padStart(len, '0');\n const time =\n `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}_` +\n `${pad(date.getHours())}-${pad(date.getMinutes())}-${pad(date.getSeconds())}-${pad(date.getMilliseconds(), 3)}`;\n const name = (device || 'satellite').replace(/[^\\w.-]/g, '_').slice(0, 60);\n return `${time}_${name}_${reason}`;\n}\n\nexport class CaptureStore {\n /** Saves run one after another, so two at once cannot prune each other's files. */\n private queue: Promise<unknown> = Promise.resolve();\n\n constructor(\n private readonly files: CaptureFiles,\n private readonly max = MAX_CAPTURES,\n ) {}\n\n /** Store one recording and drop the oldest beyond the limit. Resolves with the path of the WAV. */\n save(capture: DiscardedCapture, now = new Date()): Promise<string> {\n const run = this.queue.then(() => this.write(capture, now));\n this.queue = run.catch(() => undefined);\n return run;\n }\n\n private async write(capture: DiscardedCapture, now: Date): Promise<string> {\n const base = `${CAPTURE_DIR}/${captureBaseName(now, capture.device, capture.reason)}`;\n const info = {\n time: now.toISOString(),\n device: capture.device,\n room: capture.room,\n wakeWord: capture.wakeWord || '(follow-up)',\n reason: capture.reason,\n seconds: Math.round((capture.pcm.length / 2 / capture.sampleRate) * 100) / 100,\n sampleRate: capture.sampleRate,\n vad: capture.vad,\n levelStepMs: LEVEL_STEP_MS,\n levels: levelProfile(capture.pcm, capture.sampleRate),\n };\n await this.files.write(`${base}.wav`, pcmToWav(Buffer.from(capture.pcm), capture.sampleRate));\n await this.files.write(`${base}.json`, `${JSON.stringify(info, null, 2)}\\n`);\n await this.prune();\n return `${base}.wav`;\n }\n\n private async prune(): Promise<void> {\n const names = (await this.files.list(CAPTURE_DIR)).filter(n => /\\.(wav|json)$/.test(n));\n const bases = [...new Set(names.map(n => n.replace(/\\.(wav|json)$/, '')))].sort();\n for (const base of bases.slice(0, Math.max(0, bases.length - this.max))) {\n for (const name of names.filter(n => n.replace(/\\.(wav|json)$/, '') === base)) {\n await this.files.remove(`${CAPTURE_DIR}/${name}`).catch(() => undefined);\n }\n }\n }\n}\n"]}
|