The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(providers): let a provider profile supply its own client
Alexander Prendota1131b2285619
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex f9be7a0476f..3017f00a10e 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -2709,6 +2709,71 @@ def anthropic_prompt_cache_policy(+def _provider_supplied_client(agent, client_kwargs: dict) -> Any | None:+ """Ask the registered ProviderProfile for a custom client, if any.++ Resolves by provider name first, then by the ``base_url`` scheme prefix so a+ runtime configured only by URL (``acp://…``) still reaches its profile.+ A profile that raises is logged and skipped: a third-party plugin must not+ be able to take the turn down, it can only fail to provide a client.+ """+ try:+ from providers import get_provider_profile+ except Exception:+ return None++ profile = None+ provider_name = (getattr(agent, "provider", "") or "").strip()+ if provider_name:+ try:+ profile = get_provider_profile(provider_name)+ except Exception:+ profile = None+ if profile is None:+ base_url = str(client_kwargs.get("base_url", "") or "").strip()+ if base_url:+ profile = _profile_for_base_url(base_url)+ if profile is None:+ return None++ try:+ return profile.create_client(**client_kwargs)+ except Exception:+ _ra().logger.warning(+ "Provider profile %r failed to create a client; falling back to the "+ "standard client path",+ getattr(profile, "name", provider_name) or "?",+ exc_info=True,+ )+ return None+++def _profile_for_base_url(base_url: str) -> Any | None:+ """Find a registered profile whose own base_url matches ``base_url``.++ Only used when the provider name did not resolve. Matches on exact base_url+ so a non-HTTP scheme (``acp://copilot``) routes to its profile even when the+ caller passed no provider name.+ """+ try:+ from providers import list_providers+ except Exception:+ return None+ target = base_url.rstrip("/").lower()+ try:+ candidates = list_providers()+ except Exception:+ return None+ for candidate in candidates or []:+ own = str(getattr(candidate, "base_url", "") or "").rstrip("/").lower()+ # Prefix match, not equality: the replaced copilot-acp branch keyed on+ # ``startswith("acp://copilot")``, so a base_url carrying a path or a+ # user override under the same root must still resolve.+ if own and (target == own or target.startswith(own + "/")):+ return candidate+ return None++def create_openai_client(agent, client_kwargs: dict, *, reason: str, shared: bool) -> Any:from agent.auxiliary_client import _validate_base_url, _validate_proxy_env_urlsfrom agent.ssl_verify import resolve_httpx_verify@@ -2737,17 +2802,24 @@ def create_openai_client(agent, client_kwargs: dict, *, reason: str, shared: boohttpx_verify = resolve_httpx_verify(ca_bundle=ssl_ca_cert, ssl_verify=ssl_verify_cfg)_validate_proxy_env_urls()_validate_base_url(client_kwargs.get("base_url"))- if agent.provider == "copilot-acp" or str(client_kwargs.get("base_url", "")).startswith("acp://copilot"):- from agent.copilot_acp_client import CopilotACPClient-- client = CopilotACPClient(**client_kwargs)+ # ── Provider-supplied client (registration seam) ──────────────────────+ # A provider whose wire protocol is not OpenAI-over-HTTP supplies its own+ # client from its ProviderProfile.create_client(). Consulted before the+ # built-in ladder so a profile registered from ~/.hermes/plugins/ or a pip+ # entry point can ship a transport without editing this function — that is+ # what makes an out-of-tree ACP provider possible at all. Returning None+ # (the default) falls through to the paths below, so every existing+ # provider is unaffected.+ provider_client = _provider_supplied_client(agent, client_kwargs)+ if provider_client is not None:_ra().logger.info(- "Copilot ACP client created (%s, shared=%s) %s",+ "%s client created from provider profile (%s, shared=%s) %s",+ agent.provider,reason,shared,agent._client_log_context(),)- return client+ return provider_clientif agent.provider == "gemini":from agent.gemini_native_adapter import GeminiNativeClient, is_native_gemini_base_urldiff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 47c682fde65..fe8292ea047 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -749,6 +749,23 @@ def _run_protected_sync_provider_call(return outcome.get("result")+def _client_declares(client_obj: Any, flag: str) -> bool:+ """Whether ``client_obj`` (or its class) sets ``flag`` truthy.++ Capability declaration instead of isinstance: a client shipped by an+ out-of-tree provider profile can opt out of the transport/async wrappers+ without this module importing it. Mirrors ``SUPPORTS_HERMES_TOOL_CALLS`` in+ ``agent/background_review.py``. Absent attribute → False, so every ordinary+ client keeps its existing behaviour.+ """+ if client_obj is None:+ return False+ try:+ return bool(getattr(client_obj, flag, False))+ except Exception:+ return False++def _safe_isinstance(obj: Any, maybe_type: Any) -> bool:"""Return False instead of raising when a patched symbol is not a type."""try:@@ -2833,7 +2850,9 @@ def _maybe_wrap_anthropic(Returns ``client_obj`` unchanged when:- - It's already an Anthropic/Codex/Gemini/CopilotACP wrapper.+ - It's already a complete client — an Anthropic/Codex wrapper, or any+ client declaring ``HERMES_SKIP_TRANSPORT_WRAP`` (the native and ACP+ shims, in-tree or from a provider plugin).- The endpoint is an OpenAI-wire endpoint.- ``api_mode`` is explicitly set to a non-Anthropic transport.- The ``anthropic`` SDK is not installed (falls back to OpenAI wire).@@ -2851,18 +2870,12 @@ def _maybe_wrap_anthropic(# Other specialized adapters we should never re-dispatch.if _safe_isinstance(client_obj, CodexAuxiliaryClient):return client_obj- try:- from agent.gemini_native_adapter import GeminiNativeClient- if _safe_isinstance(client_obj, GeminiNativeClient):- return client_obj- except ImportError:- pass- try:- from agent.copilot_acp_client import CopilotACPClient- if _safe_isinstance(client_obj, CopilotACPClient):- return client_obj- except ImportError:- pass+ # A client that declares itself complete is never re-dispatched through a+ # wire adapter. Declared as a class attribute rather than isinstance-checked+ # so an out-of-tree provider's client is covered too — and so this hot path+ # no longer imports the native/ACP client modules just to type-test.+ if _client_declares(client_obj, "HERMES_SKIP_TRANSPORT_WRAP"):+ return client_obj# Explicit non-anthropic api_mode wins over URL heuristics.if api_mode and api_mode != "anthropic_messages":@@ -6660,12 +6673,10 @@ def _to_async_client(sync_client, model: str, is_vision: bool = False):return AsyncGeminiNativeClient(sync_client), modelexcept ImportError:pass- try:- from agent.copilot_acp_client import CopilotACPClient- if isinstance(sync_client, CopilotACPClient):- return sync_client, model- except ImportError:- pass+ # Clients that are already usable from async code (the ACP shims drive a+ # subprocess, not an HTTP connection pool) opt out of the async wrapper.+ if _client_declares(sync_client, "HERMES_SKIP_ASYNC_WRAP"):+ return sync_client, modelasync_kwargs = {"api_key": sync_client.api_key,@@ -7479,34 +7490,55 @@ def resolve_provider_client(or _read_main_model_for_aux(),provider,)- if provider == "copilot-acp":+ # Any external-process provider whose registered profile supplies a+ # client is served here — keyed on the profile, not on a provider name,+ # so an out-of-tree ACP provider reaches the auxiliary path (compression,+ # vision, background review) exactly like the in-tree one.+ _extproc_profile = None+ try:+ from providers import get_provider_profile as _get_provider_profile++ _extproc_profile = _get_provider_profile(provider)+ except Exception:+ _extproc_profile = None+ if _extproc_profile is not None:api_key = str(creds.get("api_key", "")).strip()base_url = str(creds.get("base_url", "")).strip()command = str(creds.get("command", "")).strip() or Noneargs = list(creds.get("args") or [])if not final_model:logger.warning(- "resolve_provider_client: copilot-acp requested but no model "- "was provided or configured"+ "resolve_provider_client: %s requested but no model "+ "was provided or configured",+ provider,)return None, Noneif not api_key or not base_url:logger.warning(- "resolve_provider_client: copilot-acp requested but external "- "process credentials are incomplete"+ "resolve_provider_client: %s requested but external "+ "process credentials are incomplete",+ provider,)return None, None- from agent.copilot_acp_client import CopilotACPClient-- client = CopilotACPClient(- api_key=api_key,- base_url=base_url,- command=command,- args=args,- )- logger.debug("resolve_provider_client: %s (%s)", provider, final_model)- return (_to_async_client(client, final_model, is_vision=is_vision) if async_mode- else (client, final_model))+ try:+ client = _extproc_profile.create_client(+ api_key=api_key,+ base_url=base_url,+ command=command,+ args=args,+ )+ except Exception:+ logger.warning(+ "resolve_provider_client: profile %r failed to create an "+ "external-process client",+ provider,+ exc_info=True,+ )+ client = None+ if client is not None:+ logger.debug("resolve_provider_client: %s (%s)", provider, final_model)+ return (_to_async_client(client, final_model, is_vision=is_vision) if async_mode+ else (client, final_model))if provider not in _LOGGED_UNSUPPORTED_EXTPROC_KEYS:_LOGGED_UNSUPPORTED_EXTPROC_KEYS.add(provider)logger.debug("resolve_provider_client: external-process provider %s not "diff --git a/agent/copilot_acp_client.py b/agent/copilot_acp_client.pyindex a45bc46e1d3..53eb3a4c634 100644--- a/agent/copilot_acp_client.py+++ b/agent/copilot_acp_client.py@@ -358,6 +358,12 @@ class _ACPChatNamespace:class CopilotACPClient:"""Minimal OpenAI-client-compatible facade for Copilot ACP."""+ # Declared for agent/auxiliary_client.py: this shim drives an ACP subprocess+ # over stdio, so it is already a complete client (never re-dispatch it+ # through a wire adapter) and is safe to use from async code as-is.+ HERMES_SKIP_TRANSPORT_WRAP = True+ HERMES_SKIP_ASYNC_WRAP = True+def __init__(self,*,diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.pyindex 94558f87c81..821ae6b6ce3 100644--- a/agent/gemini_native_adapter.py+++ b/agent/gemini_native_adapter.py@@ -1102,6 +1102,11 @@ class _AsyncGeminiChatNamespace:class GeminiNativeClient:"""Minimal OpenAI-SDK-compatible facade over Gemini's native REST API."""+ # Declared for agent/auxiliary_client.py: already a complete client, so it+ # is never re-dispatched through a wire adapter. (No HERMES_SKIP_ASYNC_WRAP+ # — the async path has a real conversion, AsyncGeminiNativeClient.)+ HERMES_SKIP_TRANSPORT_WRAP = True+def __init__(self,*,diff --git a/plugins/model-providers/copilot-acp/__init__.py b/plugins/model-providers/copilot-acp/__init__.pyindex 6e452706c3d..95ba9700e6b 100644--- a/plugins/model-providers/copilot-acp/__init__.py+++ b/plugins/model-providers/copilot-acp/__init__.py@@ -1,10 +1,16 @@"""GitHub Copilot ACP provider profile.-copilot-acp uses an external ACP subprocess — NOT the standard-transport. api_mode="copilot_acp" is handled separately in run_agent.py.-The profile captures auth + endpoint metadata for registry migration.+copilot-acp does not speak OpenAI-over-HTTP: it drives an external ACP+subprocess over stdio. The profile therefore supplies its own client through+:meth:`ProviderProfile.create_client` instead of letting the core build an+``openai.OpenAI``. That hook is the registration seam — this profile is its+in-tree consumer, and an out-of-tree ACP provider registered from+``~/.hermes/plugins/model-providers/`` or a pip entry point uses the exact same+three lines without touching core."""+from typing import Any+from providers import register_providerfrom providers.base import ProviderProfile@@ -12,6 +18,12 @@ from providers.base import ProviderProfileclass CopilotACPProfile(ProviderProfile):"""GitHub Copilot ACP — external process, no REST models endpoint."""+ def create_client(self, **client_kwargs: Any) -> Any:+ """Build the ACP stdio shim rather than an HTTP client."""+ from agent.copilot_acp_client import CopilotACPClient++ return CopilotACPClient(**client_kwargs)+def fetch_models(self,*,diff --git a/providers/base.py b/providers/base.pyindex 5d14868eb13..7ddd01f8afd 100644--- a/providers/base.py+++ b/providers/base.py@@ -223,6 +223,31 @@ class ProviderProfile:"""return None+ def create_client(self, **client_kwargs: Any) -> Any | None:+ """Return a provider-specific client, or ``None`` for the standard one.++ Most providers speak OpenAI-compatible HTTP and want the shared+ ``openai.OpenAI`` client the core builds — they inherit this and return+ ``None``. A provider whose wire protocol is not HTTP at all (the ACP+ subprocess shims) or which needs a native SDK overrides this and+ returns its own client object.++ ``client_kwargs`` is the same mapping the core would have passed to+ ``openai.OpenAI`` (``api_key``, ``base_url``, ``command``, ``args``,+ timeouts, headers…). Unknown keys must be tolerated: the core adds to+ this mapping over time, so an override should accept ``**kwargs`` and+ pick what it needs rather than enumerate.++ Returning ``None`` (the default) is always safe — the caller falls+ through to its existing construction path.++ This is the hook that lets a provider ship *outside* this tree: with it,+ a profile registered from ``~/.hermes/plugins/model-providers/`` or a+ pip entry point can supply its own transport without any core edit. See+ ``plugins/model-providers/copilot-acp/`` for the in-tree example.+ """+ return None+def fetch_models(self,*,diff --git a/tests/agent/test_provider_client_seam.py b/tests/agent/test_provider_client_seam.pynew file mode 100644index 00000000000..752093448c6--- /dev/null+++ b/tests/agent/test_provider_client_seam.py@@ -0,0 +1,255 @@+"""A provider profile can supply its own client — the registration seam.++Most providers speak OpenAI-over-HTTP and want the client the core builds. A+provider whose wire protocol is something else (the ACP subprocess shims) must+be able to supply its own — and must be able to do so from *outside* this tree,+otherwise every such integration has to edit ``create_openai_client`` by hand.++These tests pin the hook, the two resolution paths into it (provider name and+``base_url``), its failure isolation, and the capability flags that let such a+client opt out of the transport/async wrappers without this code importing it.+"""++from __future__ import annotations++import os+import sys+from types import SimpleNamespace++import pytest++_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+if _REPO_ROOT not in sys.path:+ sys.path.insert(0, _REPO_ROOT)++import providers as _providers # noqa: E402+from providers.base import ProviderProfile # noqa: E402+++class _FakeClient:+ def __init__(self, **kwargs):+ self.kwargs = kwargs+++class _SeamProfile(ProviderProfile):+ def create_client(self, **kwargs):+ return _FakeClient(**kwargs)+++class _ExplodingProfile(ProviderProfile):+ def create_client(self, **kwargs):+ raise RuntimeError("plugin is broken")+++def registered():+ """Register profiles for one test and restore the registry afterwards."""+ _providers._discover_providers()+ snapshot = (+ dict(_providers._REGISTRY),+ dict(_providers._ALIASES),+ _providers._PROVIDER_LIST_CACHE,+ )++ def _register(profile):+ _providers.register_provider(profile)+ return profile++ yield _register++ _providers._REGISTRY.clear()+ _providers._REGISTRY.update(snapshot[0])+ _providers._ALIASES.clear()+ _providers._ALIASES.update(snapshot[1])+ _providers._PROVIDER_LIST_CACHE = snapshot[2]+++def _agent(provider: str = ""):+ """The minimal agent surface create_openai_client touches."""+ return SimpleNamespace(+ provider=provider,+ _client_log_context=lambda: "",+ _build_keepalive_http_client=lambda *a, **k: None,+ )+++# ── the hook itself ──────────────────────────────────────────────────────────+++def test_the_default_profile_supplies_no_client():+ """Every ordinary provider inherits this and keeps the standard client."""+ assert ProviderProfile(name="plain").create_client(api_key="k") is None+++def test_a_profile_can_supply_its_own_client(registered):+ from agent.agent_runtime_helpers import _provider_supplied_client++ registered(_SeamProfile(name="seam-test", base_url="acp://seam-test"))+ client = _provider_supplied_client(_agent("seam-test"), {"api_key": "k"})+ assert isinstance(client, _FakeClient)+ assert client.kwargs == {"api_key": "k"}+++def test_an_alias_reaches_the_same_profile(registered):+ from agent.agent_runtime_helpers import _provider_supplied_client++ registered(_SeamProfile(name="seam-test", aliases=("seam",), base_url="acp://seam-test"))+ assert isinstance(_provider_supplied_client(_agent("seam"), {}), _FakeClient)+++def test_the_base_url_resolves_the_profile_when_the_name_does_not(registered):+ """A runtime configured only by URL still reaches its provider's client."""+ from agent.agent_runtime_helpers import _provider_supplied_client++ registered(_SeamProfile(name="seam-test", base_url="acp://seam-test"))+ client = _provider_supplied_client(_agent(""), {"base_url": "acp://seam-test"})+ assert isinstance(client, _FakeClient)+ # Prefix, not equality — the branch this replaced keyed on startswith().+ assert isinstance(+ _provider_supplied_client(_agent(""), {"base_url": "acp://seam-test/x"}),+ _FakeClient,+ )+ # A different scheme must not be captured.+ assert _provider_supplied_client(_agent(""), {"base_url": "https://api.example/v1"}) is None+++def test_an_unregistered_provider_gets_no_client(registered):+ from agent.agent_runtime_helpers import _provider_supplied_client++ assert _provider_supplied_client(_agent("nothing-registered-here"), {}) is None+++def test_a_broken_plugin_cannot_take_the_turn_down(registered):+ """A third-party profile that raises falls through to the standard path."""+ from agent.agent_runtime_helpers import _provider_supplied_client++ registered(_ExplodingProfile(name="seam-boom", base_url="acp://seam-boom"))+ assert _provider_supplied_client(_agent("seam-boom"), {"api_key": "k"}) is None+++# ── the in-tree consumer ─────────────────────────────────────────────────────+++def test_copilot_acp_still_gets_its_acp_client():+ """copilot-acp lost its hardcoded branch in create_openai_client; it must+ still be constructed, now via its profile."""+ from agent.copilot_acp_client import CopilotACPClient+ from providers import get_provider_profile++ profile = get_provider_profile("copilot-acp")+ assert profile is not None+ client = profile.create_client(api_key="copilot-acp", base_url="acp://copilot")+ assert isinstance(client, CopilotACPClient)+++def test_copilot_acp_reaches_the_seam_by_name_and_by_url():+ from agent.agent_runtime_helpers import _provider_supplied_client+ from agent.copilot_acp_client import CopilotACPClient++ by_name = _provider_supplied_client(+ _agent("copilot-acp"), {"api_key": "copilot-acp", "base_url": "acp://copilot"}+ )+ assert isinstance(by_name, CopilotACPClient)+ by_url = _provider_supplied_client(+ _agent(""), {"api_key": "copilot-acp", "base_url": "acp://copilot"}+ )+ assert isinstance(by_url, CopilotACPClient)+++# ── the wiring, not just the helper ──────────────────────────────────────────+++def test_create_openai_client_actually_consults_the_profile(registered):+ """Exercise the real construction entry point, not the helper it calls.++ The helper being correct is worth nothing if ``create_openai_client`` stops+ calling it — that is the regression this file exists to prevent.+ """+ from agent.agent_runtime_helpers import create_openai_client++ registered(_SeamProfile(name="seam-test", base_url="acp://seam-test"))+ client = create_openai_client(+ _agent("seam-test"),+ {"api_key": "k", "base_url": "acp://seam-test"},+ reason="test",+ shared=False,+ )+ assert isinstance(client, _FakeClient)+++def test_create_openai_client_still_builds_the_standard_client(registered):+ """A provider with no profile hook is untouched by the seam."""+ from openai import OpenAI++ from agent.agent_runtime_helpers import create_openai_client++ client = create_openai_client(+ _agent("openai-api"),+ {"api_key": "k", "base_url": "https://api.example/v1"},+ reason="test",+ shared=False,+ )+ assert isinstance(client, OpenAI)+++def test_create_openai_client_builds_the_copilot_acp_client():+ """The in-tree consumer, through the same entry point its hardcoded branch+ used to serve."""+ from agent.agent_runtime_helpers import create_openai_client+ from agent.copilot_acp_client import CopilotACPClient++ client = create_openai_client(+ _agent("copilot-acp"),+ {"api_key": "copilot-acp", "base_url": "acp://copilot"},+ reason="test",+ shared=False,+ )+ assert isinstance(client, CopilotACPClient)+++# ── capability flags replacing the isinstance checks ─────────────────────────+++def test_clients_declaring_skip_flags_are_not_wrapped():+ from agent.auxiliary_client import _client_declares++ class _Final:+ HERMES_SKIP_TRANSPORT_WRAP = True+ HERMES_SKIP_ASYNC_WRAP = True++ class _Plain:+ pass++ final = _Final()+ assert _client_declares(final, "HERMES_SKIP_TRANSPORT_WRAP")+ assert _client_declares(final, "HERMES_SKIP_ASYNC_WRAP")+ # Absent attribute → False, so every ordinary client keeps its behaviour.+ assert not _client_declares(_Plain(), "HERMES_SKIP_TRANSPORT_WRAP")+ assert not _client_declares(None, "HERMES_SKIP_TRANSPORT_WRAP")+++def test_the_in_tree_clients_declare_what_their_isinstance_checks_used_to_say():+ """copilot-acp skipped both wrappers; the Gemini native client skipped only+ the transport one (its async path is a real conversion)."""+ from agent.copilot_acp_client import CopilotACPClient+ from agent.gemini_native_adapter import GeminiNativeClient++ assert CopilotACPClient.HERMES_SKIP_TRANSPORT_WRAP is True+ assert CopilotACPClient.HERMES_SKIP_ASYNC_WRAP is True+ assert GeminiNativeClient.HERMES_SKIP_TRANSPORT_WRAP is True+ assert getattr(GeminiNativeClient, "HERMES_SKIP_ASYNC_WRAP", False) is False+++def test_an_out_of_tree_client_is_covered_by_the_same_flags():+ """The point of the flags: auxiliary_client never imports this class."""+ from agent.auxiliary_client import _maybe_wrap_anthropic, _to_async_client++ class _ThirdPartyClient:+ HERMES_SKIP_TRANSPORT_WRAP = True+ HERMES_SKIP_ASYNC_WRAP = True+ api_key = "k"+ base_url = "acp://third-party"++ client = _ThirdPartyClient()+ assert _maybe_wrap_anthropic(client, "m", "k", "acp://third-party") is client+ assert _to_async_client(client, "m")[0] is client