Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4622,6 +4622,7 @@ def _ensure_runtime_credentials(self) -> bool:
requested=self.requested_provider,
explicit_api_key=self._explicit_api_key,
explicit_base_url=self._explicit_base_url,
target_model=self.model,
)
except Exception as exc:
_primary_exc = exc
Expand Down
17 changes: 12 additions & 5 deletions gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -1061,7 +1061,7 @@ def _reload_runtime_env_preserving_config_authority() -> None:
_AGENT_PENDING_SENTINEL = object()


def _resolve_runtime_agent_kwargs() -> dict:
def _resolve_runtime_agent_kwargs(target_model: str | None = None) -> dict:
"""Resolve provider credentials for gateway-created AIAgent instances.

Provider is read from ``config.yaml`` ``model.provider`` (the single
Expand All @@ -1070,6 +1070,13 @@ def _resolve_runtime_agent_kwargs() -> dict:
not consult environment variables for behavioral config — config.yaml
is authoritative.

target_model: Optional active model name. When passed, providers that
derive ``api_mode`` per-model (Copilot, OpenCode Zen/Go) compute it
from this model instead of the stale ``model.default`` in config.
Without this, mid-session ``/model`` switches caused resolver and
normalizer to disagree, flapping the agent route signature and
forcing a full agent rebuild on every turn.

If the primary provider fails with an authentication error, attempt to
resolve credentials using the fallback provider chain from config.yaml
before giving up.
Expand All @@ -1081,7 +1088,7 @@ def _resolve_runtime_agent_kwargs() -> dict:
from hermes_cli.auth import AuthError

try:
runtime = resolve_runtime_provider()
runtime = resolve_runtime_provider(target_model=target_model)
except AuthError as auth_exc:
# Primary provider auth failed (expired token, revoked key, etc.).
# Try the fallback provider chain before raising.
Expand Down Expand Up @@ -2389,7 +2396,7 @@ def _resolve_session_agent_runtime(
list(self._session_model_overrides.keys())[:5] if self._session_model_overrides else "[]",
)

runtime_kwargs = _resolve_runtime_agent_kwargs()
runtime_kwargs = _resolve_runtime_agent_kwargs(target_model=model)
runtime_model = runtime_kwargs.pop("model", None)
if runtime_model:
logger.info(
Expand Down Expand Up @@ -8025,7 +8032,7 @@ async def _prepare_inbound_message_text(
from agent.model_metadata import get_model_context_length

_msg_cwd = os.environ.get("TERMINAL_CWD", os.path.expanduser("~"))
_msg_runtime = _resolve_runtime_agent_kwargs()
_msg_runtime = _resolve_runtime_agent_kwargs(target_model=self._model)
_msg_config_ctx = None
try:
_msg_cfg = _load_gateway_config()
Expand Down Expand Up @@ -9225,7 +9232,7 @@ def _format_session_info(self) -> str:

# Resolve runtime credentials for probing
try:
runtime = _resolve_runtime_agent_kwargs()
runtime = _resolve_runtime_agent_kwargs(target_model=model)
provider = provider or runtime.get("provider")
base_url = base_url or runtime.get("base_url")
api_key = runtime.get("api_key")
Expand Down
47 changes: 36 additions & 11 deletions hermes_cli/runtime_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,22 +219,37 @@ def _provider_supports_explicit_api_mode(provider: Optional[str], configured_pro
return normalized_configured == normalized_provider


def _copilot_runtime_api_mode(model_cfg: Dict[str, Any], api_key: str) -> str:
def _copilot_runtime_api_mode(
model_cfg: Dict[str, Any],
api_key: str,
target_model: Optional[str] = None,
) -> str:
configured_provider = str(model_cfg.get("provider") or "").strip().lower()
configured_mode = _parse_api_mode(model_cfg.get("api_mode"))
if configured_mode and _provider_supports_explicit_api_mode("copilot", configured_provider):
return configured_mode

model_name = str(model_cfg.get("default") or "").strip()
model_name = str(target_model or model_cfg.get("default") or "").strip()
if not model_name:
return "chat_completions"
return configured_mode or "chat_completions"
if target_model is None and configured_mode and _provider_supports_explicit_api_mode("copilot", configured_provider):
return configured_mode

# Copilot exposes different model families through different API surfaces.
# When the caller knows the active/target model (CLI /model switch,
# subagents, cron, etc.), derive api_mode from that model instead of a
# stale persisted config default/api_mode. If inference fails, fall back to
# a matching-provider explicit config before the chat-completions default.
try:
from hermes_cli.models import copilot_model_api_mode

return copilot_model_api_mode(model_name, api_key=api_key)
inferred = copilot_model_api_mode(model_name, api_key=api_key)
if inferred:
return inferred
except Exception:
return "chat_completions"
if configured_mode and _provider_supports_explicit_api_mode("copilot", configured_provider):
return configured_mode

if configured_mode and _provider_supports_explicit_api_mode("copilot", configured_provider):
return configured_mode
return "chat_completions"


_VALID_API_MODES = {
Expand Down Expand Up @@ -340,7 +355,11 @@ def _resolve_runtime_from_pool_entry(
elif provider == "nous":
api_mode = "chat_completions"
elif provider == "copilot":
api_mode = _copilot_runtime_api_mode(model_cfg, getattr(entry, "runtime_api_key", ""))
api_mode = _copilot_runtime_api_mode(
model_cfg,
getattr(entry, "runtime_api_key", ""),
target_model=effective_model,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please pass the original target_model here, not effective_model. effective_model falls back to model_cfg["default"], so this is non-null even when the caller supplied no target; that bypasses the helper's new configured-api_mode preservation branch and changes normal pool resolution behavior.

)
base_url = base_url or PROVIDER_REGISTRY["copilot"].inference_base_url
elif provider == "azure-foundry":
# Azure Foundry: read api_mode and base_url from config
Expand Down Expand Up @@ -1058,6 +1077,7 @@ def _resolve_explicit_runtime(
model_cfg: Dict[str, Any],
explicit_api_key: Optional[str] = None,
explicit_base_url: Optional[str] = None,
target_model: Optional[str] = None,
) -> Optional[Dict[str, Any]]:
explicit_api_key = str(explicit_api_key or "").strip()
explicit_base_url = str(explicit_base_url or "").strip().rstrip("/")
Expand Down Expand Up @@ -1171,7 +1191,7 @@ def _resolve_explicit_runtime(

api_mode = "chat_completions"
if provider == "copilot":
api_mode = _copilot_runtime_api_mode(model_cfg, api_key)
api_mode = _copilot_runtime_api_mode(model_cfg, api_key, target_model=target_model)
elif provider == "xai":
api_mode = "codex_responses"
else:
Expand Down Expand Up @@ -1272,6 +1292,7 @@ def resolve_runtime_provider(
model_cfg=model_cfg,
explicit_api_key=explicit_api_key,
explicit_base_url=explicit_base_url,
target_model=target_model,
)
if explicit_runtime:
return explicit_runtime
Expand Down Expand Up @@ -1613,7 +1634,11 @@ def resolve_runtime_provider(
base_url = cfg_base_url or creds.get("base_url", "").rstrip("/")
api_mode = "chat_completions"
if provider == "copilot":
api_mode = _copilot_runtime_api_mode(model_cfg, creds.get("api_key", ""))
api_mode = _copilot_runtime_api_mode(
model_cfg,
creds.get("api_key", ""),
target_model=target_model,
)
elif provider == "xai":
api_mode = "codex_responses"
else:
Expand Down
106 changes: 106 additions & 0 deletions tests/hermes_cli/test_runtime_provider_resolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -2701,3 +2701,109 @@ def test_host_derived_key_helper_basic_cases():
for k in ("DEEPSEEK_API_KEY", "GROQ_API_KEY", "MISTRAL_API_KEY",
"OPENAI_API_KEY", "OPENROUTER_API_KEY"):
_os.environ.pop(k, None)


def test_copilot_api_mode_recomputes_from_target_model_even_with_matching_config(monkeypatch):
"""A Copilot /model switch must not let stale persisted api_mode win.

