The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(xai): alias the reserved tool_search bridge on the wire (#95003)
David Zhangde123be524ed
diff --git a/agent/transports/codex.py b/agent/transports/codex.pyindex e64cfc2a709..d7119af27b7 100644--- a/agent/transports/codex.py+++ b/agent/transports/codex.py@@ -9,7 +9,7 @@ import hashlibimport jsonimport loggingimport re-from typing import Any, Dict, List, Optional+from typing import Any, Dict, List, Optional, Tuplelogger = logging.getLogger(__name__)@@ -70,10 +70,24 @@ _XAI_CLIENT_WEB_SEARCH_ALIAS = "hermes_web_search"# rename on the wire (hermes_<name>), map back in normalize_response so# Hermes dispatch is unaffected._OPENCODE_RESERVED_TOOL_NAMES = ("web_search", "search_files")++# xAI reserves ``tool_search`` server-side for Grok's own native Tool Search+# and rejects *any* client function declared with that name:+# HTTP 400 {"code":"invalid-argument","error":"The function name+# tool_search is reserved for the tool_search tool"}+# Hermes's progressive-disclosure bridge registers exactly that literal+# (``tools.tool_search.TOOL_SEARCH_NAME``), and assembly is not provider+# gated, so with ``tools.tool_search.enabled: auto`` a grok turn dies the+# moment the catalog crosses the threshold — mid-session, and only for+# sessions large enough to activate the bridge. Same treatment as the two+# collisions above. ``tool_describe`` / ``tool_call`` are not reserved.+# Refs #95003.+_XAI_RESERVED_TOOL_NAMES = ("tool_search",)+_RESERVED_TOOL_ALIAS_PREFIX = "hermes_"_RESERVED_ALIAS_TO_NAME = {f"{_RESERVED_TOOL_ALIAS_PREFIX}{name}": name- for name in _OPENCODE_RESERVED_TOOL_NAMES+ for name in (*_OPENCODE_RESERVED_TOOL_NAMES, *_XAI_RESERVED_TOOL_NAMES)}@@ -100,11 +114,19 @@ def _is_opencode_responses_backend(params: Dict[str, Any]) -> bool:return False-def _rename_reserved_tools_for_opencode(response_tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]:- """Alias OpenCode-reserved client function names on the wire."""+def _alias_reserved_tools(+ response_tools: List[Dict[str, Any]],+ reserved_names: Tuple[str, ...],+) -> List[Dict[str, Any]]:+ """Alias provider-reserved client function names on the wire.++ Single owner for every reserved-name collision on this transport; the+ reverse mapping lives in :data:`_RESERVED_ALIAS_TO_NAME`, applied in+ ``normalize_response`` so Hermes dispatch never sees the alias.+ """rewritten: List[Dict[str, Any]] = []for tool in response_tools:- if isinstance(tool, dict) and tool.get("name") in _OPENCODE_RESERVED_TOOL_NAMES:+ if isinstance(tool, dict) and tool.get("name") in reserved_names:aliased = dict(tool)aliased["name"] = f"{_RESERVED_TOOL_ALIAS_PREFIX}{tool['name']}"rewritten.append(aliased)@@ -626,7 +648,17 @@ class ResponsesApiTransport(ProviderTransport):# function names (HTTP 400 "custom function name 'X' is reserved",# #85589). Alias them on the wire; normalize_response maps them back.if response_tools and _is_opencode_responses_backend(params):- response_tools = _rename_reserved_tools_for_opencode(response_tools)+ response_tools = _alias_reserved_tools(+ response_tools, _OPENCODE_RESERVED_TOOL_NAMES+ )++ # xAI reserves ``tool_search`` for its native server-side tool and+ # rejects the client declaration outright (#95003). Alias it on the+ # wire; normalize_response maps it back before dispatch.+ if is_xai_responses and response_tools:+ response_tools = _alias_reserved_tools(+ response_tools, _XAI_RESERVED_TOOL_NAMES+ )# ``tools`` MUST be omitted entirely when there are no functions to# expose: the openai SDK's ``responses.stream()`` / ``responses.parse()``diff --git a/tests/agent/transports/test_codex_transport.py b/tests/agent/transports/test_codex_transport.pyindex 9d80ffed477..4f0bdbf69bb 100644--- a/tests/agent/transports/test_codex_transport.py+++ b/tests/agent/transports/test_codex_transport.py@@ -937,6 +937,109 @@ class TestOpencodeReservedToolAliases:assert names == ["search_files", "web_search"]+class TestXaiReservedToolSearchAlias:+ """xAI reserves ``tool_search`` for Grok's native Tool Search and rejects+ the client declaration with HTTP 400 (#95003). The transport aliases the+ progressive-disclosure bridge on the wire and maps it back on dispatch."""++ @pytest.fixture+ def transport(self):+ from agent.transports.codex import ResponsesApiTransport+ return ResponsesApiTransport()++ _TOOLS = [+ {"type": "function", "function": {+ "name": "tool_search", "description": "Search deferred tools.",+ "parameters": {"type": "object",+ "properties": {"query": {"type": "string"}}}}},+ {"type": "function", "function": {+ "name": "tool_describe", "description": "Describe a deferred tool.",+ "parameters": {"type": "object",+ "properties": {"name": {"type": "string"}}}}},+ {"type": "function", "function": {+ "name": "read_file", "description": "Read a file.",+ "parameters": {"type": "object",+ "properties": {"path": {"type": "string"}}}}},+ ]++ def _names(self, kw):+ return [t.get("name") for t in kw.get("tools", []) if t.get("type") == "function"]++ def test_xai_aliases_reserved_tool_search(self, transport):+ kw = transport.build_kwargs(+ model="grok-4.6",+ messages=[{"role": "user", "content": "hi"}],+ tools=list(self._TOOLS),+ is_xai_responses=True,+ )+ names = self._names(kw)+ assert "hermes_tool_search" in names+ assert "tool_search" not in names+ # Only ``tool_search`` is reserved — the sibling bridge tools and+ # ordinary tools go out untouched.+ assert "tool_describe" in names+ assert "read_file" in names++ def test_non_xai_backend_keeps_tool_search_name(self, transport):+ kw = transport.build_kwargs(+ model="gpt-5.4",+ messages=[{"role": "user", "content": "hi"}],+ tools=list(self._TOOLS),+ is_codex_backend=True,+ base_url="https://api.openai.com/v1",+ )+ names = self._names(kw)+ assert "tool_search" in names+ assert "hermes_tool_search" not in names++ def test_alias_composes_with_native_web_search_swap(self, transport, monkeypatch):+ """The bridge alias must survive the xAI web_search branch (#48108)."""+ import agent.transports.codex as codex_mod++ monkeypatch.setattr(codex_mod, "_xai_prefers_native_web_search", lambda: True)+ tools = list(self._TOOLS) + [+ {"type": "function", "function": {+ "name": "web_search", "description": "Search the web.",+ "parameters": {"type": "object",+ "properties": {"query": {"type": "string"}}}}},+ ]+ kw = transport.build_kwargs(+ model="grok-4.6",+ messages=[{"role": "user", "content": "hi"}],+ tools=tools,+ is_xai_responses=True,+ )+ assert any(t.get("type") == "web_search" for t in kw.get("tools", []))+ names = self._names(kw)+ assert "hermes_tool_search" in names+ assert "tool_search" not in names++ def test_normalize_maps_tool_search_alias_back(self, transport, monkeypatch):+ msg = SimpleNamespace(+ content=None,+ reasoning=None,+ tool_calls=[+ SimpleNamespace(+ id="call_1", call_id="call_1", response_item_id="fc_1",+ function=SimpleNamespace(+ name="hermes_tool_search",+ arguments='{"query":"create github issue"}',+ ),+ ),+ ],+ codex_reasoning_items=None,+ codex_message_items=None,+ reasoning_details=None,+ )+ response = SimpleNamespace(output=[], status="completed")+ monkeypatch.setattr(+ "agent.codex_responses_adapter._normalize_codex_response",+ lambda resp, issuer_kind=None: (msg, "tool_calls"),+ )+ normalized = transport.normalize_response(response)+ assert [tc.name for tc in normalized.tool_calls] == ["tool_search"]++class TestXaiWebSearchBackendPreference:"""``_xai_prefers_native_web_search`` must honor web backend config."""