Skip to content

The agent that grows with you

refactor(web): drop the gate's leftovers and keep the tier rules tested

kshitijk4poor343500b3547e
diff --git a/hermes_cli/nous_account.py b/hermes_cli/nous_account.py
index 7ba90a015c0..f08c1116d39 100644
--- a/hermes_cli/nous_account.py
+++ b/hermes_cli/nous_account.py
@@ -584,7 +584,8 @@ def _error_info(
raw_account: Optional[dict[str, Any]] = None, account_tier: Optional[str] = None,
) -> NousPortalAccountInfo:
"""A failed-lookup snapshot. ``account_tier`` is carried through when the caller still holds the
- stored state: without it a guest whose lookup failed reads as a registered identity."""
+ stored state, so a guest whose lookup failed still gets the "needs a Nous account" copy rather
+ than billing or re-login guidance."""
return NousPortalAccountInfo(
logged_in=logged_in, source="error", fresh=False, portal_base_url=portal_base_url,
raw_account=raw_account, error=str(error), account_tier=account_tier,
diff --git a/plugins/web/perplexity/provider.py b/plugins/web/perplexity/provider.py
index 49e961f5ab5..f16c77ac1aa 100644
--- a/plugins/web/perplexity/provider.py
+++ b/plugins/web/perplexity/provider.py
@@ -23,7 +23,8 @@ Env vars::
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.
+gateway serves to any Nous identity (paid, unpaid or anonymous guest); a direct key
+takes precedence.
Managed extract stays on Firecrawl.
Extract caveat: Perplexity's only supported page-content route returns the
@@ -71,18 +72,12 @@ def _missing_key_error() -> str:
return f"PERPLEXITY_API_KEY is not set. Get a key at {_KEY_URL}"
-def _managed_gateway(token_reader=None, managed=None):
- """Nous Tool Gateway config when web_search is on the managed route, else None.
-
- ``managed`` lets a caller that already resolved the route reuse that answer instead of
- walking the autodetect ladder again."""
+def _managed_gateway(token_reader=None):
+ """Nous Tool Gateway config when web_search is on the managed route, else None."""
from tools import managed_tool_gateway as gw
+ from tools.web_tools import _managed_web_search
- if managed is None:
- from tools.web_tools import _managed_web_search
-
- managed = _managed_web_search()
- if not managed:
+ if not _managed_web_search():
return None
return gw.resolve_free_search_gateway(token_reader=token_reader)
@@ -216,11 +211,12 @@ class PerplexityWebSearchProvider(WebSearchProvider):
return {"success": False, "error": "Interrupted"}
from agent.web_search_provider import get_provider_env
+ from tools.managed_tool_gateway import resolve_free_search_gateway
from tools.web_tools import _managed_web_search
direct = bool(get_provider_env("PERPLEXITY_API_KEY"))
managed = False if direct else _managed_web_search()
- gateway = _managed_gateway(managed=managed) if managed else None
+ gateway = resolve_free_search_gateway() if managed else None
if gateway is None and managed:
from tools.tool_backend_helpers import NOUS_MANAGED_PROVIDER, selection_error
diff --git a/tests/hermes_cli/test_anon_surfaces.py b/tests/hermes_cli/test_anon_surfaces.py
index b19b15e2fb6..979f2c2a8ca 100644
--- a/tests/hermes_cli/test_anon_surfaces.py
+++ b/tests/hermes_cli/test_anon_surfaces.py
@@ -127,6 +127,28 @@ def test_real_account_keeps_account_rendering(isolated_store, capsys):
assert nous_account.format_nous_portal_entitlement_message(info) is None # paid_access claim entitles
[email protected]("tier", ["Anonymous", "ANONYMOUS", " anonymous "])
+def test_anonymous_tier_matches_case_and_whitespace_insensitively(isolated_store, tier):
+ """The tier claim is wire data; casing must not hand a guest billing copy instead of the sign-in copy."""
+ _write_auth({**_guest_state(), "account_tier": tier, "access_token": _jwt(account_tier=tier)})
+ info = nous_account.get_nous_portal_account_info()
+ assert info.is_anonymous_tier
+ assert nous_account.format_nous_portal_entitlement_message(info) == nous_account.FREE_TIER_NEEDS_ACCOUNT
+
+
+def test_guest_whose_lookup_fails_still_gets_the_sign_in_copy(isolated_store, monkeypatch):
+ """A token inside its refresh window falls through to the account API; when that fails the
+ stored tier must survive on the error snapshot."""
+ state = {**_guest_state(), "access_token": _jwt(exp=int(time.time()) + 30),
+ "portal_base_url": "http://127.0.0.1:9"}
+ _write_auth(state)
+ monkeypatch.setattr(nous_account, "_fetch_nous_account_info",
+ lambda *a, **k: (_ for _ in ()).throw(RuntimeError("portal down")))
+ info = nous_account.get_nous_portal_account_info()
+ assert info.error is not None and info.is_anonymous_tier
+ assert nous_account.format_nous_portal_entitlement_message(info) == nous_account.FREE_TIER_NEEDS_ACCOUNT
+
+
def test_keepalive_does_not_start_for_free_tier(isolated_store, monkeypatch):
started: list = []
diff --git a/tests/tools/test_web_free_fast_search.py b/tests/tools/test_web_free_fast_search.py
index 2fdf64445bb..8b1832a73ff 100644
--- a/tests/tools/test_web_free_fast_search.py
+++ b/tests/tools/test_web_free_fast_search.py
@@ -17,13 +17,12 @@ 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, exp_offset: int = 3600) -> dict:
+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()) + exp_offset})}.sig"
+ token = f"{seg({'alg': 'none'})}.{seg({**claims, 'exp': int(time.time()) + 3600})}.sig"
state = {"auth_method": auth_method, "access_token": token, "expires_at": "2099-01-01T00:00:00Z"}
- # anon_auth persists the tier alongside the token, and it is what survives a failed lookup
- # (the JWT claim is unreachable once the token is inside its refresh window).
+ # anon_auth persists the tier alongside the token.
if claims.get("account_tier"):
state["account_tier"] = claims["account_tier"]
return state
@@ -99,11 +98,14 @@ def _calls(log):
def test_unentitled_nous_identity_autodetects_free_fast_search(monkeypatch, tmp_path, gateway_server, state):
"""Guests are the users this route exists for: an anonymous identity and a zero-credit account
both reach the gateway, while the paid gate stays closed for extract and every other vendor."""
+ from hermes_cli.nous_account import get_nous_portal_account_info
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.
+ # Premise: the guest case really reads as the anonymous tier, and the paid-tool gate is closed
+ # for this identity and stays closed for extract.
+ assert get_nous_portal_account_info().is_anonymous_tier is (state["auth_method"] == "anonymous")
assert managed_nous_tools_enabled() is False
assert web_tools.check_firecrawl_api_key() is False
assert web_tools._get_extract_backend() != "perplexity"
diff --git a/tools/tool_backend_helpers.py b/tools/tool_backend_helpers.py
index a27f37680bc..3e0a3bd464b 100644
--- a/tools/tool_backend_helpers.py
+++ b/tools/tool_backend_helpers.py
@@ -15,25 +15,18 @@ _DEFAULT_MODAL_MODE = "auto"
_VALID_MODAL_MODES = {"auto", "direct", "managed"}
-def _account_info(force_fresh: bool = False):
- """The profile's normalized Portal account snapshot, or None when the read itself failed.
-
- The ``force_fresh`` branch is deliberate, not stylistic: callers stub this reader with a
- zero-argument lambda, so the falsy path must invoke it without keyword arguments."""
- try:
- from hermes_cli.nous_account import get_nous_portal_account_info
- return (get_nous_portal_account_info(force_fresh=True) if force_fresh
- else get_nous_portal_account_info())
- except Exception:
- return None
-
-
def managed_nous_tools_enabled(*, force_fresh: bool = False) -> bool:
"""Coarse gate: entitled to the Nous Tool Gateway (paid Portal access OR a live free
pool). Fails closed on unknown/error — never blocks startup. Callers narrow per category
via ``tool_gateway_entitled_for``; ``force_fresh`` is for flows needing a just-bought grant."""
- account_info = _account_info(force_fresh)
- return bool(account_info is not None and account_info.logged_in and account_info.tool_gateway_entitled)
+ try:
+ from hermes_cli.nous_account import get_nous_portal_account_info
+ # Branched call, not ``force_fresh=force_fresh``: tests stub the reader with zero-arg lambdas.
+ account_info = (get_nous_portal_account_info(force_fresh=True) if force_fresh
+ else get_nous_portal_account_info())
+ return bool(account_info.logged_in) and account_info.tool_gateway_entitled
+ except Exception:
+ return False
def nous_tool_gateway_unavailable_message(capability: str = "the Nous Tool Gateway", *,
diff --git a/website/docs/user-guide/features/web-search.md b/website/docs/user-guide/features/web-search.md
index dc57d7b1584..719a9396082 100644
--- a/website/docs/user-guide/features/web-search.md
+++ b/website/docs/user-guide/features/web-search.md
@@ -298,7 +298,7 @@ Get a key at [app.tavily.com](https://app.tavily.com/home). See [Tavily keyless]
### Perplexity
-[Perplexity's Search API](https://docs.perplexity.ai/docs/search/quickstart) returns ranked, date-stamped results from Perplexity's own index (`web_search`). For `web_extract` it uses the same query-relevant *snippets* route as the official `pplx` CLI: you get the passages of each page that matter, with elisions marked `…`, rather than a verbatim full-page dump — pick Firecrawl / Exa / Parallel as `web.extract_backend` when you need the whole page. Keyed only; there is no anonymous tier.
+[Perplexity's Search API](https://docs.perplexity.ai/docs/search/quickstart) returns ranked, date-stamped results from Perplexity's own index (`web_search`). For `web_extract` it uses the same query-relevant *snippets* route as the official `pplx` CLI: you get the passages of each page that matter, with elisions marked `…`, rather than a verbatim full-page dump — pick Firecrawl / Exa / Parallel as `web.extract_backend` when you need the whole page. Keyed only at Perplexity itself; the managed Nous route (any Nous identity, guests included) serves `web_search` without a key.
```bash
# ~/.hermes/.env