Skip to content

The agent that grows with you

feat(tts): let PCM-streaming plugin TTS providers join the streaming path

Moninja65ea2324af2c
diff --git a/tests/tools/test_tts_streaming.py b/tests/tools/test_tts_streaming.py
index 5acefdabefd..6ba8a1b63ea 100644
--- a/tests/tools/test_tts_streaming.py
+++ b/tests/tools/test_tts_streaming.py
@@ -48,6 +48,81 @@ 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.py
index 87ee1fe80fc..4407a3bd739 100644
--- a/tools/tts_streaming.py
+++ b/tools/tts_streaming.py
@@ -169,6 +169,70 @@ 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).
+ """
+
+ def __init__(self, provider: Any, tts_config: Dict):
+ super().__init__(tts_config, tts_config.get(str(getattr(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)
+
+ @staticmethod
+ def available() -> bool:
+ return True # a registry entry exists only when its plugin actually loaded
+
+ def 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)
+
+
+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
+
+
def resolve_streaming_provider(
tts_config: Dict, preferred: Optional[str] = None) -> Optional[StreamingTTSProvider]:
"""Return a ready streamer for the *configured* provider, else ``None``.
@@ -176,12 +240,21 @@ def resolve_streaming_provider(
``auto`` returns the first usable in ``_PROVIDER_PRIORITY``. Otherwise the configured TTS
provider (or ``preferred``): ``None`` means "no chunked API" — the dispatcher speaks
per-sentence via the sync path, preserving the user's chosen voice. We never silently swap
- providers just to get streaming."""
+ providers 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."""
pinned = str((tts_config.get("streaming") or {}).get("provider") or "").lower().strip()
if pinned == "auto":
- return next((inst for name in _PROVIDER_PRIORITY
- if (inst := _try_instantiate(name, tts_config))), None)
- return _try_instantiate(pinned or (preferred or _get_provider(tts_config)).lower().strip(), tts_config)
+ 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)
def _capped(chunks: Iterator[bytes], label: str) -> Iterator[bytes]: