Skip to content

The agent that grows with you

refactor(agent): derive provider-named core sets from registered profiles

Teknium58cf3ee9acb7
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 285c190e2c9..bf85ee21e27 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -3180,12 +3180,10 @@ def looks_like_codex_intermediate_ack(
assistant_text = agent._strip_think_blocks(assistant_content or "").strip().lower()
if not assistant_text or len(assistant_text) > 1200:
return False
- # Some tool-using providers narrate the next action in terse log style
- # rather than with a first-person lead-in: "Brief written. Creating the
- # session now." Bare gerunds are too ambiguous ("Reading the traceback
- # explains the failure" is a final answer), so this path also requires an
- # explicit transition cue such as "now", "via acpx", "actual log", or
- # "then launching". Completed reports and questions stay final.
+ # Some tool-using providers narrate the next action in terse log style: "Brief written. Creating the
+ # session now." Bare gerunds are too ambiguous ("Reading the traceback explains the failure" is a final
+ # answer), so this path also requires an explicit transition cue such as "now", "on <provider> via acpx",
+ # "actual log", or "then launching". Completed reports and questions stay final.
action_clause_pattern = re.compile(
r"(?:^|[.!…—–]\s+|\n+\s*|,\s+then\s+)"
r"(?:(?P<transition>then)\s+)?"
@@ -3227,9 +3225,11 @@ def looks_like_codex_intermediate_ack(
r"\s+now\s*[—–-]\s*see\s+https?://\S+"
r"(?:\s+for\s+progress)?\s*$"
)
+ from providers import list_providers # "relaunching it on <any registered provider name or alias>"
+ provider_names = sorted({n.lower() for p in list_providers() for n in (p.name, *p.aliases) if n})
provider_tail_pattern = re.compile(
r"\s+(?:it|(?:the\s+)?(?:session|worker|agent|job|process))\s+"
- r"on\s+copilot(?:\s+via\s+acpx)?\s*$"
+ rf"on\s+(?:{'|'.join(map(re.escape, provider_names)) or '(?!)'})(?:\s+via\s+acpx)?\s*$"
)
actual_log_tail_pattern = re.compile(
r"\s+(?:the\s+)?actual\s+(?:log|output)\s*$"
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index c7b6e12657e..38063ac765e 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -3781,12 +3781,9 @@ def _prepare_same_provider_retry(
extra_body=effective_extra_body, reasoning_config=reasoning_config,
base_url=retry_base or resolved_base_url, task=task,
)
- # Preserve per-request attribution headers (e.g. Copilot ``x-initiator``) so the retry keeps capability gating.
+ # Preserve per-request attribution headers (a profile's ``request_headers``) across the rebuilt-client
+ # retry: dropping them would let a recovery retry silently lose capability gating (#60293).
if extra_headers:
- # Copilot's ``x-initiator: user``) across the rebuilt-client retry — dropping them here would let a
- # recovery retry silently lose capability gating (#60293).
- # Preserve per-request attribution headers across the rebuilt-client retry — see the sync variant
- # above (#60293).
retry_kwargs["extra_headers"] = dict(extra_headers)
if _is_anthropic_compat_endpoint(resolved_provider, retry_base):
retry_kwargs["messages"] = _convert_openai_images_to_anthropic(retry_kwargs["messages"])
@@ -4699,7 +4696,7 @@ def _effective_provider_for_client(client: Any, fallback: str) -> str:
def _to_async_client(sync_client, model: str, is_vision: bool = False):
- """Sync client → async counterpart, preserving Codex routing (``is_vision`` adds the Copilot vision header)."""
+ """Sync client → async counterpart, preserving Codex routing (``is_vision`` keeps the endpoint's vision headers)."""
from openai import AsyncOpenAI
if isinstance(sync_client, _AuxProbeClientStub):
return sync_client, model
@@ -6106,30 +6103,29 @@ def _preserve_provider_with_base_url(prov: Optional[str]) -> bool:
def _builtin_provider_present(name: str) -> bool:
- """Look up *name* in the built-in provider registry, returning False
- (not raising) when the catalog fails to load.
-
- Used by ``_preserve_provider_with_base_url`` so a built-in lookup
- exception cannot suppress the parallel user-defined provider lookup
- (#76602).
- """
+ """*name* is a built-in provider. Never raises, so a failing catalog cannot suppress the parallel
+ user-defined lookup in ``_preserve_provider_with_base_url`` (#76602)."""
try:
from hermes_cli.providers import get_provider
return get_provider(name) is not None
except Exception:
- # Keep the high-risk provider-backed routes safe even if provider
- # catalog loading is unavailable during early import/test paths.
- return name in {
- "anthropic",
- "copilot",
- "copilot-acp",
- "minimax-oauth",
- "nous",
- "openai-codex",
- "qwen-oauth",
- "xai-oauth",
- }
+ # Catalog unavailable (early import/test paths): still keep the high-risk provider-backed routes.
+ return (name in {"anthropic", "minimax-oauth", "nous", "openai-codex", "qwen-oauth", "xai-oauth"}
+ or _profile_credentials_bypass_custom(name))
+
+
+def _profile_credentials_bypass_custom(name: str) -> bool:
+ """A profile (canonical name) whose credentials ``custom`` cannot carry: ambient, or an external process's."""
+ try:
+ from providers import get_provider_profile
+
+ profile = get_provider_profile(name)
+ except Exception:
+ logger.debug("provider profile lookup for %s failed", name, exc_info=True)
+ return False
+ return profile is not None and profile.name == name and (
+ profile.ambient_credentials or profile.auth_type == "external_process")
def _named_custom_provider_present(name: str) -> bool:
diff --git a/agent/message_metadata.py b/agent/message_metadata.py
index 98d84eb9636..86bcbe3c31a 100644
--- a/agent/message_metadata.py
+++ b/agent/message_metadata.py
@@ -78,8 +78,17 @@ def lift_data_use(message: MutableMapping[str, Any]) -> None:
# Replay carriers the preflight estimate prices at 0, exactly as the compaction tail walk does (opaque signatures,
# duplicate reasoning copies, ordered sidecars); a mismatch between the two estimates loops compaction.
-UNPRICED_REPLAY_FIELDS = frozenset({"_anthropic_content_blocks", "reasoning_details", "extra_content",
- "reasoning_opaque", "reasoning_text", "bedrock_content_blocks", DATA_USE})
+_UNPRICED_CORE_FIELDS = frozenset({"_anthropic_content_blocks", "reasoning_details", "extra_content",
+ "bedrock_content_blocks", DATA_USE})
+
+
+def unpriced_replay_fields() -> frozenset[str]:
+ """The core unpriced carriers plus every message carrier key a registered profile declares
+ (``ProviderProfile.message_carrier_*``). Resolve once per message, never per key."""
+ from agent.reasoning_carriers import declared_carrier_keys
+
+ opaque, text = declared_carrier_keys()
+ return _UNPRICED_CORE_FIELDS.union(opaque, text)
def without_persistence_fields(msg: Mapping[str, Any]) -> Mapping[str, Any]:
diff --git a/agent/model_metadata.py b/agent/model_metadata.py
index 8aa0da3444a..8bb2dd51984 100644
--- a/agent/model_metadata.py
+++ b/agent/model_metadata.py
@@ -24,7 +24,7 @@ from agent.model_metadata_llamacpp import llamacpp_context
from utils import atomic_json_write, base_url_host_matches, base_url_hostname
from hermes_constants import OPENROUTER_MODELS_URL, openrouter_variant_base
-from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS, UNPRICED_REPLAY_FIELDS, without_persistence_fields
+from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS, unpriced_replay_fields, without_persistence_fields
logger = logging.getLogger(__name__)
@@ -2532,11 +2532,11 @@ def _wire_message_shadow(msg: dict[str, Any]) -> dict[str, Any]:
prices them, and the usage anchor carries that price forward."""
sidecar = msg.get("api_content")
sidecar_wins = isinstance(sidecar, str) and bool(sidecar) and msg.get("role") in ("user", "assistant")
- _rc = msg.get("reasoning_content")
- drop_reasoning_dup = isinstance(_rc, str) and bool(_rc.strip())
+ drop_reasoning_dup = isinstance(_rc := msg.get("reasoning_content"), str) and bool(_rc.strip())
+ unpriced = unpriced_replay_fields()
shadow: dict[str, Any] = {}
for k, v in msg.items():
- if k in UNPRICED_REPLAY_FIELDS or k in PERSISTENCE_ONLY_MESSAGE_FIELDS or (k == "reasoning" and drop_reasoning_dup):
+ if k in unpriced or k in PERSISTENCE_ONLY_MESSAGE_FIELDS or (k == "reasoning" and drop_reasoning_dup):
continue
if k == "api_content":
if sidecar_wins:
diff --git a/tests/agent/test_profile_declared_core_sets.py b/tests/agent/test_profile_declared_core_sets.py
new file mode 100644
index 00000000000..1cdcfde660f
--- /dev/null
+++ b/tests/agent/test_profile_declared_core_sets.py
@@ -0,0 +1,61 @@
+"""Core sets that used to name one provider now come from the registered provider profiles.
+
+Each contract runs through a fake, non-built-in profile: whatever a profile declares (an ambient
+credential, a message-level reasoning carrier, its name) is what core honours, with no provider
+named in core.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import patch
+
+from providers.base import ProviderProfile
+
+ACME = ProviderProfile(name="acme-cloud", aliases=("acme",), base_url="https://api.acme.test/v1",
+ ambient_credentials=True, message_carrier_opaque="acme_sig",
+ message_carrier_text="acme_thoughts")
+PLAIN = ProviderProfile(name="plain-key", base_url="https://api.plain.test/v1")
+_PROFILES = {p.name: p for p in (ACME, PLAIN)}
+
+
+def _catalog_down(_name):
+ raise RuntimeError("catalog unavailable")
+
+
+def test_ambient_credential_profile_keeps_identity_when_catalog_fails():
+ import agent.auxiliary_client as ac
+
+ with patch("hermes_cli.providers.get_provider", side_effect=_catalog_down), \
+ patch("hermes_cli.runtime_provider._get_named_custom_provider", return_value=None), \
+ patch("providers.get_provider_profile", side_effect=_PROFILES.get):
+ assert ac._preserve_provider_with_base_url("acme-cloud") is True
+ assert ac._preserve_provider_with_base_url("plain-key") is False
+
+
+def test_ack_detector_transition_cue_names_any_registered_provider():
+ from agent.agent_runtime_helpers import looks_like_codex_intermediate_ack
+
+ agent = SimpleNamespace(_strip_think_blocks=lambda s: s)
+
+ def ack(text):
+ return looks_like_codex_intermediate_ack(agent, "go", text, [], require_workspace=False)
+
+ with patch("providers.list_providers", return_value=[ACME, PLAIN]):
+ assert ack("Launching it on acme-cloud via acpx.") is True
+ assert ack("Relaunching the session on acme.") is True
+ assert ack("Starting the job on monday.") is False
+
+
+def test_declared_message_carriers_are_unpriced():
+ from agent.message_metadata import unpriced_replay_fields
+ from agent.model_metadata import estimate_messages_tokens_rough
+
+ plain = {"role": "assistant", "content": "ok"}
+ carried = {**plain, "acme_sig": "S" * 4000, "acme_thoughts": "T" * 4000}
+ with patch("providers.list_providers", return_value=[ACME, PLAIN]):
+ assert {"acme_sig", "acme_thoughts"} <= unpriced_replay_fields()
+ assert estimate_messages_tokens_rough([carried]) == estimate_messages_tokens_rough([plain])
+ with patch("providers.list_providers", return_value=[PLAIN]):
+ fresh = {**plain, "acme_sig": "s" * 4000, "acme_thoughts": "t" * 4000} # new strings: no memo hit
+ assert estimate_messages_tokens_rough([fresh]) > estimate_messages_tokens_rough([plain])