Skip to content

The agent that grows with you

fix(providers): keep a built-in's key off a custom entry that shares its name

unsupportedpastelsed6414fd6d92
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 15cd862855c..d80b3403eb7 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -27,7 +27,7 @@ from agent.think_scrubber import THINK_TAG_NAMES
from agent.trajectory import convert_scratchpad_to_think
from agent.credential_pool import (
STATUS_EXHAUSTED, _parse_absolute_timestamp, credential_pool_entry_serves_endpoint,
- credential_pool_matches_provider, resolve_runtime_pool_key,
+ credential_pool_matches_provider,
)
from agent.error_classifier import FailoverReason
from agent.retry_utils import parse_retry_after_seconds, reset_delay_from_message
@@ -1451,10 +1451,9 @@ def restore_primary_runtime(agent) -> bool:
return credential_pool_matches_provider(candidate, primary_provider, base_url=primary_runtime_base_url)
def _load_primary_pool():
- """Load the primary provider's pool; None when absent or provider-mismatched."""
- from agent.credential_pool import load_pool
- key = resolve_runtime_pool_key(primary_provider, primary_runtime_base_url)
- loaded = load_pool(key) if key else None
+ """The primary's pool (entry-scoped for a custom entry); None when absent or provider-mismatched."""
+ from agent.custom_entry_pool import load_runtime_pool
+ loaded = load_runtime_pool(primary_provider, primary_runtime_base_url, (rt or {}).get("requested_provider"))
return loaded if loaded is not None and _matches_primary(loaded) else None
if _primary_quota_reopened_early(agent, primary_provider, primary_model, _matches_primary, _load_primary_pool):
agent._rate_limited_until = 0
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index 91fb9c47c37..707182dc727 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -4777,16 +4777,16 @@ def _named_custom_api_key(custom_entry: dict[str, Any], provider: str, custom_ba
if not custom_key:
with contextlib.suppress(Exception):
from agent.credential_pool import custom_provider_pool_key_candidates
+ from agent.custom_entry_pool import entry_scoped_pool
pool_name = custom_entry.get("provider_key") or custom_entry.get("name") or provider
for pool_key in custom_provider_pool_key_candidates(custom_base, pool_name):
try:
pool = load_pool(pool_key)
except Exception:
continue
- if not pool.has_credentials():
+ if (pool := entry_scoped_pool(pool, pool_key, custom_entry)) is None or not pool.has_credentials():
continue
- pool_entry = pool.select()
- if pool_entry is None:
+ if (pool_entry := pool.select()) is None:
continue
pool_api_key = getattr(pool_entry, "runtime_api_key", None) or getattr(pool_entry, "access_token", "") or ""
if str(pool_api_key).strip():
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index 16765611b0c..163fb35f58a 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -520,26 +520,11 @@ def custom_provider_pool_key_candidates(
skipped for the ``no-key-required`` placeholder. ``config`` is a frozen route's config: ITS
entry owns the endpoint, so a live edit of that entry's URL neither drops nor redirects the pool.
"""
- if not base_url:
- return []
- normalized_url = _norm_url(base_url)
- requested_aliases = _requested_custom_name_aliases(provider_name) if provider_name else set()
-
- if requested_aliases:
- for norm_name, entry in _iter_custom_providers(config):
- if requested_aliases & _custom_entry_name_aliases(norm_name, entry):
- # A named pool holds credentials for its configured endpoint only: a launch-
- # overridden base_url must not inherit them (R2-M1), nor borrow a sibling's by URL.
- entry_url = _norm_url(entry.get("base_url"))
- if entry_url and entry_url != normalized_url:
- return []
- return _pool_keys_for_custom_entry(norm_name, entry)
-
- for norm_name, entry in _iter_custom_providers(config):
- entry_url = _norm_url(entry.get("base_url"))
- if entry_url and entry_url == normalized_url:
- return _pool_keys_for_custom_entry(norm_name, entry)
- return []
+ # A named pool holds credentials for its configured endpoint only: a launch-overridden base_url
+ # must not inherit them (R2-M1), nor borrow a sibling's by URL.
+ from agent.custom_entry_pool import custom_entry_for_endpoint
+ match = custom_entry_for_endpoint(base_url, provider_name, config)
+ return _pool_keys_for_custom_entry(*match) if match else []
def get_custom_provider_pool_key(base_url: Optional[str], provider_name: Optional[str] = None) -> Optional[str]:
diff --git a/agent/custom_entry_pool.py b/agent/custom_entry_pool.py
new file mode 100644
index 00000000000..5b77b7218b9
--- /dev/null
+++ b/agent/custom_entry_pool.py
@@ -0,0 +1,86 @@
+"""Credential ownership for ``providers:`` entries whose pool slug is also a built-in's pool id.
+
+``providers.deepseek`` pools under the slug ``deepseek``, which ``load_pool`` also seeds from the
+built-in DeepSeek provider's env vars and auth files. Those rows are the built-in's accounts. Every
+acquisition of a pool for the custom entry's runtime (main, frozen and auxiliary resolution, a
+URL-matched bare ``custom`` route, restoring the primary after a fallback, a delegated child's pool)
+takes the entry-scoped view from here, so the built-in's account never stands in for the entry's
+declared credential. The built-in provider itself still loads, and persists, the whole pool.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Optional
+
+_DECLARED_CREDENTIAL_KEYS = ("api_key", "key_env", "api_key_env", "key_cmd")
+
+
+def entry_declares_credential(entry: Any) -> bool:
+ """Whether a custom entry names its own credential (``api_key`` / ``key_env`` / ``key_cmd``)."""
+ return isinstance(entry, dict) and any(str(entry.get(k) or "").strip() for k in _DECLARED_CREDENTIAL_KEYS)
+
+
+def row_owned_by_entry(row: Any, entry: Any) -> bool:
+ """Ownership by provenance: ``hermes auth add`` (manual) rows, and rows seeded from the entry's
+ own ``key_env``. Rows the built-in seeded from its registry env vars or auth files are foreign."""
+ from agent.credential_pool import _is_manual_source
+ source = str(getattr(row, "source", "") or "").strip()
+ own_env = {f"env:{name}" for name in (str(entry.get(k) or "").strip() for k in ("key_env", "api_key_env")) if name}
+ return _is_manual_source(source) or source in own_env
+
+
+def entry_scoped_pool(pool: Any, pool_key: str, entry: Optional[dict[str, Any]]) -> Any:
+ """The rows of ``pool`` the custom ``entry`` owns: the pool itself when it owns them all, else a
+ view of them, or None when it owns none. ``custom:<name>`` pools are seeded from the entry's own
+ config and stay whole; so does any pool for an entry that declares no credential (as before).
+
+ The view shares the loaded rows and token baselines, so persisting it merges into the stored
+ pool under its lock and leaves the built-in's omitted rows on disk.
+ """
+ from agent.credential_pool import CUSTOM_POOL_PREFIX, CredentialPool
+ if pool is None or str(pool_key or "").startswith(CUSTOM_POOL_PREFIX) or not entry_declares_credential(entry):
+ return pool
+ rows = pool.entries()
+ owned = [row for row in rows if row_owned_by_entry(row, entry)]
+ if len(owned) == len(rows):
+ return pool
+ if not owned:
+ return None
+ view = CredentialPool(pool.provider, owned)
+ view._persisted_token_pairs = pool._persisted_token_pairs
+ return view
+
+
+def custom_entry_for_endpoint(
+ base_url: Optional[str], provider_name: Optional[str] = None, config: Optional[dict] = None,
+) -> Optional[tuple[str, dict[str, Any]]]:
+ """``(normalized_name, entry)`` of the configured custom entry that owns ``base_url``: by name
+ first (a named entry's pool never serves another URL), else by URL. ``config`` is a frozen
+ route's config, whose entry owns the endpoint even after a live edit."""
+ from agent import credential_pool as cp
+ if not base_url:
+ return None
+ url = cp._norm_url(base_url)
+ aliases = cp._requested_custom_name_aliases(provider_name) if provider_name else set()
+ if aliases:
+ for norm_name, entry in cp._iter_custom_providers(config):
+ if aliases & cp._custom_entry_name_aliases(norm_name, entry):
+ entry_url = cp._norm_url(entry.get("base_url"))
+ return None if entry_url and entry_url != url else (norm_name, entry)
+ return next(((n, e) for n, e in cp._iter_custom_providers(config) if url and cp._norm_url(e.get("base_url")) == url), None)
+
+
+def load_runtime_pool(provider: Optional[str], base_url: Optional[str], requested_provider: Optional[str] = None) -> Any:
+ """The pool for a runtime snapshot's identity. A custom runtime (``custom`` or ``custom:<name>``)
+ is the entry's, so it gets the entry-scoped view; a built-in identity loads its whole pool.
+ Ownership comes from the runtime identity, never from the pool slug, which both share."""
+ from agent.credential_pool import CUSTOM_POOL_PREFIX, load_pool, resolve_runtime_pool_key
+ key = resolve_runtime_pool_key(provider, base_url)
+ if not key:
+ return None
+ identities = [str(v or "").strip().lower() for v in (provider, requested_provider)]
+ if not any(v == "custom" or v.startswith(CUSTOM_POOL_PREFIX) for v in identities):
+ return load_pool(key)
+ name = next((v for v in identities if v.startswith(CUSTOM_POOL_PREFIX)), None)
+ match = custom_entry_for_endpoint(base_url, name)
+ return entry_scoped_pool(load_pool(key), key, match[1] if match else None)
diff --git a/hermes_cli/runtime_provider_backends.py b/hermes_cli/runtime_provider_backends.py
index 8c9a50b1222..484c22a8f70 100644
--- a/hermes_cli/runtime_provider_backends.py
+++ b/hermes_cli/runtime_provider_backends.py
@@ -156,6 +156,10 @@ def _resolve_openrouter_runtime(
and base_url == (env_openrouter_base_url or "").rstrip("/"))
)
)
+ # A bare ``custom`` route to a URL a ``providers:`` entry owns, when that entry declares a credential:
+ # the entry's key replaces the implicit env keys (on its built-in's host those are another account's).
+ from hermes_cli.runtime_provider_custom import _model_cfg_key_env_for, _owning_entry_credential
+ declared, entry_key = _owning_entry_credential(rp, base_url) if requested_norm == "custom" else (False, "")
if is_openrouter_context:
# Same read order as the credential pool and _resolve_api_key_provider_secret
# (.env, then scope-aware os.environ, raw op:// references yielding to the resolved
@@ -174,15 +178,14 @@ def _resolve_openrouter_runtime(
else:
openai_key_ok = not is_openrouter_url or rp.looks_like_openrouter_key(openai_key)
candidates = [explicit_api_key, get_env_value_prefer_dotenv("OPENROUTER_API_KEY"),
- openai_key if openai_key_ok else ""]
+ openai_key if openai_key_ok else ""][:1 if declared else None]
else:
# ``model.api_key`` and ``model.key_env`` back a trusted config base_url only; the key_env
# rung is what a bare ``provider: custom`` block relies on (#67453).
- from hermes_cli.runtime_provider_custom import _model_cfg_key_env_for
candidates = [explicit_api_key, (cfg_api_key if use_config_base_url else ""),
(_model_cfg_key_env_for(model_cfg, base_url) if use_config_base_url else ""),
- *rp._host_gated_env_key_candidates(base_url, ollama=True)]
- api_key = next((str(c or "").strip() for c in candidates if rp.has_usable_secret(c)), "")
+ *([] if declared else rp._host_gated_env_key_candidates(base_url, ollama=True))]
+ api_key = next((str(c or "").strip() for c in candidates if rp.has_usable_secret(c)), "") or entry_key
source = "explicit" if (explicit_api_key or explicit_base_url) else "env/config"
cfg_api_mode = rp._parse_api_mode(model_cfg.get("api_mode"))
# Explicit "custom" stays "custom" rather than relabeling to "openrouter".
diff --git a/hermes_cli/runtime_provider_custom.py b/hermes_cli/runtime_provider_custom.py
index 42753844f75..96d97846ee0 100644
--- a/hermes_cli/runtime_provider_custom.py
+++ b/hermes_cli/runtime_provider_custom.py
@@ -12,6 +12,7 @@ import os
from typing import Any, Callable, Dict, Optional, Tuple
from hermes_cli.providers import custom_provider_aliases, custom_provider_slug
+from agent.custom_entry_pool import custom_entry_for_endpoint, entry_declares_credential, entry_scoped_pool
from agent.secret_scope import get_secret_str
from utils import base_url_hostname
@@ -44,15 +45,17 @@ def _key_env_secret(entry: dict[str, Any], label: str) -> str:
A declared variable that resolves to nothing is logged: every custom rung substitutes
``no-key-required`` for an empty key (keyless local servers), so a misnamed or unexported
variable otherwise surfaces only as the provider's 401/403 (#67453). A block with no key_env at
- all stays silent — that IS the keyless-server configuration.
+ all stays silent — that IS the keyless-server configuration. A ``providers:`` entry with a
+ declared credential never falls back to an implicit env key, so the placeholder is what it gets.
"""
key_env = _clean(entry.get("key_env") or entry.get("api_key_env"))
if not key_env:
return ""
value = get_secret_str(key_env, "").strip()
if not value:
- logger.warning("%s: key_env %s is set but the variable is empty/unset — the request will carry the "
- "placeholder no-key-required and the endpoint will reject it", label, key_env)
+ logger.warning("%s: key_env %s is set but the variable is empty/unset — unless another credential "
+ "is configured for it, the request carries the placeholder no-key-required and the "
+ "endpoint will reject it", label, key_env)
return value
@@ -420,23 +423,52 @@ def is_routable_provider(provider: Optional[str]) -> bool:
# ── runtime builders ───────────────────────────────────────────────────────────────────────
+def _owning_entry(rp, base_url: str, provider_name: Optional[str] = None) -> Optional[dict[str, Any]]:
+ """The ``providers:`` entry that owns a custom endpoint, from the frozen route's config when the
+ session froze one (a live edit then neither drops nor reassigns it)."""
+ frozen = rp._FROZEN_RUNTIME_CONFIG.get()
+ match = custom_entry_for_endpoint(base_url, provider_name, frozen)
+ return match[1] if match else None
+
+
+def _owning_entry_credential(rp, base_url: str) -> tuple[bool, Any]:
+ """``(declared, key)`` for a bare ``provider: custom`` route whose URL a ``providers:`` entry owns.
+ ``declared`` is False when no entry owns the URL or it names no credential; the caller then keeps
+ its implicit env fallbacks. Otherwise ``key`` is the entry's own (key_cmd first, as on the named
+ path), or "" when it resolves to nothing: no other account's env key may stand in for it."""
+ entry = _owning_entry(rp, base_url)
+ if entry is None or not entry_declares_credential(entry):
+ return False, ""
+ name = str(entry.get("name") or "custom")
+ key_cmd = _clean(entry.get("key_cmd"))
+ if key_cmd:
+ from agent.command_token_source import build_command_token_provider
+ token_provider = build_command_token_provider(key_cmd, name)
+ if token_provider is not None:
+ return True, token_provider
+ return True, _clean(entry.get("api_key")) or _key_env_secret(entry, f"custom provider '{name}'")
+
+
def _try_resolve_from_custom_pool(
- base_url: str, provider_label: str, api_mode_override: Optional[str] = None, provider_name: Optional[str] = None
+ base_url: str, provider_label: str, api_mode_override: Optional[str] = None, provider_name: Optional[str] = None,
) -> Optional[dict[str, Any]]:
- """Runtime dict from the first credential pool that owns this custom endpoint, else None."""
+ """Runtime dict from the first credential pool that owns this custom endpoint, else None. A pool
+ the owning entry shares with a same-named built-in yields only the entry's rows (entry_scoped_pool)."""
rp = _rp()
try:
# A frozen route's entry owns the pool, never the live one (a live URL edit would drop it).
frozen = rp._FROZEN_RUNTIME_CONFIG.get()
scope = {} if frozen is None else {"config": frozen}
raw_keys = list(rp.custom_provider_pool_key_candidates(base_url, provider_name, **scope))
+ owner = _owning_entry(rp, base_url, provider_name)
except Exception:
- raw_keys = []
+ raw_keys, owner = [], None
# Order-preserving dedupe of normalized keys.
candidates = list(dict.fromkeys(k for k in (str(key or "").strip().lower() for key in raw_keys) if k))
for pool_key in candidates:
try:
- pool = rp.load_pool(pool_key)
+ if (pool := entry_scoped_pool(rp.load_pool(pool_key), pool_key, owner)) is None:
+ continue
entry = pool.select() if pool.has_credentials() else None
pool_api_key = rp._pool_entry_api_key(entry) if entry is not None else ""
if not pool_api_key:
@@ -554,9 +586,12 @@ def _resolve_direct_alias_runtime(requested_provider: str, explicit_api_key: Opt
# OLLAMA_API_KEY gets its own gate here: without it a `model_aliases:` entry pointing at
# Ollama Cloud resolved no key at all.
# ``model.key_env`` only when this alias endpoint IS the configured model.base_url (#67453).
+ # A ``providers:`` entry that owns the URL and declares a credential supplies it instead of
+ # the host-gated env keys (on the entry's built-in's host those are another account's).
+ declared, entry_key = _owning_entry_credential(rp, base_url)
candidates = [(explicit_api_key or "").strip(), _model_cfg_key_env_for(rp._get_model_config(), base_url),
- *rp._host_gated_env_key_candidates(base_url, ollama=True)]
- api_key = next((c for c in candidates if rp.has_usable_secret(c)), "")
+ *([] if declared else rp._host_gated_env_key_candidates(base_url, ollama=True))]
+ api_key = next((c for c in candidates if rp.has_usable_secret(c)), "") or entry_key
return _custom_runtime(rp, base_url, api_key, None, source="direct-alias", requested_provider=requested_provider)
@@ -613,7 +648,8 @@ def _resolve_named_custom_runtime(*, requested_provider: str, explicit_api_key:
# The credential pool is the profile's auth store (``hermes auth add``), not config: a frozen
# config snapshot still owes a pooled ``providers:`` entry its keys, or the turn ships the
# ``no-key-required`` placeholder to a host that wants one (C11 pool rows). An explicit launch
- # key is the operator's credential for this route and wins over the pool (R2-M1).
+ # key is the operator's credential for this route and wins over the pool (R2-M1). An entry
+ # that names its own credential never borrows a same-named built-in's env-seeded pool rows.
pool_result = None if rp.has_usable_secret(explicit_key) else rp._try_resolve_from_custom_pool(
base_url, "custom", custom_provider.get("api_mode"),
provider_name=custom_provider.get("provider_key") or custom_provider.get("name"),
@@ -622,11 +658,13 @@ def _resolve_named_custom_runtime(*, requested_provider: str, explicit_api_key:
# The pool doesn't know the custom_providers fields — propagate them here too.
_apply_custom_provider_extras(custom_provider, target_model, pool_result)
return pool_result
+ # A declared credential that resolves to nothing gets no implicit host-gated env key: on the
+ # entry's built-in's host that is another account's key.
candidates = [
explicit_key,
_clean(custom_provider.get("api_key", "")),
_key_env_secret(custom_provider, f"custom provider '{custom_provider.get('name', requested_provider)}'"),
- *rp._host_gated_env_key_candidates(base_url, ollama=False),
+ *([] if entry_declares_credential(custom_provider) else rp._host_gated_env_key_candidates(base_url, ollama=False)),
]
api_key: Any = next((c for c in candidates if rp.has_usable_secret(c)), "")
# ``key_cmd`` credentials are minted per request (short-lived bearers would go stale
diff --git a/tests/hermes_cli/test_custom_entry_shadow_key_env.py b/tests/hermes_cli/test_custom_entry_shadow_key_env.py
new file mode 100644
index 00000000000..5fa25c7109b
--- /dev/null
+++ b/tests/hermes_cli/test_custom_entry_shadow_key_env.py
@@ -0,0 +1,312 @@
+"""A ``providers:`` entry keyed like a built-in sends its own ``key_env``, never the built-in's key.
+
+The entry's durable pool slug equals the built-in's pool id, and ``load_pool`` seeds that pool
+from the built-in's env vars (``env:DEEPSEEK_API_KEY``). The named-custom rung consulted the pool
+before ``key_env``, so every turn to the custom endpoint carried the built-in provider's secret.
+"""
+
+from __future__ import annotations
+
+import json
+
+import hermes_yaml as yaml
+import pytest
+
+ENDPOINT = "http://127.0.0.1:18080/v1"
+ENTRY_KEY = "entry-key-A-0123456789"
+BUILTIN_KEY = "builtin-key-B-0123456789"
+MANUAL_KEY = "manual-pool-key-0123456789"
+
+# (entry key == built-in pool id, the built-in's api-key env var)
+SHADOWED_BUILTINS = [
+ ("deepseek", "DEEPSEEK_API_KEY"),
+ ("openrouter", "OPENROUTER_API_KEY"),
+ ("anthropic", "ANTHROPIC_API_KEY"),
+ ("xai", "XAI_API_KEY"),
+]
+
+
+def _home(tmp_path, monkeypatch, name, builtin_env, *, entry_extra=None, pool=None):
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ entry = {"name": name, "api": ENDPOINT, "transport": "chat_completions", "default_model": "m"}
+ entry.update({"key_env": "ENTRY_KEY_VAR"} if entry_extra is None else entry_extra)
+ config = {"model": {"default": "m", "provider": f"custom:{name}"}, "providers": {name: entry}}
+ (hermes_home / "config.yaml").write_text(yaml.safe_dump(config), encoding="utf-8")
+ (hermes_home / "auth.json").write_text(
+ json.dumps({"version": 1, "providers": {}, "credential_pool": pool or {}}), encoding="utf-8")
+ monkeypatch.setenv(builtin_env, BUILTIN_KEY)
+ monkeypatch.setenv("ENTRY_KEY_VAR", ENTRY_KEY)
+ return hermes_home
+
+
[email protected]("name,builtin_env", SHADOWED_BUILTINS)
+def test_shadowing_entry_main_runtime_sends_its_key_env(tmp_path, monkeypatch, name, builtin_env):
+ """``model.provider: custom:<name>`` (which pick a bare ``<name>`` routes to is #140107's scope)."""
+ _home(tmp_path, monkeypatch, name, builtin_env)
+ from hermes_cli import runtime_provider as rp
+
+ resolved = rp.resolve_runtime_provider(requested=f"custom:{name}")
+ assert resolved["base_url"] == ENDPOINT
+ assert resolved["api_key"] == ENTRY_KEY
+
+
[email protected]("name,builtin_env", SHADOWED_BUILTINS)
+def test_shadowing_entry_frozen_policy_sends_its_key_env(tmp_path, monkeypatch, name, builtin_env):
+ """The session's frozen route ``{provider: custom:<name>, base_url, key_env}``."""
+ _home(tmp_path, monkeypatch, name, builtin_env)
+ from hermes_cli import runtime_provider as rp
+ from hermes_cli.runtime_provider_custom import _resolve_named_custom_runtime
+
+ frozen = rp.load_config()
+ resolved = _resolve_named_custom_runtime(requested_provider=f"custom:{name}", config=frozen)
+ assert (resolved["base_url"], resolved["api_key"]) == (ENDPOINT, ENTRY_KEY)
+ with rp.frozen_runtime_config(frozen):
+ resolved = rp.resolve_runtime_provider(requested=f"custom:{name}")
+ assert (resolved["base_url"], resolved["api_key"]) == (ENDPOINT, ENTRY_KEY)
+
+
[email protected]("name,builtin_env", SHADOWED_BUILTINS)
[email protected]("entry_key_set", [True, False])
+def test_shadowing_entry_auxiliary_client_never_borrows_builtin_key(tmp_path, monkeypatch, name, builtin_env,
+ entry_key_set):
+ """Aux reads key_env first; with key_env declared but unset it must not fall back to the
+ built-in's env-seeded pool row (the placeholder + warning is the documented outcome)."""
+ _home(tmp_path, monkeypatch, name, builtin_env)
+ if not entry_key_set:
+ monkeypatch.delenv("ENTRY_KEY_VAR")
+ from agent.auxiliary_client import _named_custom_api_key
+ from hermes_cli.runtime_provider import _get_named_custom_provider
+
+ entry = _get_named_custom_provider(f"custom:{name}")
+ expected = ENTRY_KEY if entry_key_set else "no-key-required"
+ assert _named_custom_api_key(entry, name, ENDPOINT) == expected
+
+
+def test_shadowing_entry_unset_key_env_never_borrows_builtin_key(tmp_path, monkeypatch):
+ _home(tmp_path, monkeypatch, "deepseek", "DEEPSEEK_API_KEY")
+ monkeypatch.delenv("ENTRY_KEY_VAR")
+ from hermes_cli import runtime_provider as rp
+
+ resolved = rp.resolve_runtime_provider(requested="custom:deepseek")
+ assert resolved["base_url"] == ENDPOINT
+ assert resolved["api_key"] == "no-key-required"
+
+
+def test_shadowing_entry_inline_api_key_beats_builtin_env(tmp_path, monkeypatch):
+ _home(tmp_path, monkeypatch, "deepseek", "DEEPSEEK_API_KEY", entry_extra={"api_key": ENTRY_KEY})
+ from hermes_cli import runtime_provider as rp
+
+ assert rp.resolve_runtime_provider(requested="custom:deepseek")["api_key"] == ENTRY_KEY
+
+
+def test_shadowing_entry_manual_pool_row_still_wins(tmp_path, monkeypatch):
+ """``hermes auth add deepseek`` rows are the operator's credential for the slug and keep
+ their precedence over key_env, exactly like a non-shadowing keyed entry."""
+ manual = {"id": "m1", "label": "manual", "auth_type": "api_key", "priority": 0, "source": "manual",
+ "access_token": MANUAL_KEY}
+ _home(tmp_path, monkeypatch, "deepseek", "DEEPSEEK_API_KEY", pool={"deepseek": [manual]})
+ from hermes_cli import runtime_provider as rp
+
+ for _ in range(3):
+ resolved = rp.resolve_runtime_provider(requested="custom:deepseek")
+ assert resolved["api_key"] == MANUAL_KEY
+ pool = resolved["credential_pool"]
+ # The rotation pool must not reach the built-in's env-seeded row either.
+ assert {e.access_token for e in pool.entries()} == {MANUAL_KEY}
+ # The built-in's own pool keeps its env-seeded row on disk.
+ from agent.credential_pool import load_pool
+
+ assert BUILTIN_KEY in {e.access_token for e in load_pool("deepseek").entries()}
+
+
+def test_entry_without_key_env_keeps_existing_resolution(tmp_path, monkeypatch):
+ """No key_env / api_key / key_cmd: resolution is unchanged by this fix (pool first, then
+ host-gated env, then the keyless placeholder)."""
+ _home(tmp_path, monkeypatch, "deepseek", "DEEPSEEK_API_KEY", entry_extra={})
+ from hermes_cli import runtime_provider as rp
+
+ assert rp.resolve_runtime_provider(requested="custom:deepseek")["api_key"] == BUILTIN_KEY
+
+
+def test_non_shadowing_entry_sends_its_key_env(tmp_path, monkeypatch):
+ _home(tmp_path, monkeypatch, "mydeep", "DEEPSEEK_API_KEY")
+ from hermes_cli import runtime_provider as rp
+
+ resolved = rp.resolve_runtime_provider(requested="custom:mydeep")
+ assert (resolved["base_url"], resolved["api_key"]) == (ENDPOINT, ENTRY_KEY)
+
+
+# ── every later pool acquisition keeps the entry's ownership ───────────────────────────────────
+
+BUILTIN_HOST = "https://api.deepseek.com/v1"
+
+
+def _edit_config(home, *, model=None, entry=None):
+ cfg = yaml.safe_load((home / "config.yaml").read_text())
+ cfg["model"].update(model or {})
+ cfg["providers"]["deepseek"].update(entry or {})
+ (home / "config.yaml").write_text(yaml.safe_dump(cfg), encoding="utf-8")
+
+
[email protected]("explicit", [False, True], ids=["model_base_url", "explicit_base_url"])
+def test_url_matched_bare_custom_sends_the_entry_key(tmp_path, monkeypatch, explicit):
+ """Bare ``provider: custom`` whose URL matches ``providers.deepseek`` gets the entry's key_env."""
+ home = _home(tmp_path, monkeypatch, "deepseek", "DEEPSEEK_API_KEY")
+ _edit_config(home, model={"provider": "custom", "base_url": ENDPOINT})
+ from hermes_cli import runtime_provider as rp
+
+ resolved = rp.resolve_runtime_provider(requested="custom", **({"explicit_base_url": ENDPOINT} if explicit else {}))
+ assert (resolved["base_url"], resolved["api_key"]) == (ENDPOINT, ENTRY_KEY)
+
+
[email protected]("explicit", [False, True], ids=["model_base_url", "explicit_base_url"])
+def test_url_matched_bare_custom_frozen_route_sends_the_entry_key(tmp_path, monkeypatch, explicit):
+ home = _home(tmp_path, monkeypatch, "deepseek", "DEEPSEEK_API_KEY")
+ _edit_config(home, model={"provider": "custom", "base_url": ENDPOINT})
+ from hermes_cli import runtime_provider as rp
+
+ frozen = rp.load_config()
+ # A live edit after the session froze its route must not change who owns the endpoint.
+ _edit_config(home, entry={"key_env": "OTHER_UNSET_VAR"})
+ with rp.frozen_runtime_config(frozen):
+ resolved = rp.resolve_runtime_provider(requested="custom", **({"explicit_base_url": ENDPOINT} if explicit else {}))
+ assert (resolved["base_url"], resolved["api_key"]) == (ENDPOINT, ENTRY_KEY)
+
+
+def test_url_matched_entry_without_declared_credential_keeps_existing_resolution(tmp_path, monkeypatch):
+ _home(tmp_path, monkeypatch, "deepseek", "DEEPSEEK_API_KEY", entry_extra={})
+ from hermes_cli import runtime_provider as rp
+
+ resolved = rp.resolve_runtime_provider(requested="custom", explicit_base_url=ENDPOINT)
+ assert resolved["api_key"] == BUILTIN_KEY
+
+
[email protected]("requested", ["custom:deepseek", "custom"])
+def test_declared_key_env_unset_never_falls_back_to_the_builtin_host_key(tmp_path, monkeypatch, caplog, requested):
+ """On the built-in's own host the host-derived ``DEEPSEEK_API_KEY`` is another account's key."""
+ home = _home(tmp_path, monkeypatch, "deepseek", "DEEPSEEK_API_KEY")
+ _edit_config(home, entry={"api": BUILTIN_HOST})
+ monkeypatch.delenv("ENTRY_KEY_VAR")
+ from hermes_cli import runtime_provider as rp
+
+ with caplog.at_level("WARNING"):
+ resolved = rp.resolve_runtime_provider(requested=requested, explicit_base_url=BUILTIN_HOST if requested == "custom" else None)
+ assert resolved["api_key"] == "no-key-required"
+ warning = next(r.getMessage() for r in caplog.records if "ENTRY_KEY_VAR" in r.getMessage())
+ assert "no-key-required" in warning
+
+
+def test_entry_owns_pool_rows_seeded_from_its_own_key_env(tmp_path, monkeypatch):
+ """Ownership is by provenance: an ``env:<the entry's key_env>`` row (#125447 seeds those into the
+ slug pool) is the entry's own and keeps its rotation state; the built-in's env row is not."""
+ row = {"id": "e1", "label": "ENTRY_KEY_VAR", "auth_type": "api_key", "priority": 0,
+ "source": "env:ENTRY_KEY_VAR", "access_token": ENTRY_KEY, "base_url": ENDPOINT}
+ _home(tmp_path, monkeypatch, "deepseek", "DEEPSEEK_API_KEY", pool={"deepseek": [row]})
+ from hermes_cli import runtime_provider as rp
+
+ resolved = rp.resolve_runtime_provider(requested="custom:deepseek")
+ assert resolved["api_key"] == ENTRY_KEY
+ pool = resolved.get("credential_pool")
+ assert pool is not None and [e.source for e in pool.entries()] == ["env:ENTRY_KEY_VAR"]
+
+
+def _restorable_agent(primary: dict):
+ """An agent on a cross-provider fallback (OpenRouter pool attached) whose snapshot is ``primary``."""
+ from unittest.mock import MagicMock
+
+ from agent.credential_pool import CredentialPool
+ from run_agent import AIAgent
+
+ agent = AIAgent.__new__(AIAgent)
+ agent.model, agent.provider, agent.base_url = "fallback-model", "openrouter", "https://openrouter.ai/api/v1"
+ agent.api_mode, agent.api_key = "chat_completions", "fallback-key-0123456789"
+ agent._client_kwargs = {"api_key": agent.api_key, "base_url": agent.base_url}
+ agent._credential_pool = CredentialPool("openrouter", [])
+ agent._fallback_activated, agent._fallback_index, agent._rate_limited_until = True, 1, 0
+ agent._use_prompt_caching = agent._use_native_cache_layout = False
+ agent.context_compressor = MagicMock()
+ agent._primary_runtime = {
+ "model": "m", "api_mode": "chat_completions", **primary,
+ "client_kwargs": {"api_key": primary["api_key"], "base_url": primary["base_url"]},
+ "use_prompt_caching": False, "use_native_cache_layout": False, "compressor_model": "m",
+ "compressor_base_url": primary["base_url"], "compressor_api_key": primary["api_key"],
+ "compressor_provider": primary["provider"], "compressor_context_length": 128000,
+ "compressor_threshold_tokens": 0.8,
+ }
+ agent._create_openai_client = MagicMock(return_value=MagicMock())
+ agent._apply_client_headers_for_base_url = MagicMock()
+ agent._replace_primary_openai_client = MagicMock(return_value=True)
+ return agent
+
+
+def test_restoring_the_primary_after_fallback_keeps_the_entry_endpoint_and_key(tmp_path, monkeypatch):
+ _home(tmp_path, monkeypatch, "deepseek", "DEEPSEEK_API_KEY")
+ from hermes_cli import runtime_provider as rp
+
+ initial = rp.resolve_runtime_provider(requested="custom:deepseek")
+ assert initial["api_key"] == ENTRY_KEY
+ agent = _restorable_agent({"provider": initial["provider"], "requested_provider": "custom:deepseek",
+ "base_url": ENDPOINT, "api_key": ENTRY_KEY})
+ assert agent._restore_primary_runtime() is True
+ assert (agent.api_key, agent.base_url) == (ENTRY_KEY, ENDPOINT)
+ assert agent._credential_pool is None
+
+
+def test_restoring_a_builtin_primary_still_reselects_its_own_pool(tmp_path, monkeypatch):
+ _home(tmp_path, monkeypatch, "deepseek", "DEEPSEEK_API_KEY")
+ agent = _restorable_agent({"provider": "deepseek", "requested_provider": "deepseek",
+ "base_url": BUILTIN_HOST, "api_key": "stale-snapshot-key-0123"})
+ assert agent._restore_primary_runtime() is True
+ assert agent.api_key == BUILTIN_KEY
+
+
+def test_delegated_child_never_leases_the_builtin_account(tmp_path, monkeypatch):
+ """Entry on DeepSeek's own endpoint with a separately declared account key."""
+ from types import SimpleNamespace
+ from unittest.mock import MagicMock
+
+ home = _home(tmp_path, monkeypatch, "deepseek", "DEEPSEEK_API_KEY")
+ _edit_config(home, entry={"api": BUILTIN_HOST})
+ from hermes_cli import runtime_provider as rp
+ from tools.delegate_tool_child_run import _lease_child_credential
+ from tools.delegate_tool_config import _resolve_child_credential_pool
+
+ resolved = rp.resolve_runtime_provider(requested="custom:deepseek")
+ assert resolved["api_key"] == ENTRY_KEY
+ parent = SimpleNamespace(provider="custom", requested_provider="custom:deepseek", base_url=BUILTIN_HOST,
+ _credential_pool=resolved.get("credential_pool"))
+ child = SimpleNamespace(base_url=BUILTIN_HOST, _swap_credential=MagicMock(),
+ _credential_pool=_resolve_child_credential_pool("custom", parent, BUILTIN_HOST, "custom:deepseek"))
+ pool, lease_id = _lease_child_credential(child)
+ if lease_id is not None:
+ pool.release_lease(lease_id)
+ assert [c.args[0].runtime_api_key for c in child._swap_credential.call_args_list] == []
+
+
[email protected]("name,builtin_env", SHADOWED_BUILTINS)
+def test_explicit_builtin_pick_keeps_its_env_key(tmp_path, monkeypatch, name, builtin_env):
+ _home(tmp_path, monkeypatch, name, builtin_env)
+ from hermes_cli import runtime_provider as rp
+
+ resolved = rp.resolve_runtime_provider(requested=name)
+ assert resolved["api_key"] == BUILTIN_KEY
+ assert resolved["base_url"] != ENDPOINT
+
+
+def test_persisting_the_entry_view_keeps_the_builtin_rows_and_writes_no_secret(tmp_path, monkeypatch):
+ manual = {"id": "m1", "label": "manual", "auth_type": "api_key", "priority": 0, "source": "manual",
+ "access_token": MANUAL_KEY}
+ home = _home(tmp_path, monkeypatch, "deepseek", "DEEPSEEK_API_KEY", pool={"deepseek": [manual]})
+ from agent.credential_pool import load_pool
+ from hermes_cli import runtime_provider as rp
+
+ load_pool("deepseek")
+ before = {r["id"] for r in json.loads((home / "auth.json").read_text())["credential_pool"]["deepseek"]}
+ rp.resolve_runtime_provider(requested="custom:deepseek")["credential_pool"]._persist()
+ text = (home / "auth.json").read_text()
+ after = json.loads(text)["credential_pool"]["deepseek"]
+ assert {r["id"] for r in after} == before
+ assert any(r["source"] == "env:DEEPSEEK_API_KEY" for r in after)
+ assert BUILTIN_KEY not in text and ENTRY_KEY not in text
diff --git a/tools/delegate_tool_config.py b/tools/delegate_tool_config.py
index 1f096bd220e..357d1ba43a8 100644
--- a/tools/delegate_tool_config.py
+++ b/tools/delegate_tool_config.py
@@ -267,7 +267,11 @@ def _resolve_child_credential_pool(
)
if parent_pool is not None and parent_provider == "custom" and parent_key is not None and parent_key == child_key:
return parent_pool
- return _loaded_pool(child_key)
+ # The entry's slug may also be a same-named built-in's pool: lease only the rows the entry
+ # owns, or a fixed entry credential becomes the built-in's account on a shared endpoint.
+ from agent.custom_entry_pool import custom_entry_for_endpoint, entry_scoped_pool
+ owner = custom_entry_for_endpoint(effective_base_url, effective_requested_provider)
+ return entry_scoped_pool(_loaded_pool(child_key), child_key, owner[1] if owner else None)
if effective_provider == parent_provider:
# A same-provider parent with no pool is using a fixed credential.
# Loading a separate provider pool here can replace the inherited