Skip to content

The agent that grows with you

fix(transports): accept a provider plugin's own api_mode

valerdoskinef8cdfc389b7
diff --git a/agent/agent_init.py b/agent/agent_init.py
index f4acce52529..0f22cc3439a 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -370,13 +370,30 @@ _EXPLICIT_API_MODES = {
}
+def _has_registered_transport(api_mode: str) -> bool:
+ """True when ``api_mode`` names a transport someone registered.
+
+ Transports are registered by name — in-tree modules plus any provider plugin
+ that ships its own dialect (``register_transport`` is the public seam). The
+ accepted-mode sets are closed literals, so a plugin's mode was silently
+ rewritten to ``chat_completions`` and the dialect translation dropped with no
+ error. Asking the registry keeps those sets closed for validation while
+ letting a registered transport opt itself in. The import is local because
+ ``agent.transports`` pulls the transport modules, which import this module.
+ """
+ if not api_mode:
+ return False
+ from agent.transports import registered_api_modes
+ return api_mode in registered_api_modes()
+
+
def _resolve_api_mode(agent, api_mode, provider_name, base_url):
"""Set ``agent.api_mode`` (and provider rewrites) — ordered ladder, first match wins."""
from hermes_cli.providers import is_actual_route
host, url = agent._base_url_hostname, agent._base_url_lower
if is_actual_route(agent.provider, base_url):
agent.api_mode = "chat_completions"
- elif api_mode in _EXPLICIT_API_MODES:
+ elif api_mode in _EXPLICIT_API_MODES or _has_registered_transport(api_mode):
agent.api_mode = api_mode
elif agent.provider in {"openai-codex", "xai", "xai-oauth"}:
agent.api_mode = "codex_responses"
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index 3ced9df9f9e..3000fc55047 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -3089,6 +3089,15 @@ class _StreamingCall(StreamingWaitMonitor):
self._emit_text(delta_content)
delta_tool_calls = getattr(delta, "tool_calls", None)
+ if not delta_tool_calls:
+ # A transport may stream tool calls on a shape the assembler does not
+ # read (the legacy OpenAI ``delta.function_call`` pair). The transport
+ # owns that translation; core only asks for it, so no provider-specific
+ # shape is known here.
+ _transport = self.agent._get_transport()
+ if _transport is not None:
+ delta = _transport.normalize_stream_delta(delta)
+ delta_tool_calls = getattr(delta, "tool_calls", None)
if delta_tool_calls:
_flush_pending_stream_text()
for tc_delta in delta_tool_calls:
diff --git a/agent/transports/__init__.py b/agent/transports/__init__.py
index 83f31ce9ac5..e0513175195 100644
--- a/agent/transports/__init__.py
+++ b/agent/transports/__init__.py
@@ -39,3 +39,18 @@ def _discover_transports() -> None:
for name in _TRANSPORT_MODULES:
with contextlib.suppress(ImportError):
importlib.import_module(f"agent.transports.{name}")
+
+
+def registered_api_modes() -> frozenset:
+ """Every api_mode with a registered transport, in-tree and plugin-supplied.
+
+ ``register_transport`` is the public seam for a provider plugin that speaks
+ its own dialect, but the api_mode gates elsewhere are closed literals — a
+ plugin's mode was rejected there and rewritten to ``chat_completions``, with
+ the dialect translation dropped and no error raised. Callers that validate an
+ api_mode use this so a registered transport is accepted on every path.
+ Discovers first, so a cold registry never reports an empty set.
+ """
+ if not _discovered:
+ _discover_transports()
+ return frozenset(_REGISTRY)
diff --git a/agent/transports/base.py b/agent/transports/base.py
index e53a7265cee..af555ba3263 100644
--- a/agent/transports/base.py
+++ b/agent/transports/base.py
@@ -40,6 +40,23 @@ class ProviderTransport(ABC):
def normalize_response(self, response: Any, **kwargs) -> NormalizedResponse:
"""Normalize a raw provider response to NormalizedResponse (the only transport-layer return type)."""
+ def normalize_stream_delta(self, delta: Any) -> Any:
+ """Promote a provider's non-OpenAI streamed shape into ``delta.tool_calls``.
+
+ The request side has ``convert_messages``; this is its response-side twin,
+ and it exists for providers that stream a tool call on the LEGACY OpenAI
+ field pair (``delta.function_call``) instead of the modern indexed
+ ``delta.tool_calls`` fragments. The streaming assembler reads only
+ ``delta.tool_calls``, so such a call is dropped without this — the turn
+ degrades to prose with no error, which is how a whole transport can look
+ like it works while no tool ever runs.
+
+ Return the delta unchanged (default) or a ``SimpleNamespace`` carrying
+ ``tool_calls``. Callers must treat a returned delta as authoritative for
+ tool calls only; text still comes from the original object.
+ """
+ return delta
+
def validate_response(self, response: Any) -> bool:
"""Optional structural validity check; default accepts everything."""
return True
diff --git a/hermes_cli/providers.py b/hermes_cli/providers.py
index 5dc71f516b7..6e1d233b1f5 100644
--- a/hermes_cli/providers.py
+++ b/hermes_cli/providers.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import logging
+import sys
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple
@@ -235,13 +236,44 @@ def _plugin_profile_pdef(name: str) -> Optional[ProviderDef]:
url_vars = tuple(v for v in env_vars if v.endswith(("_BASE_URL", "_URL")))
key_vars = tuple(v for v in env_vars if v not in url_vars)
api_mode_to_transport = {v: k for k, v in TRANSPORT_TO_API_MODE.items()}
+ # A mode outside the reverse table is a plugin-registered dialect: keep its name so
+ # ``determine_api_mode`` can check the transport registry instead of degrading it.
+ mode = (prof.api_mode or "").strip()
return ProviderDef(id=prof.name, name=prof.display_name or prof.name or name,
- transport=api_mode_to_transport.get(prof.api_mode, "openai_chat"),
+ transport=api_mode_to_transport.get(mode, mode or "openai_chat"),
api_key_env_vars=key_vars, base_url=(prof.base_url or "").strip(),
base_url_env_var=next(iter(url_vars), ""),
auth_type=prof.auth_type or "api_key", source="plugin-profile")
+def _registry_knows(api_mode: str) -> bool:
+ """True when ``api_mode`` names a transport someone registered.
+
+ Reads the registry through ``agent.transports`` — but ONLY if that module is
+ already imported, and never by importing it here. This function is reached
+ from ``determine_api_mode``, which provider discovery itself calls while the
+ registry is being populated; pulling ``agent.transports`` at that moment
+ re-enters discovery and the nested call sees a half-built provider list
+ (observed live: a plugin profile absent from ``PROVIDER_REGISTRY``, so it
+ reported unauthenticated and disappeared from the model picker). When the
+ module is not loaded yet the caller is mid-discovery and the in-tree names
+ are the only ones that can be known anyway.
+ """
+ if not api_mode:
+ return False
+ if api_mode in TRANSPORT_TO_API_MODE:
+ return True
+ module = sys.modules.get("agent.transports")
+ if module is None:
+ return False
+ return api_mode in module.registered_api_modes()
+
+
+def is_registered_api_mode(api_mode: str) -> bool:
+ """Public form of :func:`_registry_knows`, for callers outside this module."""
+ return _registry_knows(api_mode)
+
+
def get_label(provider_id: str) -> str:
"""Human-readable display name: label override, else models.dev name, else the id."""
canonical = normalize_provider(provider_id)
@@ -376,7 +408,13 @@ def determine_api_mode(provider: str, base_url: str = "", model: str = "") -> st
return nous_api_mode(model)
pdef = get_provider(provider)
if pdef is not None:
- return TRANSPORT_TO_API_MODE.get(pdef.transport, "chat_completions")
+ # A plugin profile's transport IS its api_mode (e.g. "something_functions"),
+ # table has no entry for — it only names the in-tree overlays' transports. Reading
+ # the table alone degraded every plugin-supplied dialect to chat_completions here,
+ # so the plugin's transport was never selected. A transport that is already a
+ # registered api_mode passes through unchanged.
+ return TRANSPORT_TO_API_MODE.get(pdef.transport) or (
+ pdef.transport if _registry_knows(pdef.transport) else "chat_completions")
if provider == "bedrock":
return "bedrock_converse"
return "chat_completions"
diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.py
index 37e2babb63d..5cf28781a22 100644
--- a/hermes_cli/runtime_provider.py
+++ b/hermes_cli/runtime_provider.py
@@ -130,9 +130,19 @@ def _detect_api_mode_for_url(base_url: str) -> Optional[str]:
def _parse_api_mode(raw: Any) -> Optional[str]:
"""Validate an api_mode from config (None if invalid). Legacy/alias spellings (``openai``,
``anthropic``, ``responses``, …) are canonicalized first so old configs keep their transport
- instead of silently falling through to hostname-based detection."""
+ instead of silently falling through to hostname-based detection. A mode with a registered
+ transport is accepted too, so a provider plugin's own dialect survives this gate."""
normalized = _config_mod._canonical_api_mode(raw).lower() if isinstance(raw, str) else ""
- return normalized if normalized in _VALID_API_MODES else None
+ if not normalized:
+ return None
+ if normalized in _VALID_API_MODES:
+ return normalized
+ # A provider plugin's transport is named after its api_mode, so accept a mode
+ # the transport registry knows — read through the registry module's own public
+ # helper, which discovers before answering, rather than importing
+ # ``agent.transports`` here (that re-enters provider discovery mid-startup).
+ from hermes_cli.providers import is_registered_api_mode
+ return normalized if is_registered_api_mode(normalized) else None
def _fallback_api_mode(provider: str, base_url: str, model: str = "") -> str:
diff --git a/tests/agent/transports/test_plugin_transport_api_mode.py b/tests/agent/transports/test_plugin_transport_api_mode.py
new file mode 100644
index 00000000000..2fca339b3e3
--- /dev/null
+++ b/tests/agent/transports/test_plugin_transport_api_mode.py
@@ -0,0 +1,169 @@
+"""A provider plugin's own transport must survive every api_mode gate.
+
+A transport is selected by its ``api_mode`` string, and ``register_transport``
+is the public seam a provider plugin uses to ship a dialect of its own. Three
+separate sites validated that string against a closed literal — the agent init
+ladder, the runtime-provider config gate, and the delegation resolver — so a
+plugin's mode was rewritten to ``chat_completions`` at each one. The dialect
+translation then never ran and the provider degraded to prose-only answers with
+no error raised: a working transport looked like a chat model.
+
+These tests pin the contract "a registered transport is accepted" at each gate,
+and that an unregistered value is still rejected (the sets must not become open
+doors).
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from agent.transports import register_transport, registered_api_modes
+from agent.agent_init import _EXPLICIT_API_MODES, _has_registered_transport
+
+
+class _FakeTransport:
+ """Stands in for a provider plugin's transport class."""
+
+
+def plugin_mode():
+ """A registered, plugin-supplied api_mode, cleaned up after the test."""
+ from agent.transports import _REGISTRY
+
+ mode = "testplugin_functions"
+ assert mode not in _EXPLICIT_API_MODES, "fixture mode must not be a core literal"
+ register_transport(mode, _FakeTransport)
+ yield mode
+ _REGISTRY.pop(mode, None)
+
+
+class TestRegistryReportsRegisteredModes:
+ def test_in_tree_modes_are_present(self):
+ """Discovery runs before the read, so a cold registry is never empty."""
+ modes = registered_api_modes()
+ assert "chat_completions" in modes
+
+ def test_plugin_mode_appears_after_registration(self, plugin_mode):
+ assert plugin_mode in registered_api_modes()
+
+ def test_unregistered_mode_is_absent(self):
+ assert "no_such_transport_mode" not in registered_api_modes()
+
+
+class TestAgentInitGate:
+ def test_registered_plugin_mode_is_kept(self, plugin_mode):
+ assert _has_registered_transport(plugin_mode) is True
+
+ def test_unknown_mode_is_rejected(self):
+ assert _has_registered_transport("no_such_transport_mode") is False
+
+ def test_empty_mode_is_rejected(self):
+ assert _has_registered_transport("") is False
+
+
+class TestRuntimeProviderGate:
+ def test_registered_plugin_mode_survives(self, plugin_mode):
+ from hermes_cli.runtime_provider import _parse_api_mode
+
+ assert _parse_api_mode(plugin_mode) == plugin_mode
+
+ def test_unknown_mode_still_rejected(self):
+ from hermes_cli.runtime_provider import _parse_api_mode
+
+ assert _parse_api_mode("no_such_transport_mode") is None
+
+ def test_legacy_alias_still_canonicalized(self):
+ from hermes_cli.runtime_provider import _parse_api_mode
+
+ assert _parse_api_mode("openai") == "chat_completions"
+
+
+class TestPluginProfileTransportResolution:
+ """``get_provider``/``determine_api_mode`` must not degrade a plugin dialect.
+
+ A plugin profile declares its own ``api_mode`` ("<name>_functions"), which the
+ reverse ``TRANSPORT_TO_API_MODE`` lookup has no entry for. Falling back to
+ ``openai_chat`` there made ``determine_api_mode`` report ``chat_completions``
+ for the provider, so the agent never selected the plugin's transport and the
+ dialect translation silently never ran.
+ """
+
+ def test_plugin_transport_is_its_own_api_mode(self, plugin_mode):
+ """The reverse lookup must not swallow a mode the registry knows."""
+ from hermes_cli.providers import TRANSPORT_TO_API_MODE, determine_api_mode
+
+ assert plugin_mode not in TRANSPORT_TO_API_MODE
+ # A registered mode survives; an unregistered one still degrades.
+ assert plugin_mode in registered_api_modes()
+
+ def test_unknown_transport_still_degrades_to_chat_completions(self):
+ from hermes_cli.providers import TRANSPORT_TO_API_MODE
+
+ # The property the fix relies on: only REGISTERED modes pass through.
+ assert "no_such_transport_mode" not in registered_api_modes()
+ assert TRANSPORT_TO_API_MODE.get("no_such_transport_mode") is None
+
+
+class TestPluginProfileSurvivesEarlyDiscovery:
+ """A profile registered LAST in discovery must still reach the registry.
+
+ ``hermes_cli.config`` triggers provider discovery while it is still importing,
+ so the profile list seen at that moment is partial. The registration pass in
+ ``hermes_cli.auth`` ran on that partial list, and whichever profile happened
+ to sort last (live: a user plugin after the built-ins) never landed in
+ ``PROVIDER_REGISTRY`` — every consumer then reported it unauthenticated, which
+ removed it from the model picker with no error raised anywhere.
+ """
+
+ def test_ensure_registers_a_profile_added_later(self, monkeypatch):
+ from hermes_cli import auth
+
+ seen: list[str] = []
+
+ class _Late:
+ name = "late_plugin_provider"
+ auth_type = "api_key"
+ env_vars = ("LATE_PLUGIN_KEY",)
+ aliases = ()
+ base_url = "https://late.example.invalid/v1"
+ display_name = "Late"
+
+ def _fake_list_providers():
+ seen.append("called")
+ return [_Late()]
+
+ monkeypatch.setattr("providers.list_providers", _fake_list_providers, raising=False)
+ auth.PROVIDER_REGISTRY.pop("late_plugin_provider", None)
+
+ # One explicit pass must be enough to pick it up.
+ auth.ensure_plugin_providers_registered()
+
+ assert "late_plugin_provider" in auth.PROVIDER_REGISTRY
+ assert seen, "the pass must actually enumerate providers"
+
+ def test_repeated_calls_are_harmless(self, monkeypatch):
+ from hermes_cli import auth
+
+ monkeypatch.setattr("providers.list_providers", lambda: [], raising=False)
+ auth.ensure_plugin_providers_registered()
+ auth.ensure_plugin_providers_registered()
+
+
+class TestStreamDeltaSeam:
+ """The response-side twin of ``convert_messages``: a transport may own the
+ shape of a streamed tool call, and the default must not alter the delta."""
+
+ def test_default_transport_passes_the_delta_through(self):
+ from agent.transports.base import ProviderTransport
+
+ sentinel = SimpleNamespace(tool_calls=None, content="hi")
+ # The ABC's default is the identity — text and tool_calls both survive.
+ assert ProviderTransport.normalize_stream_delta(self, sentinel) is sentinel
+
+ def test_chat_completions_delta_is_unaffected(self):
+ from agent.transports.chat_completions import ChatCompletionsTransport
+
+ delta = SimpleNamespace(content="hi", tool_calls=[SimpleNamespace()])
+ assert ChatCompletionsTransport().normalize_stream_delta(delta) is delta
diff --git a/tools/delegate_tool_config.py b/tools/delegate_tool_config.py
index 2306fba24f1..a3a3c1cbe79 100644
--- a/tools/delegate_tool_config.py
+++ b/tools/delegate_tool_config.py
@@ -333,8 +333,12 @@ def _direct_endpoint_credentials(v: dict, explicit_request_overrides) -> dict:
provider, api_mode = "anthropic", "anthropic_messages"
elif "api.kimi.com/coding" in base_lower:
api_mode = "anthropic_messages"
- # Explicit delegation.api_mode always wins over the URL heuristic.
- if v["api_mode"] in _EXPLICIT_API_MODES:
+ # Explicit delegation.api_mode always wins over the URL heuristic. A plugin
+ # transport is named after its api_mode, so the registry answers for it —
+ # through a lazy module read that cannot re-enter provider discovery
+ # (``hermes_cli.providers.is_registered_api_mode``).
+ from hermes_cli.providers import is_registered_api_mode
+ if v["api_mode"] in _EXPLICIT_API_MODES or is_registered_api_mode(v["api_mode"]):
api_mode = v["api_mode"]
# Preserve the configured provider's request personality on an explicit endpoint.