Skip to content

The agent that grows with you

fix(auxiliary): origin-scoped key shield, task overrides over named providers, negotiation-only stream fallback

Tekniumedac5f63787d
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index 422803425b2..121fe0f352e 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -114,7 +114,7 @@ from agent.model_metadata import (
from hermes_cli.config import get_hermes_home
from agent.auxiliary_health import _custom_health_base_url, _unhealthy_cache_key
from hermes_constants import OPENROUTER_BASE_URL
-from utils import base_url_host_matches, base_url_hostname, env_float, is_truthy_value, model_forces_max_completion_tokens, normalize_proxy_env_vars
+from utils import base_url_host_matches, base_url_hostname, base_url_origin, env_float, is_truthy_value, model_forces_max_completion_tokens, normalize_proxy_env_vars
logger = logging.getLogger(__name__)
@@ -3300,11 +3300,17 @@ def _recoverable_pool_provider(
base = str(getattr(client, "base_url", "") or "")
runtime = _normalize_main_runtime(main_runtime)
rt_base = str(runtime.get("base_url") or "")
+ rt_key = runtime.get("api_key")
+ client_key = getattr(client, "api_key", None)
+ # Only the SESSION's own key is shielded, and only when it was sent somewhere other than the
+ # session's origin (scheme+host+port — a port or HTTPS→HTTP change is a different trust boundary).
+ # An independently owned auxiliary pool keeps rotating at its own origin.
if (base and rt_base and normalized == runtime.get("provider")
- and not base_url_host_matches(base, base_url_hostname(rt_base))):
- logger.info("Auxiliary: %s rejected at %s, but the session's %s endpoint is %s — "
+ and isinstance(rt_key, str) and rt_key and client_key == rt_key
+ and base_url_origin(base) != base_url_origin(rt_base)):
+ logger.info("Auxiliary: %s rejected the session key at %s, but the session's endpoint is %s — "
"endpoint mismatch, not a dead key; skipping credential rotation",
- normalized, base_url_hostname(base), normalized, base_url_hostname(rt_base))
+ normalized, base_url_hostname(base), base_url_hostname(rt_base))
return None
if normalized not in {"", "auto", "custom"}:
return normalized
@@ -4642,8 +4648,11 @@ def _resolve_named_custom_branch(req: _ResolveRequest) -> Optional[_ResolveResul
custom_entry = _get_named_custom_provider(provider)
if not custom_entry:
return None
- custom_base = (custom_entry.get("base_url") or "").strip()
- custom_key = _named_custom_api_key(custom_entry, provider, custom_base)
+ # A per-task/explicit base_url or api_key composes OVER the named entry's defaults: the entry supplies
+ # whatever the caller left blank, never replaces what the caller set (compression prompts carry
+ # conversation history, so a silently swapped destination is a data-routing bug, not a nuisance).
+ custom_base = (req.explicit_base_url or custom_entry.get("base_url") or "").strip()
+ custom_key = (req.explicit_api_key or "").strip() or _named_custom_api_key(custom_entry, provider, custom_base)
if custom_key == "no-key-required":
logger.warning("resolve_provider_client: named custom provider %r has no resolvable "
"api_key — request will be sent with placeholder no-key-required "
@@ -6543,9 +6552,13 @@ async def _acreate_with_progress(
if not _async_client_streams_internally(client):
_notify_aux_provider_response()
return response
+ stream_kwargs, model, total_ceiling = _stream_request_plan(kwargs)
try:
- return await _acreate_with_stream(client, kwargs, task)
+ chunks = await client.chat.completions.create(**stream_kwargs)
except Exception as exc:
+ # Only a rejected stream NEGOTIATION falls back to a plain call (mirrors the sync wrapper); a
+ # failure mid-consumption below reaches the classified recovery ladder instead of silently
+ # re-sending the whole prompt non-streaming.
if (force_stream or _is_transient_transport_error(exc) or _is_auth_error(exc)
or _is_payment_error(exc) or _is_rate_limit_error(exc)):
raise
@@ -6555,6 +6568,10 @@ async def _acreate_with_progress(
response = await client.chat.completions.create(**kwargs)
_notify_aux_provider_response()
return response
+ if hasattr(chunks, "choices"): # shims may hand back a complete response despite stream=True
+ _notify_aux_provider_response()
+ return chunks
+ return await _aggregate_chat_stream_async(chunks, model=model, total_ceiling=total_ceiling)
# Shared request head + recovery ladder for call_llm / async_call_llm: the entry points differ
diff --git a/tests/agent/test_aux_relay_progress_seam.py b/tests/agent/test_aux_relay_progress_seam.py
index 9e14151600d..90a7fe268b3 100644
--- a/tests/agent/test_aux_relay_progress_seam.py
+++ b/tests/agent/test_aux_relay_progress_seam.py
@@ -62,3 +62,27 @@ def test_relay_default_callback_is_plain_create_without_hook():
resp = aux._relay_sync_completion(client, {"model": "m", "messages": []})
assert client.wire == [None]
assert resp.choices[0].message.content == "plain"
+
+
+def test_async_midstream_failure_is_not_retried_non_streaming():
+ """Plain-create fallback covers stream NEGOTIATION rejections only; a failure after content has
+ streamed must surface to the classified recovery ladder, not silently re-send the prompt."""
+ class _Client(_AsyncClient):
+ async def _create(self, **kwargs):
+ self.wire.append(kwargs.get("stream"))
+ if kwargs.get("stream"):
+ async def agen():
+ yield _chunk("partial")
+ raise ValueError("bad frame")
+ return agen()
+ return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content="plain"))])
+
+ client = _Client()
+ with aux.aux_progress_hook(lambda: None):
+ try:
+ asyncio.run(aux._acreate_with_progress(client, {"model": "m", "messages": []}))
+ except ValueError:
+ pass
+ else:
+ raise AssertionError("midstream failure must propagate")
+ assert client.wire == [True]
diff --git a/tests/agent/test_aux_session_endpoint_affinity.py b/tests/agent/test_aux_session_endpoint_affinity.py
index 92dbeaf6633..7834203f296 100644
--- a/tests/agent/test_aux_session_endpoint_affinity.py
+++ b/tests/agent/test_aux_session_endpoint_affinity.py
@@ -5,8 +5,13 @@ hop to api.openai.com, 401 with the proxy-issued key, and then have that key qua
"""
from types import SimpleNamespace
+import pytest
+
from agent import auxiliary_client as aux
+SESSION = {"provider": "openai-api", "model": "gpt-5.4",
+ "base_url": "https://proxy.example:8443/v1", "api_key": "sk-session"}
+
def test_openai_alias_prefers_configured_endpoint_over_public_default(monkeypatch):
monkeypatch.setenv("OPENAI_BASE_URL", "https://llm-proxy.corp.example/v1")
@@ -17,10 +22,39 @@ def test_openai_alias_prefers_configured_endpoint_over_public_default(monkeypatc
assert aux._expand_direct_api_alias("openai", None) == ("custom", "https://api.openai.com/v1")
-def test_rejection_at_foreign_host_does_not_name_the_session_pool():
- runtime = {"provider": "openai-api", "model": "gpt-5.4",
- "base_url": "https://llm-proxy.corp.example/v1", "api_key": "sk-proxy"}
- foreign = SimpleNamespace(base_url="https://api.openai.com/v1/", api_key="sk-proxy")
- same = SimpleNamespace(base_url="https://llm-proxy.corp.example/v1/", api_key="sk-proxy")
- assert aux._recoverable_pool_provider("openai-api", foreign, main_runtime=runtime) is None
- assert aux._recoverable_pool_provider("openai-api", same, main_runtime=runtime) == "openai-api"
[email protected]("rejecting_base", [
+ "https://api.openai.com/v1/", # different host
+ "https://proxy.example:9443/v1/", # same host, different port
+ "http://proxy.example:8443/v1/", # same host+port, scheme downgrade
+])
+def test_session_key_rejected_at_foreign_origin_is_not_rotated(rejecting_base):
+ client = SimpleNamespace(base_url=rejecting_base, api_key="sk-session")
+ assert aux._recoverable_pool_provider("openai-api", client, main_runtime=SESSION) is None
+
+
+def test_rotation_survives_at_session_origin_and_for_independent_aux_pool():
+ same_origin = SimpleNamespace(base_url="https://proxy.example:8443/v1/", api_key="sk-session")
+ assert aux._recoverable_pool_provider("openai-api", same_origin, main_runtime=SESSION) == "openai-api"
+ # A separately owned aux credential at its own configured endpoint must keep rotating.
+ independent = SimpleNamespace(base_url="https://api.openai.com/v1/", api_key="sk-aux-pool-1")
+ assert aux._recoverable_pool_provider("openai-api", independent, main_runtime=SESSION) == "openai-api"
+
+
+def test_named_provider_defaults_compose_under_task_overrides(monkeypatch, tmp_path):
+ """URL-only / key-only task overrides win field-by-field; the named entry fills only the blanks."""
+ monkeypatch.setenv("NAMED_KEY", "named-key")
+ (tmp_path / "config.yaml").write_text(
+ "model:\n provider: openai\n default: gpt-5.4\n"
+ "providers:\n openai:\n api: https://named.example/v1\n key_env: NAMED_KEY\n")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ def route(**overrides):
+ aux._client_cache.clear()
+ client, _ = aux.resolve_provider_client("openai", "gpt-5.4-mini", **overrides)
+ assert client is not None
+ return str(client.base_url).rstrip("/"), str(client.api_key)
+
+ assert route() == ("https://named.example/v1", "named-key")
+ assert route(explicit_base_url="https://aux-explicit.example/v1") == ("https://aux-explicit.example/v1", "named-key")
+ assert route(explicit_api_key="task-key") == ("https://named.example/v1", "task-key")
+ assert route(explicit_base_url="https://aux-explicit.example/v1", explicit_api_key="task-key") == (
+ "https://aux-explicit.example/v1", "task-key")