The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools/web): split web_tools into truncate/extract siblings; dispatch tables for backend probes and stdlib extractors; compact url_safety/website_policy/result cache
Teknium8b3dde5dccb9
diff --git a/tools/read_extract.py b/tools/read_extract.pyindex 0deeebb4eb9..5c8876f8e06 100644--- a/tools/read_extract.py+++ b/tools/read_extract.py@@ -81,7 +81,8 @@ def _anydoc() -> Optional[Any]:"""Lazily import the optional anydoc converter; None when unavailable.A failed load is retried after :data:`ANYDOC_RETRY_SECONDS` rather than- disabling extraction for the rest of a long-lived process.+ disabling extraction for the rest of the process, so one transient failure+ (network blip, pip race) does not stick in long-lived workers."""global _anydoc_module, _anydoc_failed_atif _anydoc_module is not _ANYDOC_UNSET:@@ -186,8 +187,9 @@ def _hosted_ocr_config() -> tuple:Maintainer decision: the ONLY route is a direct ``FIRECRAWL_API_KEY``(anydoc defaults api_url to https://api.firecrawl.dev); the Nous managedgateway is NOT used — its Parse proxy live-probed broken while scrape/search- worked. ``file_tools.hosted_ocr: false`` disables even with a key;- true/unset → enabled iff the key is present. Env probe only, no network.+ worked (revisit when it grows Parse support). ``file_tools.hosted_ocr:+ false`` disables even with a key; true/unset → enabled iff the key is+ present. Env probe only, no network at schema-build time."""api_key = os.environ.get("FIRECRAWL_API_KEY") or Noneenabled = api_key is not None@@ -234,28 +236,14 @@ def _needs_ocr_warning(path: str, pages, hosted_error: str = "") -> str:return msg + "]\n"-def _convert_anydoc(path: str, size: int, convert: Callable[[Any], str], pdf_note: Callable[[], str]) -> str:- """Shared anydoc pipeline: availability + size gate, convert, normalize, PDF note.+def _finalize_anydoc_text(text: Any, path: str, pdf_note: Callable[[], str]) -> str:+ """Normalize converter output and, for PDFs, PREPEND the coverage note.- ``convert(mod)`` runs the converter; its exceptions become ExtractionError- (anydoc raises one ConvertError subclass per failure mode — Unsupported,- Malformed, Encrypted, ResourceLimit, MissingPart — all meaning "no meaningful- text", so read_file falls back to normal path/binary handling). The PDF- coverage note is PREPENDED: read_file paginates the extraction, so a footer- on a long document would sit on a page the model may never fetch. It covers+ Prepended because read_file paginates the extraction: a footer on a long+ document would sit on a page the model may never fetch. The note coversPARTIAL gaps (text layer plus some scanned pages) that convert withoutraising NeedsOcrError."""- mod = _anydoc()- if mod is None:- raise ExtractionError(_anydoc_missing_error(path))- _check_size(size, MAX_ANYDOC_BYTES)- try:- text = convert(mod)- except ExtractionError:- raise- except Exception as exc:- raise ExtractionError(f"{type(exc).__name__}: {exc}") from excif not isinstance(text, str) or not text.strip():raise ExtractionError("Document contains no extractable text")text = text.rstrip("\n") + "\n"@@ -267,7 +255,7 @@ def _convert_anydoc(path: str, size: int, convert: Callable[[Any], str], pdf_notdef _ocr_scanned_pdf(mod: Any, path: str, exc: BaseException) -> str:- """Typed scanned-pages signal (anydoc >= 0.2): try hosted OCR, else teach recovery."""+ """Typed scanned-pages signal (anydoc >= 0.2): try hosted OCR when a Firecrawl route exists, else teach recovery."""pages = list(getattr(exc, "pages", []) or [])enabled, api_key, api_url = _hosted_ocr_config()hosted_error = ""@@ -281,43 +269,48 @@ def _ocr_scanned_pdf(mod: Any, path: str, exc: BaseException) -> str:return mod.to_markdown(path, **kwargs).rstrip("\n") + "\n"except Exception as hosted_exc: # noqa: BLE001hosted_error = f"{type(hosted_exc).__name__}: {hosted_exc}"- # Whole doc is scans — nothing to extract, so the warning IS the result.+ # No route / disabled / hosted failed: whole doc is scans — nothing to+ # extract, so the warning IS the result.return _needs_ocr_warning(path, pages, hosted_error)-class _ScannedPdfResult(ExtractionError):- """Internal: carries the hosted-OCR/NEEDS-OCR text out of the converter callback."""+def _require_anydoc(path: str) -> Any:+ mod = _anydoc()+ if mod is None:+ raise ExtractionError(_anydoc_missing_error(path))+ return moddef _extract_anydoc(path: str) -> str:- def convert(mod: Any) -> str:- try:- return mod.to_markdown(path)- except OSError as exc:- raise ExtractionError(str(exc)) from exc- except Exception as exc:- needs_ocr = getattr(mod, "NeedsOcrError", None)- if needs_ocr is not None and isinstance(exc, needs_ocr):- raise _ScannedPdfResult(_ocr_scanned_pdf(mod, path, exc)) from exc- raise-- if _anydoc() is None:- raise ExtractionError(_anydoc_missing_error(path))+ mod = _require_anydoc(path)try:size = os.path.getsize(path)except OSError as exc:raise ExtractionError(str(exc)) from exc+ _check_size(size, MAX_ANYDOC_BYTES)try:- return _convert_anydoc(path, size, convert, lambda: _pdf_coverage_note(path))- except _ScannedPdfResult as result:- return str(result)+ text = mod.to_markdown(path)+ except OSError as exc:+ raise ExtractionError(str(exc)) from exc+ except Exception as exc:+ needs_ocr = getattr(mod, "NeedsOcrError", None)+ if needs_ocr is not None and isinstance(exc, needs_ocr):+ return _ocr_scanned_pdf(mod, path, exc)+ # anydoc raises one ConvertError subclass per failure mode (Unsupported,+ # Malformed, Encrypted, ResourceLimit, MissingPart); all mean "no+ # meaningful text", so read_file falls back to path/binary handling.+ raise ExtractionError(f"{type(exc).__name__}: {exc}") from exc+ return _finalize_anydoc_text(text, path, lambda: _pdf_coverage_note(path))def _extract_anydoc_bytes(data: bytes, path: str) -> str:- return _convert_anydoc(- path, len(data), lambda mod: mod.to_markdown_bytes(data),- lambda: _pdf_coverage_note_from_bytes(data, path),- )+ mod = _require_anydoc(path)+ _check_size(len(data), MAX_ANYDOC_BYTES)+ try:+ text = mod.to_markdown_bytes(data)+ except Exception as exc:+ raise ExtractionError(f"{type(exc).__name__}: {exc}") from exc+ return _finalize_anydoc_text(text, path, lambda: _pdf_coverage_note_from_bytes(data, path))# ── Scanned-PDF coverage detection ──────────────────────────────────diff --git a/tools/url_safety.py b/tools/url_safety.pyindex 08a3ccc71e3..bf62f8be5b7 100644--- a/tools/url_safety.py+++ b/tools/url_safety.py@@ -5,12 +5,14 @@ for environments whose DNS resolves public names to private/benchmark ranges.Even then, cloud metadata hostnames/IPs are **always** blocked.Limitations:- - DNS rebinding (TOCTOU): Hermes-owned direct httpx paths should use- ``create_ssrf_safe_client()`` / ``create_ssrf_safe_async_client()`` so the- policy is re-applied at TCP connect and the socket dials the validated IP- while preserving Host/SNI semantics.+ - DNS rebinding (TOCTOU): an attacker DNS server with TTL=0 can answer a public+ IP for the check and a private one for the connect. Hermes-owned direct httpx+ paths should use ``create_ssrf_safe_client()`` / ``create_ssrf_safe_async_client()``+ so the policy is re-applied at TCP connect and the socket dials the validated+ IP while preserving Host/SNI semantics.- Redirect bypass is mitigated by httpx response hooks re-validating each- redirect target (see ``redirect_target_from_response``).+ redirect target (see ``redirect_target_from_response``). Web tools go through+ third-party SDKs (Firecrawl/Tavily) whose redirect handling is server-side."""import ipaddress@@ -233,18 +235,24 @@ def _normalize_hostname(host: Optional[str]) -> str:return (host or "").strip().lower().rstrip(".")-def _is_ip_literal(hostname: str) -> bool:+def _parse_ip(hostname: str) -> Optional[ipaddress.IPv4Address | ipaddress.IPv6Address]:+ """Return the IP object for a literal-IP hostname, else None."""try:- ipaddress.ip_address(hostname)+ return ipaddress.ip_address(hostname)except ValueError:- return False- return True+ return None-def _sockaddr_ip(sockaddr: Any) -> str:- """Return the IP string from a getaddrinfo sockaddr, minus any IPv6 scope ID."""- ip_str = sockaddr[0]- return ip_str.split("%")[0] if "%" in ip_str else ip_str+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.+ """+ for _family, _, _, _, sockaddr in addr_info:+ raw = sockaddr[0]+ ip_str = raw.split("%")[0] if "%" in raw else raw+ yield raw, ip_str, _parse_ip(ip_str)def _is_always_blocked_ip(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:@@ -276,53 +284,35 @@ def is_always_blocked_url(url: str) -> bool:return Falseif hostname in _BLOCKED_HOSTNAMES:- logger.warning(- "Blocked request to internal hostname (always-blocked floor): %s",- hostname,- )+ logger.warning("Blocked request to internal hostname (always-blocked floor): %s", hostname)return True- try:- ip = ipaddress.ip_address(hostname)- except ValueError:- ip = None-+ 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,- )+ logger.warning("Blocked request to cloud metadata address (always-blocked floor): %s", hostname)return Truereturn Falsetry:- addr_info = socket.getaddrinfo(- hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM- )+ addr_info = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM)except socket.gaierror:- return False+ return False # DNS failure is not part of the floor; caller's path handles it- for _family, _, _, _, sockaddr in addr_info:- ip_str = _sockaddr_ip(sockaddr)- try:- resolved = ipaddress.ip_address(ip_str)- except ValueError:- logger.warning("Unparseable IP address %r for hostname %s — skipping address", sockaddr[0], hostname)+ 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)continueif _is_always_blocked_ip(resolved):logger.warning(- "Blocked request to cloud metadata address "- "(always-blocked floor): %s -> %s",- hostname,- ip_str,+ "Blocked request to cloud metadata address (always-blocked floor): %s -> %s", hostname, ip_str)return Truereturn Falseexcept 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)return False@@ -332,6 +322,21 @@ def _allows_private_ip_resolution(hostname: str, scheme: str) -> bool:return scheme == "https" and hostname in _TRUSTED_PRIVATE_IP_HOSTS+def _resolved_ip_block_reason(+ ip: ipaddress.IPv4Address | ipaddress.IPv6Address, 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.+ """+ if _is_always_blocked_ip(ip):+ return "cloud metadata address"+ if not allow_private and _is_blocked_ip(ip):+ return "private/internal address"+ return None++def is_safe_url(url: str) -> bool:"""Return True if the URL target is not a private/internal address.@@ -356,6 +361,7 @@ def is_safe_url(url: str) -> bool:allow_all_private = _global_allow_private_urls()allow_private_ip = _allows_private_ip_resolution(hostname, scheme)+ allow_private = allow_all_private or allow_private_iptry:addr_info = socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM)@@ -364,48 +370,29 @@ def is_safe_url(url: str) -> bool:# configured, delegate resolution to it (metadata hostnames were already# rejected above). Literal IPs need no DNS, so a failure on one is not a# proxy symptom — keep them fail-closed.- if not _is_ip_literal(hostname) and _proxy_is_configured():+ 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",+ "DNS resolution failed for %s — proxy configured, allowing through for proxy-side resolution",hostname,)return Truelogger.warning("Blocked request — DNS resolution failed for: %s", hostname)return False- for family, _, _, _, sockaddr in addr_info:- ip_str = _sockaddr_ip(sockaddr)- try:- ip = ipaddress.ip_address(ip_str)- except ValueError:- logger.warning("Blocked request — unparseable IP address %r for hostname %s", sockaddr[0], hostname)- return False-- if _is_always_blocked_ip(ip):- logger.warning(- "Blocked request to cloud metadata address: %s -> %s",- hostname, ip_str,- )+ 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- if not allow_all_private and not allow_private_ip and _is_blocked_ip(ip):- logger.warning(- "Blocked request to private/internal address: %s -> %s",- hostname, ip_str,- )+ 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 Falseif allow_all_private:- logger.debug(- "Allowing private/internal resolution (security.allow_private_urls=true): %s",- hostname,- )+ 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,- )+ logger.debug("Allowing trusted hostname despite private/internal resolution: %s", hostname)return True@@ -441,37 +428,25 @@ def _resolved_http_connect_ips(host: str, port: int, scheme: str) -> list[str]:if hostname in _BLOCKED_HOSTNAMES:raise SSRFConnectionBlocked(f"Blocked request to internal hostname: {hostname}")- allow_all_private = _global_allow_private_urls()- allow_private_ip = _allows_private_ip_resolution(hostname, scheme)+ allow_private = _global_allow_private_urls() or _allows_private_ip_resolution(hostname, scheme)try:- addr_info = socket.getaddrinfo(- hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM- )+ addr_info = socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM)except socket.gaierror as exc:- raise SSRFConnectionBlocked(- f"Blocked request - DNS resolution failed for: {hostname}"- ) from exc+ raise SSRFConnectionBlocked(f"Blocked request - DNS resolution failed for: {hostname}") from excsafe_ips: list[str] = []seen: set[str] = set()- for _family, _, _, _, sockaddr in addr_info:- ip_str = _sockaddr_ip(sockaddr)- try:- ip = ipaddress.ip_address(ip_str)- except ValueError as exc:+ for raw, ip_str, ip in _iter_resolved_ips(addr_info):+ if ip is None:raise SSRFConnectionBlocked(- f"Blocked request - unparseable IP address {sockaddr[0]!r} for hostname {hostname}"- ) from exc+ 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")- if _is_always_blocked_ip(ip):+ reason = _resolved_ip_block_reason(ip, allow_private)+ if reason is not None:raise SSRFConnectionBlocked(- f"Blocked request to cloud metadata address during connect: {hostname} -> {ip_str}"- )-- if not allow_all_private and not allow_private_ip and _is_blocked_ip(ip):- raise SSRFConnectionBlocked(- f"Blocked request to private/internal address during connect: {hostname} -> {ip_str}"+ f"Blocked request to {reason} during connect: {hostname} -> {ip_str}")if ip_str not in seen and len(safe_ips) < _MAX_SSRF_CONNECT_IPS:@@ -480,20 +455,36 @@ def _resolved_http_connect_ips(host: str, port: int, scheme: str) -> list[str]:if not safe_ips:raise SSRFConnectionBlocked(f"Blocked request - DNS returned no results for: {hostname}")- return safe_ips+ return safe_ips # capped at _MAX_SSRF_CONNECT_IPS, but EVERY answer above was validated-class _SSRFGuardedAsyncNetworkBackend:+class _SSRFGuardedBackendBase:"""httpcore backend that re-resolves + validates at connect time and dials a vetted IP.- Host/SNI stay on the original hostname; Unix sockets are refused outright.+ 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."""+ def __init__(self, backend: Any, schemes_by_origin_var: Any):+ self._backend = backend+ self._schemes_by_origin_var = schemes_by_origin_var++ def _connect_scheme(self, host: str, port: int) -> str:+ return _safe_connect_scheme(host, port, self._schemes_by_origin_var.get({}))++ @staticmethod+ def _no_usable_ips(host: str, last_exc: Exception | None) -> Exception:+ if last_exc is not None:+ return last_exc+ return SSRFConnectionBlocked(f"Blocked request - DNS returned no usable IPs for: {host}")+++class _SSRFGuardedAsyncNetworkBackend(_SSRFGuardedBackendBase):def __init__(self, schemes_by_origin_var: Any):from httpcore._backends.auto import AutoBackend- self._backend = AutoBackend()- self._schemes_by_origin_var = schemes_by_origin_var+ super().__init__(AutoBackend(), schemes_by_origin_var)async def connect_tcp(self,@@ -505,7 +496,7 @@ class _SSRFGuardedAsyncNetworkBackend:) -> Any:import httpcore- scheme = _safe_connect_scheme(host, port, self._schemes_by_origin_var.get({}))+ scheme = self._connect_scheme(host, port)ips = await asyncio.to_thread(_resolved_http_connect_ips, host, port, scheme)last_exc: Exception | None = None@@ -516,10 +507,7 @@ class _SSRFGuardedAsyncNetworkBackend:)except (httpcore.ConnectError, httpcore.ConnectTimeout) as exc:last_exc = exc- continue- if last_exc is not None:- raise last_exc- raise SSRFConnectionBlocked(f"Blocked request - DNS returned no usable IPs for: {host}")+ raise self._no_usable_ips(host, last_exc)async def connect_unix_socket(self, path: str, timeout: float | None = None, socket_options: Any = None) -> Any:raise SSRFConnectionBlocked("Blocked Unix socket connection in SSRF-safe transport")@@ -528,17 +516,11 @@ class _SSRFGuardedAsyncNetworkBackend:await self._backend.sleep(seconds)-class _SSRFGuardedNetworkBackend:- """httpcore backend that re-resolves + validates at connect time and dials a vetted IP.-- Host/SNI stay on the original hostname; Unix sockets are refused outright.- """-+class _SSRFGuardedNetworkBackend(_SSRFGuardedBackendBase):def __init__(self, schemes_by_origin_var: Any):from httpcore._backends.sync import SyncBackend- self._backend = SyncBackend()- self._schemes_by_origin_var = schemes_by_origin_var+ super().__init__(SyncBackend(), schemes_by_origin_var)def connect_tcp(self,@@ -550,8 +532,7 @@ class _SSRFGuardedNetworkBackend:) -> Any:import httpcore- scheme = _safe_connect_scheme(host, port, self._schemes_by_origin_var.get({}))- ips = _resolved_http_connect_ips(host, port, scheme)+ ips = _resolved_http_connect_ips(host, port, self._connect_scheme(host, port))last_exc: Exception | None = Nonefor ip in ips:@@ -561,10 +542,7 @@ class _SSRFGuardedNetworkBackend:)except (httpcore.ConnectError, httpcore.ConnectTimeout) as exc:last_exc = exc- continue- if last_exc is not None:- raise last_exc- raise SSRFConnectionBlocked(f"Blocked request - DNS returned no usable IPs for: {host}")+ raise self._no_usable_ips(host, last_exc)def connect_unix_socket(self, path: str, timeout: float | None = None, socket_options: Any = None) -> Any:raise SSRFConnectionBlocked("Blocked Unix socket connection in SSRF-safe transport")@@ -623,6 +601,7 @@ 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 contextvarsvar_name = "hermes_ssrf_async_origin_schemes" if is_async else "hermes_ssrf_origin_schemes"diff --git a/tools/web_result_cache.py b/tools/web_result_cache.pyindex 833acae3b16..070758efee6 100644--- a/tools/web_result_cache.py+++ b/tools/web_result_cache.py@@ -84,6 +84,7 @@ def _url_host(url: str) -> str:def _deep_copy(response: dict) -> dict:+ """Defensive copy so callers mutating a hit never corrupt the cached entry."""return json.loads(json.dumps(response))@@ -311,6 +312,7 @@ def _is_local_dev_url(url: str) -> bool:def _cacheable(url: str) -> bool:+ """Extract-cache gate: enabled, not a local-dev host, not user-exempted."""return cache_enabled() and not (_is_local_dev_url(url) or _is_cache_exempt_host(url))diff --git a/tools/web_tools.py b/tools/web_tools.pyindex 71e06afeae7..8de28c403e9 100644--- a/tools/web_tools.py+++ b/tools/web_tools.py@@ -13,8 +13,6 @@ Debug: ``WEB_TOOLS_DEBUG=true`` writes ``logs/web_tools_debug_<UUID>.json``.import jsonimport loggingimport os-import re-import asynciofrom typing import List, Dict, Any, Optional, TYPE_CHECKINGimport httpx # noqa: F401 — kept at module top so tests can patch tools.web_tools.httpx@@ -61,7 +59,7 @@ from tools.tool_backend_helpers import ( # noqa: F401nous_tool_gateway_unavailable_message,prefers_gateway,)-from tools.url_safety import async_is_safe_url, normalize_url_for_request, sensitive_query_param_name+from tools.url_safety import async_is_safe_urlfrom tools.web_tools_rescue import ( # noqa: F401 — re-exported (tests patch tools.web_tools.<name>)_keyless_rescue_enabled,_policy_blocked_result,@@ -69,24 +67,36 @@ from tools.web_tools_rescue import ( # noqa: F401 — re-exported (tests patch_rescue_extract,_rescue_search,)+from tools.web_tools_truncate import ( # noqa: F401 — re-exported (tests + web_result_cache import via tools.web_tools)+ DEFAULT_EXTRACT_CHAR_LIMIT,+ MAX_STORED_TEXT_CHARS,+ _clamp_char_limit,+ _effective_char_limit,+ _get_extract_char_limit,+ _store_full_text,+ _trim_results,+ _truncate_results,+ _truncate_with_footer,+ convert_base64_images_to_links,+)+from tools.web_tools_extract import ( # noqa: F401 — re-exported+ _EXTRACT_BACKENDS_HINT,+ _NO_RESULT_ERROR,+ _disabled_plugin_error,+ _extract_error_json,+ _extract_safe_urls,+ _no_provider_error,+ _resolve_extract_provider,+ _result_entry,+ _strict_selection_error,+ _validate_extract_urls,+ _web_extract_url,+)import syslogger = logging.getLogger(__name__)-def _web_extract_url(value: Any) -> Optional[str]:- """URL from a model-supplied extract item (str, or dict with ``url``/``href``); None if unusable.-- Never stringify arbitrary objects into fetch targets.- """- if isinstance(value, dict):- value = value.get("url") or value.get("href")- if not isinstance(value, str):- return None- value = value.strip()- return value or None--# ─── Backend Selection ────────────────────────────────────────────────────────def _env_value(name: str) -> str:@@ -115,7 +125,7 @@ def _load_web_config() -> dict:try:from hermes_cli.config import load_configreturn load_config().get("web") or {}- except (ImportError, Exception):+ except Exception:return {}@@ -148,7 +158,10 @@ def _registered_web_provider(backend: str):def _probe(provider, method: str, context: str = "") -> Optional[bool]:- """``bool(provider.<method>())``, or ``None`` if it raised (logged; a broken provider is unavailable)."""+ """``bool(provider.<method>())``, or ``None`` if it raised (logged; a broken provider is unavailable).++ ``context`` is appended to the debug log line (e.g. " during readiness check").+ """try:return bool(getattr(provider, method)())except Exception as exc: # noqa: BLE001 — a broken provider is "unavailable"@@ -197,7 +210,8 @@ def _get_backend() -> str:from tools.tool_backend_helpers import selection_existsif selection_exists("web"):- # Selection exists (use_gateway / per-capability keys) but no shared name.+ # Selection exists (use_gateway / per-capability keys) but no shared+ # name: keep the firecrawl default rather than credential-laddering.return "firecrawl"# Never-configured install. Explicit user credentials beat the managed-@@ -311,14 +325,15 @@ def _is_backend_available(backend: str) -> bool:if registered is not None:return registeredprobe = _BUILTIN_AVAILABILITY.get(backend)- return bool(probe()) if probe else False+ return probe() if probe else Falsedef _web_requires_env() -> list[str]:"""Tool-registry metadata env vars for the web backends.Gateway vars are always listed: gating them on ``managed_nous_tools_enabled()``- cost a synchronous portal HTTP refresh at every CLI startup.+ cost a synchronous portal HTTP refresh at every CLI startup. Contract: set var+ -> tool sees it; not-logged-in users simply lack the vars, so extras are harmless."""return ["EXA_API_KEY",@@ -334,151 +349,10 @@ def _web_requires_env() -> list[str]:]-# ─── Truncate-and-store pipeline ──────────────────────────────────────────────--# Per-page char budget sent to the model (override: web.extract_char_limit).-# Larger pages are head+tail truncated and the full text stored on disk.-DEFAULT_EXTRACT_CHAR_LIMIT = 15000--# Ceiling on the full-text file written to cache/web so a multi-MB page can't-# write unbounded bytes on every extract; the model only ever sees char_limit.-MAX_STORED_TEXT_CHARS = 2_000_000--_CHAR_LIMIT_FLOOR, _CHAR_LIMIT_CEILING = 2000, 500_000-+# Truncate-and-store pipeline lives in tools/web_tools_truncate.py (re-imported above)._debug = DebugSession("web_tools", env_var="WEB_TOOLS_DEBUG")-def _clamp_char_limit(value: Any) -> int:- """Clamp to [2k, 500k]; raises TypeError/ValueError for non-numeric input.-- Floor: below 2k the truncation footer dominates. Ceiling: a config typo- must not blow up context.- """- return max(_CHAR_LIMIT_FLOOR, min(int(value), _CHAR_LIMIT_CEILING))---def _get_extract_char_limit() -> int:- """``web.extract_char_limit`` clamped to a sane range, else the default."""- try:- configured = _load_web_config().get("extract_char_limit")- if configured is not None:- return _clamp_char_limit(configured)- except (TypeError, ValueError):- pass- return DEFAULT_EXTRACT_CHAR_LIMIT---def convert_base64_images_to_links(text: str) -> str:- """Replace inline base64 image blobs (token bombs) with ``[IMAGE: alt]`` placeholders.-- Handles markdown images (alt text kept), parenthesised blobs, and bare- ``data:image/...;base64,`` payloads. Real http(s) markdown image links are- left untouched so the agent can ``web_extract`` / ``vision_analyze`` them.- """- def _md_repl(m: "re.Match[str]") -> str:- alt = (m.group("alt") or "").strip()- return f"[IMAGE: {alt}]" if alt else "[IMAGE]"-- md_b64 = re.compile(- r"!\[(?P<alt>[^\]]*)\]\(\s*data:image/[^;]+;base64,[A-Za-z0-9+/=\s]+\)"- )- out = md_b64.sub(_md_repl, text)- out = re.sub(r"\(\s*data:image/[^;]+;base64,[A-Za-z0-9+/=\s]+\)", "[IMAGE]", out)- out = re.sub(r"data:image/[^;]+;base64,[A-Za-z0-9+/=]+", "[IMAGE]", out)- return out---def _store_full_text(url: str, content: str) -> Optional[str]:- """Write the full page to cache/web (mounted read-only into remote backends); absolute path or None.-- Best-effort: on failure the truncated content is still returned to the model.- """- try:- import hashlib- from hermes_constants import get_hermes_dir- from tools.web_result_cache import _host_slug-- cache_dir = get_hermes_dir("cache/web", "web_cache")- cache_dir.mkdir(parents=True, exist_ok=True)-- digest = hashlib.sha256(url.encode("utf-8")).hexdigest()[:10]- path = cache_dir / f"{_host_slug(url)}-{digest}.md"- if len(content) > MAX_STORED_TEXT_CHARS:- content = (- content[:MAX_STORED_TEXT_CHARS]- + f"\n\n[... stored copy truncated at {MAX_STORED_TEXT_CHARS:,} chars "- f"of {len(content):,}; re-extract a more specific URL for the rest ...]"- )- from tools.spill_safety import write_text_exclusive-- # Deterministic name in a well-known dir: refuse symlinks (lstat-unlink +- # exclusive create); same-URL re-extraction legitimately overwrites. Not- # private: cache/web is bind-mounted into remote backends' container UID.- write_text_exclusive(path, content, private=False, overwrite=True)- return str(path)- except Exception as exc: # noqa: BLE001- logger.debug("Failed to store full web_extract text for %s: %s", url, exc)- return None---def _truncate_with_footer(- content: str,- url: str,- char_limit: int,-) -> tuple[str, bool]:- """Return (model_text, was_truncated).-- Pages over ``char_limit`` become a ~75% head / ~25% tail window cut on line- boundaries, plus a footer saying how much is shown, where the full text is- stored, and the read_file call that pages the omitted middle. Deterministic.- """- if len(content) <= char_limit:- return content, False-- head_budget = int(char_limit * 0.75)- tail_budget = char_limit - head_budget-- head = content[:head_budget]- tail = content[-tail_budget:]- # Snap both cuts to line boundaries (head back, tail forward) so we never slice mid-line.- nl = head.rfind("\n")- if nl > head_budget * 0.5:- head = head[:nl]- nl = tail.find("\n")- if 0 <= nl < tail_budget * 0.5:- tail = tail[nl + 1:]-- total = len(content)- stored_path = _store_full_text(url, content)-- footer_lines = [- "",- "─" * 8 + " [TRUNCATED] " + "─" * 8,- f"Showing {len(head):,} chars (head) + {len(tail):,} chars (tail) "- f"of {total:,} total clean characters.",- ]- if stored_path:- # read_file is 1-indexed; +2 lands on the first line after the shown head.- middle_start_line = head.count("\n") + 2- footer_lines.append(f"Full text saved to: {stored_path}")- footer_lines.append(- f'To read the omitted middle: read_file path="{stored_path}" '- f"offset={middle_start_line} limit=200 (the file is the complete page; "- f"raise/lower offset to page through it)."- )- else:- footer_lines.append(- "Full text could not be stored; re-run web_extract on a more "- "specific URL or use browser_navigate for the complete page."- )- footer_lines.append("─" * 29)-- model_text = head + "\n\n[... middle omitted — see footer ...]\n\n" + tail- model_text += "\n" + "\n".join(footer_lines)- return model_text, True--# ─── Dispatch ─────────────────────────────────────────────────────────────────def _ensure_web_plugins_loaded() -> None:@@ -498,41 +372,6 @@ def _ensure_web_plugins_loaded() -> None:logger.warning("Web plugin discovery failed (non-fatal): %s", exc)-def _disabled_plugin_error(capability: str, disabled_key: str) -> str:- """Error text when the configured backend's bundled plugin is disabled in config."""- vendor = disabled_key.split("/", 1)[-1]- return (- f"web.{capability}_backend is set to '{vendor}', but its "- f"plugin ('{disabled_key}') is disabled in config. "- f"Re-enable it with `hermes plugins enable {disabled_key}` "- "(or remove it from plugins.disabled)."- )---def _strict_selection_error(capability: str, backend: str) -> str:- """Error for a stored-but-unregistered backend: name the disabled plugin, else the bad selection.-- Strict selection never silently switches to whatever the availability walk finds.- """- from agent.web_search_registry import _disabled_web_plugin_for- from tools.tool_backend_helpers import selection_error-- disabled_key = _disabled_web_plugin_for(capability=capability)- if disabled_key:- return _disabled_plugin_error(capability, disabled_key)- return selection_error(- "web", f"'{backend}'", f"no registered web {capability} provider has that name"- )---def _no_provider_error(capability: str, fallback: str) -> str:- """Error when no provider resolved: point at a disabled bundled plugin if that is the real cause."""- from agent.web_search_registry import _disabled_web_plugin_for-- disabled_key = _disabled_web_plugin_for(capability=capability)- return _disabled_plugin_error(capability, disabled_key) if disabled_key else fallback--def _finish_debug(call_name: str, debug_call_data: dict) -> None:_debug.log_call(call_name, debug_call_data)_debug.save()@@ -651,188 +490,6 @@ def _memoized_search(provider, query: str, limit: int) -> dict:return slice_search_response(response_data, limit)-def _result_entry(url: str, error: Optional[str]) -> Dict[str, Any]:- return {"url": url, "title": "", "content": "", "error": error}---_NO_RESULT_ERROR = "Extract backend returned no result for this URL"-_EXTRACT_BACKENDS_HINT = "firecrawl, tavily, keenable, exa, or parallel."---def _extract_error_json(error: str) -> str:- return json.dumps({"success": False, "error": error}, ensure_ascii=False)---def _validate_extract_urls(urls: List[Any]):- """Normalize model-supplied items and block URLs carrying secrets.-- Returns ``(normalized_urls, normalized_indices, invalid_urls, blocked_json)``;- ``blocked_json`` is a whole-call refusal (exfiltration prevention) or None.- Percent-encoded secrets are caught by checking the unquoted forms too.- """- from agent.redact import _PREFIX_RE- from urllib.parse import unquote-- normalized_urls: List[str] = []- normalized_indices: List[int] = []- invalid_urls: Dict[int, Dict[str, Any]] = {}- for index, item in enumerate(urls):- _url = _web_extract_url(item)- if _url is None:- invalid_urls[index] = _result_entry(- "",- f"Invalid URL item at index {index}: expected a URL string "- "or an object with a string 'url' or 'href' field",- )- continue- normalized_url = normalize_url_for_request(_url)- if any(- _PREFIX_RE.search(candidate)- for candidate in (_url, unquote(_url), normalized_url, unquote(normalized_url))- ):- return None, None, None, json.dumps({- "success": False,- "error": "Blocked: URL contains what appears to be an API key or token. "- "Secrets must not be sent in URLs.",- })- sensitive_query_key = sensitive_query_param_name(normalized_url)- if sensitive_query_key:- return None, None, None, json.dumps({- "success": False,- "error": (- "Blocked: URL contains a credential-like query parameter "- f"({sensitive_query_key}). Web extract backends are third-party "- "readers; remove the sensitive query parameter or use a local "- "browser session when this access is explicitly required."- ),- })- normalized_urls.append(normalized_url)- normalized_indices.append(index)- return normalized_urls, normalized_indices, invalid_urls, None---def _resolve_extract_provider(backend: str):- """Resolve the extract provider for *backend*; returns ``(provider, error_json)``.-- A registered search-only backend is a typed error (never a silent switch).- An unregistered name with a stored web selection is a strict-selection- error; with no selection, fall through to the availability walk.- """- from agent.web_search_registry import (- get_active_extract_provider,- get_provider as _wsp_get_provider,- )-- provider = _wsp_get_provider(backend) if backend else None- if provider is not None and provider.supports_extract():- return provider, None- if provider is not None:- return None, _extract_error_json(- f"{provider.display_name} is a search-only "- "backend and cannot extract URL content. "- "Set web.extract_backend to " + _EXTRACT_BACKENDS_HINT- )- from tools.tool_backend_helpers import selection_exists-- if backend and selection_exists("web"):- return None, _extract_error_json(_strict_selection_error("extract", backend))- provider = get_active_extract_provider()- if provider is None:- return None, _extract_error_json(_no_provider_error(- "extract",- "No web extract provider configured. Set web.extract_backend to "- + _EXTRACT_BACKENDS_HINT,- ))- return provider, None---async def _dispatch_extract(provider, fetch_urls: List[str], format: Optional[str]) -> List[dict]:- """Call ``provider.extract`` (async or sync-in-thread), with one-shot keyless rescue.-- Rescue fires on a raised exception or when the WHOLE batch failed (backend- outage, not per-page problems). Rescued batches are never cached.- """- import inspect- from tools.web_result_cache import extract_cache_put-- try:- if inspect.iscoroutinefunction(provider.extract):- results = await provider.extract(fetch_urls, format=format)- else:- results = await asyncio.to_thread(provider.extract, fetch_urls, format=format)- except Exception as exc: # noqa: BLE001 — candidate for rescue- if not _rescue_eligible(provider):- raise- failed = [_result_entry(u, str(exc)) for u in fetch_urls]- return await asyncio.to_thread(_rescue_extract, provider.name, fetch_urls, failed)- if results and all(r.get("error") for r in results) and _rescue_eligible(provider):- return await asyncio.to_thread(_rescue_extract, provider.name, fetch_urls, results)-- # Cache each successful fetch's full clean text (best-effort; oversized skipped).- for fetched_pos, fetched in enumerate(results):- if fetched_pos >= len(fetch_urls):- break- if fetched.get("error"):- continue- _content = fetched.get("raw_content", "") or fetched.get("content", "")- if _content:- extract_cache_put(- fetch_urls[fetched_pos],- _content,- title=fetched.get("title", ""),- format=format,- provider=provider.name,- )- return results---async def _extract_safe_urls(provider, safe_urls: List[str], format: Optional[str]) -> List[dict]:- """Serve cache hits, fetch the rest, and merge back in ``safe_urls`` order.-- The disk cache (tools/web_result_cache.py) sits AFTER the secret-URL gate,- SSRF gate, and provider resolution, and is gated per-URL on the website- policy — a hit skips only the vendor call, never a control. Policy-blocked- URLs are cache misses so dispatch handles them exactly as without a cache.- """- from tools.web_result_cache import extract_cache_get- from tools.website_policy import check_website_access as _check_site-- cached_results: Dict[int, Dict[str, Any]] = {}- fetch_urls: List[str] = []- fetch_positions: List[int] = []- for position, url in enumerate(safe_urls):- hit = None- try:- _policy_block = _check_site(url)- except Exception: # noqa: BLE001 — policy errors fail open like dispatch- _policy_block = None- if _policy_block is None:- hit = extract_cache_get(url, format=format, provider=provider.name)- if hit is not None:- cached_results[position] = hit- else:- fetch_urls.append(url)- fetch_positions.append(position)-- if not fetch_urls:- return [cached_results[i] for i in range(len(safe_urls))]-- logger.info("Web extract via %s: %d URL(s)", provider.name, len(fetch_urls))- results = await _dispatch_extract(provider, fetch_urls, format)- if not cached_results:- return results- merged: List[Dict[str, Any]] = [None] * len(safe_urls) # type: ignore[list-item]- for position, hit in cached_results.items():- merged[position] = hit- for fetched_pos, position in enumerate(fetch_positions):- merged[position] = (- results[fetched_pos]- if fetched_pos < len(results)- else _result_entry(safe_urls[position], _NO_RESULT_ERROR)- )- return merged--async def web_extract_tool(urls: List[Any],format: str = None,@@ -910,46 +567,9 @@ async def web_extract_tool(debug_call_data["pages_extracted"] = pages_extracteddebug_call_data["original_response_size"] = len(json.dumps(response))- effective_char_limit = char_limit if char_limit is not None else _get_extract_char_limit()- try:- effective_char_limit = _clamp_char_limit(effective_char_limit)- except (TypeError, ValueError):- effective_char_limit = DEFAULT_EXTRACT_CHAR_LIMIT-debug_call_data["processing_applied"].append("truncate_and_store")- for result in response.get("results", []):- if result.get("error"):- continue- url = result.get("url", "")- raw_content = result.get("raw_content", "") or result.get("content", "")- if not raw_content:- continue- clean = convert_base64_images_to_links(raw_content)- model_text, truncated = _truncate_with_footer(clean, url, effective_char_limit)- result["content"] = model_text- if truncated:- debug_call_data["pages_truncated"] += 1- debug_call_data["truncation_metrics"].append({- "url": url,- "original_size": len(clean),- "sent_size": len(model_text),- })- logger.info("%s (truncated %d -> %d chars)", url, len(clean), len(model_text))- else:- logger.info("%s (%d chars, whole)", url, len(clean))-- # Trim each entry to url/title/content/error (+ blocked_by_policy when present).- trimmed_results = [- {- "url": r.get("url", ""),- "title": r.get("title", ""),- "content": r.get("content", ""),- "error": r.get("error"),- **({ "blocked_by_policy": r["blocked_by_policy"]} if "blocked_by_policy" in r else {}),- }- for r in response.get("results", [])- ]- trimmed_response = {"results": trimmed_results}+ _truncate_results(response.get("results", []), _effective_char_limit(char_limit), debug_call_data)+ trimmed_response = {"results": _trim_results(response.get("results", []))}if trimmed_response.get("results") == []:result_json = tool_error("Content was inaccessible or not found")@@ -983,16 +603,12 @@ def _provider_is_ready(provider) -> bool:"""if provider is None:return False- for probe in ("is_available", "is_keyless_available"):- try:- if getattr(provider, probe)():- return True- except Exception as exc: # noqa: BLE001 — broken provider == not ready- logger.debug(- "web provider %r.%s() raised during readiness check: %s",- getattr(provider, "name", provider), probe, exc,- )+ for method in ("is_available", "is_keyless_available"):+ ready = _probe(provider, method, " during readiness check")+ if ready is None: # broken provider == not ready; don't try the next probereturn False+ if ready:+ return Truereturn Falsediff --git a/tools/web_tools_extract.py b/tools/web_tools_extract.pynew file mode 100644index 00000000000..928fd558c66--- /dev/null+++ b/tools/web_tools_extract.py@@ -0,0 +1,254 @@+"""web_extract helpers: URL validation, provider resolution, cache-aware dispatch.++Order of controls (each is a gate, never skipped by a cache hit): secret-URL+refusal -> SSRF filter (in web_tools.web_extract_tool) -> provider resolution+(strict selection) -> per-URL website policy -> disk cache -> vendor call with+one-shot keyless rescue.++Extracted from tools/web_tools.py; the names are re-imported there so+``tools.web_tools._validate_extract_urls`` etc. keep working. Logs under the+origin logger name for parity.+"""++import asyncio+import json+import logging+from typing import Any, Dict, List, Optional++from tools.url_safety import normalize_url_for_request, sensitive_query_param_name+from tools.web_tools_rescue import _rescue_eligible, _rescue_extract++logger = logging.getLogger("tools.web_tools")+++def _web_extract_url(value: Any) -> Optional[str]:+ """URL from a model-supplied extract item (str, or dict with ``url``/``href``); None if unusable.++ Models sometimes forward a whole search result instead of its URL, hence the+ dict form. Never stringify arbitrary objects into misleading fetch targets.+ """+ if isinstance(value, dict):+ value = value.get("url") or value.get("href")+ if not isinstance(value, str):+ return None+ value = value.strip()+ return value or None+++def _disabled_plugin_error(capability: str, disabled_key: str) -> str:+ """Error text when the configured backend's bundled plugin is disabled in config."""+ vendor = disabled_key.split("/", 1)[-1]+ return (+ f"web.{capability}_backend is set to '{vendor}', but its "+ f"plugin ('{disabled_key}') is disabled in config. "+ f"Re-enable it with `hermes plugins enable {disabled_key}` "+ "(or remove it from plugins.disabled)."+ )+++def _strict_selection_error(capability: str, backend: str) -> str:+ """Error for a stored-but-unregistered backend: name the disabled plugin, else the bad selection.++ Strict selection never silently switches to whatever the availability walk finds.+ """+ from agent.web_search_registry import _disabled_web_plugin_for+ from tools.tool_backend_helpers import selection_error++ disabled_key = _disabled_web_plugin_for(capability=capability)+ if disabled_key:+ return _disabled_plugin_error(capability, disabled_key)+ return selection_error(+ "web", f"'{backend}'", f"no registered web {capability} provider has that name"+ )+++def _no_provider_error(capability: str, fallback: str) -> str:+ """Error when no provider resolved: point at a disabled bundled plugin if that is the real cause."""+ from agent.web_search_registry import _disabled_web_plugin_for++ disabled_key = _disabled_web_plugin_for(capability=capability)+ return _disabled_plugin_error(capability, disabled_key) if disabled_key else fallback+++def _result_entry(url: str, error: Optional[str]) -> Dict[str, Any]:+ return {"url": url, "title": "", "content": "", "error": error}+++_NO_RESULT_ERROR = "Extract backend returned no result for this URL"+_EXTRACT_BACKENDS_HINT = "firecrawl, tavily, keenable, exa, or parallel."+++def _extract_error_json(error: str) -> str:+ return json.dumps({"success": False, "error": error}, ensure_ascii=False)+++def _validate_extract_urls(urls: List[Any]):+ """Normalize model-supplied items and block URLs carrying secrets.++ Returns ``(normalized_urls, normalized_indices, invalid_urls, blocked_json)``;+ ``blocked_json`` is a whole-call refusal (exfiltration prevention) or None.+ Percent-encoded secrets are caught by checking the unquoted forms too.+ """+ from agent.redact import _PREFIX_RE+ from urllib.parse import unquote++ normalized_urls: List[str] = []+ normalized_indices: List[int] = []+ invalid_urls: Dict[int, Dict[str, Any]] = {}+ for index, item in enumerate(urls):+ _url = _web_extract_url(item)+ if _url is None:+ invalid_urls[index] = _result_entry(+ "",+ f"Invalid URL item at index {index}: expected a URL string "+ "or an object with a string 'url' or 'href' field",+ )+ continue+ normalized_url = normalize_url_for_request(_url)+ if any(+ _PREFIX_RE.search(candidate)+ for candidate in (_url, unquote(_url), normalized_url, unquote(normalized_url))+ ):+ return None, None, None, json.dumps({+ "success": False,+ "error": "Blocked: URL contains what appears to be an API key or token. "+ "Secrets must not be sent in URLs.",+ })+ sensitive_query_key = sensitive_query_param_name(normalized_url)+ if sensitive_query_key:+ return None, None, None, json.dumps({+ "success": False,+ "error": (+ "Blocked: URL contains a credential-like query parameter "+ f"({sensitive_query_key}). Web extract backends are third-party "+ "readers; remove the sensitive query parameter or use a local "+ "browser session when this access is explicitly required."+ ),+ })+ normalized_urls.append(normalized_url)+ normalized_indices.append(index)+ return normalized_urls, normalized_indices, invalid_urls, None+++def _resolve_extract_provider(backend: str):+ """Resolve the extract provider for *backend*; returns ``(provider, error_json)``.++ A registered search-only backend is a typed error (never a silent switch).+ An unregistered name with a stored web selection is a strict-selection+ error; with no selection, fall through to the availability walk.+ """+ from agent.web_search_registry import (+ get_active_extract_provider,+ get_provider as _wsp_get_provider,+ )++ provider = _wsp_get_provider(backend) if backend else None+ if provider is not None and provider.supports_extract():+ return provider, None+ if provider is not None:+ return None, _extract_error_json(+ f"{provider.display_name} is a search-only "+ "backend and cannot extract URL content. "+ "Set web.extract_backend to " + _EXTRACT_BACKENDS_HINT+ )+ from tools.tool_backend_helpers import selection_exists++ if backend and selection_exists("web"):+ return None, _extract_error_json(_strict_selection_error("extract", backend))+ provider = get_active_extract_provider()+ if provider is None:+ return None, _extract_error_json(_no_provider_error(+ "extract",+ "No web extract provider configured. Set web.extract_backend to "+ + _EXTRACT_BACKENDS_HINT,+ ))+ return provider, None+++async def _dispatch_extract(provider, fetch_urls: List[str], format: Optional[str]) -> List[dict]:+ """Call ``provider.extract`` (async or sync-in-thread), with one-shot keyless rescue.++ Rescue fires on a raised exception or when the WHOLE batch failed (backend+ outage, not per-page problems). Rescued batches are never cached.+ """+ import inspect+ from tools.web_result_cache import extract_cache_put++ try:+ if inspect.iscoroutinefunction(provider.extract):+ results = await provider.extract(fetch_urls, format=format)+ else: # sync extract() runs in a thread so network I/O never blocks the loop+ results = await asyncio.to_thread(provider.extract, fetch_urls, format=format)+ except Exception as exc: # noqa: BLE001 — candidate for rescue+ if not _rescue_eligible(provider):+ raise+ failed = [_result_entry(u, str(exc)) for u in fetch_urls]+ return await asyncio.to_thread(_rescue_extract, provider.name, fetch_urls, failed)+ if results and all(r.get("error") for r in results) and _rescue_eligible(provider):+ return await asyncio.to_thread(_rescue_extract, provider.name, fetch_urls, results)++ # Cache each successful fetch's full clean text (best-effort; oversized skipped).+ for fetched_pos, fetched in enumerate(results):+ if fetched_pos >= len(fetch_urls):+ break+ if fetched.get("error"):+ continue+ _content = fetched.get("raw_content", "") or fetched.get("content", "")+ if _content:+ extract_cache_put(+ fetch_urls[fetched_pos],+ _content,+ title=fetched.get("title", ""),+ format=format,+ provider=provider.name,+ )+ return results+++async def _extract_safe_urls(provider, safe_urls: List[str], format: Optional[str]) -> List[dict]:+ """Serve cache hits, fetch the rest, and merge back in ``safe_urls`` order.++ The disk cache (tools/web_result_cache.py) sits AFTER the secret-URL gate,+ SSRF gate, and provider resolution, and is gated per-URL on the website+ policy — a hit skips only the vendor call, never a control. Policy-blocked+ URLs are cache misses so dispatch handles them exactly as without a cache.+ Keys include provider and format, so switching either within the TTL never+ serves the other's content.+ """+ from tools.web_result_cache import extract_cache_get+ from tools.website_policy import check_website_access as _check_site++ cached_results: Dict[int, Dict[str, Any]] = {}+ fetch_urls: List[str] = []+ fetch_positions: List[int] = []+ for position, url in enumerate(safe_urls):+ hit = None+ try:+ _policy_block = _check_site(url)+ except Exception: # noqa: BLE001 — policy errors fail open like dispatch+ _policy_block = None+ if _policy_block is None:+ hit = extract_cache_get(url, format=format, provider=provider.name)+ if hit is not None:+ cached_results[position] = hit+ else:+ fetch_urls.append(url)+ fetch_positions.append(position)++ if not fetch_urls:+ return [cached_results[i] for i in range(len(safe_urls))]++ logger.info("Web extract via %s: %d URL(s)", provider.name, len(fetch_urls))+ results = await _dispatch_extract(provider, fetch_urls, format)+ if not cached_results:+ return results+ merged: List[Dict[str, Any]] = [None] * len(safe_urls) # type: ignore[list-item]+ for position, hit in cached_results.items():+ merged[position] = hit+ for fetched_pos, position in enumerate(fetch_positions):+ merged[position] = (+ results[fetched_pos]+ if fetched_pos < len(results)+ else _result_entry(safe_urls[position], _NO_RESULT_ERROR)+ )+ return mergeddiff --git a/tools/web_tools_truncate.py b/tools/web_tools_truncate.pynew file mode 100644index 00000000000..965f3db01d2--- /dev/null+++ b/tools/web_tools_truncate.py@@ -0,0 +1,211 @@+"""Truncate-and-store pipeline for web_extract (no LLM).++Pages at or under the char budget are returned whole; larger pages become a+head+tail window plus a footer that says how much is shown, where the full text+is stored (cache/web) and the exact read_file call that pages the omitted middle.+Inline base64 images are replaced with ``[IMAGE: alt]`` placeholders.++Extracted from tools/web_tools.py; the names are re-imported there so+``tools.web_tools.MAX_STORED_TEXT_CHARS`` etc. keep working. Logs under the+origin logger name for parity.+"""++import logging+import re+from typing import Any, List, Optional++logger = logging.getLogger("tools.web_tools")++# Per-page char budget sent to the model (override: web.extract_char_limit).+# Larger pages are head+tail truncated and the full text stored on disk.+DEFAULT_EXTRACT_CHAR_LIMIT = 15000++# Ceiling on the full-text file written to cache/web so a multi-MB page can't+# write unbounded bytes on every extract; the model only ever sees char_limit.+MAX_STORED_TEXT_CHARS = 2_000_000++_CHAR_LIMIT_FLOOR, _CHAR_LIMIT_CEILING = 2000, 500_000+++def _clamp_char_limit(value: Any) -> int:+ """Clamp to [2k, 500k]; raises TypeError/ValueError for non-numeric input.++ Floor: below 2k the truncation footer dominates. Ceiling: a config typo+ must not blow up context.+ """+ return max(_CHAR_LIMIT_FLOOR, min(int(value), _CHAR_LIMIT_CEILING))+++def _get_extract_char_limit() -> int:+ """``web.extract_char_limit`` clamped to a sane range, else the default."""+ from tools.web_tools import _load_web_config # lazy: tests patch tools.web_tools._load_web_config++ try:+ configured = _load_web_config().get("extract_char_limit")+ if configured is not None:+ return _clamp_char_limit(configured)+ except (TypeError, ValueError):+ pass+ return DEFAULT_EXTRACT_CHAR_LIMIT+++def convert_base64_images_to_links(text: str) -> str:+ """Replace inline base64 image blobs (token bombs) with ``[IMAGE: alt]`` placeholders.++ Handles markdown images (alt text kept), parenthesised blobs, and bare+ ``data:image/...;base64,`` payloads. Real http(s) markdown image links are+ left untouched so the agent can ``web_extract`` / ``vision_analyze`` them.+ """+ def _md_repl(m: "re.Match[str]") -> str:+ alt = (m.group("alt") or "").strip()+ return f"[IMAGE: {alt}]" if alt else "[IMAGE]"++ md_b64 = re.compile(+ r"!\[(?P<alt>[^\]]*)\]\(\s*data:image/[^;]+;base64,[A-Za-z0-9+/=\s]+\)"+ )+ out = md_b64.sub(_md_repl, text)+ out = re.sub(r"\(\s*data:image/[^;]+;base64,[A-Za-z0-9+/=\s]+\)", "[IMAGE]", out)+ out = re.sub(r"data:image/[^;]+;base64,[A-Za-z0-9+/=]+", "[IMAGE]", out)+ return out+++def _store_full_text(url: str, content: str) -> Optional[str]:+ """Write the full page to cache/web; absolute path or None.++ cache/web is mounted read-only into remote backends (credential_files+ _CACHE_DIRS) so read_file can page the complete text on any backend.+ Best-effort: on failure the truncated content is still returned to the model.+ """+ try:+ import hashlib+ from hermes_constants import get_hermes_dir+ from tools.web_result_cache import _host_slug++ cache_dir = get_hermes_dir("cache/web", "web_cache")+ cache_dir.mkdir(parents=True, exist_ok=True)++ digest = hashlib.sha256(url.encode("utf-8")).hexdigest()[:10]+ path = cache_dir / f"{_host_slug(url)}-{digest}.md"+ if len(content) > MAX_STORED_TEXT_CHARS:+ content = (+ content[:MAX_STORED_TEXT_CHARS]+ + f"\n\n[... stored copy truncated at {MAX_STORED_TEXT_CHARS:,} chars "+ f"of {len(content):,}; re-extract a more specific URL for the rest ...]"+ )+ from tools.spill_safety import write_text_exclusive++ # Deterministic name in a well-known dir: refuse symlinks (lstat-unlink ++ # exclusive create); same-URL re-extraction legitimately overwrites. Not+ # private: cache/web is bind-mounted into remote backends' container UID.+ write_text_exclusive(path, content, private=False, overwrite=True)+ return str(path)+ except Exception as exc: # noqa: BLE001+ logger.debug("Failed to store full web_extract text for %s: %s", url, exc)+ return None+++def _truncate_with_footer(+ content: str,+ url: str,+ char_limit: int,+) -> tuple[str, bool]:+ """Return (model_text, was_truncated).++ Pages over ``char_limit`` become a ~75% head / ~25% tail window cut on line+ boundaries, plus a footer saying how much is shown, where the full text is+ stored, and the read_file call that pages the omitted middle. Deterministic.+ """+ if len(content) <= char_limit:+ return content, False++ head_budget = int(char_limit * 0.75)+ tail_budget = char_limit - head_budget++ head = content[:head_budget]+ tail = content[-tail_budget:]+ # Snap both cuts to line boundaries (head back, tail forward) so we never slice mid-line.+ nl = head.rfind("\n")+ if nl > head_budget * 0.5:+ head = head[:nl]+ nl = tail.find("\n")+ if 0 <= nl < tail_budget * 0.5:+ tail = tail[nl + 1:]++ total = len(content)+ stored_path = _store_full_text(url, content)++ footer_lines = [+ "",+ "─" * 8 + " [TRUNCATED] " + "─" * 8,+ f"Showing {len(head):,} chars (head) + {len(tail):,} chars (tail) "+ f"of {total:,} total clean characters.",+ ]+ if stored_path:+ # read_file is 1-indexed; +2 lands on the first line after the shown head.+ middle_start_line = head.count("\n") + 2+ footer_lines.append(f"Full text saved to: {stored_path}")+ footer_lines.append(+ f'To read the omitted middle: read_file path="{stored_path}" '+ f"offset={middle_start_line} limit=200 (the file is the complete page; "+ f"raise/lower offset to page through it)."+ )+ else:+ footer_lines.append(+ "Full text could not be stored; re-run web_extract on a more "+ "specific URL or use browser_navigate for the complete page."+ )+ footer_lines.append("─" * 29)++ model_text = head + "\n\n[... middle omitted — see footer ...]\n\n" + tail+ model_text += "\n" + "\n".join(footer_lines)+ return model_text, True+++def _effective_char_limit(char_limit: Optional[int]) -> int:+ """Caller's ``char_limit`` (else config) clamped; non-numeric input falls back to the default."""+ value = char_limit if char_limit is not None else _get_extract_char_limit()+ try:+ return _clamp_char_limit(value)+ except (TypeError, ValueError):+ return DEFAULT_EXTRACT_CHAR_LIMIT+++def _truncate_results(results: List[dict], char_limit: int, debug_call_data: dict) -> None:+ """In place: replace each successful entry's content with its base64-cleaned, budgeted text.++ Records per-page truncation metrics into ``debug_call_data``.+ """+ for result in results:+ if result.get("error"):+ continue+ url = result.get("url", "")+ raw_content = result.get("raw_content", "") or result.get("content", "")+ if not raw_content:+ continue+ clean = convert_base64_images_to_links(raw_content)+ model_text, truncated = _truncate_with_footer(clean, url, char_limit)+ result["content"] = model_text+ if truncated:+ debug_call_data["pages_truncated"] += 1+ debug_call_data["truncation_metrics"].append({+ "url": url,+ "original_size": len(clean),+ "sent_size": len(model_text),+ })+ logger.info("%s (truncated %d -> %d chars)", url, len(clean), len(model_text))+ else:+ logger.info("%s (%d chars, whole)", url, len(clean))+++def _trim_results(results: List[dict]) -> List[dict]:+ """Keep only url/title/content/error per entry (+ blocked_by_policy when present)."""+ return [+ {+ "url": r.get("url", ""),+ "title": r.get("title", ""),+ "content": r.get("content", ""),+ "error": r.get("error"),+ **({"blocked_by_policy": r["blocked_by_policy"]} if "blocked_by_policy" in r else {}),+ }+ for r in results+ ]diff --git a/tools/website_policy.py b/tools/website_policy.pyindex a66f563d9ec..80a2e588b9d 100644--- a/tools/website_policy.py+++ b/tools/website_policy.py@@ -17,6 +17,7 @@ from typing import Any, Dict, List, Optional, Tuplefrom urllib.parse import urlparsefrom hermes_constants import get_hermes_home+from tools.url_safety import _normalize_hostname as _normalize_hostlogger = logging.getLogger(__name__)@@ -26,6 +27,7 @@ _DEFAULT_WEBSITE_BLOCKLIST = {"shared_files": [],}+# Without this cache a 50-URL extract would mean 51 YAML parses of config.yaml._CACHE_TTL_SECONDS = 30.0_cache_lock = threading.Lock()_cached_policy: Optional[Dict[str, Any]] = None@@ -41,10 +43,6 @@ class WebsitePolicyError(Exception):"""Raised when a website policy file is malformed."""-def _normalize_host(host: str) -> str:- return (host or "").strip().lower().rstrip(".")--def _normalize_rule(rule: Any) -> Optional[str]:"""Reduce a rule (bare host, URL, or ``host/path``) to a lowercase host; None for blanks/comments."""if not isinstance(rule, str):@@ -79,6 +77,7 @@ def _iter_blocklist_file_rules(path: Path) -> List[str]:def _require_mapping(value: Any, label: str) -> Dict[str, Any]:+ """``None`` (empty YAML section) counts as an empty mapping; other non-dicts are errors."""if value is None:return {}if not isinstance(value, dict):@@ -118,6 +117,7 @@ def _load_policy_config(config_path: Optional[Path] = None) -> Dict[str, Any]:def _require_type(policy: Dict[str, Any], key: str, kind: type, default: Any) -> Any:+ """Typed policy field; ``None``/empty list values are coerced to ``[]`` for lists only."""value = policy.get(key, default)if kind is list:value = value or []@@ -176,7 +176,7 @@ def load_website_blocklist(config_path: Optional[Path] = None) -> Dict[str, Any]result = {"enabled": enabled, "rules": rules}- if config_path == default_path:+ if config_path == default_path: # explicit paths are tests — never cache themwith _cache_lock:_cached_policy = result_cached_policy_path = resolved_pathdiff --git a/tools/xai_http.py b/tools/xai_http.pyindex 1aa817f75bd..33cced4d037 100644--- a/tools/xai_http.py+++ b/tools/xai_http.py@@ -26,7 +26,9 @@ def has_xai_credentials() -> bool:must not do network I/O. Checks, fast-to-slow: ``XAI_API_KEY``; a non-empty``providers.xai-oauth.tokens.access_token`` in ``auth.json``; any``credential_pool.xai-oauth`` entry with an ``access_token`` (pool-only- multi-account grants never write the providers singleton). Never raises.+ multi-account grants never write the providers singleton). Returns False on+ any exception so a corrupted auth store can't block other availability+ scans; truthful refresh/expiry handling happens in the caller's request."""try:from agent.secret_scope import get_secret@@ -225,7 +227,12 @@ def _xai_base_url_override() -> str:def _resolve_explicit_xai_base_url(default: str = DEFAULT_XAI_BASE_URL) -> str:- """Base URL for the explicit-API-key path, origin-pinned so a tampered env override can't exfiltrate the bearer."""+ """Base URL for the explicit-API-key path.++ Origin-pinned via ``_xai_validate_inference_base_url`` so a tampered env+ override can't exfiltrate the bearer; on rejection falls back to ``default``+ rather than raising.+ """override = _xai_base_url_override()try:import hermes_cli.auth as auth_mod@@ -247,8 +254,10 @@ def resolve_xai_http_credentials(``get_env_value`` so ``~/.hermes/.env`` keys count). ``prefer_api_key=True``inverts that for API-metered endpoints where the subscription OAuth bearerauthorizes but misbehaves (x_search answers without citations, TTS 403s).- ``force_refresh=True`` forces an OAuth refresh; pass the rejected bearer as- ``api_key_hint`` so a multi-account pool refreshes the issuing entry.+ Both branches honor ``HERMES_XAI_BASE_URL``/``XAI_BASE_URL`` behind the same+ origin-pinning validation. ``force_refresh=True`` forces an OAuth refresh;+ pass the rejected bearer as ``api_key_hint`` so a multi-account pool+ refreshes the issuing entry, not whichever its strategy selects first."""if prefer_api_key:explicit_key = str(_resolve_explicit_xai_api_key() or "").strip()