From 7c79360e9a3433796c20c85d524c5e7398478bfa Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:13:53 -0700 Subject: [PATCH 01/10] refactor(tools): skills_tool readiness/plugin walrus compaction --- tools/skills_tool.py | 27 +++++++++++---------------- tools/skills_tool_plugin.py | 6 ++---- 2 files changed, 13 insertions(+), 20 deletions(-) diff --git a/tools/skills_tool.py b/tools/skills_tool.py index 279454f225..e359190225 100644 --- a/tools/skills_tool.py +++ b/tools/skills_tool.py @@ -330,6 +330,7 @@ def _resolve_plugin_skill(name, file_path, task_id, preprocess): active_memory_provider = None try: from plugins.memory import _get_active_memory_provider, _prune_inactive_memory_provider_skills + active_memory_provider = _get_active_memory_provider() _prune_inactive_memory_provider_skills(active_memory_provider) except Exception as exc: @@ -356,8 +357,7 @@ def _resolve_plugin_skill(name, file_path, task_id, preprocess): return _serve_plugin_skill( plugin_skill_md, namespace, bare, file_path=file_path, preprocess=preprocess, session_id=task_id), None - available = pm.list_plugin_skills(namespace) - if available: # plugin exists but this specific skill is missing + if available := pm.list_plugin_skills(namespace): # plugin exists but this specific skill is missing return _fail( f"Skill '{bare}' not found in plugin '{namespace}'.", available_skills=[f"{namespace}:{s}" for s in available], @@ -493,8 +493,7 @@ def _skill_readiness(frontmatter: Dict[str, Any], skill_name: str) -> Tuple[dict setup_needed = bool(remaining) # Only vars actually set pass through to sandboxed execution (execute_code, terminal). - available_env_names = [e["name"] for e in required_env_vars if e["name"] not in remaining] - if available_env_names: + if available_env_names := [e["name"] for e in required_env_vars if e["name"] not in remaining]: try: from tools.env_passthrough import register_env_passthrough @@ -515,6 +514,7 @@ def _skill_readiness(frontmatter: Dict[str, Any], skill_name: str) -> Tuple[dict except Exception: logger.debug("Could not register credential files for skill %s", skill_name, exc_info=True) + status = SkillReadinessStatus.SETUP_NEEDED if setup_needed else SkillReadinessStatus.AVAILABLE fields = { "required_environment_variables": required_env_vars, "required_commands": [], @@ -523,18 +523,15 @@ def _skill_readiness(frontmatter: Dict[str, Any], skill_name: str) -> Tuple[dict "missing_required_commands": [], "setup_needed": setup_needed, "setup_skipped": capture_result["setup_skipped"], - "readiness_status": ( - SkillReadinessStatus.SETUP_NEEDED if setup_needed else SkillReadinessStatus.AVAILABLE - ).value} + "readiness_status": status.value} extras: dict = {} - setup_help = next((e["help"] for e in required_env_vars if e.get("help")), None) - if setup_help: + if setup_help := next((e["help"] for e in required_env_vars if e.get("help")), None): extras["setup_help"] = setup_help if capture_result["gateway_setup_hint"]: extras["gateway_setup_hint"] = capture_result["gateway_setup_hint"] if setup_needed: missing_items = [f"env ${n}" for n in remaining] + [f"file {p}" for p in missing_cred_files] - setup_note = _build_setup_note(SkillReadinessStatus.SETUP_NEEDED, missing_items, setup_help) + setup_note = _build_setup_note(status, missing_items, setup_help) if _is_remote_env_backend(backend) and setup_note: setup_note = f"{setup_note} {backend.upper()}-backed skills need these requirements available inside the remote environment as well." if setup_note: @@ -667,8 +664,8 @@ def skill_view( # tags/related_skills: metadata.hermes.* (agentskills.io) first, then top-level. metadata = frontmatter.get("metadata") hermes_meta = (metadata.get("hermes", {}) or {}) if isinstance(metadata, dict) else {} - tags = _parse_tags(hermes_meta.get("tags") or frontmatter.get("tags", "")) - related_skills = _parse_tags(hermes_meta.get("related_skills") or frontmatter.get("related_skills", "")) + tags, related_skills = ( + _parse_tags(hermes_meta.get(k) or frontmatter.get(k, "")) for k in ("tags", "related_skills")) linked_files = _skill_linked_files(skill_dir) try: @@ -678,10 +675,8 @@ def skill_view( skill_name = frontmatter.get("name", skill_md.stem if not skill_dir else skill_dir.name) readiness, readiness_extras = _skill_readiness(frontmatter, skill_name) - rendered_content = content - if preprocess: - rendered_content = _preprocess_skill( - content, skill_dir, task_id, "Could not preprocess skill content for %s", skill_name) + rendered_content = content if not preprocess else _preprocess_skill( + content, skill_dir, task_id, "Could not preprocess skill content for %s", skill_name) org_provenance = None if skill_dir: try: diff --git a/tools/skills_tool_plugin.py b/tools/skills_tool_plugin.py index 392997565a..ff7b22cd4f 100644 --- a/tools/skills_tool_plugin.py +++ b/tools/skills_tool_plugin.py @@ -67,8 +67,7 @@ def _available_skill_files(skill_dir: Path) -> Dict[str, List[str]]: def _serve_skill_file( skill_root: Path, file_path: str, label: str, *, hint: str | None = None, - list_available: bool = False, read_error_prefix: bool = False, mark_read: bool = False, -) -> str: + list_available: bool = False, read_error_prefix: bool = False, mark_read: bool = False) -> str: """Serve one linked file from a skill directory as a skill_view JSON result. ``hint`` decorates traversal/containment errors and ``list_available`` adds the @@ -130,8 +129,7 @@ def _preprocess_skill(content: str, skill_dir, session_id, debug_msg: str, *args def _serve_plugin_skill( skill_md: Path, namespace: str, bare: str, file_path: str | None = None, *, - preprocess: bool = True, session_id: str | None = None, -) -> str: + preprocess: bool = True, session_id: str | None = None) -> str: """Read a plugin-provided skill, apply guards, return JSON.""" from hermes_cli.plugins import _get_disabled_plugins, get_plugin_manager from tools import skills_tool as _st From d257aa9335e76bb00e22189b97e538f72e981ce3 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:13:58 -0700 Subject: [PATCH 02/10] refactor(tools): fold trivial spans, async comprehension in xAI streamer --- tools/transcription_tools.py | 4 +--- tools/tts_streaming.py | 5 +---- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/tools/transcription_tools.py b/tools/transcription_tools.py index a93d28bdc1..e0292f505c 100644 --- a/tools/transcription_tools.py +++ b/tools/transcription_tools.py @@ -673,9 +673,7 @@ def transcribe_audio( shutil.rmtree(cleanup_dir, ignore_errors=True) -def transcribe_audio_local_fallback( - file_path: str, model: Optional[str] = None -) -> Dict[str, Any]: +def transcribe_audio_local_fallback(file_path: str, model: Optional[str] = None) -> Dict[str, Any]: """Try an already-installed local STT backend without changing config. Passive inbound-media recovery after the configured provider failed: never diff --git a/tools/tts_streaming.py b/tools/tts_streaming.py index 823e48aec1..a84625048f 100644 --- a/tools/tts_streaming.py +++ b/tools/tts_streaming.py @@ -335,10 +335,7 @@ class XAIStreamer(StreamingTTSProvider): return asyncio.run(self._drain_async(text)) async def _drain_async(self, text: str) -> List[bytes]: - frames: List[bytes] = [] - async for frame in self._async_frames(text): - frames.append(frame) - return frames + return [frame async for frame in self._async_frames(text)] async def _async_frames(self, text: str): import json as _json From c1f117970708076f6d75dec82999bcc579d1409b Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:14:31 -0700 Subject: [PATCH 03/10] refactor(tools): pack tts_tool/speaker signatures (AST-neutral) --- tools/tts_tool.py | 24 ++++++------------------ tools/tts_tool_speaker.py | 7 ++----- 2 files changed, 8 insertions(+), 23 deletions(-) diff --git a/tools/tts_tool.py b/tools/tts_tool.py index 0dd14e086a..6cb7252fca 100644 --- a/tools/tts_tool.py +++ b/tools/tts_tool.py @@ -486,14 +486,8 @@ def _tool_failure(prefix: str, provider: str, exc: BaseException) -> str: 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], + 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. @@ -580,11 +574,8 @@ def _synthesize_chunks(chunks: List[str], base_path: Path, generated_artifacts: def text_to_speech_tool( - text: str, - output_path: Optional[str] = None, - speed: Optional[float] = None, - instructions: Optional[str] = None, - provider: Optional[str] = None, + 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. @@ -628,11 +619,8 @@ def text_to_speech_tool( final_paths: List[str] = [] try: encoded_paths, chunk_results = _synthesize_chunks( - chunks, base_path, generated_artifacts, - provider=provider, - tts_config=tts_config, - command_provider_config=command_provider_config, - want_opus=want_opus, + chunks, base_path, generated_artifacts, provider=provider, tts_config=tts_config, + command_provider_config=command_provider_config, want_opus=want_opus, instructions=instructions, ) voice_compatible = bool(chunk_results) and all(bool(r.get("voice_compatible")) for r in chunk_results) diff --git a/tools/tts_tool_speaker.py b/tools/tts_tool_speaker.py index 7edc25a543..6d7b2fd8c5 100644 --- a/tools/tts_tool_speaker.py +++ b/tools/tts_tool_speaker.py @@ -337,11 +337,8 @@ class _StreamerPlayback: 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, + 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. From 35f68c5b77e764e8501bdec99013ff88e31a80b9 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:16:29 -0700 Subject: [PATCH 04/10] refactor(tools): pack tts re-export import lists, one-line section banners --- tools/tts_tool.py | 128 +++++++++--------------------------- tools/tts_tool_delivery.py | 16 ++--- tools/tts_tool_local.py | 16 ++--- tools/tts_tool_providers.py | 32 +++------ 4 files changed, 47 insertions(+), 145 deletions(-) diff --git a/tools/tts_tool.py b/tools/tts_tool.py index 6cb7252fca..374f9d1c2e 100644 --- a/tools/tts_tool.py +++ b/tools/tts_tool.py @@ -46,111 +46,55 @@ def _resolve_provider_key(env_var: str, provider_id: str) -> str: from tools.managed_tool_gateway import resolve_managed_tool_gateway # noqa: F401 — seam patched by tests from tools.tts_command_provider import ( # noqa: F401 — historical names re-exported - BUILTIN_TTS_PROVIDERS, - COMMAND_TTS_OUTPUT_FORMATS, - DEFAULT_COMMAND_TTS_MAX_TEXT_LENGTH, - DEFAULT_COMMAND_TTS_OUTPUT_FORMAT, - DEFAULT_COMMAND_TTS_TIMEOUT_SECONDS, - _configured_command_tts_output_path, - _generate_command_tts, - _get_command_tts_output_format, - _get_command_tts_timeout, - _get_named_provider_config, - _is_command_provider_config, - _is_command_tts_voice_compatible, - _iter_command_providers, - _resolve_command_provider_config, + BUILTIN_TTS_PROVIDERS, COMMAND_TTS_OUTPUT_FORMATS, DEFAULT_COMMAND_TTS_MAX_TEXT_LENGTH, + DEFAULT_COMMAND_TTS_OUTPUT_FORMAT, DEFAULT_COMMAND_TTS_TIMEOUT_SECONDS, + _configured_command_tts_output_path, _generate_command_tts, _get_command_tts_output_format, + _get_command_tts_timeout, _get_named_provider_config, _is_command_provider_config, + _is_command_tts_voice_compatible, _iter_command_providers, _resolve_command_provider_config, command_env_passthrough as _command_provider_env_passthrough, render_command_template as _render_command_tts_template, - run_command_provider as _run_command_tts, - shell_quote_context as _shell_quote_context, + run_command_provider as _run_command_tts, shell_quote_context as _shell_quote_context, ) from tools.tool_backend_helpers import ( # noqa: F401 — seams patched by tests, resolved via tts_tool_openai._origin() - NOUS_MANAGED_PROVIDER, - managed_nous_tools_enabled, - read_selection, - resolve_openai_audio_api_key, + NOUS_MANAGED_PROVIDER, managed_nous_tools_enabled, read_selection, resolve_openai_audio_api_key, ) from tools.tts_tool_delivery import ( # noqa: F401 — historical names re-exported - FALLBACK_MAX_TEXT_LENGTH, - PROVIDER_MAX_TEXT_LENGTH, - _resolve_max_text_length, - AudioDeliveryProfile, - _build_audio_delivery_files, - _concat_audio_files, - _convert_to_opus, - _pack_audio_files_for_delivery, - _repair_ogg_container, - _resolve_audio_delivery_profile, - _sniff_audio_container, - _split_oversized_sentence, - _split_text_for_tts, - _wrap_pcm_as_wav, + FALLBACK_MAX_TEXT_LENGTH, PROVIDER_MAX_TEXT_LENGTH, _resolve_max_text_length, + AudioDeliveryProfile, _build_audio_delivery_files, _concat_audio_files, _convert_to_opus, + _pack_audio_files_for_delivery, _repair_ogg_container, _resolve_audio_delivery_profile, + _sniff_audio_container, _split_oversized_sentence, _split_text_for_tts, _wrap_pcm_as_wav, ) from tools.tts_tool_providers import ( # noqa: F401 — historical names re-exported - DEFAULT_ELEVENLABS_MODEL_ID, - DEFAULT_ELEVENLABS_VOICE_ID, - DEFAULT_GEMINI_TTS_MODEL, - DEFAULT_GEMINI_TTS_VOICE, - DEFAULT_MINIMAX_BASE_URL, - DEFAULT_MINIMAX_CN_BASE_URL, - TTS_RESPONSE_BODY_LIMIT_BYTES, - _XAI_FIRST_SENTENCE_RE, - _XAI_INLINE_SPEECH_TAGS, - _XAI_WRAPPING_SPEECH_TAGS, - _apply_xai_auto_speech_tags, - _elevenlabs_environment_kwargs, - _generate_edge_tts, - _generate_elevenlabs, - _generate_gemini_tts, - _generate_minimax_tts, - _generate_mistral_tts, - _generate_xai_tts, - _resolve_minimax_tts_runtime, + DEFAULT_ELEVENLABS_MODEL_ID, DEFAULT_ELEVENLABS_VOICE_ID, DEFAULT_GEMINI_TTS_MODEL, + DEFAULT_GEMINI_TTS_VOICE, DEFAULT_MINIMAX_BASE_URL, DEFAULT_MINIMAX_CN_BASE_URL, + TTS_RESPONSE_BODY_LIMIT_BYTES, _XAI_FIRST_SENTENCE_RE, _XAI_INLINE_SPEECH_TAGS, + _XAI_WRAPPING_SPEECH_TAGS, _apply_xai_auto_speech_tags, _elevenlabs_environment_kwargs, + _generate_edge_tts, _generate_elevenlabs, _generate_gemini_tts, _generate_minimax_tts, + _generate_mistral_tts, _generate_xai_tts, _resolve_minimax_tts_runtime, ) from tools.tts_tool_local import ( # noqa: F401 — historical names re-exported - DEFAULT_PIPER_VOICE, - _LOCAL_TTS_MODEL_CACHES, - _TTS_MODEL_CACHE_MAX, - _generate_kittentts, - _generate_neutts, - _generate_piper_tts, - _kittentts_model_cache, - _piper_voice_cache, - _resolve_piper_voice_path, - _tts_cache_get_or_load, + DEFAULT_PIPER_VOICE, _LOCAL_TTS_MODEL_CACHES, _TTS_MODEL_CACHE_MAX, _generate_kittentts, + _generate_neutts, _generate_piper_tts, _kittentts_model_cache, _piper_voice_cache, + _resolve_piper_voice_path, _tts_cache_get_or_load, ) from tools.tts_tool_speaker import stream_tts_to_speaker # noqa: F401 — historical name re-exported from tools.tts_text_normalize import _strip_markdown_for_tts # noqa: F401 — historical name re-exported from tools.tts_tool_plugins import ( # noqa: F401 — historical names re-exported - _dispatch_to_plugin_provider, - _plugin_provider_is_available, + _dispatch_to_plugin_provider, _plugin_provider_is_available, _plugin_provider_is_voice_compatible, ) from tools.tts_tool_openai import ( # noqa: F401 — historical names re-exported - DEFAULT_OPENAI_BASE_URL, - DEFAULT_OPENAI_MODEL, - DEFAULT_OPENAI_VOICE, - MANAGED_OPENAI_TTS_MODELS, - _generate_deepinfra_tts, - _generate_openai_tts, - _has_openai_audio_backend, + DEFAULT_OPENAI_BASE_URL, DEFAULT_OPENAI_MODEL, DEFAULT_OPENAI_VOICE, MANAGED_OPENAI_TTS_MODELS, + _generate_deepinfra_tts, _generate_openai_tts, _has_openai_audio_backend, _resolve_openai_audio_client_config, ) from tools.tts_tool_lifecycle import ( # noqa: F401 — historical names re-exported - _local_tts_warmers, - _reset_tts_leases_for_tests, - acquire_tts_lease, - release_tts_lease, - release_tts_provider, - tts_lease_holders, - warm_tts_provider, + _local_tts_warmers, _reset_tts_leases_for_tests, acquire_tts_lease, release_tts_lease, + release_tts_provider, tts_lease_holders, warm_tts_provider, ) -# --------------------------------------------------------------------------- -# Lazy SDK importers -- providers import only when used (headless boxes lack PortAudio etc.) -# --------------------------------------------------------------------------- +# --- Lazy SDK importers -- providers import only when used (headless boxes lack PortAudio etc.) --- def _sdk_importer(module: str, attr: Optional[str] = None, feature: Optional[str] = None) -> Callable[[], Any]: """Lazy SDK importer: returns ``module`` (or ``module.attr``), raising ImportError when absent. @@ -209,9 +153,7 @@ def _check_piper_available() -> bool: return _package_installed("piper") -# --------------------------------------------------------------------------- -# Defaults / config -# --------------------------------------------------------------------------- +# --- Defaults / config --- DEFAULT_PROVIDER = "edge" @@ -278,9 +220,7 @@ def _has_any_command_tts_provider(tts_config: Optional[Dict[str, Any]] = None) - return any(True for _ in _iter_command_providers(tts_config)) -# --------------------------------------------------------------------------- -# Built-in provider dispatch -# --------------------------------------------------------------------------- +# --- Built-in provider dispatch --- # provider -> (availability predicate or None, "package missing" error, log line, generator # name). Predicates and generator names resolve module globals at call time so tests that # monkeypatch ``tools.tts_tool._import_x`` / ``_check_x`` / ``_generate_x`` apply. @@ -418,9 +358,7 @@ def _finalize_voice_delivery( return file_str, file_str.endswith(".ogg") -# --------------------------------------------------------------------------- -# Main tool function -# --------------------------------------------------------------------------- +# --- Main tool function --- def _apply_call_overrides(tts_config: Dict[str, Any], speed: Optional[float], provider: Optional[str]): """Apply per-call ``speed`` (clamped, on a shallow copy) and resolve the provider name.""" @@ -666,9 +604,7 @@ def text_to_speech_tool( pass -# --------------------------------------------------------------------------- -# check_fn -# --------------------------------------------------------------------------- +# --- check_fn --- def _minimax_requirements() -> bool: try: @@ -716,9 +652,7 @@ def check_tts_requirements() -> bool: return _plugin_provider_is_available(provider) -# --------------------------------------------------------------------------- -# Registry -# --------------------------------------------------------------------------- +# --- Registry --- from tools.registry import registry, tool_error TTS_SCHEMA = { diff --git a/tools/tts_tool_delivery.py b/tools/tts_tool_delivery.py index edbd885577..529f5a9cf4 100644 --- a/tools/tts_tool_delivery.py +++ b/tools/tts_tool_delivery.py @@ -118,9 +118,7 @@ _OPUS_VOICE_ARGS = [ ] -# --------------------------------------------------------------------------- -# Text chunking and delivery profiles -# --------------------------------------------------------------------------- +# --- Text chunking and delivery profiles --- @dataclass(frozen=True) class AudioDeliveryProfile: @@ -248,9 +246,7 @@ def _pack_audio_files_for_delivery(audio_paths: List[str], profile: AudioDeliver return groups -# --------------------------------------------------------------------------- -# ffmpeg encoding helpers -# --------------------------------------------------------------------------- +# --- ffmpeg encoding helpers --- def _ffmpeg_run( ffmpeg: str, args: List[str], *, timeout: int = 30, check: bool = False, capture: bool = True, @@ -382,9 +378,7 @@ def _ffmpeg_transcode_to_opus(input_path: str, ogg_path: str) -> Optional[str]: return None -# --------------------------------------------------------------------------- -# Container sniffing / repair -# --------------------------------------------------------------------------- +# --- Container sniffing / repair --- # Several backends silently ignore the requested opus format (Edge only emits MP3, Piper # writes WAV, xAI writes MP3, some OpenAI-compatible servers ignore response_format="opus"), # which breaks native voice bubbles. Sniff the magic bytes once after synthesis and repair @@ -432,9 +426,7 @@ def _repair_ogg_container(file_str: str) -> str: return file_str -# --------------------------------------------------------------------------- -# Long-form audio combination and delivery packing -# --------------------------------------------------------------------------- +# --- 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. diff --git a/tools/tts_tool_local.py b/tools/tts_tool_local.py index f0c41e1bfa..a98c2b9acc 100644 --- a/tools/tts_tool_local.py +++ b/tools/tts_tool_local.py @@ -31,9 +31,7 @@ def _origin(): return tts_tool -# --------------------------------------------------------------------------- -# Bounded model caches -# --------------------------------------------------------------------------- +# --- Bounded model caches --- # Each cached entry is a whole loaded model (tens of MB); an unbounded dict would pin one # per distinct voice for the process lifetime. Most sessions use one or two voices and a # cold reload is cheap. @@ -74,9 +72,7 @@ def _run_helper(cmd: list, timeout: int) -> subprocess.CompletedProcess: ) -# --------------------------------------------------------------------------- -# NeuTTS (subprocess via tools/neutts_synth.py so the ~500MB model exits after use) -# --------------------------------------------------------------------------- +# --- NeuTTS (subprocess via tools/neutts_synth.py so the ~500MB model exits after use) --- def _generate_neutts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str: neutts_config = tts_config.get("neutts") or {} @@ -98,9 +94,7 @@ def _generate_neutts(text: str, output_path: str, tts_config: Dict[str, Any]) -> return _finalize_wav_output(wav_path, output_path) -# --------------------------------------------------------------------------- -# Piper (local neural VITS, 44 languages) -# --------------------------------------------------------------------------- +# --- Piper (local neural VITS, 44 languages) --- def _get_piper_voices_dir() -> Path: """``/cache/piper-voices/`` so voice downloads follow profile boundaries.""" @@ -211,9 +205,7 @@ def _generate_piper_tts(text: str, output_path: str, tts_config: Dict[str, Any]) return _finalize_wav_output(wav_path, output_path) -# --------------------------------------------------------------------------- -# KittenTTS (local ONNX, 25-80MB models, CPU only) -# --------------------------------------------------------------------------- +# --- KittenTTS (local ONNX, 25-80MB models, CPU only) --- def _load_kittentts_model_for_config(tts_config: Dict[str, Any]) -> Tuple[Any, Dict[str, Any]]: """Load (or fetch from cache) the KittenTTS model; returns ``(model, kittentts_config)``.""" diff --git a/tools/tts_tool_providers.py b/tools/tts_tool_providers.py index bb1f35e6f4..a4eaf775ba 100644 --- a/tools/tts_tool_providers.py +++ b/tools/tts_tool_providers.py @@ -100,9 +100,7 @@ def _section(tts_config: Dict[str, Any], key: str) -> Dict[str, Any]: return section if isinstance(section, dict) else {} -# --------------------------------------------------------------------------- -# Bounded upstream response reading -# --------------------------------------------------------------------------- +# --- Bounded upstream response reading --- def _response_has_explicit_stream(response: Any) -> bool: """True for real ``requests`` responses (or doubles defining ``iter_content`` themselves).""" @@ -182,9 +180,7 @@ def _post_json(url: str, payload: Dict[str, Any], headers: Dict[str, str], **ext return requests.post(url, headers=headers, json=payload, timeout=60, stream=True, **extra) -# --------------------------------------------------------------------------- -# Auxiliary-model speech-tag rewrites -# --------------------------------------------------------------------------- +# --- Auxiliary-model speech-tag rewrites --- def _extract_auxiliary_message_content(response: Any) -> str: try: @@ -232,9 +228,7 @@ def _rewrite_with_auxiliary_model( return fallback -# --------------------------------------------------------------------------- -# Edge TTS (free default) -# --------------------------------------------------------------------------- +# --- Edge TTS (free default) --- async def _generate_edge_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str: _edge_tts = _origin()._import_edge_tts() @@ -247,9 +241,7 @@ async def _generate_edge_tts(text: str, output_path: str, tts_config: Dict[str, return output_path -# --------------------------------------------------------------------------- -# ElevenLabs -# --------------------------------------------------------------------------- +# --- 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``. @@ -285,9 +277,7 @@ def _generate_elevenlabs(text: str, output_path: str, tts_config: Dict[str, Any] return output_path -# --------------------------------------------------------------------------- -# xAI TTS (dedicated /v1/tts endpoint, not the OpenAI audio shape) -# --------------------------------------------------------------------------- +# --- xAI TTS (dedicated /v1/tts endpoint, not the OpenAI audio shape) --- _XAI_INLINE_SPEECH_TAGS = ( "pause", "long-pause", "hum-tune", "laugh", "chuckle", "giggle", "cry", "tsk", "tongue-click", "lip-smack", "breath", "inhale", "exhale", "sigh", @@ -425,9 +415,7 @@ def _generate_xai_tts(text: str, output_path: str, tts_config: Dict[str, Any]) - return output_path -# --------------------------------------------------------------------------- -# MiniMax TTS -# --------------------------------------------------------------------------- +# --- MiniMax TTS --- @dataclass(frozen=True) class _MiniMaxTTSRuntime: @@ -564,9 +552,7 @@ def _generate_minimax_tts(text: str, output_path: str, tts_config: Dict[str, Any raise RuntimeError("MiniMax TTS returned no audio data") -# --------------------------------------------------------------------------- -# Mistral (Voxtral TTS) — base64 audio, native Opus for voice bubbles -# --------------------------------------------------------------------------- +# --- Mistral (Voxtral TTS) — base64 audio, native Opus for voice bubbles --- def _generate_mistral_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str: origin = _origin() @@ -596,9 +582,7 @@ def _generate_mistral_tts(text: str, output_path: str, tts_config: Dict[str, Any return _write_bytes(output_path, audio_bytes) -# --------------------------------------------------------------------------- -# Google Gemini TTS -# --------------------------------------------------------------------------- +# --- Google Gemini TTS --- def _read_gemini_persona_prompt(gemini_config: Dict[str, Any]) -> str: """Read ``tts.gemini.persona_prompt_file`` (relative -> under HERMES_HOME), failing soft.""" From af4416a8288e4222929e07658b05bb52072bd5e9 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:19:53 -0700 Subject: [PATCH 05/10] refactor(tools): reuse int16 aligner in speaker stream path; shared _require_key for tts providers --- tools/tts_tool_providers.py | 24 ++++++++++++------------ tools/tts_tool_speaker.py | 34 +++++++++++++--------------------- 2 files changed, 25 insertions(+), 33 deletions(-) diff --git a/tools/tts_tool_providers.py b/tools/tts_tool_providers.py index a4eaf775ba..9da7400887 100644 --- a/tools/tts_tool_providers.py +++ b/tools/tts_tool_providers.py @@ -100,6 +100,14 @@ def _section(tts_config: Dict[str, Any], key: str) -> Dict[str, Any]: return section if isinstance(section, dict) else {} +def _require_key(env_var: str, provider_id: str, hint: str) -> str: + """Resolve *env_var* via the origin key resolver; ValueError ``" not set. "`` when absent.""" + api_key = _origin()._resolve_provider_key(env_var, provider_id) or "" + if not api_key: + raise ValueError(f"{env_var} not set. {hint}") + return api_key + + # --- Bounded upstream response reading --- def _response_has_explicit_stream(response: Any) -> bool: @@ -258,13 +266,9 @@ def _elevenlabs_environment_kwargs(el_config: Dict[str, Any]) -> Dict[str, Any]: def _generate_elevenlabs(text: str, output_path: str, tts_config: Dict[str, Any]) -> str: - origin = _origin() - api_key = origin._resolve_provider_key("ELEVENLABS_API_KEY", "elevenlabs") or "" - if not api_key: - raise ValueError("ELEVENLABS_API_KEY not set. Get one at https://elevenlabs.io/") - + api_key = _require_key("ELEVENLABS_API_KEY", "elevenlabs", "Get one at https://elevenlabs.io/") el_config = tts_config.get("elevenlabs") or {} - client = origin._import_elevenlabs()(api_key=api_key, **_elevenlabs_environment_kwargs(el_config)) + client = _origin()._import_elevenlabs()(api_key=api_key, **_elevenlabs_environment_kwargs(el_config)) audio_generator = client.text_to_speech.convert( text=text, voice_id=el_config.get("voice_id", DEFAULT_ELEVENLABS_VOICE_ID), @@ -555,16 +559,12 @@ def _generate_minimax_tts(text: str, output_path: str, tts_config: Dict[str, Any # --- Mistral (Voxtral TTS) — base64 audio, native Opus for voice bubbles --- def _generate_mistral_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -> str: - origin = _origin() - api_key = origin._resolve_provider_key("MISTRAL_API_KEY", "mistral") or "" - if not api_key: - raise ValueError("MISTRAL_API_KEY not set. Get one at https://console.mistral.ai/") - + api_key = _require_key("MISTRAL_API_KEY", "mistral", "Get one at https://console.mistral.ai/") mi_config = tts_config.get("mistral") or {} client_kwargs: Dict[str, Any] = {"api_key": api_key} if mi_config.get("base_url"): client_kwargs["server_url"] = mi_config["base_url"] # the Mistral SDK calls it server_url - Mistral = origin._import_mistral_client() + Mistral = _origin()._import_mistral_client() try: with Mistral(**client_kwargs) as client: response = client.audio.speech.complete( diff --git a/tools/tts_tool_speaker.py b/tools/tts_tool_speaker.py index 6d7b2fd8c5..92525a8c2b 100644 --- a/tools/tts_tool_speaker.py +++ b/tools/tts_tool_speaker.py @@ -37,8 +37,8 @@ def _unlink_quietly(path: Optional[str]) -> None: pass -def _align_int16_chunks(chunks: Iterable[bytes], stop_evt: threading.Event) -> Iterator[bytes]: - """Yield int16-aligned byte chunks; a dangling odd byte is padded at the end.""" +def _align_int16_chunks(chunks: Iterable[bytes], stop_evt: threading.Event, *, pad_tail: bool = True) -> Iterator[bytes]: + """Yield int16-aligned byte chunks; a dangling odd byte is padded at the end (or dropped).""" leftover = b"" for chunk in chunks: if stop_evt.is_set(): @@ -48,7 +48,7 @@ def _align_int16_chunks(chunks: Iterable[bytes], stop_evt: threading.Event) -> I if aligned_len >= 2: yield buf[:aligned_len] leftover = buf[aligned_len:] if aligned_len < len(buf) else b"" - if leftover: + if leftover and pad_tail: yield b"\x00" @@ -284,25 +284,17 @@ class _StreamerPlayback: if self._current_stream is None: self._play_sentence_via_tempfile(chunk_queue) return - pcm_leftover = b"" - while True: - chunk = chunk_queue.get() - if chunk is None or self.stop_event.is_set(): - return - buf = pcm_leftover + chunk - aligned_len = len(buf) - (len(buf) % 2) - if aligned_len >= 2: + for aligned in _align_int16_chunks(iter(chunk_queue.get, None), self.stop_event, pad_tail=False): + try: + self._write_pcm(aligned) + except Exception as write_exc: + logger.warning("PortAudio write failed, attempting stream reinit: %s", write_exc) + if not self._recover_stream(): + return try: - self._write_pcm(buf[:aligned_len]) - except Exception as write_exc: - logger.warning("PortAudio write failed, attempting stream reinit: %s", write_exc) - if not self._recover_stream(): - return - try: - self._write_pcm(buf[:aligned_len]) - except Exception: - pass - pcm_leftover = buf[aligned_len:] if aligned_len < len(buf) else b"" + self._write_pcm(aligned) + except Exception: + pass def _playback_worker(self) -> None: """Single consumer: play audio segments from the queue in order.""" From da057c0050d0bb96da55128088a66588a4ba6c30 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:22:40 -0700 Subject: [PATCH 06/10] refactor(tools): skills_guard cache/report paths and skill_usage report rows collapsed; frontmatter name parse simplified --- tools/skill_usage.py | 134 ++++++++++++++--------------------- tools/skillevaluator_scan.py | 4 +- tools/skills_guard.py | 114 +++++++++++------------------ 3 files changed, 95 insertions(+), 157 deletions(-) diff --git a/tools/skill_usage.py b/tools/skill_usage.py index 0c1892643b..3412d9e25e 100644 --- a/tools/skill_usage.py +++ b/tools/skill_usage.py @@ -40,10 +40,9 @@ STATE_STALE = "stale" STATE_ARCHIVED = "archived" _VALID_STATES = {STATE_ACTIVE, STATE_STALE, STATE_ARCHIVED} -# Load-bearing built-ins (by frontmatter ``name``) the curator must NEVER archive or consolidate, regardless -# of ``curator.prune_builtins``, pin state, or LLM judgment — silently archiving one turns its slash command -# into "Unknown command". Keep tiny; it is not a substitute for ``curator.prune_builtins: false``. -# (``plan`` used to live here; it is now a first-class command with no skill on disk.) +# Load-bearing built-ins (by frontmatter ``name``) the curator must NEVER archive/consolidate regardless of +# ``curator.prune_builtins``, pins or LLM judgment — archiving one turns its slash command into "Unknown +# command". Keep tiny; not a substitute for ``prune_builtins: false``. (``plan`` moved to a built-in command.) PROTECTED_BUILTIN_SKILLS: Set[str] = set() @@ -174,8 +173,7 @@ def _read_hub_installed_names() -> Set[str]: return set() names = {str(k) for k in installed} skills_dir = _skills_dir() - for entry in installed.values(): - install_path = entry.get("install_path") if isinstance(entry, dict) else None + for install_path in (e.get("install_path") for e in installed.values() if isinstance(e, dict)): if not isinstance(install_path, str) or not install_path.strip(): continue try: @@ -225,9 +223,8 @@ def _toggle_suppressed_name(skill_name: str, *, add: bool) -> None: def _iter_skill_mds(base: Path, *, local_only: bool) -> Iterator[Tuple[str, Path]]: - """``(frontmatter name, SKILL.md)`` for flat and category-nested skills under *base*, skipping metadata/VCS/ - venv/cache dirs. *local_only* also skips external skill dirs mounted below the tree — discovery may see - them, autonomous curation must not.""" + """``(frontmatter name, SKILL.md)`` for flat and nested skills under *base*, skipping metadata/VCS/venv/cache + dirs. *local_only* also skips external skill dirs mounted below the tree (discovery sees them; curation must not).""" for skill_md in base.rglob("SKILL.md"): if not (is_excluded_skill_path(skill_md) or (local_only and is_external_skill_path(skill_md))): yield _read_skill_name(skill_md, fallback=skill_md.parent.name), skill_md @@ -249,11 +246,9 @@ def list_agent_created_skill_names() -> List[str]: """Skills the curator may manage: agent-authored (``created_by: agent`` record) plus, when ``curator.prune_builtins`` is on, bundled built-ins (inactivity anchored on first sight). Never hub skills.""" prune_builtins = _prune_builtins_enabled() # read once, before the walk - - def _keep(name: str, _skill_md: Path, bundled: Set[str], usage: Dict[str, Any]) -> bool: - # Built-ins never carry a curator-managed record, so the record gate applies only to local skills. - return prune_builtins if name in bundled else _is_curator_managed_record(usage.get(name)) - return _scan_local_skills(_keep) + # Built-ins never carry a curator-managed record, so the record gate applies only to local skills. + return _scan_local_skills( + lambda name, _md, bundled, usage: prune_builtins if name in bundled else _is_curator_managed_record(usage.get(name))) def list_archived_skill_names() -> List[str]: @@ -265,20 +260,16 @@ def list_archived_skill_names() -> List[str]: def _read_skill_name(skill_md: Path, fallback: str) -> str: """The frontmatter ``name:`` field of a SKILL.md (first 4000 chars), else *fallback*.""" try: - text = skill_md.read_text(encoding="utf-8", errors="replace")[:4000] + lines = [line.strip() for line in skill_md.read_text(encoding="utf-8", errors="replace")[:4000].split("\n")] except OSError: return fallback - in_frontmatter = False - for stripped in (line.strip() for line in text.split("\n")): - if stripped == "---": - if in_frontmatter: - break - in_frontmatter = True - elif in_frontmatter and stripped.startswith("name:"): - value = stripped.split(":", 1)[1].strip().strip("\"'") - if value: - return value - return fallback + if "---" not in lines: + return fallback + block = lines[lines.index("---") + 1:] # frontmatter runs to the closing --- or (truncated) end of text + if "---" in block: + block = block[:block.index("---")] + values = (line.split(":", 1)[1].strip().strip("\"'") for line in block if line.startswith("name:")) + return next((v for v in values if v), fallback) def is_agent_created(skill_name: str) -> bool: @@ -301,9 +292,8 @@ def _external_read_only_message(skill_name: str) -> str: def is_curation_eligible(skill_name: str, skill_path: Optional[Path] = None) -> bool: - """May the curator track/archive this skill? Agent-created: yes. Bundled: only with - ``curator.prune_builtins``. Hub-installed / external-dir / protected built-ins: never (external owner). - Org-shared skills are eligible for improvement (edits stay local) but protected from ARCHIVE/DELETE elsewhere.""" + """Agent-created: yes. Bundled: only with ``curator.prune_builtins``. Hub / external-dir / protected built-ins: + never (external owner). Org-shared skills are eligible for improvement but protected from ARCHIVE/DELETE elsewhere.""" if ((skill_path is not None and is_external_skill_path(skill_path)) or is_protected_builtin(skill_name) or is_hub_installed(skill_name)): return False @@ -314,9 +304,8 @@ def is_curation_eligible(skill_name: str, skill_path: Optional[Path] = None) -> def _is_curator_managed_record(record: Any) -> bool: - """The on-disk ``created_by`` field reads like provenance but is a curator-management OPT-IN policy flag: - ``"agent"`` means "curator-managed", not proof of authorship (the user can flip it via ``hermes curator - adopt``). The name is kept because it is already in every user's ``.usage.json``.""" + """``created_by`` reads like provenance but is a curator-management OPT-IN flag: ``"agent"`` means "curator-managed", + not proof of authorship (``hermes curator adopt`` flips it). Name kept: it is in every user's ``.usage.json``.""" return isinstance(record, dict) and (record.get("created_by") == "agent" or record.get("agent_created") is True) @@ -326,30 +315,26 @@ def is_curator_managed(skill_name: str) -> bool: def list_unmanaged_skill_names() -> List[str]: - """Curation-ELIGIBLE skills with no provenance marker: records predating ``created_by``, or FOREGROUND - ``skill_manage(action="create")`` results (skills a user asks for belong to the user). Invisible to - ``curated_report()`` and every automatic transition; surfaced by ``hermes curator status`` and handed over - only by explicit ``hermes curator adopt`` — provenance is a declaration, never inferred from activity.""" - def _keep(name: str, skill_md: Path, bundled: Set[str], usage: Dict[str, Any]) -> bool: - return name not in bundled and not _is_curator_managed_record(usage.get(name)) and is_curation_eligible(name, skill_md) - return _scan_local_skills(_keep) + """Curation-ELIGIBLE skills with no provenance marker (records predating ``created_by``, or FOREGROUND + ``skill_manage`` creates — those belong to the user). Invisible to ``curated_report()`` and automatic + transitions; surfaced by ``hermes curator status``, handed over only by explicit ``hermes curator adopt`` — + provenance is a declaration, never inferred from activity.""" + return _scan_local_skills( + lambda name, md, bundled, usage: name not in bundled and not _is_curator_managed_record(usage.get(name)) + and is_curation_eligible(name, md)) def unmanaged_report() -> List[Dict[str, Any]]: - """Rows for :func:`list_unmanaged_skill_names`. ``has_provenance_key`` is False when the record has no - ``created_by`` key (pre-dates the mechanism), True when present but unset (foreground create) — explains - WHY a skill is unmanaged; not a signal to adopt on.""" + """Rows for :func:`list_unmanaged_skill_names`. ``has_provenance_key`` False = no ``created_by`` key (pre-dates + the mechanism), True = present but unset (foreground create); explains WHY, not a signal to adopt on.""" usage = load_usage() - return [ - _report_row(name, raw, has_provenance_key=isinstance(raw, dict) and "created_by" in raw, - has_record=isinstance(raw, dict)) - for name, raw in ((n, usage.get(n)) for n in list_unmanaged_skill_names())] + return [_report_row(n, usage.get(n), has_provenance_key="created_by" in usage.get(n, {}), has_record=n in usage) + for n in list_unmanaged_skill_names()] def adopt_skill(skill_name: str) -> Tuple[bool, str]: - """Hand *skill_name* to the curator by user declaration — writes the same ``created_by: agent`` marker the - background review fork writes. The inactivity clock is NOT reset. Refuses hub-installed, external, bundled - and protected built-in skills. Returns (ok, message).""" + """User-declared handover: writes the same ``created_by: agent`` marker the review fork writes; the inactivity + clock is NOT reset. Refuses hub, external, bundled and protected skills. Returns (ok, message).""" if not skill_name: return False, "no skill name given" if is_protected_builtin(skill_name): @@ -428,9 +413,8 @@ def get_record(skill_name: str) -> Dict[str, Any]: def _locked_update( skill_name: str, op: Callable[[Dict[str, Dict[str, Any]]], Tuple[Any, bool]], fail_log: str, guard: Optional[Callable[[], bool]] = None) -> Any: - """Run *op(data) -> (result, dirty)* on the usage map under the file lock; save only when dirty. *guard* - runs before the lock is taken. Returns result, or None when the guard failed, the save did not land, or - anything raised (logged at DEBUG via *fail_log*).""" + """Run *op(data) -> (result, dirty)* under the file lock, saving only when dirty; *guard* runs before locking. + None when the guard failed, the save did not land, or anything raised (DEBUG-logged via *fail_log*).""" try: if guard is not None and not guard(): return None @@ -449,8 +433,8 @@ def seed_record_if_missing(skill_name: str) -> None: if not skill_name or not is_curation_eligible(skill_name): return - def _seed(data): - if missing := not isinstance(data.get(skill_name), dict): + def _seed(data): # load_usage() already dropped non-dict values, so "missing" == key absent + if missing := skill_name not in data: data[skill_name] = _empty_record() return None, missing _locked_update(skill_name, _seed, "skill_usage.seed_record_if_missing(%s) failed: %s") @@ -462,12 +446,9 @@ def _mutate(skill_name: str, mutator, *, require_curation_eligible: bool = False ``require_curation_eligible=True`` so they never write state onto a skill the curator can't manage.""" if not skill_name: return None - - def _apply(data): - rec = data[skill_name] = data[skill_name] if isinstance(data.get(skill_name), dict) else _empty_record() - return mutator(rec), True guard = (lambda: is_curation_eligible(skill_name)) if require_curation_eligible else None - return _locked_update(skill_name, _apply, "skill_usage._mutate(%s) failed: %s", guard) + return _locked_update(skill_name, lambda data: (mutator(data.setdefault(skill_name, _empty_record())), True), + "skill_usage._mutate(%s) failed: %s", guard) def _set_field(skill_name: str, key: str, value: Any) -> bool: @@ -556,8 +537,7 @@ def bump_patch( _bump(rec, "patch_count", "last_patched_at") rec["patch_generation"] = _non_negative_int(rec.get("patch_generation")) + 1 return {"created_by": rec.get("created_by")} - lifecycle_action = "patched" if action == "patch" else "edited" - _mutate_and_emit(skill_name, lifecycle_action, _apply, task_id=task_id, session_id=session_id) + _mutate_and_emit(skill_name, "patched" if action == "patch" else "edited", _apply, task_id=task_id, session_id=session_id) def record_created( @@ -633,9 +613,8 @@ def forget(skill_name: str) -> None: # --- Archive / restore --- def _relocate(src: Path, dest: Path, skill_name: str, action: str, **capture_kwargs: Any) -> Tuple[bool, str]: - """Move *src* to *dest* for *action* ("archive" | "restore") with an audit-ledger entry around it, then - apply the suppression + state side effects. Ledger capture is best-effort and never blocks the move; the - rename falls back to shutil.move across devices. Returns (ok, message).""" + """Move *src* to *dest* for *action* ("archive" | "restore") inside an audit-ledger entry, then apply the + suppression + state side effects. Ledger capture is best-effort; rename falls back to shutil.move across devices.""" try: from tools import skill_ledger as _ledger _ledger_before = _ledger.capture_before(src, **capture_kwargs) @@ -693,10 +672,9 @@ def archive_skill(skill_name: str) -> Tuple[bool, str]: def restore_skill(skill_name: str) -> Tuple[bool, str]: - """Move an archived skill back to the flat top-level layout (category nesting is NOT reconstructed). - - Refuses names that now collide with a hub skill, or a bundled built-in unless ``curator.prune_builtins`` - is on (then restoring is the documented way to lift a prune) — either would shadow the upstream copy.""" + """Move an archived skill back to the flat top-level layout (category nesting is NOT reconstructed). Refuses + names now colliding with a hub skill, or a bundled built-in unless ``curator.prune_builtins`` is on (then + restoring is the documented way to lift a prune) — either would shadow the upstream copy.""" if is_hub_installed(skill_name): return False, f"skill '{skill_name}' is now hub-installed; restore would shadow the upstream version" if is_bundled(skill_name) and not _prune_builtins_enabled(): @@ -704,7 +682,6 @@ def restore_skill(skill_name: str) -> Tuple[bool, str]: archive_root = _archive_dir() if not archive_root.exists(): return False, "no archive directory" - # Exact name first (recursive: older archive paths left nested layouts), then the timestamped-duplicate # fallback. Only "-YYYYMMDDHHMMSS" (14 digits) counts — a bare startswith("-") would let # restoring "git" pull an archived "git-helpers" out and rename it, destroying the sibling's only copy. @@ -748,21 +725,15 @@ def _find_external_skill_dir(skill_name: str) -> Optional[Path]: # --- Reporting — for the curator CLI / slash command --- def curated_report() -> List[Dict[str, Any]]: - """One backfilled row per curator-managed skill with ``provenance`` ('agent'|'bundled'|'hub') and - ``_persisted`` (a real record exists — the curator seeds the inactivity clock for fresh backfills instead of - treating them as ancient). Bundled skills only with ``curator.prune_builtins``; hub skills never.""" + """One backfilled row per curator-managed skill with ``provenance`` ('agent'|'bundled'|'hub') and ``_persisted`` + (real record exists; fresh backfills get their inactivity clock seeded instead of counting as ancient).""" data = load_usage() names = set(list_agent_created_skill_names()) # A pinned-but-unmanaged skill must stay visible or its pin silently vanishes from `curator status`; the # local-dir guard keeps stale records for deleted dirs from rendering as ghost rows (`curator unpin` cleans up). - names.update( - name for name, rec in data.items() - if isinstance(rec, dict) and rec.get("pinned") and is_curation_eligible(name) and _find_skill_dir(name) is not None - ) - rows = [_report_row(name, data.get(name), _persisted=isinstance(data.get(name), dict)) for name in sorted(names)] - for row in rows: - row["provenance"] = provenance(row["name"]) - return rows + names.update(name for name, rec in data.items() + if rec.get("pinned") and is_curation_eligible(name) and _find_skill_dir(name) is not None) + return [_report_row(n, data.get(n), _persisted=n in data, provenance=provenance(n)) for n in sorted(names)] def provenance(skill_name: str) -> str: @@ -778,5 +749,4 @@ def usage_report() -> List[Dict[str, Any]]: return [] data = load_usage() names = sorted({name for name, _skill_md in _iter_skill_mds(base, local_only=False)}) - return [_report_row(n, data.get(n), provenance=provenance(n), _persisted=isinstance(data.get(n), dict)) - for n in names] + return [_report_row(n, data.get(n), provenance=provenance(n), _persisted=n in data) for n in names] diff --git a/tools/skillevaluator_scan.py b/tools/skillevaluator_scan.py index 21d6f82b39..53cbc412ca 100644 --- a/tools/skillevaluator_scan.py +++ b/tools/skillevaluator_scan.py @@ -77,9 +77,7 @@ def tier1_advisory_enabled() -> bool: try: from hermes_cli.config import load_config skills_cfg = load_config().get("skills") or {} - if not isinstance(skills_cfg, dict): - return True - value = skills_cfg.get("tier1_advisory", True) + value = skills_cfg.get("tier1_advisory", True) if isinstance(skills_cfg, dict) else True if isinstance(value, str): return value.strip().lower() not in ("false", "0", "no", "off") return bool(value) diff --git a/tools/skills_guard.py b/tools/skills_guard.py index 6bdc2d3cdf..4f81f8916e 100644 --- a/tools/skills_guard.py +++ b/tools/skills_guard.py @@ -12,6 +12,7 @@ import re import fnmatch import hashlib import json +from contextlib import suppress from dataclasses import asdict, dataclass, field from datetime import datetime, timezone from pathlib import Path @@ -20,21 +21,15 @@ from typing import List, Tuple SCANNER_VERSION = "skills-guard-v2" -TRUSTED_REPOS = { - "openai/skills", - "anthropics/skills", - "huggingface/skills", - # NVIDIA-verified: each entry ships a signed `skill.oms.sig` + governance `skill-card.md`. - "NVIDIA/skills", -} +# NVIDIA-verified skills each ship a signed `skill.oms.sig` + governance `skill-card.md`. +TRUSTED_REPOS = {"openai/skills", "anthropics/skills", "huggingface/skills", "NVIDIA/skills"} INSTALL_POLICY = { # safe caution dangerous "builtin": ("allow", "allow", "allow"), "trusted": ("allow", "allow", "block"), "community": ("allow", "block", "block"), - # "ask" surfaces as an error to the agent, which can retry without the flagged content. Only - # consulted when skills.guard_agent_created is on (skill_manager_tool._guard_agent_created_enabled). + # "ask" = error to the agent (retry without the flagged content); only when skills.guard_agent_created is on. "agent-created": ("allow", "allow", "ask"), } @@ -83,11 +78,10 @@ _OTHER_AGENT_CONFIG_FILES = r'\.(?:claude/settings|codex/config)[\w.]*' def _shell_write_re(file_alt: str) -> str: - """Mechanical shell write into *file_alt*: ``>``/``>>`` redirection, ``sed -i``, ``tee`` (target as - immediate argument, so ``| tee output | AGENTS.md |`` table cells miss), ``cp``/``mv`` with the file in - destination position (a source arg is required, so ``cp AGENTS.md backup/`` — a read — misses; - ``AGENTS.md.bak`` is not the file). A single ``>`` needs a preceding word/quote/paren char so - blockquotes (``> text``) and arrows (``-> file``) miss.""" + """Mechanical shell write into *file_alt*: ``>``/``>>``, ``sed -i``, ``tee`` (target as immediate argument, so + ``| tee output | AGENTS.md |`` cells miss), ``cp``/``mv`` with the file as destination (a source arg is required, + so ``cp AGENTS.md backup/`` misses; ``AGENTS.md.bak`` is not the file). A single ``>`` needs a preceding + word/quote/paren char so blockquotes (``> text``) and arrows (``-> file``) miss.""" return ( rf'(?:>>|[\w"\'`)\]]\s*>)\s*[~\w./-]*{file_alt}(?!\.?\w)' rf'|\bsed\b[^\n]*\s(?:-[A-Za-z]*i[A-Za-z]*|--in-place)\b[^\n]*{file_alt}(?!\.?\w)' @@ -97,10 +91,9 @@ def _shell_write_re(file_alt: str) -> str: def _prose_modify_re(file_alt: str) -> str: - """Prose instructing modification of *file_alt*: an imperative-position verb (line start / bullet), or - a mid-line verb strengthened by a directive marker ("you must", "please", "make sure to"). - Descriptive prose ("skills that edit AGENTS.md") matches neither; the verb→file gap forbids commas so - enumerations ("Write or refactor skills, AGENTS.md, CLAUDE.md") miss.""" + """Prose instructing modification of *file_alt*: an imperative-position verb (line start / bullet), or a mid-line + verb with a directive marker ("you must", "please", "make sure to"). Descriptive prose ("skills that edit + AGENTS.md") misses; the verb→file gap forbids commas so enumerations ("Write skills, AGENTS.md, CLAUDE.md") miss.""" return ( rf'^\s*(?:[-*+]\s+|\d+[.)]\s+)?{MODIFY_VERB_RE}[^\n,]{{0,80}}?{file_alt}\b' rf'|(?:\byou\s+(?:must|should|need\s+to)\s+|\bplease\s+' @@ -397,11 +390,9 @@ def _unicode_char_name(char: str) -> str: def _compute_docstring_lines(lines: list) -> set: - """1-indexed line numbers inside (or on the boundary of) triple-quoted strings. - - ``in_docstring`` toggles on each line with an odd count of a marker; opening, interior, closing and - self-contained single-line docstrings are all included so ``os.environ`` in prose is not scored. - Heuristic (ignores a triple quote inside a string literal) but covers the common false-positive shapes.""" + """1-indexed line numbers inside (or on the boundary of) triple-quoted strings: opening, interior, closing and + self-contained one-line docstrings all count, so ``os.environ`` in prose is not scored. Heuristic (ignores a + triple quote inside a string literal) but covers the common false-positive shapes.""" doc_lines: set = set() in_docstring = False for i, line in enumerate(lines): @@ -413,8 +404,6 @@ def _compute_docstring_lines(lines: list) -> set: return doc_lines -# --- Scanning functions ----------------------------------------------------- - def scan_file(file_path: Path, rel_path: str = "") -> List[Finding]: """Scan one file for threat patterns and invisible unicode. *rel_path* is the display path (defaults to the file name). Regex findings dedupe per pattern per line; invisible chars yield one per line.""" @@ -431,10 +420,9 @@ def scan_file(file_path: Path, rel_path: str = "") -> List[Finding]: for pattern, pid, severity, category, description in _COMPILED_THREAT_PATTERNS: for i, line in enumerate(lines, start=1): if i not in docstring_lines and pattern.search(line): - matched_text = line.strip() - if len(matched_text) > 120: - matched_text = matched_text[:117] + "..." - findings.append(Finding(pid, severity, category, rel_path, i, matched_text, description)) + text = line.strip() + findings.append(Finding(pid, severity, category, rel_path, i, + text if len(text) <= 120 else text[:117] + "...", description)) for i, line in enumerate(lines, start=1): char = next((c for c in INVISIBLE_CHARS if c in line), None) if char is not None: @@ -446,11 +434,9 @@ def scan_file(file_path: Path, rel_path: str = "") -> List[Finding]: def scan_skill(skill_path: Path, source: str = "community") -> ScanResult: - """Structural checks + pattern scan of every text file in a skill dir (or a single file). - - A `.skillignore` / `.clawhubignore` (gitignore-style) excludes dev/docs artifacts from BOTH the - structural checks and the pattern scan; the ignore file itself is always excluded and `SKILL.md` can - never be un-ignored. *source* (e.g. "openai/skills") resolves the trust level.""" + """Structural checks + pattern scan of every text file in a skill dir (or a single file). A `.skillignore` / + `.clawhubignore` (gitignore-style) excludes dev/docs artifacts from BOTH passes; the ignore file itself is + always excluded and `SKILL.md` can never be un-ignored. *source* (e.g. "openai/skills") sets the trust level.""" skill_name = skill_path.name trust_level = _resolve_trust_level(source) all_findings: List[Finding] = [] @@ -472,11 +458,9 @@ def scan_skill(skill_path: Path, source: str = "community") -> ScanResult: def _content_digest(skill_path: Path) -> str: - """Canonical SHA-256 over (POSIX relative path, file bytes), ORDERED by the rel-path string. - - Sorting Paths diverged on Windows (case-insensitive normcase) from ``tools.skills_hub.bundle_content_hash``, - which sorts plain strings — every installed skill then reported ``update_available`` forever. Sorting the - posix strings keeps the digest OS-independent and byte-symmetric with the bundle side.""" + """Canonical SHA-256 over (POSIX relative path, file bytes), ORDERED by the rel-path STRING: sorting Paths is + case-insensitive on Windows and diverged from ``tools.skills_hub.bundle_content_hash`` (plain-string sort), so + every installed skill reported ``update_available`` forever. String order keeps both sides byte-symmetric.""" h = hashlib.sha256() if not skill_path.is_dir(): h.update(skill_path.read_bytes()) @@ -511,28 +495,23 @@ def scan_skill_cached( cached = json.loads(cache_file.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): cached = None - if (isinstance(cached, dict) and cached.get("bundle_hash") == bundle_hash - and cached.get("scanner_version") == SCANNER_VERSION - and cached.get("source") == source and cached.get("source_url") == source_url): + expected = {"bundle_hash": bundle_hash, "scanner_version": SCANNER_VERSION, "source": source, "source_url": source_url} + if isinstance(cached, dict) and all(cached.get(k) == v for k, v in expected.items()): result = ScanResult( skill_name=skill_path.name, source=source, trust_level=cached["trust_level"], verdict=cached["verdict"], findings=[Finding(**item) for item in cached.get("findings", [])], scanned_at=cached["scanned_at"], summary=cached.get("summary", "")) - result.scan_provenance = provenance = {**cached, "fresh": False} - return result, provenance - - result = scan_skill(skill_path, source=source) - findings = [asdict(item) for item in result.findings] - provenance = { - "source": source, "source_url": source_url, "bundle_hash": bundle_hash, "scanner_version": SCANNER_VERSION, - "verdict": result.verdict, "trust_level": result.trust_level, "findings": findings, - "rules": sorted({item["pattern_id"] for item in findings}), - "scanned_at": result.scanned_at, "summary": result.summary, "fresh": True} - try: - cache_root.mkdir(parents=True, exist_ok=True) - cache_file.write_text(json.dumps(provenance, indent=2) + "\n", encoding="utf-8") - except OSError: - pass + provenance = {**cached, "fresh": False} + else: + result = scan_skill(skill_path, source=source) + findings = [asdict(item) for item in result.findings] + provenance = { + **expected, "verdict": result.verdict, "trust_level": result.trust_level, "findings": findings, + "rules": sorted({item["pattern_id"] for item in findings}), + "scanned_at": result.scanned_at, "summary": result.summary, "fresh": True} + with suppress(OSError): + cache_root.mkdir(parents=True, exist_ok=True) + cache_file.write_text(json.dumps(provenance, indent=2) + "\n", encoding="utf-8") result.scan_provenance = provenance return result, provenance @@ -572,8 +551,6 @@ def format_scan_report(result: ScanResult) -> str: return "\n".join(lines) -# --- Structural checks ------------------------------------------------------ - def _check_structure(skill_dir: Path, ignore=None) -> List[Finding]: """Structural anomalies: file count, total size, binary/executable files, symlinks escaping the skill dir, oversized files. *ignore(rel_path) -> bool* excludes paths from every count and finding.""" @@ -583,14 +560,10 @@ def _check_structure(skill_dir: Path, ignore=None) -> List[Finding]: def add(pid: str, severity: str, category: str, rel: str, match: str, description: str) -> None: findings.append(Finding(pid, severity, category, rel, 0, match, description)) - - file_count = 0 - total_size = 0 + file_count = total_size = 0 for f in skill_dir.rglob("*"): - if not f.is_file() and not f.is_symlink(): - continue rel = str(f.relative_to(skill_dir)) - if ignore(rel): + if not (f.is_file() or f.is_symlink()) or ignore(rel): continue file_count += 1 if f.is_symlink(): @@ -626,8 +599,6 @@ def _check_structure(skill_dir: Path, ignore=None) -> List[Finding]: return findings -# --- Internal helpers ------------------------------------------------------- - # `.skillignore` is Hermes-native; `.clawhubignore` is honored for skills published through ClawHub. _SKILL_IGNORE_FILENAMES = (".skillignore", ".clawhubignore") _ALWAYS_IGNORED_NAMES = set(_SKILL_IGNORE_FILENAMES) @@ -635,11 +606,10 @@ _NEVER_IGNORABLE = {"SKILL.md"} def _load_skill_ignore(skill_dir: Path): - """Build ``ignore(rel_posix_path) -> bool`` from a skill's `.skillignore` / `.clawhubignore`. - - gitignore basics: blank lines and ``#`` comments skipped; trailing ``/`` marks a directory (matches it - and everything under it); ``*``/``?`` globs via fnmatch on the full relative path and each segment; - leading ``/`` anchors to the skill root. Ignore files are always excluded; ``SKILL.md`` never is.""" + """Build ``ignore(rel_posix_path) -> bool`` from `.skillignore` / `.clawhubignore`. gitignore basics: blank + lines and ``#`` comments skipped; trailing ``/`` = directory (it and everything under it); ``*``/``?`` globs via + fnmatch on the full path and each segment; leading ``/`` anchors to the root. Ignore files always excluded; + ``SKILL.md`` never.""" patterns: List[str] = [] for ig in (skill_dir / name for name in _SKILL_IGNORE_FILENAMES): try: From 62e1d06ab40e3598eda6fa98e15f3489adde57d3 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:23:16 -0700 Subject: [PATCH 07/10] refactor(tools): compact tts builtin dispatch rows to one label per provider --- tools/tts_tool.py | 90 ++++++++++++++++------------------------------- 1 file changed, 30 insertions(+), 60 deletions(-) diff --git a/tools/tts_tool.py b/tools/tts_tool.py index 374f9d1c2e..023f95e5f5 100644 --- a/tools/tts_tool.py +++ b/tools/tts_tool.py @@ -221,61 +221,33 @@ def _has_any_command_tts_provider(tts_config: Optional[Dict[str, Any]] = None) - # --- Built-in provider dispatch --- -# provider -> (availability predicate or None, "package missing" error, log line, generator -# name). Predicates and generator names resolve module globals at call time so tests that -# monkeypatch ``tools.tts_tool._import_x`` / ``_check_x`` / ``_generate_x`` apply. +# provider -> (availability predicate or None, log label, generator name, "package missing" error). +# Predicates and generator names resolve module globals at call time so tests that monkeypatch +# ``tools.tts_tool._import_x`` / ``_check_x`` / ``_generate_x`` apply. _BUILTIN_DISPATCH: Dict[str, tuple] = { - "elevenlabs": ( - lambda: _importable(_import_elevenlabs), - "ElevenLabs provider selected but 'elevenlabs' package not installed. Run: pip install elevenlabs", - "Generating speech with ElevenLabs...", - "_generate_elevenlabs", - ), - "openai": ( - lambda: _importable(_import_openai_client), - "OpenAI provider selected but 'openai' package not installed.", - "Generating speech with OpenAI TTS...", - "_generate_openai_tts", - ), - "deepinfra": ( - lambda: _importable(_import_openai_client), - "DeepInfra TTS uses the 'openai' SDK but it isn't installed.", - "Generating speech with DeepInfra TTS...", - "_generate_deepinfra_tts", - ), - "minimax": (None, None, "Generating speech with MiniMax TTS...", "_generate_minimax_tts"), - "xai": (None, None, "Generating speech with xAI TTS...", "_generate_xai_tts"), - "mistral": ( - lambda: _importable(_import_mistral_client), - "Mistral provider selected but 'mistralai' package not installed. " - "Run `hermes setup` to install Mistral support.", - "Generating speech with Mistral Voxtral TTS...", - "_generate_mistral_tts", - ), - "gemini": (None, None, "Generating speech with Google Gemini TTS...", "_generate_gemini_tts"), - "neutts": ( - lambda: _check_neutts_available(), - "NeuTTS provider selected but neutts is not installed. " - "Run hermes setup and choose NeuTTS, or install espeak-ng and run python -m pip install -U neutts[all].", - "Generating speech with NeuTTS (local)...", - "_generate_neutts", - ), - "kittentts": ( - lambda: _importable(_import_kittentts), - "KittenTTS provider selected but 'kittentts' package not installed. " - "Run 'hermes setup tts' and choose KittenTTS, or install manually: " - "pip install https://github.com/KittenML/KittenTTS/releases/download/0.8.1/kittentts-0.8.1-py3-none-any.whl", - "Generating speech with KittenTTS (local, ~25MB)...", - "_generate_kittentts", - ), - "piper": ( - lambda: _importable(_import_piper), - "Piper provider selected but 'piper-tts' package not installed. " - "Run 'hermes tools' and select Piper under TTS, or install manually: " - "pip install piper-tts", - "Generating speech with Piper (local)...", - "_generate_piper_tts", - ), + "elevenlabs": (lambda: _importable(_import_elevenlabs), "ElevenLabs", "_generate_elevenlabs", + "ElevenLabs provider selected but 'elevenlabs' package not installed. Run: pip install elevenlabs"), + "openai": (lambda: _importable(_import_openai_client), "OpenAI TTS", "_generate_openai_tts", + "OpenAI provider selected but 'openai' package not installed."), + "deepinfra": (lambda: _importable(_import_openai_client), "DeepInfra TTS", "_generate_deepinfra_tts", + "DeepInfra TTS uses the 'openai' SDK but it isn't installed."), + "minimax": (None, "MiniMax TTS", "_generate_minimax_tts", None), + "xai": (None, "xAI TTS", "_generate_xai_tts", None), + "mistral": (lambda: _importable(_import_mistral_client), "Mistral Voxtral TTS", "_generate_mistral_tts", + "Mistral provider selected but 'mistralai' package not installed. " + "Run `hermes setup` to install Mistral support."), + "gemini": (None, "Google Gemini TTS", "_generate_gemini_tts", None), + "neutts": (lambda: _check_neutts_available(), "NeuTTS (local)", "_generate_neutts", + "NeuTTS provider selected but neutts is not installed. " + "Run hermes setup and choose NeuTTS, or install espeak-ng and run python -m pip install -U neutts[all]."), + "kittentts": (lambda: _importable(_import_kittentts), "KittenTTS (local, ~25MB)", "_generate_kittentts", + "KittenTTS provider selected but 'kittentts' package not installed. " + "Run 'hermes setup tts' and choose KittenTTS, or install manually: " + "pip install https://github.com/KittenML/KittenTTS/releases/download/0.8.1/kittentts-0.8.1-py3-none-any.whl"), + "piper": (lambda: _importable(_import_piper), "Piper (local)", "_generate_piper_tts", + "Piper provider selected but 'piper-tts' package not installed. " + "Run 'hermes tools' and select Piper under TTS, or install manually: " + "pip install piper-tts"), } @@ -301,7 +273,7 @@ def _select_builtin_engine(provider: str) -> tuple: """ entry = _BUILTIN_DISPATCH.get(provider) if entry is not None: - available, missing_error = entry[0], entry[1] + available, missing_error = entry[0], entry[3] if available is not None and not available(): return provider, _error_json(missing_error) return provider, None @@ -319,15 +291,13 @@ def _select_builtin_engine(provider: str) -> tuple: def _synthesize_builtin(engine: str, text: str, file_str: str, tts_config: Dict[str, Any], instructions: Optional[str]) -> None: """Run the already-selected built-in *engine*.""" entry = _BUILTIN_DISPATCH.get(engine) + logger.info("Generating speech with %s...", entry[1] if entry else "Edge TTS") if entry is None: - logger.info("Generating speech with Edge TTS...") _run_edge_tts(text, file_str, tts_config) - return - logger.info(entry[2]) - if engine == "openai": + elif engine == "openai": _generate_openai_tts(text, file_str, tts_config, instructions=instructions) else: - globals()[entry[3]](text, file_str, tts_config) + globals()[entry[2]](text, file_str, tts_config) def _finalize_voice_delivery( From c4a9f2bf4966e4b5f973a27b2abc8ab24546523d Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:28:33 -0700 Subject: [PATCH 08/10] =?UTF-8?q?refactor(tools):=20vision/video/url=5Fsaf?= =?UTF-8?q?ety=20=E2=80=94=20inline=20single-use=20helpers,=20dedupe=20bac?= =?UTF-8?q?kends,=20compact=20docstrings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/url_safety.py | 247 +++------- tools/video_generation_tool.py | 213 +++----- tools/vision_tools.py | 809 +++++++++++-------------------- tools/vision_tools_image_prep.py | 202 +++----- 4 files changed, 482 insertions(+), 989 deletions(-) diff --git a/tools/url_safety.py b/tools/url_safety.py index 56001e97f7..88dbdc8b83 100644 --- a/tools/url_safety.py +++ b/tools/url_safety.py @@ -1,12 +1,10 @@ """URL safety checks — blocks requests to private/internal network addresses (SSRF). -``security.allow_private_urls: true`` disables private-IP blocking for environments -whose DNS resolves public names to private/benchmark ranges; cloud metadata -hostnames/IPs are **always** blocked. DNS rebinding (TOCTOU) is closed for Hermes-owned -httpx paths by ``create_ssrf_safe_client()`` / ``create_ssrf_safe_async_client()``, which -re-apply the policy at TCP connect and dial the validated IP while preserving Host/SNI. -Redirect bypass is mitigated by response hooks re-validating each target -(``redirect_target_from_response``); third-party SDK fetches redirect server-side. +``security.allow_private_urls: true`` disables private-IP blocking (DNS that resolves public +names to private ranges); cloud metadata hostnames/IPs are **always** blocked. DNS rebinding +(TOCTOU) is closed for Hermes-owned httpx paths by ``create_ssrf_safe_[async_]client()``, which +re-apply the policy at TCP connect and dial the validated IP while preserving Host/SNI. Redirect +bypass is mitigated by response hooks re-validating each target (``redirect_target_from_response``). """ import ipaddress @@ -26,9 +24,7 @@ logger = logging.getLogger(__name__) # Proxy env vars: when set, the runtime should delegate DNS to the proxy. _PROXY_ENV_VARS = ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy") - _HTTP_SCHEMES = frozenset({"http", "https"}) - _IPAddress = ipaddress.IPv4Address | ipaddress.IPv6Address @@ -37,15 +33,11 @@ def _proxy_is_configured() -> bool: def normalize_url_for_request(url: str) -> str: - """Return an ASCII-safe HTTP URL for Hermes-owned URL tools (IRI -> URI). - - Users/models often supply IRIs (``https://wttr.in/Köln``). Preserves URL syntax - and existing percent escapes while IDNA-encoding the host and percent-encoding - non-ASCII path/query/fragment text. URL tool inputs only — never shell commands. - """ + """ASCII-safe HTTP URL for Hermes-owned URL tools (IRI -> URI, e.g. ``https://wttr.in/Köln``). + Preserves URL syntax and existing percent escapes while IDNA-encoding the host and + percent-encoding non-ASCII path/query/fragment text. URL tool inputs only — never shell commands.""" if not isinstance(url, str): return url - raw = url.strip() if not raw: return raw @@ -53,17 +45,13 @@ def normalize_url_for_request(url: str) -> str: # Repair model-emitted whitespace between scheme separator and authority # (``https:// docs.example``); that position is never meaningful in HTTP URLs. raw = re.sub(r"^([A-Za-z][A-Za-z0-9+.-]*://)\s+", r"\1", raw) - try: parsed = urlsplit(raw) except ValueError: return raw - if parsed.scheme.lower() not in _HTTP_SCHEMES: return raw - - netloc = parsed.netloc - hostname = parsed.hostname + netloc, hostname = parsed.netloc, parsed.hostname if hostname: try: ascii_host = hostname.encode("idna").decode("ascii") @@ -71,12 +59,9 @@ def normalize_url_for_request(url: str) -> str: ascii_host = hostname if ascii_host != hostname: netloc = netloc.replace(hostname, ascii_host, 1) - - path = quote(parsed.path, safe="/%:@!$&'()*+,;=") - query = quote(parsed.query, safe="/%:@!$&'()*+,;=?") - fragment = quote(parsed.fragment, safe="/%:@!$&'()*+,;=?") - - return urlunsplit((parsed.scheme, netloc, path, query, fragment)) + safe = "/%:@!$&'()*+,;=" + return urlunsplit((parsed.scheme, netloc, quote(parsed.path, safe=safe), + quote(parsed.query, safe=safe + "?"), quote(parsed.fragment, safe=safe + "?"))) # Unambiguously credential-bearing query param names. Deliberately narrow: bare @@ -86,17 +71,13 @@ _SENSITIVE_QUERY_PARAM_NAMES = frozenset({ "access_token", "api_key", "apikey", "auth_token", "authorization", "awsaccesskeyid", "client_secret", "credential", "credentials", "jwt", "password", "passwd", "secret", "session_id", "signature", "token", "x_amz_security_token", "x_amz_signature", - "x-amz-security-token", "x-amz-signature", -}) + "x-amz-security-token", "x-amz-signature"}) def sensitive_query_param_name(url: str) -> Optional[str]: - """Return the first credential-named query parameter in ``url`` (with a value), if any. - - Checked before handing URLs to third-party fetch/browser backends: catches opaque - magic links, OAuth codes, signed-URL signatures and custom ``?token=...`` values - that prefix-based token redaction misses. - """ + """First credential-named query parameter in ``url`` (with a value), if any. Checked before + handing URLs to third-party fetch/browser backends: catches opaque magic links, OAuth codes, + signed-URL signatures and custom ``?token=...`` values that prefix-based redaction misses.""" if not isinstance(url, str) or "?" not in url: return None try: @@ -105,18 +86,15 @@ def sensitive_query_param_name(url: str) -> Optional[str]: return None if parsed.scheme.lower() not in _HTTP_SCHEMES or not parsed.query: return None - for key, value in parse_qsl(parsed.query, keep_blank_values=True): - if value and unquote(key).lower() in _SENSITIVE_QUERY_PARAM_NAMES: - return key - return None + return next((key for key, value in parse_qsl(parsed.query, keep_blank_values=True) + if value and unquote(key).lower() in _SENSITIVE_QUERY_PARAM_NAMES), None) # Cloud metadata hostnames — always blocked regardless of DNS or config toggle. _BLOCKED_HOSTNAMES = frozenset({"metadata.google.internal", "metadata.goog"}) -# Cloud metadata / credential endpoints (the #1 SSRF target) — always blocked. -# IPv4-mapped IPv6 forms are listed because resolvers may return ``::ffff:x.x.x.x`` -# and ipaddress treats those as distinct. +# Cloud metadata / credential endpoints (the #1 SSRF target) — always blocked, also in +# IPv4-mapped IPv6 form (resolvers may return ``::ffff:x.x.x.x``; ipaddress treats those as distinct). _METADATA_V4 = ( "169.254.169.254", # AWS/GCP/Azure/DO/Oracle metadata "169.254.170.2", # AWS ECS task metadata (task IAM creds) @@ -128,15 +106,12 @@ _ALWAYS_BLOCKED_IPS = frozenset( | {ipaddress.ip_address("::ffff:" + ip) for ip in _METADATA_V4} | {ipaddress.ip_address("fd00:ec2::254")} # AWS metadata (IPv6) ) -_ALWAYS_BLOCKED_NETWORKS = ( - ipaddress.ip_network("169.254.0.0/16"), # entire link-local range (no legit agent target) - ipaddress.ip_network("::ffff:169.254.0.0/112"), # IPv4-mapped link-local range -) +# Entire link-local range (no legit agent target), plus its IPv4-mapped form. +_ALWAYS_BLOCKED_NETWORKS = tuple(ipaddress.ip_network(n) for n in ("169.254.0.0/16", "::ffff:169.254.0.0/112")) # Exact HTTPS hostnames allowed to resolve to private/benchmark-space IPs # (QQ media legitimately resolves to 198.18.0.0/15 behind local proxy infra). _TRUSTED_PRIVATE_IP_HOSTS = frozenset({"multimedia.nt.qq.com.cn"}) - _MAX_SSRF_CONNECT_IPS = 8 # 100.64.0.0/10 (CGNAT, RFC 6598) is neither is_private nor is_global in @@ -144,27 +119,19 @@ _MAX_SSRF_CONNECT_IPS = 8 _CGNAT_NETWORK = ipaddress.ip_network("100.64.0.0/10") # Global toggle cache (process lifetime; see _global_allow_private_urls). -_allow_private_resolved = False -_cached_allow_private: bool = False +_allow_private_resolved, _cached_allow_private = False, False def _global_allow_private_urls() -> bool: - """Return True when the user has opted out of private-IP blocking. - - Priority: ``HERMES_ALLOW_PRIVATE_URLS`` env, ``security.allow_private_urls``, - legacy ``browser.allow_private_urls``. A multiplex gateway serves several - independently configured profiles in one process, so profile-scoped turns - (``get_hermes_home_override()`` set) bypass the process-global cache — - otherwise the first profile's opt-out would disable blocking for every later one. - """ + """True when the user has opted out of private-IP blocking. Priority: ``HERMES_ALLOW_PRIVATE_URLS`` + env, ``security.allow_private_urls``, legacy ``browser.allow_private_urls``. Profile-scoped turns + (``get_hermes_home_override()`` set) bypass the process-global cache — a multiplex gateway serves + several profiles in one process; the first profile's opt-out must not disable blocking for later ones.""" global _allow_private_resolved, _cached_allow_private - if get_hermes_home_override() is not None: return _resolve_allow_private_urls() - if not _allow_private_resolved: - _allow_private_resolved = True - _cached_allow_private = _resolve_allow_private_urls() + _allow_private_resolved, _cached_allow_private = True, _resolve_allow_private_urls() return _cached_allow_private @@ -175,7 +142,6 @@ def _resolve_allow_private_urls() -> bool: return True if env_val in {"false", "0", "no"}: return False # explicit false does not fall through to config - try: from hermes_cli.config import read_raw_config cfg = read_raw_config() @@ -185,15 +151,13 @@ def _resolve_allow_private_urls() -> bool: return True except Exception: pass # config unavailable (tests, early import) — keep default - return False def _reset_allow_private_cache() -> None: """Reset the cached toggle — only for tests.""" global _allow_private_resolved, _cached_allow_private - _allow_private_resolved = False - _cached_allow_private = False + _allow_private_resolved = _cached_allow_private = False def _normalize_hostname(host: Optional[str]) -> str: @@ -201,7 +165,7 @@ def _normalize_hostname(host: Optional[str]) -> str: def _parse_ip(hostname: str) -> Optional[_IPAddress]: - """Return the IP object for a literal-IP hostname, else None.""" + """IP object for a literal-IP hostname, else None.""" try: return ipaddress.ip_address(hostname) except ValueError: @@ -209,14 +173,11 @@ def _parse_ip(hostname: str) -> Optional[_IPAddress]: def _iter_resolved_ips(addr_info: Any): - """Yield ``(raw, ip_str, ip)`` per getaddrinfo answer. - - ``ip_str`` has any IPv6 scope ID (``%eth0``) stripped; ``ip`` is None when the - answer is still unparseable — each caller decides skip / fail-closed / raise. - """ + """Yield ``(raw, ip_str, ip)`` per getaddrinfo answer. ``ip_str`` has any IPv6 scope ID + (``%eth0``) stripped; ``ip`` is None when still unparseable — each caller decides skip/fail/raise.""" for _family, _, _, _, sockaddr in addr_info: raw = sockaddr[0] - ip_str = raw.split("%")[0] if "%" in raw else raw + ip_str = raw.split("%")[0] yield raw, ip_str, _parse_ip(ip_str) @@ -238,36 +199,28 @@ def _is_blocked_ip(ip: _IPAddress) -> bool: def is_always_blocked_url(url: str) -> bool: - """Return True when the URL targets the always-blocked floor (cloud metadata). - - Narrower than ``is_safe_url``: only the sentinel hostnames/IPs, regardless of - backend, routing, or ``allow_private_urls`` — for callers that deliberately bypass - the full check (e.g. hybrid cloud browser routing private URLs to a local sidecar) - but must still enforce the non-negotiable floor. Returns False for ordinary - private/loopback URLs, DNS failures on non-sentinel hosts, and parse errors - (the caller's ordinary fail-closed path handles those). - """ + """True when the URL targets the always-blocked floor (cloud metadata) — only the sentinel + hostnames/IPs, regardless of backend, routing, or ``allow_private_urls``. For callers that + deliberately bypass the full check (e.g. hybrid cloud browser routing private URLs to a local + sidecar) but must still enforce the floor. False for ordinary private/loopback URLs, DNS + failures and parse errors (the caller's ordinary fail-closed path handles those).""" try: hostname = _normalize_hostname(urlparse(url).hostname) if not hostname: return False - if hostname in _BLOCKED_HOSTNAMES: logger.warning("Blocked request to internal hostname (always-blocked floor): %s", hostname) return True - ip = _parse_ip(hostname) if ip is not None: if _is_always_blocked_ip(ip): logger.warning("Blocked request to cloud metadata address (always-blocked floor): %s", hostname) return True return False - try: addr_info = _getaddrinfo(hostname) except socket.gaierror: return False # DNS failure is not part of the floor; caller's path handles it - for raw, ip_str, resolved in _iter_resolved_ips(addr_info): if resolved is None: logger.warning("Unparseable IP address %r for hostname %s — skipping address", raw, hostname) @@ -277,9 +230,7 @@ def is_always_blocked_url(url: str) -> bool: "Blocked request to cloud metadata address (always-blocked floor): %s -> %s", hostname, ip_str ) return True - return False - except Exception as exc: # Parse/unexpected errors are not "always blocked"; caller decides fail-open/closed. logger.debug("is_always_blocked_url error for %s: %s", url, exc) @@ -292,11 +243,8 @@ def _allows_private_ip_resolution(hostname: str, scheme: str) -> bool: def _resolved_ip_block_reason(ip: _IPAddress, allow_private: bool) -> Optional[str]: - """Why a resolved answer must be rejected, or None if it may be dialed. - - The metadata floor is checked first and ignores ``allow_private``; ordinary - private/internal classes are only blocked when ``allow_private`` is False. - """ + """Why a resolved answer must be rejected, or None if it may be dialed. The metadata floor + ignores ``allow_private``; ordinary private/internal classes are blocked only when it is False.""" if _is_always_blocked_ip(ip): return "cloud metadata address" if not allow_private and _is_blocked_ip(ip): @@ -305,12 +253,9 @@ def _resolved_ip_block_reason(ip: _IPAddress, allow_private: bool) -> Optional[s def is_safe_url(url: str) -> bool: - """Return True if the URL target is not a private/internal address. - - Resolves the hostname and checks every answer. Fails closed on DNS errors and - unexpected exceptions. ``allow_private_urls`` skips private-IP blocking, but - cloud metadata endpoints remain blocked regardless. - """ + """True if the URL target is not a private/internal address. Resolves the hostname and checks + every answer; fails closed on DNS errors and unexpected exceptions. ``allow_private_urls`` + skips private-IP blocking, but cloud metadata endpoints remain blocked regardless.""" try: parsed = urlparse(url) hostname = _normalize_hostname(parsed.hostname) @@ -325,11 +270,9 @@ def is_safe_url(url: str) -> bool: if hostname in _BLOCKED_HOSTNAMES: logger.warning("Blocked request to internal hostname: %s", hostname) return False - allow_all_private = _global_allow_private_urls() allow_private_ip = _allows_private_ip_resolution(hostname, scheme) allow_private = allow_all_private or allow_private_ip - try: addr_info = _getaddrinfo(hostname) except socket.gaierror: @@ -340,29 +283,23 @@ def is_safe_url(url: str) -> bool: if _parse_ip(hostname) is None and _proxy_is_configured(): logger.debug( "DNS resolution failed for %s — proxy configured, allowing through for proxy-side resolution", - hostname, - ) + hostname) return True logger.warning("Blocked request — DNS resolution failed for: %s", hostname) return False - for raw, ip_str, ip in _iter_resolved_ips(addr_info): if ip is None: logger.warning("Blocked request — unparseable IP address %r for hostname %s", raw, hostname) return False - reason = _resolved_ip_block_reason(ip, allow_private) if reason is not None: logger.warning("Blocked request to %s: %s -> %s", reason, hostname, ip_str) return False - if allow_all_private: logger.debug("Allowing private/internal resolution (security.allow_private_urls=true): %s", hostname) elif allow_private_ip: logger.debug("Allowing trusted hostname despite private/internal resolution: %s", hostname) - return True - except Exception as exc: # Fail closed: parsing edge cases must not become SSRF bypass vectors. logger.warning("Blocked request — URL safety check error for %s: %s", url, exc) @@ -370,7 +307,7 @@ def is_safe_url(url: str) -> bool: async def async_is_safe_url(url: str) -> bool: - """Same rules as :func:`is_safe_url`, with the blocking DNS work off the event loop.""" + """:func:`is_safe_url` with the blocking DNS work off the event loop.""" return await asyncio.to_thread(is_safe_url, url) @@ -379,40 +316,30 @@ class SSRFConnectionBlocked(ValueError): def _resolved_http_connect_ips(host: str, port: int, scheme: str) -> list[str]: - """Resolve and validate *host* at TCP-connect time; return dialable IP strings. - - Closes the DNS-rebinding gap between pre-flight validation and connection - setup for direct httpx clients. The result is capped at ``_MAX_SSRF_CONNECT_IPS``, - but EVERY answer is validated. - """ + """Resolve and validate *host* at TCP-connect time; return dialable IP strings. Closes the + DNS-rebinding gap between pre-flight validation and connect for direct httpx clients. The + result is capped at ``_MAX_SSRF_CONNECT_IPS``, but EVERY answer is validated.""" hostname = _normalize_hostname(host) if not hostname: raise SSRFConnectionBlocked("Blocked request with empty hostname") - if hostname in _BLOCKED_HOSTNAMES: raise SSRFConnectionBlocked(f"Blocked request to internal hostname: {hostname}") - allow_private = _global_allow_private_urls() or _allows_private_ip_resolution(hostname, scheme) - try: addr_info = _getaddrinfo(hostname, port) except socket.gaierror as exc: raise SSRFConnectionBlocked(f"Blocked request - DNS resolution failed for: {hostname}") from exc - safe_ips: list[str] = [] for raw, ip_str, ip in _iter_resolved_ips(addr_info): if ip is None: raise SSRFConnectionBlocked( f"Blocked request - unparseable IP address {raw!r} for hostname {hostname}" ) from ValueError(f"{ip_str!r} does not appear to be an IPv4 or IPv6 address") - reason = _resolved_ip_block_reason(ip, allow_private) if reason is not None: raise SSRFConnectionBlocked(f"Blocked request to {reason} during connect: {hostname} -> {ip_str}") - if ip_str not in safe_ips and len(safe_ips) < _MAX_SSRF_CONNECT_IPS: safe_ips.append(ip_str) - if not safe_ips: raise SSRFConnectionBlocked(f"Blocked request - DNS returned no results for: {hostname}") return safe_ips @@ -420,11 +347,8 @@ def _resolved_http_connect_ips(host: str, port: int, scheme: str) -> list[str]: class _SSRFGuardedBackendBase: """httpcore backend that re-resolves + validates at connect time and dials a vetted IP. - - Host/SNI stay on the original hostname (the transport still sees ``host``); - Unix sockets are refused outright. Candidate IPs are tried in order and the - last connect error is re-raised so callers see the real network failure. - """ + Host/SNI stay on the original hostname; Unix sockets are refused outright. Candidate IPs are + tried in order and the last connect error is re-raised so callers see the real failure.""" def __init__(self, backend: Any, schemes_by_origin_var: Any): self._backend = backend @@ -434,6 +358,11 @@ class _SSRFGuardedBackendBase: scheme = self._schemes_by_origin_var.get({}).get((host, port)) or ("https" if port == 443 else "http") return _resolved_http_connect_ips(host, port, scheme) + @staticmethod + def _connect_errors() -> tuple: + import httpcore + return (httpcore.ConnectError, httpcore.ConnectTimeout) + @staticmethod def _no_usable_ips(host: str, last_exc: Exception | None) -> Exception: if last_exc is not None: @@ -451,16 +380,12 @@ class _SSRFGuardedAsyncNetworkBackend(_SSRFGuardedBackendBase): async def connect_tcp(self, host: str, port: int, timeout: float | None = None, local_address: str | None = None, socket_options: Any = None) -> Any: - import httpcore - - ips = await asyncio.to_thread(self._connect_ips, host, port) last_exc: Exception | None = None - for ip in ips: + for ip in await asyncio.to_thread(self._connect_ips, host, port): try: return await self._backend.connect_tcp( - ip, port, timeout=timeout, local_address=local_address, socket_options=socket_options, - ) - except (httpcore.ConnectError, httpcore.ConnectTimeout) as exc: + ip, port, timeout=timeout, local_address=local_address, socket_options=socket_options) + except self._connect_errors() as exc: last_exc = exc raise self._no_usable_ips(host, last_exc) @@ -478,15 +403,12 @@ class _SSRFGuardedNetworkBackend(_SSRFGuardedBackendBase): def connect_tcp(self, host: str, port: int, timeout: float | None = None, local_address: str | None = None, socket_options: Any = None) -> Any: - import httpcore - last_exc: Exception | None = None for ip in self._connect_ips(host, port): try: return self._backend.connect_tcp( - ip, port, timeout=timeout, local_address=local_address, socket_options=socket_options, - ) - except (httpcore.ConnectError, httpcore.ConnectTimeout) as exc: + ip, port, timeout=timeout, local_address=local_address, socket_options=socket_options) + except self._connect_errors() as exc: last_exc = exc raise self._no_usable_ips(host, last_exc) @@ -496,9 +418,7 @@ class _SSRFGuardedNetworkBackend(_SSRFGuardedBackendBase): def _origin_scheme_context(request: Any) -> dict[tuple[str, int], str]: host, port, scheme = request.url.host, request.url.port, request.url.scheme - if not host or port is None or scheme not in _HTTP_SCHEMES: - return {} - return {(host, port): scheme} + return {(host, port): scheme} if host and port is not None and scheme in _HTTP_SCHEMES else {} @contextmanager @@ -512,22 +432,17 @@ def _origin_scope(schemes_by_origin_var: Any, request: Any): def _install_ssrf_guard_on_transport(transport: Any, schemes_by_origin_var: Any, *, is_async: bool = False) -> None: - """Swap the transport's pool network backend for the SSRF-guarded one (idempotent). - - Only the client's direct transport is guarded; proxy mounts are left alone so - final-target resolution is delegated to the (trusted) proxy egress. - """ + """Swap the transport's pool network backend for the SSRF-guarded one (idempotent). Only the + direct transport is guarded; proxy mounts delegate final-target resolution to the trusted proxy.""" state = getattr(transport, "__dict__", {}) if transport is not None else {} if transport is None or state.get("_hermes_ssrf_guarded", False): return - label = "async httpx transport" if is_async else "httpx transport" pool = state.get("_pool") if pool is None or not hasattr(pool, "_network_backend"): raise SSRFConnectionBlocked(f"Unsupported {label} cannot be made SSRF-safe") backend_cls = _SSRFGuardedAsyncNetworkBackend if is_async else _SSRFGuardedNetworkBackend pool._network_backend = backend_cls(schemes_by_origin_var) - method_name = "handle_async_request" if is_async else "handle_request" handle = getattr(transport, method_name, None) if handle is None: @@ -540,7 +455,6 @@ def _install_ssrf_guard_on_transport(transport: Any, schemes_by_origin_var: Any, def guarded_sync(request: Any) -> Any: with _origin_scope(schemes_by_origin_var, request): return handle(request) - setattr(transport, method_name, guarded_async if is_async else guarded_sync) transport._hermes_ssrf_guarded = True @@ -548,22 +462,16 @@ def _install_ssrf_guard_on_transport(transport: Any, schemes_by_origin_var: Any, def _install_ssrf_guard_on_client(client: Any, *, is_async: bool = False) -> None: """Guard ``client._transport`` only; ``_mounts`` (env/explicit proxies) stay untouched.""" import contextvars - var_name = "hermes_ssrf_async_origin_schemes" if is_async else "hermes_ssrf_origin_schemes" _install_ssrf_guard_on_transport( - getattr(client, "__dict__", {}).get("_transport"), contextvars.ContextVar(var_name), is_async=is_async, - ) + getattr(client, "__dict__", {}).get("_transport"), contextvars.ContextVar(var_name), is_async=is_async) def create_ssrf_safe_async_client(**kwargs: Any) -> Any: - """Create an ``httpx.AsyncClient`` with connect-time SSRF validation. - - Direct HTTP(S) connections are resolved, validated, and dialed by IP at - TCP-connect time while the request hostname is preserved for Host, SNI, and - certificate verification. Proxied requests delegate resolution to the proxy. - """ + """``httpx.AsyncClient`` with connect-time SSRF validation: direct HTTP(S) connections are + resolved, validated, and dialed by IP while the hostname is preserved for Host, SNI, and + certificate verification. Proxied requests delegate resolution to the proxy.""" import httpx - client = httpx.AsyncClient(**kwargs) _install_ssrf_guard_on_client(client, is_async=True) return client @@ -572,30 +480,19 @@ def create_ssrf_safe_async_client(**kwargs: Any) -> Any: def create_ssrf_safe_client(**kwargs: Any) -> Any: """Create an ``httpx.Client`` with connect-time SSRF validation.""" import httpx - client = httpx.Client(**kwargs) _install_ssrf_guard_on_client(client) return client def redirect_target_from_response(response: Any) -> Optional[str]: - """Return the redirect target visible from inside an httpx response hook. - - ``response.next_request`` is frequently ``None`` inside hooks (populated later - by the redirect follower), which would make an SSRF redirect guard silently - never fire. Resolve from the ``Location`` header first (relative via - ``urljoin``), falling back to ``next_request``. - """ + """Redirect target visible from inside an httpx response hook. ``response.next_request`` is + frequently ``None`` inside hooks (populated later by the follower), which would make an SSRF + redirect guard silently never fire — so resolve from ``Location`` first, then ``next_request``.""" if not getattr(response, "is_redirect", False): return None - - headers = getattr(response, "headers", {}) or {} - location = headers.get("location") + location = (getattr(response, "headers", {}) or {}).get("location") if location: return urljoin(str(getattr(response, "url", "")), str(location)) - next_request = getattr(response, "next_request", None) - if next_request: - return str(next_request.url) - - return None + return str(next_request.url) if next_request else None diff --git a/tools/video_generation_tool.py b/tools/video_generation_tool.py index 287f21dfa3..1397c2ac57 100644 --- a/tools/video_generation_tool.py +++ b/tools/video_generation_tool.py @@ -3,9 +3,8 @@ (``agent/video_gen_provider.py`` ABC, ``agent/video_gen_registry.py``, ``plugins/video_gen//``). Ships **no in-tree provider**: enable a plugin and select it in ``hermes tools`` → Video -Generation. Covers text-, image- and reference-to-video; the tool layer only does lightweight -validation and each provider clamps/ignores unsupported params inside ``generate``, so the -surface stays stable as providers ship. Video edit/extend are deliberately not exposed here. +Generation. The tool layer only does lightweight validation; each provider clamps/ignores +unsupported params inside ``generate``. Video edit/extend are deliberately not exposed here. """ from __future__ import annotations @@ -19,8 +18,7 @@ from agent.video_gen_provider import ( COMMON_RESOLUTIONS, DEFAULT_ASPECT_RATIO, DEFAULT_RESOLUTION, - error_response, -) + error_response) from tools.registry import registry, tool_error logger = logging.getLogger(__name__) @@ -75,23 +73,15 @@ VIDEO_GENERATE_SCHEMA: Dict[str, Any] = { } -# --------------------------------------------------------------------------- -# Config readers (mirror image_generation_tool.py) -# --------------------------------------------------------------------------- def _read_video_gen_key(key: str) -> Optional[str]: """Return the stripped ``video_gen.`` string from config.yaml, or None.""" try: - from hermes_cli.config import load_config - - cfg = load_config() - section = cfg.get("video_gen") if isinstance(cfg, dict) else None - value = section.get(key) if isinstance(section, dict) else None + from hermes_cli.config import cfg_get, load_config + value = cfg_get(load_config(), "video_gen", key) except Exception as exc: logger.debug("Could not read video_gen config: %s", exc) return None - if isinstance(value, str) and value.strip(): - return value.strip() - return None + return value.strip() if isinstance(value, str) and value.strip() else None def _read_configured_video_provider() -> Optional[str]: @@ -106,32 +96,21 @@ def _discovered_registry(): """Import the provider registry after (idempotent) plugin discovery so user-installed plugins are visible.""" from agent import video_gen_registry from hermes_cli.plugins import _ensure_plugins_discovered - _ensure_plugins_discovered() return video_gen_registry, _ensure_plugins_discovered -# --------------------------------------------------------------------------- -# Availability check + provider resolution -# --------------------------------------------------------------------------- def check_video_generation_requirements() -> bool: """True when at least one registered provider reports available.""" try: registry_mod, _ = _discovered_registry() - for provider in registry_mod.list_providers(): - try: - if provider.is_available(): - return True - except Exception: - continue + return any(_provider_call(p, "is_available", False) for p in registry_mod.list_providers()) except Exception: - pass - return False + return False def _resolve_active_provider(): - """Active provider or None; forces a discovery refresh on a miss (long-lived sessions - that started before a plugin was installed).""" + """Active provider or None; a miss forces a discovery refresh (sessions older than the plugin install).""" try: registry_mod, ensure_discovered = _discovered_registry() provider = registry_mod.get_active_provider() @@ -147,32 +126,23 @@ def _resolve_active_provider(): def _missing_provider_error(configured: Optional[str]) -> str: if configured: return json.dumps(error_response( - error=( - f"video_gen.provider='{configured}' is set but no plugin " - f"registered that name. Run `hermes plugins list` to see " - f"installed video gen backends, or `hermes tools` → Video " - f"Generation to pick one." - ), - error_type="provider_not_registered", - provider=configured, - )) + error=(f"video_gen.provider='{configured}' is set but no plugin registered that name. " + f"Run `hermes plugins list` to see installed video gen backends, or " + f"`hermes tools` → Video Generation to pick one."), + error_type="provider_not_registered", provider=configured)) return json.dumps(error_response( - error=( - "No video generation backend is configured. Run `hermes tools` → " - "Video Generation to enable one (xAI, FAL, or Google Veo)." - ), - error_type="no_provider_configured", - )) + error=("No video generation backend is configured. Run `hermes tools` → " + "Video Generation to enable one (xAI, FAL, or Google Veo)."), + error_type="no_provider_configured")) + + +_BOOL_WORDS = {"true": True, "1": True, "yes": True, "on": True, + "false": False, "0": False, "no": False, "off": False} -# --------------------------------------------------------------------------- -# Handler -# --------------------------------------------------------------------------- def _coerce_int(value: Any) -> Optional[int]: - if value is None or value == "": - return None try: - return int(value) + return None if value is None or value == "" else int(value) except (TypeError, ValueError): return None @@ -180,21 +150,15 @@ def _coerce_int(value: Any) -> Optional[int]: def _coerce_bool(value: Any) -> Optional[bool]: if isinstance(value, bool): return value - if isinstance(value, str): - return {"true": True, "1": True, "yes": True, "on": True, - "false": False, "0": False, "no": False, "off": False}.get(value.strip().lower()) - return None + return _BOOL_WORDS.get(value.strip().lower()) if isinstance(value, str) else None def _normalize_reference_images(value: Any) -> Optional[List[str]]: - if value is None: - return None if isinstance(value, str): value = [value] if not isinstance(value, (list, tuple)): return None - out = [item.strip() for item in value if isinstance(item, str) and item.strip()] - return out or None + return [item.strip() for item in value if isinstance(item, str) and item.strip()] or None def _handle_video_generate(args: Dict[str, Any], **_kw: Any) -> str: @@ -205,29 +169,28 @@ def _handle_video_generate(args: Dict[str, Any], **_kw: Any) -> str: # Confinement chokepoint (mirrors image_generate): non-local backends hand providers data: URLs. from tools.image_generation_tool import _confine_source_images - image_url, reference_image_urls, confine_error = _confine_source_images( image_url, reference_image_urls, task_id) if confine_error is not None: return confine_error - duration = _coerce_int(args.get("duration")) - aspect_ratio = (args.get("aspect_ratio") or DEFAULT_ASPECT_RATIO).strip() or DEFAULT_ASPECT_RATIO - resolution = (args.get("resolution") or DEFAULT_RESOLUTION).strip() or DEFAULT_RESOLUTION - negative_prompt = (args.get("negative_prompt") or "").strip() or None - audio = _coerce_bool(args.get("audio")) - seed = _coerce_int(args.get("seed")) - upscale = _coerce_bool(args.get("upscale")) + # Coerced BEFORE validation (ordering parity: a bad value raises before a missing prompt). + optional = { + "duration": _coerce_int(args.get("duration")), + "aspect_ratio": (args.get("aspect_ratio") or DEFAULT_ASPECT_RATIO).strip() or DEFAULT_ASPECT_RATIO, + "resolution": (args.get("resolution") or DEFAULT_RESOLUTION).strip() or DEFAULT_RESOLUTION, + "negative_prompt": (args.get("negative_prompt") or "").strip() or None, + "audio": _coerce_bool(args.get("audio")), + "seed": _coerce_int(args.get("seed")), + "upscale": _coerce_bool(args.get("upscale"))} model_override = (args.get("model") or "").strip() or None - # Soft validation — providers do their own; a backend may accept image-only, our surface never does. + # Soft validation — providers do their own; our surface never accepts image-only. if not prompt: return tool_error("prompt is required for video generation") if "operation" in args or "video_url" in args: return tool_error( "video_generate only supports text-to-video, image-to-video, and " - "reference-to-video; use a provider-specific tool for video edit/extend" - ) - + "reference-to-video; use a provider-specific tool for video edit/extend") configured = _read_configured_video_provider() provider = _resolve_active_provider() if provider is None: @@ -235,20 +198,9 @@ def _handle_video_generate(args: Dict[str, Any], **_kw: Any) -> str: # Explicit arg wins, then config, then provider default. model = model_override or _read_configured_video_model() or provider.default_model() - kwargs: Dict[str, Any] = { - "model": model, - "_model_override_explicit": bool(model_override), - "image_url": image_url, - "reference_image_urls": reference_image_urls, - "duration": duration, - "aspect_ratio": aspect_ratio, - "resolution": resolution, - "negative_prompt": negative_prompt, - "audio": audio, - "seed": seed, - "upscale": upscale, - } + "model": model, "_model_override_explicit": bool(model_override), + "image_url": image_url, "reference_image_urls": reference_image_urls, **optional} # Drop None entries so providers see clean defaults. kwargs = {k: v for k, v in kwargs.items() if v is not None} pname = getattr(provider, "name", "?") @@ -256,42 +208,28 @@ def _handle_video_generate(args: Dict[str, Any], **_kw: Any) -> str: def _err(error: str, error_type: str) -> str: return json.dumps(error_response( error=error, error_type=error_type, - provider=getattr(provider, "name", ""), model=model or "", prompt=prompt, - )) - + provider=getattr(provider, "name", ""), model=model or "", prompt=prompt)) try: result = provider.generate(prompt=prompt, **kwargs) except TypeError as exc: # An un-widened provider signature is a plugin bug, not a caller error. - logger.warning( - "video_gen provider '%s' rejected kwargs (signature too narrow): %s", - pname, exc, - ) + logger.warning("video_gen provider '%s' rejected kwargs (signature too narrow): %s", pname, exc) return _err( - f"Provider '{pname}' signature is " - f"out of date with the video_generate schema. Report this " - f"to the plugin author.", - "provider_contract", - ) + f"Provider '{pname}' signature is out of date with the video_generate schema. " + f"Report this to the plugin author.", + "provider_contract") except Exception as exc: logger.warning("video_gen provider '%s' raised: %s", pname, exc) return _err(f"Provider '{pname}' error: {exc}", "provider_exception") - if not isinstance(result, dict): return _err("Provider returned a non-dict result", "provider_contract") - return json.dumps(result) -# --------------------------------------------------------------------------- -# Dynamic schema — reflect the active backend's actual capabilities -# --------------------------------------------------------------------------- -# Surfacing the per-model surface (modalities, enums, durations, audio/negative-prompt) -# means the model usually gets the call right first try. model_tools.get_tool_definitions() -# keys its cache on config.yaml mtime, so the schema rebuilds on provider/model change. - -# Optional params advertised only when the provider's capabilities() sets the flag -# (order = schema property order). +# Dynamic schema — reflects the active backend's actual capabilities so the model usually gets +# the call right first try. model_tools.get_tool_definitions() keys its cache on config.yaml +# mtime, so the schema rebuilds on provider/model change. Optional params below are advertised +# only when the provider's capabilities() sets the flag (order = schema property order). _CAPABILITY_PARAMS = ( ("supports_negative_prompt", "negative_prompt", { "type": "string", @@ -334,34 +272,31 @@ _GENERIC_DESCRIPTION = ( def _schema(description: str, properties: Dict[str, Any]) -> Dict[str, Any]: return { "description": description, - "parameters": {"type": "object", "properties": properties, "required": ["prompt"]}, - } + "parameters": {"type": "object", "properties": properties, "required": ["prompt"]}} + + +def _provider_call(provider: Any, method: str, default: Any) -> Any: + """``provider.()`` or ``default`` when it raises or returns a falsy value.""" + try: + return getattr(provider, method)() or default + except Exception: + return default def _build_dynamic_video_schema() -> Dict[str, Any]: - """Render description AND params from capabilities() + the model's catalog entry; enums and - duration bounds tighten to the active model. Unadvertised args are still accepted (replay compat).""" + """Description AND params from capabilities() + the model's catalog entry; enums and duration + bounds tighten to the active model. Unadvertised args are still accepted (replay compat).""" static_props = VIDEO_GENERATE_SCHEMA["parameters"]["properties"] parts: List[str] = [_GENERIC_DESCRIPTION] - configured_model = _read_configured_video_model() provider = _resolve_active_provider() - if provider is None: parts.append( "\nNo video backend is available. Calls will return an error " - "until the user picks one via `hermes tools` → Video Generation." - ) + "until the user picks one via `hermes tools` → Video Generation.") return _schema("\n".join(parts), {"prompt": static_props["prompt"]}) - - try: - caps = provider.capabilities() or {} - except Exception: - caps = {} - try: - models = provider.list_models() or [] - except Exception: - models = [] + caps = _provider_call(provider, "capabilities", {}) + models = _provider_call(provider, "list_models", []) active_model = configured_model or provider.default_model() model_meta = next((m for m in models if isinstance(m, dict) and m.get("id") == active_model), {}) @@ -374,11 +309,9 @@ def _build_dynamic_video_schema() -> Dict[str, Any]: if "image" in model_modalities and "text" not in model_modalities: parts.append( "- this model is image-to-video only — image_url is REQUIRED; " - "text-only calls will be rejected" - ) + "text-only calls will be rejected") elif "text" in model_modalities and "image" not in model_modalities: parts.append("- this model is text-to-video only — image_url is not supported") - effective_modalities = model_modalities or set(caps.get("modalities") or []) can_i2v = "image" in effective_modalities t2v = "text" in effective_modalities @@ -386,33 +319,26 @@ def _build_dynamic_video_schema() -> Dict[str, Any]: parts.append("- image-to-video only: image_url is REQUIRED") elif not can_i2v: parts.append("- text-to-video only (no image input)") - if provider.name == "xai": parts.append( "- chaining: for edit/extend pass the public HTTPS MP4 in `video` " "or `public_url` from the prior Imagine result (files-cdn). For " "image-to-video / reference-to-video pass public image URLs the " - "same way" - ) + "same way") try: from tools.xai_http import xai_storage_notice_text - notice = xai_storage_notice_text("video_gen") except Exception: notice = "" if notice: parts.append(f"- storage: {notice}") - properties: Dict[str, Any] = {"prompt": static_props["prompt"]} - if can_i2v: properties["image_url"] = { "type": "string", "description": ( "Public HTTPS URL of a still image to animate " - "(image-to-video). Omit for text-to-video." - ), - } + "(image-to-video). Omit for text-to-video.")} max_refs = int(caps.get("max_reference_images") or 0) if max_refs > 0: properties["reference_image_urls"] = { @@ -421,10 +347,7 @@ def _build_dynamic_video_schema() -> Dict[str, Any]: "maxItems": max_refs, "description": ( f"Up to {max_refs} public HTTPS reference image URLs " - "(style or character refs)." - ), - } - + "(style or character refs).")} min_duration = model_meta.get("min_duration", caps.get("min_duration")) max_duration = model_meta.get("max_duration", caps.get("max_duration")) duration_param = dict(static_props["duration"]) @@ -433,8 +356,7 @@ def _build_dynamic_video_schema() -> Dict[str, Any]: duration_param["maximum"] = int(max_duration) duration_param["description"] = ( f"Video duration in seconds ({min_duration}-{max_duration}). " - "Omit for the provider default." - ) + "Omit for the provider default.") properties["duration"] = duration_param # Tighten enums to the active backend's actual sets when declared. @@ -443,7 +365,6 @@ def _build_dynamic_video_schema() -> Dict[str, Any]: if caps.get(caps_key): param["enum"] = list(caps[caps_key]) properties[key] = param - for flag, key, param in _CAPABILITY_PARAMS: if caps.get(flag): properties[key] = param @@ -451,8 +372,7 @@ def _build_dynamic_video_schema() -> Dict[str, Any]: parts.append( "- audio: native stereo audio is generated with every video " "(always on; no toggle) — describe the desired sound in the " - "prompt" - ) + "prompt") properties["model"] = static_props["model"] return _schema("\n".join(parts), properties) @@ -466,5 +386,4 @@ registry.register( requires_env=[], is_async=False, emoji="🎬", - dynamic_schema_overrides=_build_dynamic_video_schema, -) + dynamic_schema_overrides=_build_dynamic_video_schema) diff --git a/tools/vision_tools.py b/tools/vision_tools.py index edbe99442d..b8a45eddff 100644 --- a/tools/vision_tools.py +++ b/tools/vision_tools.py @@ -1,10 +1,9 @@ #!/usr/bin/env python3 """Vision tools: ``vision_analyze`` (image) and ``video_analyze``. -Images resolve through :mod:`tools.image_source`, are normalized to a -provider-supported format (:mod:`tools.vision_tools_image_prep`), then either -attach natively to a vision-capable main model (multimodal tool-result -envelope) or are described by the auxiliary vision LLM router. +Images resolve through :mod:`tools.image_source`, are normalized to a provider-supported format +(:mod:`tools.vision_tools_image_prep`), then either attach natively to a vision-capable main +model (multimodal tool-result envelope) or are described by the auxiliary vision LLM router. """ import base64 @@ -16,13 +15,12 @@ import logging import os import uuid from pathlib import Path -from typing import Any, Awaitable, Callable, Dict, Optional +from typing import Any, Awaitable, Callable, Dict, NamedTuple, Optional from urllib.parse import urlparse import httpx -# ``agent.auxiliary_client`` costs ~50 ms cold; only the handlers need it. Both -# names stay module attributes so tests can patch ``tools.vision_tools.async_call_llm``; -# truthy-skip means injected mocks win. +# ``agent.auxiliary_client`` costs ~50 ms cold; only the handlers need it. Both names stay +# module attributes so tests can patch ``tools.vision_tools.async_call_llm`` (truthy-skip: mocks win). async_call_llm: Any = None extract_content_or_reasoning: Any = None @@ -30,11 +28,9 @@ extract_content_or_reasoning: Any = None def _load_auxiliary_client() -> None: global async_call_llm, extract_content_or_reasoning if async_call_llm is None or extract_content_or_reasoning is None: - from agent.auxiliary_client import async_call_llm as _acl, extract_content_or_reasoning as _ecr - if async_call_llm is None: - async_call_llm = _acl - if extract_content_or_reasoning is None: - extract_content_or_reasoning = _ecr + from agent import auxiliary_client as _aux + async_call_llm = async_call_llm or _aux.async_call_llm + extract_content_or_reasoning = extract_content_or_reasoning or _aux.extract_content_or_reasoning from hermes_constants import get_hermes_dir @@ -51,8 +47,7 @@ from tools.vision_tools_image_prep import ( # noqa: F401 — re-exported for te _normalize_to_supported_image, _rasterize_svg_to_png, _supported_media_types, - _validate_raster_image_decodable, -) + _validate_raster_image_decodable) logger = logging.getLogger(__name__) @@ -69,25 +64,16 @@ def _cfg_auxiliary(*keys: str, default=None): def _read_vision_setting(env_var: str, key: str, cast, minimum=None): - """Env var → ``auxiliary.vision.`` → None. - - Values that fail ``cast`` or fall below ``minimum`` are skipped in favor of - the next source (a cap can never be disabled by a bad value). - """ + """Env var → ``auxiliary.vision.`` → None. Values that fail ``cast`` or fall below + ``minimum`` are skipped in favor of the next source (a cap can never be disabled by a bad value).""" def _accept(raw): try: val = cast(raw) except (TypeError, ValueError): return None return val if minimum is None or val >= minimum else None - - env_val = os.getenv(env_var, "").strip() - if env_val: - val = _accept(env_val) - if val is not None: - return val - raw = _cfg_auxiliary("vision", key) - return None if raw is None else _accept(raw) + val = _accept(os.getenv(env_var, "").strip() or None) + return val if val is not None else _accept(_cfg_auxiliary("vision", key)) # HTTP download timeout (separate from ``auxiliary.vision.timeout``, which governs the LLM call). @@ -99,13 +85,12 @@ if _VISION_DOWNLOAD_TIMEOUT is None: _VISION_MAX_DOWNLOAD_BYTES = 50 * 1024 * 1024 -# CPU-burst concurrency cap. A turn can fan out dozens of vision_analyze calls, -# each a CPU-heavy base64 encode + Pillow resize; unbounded they saturate every -# core and starve the shared event loop. Only the CPU burst is capped (LLM calls -# stay fully concurrent) on a dedicated executor sized to the usable core count. -# Must be a threading primitive: each call runs via model_tools._run_async on a -# PER-THREAD loop, so an asyncio semaphore cannot coordinate across them. The -# default executor is NOT used: it is shared with the gateway/web server. +# CPU-burst cap: a turn can fan out dozens of vision_analyze calls (base64 encode + Pillow +# resize each) that would saturate every core and starve the shared event loop. Only the CPU +# burst is capped (LLM calls stay concurrent), on a dedicated executor sized to usable cores. +# Must be a threading primitive — each call runs via model_tools._run_async on a PER-THREAD +# loop, so an asyncio semaphore cannot coordinate; the default executor is shared with the +# gateway/web server and is deliberately NOT used. def _detect_host_cpus() -> int: """Usable CPU count (``sched_getaffinity`` honors cpuset pinning), at least 1.""" try: @@ -115,14 +100,16 @@ def _detect_host_cpus() -> int: def _resolve_vision_cpu_workers() -> int: - """HERMES_VISION_MAX_CONCURRENCY → ``auxiliary.vision.max_concurrency`` → host cores (values < 1 ignored).""" + """HERMES_VISION_MAX_CONCURRENCY → ``auxiliary.vision.max_concurrency`` → host cores (< 1 ignored).""" val = _read_vision_setting("HERMES_VISION_MAX_CONCURRENCY", "max_concurrency", int, minimum=1) - return _detect_host_cpus() if val is None else val + return val or _detect_host_cpus() _VISION_CPU_WORKERS = _resolve_vision_cpu_workers() -_vision_cpu_executor = ThreadPoolExecutor(max_workers=_VISION_CPU_WORKERS, thread_name_prefix="vision-encode") +_vision_cpu_executor = ThreadPoolExecutor( + max_workers=_VISION_CPU_WORKERS, thread_name_prefix="vision-encode", +) async def _run_encode_on_cpu_executor(fn, *args, **kwargs): @@ -132,33 +119,22 @@ async def _run_encode_on_cpu_executor(fn, *args, **kwargs): return await loop.run_in_executor(_vision_cpu_executor, functools.partial(fn, *args, **kwargs)) -def _image_url_shape_ok(url: str) -> bool: - """HTTP(S) shape check only (scheme + netloc; no DNS). Extension-less CDN URLs pass.""" - if not url or not isinstance(url, str) or not url.startswith(("http://", "https://")): - return False - return bool(urlparse(url).netloc) - - async def _validate_image_url_async(url: str) -> bool: - """Validate remote image URL (SSRF guard) without blocking the event loop on DNS.""" - if not _image_url_shape_ok(url): + """HTTP(S) shape check (extension-less CDN URLs pass) + SSRF guard, DNS off the event loop.""" + if not (isinstance(url, str) and url.startswith(("http://", "https://")) and urlparse(url).netloc): return False from tools.url_safety import async_is_safe_url return await async_is_safe_url(url) def _is_retryable_download_error(error: Exception) -> bool: - """True only for transient download failures worth retrying. - - Fail-fast: 4xx other than 429, PermissionError (policy/SSRF block), ValueError - (too large / blocked redirect — deterministic). Retryable: 429, 5xx, transport - errors and anything unclassified. - """ + """Transient failures only: 429, 5xx, transport errors and anything unclassified. Fail-fast on + other 4xx, PermissionError (policy/SSRF block) and ValueError (too large / blocked redirect).""" if isinstance(error, (PermissionError, ValueError)): return False if isinstance(error, httpx.HTTPStatusError): status = error.response.status_code - return not (400 <= status < 500 and status != 429) + return status == 429 or not 400 <= status < 500 return True @@ -168,58 +144,9 @@ _DOWNLOAD_USER_AGENT = ( ) -async def _stream_download_to_file( - client, url: str, destination: Path, max_bytes: int, *, headers: dict, media_label: str = "Image", -) -> Path: - """Stream a GET to *destination* via a temp file with a running size cap. - - The body is never fully buffered; Content-Length gives an early reject but - servers can omit or lie, so the streaming cap is authoritative. The temp file - is atomically moved onto *destination* on success, deleted on failure. - """ - from utils import atomic_replace - - async with client.stream("GET", url, headers=headers) as response: - response.raise_for_status() - - cl = response.headers.get("content-length") - if cl: - try: - declared_size = int(cl) - except ValueError: - declared_size = None - if declared_size is not None and declared_size > max_bytes: - raise ValueError(f"{media_label} too large ({declared_size} bytes, max {max_bytes})") - - blocked = check_website_access(str(response.url)) - if blocked: - raise PermissionError(blocked["message"]) - - tmp_destination = destination.with_name(f".{destination.name}.{uuid.uuid4().hex}.tmp") - bytes_written = 0 - try: - with tmp_destination.open("wb") as f: - async for chunk in response.aiter_bytes(): - if not chunk: - continue - bytes_written += len(chunk) - if bytes_written > max_bytes: - raise ValueError(f"{media_label} too large ({bytes_written} bytes, max {max_bytes})") - f.write(chunk) - atomic_replace(tmp_destination, destination) - except Exception: - try: - tmp_destination.unlink(missing_ok=True) - except OSError: - logger.debug("Could not delete partial download: %s", tmp_destination, exc_info=True) - raise - - return destination - - async def _ssrf_redirect_guard(response): - """Re-validate each redirect target (a public URL 302ing to 169.254.169.254 would - otherwise bypass the pre-flight check). Async because httpx.AsyncClient awaits hooks.""" + """Re-validate each redirect target (a public URL 302ing to 169.254.169.254 would otherwise + bypass the pre-flight check). Async because httpx.AsyncClient awaits hooks.""" from tools.url_safety import async_is_safe_url, redirect_target_from_response redirect_url = redirect_target_from_response(response) if redirect_url and not await async_is_safe_url(redirect_url): @@ -228,16 +155,12 @@ async def _ssrf_redirect_guard(response): async def _download_media( url: str, destination: Path, max_retries: int, *, - media_label: str, accept: str, max_bytes: int, timeout: float, retry_all: bool, -) -> Path: - """Shared SSRF-safe streaming download with exponential backoff (2s/4s/8s). - - ``retry_all=False`` (images) only retries transient errors per - :func:`_is_retryable_download_error` — a 404/403 never succeeds on retry. - ``retry_all=True`` (video) keeps the legacy retry-everything behavior. - """ + media_label: str, accept: str, max_bytes: int, timeout: float, retry_all: bool) -> Path: + """SSRF-safe streaming download with exponential backoff (2s/4s/8s). ``retry_all=False`` (images) + retries only :func:`_is_retryable_download_error` errors — a 404/403 never succeeds on retry.""" + from utils import atomic_replace + from tools.url_safety import create_ssrf_safe_async_client destination.parent.mkdir(parents=True, exist_ok=True) - last_error = None for attempt in range(max_retries): try: @@ -245,23 +168,53 @@ async def _download_media( if blocked: raise PermissionError(blocked["message"]) - from tools.url_safety import create_ssrf_safe_async_client - # follow_redirects for CDNs; the client validates DNS at connect # time and the hook re-validates each redirect target. async with create_ssrf_safe_async_client( timeout=timeout, follow_redirects=True, event_hooks={"response": [_ssrf_redirect_guard]}, - ) as client: - await _stream_download_to_file( - client, url, destination, max_bytes, - headers={"User-Agent": _DOWNLOAD_USER_AGENT, "Accept": accept}, - media_label=media_label, - ) + ) as client, client.stream( + "GET", url, headers={"User-Agent": _DOWNLOAD_USER_AGENT, "Accept": accept}, + ) as response: + response.raise_for_status() + + # Content-Length gives an early reject but servers can omit or lie, + # so the streaming cap below is authoritative. + cl = response.headers.get("content-length") + try: + declared_size = int(cl) if cl else None + except ValueError: + declared_size = None + if declared_size is not None and declared_size > max_bytes: + raise ValueError(f"{media_label} too large ({declared_size} bytes, max {max_bytes})") + blocked = check_website_access(str(response.url)) + if blocked: + raise PermissionError(blocked["message"]) + + # Stream to a temp file, atomically moved onto destination on success. + tmp_destination = destination.with_name(f".{destination.name}.{uuid.uuid4().hex}.tmp") + bytes_written = 0 + try: + with tmp_destination.open("wb") as f: + async for chunk in response.aiter_bytes(): + if not chunk: + continue + bytes_written += len(chunk) + if bytes_written > max_bytes: + raise ValueError( + f"{media_label} too large ({bytes_written} bytes, max {max_bytes})" + ) + f.write(chunk) + atomic_replace(tmp_destination, destination) + except Exception: + try: + tmp_destination.unlink(missing_ok=True) + except OSError: + logger.debug("Could not delete partial download: %s", tmp_destination, exc_info=True) + raise return destination except Exception as e: last_error = e - final = attempt >= max_retries - 1 - if final or (not retry_all and not _is_retryable_download_error(e)): + if attempt >= max_retries - 1 or (not retry_all and not _is_retryable_download_error(e)): logger.error("%s download failed after %s attempt(s): %s", media_label, attempt + 1, str(e)[:100], exc_info=True) if not retry_all: @@ -273,13 +226,11 @@ async def _download_media( if not retry_all: logger.warning("Retrying in %ss...", wait_time) await asyncio.sleep(wait_time) - # Reaching here means max_retries was non-positive (or video exhausted retries). if last_error is not None: raise last_error raise RuntimeError( - f"_download_{media_label.lower()} exited retry loop without attempting (max_retries={max_retries})" - ) + f"_download_{media_label.lower()} exited retry loop without attempting (max_retries={max_retries})") async def _download_image(image_url: str, destination: Path, max_retries: int = 3) -> Path: @@ -287,23 +238,21 @@ async def _download_image(image_url: str, destination: Path, max_retries: int = return await _download_media( image_url, destination, max_retries, media_label="Image", accept="image/*,*/*;q=0.8", - max_bytes=_VISION_MAX_DOWNLOAD_BYTES, timeout=_VISION_DOWNLOAD_TIMEOUT, retry_all=False, - ) + max_bytes=_VISION_MAX_DOWNLOAD_BYTES, timeout=_VISION_DOWNLOAD_TIMEOUT, retry_all=False) def _image_to_base64_data_url(image_path: Path, mime_type: Optional[str] = None) -> str: """``data:;base64,...`` for a file (MIME from extension when not given).""" - encoded = base64.b64encode(image_path.read_bytes()).decode("ascii") - return f"data:{mime_type or _determine_mime_type(image_path)};base64,{encoded}" + mime = mime_type or _determine_mime_type(image_path) + return f"data:{mime};base64,{base64.b64encode(image_path.read_bytes()).decode('ascii')}" # Absolute hard ceiling for vision payloads (20 MB): no major provider accepts more. _MAX_BASE64_BYTES = 20 * 1024 * 1024 -# Proactive embed caps for conversation-history reuse: the native path bakes the -# data URL into the tool result, re-sent every later turn (a 4 MB embed cost -# ~100-260K billed tokens). Anthropic downsamples to a 1568px long edge anyway, -# so pixels past that cost wire bytes for no fidelity. +# Proactive embed caps for history reuse: the native path bakes the data URL into the tool +# result, re-sent every later turn (a 4 MB embed cost ~100-260K billed tokens). Anthropic +# downsamples to a 1568px long edge anyway, so pixels past that cost wire bytes for no fidelity. _EMBED_TARGET_BYTES = 256 * 1024 _EMBED_MAX_DIMENSION = 1568 @@ -328,44 +277,34 @@ def _build_scale_note(scale_info: Optional[dict], crop_offset: Optional[dict]) - if scale_info: ow, oh = scale_info["orig_width"], scale_info["orig_height"] nw, nh = scale_info["new_width"], scale_info["new_height"] - fx = ow / nw if nw else 1.0 - fy = oh / nh if nh else 1.0 - if f"{fx:.2f}" == f"{fy:.2f}": - factor_clause = f"multiply any coordinates you report by {fx:.2f} to map back to the original image." - else: - factor_clause = ( - f"multiply any x coordinates you report by {fx:.2f} and " - f"any y coordinates by {fy:.2f} to map back to the original image." - ) - parts.append(f"Image downscaled from {ow}x{oh} to {nw}x{nh} for vision; {factor_clause}") + fx, fy = (ow / nw if nw else 1.0), (oh / nh if nh else 1.0) + axes = (f"any coordinates you report by {fx:.2f}" if f"{fx:.2f}" == f"{fy:.2f}" + else f"any x coordinates you report by {fx:.2f} and any y coordinates by {fy:.2f}") + parts.append(f"Image downscaled from {ow}x{oh} to {nw}x{nh} for vision; " + f"multiply {axes} to map back to the original image.") if crop_offset: parts.append( f"Analysis was performed on a cropped region of the original " f"image starting at offset ({crop_offset['x']}, " f"{crop_offset['y']}); coordinates are relative to that crop " - f"origin — add the offset to map back to the full image." - ) + f"origin — add the offset to map back to the full image.") return " ".join(parts) if parts else None def _import_pillow_for_resize(): - """Return ``PIL.Image`` or None (Pillow is a lazy-installable soft dependency). - - ``prompt=False``: a blocking input() deadlocks the interactive CLI where - prompt_toolkit owns stdin; the install is already gated by security.allow_lazy_installs. - """ + """Return ``PIL.Image`` or None (Pillow is a lazy-installable soft dependency). ``prompt=False``: + a blocking input() deadlocks the CLI where prompt_toolkit owns stdin; the install is already + gated by security.allow_lazy_installs.""" try: from PIL import Image - return Image except ImportError: - pass - try: - from tools.lazy_deps import ensure as _ensure_dep - _ensure_dep("tool.vision", prompt=False) - from PIL import Image - return Image - except Exception: - return None + try: + from tools.lazy_deps import ensure as _ensure_dep + _ensure_dep("tool.vision", prompt=False) + from PIL import Image + except Exception: + return None + return Image def _resize_image_for_vision(image_path: Path, mime_type: Optional[str] = None, @@ -375,68 +314,55 @@ def _resize_image_for_vision(image_path: Path, mime_type: Optional[str] = None, force_jpeg: bool = False) -> str: """Base64 data URL, progressively downscaled with Pillow while over budget. - Halves dimensions (aspect-preserving, 64px floor) up to 4 times; JPEG also - walks a quality ladder (85/70/50) at each step. Without Pillow, or if it - still doesn't fit, returns the best attempt (or raw bytes) and lets the - caller apply the size check. - - ``max_dimension``: force a downscale above this long edge even when bytes - fit (Anthropic's 8000px cap is independent of bytes). ``force_jpeg``: - re-encode PNG input as JPEG when a resize is needed — PNG's only shrink - lever is halving dimensions, which destroys text legibility on dense - screenshots; history-reuse embeds opt in. Images under both caps return unchanged. + Halves dimensions (aspect-preserving, 64px floor) up to 4 times; JPEG also walks a + quality ladder (85/70/50) per step. Without Pillow, or if it still doesn't fit, returns + the best attempt (or raw bytes) and lets the caller apply the size check. + ``max_dimension``: force a downscale above this long edge even when bytes fit + (Anthropic's 8000px cap is independent of bytes). ``force_jpeg``: re-encode PNG as JPEG + when resizing — halving PNG dimensions destroys text legibility on dense screenshots. """ file_size = image_path.stat().st_size estimated_b64 = (file_size * 4) // 3 + 100 # base64 ~4/3 + data URL header - needs_resize_for_bytes = estimated_b64 > max_base64_bytes - needs_resize_for_dims = max_dimension is not None and _image_exceeds_dimension(image_path, max_dimension) - data_url = None - if not needs_resize_for_bytes and not needs_resize_for_dims: + if estimated_b64 <= max_base64_bytes and not ( + max_dimension is not None and _image_exceeds_dimension(image_path, max_dimension) + ): data_url = _image_to_base64_data_url(image_path, mime_type=mime_type) if len(data_url) <= max_base64_bytes: return data_url def _raw() -> str: return data_url or _image_to_base64_data_url(image_path, mime_type=mime_type) - Image = _import_pillow_for_resize() if Image is None: logger.info("Pillow not installed — cannot auto-resize oversized image") return _raw() # caller will raise the size error - logger.info("Image file is %.1f MB (estimated base64 %.1f MB, limit %.1f MB, max_dimension=%s), auto-resizing...", file_size / (1024 * 1024), estimated_b64 / (1024 * 1024), max_base64_bytes / (1024 * 1024), max_dimension) - - mime = mime_type or _determine_mime_type(image_path) # JPEG for photos (smaller), PNG for transparency — unless force_jpeg. - pil_format = "PNG" if (mime == "image/png" and not force_jpeg) else "JPEG" - out_mime = "image/png" if pil_format == "PNG" else "image/jpeg" - + is_png = (mime_type or _determine_mime_type(image_path)) == "image/png" and not force_jpeg + pil_format, out_mime = ("PNG", "image/png") if is_png else ("JPEG", "image/jpeg") try: img = Image.open(image_path) except Exception as exc: logger.info("Pillow cannot open image for resizing: %s", exc) return _raw() - # JPEG cannot encode alpha/palette modes (force_jpeg routes PNGs here). - if pil_format == "JPEG" and img.mode not in {"RGB", "L"}: - img = img.convert("RGB") - quality_steps = (85, 70, 50) if pil_format == "JPEG" else (None,) + # JPEG cannot encode alpha/palette modes (force_jpeg routes PNGs here). + if not is_png and img.mode not in {"RGB", "L"}: + img = img.convert("RGB") + quality_steps = (None,) if is_png else (85, 70, 50) orig_dims = prev_dims = (img.width, img.height) candidate = None def _record_scale(w: int, h: int) -> None: if scale_out is not None and (w, h) != orig_dims: scale_out.update(orig_width=orig_dims[0], orig_height=orig_dims[1], new_width=w, new_height=h) - for attempt in range(5): if attempt > 0: - # Halve, then re-derive the scale from whichever axis hit the 64px - # floor so both axes shrink by the same factor. - new_w = max(int(img.width * 0.5), 64) - new_h = max(int(img.height * 0.5), 64) + # Halve, then re-derive from whichever axis hit the 64px floor so both shrink equally. + new_w, new_h = max(int(img.width * 0.5), 64), max(int(img.height * 0.5), 64) if new_w == 64 and img.width > 0: new_h = max(int(img.height * (64 / img.width)), 64) elif new_h == 64 and img.height > 0: @@ -446,35 +372,29 @@ def _resize_image_for_vision(image_path: Path, mime_type: Optional[str] = None, img = img.resize((new_w, new_h), Image.LANCZOS) prev_dims = (new_w, new_h) logger.info("Resized to %dx%d (attempt %d)", new_w, new_h, attempt) - + dims_ok = max_dimension is None or max(img.width, img.height) <= max_dimension for q in quality_steps: buf = BytesIO() img.save(buf, format=pil_format, **({} if q is None else {"quality": q})) candidate = f"data:{out_mime};base64,{base64.b64encode(buf.getvalue()).decode('ascii')}" - dims_ok = max_dimension is None or max(img.width, img.height) <= max_dimension if len(candidate) <= max_base64_bytes and dims_ok: logger.info("Auto-resized image fits: %.1f MB (quality=%s, %dx%d)", len(candidate) / (1024 * 1024), q, img.width, img.height) _record_scale(img.width, img.height) return candidate - - if candidate is not None: - logger.warning("Auto-resize could not fit image under %.1f MB (best: %.1f MB)", - max_base64_bytes / (1024 * 1024), len(candidate) / (1024 * 1024)) - _record_scale(img.width, img.height) - return candidate - return _raw() + if candidate is None: + return _raw() + logger.warning("Auto-resize could not fit image under %.1f MB (best: %.1f MB)", + max_base64_bytes / (1024 * 1024), len(candidate) / (1024 * 1024)) + _record_scale(img.width, img.height) + return candidate -# --------------------------------------------------------------------------- -# Native fast path: a vision-capable main model gets the image bytes as a -# multimodal tool-result envelope (agent loop unwraps it into an OpenAI-style -# content list on the `tool` role); no aux LLM, no information loss. -# --------------------------------------------------------------------------- - -# Providers whose tool results accept image content: Anthropic Messages (and -# aggregators proxying Claude — assume support), OpenAI Chat/Responses. Gemini -# is gated on model: only 3.x supports multimodal functionResponse. +# Native fast path: a vision-capable main model gets the image bytes as a multimodal +# tool-result envelope (the agent loop unwraps it into an OpenAI-style content list on the +# `tool` role); no aux LLM, no information loss. Providers whose tool results accept image +# content: Anthropic Messages (and aggregators proxying Claude — assume support), OpenAI +# Chat/Responses. Gemini is gated on model: only 3.x supports multimodal functionResponse. _TOOL_RESULT_MEDIA_PROVIDERS = frozenset({ "openrouter", "nous", "vertex", "bedrock", "anthropic-vertex", "google-vertex", "anthropic", "claude", "anthropic-direct", @@ -484,22 +404,16 @@ _GEMINI_PROVIDERS = frozenset({"google", "gemini", "google-gemini", "google-vert def _supports_media_in_tool_results(provider: str, model: str) -> bool: - """Whether provider+model accepts image content inside a tool-result message. - - Unknown providers are conservatively False (caller falls back to the aux-LLM - text path) unless their ``ProviderProfile`` declares ``supports_vision``. - """ - if not isinstance(provider, str): - return False - p = provider.strip().lower() + """Whether provider+model accepts image content inside a tool-result message. Unknown + providers are False (caller falls back to aux-LLM text) unless their ``ProviderProfile`` + declares ``supports_vision``.""" + p = provider.strip().lower() if isinstance(provider, str) else "" if not p: return False if p in _TOOL_RESULT_MEDIA_PROVIDERS: return True if p in _GEMINI_PROVIDERS: - if not isinstance(model, str): - return False - m = model.strip().lower() + m = model.strip().lower() if isinstance(model, str) else "" return any(tag in m for tag in ("gemini-3", "gemini-pro-3", "gemini-flash-3")) try: from providers import get_provider_profile @@ -510,14 +424,13 @@ def _supports_media_in_tool_results(provider: str, model: str) -> bool: def _should_use_native_vision_fast_path() -> bool: - """True when image routing resolves to ``native`` AND the provider accepts - images in tool results, or the user set the ``model.supports_vision`` - override (escape hatch for custom/local providers). Any failure → False.""" + """True when image routing resolves to ``native`` AND the provider accepts images in tool + results, or the user set the ``model.supports_vision`` override (escape hatch for + custom/local providers). Any failure → False.""" try: from agent.auxiliary_client import _read_main_provider, _read_main_model from agent.image_routing import decide_image_input_mode, _lookup_supports_vision from hermes_cli.config import load_config - provider = _read_main_provider() model = _read_main_model() cfg = load_config() @@ -525,49 +438,34 @@ def _should_use_native_vision_fast_path() -> bool: return False return ( _supports_media_in_tool_results(provider, model) - or _lookup_supports_vision(provider, model, cfg) is True - ) + or _lookup_supports_vision(provider, model, cfg) is True) except Exception as exc: logger.debug("Native vision fast-path check failed: %s", exc) return False def _build_native_vision_tool_result( - image_url: str, question: str, image_data_url: str, image_size_bytes: int, scale_note: Optional[str] = None, + image_url: str, question: str, image_data_url: str, image_size_bytes: int, + scale_note: Optional[str] = None, ) -> Dict[str, Any]: - """Multimodal tool-result envelope (``_multimodal`` + ``content`` list). - - The text part is intentionally minimal — the model already has the question - in context. ``text_summary`` is the fallback for providers without multimodal tool results. - """ + """Multimodal tool-result envelope. The text part is intentionally minimal (the model already + has the question); ``text_summary`` is the fallback for providers without multimodal tool results.""" text_part = ( "Image loaded into your context — you can see it natively now. " - "Use your built-in vision to answer the user." - ) + "Use your built-in vision to answer the user.") if isinstance(question, str) and question.strip(): text_part += f"\n\nQuestion: {question.strip()}" if scale_note: text_part += f"\n\nNote: {scale_note}" - - summary = ( - f"Image attached natively for the main model " - f"({image_size_bytes / 1024:.1f} KB). " - "Answer using built-in vision." - ) - return { "_multimodal": True, "content": [ {"type": "text", "text": text_part}, - {"type": "image_url", "image_url": {"url": image_data_url}}, - ], - "text_summary": summary, - "meta": { - "image_url": image_url[:200], - "size_bytes": image_size_bytes, - "native_vision": True, - }, - } + {"type": "image_url", "image_url": {"url": image_data_url}}], + "text_summary": ( + f"Image attached natively for the main model ({image_size_bytes / 1024:.1f} KB). " + "Answer using built-in vision."), + "meta": {"image_url": image_url[:200], "size_bytes": image_size_bytes, "native_vision": True}} def _unlink_quietly(path: Optional[Path]) -> None: @@ -582,39 +480,31 @@ class _ImagePrepError(ValueError): """Raised by :func:`_prepare_image`; the message is user-facing.""" -class _PreparedImage: +class _PreparedImage(NamedTuple): """Temp image ready to encode; ``path`` is owned by the caller (delete it).""" - __slots__ = ("path", "mime", "size_bytes", "crop_offset") - - def __init__(self, path: Path, mime: Optional[str], size_bytes: int, crop_offset: dict): - self.path, self.mime, self.size_bytes, self.crop_offset = path, mime, size_bytes, crop_offset + path: Path + mime: Optional[str] + size_bytes: int + crop_offset: dict async def _prepare_image( image_url: str, task_id: Optional[str], region: Optional[list], *, validate_decode: bool, ) -> _PreparedImage: """Resolve → materialize → normalize → (validate) → (crop). Raises ``_ImagePrepError``. - - Unsupported formats (SVG, BMP) are converted to PNG BEFORE encoding — an - unsupported media_type baked into immutable history would 400 on every - resume. The crop runs BEFORE any downscale so the region keeps the full - resolution budget. Blocking rasterizer/Pillow work is offloaded; on error - no temp file is left behind. - """ + Unsupported formats (SVG, BMP) become PNG BEFORE encoding — an unsupported media_type baked + into immutable history would 400 on every resume. The crop runs BEFORE any downscale so the + region keeps the full resolution budget. On error no temp file is left.""" from tools.image_source import ImageResolutionError, ResolveContext, resolve_image_source - try: resolved = await resolve_image_source(image_url, ResolveContext(task_id=task_id)) except ImageResolutionError as exc: raise _ImagePrepError(str(exc)) from exc - temp_dir = get_hermes_dir("cache/vision", "temp_vision_images") temp_dir.mkdir(parents=True, exist_ok=True) path = temp_dir / f"temp_image_{uuid.uuid4()}.img" await asyncio.to_thread(path.write_bytes, resolved.data) - mime = resolved.mime - size_bytes = len(resolved.data) - crop_offset: dict = {} + mime, size_bytes, crop_offset = resolved.mime, len(resolved.data), {} try: normalized_path, mime, norm_err = await asyncio.to_thread(_normalize_to_supported_image, path, mime) if norm_err or normalized_path is None: @@ -623,25 +513,19 @@ async def _prepare_image( _unlink_quietly(path) path = normalized_path size_bytes = path.stat().st_size - if validate_decode: decode_error = await _run_encode_on_cpu_executor( _validate_raster_image_decodable, path, - _VISION_MAX_VALIDATED_FRAME_COUNT, _VISION_MAX_VALIDATED_AGGREGATE_PIXELS, - ) + _VISION_MAX_VALIDATED_FRAME_COUNT, _VISION_MAX_VALIDATED_AGGREGATE_PIXELS) if decode_error: raise _ImagePrepError(decode_error) - if region is not None: cropped_path, cropped_mime, crop_err = await asyncio.to_thread( - _crop_image_region, path, region, offset_out=crop_offset, - ) + _crop_image_region, path, region, offset_out=crop_offset) if crop_err or cropped_path is None: raise _ImagePrepError(crop_err or "Region crop failed.") _unlink_quietly(path) - path = cropped_path - mime = cropped_mime - size_bytes = path.stat().st_size + path, mime, size_bytes = cropped_path, cropped_mime, cropped_path.stat().st_size except BaseException: _unlink_quietly(path) raise @@ -650,13 +534,9 @@ async def _prepare_image( def _too_large_message(image_data_url: str) -> str: return ( - f"Image too large for vision API: base64 payload is " - f"{len(image_data_url) / (1024 * 1024):.1f} MB " - f"(limit {_MAX_BASE64_BYTES / (1024 * 1024):.0f} MB) " - f"even after resizing. Install Pillow " - f"(`pip install Pillow`) for better auto-resize, " - f"or compress the image manually." - ) + f"Image too large for vision API: base64 payload is {len(image_data_url) / (1024 * 1024):.1f} MB " + f"(limit {_MAX_BASE64_BYTES / (1024 * 1024):.0f} MB) even after resizing. Install Pillow " + f"(`pip install Pillow`) for better auto-resize, or compress the image manually.") async def _resize_prepared(prepared: _PreparedImage, scale_info: dict, **kwargs) -> str: @@ -669,51 +549,37 @@ async def _resize_prepared(prepared: _PreparedImage, scale_info: dict, **kwargs) async def _vision_analyze_native( image_url: str, question: str, task_id: Optional[str] = None, region: Optional[list] = None, ) -> Any: - """Fast path for vision-capable main models. - - Returns a ``_multimodal`` envelope dict on success, or a JSON error string - (the normal tool-result contract) on failure. - """ + """Fast path for vision-capable main models: a ``_multimodal`` envelope dict on success, + or a JSON error string (the normal tool-result contract) on failure.""" if not isinstance(image_url, str) or not image_url.strip(): return tool_error("image_url is required", success=False) - prepared: Optional[_PreparedImage] = None try: from tools.interrupt import is_interrupted if is_interrupted(): return tool_error("Interrupted", success=False) - try: prepared = await _prepare_image(image_url, task_id, region, validate_decode=True) except _ImagePrepError as exc: return tool_error(str(exc), success=False) - image_data_url = await _run_encode_on_cpu_executor( - _image_to_base64_data_url, prepared.path, mime_type=prepared.mime, - ) - - # Proactive embed cap: this image is re-sent on every later turn, so - # resize DOWN to the history-reuse target whenever the byte or long-edge - # cap is exceeded, not just at the 20 MB hard ceiling. + _image_to_base64_data_url, prepared.path, mime_type=prepared.mime) + # Proactive embed cap: this image is re-sent on every later turn, so resize DOWN to the + # history-reuse target whenever the byte or long-edge cap is exceeded, not just at 20 MB. _scale_info: dict = {} - _over_dims = await _run_encode_on_cpu_executor(_image_exceeds_dimension, prepared.path, _EMBED_MAX_DIMENSION) + _over_dims = await _run_encode_on_cpu_executor( + _image_exceeds_dimension, prepared.path, _EMBED_MAX_DIMENSION) if len(image_data_url) > _EMBED_TARGET_BYTES or _over_dims: image_data_url = await _resize_prepared( prepared, _scale_info, - max_base64_bytes=_EMBED_TARGET_BYTES, max_dimension=_EMBED_MAX_DIMENSION, force_jpeg=True, - ) + max_base64_bytes=_EMBED_TARGET_BYTES, max_dimension=_EMBED_MAX_DIMENSION, force_jpeg=True) # Reject rather than embed a session-wedging payload. if len(image_data_url) > _MAX_BASE64_BYTES: return tool_error(_too_large_message(image_data_url), success=False) - return _build_native_vision_tool_result( - image_url=image_url, - question=question, - image_data_url=image_data_url, + image_url=image_url, question=question, image_data_url=image_data_url, image_size_bytes=prepared.size_bytes, - scale_note=_build_scale_note(_scale_info or None, prepared.crop_offset or None), - ) - + scale_note=_build_scale_note(_scale_info or None, prepared.crop_offset or None)) except Exception as exc: logger.warning("Native vision fast path failed: %s", exc) return tool_error(f"Native vision failed: {exc}", success=False) @@ -726,40 +592,28 @@ async def _vision_analyze_native( def _aux_call_kwargs(messages: list, model: Optional[str], default_timeout: float, *, min_timeout: Optional[float] = None) -> dict: """``async_call_llm`` kwargs with ``auxiliary.vision.timeout`` / ``.temperature`` from config. - - Local vision models (llama.cpp, ollama) can take well over 30s, hence the - generous defaults (temperature 0.1); ``min_timeout`` lets video enforce a floor. - """ + Local vision models (llama.cpp, ollama) can take well over 30s, hence generous defaults + (temperature 0.1); ``min_timeout`` lets video enforce a floor.""" timeout, temperature = default_timeout, 0.1 try: - _vision_cfg = _cfg_auxiliary("vision", default={}) - _vt = _vision_cfg.get("timeout") - if _vt is not None: - timeout = float(_vt) if min_timeout is None else max(float(_vt), min_timeout) - _vtemp = _vision_cfg.get("temperature") - if _vtemp is not None: - temperature = float(_vtemp) + _vision_cfg = _cfg_auxiliary("vision", default={}) or {} + if _vision_cfg.get("timeout") is not None: + timeout = max(float(_vision_cfg["timeout"]), float("-inf") if min_timeout is None else min_timeout) + if _vision_cfg.get("temperature") is not None: + temperature = float(_vision_cfg["temperature"]) except Exception: pass - call_kwargs = {"task": "vision", "messages": messages, "temperature": temperature, "timeout": timeout} - if model: - call_kwargs["model"] = model - return call_kwargs + return {"task": "vision", "messages": messages, "temperature": temperature, "timeout": timeout, + **({"model": model} if model else {})} def _media_messages(user_prompt: str, part_type: str, data_url: str) -> list: """Single user message: text + one ``image_url``/``video_url`` data-URL part.""" - return [{ - "role": "user", - "content": [ - {"type": "text", "text": user_prompt}, - {"type": part_type, part_type: {"url": data_url}}, - ], - }] + return [{"role": "user", "content": [ + {"type": "text", "text": user_prompt}, {"type": part_type, part_type: {"url": data_url}}]}] -# Error-message classification for the aux-LLM paths: first matching hint set -# wins (order matters — billing before capability before size/format). +# Aux-LLM error classification: first matching hint set wins (billing → capability → size/format). _BILLING_HINTS = ("402", "insufficient", "payment required", "credits", "billing") _IMAGE_ERROR_RULES = ( (_BILLING_HINTS, @@ -789,53 +643,19 @@ _VIDEO_ERROR_RULES = ( # kind -> (debug tool name, error rules) _ANALYSIS_KINDS = { "image": ("vision_analyze_tool", _IMAGE_ERROR_RULES), - "video": ("video_analyze_tool", _VIDEO_ERROR_RULES), -} - - -def _classify_analysis_error(e: Exception, rules, fallback: str, **fmt) -> str: - err_str = str(e).lower() - for hints, template in rules: - if any(hint in err_str for hint in hints): - return template.format(e=e, **fmt) - return fallback.format(e=e) + "video": ("video_analyze_tool", _VIDEO_ERROR_RULES)} def _debug_call_data(kind: str, source: str, user_prompt: str, model) -> dict: + prompt = user_prompt[:200] + "..." if len(user_prompt) > 200 else user_prompt return { - "parameters": { - f"{kind}_url": source, - "user_prompt": user_prompt[:200] + "..." if len(user_prompt) > 200 else user_prompt, - "model": model, - }, - "error": None, - "success": False, - "analysis_length": 0, - "model_used": model, - f"{kind}_size_bytes": 0, - } - - -def _finish_analysis(tool_name: str, debug_call_data: dict, result: dict) -> str: - _debug.log_call(tool_name, debug_call_data) - _debug.save() - return json.dumps(result, indent=2, ensure_ascii=False) - - -def _cleanup_temp_media(path: Optional[Path], label: str) -> None: - if path and path.exists(): - try: - path.unlink() - logger.debug("Cleaned up temporary %s file", label) - except Exception as cleanup_error: - logger.warning("Could not delete temporary file: %s", cleanup_error, exc_info=True) + "parameters": {f"{kind}_url": source, "user_prompt": prompt, "model": model}, + "error": None, "success": False, "analysis_length": 0, "model_used": model, f"{kind}_size_bytes": 0} async def _call_vision_llm(call_kwargs: dict, empty_log: str, response=None): """Aux vision LLM analysis text, retrying once on empty content (reasoning-only response). - - ``response``: an already-made first call (image path retries it on size errors itself). - """ + ``response``: an already-made first call (the image path handles size-error retries itself).""" _load_auxiliary_client() if response is None: response = await async_call_llm(**call_kwargs) @@ -848,97 +668,80 @@ async def _call_vision_llm(call_kwargs: dict, empty_log: str, response=None): async def _run_analysis( kind: str, source: str, user_prompt: str, model: Optional[str], - stage: Callable[[str, dict, list], Awaitable[tuple]], -) -> str: - """Shared aux-LLM analysis skeleton for image/video: interrupt check → ``stage`` → JSON result. + stage: Callable[[str, dict, list], Awaitable[tuple]]) -> str: + """Aux-LLM analysis skeleton for image/video: interrupt check → ``stage`` → JSON result. - ``stage(user_prompt, debug_call_data, temp_paths)`` prepares the media and - returns ``(analysis, scale_note)``; temp files it appends to ``temp_paths`` - are deleted in ``finally`` (also on error). Returns JSON - ``{"success": bool, "analysis": str}`` (``analysis`` carries the error - explanation on failure). + ``stage(user_prompt, debug_call_data, temp_paths)`` returns ``(analysis, scale_note)``; temp + files it appends to ``temp_paths`` are deleted in ``finally``. Returns JSON + ``{"success": bool, "analysis": str}`` (``analysis`` carries the error explanation on failure). """ tool_name, rules = _ANALYSIS_KINDS[kind] if not isinstance(user_prompt, str): user_prompt = str(user_prompt) if user_prompt is not None else "" debug_call_data = _debug_call_data(kind, source, user_prompt, model) temp_paths: list = [] + + def finish(result: dict) -> str: + _debug.log_call(tool_name, debug_call_data) + _debug.save() + return json.dumps(result, indent=2, ensure_ascii=False) + try: from tools.interrupt import is_interrupted if is_interrupted(): return tool_error("Interrupted", success=False) - logger.info("Analyzing %s: %s", kind, source[:60]) logger.info("User prompt: %s", user_prompt[:100]) - analysis, scale_note = await stage(user_prompt, debug_call_data, temp_paths) - analysis_length = len(analysis) if analysis else 0 logger.info("%s analysis completed (%s characters)", kind.capitalize(), analysis_length) - analysis = analysis or f"There was a problem with the request and the {kind} could not be analyzed." - result = { - "success": True, - "analysis": f"[{scale_note}] {analysis}" if scale_note else analysis, - } + result = {"success": True, "analysis": f"[{scale_note}] {analysis}" if scale_note else analysis} if scale_note: result["scale_note"] = scale_note - debug_call_data["success"] = True - debug_call_data["analysis_length"] = analysis_length - return _finish_analysis(tool_name, debug_call_data, result) - + debug_call_data.update(success=True, analysis_length=analysis_length) + return finish(result) except Exception as e: error_msg = f"Error analyzing {kind}: {str(e)}" logger.error("%s", error_msg, exc_info=True) - analysis = _classify_analysis_error( - e, rules, - f"There was a problem with the request and the {kind} could not be analyzed. Error: {{e}}", - model=model, - ) + err_str = str(e).lower() + template = next( + (tpl for hints, tpl in rules if any(hint in err_str for hint in hints)), + f"There was a problem with the request and the {kind} could not be analyzed. Error: {{e}}") + analysis = template.format(e=e, model=model) debug_call_data["error"] = error_msg - return _finish_analysis(tool_name, debug_call_data, { - "success": False, - "error": error_msg, - "analysis": analysis, - }) - + return finish({"success": False, "error": error_msg, "analysis": analysis}) finally: for path in temp_paths: - _cleanup_temp_media(path, kind) + if path and path.exists(): + try: + path.unlink() + logger.debug("Cleaned up temporary %s file", kind) + except Exception as cleanup_error: + logger.warning("Could not delete temporary file: %s", cleanup_error, exc_info=True) async def vision_analyze_tool( - image_url: str, - user_prompt: str, - model: str = None, - task_id: Optional[str] = None, - region: Optional[list] = None, -) -> str: - """Describe an image (URL, local path, data: URL) with the auxiliary vision LLM. - - ``user_prompt`` is pre-formatted by the caller. Returns JSON - ``{"success": bool, "analysis": str}``. Temp images live under $HERMES_HOME/cache/vision/. - """ + image_url: str, user_prompt: str, model: str = None, + task_id: Optional[str] = None, region: Optional[list] = None) -> str: + """Describe an image (URL, local path, data: URL) with the auxiliary vision LLM. ``user_prompt`` + is pre-formatted by the caller. Temp images live under $HERMES_HOME/cache/vision/.""" async def stage(prompt: str, debug_call_data: dict, temp_paths: list) -> tuple: prepared = await _prepare_image(image_url, task_id, region, validate_decode=False) temp_paths.append(prepared.path) logger.info("Image ready (%.1f KB)", prepared.size_bytes / 1024) - # Send at full resolution first; on a size rejection, downscale and retry. logger.info("Converting image to base64...") image_data_url = await _run_encode_on_cpu_executor( _image_to_base64_data_url, prepared.path, mime_type=prepared.mime) logger.info("Image converted to base64 (%.1f KB)", len(image_data_url) / 1024) - _scale_info: dict = {} if len(image_data_url) > _MAX_BASE64_BYTES: image_data_url = await _resize_prepared(prepared, _scale_info) if len(image_data_url) > _MAX_BASE64_BYTES: raise ValueError(_too_large_message(image_data_url)) - debug_call_data["image_size_bytes"] = prepared.size_bytes messages = _media_messages(prompt, "image_url", image_data_url) - logger.info("Processing image with vision model...") call_kwargs = _aux_call_kwargs(messages, model, 120.0) _load_auxiliary_client() @@ -949,44 +752,33 @@ async def vision_analyze_tool( raise logger.info( "API rejected image (%.1f MB, likely too large); auto-resizing to ~%.0f MB and retrying...", - len(image_data_url) / (1024 * 1024), _RESIZE_TARGET_BYTES / (1024 * 1024), - ) + len(image_data_url) / (1024 * 1024), _RESIZE_TARGET_BYTES / (1024 * 1024)) image_data_url = await _resize_prepared(prepared, _scale_info) messages[0]["content"][1]["image_url"]["url"] = image_data_url response = await async_call_llm(**call_kwargs) - - analysis = await _call_vision_llm(call_kwargs, "Vision LLM returned empty content, retrying once", response) + analysis = await _call_vision_llm( + call_kwargs, "Vision LLM returned empty content, retrying once", response) return analysis, _build_scale_note(_scale_info or None, prepared.crop_offset or None) - return await _run_analysis("image", image_url, user_prompt, model, stage) def check_vision_requirements() -> bool: """True when ``call_llm(task="vision")`` could resolve a client. - Mirrors its runtime fallback chain: explicit ``auxiliary.vision.provider``, - then the auto chain (main provider → openrouter → nous) — without the auto - step the tool would vanish whenever the explicit name was unresolvable. - Probe mode skips real SDK client construction on the tool-gating path. + Mirrors its fallback chain: explicit ``auxiliary.vision.provider``, then auto (main + provider → openrouter → nous) — without the auto step the tool would vanish whenever + the explicit name was unresolvable. Probe mode skips real SDK client construction. """ try: from agent.auxiliary_client import aux_probe_mode, resolve_vision_provider_client - except ImportError: - return False - try: with aux_probe_mode(): - _provider, client, _model = resolve_vision_provider_client() - if client is not None: - return True - _provider, client, _model = resolve_vision_provider_client(provider="auto") - return client is not None + return any( + resolve_vision_provider_client(**kw)[1] is not None for kw in ({}, {"provider": "auto"}) + ) except Exception: return False -# --------------------------------------------------------------------------- -# Registry -# --------------------------------------------------------------------------- from tools.registry import registry, tool_error VISION_ANALYZE_SCHEMA = { @@ -1030,31 +822,22 @@ VISION_ANALYZE_SCHEMA = { def _configured_aux_model(sections: tuple, env_vars: tuple) -> Optional[str]: - """First non-empty ``auxiliary.
.model`` from config.yaml, else the - first non-empty env var (legacy override), else None.""" + """First non-empty ``auxiliary.
.model`` from config.yaml, else the first non-empty + env var (legacy override), else None.""" for section in sections: _vmodel = _cfg_auxiliary(section, "model") if _vmodel: - model = str(_vmodel).strip() - if model: - return model + if str(_vmodel).strip(): + return str(_vmodel).strip() break - for env_var in env_vars: - val = os.getenv(env_var, "").strip() - if val: - return val - return None + return next((v for v in (os.getenv(e, "").strip() for e in env_vars) if v), None) async def _handle_vision_analyze(args: Dict[str, Any], **kw: Any) -> str: - image_url = args.get("image_url", "") - question = args.get("question", "") - region = args.get("region") + image_url, question, region = args.get("image_url", ""), args.get("question", ""), args.get("region") task_id = kw.get("task_id") - - # No concurrency gate around the whole analysis — the CPU burst is bounded - # inside the encode/resize step, so multi-image fan-out keeps full request - # concurrency. Native fast path: main model sees the pixels directly. + # No concurrency gate around the whole analysis — the CPU burst is bounded inside the + # encode/resize step, so multi-image fan-out keeps full request concurrency. if _should_use_native_vision_fast_path(): logger.info("vision_analyze: native fast path") return await _vision_analyze_native(image_url, question, task_id=task_id, region=region) @@ -1062,8 +845,7 @@ async def _handle_vision_analyze(args: Dict[str, Any], **kw: Any) -> str: # Legacy path: aux LLM describes the image and we return its text. full_prompt = ( "Fully describe and explain everything about this image, then answer the " - f"following question:\n\n{question}" - ) + f"following question:\n\n{question}") model = _configured_aux_model(("vision",), ("AUXILIARY_VISION_MODEL",)) return await vision_analyze_tool(image_url, full_prompt, model, task_id=task_id, region=region) @@ -1075,14 +857,10 @@ registry.register( handler=_handle_vision_analyze, check_fn=check_vision_requirements, is_async=True, - emoji="👁️", -) + emoji="👁️") -# --------------------------------------------------------------------------- -# Video Analysis Tool -# --------------------------------------------------------------------------- - +# --- video_analyze -------------------------------------------------------- # Extension → MIME. avi/mkv fall back to mp4. _VIDEO_MIME_TYPES = { ".mp4": "video/mp4", @@ -1108,62 +886,36 @@ def _unsupported_video_format(suffix: str) -> str: def _video_to_base64_data_url(video_path: Path, mime_type: Optional[str] = None) -> str: - encoded = base64.b64encode(video_path.read_bytes()).decode("ascii") - mime = mime_type or _VIDEO_MIME_TYPES.get(video_path.suffix.lower(), "video/mp4") - return f"data:{mime};base64,{encoded}" - - -def _is_path_like_video_source(value: str) -> bool: - lowered = (value or "").strip().lower() - return bool(lowered) and not lowered.startswith(("http://", "https://", "data:")) - - -async def _materialize_video_from_terminal_backend(video_source: str, task_id: Optional[str]) -> Path: - """Read a path via the shared media resolver into a local temp video file. - - ``permitted=("video",)`` gives terminal-backend video reads the exact - pipeline vision_analyze uses: media-cache host reads, bounded in-sandbox - exec-read, lazy env bring-up, the credential-read guard, and the 50MB ingest cap. - """ - from tools.image_source import ImageResolutionError, ResolveContext, resolve_image_source - - source = video_source.removeprefix("file://") - suffix = Path(source).suffix.lower() - if suffix not in _VIDEO_MIME_TYPES: - raise ValueError(_unsupported_video_format(suffix)) - - try: - resolved = await resolve_image_source(video_source, ResolveContext(task_id=task_id), permitted=("video",)) - except ImageResolutionError as exc: - raise ValueError(f"Could not read video from terminal backend: {exc}") from exc - - temp_dir = get_hermes_dir("cache/video", "temp_video_files") - temp_dir.mkdir(parents=True, exist_ok=True) - temp_path = temp_dir / f"terminal_video_{uuid.uuid4()}{suffix}" - temp_path.write_bytes(resolved.data) - return temp_path - - -async def _download_video(video_url: str, destination: Path, max_retries: int = 3) -> Path: - """Download video with SSRF protection; every failure class is retried.""" - return await _download_media( - video_url, destination, max_retries, - media_label="Video", accept="video/*,*/*;q=0.8", - max_bytes=_MAX_VIDEO_BASE64_BYTES, timeout=60.0, retry_all=True, - ) + mime = mime_type or _detect_video_mime_type(video_path) or "video/mp4" + return f"data:{mime};base64,{base64.b64encode(video_path.read_bytes()).decode('ascii')}" async def _materialize_video(video_url: str, task_id: Optional[str], temp_paths: list) -> Path: - """Local video path for a terminal-backend path, local file, or HTTP(S) URL. - - Only files this function created are appended to ``temp_paths`` — never user-provided paths. - """ - local_path = Path(os.path.expanduser(video_url.removeprefix("file://"))) - - from tools.image_source import _is_local_terminal_backend - if not _is_local_terminal_backend() and _is_path_like_video_source(video_url): + """Local video path for a terminal-backend path, local file, or HTTP(S) URL. Only files created + here are appended to ``temp_paths`` — never user-provided paths. Terminal-backend reads use the + shared media resolver with ``permitted=("video",)`` — the exact pipeline vision_analyze uses + (media-cache host reads, bounded in-sandbox exec-read, credential-read guard, 50MB cap).""" + from tools.image_source import ( + ImageResolutionError, ResolveContext, _is_local_terminal_backend, resolve_image_source, + ) + source = video_url.removeprefix("file://") + local_path = Path(os.path.expanduser(source)) + lowered = (video_url or "").strip().lower() + path_like = bool(lowered) and not lowered.startswith(("http://", "https://", "data:")) + if not _is_local_terminal_backend() and path_like: logger.info("Reading video source via terminal backend: %s", video_url) - path = await _materialize_video_from_terminal_backend(video_url, task_id) + suffix = Path(source).suffix.lower() + if suffix not in _VIDEO_MIME_TYPES: + raise ValueError(_unsupported_video_format(suffix)) + try: + resolved = await resolve_image_source( + video_url, ResolveContext(task_id=task_id), permitted=("video",)) + except ImageResolutionError as exc: + raise ValueError(f"Could not read video from terminal backend: {exc}") from exc + temp_dir = get_hermes_dir("cache/video", "temp_video_files") + temp_dir.mkdir(parents=True, exist_ok=True) + path = temp_dir / f"terminal_video_{uuid.uuid4()}{suffix}" + path.write_bytes(resolved.data) temp_paths.append(path) return path if local_path.is_file(): @@ -1177,46 +929,38 @@ async def _materialize_video(video_url: str, task_id: Optional[str], temp_paths: raise PermissionError(blocked["message"]) path = get_hermes_dir("cache/video", "temp_video_files") / f"temp_video_{uuid.uuid4()}.mp4" temp_paths.append(path) - await _download_video(video_url, path) + # Video downloads retry every failure class (legacy behavior). + await _download_media( + video_url, path, 3, media_label="Video", accept="video/*,*/*;q=0.8", + max_bytes=_MAX_VIDEO_BASE64_BYTES, timeout=60.0, retry_all=True) return path raise ValueError("Invalid video source. Provide an HTTP/HTTPS URL or a valid local file path.") async def video_analyze_tool( - video_url: str, - user_prompt: str, - model: str = None, - task_id: Optional[str] = None, -) -> str: + video_url: str, user_prompt: str, model: str = None, task_id: Optional[str] = None) -> str: """Analyze a video via multimodal LLM. Returns JSON {success, analysis}.""" async def stage(prompt: str, debug_call_data: dict, temp_paths: list) -> tuple: temp_video_path = await _materialize_video(video_url, task_id, temp_paths) - video_size_bytes = temp_video_path.stat().st_size video_size_mb = video_size_bytes / (1024 * 1024) logger.info("Video ready (%.1f MB)", video_size_mb) - detected_mime = _detect_video_mime_type(temp_video_path) if not detected_mime: raise ValueError(_unsupported_video_format(temp_video_path.suffix)) - if video_size_bytes > _VIDEO_SIZE_WARN_BYTES: logger.warning("Video is %.1f MB — may be slow or rejected", video_size_mb) - video_data_url = _video_to_base64_data_url(temp_video_path, mime_type=detected_mime) if len(video_data_url) > _MAX_VIDEO_BASE64_BYTES: raise ValueError( f"Video too large for API: base64 payload is {len(video_data_url) / (1024 * 1024):.1f} MB " f"(limit {_MAX_VIDEO_BASE64_BYTES / (1024 * 1024):.0f} MB). " - f"Compress or trim the video and retry." - ) - + f"Compress or trim the video and retry.") debug_call_data["video_size_bytes"] = video_size_bytes messages = _media_messages(prompt, "video_url", video_data_url) call_kwargs = _aux_call_kwargs(messages, model, 180.0, min_timeout=180.0) analysis = await _call_vision_llm(call_kwargs, "Empty video response, retrying once") return analysis, None - return await _run_analysis("video", video_url, user_prompt, model, stage) @@ -1247,13 +991,11 @@ VIDEO_ANALYZE_SCHEMA = { def _handle_video_analyze(args: Dict[str, Any], **kw: Any) -> Awaitable[str]: - video_url = args.get("video_url", "") - question = args.get("question", "") + video_url, question = args.get("video_url", ""), args.get("question", "") full_prompt = ( "Fully describe and explain everything happening in this video, " "including visual content, motion, audio cues, text overlays, and scene " - f"transitions. Then answer the following question:\n\n{question}" - ) + f"transitions. Then answer the following question:\n\n{question}") model = _configured_aux_model(("video", "vision"), ("AUXILIARY_VIDEO_MODEL", "AUXILIARY_VISION_MODEL")) return video_analyze_tool(video_url, full_prompt, model, task_id=kw.get("task_id")) @@ -1265,5 +1007,4 @@ registry.register( handler=_handle_video_analyze, check_fn=check_vision_requirements, is_async=True, - emoji="🎬", -) + emoji="🎬") diff --git a/tools/vision_tools_image_prep.py b/tools/vision_tools_image_prep.py index 2c67d93e58..908c1ef185 100644 --- a/tools/vision_tools_image_prep.py +++ b/tools/vision_tools_image_prep.py @@ -1,9 +1,8 @@ """Image format detection, normalization and region cropping for vision tools. -Everything here runs BEFORE an image is base64-embedded. A vision tool result -is baked into immutable conversation history and re-sent every turn, so an -unsupported media type or corrupt bytes would wedge the session with a -non-retryable 400 on every resume — normalization must happen up front. +Everything here runs BEFORE an image is base64-embedded: a vision tool result is +baked into immutable history and re-sent every turn, so an unsupported media type +or corrupt bytes would wedge the session with a non-retryable 400 on every resume. """ from __future__ import annotations @@ -30,8 +29,11 @@ _EXTENSION_MIME_TYPES = { # Media types the major vision providers (Anthropic in particular) accept # inline. SVG/BMP/TIFF are rejected with a non-retryable 400. -_ANTHROPIC_SUPPORTED_MEDIA_TYPES = frozenset( - {"image/jpeg", "image/png", "image/gif", "image/webp"} +_ANTHROPIC_SUPPORTED_MEDIA_TYPES = frozenset({"image/jpeg", "image/png", "image/gif", "image/webp"}) + + +_MAGIC_MIME_TYPES = ( + (b"\xff\xd8\xff", "image/jpeg"), ((b"GIF87a", b"GIF89a"), "image/gif"), (b"BM", "image/bmp"), ) @@ -41,17 +43,12 @@ def _determine_mime_type(image_path: Path) -> str: def _detect_image_mime_type_from_bytes(data: bytes) -> Optional[str]: - """Magic-byte MIME sniff (authoritative; no extension trust). - - Returns ``None`` for anything without a recognized header — including SVG, - which has no magic bytes (the resolver sniffs `` Optional[str]: try: with Image.open(BytesIO(data)) as image: image.verify() + return "image/png" except Exception: return None - return "image/png" - if header.startswith(b"\xff\xd8\xff"): - return "image/jpeg" - if header.startswith((b"GIF87a", b"GIF89a")): - return "image/gif" - if header.startswith(b"BM"): - return "image/bmp" + for magic, mime in _MAGIC_MIME_TYPES: + if header.startswith(magic): + return mime if len(header) >= 12 and header[:4] == b"RIFF" and header[8:12] == b"WEBP": return "image/webp" return None def _supported_media_types() -> frozenset: - """Formats the ACTIVE main model's server can decode. - - The managed llama-server decodes with stb_image — no WebP — and an - undecodable image part fails SILENTLY (the model confabulates), so the set - is narrowed there and normalization converts those formats to PNG. - """ + """Formats the ACTIVE main model's server can decode. The managed llama-server decodes with + stb_image — no WebP — and an undecodable image part fails SILENTLY (the model confabulates), + so the set is narrowed there and normalization converts those formats to PNG.""" try: - from agent.auxiliary_client import _runtime_main_value - from hermes_cli.local_runtime.capabilities import ( - ACCEPTED_IMAGE_MIMES, - is_managed_provider, - ) - - if is_managed_provider( - str(_runtime_main_value("provider") or ""), - str(_runtime_main_value("base_url") or "")): + from agent.auxiliary_client import _runtime_main_value as _v + from hermes_cli.local_runtime.capabilities import ACCEPTED_IMAGE_MIMES, is_managed_provider + if is_managed_provider(str(_v("provider") or ""), str(_v("base_url") or "")): return ACCEPTED_IMAGE_MIMES - except Exception: # noqa: BLE001 — best-effort narrowing only + except Exception: # best-effort narrowing only pass return _ANTHROPIC_SUPPORTED_MEDIA_TYPES +def _nonempty_file(path: Path) -> bool: + return path.exists() and path.stat().st_size > 0 + + def _rasterize_svg_to_png(svg_path: Path, out_path: Path) -> bool: """Best-effort SVG → PNG via cairosvg, svglib+reportlab, rsvg-convert, inkscape (all soft deps).""" - def _ok() -> bool: - return out_path.exists() and out_path.stat().st_size > 0 - try: import cairosvg # type: ignore cairosvg.svg2png(url=str(svg_path), write_to=str(out_path)) - return _ok() + return _nonempty_file(out_path) except Exception: pass try: @@ -113,23 +99,18 @@ def _rasterize_svg_to_png(svg_path: Path, out_path: Path) -> bool: drawing = svg2rlg(str(svg_path)) if drawing is not None: renderPM.drawToFile(drawing, str(out_path), fmt="PNG") - return _ok() + return _nonempty_file(out_path) except Exception: pass import shutil import subprocess for cmd in ( ["rsvg-convert", "-o", str(out_path), str(svg_path)], - ["inkscape", str(svg_path), "--export-type=png", - f"--export-filename={out_path}"], - ): + ["inkscape", str(svg_path), "--export-type=png", f"--export-filename={out_path}"]): if shutil.which(cmd[0]): try: - subprocess.run( - cmd, check=True, capture_output=True, timeout=30, - stdin=subprocess.DEVNULL, - ) - if _ok(): + subprocess.run(cmd, check=True, capture_output=True, timeout=30, stdin=subprocess.DEVNULL) + if _nonempty_file(out_path): return True except Exception: continue @@ -137,58 +118,43 @@ def _rasterize_svg_to_png(svg_path: Path, out_path: Path) -> bool: def _normalize_to_supported_image( - image_path: Path, detected_mime: str -) -> tuple[Optional[Path], Optional[str], Optional[str]]: - """Ensure an image is in a provider-supported format. - - Returns ``(path, mime, error)``: the input unchanged when already - supported; ``(new_png_path, "image/png", None)`` after conversion — a temp - file the CALLER must clean up; ``(None, None, message)`` when impossible. - SVG is rasterized; other Pillow-readable rasters (BMP, TIFF) re-encode to PNG. - """ + image_path: Path, detected_mime: str) -> tuple[Optional[Path], Optional[str], Optional[str]]: + """Ensure an image is in a provider-supported format. Returns ``(path, mime, error)``: the input + unchanged when supported; ``(new_png_path, "image/png", None)`` after conversion — a temp file + the CALLER must clean up; ``(None, None, message)`` when impossible. SVG is rasterized; other + Pillow-readable rasters (BMP, TIFF) re-encode to PNG.""" if detected_mime in _supported_media_types(): return image_path, detected_mime, None - out_dir = get_hermes_dir("cache/vision", "temp_vision_images") out_dir.mkdir(parents=True, exist_ok=True) out_path = out_dir / f"converted_{uuid.uuid4()}.png" - if detected_mime == "image/svg+xml": if _rasterize_svg_to_png(image_path, out_path): return out_path, "image/png", None - return ( - None, - None, + return None, None, ( "This is an SVG, which vision models cannot read directly, and no " "SVG rasterizer is installed (tried cairosvg, svglib, rsvg-convert, " "inkscape). Convert the SVG to PNG first — e.g. open it in a browser " "and screenshot it, or install a rasterizer " - "(`pip install cairosvg`) — then re-run vision_analyze on the PNG.", - ) - + "(`pip install cairosvg`) — then re-run vision_analyze on the PNG.") try: from PIL import Image as _PILImage with _PILImage.open(image_path) as _img: if _img.mode not in ("RGB", "RGBA", "L"): _img = _img.convert("RGBA") _img.save(out_path, format="PNG") - if out_path.exists() and out_path.stat().st_size > 0: + if _nonempty_file(out_path): return out_path, "image/png", None except Exception as _exc: - logger.warning("Failed to normalize %s image to PNG: %s", - detected_mime, _exc) - return ( - None, - None, + logger.warning("Failed to normalize %s image to PNG: %s", detected_mime, _exc) + return None, None, ( f"Image format {detected_mime!r} is not supported by the vision API " f"and could not be converted to PNG (install Pillow for raster " - f"conversion). Convert it to PNG or JPEG and try again.", - ) + f"conversion). Convert it to PNG or JPEG and try again.") -# Full raster validation runs on untrusted images in a shared CPU executor: -# bound animated-image work by frame count AND total decoded area so a compact -# file cannot monopolize a worker with unbounded frames. +# Full raster validation runs on untrusted images in a shared CPU executor: bound animated +# work by frame count AND total decoded area so a compact file cannot monopolize a worker. _VISION_MAX_VALIDATED_FRAME_COUNT = 100 _VISION_MAX_VALIDATED_AGGREGATE_PIXELS = 100_000_000 @@ -196,17 +162,12 @@ _VISION_MAX_VALIDATED_AGGREGATE_PIXELS = 100_000_000 def _validate_raster_image_decodable( image_path: Path, max_frames: int = _VISION_MAX_VALIDATED_FRAME_COUNT, - max_pixels: int = _VISION_MAX_VALIDATED_AGGREGATE_PIXELS, -) -> Optional[str]: - """Return an error unless Pillow can fully decode every frame. - - Header sniffing and ``Image.open`` only inspect containers: a timed-out - download can look like a valid PNG with a truncated pixel stream. Without - Pillow the image passes unvalidated rather than rejecting everything. - """ + max_pixels: int = _VISION_MAX_VALIDATED_AGGREGATE_PIXELS) -> Optional[str]: + """Return an error unless Pillow can fully decode every frame. Header sniffing and ``Image.open`` + only inspect containers: a timed-out download can look like a valid PNG with a truncated pixel + stream. Without Pillow the image passes unvalidated rather than rejecting everything.""" try: - from PIL import Image as _PILImage - from PIL import ImageSequence as _PILImageSequence + from PIL import Image as _PILImage, ImageSequence as _PILImageSequence except ImportError: return None try: @@ -214,23 +175,19 @@ def _validate_raster_image_decodable( image.verify() with _PILImage.open(image_path) as image: validated_pixels = 0 - for frame_number, frame in enumerate( - _PILImageSequence.Iterator(image), start=1 - ): + for frame_number, frame in enumerate(_PILImageSequence.Iterator(image), start=1): if frame_number > max_frames: return ( "Image validation rejected animation: " f"frame {frame_number} exceeds the maximum " - f"{max_frames} validated frames." - ) + f"{max_frames} validated frames.") next_validated_pixels = validated_pixels + frame.width * frame.height if next_validated_pixels > max_pixels: return ( "Image validation rejected animation: aggregate decoded " f"pixel count would reach {next_validated_pixels} at frame " f"{frame_number}, exceeding the maximum " - f"{max_pixels}." - ) + f"{max_pixels}.") frame.load() validated_pixels = next_validated_pixels except Exception as exc: @@ -239,12 +196,9 @@ def _validate_raster_image_decodable( def _image_exceeds_dimension(image_path: Path, max_dimension: int) -> bool: - """True if the longest side exceeds ``max_dimension`` px. - - Anthropic enforces an 8000px per-side cap independently of the byte cap. - Returns False (no forced resize) without Pillow or on unreadable files — - a missing soft dependency must never break the embed path. - """ + """True if the longest side exceeds ``max_dimension`` px (Anthropic's 8000px per-side cap is + independent of bytes). False without Pillow or on unreadable files — a missing soft + dependency must never break the embed path.""" try: from PIL import Image as _PILImage with _PILImage.open(image_path) as _img: @@ -254,57 +208,39 @@ def _image_exceeds_dimension(image_path: Path, max_dimension: int) -> bool: def _crop_image_region( - image_path: Path, - region: Any, - offset_out: Optional[dict] = None, + image_path: Path, region: Any, offset_out: Optional[dict] = None ) -> tuple[Optional[Path], Optional[str], Optional[str]]: - """Crop to ``region`` = [x1, y1, x2, y2] (original-image pixels). - - Applied BEFORE downscaling so the crop gets the full resolution budget. - Coordinates clamp to the image bounds; a zero-area/inverted region is - rejected with an error naming the real dimensions. Returns - ``(cropped_temp_path, mime, None)`` — caller owns cleanup — or - ``(None, None, error)``. Ported from QwenLM/qwen-code zoom-image.ts (Apache-2.0). - """ + """Crop to ``region`` = [x1, y1, x2, y2] (original-image pixels), BEFORE downscaling so the crop + gets the full resolution budget. Coordinates clamp to the image bounds; a zero-area/inverted + region is rejected with an error naming the real dimensions. Returns ``(cropped_temp_path, + mime, None)`` — caller owns cleanup — or ``(None, None, error)``. + Ported from QwenLM/qwen-code zoom-image.ts (Apache-2.0).""" try: from PIL import Image except ImportError: return None, None, ( "region cropping requires Pillow (`pip install Pillow`); " - "retry without the region parameter." - ) - - if ( - not isinstance(region, (list, tuple)) - or len(region) != 4 - or not all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in region) - ): + "retry without the region parameter.") + if not (isinstance(region, (list, tuple)) and len(region) == 4 + and all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in region)): return None, None, ( "Invalid region: expected [x1, y1, x2, y2] as four numbers " - "(pixel coordinates in the original image)." - ) - + "(pixel coordinates in the original image).") try: with Image.open(image_path) as img: width, height = img.size x1, y1, x2, y2 = (int(v) for v in region) - cx1 = max(0, min(x1, width)) - cy1 = max(0, min(y1, height)) - cx2 = max(0, min(x2, width)) - cy2 = max(0, min(y2, height)) + cx1, cy1, cx2, cy2 = (max(0, min(v, b)) for v, b in zip((x1, y1, x2, y2), (width, height) * 2)) if cx2 <= cx1 or cy2 <= cy1: return None, None, ( f"Invalid region [{x1}, {y1}, {x2}, {y2}]: crops to zero " f"area after clamping to the image bounds. The image is " f"{width}x{height} px — pick x1 Date: Wed, 2 Sep 2026 23:30:19 -0700 Subject: [PATCH 09/10] refactor(tools): unify tts text packers, drop dead MAX_TEXT_LENGTH alias, compact docstrings --- tools/tts_tool.py | 82 ++++++++++------------------ tools/tts_tool_delivery.py | 104 ++++++++++++------------------------ tools/tts_tool_lifecycle.py | 44 +++++---------- tools/tts_tool_local.py | 23 +++----- tools/tts_tool_openai.py | 33 ++++-------- tools/tts_tool_plugins.py | 18 +++---- tools/tts_tool_providers.py | 55 ++++++------------- tools/tts_tool_speaker.py | 39 +++++--------- 8 files changed, 126 insertions(+), 272 deletions(-) diff --git a/tools/tts_tool.py b/tools/tts_tool.py index 023f95e5f5..5485725b6d 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_DIR def _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_DIR return _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: ``