The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(web): serve free managed fast search to every Nous identity
Robin Fernandesfd24751a9ff5
diff --git a/plugins/web/perplexity/provider.py b/plugins/web/perplexity/provider.pyindex b2d446f5d88..173b758d672 100644--- a/plugins/web/perplexity/provider.py+++ b/plugins/web/perplexity/provider.py@@ -21,9 +21,10 @@ Env vars::PERPLEXITY_API_KEY=... # required for direct search and extractPERPLEXITY_BASE_URL=... # optional override of https://api.perplexity.ai-No anonymous tier. The Nous Subscription selection serves search through-``perplexity-gateway.<TOOL_GATEWAY_DOMAIN>`` using the Nous token; a direct-key takes precedence. Managed extract stays on Firecrawl.+No anonymous tier at Perplexity itself. The managed route serves search through+``perplexity-gateway.<TOOL_GATEWAY_DOMAIN>`` as ``search_type: "fast"``, which the+gateway serves to any Nous identity (paid or not); a direct key takes precedence.+Managed extract stays on Firecrawl.Extract caveat: Perplexity's only supported page-content route returns thepassages of a page relevant to a *query* (elisions marked ``…``), not the@@ -77,7 +78,7 @@ def _managed_gateway(token_reader=None):if not _managed_web_search():return None- return gw.resolve_managed_tool_gateway("perplexity", token_reader=token_reader)+ return gw.resolve_free_search_gateway(token_reader=token_reader)def _perplexity_request(endpoint: str, payload: Dict[str, Any], gateway=None) -> Dict[str, Any]:@@ -216,7 +217,7 @@ class PerplexityWebSearchProvider(WebSearchProvider):if gateway is None and not direct and _managed_web_search():from tools.tool_backend_helpers import NOUS_MANAGED_PROVIDER, selection_errorraise ValueError(selection_error(- "web", NOUS_MANAGED_PROVIDER, "the Nous Tool Gateway is not available (not entitled or unreachable)"))+ "web", NOUS_MANAGED_PROVIDER, "the Nous Tool Gateway is not available (no Nous identity or unreachable)"))logger.info("Perplexity search: '%s' (limit=%d%s)", query, limit, ", managed" if gateway else "")payload = {"query": query,diff --git a/tests/tools/test_web_free_fast_search.py b/tests/tools/test_web_free_fast_search.pynew file mode 100644index 00000000000..fbcecddac7f--- /dev/null+++ b/tests/tools/test_web_free_fast_search.py@@ -0,0 +1,168 @@+"""Free managed Perplexity fast search for any Nous identity: anonymous, or signed in with no usable+credits and no tool pool. The gateway serves ``POST /search`` + ``search_type: "fast"`` without funding+checks, so the local paid-tool gate must not block this one route while every other managed vendor+keeps it. Real config, real auth store, real selection-to-provider dispatch over local HTTP."""++import base64+import json+import time+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from threading import Thread++import pytest++ANON = {"sub": "anon-1", "account_tier": "anonymous", "paid_access": False}+EXHAUSTED = {"sub": "user-1", "paid_access": False, "tool_access": {"enabled": False, "coverage": {}}}+++def _nous_state(claims: dict, auth_method: str) -> dict:+ def seg(obj):+ return base64.urlsafe_b64encode(json.dumps(obj).encode()).rstrip(b"=").decode()+ token = f"{seg({'alg': 'none'})}.{seg({**claims, 'exp': int(time.time()) + 3600})}.sig"+ return {"auth_method": auth_method, "access_token": token, "expires_at": "2099-01-01T00:00:00Z"}+++def gateway_server(monkeypatch):+ class Log(list):+ base = ""++ requests = Log()++ class Handler(BaseHTTPRequestHandler):+ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))+ requests.append((self.path, dict(self.headers), body))+ ok = self.path in ("/perplexity/search", "/direct/search")+ content = json.dumps({"results": [{"title": "t", "url": "https://example.test", "snippet": "s"}]}+ if ok else {"error": "payment required"}).encode()+ self.send_response(200 if ok else 402)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(content)))+ self.end_headers()+ self.wfile.write(content)++ def log_message(self, format, *args):+ pass++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = Thread(target=server.serve_forever, daemon=True)+ thread.start()+ requests.base = f"http://127.0.0.1:{server.server_port}"+ monkeypatch.setenv("PERPLEXITY_GATEWAY_URL", requests.base + "/perplexity")+ monkeypatch.setenv("PERPLEXITY_BASE_URL", requests.base + "/direct")+ monkeypatch.setenv("FIRECRAWL_GATEWAY_URL", requests.base)+ monkeypatch.setattr("tools.web_tools._firecrawl_client", None, raising=False)+ try:+ yield requests+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=2)+++def _write_home(home, monkeypatch, *, nous_state=None, config=None):+ from hermes_cli.config import atomic_config_write+ from hermes_cli.nous_account import reset_nous_portal_account_info_cache++ home.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setenv("HERMES_GUEST_ONBOARDING", "1")+ monkeypatch.delenv("PERPLEXITY_API_KEY", raising=False)+ monkeypatch.delenv("TOOL_GATEWAY_USER_TOKEN", raising=False)+ atomic_config_write(home / "config.yaml", {"web": {"keyless_rescue": False}, **(config or {})})+ if nous_state is not None:+ (home / "auth.json").write_text(json.dumps({"version": 1, "providers": {"nous": nous_state}}))+ reset_nous_portal_account_info_cache()+++def _search():+ from tools import web_tools+ from tests.tools.conftest import register_all_web_providers++ register_all_web_providers()+ return json.loads(web_tools.web_search_tool("free fast search", limit=3))+++def _calls(log):+ return [(path, headers["Authorization"], body.get("search_type")) for path, headers, body in log]++[email protected]("state", [_nous_state(ANON, "anonymous"), _nous_state(EXHAUSTED, "oauth")])+def test_unentitled_nous_identity_autodetects_free_fast_search(monkeypatch, tmp_path, gateway_server, state):+ from tools import web_tools+ from tools.tool_backend_helpers import managed_nous_tools_enabled++ _write_home(tmp_path / "home", monkeypatch, nous_state=state)+ # Premise: the paid-tool gate is closed for this identity and stays closed for extract.+ assert managed_nous_tools_enabled() is False+ assert web_tools.check_firecrawl_api_key() is False+ assert web_tools._get_extract_backend() != "perplexity"++ result = _search()++ assert result["success"] is True, result+ assert _calls(gateway_server) == [("/perplexity/search", f"Bearer {state['access_token']}", "fast")]+++def test_free_fast_search_failure_skips_paid_firecrawl_but_keeps_keyless_rescue(monkeypatch, tmp_path, gateway_server):+ from plugins.web import keyless_mcp++ state = _nous_state(ANON, "anonymous")+ _write_home(tmp_path / "home", monkeypatch, nous_state=state, config={"web": {"keyless_rescue": True}})+ monkeypatch.setenv("PERPLEXITY_GATEWAY_URL", gateway_server.base + "/down")+ rescued = {"success": True, "data": {"web": [{"title": "ring", "url": "https://ring.test", "description": "", "position": 1}]}}+ monkeypatch.setattr(keyless_mcp, "search_with_failover", lambda *a, **kw: dict(rescued, data=dict(rescued["data"])))++ result = _search()++ assert result["data"]["rescued_from"] == "perplexity"+ assert _calls(gateway_server) == [("/down/search", f"Bearer {state['access_token']}", "fast")]++[email protected]("state,config", [+ (_nous_state(ANON, "anonymous"), {"nous": {"guest": False}}),+ (None, {}),+ (_nous_state(ANON, "anonymous"), {"web": {"search_backend": "exa"}}),+])+def test_free_fast_search_needs_a_usable_identity_and_no_explicit_selection(monkeypatch, tmp_path, gateway_server, state, config):+ from tools import web_tools++ _write_home(tmp_path / "home", monkeypatch, nous_state=state, config=config)++ assert web_tools._managed_web_search() is False+ assert web_tools._get_search_backend() != "perplexity"+++def test_direct_perplexity_key_beats_free_fast_search(monkeypatch, tmp_path, gateway_server):+ _write_home(tmp_path / "home", monkeypatch, nous_state=_nous_state(ANON, "anonymous"))+ monkeypatch.setenv("PERPLEXITY_API_KEY", "direct-key")++ assert _search()["success"] is True+ assert _calls(gateway_server) == [("/direct/search", "Bearer direct-key", None)]+++def test_free_fast_search_eligibility_follows_the_served_profile(monkeypatch, tmp_path, gateway_server):+ """Multiplex A→B→A: profile A holds an anonymous identity, B none; each answers from its own store."""+ from hermes_cli.nous_account import reset_nous_portal_account_info_cache+ from agent.secret_scope import set_multiplex_active+ from gateway.run import _profile_runtime_scope+ from tools import web_tools++ root = tmp_path / ".hermes"+ profile_a, profile_b = root / "profiles" / "a", root / "profiles" / "b"+ _write_home(profile_a, monkeypatch, nous_state=_nous_state(ANON, "anonymous"), config={"web": {"keyless_fallback": False}})+ _write_home(profile_b, monkeypatch, config={"web": {"keyless_fallback": False}})+ monkeypatch.setenv("HERMES_HOME", str(root))+ (root / "config.yaml").write_text("")+ set_multiplex_active(True)+ try:+ seen = []+ for home in (profile_a, profile_b, profile_a):+ reset_nous_portal_account_info_cache()+ with _profile_runtime_scope(home):+ seen.append(web_tools._get_search_backend())+ finally:+ set_multiplex_active(False)+ assert seen[0] == seen[2] == "perplexity"+ assert seen[1] != "perplexity"diff --git a/tests/tools/test_web_managed_routing.py b/tests/tools/test_web_managed_routing.pyindex fc88e64672d..a6f833aa130 100644--- a/tests/tools/test_web_managed_routing.py+++ b/tests/tools/test_web_managed_routing.py@@ -119,7 +119,7 @@ def test_only_managed_search_may_use_billed_fallback(assert headers.get("X-Pplx-Integration") == (None if managed else "hermes-agent")-def test_unentitled_managed_search_names_the_gateway(monkeypatch, tmp_path, local_gateway):+def test_managed_search_without_identity_names_the_gateway(monkeypatch, tmp_path, local_gateway):from hermes_cli.config import atomic_config_writefrom tools import managed_tool_gateway, web_toolsfrom tests.tools.conftest import register_all_web_providers@@ -127,6 +127,7 @@ def test_unentitled_managed_search_names_the_gateway(monkeypatch, tmp_path, locamonkeypatch.setenv("HERMES_HOME", str(tmp_path))atomic_config_write(tmp_path / "config.yaml", {"web": {"backend": "nous", "keyless_rescue": False}})monkeypatch.delenv("PERPLEXITY_API_KEY", raising=False)+ monkeypatch.delenv("TOOL_GATEWAY_USER_TOKEN", raising=False)monkeypatch.setattr(managed_tool_gateway, "managed_nous_tools_enabled", lambda **kw: False)register_all_web_providers()@@ -134,3 +135,19 @@ def test_unentitled_managed_search_names_the_gateway(monkeypatch, tmp_path, locaassert "Nous Tool Gateway" in error and "hermes tools" in errorassert "PERPLEXITY_API_KEY" not in errorassert local_gateway == []+++def test_unentitled_managed_search_gets_fast_search_but_no_billed_fallback(monkeypatch, tmp_path, local_gateway):+ from hermes_cli.config import atomic_config_write+ from tools import managed_tool_gateway, web_tools+ from tests.tools.conftest import register_all_web_providers++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ atomic_config_write(tmp_path / "config.yaml", {"web": {"backend": "nous", "keyless_rescue": False}})+ monkeypatch.delenv("PERPLEXITY_API_KEY", raising=False)+ monkeypatch.setattr(managed_tool_gateway, "managed_nous_tools_enabled", lambda **kw: False)+ register_all_web_providers()++ # The fixture 503s the Perplexity route; an entitled caller would then be served by /v2/search.+ assert json.loads(web_tools.web_search_tool("local fixture", limit=3))["success"] is False+ assert [(path, body.get("search_type")) for path, _, body in local_gateway] == [("/perplexity/search", "fast")]diff --git a/tools/managed_tool_gateway.py b/tools/managed_tool_gateway.pyindex c893e6bc1c2..2968165709e 100644--- a/tools/managed_tool_gateway.py+++ b/tools/managed_tool_gateway.py@@ -162,12 +162,7 @@ def build_vendor_gateway_url(vendor: str) -> str:return f"{get_tool_gateway_scheme()}://{vendor}-gateway.{shared_domain}"-def resolve_managed_tool_gateway(- vendor: str, gateway_builder: Optional[Callable[[str], str]] = None,- token_reader: Optional[Callable[[], Optional[str]]] = None) -> Optional[ManagedToolGatewayConfig]:- """Resolve shared managed-tool gateway config for a vendor."""- if not managed_nous_tools_enabled():- return None+def _vendor_gateway(vendor: str, gateway_builder, token_reader) -> Optional[ManagedToolGatewayConfig]:gateway_origin = (gateway_builder or build_vendor_gateway_url)(vendor)nous_user_token = (token_reader or read_nous_access_token)()if not gateway_origin or not nous_user_token:@@ -175,6 +170,22 @@ def resolve_managed_tool_gateway(return ManagedToolGatewayConfig(vendor=vendor, gateway_origin=gateway_origin, nous_user_token=nous_user_token, managed_mode=True)+def resolve_managed_tool_gateway(+ vendor: str, gateway_builder: Optional[Callable[[str], str]] = None,+ token_reader: Optional[Callable[[], Optional[str]]] = None) -> Optional[ManagedToolGatewayConfig]:+ """Resolve shared managed-tool gateway config for a vendor (entitled accounts only)."""+ if not managed_nous_tools_enabled():+ return None+ return _vendor_gateway(vendor, gateway_builder, token_reader)+++def resolve_free_search_gateway(token_reader: Optional[Callable[[], Optional[str]]] = None) -> Optional[ManagedToolGatewayConfig]:+ """Perplexity ``search_type: "fast"`` is served to every Nous identity with no funding check, so it needs a+ token this profile may use (guest-disabled and refresh rules live in the reader), not paid entitlement.+ Search only: every other vendor route goes through :func:`resolve_managed_tool_gateway`."""+ return _vendor_gateway("perplexity", None, token_reader)++def is_managed_tool_gateway_ready(vendor: str, gateway_builder: Optional[Callable[[str], str]] = None,token_reader: Optional[Callable[[], Optional[str]]] = None) -> bool:diff --git a/tools/web_tools.py b/tools/web_tools.pyindex 8c49d33110b..7e7beb8d673 100644--- a/tools/web_tools.py+++ b/tools/web_tools.py@@ -111,9 +111,14 @@ def _get_backend() -> str:# Shared selection exists (use_gateway) but no shared name: firecrawl, no ladder.return "firecrawl"- # Never-configured install. Explicit user credentials beat the managed-gateway probe (a Nous OAuth- # token's tier may not grant web access; the gateway then fails at runtime with no fallback).- # Free tiers trail paid.+ # Never-configured install.+ return _autodetect_backend() or _keyless_backend() or "firecrawl" # default (backward compat)+++def _autodetect_backend() -> Optional[str]:+ """Autodetect rungs above the keyless tier, or None. Explicit user credentials beat the managed-gateway+ probe (a Nous OAuth token's tier may not grant web access; the gateway then fails at runtime with no+ fallback). Free tiers trail paid."""backend_candidates = (("tavily", _has_env("TAVILY_API_KEY")), ("perplexity", _has_env("PERPLEXITY_API_KEY")),("exa", _has_env("EXA_API_KEY")),@@ -130,8 +135,7 @@ def _get_backend() -> str:for provider in _list_registered_web_providers():if provider.name not in _LEGACY_WEB_BACKENDS and _probe(provider, "is_available"):return provider.name-- return _keyless_backend() or "firecrawl" # default (backward compat)+ return Nonedef _keyless_backend() -> Optional[str]:@@ -153,13 +157,19 @@ def _keyless_backend() -> Optional[str]:def _managed_web_search() -> bool:"""True when web_search is on the managed Nous route: the stored ``nous`` selection, or a- never-configured install whose autodetect lands on the gateway. A stored vendor selection never is."""+ never-configured install whose autodetect lands on the gateway — the entitled Firecrawl gateway, or+ free Perplexity fast search for any Nous identity when nothing else is configured (search-only: the+ extract ladder is untouched). A stored vendor selection never is."""if _configured_backend("search_backend"):return Falseselected = read_selection("web")if selected is not None:return selected == NOUS_MANAGED_PROVIDER- return _get_backend() == "firecrawl" and not (_has_env("FIRECRAWL_API_KEY") or _has_env("FIRECRAWL_API_URL")) and _is_tool_gateway_ready()+ backend = _autodetect_backend()+ if backend == "firecrawl":+ return not (_has_env("FIRECRAWL_API_KEY") or _has_env("FIRECRAWL_API_URL")) and _is_tool_gateway_ready()+ from tools.managed_tool_gateway import peek_nous_access_token, resolve_free_search_gateway+ return backend is None and resolve_free_search_gateway(token_reader=peek_nous_access_token) is not Nonedef _get_search_backend() -> str:diff --git a/tools/web_tools_rescue.py b/tools/web_tools_rescue.pyindex 4ae364cd3b6..c85a91f2c95 100644--- a/tools/web_tools_rescue.py+++ b/tools/web_tools_rescue.py@@ -48,11 +48,12 @@ def _ring_vendor_keyless(name: str) -> bool:def _managed_search_fallback(provider, original_error: str, query: str, limit: int):- """Try managed Firecrawl for this call only; None leaves the original error for keyless rescue."""+ """Try managed Firecrawl for this call only; None leaves the original error for keyless rescue.+ Managed Firecrawl is billed, so a caller on free fast search alone never reaches it."""from agent.web_search_provider import get_provider_env- from tools.web_tools import _managed_web_search+ from tools import web_tools as _wtif (getattr(provider, "name", "") != "perplexity"- or get_provider_env("PERPLEXITY_API_KEY") or not _managed_web_search()):+ or get_provider_env("PERPLEXITY_API_KEY") or not _wt._managed_web_search() or not _wt._is_tool_gateway_ready()):return Nonelogger.warning("web_search managed Perplexity failed (%s); serving this call from managed Firecrawl", (original_error or "")[:200])try:diff --git a/website/docs/user-guide/features/web-search.md b/website/docs/user-guide/features/web-search.mdindex 81e515d344e..d046c4e1e74 100644--- a/website/docs/user-guide/features/web-search.md+++ b/website/docs/user-guide/features/web-search.md@@ -445,6 +445,7 @@ If no shared backend has **ever** been selected (no `web.backend` written by you| `SEARXNG_URL` | searxng || `BRAVE_SEARCH_API_KEY` | brave-free || `ddgs` package importable | ddgs |+| Nous identity present (any account, including the free tier) | managed web search (`web_search` only); extract and the keyless ring below are unchanged || *(nothing set at all)* | keyless ring: exa / parallel / firecrawl / keenable (round-robin) |**Keyless free-tier ring:** when *no* credential above is present, requests rotate across the ring vendors' public free tiers (Exa, Parallel, Firecrawl, Keenable) so web tools work on a fresh install with zero setup — and a rate-limited request fails over to the next vendor in the ring automatically. Pin one vendor in `hermes tools` to stop the rotation (the ring is then only used as failover succession on throttles). All free tiers are vendor-rate-limited under burst load; sustained normal usage goes through fine. Set `web.keyless_fallback: false` to turn the tier off — with it off and no credentials, web tools are unavailable until a provider is configured.