The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): unify tts text packers, drop dead MAX_TEXT_LENGTH alias, compact docstrings
Teknium70d290fa469d
diff --git a/tools/tts_tool.py b/tools/tts_tool.pyindex 023f95e5f5e..5485725b6d2 100644--- a/tools/tts_tool.py+++ b/tools/tts_tool.py@@ -100,10 +100,8 @@ def _sdk_importer(module: str, attr: Optional[str] = None, feature: Optional[str"""Lazy SDK importer: returns ``module`` (or ``module.attr``), raising ImportError when absent.``feature`` names a ``tools.lazy_deps`` feature to best-effort install first (users who- enabled a provider by editing config.yaml never ran the post-setup hook); any failure- there falls through so the raw import still raises a clean ImportError. sounddevice- additionally raises OSError when PortAudio is unavailable.- """+ enabled a provider in config.yaml never ran the post-setup hook); any failure there falls+ through so the raw import still raises cleanly. sounddevice also raises OSError without PortAudio."""def _import():if feature:try:@@ -167,21 +165,13 @@ _DEFAULT_OUTPUT_DIR_AT_IMPORT = DEFAULT_OUTPUT_DIRdef _default_output_dir() -> str:- """The active profile's audio output dir at call time.-- Long-lived multi-profile runtimes switch profiles after import, so a frozen constant- would keep writing into the launch profile's cache. ``DEFAULT_OUTPUT_DIR`` stays a- module attribute for tests/patchers and wins whenever it has been patched.- """+ """The active profile's audio output dir at call time (long-lived runtimes switch profiles+ after import); a monkeypatched ``DEFAULT_OUTPUT_DIR`` wins."""if DEFAULT_OUTPUT_DIR != _DEFAULT_OUTPUT_DIR_AT_IMPORT:return DEFAULT_OUTPUT_DIRreturn _get_default_output_dir()-# Back-compat alias. Prefer ``_resolve_max_text_length()`` for new code.-MAX_TEXT_LENGTH = FALLBACK_MAX_TEXT_LENGTH--def _load_tts_config() -> Dict[str, Any]:"""Return the ``tts`` config section ({} when unavailable)."""try:@@ -196,12 +186,8 @@ def _load_tts_config() -> Dict[str, Any]:def _get_provider(tts_config: Dict[str, Any]) -> str:- """The explicitly configured TTS provider, or the free default.-- Inference credentials do not imply consent to paid speech generation: cloud TTS is- opt-in via ``tts.provider``. The managed selection (``nous``) is serviced by the- OpenAI implementation routed through the managed openai-audio gateway.- """+ """The configured TTS provider, or the free default — inference credentials never imply consent+ to paid speech. ``nous`` is serviced by the OpenAI path via the managed openai-audio gateway."""provider = (tts_config.get("provider") or DEFAULT_PROVIDER).lower().strip()return "openai" if provider == NOUS_MANAGED_PROVIDER else provider@@ -266,11 +252,8 @@ def _run_edge_tts(text: str, file_str: str, tts_config: Dict[str, Any]) -> None:def _select_builtin_engine(provider: str) -> tuple:- """Check a built-in provider's SDK. Returns ``(engine, None)`` or ``(provider, error_json)``.-- Unknown names take the Edge default; when edge-tts is missing, NeuTTS is the local- fallback (``engine`` then differs from ``provider``).- """+ """Check a built-in provider's SDK -> ``(engine, None)`` or ``(provider, error_json)``. Unknown+ names take the Edge default; without edge-tts NeuTTS is the fallback (engine != provider)."""entry = _BUILTIN_DISPATCH.get(provider)if entry is not None:available, missing_error = entry[0], entry[3]@@ -303,12 +286,11 @@ def _synthesize_builtin(engine: str, text: str, file_str: str, tts_config: Dict[def _finalize_voice_delivery(file_str: str, provider: str, command_provider_config: Optional[Dict[str, Any]], want_opus: bool,) -> tuple:- """Decide voice-bubble eligibility and Opus-convert when needed; returns ``(path, voice_compatible)``.+ """Decide voice-bubble eligibility, Opus-converting when needed -> ``(path, voice_compatible)``.- Command and plugin providers are documents by default and opt in via ``voice_compatible``;- native-Opus built-ins are voice-compatible when the platform wants Opus and they wrote- .ogg; MP3/WAV built-ins are converted with ffmpeg only when the platform needs Opus.- """+ Command/plugin providers are documents unless they opt in via ``voice_compatible``; native-Opus+ built-ins qualify when the platform wants Opus and they wrote .ogg; MP3/WAV built-ins are+ ffmpeg-converted only when the platform needs Opus."""if command_provider_config is not None:opted_in = _is_command_tts_voice_compatible(command_provider_config)elif provider not in BUILTIN_TTS_PROVIDERS:@@ -349,13 +331,11 @@ def _session_platform() -> tuple:def _resolve_output_base(output_path: Optional[str], provider: str, command_provider_config: Optional[Dict[str, Any]], want_opus: bool,) -> tuple:- """Pick the output file. Returns ``(Path, None)`` or ``(None, error_json)``.+ """Pick the output file -> ``(Path, None)`` or ``(None, error_json)``.- A caller-supplied path is rejected on ``..`` traversal (bug or prompt-injection; an- absolute path is fine) and on protected credential/system locations. Command providers- get their configured extension. Default: ``<audio cache>/tts_<timestamp>.<ext>`` where- ext is the command format, ``.ogg`` for native-Opus providers on Opus platforms, else ``.mp3``.- """+ A caller path is rejected on ``..`` traversal (bug or prompt-injection; absolute is fine) and+ on protected credential/system locations. Default ``<audio cache>/tts_<timestamp>.<ext>``: the+ command format, ``.ogg`` for native-Opus providers on Opus platforms, else ``.mp3``."""if output_path:from tools.path_security import has_traversal_componentif has_traversal_component(output_path):@@ -397,14 +377,11 @@ def _text_to_speech_single(text: str, file_str: str, *, provider: str, tts_config: Dict[str, Any],command_provider_config: Optional[Dict[str, Any]], want_opus: bool, instructions: Optional[str],) -> str:- """Synthesize one provider-safe text chunk into *file_str* and return one final-encoded file.-- Text arrives already normalized and the output path already validated. Command providers- resolve BEFORE built-in dispatch; built-in names short-circuit so- ``tts.providers.openai.command`` can't shadow OpenAI. Plugin providers fire only for names- that are neither built-in nor command; a None return falls through to built-in dispatch- (unknown -> Edge default).- """+ """Synthesize one normalized, provider-safe chunk into *file_str*; returns the result envelope.++ Command providers resolve BEFORE built-in dispatch, but built-in names short-circuit so+ ``tts.providers.openai.command`` can't shadow OpenAI. Plugins fire only for names that are+ neither; a None return falls through to built-in dispatch (unknown -> Edge default)."""try:if command_provider_config is not None:logger.info("Generating speech with command TTS provider '%s'...", provider)@@ -450,12 +427,10 @@ class _ChunkFailed(Exception):def _synthesize_chunks(chunks: List[str], base_path: Path, generated_artifacts: set, **single_kwargs) -> tuple:- """Synthesize every chunk into ``<base>.chunkNNN<ext>`` (or ``base`` alone) sequentially.+ """Synthesize chunks into ``<base>.chunkNNN<ext>`` (or ``base`` alone) -> ``(encoded_paths, results)``.- Every path touched is added to *generated_artifacts* so the caller can sweep non-final- files. Returns ``(encoded_paths, chunk_results)``; raises :class:`_ChunkFailed` when a- chunk reports failure and ``RuntimeError`` when it returns garbage or no audio.- """+ Every touched path lands in *generated_artifacts* for the caller's sweep. Raises+ :class:`_ChunkFailed` on a reported failure, ``RuntimeError`` on garbage or missing audio."""provider = single_kwargs["provider"]encoded_paths: List[str] = []chunk_results: List[Dict[str, Any]] = []@@ -485,14 +460,11 @@ def text_to_speech_tool(text: str, output_path: Optional[str] = None, speed: Optional[float] = None,instructions: Optional[str] = None, provider: Optional[str] = None,) -> str:- """Convert text to speech audio with long-form chunking; returns the JSON result envelope.-- Text is normalized, split into provider-safe chunks (never silently truncated),- synthesized sequentially (each chunk final-encoded), then packed against the destination- platform's upload limit. Multi-chunk voice output is re-encoded when combined; a failed- combine keeps separate valid files; no over-limit artifact is returned. ``speed`` is a- 0.25-4.0 multiplier; ``instructions`` is voice-design guidance for backends that take it.- """+ """Convert text to speech with long-form chunking; returns the JSON result envelope.++ Text is normalized, split into provider-safe chunks (never silently truncated), synthesized+ sequentially, then packed against the platform's upload limit: a failed combine keeps the+ separate valid files and no over-limit artifact is ever returned."""if not text or not text.strip():return tool_error("Text is required", success=False)diff --git a/tools/tts_tool_delivery.py b/tools/tts_tool_delivery.pyindex 529f5a9cf48..34e3a834861 100644--- a/tools/tts_tool_delivery.py+++ b/tools/tts_tool_delivery.py@@ -71,14 +71,10 @@ def _positive_int(value: Any) -> Optional[int]:def _resolve_max_text_length(provider: Optional[str], tts_config: Optional[Dict[str, Any]] = None) -> int:- """Return the input-character cap for *provider*.-- Order: ``tts.<provider>.max_text_length`` > ElevenLabs model table >- ``PROVIDER_MAX_TEXT_LENGTH`` > command provider's own ``max_text_length``- (else ``DEFAULT_COMMAND_TTS_MAX_TEXT_LENGTH``) > ``FALLBACK_MAX_TEXT_LENGTH``.- Non-positive / non-int overrides fall through so a broken config can't- disable truncation.- """+ """Input-character cap for *provider*: ``tts.<provider>.max_text_length`` > ElevenLabs model+ table > ``PROVIDER_MAX_TEXT_LENGTH`` > command provider's own ``max_text_length`` (else+ ``DEFAULT_COMMAND_TTS_MAX_TEXT_LENGTH``) > ``FALLBACK_MAX_TEXT_LENGTH``. Non-positive /+ non-int overrides fall through so a broken config can't disable truncation."""if not provider:return FALLBACK_MAX_TEXT_LENGTHkey = provider.lower().strip()@@ -159,41 +155,25 @@ def _resolve_audio_delivery_profile(return AudioDeliveryProfile(platform=key, max_file_bytes=max_file_bytes, safety_ratio=float(safety_ratio))-def _pack_under_cap(pieces: List[str], max_chars: int) -> List[str]:- """Greedily join *pieces* with single spaces, starting a new chunk past *max_chars*."""- chunks: List[str] = []- current = ""- for piece in pieces:- candidate = f"{current} {piece}".strip()- if current and len(candidate) > max_chars:- chunks.append(current)- current = piece- else:- current = candidate- if current:- chunks.append(current)- return chunks---def _split_oversized_sentence(sentence: str, max_chars: int) -> List[str]:- """Split one over-limit sentence on word boundaries, then hard boundaries.+def _pack_under_cap(pieces: List[str], max_chars: int, *, slice_oversized: bool = False) -> List[str]:+ """Greedily join *pieces* with single spaces, starting a new chunk past *max_chars*.- An over-long word flushes the running chunk and emits its slices as their- own chunks (the tail slice is not merged with following words).+ With ``slice_oversized`` an over-long piece flushes the running chunk and emits its hard+ slices as their own chunks (the tail slice is not merged with following pieces)."""chunks: List[str] = []current = ""- for word in sentence.split():- if len(word) > max_chars:+ for piece in pieces:+ if slice_oversized and len(piece) > max_chars:if current:chunks.append(current)current = ""- chunks.extend(word[i:i + max_chars] for i in range(0, len(word), max_chars))+ chunks.extend(piece[i:i + max_chars] for i in range(0, len(piece), max_chars))continue- candidate = f"{current} {word}".strip()+ candidate = f"{current} {piece}".strip()if current and len(candidate) > max_chars:chunks.append(current)- current = word+ current = pieceelse:current = candidateif current:@@ -201,6 +181,11 @@ def _split_oversized_sentence(sentence: str, max_chars: int) -> List[str]:return chunks+def _split_oversized_sentence(sentence: str, max_chars: int) -> List[str]:+ """Split one over-limit sentence on word boundaries, then hard boundaries."""+ return _pack_under_cap(sentence.split(), max_chars, slice_oversized=True)++def _split_text_for_tts(text: str, max_chars: int) -> List[str]:"""Split text under a provider cap without dropping normalized content."""if max_chars <= 0:@@ -224,10 +209,7 @@ def _split_text_for_tts(text: str, max_chars: int) -> List[str]:def _pack_audio_files_for_delivery(audio_paths: List[str], profile: AudioDeliveryProfile) -> List[List[str]]:- """Group already-final-encoded chunks under the conservative size target.-- A group never mixes container suffixes (they can't be concat-copied).- """+ """Group final-encoded chunks under the size target; never mixes suffixes (can't concat-copy)."""groups: List[List[str]] = []current: List[str] = []current_size = 0@@ -273,11 +255,8 @@ def _wav_sidecar_path(output_path: str) -> str:def _finalize_wav_output(wav_path: str, output_path: str) -> str:- """Move a WAV-native engine's output (NeuTTS / Piper / KittenTTS) into the requested container.-- ffmpeg-convert when available, otherwise rename the WAV to the expected path so the- tool stays usable (the extension is then misleading but the audio plays).- """+ """Move a WAV-native engine's output into the requested container: ffmpeg-convert when+ available, else rename so the tool stays usable (misleading extension, audio plays)."""if wav_path == output_path:return output_pathffmpeg = shutil.which("ffmpeg")@@ -311,11 +290,9 @@ def _wrap_pcm_as_wav(def _write_wav_bytes_as(wav_bytes: bytes, output_path: str) -> str:"""Write in-memory WAV to *output_path*, ffmpeg-converting to its container.- ``.wav`` is written directly; ``.ogg`` is forced to Opus (ffmpeg's .ogg default is- Vorbis, which voice bubbles reject); anything else is a plain ffmpeg conversion. A- failed conversion raises RuntimeError. Without ffmpeg the raw WAV is written under- the requested name (misleading extension, but the audio still plays).- """+ ``.ogg`` is forced to Opus (ffmpeg's .ogg default is Vorbis, which voice bubbles reject).+ A failed conversion raises RuntimeError; without ffmpeg the raw WAV is written under+ the requested name (misleading extension, but the audio still plays)."""if output_path.lower().endswith(".wav"):with open(output_path, "wb") as f:f.write(wav_bytes)@@ -346,11 +323,7 @@ def _convert_to_opus(mp3_path: str) -> Optional[str]:def _ffmpeg_transcode_to_opus(input_path: str, ogg_path: str) -> Optional[str]:- """Transcode *input_path* to real Ogg/Opus at *ogg_path* via ffmpeg.-- Safe when ``input_path == ogg_path`` (writes to a temp file, then replaces).- Returns the output path on success, None on failure.- """+ """Transcode *input_path* to real Ogg/Opus at *ogg_path* (in-place safe via temp file); None on failure."""if shutil.which("ffmpeg") is None:return None@@ -397,12 +370,8 @@ def _sniff_audio_container(path: str) -> str:def _repair_ogg_container(file_str: str) -> str:- """Ensure a path claiming ``.ogg`` actually contains an Ogg container.-- MP3/WAV/FLAC bytes are transcoded in place to real Ogg/Opus. On failure the file is- renamed to its sniffed real extension so platforms get an honest file instead of a- 0-second voice bubble.- """+ """Ensure a ``.ogg`` path really holds Ogg: transcode in place, else rename to the sniffed+ real extension so platforms get an honest file instead of a 0-second voice bubble."""if not file_str.endswith(".ogg"):return file_strcontainer = _sniff_audio_container(file_str)@@ -429,13 +398,10 @@ def _repair_ogg_container(file_str: str) -> str:# --- Long-form audio combination and delivery packing ---def _concat_audio_files(audio_paths: List[str], output_path: str, *, voice_compatible: bool = False) -> Optional[str]:- """Combine independently encoded chunks with ffmpeg.+ """Combine independently encoded chunks with ffmpeg (never byte-joined).- OGG/Opus is always decoded and re-encoded (even without voice opt-in); matching MP3- chunks keep their encoded frames (``-c:a copy``). Structured containers are never- byte-joined. Returns ``None`` when ffmpeg is missing or fails so callers keep the- individually valid files.- """+ OGG/Opus is always re-encoded (even without voice opt-in); matching MP3 chunks keep their+ frames (``-c:a copy``). None when ffmpeg is missing/fails so callers keep the valid parts."""if not audio_paths:raise ValueError("No audio chunks to combine")if len(audio_paths) == 1:@@ -481,13 +447,11 @@ def _concat_audio_files(audio_paths: List[str], output_path: str, *, voice_compadef _build_audio_delivery_files(audio_paths: List[str], output_path: str, profile: AudioDeliveryProfile, *, voice_compatible: bool = False,) -> Tuple[List[str], bool]:- """Pack final-encoded chunks and enforce the hard upload limit.+ """Pack final-encoded chunks and enforce the hard upload limit; returns ``(final_paths, combined_any)``.- Groups are packed against the conservative target, then every combined artifact is- checked at its real post-encoding size; an over-limit group is split in half and- retried. A failed combine returns the constituent files separately. A single chunk- above the hard limit fails closed. Returns ``(final_paths, combined_any)``.- """+ Groups are packed against the conservative target, then each combined artifact is checked+ at its real size; an over-limit group is split in half and retried. A failed combine+ returns the constituent files separately. A single chunk above the hard limit fails closed."""if not audio_paths:raise ValueError("No final-encoded TTS audio chunks")for path in audio_paths:diff --git a/tools/tts_tool_lifecycle.py b/tools/tts_tool_lifecycle.pyindex d38cb9a17d2..cb2ca73ac7d 100644--- a/tools/tts_tool_lifecycle.py+++ b/tools/tts_tool_lifecycle.py@@ -55,14 +55,11 @@ _LAZY_SDK_FEATURES = {"edge": "tts.edge", "elevenlabs": "tts.elevenlabs", "mistrdef _signal_user_tts_provider(name: str, tts_config: Dict[str, Any], hook: str) -> Optional[str]:- """Forward a lease ``hook`` (``"warm"`` / ``"release"``) to a user-declared provider.-- Command providers run their optional ``warm_command`` / ``release_command`` (same- template/env/timeout rules as ``command``; output discarded) on a background thread so- a toggle never waits on a model server. Plugin providers get :meth:`TTSProvider.warm`- / :meth:`TTSProvider.release`. Best-effort: failures are logged at debug. Returns the- action taken.- """+ """Forward a lease ``hook`` (``"warm"``/``"release"``) to a user-declared provider; returns the action.++ Command providers run their optional ``<hook>_command`` (same template/env/timeout rules as+ ``command``) on a background thread so a toggle never waits on a model server; plugins get+ :meth:`TTSProvider.warm`/``release``. Best-effort: failures are logged at debug."""if not name or name in BUILTIN_TTS_PROVIDERS:return Nonecfg = _get_named_provider_config(tts_config, name)@@ -97,14 +94,11 @@ def _signal_user_tts_provider(name: str, tts_config: Dict[str, Any], hook: str)def warm_tts_provider(tts_config: Optional[Dict[str, Any]] = None, provider: Optional[str] = None) -> Dict[str, Any]:- """Pre-load the configured TTS provider so the next synthesis starts hot.-- Local engines load their voice/model into the same LRU slot synthesis reads (including- first-use download); lazily-installed cloud SDKs are made importable; user-declared- providers get ``warm_command`` / :meth:`TTSProvider.warm`; everything else is- ``action: "noop"``. Never raises — the result dict carries ``warmed`` / ``action`` /- ``error``. Blocking; UI threads should run it in the background.- """+ """Pre-load the configured TTS provider so the next synthesis starts hot (blocking; never raises).++ Local engines fill the same LRU slot synthesis reads (including first-use download); lazily+ installed cloud SDKs are made importable; user-declared providers get their warm hook;+ everything else is ``action: "noop"``. The result carries ``warmed`` / ``action`` / ``error``."""if tts_config is None:tts_config = _origin()._load_tts_config()name = (provider or _origin()._get_provider(tts_config) or "").lower().strip()@@ -153,12 +147,8 @@ def warm_tts_provider(tts_config: Optional[Dict[str, Any]] = None, provider: Optdef release_tts_provider(provider: Optional[str] = None) -> Dict[str, Any]:- """Drop resident local TTS models so their memory is returned.-- With ``provider`` given only that engine's cache is cleared; otherwise every local- cache is, and the configured user-declared provider is signalled (plugin ``release()``- / command ``release_command``). Returns ``{"released": <model instances dropped>}``.- """+ """Drop resident local models -> ``{"released": <count>}``. With ``provider`` only that engine's+ cache is cleared; otherwise every cache is, and the configured user provider is signalled."""name = (provider or "").lower().strip()if not name:tts_config = _origin()._load_tts_config()@@ -175,11 +165,8 @@ def release_tts_provider(provider: Optional[str] = None) -> Dict[str, Any]:def acquire_tts_lease(lease: str, tts_config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:- """Register ``lease`` (e.g. ``"desktop:read-aloud"``) as a live consumer and warm the provider.-- Re-acquiring is idempotent but still re-warms (cheap on a cache hit, and heals a cache- cleared elsewhere).- """+ """Register ``lease`` (e.g. ``"desktop:read-aloud"``) and warm the provider. Re-acquiring is+ idempotent but still re-warms (cheap on a cache hit; heals a cache cleared elsewhere)."""with _tts_lease_lock:_tts_leases.add(lease)holders = len(_tts_leases)@@ -189,11 +176,8 @@ def acquire_tts_lease(lease: str, tts_config: Optional[Dict[str, Any]] = None) -def release_tts_lease(lease: str) -> Dict[str, Any]:- """Drop ``lease``; when it was the last one, unload resident local models.-- Releasing a never-acquired lease is a no-op (still reports the holder count) so- surfaces can call it unconditionally on their "off" path.- """+ """Drop ``lease``; the last one out unloads resident local models. A never-acquired lease is a+ no-op (still reports the holder count) so surfaces can call this unconditionally."""with _tts_lease_lock:_tts_leases.discard(lease)holders = len(_tts_leases)diff --git a/tools/tts_tool_local.py b/tools/tts_tool_local.pyindex a98c2b9acc7..db1de1b4dfc 100644--- a/tools/tts_tool_local.py+++ b/tools/tts_tool_local.py@@ -46,12 +46,8 @@ _LOCAL_TTS_MODEL_CACHES: Dict[str, Dict[str, Any]] = {"piper": _piper_voice_cachdef _tts_cache_get_or_load(cache: Dict[str, Any], key: str, load: Callable[[], Any]) -> Any:- """Get ``key`` from ``cache`` or load it, keeping the cache LRU-bounded.-- A hit refreshes recency (pop + reinsert on the insertion-ordered dict); a miss loads- then evicts LRU entries beyond ``_TTS_MODEL_CACHE_MAX``. Callers holding an evicted- reference keep it alive; only the slot is released.- """+ """Get ``key`` from ``cache`` or load it, LRU-bounded at ``_TTS_MODEL_CACHE_MAX`` (a hit refreshes+ recency via pop + reinsert; eviction only releases the slot, not live references)."""if key in cache:cache[key] = cache.pop(key)return cache[key]@@ -105,12 +101,8 @@ def _get_piper_voices_dir() -> Path:def _resolve_piper_voice_path(voice: str, download_dir: Path) -> str:- """Resolve *voice* (an .onnx path or a voice name) to a concrete .onnx file.-- Names like ``en_US-lessac-medium`` are downloaded into *download_dir* on first use via- ``python -m piper.download_voices``. Raises RuntimeError when the model can't be- located or downloaded.- """+ """Resolve *voice* (an .onnx path or a name like ``en_US-lessac-medium``, downloaded into+ *download_dir* on first use) to a concrete .onnx file; RuntimeError when it can't be."""voice = voice or DEFAULT_PIPER_VOICEcandidate = Path(voice).expanduser()if candidate.suffix.lower() == ".onnx" and candidate.exists():@@ -140,11 +132,8 @@ def _resolve_piper_voice_path(voice: str, download_dir: Path) -> str:def _load_piper_voice_for_config(tts_config: Dict[str, Any]) -> Tuple[Any, Dict[str, Any]]:- """Resolve + load (or fetch from cache) the Piper voice ``tts_config`` selects.-- Shared by synthesis and ``warm_tts_provider`` so a warm-up fills exactly the cache- slot the next synthesis hits. Returns ``(voice, piper_config)``.- """+ """Resolve + load (or fetch from cache) the selected Piper voice -> ``(voice, piper_config)``.+ Shared by synthesis and ``warm_tts_provider`` so a warm-up fills exactly the slot synthesis hits."""PiperVoice = _origin()._import_piper()piper_config = _section(tts_config, "piper")voice_name = piper_config.get("voice") or DEFAULT_PIPER_VOICEdiff --git a/tools/tts_tool_openai.py b/tools/tts_tool_openai.pyindex 6553e2a20f4..8952bffe796 100644--- a/tools/tts_tool_openai.py+++ b/tools/tts_tool_openai.py@@ -52,15 +52,10 @@ def _openai_section(tts_config: Any, key: str) -> Dict[str, Any]:def _resolve_openai_audio_client_config() -> tuple[str, str, bool]:- """Return ``(api_key, base_url, is_managed)`` for the OpenAI audio client.-- ``is_managed`` marks the Nous managed audio gateway (a restricted proxy) so callers can- coerce the request to what it supports. Strict selection semantics on the stored- ``tts`` provider: ``"nous"`` → managed gateway ONLY (unentitled/unreachable is an- error); any other stored provider → direct credentials ONLY (``tts.openai.api_key``- then ``VOICE_TOOLS_OPENAI_KEY``/``OPENAI_API_KEY``), no silent managed fallback;- never-configured tts section → legacy ladder: config key → env key → managed.- """+ """``(api_key, base_url, is_managed)`` for the OpenAI audio client (``is_managed`` = the restricted+ Nous proxy, so callers coerce the request). Strict on the stored ``tts`` selection: ``"nous"``+ → managed ONLY (error if unavailable); any other → direct credentials ONLY (``tts.openai.api_key``+ then ``VOICE_TOOLS_OPENAI_KEY``/``OPENAI_API_KEY``); unset → config key → env key → managed."""origin = _origin()openai_cfg = _openai_section(origin._load_tts_config(), "openai")direct_base = openai_cfg.get("base_url") or DEFAULT_OPENAI_BASE_URL@@ -115,14 +110,10 @@ def _generate_openai_tts(instructions: Optional[str] = None) -> str:"""Generate audio via the OpenAI ``audio.speech.create`` SDK shape.- Explicit kwargs let OpenAI-compatible backends (DeepInfra) pass their own- credentials/model/voice and skip ``_resolve_openai_audio_client_config`` (the- managed-gateway path). When None: ``api_key`` comes from the OpenAI auth chain,- ``base_url`` from ``tts.openai.base_url`` then the auth-chain fallback then the OpenAI- default, model/voice/speed from ``tts.openai`` (speed falling back to global- ``tts.speed``). ``instructions`` is forwarded only when truthy so ``tts-1`` and strict- OpenAI-compatible servers that reject unknown kwargs are unaffected.- """+ Explicit kwargs let OpenAI-compatible backends (DeepInfra) supply credentials/model/voice+ and skip the managed-gateway resolution; otherwise the OpenAI auth chain and ``tts.openai``+ (speed falling back to ``tts.speed``) apply. ``instructions`` is forwarded only when truthy+ so ``tts-1`` and strict OpenAI-compatible servers that reject unknown kwargs are unaffected."""fallback_base: Optional[str] = Noneis_managed = Falseexplicit_base_url = base_url is not None@@ -181,12 +172,8 @@ def _generate_openai_tts(def _generate_deepinfra_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:- """Resolve DeepInfra credentials/model, then delegate to the OpenAI handler.-- DeepInfra's audio endpoint is OpenAI-compatible. Model ids come live from the shared- ``hermes_cli.models`` catalog helpers (no hardcoded ids, so retired models disappear- without a patch).- """+ """Resolve DeepInfra credentials/model (live ``hermes_cli.models`` catalog, no hardcoded ids), then+ delegate to the OpenAI-compatible handler."""api_key = _origin()._resolve_provider_key("DEEPINFRA_API_KEY", "deepinfra")if not api_key:raise ValueError("DEEPINFRA_API_KEY not set. Run `hermes setup` to configure, or set the env var directly.")diff --git a/tools/tts_tool_plugins.py b/tools/tts_tool_plugins.pyindex 46c0d8f7e8b..5e8a690f429 100644--- a/tools/tts_tool_plugins.py+++ b/tools/tts_tool_plugins.py@@ -22,12 +22,9 @@ logger = logging.getLogger("tools.tts_tool")def _lookup_plugin_provider(key: str, *, discover: bool = True, retry: bool = False):- """The registered ``TTSProvider`` named *key*, or None.-- ``discover`` runs plugin discovery first; ``retry`` re-discovers with ``force=True`` on- a miss (long-lived sessions may have discovered plugins before this one was- installed/enabled). Raises on registry/discovery failure — callers decide if fatal.- """+ """The registered ``TTSProvider`` named *key*, or None. ``discover`` runs plugin discovery first;+ ``retry`` re-discovers with ``force=True`` on a miss (a long-lived session may predate the+ plugin's install). Raises on registry/discovery failure — callers decide if fatal."""from agent.tts_registry import get_providerif discover:@@ -44,12 +41,9 @@ def _lookup_plugin_provider(key: str, *, discover: bool = True, retry: bool = Fadef _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".- Invariants enforced here even though the caller checks them too, so a caller refactor- can't silently break them: built-in names never reach the plugin registry; a same-named- ``type: command`` provider wins over a plugin; dispatch fires only for a registered- :class:`TTSProvider` whose name equals the configured value (unknown names -> None).- Plugin exceptions propagate — ``text_to_speech_tool`` converts them to the error envelope.- """+ Invariants re-checked here so a caller refactor can't break them: built-in names never reach+ the registry; a same-named ``type: command`` provider wins; only an exact registered name+ dispatches. Plugin exceptions propagate to ``text_to_speech_tool``'s error envelope."""if not provider:return Nonekey = provider.lower().strip()diff --git a/tools/tts_tool_providers.py b/tools/tts_tool_providers.pyindex 9da7400887c..43c925d3d5b 100644--- a/tools/tts_tool_providers.py+++ b/tools/tts_tool_providers.py@@ -252,11 +252,8 @@ async def _generate_edge_tts(text: str, output_path: str, tts_config: Dict[str,# --- ElevenLabs ---def _elevenlabs_environment_kwargs(el_config: Dict[str, Any]) -> Dict[str, Any]:- """Client kwargs redirecting the SDK to ``tts.elevenlabs.base_url``/``wss_url``.-- Empty when no base_url is set (SDK default environment); ``wss_url`` defaults- to the base_url host with a ``ws(s)://`` scheme.- """+ """SDK client kwargs for ``tts.elevenlabs.base_url``/``wss_url``; empty (SDK default environment)+ without a base_url. ``wss_url`` defaults to the base_url host with a ``ws(s)://`` scheme."""base_url = (el_config.get("base_url") or "").rstrip("/")if not base_url:return {}@@ -298,13 +295,9 @@ _XAI_FIRST_SENTENCE_RE = re.compile(r"^(.{12,120}?[.!?…])\s+(?=\S)", flags=re.def _apply_xai_auto_speech_tags(text: str) -> str:- """Add xAI speech tags for more natural voice-mode replies.-- Local conservative pass first ([pause] between paragraphs and after the first- sentence). If the text carried no explicit speech tags already, the auxiliary- model then rewrites it with the richer xAI tag set; any failure falls back to- the locally tagged text.- """+ """Add xAI speech tags: a conservative local pass ([pause] between paragraphs / after the first+ sentence), then — only when the text carried no explicit tags — an auxiliary-model rewrite+ with the richer xAI tag set, falling back to the locally tagged text on any failure."""clean = text.strip()if not clean:return text@@ -337,11 +330,8 @@ def _apply_xai_auto_speech_tags(text: str) -> str:def _clamped_number(raw: Any, cast, lo, hi):- """Parse an optional numeric knob and clamp into [lo, hi]; ``None``/unparseable -> None.-- An empty string is deliberately passed to the clamp unconverted (the resulting- TypeError is reported by the caller's generic handler as a TTS failure).- """+ """Parse an optional numeric knob and clamp into [lo, hi]; ``None``/unparseable -> None. An empty+ string is deliberately clamped unconverted (its TypeError surfaces as a generic TTS failure)."""if raw is None:return Noneif raw != "":@@ -439,12 +429,8 @@ _MINIMAX_OFFICIAL_HOSTS = {def _resolve_minimax_tts_runtime(tts_config: Dict[str, Any]) -> _MiniMaxTTSRuntime:- """Select MiniMax TTS region, endpoint, and credential atomically.-- An explicit ``tts.minimax.region`` wins. Without one, the legacy global- credential wins when present; a China credential is selected only when it- is the sole configured MiniMax credential.- """+ """Select MiniMax region, endpoint and credential atomically: explicit ``tts.minimax.region`` wins,+ else the legacy global credential; ``cn`` only when it is the sole configured credential."""mm_config = _section(tts_config, "minimax")resolve_key = _origin()._resolve_provider_keycredentials = {@@ -481,12 +467,8 @@ def _raise_minimax_api_error(result: Dict[str, Any]) -> None:def _generate_minimax_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:- """Generate audio via MiniMax.-- Two endpoints, detected from the URL: ``t2a_v2`` (nested payload, JSON reply- with hex-encoded audio) and legacy ``text_to_speech`` (flat payload, raw- ``audio/*`` body).- """+ """Generate audio via MiniMax: ``t2a_v2`` (nested payload, JSON reply with hex audio) or the legacy+ ``text_to_speech`` endpoint (flat payload, raw ``audio/*`` body), detected from the URL."""runtime = _resolve_minimax_tts_runtime(tts_config)mm_config = _section(tts_config, "minimax")model = mm_config.get("model", DEFAULT_MINIMAX_MODEL)@@ -648,11 +630,8 @@ def _rewrite_gemini_tts_audio_tags(text: str, persona_prompt: str = "") -> str:def _compose_gemini_tts_prompt(text: str, gemini_config: Dict[str, Any], persona_prompt: Optional[str] = None) -> str:- """Build the Gemini prompt from persona direction plus the live transcript.-- A ``{transcript}`` / ``{{transcript}}`` placeholder in the persona prompt is- substituted in place; otherwise the transcript is appended under a heading.- """+ """Gemini prompt = persona direction + transcript; a ``{transcript}`` / ``{{transcript}}``+ placeholder is substituted in place, otherwise the transcript is appended under a heading."""transcript = text.strip()if persona_prompt is None:persona_prompt = _read_gemini_persona_prompt(gemini_config)@@ -687,12 +666,8 @@ def _gemini_error_detail(response: Any) -> str:def _generate_gemini_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str:- """Generate audio via Gemini ``generateContent`` with ``responseModalities=["AUDIO"]``.-- The API returns raw 24kHz mono 16-bit PCM as base64; it is wrapped as WAV and- ffmpeg-converted to MP3/Opus when the caller asked for those (no ffmpeg -> the- WAV is written under the requested name, same as NeuTTS).- """+ """Generate audio via Gemini ``generateContent`` (``responseModalities=["AUDIO"]``). The reply is+ base64 24kHz mono 16-bit PCM, wrapped as WAV and ffmpeg-converted to the requested container."""origin = _origin()api_key = (origin._resolve_provider_key("GEMINI_API_KEY", "gemini")diff --git a/tools/tts_tool_speaker.py b/tools/tts_tool_speaker.pyindex 92525a8c2bd..a1cebd7f2f7 100644--- a/tools/tts_tool_speaker.py+++ b/tools/tts_tool_speaker.py@@ -95,13 +95,10 @@ def _drain_chunks(chunk_queue: "queue.Queue[Optional[bytes]]") -> List[bytes]:class _SyncSentencePipeline:"""Overlap per-sentence synthesis with playback for non-streaming providers.- Serial synthesize-then-play added a full synthesis-time of dead air per sentence. One- single-thread synthesis executor (sentences FIFO; providers never see concurrent calls)- feeds one playback worker through a small bounded queue: while sentence n plays, n+1 is- already synthesizing. The bound keeps lookahead/temp files small and gives the caller- backpressure. ``text_to_speech_tool`` / ``play_audio_file`` are resolved late so tests- that monkeypatch them keep working.- """+ One single-thread synthesis executor (FIFO; providers never see concurrent calls) feeds one+ playback worker through a small bounded queue, so sentence n+1 synthesizes while n plays;+ the bound keeps lookahead/temp files small and gives the caller backpressure.+ ``text_to_speech_tool`` / ``play_audio_file`` are resolved late so test patches apply."""def __init__(self, stop_event: threading.Event, *, lookahead: int = 2):self._stop = stop_event@@ -157,13 +154,11 @@ class _SyncSentencePipeline:class _StreamerPlayback:"""Prefetch + FIFO playback for a chunked :class:`StreamingTTSProvider`.- ``speak(text)`` calls ``streamer.stream()`` right away and hands the iterator to a- prefetch thread (at most 3 in flight) that buffers chunks into a bounded per-sentence- queue; the single playback worker plays those queues in order, so sentence N+1 is- already arriving while N plays. Output goes to a PortAudio stream when one could be- opened, otherwise via temp WAV files. A failing PortAudio write is retried on a- reinitialized stream up to ``_MAX_REINIT`` times before falling back to temp files.- """+ ``speak(text)`` starts ``streamer.stream()`` immediately on a prefetch thread (at most 3 in+ flight) buffering into a bounded per-sentence queue; one playback worker drains those in+ order, so sentence N+1 arrives while N plays. Output is a PortAudio stream when one opened,+ else temp WAV files; a failing write is retried on a reinitialized stream up to+ ``_MAX_REINIT`` times before falling back to temp files."""_MAX_REINIT = 3_CHUNK_QUEUE_MAX = 64@@ -332,18 +327,12 @@ def stream_tts_to_speaker(text_queue: queue.Queue, stop_event: threading.Event, tts_done_event: threading.Event,display_callback: Optional[Callable[[str], None]] = None, provider: Optional[str] = None,):- """Consume text deltas from *text_queue*, cut them into sentences, and speak each one- the moment it's ready — the conversational path.-- A registered streaming provider plays chunked PCM for the lowest latency; every other- provider (edge, the default) is spoken per-sentence via the sync ``text_to_speech_tool``- path, so audio still starts on sentence one.-- Protocol: the producer puts ``str`` deltas onto *text_queue*; a ``None`` sentinel- signals end-of-text (flush remaining buffer); *stop_event* aborts early (barge-in);- *tts_done_event* is **set** in the ``finally`` block so callers waiting on it- (continuous voice mode) know playback is finished.- """+ """Consume text deltas from *text_queue*, cut into sentences, speak each the moment it's ready.++ A registered streaming provider plays chunked PCM; every other provider is spoken+ per-sentence via ``text_to_speech_tool``, so audio still starts on sentence one. Protocol:+ ``str`` deltas, a ``None`` sentinel = end-of-text (flush), *stop_event* aborts (barge-in),+ *tts_done_event* is **set** in ``finally`` so continuous voice mode knows playback finished."""tts_done_event.clear()origin = _origin()sync_pipeline: Optional[_SyncSentencePipeline] = None