The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(web): Exa and Keenable origin statuses never read as vendor throttling
Teknium6696c7b0a404
diff --git a/plugins/web/_common.py b/plugins/web/_common.pyindex 042564d2415..8ec4e439cd1 100644--- a/plugins/web/_common.py+++ b/plugins/web/_common.py@@ -7,6 +7,7 @@ slots) lazily at call time so monkeypatching the source module keeps working.from __future__ import annotations+import jsonimport loggingimport refrom typing import Any, Awaitable, Callable, Dict, List, Optional@@ -96,6 +97,33 @@ def origin_http_error(status: Any, reason: Any = None) -> Optional[str]:return f"HTTP {code} from origin: {detail}" if detail else f"HTTP {code} from origin"+# Vendors that fetch the page themselves also report its status in their own words: Exa+# ``CRAWL_HTTP_<code>`` / ``CRAWL_NOT_FOUND``; Keenable mirrors the target's code as its own HTTP+# status with a message about the target. Read as vendor errors, an origin 429 looked like the+# vendor throttling us and walked the keyless ring.+_EXA_CRAWL_STATUS_RE = re.compile(r"\bCRAWL_(?:HTTP_(\d{3})|(NOT_FOUND))\s*$")+_KEENABLE_ORIGIN_MESSAGE_RE = re.compile(r"the (?:target server|page does not exist)\b", re.IGNORECASE)+++def exa_crawl_status(text: Any) -> Optional[int]:+ """The origin status an Exa crawl error tag ends with (``CRAWL_HTTP_429`` → 429, ``CRAWL_NOT_FOUND`` → 404)."""+ match = _EXA_CRAWL_STATUS_RE.search(str(text or ""))+ if match is None:+ return None+ return int(match.group(1)) if match.group(1) else 404+++def keenable_origin_error(status: Any, body: str) -> Optional[str]:+ """``HTTP <status> from origin: <message>`` when a Keenable fetch error describes the target's+ answer; None for Keenable's own refusals (its rate limit for this client, auth, 5xx)."""+ try:+ data = json.loads(body or "")+ except ValueError:+ return None+ message = str(data.get("message") or "").strip() if isinstance(data, dict) else ""+ return origin_http_error(status, message) if _KEENABLE_ORIGIN_MESSAGE_RE.match(message) else None++def with_origin_status(entry: dict[str, Any], status: Any, reason: Any = None) -> dict[str, Any]:"""Set ``error`` on an extract entry whose target answered >= 400; the error page bodystays in ``content`` (it can still explain the refusal)."""diff --git a/plugins/web/exa/provider.py b/plugins/web/exa/provider.pyindex 865c29ea995..1794d647ca6 100644--- a/plugins/web/exa/provider.py+++ b/plugins/web/exa/provider.py@@ -10,7 +10,7 @@ import loggingfrom typing import Any, Dict, Listfrom plugins.web._common import (- BaseWebSearchProvider, cached_sdk_client, document, keyless_extract, keyless_search, keyless_variant_schema,+ BaseWebSearchProvider, cached_sdk_client, document, exa_crawl_status, keyless_extract, keyless_search, keyless_variant_schema,provider_env, run_extract, run_search, search_ok, use_keyless, vendor_error_entry, web_hit,)@@ -29,6 +29,11 @@ def _get_exa_client() -> Any:return cached_sdk_client("_exa_client", "EXA_API_KEY", _MISSING_KEY, "exa", _factory)+def _crawl_status(error: Any) -> Any:+ """The origin status of a failed ``statuses[]`` entry: ``http_status_code``, else the one its tag names."""+ return getattr(error, "http_status_code", None) or exa_crawl_status(getattr(error, "tag", None))++class ExaWebSearchProvider(BaseWebSearchProvider):"""Exa search + extract provider."""@@ -60,7 +65,7 @@ class ExaWebSearchProvider(BaseWebSearchProvider):results = [document(r.url or "", r.title or "", r.text or "") for r in response.results or []]# A URL Exa could not fetch is absent from ``results``; its reason is in ``statuses``.return results + [- vendor_error_entry(s.id or "", status=getattr(s.error, "http_status_code", None), reason=getattr(s.error, "tag", None))+ vendor_error_entry(s.id or "", status=_crawl_status(s.error), reason=getattr(s.error, "tag", None))for s in getattr(response, "statuses", None) or [] if s.status == "error"]diff --git a/plugins/web/keenable/provider.py b/plugins/web/keenable/provider.pyindex a0e9ce25a4f..49dd4a32b78 100644--- a/plugins/web/keenable/provider.py+++ b/plugins/web/keenable/provider.py@@ -12,7 +12,7 @@ from typing import Any, Dict, Listfrom agent.ssl_verify import requests_verifyfrom plugins.web._common import (- SEARCH_LIMIT_CAP, BaseWebSearchProvider, document, http_status_detail, keyless_extract, keyless_search,+ SEARCH_LIMIT_CAP, BaseWebSearchProvider, document, http_status_detail, keenable_origin_error, keyless_extract, keyless_search,keyless_variant_schema, page_error, provider_env, run_extract, run_search, search_fail, search_ok, use_keyless, web_hit,)@@ -74,6 +74,9 @@ class KeenableWebSearchProvider(BaseWebSearchProvider):try:response = requests.get(f"{_KEENABLE_API_URL}/v1/fetch", params={"url": url}, headers=_keenable_headers(api_key), timeout=30, verify=requests_verify())if response.status_code >= 400:+ if origin := keenable_origin_error(response.status_code, response.text):+ results.append(page_error(url, origin))+ continueraise ValueError(http_status_detail(response))data = response.json()results.append(document(data.get("url") or url, data.get("title") or "", data.get("content") or "", source_url=url))diff --git a/plugins/web/keyless_mcp.py b/plugins/web/keyless_mcp.pyindex d4a633c8a52..f97f77a1158 100644--- a/plugins/web/keyless_mcp.py+++ b/plugins/web/keyless_mcp.py@@ -15,7 +15,8 @@ import uuidfrom typing import Any, Callable, Dict, List, Optionalfrom plugins.web._common import (- document as _page, is_origin_http_error, page_error as _page_error, search_fail, search_ok, vendor_error_entry, web_hit as _row,+ document as _page, exa_crawl_status, is_origin_http_error, keenable_origin_error, origin_http_error, page_error as _page_error, search_fail,+ search_ok, vendor_error_entry, web_hit as _row,)logger = logging.getLogger(__name__)@@ -279,7 +280,13 @@ def exa_search_keyless(query: str, limit: int = 5) -> dict[str, Any]:def exa_extract_keyless(urls: list[str]) -> list[dict[str, Any]]:"""Called per-URL; the tool returns one combined text payload."""def _fetch(url: str) -> dict[str, Any]:- text = mcp_call(EXA_MCP_URL, "web_fetch_exa", {"urls": [url]})+ try:+ text = mcp_call(EXA_MCP_URL, "web_fetch_exa", {"urls": [url]})+ except KeylessMCPError as exc:+ # ``...: CRAWL_HTTP_429`` is the page's answer, not Exa throttling this client.+ if origin := origin_http_error(exa_crawl_status(exc)):+ return _page_error(url, origin)+ raise# Title: first markdown H1 or ``Title:`` line, whichever comes first.titles = (_after(s, "# " if s.startswith("# ") else "Title:") for s in map(str.strip, text.splitlines()) if s.startswith(("# ", "Title:")))return _page(url, next(titles, ""), text)@@ -316,7 +323,8 @@ def _keenable_request(method: str, path: str, **kwargs: Any) -> dict[str, Any]:headers["Content-Type"] = "application/json"response = getattr(requests, method)(f"{KEENABLE_API_URL}{path}", headers=headers, timeout=_TIMEOUT_SECONDS, **kwargs)if response.status_code >= 400:- raise KeylessMCPError(f"HTTP {response.status_code}: {_response_text(response).strip()[:300]}")+ body = _response_text(response).strip()+ raise KeylessMCPError(keenable_origin_error(response.status_code, body) or f"HTTP {response.status_code}: {body[:300]}")return response.json()@@ -333,7 +341,12 @@ def keenable_search_keyless(query: str, limit: int = 5) -> dict[str, Any]:def keenable_extract_keyless(urls: list[str]) -> list[dict[str, Any]]:def _fetch(url: str) -> dict[str, Any]:- data = _keenable_request("get", "/v1/fetch/public", params={"url": url})+ try:+ data = _keenable_request("get", "/v1/fetch/public", params={"url": url})+ except KeylessMCPError as exc:+ if is_origin_http_error(str(exc)): # the target's answer, relayed by Keenable+ return _page_error(url, str(exc))+ raisereturn _page(data.get("url") or url, data.get("title") or "", data.get("content") or "", source_url=url)return _per_url(urls, _fetch, "keenable")diff --git a/tests/plugins/web/test_extract_origin_status.py b/tests/plugins/web/test_extract_origin_status.pyindex edfb51250e3..80bb87461f7 100644--- a/tests/plugins/web/test_extract_origin_status.py+++ b/tests/plugins/web/test_extract_origin_status.py@@ -131,3 +131,38 @@ def test_origin_429_does_not_walk_the_keyless_extract_ring():keyless_mcp._KEYLESS_EXTRACTORS["parallel"] = _extractor("parallel", "HTTP 429: Too Many Requests")[entry] = keyless_mcp.extract_with_failover("parallel", ["https://t.test/x"])assert (calls, entry["error"]) == (["parallel", "firecrawl"], "Firecrawl: other error")+++def test_vendor_reported_origin_status_does_not_walk_the_keyless_extract_ring():+ """Keenable and keyless Exa relay the target's 429 in their own words (bodies as served live+ for httpbin.org/status/429). That is the page's answer: no failover, and the error says so.+ Keenable throttling this client is still a vendor rate limit and fails over."""+ def _http(status, body, content_type="application/json"):+ return SimpleNamespace(status_code=status, headers={"Content-Type": content_type},+ content=body.encode(), json=lambda: json.loads(body))++ target_429 = json.dumps({"error": "Rate limit exceeded", "message": "The target server rate-limited this fetch, please retry shortly."})+ own_429 = json.dumps({"error": "Rate limit exceeded", "message": "Too many requests, slow down."})+ exa_crawl_429 = "data: " + json.dumps({"jsonrpc": "2.0", "id": 1, "result": {"isError": True, "content": [+ {"type": "text", "text": "Error fetching URL(s): https://t.test/x: CRAWL_HTTP_429"}]}})+ keenable = {"body": target_429}++ def _ring(start):+ return ["keenable", "exa"] if start == "keenable" else ["exa", "keenable"]++ url = "https://t.test/x"+ with patch.object(keyless_mcp, "_ring_order", side_effect=_ring), \+ patch("requests.get", side_effect=lambda *_a, **_kw: _http(429, keenable["body"])) as keenable_get, \+ patch("requests.post", return_value=_http(200, exa_crawl_429, "text/event-stream")) as exa_post:+ [entry] = keyless_mcp.extract_with_failover("keenable", [url])+ assert entry["error"] == "HTTP 429 from origin: The target server rate-limited this fetch, please retry shortly."+ assert (keenable_get.call_count, exa_post.call_count) == (1, 0)++ [entry] = keyless_mcp.extract_with_failover("exa", [url])+ assert entry["error"] == "HTTP 429 from origin"+ assert (exa_post.call_count, keenable_get.call_count) == (1, 1)++ keenable["body"] = own_429+ keenable_get.reset_mock(), exa_post.reset_mock()+ keyless_mcp.extract_with_failover("keenable", [url])+ assert (keenable_get.call_count, exa_post.call_count) == (1, 1)