The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(web): explicit Firecrawl selection works keyless against the public cloud API
LeonSGP43f51e61136ac6
diff --git a/plugins/web/firecrawl/plugin.yaml b/plugins/web/firecrawl/plugin.yamlindex 063af47d738..6910545a5a6 100644--- a/plugins/web/firecrawl/plugin.yaml+++ b/plugins/web/firecrawl/plugin.yaml@@ -1,6 +1,6 @@name: web-firecrawlversion: 1.0.0-description: "Firecrawl web search + content extraction. Supports direct API and Nous-hosted tool-gateway routing for subscribers. Requires FIRECRAWL_API_KEY (or FIRECRAWL_API_URL for self-hosted), or an active Nous subscription with FIRECRAWL_GATEWAY_URL."+description: "Firecrawl web search + content extraction. Supports keyless cloud, direct API, and Nous-hosted tool-gateway routing for subscribers."author: NousResearchkind: backendprovides_web_providers:diff --git a/plugins/web/firecrawl/provider.py b/plugins/web/firecrawl/provider.pyindex e18e78ea487..2d5feda823f 100644--- a/plugins/web/firecrawl/provider.py+++ b/plugins/web/firecrawl/provider.py@@ -50,12 +50,16 @@ import loggingimport osfrom typing import Any, Dict, List, NoReturn, Optional, TYPE_CHECKING+import httpx+from agent.web_search_provider import WebSearchProviderfrom tools.url_safety import is_safe_urlfrom tools.website_policy import check_website_accesslogger = logging.getLogger(__name__)+_FIRECRAWL_CLOUD_API_URL = "https://api.firecrawl.dev"+# ---------------------------------------------------------------------------# Lazy Firecrawl SDK proxy@@ -121,13 +125,26 @@ Firecrawl = _FirecrawlProxy()def _get_direct_firecrawl_config() -> Optional[tuple]:- """Return explicit direct Firecrawl kwargs + cache key, or None when unset."""+ """Return direct Firecrawl (mode, kwargs, cache key), or None when unavailable.++ ``mode`` is ``"sdk"`` (keyed / self-hosted via the Firecrawl SDK) or+ ``"keyless"`` (explicit Firecrawl selection with no credentials — served+ by :class:`_KeylessFirecrawlClient` against the public cloud API, which+ accepts anonymous rate-limited requests). Keyless requires the explicit+ selection so an unconfigured install never silently routes to it.+ """from hermes_cli.config import get_env_valueapi_key = (get_env_value("FIRECRAWL_API_KEY") or "").strip()api_url = (get_env_value("FIRECRAWL_API_URL") or "").strip().rstrip("/")if not api_key and not api_url:+ if _is_explicit_firecrawl_selection():+ return (+ "keyless",+ {"api_url": _FIRECRAWL_CLOUD_API_URL},+ ("direct-keyless", _FIRECRAWL_CLOUD_API_URL, None),+ )return Nonekwargs: Dict[str, str] = {}@@ -136,7 +153,46 @@ def _get_direct_firecrawl_config() -> Optional[tuple]:if api_url:kwargs["api_url"] = api_url- return kwargs, ("direct", api_url or None, api_key or None)+ return "sdk", kwargs, ("direct", api_url or None, api_key or None)+++def _is_explicit_firecrawl_selection() -> bool:+ """Return True when config explicitly selects Firecrawl for web tools."""+ import tools.web_tools as _wt++ cfg = _wt._load_web_config()+ return any(+ (cfg.get(key) or "").lower().strip() == "firecrawl"+ for key in ("backend", "search_backend", "extract_backend")+ )+++class _KeylessFirecrawlClient:+ """Minimal REST client for Firecrawl's keyless cloud mode.++ Duck-types the two SDK methods the provider calls (``search`` /+ ``scrape``) so the rest of the pipeline (result normalizers, caching)+ is unchanged. No Authorization header is ever sent.+ """++ def __init__(self, api_url: str = _FIRECRAWL_CLOUD_API_URL):+ self.api_url = api_url.rstrip("/")++ def _post(self, path: str, payload: Dict[str, Any]) -> Dict[str, Any]:+ response = httpx.post(+ f"{self.api_url}{path}",+ json=payload,+ headers={"Content-Type": "application/json"},+ timeout=60.0,+ )+ response.raise_for_status()+ return response.json()++ def search(self, *, query: str, limit: int = 5) -> Dict[str, Any]:+ return self._post("/v2/search", {"query": query, "limit": limit})++ def scrape(self, *, url: str, formats: List[str]) -> Dict[str, Any]:+ return self._post("/v2/scrape", {"url": url, "formats": formats})def _get_firecrawl_gateway_url() -> str:@@ -286,9 +342,11 @@ def _get_firecrawl_client() -> Any:"unreachable)",))kwargs, client_config = managed+ client_mode = "sdk"elif selected is not None or selection_exists("web"):# Stored vendor selection (or per-capability web keys routing to- # firecrawl): direct Firecrawl only.+ # firecrawl): direct Firecrawl only. With no credentials, the+ # explicit selection unlocks keyless cloud mode instead of erroring.if direct_config is None:logger.error("Firecrawl client initialization failed: direct Firecrawl "@@ -299,9 +357,9 @@ def _get_firecrawl_client() -> Any:selected or "firecrawl","neither FIRECRAWL_API_KEY nor FIRECRAWL_API_URL is set",))- kwargs, client_config = direct_config+ client_mode, kwargs, client_config = direct_configelif direct_config is not None:- kwargs, client_config = direct_config+ client_mode, kwargs, client_config = direct_configelse:# Never-configured web section: legacy managed fallback.managed = _managed_kwargs()@@ -312,6 +370,7 @@ def _get_firecrawl_client() -> Any:)_raise_web_backend_configuration_error()kwargs, client_config = managed+ client_mode = "sdk"cached = getattr(_wt, "_firecrawl_client", None)cached_config = getattr(_wt, "_firecrawl_client_config", None)@@ -320,7 +379,10 @@ def _get_firecrawl_client() -> Any:# Construct via the re-exported Firecrawl proxy on tools.web_tools so# unit tests patching ``tools.web_tools.Firecrawl`` see their mock.- _wt._firecrawl_client = _wt.Firecrawl(**kwargs)+ if client_mode == "keyless":+ _wt._firecrawl_client = _KeylessFirecrawlClient(api_url=kwargs["api_url"])+ else:+ _wt._firecrawl_client = _wt.Firecrawl(**kwargs)_wt._firecrawl_client_config = client_configreturn _wt._firecrawl_client@@ -662,15 +724,15 @@ class FirecrawlWebSearchProvider(WebSearchProvider):def get_setup_schema(self) -> Dict[str, Any]:return {"name": "Firecrawl",- "badge": "paid · optional gateway",+ "badge": "keyless/paid · optional gateway","tag": (- "Full search + extract; supports direct API and "- "Nous tool-gateway routing."+ "Full search + extract; supports keyless cloud, direct API, "+ "and Nous tool-gateway routing."),"env_vars": [{"key": "FIRECRAWL_API_KEY",- "prompt": "Firecrawl API key (or leave blank for self-hosted)",+ "prompt": "Firecrawl API key (optional; blank = keyless cloud or self-hosted)","url": "https://docs.firecrawl.dev/introduction",},],diff --git a/tests/plugins/web/test_web_search_provider_plugins.py b/tests/plugins/web/test_web_search_provider_plugins.pyindex a24b303a5ef..d462c0a9339 100644--- a/tests/plugins/web/test_web_search_provider_plugins.py+++ b/tests/plugins/web/test_web_search_provider_plugins.py@@ -203,6 +203,23 @@ class TestIsAvailable:monkeypatch.setenv("FIRECRAWL_API_URL", "http://localhost:3002")assert p.is_available() is True+ def test_firecrawl_explicit_config_allows_keyless_cloud(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _ensure_plugins_loaded()+ from agent.web_search_registry import get_provider++ p = get_provider("firecrawl")+ assert p is not None+ assert p.is_available() is False++ monkeypatch.setattr(+ "tools.web_tools._load_web_config",+ lambda: {"backend": "firecrawl"},+ raising=False,+ )+ assert p.is_available() is True+def test_ddgs_always_available_when_package_importable(self) -> None:"""DDGS is the always-on fallback — no API key required.diff --git a/tests/tools/test_web_tools_config.py b/tests/tools/test_web_tools_config.pyindex a4753c74c02..49b2e6adecb 100644--- a/tests/tools/test_web_tools_config.py+++ b/tests/tools/test_web_tools_config.py@@ -115,6 +115,82 @@ class TestFirecrawlClientConfig:with pytest.raises(ValueError):_get_firecrawl_client()+ def test_explicit_firecrawl_config_without_creds_uses_keyless_client(self):+ """Explicit Firecrawl config should build the keyless cloud client."""+ from plugins.web.firecrawl import provider as firecrawl_provider++ with patch("tools.web_tools._load_web_config", return_value={"backend": "firecrawl"}):+ with patch("tools.web_tools._read_nous_access_token", return_value=None):+ with patch("tools.web_tools.Firecrawl", side_effect=AssertionError("SDK path should not run")):+ from tools.web_tools import _get_firecrawl_client++ result = _get_firecrawl_client()++ assert isinstance(result, firecrawl_provider._KeylessFirecrawlClient)+ assert result.api_url == "https://api.firecrawl.dev"++ def test_keyless_firecrawl_search_omits_authorization_header(self, monkeypatch):+ """Keyless Firecrawl search must not send a bearer header."""+ from plugins.web.firecrawl import provider as firecrawl_provider++ captured = {}++ class _Response:+ def raise_for_status(self):+ return None++ def json(self):+ return {"success": True, "data": {"web": []}}++ def _fake_post(url, *, json, headers, timeout):+ captured["url"] = url+ captured["json"] = json+ captured["headers"] = headers+ captured["timeout"] = timeout+ return _Response()++ monkeypatch.setattr(firecrawl_provider.httpx, "post", _fake_post)++ client = firecrawl_provider._KeylessFirecrawlClient()+ result = client.search(query="firecrawl", limit=1)++ assert result["success"] is True+ assert captured["url"] == "https://api.firecrawl.dev/v2/search"+ assert captured["json"] == {"query": "firecrawl", "limit": 1}+ assert captured["headers"] == {"Content-Type": "application/json"}+ assert "Authorization" not in captured["headers"]++ def test_keyless_firecrawl_scrape_omits_authorization_header(self, monkeypatch):+ """Keyless Firecrawl scrape must not send a bearer header."""+ from plugins.web.firecrawl import provider as firecrawl_provider++ captured = {}++ class _Response:+ def raise_for_status(self):+ return None++ def json(self):+ return {"success": True, "data": {"markdown": "# ok"}}++ def _fake_post(url, *, json, headers, timeout):+ captured["url"] = url+ captured["json"] = json+ captured["headers"] = headers+ captured["timeout"] = timeout+ return _Response()++ monkeypatch.setattr(firecrawl_provider.httpx, "post", _fake_post)++ client = firecrawl_provider._KeylessFirecrawlClient()+ result = client.scrape(url="https://example.com", formats=["markdown"])++ assert result["success"] is True+ assert captured["url"] == "https://api.firecrawl.dev/v2/scrape"+ assert captured["json"] == {"url": "https://example.com", "formats": ["markdown"]}+ assert captured["headers"] == {"Content-Type": "application/json"}+ assert "Authorization" not in captured["headers"]+class TestBackendSelection:"""Test suite for _get_backend() backend selection logic.@@ -608,7 +684,8 @@ class TestFirecrawlEnvResolution:result = _get_direct_firecrawl_config()assert result is not None, "get_env_value fallback should find the key"- kwargs, _cache_key = result+ mode, kwargs, _cache_key = result+ assert mode == "sdk"assert kwargs["api_key"] == fake_keydef test_direct_config_reads_url_via_get_env_value(self, monkeypatch: pytest.MonkeyPatch) -> None:@@ -625,7 +702,8 @@ class TestFirecrawlEnvResolution:result = _get_direct_firecrawl_config()assert result is not None- kwargs, _cache_key = result+ mode, kwargs, _cache_key = result+ assert mode == "sdk"assert kwargs["api_url"] == fake_url.rstrip("/")diff --git a/tests/tools/test_web_tools_tavily.py b/tests/tools/test_web_tools_tavily.pyindex 92baef2aa8b..46849ed2d88 100644--- a/tests/tools/test_web_tools_tavily.py+++ b/tests/tools/test_web_tools_tavily.py@@ -192,11 +192,16 @@ class TestTavilyAvailability:assert _get_backend() == "ddgs"def test_no_keys_defaults_to_firecrawl(self):+ """Keyless tier disabled: zero-credential resolve hits the legacy+ firecrawl sentinel. (With the tier on — the default — it resolves+ to the Exa/Parallel keyless split; see test_web_keyless_fallback.py.)+ """from tools.web_tools import _get_backendwith patch("tools.web_tools._load_web_config", return_value={}), \patch("tools.web_tools._is_tool_gateway_ready", return_value=False), \patch("tools.web_tools._ddgs_package_importable", return_value=False), \- patch("tools.web_tools._list_registered_web_providers", return_value=[]):+ patch("tools.web_tools._list_registered_web_providers", return_value=[]), \+ patch("agent.web_search_registry._keyless_tier_enabled", return_value=False):os.environ.pop("TAVILY_API_KEY", None)assert _get_backend() == "firecrawl"