Skip to content

The agent that grows with you

refactor(stt): collapse duplicate validators/process-error detail/CAF converter, managed-gateway helper, read-block guard

Tekniumbf427a20a1ab
diff --git a/tools/transcription_audio.py b/tools/transcription_audio.py
index 7608ab4c20d..de446f7803d 100644
--- a/tools/transcription_audio.py
+++ b/tools/transcription_audio.py
@@ -23,6 +23,7 @@ from tools.transcription_common import (
SUPPORTED_FORMATS,
_config_number,
_error_result,
+ _process_error_detail,
)
# Log-record parity with the origin module.
@@ -97,7 +98,7 @@ def _transcode_audio_for_stt(file_path: str, work_dir: str) -> tuple[Optional[st
_run_ffmpeg_stt_encode(ffmpeg, file_path, converted_path)
return converted_path, None
except subprocess.CalledProcessError as exc:
- details = exc.stderr.strip() or exc.stdout.strip() or str(exc)
+ details = _process_error_detail(exc)
logger.error("ffmpeg STT transcode failed for %s: %s", file_path, details)
return None, f"failed to transcode audio for the STT API: {details}"
except Exception as exc: # noqa: BLE001 - transcode is best-effort
@@ -105,13 +106,13 @@ def _transcode_audio_for_stt(file_path: str, work_dir: str) -> tuple[Optional[st
return None, f"failed to transcode audio for the STT API: {exc}"
-def _validate_audio_file_size(audio_path: Path) -> Optional[Dict[str, Any]]:
- """Return an error when *audio_path* exceeds the remote upload cap."""
+def _validate_audio_file_size(audio_path: Path, *, enforce_size_limit: bool = True) -> Optional[Dict[str, Any]]:
+ """Return an error when *audio_path* is inaccessible or (if enforced) exceeds the remote upload cap."""
try:
file_size = audio_path.stat().st_size
except OSError as e:
return _error_result(f"Failed to access file: {e}")
- if file_size > MAX_FILE_SIZE:
+ if enforce_size_limit and file_size > MAX_FILE_SIZE:
return _error_result(
f"File too large: {file_size / (1024*1024):.1f}MB (max {MAX_FILE_SIZE / (1024*1024):.0f}MB)"
)
@@ -132,13 +133,7 @@ def _validate_audio_source_file(
return _error_result(f"Audio file not found: {file_path}")
if not audio_path.is_file():
return _error_result(f"Path is not a file: {file_path}")
- if enforce_size_limit:
- return _validate_audio_file_size(audio_path)
- try:
- audio_path.stat()
- except OSError as e:
- return _error_result(f"Failed to access file: {e}")
- return None
+ return _validate_audio_file_size(audio_path, enforce_size_limit=enforce_size_limit)
def _validate_audio_file(
@@ -216,7 +211,7 @@ def _prepare_local_audio(file_path: str, work_dir: str) -> tuple[Optional[str],
logger.error("ffmpeg conversion timed out for %s", file_path)
return None, "Audio conversion for local STT timed out"
except subprocess.CalledProcessError as e:
- details = e.stderr.strip() or e.stdout.strip() or str(e)
+ details = _process_error_detail(e)
logger.error("ffmpeg conversion failed for %s: %s", file_path, details)
return None, f"Failed to convert audio for local STT: {details}"
@@ -227,24 +222,19 @@ def _convert_caf_to_wav(file_path: str) -> Optional[str]:
audio_path = Path(file_path)
wav_path = os.path.join(audio_path.parent, f"{audio_path.stem}.wav")
ffmpeg = _find_ffmpeg_binary()
- if ffmpeg:
- try:
- subprocess.run([ffmpeg, "-y", "-i", file_path, wav_path],
- check=True, capture_output=True, text=True,
- timeout=300, stdin=subprocess.DEVNULL,
- creationflags=windows_hide_flags())
- return wav_path
- except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
- logger.warning("ffmpeg CAF to WAV failed for %s: %s", file_path, e)
afconvert = shutil.which("afconvert")
- if afconvert:
+ candidates = (
+ ("ffmpeg", [ffmpeg, "-y", "-i", file_path, wav_path] if ffmpeg else None),
+ ("afconvert", [afconvert, file_path, wav_path, "-d", "LEI16", "-f", "WAVE"] if afconvert else None),
+ )
+ for label, command in candidates:
+ if not command:
+ continue
try:
- subprocess.run([afconvert, file_path, wav_path, "-d", "LEI16", "-f", "WAVE"],
- check=True, capture_output=True, text=True,
- timeout=300, stdin=subprocess.DEVNULL)
+ _run_quiet(command, timeout=300)
return wav_path
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
- logger.warning("afconvert CAF to WAV failed for %s: %s", file_path, e)
+ logger.warning("%s CAF to WAV failed for %s: %s", label, file_path, e)
return None
diff --git a/tools/transcription_cloud.py b/tools/transcription_cloud.py
index 1c68a3722a2..92ef8d9221c 100644
--- a/tools/transcription_cloud.py
+++ b/tools/transcription_cloud.py
@@ -327,9 +327,7 @@ def _transcribe_xai(
creds = {
"provider": "xai",
"api_key": direct_api_key,
- "base_url": str(
- get_env_value("XAI_BASE_URL") or "https://api.x.ai/v1"
- ).strip().rstrip("/"),
+ "base_url": str(get_env_value("XAI_BASE_URL") or "https://api.x.ai/v1").strip().rstrip("/"),
}
else:
creds = resolve_xai_http_credentials()
@@ -346,15 +344,10 @@ def _transcribe_xai(
# OAuth bearers are pinned to the resolver-validated xAI origin;
# config/env base URL overrides only apply to API-key credentials.
if resolved_creds.get("provider") == "xai-oauth":
- return str(
- resolved_creds.get("base_url") or XAI_STT_BASE_URL
- ).strip().rstrip("/")
- return str(
- xai_config.get("base_url")
- or get_env_value("XAI_STT_BASE_URL")
- or resolved_creds.get("base_url")
- or XAI_STT_BASE_URL
- ).strip().rstrip("/")
+ url = resolved_creds.get("base_url")
+ else:
+ url = xai_config.get("base_url") or get_env_value("XAI_STT_BASE_URL") or resolved_creds.get("base_url")
+ return str(url or XAI_STT_BASE_URL).strip().rstrip("/")
base_url = _resolve_base_url(creds)
# Language: hook override > stt.xai.language > stt.language > env.
@@ -368,10 +361,9 @@ def _transcribe_xai(
data: Dict[str, str] = {}
if language:
data["language"] = language
- if use_format:
- data["format"] = "true"
- if use_diarize:
- data["diarize"] = "true"
+ for flag, enabled in (("format", use_format), ("diarize", use_diarize)):
+ if enabled:
+ data[flag] = "true"
def _post_transcription(bearer: str, endpoint_base_url: str):
return _post_audio_multipart(
@@ -602,18 +594,22 @@ def _resolve_openai_audio_client_config() -> tuple[str, str]:
selected = read_selection("stt")
+ def _managed() -> Optional[tuple[str, str]]:
+ gateway = resolve_managed_tool_gateway("openai-audio")
+ if gateway is None:
+ return None
+ return gateway.nous_user_token, urljoin(f"{gateway.gateway_origin.rstrip('/')}/", "v1")
+
if selected == NOUS_MANAGED_PROVIDER:
- managed_gateway = resolve_managed_tool_gateway("openai-audio")
- if managed_gateway is None:
+ managed = _managed()
+ if managed is None:
raise ValueError(selection_error(
"stt",
NOUS_MANAGED_PROVIDER,
"the Nous Tool Gateway is not available (not entitled or "
"unreachable)",
))
- return managed_gateway.nous_user_token, urljoin(
- f"{managed_gateway.gateway_origin.rstrip('/')}/", "v1"
- )
+ return managed
direct = _direct_openai_credentials(cfg_api_key, cfg_base_url)
if direct is not None:
@@ -627,21 +623,13 @@ def _resolve_openai_audio_client_config() -> tuple[str, str]:
"VOICE_TOOLS_OPENAI_KEY/OPENAI_API_KEY is set",
))
- managed_gateway = resolve_managed_tool_gateway("openai-audio")
- if managed_gateway is None:
+ managed = _managed()
+ if managed is None:
message = "Neither stt.openai.api_key in config nor VOICE_TOOLS_OPENAI_KEY/OPENAI_API_KEY is set"
if managed_nous_tools_enabled():
- message += (
- ". "
- + nous_tool_gateway_unavailable_message(
- "managed OpenAI audio for transcription",
- )
- )
+ message += ". " + nous_tool_gateway_unavailable_message("managed OpenAI audio for transcription")
raise ValueError(message)
-
- return managed_gateway.nous_user_token, urljoin(
- f"{managed_gateway.gateway_origin.rstrip('/')}/", "v1"
- )
+ return managed
def _extract_transcript_text(transcription: Any) -> str:
diff --git a/tools/transcription_command.py b/tools/transcription_command.py
index b4252ca3d61..1233a07aa0d 100644
--- a/tools/transcription_command.py
+++ b/tools/transcription_command.py
@@ -98,12 +98,12 @@ def _resolve_command_stt_provider_config(
def _get_command_stt_timeout(config: Dict[str, Any]) -> float:
- """Return timeout in seconds, falling back when invalid."""
+ """Return timeout in seconds (``timeout`` > ``timeout_seconds``), falling back when invalid or <= 0."""
raw = config.get("timeout", config.get("timeout_seconds", DEFAULT_COMMAND_STT_TIMEOUT_SECONDS))
try:
value = float(raw)
except (TypeError, ValueError):
- return float(DEFAULT_COMMAND_STT_TIMEOUT_SECONDS)
+ value = 0.0
return value if value > 0 else float(DEFAULT_COMMAND_STT_TIMEOUT_SECONDS)
@@ -200,11 +200,11 @@ def _transcribe_command_stt(
except subprocess.TimeoutExpired:
return fail(f"STT command provider '{provider_name}' timed out after {timeout:g}s")
except subprocess.CalledProcessError as exc:
- detail_parts = []
- if exc.stderr:
- detail_parts.append(f"stderr: {exc.stderr.strip()}")
- if exc.stdout:
- detail_parts.append(f"stdout: {exc.stdout.strip()}")
+ detail_parts = [
+ f"{stream}: {text.strip()}"
+ for stream, text in (("stderr", exc.stderr), ("stdout", exc.stdout))
+ if text
+ ]
detail = "; ".join(detail_parts) or "no command output"
return fail(
f"STT command provider '{provider_name}' exited with code "
diff --git a/tools/transcription_common.py b/tools/transcription_common.py
index d27e523d04a..446101e9e00 100644
--- a/tools/transcription_common.py
+++ b/tools/transcription_common.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import logging
import os
+import subprocess # noqa: F401 (type annotation only)
from typing import Any, Dict
# Log-record parity with the origin module.
@@ -66,6 +67,11 @@ def _get_stt_section(stt_config: Dict[str, Any], name: str) -> Dict[str, Any]:
return section if isinstance(section, dict) else {}
+def _process_error_detail(exc: "subprocess.CalledProcessError") -> str:
+ """stderr > stdout > str(exc) for a failed helper binary."""
+ return exc.stderr.strip() or exc.stdout.strip() or str(exc)
+
+
def _log_prompt_unsupported(label: str) -> None:
logger.debug("%s does not support transcription prompts — proceeding without the prompt.", label)
diff --git a/tools/transcription_local.py b/tools/transcription_local.py
index fe0f3af5500..eda2a75312c 100644
--- a/tools/transcription_local.py
+++ b/tools/transcription_local.py
@@ -27,6 +27,7 @@ from tools.transcription_common import (
_error_result,
_log_prompt_unsupported,
_ok_result,
+ _process_error_detail,
)
# Log-record parity with the origin module.
@@ -137,18 +138,12 @@ def _should_force_faster_whisper_cpu() -> bool:
return True
# Under Rosetta platform.machine() reports x86_64; sysctl.proc_translated
# flags translation and hw.optional.arm64 distinguishes Apple Silicon hosts.
- if _sysctl_value("sysctl.proc_translated") == "1":
- return True
- return _sysctl_value("hw.optional.arm64") == "1"
+ return _sysctl_value("sysctl.proc_translated") == "1" or _sysctl_value("hw.optional.arm64") == "1"
def _get_idle_unload_seconds(local_cfg: Dict[str, Any]) -> int:
"""Resolve the idle unload timeout from config; 0 = never (default), negatives clamp to 0."""
- try:
- val = int(local_cfg.get("unload_after_idle_seconds", 0))
- except (TypeError, ValueError):
- return 0
- return max(val, 0)
+ return max(_config_number(local_cfg, "unload_after_idle_seconds", 0, int), 0)
def _load_local_whisper_model(model_name: str, device: str = "auto", compute_type: str = "auto"):
@@ -351,7 +346,7 @@ def _transcribe_local_command(
except KeyError as e:
return _error_result(f"Invalid {LOCAL_STT_COMMAND_ENV} template, missing placeholder: {e}")
except subprocess.CalledProcessError as e:
- details = e.stderr.strip() or e.stdout.strip() or str(e)
+ details = _process_error_detail(e)
logger.error("Local STT command failed for %s: %s", file_path, details)
return _error_result(f"Local STT failed: {details}")
except Exception as e:
diff --git a/tools/transcription_tools.py b/tools/transcription_tools.py
index 03b6e7405e4..ded56eceff2 100644
--- a/tools/transcription_tools.py
+++ b/tools/transcription_tools.py
@@ -522,7 +522,8 @@ def _transcribe_local(
return _error_result("faster-whisper not installed")
try:
- local_cfg = _load_stt_config().get("local") or {}
+ stt_config = _load_stt_config()
+ local_cfg = stt_config.get("local") or {}
# Reset the idle timer BEFORE loading/transcribing so the watcher can't
# count a long in-flight transcription as idle time and unload mid-use.
_touch_transcription_time()
@@ -530,8 +531,6 @@ def _transcribe_local(
if model is None: # defensive: load failed without raising
return _error_result("Local whisper model failed to load")
- stt_config = _load_stt_config()
- local_config = stt_config.get("local") or {}
transcribe_kwargs = build_local_transcribe_kwargs(stt_config)
# pre_transcription hook overrides win over config-resolved values.
if language:
@@ -541,7 +540,7 @@ def _transcribe_local(
try:
segments, info = model.transcribe(file_path, **transcribe_kwargs)
- transcript = _join_confident_segments(segments, local_config)
+ transcript = _join_confident_segments(segments, local_cfg)
except Exception as exc:
# CUDA libs sometimes only fail at dlopen-on-first-use, AFTER the
# model loaded. Evict the poisoned cached model, reload on CPU and
@@ -559,7 +558,7 @@ def _transcribe_local(
_local_model = model
_local_model_name = model_name
segments, info = model.transcribe(file_path, **transcribe_kwargs)
- transcript = _join_confident_segments(segments, local_config)
+ transcript = _join_confident_segments(segments, local_cfg)
logger.info(
"Transcribed %s via local whisper (%s, lang=%s, %.1fs audio)",
@@ -583,6 +582,15 @@ def _transcribe_local(
# ---------------------------------------------------------------------------
+def _read_block_error(file_path: str) -> Optional[Dict[str, Any]]:
+ """Refuse to feed a credential / secret store (auth.json, .env, OAuth tokens, ...)
+ to an STT provider, which would ship its plaintext to a third-party API.
+ Mirrors the image-gen / video-gen read guards."""
+ from agent.file_safety import get_read_block_error
+ blocked = get_read_block_error(file_path)
+ return _error_result(blocked) if blocked else None
+
+
def _transcribe_prepared_audio(
file_path: str,
model: Optional[str] = None,
@@ -594,13 +602,9 @@ def _transcribe_prepared_audio(
label (``"gateway"``, ``"voice_mode"``) forwarded to the ``pre_transcription``
hook for observability only. Returns the standard result envelope.
"""
- # Refuse to feed a credential / secret store (auth.json, .env, OAuth
- # tokens, ...) to an STT provider, which would ship its plaintext to a
- # third-party API. Mirrors the image-gen / video-gen read guards.
- from agent.file_safety import get_read_block_error
- blocked = get_read_block_error(file_path)
+ blocked = _read_block_error(file_path)
if blocked:
- return _error_result(blocked)
+ return blocked
# Validate before provider resolution so invalid files cannot trigger
# provider setup or lazy installation. The remote-upload size cap is
@@ -777,10 +781,9 @@ def transcribe_audio(
"""
# Secret-store refusal runs before ANY validation so the error names the
# real reason rather than a format error.
- from agent.file_safety import get_read_block_error
- blocked = get_read_block_error(file_path)
+ blocked = _read_block_error(file_path)
if blocked:
- return _error_result(blocked)
+ return blocked
# Cap .silk sources before the decoder runs (decoder safety); for all other
# inputs the upload cap is provider-scoped in _transcribe_prepared_audio,