The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: bypass the proxy on loopback HTTP CDP discovery and keep NO_PROXY=* intact
teknium195987fb85a2d
diff --git a/agent/proxy_bypass.py b/agent/proxy_bypass.pyindex 4ab7c56632c..d073410413e 100644--- a/agent/proxy_bypass.py+++ b/agent/proxy_bypass.py@@ -69,8 +69,11 @@ LOOPBACK_HOSTS = ("127.0.0.1", "localhost", "::1")def is_loopback_host(host: str | None) -> bool:- """True for a host that must always bypass a proxy (loopback literal or ``localhost``)."""- return str(host or "").strip().lower().strip("[]") in LOOPBACK_HOSTS+ """True for a host that must always bypass a proxy: ``localhost`` or any loopback IP literal+ (``127.x.x.x``, ``::1``, ``::ffff:127.0.0.1``)."""+ host = str(host or "").strip().lower().strip("[]")+ ip = _ip_or_none(host)+ return host == "localhost" or (ip is not None and ip.is_loopback)def loopback_connect_kwargs(url: str) -> dict:@@ -80,9 +83,19 @@ def loopback_connect_kwargs(url: str) -> dict:return {"proxy": None} if is_loopback_host(split_host_port(url)[0]) else {}+def loopback_request_kwargs(url: str) -> dict:+ """``requests.get`` kwargs for an in-process HTTP dial (CDP ``/json/version`` discovery /+ readiness): ``{"proxies": {"http": None, "https": None}}`` when ``url`` targets loopback so+ ``requests`` skips ``getproxies()`` (env and macOS system proxy), else ``{}``."""+ return {"proxies": {"http": None, "https": None}} if is_loopback_host(split_host_port(url)[0]) else {}++def add_loopback_no_proxy(env: dict) -> dict:"""Append the loopback hosts to ``NO_PROXY`` / ``no_proxy`` in ``env`` (both casings),- keeping every operator-provided entry; returns ``env``."""+ keeping every operator-provided entry; returns ``env``. An operator ``*`` (bypass everything)+ already covers loopback and would stop being the wildcard once anything is appended to it."""+ if any("*" in no_proxy_entries(env.get(key) or "") for key in ("NO_PROXY", "no_proxy")):+ return env # both casings: requests/urllib read ``no_proxy`` first, so a loopback-only one would winfor key in ("NO_PROXY", "no_proxy"):entries = no_proxy_entries(env.get(key) or "")missing = [host for host in LOOPBACK_HOSTS if host not in entries]diff --git a/hermes_cli/browser_connect.py b/hermes_cli/browser_connect.pyindex 1166ab1ff03..d07bd2a10da 100644--- a/hermes_cli/browser_connect.py+++ b/hermes_cli/browser_connect.py@@ -26,6 +26,7 @@ import urllib.requestfrom dataclasses import dataclass, fieldfrom pathlib import Path+from agent.proxy_bypass import is_loopback_hostfrom hermes_constants import get_hermes_homelogger = logging.getLogger(__name__)@@ -751,9 +752,12 @@ def is_browser_debug_ready(url: str, timeout: float = 1.0) -> bool:if scheme not in {"http", "https"} or not parsed.netloc:return Falseroot = f"{scheme}://{parsed.netloc}".rstrip("/")+ # Loopback readiness must not route through getproxies() (env or macOS system proxy, #110565).+ handlers = [urllib.request.ProxyHandler({})] if is_loopback_host(parsed.hostname) else []+ opener = urllib.request.build_opener(*handlers)for probe in (f"{root}/json/version", f"{root}/json"):try:- with urllib.request.urlopen(probe, timeout=timeout) as resp:+ with opener.open(probe, timeout=timeout) as resp:if 200 <= getattr(resp, "status", 200) < 300:return Trueexcept Exception:diff --git a/tests/hermes_cli/test_cli_browser_connect.py b/tests/hermes_cli/test_cli_browser_connect.pyindex bb84ada79c6..50ab9354d97 100644--- a/tests/hermes_cli/test_cli_browser_connect.py+++ b/tests/hermes_cli/test_cli_browser_connect.py@@ -48,13 +48,13 @@ class TestChromeDebugLaunch:return _FakeResponse()raise OSError("unexpected probe")- with patch("urllib.request.urlopen", side_effect=fake_urlopen):+ with patch("urllib.request.OpenerDirector.open", side_effect=fake_urlopen):assert is_browser_debug_ready("http://127.0.0.1:9222", timeout=0.1) is Trueassert requested == ["http://127.0.0.1:9222/json/version"]def test_browser_debug_ready_rejects_non_cdp_listener(self):- with patch("urllib.request.urlopen", side_effect=OSError("not cdp")):+ with patch("urllib.request.OpenerDirector.open", side_effect=OSError("not cdp")):assert is_browser_debug_ready("http://127.0.0.1:9222", timeout=0.1) is Falsediff --git a/tests/tools/test_browser_env_loopback_no_proxy.py b/tests/tools/test_browser_env_loopback_no_proxy.pyindex 6a7710051d4..919f663e6d9 100644--- a/tests/tools/test_browser_env_loopback_no_proxy.py+++ b/tests/tools/test_browser_env_loopback_no_proxy.py@@ -10,7 +10,7 @@ for loopback URLs only.import pytestimport tools.browser_tool as bt-from agent.proxy_bypass import loopback_connect_kwargs+from agent.proxy_bypass import add_loopback_no_proxy, loopback_connect_kwargs, loopback_request_kwargs@pytest.fixture@@ -30,11 +30,24 @@ def test_browser_env_appends_loopback_to_operator_no_proxy(stub_sanitized_env):assert env["no_proxy"] == "127.0.0.1,localhost,::1"[email protected]("url, expected", [- ("ws://127.0.0.1:9222/devtools/browser/abc", {"proxy": None}),- ("ws://localhost:9222/devtools/browser/abc", {"proxy": None}),- ("ws://[::1]:9222/devtools/browser/abc", {"proxy": None}),- ("wss://connect.browserbase.com/cdp?apiKey=x", {}),+def test_operator_no_proxy_wildcard_is_left_alone():+ # ``*,127.0.0.1,...`` is no longer the wildcard for urllib/requests: appending would flip a+ # bypass-everything config into proxy-everything-but-loopback.+ assert add_loopback_no_proxy({"NO_PROXY": "*"}) == {"NO_PROXY": "*"}+++NO_PROXIES = {"proxies": {"http": None, "https": None}}++[email protected]("url, expected, http_expected", [+ ("ws://127.0.0.1:9222/devtools/browser/abc", {"proxy": None}, NO_PROXIES),+ ("ws://localhost:9222/devtools/browser/abc", {"proxy": None}, NO_PROXIES),+ ("ws://[::1]:9222/devtools/browser/abc", {"proxy": None}, NO_PROXIES),+ ("http://127.0.0.2:9222", {"proxy": None}, NO_PROXIES),+ ("http://[::ffff:127.0.0.1]:9222", {"proxy": None}, NO_PROXIES),+ ("ws://localhost.evil.com:9222/devtools/browser/abc", {}, {}),+ ("wss://connect.browserbase.com/cdp?apiKey=x", {}, {}),])-def test_in_process_cdp_dial_disables_proxy_only_for_loopback(url, expected):+def test_in_process_cdp_dial_disables_proxy_only_for_loopback(url, expected, http_expected):assert loopback_connect_kwargs(url) == expected+ assert loopback_request_kwargs(url) == http_expecteddiff --git a/tools/browser_tool_cdp.py b/tools/browser_tool_cdp.pyindex c5386c9d5c5..e59f5bec1a9 100644--- a/tools/browser_tool_cdp.py+++ b/tools/browser_tool_cdp.py@@ -6,6 +6,7 @@ import contextlibimport osfrom typing import Tuple+from agent.proxy_bypass import loopback_request_kwargsfrom tools.browser_tool_origin import origin_module as _origin@@ -33,7 +34,7 @@ def _resolve_cdp_override(cdp_url: str) -> str:san = _bt._sanitize_url_for_logstry:import requests # lazy — shared module object, test patches still apply- response = requests.get(version_url, timeout=10)+ response = requests.get(version_url, timeout=10, **loopback_request_kwargs(version_url))response.raise_for_status()payload = response.json()except Exception as exc:diff --git a/tools/browser_tool_real_profile.py b/tools/browser_tool_real_profile.pyindex 103bc7a64cc..f2838302a7a 100644--- a/tools/browser_tool_real_profile.py+++ b/tools/browser_tool_real_profile.py@@ -12,6 +12,7 @@ import subprocessimport sysimport timefrom typing import Optional, Tuple+from agent.proxy_bypass import loopback_request_kwargsfrom tools.browser_tool_origin import origin_module as _originfrom tools import browser_tool_cloud as _cloudfrom tools import browser_tool_install as _install@@ -94,7 +95,8 @@ def _surviving_chrome_cdp(data_dir: str) -> Optional[str]:http_cdp = f"http://127.0.0.1:{port}"try:import requests- ws_url = str(requests.get(f"{http_cdp}/json/version", timeout=2).json().get("webSocketDebuggerUrl") or "")+ ws_url = str(requests.get(f"{http_cdp}/json/version", timeout=2, **loopback_request_kwargs(http_cdp))+ .json().get("webSocketDebuggerUrl") or "")except Exception:return Nonereturn http_cdp if ws_url.endswith(browser_path) else None