Repro shape: config/default is GPT-5.x with codex_responses, active target
is Claude via Copilot. The active target model must drive endpoint mode.
"""
model_cfg = {
"provider": "copilot",
"api_mode": "codex_responses",
"default": "gpt-5.5",
}

def fake_copilot_model_api_mode(model_name, api_key=None):
return "chat_completions" if "claude" in model_name else "codex_responses"

monkeypatch.setattr("hermes_cli.models.copilot_model_api_mode", fake_copilot_model_api_mode)

assert (
rp._copilot_runtime_api_mode(
model_cfg,
api_key="gho_fake",
target_model="claude-opus-4.7-1m-internal",
)
== "chat_completions"
)


def test_resolve_runtime_provider_threads_target_model_to_copilot_explicit_path(monkeypatch):
"""The non-pool Copilot resolver path must also use target_model."""
monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "copilot")
monkeypatch.setattr(
rp,
"_get_model_config",
lambda: {
"provider": "copilot",
"api_mode": "codex_responses",
"default": "gpt-5.5",
},
)
monkeypatch.setattr(
rp,
"resolve_api_key_provider_credentials",
lambda provider: {
"api_key": "gho_fake",
"base_url": "https://api.githubcopilot.com",
"source": "env:COPILOT_GITHUB_TOKEN",
},
)

def fake_copilot_model_api_mode(model_name, api_key=None):
return "chat_completions" if "claude" in model_name else "codex_responses"

monkeypatch.setattr("hermes_cli.models.copilot_model_api_mode", fake_copilot_model_api_mode)

resolved = rp.resolve_runtime_provider(
requested="copilot",
target_model="claude-opus-4.7-1m-internal",
)

assert resolved["provider"] == "copilot"
assert resolved["api_mode"] == "chat_completions"


def test_resolve_runtime_provider_threads_target_model_to_copilot_pool_path(monkeypatch):
"""The credential-pool Copilot resolver path must use target_model too."""
class _Entry:
runtime_api_key = "gho_fake"
access_token = "gho_fake"
source = "env:COPILOT_GITHUB_TOKEN"
base_url = "https://api.githubcopilot.com"

class _Pool:
def has_credentials(self):
return True

def select(self):
return _Entry()

monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "copilot")
monkeypatch.setattr(
rp,
"_get_model_config",
lambda: {
"provider": "copilot",
"api_mode": "codex_responses",
"default": "gpt-5.5",
},
)
monkeypatch.setattr(rp, "load_pool", lambda provider: _Pool())
# Force pool path instead of the explicit api-key provider path.
monkeypatch.setattr(rp, "_resolve_explicit_runtime", lambda **kwargs: None)

def fake_copilot_model_api_mode(model_name, api_key=None):
return "chat_completions" if "claude" in model_name else "codex_responses"

monkeypatch.setattr("hermes_cli.models.copilot_model_api_mode", fake_copilot_model_api_mode)

resolved = rp.resolve_runtime_provider(
requested="copilot",
target_model="claude-opus-4.7-1m-internal",
)

assert resolved["provider"] == "copilot"
assert resolved["api_mode"] == "chat_completions"