The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tts): plugin PCM streamers keep the sync dispatcher's voice and routing
Teknium10f553096734
diff --git a/agent/tts_provider.py b/agent/tts_provider.pyindex 9b49fcaea8f..c38469a3d25 100644--- a/agent/tts_provider.py+++ b/agent/tts_provider.py@@ -28,8 +28,18 @@ class TTSProvider(CatalogProviderBase):Subclasses must implement :attr:`name` (rejected at registration if itcollides with a built-in TTS provider name) and :meth:`synthesize`.++ Opting into the streaming voice path (CLI/TUI speaker, desktop speak-stream,+ gateway streaming audio): set :attr:`streams_pcm` and :attr:`stream_sample_rate`+ and make ``stream(text, format="pcm", ...)`` yield raw int16 little-endian mono+ PCM at that rate. Both are read (with :meth:`is_available`) each time a reply+ resolves its streamer, so they may be properties reflecting live state; a+ missing rate falls back to per-sentence :meth:`synthesize`."""+ streams_pcm: bool = False+ stream_sample_rate: Optional[int] = None+def list_voices(self) -> List[Dict[str, Any]]:"""Voice catalog entries: ``{"id"}`` required; ``display`` / ``language``/ ``gender`` / ``preview_url`` optional. Default: empty."""diff --git a/tests/tools/test_tts_plugin_dispatch.py b/tests/tools/test_tts_plugin_dispatch.pyindex cdd8a316fed..519825f8757 100644--- a/tests/tools/test_tts_plugin_dispatch.py+++ b/tests/tools/test_tts_plugin_dispatch.py@@ -225,3 +225,54 @@ class TestVoiceCompatibleHelper:tts_registry.register_provider(_ExplodingProvider(name="cartesia"))assert tts_tool._plugin_provider_is_voice_compatible("cartesia") is False+++# ── Streaming voice path (tools.tts_streaming) ──────────────────────────────+++class _PCMPlugin(TTSProvider):+ def __init__(self, streams_pcm=True, rate=22050, available=True):+ self.streams_pcm, self.stream_sample_rate, self._available = streams_pcm, rate, available+ self.calls = []++ @property+ def name(self) -> str:+ return "fake-pcm"++ def is_available(self) -> bool:+ return self._available++ def synthesize(self, text, output_path, **kw): # pragma: no cover — streaming must not use it+ raise AssertionError("synthesize() on the streaming path")++ def stream(self, text, **kw):+ self.calls.append(kw)+ yield b"\x01\x02" * 4++[email protected]("streaming", [{}, {"provider": "auto"}, {"provider": "fake-pcm"}])+def test_opted_in_plugin_streams_pcm_in_the_configured_voice(monkeypatch, streaming):+ from tools import tts_streaming+ monkeypatch.setattr(tts_streaming, "_try_instantiate", lambda name, cfg: None) # no built-in creds+ plugin = _PCMPlugin()+ tts_registry.register_provider(plugin)+ cfg = {"provider": "fake-pcm", "voice": "v1", "speed": 1.25, "streaming": streaming}+ streamer = tts_streaming.resolve_streaming_provider(cfg)+ assert streamer.sample_rate == 22050+ assert list(streamer.stream("Hi.")) == [b"\x01\x02" * 4]+ # The voice/model/speed synthesize() gets on the sync path: streaming never swaps the voice.+ assert plugin.calls == [{"format": "pcm", "voice": "v1", "model": None, "speed": 1.25}]++[email protected]("plugin, extra_cfg", [+ (_PCMPlugin(streams_pcm=False), {}),+ (_PCMPlugin(rate=None), {}),+ (_PCMPlugin(rate=0), {}),+ (_PCMPlugin(available=False), {}),+ (_PCMPlugin(), {"providers": {"fake-pcm": {"type": "command", "command": "say {input_path}"}}}),+])+def test_plugin_without_full_opt_in_keeps_per_sentence_synthesis(plugin, extra_cfg):+ from tools import tts_streaming+ tts_registry.register_provider(plugin)+ assert tts_streaming.resolve_streaming_provider({"provider": "fake-pcm", **extra_cfg}) is None+ assert plugin.calls == []diff --git a/tests/tools/test_tts_streaming.py b/tests/tools/test_tts_streaming.pyindex 6ba8a1b63ea..5acefdabefd 100644--- a/tests/tools/test_tts_streaming.py+++ b/tests/tools/test_tts_streaming.py@@ -48,81 +48,6 @@ class TestSentenceChunker:]-# ── Plugin TTS providers on the streaming path ────────────────────────────---class _FakePluginProvider:- """Minimal stand-in for a registered plugin TTSProvider that opted into PCM streaming."""-- def __init__(self, name="fake-piper", rate=22050, streams_pcm=True):- self.name = name- self.streams_pcm = streams_pcm- self._rate = rate- self.calls = []-- @property- def stream_sample_rate(self):- return self._rate-- def stream(self, text, *, voice=None, model=None, format="opus", **extra):- self.calls.append({"text": text, "voice": voice, "model": model, "format": format})- yield b"\x01\x02" * 4-- def synthesize(self, text, output_path, **kwargs): # pragma: no cover — not exercised- raise AssertionError("streaming path must not fall back to synthesize()")---class TestPluginProviderStreaming:- def _patch_lookup(self, monkeypatch, provider):- import hermes_cli.plugins as plugins_mod- import agent.tts_registry as registry_mod- monkeypatch.setattr(plugins_mod, "_ensure_plugins_discovered", lambda *a, **k: None)- monkeypatch.setattr(registry_mod, "get_provider", lambda key: provider if key == provider.name else None)-- def test_plugin_provider_declaring_pcm_is_adapted(self, monkeypatch):- provider = _FakePluginProvider()- self._patch_lookup(monkeypatch, provider)- streamer = ts.resolve_streaming_provider({"provider": "fake-piper", "fake-piper": {"voice": "v1"}})- assert isinstance(streamer, ts._PluginProviderStreamer)- assert streamer.sample_rate == 22050- assert list(streamer.stream("你好。")) == [b"\x01\x02" * 4]- assert provider.calls == [{"text": "你好。", "voice": "v1", "model": None, "format": "pcm"}]--- def test_plugin_without_pcm_optin_is_not_adapted(self, monkeypatch):- provider = _FakePluginProvider(name="fake-sync", streams_pcm=False)- self._patch_lookup(monkeypatch, provider)- assert ts.resolve_streaming_provider({"provider": "fake-sync"}) is None--- def test_plugin_without_usable_rate_is_refused(self, monkeypatch):- provider = _FakePluginProvider(name="fake-norate", rate=0)- self._patch_lookup(monkeypatch, provider)- assert ts.resolve_streaming_provider({"provider": "fake-norate"}) is None--- def test_unusable_pinned_builtin_returns_none(self, monkeypatch):- """A pinned built-in that can't run must return None, never another provider's voice."""- self._patch_lookup(monkeypatch, _FakePluginProvider(name="fake-other"))- monkeypatch.setattr(ts, "_try_instantiate", lambda name, cfg: None)- assert ts.resolve_streaming_provider({"streaming": {"provider": "elevenlabs"}}) is None--- def test_pinned_plugin_name_resolves(self, monkeypatch):- provider = _FakePluginProvider(name="fake-piper")- self._patch_lookup(monkeypatch, provider)- streamer = ts.resolve_streaming_provider({"streaming": {"provider": "fake-piper"}})- assert isinstance(streamer, ts._PluginProviderStreamer)--- def test_auto_falls_back_to_configured_plugin(self, monkeypatch):- provider = _FakePluginProvider(name="fake-piper")- self._patch_lookup(monkeypatch, provider)- monkeypatch.setattr(ts, "_try_instantiate", lambda name, cfg: None)- streamer = ts.resolve_streaming_provider({"provider": "fake-piper", "streaming": {"provider": "auto"}})- assert isinstance(streamer, ts._PluginProviderStreamer)--# ── Interruption latch ───────────────────────────────────────────────────diff --git a/tools/tts_streaming.py b/tools/tts_streaming.pyindex 4407a3bd739..cd72c31ecce 100644--- a/tools/tts_streaming.py+++ b/tools/tts_streaming.py@@ -6,6 +6,7 @@ starts on sentence one. True streamers (``StreamingTTSProvider.stream``) wrap chAPIs; providers with no chunked API (edge, the default) get per-sentence playback viathe sync ``text_to_speech_tool`` path. Adding a streamer is ``@register("name")`` ona subclass; the dispatcher, config gate (``tts.<name>.streaming``) and resolver come free.+Plugin ``TTSProvider``s join by declaring ``streams_pcm`` + ``stream_sample_rate``."""from __future__ import annotations@@ -14,11 +15,12 @@ import loggingimport reimport timefrom abc import ABC, abstractmethod-from typing import Callable, Dict, Iterator, List, Optional+from typing import Any, Callable, Dict, Iterator, List, Optionalfrom agent.think_scrubber import THINK_TAG_NAMESfrom tools.tool_backend_helpers import resolve_openai_audio_api_keyfrom tools.tts_tool import _get_provider, _load_tts_config+from tools.tts_tool_plugins import _plugin_pcm_streaming_provider, _plugin_voice_kwargsfrom tools.tts_tool_providers import DEFAULT_XAI_SAMPLE_RATElogger = logging.getLogger(__name__)@@ -169,68 +171,28 @@ def _try_instantiate(name: str, tts_config: Dict) -> Optional[StreamingTTSProvid_PROVIDER_PRIORITY: List[str] = ["elevenlabs", "gemini", "openai", "xai"]-class _PluginProviderStreamer(StreamingTTSProvider):- """Adapter: a plugin-registered ``TTSProvider``'s PCM ``stream()`` behind this ABC.-- Plugin providers reach the *sync* dispatcher (``tools.tts_tool``) by default. A provider that- declares ``streams_pcm = True`` plus ``stream_sample_rate`` (Hz) is opting into the- speaker/gateway streaming path too, yielding raw int16 mono PCM from ``stream()`` — the- contract this ABC needs. Optional ``stream_channels`` / ``stream_sample_width`` refine the- format; a raw-PCM streamer without a usable sample rate is refused (playing PCM at a guessed- rate garbles speech — better to fall back to per-sentence synthesis).- """+class _PluginPCMStreamer(StreamingTTSProvider):+ """A plugin ``TTSProvider`` that opted into raw PCM (``streams_pcm``; see+ ``tools.tts_tool_plugins._plugin_pcm_streaming_provider``) behind this ABC."""def __init__(self, provider: Any, tts_config: Dict):- super().__init__(tts_config, tts_config.get(str(getattr(provider, "name", ""))) or {})+ super().__init__(tts_config, tts_config.get(provider.name) or {})self._provider = provider- self.sample_rate = int(getattr(provider, "stream_sample_rate"))- self.channels = int(getattr(provider, "stream_channels", 1) or 1)- self.sample_width = int(getattr(provider, "stream_sample_width", 2) or 2)+ self.sample_rate = int(provider.stream_sample_rate)@staticmethoddef available() -> bool:- return True # a registry entry exists only when its plugin actually loaded+ return True # gated at resolve time, per instancedef stream(self, text: str) -> Iterator[bytes]:- section = self.section if isinstance(self.section, dict) else {}- voice = section.get("voice")- model = section.get("model")- label = f"plugin streamer {getattr(self._provider, 'name', '?')}"yield from _capped(- self._provider.stream(- text,- voice=voice if isinstance(voice, str) and voice else None,- model=model if isinstance(model, str) and model else None,- format="pcm"),- label)+ self._provider.stream(text, format="pcm", **_plugin_voice_kwargs(self.tts_config)),+ f"plugin streamer {self._provider.name}")def _plugin_streamer(name: str, tts_config: Dict) -> Optional[StreamingTTSProvider]:- """The plugin ``TTSProvider`` named *name* adapted for streaming, or None (never raises)."""- key = (name or "").lower().strip()- if not key:- return None- try:- from hermes_cli.plugins import _ensure_plugins_discovered- _ensure_plugins_discovered()- from agent.tts_registry import get_provider- provider = get_provider(key)- except Exception as exc: # noqa: BLE001 — plugin machinery is optional- logger.debug("plugin TTS streaming lookup failed for %r: %s", key, exc)- return None- if provider is None or not getattr(provider, "streams_pcm", False):- return None- rate = getattr(provider, "stream_sample_rate", None)- if isinstance(rate, bool) or not isinstance(rate, (int, float)) or rate <= 0:- logger.warning(- "TTS provider %r sets streams_pcm without a positive stream_sample_rate; "- "using per-sentence synthesis instead", key)- return None- try:- return _PluginProviderStreamer(provider, tts_config)- except Exception as exc: # noqa: BLE001- logger.debug("streaming adapter for plugin TTS provider %r failed: %s", key, exc)- return None+ provider = _plugin_pcm_streaming_provider(name, tts_config)+ return _PluginPCMStreamer(provider, tts_config) if provider is not None else Nonedef resolve_streaming_provider(@@ -242,16 +204,13 @@ def resolve_streaming_provider(per-sentence via the sync path, preserving the user's chosen voice. We never silently swapproviders just to get streaming.- A registered *plugin* TTS provider that declares ``streams_pcm`` + ``stream_sample_rate`` is- adapted for this path too (see :func:`_plugin_streamer`), so a local engine plugin streams- chunked PCM exactly like a built-in."""+ A plugin ``TTSProvider`` that opted into raw PCM (``streams_pcm``) streams here too, after the+ built-ins and under the same rules (a pinned name never substitutes another voice)."""pinned = str((tts_config.get("streaming") or {}).get("provider") or "").lower().strip()if pinned == "auto":for name in _PROVIDER_PRIORITY:if (inst := _try_instantiate(name, tts_config)) is not None:return inst- # No built-in chunked provider is usable: fall back to the configured provider's plugin- # streamer (e.g. a local Piper plugin), never a silent voice swap.return _plugin_streamer(_get_provider(tts_config), tts_config)name = pinned or (preferred or _get_provider(tts_config)).lower().strip()return _try_instantiate(name, tts_config) or _plugin_streamer(name, tts_config)diff --git a/tools/tts_tool_plugins.py b/tools/tts_tool_plugins.pyindex 12eeda9be1c..2d2624dbcff 100644--- a/tools/tts_tool_plugins.py+++ b/tools/tts_tool_plugins.py@@ -31,6 +31,52 @@ def _lookup_plugin_provider(key: str, *, discover: bool = True, retry: bool = Fareturn plugin_provider+def _plugin_route_key(provider: str, tts_config: Dict[str, Any]) -> Optional[str]:+ """Normalized *provider* when a plugin may service it, else None: built-in names never reach the+ registry and a same-named ``type: command`` provider wins (config is more local than a plugin)."""+ key = (provider or "").lower().strip()+ if not key or key in BUILTIN_TTS_PROVIDERS:+ return None+ if _is_command_provider_config(_get_named_provider_config(tts_config, key)):+ return None+ return key+++def _plugin_voice_kwargs(tts_config: Dict[str, Any]) -> Dict[str, Any]:+ """``voice`` / ``model`` / ``speed`` for a plugin call (None = provider default). Shared by+ ``synthesize`` and the streaming path so a streamed reply keeps the configured voice."""+ cfg = tts_config if isinstance(tts_config, dict) else {}+ voice, model, speed = cfg.get("voice"), cfg.get("model"), cfg.get("speed")+ return {"voice": voice if isinstance(voice, str) and voice else None,+ "model": model if isinstance(model, str) and model else None,+ "speed": float(speed) if isinstance(speed, (int, float)) else None}+++def _plugin_pcm_streaming_provider(provider: str, tts_config: Dict[str, Any]):+ """The plugin that services *provider* when it opted into raw-PCM streaming, else None.++ Opt-in = ``streams_pcm`` truthy AND a positive ``stream_sample_rate`` AND ``is_available()`` —+ all read at resolve time, so per-profile state (key present, user opted out) belongs there.+ A missing rate is refused loudly: PCM played at a guessed rate garbles speech.+ """+ key = _plugin_route_key(provider, tts_config)+ if key is None:+ return None+ try:+ plugin = _lookup_plugin_provider(key)+ if plugin is None or not plugin.streams_pcm or not plugin.is_available():+ return None+ rate = plugin.stream_sample_rate+ except Exception as exc: # noqa: BLE001 — a broken plugin falls back to per-sentence synthesis+ logger.debug("plugin TTS streaming lookup failed for '%s': %s", key, exc)+ return None+ if isinstance(rate, bool) or not isinstance(rate, (int, float)) or rate <= 0:+ logger.warning("TTS provider '%s' sets streams_pcm without a positive stream_sample_rate; "+ "using per-sentence synthesis instead", key)+ return None+ return plugin++def _dispatch_to_plugin_provider(text: str, output_path: str, provider: str, tts_config: Dict[str, Any]) -> Optional[str]:"""Route to a plugin-registered TTS provider; None means "fall through".@@ -44,10 +90,8 @@ def _dispatch_to_plugin_provider(text: str, output_path: str, provider: str, ttsregistered :class:`TTSProvider` whose ``name`` equals the configured value. Unknown names return None(caller falls through to Edge default). See #17843."""- key = (provider or "").lower().strip()- if not key or key in BUILTIN_TTS_PROVIDERS:- return None- if _is_command_provider_config(_get_named_provider_config(tts_config, key)):+ key = _plugin_route_key(provider, tts_config)+ if key is None:return Nonetry:plugin_provider = _lookup_plugin_provider(key, retry=True)@@ -56,16 +100,11 @@ def _dispatch_to_plugin_provider(text: str, output_path: str, provider: str, ttsreturn Noneif plugin_provider is None:return None- # voice/model/speed/format are optional per TTSProvider.synthesize; providers default on None.- cfg = tts_config if isinstance(tts_config, dict) else {}- voice, model, speed = cfg.get("voice"), cfg.get("model"), cfg.get("speed")- fmt = cfg.get("output_format", DEFAULT_COMMAND_TTS_OUTPUT_FORMAT)+ fmt = (tts_config if isinstance(tts_config, dict) else {}).get(+ "output_format", DEFAULT_COMMAND_TTS_OUTPUT_FORMAT)logger.info("Generating speech with plugin TTS provider '%s'...", key)written = plugin_provider.synthesize(- text, output_path, voice=voice if isinstance(voice, str) and voice else None,- model=model if isinstance(model, str) and model else None,- speed=float(speed) if isinstance(speed, (int, float)) else None,- format=str(fmt).lower() if fmt else "mp3")+ text, output_path, format=str(fmt).lower() if fmt else "mp3", **_plugin_voice_kwargs(tts_config))return written if isinstance(written, str) and written else output_pathdiff --git a/website/docs/developer-guide/streaming-tts.md b/website/docs/developer-guide/streaming-tts.mdindex c18df3ef871..497011631cd 100644--- a/website/docs/developer-guide/streaming-tts.md+++ b/website/docs/developer-guide/streaming-tts.md@@ -64,6 +64,7 @@ tts:| gemini | SSE (`streamGenerateContent?alt=sse`) | yes | `GEMINI_API_KEY` / `GOOGLE_API_KEY` || xai | WebSocket (`wss://api.x.ai/v1/tts`) | yes | `XAI_API_KEY` preferred, else xAI OAuth (the subscription bearer 403s on metered TTS) || edge, piper, kitten, neutts, mistral, minimax, deepinfra, … | — | no (per-sentence sync fallback) | as usual |+| plugin `TTSProvider` with `streams_pcm` | the plugin's `stream(format="pcm")` | yes, at its `stream_sample_rate` | the plugin's own |All credential lookups go through `resolve_provider_secret()`(config > env/.env > credential pool) — never bare env reads. Streamed bodies@@ -83,6 +84,21 @@ The ABC enforces the contract; the registry makes the provider discoverable;the dispatcher (`stream_tts_to_speaker`) and the gateway consumer handle thesentence buffer, stop events, and audio sink for free.+## Plugin providers++A plugin `TTSProvider` (registered with `ctx.register_tts_provider()`) joins this+path without core changes. It sets `streams_pcm = True` and a positive+`stream_sample_rate`, and its `stream(text, format="pcm", voice=, model=, speed=)`+yields int16 mono PCM. `resolve_streaming_provider` adapts it+(`tools.tts_streaming._PluginPCMStreamer`) under the same routing rules as the+sync dispatcher (`tools.tts_tool_plugins`): built-in names never reach the+registry, a same-named `type: command` provider wins, and the plugin gets the+same `tts.voice` / `tts.model` / `tts.speed` as `synthesize()`. A configured+plugin streams first. Under `tts.streaming.provider: auto` it is tried only after+the built-in priority list. `streams_pcm`, `stream_sample_rate` and+`is_available()` are read every time a streamer is resolved. If the rate is+missing or the provider reports unavailable, Hermes keeps per-sentence synthesis.+## Gateway streaming (platform adapters)`gateway/streaming_tts_consumer.py` bridges agent deltas to an adapter'sdiff --git a/website/docs/user-guide/features/tts.md b/website/docs/user-guide/features/tts.mdindex ee27f91ebb5..167989fe8cb 100644--- a/website/docs/user-guide/features/tts.md+++ b/website/docs/user-guide/features/tts.md@@ -405,7 +405,7 @@ For TTS engines that can't be expressed as a single shell command — Python SDK| A single CLI reading text from a file/stdin and writing audio to a file/stdout | **Command provider** (no Python needed) || Two or three CLIs chained with shell pipes | **Command provider** || A Python SDK only — no CLI | **Plugin** |-| Streaming bytes you want to deliver chunked (mid-generation voice bubbles) | **Plugin** (override `stream()`) |+| An engine that emits audio as it synthesizes, and you want spoken replies to start on the first sentence | **Plugin** (set `streams_pcm`, override `stream()`) || A voice-listing API used by `hermes setup` | **Plugin** (override `list_voices()`) || OAuth refresh flow (not a static bearer token) | **Plugin** |@@ -468,7 +468,8 @@ Override these on your provider class for richer integration:- `list_voices()` → list of `{id, display, language, gender, preview_url}` dicts shown in `hermes tools`.- `list_models()` → list of `{id, display, languages, max_text_length}` dicts.- `get_setup_schema()` → return `{name, badge, tag, env_vars: [{key, prompt, url}]}` to power the picker row in `hermes tools` / `hermes setup`. Without this, the plugin still works but its row in the picker is minimal.-- `stream(text, *, voice, model, format, **extra)` → iterator yielding audio bytes for streaming delivery (default raises `NotImplementedError`).+- `stream(text, *, voice, model, format, **extra)` → iterator yielding audio bytes (default raises `NotImplementedError`).+- `streams_pcm = True` + `stream_sample_rate` (Hz) → join the streaming voice path (CLI/TUI voice mode, desktop read-aloud, gateway streaming audio). Hermes then calls `stream(text, format="pcm", voice=..., model=..., speed=...)` with the same `tts.voice` / `tts.model` / `tts.speed` that `synthesize()` gets, and expects raw int16 little-endian mono PCM at that rate. Both attributes and `is_available()` are read each time a reply starts, so they can be properties that reflect live state. Without a positive `stream_sample_rate`, or when `is_available()` is `False`, Hermes keeps synthesizing one sentence at a time.- `voice_compatible` property → set `True` if your output is Opus-compatible and the gateway should deliver it as a voice bubble (default `False` = regular audio attachment).- `warm()` / `release()` → called when a surface toggles speech output on / when the last lease across surfaces is released, while your provider is the configured `tts.provider` — preload or unload a local model server here. Both default to no-ops; exceptions are logged at debug and never fail the toggle.