Skip to content

The agent that grows with you

refactor(providers): move the Copilot catalog into the copilot plugins behind generic catalog hooks

Teknium35ac64046486
diff --git a/hermes_cli/models.py b/hermes_cli/models.py
index 57a3503ee49..421be38de8e 100644
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@ -39,7 +39,6 @@ from hermes_cli.models_catalog_static import (
_AGGREGATOR_PROVIDERS,
_AZURE_FOUNDRY_RESPONSES_PREFIXES,
_BORROWED_MODEL_PROVIDERS,
- _COPILOT_MODEL_ALIASES,
_LIVE_FIRST_PICKER_PROVIDERS,
_MODELS_DEV_PREFERRED,
_OPENAI_FAST_MODE_PREFIXES,
@@ -67,11 +66,6 @@ from hermes_cli.models_local import (
logger = logging.getLogger(__name__)
-COPILOT_BASE_URL = "https://api.githubcopilot.com"
-COPILOT_MODELS_URL = f"{COPILOT_BASE_URL}/models"
-COPILOT_EDITOR_VERSION = "vscode/1.104.1"
-COPILOT_REASONING_EFFORTS_GPT5 = ["minimal", "low", "medium", "high"]
-COPILOT_REASONING_EFFORTS_O_SERIES = ["low", "medium", "high"]
def _urlopen_model_catalog_request(req: urllib.request.Request, *, timeout: float, ssl_context=None):
"""Open catalog requests without forwarding headers across origins."""
@@ -622,18 +616,6 @@ def clamp_reasoning_effort_to_supported(
return _clamp_effort(effort, supported_efforts)
-def clamp_github_reasoning_effort(effort: Any, supported: list[str]) -> str:
- """Copilot/GitHub Models effort for a non-empty *supported* list: the level itself when listed,
- else the nearest WEAKER listed level; bespoke names the ladder can't place fall to ``medium``
- (or the first listed level)."""
- effort = str(effort or "medium").strip().lower()
- if effort not in supported:
- effort = _clamp_effort(effort, supported)
- if effort not in supported:
- effort = "medium" if "medium" in supported else supported[0]
- return effort
-
-
def _fetch_live_catalog_index(url: str, timeout: float, opener) -> Optional[tuple[list, dict[str, dict[str, Any]]]]:
"""GET an OpenAI-style ``/models`` listing → ``(raw data array, {id: item})``, or None when the
endpoint is unreachable or the payload has no ``data`` list."""
@@ -1295,65 +1277,6 @@ def resolve_fast_mode_overrides(
return {"speed": "fast"} if _is_anthropic_fast_model(model_id) else {"service_tier": "priority"}
-def _first_exchangeable_copilot_token(raw_tokens) -> str:
- """Exchange stored GitHub tokens in order; the first that validates AND exchanges wins (every
- entry is tried so a later valid token survives an earlier malformed one)."""
- from providers import get_provider_profile
- get_provider_profile("copilot") # loads the plugin package that owns these credentials
- from plugins.model_providers.copilot.credentials import exchange_copilot_token, validate_copilot_token
- for raw in raw_tokens:
- raw = str(raw or "").strip()
- if not raw or not validate_copilot_token(raw)[0]:
- continue
- try:
- api_token = exchange_copilot_token(raw)[0] # (api_token, expires_at, base_url)
- except Exception:
- continue
- if api_token:
- return api_token
- return ""
-
-
-def _copilot_cli_config_tokens() -> list[str]:
- """``copilotTokens`` from the GitHub Copilot CLI's own plaintext store (JSONC — strip
- ``//``-comment lines), written by ``copilot login`` on hosts without an OS keychain."""
- cli_config = os.path.expanduser("~/.copilot/config.json")
- if not os.path.isfile(cli_config):
- return []
- with open(cli_config, "r", encoding="utf-8-sig", errors="ignore") as fh:
- raw_text = "\n".join(
- line for line in fh.read().splitlines() if not line.lstrip().startswith("//"))
- data = json.loads(raw_text) if raw_text.strip() else {}
- tokens = data.get("copilotTokens")
- return list(tokens.values()) if isinstance(tokens, dict) else []
-
-
-def _resolve_copilot_catalog_api_key() -> str:
- """Best-effort GitHub token for the Copilot catalog: env vars / ``gh auth token`` via
- ``resolve_api_key_provider_credentials``, then ``auth.json`` ``credential_pool.copilot[]``, then
- ``~/.copilot/config.json`` ``copilotTokens`` (the ACP CLI's own store). Without the latter two,
- keyless users see the picker fall back to the stale curated list on a silent 401."""
- def _pool_token() -> str:
- from hermes_cli.auth import read_credential_pool
-
- return _first_exchangeable_copilot_token(
- entry.get("access_token") for entry in read_credential_pool("copilot") if isinstance(entry, dict))
-
- sources = (
- lambda: _api_key_credentials("copilot")[0],
- _pool_token,
- lambda: _first_exchangeable_copilot_token(_copilot_cli_config_tokens()),
- )
- for source in sources:
- try:
- token = source()
- except Exception:
- continue
- if token:
- return token
- return ""
-
-
def _model_dedup_key(model_id: str) -> str:
"""Case-insensitive dedup key folded through the picker-search alias table, so a bare live wire
id and its curated public slug (Kimi ``k3`` / ``kimi-k3``) don't both survive a merge."""
@@ -1420,46 +1343,6 @@ def _codex_catalog(normalized: str, force_refresh: bool) -> list[str]:
return get_codex_model_ids(access_token=access_token, base_url=base_url)
-_COPILOT_ACP_SESSION_MEMO_TTL = 300.0 # 5 min; SWR disk cache handles the rest
-_COPILOT_ACP_SESSION_FAIL_TTL = 30.0 # failed probes re-probe quickly so a fresh CLI login is picked up
-_copilot_acp_session_memo: Optional[tuple[float, float, Optional[list[str]]]] = None # (at, ttl, models)
-
-
-def _copilot_acp_session_models(force_refresh: bool) -> Optional[list[str]]:
- """Enabled models from a signed-in ``copilot --acp`` session, memoized for a few minutes —
- successes AND failures. Model-switch validation (``models_validate._static_catalog``) reads
- this uncached on every ``/model`` switch, and each miss is a CLI spawn + handshake (up to the
- probe timeout), so without the memo every switch paid a subprocess. A failed probe is
- memoized much more briefly so a user who signs in to the CLI right after a miss is picked up
- on the next switch (or immediately via ``/model --refresh``, which clears this memo)."""
- global _copilot_acp_session_memo
- now = time.monotonic()
- memo = _copilot_acp_session_memo
- if not force_refresh and memo is not None and now - memo[0] < memo[1]:
- return memo[2]
- from providers import get_provider_profile
-
- try:
- live = get_provider_profile("copilot-acp").fetch_models() or None
- except Exception:
- logger.debug("copilot-acp session model discovery failed", exc_info=True)
- live = None
- _copilot_acp_session_memo = (now, _COPILOT_ACP_SESSION_MEMO_TTL if live else _COPILOT_ACP_SESSION_FAIL_TTL, live)
- return live
-
-
-def _copilot_catalog(normalized: str, force_refresh: bool) -> Optional[list[str]]:
- if normalized == "copilot-acp" and (live := _copilot_acp_session_models(force_refresh)):
- return live
- try:
- live = _fetch_github_models(_resolve_copilot_catalog_api_key())
- if live:
- return live
- except Exception:
- pass
- return CuratedFallbackModels(_PROVIDER_MODELS.get("copilot", []))
-
-
def _nous_catalog(normalized: str, force_refresh: bool) -> Optional[list[str]]:
try:
from hermes_cli.anon_challenge import background_caller
@@ -1617,13 +1500,12 @@ def _azure_foundry_catalog(normalized: str, force_refresh: bool) -> Optional[lis
return None
-# Per-provider catalog sources tried before the generic profile fetch. A fetcher returning None
-# falls through to the profile/curated path; a list is returned as-is (even empty).
+# Per-provider catalog sources tried before the generic profile fetch (a profile's ``picker_catalog``
+# hook fills the same slot, see ``_catalog_fetcher``). A fetcher returning None falls through to the
+# profile/curated path; a list is returned as-is (even empty).
_PROVIDER_CATALOG_FETCHERS: dict[str, Any] = {
"openrouter": lambda normalized, force_refresh: model_ids(force_refresh=force_refresh),
"openai-codex": _codex_catalog,
- "copilot": _copilot_catalog,
- "copilot-acp": _copilot_catalog,
"nous": _nous_catalog,
"stepfun": _stepfun_catalog,
"gmi": _api_key_provider_live,
@@ -1649,6 +1531,19 @@ _OPENCODE_FREE_EXCLUDED_MODELS = frozenset(
)
+def _catalog_fetcher(normalized: str):
+ """The built-in fetcher for *normalized*, else its profile's ``picker_catalog`` hook, else None."""
+ fetcher = _PROVIDER_CATALOG_FETCHERS.get(normalized)
+ if fetcher is not None:
+ return fetcher
+ from providers import get_provider_profile
+ from providers.base import ProviderProfile
+
+ profile = get_provider_profile(normalized)
+ hook = profile.picker_catalog if isinstance(profile, ProviderProfile) else None
+ return (lambda _normalized, force_refresh: hook(force_refresh)) if hook is not None else None
+
+
def _profile_live_catalog(normalized: str) -> Optional[list[str]]:
"""Generic live fetch for any provider registered in providers/ with ``auth_type="api_key"``.
@@ -1838,8 +1733,8 @@ def provider_model_ids(provider: Optional[str], *, force_refresh: bool = False)
relayed = _relay_model_catalog(normalized, relay)
if relayed:
return _chat_catalog_rows(relayed)
- return _static_catalog(normalized, _PROVIDER_CATALOG_FETCHERS.get(normalized))
- fetcher = _PROVIDER_CATALOG_FETCHERS.get(normalized)
+ return _static_catalog(normalized, _catalog_fetcher(normalized))
+ fetcher = _catalog_fetcher(normalized)
if fetcher is not None:
models = fetcher(normalized, force_refresh)
if models is not None:
@@ -2035,8 +1930,9 @@ def _credential_fingerprint(provider: str) -> str:
_mtime_part(rel, get_hermes_home() / rel)
except Exception:
pass
- for rel in ("~/.codex/auth.json", "~/.claude/.credentials.json",
- "~/.config/github-copilot/hosts.json", "~/.minimax/credentials.json"):
+ from providers import list_providers
+ profile_files = [rel for profile in list_providers() for rel in profile.catalog_credential_files]
+ for rel in ("~/.codex/auth.json", "~/.claude/.credentials.json", *profile_files, "~/.minimax/credentials.json"):
path = os.path.expanduser(rel)
_mtime_part(path, path)
@@ -2162,10 +2058,11 @@ def clear_provider_models_cache(provider: Optional[str] = None) -> None:
_OLLAMA_LOCAL_MODELS_CACHE.clear()
_OLLAMA_LOCAL_PROBE_FAILURE_CACHE.clear()
_OLLAMA_LOCAL_PROBE_REACHABLE.clear()
- # A fresh copilot-acp CLI login must show on the next /model switch: ``--refresh`` drops the
- # 5-min session memo (and its failure memo) so it never serves a stale signed-out probe.
- global _copilot_acp_session_memo
- _copilot_acp_session_memo = None
+ # Provider-owned in-process memos (e.g. an external CLI's session catalog) must re-probe so a
+ # fresh login shows on the next switch.
+ from providers import list_providers
+ for profile in list_providers():
+ profile.invalidate_catalog_cache()
from hermes_cli.models_cache_lock import write_under_cache_lock
path = _provider_models_cache_path()
@@ -2269,212 +2166,6 @@ def _fetch_anthropic_models(
return None
-def _payload_items(payload: Any) -> list[dict[str, Any]]:
- data = payload.get("data", []) if isinstance(payload, dict) else payload
- return [item for item in data if isinstance(item, dict)] if isinstance(data, list) else []
-
-
-def copilot_default_headers(*, is_agent_turn: bool = True) -> dict[str, str]:
- """Standard headers for Copilot API requests."""
- try:
- from providers import get_provider_profile
- get_provider_profile("copilot") # loads the plugin package that owns these credentials
- from plugins.model_providers.copilot.credentials import copilot_request_headers
- return copilot_request_headers(is_agent_turn=is_agent_turn)
- except ImportError:
- return {"Editor-Version": COPILOT_EDITOR_VERSION, "User-Agent": "HermesAgent/1.0",
- "Openai-Intent": "conversation-edits", "x-initiator": "agent" if is_agent_turn else "user"}
-
-
-_COPILOT_CHAT_ENDPOINTS = {"/chat/completions", "/responses", "/v1/messages"}
-
-
-def _copilot_catalog_item_is_text_model(
- item: dict[str, Any], *, ignore_picker_flag: bool = False) -> bool:
- if not str(item.get("id") or "").strip():
- return False
- if not ignore_picker_flag and item.get("model_picker_enabled") is False:
- return False
- capabilities = item.get("capabilities")
- if isinstance(capabilities, dict):
- model_type = str(capabilities.get("type") or "").strip().lower()
- if model_type and model_type != "chat":
- return False
- supported_endpoints = item.get("supported_endpoints")
- if isinstance(supported_endpoints, list):
- endpoints = {e for endpoint in supported_endpoints if (e := str(endpoint).strip())}
- if endpoints and not endpoints & _COPILOT_CHAT_ENDPOINTS:
- return False
- return True
-
-
-def _copilot_text_models(items: list[dict[str, Any]], *, ignore_picker_flag: bool = False) -> list[dict[str, Any]]:
- """Chat-capable catalog rows, deduped by id, in catalog order."""
- models: list[dict[str, Any]] = []
- seen_ids: set[str] = set()
- for item in items:
- model_id = str(item.get("id") or "").strip()
- if model_id in seen_ids:
- continue
- if not _copilot_catalog_item_is_text_model(item, ignore_picker_flag=ignore_picker_flag):
- continue
- seen_ids.add(model_id)
- models.append(item)
- return models
-
-
-# Short-TTL cache of the filtered GitHub Copilot /models catalog (picker + context/normalize helpers
-# share it). Keyed by the api_key of the successful fetch so a credential swap never serves the
-# previous account's catalog; monotonic clock; lock-free (a race at worst duplicates one fetch).
-_github_model_catalog_cache: Optional[list[dict[str, Any]]] = None
-_github_model_catalog_cache_key: Optional[str] = None
-_github_model_catalog_cache_time: float = 0.0
-_GITHUB_MODEL_CATALOG_CACHE_TTL = 300 # 5 minutes
-
-
-def fetch_github_model_catalog(
- api_key: Optional[str] = None, timeout: float = 5.0) -> Optional[list[dict[str, Any]]]:
- """Fetch the live GitHub Copilot model catalog for this account."""
- global _github_model_catalog_cache, _github_model_catalog_cache_key
- global _github_model_catalog_cache_time
-
- if (
- _github_model_catalog_cache is not None
- and _github_model_catalog_cache_key == api_key
- and (time.monotonic() - _github_model_catalog_cache_time) < _GITHUB_MODEL_CATALOG_CACHE_TTL
- ):
- return copy.deepcopy(_github_model_catalog_cache) # deep: callers must not mutate cached dicts
-
- attempts: list[dict[str, str]] = []
- if api_key:
- attempts.append({**copilot_default_headers(), "Authorization": f"Bearer {api_key}"})
- attempts.append(copilot_default_headers())
-
- for headers in attempts:
- try:
- items = _payload_items(_get_json(COPILOT_MODELS_URL, timeout=timeout, headers=headers))
- except Exception:
- continue
- models = _copilot_text_models(items)
- if not models and items:
- # GitHub has been observed returning ``model_picker_enabled: false`` for EVERY model on
- # some accounts, which would strand the picker on the stale curated fallback. The flag
- # is a display hint, not an availability contract — retry without it (chat/endpoint
- # checks still apply).
- models = _copilot_text_models(items, ignore_picker_flag=True)
- if models:
- _github_model_catalog_cache = copy.deepcopy(models)
- _github_model_catalog_cache_key = api_key
- _github_model_catalog_cache_time = time.monotonic()
- return models
- return None
-
-
-# ─── Copilot catalog context-window helpers ───
-
-# Module-level cache: {model_id: max_prompt_tokens}
-_copilot_context_cache: dict[str, int] = {}
-_copilot_context_cache_time: float = 0.0
-_copilot_context_cache_key: Optional[str] = None # fingerprint of the api_key the entry was fetched with
-_COPILOT_CONTEXT_CACHE_TTL = 3600 # 1 hour
-
-
-def get_copilot_model_context(model_id: str, api_key: Optional[str] = None) -> Optional[int]:
- """``max_prompt_tokens`` for a Copilot model from the live /models API (cached in-process 1h; a
- miss on a fresh cache does not re-fetch), or None."""
- global _copilot_context_cache, _copilot_context_cache_time, _copilot_context_cache_key
-
- # Keyed on the credential like fetch_github_model_catalog: the catalog (and its limits) is
- # per-account, so another profile's token must not be served this entry.
- from agent.credential_persistence import fingerprint_secret_value
- key_fp = fingerprint_secret_value(api_key)
- if (_copilot_context_cache and _copilot_context_cache_key == key_fp
- and (time.time() - _copilot_context_cache_time < _COPILOT_CONTEXT_CACHE_TTL)):
- return _copilot_context_cache.get(model_id)
-
- catalog = fetch_github_model_catalog(api_key=api_key)
- if not catalog:
- return None
- cache: dict[str, int] = {}
- for item in catalog:
- mid = str(item.get("id") or "").strip()
- max_prompt = ((item.get("capabilities") or {}).get("limits") or {}).get("max_prompt_tokens")
- if mid and isinstance(max_prompt, int) and max_prompt > 0:
- cache[mid] = max_prompt
- _copilot_context_cache = cache
- _copilot_context_cache_time = time.time()
- _copilot_context_cache_key = key_fp
- return cache.get(model_id)
-
-
-def _is_github_models_base_url(base_url: Optional[str]) -> bool:
- return (base_url or "").strip().rstrip("/").lower().startswith(
- (COPILOT_BASE_URL, "https://models.github.ai/inference", "https://models.inference.ai.azure.com")
- )
-
-
-def _fetch_github_models(api_key: Optional[str] = None, timeout: float = 5.0) -> Optional[list[str]]:
- catalog = fetch_github_model_catalog(api_key=api_key, timeout=timeout)
- return [item.get("id", "") for item in catalog if item.get("id")] if catalog else None
-
-
-def _copilot_catalog_ids(
- catalog: Optional[list[dict[str, Any]]] = None, api_key: Optional[str] = None) -> set[str]:
- if catalog is None and api_key:
- catalog = fetch_github_model_catalog(api_key=api_key)
- return {mid for item in (catalog or []) if (mid := str(item.get("id") or "").strip())}
-
-
-def normalize_copilot_model_id(
- model_id: Optional[str], *, catalog: Optional[list[dict[str, Any]]] = None,
- api_key: Optional[str] = None) -> str:
- raw = str(model_id or "").strip()
- if not raw:
- return ""
-
- catalog_ids = _copilot_catalog_ids(catalog=catalog, api_key=api_key)
- alias = _COPILOT_MODEL_ALIASES.get(raw)
- if alias:
- return alias
-
- candidates = [raw]
- if "/" in raw:
- candidates.append(raw.split("/", 1)[1].strip())
- if raw.endswith(("-mini", "-nano", "-chat")):
- candidates.append(raw[:-5])
-
- seen: set[str] = set()
- for candidate in candidates:
- if not candidate or candidate in seen:
- continue
- seen.add(candidate)
- if candidate in _COPILOT_MODEL_ALIASES:
- return _COPILOT_MODEL_ALIASES[candidate]
- if candidate in catalog_ids:
- return candidate
-
- if "/" in raw:
- stripped = raw.split("/", 1)[1].strip()
- # Enterprise BYOK custom models expose ``owner/sub/model`` ids (two
- # slashes). A strip guess that still contains "/" cannot be a Copilot
- # id, so pass the input through untouched instead of corrupting it.
- if stripped and "/" not in stripped:
- return stripped
- return raw
-
-
-def _github_reasoning_efforts_for_model_id(model_id: str) -> list[str]:
- raw = (model_id or "").strip().lower()
- if raw.startswith(("openai/o1", "openai/o3", "openai/o4", "o1", "o3", "o4")):
- return list(COPILOT_REASONING_EFFORTS_O_SERIES)
- normalized = normalize_copilot_model_id(model_id).lower()
- if is_astra_model(normalized):
- return list(CODEX_ASTRA_EFFORTS)
- if normalized.startswith("gpt-5"):
- return list(COPILOT_REASONING_EFFORTS_GPT5)
- return []
-
-
def azure_foundry_model_api_mode(model_name: Optional[str]) -> Optional[str]:
"""``"codex_responses"`` for families that only accept the Responses API on Azure Foundry (GPT-5.x
incl. gpt-5-mini, codex, o1/o3/o4), else None. Any ``vendor/`` prefix is stripped first."""
@@ -2571,32 +2262,6 @@ def normalize_opencode_base_url(
return urllib.parse.urlunparse(parsed._replace(path=path))
-def github_model_reasoning_efforts(
- model_id: Optional[str], *, catalog: Optional[list[dict[str, Any]]] = None,
- api_key: Optional[str] = None) -> list[str]:
- """Return supported reasoning-effort levels for a Copilot-visible model."""
- normalized = normalize_copilot_model_id(model_id, catalog=catalog, api_key=api_key)
- if not normalized:
- return []
-
- if catalog is None and api_key:
- catalog = fetch_github_model_catalog(api_key=api_key)
- catalog_entry = next((item for item in catalog if item.get("id") == normalized), None) if catalog else None
- if catalog_entry is not None:
- capabilities = catalog_entry.get("capabilities")
- if isinstance(capabilities, dict):
- # Structured catalog: the advertised list is authoritative (empty when absent).
- supports = capabilities.get("supports")
- efforts = supports.get("reasoning_effort") if isinstance(supports, dict) else None
- if not isinstance(efforts, list):
- return []
- return list(dict.fromkeys(e for effort in efforts if (e := str(effort).strip().lower())))
- # Legacy list-shaped capabilities: only a "reasoning" tag unlocks the pattern defaults.
- if "reasoning" not in {str(c).strip().lower() for c in catalog_entry.get("capabilities", [])}:
- return []
- return _github_reasoning_efforts_for_model_id(str(model_id or normalized))
-
-
# Negative cache: monotonic timestamp of the last timed-out probe, keyed
# by ``host:port`` so both URL candidates (``/v1`` + root) share one entry.
# Without this, an unreachable endpoint (TCP blackhole — SYN draws no reply,
@@ -2638,9 +2303,12 @@ def probe_api_models(
normalized = (base_url or "").strip().rstrip("/")
if not normalized:
return _probe_result(None, None, "")
- if _is_github_models_base_url(normalized):
- models = _fetch_github_models(api_key=api_key, timeout=timeout)
- return _probe_result(models, COPILOT_MODELS_URL, COPILOT_BASE_URL)
+ from providers import profile_for_host
+
+ owner = profile_for_host(normalized, metadata=True)
+ owned = owner.probe_models(base_url=normalized, api_key=api_key, timeout=timeout) if owner else None
+ if owned is not None:
+ return _probe_result(*owned)
alternate_base = normalized[:-3].rstrip("/") if normalized.endswith("/v1") else normalized + "/v1"
candidates: list[tuple[str, bool]] = [(normalized, False)]
@@ -2663,8 +2331,6 @@ def probe_api_models(
headers["anthropic-version"] = "2023-06-01"
elif api_key:
headers["Authorization"] = f"Bearer {api_key}"
- if normalized.startswith(COPILOT_BASE_URL):
- headers.update(copilot_default_headers())
if isinstance(request_headers, dict):
# Per-provider custom headers can contain secrets: merge last so endpoint config wins; never log.
from hermes_cli.config import normalize_extra_headers
diff --git a/hermes_cli/models_catalog_static.py b/hermes_cli/models_catalog_static.py
index 821e04ce84a..3a59b8a7d96 100644
--- a/hermes_cli/models_catalog_static.py
+++ b/hermes_cli/models_catalog_static.py
@@ -145,7 +145,7 @@ def _xai_curated_models() -> list[str]:
return _xai_finalize_catalog(list(_XAI_STATIC_FALLBACK))
-# Native OpenAI Chat Completions (api.openai.com); also the head of the Copilot list.
+# Native OpenAI Chat Completions (api.openai.com).
_OPENAI_CHAT_MODELS = [
"gpt-5.4", "gpt-5.4-mini", "gpt-5-mini", "gpt-5.3-codex", "gpt-5.2-codex", "gpt-4.1", "gpt-4o", "gpt-4o-mini",
]
@@ -184,11 +184,6 @@ _PROVIDER_MODELS: dict[str, list[str]] = {
],
"openai-codex": _codex_curated_models(),
"xai-oauth": list(_XAI_MODELS),
- "copilot-acp": ["copilot-acp"],
- "copilot": _OPENAI_CHAT_MODELS + [
- "claude-sonnet-4.6", "claude-sonnet-5", "claude-sonnet-4", "claude-sonnet-4.5", "claude-haiku-4.5",
- "gemini-3.1-pro-preview", "gemini-3-pro-preview", "gemini-3-flash-preview", "gemini-2.5-pro",
- ],
"gemini": [
# Argon second: [0] is the silent default when no model is configured, and a flagship never is.
"gemini-3.8-flash", "gemini-4-argon", "gemini-3.7-flash",
@@ -406,6 +401,8 @@ def sync_plugin_provider_catalog() -> int:
return 0
added = 0
for pp in profiles:
+ if pp.static_models:
+ _PROVIDER_MODELS.setdefault(pp.name, list(pp.static_models))
if not _plugin_provider_enters_picker(pp):
continue
label = pp.display_name or pp.name
@@ -582,7 +579,7 @@ _LIVE_FIRST_PICKER_PROVIDERS: frozenset[str] = frozenset({"opencode-zen", "openc
# Models supporting OpenAI Priority Processing (service_tier="priority"; see
# openai.com/api-priority-processing). Pattern-based: any OpenAI flagship (gpt-*, o1*, o3*, o4*).
-# Non-OpenAI endpoints (OpenRouter/Copilot/opencode-zen proxies) strip service_tier, so false
+# Non-OpenAI endpoints (OpenRouter/opencode-zen and other proxies) strip service_tier, so false
# positives are harmless. Codex-series models are excluded — the Codex Responses API doesn't
# expose service_tier.
_OPENAI_FAST_MODE_PREFIXES: tuple[str, ...] = ("gpt-", "o1", "o3", "o4")
@@ -597,34 +594,13 @@ _OPENAI_ULTRAFAST_MODELS: frozenset[str] = frozenset({"gpt-6-astra", "gpt-6.1-so
# and the gateway /model picker. DELIBERATELY EXCLUDED: "openrouter" (curated list is a hand-picked
# agentic subset of 400+ models — merging would dump everything), "nous" (curated list + Portal
# /models are the subscription-tier source of truth), and providers with dedicated live-endpoint
-# branches (copilot, anthropic, ai-gateway, ollama-cloud, custom, stepfun, openai-codex).
+# branches or a profile catalog hook (anthropic, ai-gateway, ollama-cloud, custom, stepfun, openai-codex).
_MODELS_DEV_PREFERRED: frozenset[str] = frozenset({
"opencode-go", "opencode-zen", "kilocode", "fireworks", "mistral", "togetherai", "cohere",
"perplexity", "groq", "nvidia", "huggingface", "zai", "gemini", "google", "xai", "xai-oauth",
})
-# OpenRouter-style ids -> Copilot ids. Dash-notation Claude ids are accepted too: Hermes' default
-# Claude IDs use hyphens (Anthropic native) but Copilot's API only accepts dot-notation, so a
-# copilot + hyphenated default would otherwise hit HTTP 400 "model_not_supported".
-_COPILOT_MODEL_ALIASES = dict((
- ("openai/gpt-5", "gpt-5-mini"), ("openai/gpt-5-chat", "gpt-5-mini"), ("openai/gpt-5-mini", "gpt-5-mini"),
- ("openai/gpt-5-nano", "gpt-5-mini"), ("openai/gpt-4.1", "gpt-4.1"), ("openai/gpt-4.1-mini", "gpt-4.1"),
- ("openai/gpt-4.1-nano", "gpt-4.1"), ("openai/gpt-4o", "gpt-4o"), ("openai/gpt-4o-mini", "gpt-4o-mini"),
- ("openai/o1", "gpt-5.2"), ("openai/o1-mini", "gpt-5-mini"), ("openai/o1-preview", "gpt-5.2"),
- ("openai/o3", "gpt-5.3-codex"), ("openai/o3-mini", "gpt-5-mini"), ("openai/o4-mini", "gpt-5-mini"),
- ("anthropic/claude-opus-4.6", "claude-opus-4.6"), ("anthropic/claude-sonnet-5", "claude-sonnet-5"),
- ("anthropic/claude-sonnet-4.6", "claude-sonnet-4.6"), ("anthropic/claude-sonnet-4", "claude-sonnet-4"),
- ("anthropic/claude-sonnet-4.5", "claude-sonnet-4.5"), ("anthropic/claude-haiku-4.5", "claude-haiku-4.5"),
- ("claude-sonnet-5", "claude-sonnet-5"), ("claude-opus-4-6", "claude-opus-4.6"),
- ("claude-sonnet-4-6", "claude-sonnet-4.6"), ("claude-sonnet-4-0", "claude-sonnet-4"),
- ("claude-sonnet-4-5", "claude-sonnet-4.5"), ("claude-haiku-4-5", "claude-haiku-4.5"),
- ("anthropic/claude-opus-4-6", "claude-opus-4.6"), ("anthropic/claude-sonnet-4-6", "claude-sonnet-4.6"),
- ("anthropic/claude-sonnet-4-0", "claude-sonnet-4"), ("anthropic/claude-sonnet-4-5", "claude-sonnet-4.5"),
- ("anthropic/claude-haiku-4-5", "claude-haiku-4.5"),
-))
-
-
# Azure Foundry model families that require the Responses API: Azure rejects /chat/completions
# against them with ``400 "The requested operation is unsupported."`` (seen on gpt-5.3-codex while
# gpt-4o on the same endpoint worked). Broad enough for vendor-renamed deployments (gpt-5.x-codex,
diff --git a/plugins/model-providers/copilot-acp/__init__.py b/plugins/model-providers/copilot-acp/__init__.py
index 26c8497166a..6fd478e4c31 100644
--- a/plugins/model-providers/copilot-acp/__init__.py
+++ b/plugins/model-providers/copilot-acp/__init__.py
@@ -11,6 +11,7 @@ from typing import Any
from providers import register_provider
from providers.base import ProviderProfile
+from .catalog import acp_picker_catalog, clear_session_memo
from .setup import SETUP_FIELDS
@@ -64,6 +65,9 @@ class CopilotACPProfile(ProviderProfile):
copilot = get_provider_profile("copilot")
return copilot.live_context_length(model, api_key=api_key, base_url=base_url) if copilot else None
+ def invalidate_catalog_cache(self) -> None:
+ clear_session_memo()
+
def normalize_model_id(self, model: str, *, api_key: str = "") -> str | None:
"""Copilot id space; the ACP marker key never reaches the HTTP catalog."""
from providers import get_provider_profile
@@ -86,6 +90,7 @@ copilot_acp = CopilotACPProfile(
process_args_env_var="HERMES_COPILOT_ACP_ARGS",
# A delegation.command no other profile claims has always run through this ACP client.
process_command_fallback=True,
+ picker_catalog=acp_picker_catalog, static_models=("copilot-acp",),
**SETUP_FIELDS,
)
diff --git a/plugins/model-providers/copilot-acp/catalog.py b/plugins/model-providers/copilot-acp/catalog.py
new file mode 100644
index 00000000000..8f1c25ae0a8
--- /dev/null
+++ b/plugins/model-providers/copilot-acp/catalog.py
@@ -0,0 +1,55 @@
+"""copilot-acp picker catalog: the signed-in CLI session's models (memoized), else the HTTP
+``copilot`` provider's catalog (same account id space)."""
+
+from __future__ import annotations
+
+import logging
+import time
+from typing import Optional
+
+logger = logging.getLogger(__name__)
+
+_SESSION_MEMO_TTL = 300.0 # 5 min; SWR disk cache handles the rest
+_SESSION_FAIL_TTL = 30.0 # failed probes re-probe quickly so a fresh CLI login is picked up
+_session_memo: Optional[tuple[float, float, Optional[list[str]]]] = None # (at, ttl, models)
+
+
+def session_models(force_refresh: bool) -> Optional[list[str]]:
+ """Enabled models from a signed-in ``copilot --acp`` session, memoized for a few minutes —
+ successes AND failures. Model-switch validation (``models_validate._static_catalog``) reads
+ this uncached on every ``/model`` switch, and each miss is a CLI spawn + handshake (up to the
+ probe timeout), so without the memo every switch paid a subprocess. A failed probe is
+ memoized much more briefly so a user who signs in to the CLI right after a miss is picked up
+ on the next switch (or immediately via ``/model --refresh``, which clears this memo)."""
+ global _session_memo
+ now = time.monotonic()
+ memo = _session_memo
+ if not force_refresh and memo is not None and now - memo[0] < memo[1]:
+ return memo[2]
+ from providers import get_provider_profile
+
+ try:
+ live = get_provider_profile("copilot-acp").fetch_models() or None
+ except Exception:
+ logger.debug("copilot-acp session model discovery failed", exc_info=True)
+ live = None
+ _session_memo = (now, _SESSION_MEMO_TTL if live else _SESSION_FAIL_TTL, live)
+ return live
+
+
+def clear_session_memo() -> None:
+ """A fresh CLI login must show on the next ``/model`` switch: ``--refresh`` drops the memo
+ (and its failure memo) so it never serves a stale signed-out probe."""
+ global _session_memo
+ _session_memo = None
+
+
+def acp_picker_catalog(force_refresh: bool = False) -> Optional[list[str]]:
+ if live := session_models(force_refresh):
+ return live
+ from providers import get_provider_profile
+
+ copilot = get_provider_profile("copilot")
+ if copilot is None or copilot.picker_catalog is None:
+ return None
+ return copilot.picker_catalog(force_refresh)
diff --git a/plugins/model-providers/copilot/__init__.py b/plugins/model-providers/copilot/__init__.py
index deedcee0a7e..408cbd3c88e 100644
--- a/plugins/model-providers/copilot/__init__.py
+++ b/plugins/model-providers/copilot/__init__.py
@@ -10,7 +10,7 @@ from typing import Any
from providers import register_provider
from providers.base import ProviderProfile
-from .catalog import HOSTNAMES, METADATA_HOSTNAMES, MODELS_DEV_ID, CopilotCatalogMixin
+from .catalog import CATALOG_FIELDS, HOSTNAMES, METADATA_HOSTNAMES, MODELS_DEV_ID, CopilotCatalogMixin
from .credentials import CopilotCredentialsMixin
from .responses import RESPONSES_PROFILE_FIELDS, CopilotResponsesMixin
from .setup import SETUP_FIELDS
@@ -27,7 +27,7 @@ class CopilotProfile(CopilotWireMixin, CopilotResponsesMixin, CopilotCatalogMixi
if not (supports_reasoning and model):
return {}, {}
try:
- from hermes_cli.models import clamp_github_reasoning_effort, github_model_reasoning_efforts
+ from .catalog import clamp_github_reasoning_effort, github_model_reasoning_efforts
supported = github_model_reasoning_efforts(model)
if not supported:
@@ -45,7 +45,7 @@ copilot = CopilotProfile(
name="copilot", aliases=("github-copilot", "github-models", "github-model", "github"),
env_vars=("COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"), base_url="https://api.githubcopilot.com",
auth_type="copilot", ambient_credentials=True, **RESPONSES_PROFILE_FIELDS, **SETUP_FIELDS,
- hostnames=HOSTNAMES, metadata_hostnames=METADATA_HOSTNAMES, models_dev_id=MODELS_DEV_ID,
+ hostnames=HOSTNAMES, metadata_hostnames=METADATA_HOSTNAMES, models_dev_id=MODELS_DEV_ID, **CATALOG_FIELDS,
)
register_provider(copilot)
diff --git a/plugins/model-providers/copilot/catalog.py b/plugins/model-providers/copilot/catalog.py
index d90bfd10ce7..608838ae095 100644
--- a/plugins/model-providers/copilot/catalog.py
+++ b/plugins/model-providers/copilot/catalog.py
@@ -1,7 +1,22 @@
-"""Copilot catalog and model-metadata hooks (lane L4): hosts, models.dev id, live context windows."""
+"""Copilot catalog and model metadata: hosts, models.dev id, the live ``/models`` catalog (picker,
+context windows, id normalization, reasoning efforts) and the curated fallback list.
+
+Fills the generic ProviderProfile catalog seams (``providers/base.py`` L4 + I2-cat blocks). Core
+helpers (``hermes_cli.models._get_json`` / ``_api_key_credentials``) are imported at call time, so
+this module never imports ``hermes_cli`` while the provider registry is being discovered.
+"""
from __future__ import annotations
+import copy
+import json
+import logging
+import os
+import time
+from typing import Any, Optional
+
+logger = logging.getLogger(__name__)
+
# Copilot business/enterprise accounts are served from ``api.<plan>.githubcopilot.com``; GitHub Models
# (models.github.ai) speaks the same wire (Responses quirks, reasoning payloads, x-initiator billing).
# Per-site differences (carriers, editor headers: githubcopilot.com only) live in the hooks, keyed on base_url.
@@ -9,17 +24,387 @@ HOSTNAMES = ("githubcopilot.com", "models.github.ai")
# The ~8K-capped GitHub Models free tier shares the Copilot catalog only (model metadata lookups).
METADATA_HOSTNAMES = ("models.inference.ai.azure.com",)
MODELS_DEV_ID = "github-copilot"
+# Credential stores whose change re-keys every cached provider catalog (core's catalog fingerprint).
+CATALOG_CREDENTIAL_FILES = ("~/.config/github-copilot/hosts.json",)
+
+COPILOT_BASE_URL = "https://api.githubcopilot.com"
+COPILOT_MODELS_URL = f"{COPILOT_BASE_URL}/models"
+# Base URLs whose ``/models`` probe is answered from the Copilot catalog (GitHub Models included).
+_CATALOG_BASE_URLS = (COPILOT_BASE_URL, "https://models.github.ai/inference", "https://models.inference.ai.azure.com")
+REASONING_EFFORTS_GPT5 = ["minimal", "low", "medium", "high"]
+REASONING_EFFORTS_O_SERIES = ["low", "medium", "high"]
+
+# Curated list (core's static catalog row): served when the live catalog is unreachable.
+STATIC_MODELS = (
+ "gpt-5.4", "gpt-5.4-mini", "gpt-5-mini", "gpt-5.3-codex", "gpt-5.2-codex", "gpt-4.1", "gpt-4o", "gpt-4o-mini",
+ "claude-sonnet-4.6", "claude-sonnet-5", "claude-sonnet-4", "claude-sonnet-4.5", "claude-haiku-4.5",
+ "gemini-3.1-pro-preview", "gemini-3-pro-preview", "gemini-3-flash-preview", "gemini-2.5-pro",
+)
+
+# OpenRouter-style ids -> Copilot ids. Dash-notation Claude ids are accepted too: Hermes' default
+# Claude IDs use hyphens (Anthropic native) but Copilot's API only accepts dot-notation, so a
+# copilot + hyphenated default would otherwise hit HTTP 400 "model_not_supported".
+MODEL_ALIASES: dict[str, str] = dict((
+ ("openai/gpt-5", "gpt-5-mini"), ("openai/gpt-5-chat", "gpt-5-mini"), ("openai/gpt-5-mini", "gpt-5-mini"),
+ ("openai/gpt-5-nano", "gpt-5-mini"), ("openai/gpt-4.1", "gpt-4.1"), ("openai/gpt-4.1-mini", "gpt-4.1"),
+ ("openai/gpt-4.1-nano", "gpt-4.1"), ("openai/gpt-4o", "gpt-4o"), ("openai/gpt-4o-mini", "gpt-4o-mini"),
+ ("openai/o1", "gpt-5.2"), ("openai/o1-mini", "gpt-5-mini"), ("openai/o1-preview", "gpt-5.2"),
+ ("openai/o3", "gpt-5.3-codex"), ("openai/o3-mini", "gpt-5-mini"), ("openai/o4-mini", "gpt-5-mini"),
+ ("anthropic/claude-opus-4.6", "claude-opus-4.6"), ("anthropic/claude-sonnet-5", "claude-sonnet-5"),
+ ("anthropic/claude-sonnet-4.6", "claude-sonnet-4.6"), ("anthropic/claude-sonnet-4", "claude-sonnet-4"),
+ ("anthropic/claude-sonnet-4.5", "claude-sonnet-4.5"), ("anthropic/claude-haiku-4.5", "claude-haiku-4.5"),
+ ("claude-sonnet-5", "claude-sonnet-5"), ("claude-opus-4-6", "claude-opus-4.6"),
+ ("claude-sonnet-4-6", "claude-sonnet-4.6"), ("claude-sonnet-4-0", "claude-sonnet-4"),
+ ("claude-sonnet-4-5", "claude-sonnet-4.5"), ("claude-haiku-4-5", "claude-haiku-4.5"),
+ ("anthropic/claude-opus-4-6", "claude-opus-4.6"), ("anthropic/claude-sonnet-4-6", "claude-sonnet-4.6"),
+ ("anthropic/claude-sonnet-4-0", "claude-sonnet-4"), ("anthropic/claude-sonnet-4-5", "claude-sonnet-4.5"),
+ ("anthropic/claude-haiku-4-5", "claude-haiku-4.5"),
+))
+
+
+# ─── catalog credential (best effort) ───
+
+def _first_exchangeable_copilot_token(raw_tokens) -> str:
+ """Exchange stored GitHub tokens in order; the first that validates AND exchanges wins (every
+ entry is tried so a later valid token survives an earlier malformed one)."""
+ from .credentials import exchange_copilot_token, validate_copilot_token
+
+ for raw in raw_tokens:
+ raw = str(raw or "").strip()
+ if not raw or not validate_copilot_token(raw)[0]:
+ continue
+ try:
+ api_token = exchange_copilot_token(raw)[0] # (api_token, expires_at, base_url)
+ except Exception:
+ continue
+ if api_token:
+ return api_token
+ return ""
+
+
+def _copilot_cli_config_tokens() -> list[str]:
+ """``copilotTokens`` from the GitHub Copilot CLI's own plaintext store (JSONC — strip
+ ``//``-comment lines), written by ``copilot login`` on hosts without an OS keychain."""
+ cli_config = os.path.expanduser("~/.copilot/config.json")
+ if not os.path.isfile(cli_config):
+ return []
+ with open(cli_config, "r", encoding="utf-8-sig", errors="ignore") as fh:
+ raw_text = "\n".join(
+ line for line in fh.read().splitlines() if not line.lstrip().startswith("//"))
+ data = json.loads(raw_text) if raw_text.strip() else {}
+ tokens = data.get("copilotTokens")
+ return list(tokens.values()) if isinstance(tokens, dict) else []
+
+
+def _resolve_copilot_catalog_api_key() -> str:
+ """Best-effort GitHub token for the Copilot catalog: env vars / ``gh auth token`` via
+ ``resolve_api_key_provider_credentials``, then ``auth.json`` ``credential_pool.copilot[]``, then
+ ``~/.copilot/config.json`` ``copilotTokens`` (the ACP CLI's own store). Without the latter two,
+ keyless users see the picker fall back to the stale curated list on a silent 401."""
+ def _env_token() -> str:
+ from hermes_cli.models import _api_key_credentials
+
+ return _api_key_credentials("copilot")[0]
+
+ def _pool_token() -> str:
+ from hermes_cli.auth import read_credential_pool
+
+ return _first_exchangeable_copilot_token(
+ entry.get("access_token") for entry in read_credential_pool("copilot") if isinstance(entry, dict))
+
+ sources = (
+ _env_token,
+ _pool_token,
+ lambda: _first_exchangeable_copilot_token(_copilot_cli_config_tokens()),
+ )
+ for source in sources:
+ try:
+ token = source()
+ except Exception:
+ continue
+ if token:
+ return token
+ return ""
+
+
+# ─── live /models catalog ───
+
+def copilot_default_headers(*, is_agent_turn: bool = True) -> dict[str, str]:
+ """Standard headers for Copilot API requests."""
+ from .credentials import copilot_request_headers
+
+ return copilot_request_headers(is_agent_turn=is_agent_turn)
+
+
+_COPILOT_CHAT_ENDPOINTS = {"/chat/completions", "/responses", "/v1/messages"}
+
+
+def _payload_items(payload: Any) -> list[dict[str, Any]]:
+ data = payload.get("data", []) if isinstance(payload, dict) else payload
+ return [item for item in data if isinstance(item, dict)] if isinstance(data, list) else []
+
+
+def _copilot_catalog_item_is_text_model(
+ item: dict[str, Any], *, ignore_picker_flag: bool = False) -> bool:
+ if not str(item.get("id") or "").strip():
+ return False
+ if not ignore_picker_flag and item.get("model_picker_enabled") is False:
+ return False
+ capabilities = item.get("capabilities")
+ if isinstance(capabilities, dict):
+ model_type = str(capabilities.get("type") or "").strip().lower()
+ if model_type and model_type != "chat":
+ return False
+ supported_endpoints = item.get("supported_endpoints")
+ if isinstance(supported_endpoints, list):
+ endpoints = {e for endpoint in supported_endpoints if (e := str(endpoint).strip())}
+ if endpoints and not endpoints & _COPILOT_CHAT_ENDPOINTS:
+ return False
+ return True
+
+
+def _copilot_text_models(items: list[dict[str, Any]], *, ignore_picker_flag: bool = False) -> list[dict[str, Any]]:
+ """Chat-capable catalog rows, deduped by id, in catalog order."""
+ models: list[dict[str, Any]] = []
+ seen_ids: set[str] = set()
+ for item in items:
+ model_id = str(item.get("id") or "").strip()
+ if model_id in seen_ids:
+ continue
+ if not _copilot_catalog_item_is_text_model(item, ignore_picker_flag=ignore_picker_flag):
+ continue
+ seen_ids.add(model_id)
+ models.append(item)
+ return models
+
+
+# Short-TTL cache of the filtered GitHub Copilot /models catalog (picker + context/normalize helpers
+# share it). Keyed by the api_key of the successful fetch so a credential swap never serves the
+# previous account's catalog; monotonic clock; lock-free (a race at worst duplicates one fetch).
+_github_model_catalog_cache: Optional[list[dict[str, Any]]] = None
+_github_model_catalog_cache_key: Optional[str] = None
+_github_model_catalog_cache_time: float = 0.0
+_GITHUB_MODEL_CATALOG_CACHE_TTL = 300 # 5 minutes
+
+
+def fetch_github_model_catalog(
+ api_key: Optional[str] = None, timeout: float = 5.0) -> Optional[list[dict[str, Any]]]:
+ """Fetch the live GitHub Copilot model catalog for this account."""
+ global _github_model_catalog_cache, _github_model_catalog_cache_key
+ global _github_model_catalog_cache_time
+ from hermes_cli.models import _get_json
+
+ if (
+ _github_model_catalog_cache is not None
+ and _github_model_catalog_cache_key == api_key
+ and (time.monotonic() - _github_model_catalog_cache_time) < _GITHUB_MODEL_CATALOG_CACHE_TTL
+ ):
+ return copy.deepcopy(_github_model_catalog_cache) # deep: callers must not mutate cached dicts
+
+ attempts: list[dict[str, str]] = []
+ if api_key:
+ attempts.append({**copilot_default_headers(), "Authorization": f"Bearer {api_key}"})
+ attempts.append(copilot_default_headers())
+
+ for headers in attempts:
+ try:
+ items = _payload_items(_get_json(COPILOT_MODELS_URL, timeout=timeout, headers=headers))
+ except Exception:
+ continue
+ models = _copilot_text_models(items)
+ if not models and items:
+ # GitHub has been observed returning ``model_picker_enabled: false`` for EVERY model on
+ # some accounts, which would strand the picker on the stale curated fallback. The flag
+ # is a display hint, not an availability contract — retry without it (chat/endpoint
+ # checks still apply).
+ models = _copilot_text_models(items, ignore_picker_flag=True)
+ if models:
+ _github_model_catalog_cache = copy.deepcopy(models)
+ _github_model_catalog_cache_key = api_key
+ _github_model_catalog_cache_time = time.monotonic()
+ return models
+ return None
+
+
+def _fetch_github_models(api_key: Optional[str] = None, timeout: float = 5.0) -> Optional[list[str]]:
+ catalog = fetch_github_model_catalog(api_key=api_key, timeout=timeout)
+ return [item.get("id", "") for item in catalog if item.get("id")] if catalog else None
+
+
+def copilot_picker_catalog(force_refresh: bool = False) -> Optional[list[str]]:
+ """The account's live catalog ids, else the curated list marked as a placeholder."""
+ from hermes_cli.models import CuratedFallbackModels, _PROVIDER_MODELS
+
+ try:
+ live = _fetch_github_models(_resolve_copilot_catalog_api_key())
+ if live:
+ return live
+ except Exception: # the picker degrades to the curated list on any catalog failure
+ logger.debug("copilot live catalog fetch failed", exc_info=True)
+ return CuratedFallbackModels(_PROVIDER_MODELS.get("copilot", list(STATIC_MODELS)))
+
+
+def _is_github_models_base_url(base_url: Optional[str]) -> bool:
+ return (base_url or "").strip().rstrip("/").lower().startswith(_CATALOG_BASE_URLS)
+
+
+# ─── context windows ───
+
+# Module-level cache: {model_id: max_prompt_tokens}
+_copilot_context_cache: dict[str, int] = {}
+_copilot_context_cache_time: float = 0.0
+_copilot_context_cache_key: Optional[str] = None # fingerprint of the api_key the entry was fetched with
+_COPILOT_CONTEXT_CACHE_TTL = 3600 # 1 hour
+
+
+def get_copilot_model_context(model_id: str, api_key: Optional[str] = None) -> Optional[int]:
+ """``max_prompt_tokens`` for a Copilot model from the live /models API (cached in-process 1h; a
+ miss on a fresh cache does not re-fetch), or None."""
+ global _copilot_context_cache, _copilot_context_cache_time, _copilot_context_cache_key
+
+ # Keyed on the credential like fetch_github_model_catalog: the catalog (and its limits) is
+ # per-account, so another profile's token must not be served this entry.
+ from agent.credential_persistence import fingerprint_secret_value
+ key_fp = fingerprint_secret_value(api_key)
+ if (_copilot_context_cache and _copilot_context_cache_key == key_fp
+ and (time.time() - _copilot_context_cache_time < _COPILOT_CONTEXT_CACHE_TTL)):
+ return _copilot_context_cache.get(model_id)
+
+ catalog = fetch_github_model_catalog(api_key=api_key)
+ if not catalog:
+ return None
+ cache: dict[str, int] = {}
+ for item in catalog:
+ mid = str(item.get("id") or "").strip()
+ max_prompt = ((item.get("capabilities") or {}).get("limits") or {}).get("max_prompt_tokens")
+ if mid and isinstance(max_prompt, int) and max_prompt > 0:
+ cache[mid] = max_prompt
+ _copilot_context_cache = cache
+ _copilot_context_cache_time = time.time()
+ _copilot_context_cache_key = key_fp
+ return cache.get(model_id)
+
+
+# ─── id normalization and reasoning efforts ───
+
+def _copilot_catalog_ids(
+ catalog: Optional[list[dict[str, Any]]] = None, api_key: Optional[str] = None) -> set[str]:
+ if catalog is None and api_key:
+ catalog = fetch_github_model_catalog(api_key=api_key)
+ return {mid for item in (catalog or []) if (mid := str(item.get("id") or "").strip())}
+
+
+def normalize_copilot_model_id(
+ model_id: Optional[str], *, catalog: Optional[list[dict[str, Any]]] = None,
+ api_key: Optional[str] = None) -> str:
+ raw = str(model_id or "").strip()
+ if not raw:
+ return ""
+
+ catalog_ids = _copilot_catalog_ids(catalog=catalog, api_key=api_key)
+ alias = MODEL_ALIASES.get(raw)
+ if alias:
+ return alias
+
+ candidates = [raw]
+ if "/" in raw:
+ candidates.append(raw.split("/", 1)[1].strip())
+ if raw.endswith(("-mini", "-nano", "-chat")):
+ candidates.append(raw[:-5])
+
+ seen: set[str] = set()
+ for candidate in candidates:
+ if not candidate or candidate in seen:
+ continue
+ seen.add(candidate)
+ if candidate in MODEL_ALIASES:
+ return MODEL_ALIASES[candidate]
+ if candidate in catalog_ids:
+ return candidate
+
+ if "/" in raw:
+ stripped = raw.split("/", 1)[1].strip()
+ # Enterprise BYOK custom models expose ``owner/sub/model`` ids (two
+ # slashes). A strip guess that still contains "/" cannot be a Copilot
+ # id, so pass the input through untouched instead of corrupting it.
+ if stripped and "/" not in stripped:
+ return stripped
+ return raw
+
+
+def clamp_github_reasoning_effort(effort: Any, supported: list[str]) -> str:
+ """Copilot/GitHub Models effort for a non-empty *supported* list: the level itself when listed,
+ else the nearest WEAKER listed level; bespoke names the ladder can't place fall to ``medium``
+ (or the first listed level)."""
+ from agent.reasoning_effort import clamp_effort
+
+ effort = str(effort or "medium").strip().lower()
+ if effort not in supported:
+ effort = clamp_effort(effort, supported)
+ if effort not in supported:
+ effort = "medium" if "medium" in supported else supported[0]
+ return effort
+
+
+def _github_reasoning_efforts_for_model_id(model_id: str) -> list[str]:
+ from agent.reasoning_effort import CODEX_ASTRA_EFFORTS, is_astra_model
+
+ raw = (model_id or "").strip().lower()
+ if raw.startswith(("openai/o1", "openai/o3", "openai/o4", "o1", "o3", "o4")):
+ return list(REASONING_EFFORTS_O_SERIES)
+ normalized = normalize_copilot_model_id(model_id).lower()
+ if is_astra_model(normalized):
+ return list(CODEX_ASTRA_EFFORTS)
+ if normalized.startswith("gpt-5"):
+ return list(REASONING_EFFORTS_GPT5)
+ return []
+
+
+def github_model_reasoning_efforts(
+ model_id: Optional[str], *, catalog: Optional[list[dict[str, Any]]] = None,
+ api_key: Optional[str] = None) -> list[str]:
+ """Return supported reasoning-effort levels for a Copilot-visible model."""
+ normalized = normalize_copilot_model_id(model_id, catalog=catalog, api_key=api_key)
+ if not normalized:
+ return []
+
+ if catalog is None and api_key:
+ catalog = fetch_github_model_catalog(api_key=api_key)
+ catalog_entry = next((item for item in catalog if item.get("id") == normalized), None) if catalog else None
+ if catalog_entry is not None:
+ capabilities = catalog_entry.get("capabilities")
+ if isinstance(capabilities, dict):
+ # Structured catalog: the advertised list is authoritative (empty when absent).
+ supports = capabilities.get("supports")
+ efforts = supports.get("reasoning_effort") if isinstance(supports, dict) else None
+ if not isinstance(efforts, list):
+ return []
+ return list(dict.fromkeys(e for effort in efforts if (e := str(effort).strip().lower())))
+ # Legacy list-shaped capabilities: only a "reasoning" tag unlocks the pattern defaults.
+ if "reasoning" not in {str(c).strip().lower() for c in catalog_entry.get("capabilities", [])}:
+ return []
+ return _github_reasoning_efforts_for_model_id(str(model_id or normalized))
+
+
+# ProviderProfile kwargs filling the I2-cat catalog seams.
+CATALOG_FIELDS = dict(
+ picker_catalog=copilot_picker_catalog, static_models=STATIC_MODELS,
+ catalog_credential_files=CATALOG_CREDENTIAL_FILES,
+)
class CopilotCatalogMixin:
"""Catalog/metadata hooks for the Copilot profiles."""
def live_context_length(self, model: str, *, api_key: str = "", base_url: str = "") -> int | None:
- from hermes_cli.models import get_copilot_model_context
-
return get_copilot_model_context(model, api_key=api_key)
def normalize_model_id(self, model: str, *, api_key: str = "") -> str | None:
- from hermes_cli.models import normalize_copilot_model_id
-
return normalize_copilot_model_id(model, api_key=api_key or None)
+
+ def probe_models(
+ self, *, base_url: str, api_key: str | None = None, timeout: float = 5.0,
+ ) -> tuple[list[str] | None, str, str] | None:
+ if not _is_github_models_base_url(base_url):
+ return None
+ return _fetch_github_models(api_key=api_key, timeout=timeout), COPILOT_MODELS_URL, COPILOT_BASE_URL
diff --git a/plugins/model-providers/copilot/responses.py b/plugins/model-providers/copilot/responses.py
index 1db63383895..eab4549b808 100644
--- a/plugins/model-providers/copilot/responses.py
+++ b/plugins/model-providers/copilot/responses.py
@@ -38,7 +38,7 @@ class CopilotResponsesMixin:
"""Endpoint ownership, catalog-clamped reasoning payloads and the ``/chat/completions`` carriers."""
def reasoning_payload(self, model: str | None, reasoning_config: dict | None, *, base_url: str) -> dict | None:
- from hermes_cli.models import clamp_github_reasoning_effort, github_model_reasoning_efforts
+ from .catalog import clamp_github_reasoning_effort, github_model_reasoning_efforts
supported = github_model_reasoning_efforts(model)
if not supported:
diff --git a/plugins/model-providers/copilot/setup.py b/plugins/model-providers/copilot/setup.py
index 877dbf64dd4..19cdbd9db91 100644
--- a/plugins/model-providers/copilot/setup.py
+++ b/plugins/model-providers/copilot/setup.py
@@ -36,7 +36,7 @@ def _copilot_model_list(live_ids) -> list:
def _copilot_catalog(api_key: str):
"""``(catalog, catalog_ids, normalize)`` for a GitHub token; *normalize* canonicalizes a
model id against the catalog (identity when unknown)."""
- from hermes_cli.models import fetch_github_model_catalog, normalize_copilot_model_id
+ from .catalog import fetch_github_model_catalog, normalize_copilot_model_id
catalog = fetch_github_model_catalog(api_key)
ids = [item.get("id", "") for item in catalog if item.get("id")] if catalog else []
@@ -141,7 +141,7 @@ def model_flow_copilot(config, current_model="", args=None):
def setup_reasoning_efforts(model: str) -> tuple:
"""Copilot publishes a per-model effort set; ``()`` when the model takes none."""
- from hermes_cli.models import github_model_reasoning_efforts
+ from .catalog import github_model_reasoning_efforts
return tuple(github_model_reasoning_efforts(model) or ())
diff --git a/plugins/model-providers/copilot/wire.py b/plugins/model-providers/copilot/wire.py
index cde6f371c47..e15e9ac7182 100644
--- a/plugins/model-providers/copilot/wire.py
+++ b/plugins/model-providers/copilot/wire.py
@@ -35,7 +35,7 @@ def model_api_mode(
"""API mode for a Copilot model from the id pattern (opencode's approach). Copilot's Claude models
go through its OpenAI-compatible chat endpoint, not the native Anthropic adapter: the catalog may
advertise /v1/messages but the Copilot token/header scheme lives in the OpenAI client path."""
- from hermes_cli.models import fetch_github_model_catalog, normalize_copilot_model_id
+ from .catalog import fetch_github_model_catalog, normalize_copilot_model_id
if catalog is None and api_key: # fetch once so normalize + endpoint check share it
catalog = fetch_github_model_catalog(api_key=api_key)
diff --git a/providers/base.py b/providers/base.py
index da1f3bca24a..c9fc514f473 100644
--- a/providers/base.py
+++ b/providers/base.py
@@ -688,3 +688,24 @@ class ProviderProfile:
def replays_function_thought_signature(self, *, model: str | None, base_url: str) -> bool:
"""True when replayed tool calls keep ``function.thought_signature`` (stripped everywhere else)."""
return False
+
+ # --- I2-cat: provider-owned catalog sources ---
+ # ``picker_catalog(force_refresh) -> list | None``: the provider's own model-picker catalog (own
+ # credential lookup, live fetch, curated fallback); set = a live source, tried before the generic
+ # profile fetch like a built-in per-provider fetcher. None return falls through to that path.
+ picker_catalog: Callable[[bool], Any] | None = field(default=None, kw_only=True)
+ # Curated ids registered as this provider's row of core's static catalog (model detection,
+ # defaults, validation) the way a built-in provider's curated list is; empty = no row.
+ static_models: tuple = field(default=(), kw_only=True)
+ # Credential files (``~`` allowed) whose mtime is folded into every cached catalog's fingerprint.
+ catalog_credential_files: tuple = field(default=(), kw_only=True)
+
+ def probe_models(
+ self, *, base_url: str, api_key: str | None = None, timeout: float = 5.0,
+ ) -> tuple[list[str] | None, str, str] | None:
+ """``(model ids or None, probed_url, resolved_base_url)`` for a ``/models`` probe of *base_url*
+ this provider answers from its own catalog; None = the generic HTTP probe."""
+ return None
+
+ def invalidate_catalog_cache(self) -> None:
+ """Drop in-process catalog memos (``/model --refresh``); default none."""
diff --git a/tests/agent/test_copilot_initiator.py b/tests/agent/test_copilot_initiator.py
index dc7c95392d8..997aa065cff 100644
--- a/tests/agent/test_copilot_initiator.py
+++ b/tests/agent/test_copilot_initiator.py
@@ -72,9 +72,9 @@ class TestHeaderValues:
"""copilot_default_headers(is_agent_turn=...) sets x-initiator correctly."""
def test_default_is_agent(self):
- from hermes_cli.models import copilot_default_headers
+ from plugins.model_providers.copilot.catalog import copilot_default_headers
assert copilot_default_headers()["x-initiator"] == "agent"
def test_user_turn(self):
- from hermes_cli.models import copilot_default_headers
+ from plugins.model_providers.copilot.catalog import copilot_default_headers
assert copilot_default_headers(is_agent_turn=False)["x-initiator"] == "user"
diff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.py
index 1008c64d757..4638796e07c 100644
--- a/tests/agent/test_run_agent.py
+++ b/tests/agent/test_run_agent.py
@@ -1350,8 +1350,9 @@ class TestBuildApiKwargs:
def test_core_responses_preserves_supported_xhigh(self, agent, monkeypatch):
"""The core GitHub Responses path must preserve a supported xhigh."""
- monkeypatch.setattr(
- "hermes_cli.models.github_model_reasoning_efforts",
+ from plugins.model_providers.copilot import catalog as copilot_catalog
+
+ monkeypatch.setattr(copilot_catalog, "github_model_reasoning_efforts",
lambda _model: ["none", "low", "medium", "high", "xhigh"],
)
agent.model, agent.base_url = "gpt-5.5", "https://api.githubcopilot.com"
diff --git a/tests/hermes_cli/test_api_key_providers.py b/tests/hermes_cli/test_api_key_providers.py
index 848c72d3995..98e2decb150 100644
--- a/tests/hermes_cli/test_api_key_providers.py
+++ b/tests/hermes_cli/test_api_key_providers.py
@@ -34,6 +34,7 @@ from plugins.model_providers.copilot.credentials import _try_gh_cli_token
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 catalog as copilot_catalog
from plugins.model_providers.copilot import credentials as copilot_credentials
_EXTRA_ENV_VARS = (
@@ -277,8 +278,7 @@ class TestRuntimeProviderResolution:
"hermes_cli.runtime_provider._get_model_config",
lambda: {"provider": "copilot", "default": "gpt-5.4"},
)
- monkeypatch.setattr(
- "hermes_cli.models.fetch_github_model_catalog",
+ monkeypatch.setattr(copilot_catalog, "fetch_github_model_catalog",
lambda api_key=None, timeout=5.0: [
{
"id": "gpt-5.4",
diff --git a/tests/hermes_cli/test_copilot_in_model_list.py b/tests/hermes_cli/test_copilot_in_model_list.py
index b75cb6abf8a..7d383cd68e9 100644
--- a/tests/hermes_cli/test_copilot_in_model_list.py
+++ b/tests/hermes_cli/test_copilot_in_model_list.py
@@ -9,6 +9,10 @@ from hermes_cli.model_switch import list_authenticated_providers
from hermes_cli import model_switch_providers
from hermes_cli import models
from hermes_cli.models import provider_model_ids
+import providers as _providers
+
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (catalog module)
+from plugins.model_providers.copilot import catalog as copilot_catalog
@patch.dict(os.environ, {"GH_TOKEN": "test-key"}, clear=False)
@@ -16,8 +20,8 @@ def test_copilot_picker_uses_live_catalog_when_available():
live_models = ["gpt-5.4", "claude-sonnet-4.6", "gemini-3.1-pro-preview"]
with patch("agent.models_dev.fetch_models_dev", return_value={}), \
- patch("hermes_cli.models._resolve_copilot_catalog_api_key", return_value="gh-token"), \
- patch("hermes_cli.models._fetch_github_models", return_value=live_models):
+ patch.object(copilot_catalog, "_resolve_copilot_catalog_api_key", return_value="gh-token"), \
+ patch.object(copilot_catalog, "_fetch_github_models", return_value=live_models):
providers = list_authenticated_providers(current_provider="openrouter", max_models=50)
copilot = next((p for p in providers if p["slug"] == "copilot"), None)
@@ -61,8 +65,8 @@ def test_copilot_acp_listed_when_executable_resolves(tmp_path, monkeypatch, _no_
monkeypatch.setenv("HERMES_COPILOT_ACP_COMMAND", str(fake))
with patch("agent.models_dev.fetch_models_dev", return_value={}), \
- patch("hermes_cli.models._resolve_copilot_catalog_api_key", return_value=None), \
- patch("hermes_cli.models._fetch_github_models", return_value=[]):
+ patch.object(copilot_catalog, "_resolve_copilot_catalog_api_key", return_value=None), \
+ patch.object(copilot_catalog, "_fetch_github_models", return_value=[]):
providers = list_authenticated_providers(current_provider="openrouter", max_models=50)
acp = next((p for p in providers if p["slug"] == "copilot-acp"), None)
@@ -79,8 +83,8 @@ def test_copilot_acp_hidden_when_executable_missing(monkeypatch, _no_other_copil
monkeypatch.setattr(auth.shutil, "which", lambda *_a, **_k: None)
with patch("agent.models_dev.fetch_models_dev", return_value={}), \
- patch("hermes_cli.models._resolve_copilot_catalog_api_key", return_value=None), \
- patch("hermes_cli.models._fetch_github_models", return_value=[]):
+ patch.object(copilot_catalog, "_resolve_copilot_catalog_api_key", return_value=None), \
+ patch.object(copilot_catalog, "_fetch_github_models", return_value=[]):
providers = list_authenticated_providers(current_provider="openrouter", max_models=50)
assert all(p["slug"] != "copilot-acp" for p in providers), \
@@ -90,12 +94,21 @@ def test_copilot_acp_hidden_when_executable_missing(monkeypatch, _no_other_copil
_ACP_CREDS = {"api_key": "copilot-acp", "base_url": "acp://copilot", "command": "copilot", "args": ["--acp", "--stdio"]}
+def _acp_catalog():
+ import providers
+
+ providers.get_provider_profile("copilot-acp") # discovery imports the bundled plugin package
+ from plugins.model_providers.copilot_acp import catalog
+
+ return catalog
+
+
@pytest.fixture()
def _fresh_acp_memo(monkeypatch):
- monkeypatch.setattr(models, "_copilot_acp_session_memo", None)
+ monkeypatch.setattr(_acp_catalog(), "_session_memo", None)
yield
# Don't leak a memoized (possibly failed) probe into other tests in this process.
- monkeypatch.setattr(models, "_copilot_acp_session_memo", None)
+ monkeypatch.setattr(_acp_catalog(), "_session_memo", None)
def _copilot_acp_client():
@@ -121,8 +134,8 @@ def test_copilot_acp_catalog_prefers_authenticated_session(
_fresh_acp_memo, session_probe, github_token, github_models, expected):
with patch("hermes_cli.auth.resolve_external_process_provider_credentials", return_value=_ACP_CREDS), \
patch.object(_copilot_acp_client(), "list_models", **session_probe) as list_models, \
- patch("hermes_cli.models._resolve_copilot_catalog_api_key", return_value=github_token), \
- patch("hermes_cli.models._fetch_github_models", return_value=github_models) as github:
+ patch.object(copilot_catalog, "_resolve_copilot_catalog_api_key", return_value=github_token), \
+ patch.object(copilot_catalog, "_fetch_github_models", return_value=github_models) as github:
assert provider_model_ids("copilot-acp", force_refresh=True) == expected
list_models.assert_called_once()
@@ -136,18 +149,18 @@ def test_copilot_acp_session_probe_is_memoized_across_model_switch_validation(_f
with patch("hermes_cli.auth.resolve_external_process_provider_credentials", return_value=_ACP_CREDS), \
patch.object(_copilot_acp_client(), "list_models", return_value=["gpt-5.6-terra"]) as list_models, \
- patch("hermes_cli.models._resolve_copilot_catalog_api_key", return_value=""), \
- patch("hermes_cli.models._fetch_github_models", return_value=[]):
+ patch.object(copilot_catalog, "_resolve_copilot_catalog_api_key", return_value=""), \
+ patch.object(copilot_catalog, "_fetch_github_models", return_value=[]):
for _ in range(3):
verdict = validate_requested_model("gpt-5.6-terra", "copilot-acp", api_key="copilot-acp", base_url="acp://copilot")
assert verdict["accepted"] and verdict["recognized"]
assert list_models.call_count == 1
- models._copilot_acp_session_memo = None # (teardown in _fresh_acp_memo restores it)
+ _acp_catalog()._session_memo = None # (teardown in _fresh_acp_memo restores it)
with patch("hermes_cli.auth.resolve_external_process_provider_credentials", return_value=_ACP_CREDS), \
patch.object(_copilot_acp_client(), "list_models", side_effect=RuntimeError("not signed in")) as list_models, \
- patch("hermes_cli.models._resolve_copilot_catalog_api_key", return_value=""), \
- patch("hermes_cli.models._fetch_github_models", return_value=[]):
+ patch.object(copilot_catalog, "_resolve_copilot_catalog_api_key", return_value=""), \
+ patch.object(copilot_catalog, "_fetch_github_models", return_value=[]):
for _ in range(3):
provider_model_ids("copilot-acp")
assert list_models.call_count == 1
diff --git a/tests/hermes_cli/test_copilot_runtime_api_mode.py b/tests/hermes_cli/test_copilot_runtime_api_mode.py
index 2800e03971b..a9cf2d917da 100644
--- a/tests/hermes_cli/test_copilot_runtime_api_mode.py
+++ b/tests/hermes_cli/test_copilot_runtime_api_mode.py
@@ -43,15 +43,18 @@ def test_resolver_routes_copilot_by_target_model_for_every_credential_path(
expected_mode,
):
"""The public resolver must propagate the target through every auth path."""
- from hermes_cli import models
+ import providers
from hermes_cli import runtime_provider as rp
+ providers.get_provider_profile("copilot") # imports the copilot plugin package (catalog module)
+ from plugins.model_providers.copilot import catalog as copilot_catalog
+
model_cfg = {"provider": "copilot", "default": configured_model}
monkeypatch.setattr(rp, "_get_model_config", lambda: model_cfg)
monkeypatch.setattr(rp, "resolve_provider", lambda *_args, **_kwargs: "copilot")
# Keep this a real Copilot model_api_mode decision without making a live
# catalog request. The API-mode contract is determined by the model family.
- monkeypatch.setattr(models, "fetch_github_model_catalog", lambda **_kwargs: [])
+ monkeypatch.setattr(copilot_catalog, "fetch_github_model_catalog", lambda **_kwargs: [])
kwargs = {"requested": "copilot", "target_model": target_model}
if credential_source == "pool":
diff --git a/tests/hermes_cli/test_external_process_auth_status.py b/tests/hermes_cli/test_external_process_auth_status.py
index f95d10c7c67..25d45c86805 100644
--- a/tests/hermes_cli/test_external_process_auth_status.py
+++ b/tests/hermes_cli/test_external_process_auth_status.py
@@ -338,7 +338,7 @@ def test_catalog_key_resolves_from_copilot_cli_store(tmp_path, monkeypatch, _cle
# curated list (visibly wrong vs. what their subscription serves).
from unittest.mock import patch as mock_patch
- from hermes_cli import models as models_mod
+ from plugins.model_providers.copilot import catalog
monkeypatch.setenv("HOME", str(tmp_path))
cfg_dir = tmp_path / ".copilot"
@@ -350,7 +350,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
+ catalog, "_resolve_copilot_catalog_api_key", wraps=catalog._resolve_copilot_catalog_api_key
), mock_patch.object(copilot_credentials, "exchange_copilot_token",
return_value=("exchanged-api-token", 0.0, None),
), mock_patch(
@@ -359,7 +359,7 @@ def test_catalog_key_resolves_from_copilot_cli_store(tmp_path, monkeypatch, _cle
), mock_patch(
"hermes_cli.auth.read_credential_pool", return_value=[]
):
- key = models_mod._resolve_copilot_catalog_api_key()
+ key = catalog._resolve_copilot_catalog_api_key()
assert key == "exchanged-api-token"
@@ -367,7 +367,7 @@ def test_catalog_key_resolves_from_copilot_cli_store(tmp_path, monkeypatch, _cle
def test_catalog_key_empty_when_cli_store_absent(tmp_path, monkeypatch, _clean_copilot_env):
from unittest.mock import patch as mock_patch
- from hermes_cli import models as models_mod
+ from plugins.model_providers.copilot import catalog
monkeypatch.setenv("HOME", str(tmp_path)) # no ~/.copilot at all
@@ -377,6 +377,6 @@ def test_catalog_key_empty_when_cli_store_absent(tmp_path, monkeypatch, _clean_c
), mock_patch(
"hermes_cli.auth.read_credential_pool", return_value=[]
):
- key = models_mod._resolve_copilot_catalog_api_key()
+ key = catalog._resolve_copilot_catalog_api_key()
assert key == ""
diff --git a/tests/hermes_cli/test_model_cache_fallback_rows.py b/tests/hermes_cli/test_model_cache_fallback_rows.py
index b2a05f08070..42c6242bc2d 100644
--- a/tests/hermes_cli/test_model_cache_fallback_rows.py
+++ b/tests/hermes_cli/test_model_cache_fallback_rows.py
@@ -12,6 +12,11 @@ from unittest.mock import patch
import pytest
import hermes_cli.models as mod
+import providers as _providers
+
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (catalog module)
+from plugins.model_providers.copilot import catalog as copilot_catalog
+from plugins.model_providers.copilot_acp import catalog as acp_catalog
@pytest.fixture(autouse=True)
@@ -73,9 +78,9 @@ def test_fallback_row_is_recorded_as_fallback_and_never_served_stale():
def test_copilot_catalog_marks_the_static_list_as_fallback_on_a_failed_live_fetch():
- with patch.object(mod, "_copilot_acp_session_models", return_value=None), \
- patch.object(mod, "_resolve_copilot_catalog_api_key", return_value="tok"), \
- patch.object(mod, "_fetch_github_models", side_effect=OSError("503")):
+ with patch.object(acp_catalog, "session_models", return_value=None), \
+ patch.object(copilot_catalog, "_resolve_copilot_catalog_api_key", return_value="tok"), \
+ patch.object(copilot_catalog, "_fetch_github_models", side_effect=OSError("503")):
for slug in ("copilot", "copilot-acp"):
rows = mod.provider_model_ids(slug)
assert isinstance(rows, mod.CuratedFallbackModels), slug
diff --git a/tests/hermes_cli/test_multiplex_cli_cache_scope.py b/tests/hermes_cli/test_multiplex_cli_cache_scope.py
index 6f6fb4c11be..4780eb9fdbd 100644
--- a/tests/hermes_cli/test_multiplex_cli_cache_scope.py
+++ b/tests/hermes_cli/test_multiplex_cli_cache_scope.py
@@ -82,11 +82,15 @@ def test_deepinfra_catalog_is_fetched_with_each_profiles_key(homes, monkeypatch)
def test_copilot_context_cache_hit_requires_same_api_key(homes, monkeypatch):
+ import providers
from hermes_cli import models
- monkeypatch.setattr(models, "_copilot_context_cache", {})
- monkeypatch.setattr(models, "_copilot_context_cache_time", 0.0)
- monkeypatch.setattr(models, "_github_model_catalog_cache", None)
+ providers.get_provider_profile("copilot") # imports the copilot plugin package (catalog module)
+ from plugins.model_providers.copilot import catalog
+
+ monkeypatch.setattr(catalog, "_copilot_context_cache", {})
+ monkeypatch.setattr(catalog, "_copilot_context_cache_time", 0.0)
+ monkeypatch.setattr(catalog, "_github_model_catalog_cache", None)
def transport(req, *, timeout, **kw):
limit = 111 if req.headers.get("Authorization", "").endswith("copilot-A") else 222
@@ -95,9 +99,9 @@ def test_copilot_context_cache_hit_requires_same_api_key(homes, monkeypatch):
"capabilities": {"type": "chat", "limits": {"max_prompt_tokens": limit}}}]})
monkeypatch.setattr(models, "_urlopen_model_catalog_request", transport)
- assert models.get_copilot_model_context("gpt-x", api_key="copilot-A") == 111
- assert models.get_copilot_model_context("gpt-x", api_key="copilot-B") == 222
- assert models.get_copilot_model_context("gpt-x", api_key="copilot-A") == 111
+ assert catalog.get_copilot_model_context("gpt-x", api_key="copilot-A") == 111
+ assert catalog.get_copilot_model_context("gpt-x", api_key="copilot-B") == 222
+ assert catalog.get_copilot_model_context("gpt-x", api_key="copilot-A") == 111
def test_nous_reasoning_caps_follow_each_profiles_portal(homes, monkeypatch):
diff --git a/tests/plugins/model_providers/test_copilot_acp_deprecation.py b/tests/plugins/model_providers/test_copilot_acp_deprecation.py
index c815b8a8ac9..fab5f8f3b41 100644
--- a/tests/plugins/model_providers/test_copilot_acp_deprecation.py
+++ b/tests/plugins/model_providers/test_copilot_acp_deprecation.py
@@ -64,12 +64,12 @@ class TestGitHubModelsAzureUrl:
def test_is_github_models_base_url_recognises_azure(self):
- from hermes_cli.models import _is_github_models_base_url
+ from plugins.model_providers.copilot.catalog import _is_github_models_base_url
assert _is_github_models_base_url("https://models.inference.ai.azure.com")
assert _is_github_models_base_url("https://models.inference.ai.azure.com/v1/chat")
def test_is_github_models_base_url_still_recognises_github_ai(self):
- from hermes_cli.models import _is_github_models_base_url
+ from plugins.model_providers.copilot.catalog import _is_github_models_base_url
assert _is_github_models_base_url("https://models.github.ai/inference")
diff --git a/tests/plugins/model_providers/test_copilot_auth.py b/tests/plugins/model_providers/test_copilot_auth.py
index e6d934bb5b8..d7994a56f88 100644
--- a/tests/plugins/model_providers/test_copilot_auth.py
+++ b/tests/plugins/model_providers/test_copilot_auth.py
@@ -134,12 +134,12 @@ class TestRequestHeaders:
class TestCopilotDefaultHeaders:
- """The models.py copilot_default_headers uses copilot_credentials."""
+ """The catalog module's copilot_default_headers uses copilot_credentials."""
def test_param_passthrough_both_values(self):
"""is_agent_turn param correctly maps to x-initiator for both True and False."""
- from hermes_cli.models import copilot_default_headers
+ from plugins.model_providers.copilot.catalog import copilot_default_headers
for is_agent, expected in [(True, "agent"), (False, "user")]:
headers = copilot_default_headers(is_agent_turn=is_agent)
assert headers["x-initiator"] == expected, (
diff --git a/tests/hermes_cli/test_copilot_catalog_oauth_fallback.py b/tests/plugins/model_providers/test_copilot_catalog_oauth_fallback.py
similarity index 96%
rename from tests/hermes_cli/test_copilot_catalog_oauth_fallback.py
rename to tests/plugins/model_providers/test_copilot_catalog_oauth_fallback.py
index 85e83bac4a2..66705abc061 100644
--- a/tests/hermes_cli/test_copilot_catalog_oauth_fallback.py
+++ b/tests/plugins/model_providers/test_copilot_catalog_oauth_fallback.py
@@ -12,10 +12,10 @@ 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
+from plugins.model_providers.copilot.catalog import _resolve_copilot_catalog_api_key
class TestCopilotCatalogApiKeyResolution:
diff --git a/tests/hermes_cli/test_copilot_context.py b/tests/plugins/model_providers/test_copilot_context.py
similarity index 86%
rename from tests/hermes_cli/test_copilot_context.py
rename to tests/plugins/model_providers/test_copilot_context.py
index 8914537de88..1778530af13 100644
--- a/tests/hermes_cli/test_copilot_context.py
+++ b/tests/plugins/model_providers/test_copilot_context.py
@@ -7,7 +7,11 @@ from unittest.mock import patch
import pytest
-from hermes_cli.models import get_copilot_model_context
+import providers as _providers
+
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (catalog module)
+from plugins.model_providers.copilot import catalog as copilot_catalog
+from plugins.model_providers.copilot.catalog import get_copilot_model_context
# Sample catalog items mimicking the Copilot /models API response
@@ -50,7 +54,7 @@ _SAMPLE_CATALOG = [
@pytest.fixture(autouse=True)
def _clear_cache():
"""Reset module-level cache before each test."""
- import hermes_cli.models as mod
+ from plugins.model_providers.copilot import catalog as mod
mod._copilot_context_cache = {}
mod._copilot_context_cache_time = 0.0
@@ -62,15 +66,15 @@ def _clear_cache():
class TestGetCopilotModelContext:
"""Tests for get_copilot_model_context()."""
- @patch("hermes_cli.models.fetch_github_model_catalog", return_value=_SAMPLE_CATALOG)
+ @patch.object(copilot_catalog, "fetch_github_model_catalog", return_value=_SAMPLE_CATALOG)
def test_returns_max_prompt_tokens(self, mock_fetch):
assert get_copilot_model_context("claude-opus-4.6-1m") == 1_000_000
assert get_copilot_model_context("gpt-4.1") == 128_000
- @patch("hermes_cli.models.fetch_github_model_catalog", return_value=_SAMPLE_CATALOG)
+ @patch.object(copilot_catalog, "fetch_github_model_catalog", return_value=_SAMPLE_CATALOG)
def test_cache_expires(self, mock_fetch):
- import hermes_cli.models as mod
+ from plugins.model_providers.copilot import catalog as mod
get_copilot_model_context("gpt-4.1")
assert mock_fetch.call_count == 1
@@ -85,7 +89,7 @@ class TestGetCopilotModelContext:
@patch("hermes_cli.models._urlopen_model_catalog_request")
def test_fetch_github_model_catalog_uses_short_lived_cache(self, mock_urlopen):
import json as _json
- import hermes_cli.models as mod
+ from plugins.model_providers.copilot import catalog as mod
mod._github_model_catalog_cache = None
mod._github_model_catalog_cache_key = None
@@ -129,7 +133,7 @@ class TestGetCopilotModelContext:
def test_fetch_github_model_catalog_cache_expires_after_ttl(self, mock_urlopen):
import json as _json
import time as _time
- import hermes_cli.models as mod
+ from plugins.model_providers.copilot import catalog as mod
mod._github_model_catalog_cache = None
mod._github_model_catalog_cache_key = None
@@ -168,7 +172,7 @@ class TestGetCopilotModelContext:
@patch("hermes_cli.models._urlopen_model_catalog_request")
def test_fetch_github_model_catalog_cache_misses_on_credential_change(self, mock_urlopen):
import json as _json
- import hermes_cli.models as mod
+ from plugins.model_providers.copilot import catalog as mod
mod._github_model_catalog_cache = None
mod._github_model_catalog_cache_key = None
@@ -200,7 +204,7 @@ class TestGetCopilotModelContext:
mod.fetch_github_model_catalog(api_key="token-b")
assert mock_urlopen.call_count == 2
- @patch("hermes_cli.models.fetch_github_model_catalog", return_value=[])
+ @patch.object(copilot_catalog, "fetch_github_model_catalog", return_value=[])
def test_returns_none_for_empty_catalog(self, mock_fetch):
assert get_copilot_model_context("gpt-4.1") is None
@@ -208,7 +212,7 @@ class TestGetCopilotModelContext:
class TestModelMetadataCopilotIntegration:
"""Test that get_model_context_length() uses Copilot live API for copilot provider."""
- @patch("hermes_cli.models.fetch_github_model_catalog", return_value=_SAMPLE_CATALOG)
+ @patch.object(copilot_catalog, "fetch_github_model_catalog", return_value=_SAMPLE_CATALOG)
def test_copilot_provider_uses_live_api(self, mock_fetch):
from agent.model_metadata import get_model_context_length
diff --git a/tests/hermes_cli/test_copilot_custom_model_ids.py b/tests/plugins/model_providers/test_copilot_custom_model_ids.py
similarity index 89%
rename from tests/hermes_cli/test_copilot_custom_model_ids.py
rename to tests/plugins/model_providers/test_copilot_custom_model_ids.py
index 20e83ba3991..c4a684533ac 100644
--- a/tests/hermes_cli/test_copilot_custom_model_ids.py
+++ b/tests/plugins/model_providers/test_copilot_custom_model_ids.py
@@ -10,7 +10,10 @@ Every such call failed, for both custom models a tenant had configured.
import pytest
-from hermes_cli.models import normalize_copilot_model_id
+import providers as _providers
+
+_providers.get_provider_profile("copilot") # imports the copilot plugin package (catalog module)
+from plugins.model_providers.copilot.catalog import normalize_copilot_model_id
# ``owner/sub/model`` — the shape an enterprise BYOK custom model has (tenant name sanitized).
diff --git a/tests/plugins/model_providers/test_copilot_profile.py b/tests/plugins/model_providers/test_copilot_profile.py
index 24e987dce6f..1112f133f51 100644
--- a/tests/plugins/model_providers/test_copilot_profile.py
+++ b/tests/plugins/model_providers/test_copilot_profile.py
@@ -35,10 +35,12 @@ def copilot_profile():
def _patch_efforts(monkeypatch, efforts):
"""Stub the catalog lookup the profile and main-agent path call for supported efforts."""
- import hermes_cli.models as models_mod
- monkeypatch.setattr(
- models_mod, "github_model_reasoning_efforts", lambda model: list(efforts)
- )
+ import providers
+
+ providers.get_provider_profile("copilot") # imports the copilot plugin package (catalog module)
+ from plugins.model_providers.copilot import catalog as copilot_catalog
+
+ monkeypatch.setattr(copilot_catalog, "github_model_reasoning_efforts", lambda model: list(efforts))
class TestCopilotReasoningEffortClamp:
@@ -112,12 +114,12 @@ class TestCopilotOfflineAstraEfforts:
("gpt-6-astra-pro", []), # speed-tier / unknown suffixes stay off the Astra ladder
])
def test_offline_fallback_uses_exact_astra_slugs(self, model, expected):
- from hermes_cli.models import github_model_reasoning_efforts
+ from plugins.model_providers.copilot.catalog import github_model_reasoning_efforts
assert github_model_reasoning_efforts(model, catalog=[]) == expected
def test_structured_catalog_beats_offline_fallback(self):
- from hermes_cli.models import github_model_reasoning_efforts
+ from plugins.model_providers.copilot.catalog import github_model_reasoning_efforts
catalog = [{"id": "gpt-6-astra", "capabilities": {
"type": "chat", "supports": {"reasoning_effort": ["low", "high"]}}}]