The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(xai): lift API-key precedence into resolve_xai_http_credentials behind prefer_api_key
Teknium3b9a963b8e5c
diff --git a/tests/tools/test_tts_xai_speech_tags.py b/tests/tools/test_tts_xai_speech_tags.pyindex d79e7cd0fc9..ba800a7e883 100644--- a/tests/tools/test_tts_xai_speech_tags.py+++ b/tests/tools/test_tts_xai_speech_tags.py@@ -134,7 +134,7 @@ def test_generate_xai_tts_uses_oauth_pinned_base_url(tmp_path, monkeypatch):monkeypatch.setenv("XAI_BASE_URL", "https://attacker.example/v1")monkeypatch.setattr("tools.xai_http.resolve_xai_http_credentials",- lambda: {+ lambda **_kwargs: {"provider": "xai-oauth","api_key": "oauth-bearer-token","base_url": "https://api.x.ai/v1",@@ -158,6 +158,65 @@ def test_generate_xai_tts_uses_oauth_pinned_base_url(tmp_path, monkeypatch):assert captured["headers"]["Authorization"] == "Bearer oauth-bearer-token"+def test_generate_xai_tts_prefers_explicit_api_key_over_oauth(tmp_path, monkeypatch):+ """TTS requires API billing even when chat OAuth is configured (#87045).++ Adapted from PR #87081 (@enwaiax): the precedence now lives in the shared+ resolver behind ``prefer_api_key=True`` instead of an inline early return,+ so the key is read via ``resolve_provider_secret`` and the base URL+ override goes through the same *.x.ai origin validation as OAuth.+ """+ captured = {}++ class FakeResponse:+ content = b"audio"++ def raise_for_status(self):+ pass++ def fake_post(url, headers, json, timeout, stream=False):+ captured["url"] = url+ captured["headers"] = headers+ return FakeResponse()++ from types import SimpleNamespace++ entry = SimpleNamespace(+ access_token="oauth-token",+ runtime_api_key=None,+ runtime_base_url=None,+ base_url="https://api.x.ai/v1",+ )++ class _FakePool:+ def select(self):+ return entry++ def try_refresh_matching(self, _hint):+ return entry++ monkeypatch.setattr(+ "agent.credential_pool.load_pool",+ lambda provider_id: _FakePool() if provider_id == "xai-oauth" else None,+ )+ monkeypatch.delenv("XAI_API_KEY", raising=False)+ monkeypatch.setattr(+ "tools.xai_http.get_env_value",+ lambda name, default=None: {+ "XAI_API_KEY": "paid-api-key",+ "XAI_BASE_URL": "https://staging.x.ai/v1/",+ }.get(name, default),+ )+ monkeypatch.setattr("requests.post", fake_post)++ _generate_xai_tts(+ "hello", str(tmp_path / "out.mp3"), {"xai": {"auto_speech_tags": False}}+ )++ assert captured["headers"]["Authorization"] == "Bearer paid-api-key"+ assert captured["url"] == "https://staging.x.ai/v1/tts"++def test_auto_speech_tags_calls_auxiliary_rewriter_with_tts_audio_tags_task():"""When input has no explicit speech tags, the function must call theauxiliary rewriter with task='tts_audio_tags' and a system promptdiff --git a/tests/tools/test_x_search_tool.py b/tests/tools/test_x_search_tool.pyindex 37dbdcd5317..7f5e834a624 100644--- a/tests/tools/test_x_search_tool.py+++ b/tests/tools/test_x_search_tool.py@@ -213,7 +213,7 @@ def test_x_search_uses_xai_oauth_when_only_oauth_available(monkeypatch):_no_xai_env(monkeypatch)- def _fake_resolve():+ def _fake_resolve(**_kwargs):return {"provider": "xai-oauth","api_key": "oauth-bearer-token",@@ -249,7 +249,7 @@ def test_x_search_returns_tool_error_when_no_credentials(monkeypatch):_no_xai_env(monkeypatch)- def _fake_resolve():+ def _fake_resolve(**_kwargs):return {"provider": "xai","api_key": "",@@ -318,35 +318,59 @@ def _xcred(prefix: str) -> str:return prefix + "-key-" + "x1"+def _install_fake_oauth_pool(monkeypatch, oauth_token: str) -> None:+ """Make the shared resolver's OAuth branch yield ``oauth_token``.++ Patches ``agent.credential_pool.load_pool`` (the seam+ ``resolve_xai_http_credentials`` imports at call time). Any pool key+ other than ``xai-oauth`` raises so ``resolve_provider_secret``'s+ credential-pool fallback can't accidentally surface the OAuth bearer+ as an "explicit key".+ """+ from types import SimpleNamespace++ entry = SimpleNamespace(+ access_token=oauth_token,+ runtime_api_key=None,+ runtime_base_url=None,+ base_url="https://api.x.ai/v1",+ )++ class _FakePool:+ def select(self):+ return entry++ def try_refresh_matching(self, _hint):+ return entry++ def _fake_load_pool(provider_id):+ if provider_id == "xai-oauth":+ return _FakePool()+ raise KeyError(provider_id)++ monkeypatch.setattr("agent.credential_pool.load_pool", _fake_load_pool)++def test_x_search_prefers_explicit_api_key_over_oauth(monkeypatch):"""#88040: with a paid XAI_API_KEY configured alongside subscriptionOAuth, x_search must use the API key — the OAuth path authorizes butanswers /v1/responses in a degraded Grok explanatory mode with no- citations. Same prefer-API-key shape as the TTS fix (#87045/#87081)."""+ citations. Same prefer-API-key root cause as the TTS fix (#87045/#87081);+ the precedence lives in the shared resolver behind ``prefer_api_key``."""from tools.registry import invalidate_check_fn_cachefrom tools.x_search_tool import x_search_toolpaid_key = _xcred("paid")oauth_token = _xcred("oauth")+ monkeypatch.delenv("XAI_API_KEY", raising=False)monkeypatch.setattr(- "hermes_cli.config.get_env_value",+ "tools.xai_http.get_env_value",lambda name, default=None: {"XAI_API_KEY": paid_key,- "XAI_BASE_URL": None,}.get(name, default),)-- def _fake_resolve():- return {- "provider": "xai-oauth",- "api_key": oauth_token,- "base_url": "https://api.x.ai/v1",- }-- monkeypatch.setattr(- "tools.x_search_tool.resolve_xai_http_credentials", _fake_resolve- )+ _install_fake_oauth_pool(monkeypatch, oauth_token)invalidate_check_fn_cache()captured = {}@@ -365,20 +389,38 @@ def test_x_search_prefers_explicit_api_key_over_oauth(monkeypatch):def test_x_search_bearer_helper_falls_back_to_oauth_without_api_key(monkeypatch):- """No explicit XAI_API_KEY: the OAuth-first resolver path is unchanged."""+ """No explicit XAI_API_KEY: the OAuth resolver path is unchanged."""from tools.x_search_tool import _resolve_xai_beareroauth_token = _xcred("oauth")+ monkeypatch.delenv("XAI_API_KEY", raising=False)monkeypatch.setattr(- "hermes_cli.config.get_env_value",+ "tools.xai_http.get_env_value",lambda name, default=None: default,)+ _install_fake_oauth_pool(monkeypatch, oauth_token)- def _fake_resolve():+ api_key, base_url, source = _resolve_xai_bearer()+ assert (api_key, base_url, source) == (+ oauth_token,+ "https://api.x.ai/v1",+ "xai-oauth",+ )+++def test_x_search_bearer_requests_prefer_api_key_from_shared_resolver(monkeypatch):+ """The x_search call site must opt into the shared resolver's+ ``prefer_api_key`` precedence rather than re-implementing it inline."""+ from tools.x_search_tool import _resolve_xai_bearer++ captured = {}++ def _fake_resolve(**kwargs):+ captured.update(kwargs)return {- "provider": "xai-oauth",- "api_key": oauth_token,+ "provider": "xai",+ "api_key": _xcred("paid"),"base_url": "https://api.x.ai/v1",}@@ -386,10 +428,7 @@ def test_x_search_bearer_helper_falls_back_to_oauth_without_api_key(monkeypatch)"tools.x_search_tool.resolve_xai_http_credentials", _fake_resolve)- api_key, base_url, source = _resolve_xai_bearer()- assert (api_key, base_url, source) == (- oauth_token,- "https://api.x.ai/v1",- "xai-oauth",- )+ _api_key, _base_url, source = _resolve_xai_bearer()+ assert captured.get("prefer_api_key") is True+ assert source == "xai"diff --git a/tests/tools/test_xai_http_credentials.py b/tests/tools/test_xai_http_credentials.pyindex 4217823f8c8..28f249b77e2 100644--- a/tests/tools/test_xai_http_credentials.py+++ b/tests/tools/test_xai_http_credentials.py@@ -55,3 +55,130 @@ def test_xai_credentials_do_not_fall_back_to_environ_when_scope_has_no_key(secret_scope.reset_secret_scope(token)secret_scope.set_multiplex_active(previous_multiplex)invalidate_env_cache()+++# ---------------------------------------------------------------------------+# prefer_api_key opt-in (#88040 x_search / #87045 TTS): explicit API key wins+# over subscription OAuth, via the shared resolver — not per-caller inlining.+# ---------------------------------------------------------------------------+++def _install_fake_oauth_pool(monkeypatch, oauth_token: str) -> None:+ from types import SimpleNamespace++ entry = SimpleNamespace(+ access_token=oauth_token,+ runtime_api_key=None,+ runtime_base_url=None,+ base_url="https://api.x.ai/v1",+ )++ class _FakePool:+ def select(self):+ return entry++ def try_refresh_matching(self, _hint):+ return entry++ def _fake_load_pool(provider_id):+ if provider_id == "xai-oauth":+ return _FakePool()+ raise KeyError(provider_id)++ monkeypatch.setattr("agent.credential_pool.load_pool", _fake_load_pool)+++def test_prefer_api_key_wins_over_available_oauth(monkeypatch):+ from tools.xai_http import resolve_xai_http_credentials++ monkeypatch.delenv("XAI_API_KEY", raising=False)+ monkeypatch.setattr(+ "tools.xai_http.get_env_value",+ lambda name, default=None: {"XAI_API_KEY": "paid-key-x1"}.get(name, default),+ )+ _install_fake_oauth_pool(monkeypatch, "oauth-token-x1")++ creds = resolve_xai_http_credentials(prefer_api_key=True)+ assert creds == {+ "provider": "xai",+ "api_key": "paid-key-x1",+ "base_url": "https://api.x.ai/v1",+ }++ # Default order is unchanged: OAuth still wins without the opt-in.+ creds = resolve_xai_http_credentials()+ assert creds["provider"] == "xai-oauth"+ assert creds["api_key"] == "oauth-token-x1"+++def test_prefer_api_key_falls_back_to_oauth_without_explicit_key(monkeypatch):+ from tools.xai_http import resolve_xai_http_credentials++ monkeypatch.delenv("XAI_API_KEY", raising=False)+ monkeypatch.setattr(+ "tools.xai_http.get_env_value", lambda name, default=None: default+ )+ _install_fake_oauth_pool(monkeypatch, "oauth-token-x1")++ creds = resolve_xai_http_credentials(prefer_api_key=True)+ assert creds["provider"] == "xai-oauth"+ assert creds["api_key"] == "oauth-token-x1"+++def test_prefer_api_key_honors_hermes_xai_base_url_with_validation(monkeypatch):+ """The preferred-key path reads the same override pair as the OAuth+ branch (HERMES_XAI_BASE_URL first, then XAI_BASE_URL) behind the same+ origin-pinning validation: an *.x.ai override is honored, a foreign+ origin is rejected in favor of the default."""+ from tools.xai_http import resolve_xai_http_credentials++ monkeypatch.delenv("XAI_API_KEY", raising=False)+ monkeypatch.setattr(+ "tools.xai_http.get_env_value",+ lambda name, default=None: {+ "XAI_API_KEY": "paid-key-x1",+ "HERMES_XAI_BASE_URL": "https://staging.x.ai/v1",+ "XAI_BASE_URL": "https://ignored.x.ai/v1",+ }.get(name, default),+ )+ _install_fake_oauth_pool(monkeypatch, "oauth-token-x1")++ creds = resolve_xai_http_credentials(prefer_api_key=True)+ assert creds["base_url"] == "https://staging.x.ai/v1"++ monkeypatch.setattr(+ "tools.xai_http.get_env_value",+ lambda name, default=None: {+ "XAI_API_KEY": "paid-key-x1",+ "XAI_BASE_URL": "https://attacker.example/v1",+ }.get(name, default),+ )+ creds = resolve_xai_http_credentials(prefer_api_key=True)+ assert creds["base_url"] == "https://api.x.ai/v1"+++def test_prefer_api_key_honors_profile_scope_only_key(tmp_path, monkeypatch):+ """A key present only in the active profile's secret scope (not in+ os.environ / .env) is honored on the preferred path — the read goes+ through resolve_provider_secret, not a raw env lookup."""+ from agent import secret_scope+ from hermes_cli.config import invalidate_env_cache+ from tools.xai_http import resolve_xai_http_credentials++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.delenv("XAI_API_KEY", raising=False)+ monkeypatch.delenv("XAI_BASE_URL", raising=False)+ monkeypatch.delenv("HERMES_XAI_BASE_URL", raising=False)+ invalidate_env_cache()+ previous_multiplex = secret_scope.is_multiplex_active()+ token = secret_scope.set_secret_scope({"XAI_API_KEY": "scoped-key-x1"})+ secret_scope.set_multiplex_active(True)+ try:+ creds = resolve_xai_http_credentials(prefer_api_key=True)+ assert creds["provider"] == "xai"+ assert creds["api_key"] == "scoped-key-x1"+ assert creds["base_url"] == "https://api.x.ai/v1"+ finally:+ secret_scope.reset_secret_scope(token)+ secret_scope.set_multiplex_active(previous_multiplex)+ invalidate_env_cache()diff --git a/tools/tts_tool.py b/tools/tts_tool.pyindex 9338afceda4..fba661fd5ba 100644--- a/tools/tts_tool.py+++ b/tools/tts_tool.py@@ -2099,7 +2099,10 @@ def _generate_xai_tts(text: str, output_path: str, tts_config: Dict[str, Any]) -from tools.xai_http import resolve_xai_http_credentials- creds = resolve_xai_http_credentials()+ # TTS is API-billed: a subscription OAuth bearer can authorize chat while+ # returning 403 for /v1/tts (#87045, same root cause as x_search #88040),+ # so prefer an explicit XAI_API_KEY with OAuth as the fallback.+ creds = resolve_xai_http_credentials(prefer_api_key=True)api_key = str(creds.get("api_key") or "").strip()if not api_key:raise ValueError("No xAI credentials found. Configure xAI OAuth in `hermes model` or set XAI_API_KEY.")diff --git a/tools/x_search_tool.py b/tools/x_search_tool.pyindex 579e4355936..9f55ff5dedd 100644--- a/tools/x_search_tool.py+++ b/tools/x_search_tool.py@@ -11,12 +11,15 @@ The tool registers when **either** xAI credential path is available:i.e. ``hermes auth add xai-oauth`` has been run and the stored refreshtoken still works.-Credential preference at call time matches-:func:`tools.xai_http.resolve_xai_http_credentials`: SuperGrok OAuth first,-direct OAuth resolver second, ``XAI_API_KEY`` last. That helper also-auto-refreshes the OAuth access token when it's within the refresh skew-window, so a ``True`` from :func:`check_x_search_requirements` means the-bearer is fetchable AND non-empty.+Credential preference at call time uses+:func:`tools.xai_http.resolve_xai_http_credentials` with+``prefer_api_key=True``: an explicit ``XAI_API_KEY`` wins when configured+(x_search is API-metered; the subscription OAuth bearer answers+``/v1/responses`` in a degraded no-citation mode — #88040), with SuperGrok+OAuth as the fallback. That helper also auto-refreshes the OAuth access+token when it's within the refresh skew window, so a ``True`` from+:func:`check_x_search_requirements` means the bearer is fetchable AND+non-empty.Defensive output----------------@@ -52,6 +55,7 @@ import requestsfrom tools.registry import registry, tool_errorfrom tools.xai_http import hermes_xai_user_agent, resolve_xai_http_credentials+logger = logging.getLogger(__name__)DEFAULT_XAI_BASE_URL = "https://api.x.ai/v1"@@ -131,19 +135,12 @@ def _resolve_xai_bearer() -> Tuple[str, str, str]:x_search is API-index access: when a subscription OAuth credential isconfigured alongside a paid ``XAI_API_KEY``, the OAuth path authorizesbut answers ``/v1/responses`` in a degraded Grok explanatory mode with- no citations, while the API key returns real posts (#88040). Prefer the- explicit API key — same shape as the TTS fix for #87045 (#87081) —+ no citations, while the API key returns real posts (#88040). Pass+ ``prefer_api_key=True`` so the shared resolver checks the explicit API+ key first — same root cause as the TTS fix for #87045 (#87081) —keeping OAuth as the fallback when no API key is configured."""- from hermes_cli.config import get_env_value-- explicit_key = str(get_env_value("XAI_API_KEY") or "").strip()- if explicit_key:- base_url = str(- get_env_value("XAI_BASE_URL") or DEFAULT_XAI_BASE_URL- ).strip().rstrip("/")- return explicit_key, base_url, "xai"- creds = resolve_xai_http_credentials()+ creds = resolve_xai_http_credentials(prefer_api_key=True)api_key = str(creds.get("api_key") or "").strip()if not api_key:raise RuntimeError(diff --git a/tools/xai_http.py b/tools/xai_http.pyindex d7b60b8d057..58a7941bd41 100644--- a/tools/xai_http.py+++ b/tools/xai_http.py@@ -254,10 +254,50 @@ def maybe_mark_xai_storage_notice_seen(section_name: str) -> Optional[str]:return notice+def _resolve_explicit_xai_api_key() -> str:+ """Read the explicit ``XAI_API_KEY`` through the shared secret machinery.++ Delegates to :func:`tools.tool_backend_helpers.resolve_provider_secret`+ (config → profile secret scope → env/.env → credential pool) so the+ preferred-key path enforces the exact same scope policy as the no-OAuth+ fallback branch — including failing closed under a multiplexed gateway+ turn. Never re-implement scope policy per-caller.+ """+ try:+ from tools.tool_backend_helpers import resolve_provider_secret++ return resolve_provider_secret("XAI_API_KEY", "xai", env_getter=get_env_value)+ except ImportError: # pragma: no cover — helpers are in-repo+ return str(get_env_value("XAI_API_KEY") or "").strip()+++def _resolve_explicit_xai_base_url(default: str = "https://api.x.ai/v1") -> str:+ """Base URL for the explicit-API-key path.++ Honors ``HERMES_XAI_BASE_URL`` then ``XAI_BASE_URL`` (the same override+ pair the OAuth branch reads) and pins the origin with+ :func:`hermes_cli.auth._xai_validate_inference_base_url` so a tampered+ env override can't exfiltrate the bearer; on rejection it falls back to+ the default rather than raising.+ """+ override = str(+ get_env_value("HERMES_XAI_BASE_URL")+ or get_env_value("XAI_BASE_URL")+ or ""+ ).strip().rstrip("/")+ try:+ import hermes_cli.auth as auth_mod++ return auth_mod._xai_validate_inference_base_url(override, fallback=default)+ except Exception: # pragma: no cover — auth is in-repo+ return override or default++def resolve_xai_http_credentials(*,force_refresh: bool = False,api_key_hint: Optional[str] = None,+ prefer_api_key: bool = False,) -> Dict[str, str]:"""Resolve bearer credentials for direct xAI HTTP endpoints.@@ -268,11 +308,31 @@ def resolve_xai_http_credentials(endpoints (images, TTS, STT, etc.) aligned with the main runtime auth modeland preserves the regression contract from PR #17140 / #17163.+ Set ``prefer_api_key=True`` to invert that order: check the explicit+ ``XAI_API_KEY`` first and use OAuth only as the fallback. This is for+ API-metered endpoints where a subscription OAuth bearer *authorizes* but+ misbehaves — ``/v1/responses`` x_search answers in a degraded Grok+ explanatory mode with no citations (#88040), and ``/v1/tts`` returns 403+ (#87045). The key is read through+ :func:`tools.tool_backend_helpers.resolve_provider_secret` so profile+ secret scoping is identical to the fallback branch, and the base URL+ honors ``HERMES_XAI_BASE_URL`` / ``XAI_BASE_URL`` behind the same+ origin-pinning validation as the OAuth branch.+Set ``force_refresh=True`` to perform an unconditional OAuth refresh.Reactive callers should also pass the rejected bearer as ``api_key_hint``so a freshly loaded multi-account pool refreshes the exact issuing entry,not whichever entry its strategy would otherwise select first."""+ if prefer_api_key:+ explicit_key = str(_resolve_explicit_xai_api_key() or "").strip()+ if explicit_key:+ return {+ "provider": "xai",+ "api_key": explicit_key,+ "base_url": _resolve_explicit_xai_base_url(),+ }+try:from agent.credential_pool import load_poolimport hermes_cli.auth as auth_moddiff --git a/website/docs/user-guide/features/x-search.md b/website/docs/user-guide/features/x-search.mdindex 7b8271d9ae5..ec06adde31e 100644--- a/website/docs/user-guide/features/x-search.md+++ b/website/docs/user-guide/features/x-search.md@@ -32,10 +32,10 @@ If you're paying Portal for an xAI model anyway, Live Search calls bill against| Credential | Source | Setup ||------------|--------|-------|-| **SuperGrok / X Premium+ OAuth** (preferred) | Browser login at `accounts.x.ai`, refreshed automatically | `hermes auth add xai-oauth` — see [xAI Grok OAuth (SuperGrok / X Premium+)](../../guides/xai-grok-oauth.md) |-| **`XAI_API_KEY`** | Paid xAI API key | Set in `~/.hermes/.env` |+| **SuperGrok / X Premium+ OAuth** | Browser login at `accounts.x.ai`, refreshed automatically | `hermes auth add xai-oauth` — see [xAI Grok OAuth (SuperGrok / X Premium+)](../../guides/xai-grok-oauth.md) |+| **`XAI_API_KEY`** (preferred) | Paid xAI API key | Set in `~/.hermes/.env` |-Both hit the same endpoint with the same payload — the only difference is the bearer token. **When both are configured, SuperGrok OAuth wins** so x_search runs against your subscription quota instead of paid API spend.+Both hit the same endpoint with the same payload — the only difference is the bearer token. **When both are configured, the explicit `XAI_API_KEY` wins** — the subscription OAuth bearer authorizes `/v1/responses` but answers x_search in a degraded Grok explanatory mode with no citations, while the API key returns real posts. Note this means x_search runs against metered API billing when a key is set; remove `XAI_API_KEY` to fall back to your subscription quota (with the degraded-answer caveat).The tool's `check_fn` runs the xAI credential resolver every time the model's tool list is rebuilt. A `True` return means the bearer is fetchable AND non-empty AND (if it had expired) successfully refreshed. Revoked tokens with a failed refresh hide the tool from the schema; the model simply can't see it.