Skip to content

The agent that grows with you

fix(opencode): family-wide provider predicate + reserved tool-name aliases for custom opencode-* providers

Tekniuma83c3915a336
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 2744c1b72da..0d8dd855928 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -2616,9 +2616,11 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo
# hit /v1/v1/messages. `model_switch.switch_model()` already strips
# this, but we guard here so any direct callers (future code paths,
# tests) can't reintroduce the double-/v1 404 bug.
+ from hermes_cli.models import opencode_provider_family
+
if (
api_mode == "anthropic_messages"
- and new_provider in {"opencode-zen", "opencode-go"}
+ and opencode_provider_family(new_provider) is not None
and isinstance(base_url, str)
and base_url
):
diff --git a/agent/transports/codex.py b/agent/transports/codex.py
index 02e7390c630..38e86a654cf 100644
--- a/agent/transports/codex.py
+++ b/agent/transports/codex.py
@@ -59,6 +59,56 @@ def _bounded_prompt_cache_key(value: Any) -> Optional[str]:
# (Firecrawl / Tavily / …). Mapped back to ``web_search`` in normalize_response.
_XAI_CLIENT_WEB_SEARCH_ALIAS = "hermes_web_search"
+# OpenCode's /v1/responses endpoints (Zen and Go, including custom providers
+# pointing at opencode.ai) reserve certain function names server-side and
+# reject client tools that use them with HTTP 400 ("custom function name
+# 'X' is reserved"). Reported for grok-4.5 on Go with `search_files` and
+# `web_search` (#85589). Same treatment as the xAI web_search collision:
+# rename on the wire (hermes_<name>), map back in normalize_response so
+# Hermes dispatch is unaffected.
+_OPENCODE_RESERVED_TOOL_NAMES = ("web_search", "search_files")
+_RESERVED_TOOL_ALIAS_PREFIX = "hermes_"
+_RESERVED_ALIAS_TO_NAME = {
+ f"{_RESERVED_TOOL_ALIAS_PREFIX}{name}": name
+ for name in _OPENCODE_RESERVED_TOOL_NAMES
+}
+
+
+def _is_opencode_responses_backend(params: Dict[str, Any]) -> bool:
+ """True when this Responses request targets an OpenCode endpoint.
+
+ Matches the built-in opencode-zen/go providers, custom ``opencode-go-*`` /
+ ``opencode-zen-*`` family providers, and any base_url hosted on
+ opencode.ai (covers custom providers with arbitrary names pointing at
+ the OpenCode gateway).
+ """
+ try:
+ from hermes_cli.models import opencode_provider_family
+
+ if opencode_provider_family(params.get("provider")) is not None:
+ return True
+ except Exception:
+ pass
+ try:
+ from utils import base_url_hostname
+
+ return base_url_hostname(str(params.get("base_url") or "")).lower() == "opencode.ai"
+ except Exception:
+ 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."""
+ rewritten: List[Dict[str, Any]] = []
+ for tool in response_tools:
+ if isinstance(tool, dict) and tool.get("name") in _OPENCODE_RESERVED_TOOL_NAMES:
+ aliased = dict(tool)
+ aliased["name"] = f"{_RESERVED_TOOL_ALIAS_PREFIX}{tool['name']}"
+ rewritten.append(aliased)
+ else:
+ rewritten.append(tool)
+ return rewritten
+
def _xai_prefers_native_web_search() -> bool:
"""True when xAI Responses should use Grok's native ``web_search`` built-in.
@@ -503,6 +553,12 @@ class ResponsesApiTransport(ProviderTransport):
else:
response_tools = _rename_client_web_search_for_xai(response_tools)
+ # OpenCode Responses backends reserve web_search / search_files as
+ # 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)
+
# ``tools`` MUST be omitted entirely when there are no functions to
# expose: the openai SDK's ``responses.stream()`` / ``responses.parse()``
# eagerly call ``_make_tools(tools)`` which does ``for tool in tools``
@@ -734,6 +790,10 @@ class ResponsesApiTransport(ProviderTransport):
# the real ``web_search`` tool (Firecrawl / etc.).
if name == _XAI_CLIENT_WEB_SEARCH_ALIAS:
name = "web_search"
+ # Undo the OpenCode reserved-name wire aliases the same way
+ # (hermes_web_search / hermes_search_files, #85589).
+ elif name in _RESERVED_ALIAS_TO_NAME:
+ name = _RESERVED_ALIAS_TO_NAME[name]
tool_calls.append(ToolCall(
id=tc.id if hasattr(tc, "id") else (name or None),
name=name,
diff --git a/cli.py b/cli.py
index 66d63321aea..b53906386ac 100644
--- a/cli.py
+++ b/cli.py
@@ -7384,7 +7384,9 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin):
pass
return changed
- if resolved_provider in {"opencode-zen", "opencode-go"}:
+ from hermes_cli.models import opencode_provider_family
+
+ if opencode_provider_family(resolved_provider) is not None:
try:
from hermes_cli.models import normalize_opencode_model_id, opencode_model_api_mode
diff --git a/hermes_cli/model_normalize.py b/hermes_cli/model_normalize.py
index d2dfe132a8a..31bd5ff3c57 100644
--- a/hermes_cli/model_normalize.py
+++ b/hermes_cli/model_normalize.py
@@ -504,11 +504,14 @@ def normalize_model_for_provider(model_input: str, target_provider: str) -> str:
# — commonly copied from aggregator slugs into fallback_model lists —
# resolve to bare ``minimax-m2.7`` / ``deepseek-v4-flash`` the API
# actually serves. See PR reviewing opencode-go fallback 401s. ---
- if provider in {"opencode-zen", "opencode-go"}:
+ from hermes_cli.models import opencode_provider_family
+
+ _oc_family = opencode_provider_family(provider)
+ if _oc_family is not None:
if "/" in name:
_, bare_after_slash = name.split("/", 1)
name = bare_after_slash.strip() or name
- if provider == "opencode-zen" and name.lower().startswith("claude-"):
+ if _oc_family == "opencode-zen" and name.lower().startswith("claude-"):
return _dots_to_hyphens(name)
return name
diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.py
index aae5f4cadee..d8d1f476ba6 100644
--- a/hermes_cli/model_switch.py
+++ b/hermes_cli/model_switch.py
@@ -2164,7 +2164,8 @@ def switch_model(
# page — and without the re-append, a stripped URL persisted to
# model.base_url broke every later chat_completions model (glm, deepseek,
# kimi) the same way.
- if target_provider in {"opencode-zen", "opencode-go"} and isinstance(base_url, str):
+ from hermes_cli.models import opencode_provider_family as _oc_family_fn
+ if _oc_family_fn(target_provider) is not None and isinstance(base_url, str):
from hermes_cli.models import normalize_opencode_base_url
base_url = normalize_opencode_base_url(target_provider, api_mode, base_url)
diff --git a/hermes_cli/models.py b/hermes_cli/models.py
index bea8f590d04..98337c5ad4e 100644
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@ -5271,20 +5271,44 @@ def azure_foundry_model_api_mode(model_name: Optional[str]) -> Optional[str]:
return None
+def opencode_provider_family(provider_id: Optional[str]) -> Optional[str]:
+ """Resolve a provider id to its OpenCode family, or None.
+
+ Returns ``"opencode-zen"`` or ``"opencode-go"`` for the built-in
+ providers AND for custom providers whose name extends a family slug
+ (e.g. ``opencode-go-bridge`` pointing at ``https://opencode.ai/zen/go/v1``,
+ issue #85589). Matching is case-insensitive. Custom family providers
+ need the same per-model api_mode routing and /v1 base-url normalization
+ as the built-ins — this predicate is the single owner of that
+ family-membership question; do not re-implement it inline.
+
+ ``opencode-go`` is checked before ``opencode-zen`` but the two slugs are
+ not prefixes of each other, so order is cosmetic.
+ """
+ raw = str(provider_id or "").strip().lower()
+ if not raw:
+ return None
+ canonical = normalize_provider(provider_id)
+ if canonical in {"opencode-zen", "opencode-go"}:
+ return canonical
+ if raw.startswith("opencode-go"):
+ return "opencode-go"
+ if raw.startswith("opencode-zen"):
+ return "opencode-zen"
+ return None
+
+
def normalize_opencode_model_id(provider_id: Optional[str], model_id: Optional[str]) -> str:
"""Normalize OpenCode config IDs to the bare model slug used in API requests."""
- provider = normalize_provider(provider_id)
+ family = opencode_provider_family(provider_id)
current = str(model_id or "").strip()
- is_opencode = provider in {"opencode-zen", "opencode-go"} or (
- isinstance(provider_id, str) and provider_id.lower().startswith(("opencode-go", "opencode-zen"))
- )
- if not current or not is_opencode:
+ if not current or family is None:
return current
- prefix = f"{provider_id}/" if provider_id else f"{provider}/"
+ prefix = f"{provider_id}/" if provider_id else f"{family}/"
if current.lower().startswith(prefix.lower()):
return current[len(prefix):]
- fallback_prefix = f"{provider}/"
+ fallback_prefix = f"{family}/"
if current.lower().startswith(fallback_prefix.lower()):
return current[len(fallback_prefix):]
return current
@@ -5308,15 +5332,12 @@ def opencode_model_api_mode(provider_id: Optional[str], model_id: Optional[str])
This follows the published OpenCode docs for Zen and Go endpoints
(https://opencode.ai/docs/zen/ and https://opencode.ai/docs/go/).
"""
- provider = normalize_provider(provider_id)
+ family = opencode_provider_family(provider_id)
normalized = normalize_opencode_model_id(provider_id, model_id).lower()
if not normalized:
return "chat_completions"
- is_opencode_go = provider == "opencode-go" or (
- isinstance(provider_id, str) and provider_id.lower().startswith("opencode-go")
- )
- if is_opencode_go:
+ if family == "opencode-go":
if normalized.startswith("gpt-") or normalized.startswith("grok-"):
# GPT and Grok models on Go (gpt-5.6-luna, grok-4.5) are served
# via /v1/responses per the published Go endpoint table, same as
@@ -5335,10 +5356,7 @@ def opencode_model_api_mode(provider_id: Optional[str], model_id: Optional[str])
return "anthropic_messages"
return "chat_completions"
- is_opencode_zen = provider == "opencode-zen" or (
- isinstance(provider_id, str) and provider_id.lower().startswith("opencode-zen")
- )
- if is_opencode_zen:
+ if family == "opencode-zen":
if normalized.startswith("claude-"):
return "anthropic_messages"
if normalized.startswith("gpt-") or normalized.startswith("grok-"):
@@ -5383,11 +5401,7 @@ def normalize_opencode_base_url(
url = str(base_url or "").strip().rstrip("/")
if not url:
return url
- provider = normalize_provider(provider_id)
- is_opencode = provider in {"opencode-zen", "opencode-go"} or (
- isinstance(provider_id, str) and provider_id.lower().startswith(("opencode-go", "opencode-zen"))
- )
- if not is_opencode:
+ if opencode_provider_family(provider_id) is None:
return url
import re as _re
diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.py
index fd12b9c2fda..a0ef2394935 100644
--- a/hermes_cli/runtime_provider.py
+++ b/hermes_cli/runtime_provider.py
@@ -567,10 +567,8 @@ def _resolve_runtime_from_pool_entry(
if cfg_base_url:
base_url = cfg_base_url
configured_mode = _parse_api_mode(model_cfg.get("api_mode"))
- is_opencode_provider = provider in {"opencode-zen", "opencode-go"} or (
- isinstance(provider, str) and provider.lower().startswith(("opencode-go", "opencode-zen"))
- )
- if is_opencode_provider:
+ from hermes_cli.models import opencode_provider_family
+ if opencode_provider_family(provider) is not None:
# Re-derive api_mode from the effective model rather than the
# persisted api_mode: the opencode providers serve both
# anthropic_messages and chat_completions models, so the previous
@@ -591,10 +589,8 @@ def _resolve_runtime_from_pool_entry(
# symmetrically: strip /v1 for anthropic_messages, re-append it for
# chat_completions / codex_responses (heals a stripped URL persisted to
# model.base_url by an earlier switch into an anthropic-routed model).
- is_opencode_provider = provider in {"opencode-zen", "opencode-go"} or (
- isinstance(provider, str) and provider.lower().startswith(("opencode-go", "opencode-zen"))
- )
- if is_opencode_provider:
+ from hermes_cli.models import opencode_provider_family
+ if opencode_provider_family(provider) is not None:
from hermes_cli.models import normalize_opencode_base_url
base_url = normalize_opencode_base_url(provider, api_mode, base_url)
@@ -2311,10 +2307,8 @@ def resolve_runtime_provider(
configured_provider = str(model_cfg.get("provider") or "").strip().lower()
# Only honor persisted api_mode when it belongs to the same provider family.
configured_mode = _parse_api_mode(model_cfg.get("api_mode"))
- is_opencode_provider = provider in {"opencode-zen", "opencode-go"} or (
- isinstance(provider, str) and provider.lower().startswith(("opencode-go", "opencode-zen"))
- )
- if is_opencode_provider:
+ from hermes_cli.models import opencode_provider_family
+ if opencode_provider_family(provider) is not None:
# opencode-zen/go must always re-derive api_mode from the
# target model (not the stale persisted api_mode), because
# the same provider serves both anthropic_messages
@@ -2336,10 +2330,8 @@ def resolve_runtime_provider(
provider, base_url, target_model or model_cfg.get("default", "")
)
# Normalize the /v1 suffix for OpenCode by API mode (see comment above).
- is_opencode_provider = provider in {"opencode-zen", "opencode-go"} or (
- isinstance(provider, str) and provider.lower().startswith(("opencode-go", "opencode-zen"))
- )
- if is_opencode_provider:
+ from hermes_cli.models import opencode_provider_family
+ if opencode_provider_family(provider) is not None:
from hermes_cli.models import normalize_opencode_base_url
base_url = normalize_opencode_base_url(provider, api_mode, base_url)
if provider == "lmstudio":
diff --git a/tests/agent/transports/test_codex_transport.py b/tests/agent/transports/test_codex_transport.py
index 533bba8551d..47b5c4e0474 100644
--- a/tests/agent/transports/test_codex_transport.py
+++ b/tests/agent/transports/test_codex_transport.py
@@ -805,6 +805,122 @@ class TestCodexBuildKwargs:
assert "reasoning" not in kw, f"{model} must not receive reasoning"
+class TestOpencodeReservedToolAliases:
+ """OpenCode /v1/responses reserves web_search / search_files as function
+ names (HTTP 400 "custom function name 'X' is reserved", #85589). The
+ transport aliases them on the wire and maps them back on dispatch."""
+
+ @pytest.fixture
+ def transport(self):
+ from agent.transports.codex import ResponsesApiTransport
+ return ResponsesApiTransport()
+
+ _TOOLS = [
+ {"type": "function", "function": {
+ "name": "search_files", "description": "Search files.",
+ "parameters": {"type": "object",
+ "properties": {"pattern": {"type": "string"}}}}},
+ {"type": "function", "function": {
+ "name": "web_search", "description": "Search the web.",
+ "parameters": {"type": "object",
+ "properties": {"query": {"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_builtin_opencode_go_aliases_reserved_names(self, transport):
+ kw = transport.build_kwargs(
+ model="grok-4.5",
+ messages=[{"role": "user", "content": "hi"}],
+ tools=list(self._TOOLS),
+ provider="opencode-go",
+ base_url="https://opencode.ai/zen/go/v1",
+ )
+ names = self._names(kw)
+ assert "hermes_search_files" in names
+ assert "hermes_web_search" in names
+ assert "search_files" not in names
+ assert "web_search" not in names
+ assert "read_file" in names # non-reserved untouched
+
+ def test_custom_opencode_family_provider_aliases_reserved_names(self, transport):
+ """Custom opencode-go-* providers get the same aliasing (#85589)."""
+ kw = transport.build_kwargs(
+ model="grok-4.5",
+ messages=[{"role": "user", "content": "hi"}],
+ tools=list(self._TOOLS),
+ provider="opencode-go-bridge",
+ base_url="https://opencode.ai/zen/go/v1",
+ )
+ names = self._names(kw)
+ assert "hermes_search_files" in names
+ assert "search_files" not in names
+
+ def test_opencode_host_match_without_family_provider(self, transport):
+ """An arbitrary custom provider pointing at opencode.ai still aliases."""
+ kw = transport.build_kwargs(
+ model="gpt-5.6-luna",
+ messages=[{"role": "user", "content": "hi"}],
+ tools=list(self._TOOLS),
+ provider="my-oc-proxy",
+ base_url="https://opencode.ai/zen/go/v1",
+ )
+ names = self._names(kw)
+ assert "hermes_search_files" in names
+ assert "hermes_web_search" in names
+
+ def test_non_opencode_backend_keeps_original_names(self, transport):
+ kw = transport.build_kwargs(
+ model="gpt-5.4",
+ messages=[{"role": "user", "content": "hi"}],
+ tools=list(self._TOOLS),
+ provider="openai-codex",
+ base_url="https://api.openai.com/v1",
+ )
+ names = self._names(kw)
+ assert "search_files" in names
+ assert "web_search" in names
+ assert "hermes_search_files" not in names
+
+ def test_normalize_maps_reserved_aliases_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_search_files",
+ arguments='{"pattern":"README"}',
+ ),
+ ),
+ SimpleNamespace(
+ id="call_2", call_id="call_2", response_item_id="fc_2",
+ function=SimpleNamespace(
+ name="hermes_web_search",
+ arguments='{"query":"hermes"}',
+ ),
+ ),
+ ],
+ 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)
+ names = [tc.name for tc in normalized.tool_calls]
+ assert names == ["search_files", "web_search"]
+
+
class TestXaiWebSearchBackendPreference:
"""``_xai_prefers_native_web_search`` must honor web backend config."""