Skip to content

The agent that grows with you

test(copilot): follow credential code into the plugin; pin the generic seams

Tekniumaa2a4e676b49
diff --git a/tests/agent/test_auxiliary_main_first.py b/tests/agent/test_auxiliary_main_first.py
index 88957e233b2..4a3b4de8363 100644
--- a/tests/agent/test_auxiliary_main_first.py
+++ b/tests/agent/test_auxiliary_main_first.py
@@ -14,6 +14,9 @@ runs when the main provider has no working client.
from __future__ import annotations
from unittest.mock import MagicMock, patch
+import providers as _providers
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (credentials module)
+from plugins.model_providers.copilot import credentials as copilot_credentials
# ── Text aux tasks — _resolve_auto_route ──────────────────────────────────────────
@@ -414,8 +417,7 @@ class TestResolveVisionMainFirst:
"api_key": "copilot-api-token",
"base_url": "https://api.githubcopilot.com",
},
- ), patch(
- "hermes_cli.copilot_auth.copilot_request_headers",
+ ), patch.object(copilot_credentials, "copilot_request_headers",
side_effect=fake_headers,
):
mock_client = MagicMock()
@@ -451,8 +453,7 @@ class TestResolveVisionMainFirst:
"api_key": "copilot-api-token",
"base_url": "https://api.githubcopilot.com",
},
- ), patch(
- "hermes_cli.copilot_auth.copilot_request_headers",
+ ), patch.object(copilot_credentials, "copilot_request_headers",
side_effect=fake_headers,
):
mock_client = MagicMock()
diff --git a/tests/agent/test_credential_pool.py b/tests/agent/test_credential_pool.py
index ab8234d1448..417772cf9b6 100644
--- a/tests/agent/test_credential_pool.py
+++ b/tests/agent/test_credential_pool.py
@@ -8,6 +8,9 @@ import time
from datetime import datetime, timezone, UTC
import pytest
+import providers as _providers
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (credentials module)
+from plugins.model_providers.copilot import credentials as copilot_credentials
def _write_auth_store(tmp_path, payload: dict) -> None:
@@ -1391,8 +1394,7 @@ def test_load_pool_seeds_copilot_via_gh_auth_token(tmp_path, monkeypatch):
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
_write_auth_store(tmp_path, {"version": 1, "credential_pool": {}})
- monkeypatch.setattr(
- "hermes_cli.copilot_auth.resolve_copilot_token",
+ monkeypatch.setattr(copilot_credentials, "resolve_copilot_token",
lambda: ("gho_fake_token_abc123", "gh auth token"),
)
@@ -1427,8 +1429,7 @@ def test_load_pool_skips_exchange_for_suppressed_copilot(tmp_path, monkeypatch):
},
)
- monkeypatch.setattr(
- "hermes_cli.copilot_auth.resolve_copilot_token",
+ monkeypatch.setattr(copilot_credentials, "resolve_copilot_token",
lambda: ("gho_fake_token_abc123", "gh auth token"),
)
@@ -1439,8 +1440,7 @@ def test_load_pool_skips_exchange_for_suppressed_copilot(tmp_path, monkeypatch):
exchange_called = True
raise AssertionError("exchange must not run for a suppressed source")
- monkeypatch.setattr(
- "hermes_cli.copilot_auth.get_copilot_api_token",
+ monkeypatch.setattr(copilot_credentials, "get_copilot_api_token",
_boom,
)
@@ -1470,8 +1470,7 @@ def test_load_pool_respects_env_var_copilot_suppression(tmp_path, monkeypatch):
},
)
- monkeypatch.setattr(
- "hermes_cli.copilot_auth.resolve_copilot_token",
+ monkeypatch.setattr(copilot_credentials, "resolve_copilot_token",
lambda: ("gho_fake_token_env", "GH_TOKEN"),
)
@@ -1482,8 +1481,7 @@ def test_load_pool_respects_env_var_copilot_suppression(tmp_path, monkeypatch):
exchange_called = True
raise AssertionError("exchange must not run for a suppressed env source")
- monkeypatch.setattr(
- "hermes_cli.copilot_auth.get_copilot_api_token",
+ monkeypatch.setattr(copilot_credentials, "get_copilot_api_token",
_boom,
)
@@ -1510,12 +1508,10 @@ def test_load_pool_gh_cli_suppression_does_not_block_env_tokens(tmp_path, monkey
},
)
- monkeypatch.setattr(
- "hermes_cli.copilot_auth.resolve_copilot_token",
+ monkeypatch.setattr(copilot_credentials, "resolve_copilot_token",
lambda: ("gho_fake_token_env", "GH_TOKEN"),
)
- monkeypatch.setattr(
- "hermes_cli.copilot_auth.get_copilot_api_token",
+ monkeypatch.setattr(copilot_credentials, "get_copilot_api_token",
lambda token: ("capi_exchanged_token", None),
)
@@ -1529,7 +1525,7 @@ def test_load_pool_skips_resolve_when_all_copilot_sources_suppressed(tmp_path, m
"""With every copilot source suppressed, resolve_copilot_token (which
shells out to ``gh auth token``) must not run at all."""
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
- from hermes_cli.copilot_auth import COPILOT_ENV_VARS
+ from plugins.model_providers.copilot.credentials import COPILOT_ENV_VARS
_write_auth_store(
tmp_path,
{
@@ -1544,7 +1540,7 @@ def test_load_pool_skips_resolve_when_all_copilot_sources_suppressed(tmp_path, m
def _boom():
raise AssertionError("resolve_copilot_token must not run when all sources are suppressed")
- monkeypatch.setattr("hermes_cli.copilot_auth.resolve_copilot_token", _boom)
+ monkeypatch.setattr(copilot_credentials, "resolve_copilot_token", _boom)
from agent.credential_pool import load_pool
pool = load_pool("copilot")
@@ -1560,16 +1556,17 @@ def test_load_pool_copilot_exchange_only_when_selected_and_warns_once(tmp_path,
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
_write_auth_store(tmp_path, {"version": 1, "credential_pool": {}})
- from agent.credential_pool import _reset_copilot_raw_degradation_warned, load_pool
- _reset_copilot_raw_degradation_warned()
- monkeypatch.setattr("hermes_cli.copilot_auth.resolve_copilot_token", lambda: ("gho_raw_initial", "gh auth token"))
+ from agent.credential_pool import load_pool
+ from plugins.model_providers.copilot.credentials import _reset_raw_degradation_warned
+ _reset_raw_degradation_warned()
+ monkeypatch.setattr(copilot_credentials, "resolve_copilot_token", lambda: ("gho_raw_initial", "gh auth token"))
exchanges = []
def degraded_exchange(token):
exchanges.append(token)
return token, None # exchange unavailable -> RAW token, no enterprise URL
- monkeypatch.setattr("hermes_cli.copilot_auth.get_copilot_api_token", degraded_exchange)
+ monkeypatch.setattr(copilot_credentials, "get_copilot_api_token", degraded_exchange)
def degradation_warnings():
return [r for r in caplog.records if "Copilot token exchange degraded to RAW token" in r.message]
@@ -1594,7 +1591,7 @@ def test_load_pool_copilot_exchange_only_when_selected_and_warns_once(tmp_path,
assert len(exchanges) == 2 and len(degradation_warnings()) == 1
# A different token is a different degradation: warned again, once.
- monkeypatch.setattr("hermes_cli.copilot_auth.resolve_copilot_token", lambda: ("gho_raw_rotated", "gh auth token"))
+ monkeypatch.setattr(copilot_credentials, "resolve_copilot_token", lambda: ("gho_raw_rotated", "gh auth token"))
load_pool("copilot")
assert len(degradation_warnings()) == 2
diff --git a/tests/agent/test_image_shrink_recovery.py b/tests/agent/test_image_shrink_recovery.py
index 5f51c14c82d..6bf0f7a7540 100644
--- a/tests/agent/test_image_shrink_recovery.py
+++ b/tests/agent/test_image_shrink_recovery.py
@@ -191,12 +191,12 @@ class TestSpentShrinkFallsBack:
agent = self._Agent()
err = _FakeApiError(400, "Please make sure your payload is below 26214400 bytes in size.")
retry = SimpleNamespace(
- image_shrink_retry_attempted=shrink_attempted, copilot_stale_cred_retry_attempted=False,
+ image_shrink_retry_attempted=shrink_attempted, provider_stale_refresh_attempted=False,
primary_recovery_attempted=False, restart_with_redirected_messages=False,
)
classified = classify_api_error(err, provider="custom")
assert classified.reason == FailoverReason.image_too_large
- with patch("agent.conversation_loop._is_copilot_provider", lambda a: False), patch(
+ with patch("agent.conversation_loop._credential_refresh_profile", lambda a: None), patch(
"agent.conversation_loop._arm_fallback_restart", lambda agent, msgs, prompt, retry: prompt
), patch("agent.turn_api_error.compute_error_backoff", lambda *a, **k: 0), patch(
"agent.turn_api_error.interruptible_backoff_sleep", lambda *a, **k: None
diff --git a/tests/agent/test_malformed_tool_args_no_fallback.py b/tests/agent/test_malformed_tool_args_no_fallback.py
index 985f5ce53dc..d3ffb81ddef 100644
--- a/tests/agent/test_malformed_tool_args_no_fallback.py
+++ b/tests/agent/test_malformed_tool_args_no_fallback.py
@@ -56,9 +56,9 @@ class _Agent:
def _settle(agent, err, provider, status_code):
- retry = SimpleNamespace(copilot_stale_cred_retry_attempted=False, primary_recovery_attempted=False)
+ retry = SimpleNamespace(provider_stale_refresh_attempted=False, primary_recovery_attempted=False)
classified = classify_api_error(err, provider=provider)
- with patch("agent.conversation_loop._is_copilot_provider", lambda a: False):
+ with patch("agent.conversation_loop._credential_refresh_profile", lambda a: None):
return settle_unrecovered_error(
agent, api_error=err, classified=classified, _retry=retry, status_code=status_code, error_msg=str(err),
is_context_length_error=False, is_rate_limited=False, _is_zai_coding_overload=False,
diff --git a/tests/agent/test_private_credential_writers.py b/tests/agent/test_private_credential_writers.py
index 268b1aae3a4..47a02978deb 100644
--- a/tests/agent/test_private_credential_writers.py
+++ b/tests/agent/test_private_credential_writers.py
@@ -17,7 +17,9 @@ import sys
from pathlib import Path
import pytest
-
+import providers as _providers
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (credentials module)
+from plugins.model_providers.copilot import credentials as copilot_credentials
pytestmark = pytest.mark.platforms("posix") # POSIX mode bits not enforced on Windows
_PRIVATE = stat.S_IRUSR | stat.S_IWUSR
@@ -48,7 +50,7 @@ def _writers(home: Path, monkeypatch):
from agent.proxy_sources import iron_proxy
from agent.vault_store import VaultStore
from gateway import pairing
- from hermes_cli import auth as auth_mod, copilot_auth
+ from hermes_cli import auth as auth_mod
from hermes_cli import process_identity
from tools import mcp_oauth
from plugins.google_meet.node.server import NodeServer
@@ -71,8 +73,8 @@ def _writers(home: Path, monkeypatch):
("secret-source cache", lambda: cache.write("k", CachedFetch(secrets={"A": "b"}, fetched_at=1.0), 60, home),
cache.path(home)),
("iron-proxy mappings", lambda: iron_proxy.write_mappings([]), home / "proxy" / "mappings.json"),
- ("exchanged JWT store", lambda: copilot_auth._save_jwt_to_disk("fp", "jwt", 9e12, None),
- copilot_auth._jwt_disk_path()),
+ ("exchanged JWT store", lambda: copilot_credentials._save_jwt_to_disk("fp", "jwt", 9e12, None),
+ copilot_credentials._jwt_disk_path()),
("photon sidecar record", lambda: photon_adapter._write_runtime_record(1, "tok", 2), photon_record),
("pairing", lambda: pairing._save_json_file(home / "pairing" / "p.json", {"a": 1}), home / "pairing" / "p.json"),
("vault blob", lambda: vault._write_all([]), vault._vault_path),
diff --git a/tests/agent/test_provider_credential_seams.py b/tests/agent/test_provider_credential_seams.py
new file mode 100644
index 00000000000..527a8291aa4
--- /dev/null
+++ b/tests/agent/test_provider_credential_seams.py
@@ -0,0 +1,79 @@
+"""Generic credential seams on ``ProviderProfile``: a profile that seeds, removes and re-mints its own
+credentials is honoured by core with no provider name in core, and a plain profile keeps the generic path."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import providers
+from providers.base import ProviderProfile
+
+
+class _OwnCreds(ProviderProfile):
+ def seed_pool_credentials(self, *, is_suppressed, explicitly_configured):
+ return [] if is_suppressed("env:ACME_TOKEN") else [
+ {"source": "env:ACME_TOKEN", "access_token": "minted", "base_url": None, "label": "ACME_TOKEN"}]
+
+ def remove_credential_source(self, source):
+ return (("env:ACME_TOKEN", "acme_cli"), ("both gone",)) if source.startswith("env:") else None
+
+ def refresh_runtime_credentials(self, *, reason):
+ return ("fresh", None) if reason == "unauthorized" else None
+
+ def request_rejection_hint(self, *, status_code, base_url):
+ return ("capped",) if status_code == 413 and "acme.example" in base_url else ()
+
+
+_ACME = _OwnCreds(name="acme", base_url="https://api.acme.example/v1")
+_PLAIN = ProviderProfile(name="plain", base_url="https://api.plain.example/v1")
+
+
+def _registry(monkeypatch):
+ profiles = {"acme": _ACME, "plain": _PLAIN}
+ monkeypatch.setattr(providers, "get_provider_profile", lambda name: profiles.get(name))
+ monkeypatch.setattr(providers, "list_providers", lambda: list(profiles.values()))
+
+
+def test_profile_seeded_rows_land_in_the_pool_and_skip_the_generic_env_loop(monkeypatch):
+ from agent import credential_pool as cp
+
+ _registry(monkeypatch)
+ monkeypatch.setattr(cp, "_is_source_suppressed_fn", lambda: lambda provider, source: False)
+ entries: list = []
+ cp._seed_from_singletons("acme", entries)
+ assert [(e.source, e.access_token) for e in entries] == [("env:ACME_TOKEN", "minted")]
+ assert cp._profile_seeds_pool("acme") is True
+ assert cp._profile_seeds_pool("plain") is False
+
+
+def test_profile_claimed_removal_suppresses_every_variant(monkeypatch):
+ from hermes_cli import auth
+ from agent.credential_sources import find_removal_step
+
+ _registry(monkeypatch)
+ suppressed: list = []
+ monkeypatch.setattr(auth, "suppress_credential_source", lambda p, s: suppressed.append((p, s)))
+ step = find_removal_step("acme", "env:ACME_TOKEN")
+ result = step.remove_fn("acme", SimpleNamespace(source="env:ACME_TOKEN"))
+ assert suppressed == [("acme", "env:ACME_TOKEN"), ("acme", "acme_cli")]
+ assert result.hints == ["both gone"]
+ # An unclaimed source keeps the generic registry step.
+ assert find_removal_step("plain", "env:PLAIN_KEY").source_id == "env:"
+
+
+def test_runtime_refresh_owner_is_found_by_name_or_by_host_of_a_custom_route(monkeypatch):
+ from agent.conversation_loop import _credential_refresh_profile
+
+ _registry(monkeypatch)
+ assert _credential_refresh_profile(SimpleNamespace(provider="acme", base_url="")) is _ACME
+ assert _credential_refresh_profile(SimpleNamespace(provider="custom", base_url="https://api.acme.example/v1")) is _ACME
+ # A profile that does not re-mint credentials never owns a refresh.
+ assert _credential_refresh_profile(SimpleNamespace(provider="plain", base_url="https://api.plain.example")) is None
+
+
+def test_endpoint_rejection_hint_reaches_any_route(monkeypatch):
+ from agent.turn_overflow import _request_rejection_hint
+
+ _registry(monkeypatch)
+ assert _request_rejection_hint(413, "https://api.acme.example/v1") == ("capped",)
+ assert _request_rejection_hint(400, "https://api.acme.example/v1") == ()
diff --git a/tests/agent/test_reasoning_disable_recovery.py b/tests/agent/test_reasoning_disable_recovery.py
index eacf2936ec1..8f50a8c4a57 100644
--- a/tests/agent/test_reasoning_disable_recovery.py
+++ b/tests/agent/test_reasoning_disable_recovery.py
@@ -61,10 +61,10 @@ def _settle(disable_drop_attempted):
assert classified.reason == FailoverReason.reasoning_mandatory
retry = SimpleNamespace(
reasoning_mandatory_retry_attempted=disable_drop_attempted, image_shrink_retry_attempted=False,
- copilot_stale_cred_retry_attempted=False, primary_recovery_attempted=False,
+ provider_stale_refresh_attempted=False, primary_recovery_attempted=False,
restart_with_redirected_messages=False,
)
- with patch("agent.conversation_loop._is_copilot_provider", lambda a: False), patch(
+ with patch("agent.conversation_loop._credential_refresh_profile", lambda a: None), patch(
"agent.conversation_loop._arm_fallback_restart", lambda agent, msgs, prompt, retry: prompt
), patch("agent.turn_api_error.compute_error_backoff", lambda *a, **k: 0), patch(
"agent.turn_api_error.interruptible_backoff_sleep", lambda *a, **k: None
diff --git a/tests/agent/test_retry_exhaustion_partial_retention.py b/tests/agent/test_retry_exhaustion_partial_retention.py
index be6529bcc28..27b6590cdcf 100644
--- a/tests/agent/test_retry_exhaustion_partial_retention.py
+++ b/tests/agent/test_retry_exhaustion_partial_retention.py
@@ -77,8 +77,8 @@ def test_terminal_error_keeps_partial_and_collapses_this_turns_trail(status, mes
messages = _messages_with_fragment()
error = _Http(status, message)
classified = classify_api_error(error, provider="openrouter", model="m")
- retry = SimpleNamespace(copilot_stale_cred_retry_attempted=False, primary_recovery_attempted=True)
- with patch("agent.conversation_loop._is_copilot_provider", lambda a: False), \
+ retry = SimpleNamespace(provider_stale_refresh_attempted=False, primary_recovery_attempted=True)
+ with patch("agent.conversation_loop._credential_refresh_profile", lambda a: None), \
patch("agent.turn_recovery_autorecover.auto_recover_after_exhaustion", lambda *a, **k: None):
verdict = settle_unrecovered_error(
_Agent(), api_error=error, classified=classified, _retry=retry, status_code=status,
diff --git a/tests/agent/test_run_agent_codex_responses.py b/tests/agent/test_run_agent_codex_responses.py
index 5f7f64351cd..c01be7e2db7 100644
--- a/tests/agent/test_run_agent_codex_responses.py
+++ b/tests/agent/test_run_agent_codex_responses.py
@@ -11,6 +11,9 @@ sys.modules.setdefault("fal_client", types.SimpleNamespace())
import run_agent
from agent.conversation_loop import _CODEX_INCOMPLETE_NUDGE
+import providers as _providers
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (credentials module)
+from plugins.model_providers.copilot import credentials as copilot_credentials
@pytest.fixture(autouse=True)
@@ -1547,24 +1550,21 @@ def test_try_refresh_copilot_client_credentials_rebuilds_client(monkeypatch):
rebuilt["kwargs"] = kwargs
return _RebuiltClient()
- monkeypatch.setattr(
- "hermes_cli.copilot_auth.resolve_copilot_token",
+ monkeypatch.setattr(copilot_credentials, "resolve_copilot_token",
lambda: ("gho_new_token", "GH_TOKEN"),
)
# The 401 refresh forces a fresh IDE-token exchange; mock it to a valid
# exchanged token so the test is deterministic and network-free.
- monkeypatch.setattr(
- "hermes_cli.copilot_auth.evict_cached_exchanged_token",
+ monkeypatch.setattr(copilot_credentials, "evict_cached_exchanged_token",
lambda _raw: None,
)
- monkeypatch.setattr(
- "hermes_cli.copilot_auth.get_copilot_api_token",
+ monkeypatch.setattr(copilot_credentials, "get_copilot_api_token",
lambda _raw: ("tid=exchanged-ide-token", None),
)
monkeypatch.setattr("agent.process_bootstrap.OpenAI", _fake_openai)
agent.client = _ExistingClient()
- ok = agent._try_refresh_copilot_client_credentials()
+ ok = agent._try_refresh_provider_runtime_credentials(reason="unauthorized")
assert ok is True
# The old client is retired by _replace_primary_openai_client (release is
@@ -1594,18 +1594,16 @@ def test_try_refresh_copilot_client_credentials_falls_back_when_exchange_unavail
def _boom(_raw):
raise RuntimeError("exchange endpoint unreachable")
- monkeypatch.setattr(
- "hermes_cli.copilot_auth.resolve_copilot_token",
+ monkeypatch.setattr(copilot_credentials, "resolve_copilot_token",
lambda: ("gho_raw_token", "GH_TOKEN"),
)
- monkeypatch.setattr(
- "hermes_cli.copilot_auth.evict_cached_exchanged_token",
+ monkeypatch.setattr(copilot_credentials, "evict_cached_exchanged_token",
lambda _raw: None,
)
- monkeypatch.setattr("hermes_cli.copilot_auth.get_copilot_api_token", _boom)
+ monkeypatch.setattr(copilot_credentials, "get_copilot_api_token", _boom)
monkeypatch.setattr("agent.process_bootstrap.OpenAI", _fake_openai)
- ok = agent._try_refresh_copilot_client_credentials()
+ ok = agent._try_refresh_provider_runtime_credentials(reason="unauthorized")
assert ok is True
# Exchange failed → falls back to the resolved raw token, client still rebuilt.
diff --git a/tests/agent/test_turn_recovery_autorecover.py b/tests/agent/test_turn_recovery_autorecover.py
index 9a402041c96..16b805d126f 100644
--- a/tests/agent/test_turn_recovery_autorecover.py
+++ b/tests/agent/test_turn_recovery_autorecover.py
@@ -73,7 +73,7 @@ class _Agent:
def _settle(agent, err, retry=None):
retry = retry or TurnRetryState(primary_recovery_attempted=True)
classified = classify_api_error(err, provider=agent.provider)
- with patch("agent.conversation_loop._is_copilot_provider", lambda a: False), \
+ with patch("agent.conversation_loop._credential_refresh_profile", lambda a: None), \
patch("agent.conversation_loop._arm_fallback_restart", lambda a, m, s, r: s), \
patch("agent.turn_recovery.interruptible_backoff_sleep", lambda agent, *a, **k: agent.sleep_outcome), \
patch("agent.turn_api_error.max_retries_exhausted_result", lambda *a, **k: {"failed": True}), \
diff --git a/tests/agent/test_turn_retry_state.py b/tests/agent/test_turn_retry_state.py
index 044d7128621..a8cee695a48 100644
--- a/tests/agent/test_turn_retry_state.py
+++ b/tests/agent/test_turn_retry_state.py
@@ -1,34 +1,23 @@
-"""Copilot provider detection used by the turn-retry recovery gates."""
+"""Provider detection used by the turn-retry credential-refresh gates."""
from __future__ import annotations
+from types import SimpleNamespace
+
def test_copilot_provider_check_accepts_alias_spellings():
"""`/model` and profile configs can leave `github-copilot` / `github` as
the provider spelling; the recovery gates must not silently skip them."""
- from agent.conversation_loop import _is_copilot_provider
- from run_agent import AIAgent
-
- class _Agent:
- # Reuse the real single-owner check unbound; only provider/_base_url
- # state is faked.
- _is_copilot_provider = AIAgent._is_copilot_provider
- _is_copilot_url = AIAgent._is_copilot_url
+ from agent.conversation_loop import _credential_refresh_profile
- def __init__(self, provider, base_url=""):
- self.provider = provider
- self._base_url_lower = base_url.lower()
+ def _owner(provider, base_url=""):
+ profile = _credential_refresh_profile(SimpleNamespace(provider=provider, base_url=base_url))
+ return profile.name if profile else None
- assert _is_copilot_provider(_Agent("copilot"))
- assert _is_copilot_provider(_Agent("github-copilot"))
- assert _is_copilot_provider(_Agent("GitHub-Copilot"))
- assert _is_copilot_provider(_Agent("github"))
+ assert _owner("copilot") == "copilot"
+ assert _owner("github-copilot") == "copilot"
+ assert _owner("GitHub-Copilot") == "copilot"
+ assert _owner("github") == "copilot"
# URL fallback: unnormalized provider but a Copilot base URL.
- assert _is_copilot_provider(_Agent("custom", "https://api.githubcopilot.com"))
- assert not _is_copilot_provider(_Agent("openrouter", "https://openrouter.ai/api/v1"))
-
- class _NoMethod:
- provider = "github-copilot"
-
- # Fallback path when the agent object lacks the method entirely.
- assert _is_copilot_provider(_NoMethod())
+ assert _owner("custom", "https://api.githubcopilot.com") == "copilot"
+ assert _owner("openrouter", "https://openrouter.ai/api/v1") is None
diff --git a/tests/hermes_cli/test_api_key_providers.py b/tests/hermes_cli/test_api_key_providers.py
index a9168d196dc..848c72d3995 100644
--- a/tests/hermes_cli/test_api_key_providers.py
+++ b/tests/hermes_cli/test_api_key_providers.py
@@ -15,7 +15,7 @@ from hermes_cli.auth import (
STEPFUN_STEP_PLAN_INTL_BASE_URL,
_resolve_kimi_base_url,
)
-from hermes_cli.copilot_auth import _try_gh_cli_token
+from plugins.model_providers.copilot.credentials import _try_gh_cli_token
# =============================================================================
@@ -32,6 +32,9 @@ from hermes_cli.copilot_auth import _try_gh_cli_token
# missing HF_TOKEN/DEEPINFRA_API_KEY, which made the auto-detection tests
# env-dependent (they failed on any machine with HF_TOKEN exported).
from hermes_cli.auth import PROVIDER_REGISTRY as _REGISTRY
+import providers as _providers
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (credentials module)
+from plugins.model_providers.copilot import credentials as copilot_credentials
_EXTRA_ENV_VARS = (
# Checked directly in resolve_provider("auto"), not via the registry.
@@ -191,7 +194,7 @@ class TestResolveApiKeyProviderCredentials:
def test_try_gh_cli_token_uses_homebrew_path_when_not_on_path(self, monkeypatch, tmp_path):
- from hermes_cli.copilot_auth import _invalidate_gh_cli_token_cache
+ from plugins.model_providers.copilot.credentials import _invalidate_gh_cli_token_cache
from hermes_platform.resolver import known_dirs
_invalidate_gh_cli_token_cache()
@@ -214,7 +217,7 @@ class TestResolveApiKeyProviderCredentials:
calls.append(cmd)
return _Result()
- monkeypatch.setattr("hermes_cli.copilot_auth.subprocess.run", _fake_run)
+ monkeypatch.setattr(copilot_credentials.subprocess, "run", _fake_run)
assert _try_gh_cli_token() == "gh-cli-secret"
assert calls == [[str(gh), "auth", "token"]]
@@ -260,7 +263,7 @@ class TestRuntimeProviderResolution:
assert result["api_key"] == "auto-kimi-key"
def test_runtime_copilot_uses_gh_cli_token(self, monkeypatch):
- monkeypatch.setattr("hermes_cli.copilot_auth._try_gh_cli_token", lambda: "gho_cli_secret")
+ monkeypatch.setattr(copilot_credentials, "_try_gh_cli_token", lambda: "gho_cli_secret")
from hermes_cli.runtime_provider import resolve_runtime_provider
result = resolve_runtime_provider(requested="copilot")
assert result["provider"] == "copilot"
@@ -269,7 +272,7 @@ class TestRuntimeProviderResolution:
assert result["base_url"] == "https://api.githubcopilot.com"
def test_runtime_copilot_uses_responses_for_gpt_5_4(self, monkeypatch):
- monkeypatch.setattr("hermes_cli.copilot_auth._try_gh_cli_token", lambda: "gho_cli_secret")
+ monkeypatch.setattr(copilot_credentials, "_try_gh_cli_token", lambda: "gho_cli_secret")
monkeypatch.setattr(
"hermes_cli.runtime_provider._get_model_config",
lambda: {"provider": "copilot", "default": "gpt-5.4"},
@@ -324,7 +327,7 @@ class TestHasAnyProviderConfigured:
hermes_home.mkdir()
monkeypatch.setattr(config_module, "get_env_path", lambda: hermes_home / ".env")
monkeypatch.setattr(config_module, "get_hermes_home", lambda: hermes_home)
- monkeypatch.setattr("hermes_cli.copilot_auth.resolve_copilot_token", lambda: ("", ""))
+ monkeypatch.setattr(copilot_credentials, "resolve_copilot_token", lambda: ("", ""))
# Clear all provider env vars so earlier checks don't short-circuit
_all_vars = {"OPENROUTER_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY",
"ANTHROPIC_TOKEN", "OPENAI_BASE_URL"}
diff --git a/tests/hermes_cli/test_auth_commands.py b/tests/hermes_cli/test_auth_commands.py
index cd24f8c5cf1..e03d01c5331 100644
--- a/tests/hermes_cli/test_auth_commands.py
+++ b/tests/hermes_cli/test_auth_commands.py
@@ -9,6 +9,9 @@ from unittest.mock import patch
import pytest
import hermes_yaml as yaml
+import providers as _providers
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (credentials module)
+from plugins.model_providers.copilot import credentials as copilot_credentials
def _write_auth_store(tmp_path, payload: dict) -> None:
@@ -937,11 +940,9 @@ def test_auth_remove_copilot_suppresses_all_variants(tmp_path, monkeypatch):
from hermes_cli.auth import is_source_suppressed
from hermes_cli.auth_commands import auth_remove_command
- with patch(
- "hermes_cli.copilot_auth.resolve_copilot_token",
+ with patch.object(copilot_credentials, "resolve_copilot_token",
return_value=("ghp_fake", "gh"),
- ), patch(
- "hermes_cli.copilot_auth.get_copilot_api_token",
+ ), patch.object(copilot_credentials, "get_copilot_api_token",
return_value=("ghu_fake_api", None),
):
auth_remove_command(SimpleNamespace(provider="copilot", target="1"))
diff --git a/tests/hermes_cli/test_copilot_catalog_oauth_fallback.py b/tests/hermes_cli/test_copilot_catalog_oauth_fallback.py
index 141fb2fdb66..85e83bac4a2 100644
--- a/tests/hermes_cli/test_copilot_catalog_oauth_fallback.py
+++ b/tests/hermes_cli/test_copilot_catalog_oauth_fallback.py
@@ -13,6 +13,9 @@ credential pool.
from unittest.mock import patch
from hermes_cli.models import _resolve_copilot_catalog_api_key
+import providers as _providers
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (credentials module)
+from plugins.model_providers.copilot import credentials as copilot_credentials
class TestCopilotCatalogApiKeyResolution:
@@ -25,8 +28,7 @@ class TestCopilotCatalogApiKeyResolution:
), patch(
"hermes_cli.auth.read_credential_pool",
return_value=[{"access_token": "gho_abc123"}],
- ), patch(
- "hermes_cli.copilot_auth.exchange_copilot_token",
+ ), patch.object(copilot_credentials, "exchange_copilot_token",
return_value=("tid_exchanged_xyz", 1234567890.0),
):
assert _resolve_copilot_catalog_api_key() == "tid_exchanged_xyz"
@@ -54,8 +56,7 @@ class TestCopilotCatalogApiKeyResolution:
{"access_token": "gho_unsupported_account"},
{"access_token": "gho_valid_token"},
],
- ), patch(
- "hermes_cli.copilot_auth.exchange_copilot_token",
+ ), patch.object(copilot_credentials, "exchange_copilot_token",
side_effect=fake_exchange,
):
assert _resolve_copilot_catalog_api_key() == "tid_from_second"
diff --git a/tests/hermes_cli/test_credential_pool_off_loop.py b/tests/hermes_cli/test_credential_pool_off_loop.py
index f53c0dc889e..b1683e7e36a 100644
--- a/tests/hermes_cli/test_credential_pool_off_loop.py
+++ b/tests/hermes_cli/test_credential_pool_off_loop.py
@@ -15,8 +15,10 @@ from unittest.mock import patch
import pytest
-from hermes_cli import copilot_auth
import hermes_cli.web_routers.ops as _rt_ops
+import providers as _providers
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (credentials module)
+from plugins.model_providers.copilot import credentials as copilot_credentials
# ---------------------------------------------------------------------------
# _urlopen_bounded
@@ -27,13 +29,13 @@ class TestUrlopenBounded:
def test_reraises_worker_exception(self):
with patch("urllib.request.urlopen", side_effect=OSError("boom")):
with pytest.raises(OSError, match="boom"):
- copilot_auth._urlopen_bounded("req", 1.0)
+ copilot_credentials._urlopen_bounded("req", 1.0)
def test_hard_cap_fires_on_hung_resolver_and_closes_late_response(self, monkeypatch):
"""A urlopen that hangs past timeout + grace must raise TimeoutError
promptly, and when the abandoned worker later *succeeds* it must close
the response instead of leaking the socket."""
- monkeypatch.setattr(copilot_auth, "_DNS_GRACE_SECONDS", 0.05)
+ monkeypatch.setattr(copilot_credentials, "_DNS_GRACE_SECONDS", 0.05)
release = threading.Event()
closed = threading.Event()
@@ -48,7 +50,7 @@ class TestUrlopenBounded:
with patch("urllib.request.urlopen", side_effect=hung_urlopen):
started = time.monotonic()
with pytest.raises(TimeoutError, match="hard cap"):
- copilot_auth._urlopen_bounded("req", 0.05)
+ copilot_credentials._urlopen_bounded("req", 0.05)
elapsed = time.monotonic() - started
assert elapsed < 2.0
release.set()
@@ -62,19 +64,19 @@ class TestExchangeSingleFlight:
@pytest.fixture(autouse=True)
def _clean_caches(self, monkeypatch, tmp_path):
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- copilot_auth._jwt_cache.clear()
- copilot_auth._exchange_failure_cache.clear()
- copilot_auth._exchange_locks.clear()
+ copilot_credentials._jwt_cache.clear()
+ copilot_credentials._exchange_failure_cache.clear()
+ copilot_credentials._exchange_locks.clear()
yield
- copilot_auth._jwt_cache.clear()
- copilot_auth._exchange_failure_cache.clear()
- copilot_auth._exchange_locks.clear()
+ copilot_credentials._jwt_cache.clear()
+ copilot_credentials._exchange_failure_cache.clear()
+ copilot_credentials._exchange_locks.clear()
def test_concurrent_callers_share_one_exchange(self, monkeypatch):
"""N concurrent callers for the same token must perform ONE network
exchange; the rest wait on the lock and hit the populated cache."""
- monkeypatch.setattr(copilot_auth, "_load_jwt_from_disk", lambda fp: None)
- monkeypatch.setattr(copilot_auth, "_save_jwt_to_disk", lambda *a, **k: None)
+ monkeypatch.setattr(copilot_credentials, "_load_jwt_from_disk", lambda fp: None)
+ monkeypatch.setattr(copilot_credentials, "_save_jwt_to_disk", lambda *a, **k: None)
calls = []
gate = threading.Event()
@@ -93,11 +95,11 @@ class TestExchangeSingleFlight:
gate.wait(timeout=5) # hold the first exchange open while others queue
return _Resp()
- monkeypatch.setattr(copilot_auth, "_urlopen_bounded", fake_bounded)
+ monkeypatch.setattr(copilot_credentials, "_urlopen_bounded", fake_bounded)
results = []
threads = [
- threading.Thread(target=lambda: results.append(copilot_auth.exchange_copilot_token("ghu_" + "x" * 30)))
+ threading.Thread(target=lambda: results.append(copilot_credentials.exchange_copilot_token("ghu_" + "x" * 30)))
for _ in range(8)
]
for t in threads:
@@ -115,8 +117,8 @@ class TestExchangeSingleFlight:
def test_waiters_observe_negative_cache_after_failed_exchange(self, monkeypatch):
"""When the single in-flight exchange fails, queued callers must not
each start their own exchange — they see the negative cache."""
- monkeypatch.setattr(copilot_auth, "_load_jwt_from_disk", lambda fp: None)
- monkeypatch.setattr(copilot_auth, "_EXCHANGE_MAX_ATTEMPTS", 1)
+ monkeypatch.setattr(copilot_credentials, "_load_jwt_from_disk", lambda fp: None)
+ monkeypatch.setattr(copilot_credentials, "_EXCHANGE_MAX_ATTEMPTS", 1)
calls = []
gate = threading.Event()
@@ -125,12 +127,12 @@ class TestExchangeSingleFlight:
gate.wait(timeout=5)
raise TimeoutError("hard cap")
- monkeypatch.setattr(copilot_auth, "_urlopen_bounded", fake_bounded)
+ monkeypatch.setattr(copilot_credentials, "_urlopen_bounded", fake_bounded)
errors = []
def run():
try:
- copilot_auth.exchange_copilot_token("ghu_" + "y" * 30)
+ copilot_credentials.exchange_copilot_token("ghu_" + "y" * 30)
except ValueError as exc:
errors.append(str(exc))
@@ -150,14 +152,14 @@ class TestExchangeSingleFlight:
"""While one exchange holds the lock, a caller whose fingerprint is
already in the failure cache must raise immediately rather than park
an executor thread behind the holder."""
- fp = copilot_auth._token_fingerprint("ghu_" + "z" * 30)
- copilot_auth._exchange_failure_cache[fp] = time.time() + 60
- lock = copilot_auth._exchange_lock_for(fp)
+ fp = copilot_credentials._token_fingerprint("ghu_" + "z" * 30)
+ copilot_credentials._exchange_failure_cache[fp] = time.time() + 60
+ lock = copilot_credentials._exchange_lock_for(fp)
lock.acquire() # simulate an in-flight holder
try:
started = time.monotonic()
with pytest.raises(ValueError, match="recently failed"):
- copilot_auth.exchange_copilot_token("ghu_" + "z" * 30)
+ copilot_credentials.exchange_copilot_token("ghu_" + "z" * 30)
assert time.monotonic() - started < 0.5
finally:
lock.release()
diff --git a/tests/hermes_cli/test_external_process_auth_status.py b/tests/hermes_cli/test_external_process_auth_status.py
index 6f5e73ef369..f95d10c7c67 100644
--- a/tests/hermes_cli/test_external_process_auth_status.py
+++ b/tests/hermes_cli/test_external_process_auth_status.py
@@ -22,6 +22,9 @@ from hermes_cli.auth import (
get_external_process_provider_status,
resolve_external_process_provider_credentials,
)
+import providers as _providers
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (credentials module)
+from plugins.model_providers.copilot import credentials as copilot_credentials
@pytest.fixture()
@@ -348,8 +351,7 @@ def test_catalog_key_resolves_from_copilot_cli_store(tmp_path, monkeypatch, _cle
with mock_patch.object(
models_mod, "_resolve_copilot_catalog_api_key", wraps=models_mod._resolve_copilot_catalog_api_key
- ), mock_patch(
- "hermes_cli.copilot_auth.exchange_copilot_token",
+ ), mock_patch.object(copilot_credentials, "exchange_copilot_token",
return_value=("exchanged-api-token", 0.0, None),
), mock_patch(
"hermes_cli.auth.resolve_api_key_provider_credentials",
diff --git a/tests/hermes_cli/test_plugin_provider_picker_residue.py b/tests/hermes_cli/test_plugin_provider_picker_residue.py
index 2b13948258c..5f25929200a 100644
--- a/tests/hermes_cli/test_plugin_provider_picker_residue.py
+++ b/tests/hermes_cli/test_plugin_provider_picker_residue.py
@@ -121,6 +121,7 @@ def test_any_external_process_plugin_counts_as_signed_in_when_its_binary_resolve
"""The Desktop ``explicit_only`` filter (``build_model_options_payload`` behind
``tui_gateway/methods_complete.py::model.options``) keeps an out-of-tree ACP row exactly like the
bundled one: binary resolves → auth evidence; missing binary → hidden."""
+ import providers
from hermes_cli import auth
from hermes_cli.inventory import _external_process_signed_in, _filter_explicit_provider_rows
@@ -141,4 +142,4 @@ def test_any_external_process_plugin_counts_as_signed_in_when_its_binary_resolve
assert [r["slug"] for r in _filter_explicit_provider_rows(rows, _Ctx())] == ["example-acp"]
# Bundled Copilot keeps its token-store evidence: a resolving binary alone is not a sign-in there.
assert auth._external_process_auth_evidence("copilot-acp", str(tmp_path / "copilot")) == \
- auth._copilot_acp_auth_evidence()
+ providers.get_provider_profile("copilot-acp").external_auth_evidence()
diff --git a/tests/hermes_cli/test_runtime_provider_resolution.py b/tests/hermes_cli/test_runtime_provider_resolution.py
index dc22dcc7734..bc4278e719f 100644
--- a/tests/hermes_cli/test_runtime_provider_resolution.py
+++ b/tests/hermes_cli/test_runtime_provider_resolution.py
@@ -62,32 +62,6 @@ def _fake_invoke_jwt(ttl_seconds=3600):
return f"{header}.{payload}.sig"
-def test_runtime_selected_copilot_exchanges_ambient_pool_token(tmp_path, monkeypatch):
- """Copilot picked at runtime without a config write (`/model copilot/<m> --session`,
- `--provider copilot`) must still hand the EXCHANGED token and the enterprise base_url to the
- client: the seeder leaves an ambient gh-CLI credential raw while copilot is not configured
- (#114740), and a raw token 400s on enterprise-only models."""
- hermes_home = tmp_path / "hermes"
- hermes_home.mkdir()
- monkeypatch.setenv("HERMES_HOME", str(hermes_home))
- (hermes_home / "auth.json").write_text(json.dumps({"version": 1, "credential_pool": {}}))
- (hermes_home / "config.yaml").write_text("model:\n provider: deepseek\n default: deepseek-chat\n")
- from hermes_cli import config as _cfg
- _cfg._LOAD_CONFIG_CACHE.clear()
- _cfg._RAW_CONFIG_CACHE.clear()
- monkeypatch.setattr("hermes_cli.copilot_auth.resolve_copilot_token", lambda: ("ghu_raw_gh_token", "gh auth token"))
- monkeypatch.setattr("hermes_cli.copilot_auth.get_copilot_api_token",
- lambda tok: ("tid=exchanged;exp=1", "https://api.enterprise.ghe.example"))
- monkeypatch.setattr(rp._models, "copilot_model_api_mode", lambda *a, **k: "chat_completions")
- monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "copilot")
-
- resolved = rp.resolve_runtime_provider(requested="copilot", target_model="gpt-4.1")
-
- assert resolved["provider"] == "copilot"
- assert resolved["api_key"] == "tid=exchanged;exp=1"
- assert resolved["base_url"].startswith("https://api.enterprise.ghe.example")
-
-
def test_resolve_runtime_provider_uses_credential_pool(monkeypatch):
class _Entry:
access_token = "pool-token"
diff --git a/tests/hermes_cli/test_copilot_auth.py b/tests/plugins/model_providers/test_copilot_auth.py
similarity index 69%
rename from tests/hermes_cli/test_copilot_auth.py
rename to tests/plugins/model_providers/test_copilot_auth.py
index 8fbc9b00335..e6d934bb5b8 100644
--- a/tests/hermes_cli/test_copilot_auth.py
+++ b/tests/plugins/model_providers/test_copilot_auth.py
@@ -1,25 +1,27 @@
-"""Tests for hermes_cli.copilot_auth — Copilot token validation and resolution."""
+"""Tests for plugins.model_providers.copilot.credentials — Copilot token validation and resolution."""
import pytest
from unittest.mock import patch
-
+import providers as _providers
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (credentials module)
+from plugins.model_providers.copilot import credentials as copilot_credentials
class TestTokenValidation:
"""Token type validation."""
def test_classic_pat_rejected(self):
- from hermes_cli.copilot_auth import validate_copilot_token
+ from plugins.model_providers.copilot.credentials import validate_copilot_token
valid, _msg = validate_copilot_token("ghp_abcdefghijklmnop1234")
assert valid is False
@pytest.mark.parametrize("token", ["gho_abcdefghijklmnop1234", "github_pat_abcdefghijklmnop1234", "ghu_abcdefghijklmnop1234"])
def test_supported_token_families_accepted(self, token):
- from hermes_cli.copilot_auth import validate_copilot_token
+ from plugins.model_providers.copilot.credentials import validate_copilot_token
assert validate_copilot_token(token) == (True, "OK")
def test_arbitrary_string_rejected(self):
"""A non-GitHub value in GITHUB_TOKEN must fail validation instead of reaching the API (#12650)."""
- from hermes_cli.copilot_auth import validate_copilot_token
+ from plugins.model_providers.copilot.credentials import validate_copilot_token
valid, _msg = validate_copilot_token("not_a_github_token")
assert valid is False
@@ -29,7 +31,7 @@ class TestResolveToken:
def test_gh_token_second_priority(self, monkeypatch):
- from hermes_cli.copilot_auth import resolve_copilot_token
+ from plugins.model_providers.copilot.credentials import resolve_copilot_token
monkeypatch.delenv("COPILOT_GITHUB_TOKEN", raising=False)
monkeypatch.setenv("GH_TOKEN", "gho_gh_second")
monkeypatch.setenv("GITHUB_TOKEN", "gho_github_third")
@@ -39,11 +41,11 @@ class TestResolveToken:
def test_gh_cli_classic_pat_raises(self, monkeypatch):
- from hermes_cli.copilot_auth import resolve_copilot_token
+ from plugins.model_providers.copilot.credentials import resolve_copilot_token
monkeypatch.delenv("COPILOT_GITHUB_TOKEN", raising=False)
monkeypatch.delenv("GH_TOKEN", raising=False)
monkeypatch.delenv("GITHUB_TOKEN", raising=False)
- with patch("hermes_cli.copilot_auth._try_gh_cli_token", return_value="ghp_classic"):
+ with patch.object(copilot_credentials, "_try_gh_cli_token", return_value="ghp_classic"):
with pytest.raises(ValueError):
resolve_copilot_token()
@@ -56,11 +58,11 @@ class TestResolveToken:
call adds up to 5s of latency on Windows cold starts (#60800).
Only fall back to the CLI when NO Copilot env var is set at all.
"""
- from hermes_cli.copilot_auth import resolve_copilot_token
+ from plugins.model_providers.copilot.credentials import resolve_copilot_token
monkeypatch.delenv("COPILOT_GITHUB_TOKEN", raising=False)
monkeypatch.delenv("GH_TOKEN", raising=False)
monkeypatch.setenv("GITHUB_TOKEN", "ghp_classic_pat_nope")
- with patch("hermes_cli.copilot_auth._try_gh_cli_token") as mock_cli:
+ with patch.object(copilot_credentials, "_try_gh_cli_token") as mock_cli:
token, source = resolve_copilot_token()
assert token == ""
assert source == ""
@@ -68,11 +70,11 @@ class TestResolveToken:
def test_all_env_vars_invalid_skips_gh_cli_fallback(self, monkeypatch):
"""All three env vars set to classic PATs → no gh CLI call."""
- from hermes_cli.copilot_auth import resolve_copilot_token
+ from plugins.model_providers.copilot.credentials import resolve_copilot_token
monkeypatch.setenv("COPILOT_GITHUB_TOKEN", "ghp_one")
monkeypatch.setenv("GH_TOKEN", "ghp_two")
monkeypatch.setenv("GITHUB_TOKEN", "ghp_three")
- with patch("hermes_cli.copilot_auth._try_gh_cli_token") as mock_cli:
+ with patch.object(copilot_credentials, "_try_gh_cli_token") as mock_cli:
token, source = resolve_copilot_token()
assert token == ""
assert source == ""
@@ -89,29 +91,27 @@ class TestGhCliTokenCache:
"""
def _reset(self):
- from hermes_cli.copilot_auth import _invalidate_gh_cli_token_cache
+ from plugins.model_providers.copilot.credentials import _invalidate_gh_cli_token_cache
_invalidate_gh_cli_token_cache()
def test_miss_is_cached_and_probe_runs_once(self):
- from hermes_cli import copilot_auth
self._reset()
- with patch.object(copilot_auth, "_probe_gh_cli_token", return_value=None) as probe:
- assert copilot_auth._try_gh_cli_token() is None
- assert copilot_auth._try_gh_cli_token() is None
- assert copilot_auth._try_gh_cli_token() is None
+ with patch.object(copilot_credentials, "_probe_gh_cli_token", return_value=None) as probe:
+ assert copilot_credentials._try_gh_cli_token() is None
+ assert copilot_credentials._try_gh_cli_token() is None
+ assert copilot_credentials._try_gh_cli_token() is None
assert probe.call_count == 1
self._reset()
def test_ttl_expiry_reprobes(self, monkeypatch):
- from hermes_cli import copilot_auth
self._reset()
clock = {"now": 1000.0}
- monkeypatch.setattr(copilot_auth.time, "monotonic", lambda: clock["now"])
- with patch.object(copilot_auth, "_probe_gh_cli_token", return_value=None) as probe:
- copilot_auth._try_gh_cli_token()
- clock["now"] += copilot_auth._GH_CLI_TOKEN_CACHE_TTL_SECONDS + 1
- copilot_auth._try_gh_cli_token()
+ monkeypatch.setattr(copilot_credentials.time, "monotonic", lambda: clock["now"])
+ with patch.object(copilot_credentials, "_probe_gh_cli_token", return_value=None) as probe:
+ copilot_credentials._try_gh_cli_token()
+ clock["now"] += copilot_credentials._GH_CLI_TOKEN_CACHE_TTL_SECONDS + 1
+ copilot_credentials._try_gh_cli_token()
assert probe.call_count == 2
self._reset()
@@ -120,7 +120,7 @@ class TestRequestHeaders:
"""Copilot API header generation."""
def test_default_headers_include_openai_intent(self):
- from hermes_cli.copilot_auth import copilot_request_headers
+ from plugins.model_providers.copilot.credentials import copilot_request_headers
headers = copilot_request_headers()
assert headers["Openai-Intent"] == "conversation-edits"
assert headers["User-Agent"] == "HermesAgent/1.0"
@@ -128,13 +128,13 @@ class TestRequestHeaders:
def test_no_vision_header_by_default(self):
- from hermes_cli.copilot_auth import copilot_request_headers
+ from plugins.model_providers.copilot.credentials import copilot_request_headers
headers = copilot_request_headers()
assert "Copilot-Vision-Request" not in headers
class TestCopilotDefaultHeaders:
- """The models.py copilot_default_headers uses copilot_auth."""
+ """The models.py copilot_default_headers uses copilot_credentials."""
def test_param_passthrough_both_values(self):
diff --git a/tests/plugins/model_providers/test_copilot_pool_exchange.py b/tests/plugins/model_providers/test_copilot_pool_exchange.py
new file mode 100644
index 00000000000..5f59ba82d03
--- /dev/null
+++ b/tests/plugins/model_providers/test_copilot_pool_exchange.py
@@ -0,0 +1,38 @@
+"""Copilot selected at runtime exchanges the raw GitHub token held in its pool row
+(``ProviderProfile.prepare_pool_entry``), moved from tests/hermes_cli/test_runtime_provider_resolution.py."""
+
+from __future__ import annotations
+
+import json
+
+import providers as _providers
+from hermes_cli import runtime_provider as rp
+
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (credentials module)
+from plugins.model_providers.copilot import credentials as copilot_credentials
+
+
+def test_runtime_selected_copilot_exchanges_ambient_pool_token(tmp_path, monkeypatch):
+ """Copilot picked at runtime without a config write (`/model copilot/<m> --session`,
+ `--provider copilot`) must still hand the EXCHANGED token and the enterprise base_url to the
+ client: the seeder leaves an ambient gh-CLI credential raw while copilot is not configured
+ (#114740), and a raw token 400s on enterprise-only models."""
+ hermes_home = tmp_path / "hermes"
+ hermes_home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ (hermes_home / "auth.json").write_text(json.dumps({"version": 1, "credential_pool": {}}))
+ (hermes_home / "config.yaml").write_text("model:\n provider: deepseek\n default: deepseek-chat\n")
+ from hermes_cli import config as _cfg
+ _cfg._LOAD_CONFIG_CACHE.clear()
+ _cfg._RAW_CONFIG_CACHE.clear()
+ monkeypatch.setattr(copilot_credentials, "resolve_copilot_token", lambda: ("ghu_raw_gh_token", "gh auth token"))
+ monkeypatch.setattr(copilot_credentials, "get_copilot_api_token",
+ lambda tok: ("tid=exchanged;exp=1", "https://api.enterprise.ghe.example"))
+ monkeypatch.setattr(rp._models, "copilot_model_api_mode", lambda *a, **k: "chat_completions")
+ monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "copilot")
+
+ resolved = rp.resolve_runtime_provider(requested="copilot", target_model="gpt-4.1")
+
+ assert resolved["provider"] == "copilot"
+ assert resolved["api_key"] == "tid=exchanged;exp=1"
+ assert resolved["base_url"].startswith("https://api.enterprise.ghe.example")
diff --git a/tests/hermes_cli/test_copilot_token_exchange.py b/tests/plugins/model_providers/test_copilot_token_exchange.py
similarity index 85%
rename from tests/hermes_cli/test_copilot_token_exchange.py
rename to tests/plugins/model_providers/test_copilot_token_exchange.py
index dc906708073..6723af52d5f 100644
--- a/tests/hermes_cli/test_copilot_token_exchange.py
+++ b/tests/plugins/model_providers/test_copilot_token_exchange.py
@@ -7,12 +7,15 @@ import time
from unittest.mock import MagicMock, patch
import pytest
+import providers as _providers
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (credentials module)
+from plugins.model_providers.copilot import credentials as copilot_credentials
@pytest.fixture(autouse=True)
def _clear_jwt_cache():
"""Reset the module-level JWT + failure caches before each test."""
- import hermes_cli.copilot_auth as mod
+ mod = copilot_credentials
mod._jwt_cache.clear()
mod._exchange_failure_cache.clear()
yield
@@ -36,7 +39,7 @@ class TestExchangeCopilotToken:
@patch("urllib.request.urlopen")
def test_exchanges_token_successfully(self, mock_urlopen):
- from hermes_cli.copilot_auth import exchange_copilot_token
+ from plugins.model_providers.copilot.credentials import exchange_copilot_token
mock_urlopen.return_value = self._mock_urlopen(token="tid=abc;exp=999")
api_token, expires_at, base_url = exchange_copilot_token("gho_test123")
@@ -54,7 +57,7 @@ class TestExchangeCopilotToken:
@patch("urllib.request.urlopen")
def test_raises_on_empty_token(self, mock_urlopen):
- from hermes_cli.copilot_auth import exchange_copilot_token
+ from plugins.model_providers.copilot.credentials import exchange_copilot_token
resp_data = json.dumps({"token": "", "expires_at": 0}).encode()
mock_resp = MagicMock()
@@ -70,8 +73,8 @@ class TestExchangeCopilotToken:
class TestCallerIntegration:
"""Test that callers correctly use token exchange."""
- @patch("hermes_cli.copilot_auth.resolve_copilot_token", return_value=("gho_raw", "GH_TOKEN"))
- @patch("hermes_cli.copilot_auth.get_copilot_api_token", return_value=("exchanged_jwt", None))
+ @patch.object(copilot_credentials, "resolve_copilot_token", return_value=("gho_raw", "GH_TOKEN"))
+ @patch.object(copilot_credentials, "get_copilot_api_token", return_value=("exchanged_jwt", None))
def test_auth_resolve_uses_exchange(self, mock_exchange, mock_resolve):
from hermes_cli.auth import _resolve_api_key_provider_secret
@@ -87,7 +90,7 @@ class TestDeriveBaseUrlFromProxyEp:
"""Tests for _derive_base_url_from_proxy_ep()."""
def test_extracts_enterprise_url(self):
- from hermes_cli.copilot_auth import _derive_base_url_from_proxy_ep
+ from plugins.model_providers.copilot.credentials import _derive_base_url_from_proxy_ep
token = "tid=abc;exp=999;proxy-ep=proxy.enterprise.githubcopilot.com;sku=copilot_enterprise"
assert _derive_base_url_from_proxy_ep(token) == "https://api.enterprise.githubcopilot.com"
@@ -97,13 +100,13 @@ class TestJwtDiskStoreBounds:
"""The on-disk JWT store must go through one bounded read everywhere."""
def _store_path(self, tmp_path, monkeypatch):
- import hermes_cli.copilot_auth as mod
+ mod = copilot_credentials
path = tmp_path / mod._JWT_DISK_FILENAME
monkeypatch.setattr(mod, "_jwt_disk_path", lambda: path)
return path
def test_read_jwt_store_rejects_oversized_file(self, tmp_path, monkeypatch):
- import hermes_cli.copilot_auth as mod
+ mod = copilot_credentials
path = self._store_path(tmp_path, monkeypatch)
path.write_text("x" * (mod._JWT_DISK_MAX_BYTES + 1))
@@ -112,7 +115,7 @@ class TestJwtDiskStoreBounds:
assert mod._load_jwt_from_disk("deadbeef") is None
def test_read_jwt_store_rejects_non_dict_and_malformed(self, tmp_path, monkeypatch):
- import hermes_cli.copilot_auth as mod
+ mod = copilot_credentials
path = self._store_path(tmp_path, monkeypatch)
path.write_text("[1, 2, 3]")
@@ -122,7 +125,7 @@ class TestJwtDiskStoreBounds:
def test_evict_ignores_oversized_store(self, tmp_path, monkeypatch):
"""Eviction on an oversized store must not parse or rewrite it."""
- import hermes_cli.copilot_auth as mod
+ mod = copilot_credentials
path = self._store_path(tmp_path, monkeypatch)
blob = "x" * (mod._JWT_DISK_MAX_BYTES + 1)
@@ -136,7 +139,7 @@ class TestJwtDiskStoreBounds:
re-serializing the oversized content back out."""
import json as _json
import time as _time
- import hermes_cli.copilot_auth as mod
+ mod = copilot_credentials
path = self._store_path(tmp_path, monkeypatch)
path.write_text("x" * (mod._JWT_DISK_MAX_BYTES + 1))
@@ -164,7 +167,7 @@ class TestExchangeFailureFastPath:
@patch("time.sleep")
@patch("urllib.request.urlopen")
def test_403_fails_fast_without_retry_or_sleep(self, mock_urlopen, mock_sleep):
- from hermes_cli.copilot_auth import exchange_copilot_token
+ from plugins.model_providers.copilot.credentials import exchange_copilot_token
mock_urlopen.side_effect = self._http_error(403)
with pytest.raises(ValueError):
@@ -175,7 +178,7 @@ class TestExchangeFailureFastPath:
@patch("time.sleep")
@patch("urllib.request.urlopen")
def test_negative_cache_skips_network_on_second_call(self, mock_urlopen, mock_sleep):
- from hermes_cli.copilot_auth import exchange_copilot_token
+ from plugins.model_providers.copilot.credentials import exchange_copilot_token
mock_urlopen.side_effect = self._http_error(403)
with pytest.raises(ValueError):
@@ -187,8 +190,8 @@ class TestExchangeFailureFastPath:
@patch("time.sleep")
@patch("urllib.request.urlopen")
def test_transient_failure_still_retries_then_caches(self, mock_urlopen, mock_sleep):
- import hermes_cli.copilot_auth as mod
- from hermes_cli.copilot_auth import exchange_copilot_token, _token_fingerprint
+ mod = copilot_credentials
+ from plugins.model_providers.copilot.credentials import exchange_copilot_token, _token_fingerprint
mock_urlopen.side_effect = OSError("network unreachable")
with pytest.raises(ValueError):
@@ -202,8 +205,8 @@ class TestExchangeFailureFastPath:
@patch("time.sleep")
@patch("urllib.request.urlopen")
def test_success_clears_negative_cache(self, mock_urlopen, mock_sleep):
- import hermes_cli.copilot_auth as mod
- from hermes_cli.copilot_auth import exchange_copilot_token, _token_fingerprint
+ mod = copilot_credentials
+ from plugins.model_providers.copilot.credentials import exchange_copilot_token, _token_fingerprint
fp = _token_fingerprint("gho_recovering")
# Simulate an expired negative-cache entry so the call proceeds.
@@ -223,8 +226,8 @@ class TestExchangeFailureFastPath:
assert fp not in mod._exchange_failure_cache
def test_evict_clears_negative_cache(self):
- import hermes_cli.copilot_auth as mod
- from hermes_cli.copilot_auth import evict_cached_exchanged_token, _token_fingerprint
+ mod = copilot_credentials
+ from plugins.model_providers.copilot.credentials import evict_cached_exchanged_token, _token_fingerprint
fp = _token_fingerprint("gho_stale")
mod._exchange_failure_cache[fp] = time.time() + 999
diff --git a/tests/tui_gateway/test_cold_start_gil_stall.py b/tests/tui_gateway/test_cold_start_gil_stall.py
index 3360e97cde8..f867a45d741 100644
--- a/tests/tui_gateway/test_cold_start_gil_stall.py
+++ b/tests/tui_gateway/test_cold_start_gil_stall.py
@@ -4,7 +4,7 @@ The Desktop/TUI cold start could stall the event loop for ~14s because
synchronous CPU-bound work ran on the loop thread during the window
between ``HERMES_BACKEND_READY`` and the first prompt. Three fixes:
-1. ``copilot_auth.resolve_copilot_token`` skips the ``gh auth token``
+1. ``copilot_credentials.resolve_copilot_token`` skips the ``gh auth token``
subprocess when a Copilot env var is explicitly set (even if invalid).
2. ``tui_gateway.ws.handle_ws`` runs ``resolve_skin()`` via
``asyncio.to_thread`` so the loop is not blocked by config/skin init.
@@ -14,6 +14,9 @@ between ``HERMES_BACKEND_READY`` and the first prompt. Three fixes:
"""
from unittest.mock import patch
+import providers as _providers
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (credentials module)
+from plugins.model_providers.copilot import credentials as copilot_credentials
# ─── Fix 1: copilot_auth skips gh CLI when env var is set ──────────────
@@ -21,19 +24,19 @@ class TestCopilotAuthSkipsGhCli:
"""resolve_copilot_token must not call _try_gh_cli_token when any
Copilot env var is set, even if the token is an unsupported classic PAT.
- See test_copilot_auth.py::TestResolveToken for the full env-var-priority
+ See test_copilot_credentials.py::TestResolveToken for the full env-var-priority
suite; these tests focus on the #60800 cold-start regression — the
gh CLI subprocess adds up to 5s on Windows and should not fire when
the user already expressed token intent via an env var.
"""
def test_invalid_env_var_skips_gh_cli(self, monkeypatch):
- from hermes_cli.copilot_auth import resolve_copilot_token
+ from plugins.model_providers.copilot.credentials import resolve_copilot_token
monkeypatch.delenv("COPILOT_GITHUB_TOKEN", raising=False)
monkeypatch.delenv("GH_TOKEN", raising=False)
monkeypatch.setenv("GITHUB_TOKEN", "ghp_classic_pat_nope")
- with patch("hermes_cli.copilot_auth._try_gh_cli_token") as mock_cli:
+ with patch.object(copilot_credentials, "_try_gh_cli_token") as mock_cli:
token, source = resolve_copilot_token()
assert token == ""
assert source == ""
@@ -41,10 +44,10 @@ class TestCopilotAuthSkipsGhCli:
def test_valid_env_var_skips_gh_cli(self, monkeypatch):
"""A valid token in an env var should return immediately — no CLI."""
- from hermes_cli.copilot_auth import resolve_copilot_token
+ from plugins.model_providers.copilot.credentials import resolve_copilot_token
monkeypatch.setenv("GITHUB_TOKEN", "gho_valid_oauth_token")
- with patch("hermes_cli.copilot_auth._try_gh_cli_token") as mock_cli:
+ with patch.object(copilot_credentials, "_try_gh_cli_token") as mock_cli:
token, source = resolve_copilot_token()
assert token == "gho_valid_oauth_token"
assert source == "GITHUB_TOKEN"
@@ -52,13 +55,12 @@ class TestCopilotAuthSkipsGhCli:
def test_no_env_vars_falls_back_to_gh_cli(self, monkeypatch):
"""When NO env var is set, the gh CLI fallback must still fire."""
- from hermes_cli.copilot_auth import resolve_copilot_token
+ from plugins.model_providers.copilot.credentials import resolve_copilot_token
monkeypatch.delenv("COPILOT_GITHUB_TOKEN", raising=False)
monkeypatch.delenv("GH_TOKEN", raising=False)
monkeypatch.delenv("GITHUB_TOKEN", raising=False)
- with patch(
- "hermes_cli.copilot_auth._try_gh_cli_token",
+ with patch.object(copilot_credentials, "_try_gh_cli_token",
return_value="gho_from_cli",
) as mock_cli:
token, source = resolve_copilot_token()