Enterprise agent platform for building, deploying, and operating AI teammates.
feat(tools): route Brave through query redaction and add a country setting (toby) (#3829)
OliverBryant1ab0c0166763
diff --git a/example.env b/example.envindex 3982ce77d..355e087dc 100644--- a/example.env+++ b/example.env@@ -900,8 +900,11 @@ LANGFUSE_SECRET_KEY="secret key"# XAGENT_MAX_TRACE_PAYLOAD_BYTES="50000"# Web Search API Keys-# Provider selection: auto, google, tavily, exa, zhipu (default: auto)-# In auto mode, priority is Zhipu > Tavily > Exa > Google.+# Provider selection: auto, google, tavily, exa, zhipu, brave (default: auto)+# In auto mode, priority is Zhipu > Tavily > Exa > Google > Brave (Brave last,+# so enabling a Brave key never changes the provider of an auto deployment).+# Unset or empty means auto. An unrecognised value disables web search entirely+# (no search tool is registered and an error is logged); it never falls back.XAGENT_WEB_SEARCH_PROVIDER="auto"# Website import TLS fingerprint impersonation for WAF-protected sites.@@ -995,6 +998,17 @@ EXA_API_KEY=""GOOGLE_API_KEY=""GOOGLE_CSE_ID=""+# Brave Search API (get key at https://brave.com/search/api/)+BRAVE_SEARCH_API_KEY=""+# Which Brave endpoint to call: "web" (default; titles, links, snippets) or+# "llm_context" (extracted page snippets, query sent in a POST body).+# An unknown value logs a warning and uses "web".+# XAGENT_BRAVE_SEARCH_ENDPOINT="web"+# Optional two-letter country for ranking results (for example AU). Unset or+# empty sends no country, so Brave defaults to US. An invalid value is ignored+# with a warning.+# XAGENT_BRAVE_SEARCH_COUNTRY=""+# ===========================================# Google OAuth Configuration (Optional)# ===========================================diff --git a/src/xagent/config.py b/src/xagent/config.pyindex 7a19aa470..b2cc3594b 100644--- a/src/xagent/config.py+++ b/src/xagent/config.py@@ -221,6 +221,7 @@ SANDBOX_WORKER_ID = "XAGENT_SANDBOX_WORKER_ID"TASK_RUNTIME_SECRETS_TTL_SECONDS = "XAGENT_TASK_RUNTIME_SECRETS_TTL_SECONDS"WEB_SEARCH_PROVIDER = "XAGENT_WEB_SEARCH_PROVIDER"BRAVE_SEARCH_ENDPOINT = "XAGENT_BRAVE_SEARCH_ENDPOINT"+BRAVE_SEARCH_COUNTRY = "XAGENT_BRAVE_SEARCH_COUNTRY"WEB_CRAWL_TLS_IMPERSONATE = "XAGENT_WEB_CRAWL_TLS_IMPERSONATE"TOOL_PARALLEL_ENABLED = "XAGENT_TOOL_PARALLEL_ENABLED"TOOL_MAX_CONCURRENCY = "XAGENT_TOOL_MAX_CONCURRENCY"@@ -4640,6 +4641,26 @@ def get_brave_search_endpoint() -> str:return "web"+def get_brave_search_country() -> str | None:+ """Get the optional Brave Search country, as a lower-case two-letter code.++ Unset or empty means the parameter is not sent (Brave then defaults to+ ``US``). A value that is not exactly two ASCII letters is ignored with one+ warning that does not echo the value.+ """+ raw = (os.getenv(BRAVE_SEARCH_COUNTRY) or "").strip()+ if not raw:+ return None+ if len(raw) == 2 and raw.isascii() and raw.isalpha():+ return raw.lower()+ logger.warning(+ "Ignoring invalid %s value (expected two ASCII letters, got %d characters).",+ BRAVE_SEARCH_COUNTRY,+ len(raw),+ )+ return None++def get_web_crawl_tls_impersonate() -> str | None:"""Get the optional TLS impersonation spec for website crawling.diff --git a/src/xagent/core/tools/core/brave_web_search.py b/src/xagent/core/tools/core/brave_web_search.pyindex f0f90374f..1e50643fb 100644--- a/src/xagent/core/tools/core/brave_web_search.py+++ b/src/xagent/core/tools/core/brave_web_search.py@@ -19,8 +19,9 @@ from typing import Any, Dict, List, Optionalimport httpx-from ....config import get_brave_search_endpoint+from ....config import get_brave_search_country, get_brave_search_endpointfrom .web_content import WebContentFetcher+from .web_search_guard import run_guarded_searchlogger = logging.getLogger(__name__)@@ -85,7 +86,14 @@ class BraveWebSearchCore:Returns:List of search results with title, link, snippet and optionally content"""- return await self._search_redacted(query, max_results, include_content)+ return await run_guarded_search(+ "brave",+ query,+ lambda redacted: self._search_redacted(+ redacted, max_results, include_content+ ),+ len,+ )async def _search_redacted(self,@@ -117,6 +125,8 @@ class BraveWebSearchCore:include_content,)+ country = get_brave_search_country()+proxy_url = self._get_proxy_url()if proxy_url:# Do not log the URL: it can carry proxy credentials.@@ -133,24 +143,30 @@ class BraveWebSearchCore:try:async with httpx.AsyncClient(**client_kwargs) as client:if endpoint == "llm_context":+ body: Dict[str, Any] = {+ "q": query,+ "count": max_results,+ "maximum_number_of_tokens": LLM_CONTEXT_MAX_TOKENS,+ }+ if country:+ body["country"] = country # documented default: "us"response = await client.post(BRAVE_LLM_CONTEXT_URL,- json={- "q": query,- "count": max_results,- "maximum_number_of_tokens": LLM_CONTEXT_MAX_TOKENS,- },+ json=body,headers=headers,timeout=30,)else:+ params: Dict[str, Any] = {+ "q": query,+ "count": max_results,+ "text_decorations": "false",+ }+ if country:+ params["country"] = country.upper() # documented default: "US"response = await client.get(BRAVE_WEB_SEARCH_URL,- params={- "q": query,- "count": max_results,- "text_decorations": "false",- },+ params=params,headers=headers,timeout=30,)diff --git a/tests/core/test_config.py b/tests/core/test_config.pyindex 7b6348f07..68cced195 100644--- a/tests/core/test_config.py+++ b/tests/core/test_config.py@@ -136,6 +136,7 @@ from xagent.config import (get_background_job_stale_seconds,get_background_job_sweep_interval_seconds,get_background_job_visibility_timeout_seconds,+ get_brave_search_country,get_brave_search_endpoint,get_browser_cua_driver_command,get_browser_cua_driver_max_elements,@@ -1043,6 +1044,20 @@ class TestGetWebSearchProvider:assert WEB_SEARCH_PROVIDER in caplog.text+class TestGetBraveSearchCountry:+ def test_values(self, monkeypatch):+ monkeypatch.delenv("XAGENT_BRAVE_SEARCH_COUNTRY", raising=False)+ assert get_brave_search_country() is None+ monkeypatch.setenv("XAGENT_BRAVE_SEARCH_COUNTRY", " Au ")+ assert get_brave_search_country() == "au"+ monkeypatch.setenv("XAGENT_BRAVE_SEARCH_COUNTRY", "")+ assert get_brave_search_country() is None++ def test_invalid_value_ignored(self, monkeypatch):+ monkeypatch.setenv("XAGENT_BRAVE_SEARCH_COUNTRY", "AUS")+ assert get_brave_search_country() is None++class TestGetBraveSearchEndpoint:def test_default_and_values(self, monkeypatch):monkeypatch.delenv("XAGENT_BRAVE_SEARCH_ENDPOINT", raising=False)diff --git a/tests/core/tools/core/test_brave_web_search.py b/tests/core/tools/core/test_brave_web_search.pyindex 77d2c7788..d9cc86285 100644--- a/tests/core/tools/core/test_brave_web_search.py+++ b/tests/core/tools/core/test_brave_web_search.py@@ -12,7 +12,7 @@ from xagent.core.tools.core import brave_web_search as modfrom xagent.core.tools.core.brave_web_search import BraveWebSearchCoreAPI_KEY = "test-brave-key-0000"-QUERY = "[email protected] quarterly forecast"+QUERY = "acme quarterly revenue forecast"@pytest.fixture(params=["httpx_warning", "httpx_notset"])@@ -172,6 +172,60 @@ async def test_llm_context_without_include_content_has_no_content(assert all("content" not in r for r in results)+async def test_country_sent_on_web_endpoint_when_set(transport, monkeypatch):+ monkeypatch.delenv("XAGENT_BRAVE_SEARCH_ENDPOINT", raising=False)+ monkeypatch.setenv("XAGENT_BRAVE_SEARCH_COUNTRY", " au ")+ requests = transport(lambda r: httpx.Response(200, json=WEB_BODY))+ await BraveWebSearchCore(api_key=API_KEY).search(QUERY)+ assert requests[0].url.params["country"] == "AU"+ assert "search_lang" not in requests[0].url.params+++async def test_country_sent_on_llm_context_endpoint_when_set(transport, monkeypatch):+ monkeypatch.setenv("XAGENT_BRAVE_SEARCH_ENDPOINT", "llm_context")+ monkeypatch.setenv("XAGENT_BRAVE_SEARCH_COUNTRY", "AU")+ requests = transport(lambda r: httpx.Response(200, json=CTX_BODY))+ await BraveWebSearchCore(api_key=API_KEY).search(QUERY)+ body = json.loads(requests[0].content)+ assert body["country"] == "au"+ assert "search_lang" not in body++[email protected]("endpoint", ["web", "llm_context"])[email protected]("value", [None, "", " "])+async def test_country_absent_when_unset(transport, monkeypatch, endpoint, value):+ monkeypatch.setenv("XAGENT_BRAVE_SEARCH_ENDPOINT", endpoint)+ if value is None:+ monkeypatch.delenv("XAGENT_BRAVE_SEARCH_COUNTRY", raising=False)+ else:+ monkeypatch.setenv("XAGENT_BRAVE_SEARCH_COUNTRY", value)+ requests = transport(lambda r: httpx.Response(200, json=WEB_BODY))+ await BraveWebSearchCore(api_key=API_KEY).search(QUERY)+ sent = requests[0].url.query.decode() + requests[0].content.decode()+ assert "country" not in sent++[email protected]("endpoint", ["web", "llm_context"])[email protected]("value", ["AUS", "7", "1x", "éé", "au-AU"])+async def test_invalid_country_ignored_with_one_warning(+ transport, monkeypatch, caplog, endpoint, value+):+ monkeypatch.setenv("XAGENT_BRAVE_SEARCH_ENDPOINT", endpoint)+ monkeypatch.setenv("XAGENT_BRAVE_SEARCH_COUNTRY", value)+ requests = transport(lambda r: httpx.Response(200, json=WEB_BODY))+ with caplog.at_level(logging.WARNING):+ await BraveWebSearchCore(api_key=API_KEY).search(QUERY)+ sent = requests[0].url.query.decode() + requests[0].content.decode()+ assert "country" not in sent+ warnings = [r for r in caplog.records if "XAGENT_BRAVE_SEARCH_COUNTRY" in r.message]+ assert len(warnings) == 1+ assert value not in warnings[0].getMessage()++@pytest.mark.asyncioasync def test_unknown_endpoint_uses_web(transport, monkeypatch, caplog):monkeypatch.setenv("XAGENT_BRAVE_SEARCH_ENDPOINT", "bogus")@@ -288,3 +342,97 @@ async def test_non_json_body_raises_clean_error(transport):transport(lambda r: httpx.Response(200, text="<html>"))with pytest.raises(ValueError, match="invalid response body"):await BraveWebSearchCore(api_key=API_KEY).search(QUERY)+++# --- redaction guard (xagent.core.tools.core.web_search_guard) ----------------++from urllib.parse import unquote_plus # noqa: E402++from xagent.core.tools.core.web_search_guard import ( # noqa: E402+ SearchAuditEvent,+ SearchQueryRedactionError,+ set_search_audit_hook,+)++PII_EMAIL = "[email protected]"+PII_PHONE = "+61 412 345 678"+PII_QUERY = f"find {PII_EMAIL} {PII_PHONE} Acme Pty Ltd"+PII_REDACTED = "find [EMAIL] [PHONE] Acme Pty Ltd"+++def audit():+ events: list[SearchAuditEvent] = []+ set_search_audit_hook(events.append)+ yield events+ set_search_audit_hook(None)+++def _wire(requests: list[httpx.Request]) -> str:+ return unquote_plus(" ".join(f"{r.url} {r.content.decode()}" for r in requests))++[email protected]("endpoint", ["web", "llm_context"])+async def test_brave_sends_and_audits_only_the_redacted_query(+ transport, monkeypatch, caplog, audit, endpoint+):+ monkeypatch.setenv("XAGENT_BRAVE_SEARCH_ENDPOINT", endpoint)+ body = WEB_BODY if endpoint == "web" else CTX_BODY+ requests = transport(lambda r: httpx.Response(200, json=body))+ with caplog.at_level(logging.DEBUG):+ results = await BraveWebSearchCore(api_key=API_KEY).search(PII_QUERY)++ wire = _wire(requests)+ assert PII_REDACTED in wire+ assert PII_EMAIL not in wire and "412 345 678" not in wire+ (event,) = audit+ assert event.provider == "brave"+ assert event.query == PII_REDACTED+ assert event.result_count == len(results) == 2+ assert event.outcome == "success"+ # The core logs no query text at all, raw or redacted.+ assert "Acme" not in caplog.text and "[EMAIL]" not in caplog.text+ assert PII_EMAIL not in caplog.text++[email protected]("endpoint", ["web", "llm_context"])+async def test_brave_query_limits_apply_to_the_redacted_text(+ transport, monkeypatch, audit, endpoint+):+ monkeypatch.setenv("XAGENT_BRAVE_SEARCH_ENDPOINT", endpoint)+ requests = transport(lambda r: httpx.Response(200, json=WEB_BODY))+ core = BraveWebSearchCore(api_key=API_KEY)++ # 601 raw characters shrink below the limit once the email is a placeholder.+ query = f"{PII_EMAIL} " + "b" * 585+ assert len(query) > 600+ await core.search(query)+ assert len(requests) == 1+ assert audit[-1].query == "[EMAIL] " + "b" * 585++ # An over-long query that stays over-long is refused after redaction, and+ # the failure event carries the redacted text, not the raw one.+ too_long = f"{PII_EMAIL} " + "c" * 600+ with pytest.raises(ValueError, match="600 characters"):+ await core.search(too_long)+ assert len(requests) == 1+ assert audit[-1].outcome == "failure"+ assert PII_EMAIL not in audit[-1].query+++async def test_brave_redaction_failure_sends_nothing(transport, monkeypatch, audit):+ import xagent.core.tools.core.search_query_redaction as redaction++ monkeypatch.setattr(+ redaction,+ "_sub",+ lambda *a, **k: (_ for _ in ()).throw(RuntimeError(PII_EMAIL)),+ )+ requests = transport(lambda r: httpx.Response(200, json=WEB_BODY))+ with pytest.raises(SearchQueryRedactionError):+ await BraveWebSearchCore(api_key=API_KEY).search(PII_QUERY)+ assert requests == []+ assert audit[-1].failure_kind == "redaction_error"