Skip to content

The agent that grows with you

refactor(run_agent): extract VisionMessagePrepMixin and ReasoningParamsMixin

Teknium0ab2e9672c67
diff --git a/agent/reasoning_params.py b/agent/reasoning_params.py
new file mode 100644
index 00000000000..a753cf954cf
--- /dev/null
+++ b/agent/reasoning_params.py
@@ -0,0 +1,294 @@
+"""Provider reasoning-parameter policy for ``AIAgent``.
+
+When ``reasoning`` extra_body is safe to send, LM Studio / Ollama / GitHub Models capability probes,
+``reasoning_content`` echo families, and strict-API tool-call sanitising.
+Extracted from ``run_agent.py``; every method resolves through ``AIAgent``'s MRO unchanged.
+"""
+from typing import Optional
+
+from agent.lazy_forward import forward as _forward, forward_static as _forward_static
+from utils import base_url_host_matches
+
+
+class ReasoningParamsMixin:
+ """Reasoning-parameter gating and echo policy (see module docstring)."""
+
+ def _supports_reasoning_extra_body(self) -> bool:
+ """Return True when reasoning extra_body is safe to send for this route/model.
+
+ OpenRouter forwards unknown extra_body upstream and some routes 400 on ``reasoning``; gate to known
+ reasoning-capable families and direct Nous Portal.
+ """
+ if base_url_host_matches(self._base_url_lower, "nousresearch.com"):
+ return True
+ if base_url_host_matches(self._base_url_lower, "ai-gateway.vercel.sh"):
+ return True
+ if (
+ base_url_host_matches(self._base_url_lower, "models.github.ai")
+ or base_url_host_matches(self._base_url_lower, "githubcopilot.com")
+ ):
+ try:
+ from hermes_cli.models import github_model_reasoning_efforts
+
+ return bool(github_model_reasoning_efforts(self.model))
+ except Exception:
+ return False
+ if (self.provider or "").strip().lower() == "lmstudio":
+ opts = self._lmstudio_reasoning_options_cached()
+ # "off-only" (or absent) means no real reasoning capability.
+ return any(opt and opt != "off" for opt in opts)
+ # Ollama Cloud: /api/show capabilities are authoritative — emit reasoning_effort only for models
+ # declaring "thinking". Cached per (model, base_url).
+ if base_url_host_matches(self._base_url_lower, "ollama.com"):
+ return self._ollama_supports_thinking_cached()
+ if not self._is_openrouter_url():
+ return False
+ if base_url_host_matches(self._base_url_lower, "api.mistral.ai"):
+ return False
+
+ model = (self.model or "").lower()
+ # Live-catalog metadata first (OpenRouter /v1/models supported_parameters) — the static prefix
+ # allowlist repeatedly went stale one vendor at a time (#75386). Unknown falls back to the static
+ # list.
+ try:
+ from hermes_cli.models import (
+ openrouter_model_reasoning_capabilities,
+ warm_openrouter_reasoning_caps_async,
+ )
+ caps = openrouter_model_reasoning_capabilities(self.model)
+ if caps is None:
+ # Cache cold — warm in the background; never block this turn on HTTP.
+ warm_openrouter_reasoning_caps_async()
+ except Exception:
+ caps = None
+ if caps is not None:
+ return bool(caps.get("supports_reasoning"))
+ reasoning_model_prefixes = (
+ "deepseek/",
+ "anthropic/",
+ "openai/",
+ "x-ai/",
+ "google/gemini-2",
+ "google/gemma-4",
+ "qwen/qwen3",
+ "tencent/hy",
+ "xiaomi/",
+ )
+ return any(model.startswith(prefix) for prefix in reasoning_model_prefixes)
+
+ def _lmstudio_reasoning_options_cached(self) -> list[str]:
+ """Probe LM Studio's published reasoning ``allowed_options`` once per (model, base_url).
+
+ Needed for the supports-reasoning gate and to clamp ``reasoning_effort`` so toggle-style models don't
+ 400 on ``high``. Non-empty results cache permanently; empty ones (transient failure OR non-reasoning
+ model) cache with a 60s TTL to avoid a round-trip per turn while retrying soon.
+ """
+ import time as _time
+
+ cache = getattr(self, "_lm_reasoning_opts_cache", None)
+ if cache is None:
+ cache = self._lm_reasoning_opts_cache = {}
+ key = (self.model, self.base_url)
+ cached = cache.get(key)
+ if cached is not None:
+ opts, ts = cached
+ # Non-empty → permanent. Empty → 60s TTL.
+ if opts or (_time.monotonic() - ts) < 60:
+ return opts
+ try:
+ from hermes_cli.models import lmstudio_model_reasoning_options
+ opts = lmstudio_model_reasoning_options(
+ self.model, self.base_url, getattr(self, "api_key", ""),
+ )
+ except Exception:
+ opts = []
+ cache[key] = (opts, _time.monotonic())
+ return opts
+
+ def _ollama_supports_thinking_cached(self) -> bool:
+ """Probe Ollama's ``/api/show`` capabilities once per (model, base_url); True only if ``thinking`` is
+ declared.
+
+ True/False cache permanently; a probe failure (None) caches 60s so an outage neither suppresses
+ reasoning for the session nor round-trips every turn.
+ """
+ import time as _time
+
+ cache = getattr(self, "_ollama_thinking_cache", None)
+ if cache is None:
+ cache = self._ollama_thinking_cache = {}
+ key = (self.model, self.base_url)
+ cached = cache.get(key)
+ if cached is not None:
+ supported, ts = cached
+ # Definitive True/False → permanent. Unknown (None) → 60s TTL.
+ if supported is not None or (_time.monotonic() - ts) < 60:
+ return bool(supported)
+ try:
+ from hermes_cli.models import ollama_model_supports_thinking
+ supported = ollama_model_supports_thinking(
+ self.model, self.base_url, getattr(self, "api_key", "")
+ )
+ except Exception:
+ supported = None
+ cache[key] = (supported, _time.monotonic())
+ return bool(supported)
+
+ def _resolve_lmstudio_summary_reasoning_effort(self) -> Optional[str]:
+ """Resolve a safe top-level ``reasoning_effort`` for LM Studio.
+
+ The iteration-limit summary calls ``chat.completions.create()`` directly, bypassing the transport;
+ share the helper so effort resolution and clamping cannot drift.
+ """
+ from agent.lmstudio_reasoning import resolve_lmstudio_effort
+ return resolve_lmstudio_effort(
+ self.reasoning_config,
+ self._lmstudio_reasoning_options_cached(),
+ )
+
+ def _github_models_reasoning_extra_body(self) -> dict | None:
+ """Format reasoning payload for GitHub Models/OpenAI-compatible routes."""
+ try:
+ from hermes_cli.models import github_model_reasoning_efforts
+ except Exception:
+ return None
+
+ supported_efforts = github_model_reasoning_efforts(self.model)
+ if not supported_efforts:
+ return None
+
+ if self.reasoning_config and isinstance(self.reasoning_config, dict):
+ if self.reasoning_config.get("enabled") is False:
+ return None
+ requested_effort = str(
+ self.reasoning_config.get("effort", "medium")
+ ).strip().lower()
+ else:
+ requested_effort = "medium"
+
+ if requested_effort == "xhigh" and "xhigh" not in supported_efforts and "high" in supported_efforts:
+ requested_effort = "high"
+ elif requested_effort not in supported_efforts:
+ if requested_effort == "minimal" and "low" in supported_efforts:
+ requested_effort = "low"
+ elif "medium" in supported_efforts:
+ requested_effort = "medium"
+ else:
+ requested_effort = supported_efforts[0]
+
+ return {"effort": requested_effort}
+
+ _build_assistant_message = _forward("agent.chat_completion_helpers", "build_assistant_message")
+
+ def _needs_thinking_reasoning_pad(self) -> bool:
+ """Return True when the active provider enforces ``reasoning_content`` echo-back on tool-call replays.
+
+ DeepSeek thinking, Kimi/Moonshot thinking and Xiaomi MiMo thinking all 400 without it. Cached per
+ (provider, model, base_url) and invalidated by ``switch_model()`` / ``_try_activate_fallback()`` —
+ the loop calls this ~16× per turn and each miss re-runs several ``urlparse`` host matches.
+ """
+ key = (self.provider, self.model, getattr(self, "_base_url_lower", self.base_url))
+ cached = getattr(self, "_thinking_pad_cache", None)
+ if cached is not None and cached[0] == key:
+ return cached[1]
+ result = (
+ self._needs_deepseek_tool_reasoning()
+ or self._needs_kimi_tool_reasoning()
+ or self._needs_mimo_tool_reasoning()
+ or self._reasoning_echo_opt_in()
+ )
+ self._thinking_pad_cache = (key, result)
+ return result
+
+ def _reasoning_echo_opt_in(self) -> bool:
+ """True when the user opted in to ``reasoning_content`` echo-back for the *current* provider via
+ config.
+
+ Covers custom providers / gateways proxying thinking models that the host-based
+ ``_REASONING_ECHO_RULES`` miss. Per-active-provider: primary from ``model.reasoning_echo``, fallback
+ from the fallback entry's field, restored by ``restore_primary_runtime()`` — so falling back to a
+ strict provider still strips it.
+ """
+ return bool(getattr(self, "_reasoning_echo_flag", False))
+
+ @staticmethod
+ def _read_reasoning_echo_from_config() -> bool:
+ """Read ``model.reasoning_echo`` from config; False on any error."""
+ try:
+ from hermes_cli.config import load_config_readonly
+ return bool(
+ (load_config_readonly().get("model") or {}).get("reasoning_echo")
+ )
+ except Exception:
+ return False
+
+ def _needs_kimi_tool_reasoning(self) -> bool:
+ """Return True when the current provider is Kimi / Moonshot thinking mode (requires
+ ``reasoning_content`` echo).
+
+ Host-driven, not model-name-driven: aggregators re-exporting Kimi reject the echo (#17400). Rule
+ table: ``message_sanitization.reasoning_echo_family``.
+ """
+ from agent.message_sanitization import matches_reasoning_echo_family
+ return matches_reasoning_echo_family(
+ "kimi", self.provider, None, self.base_url
+ )
+
+ def _needs_deepseek_tool_reasoning(self) -> bool:
+ """Return True when the current provider is DeepSeek thinking mode (requires ``reasoning_content``
+ echo).
+
+ Omitting the echo on replayed assistant tool-call turns is an HTTP 400 (#15250). Rule table:
+ ``message_sanitization.reasoning_echo_family``.
+ """
+ from agent.message_sanitization import matches_reasoning_echo_family
+ return matches_reasoning_echo_family(
+ "deepseek", (self.provider or "").lower(), self.model, self.base_url
+ )
+
+ def _needs_mimo_tool_reasoning(self) -> bool:
+ """Return True when the current provider is Xiaomi MiMo thinking mode (requires ``reasoning_content``
+ echo).
+
+ Rule table: ``message_sanitization.reasoning_echo_family``.
+ """
+ from agent.message_sanitization import matches_reasoning_echo_family
+ return matches_reasoning_echo_family(
+ "mimo", (self.provider or "").lower(), self.model, self.base_url
+ )
+
+ _copy_reasoning_content_for_api = _forward("agent.agent_runtime_helpers", "copy_reasoning_content_for_api")
+
+ _reapply_reasoning_echo_for_provider = _forward("agent.agent_runtime_helpers", "reapply_reasoning_echo_for_provider")
+
+ @staticmethod
+ def _sanitize_tool_calls_for_strict_api(api_msg: dict, model: "str | None" = None) -> dict:
+ """Strip Codex Responses fields (call_id, response_item_id, extra_content) from tool_calls for strict
+ providers.
+
+ Strict Chat Completions APIs (Mistral, Fireworks) 400/422 on unknown fields. ``extra_content`` (Gemini
+ thought_signature) is kept only when the outgoing model is Gemini-family (it 400s without it). Builds
+ new dicts so the internal history retains the Codex fields for a later fallback.
+ """
+ tool_calls = api_msg.get("tool_calls")
+ if not isinstance(tool_calls, list):
+ return api_msg
+ from agent.transports.chat_completions import _model_consumes_thought_signature
+ _STRIP_KEYS = {"call_id", "response_item_id"}
+ if not _model_consumes_thought_signature(model):
+ _STRIP_KEYS = _STRIP_KEYS | {"extra_content"}
+ api_msg["tool_calls"] = [
+ {k: v for k, v in tc.items() if k not in _STRIP_KEYS}
+ if isinstance(tc, dict) else tc
+ for tc in tool_calls
+ ]
+ return api_msg
+
+ _sanitize_tool_call_arguments = _forward_static("agent.agent_runtime_helpers", "sanitize_tool_call_arguments")
+
+ def _should_sanitize_tool_calls(self) -> bool:
+ """Determine if tool_calls need sanitization (True for every non-Codex API).
+
+ Codex Responses fields (call_id, response_item_id) are not Chat Completions schema and 400 elsewhere.
+ """
+ return self.api_mode != "codex_responses"
diff --git a/agent/vision_message_prep.py b/agent/vision_message_prep.py
new file mode 100644
index 00000000000..c487e0b18c7
--- /dev/null
+++ b/agent/vision_message_prep.py
@@ -0,0 +1,465 @@
+"""Image-part handling for ``AIAgent`` API messages.
+
+Vision capability probes, non-vision text fallbacks (cached ``vision_analyze`` descriptions), tool-result
+image stripping, and provider quirks (Anthropic dot preservation, Qwen portal message shaping).
+Extracted from ``run_agent.py``; every method resolves through ``AIAgent``'s MRO unchanged.
+"""
+import logging
+import asyncio
+import base64
+import copy
+import hashlib
+import json
+import os
+import tempfile
+from pathlib import Path
+from typing import Any, List, Optional
+
+from agent.lazy_forward import forward_static as _forward_static
+from agent.tool_dispatch_helpers import _is_multimodal_tool_result, _multimodal_text_summary
+from utils import base_url_host_matches, base_url_hostname
+
+# Same logger name as the origin module so log records / caplog filters are unchanged.
+logger = logging.getLogger("run_agent")
+
+
+class VisionMessagePrepMixin:
+ """Vision probes + image-part fallbacks for outgoing messages (see module docstring)."""
+
+ @staticmethod
+ def _content_has_image_parts(content: Any) -> bool:
+ if not isinstance(content, list):
+ return False
+ for part in content:
+ if isinstance(part, dict) and part.get("type") in {"image_url", "input_image"}:
+ return True
+ return False
+
+ # 20 MB base64 ≈ 15 MB decoded — prevents OOM from an oversized data: URL in a shared gateway process.
+ _MAX_DATA_URL_BASE64_BYTES = 20 * 1024 * 1024
+
+ @staticmethod
+ def _materialize_data_url_for_vision(image_url: str) -> tuple[str, Optional[Path]]:
+ header, _, data = str(image_url or "").partition(",")
+ if len(data) > VisionMessagePrepMixin._MAX_DATA_URL_BASE64_BYTES:
+ logger.warning(
+ "data-URL payload too large (%d bytes), skipping", len(data)
+ )
+ return "", None
+ mime = "image/jpeg"
+ if header.startswith("data:"):
+ mime_part = header[len("data:"):].split(";", 1)[0].strip()
+ if mime_part.startswith("image/"):
+ mime = mime_part
+ suffix = {
+ "image/png": ".png",
+ "image/gif": ".gif",
+ "image/webp": ".webp",
+ "image/jpeg": ".jpg",
+ "image/jpg": ".jpg",
+ }.get(mime, ".jpg")
+ tmp = tempfile.NamedTemporaryFile(prefix="anthropic_image_", suffix=suffix, delete=False)
+ try:
+ with tmp:
+ tmp.write(base64.b64decode(data))
+ except Exception:
+ # delete=False means a corrupt/unsupported data URL would otherwise
+ # leak a zero-byte temp file on every failed materialization.
+ try:
+ os.unlink(tmp.name)
+ except OSError:
+ pass
+ raise
+ path = Path(tmp.name)
+ return str(path), path
+
+ def _describe_image_for_anthropic_fallback(self, image_url: str, role: str) -> str:
+ cache_key = hashlib.sha256(str(image_url or "").encode("utf-8")).hexdigest()
+ cached = self._anthropic_image_fallback_cache.get(cache_key)
+ if cached:
+ return cached
+
+ role_label = {
+ "assistant": "assistant",
+ "tool": "tool result",
+ }.get(role, "user")
+ analysis_prompt = (
+ "Describe everything visible in this image in thorough detail. "
+ "Include any text, code, UI, data, objects, people, layout, colors, "
+ "and any other notable visual information."
+ )
+
+ vision_source = str(image_url or "")
+ cleanup_path: Optional[Path] = None
+ if vision_source.startswith("data:"):
+ vision_source, cleanup_path = self._materialize_data_url_for_vision(vision_source)
+
+ description = ""
+ try:
+ from tools.vision_tools import vision_analyze_tool
+
+ result_json = asyncio.run(
+ vision_analyze_tool(image_url=vision_source, user_prompt=analysis_prompt)
+ )
+ result = json.loads(result_json) if isinstance(result_json, str) else {}
+ description = (result.get("analysis") or "").strip()
+ except Exception as e:
+ description = f"Image analysis failed: {e}"
+ finally:
+ if cleanup_path and cleanup_path.exists():
+ try:
+ cleanup_path.unlink()
+ except OSError:
+ pass
+
+ if not description:
+ description = "Image analysis failed."
+
+ note = f"[The {role_label} attached an image. Here's what it contains:\n{description}]"
+ if vision_source and not str(image_url or "").startswith("data:"):
+ note += (
+ f"\n[If you need a closer look, use vision_analyze with image_url: {vision_source}]"
+ )
+
+ self._anthropic_image_fallback_cache[cache_key] = note
+ return note
+
+ def _model_supports_vision(self) -> bool:
+ """Return True if the active provider+model reports native vision.
+
+ Resolution: ``model.supports_vision`` > ``providers.<p>.models.<m>.supports_vision`` > models.dev
+ lookup (see ``image_routing._supports_vision_override``). Custom/local models absent from models.dev
+ would otherwise be misclassified and have their images stripped.
+ """
+ try:
+ from hermes_cli.config import load_config
+ from agent.image_routing import _lookup_supports_vision
+ cfg = load_config()
+ provider = (getattr(self, "provider", "") or "").strip()
+ model = (getattr(self, "model", "") or "").strip()
+ return _lookup_supports_vision(provider, model, cfg) is True
+ except Exception:
+ return False
+
+ def _provider_supports_vision_tool_messages(self) -> bool:
+ """Return True if the active provider accepts list-type tool content.
+
+ Some providers (Xiaomi MiMo) accept multimodal user messages but 400 on list-type tool content;
+ reads the provider profile's ``supports_vision_tool_messages``.
+ """
+ try:
+ from providers import get_provider_profile
+ provider = (getattr(self, "provider", "") or "").strip()
+ profile = get_provider_profile(provider)
+ if profile is not None:
+ return getattr(profile, "supports_vision_tool_messages", True)
+ except Exception:
+ pass
+ return True # default: assume compatible
+
+ def _preprocess_anthropic_content(self, content: Any, role: str) -> Any:
+ if not self._content_has_image_parts(content):
+ return content
+
+ text_parts: List[str] = []
+ image_notes: List[str] = []
+ for part in content:
+ if isinstance(part, str):
+ if part.strip():
+ text_parts.append(part.strip())
+ continue
+ if not isinstance(part, dict):
+ continue
+
+ ptype = part.get("type")
+ if ptype in {"text", "input_text"}:
+ text = str(part.get("text", "") or "").strip()
+ if text:
+ text_parts.append(text)
+ continue
+
+ if ptype in {"image_url", "input_image"}:
+ image_data = part.get("image_url", {})
+ image_url = image_data.get("url", "") if isinstance(image_data, dict) else str(image_data or "")
+ if image_url:
+ image_notes.append(self._describe_image_for_anthropic_fallback(image_url, role))
+ else:
+ image_notes.append("[An image was attached but no image source was available.]")
+ continue
+
+ text = str(part.get("text", "") or "").strip()
+ if text:
+ text_parts.append(text)
+
+ prefix = "\n\n".join(note for note in image_notes if note).strip()
+ suffix = "\n".join(text for text in text_parts if text).strip()
+ if prefix and suffix:
+ return f"{prefix}\n\n{suffix}"
+ if prefix:
+ return prefix
+ if suffix:
+ return suffix
+ return "[A multimodal message was converted to text for Anthropic compatibility.]"
+
+ def _get_transport(self, api_mode: str = None):
+ """Return the cached transport for the given (or current) api_mode (lazy; None if unregistered)."""
+ mode = api_mode or self.api_mode
+ cache = getattr(self, "_transport_cache", None)
+ if cache is None:
+ cache = {}
+ self._transport_cache = cache
+ t = cache.get(mode)
+ if t is None:
+ from agent.transports import get_transport
+ t = get_transport(mode)
+ cache[mode] = t
+ return t
+
+ def _prepare_messages_for_non_vision_model(self, api_messages: list) -> list:
+ """Replace native image parts with cached vision_analyze text when the active model lacks vision.
+
+ Vision-capable models pass through unchanged (the provider adapter — including the Anthropic one —
+ handles image parts natively). The text fallback is the historically Anthropic-named preprocessor.
+ """
+ if not any(
+ isinstance(msg, dict) and self._content_has_image_parts(msg.get("content"))
+ for msg in api_messages
+ ):
+ return api_messages
+
+ if self._model_supports_vision():
+ return api_messages
+
+ transformed = copy.deepcopy(api_messages)
+ for msg in transformed:
+ if not isinstance(msg, dict):
+ continue
+ msg["content"] = self._preprocess_anthropic_content(
+ msg.get("content"),
+ str(msg.get("role", "user") or "user"),
+ )
+ return transformed
+
+ # Same transform for the Anthropic route (callers/tests patch this name independently).
+ _prepare_anthropic_messages_for_api = _prepare_messages_for_non_vision_model
+
+ def _tool_result_content_for_active_model(self, tool_name: str, result: Any) -> Any:
+ """Return the tool message content that is safe for the active model.
+
+ Text-only providers must not receive image parts: a rejected tool result becomes canonical history
+ and can make the next user turn fail before the agent can recover.
+ """
+ if not _is_multimodal_tool_result(result):
+ return result
+
+ content = result.get("content") or []
+ if not self._content_has_image_parts(content):
+ return content
+
+ if self._model_supports_vision():
+ # Vision on paper, but the provider rejects list-type tool content (or we already learned that
+ # in-session): short-circuit to a text summary.
+ if not self._provider_supports_vision_tool_messages():
+ logger.debug(
+ "Tool %s: provider %s does not accept list-type tool "
+ "content — sending text summary",
+ tool_name, getattr(self, "provider", ""),
+ )
+ return _multimodal_text_summary(result)
+ key = (
+ (getattr(self, "provider", "") or "").strip().lower(),
+ (getattr(self, "model", "") or "").strip(),
+ )
+ no_list = getattr(self, "_no_list_tool_content_models", None)
+ if no_list and key in no_list:
+ logger.debug(
+ "Tool %s: model %s/%s known to reject list-type tool "
+ "content this session — sending text summary",
+ tool_name, key[0], key[1],
+ )
+ return _multimodal_text_summary(result)
+ return content
+
+ summary = _multimodal_text_summary(result)
+ if tool_name == "computer_use":
+ return json.dumps({
+ "error": (
+ "computer_use returned screenshot/image content, but the active "
+ "model/provider does not support image input. Switch to a "
+ "vision-capable model for desktop computer use, or use browser "
+ "tools for browser tasks."
+ ),
+ "text_summary": summary,
+ })
+
+ logger.warning(
+ "Tool %s returned image content for non-vision model %s/%s; "
+ "falling back to text summary",
+ tool_name,
+ self.provider,
+ self.model,
+ )
+ return summary
+
+ _try_shrink_image_parts_in_messages = _forward_static("agent.conversation_compression", "try_shrink_image_parts_in_messages")
+
+ def _try_strip_image_parts_from_tool_messages(
+ self,
+ api_messages: list,
+ *,
+ remember_model: bool = True,
+ ) -> bool:
+ """Downgrade list-type tool messages to text summaries in place; returns True if any were downgraded.
+
+ Recovery for providers that 400 on list-type tool content (e.g. MiMo "text is not set"). By default
+ records the (provider, model) in ``_no_list_tool_content_models`` so later results downgrade without a
+ round-trip; 413 recovery passes ``remember_model=False`` (body too large ≠ provider rejects lists).
+ """
+ if not isinstance(api_messages, list):
+ return False
+
+ if remember_model:
+ # Record (provider, model) so we don't relearn this lesson.
+ key = (
+ (getattr(self, "provider", "") or "").strip().lower(),
+ (getattr(self, "model", "") or "").strip(),
+ )
+ if not hasattr(self, "_no_list_tool_content_models"):
+ self._no_list_tool_content_models = set()
+ if key[1]: # only record when we actually have a model id
+ self._no_list_tool_content_models.add(key)
+
+ changed = False
+ for msg in api_messages:
+ if not isinstance(msg, dict) or msg.get("role") != "tool":
+ continue
+ content = msg.get("content")
+ if not isinstance(content, list):
+ continue
+
+ # Salvage any text parts so the model still sees some signal.
+ text_parts: List[str] = []
+ had_image = False
+ for part in content:
+ if not isinstance(part, dict):
+ if isinstance(part, str) and part.strip():
+ text_parts.append(part.strip())
+ continue
+ ptype = part.get("type")
+ if ptype == "image_url" or ptype == "input_image":
+ had_image = True
+ continue
+ if ptype in {"text", "input_text"}:
+ text = str(part.get("text") or "").strip()
+ if text:
+ text_parts.append(text)
+
+ if not had_image:
+ # List content without image parts — leave alone; stripping wouldn't reduce ambiguity.
+ continue
+
+ if text_parts:
+ msg["content"] = "\n\n".join(text_parts)
+ else:
+ msg["content"] = (
+ "[image content removed — provider does not accept "
+ "list-type tool message content]"
+ )
+ changed = True
+
+ return changed
+
+ def _anthropic_preserve_dots(self) -> bool:
+ """True when using an anthropic-compatible endpoint that preserves dots in model names.
+
+ DashScope, MiniMax, Xiaomi MiMo, OpenCode Go/Zen (non-Claude), ZAI/Zhipu keep dots; AWS Bedrock uses
+ dotted inference-profile IDs and rejects the hyphenated form with HTTP 400.
+ """
+ if (getattr(self, "provider", "") or "").lower() in {
+ "alibaba", "minimax", "minimax-cn",
+ "opencode-go", "opencode-zen",
+ "zai", "bedrock",
+ "xiaomi", "vertex",
+ }:
+ return True
+ base = (getattr(self, "base_url", "") or "").lower()
+ host = base_url_hostname(base)
+ return (
+ "dashscope" in host
+ or base_url_host_matches(base, "aliyuncs.com")
+ or "minimax" in host
+ or (base_url_host_matches(base, "opencode.ai") and "/zen/" in base)
+ or base_url_host_matches(base, "bigmodel.cn")
+ or base_url_host_matches(base, "xiaomimimo.com")
+ # Vertex AI OpenAI-compat endpoint — Gemini model ids keep dots
+ # (e.g. google/gemini-3.5-flash); the hyphenated form is wrong.
+ or base_url_host_matches(base, "aiplatform.googleapis.com")
+ # AWS Bedrock runtime endpoints — defense-in-depth when
+ # ``provider`` is unset but ``base_url`` still names Bedrock.
+ or host.startswith("bedrock-runtime.")
+ )
+
+ def _is_qwen_portal(self) -> bool:
+ """Return True when the base URL targets Qwen Portal."""
+ return base_url_host_matches(self._base_url_lower, "portal.qwen.ai")
+
+ def _qwen_prepare_chat_messages(self, api_messages: list) -> list:
+ prepared = copy.deepcopy(api_messages)
+ if not prepared:
+ return prepared
+
+ for msg in prepared:
+ if not isinstance(msg, dict):
+ continue
+ content = msg.get("content")
+ if isinstance(content, str):
+ msg["content"] = [{"type": "text", "text": content}]
+ elif isinstance(content, list):
+ # Normalize: convert bare strings to text dicts, keep dicts as-is.
+ # deepcopy already created independent copies, no need for dict().
+ normalized_parts = []
+ for part in content:
+ if isinstance(part, str):
+ normalized_parts.append({"type": "text", "text": part})
+ elif isinstance(part, dict):
+ normalized_parts.append(part)
+ if normalized_parts:
+ msg["content"] = normalized_parts
+
+ # Inject cache_control on the last part of the system message.
+ for msg in prepared:
+ if isinstance(msg, dict) and msg.get("role") == "system":
+ content = msg.get("content")
+ if isinstance(content, list) and content and isinstance(content[-1], dict):
+ content[-1]["cache_control"] = {"type": "ephemeral"}
+ break
+
+ return prepared
+
+ def _qwen_prepare_chat_messages_inplace(self, messages: list) -> None:
+ """In-place variant — mutates an already-copied message list."""
+ if not messages:
+ return
+
+ for msg in messages:
+ if not isinstance(msg, dict):
+ continue
+ content = msg.get("content")
+ if isinstance(content, str):
+ msg["content"] = [{"type": "text", "text": content}]
+ elif isinstance(content, list):
+ normalized_parts = []
+ for part in content:
+ if isinstance(part, str):
+ normalized_parts.append({"type": "text", "text": part})
+ elif isinstance(part, dict):
+ normalized_parts.append(part)
+ if normalized_parts:
+ msg["content"] = normalized_parts
+
+ for msg in messages:
+ if isinstance(msg, dict) and msg.get("role") == "system":
+ content = msg.get("content")
+ if isinstance(content, list) and content and isinstance(content[-1], dict):
+ content[-1]["cache_control"] = {"type": "ephemeral"}
+ break
diff --git a/run_agent.py b/run_agent.py
index 64e852f83ad..dc97a9de412 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -28,17 +28,12 @@ except ModuleNotFoundError:
# Missing hermes_bootstrap (partial `hermes update`) only skips Windows UTF-8 stdio setup.
pass
-import asyncio
-import base64
-import copy
-import hashlib
import json
import logging
logger = logging.getLogger(__name__)
import os
import re
import sys
-import tempfile
import time
import threading
import uuid
@@ -187,6 +182,8 @@ from agent.session_persistence import ( # noqa: F401 # re-exported: cli/gatewa
)
from agent.compression_facade import CompressionFacadeMixin
from agent.turn_facade import TurnFacadeMixin
+from agent.vision_message_prep import VisionMessagePrepMixin
+from agent.reasoning_params import ReasoningParamsMixin
from agent.lazy_forward import forward as _forward, forward_static as _forward_static
from agent.session_activity import ActivityProvenance
from agent.model_metadata import (
@@ -240,8 +237,6 @@ from agent.tool_dispatch_helpers import (
_is_destructive_command, # noqa: F401 # re-exported for tests that access `run_agent._is_destructive_command`
_extract_parallel_scope_path, # noqa: F401 # re-exported for tests that `from run_agent import _extract_parallel_scope_path`
_paths_overlap, # noqa: F401 # re-exported for tests that `from run_agent import _paths_overlap`
- _is_multimodal_tool_result,
- _multimodal_text_summary,
_append_subdir_hint_to_multimodal, # noqa: F401 # re-exported for tests that `from run_agent import _append_subdir_hint_to_multimodal`
_trajectory_normalize_msg, # noqa: F401 # re-exported for tests that `from run_agent import _trajectory_normalize_msg`
)
@@ -315,6 +310,8 @@ class AIAgent(
SessionPersistenceMixin,
CompressionFacadeMixin,
TurnFacadeMixin,
+ VisionMessagePrepMixin,
+ ReasoningParamsMixin,
):
"""AI Agent with tool calling capabilities."""
@@ -1883,726 +1880,8 @@ class AIAgent(
_try_recover_primary_transport = _forward("agent.agent_runtime_helpers", "try_recover_primary_transport")
- @staticmethod
- def _content_has_image_parts(content: Any) -> bool:
- if not isinstance(content, list):
- return False
- for part in content:
- if isinstance(part, dict) and part.get("type") in {"image_url", "input_image"}:
- return True
- return False
-
- # 20 MB base64 ≈ 15 MB decoded — prevents OOM from an oversized data: URL in a shared gateway process.
- _MAX_DATA_URL_BASE64_BYTES = 20 * 1024 * 1024
-
- @staticmethod
- def _materialize_data_url_for_vision(image_url: str) -> tuple[str, Optional[Path]]:
- header, _, data = str(image_url or "").partition(",")
- if len(data) > AIAgent._MAX_DATA_URL_BASE64_BYTES:
- logger.warning(
- "data-URL payload too large (%d bytes), skipping", len(data)
- )
- return "", None
- mime = "image/jpeg"
- if header.startswith("data:"):
- mime_part = header[len("data:"):].split(";", 1)[0].strip()
- if mime_part.startswith("image/"):
- mime = mime_part
- suffix = {
- "image/png": ".png",
- "image/gif": ".gif",
- "image/webp": ".webp",
- "image/jpeg": ".jpg",
- "image/jpg": ".jpg",
- }.get(mime, ".jpg")
- tmp = tempfile.NamedTemporaryFile(prefix="anthropic_image_", suffix=suffix, delete=False)
- try:
- with tmp:
- tmp.write(base64.b64decode(data))
- except Exception:
- # delete=False means a corrupt/unsupported data URL would otherwise
- # leak a zero-byte temp file on every failed materialization.
- try:
- os.unlink(tmp.name)
- except OSError:
- pass
- raise
- path = Path(tmp.name)
- return str(path), path
-
- def _describe_image_for_anthropic_fallback(self, image_url: str, role: str) -> str:
- cache_key = hashlib.sha256(str(image_url or "").encode("utf-8")).hexdigest()
- cached = self._anthropic_image_fallback_cache.get(cache_key)
- if cached:
- return cached
-
- role_label = {
- "assistant": "assistant",
- "tool": "tool result",
- }.get(role, "user")
- analysis_prompt = (
- "Describe everything visible in this image in thorough detail. "
- "Include any text, code, UI, data, objects, people, layout, colors, "
- "and any other notable visual information."
- )
-
- vision_source = str(image_url or "")
- cleanup_path: Optional[Path] = None
- if vision_source.startswith("data:"):
- vision_source, cleanup_path = self._materialize_data_url_for_vision(vision_source)
-
- description = ""
- try:
- from tools.vision_tools import vision_analyze_tool
-
- result_json = asyncio.run(
- vision_analyze_tool(image_url=vision_source, user_prompt=analysis_prompt)
- )
- result = json.loads(result_json) if isinstance(result_json, str) else {}
- description = (result.get("analysis") or "").strip()
- except Exception as e:
- description = f"Image analysis failed: {e}"
- finally:
- if cleanup_path and cleanup_path.exists():
- try:
- cleanup_path.unlink()
- except OSError:
- pass
-
- if not description:
- description = "Image analysis failed."
-
- note = f"[The {role_label} attached an image. Here's what it contains:\n{description}]"
- if vision_source and not str(image_url or "").startswith("data:"):
- note += (
- f"\n[If you need a closer look, use vision_analyze with image_url: {vision_source}]"
- )
-
- self._anthropic_image_fallback_cache[cache_key] = note
- return note
-
- def _model_supports_vision(self) -> bool:
- """Return True if the active provider+model reports native vision.
-
- Resolution: ``model.supports_vision`` > ``providers.<p>.models.<m>.supports_vision`` > models.dev
- lookup (see ``image_routing._supports_vision_override``). Custom/local models absent from models.dev
- would otherwise be misclassified and have their images stripped.
- """
- try:
- from hermes_cli.config import load_config
- from agent.image_routing import _lookup_supports_vision
- cfg = load_config()
- provider = (getattr(self, "provider", "") or "").strip()
- model = (getattr(self, "model", "") or "").strip()
- return _lookup_supports_vision(provider, model, cfg) is True
- except Exception:
- return False
-
- def _provider_supports_vision_tool_messages(self) -> bool:
- """Return True if the active provider accepts list-type tool content.
-
- Some providers (Xiaomi MiMo) accept multimodal user messages but 400 on list-type tool content;
- reads the provider profile's ``supports_vision_tool_messages``.
- """
- try:
- from providers import get_provider_profile
- provider = (getattr(self, "provider", "") or "").strip()
- profile = get_provider_profile(provider)
- if profile is not None:
- return getattr(profile, "supports_vision_tool_messages", True)
- except Exception:
- pass
- return True # default: assume compatible
-
- def _preprocess_anthropic_content(self, content: Any, role: str) -> Any:
- if not self._content_has_image_parts(content):
- return content
-
- text_parts: List[str] = []
- image_notes: List[str] = []
- for part in content:
- if isinstance(part, str):
- if part.strip():
- text_parts.append(part.strip())
- continue
- if not isinstance(part, dict):
- continue
-
- ptype = part.get("type")
- if ptype in {"text", "input_text"}:
- text = str(part.get("text", "") or "").strip()
- if text:
- text_parts.append(text)
- continue
-
- if ptype in {"image_url", "input_image"}:
- image_data = part.get("image_url", {})
- image_url = image_data.get("url", "") if isinstance(image_data, dict) else str(image_data or "")
- if image_url:
- image_notes.append(self._describe_image_for_anthropic_fallback(image_url, role))
- else:
- image_notes.append("[An image was attached but no image source was available.]")
- continue
-
- text = str(part.get("text", "") or "").strip()
- if text:
- text_parts.append(text)
-
- prefix = "\n\n".join(note for note in image_notes if note).strip()
- suffix = "\n".join(text for text in text_parts if text).strip()
- if prefix and suffix:
- return f"{prefix}\n\n{suffix}"
- if prefix:
- return prefix
- if suffix:
- return suffix
- return "[A multimodal message was converted to text for Anthropic compatibility.]"
-
- def _get_transport(self, api_mode: str = None):
- """Return the cached transport for the given (or current) api_mode (lazy; None if unregistered)."""
- mode = api_mode or self.api_mode
- cache = getattr(self, "_transport_cache", None)
- if cache is None:
- cache = {}
- self._transport_cache = cache
- t = cache.get(mode)
- if t is None:
- from agent.transports import get_transport
- t = get_transport(mode)
- cache[mode] = t
- return t
-
- def _prepare_messages_for_non_vision_model(self, api_messages: list) -> list:
- """Replace native image parts with cached vision_analyze text when the active model lacks vision.
-
- Vision-capable models pass through unchanged (the provider adapter — including the Anthropic one —
- handles image parts natively). The text fallback is the historically Anthropic-named preprocessor.
- """
- if not any(
- isinstance(msg, dict) and self._content_has_image_parts(msg.get("content"))
- for msg in api_messages
- ):
- return api_messages
-
- if self._model_supports_vision():
- return api_messages
-
- transformed = copy.deepcopy(api_messages)
- for msg in transformed:
- if not isinstance(msg, dict):
- continue
- msg["content"] = self._preprocess_anthropic_content(
- msg.get("content"),
- str(msg.get("role", "user") or "user"),
- )
- return transformed
-
- # Same transform for the Anthropic route (callers/tests patch this name independently).
- _prepare_anthropic_messages_for_api = _prepare_messages_for_non_vision_model
-
- def _tool_result_content_for_active_model(self, tool_name: str, result: Any) -> Any:
- """Return the tool message content that is safe for the active model.
-
- Text-only providers must not receive image parts: a rejected tool result becomes canonical history
- and can make the next user turn fail before the agent can recover.
- """
- if not _is_multimodal_tool_result(result):
- return result
-
- content = result.get("content") or []
- if not self._content_has_image_parts(content):
- return content
-
- if self._model_supports_vision():
- # Vision on paper, but the provider rejects list-type tool content (or we already learned that
- # in-session): short-circuit to a text summary.
- if not self._provider_supports_vision_tool_messages():
- logger.debug(
- "Tool %s: provider %s does not accept list-type tool "
- "content — sending text summary",
- tool_name, getattr(self, "provider", ""),
- )
- return _multimodal_text_summary(result)
- key = (
- (getattr(self, "provider", "") or "").strip().lower(),
- (getattr(self, "model", "") or "").strip(),
- )
- no_list = getattr(self, "_no_list_tool_content_models", None)
- if no_list and key in no_list:
- logger.debug(
- "Tool %s: model %s/%s known to reject list-type tool "
- "content this session — sending text summary",
- tool_name, key[0], key[1],
- )
- return _multimodal_text_summary(result)
- return content
-
- summary = _multimodal_text_summary(result)
- if tool_name == "computer_use":
- return json.dumps({
- "error": (
- "computer_use returned screenshot/image content, but the active "
- "model/provider does not support image input. Switch to a "
- "vision-capable model for desktop computer use, or use browser "
- "tools for browser tasks."
- ),
- "text_summary": summary,
- })
-
- logger.warning(
- "Tool %s returned image content for non-vision model %s/%s; "
- "falling back to text summary",
- tool_name,
- self.provider,
- self.model,
- )
- return summary
-
- _try_shrink_image_parts_in_messages = _forward_static("agent.conversation_compression", "try_shrink_image_parts_in_messages")
-
- def _try_strip_image_parts_from_tool_messages(
- self,
- api_messages: list,
- *,
- remember_model: bool = True,
- ) -> bool:
- """Downgrade list-type tool messages to text summaries in place; returns True if any were downgraded.
-
- Recovery for providers that 400 on list-type tool content (e.g. MiMo "text is not set"). By default
- records the (provider, model) in ``_no_list_tool_content_models`` so later results downgrade without a
- round-trip; 413 recovery passes ``remember_model=False`` (body too large ≠ provider rejects lists).
- """
- if not isinstance(api_messages, list):
- return False
-
- if remember_model:
- # Record (provider, model) so we don't relearn this lesson.
- key = (
- (getattr(self, "provider", "") or "").strip().lower(),
- (getattr(self, "model", "") or "").strip(),
- )
- if not hasattr(self, "_no_list_tool_content_models"):
- self._no_list_tool_content_models = set()
- if key[1]: # only record when we actually have a model id
- self._no_list_tool_content_models.add(key)
-
- changed = False
- for msg in api_messages:
- if not isinstance(msg, dict) or msg.get("role") != "tool":
- continue
- content = msg.get("content")
- if not isinstance(content, list):
- continue
-
- # Salvage any text parts so the model still sees some signal.
- text_parts: List[str] = []
- had_image = False
- for part in content:
- if not isinstance(part, dict):
- if isinstance(part, str) and part.strip():
- text_parts.append(part.strip())
- continue
- ptype = part.get("type")
- if ptype == "image_url" or ptype == "input_image":
- had_image = True
- continue
- if ptype in {"text", "input_text"}:
- text = str(part.get("text") or "").strip()
- if text:
- text_parts.append(text)
-
- if not had_image:
- # List content without image parts — leave alone; stripping wouldn't reduce ambiguity.
- continue
-
- if text_parts:
- msg["content"] = "\n\n".join(text_parts)
- else:
- msg["content"] = (
- "[image content removed — provider does not accept "
- "list-type tool message content]"
- )
- changed = True
-
- return changed
-
- def _anthropic_preserve_dots(self) -> bool:
- """True when using an anthropic-compatible endpoint that preserves dots in model names.
-
- DashScope, MiniMax, Xiaomi MiMo, OpenCode Go/Zen (non-Claude), ZAI/Zhipu keep dots; AWS Bedrock uses
- dotted inference-profile IDs and rejects the hyphenated form with HTTP 400.
- """
- if (getattr(self, "provider", "") or "").lower() in {
- "alibaba", "minimax", "minimax-cn",
- "opencode-go", "opencode-zen",
- "zai", "bedrock",
- "xiaomi", "vertex",
- }:
- return True
- base = (getattr(self, "base_url", "") or "").lower()
- host = base_url_hostname(base)
- return (
- "dashscope" in host
- or base_url_host_matches(base, "aliyuncs.com")
- or "minimax" in host
- or (base_url_host_matches(base, "opencode.ai") and "/zen/" in base)
- or base_url_host_matches(base, "bigmodel.cn")
- or base_url_host_matches(base, "xiaomimimo.com")
- # Vertex AI OpenAI-compat endpoint — Gemini model ids keep dots
- # (e.g. google/gemini-3.5-flash); the hyphenated form is wrong.
- or base_url_host_matches(base, "aiplatform.googleapis.com")
- # AWS Bedrock runtime endpoints — defense-in-depth when
- # ``provider`` is unset but ``base_url`` still names Bedrock.
- or host.startswith("bedrock-runtime.")
- )
-
- def _is_qwen_portal(self) -> bool:
- """Return True when the base URL targets Qwen Portal."""
- return base_url_host_matches(self._base_url_lower, "portal.qwen.ai")
-
- def _qwen_prepare_chat_messages(self, api_messages: list) -> list:
- prepared = copy.deepcopy(api_messages)
- if not prepared:
- return prepared
-
- for msg in prepared:
- if not isinstance(msg, dict):
- continue
- content = msg.get("content")
- if isinstance(content, str):
- msg["content"] = [{"type": "text", "text": content}]
- elif isinstance(content, list):
- # Normalize: convert bare strings to text dicts, keep dicts as-is.
- # deepcopy already created independent copies, no need for dict().
- normalized_parts = []
- for part in content:
- if isinstance(part, str):
- normalized_parts.append({"type": "text", "text": part})
- elif isinstance(part, dict):
- normalized_parts.append(part)
- if normalized_parts:
- msg["content"] = normalized_parts
-
- # Inject cache_control on the last part of the system message.
- for msg in prepared:
- if isinstance(msg, dict) and msg.get("role") == "system":
- content = msg.get("content")
- if isinstance(content, list) and content and isinstance(content[-1], dict):
- content[-1]["cache_control"] = {"type": "ephemeral"}
- break
-
- return prepared
-
- def _qwen_prepare_chat_messages_inplace(self, messages: list) -> None:
- """In-place variant — mutates an already-copied message list."""
- if not messages:
- return
-
- for msg in messages:
- if not isinstance(msg, dict):
- continue
- content = msg.get("content")
- if isinstance(content, str):
- msg["content"] = [{"type": "text", "text": content}]
- elif isinstance(content, list):
- normalized_parts = []
- for part in content:
- if isinstance(part, str):
- normalized_parts.append({"type": "text", "text": part})
- elif isinstance(part, dict):
- normalized_parts.append(part)
- if normalized_parts:
- msg["content"] = normalized_parts
-
- for msg in messages:
- if isinstance(msg, dict) and msg.get("role") == "system":
- content = msg.get("content")
- if isinstance(content, list) and content and isinstance(content[-1], dict):
- content[-1]["cache_control"] = {"type": "ephemeral"}
- break
-
_build_api_kwargs = _forward("agent.chat_completion_helpers", "build_api_kwargs")
- def _supports_reasoning_extra_body(self) -> bool:
- """Return True when reasoning extra_body is safe to send for this route/model.
-
- OpenRouter forwards unknown extra_body upstream and some routes 400 on ``reasoning``; gate to known
- reasoning-capable families and direct Nous Portal.
- """
- if base_url_host_matches(self._base_url_lower, "nousresearch.com"):
- return True
- if base_url_host_matches(self._base_url_lower, "ai-gateway.vercel.sh"):
- return True
- if (
- base_url_host_matches(self._base_url_lower, "models.github.ai")
- or base_url_host_matches(self._base_url_lower, "githubcopilot.com")
- ):
- try:
- from hermes_cli.models import github_model_reasoning_efforts
-
- return bool(github_model_reasoning_efforts(self.model))
- except Exception:
- return False
- if (self.provider or "").strip().lower() == "lmstudio":
- opts = self._lmstudio_reasoning_options_cached()
- # "off-only" (or absent) means no real reasoning capability.
- return any(opt and opt != "off" for opt in opts)
- # Ollama Cloud: /api/show capabilities are authoritative — emit reasoning_effort only for models
- # declaring "thinking". Cached per (model, base_url).
- if base_url_host_matches(self._base_url_lower, "ollama.com"):
- return self._ollama_supports_thinking_cached()
- if not self._is_openrouter_url():
- return False
- if base_url_host_matches(self._base_url_lower, "api.mistral.ai"):
- return False
-
- model = (self.model or "").lower()
- # Live-catalog metadata first (OpenRouter /v1/models supported_parameters) — the static prefix
- # allowlist repeatedly went stale one vendor at a time (#75386). Unknown falls back to the static
- # list.
- try:
- from hermes_cli.models import (
- openrouter_model_reasoning_capabilities,
- warm_openrouter_reasoning_caps_async,
- )
- caps = openrouter_model_reasoning_capabilities(self.model)
- if caps is None:
- # Cache cold — warm in the background; never block this turn on HTTP.
- warm_openrouter_reasoning_caps_async()
- except Exception:
- caps = None
- if caps is not None:
- return bool(caps.get("supports_reasoning"))
- reasoning_model_prefixes = (
- "deepseek/",
- "anthropic/",
- "openai/",
- "x-ai/",
- "google/gemini-2",
- "google/gemma-4",
- "qwen/qwen3",
- "tencent/hy",
- "xiaomi/",
- )
- return any(model.startswith(prefix) for prefix in reasoning_model_prefixes)
-
- def _lmstudio_reasoning_options_cached(self) -> list[str]:
- """Probe LM Studio's published reasoning ``allowed_options`` once per (model, base_url).
-
- Needed for the supports-reasoning gate and to clamp ``reasoning_effort`` so toggle-style models don't
- 400 on ``high``. Non-empty results cache permanently; empty ones (transient failure OR non-reasoning
- model) cache with a 60s TTL to avoid a round-trip per turn while retrying soon.
- """
- import time as _time
-
- cache = getattr(self, "_lm_reasoning_opts_cache", None)
- if cache is None:
- cache = self._lm_reasoning_opts_cache = {}
- key = (self.model, self.base_url)
- cached = cache.get(key)
- if cached is not None:
- opts, ts = cached
- # Non-empty → permanent. Empty → 60s TTL.
- if opts or (_time.monotonic() - ts) < 60:
- return opts
- try:
- from hermes_cli.models import lmstudio_model_reasoning_options
- opts = lmstudio_model_reasoning_options(
- self.model, self.base_url, getattr(self, "api_key", ""),
- )
- except Exception:
- opts = []
- cache[key] = (opts, _time.monotonic())
- return opts
-
- def _ollama_supports_thinking_cached(self) -> bool:
- """Probe Ollama's ``/api/show`` capabilities once per (model, base_url); True only if ``thinking`` is
- declared.
-
- True/False cache permanently; a probe failure (None) caches 60s so an outage neither suppresses
- reasoning for the session nor round-trips every turn.
- """
- import time as _time
-
- cache = getattr(self, "_ollama_thinking_cache", None)
- if cache is None:
- cache = self._ollama_thinking_cache = {}
- key = (self.model, self.base_url)
- cached = cache.get(key)
- if cached is not None:
- supported, ts = cached
- # Definitive True/False → permanent. Unknown (None) → 60s TTL.
- if supported is not None or (_time.monotonic() - ts) < 60:
- return bool(supported)
- try:
- from hermes_cli.models import ollama_model_supports_thinking
- supported = ollama_model_supports_thinking(
- self.model, self.base_url, getattr(self, "api_key", "")
- )
- except Exception:
- supported = None
- cache[key] = (supported, _time.monotonic())
- return bool(supported)
-
- def _resolve_lmstudio_summary_reasoning_effort(self) -> Optional[str]:
- """Resolve a safe top-level ``reasoning_effort`` for LM Studio.
-
- The iteration-limit summary calls ``chat.completions.create()`` directly, bypassing the transport;
- share the helper so effort resolution and clamping cannot drift.
- """
- from agent.lmstudio_reasoning import resolve_lmstudio_effort
- return resolve_lmstudio_effort(
- self.reasoning_config,
- self._lmstudio_reasoning_options_cached(),
- )
-
- def _github_models_reasoning_extra_body(self) -> dict | None:
- """Format reasoning payload for GitHub Models/OpenAI-compatible routes."""
- try:
- from hermes_cli.models import github_model_reasoning_efforts
- except Exception:
- return None
-
- supported_efforts = github_model_reasoning_efforts(self.model)
- if not supported_efforts:
- return None
-
- if self.reasoning_config and isinstance(self.reasoning_config, dict):
- if self.reasoning_config.get("enabled") is False:
- return None
- requested_effort = str(
- self.reasoning_config.get("effort", "medium")
- ).strip().lower()
- else:
- requested_effort = "medium"
-
- if requested_effort == "xhigh" and "xhigh" not in supported_efforts and "high" in supported_efforts:
- requested_effort = "high"
- elif requested_effort not in supported_efforts:
- if requested_effort == "minimal" and "low" in supported_efforts:
- requested_effort = "low"
- elif "medium" in supported_efforts:
- requested_effort = "medium"
- else:
- requested_effort = supported_efforts[0]
-
- return {"effort": requested_effort}
-
- _build_assistant_message = _forward("agent.chat_completion_helpers", "build_assistant_message")
-
- def _needs_thinking_reasoning_pad(self) -> bool:
- """Return True when the active provider enforces ``reasoning_content`` echo-back on tool-call replays.
-
- DeepSeek thinking, Kimi/Moonshot thinking and Xiaomi MiMo thinking all 400 without it. Cached per
- (provider, model, base_url) and invalidated by ``switch_model()`` / ``_try_activate_fallback()`` —
- the loop calls this ~16× per turn and each miss re-runs several ``urlparse`` host matches.
- """
- key = (self.provider, self.model, getattr(self, "_base_url_lower", self.base_url))
- cached = getattr(self, "_thinking_pad_cache", None)
- if cached is not None and cached[0] == key:
- return cached[1]
- result = (
- self._needs_deepseek_tool_reasoning()
- or self._needs_kimi_tool_reasoning()
- or self._needs_mimo_tool_reasoning()
- or self._reasoning_echo_opt_in()
- )
- self._thinking_pad_cache = (key, result)
- return result
-
- def _reasoning_echo_opt_in(self) -> bool:
- """True when the user opted in to ``reasoning_content`` echo-back for the *current* provider via
- config.
-
- Covers custom providers / gateways proxying thinking models that the host-based
- ``_REASONING_ECHO_RULES`` miss. Per-active-provider: primary from ``model.reasoning_echo``, fallback
- from the fallback entry's field, restored by ``restore_primary_runtime()`` — so falling back to a
- strict provider still strips it.
- """
- return bool(getattr(self, "_reasoning_echo_flag", False))
-
- @staticmethod
- def _read_reasoning_echo_from_config() -> bool:
- """Read ``model.reasoning_echo`` from config; False on any error."""
- try:
- from hermes_cli.config import load_config_readonly
- return bool(
- (load_config_readonly().get("model") or {}).get("reasoning_echo")
- )
- except Exception:
- return False
-
- def _needs_kimi_tool_reasoning(self) -> bool:
- """Return True when the current provider is Kimi / Moonshot thinking mode (requires
- ``reasoning_content`` echo).
-
- Host-driven, not model-name-driven: aggregators re-exporting Kimi reject the echo (#17400). Rule
- table: ``message_sanitization.reasoning_echo_family``.
- """
- from agent.message_sanitization import matches_reasoning_echo_family
- return matches_reasoning_echo_family(
- "kimi", self.provider, None, self.base_url
- )
-
- def _needs_deepseek_tool_reasoning(self) -> bool:
- """Return True when the current provider is DeepSeek thinking mode (requires ``reasoning_content``
- echo).
-
- Omitting the echo on replayed assistant tool-call turns is an HTTP 400 (#15250). Rule table:
- ``message_sanitization.reasoning_echo_family``.
- """
- from agent.message_sanitization import matches_reasoning_echo_family
- return matches_reasoning_echo_family(
- "deepseek", (self.provider or "").lower(), self.model, self.base_url
- )
-
- def _needs_mimo_tool_reasoning(self) -> bool:
- """Return True when the current provider is Xiaomi MiMo thinking mode (requires ``reasoning_content``
- echo).
-
- Rule table: ``message_sanitization.reasoning_echo_family``.
- """
- from agent.message_sanitization import matches_reasoning_echo_family
- return matches_reasoning_echo_family(
- "mimo", (self.provider or "").lower(), self.model, self.base_url
- )
-
- _copy_reasoning_content_for_api = _forward("agent.agent_runtime_helpers", "copy_reasoning_content_for_api")
-
- _reapply_reasoning_echo_for_provider = _forward("agent.agent_runtime_helpers", "reapply_reasoning_echo_for_provider")
-
- @staticmethod
- def _sanitize_tool_calls_for_strict_api(api_msg: dict, model: "str | None" = None) -> dict:
- """Strip Codex Responses fields (call_id, response_item_id, extra_content) from tool_calls for strict
- providers.
-
- Strict Chat Completions APIs (Mistral, Fireworks) 400/422 on unknown fields. ``extra_content`` (Gemini
- thought_signature) is kept only when the outgoing model is Gemini-family (it 400s without it). Builds
- new dicts so the internal history retains the Codex fields for a later fallback.
- """
- tool_calls = api_msg.get("tool_calls")
- if not isinstance(tool_calls, list):
- return api_msg
- from agent.transports.chat_completions import _model_consumes_thought_signature
- _STRIP_KEYS = {"call_id", "response_item_id"}
- if not _model_consumes_thought_signature(model):
- _STRIP_KEYS = _STRIP_KEYS | {"extra_content"}
- api_msg["tool_calls"] = [
- {k: v for k, v in tc.items() if k not in _STRIP_KEYS}
- if isinstance(tc, dict) else tc
- for tc in tool_calls
- ]
- return api_msg
-
- _sanitize_tool_call_arguments = _forward_static("agent.agent_runtime_helpers", "sanitize_tool_call_arguments")
-
- def _should_sanitize_tool_calls(self) -> bool:
- """Determine if tool_calls need sanitization (True for every non-Codex API).
-
- Codex Responses fields (call_id, response_item_id) are not Chat Completions schema and 400 elsewhere.
- """
- return self.api_mode != "codex_responses"
-
def _set_tool_guardrail_halt(self, decision: ToolGuardrailDecision) -> None:
"""Record the first guardrail decision that should stop this turn."""
if decision.should_halt and self._tool_guardrail_halt_decision is None: