The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(vision): MCP embeds keep both caps and their coordinate map; capture route follows config live (review)
Tekniumf070912aa44e
diff --git a/tests/computer_use/test_cua_perf_knobs.py b/tests/computer_use/test_cua_perf_knobs.pyindex dfc8cb29f4b..3f0650dc43d 100644--- a/tests/computer_use/test_cua_perf_knobs.py+++ b/tests/computer_use/test_cua_perf_knobs.py@@ -4,27 +4,16 @@from tools.computer_use import tool as cu_tool-def test_aux_vision_route_caches_per_provider_model(monkeypatch):- cu_tool._AUX_VISION_ROUTE_CACHE.clear()- calls = {"n": 0}-- monkeypatch.setattr(- "agent.auxiliary_client._read_main_provider", lambda: "openai"- )- monkeypatch.setattr(- "agent.auxiliary_client._read_main_model", lambda: "gpt-test"- )-- def fake_load():- calls["n"] += 1- return {"auxiliary": {"vision": {}}}-- monkeypatch.setattr("hermes_cli.config.load_config", fake_load)- monkeypatch.setattr(- "tools.computer_use.vision_routing.should_route_capture_to_aux_vision",- lambda *a, **k: True,- )-- assert cu_tool._should_route_through_aux_vision() is True+def test_aux_vision_route_follows_a_config_change_without_restart(monkeypatch):+ """The capture route reads the signature-cached config on every capture, so an ``image_input_mode`` edit+ (or /model, or a profile switch) applies to the next screenshot instead of a per-process verdict."""+ cfg = {"agent": {"image_input_mode": "native"}}+ monkeypatch.setattr("agent.auxiliary_client._read_main_provider", lambda: "anthropic")+ monkeypatch.setattr("agent.auxiliary_client._read_main_model", lambda: "claude-opus-4-5")+ monkeypatch.setattr("hermes_cli.config.load_config_readonly", lambda: cfg)+ monkeypatch.setattr("agent.image_routing._lookup_supports_vision", lambda *a, **k: True)+ monkeypatch.setattr("tools.vision_tools._profile_rejects_tool_media", lambda *a, **k: False)++ assert cu_tool._should_route_through_aux_vision() is False+ cfg["agent"]["image_input_mode"] = "text"assert cu_tool._should_route_through_aux_vision() is True- assert calls["n"] == 1diff --git a/tests/tools/test_computer_use_capture_routing.py b/tests/tools/test_computer_use_capture_routing.pyindex 216e609b1b5..56d297b0539 100644--- a/tests/tools/test_computer_use_capture_routing.py+++ b/tests/tools/test_computer_use_capture_routing.py@@ -227,7 +227,7 @@ class TestRoutingDecisionWiring:return_value="openrouter"), \patch("agent.auxiliary_client._read_main_model",return_value="tencent/hy3-preview"), \- patch("hermes_cli.config.load_config", return_value=cfg):+ patch("hermes_cli.config.load_config_readonly", return_value=cfg):assert cu_tool._should_route_through_aux_vision() is True@@ -239,7 +239,7 @@ class TestRoutingDecisionWiring:return_value="openrouter"), \patch("agent.auxiliary_client._read_main_model",return_value="x"), \- patch("hermes_cli.config.load_config", return_value={}), \+ patch("hermes_cli.config.load_config_readonly", return_value={}), \patch.object(vr_mod, "should_route_capture_to_aux_vision",side_effect=ValueError("policy bug")):assert cu_tool._should_route_through_aux_vision() is Falsediff --git a/tests/tools/test_mcp_image_content.py b/tests/tools/test_mcp_image_content.pyindex ce912d8b336..6cfcb4c979a 100644--- a/tests/tools/test_mcp_image_content.py+++ b/tests/tools/test_mcp_image_content.py@@ -171,14 +171,22 @@ class TestNativeImageAttach:from tools.vision_tools_history_budget import resolve_embed_target_bytesassert url.startswith("data:image/jpeg;base64,") and len(url) <= resolve_embed_target_bytes()assert "MEDIA:" in out["text_summary"]+ # Screenshot pixels are screen coordinates: the model is told how to map the embed back.+ assert "downscaled from 3000x2000 to 1500x1000" in out["content"][0]["text"]+ assert "multiply any coordinates you report by 2.00" in out["content"][0]["text"]- def test_image_input_mode_text_or_an_undecodable_image_keeps_the_string_result(self, tmp_path, monkeypatch):+ def test_text_mode_an_undecodable_or_an_unshrinkable_image_keeps_the_string_result(self, tmp_path, monkeypatch):assert "MEDIA:" in self._call(monkeypatch, tmp_path, {"agent": {"image_input_mode": "text"}})- # A valid JPEG header over a truncated pixel stream passes the cache's and the sniff's header checks.import iofrom PIL import Image+ # A valid JPEG header over a truncated pixel stream passes the cache's and the sniff's header checks.buf = io.BytesIO()Image.effect_noise((256, 256), 64).convert("RGB").save(buf, "JPEG")truncated = self._call(monkeypatch, tmp_path, {}, image=buf.getvalue()[: len(buf.getvalue()) // 2],mime="image/jpeg")assert isinstance(truncated, str) and "MEDIA:" in truncated+ # A 60000x64 strip: the resizer's 64 px short-edge floor cannot bring the long edge under 1568.+ buf = io.BytesIO()+ Image.new("RGB", (60000, 64), (20, 90, 200)).save(buf, "PNG")+ strip = self._call(monkeypatch, tmp_path, {}, image=buf.getvalue())+ assert isinstance(strip, str) and "MEDIA:" in stripdiff --git a/tests/tools/test_multiplex_tool_cache_scope.py b/tests/tools/test_multiplex_tool_cache_scope.pyindex 3cd680f7252..dcb08e279cd 100644--- a/tests/tools/test_multiplex_tool_cache_scope.py+++ b/tests/tools/test_multiplex_tool_cache_scope.py@@ -88,7 +88,6 @@ def test_home_keyed_caches_serve_each_profile_its_own_config(tmp_path, monkeypatfrom tools import mcp_tool_loopac._reset_aux_semaphores()- cu._AUX_VISION_ROUTE_CACHE.clear()with _scoped(a):assert cu._should_route_through_aux_vision() is False # no explicit aux vision: native pathdiff --git a/tools/computer_use/tool.py b/tools/computer_use/tool.pyindex dd2a0397611..9f791f0e08c 100644--- a/tools/computer_use/tool.py+++ b/tools/computer_use/tool.py@@ -83,9 +83,6 @@ _backends: Dict[str, ComputerUseBackend] = {}_backend_call_locks: Dict[str, threading.RLock] = {}_backend_permission_modes: Dict[str, str] = {}_backend_displays: Dict[str, str] = {} # DISPLAY the cached backend was spawned against (Bot Desktop rebind)-# (home key, provider, model) → bool. The decision reads the active profile's config (auxiliary.vision-# override, declared supports_vision), so a multiplexed process must not serve profile A's verdict to B.-_AUX_VISION_ROUTE_CACHE: Dict[Tuple[str, str, str], bool] = {}# Approval grants live in the shared store (``tools.approval``: session set + permanent allowlist), keyed by the# gate's session key, so a computer_use "always" is one allowlist entry like any terminal pattern. Only the# once-per-session escalation warning is tracked here.@@ -291,7 +288,6 @@ def _shutdown_backend_atexit() -> None:def reset_backend_for_tests() -> None: # pragma: no cover — tear down the cached backend and per-session state_shutdown_backend_atexit()- _AUX_VISION_ROUTE_CACHE.clear()_reset_screenshot_dedup()def _noop_stub(name: str, *params: str, result: Any = None):@@ -892,20 +888,17 @@ def _shrink_capture_for_vision(raw: bytes, ext: str, max_dim: int = _MAX_VISION_def _should_route_through_aux_vision() -> bool:"""True when ``_capture_response`` should hand the PNG to aux vision. Any failure returns False (fail open) so a- broken config never silently drops the screenshot for vision-capable main models."""+ broken config never silently drops the screenshot for vision-capable main models. Decided per capture (the+ config read is the signature-cached ``load_config_readonly``), so ``/model``, a profile switch or an+ ``image_input_mode`` edit applies to the next screenshot instead of a stale verdict."""stage = "import"try:from agent.auxiliary_client import _read_main_model, _read_main_provider- from hermes_cli.config import load_config- from hermes_constants import hermes_home_key+ from hermes_cli.config import load_config_readonlyfrom tools.computer_use.vision_routing import should_route_capture_to_aux_vision- stage = "config read"- provider, model = _read_main_provider() or "", _read_main_model() or ""- if (cached := _AUX_VISION_ROUTE_CACHE.get(key := (hermes_home_key(), str(provider), str(model)))) is not None:- return cachedstage = "decision"- _AUX_VISION_ROUTE_CACHE[key] = decision = bool(should_route_capture_to_aux_vision(provider, model, load_config()))- return decision+ provider, model = _read_main_provider() or "", _read_main_model() or ""+ return bool(should_route_capture_to_aux_vision(provider, model, load_config_readonly()))except Exception as exc: # pragma: no cover - defensivelogger.debug("computer_use: aux-vision routing %s failed: %s", stage, exc)return Falsediff --git a/tools/mcp_tool_content.py b/tools/mcp_tool_content.pyindex 0207def04b7..279ac1dfb4a 100644--- a/tools/mcp_tool_content.py+++ b/tools/mcp_tool_content.py@@ -128,12 +128,15 @@ def _cache_mcp_image_block(block) -> str:_MCP_NATIVE_IMAGE_MAX = 4 # images attached natively from one tool result; the rest stay MEDIA: paths-def _mcp_native_image_part(path: str) -> Optional[Dict[str, Any]]:- """``image_url`` part for one cached MCP image, sized like every other native embed (the result is- re-sent each later turn: ``vision.embed_target_bytes``, 1568 px long edge, JPEG) and normalized to a- provider-accepted format (BMP and friends → PNG). None when the file cannot be embedded."""+def _mcp_native_image_part(path: str) -> Optional[Tuple[Dict[str, Any], Optional[str]]]:+ """``(image_url part, scale note)`` for one cached MCP image, sized like every other native embed (the+ result is re-sent each later turn: ``vision.embed_target_bytes``, 1568 px long edge, JPEG) and normalized+ to a provider-accepted format (BMP and friends → PNG). None when the file cannot be embedded safely. The+ note maps embedded coordinates back to the original image (a screenshot's pixels are the screen's)."""from pathlib import Path- from tools.vision_tools import _EMBED_MAX_DIMENSION, _MAX_BASE64_BYTES, _resize_image_for_vision+ from PIL import Image+ from tools.vision_tools import (_EMBED_MAX_DIMENSION, _MAX_BASE64_BYTES, _build_scale_note,+ _resize_image_for_vision)from tools.vision_tools_history_budget import resolve_embed_target_bytesfrom tools.vision_tools_image_prep import (_detect_image_mime_type_from_bytes, _normalize_to_supported_image,_validate_raster_image_decodable)@@ -144,17 +147,26 @@ def _mcp_native_image_part(path: str) -> Optional[Dict[str, Any]]:normalized, mime, err = _normalize_to_supported_image(src, mime)if err or normalized is None:return None+ scale: Dict[str, int] = {}try:# A valid header over a truncated pixel stream passes the sniff and the cache; one undecodable# part makes the provider reject the whole request, so decode every frame first (as vision_analyze).if _validate_raster_image_decodable(normalized):return None+ with Image.open(normalized) as image:+ dims = image.sizeurl = _resize_image_for_vision(normalized, mime_type=mime, max_base64_bytes=resolve_embed_target_bytes(),- max_dimension=_EMBED_MAX_DIMENSION, force_jpeg=True)+ max_dimension=_EMBED_MAX_DIMENSION, force_jpeg=True, scale_out=scale)finally:if normalized != src:normalized.unlink(missing_ok=True)- return {"type": "image_url", "image_url": {"url": url}} if len(url) <= _MAX_BASE64_BYTES else None+ # The resizer is best-effort (a 64 px short-edge floor keeps a 60000x64 strip at 60000 px): never attach+ # what it could not bring under both caps, since the part rides history and providers reject it per turn.+ if max(scale.get("new_width", dims[0]), scale.get("new_height", dims[1])) > _EMBED_MAX_DIMENSION:+ return None+ if len(url) > _MAX_BASE64_BYTES:+ return None+ return {"type": "image_url", "image_url": {"url": url}}, _build_scale_note(scale or None, None)def _mcp_result_with_native_images(text: str, image_paths: List[str]) -> Any:@@ -169,14 +181,17 @@ def _mcp_result_with_native_images(text: str, image_paths: List[str]) -> Any:from tools.vision_tools import _should_use_native_vision_fast_pathif not _should_use_native_vision_fast_path():return text- parts = [p for p in map(_mcp_native_image_part, image_paths[:_MCP_NATIVE_IMAGE_MAX]) if p]+ attached = [(p, r) for p, r in ((p, _mcp_native_image_part(p)) for p in image_paths[:_MCP_NATIVE_IMAGE_MAX]) if r]except Exception: # deliberate boundary: the MEDIA: paths already carry the images, so any failure keeps the textlogger.debug("MCP native image attach failed, keeping MEDIA: paths", exc_info=True)return text- if not parts:+ if not attached:return text- attached = text + "\n\nThe image(s) from this call are attached — inspect them with your native vision."- return {"_multimodal": True, "content": [{"type": "text", "text": attached}, *parts], "text_summary": text}+ notes = "".join(f"\n- MEDIA:{p}: {note}" for p, (_part, note) in attached if note)+ header = "\n\nThe image(s) from this call are attached — inspect them with your native vision."+ return {"_multimodal": True,+ "content": [{"type": "text", "text": text + header + notes}, *(part for _p, (part, _n) in attached)],+ "text_summary": text}def _cache_mcp_audio_block(block) -> str: