Skip to content

The agent that grows with you

refactor(transports): one registry read per api_mode gate; drop the stream-delta hook

teknium10f3d32ec588e
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 0f22cc3439a..5712731afd2 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -370,30 +370,16 @@ _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
+ from agent.transports import registered_api_modes
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 or _has_registered_transport(api_mode):
+ elif api_mode in _EXPLICIT_API_MODES or (api_mode and api_mode in registered_api_modes()):
+ # A provider plugin's own dialect (``register_transport(api_mode, cls)``) is as explicit
+ # as the in-tree modes; rewriting it to chat_completions silently dropped its transport.
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 3000fc55047..3ced9df9f9e 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -3089,15 +3089,6 @@ 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/base.py b/agent/transports/base.py
index af555ba3263..e53a7265cee 100644
--- a/agent/transports/base.py
+++ b/agent/transports/base.py
@@ -40,23 +40,6 @@ 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/runtime_provider.py b/hermes_cli/runtime_provider.py
index 5cf28781a22..1320a5c36d9 100644
--- a/hermes_cli/runtime_provider.py
+++ b/hermes_cli/runtime_provider.py
@@ -131,18 +131,12 @@ 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. A mode with a registered
- transport is accepted too, so a provider plugin's own dialect survives this gate."""
+ transport (a provider plugin's own dialect) is valid too."""
normalized = _config_mod._canonical_api_mode(raw).lower() if isinstance(raw, str) else ""
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
+ from agent.transports import registered_api_modes
+ return normalized if normalized in _VALID_API_MODES or normalized in registered_api_modes() 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
index 2fca339b3e3..c4bc4dbed66 100644
--- a/tests/agent/transports/test_plugin_transport_api_mode.py
+++ b/tests/agent/transports/test_plugin_transport_api_mode.py
@@ -1,169 +1,110 @@
-"""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).
+"""A provider plugin's own ``api_mode`` reaches the runtime transport (#53054).
+
+``register_transport(api_mode, cls)`` is the public seam for a plugin that speaks its own wire
+dialect, and ``ProviderProfile.api_mode`` names it. Every gate between the profile and the agent
+(``providers.determine_api_mode`` → ``runtime_provider`` → ``agent_init._resolve_api_mode`` →
+the delegation resolver) validated the mode against a closed literal set, so the plugin's mode was
+rewritten to ``chat_completions`` and its transport never selected — no error, prose-only turns.
+
+Both tests drive a REAL plugin discovered from an isolated HERMES_HOME rather than the gates in
+isolation, so they fail if any single gate regresses.
"""
from __future__ import annotations
+import sys
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
+_PLUGIN_SOURCE = '''\
+from agent.transports import register_transport
+from agent.transports.chat_completions import ChatCompletionsTransport
+from providers import register_provider
+from providers.base import ProviderProfile
- assert _parse_api_mode("openai") == "chat_completions"
+class DialectTransport(ChatCompletionsTransport):
+ api_mode = "__MODE__"
-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.
- """
+if "__REGISTER__" == "yes":
+ register_transport("__MODE__", DialectTransport)
+register_provider(ProviderProfile(name="__NAME__", auth_type="api_key", env_vars=("__ENV__",),
+ base_url="https://relay.example.test/v1", api_mode="__MODE__", fallback_models=("example-model",)))
+'''
- 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
+def install_dialect_plugin(tmp_path, monkeypatch):
+ """Write a model-provider plugin (optionally registering its transport) under a temp HERMES_HOME."""
+ installed: list[tuple[str, str]] = []
+
+ def _install(name: str, mode: str, *, register: bool) -> None:
+ env = f"{name.upper().replace('-', '_')}_API_KEY"
+ plugin_dir = tmp_path / "hermes" / "plugins" / "model-providers" / name
+ plugin_dir.mkdir(parents=True, exist_ok=True)
+ (plugin_dir / "plugin.yaml").write_text(
+ f"name: {name}\nkind: model-provider\nversion: 0.0.1\ndescription: dialect fixture\n", encoding="utf-8")
+ source = (_PLUGIN_SOURCE.replace("__ENV__", env).replace("__NAME__", name).replace("__MODE__", mode)
+ .replace("__REGISTER__", "yes" if register else "no"))
+ (plugin_dir / "__init__.py").write_text(source, encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
+ monkeypatch.setenv(env, "sk-fixture")
+ import providers as _pkg
+ _pkg._discovered = False
+ for mod in [m for m in sys.modules if m.startswith("_hermes_user_provider")]:
+ del sys.modules[mod]
+ installed.append((name, mode))
+
+ yield _install
+
+ import providers as _pkg
+ from agent.transports import _REGISTRY
+ for name, mode in installed:
+ _pkg._REGISTRY.pop(name, None)
+ _REGISTRY.pop(mode, None)
+ for alias, canonical in list(_pkg._ALIASES.items()):
+ if canonical == name:
+ _pkg._ALIASES.pop(alias, None)
+ _pkg._PROVIDER_LIST_CACHE = None
+
+
+def _agent_ladder_mode(provider: str, base_url: str, api_mode: str) -> str:
+ from agent.agent_init import _resolve_api_mode
+ agent = SimpleNamespace(provider=provider, model="example-model", _base_url_hostname="relay.example.test",
+ _base_url_lower=base_url.lower(), api_mode=None)
+ _resolve_api_mode(agent, api_mode, provider, base_url)
+ return agent.api_mode
+
+
+def test_registered_plugin_dialect_reaches_every_gate(install_dialect_plugin):
+ """profile.api_mode → determine_api_mode → resolve_runtime_provider → agent ladder → delegation."""
+ from hermes_cli.providers import determine_api_mode
+ from hermes_cli.runtime_provider import _parse_api_mode, resolve_runtime_provider
+ from tools.delegate_tool_config import _direct_endpoint_credentials
+
+ install_dialect_plugin("example-dialect", "example_dialect", register=True)
+
+ assert determine_api_mode("example-dialect", "https://relay.example.test/v1") == "example_dialect"
+ runtime = resolve_runtime_provider(requested="example-dialect", target_model="example-model")
+ assert runtime["api_mode"] == "example_dialect"
+ assert _parse_api_mode("example_dialect") == "example_dialect"
+ assert _agent_ladder_mode(runtime["provider"], runtime["base_url"], runtime["api_mode"]) == "example_dialect"
+ creds = _direct_endpoint_credentials(
+ {"base_url": "https://relay.example.test/v1", "api_mode": "example_dialect", "provider": "", "model": "m",
+ "api_key": None}, None)
+ assert creds["api_mode"] == "example_dialect"
+
+
+def test_unregistered_profile_mode_still_degrades_to_chat_completions(install_dialect_plugin):
+ """The sets stay closed: a profile naming a transport nobody registered is not admitted."""
+ from hermes_cli.providers import determine_api_mode
+ from hermes_cli.runtime_provider import _parse_api_mode, resolve_runtime_provider
+
+ install_dialect_plugin("example-bogus", "bogus_mode", register=False)
+
+ assert determine_api_mode("example-bogus", "https://relay.example.test/v1") == "chat_completions"
+ assert resolve_runtime_provider(requested="example-bogus", target_model="example-model")["api_mode"] == "chat_completions"
+ assert _parse_api_mode("bogus_mode") is None
+ assert _agent_ladder_mode("example-bogus", "https://relay.example.test/v1", "bogus_mode") == "chat_completions"
diff --git a/tools/delegate_tool_config.py b/tools/delegate_tool_config.py
index a3a3c1cbe79..2b1390fa531 100644
--- a/tools/delegate_tool_config.py
+++ b/tools/delegate_tool_config.py
@@ -333,12 +333,10 @@ 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. 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"]):
+ # Explicit delegation.api_mode always wins over the URL heuristic; a provider plugin's
+ # registered dialect counts as explicit.
+ from agent.transports import registered_api_modes
+ if v["api_mode"] in _EXPLICIT_API_MODES or (v["api_mode"] and v["api_mode"] in registered_api_modes()):
api_mode = v["api_mode"]
# Preserve the configured provider's request personality on an explicit endpoint.