The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(providers): profile-owned setup and Desktop device-code login seams; Copilot setup moves into its plugin
Teknium9b6a9b353af8
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex d9ded68de9b..f17ecfd0e9c 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -270,7 +270,7 @@ class CLIAgentSetupMixin:# process only routes, so it must not run a second JWT exchange per launch.with deferred_token_mint():try:- # target_model: the ladder's model-keyed rungs (Zen/Go api_mode, Copilot/Nous+ # target_model: the ladder's model-keyed rungs (Zen/Go api_mode, per-model# api_mode) must see the model this CLI will actually send, not config's `default`,# or `hermes -m mimo-v2.5 --provider opencode-go` resolves an api_mode/base_url the# sent model cannot use (#112600).diff --git a/hermes_cli/cli_status_bar_mixin.py b/hermes_cli/cli_status_bar_mixin.pyindex 14dbe602930..54ce5d405c3 100644--- a/hermes_cli/cli_status_bar_mixin.py+++ b/hermes_cli/cli_status_bar_mixin.py@@ -947,7 +947,7 @@ class CLIStatusBarMixin:re-reading config per render could advertise a chord that isn't bound — and this sits onthe hot render path.- Two reasons (Copilot round-13 on 19835): See #19835.+ Two reasons (review round-13 on 19835): See #19835."""return getattr(self, "_voice_record_key_display_cache", None) or "Ctrl+B"diff --git a/hermes_cli/cli_stream_mixin.py b/hermes_cli/cli_stream_mixin.pyindex 12c7e37caee..8a580f3abf4 100644--- a/hermes_cli/cli_stream_mixin.py+++ b/hermes_cli/cli_stream_mixin.py@@ -773,7 +773,7 @@ class CLIStreamMixin:except Exception:pass# "verbose" must commit the same line as "all": non-streaming calls (MoA aggregator,- # copilot-acp) never emit the "preparing" line, so nothing else builds history.+ # ACP subprocess providers) never emit the "preparing" line, so nothing else builds history.if function_name and self.tool_progress_mode in {"new", "all", "verbose"}:duration = kwargs.get("duration", 0.0)# Pop stored args from tool.started for this functiondiff --git a/hermes_cli/cli_tui_mixin.py b/hermes_cli/cli_tui_mixin.pyindex 2fd80416f45..8398ac5b9e3 100644--- a/hermes_cli/cli_tui_mixin.py+++ b/hermes_cli/cli_tui_mixin.py@@ -2061,7 +2061,7 @@ class CLITuiMixin:# conflict with Ctrl+R readline reverse-search). Config spellings (ctrl/control/alt/option/opt) are# normalized to prompt_toolkit's c-x / a-x format via# ``normalize_voice_record_key_for_prompt_toolkit`` so the same config value binds identically in- # the TUI and CLI (Copilot round-9 review on #19835). ``super``/``win``/``windows`` configs silently+ # the TUI and CLI (review round-9 on #19835). ``super``/``win``/``windows`` configs silently# fall back to the default here since prompt_toolkit has no super modifier — log a warning so users# notice the TUI/CLI split instead of a silent mismatch (round-11)._raw_key: object = "ctrl+b"@@ -2086,7 +2086,7 @@ class CLITuiMixin:_voice_key = "c-b"# Cache the UI label here — same ``_raw_key`` that drives the prompt_toolkit binding below. Every# status / placeholder / recording-hint render reads this cached value so display can never drift- # from the live keybinding even if the user edits voice.record_key mid-session (Copilot round-13 on+ # from the live keybinding even if the user edits voice.record_key mid-session (review round-13 on# #19835).self.set_voice_record_key_cache(_raw_key)return pt_key_to_sequence(_voice_key)diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 5fd79bdf2ef..4022d8f3cd2 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -663,7 +663,7 @@ DEFAULT_CONFIG = {# (Historical key name.) When True, gpt-5.4/5.5/5.6 and gpt-6 Astra (any slug containing# "astra" without "900k") on the ChatGPT Codex OAuth route raise their compaction trigger to# 85%: Codex hard-caps them at a 272K window, so the global 50% would compact at ~136K. False = global `threshold`. Only that route; the same models via- # OpenAI direct, OpenRouter or Copilot keep the global value.+ # OpenAI direct, OpenRouter or another relay keep the global value."codex_gpt55_autoraise": True,# Show the one-time autoraise banner; False keeps the autoraise, hides the notice."codex_gpt55_autoraise_notice": True,@@ -748,7 +748,7 @@ DEFAULT_CONFIG = {# WARNING is logged whenever a non-":free" model is engaged."openrouter_model": "",# Endpoints that reject NON-streaming chat (HTTP 400): aux calls are sent with stream=True- # and aggregated. Case-insensitive URL substrings; copilot.tencent.com is always+ # and aggregated. Case-insensitive URL substrings; some vendor endpoints are always# stream-only."stream_only_base_urls": [],# Per-task blocks share one shape (_aux): provider "auto" = inherit the main model; base_urldiff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 28717e732ec..be1381699fb 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -783,8 +783,6 @@ from hermes_cli.model_setup_flows import (_model_flow_custom,_model_flow_azure_foundry,_model_flow_named_custom,- _model_flow_copilot,- _model_flow_copilot_acp,_model_flow_kimi,_model_flow_stepfun,_model_flow_bedrock,@@ -795,6 +793,7 @@ from hermes_cli.model_setup_flows import (_model_flow_ai_gateway,_model_flow_plugin_provider,_is_profile_plugin_flow_provider,+ _profile_model_setup_flow,)from hermes_cli.model_setup_flows_local import _model_flow_locallogger = logging.getLogger(__name__)@@ -1156,7 +1155,7 @@ def _has_any_provider_configured(*, strict_profile_scope: bool = False) -> bool:):return True- # Provider-specific auth fallbacks (e.g. Copilot via gh auth).+ # Provider-specific auth fallbacks (e.g. a token borrowed from a vendor CLI).if not strict_profile_scope:try:if any(@@ -1881,8 +1880,6 @@ _PROVIDER_MODEL_FLOWS = {"xai-oauth": lambda c, m, a: _model_flow_xai_oauth(c, m, args=a),"qwen-oauth": lambda c, m, a: _model_flow_qwen_oauth(c, m),"minimax-oauth": lambda c, m, a: _model_flow_minimax_oauth(c, m, args=a),- "copilot-acp": lambda c, m, a: _model_flow_copilot_acp(c, m),- "copilot": lambda c, m, a: _model_flow_copilot(c, m),"custom": lambda c, m, a: _model_flow_custom(c),"llamacpp": lambda c, m, a: _model_flow_local(c, m),"anthropic": lambda c, m, a: _model_flow_anthropic(c, m),@@ -2039,7 +2036,8 @@ def select_provider_and_model(args=None):saves_before = _model_choice_save_count()from hermes_cli.observability.shared_metrics_setup import cli_provider_setupwith cli_provider_setup(selected_provider):- flow = _PROVIDER_MODEL_FLOWS.get(selected_provider)+ # Bespoke core flow, else the profile's own (``model_setup_flow``), else the generic one.+ flow = _PROVIDER_MODEL_FLOWS.get(selected_provider) or _profile_model_setup_flow(selected_provider)if flow is None and _is_profile_plugin_flow_provider(selected_provider):# Registered plugin profile with no bespoke flow: the generic one, keyed by its auth_type.flow = lambda c, m, a: _model_flow_plugin_provider(c, selected_provider, m)diff --git a/hermes_cli/main_provider_setup.py b/hermes_cli/main_provider_setup.pyindex cbf0ae80832..4adbe2a628d 100644--- a/hermes_cli/main_provider_setup.py+++ b/hermes_cli/main_provider_setup.py@@ -663,8 +663,8 @@ def _offer_reasoning_after_pick(model_before: str, saves_before: int) -> None:def _prompt_main_reasoning_effort(model: str, provider: str) -> None:"""The effort step every ``hermes model`` flow shares: after a main-model pick, offer the- model's supported levels (Copilot publishes a per-model set; everything else gets the full- ladder) and persist ``agent.reasoning_effort``. Skipped when the catalog says the route has+ model's supported levels (a profile may declare a per-model set via ``setup_reasoning_efforts``;+ everything else gets the full ladder) and persist ``agent.reasoning_effort``. Skipped when the catalog says the route hasno reasoning control; "Skip" leaves the current value alone."""from hermes_cli.config import load_config, save_configfrom hermes_cli.setup import _current_reasoning_effort, _set_reasoning_effort@@ -684,9 +684,11 @@ def _main_model_reasoning_efforts(model: str, provider: str) -> Optional[list[st"""Levels to offer for *model* on *provider*: None when the route has no reasoning control."""from hermes_constants import VALID_REASONING_EFFORTSslug = (provider or "").strip().lower()- if slug == "copilot":- from hermes_cli.models import github_model_reasoning_efforts- return github_model_reasoning_efforts(model) or None+ from providers import get_provider_profile+ profile = get_provider_profile(slug) if slug else None+ declared = profile.setup_reasoning_efforts(model) if profile and profile.setup_reasoning_efforts else None+ if declared is not None:+ return list(declared) or Nonetry:from agent.models_dev import get_model_capabilitiesmeta = get_model_capabilities(slug, model)diff --git a/hermes_cli/model_setup_flows.py b/hermes_cli/model_setup_flows.pyindex abbe84699d4..b834b56c9ca 100644--- a/hermes_cli/model_setup_flows.py+++ b/hermes_cli/model_setup_flows.py@@ -477,157 +477,6 @@ def _model_flow_minimax_oauth(config, current_model="", args=None):_activate_provider_model(selected, "minimax-oauth", creds["base_url"], f"\u2713 Using MiniMax model: {selected}", no_change=None)-def _copilot_model_list(live_ids) -> list:- """Live GitHub Copilot ids, or the curated fallback with a warning."""- from hermes_cli.models import _PROVIDER_MODELS- if live_ids:- model_list = [model_id for model_id in live_ids if model_id]- print(f" Found {len(model_list)} model(s) from GitHub Copilot")- return model_list- model_list = _PROVIDER_MODELS.get("copilot", [])- if model_list:- _say(" ⚠ Could not auto-detect models from GitHub Copilot — showing defaults.",- ' Use "Enter custom model name" if you do not see your model.')- return model_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- catalog = fetch_github_model_catalog(api_key)- ids = [item.get("id", "") for item in catalog if item.get("id")] if catalog else []-- def _normalize(mid):- return normalize_copilot_model_id(mid, catalog=catalog, api_key=api_key) or mid-- return catalog, ids, _normalize---def _copilot_obtain_token() -> bool:- """No Copilot token yet: offer device-code login or manual entry. False = stop."""- from hermes_cli.config import save_env_value- _say("No GitHub token configured for GitHub Copilot.", "", " Supported token types:",- " → OAuth token (gho_*) via `copilot login` or device code flow",- " → Fine-grained PAT (github_pat_*) with Copilot Requests permission",- " → GitHub App token (ghu_*) via environment variable",- " ✗ Classic PAT (ghp_*) NOT supported by Copilot API", "", " Options:",- " 1. Login with GitHub (OAuth device code flow)", " 2. Enter a token manually", " 3. Cancel", "")- choice = _ask(" Choice [1-3]: ", raw=True, cancel_msg="")- if choice is None:- return False- if choice == "1":- try:- from hermes_cli.copilot_auth import copilot_device_code_login- token = copilot_device_code_login()- if not token:- print(" Login cancelled or failed.")- return False- save_env_value("COPILOT_GITHUB_TOKEN", token)- _say(" Copilot token saved.", "")- except Exception as exc:- print(f" Login failed: {exc}")- _note_setup_failure("auth")- return False- return True- if choice == "2":- new_key = _ask(" Token (COPILOT_GITHUB_TOKEN): ", secret=True, cancel_msg="")- if new_key is None:- return False- if not new_key:- print(" Cancelled.")- return False- # Validate token type- with contextlib.suppress(ImportError):- from hermes_cli.copilot_auth import validate_copilot_token- valid, msg = validate_copilot_token(new_key)- if not valid:- print(f" ✗ {msg}")- return False- save_env_value("COPILOT_GITHUB_TOKEN", new_key)- _say(" Token saved.", "")- return True- print(" Cancelled.")- return False---def _model_flow_copilot(config, current_model=""):- """GitHub Copilot flow using env vars, gh CLI, or OAuth device code. The reasoning-effort step- is the shared post-pick one in ``select_provider_and_model`` (Copilot's per-model level set- comes from ``github_model_reasoning_efforts`` there)."""- from hermes_cli.auth import PROVIDER_REGISTRY, resolve_api_key_provider_credentials- from hermes_cli.models import fetch_api_models, copilot_model_api_mode- provider_id = "copilot"- pconfig = PROVIDER_REGISTRY[provider_id]- creds = resolve_api_key_provider_credentials(provider_id)- api_key = creds.get("api_key", "")- source = creds.get("source", "")- if not api_key:- if not _copilot_obtain_token():- return- creds = resolve_api_key_provider_credentials(provider_id)- api_key = creds.get("api_key", "")- else:- if source in {"GITHUB_TOKEN", "GH_TOKEN"}:- from hermes_cli.env_loader import format_secret_source_suffix- _say(f" GitHub token: {api_key[:8]}... ✓ ({source}{format_secret_source_suffix(source)})", "")- else:- _say(" GitHub token: ✓ (from `gh auth token`)" if source == "gh auth token" else " GitHub token: ✓", "")-- effective_base = pconfig.inference_base_url- catalog, live_models, _normalize = _copilot_catalog(api_key)- if not catalog:- live_models = fetch_api_models(api_key, effective_base)-- selected = _pick_model_or_prompt(- _copilot_model_list(live_models), "Model name: ", current_model=_normalize(current_model),- confirm_provider=provider_id, confirm_base_url=effective_base, confirm_api_key=api_key)- if not selected:- print("No change.")- return- selected = _normalize(selected)- _persist_model(selected, provider_id, base_url=effective_base,- api_mode=copilot_model_api_mode(selected, catalog=catalog, api_key=api_key))- print(f"Default model set to: {selected} (via {pconfig.name})")---def _model_flow_copilot_acp(config, current_model=""):- """GitHub Copilot ACP flow using the local Copilot CLI."""- from hermes_cli.auth import (- PROVIDER_REGISTRY, get_external_process_provider_status, resolve_api_key_provider_credentials,- resolve_external_process_provider_credentials)-- del config- provider_id = "copilot-acp"- pconfig = PROVIDER_REGISTRY[provider_id]- status = get_external_process_provider_status(provider_id)- resolved_command = status.get("resolved_command") or status.get("command") or "copilot"- effective_base = status.get("base_url") or pconfig.inference_base_url-- _say(" GitHub Copilot ACP delegates Hermes turns to `copilot --acp`.",- " Hermes currently starts its own ACP subprocess for each request.",- " Hermes uses your selected model as a hint for the Copilot ACP session.",- f" Command: {resolved_command}", f" Backend marker: {effective_base}", "")- try:- creds = resolve_external_process_provider_credentials(provider_id)- except Exception as exc:- _say(f" ⚠ {exc}", " Set HERMES_COPILOT_ACP_COMMAND or COPILOT_CLI_PATH if Copilot CLI is installed elsewhere.")- return- effective_base = creds.get("base_url") or effective_base-- catalog_api_key = ""- with contextlib.suppress(Exception):- catalog_api_key = resolve_api_key_provider_credentials("copilot").get("api_key", "")- _catalog, catalog_ids, _normalize = _copilot_catalog(catalog_api_key)- selected = _pick_model_or_prompt(- _copilot_model_list(catalog_ids), "Model name: ", current_model=_normalize(current_model),- confirm_provider=provider_id, confirm_base_url=effective_base, confirm_api_key=catalog_api_key)- if selected:- selected = _normalize(selected)- _finish_model(selected, provider_id, f"Default model set to: {selected} (via {pconfig.name})",- base_url=effective_base, api_mode="chat_completions")--def _model_flow_kimi(config, current_model=""):"""Kimi / Moonshot model selection; the endpoint is chosen by key prefix (no URL prompt):``sk-kimi-*`` → api.kimi.com/coding/v1 (Kimi Coding Plan), other keys → Moonshot."""@@ -1149,6 +998,14 @@ _PLUGIN_FLOW_CREDENTIALS = {}+def _profile_model_setup_flow(provider_id: str):+ """``flow(config, current_model, args)`` for a registered profile that owns its ``hermes model``+ step (``ProviderProfile.model_setup_flow``), else None."""+ from providers import get_provider_profile+ profile = get_provider_profile(provider_id)+ return getattr(profile, "model_setup_flow", None) if profile is not None else None++def _is_profile_plugin_flow_provider(provider_id: str) -> bool:"""True when *provider_id* is a registered profile whose auth_type the generic plugin flow handles."""from hermes_cli.auth_plugin_providers import plugin_profilediff --git a/hermes_cli/setup_migration.py b/hermes_cli/setup_migration.pyindex c40b64a46be..9727d5c8e3c 100644--- a/hermes_cli/setup_migration.py+++ b/hermes_cli/setup_migration.py@@ -47,9 +47,11 @@ def _model_section_has_credentials(config: dict) -> bool:# OpenRouter aggregator fallback (no provider declared in config).if any_openrouter_key:return True- # Skip copilot in auto-detect: GH_TOKEN / GITHUB_TOKEN are commonly set for git tooling.- # Mirrors resolve_provider in auth.py.- return any(_has_key(pconfig) for pid, pconfig in PROVIDER_REGISTRY.items() if pid != "copilot")+ # Skip providers whose credentials are commonly ambient (a token exported for other tooling):+ # auto-detect never selects them. Mirrors resolve_provider in auth.py.+ from providers import get_provider_profile+ return any(_has_key(pconfig) and not getattr(get_provider_profile(pid), "ambient_credentials", False)+ for pid, pconfig in PROVIDER_REGISTRY.items())def _model_summary(config: dict) -> Optional[str]:diff --git a/hermes_cli/voice.py b/hermes_cli/voice.pyindex cd424cc496b..bea8b37d3e0 100644--- a/hermes_cli/voice.py+++ b/hermes_cli/voice.py@@ -21,7 +21,7 @@ _VOICE_MOD_ALIASES = {"ctrl": "c-", "control": "c-", "alt": "a-", "option": "a-"# Named keys prompt_toolkit accepts as ``c-<name>`` / ``a-<name>``; aliases collapse to canonical.# Aliases collapse to prompt_toolkit's canonical spelling so the same config value binds identically in both-# runtimes (Copilot round-10 on #19835).+# runtimes (review round-10 on #19835)._VOICE_NAMED_KEYS = {"space": "space", "spc": "space", "enter": "enter", "return": "enter", "ret": "enter", "tab": "tab","escape": "escape", "esc": "escape", "backspace": "backspace", "bs": "backspace", "delete": "delete", "del": "delete",@@ -36,7 +36,7 @@ _VOICE_RESERVED_CHARS = frozenset({"c", "d", "l"})# On macOS the classic CLI's prompt_toolkit bindings for copy / exit / clear also claim ``a-c`` / ``a-d`` /# ``a-l`` via the action-modifier lookup, and hermes-ink reports Alt as ``key.meta`` on many terminals.# Mirror the TUI parser's darwin-only reservation so ``option+c`` etc. don't bind Alt+C in the CLI while the-# TUI silently falls back to Ctrl+B (Copilot round-14 on #19835).+# TUI silently falls back to Ctrl+B (review round-14 on #19835)._DEFAULT_PT_KEY = "c-b"@@ -46,7 +46,7 @@ def voice_record_key_from_config(cfg: Any) -> Any:``load_config()`` deep-merges raw YAML and preserves scalar overrides, so a hand-edited ``voice: true``/ ``voice: cmd+b`` leaves ``cfg["voice"]`` as a bool/str instead of a dict, and the naive- ``.get("voice", {}).get("record_key")`` chain raises AttributeError before voice can even start (Copilot+ ``.get("voice", {}).get("record_key")`` chain raises AttributeError before voice can even start (reviewround-11 on 19835). Return ``None`` for malformed shapes so call sites can feed the result straight intothe normalizer/formatter and get the documented default. See #19835."""@@ -65,7 +65,7 @@ def normalize_voice_record_key_for_prompt_toolkit(raw: Any) -> str:* ``super`` / ``win`` / ``windows`` → ``c-b`` (TUI-only modifiers — prompt_toolkit has no super mod; theCLI binding site is expected to warn when this fallback fires so users see the cross-runtime split,- Copilot round-11 on #19835)+ review round-11 on #19835)"""if not isinstance(raw, str):return _DEFAULT_PT_KEY@@ -76,7 +76,7 @@ def normalize_voice_record_key_for_prompt_toolkit(raw: Any) -> str:# ``super`` / ``win`` / ``windows`` are TUI-only (prompt_toolkit has no super modifier, so# ``@kb.add(super+b)`` crashes the CLI at startup). Fall back to the documented default here; the CLI# binding site is expected to log a warning when the configured value is one of these spellings so users- # know the TUI+CLI runtimes diverge on that shortcut (Copilot round-11 on #19835).+ # know the TUI+CLI runtimes diverge on that shortcut (review round-11 on #19835).normalized_mod = _VOICE_MOD_ALIASES.get(modifier_token)if not normalized_mod:return _DEFAULT_PT_KEYdiff --git a/hermes_cli/web_routers/config_env.py b/hermes_cli/web_routers/config_env.pyindex 644be8c2cfe..221778d306b 100644--- a/hermes_cli/web_routers/config_env.py+++ b/hermes_cli/web_routers/config_env.py@@ -190,7 +190,7 @@ def _catalog_provider_env_metadata() -> dict:# Env vars declared with a NON-provider category (e.g. the shared# GITHUB_TOKEN, a Skills-Hub "tool" credential) must not be promoted into a- # provider card even when a provider (Copilot) lists them as auth aliases.+ # provider card even when a provider lists them as auth aliases._non_provider_keys = {k for k, v in OPTIONAL_ENV_VARS.items()if (v or {}).get("category") and (v or {}).get("category") != "provider"diff --git a/hermes_cli/web_routers/oauth.py b/hermes_cli/web_routers/oauth.pyindex 61db6225bcf..220ee93f550 100644--- a/hermes_cli/web_routers/oauth.py+++ b/hermes_cli/web_routers/oauth.py@@ -41,6 +41,7 @@ _OAUTH_PROVIDER_CATALOG = LateState("_OAUTH_PROVIDER_CATALOG", "hermes_cli.web_s_nous_sign_in_poller = late("_nous_sign_in_poller", "hermes_cli.web_server_oauth")_minimax_poller = late("_minimax_poller", "hermes_cli.web_server_oauth")_xai_device_poller = late("_xai_device_poller", "hermes_cli.web_server_oauth")+_profile_device_poller = late("_profile_device_poller", "hermes_cli.web_server_oauth")_CODEX_ISSUER = "https://auth.openai.com"_JSON_HEADERS = {"Content-Type": "application/json"}@@ -584,11 +585,39 @@ _DEVICE_CODE_STARTERS = {}+def _device_login_profile(provider_id: str):+ """The registered provider profile that owns an in-app device-code login, or None."""+ from providers import get_provider_profile+ prof = get_provider_profile(provider_id)+ if prof is None or not (prof.start_device_login and prof.poll_device_login and prof.save_device_login):+ return None+ return prof+++async def _start_profile_device_login(provider_id: str, profile: Optional[str]) -> dict[str, Any]:+ """Device-code login a provider profile owns: its ``start_device_login`` runs in the request's+ profile scope; ``_profile_device_poller`` polls and saves."""+ def _begin():+ prof = _device_login_profile(provider_id)+ return (prof, dict(prof.start_device_login() or {})) if prof is not None else (None, {})++ prof, login = await scoped_to_thread(profile, _begin)+ if prof is None or not login:+ raise HTTPException(status_code=400, detail=f"Provider {provider_id} does not support device-code flow")+ expires_in, interval = int(login["expires_in"]), max(1, int(login["interval"]))+ return _device_session_started(+ provider_id, profile, _profile_device_poller,+ dict(_provider_profile=prof, _device_state=login.get("state"), interval=interval,+ expires_at=time.time() + expires_in),+ str(login["user_code"]), str(login["verification_url"]), expires_in, interval,+ )++async def _start_device_code_flow(provider_id: str, profile: Optional[str] = None) -> dict[str, Any]:"""Hit the provider's device-auth endpoint, spawn its poller, return the display fields."""starter = _DEVICE_CODE_STARTERS.get(provider_id)if starter is None:- raise HTTPException(status_code=400, detail=f"Provider {provider_id} does not support device-code flow")+ return await _start_profile_device_login(provider_id, profile)return await starter(profile)@@ -656,18 +685,36 @@ def _build_oauth_catalog() -> list[dict[str, Any]]:try:from hermes_cli.provider_catalog import provider_catalogfor d in provider_catalog():- if d.tab != "accounts" or d.slug in seen:+ if d.slug in seen:continue- seen.add(d.slug)- rows.append({- "id": d.slug, "name": d.label, "flow": "external",- "cli_command": f"hermes auth add {d.slug}", "docs_url": d.signup_url or "", "status_fn": None,- })+ row = _profile_account_row(d)+ if row is not None:+ seen.add(d.slug)+ rows.append(row)except Exception:passreturn rows+def _profile_account_row(d) -> Optional[dict[str, Any]]:+ """Accounts-tab card for one catalog provider: the generic external card, overlaid with what its+ profile declares (``account_card``, ``account_status``, an in-app ``start_device_login``). A+ Keys-tab provider gets a card only when its profile asks for one."""+ from providers import get_provider_profile+ prof = get_provider_profile(d.slug)+ card = dict(getattr(prof, "account_card", None) or {})+ device = _device_login_profile(d.slug) is not None+ if d.tab != "accounts" and not (card or device):+ return None+ return {+ "id": d.slug, "name": card.get("name") or d.label,+ "flow": "device_code" if device else card.get("flow") or "external",+ "cli_command": card.get("cli_command") or f"hermes auth add {d.slug}",+ "docs_url": card.get("docs_url") or d.signup_url or "",+ "status_fn": getattr(prof, "account_status", None),+ }++@router.get("/api/providers/oauth")async def list_oauth_providers(profile: Optional[str] = None):"""Every OAuth-capable provider with current status (token_preview is the last@@ -797,7 +844,9 @@ async def start_oauth_login(provider_id: str, request: Request, profile: Optiona_require_token(request)_gc_oauth_sessions()_validate_oauth_profile(profile)- catalog_entry = next((p for p in _OAUTH_PROVIDER_CATALOG if p["id"] == provider_id), None)+ # The whole Accounts catalog, in the request's profile scope: a provider profile's card counts.+ catalog = await scoped_to_thread(profile, _build_oauth_catalog)+ catalog_entry = next((p for p in catalog if p["id"] == provider_id), None)if catalog_entry is None:raise HTTPException(status_code=400, detail=f"Unknown provider {provider_id}")if catalog_entry["flow"] == "external":diff --git a/hermes_cli/web_routers/ops.py b/hermes_cli/web_routers/ops.pyindex 0df948a5db7..7f805cf51b7 100644--- a/hermes_cli/web_routers/ops.py+++ b/hermes_cli/web_routers/ops.py@@ -325,7 +325,7 @@ async def stop_gateway(profile: Optional[str] = None, interrupt: bool = False):# --- Credential pool (auth.json -> credential_pool.<provider>[]): secrets are# redacted on read; only the agent sees raw values at session start.#-# load_pool() may hit the network synchronously (Copilot token exchange over raw+# load_pool() may hit the network synchronously (a provider token exchange over raw# urllib, whose timeout does NOT bound DNS resolution) — on a networkless host it# once froze the uvicorn loop for 17 minutes. Every pool load below runs off-loop.diff --git a/hermes_cli/web_server_lifecycle.py b/hermes_cli/web_server_lifecycle.pyindex 9c904dc05c9..4f1d7d14052 100644--- a/hermes_cli/web_server_lifecycle.py+++ b/hermes_cli/web_server_lifecycle.py@@ -148,8 +148,8 @@ def _warm_gateway_module() -> None:"""for mod in ("hermes_cli.gateway",- "hermes_cli.auth", # provider auth state → copilot_auth → subprocess- "hermes_cli.copilot_auth",+ "hermes_cli.auth", # provider auth state+ "providers", # provider plugin discovery (below) imports every profile's module chain"hermes_cli.runtime_provider","hermes_cli.skin_engine", # resolve_skin() config + skin engine init"hermes_cli.inventory", # provider catalogs + models.dev cache@@ -157,8 +157,14 @@ def _warm_gateway_module() -> None:):try:__import__(mod)- except Exception:- pass+ except Exception: # health: allow BLE001 -- best-effort warm-up; the real import reports+ _log.debug("warm-up import of %s failed", mod, exc_info=True)+ try:+ # Provider plugins carry their own auth chains (token exchange, CLI probes): warm them too.+ import providers+ providers.list_providers()+ except Exception: # health: allow BLE001 -- best-effort warm-up; discovery reports on real use+ _log.debug("warm-up provider discovery failed", exc_info=True)def _resolve_restart_drain_timeout() -> float:diff --git a/hermes_cli/web_server_oauth.py b/hermes_cli/web_server_oauth.pyindex e1827595521..8aabe98f358 100644--- a/hermes_cli/web_server_oauth.py+++ b/hermes_cli/web_server_oauth.py@@ -1,5 +1,5 @@"""Dashboard OAuth/login-status helpers: provider catalog, per-provider device pollers,-Anthropic/Copilot/Claude-Code status probes.+Anthropic/Claude-Code status probes, and the poller for provider-profile device logins."""import contextlib@@ -92,33 +92,9 @@ def _claude_code_only_status() -> dict[str, Any]:return dict(_LOGGED_OUT)-def _copilot_acp_status() -> dict[str, Any]:- """Status for copilot-acp. ``logged_in`` only on positive evidence (env token or known on-disk- store); the CLI may hold its session in an OS keychain Hermes can't read, so the unverified- state reads "managed by the Copilot CLI" — never signed out."""- try:- from hermes_cli.auth import get_external_process_provider_status- status = get_external_process_provider_status("copilot-acp") or {}- except Exception:- status = {}- verified = bool(status.get("auth_verified"))- configured = bool(status.get("configured"))- if verified:- source_label = status.get("auth_source") or "Copilot credentials detected"- elif configured:- found = status.get("resolved_command") or status.get("command") or "copilot"- source_label = f"Managed by the GitHub Copilot CLI ({found})"- else:- source_label = "GitHub Copilot CLI not found on PATH"- return {- "logged_in": verified, "source": "copilot_cli", "source_label": source_label, "token_preview": None,- "expires_at": None, "has_refresh_token": False, "configured": configured,- }--def _external_process_cli_command(provider_id: str, default: str) -> str:"""Render an external-process provider's sign-in command with the CLI actually configured- (``HERMES_COPILOT_ACP_COMMAND`` / ``COPILOT_CLI_PATH``); others get ``default`` untouched."""+ (its profile's ``process_command_env_vars`` override); others get ``default`` untouched."""try:from hermes_cli.auth import PROVIDER_REGISTRY, get_external_process_provider_statuspconfig = PROVIDER_REGISTRY.get(provider_id)@@ -138,7 +114,8 @@ def _external_process_cli_command(provider_id: str, default: str) -> str:# Hand-tuned OAuth/account cards: the bits not derivable from the unified provider catalog# (``flow``, ``status_fn``, ``cli_command``, display order). OVERRIDE BASE for# ``_build_oauth_catalog()``, which unions them with every accounts-tab provider so new-# providers appear automatically. Also carries two non-catalog rows the Accounts tab needs:+# providers appear automatically (a provider profile customises its own card through+# ``account_card`` / ``account_status`` / ``start_device_login``). Also carries two non-catalog rows:# the Anthropic credential-status card and the synthetic ``claude-code`` row.# ``flow``: ``device_code`` = show code + URL + poll; ``external`` = delegated to a terminal/CLI._OAUTH_PROVIDER_CATALOG: tuple[dict[str, Any], ...] = (@@ -159,10 +136,6 @@ _OAUTH_PROVIDER_CATALOG: tuple[dict[str, Any], ...] = ({"id": "xai-oauth", "name": "xAI Grok OAuth (SuperGrok / Premium+)", "flow": "device_code","cli_command": "hermes auth add xai-oauth","docs_url": "https://hermes-agent.nousresearch.com/docs/guides/xai-grok-oauth", "status_fn": None},- # `copilot login` is the non-interactive subcommand; `copilot /login` is not valid- # (slash-commands only exist inside an interactive session).- {"id": "copilot-acp", "name": "GitHub Copilot (ACP)", "flow": "external", "cli_command": "copilot login",- "docs_url": "https://docs.github.com/en/copilot", "status_fn": _copilot_acp_status},# Anthropic / Claude entries sit at the bottom. Deliberately flow == "external": an# in-dashboard Connect button would let a scriptable HTTP endpoint mint Claude Pro/Max# subscription tokens outside Anthropic's own client, against its OAuth usage policies.@@ -363,3 +336,49 @@ def _xai_device_poller(session_id: str, sess: dict[str, Any]) -> None:# duplicates the single-use refresh token and triggers ``refresh_token_reused`` churn.# An interactive login is an explicit re-enable, so clear any prior suppression.unsuppress_credential_source("xai-oauth", "device_code")+++def _sleep_unless_cancelled(sess: dict[str, Any], seconds: float) -> bool:+ """Sleep *seconds* in short ticks; True as soon as the session is cancelled."""+ deadline = time.monotonic() + seconds+ while True:+ with _oauth_sessions_lock:+ if sess.get("cancelled"):+ return True+ left = deadline - time.monotonic()+ if left <= 0:+ return False+ time.sleep(min(0.25, left))+++_DEVICE_LOGIN_ENDINGS = {"denied": "Authorization was denied.", "expired": "Device code expired before approval"}+++@_oauth_poller("provider-profile")+def _profile_device_poller(session_id: str, sess: dict[str, Any]) -> None:+ """Drive a device-code login a provider profile owns (``ProviderProfile.start_device_login``):+ one ``poll_device_login`` per interval until approved, then ``save_device_login`` under the+ session's profile scope, in one critical section with the cancel check like the built-in savers."""+ from hermes_cli.web_server_profiles import _profile_scope+ profile, state, interval = sess["_provider_profile"], sess["_device_state"], int(sess["interval"])+ result: dict[str, Any] = {}+ while time.time() < sess["expires_at"]:+ if _sleep_unless_cancelled(sess, interval):+ break+ result = dict(profile.poll_device_login(state) or {})+ state = result.get("state", state)+ if result.get("status") != "pending":+ break+ interval = int(result.get("interval") or interval)+ with _profile_scope(sess.get("profile")), _oauth_sessions_lock:+ if sess.get("cancelled"):+ sess["status"] = "cancelled"+ return+ status = result.get("status")+ if status in (None, "pending"): # the code's lifetime ran out+ status = "expired"+ if status != "approved":+ sess["status"] = status if status in _DEVICE_LOGIN_ENDINGS else "error"+ sess["error_message"] = result.get("message") or _DEVICE_LOGIN_ENDINGS.get(status) or "Sign-in failed"+ return+ profile.save_device_login(result.get("credential"))diff --git a/plugins/model-providers/copilot-acp/__init__.py b/plugins/model-providers/copilot-acp/__init__.pyindex 6027873a84e..2fd6e77782c 100644--- a/plugins/model-providers/copilot-acp/__init__.py+++ b/plugins/model-providers/copilot-acp/__init__.py@@ -11,6 +11,8 @@ from typing import Anyfrom providers import register_providerfrom providers.base import ProviderProfile+from .setup import SETUP_FIELDS+class CopilotACPProfile(ProviderProfile):"""GitHub Copilot ACP — external process, no REST models endpoint."""@@ -59,6 +61,7 @@ copilot_acp = CopilotACPProfile(process_args=("--acp", "--stdio"),process_command_env_vars=("HERMES_COPILOT_ACP_COMMAND", "COPILOT_CLI_PATH"),process_args_env_var="HERMES_COPILOT_ACP_ARGS",+ **SETUP_FIELDS,)register_provider(copilot_acp)diff --git a/plugins/model-providers/copilot-acp/setup.py b/plugins/model-providers/copilot-acp/setup.pynew file mode 100644index 00000000000..6902c932d04--- /dev/null+++ b/plugins/model-providers/copilot-acp/setup.py@@ -0,0 +1,88 @@+"""GitHub Copilot ACP setup and Accounts-card surfaces: the ``hermes model`` flow and the+Desktop card that points at the Copilot CLI's own login. Reached through ``SETUP_FIELDS``."""++from __future__ import annotations++import contextlib+from typing import Any+++def account_status() -> dict[str, Any]:+ """Status for copilot-acp. ``logged_in`` only on positive evidence (env token or known on-disk+ store); the CLI may hold its session in an OS keychain Hermes can't read, so the unverified+ state reads "managed by the Copilot CLI" — never signed out."""+ try:+ from hermes_cli.auth import get_external_process_provider_status+ status = get_external_process_provider_status("copilot-acp") or {}+ except Exception:+ status = {}+ verified = bool(status.get("auth_verified"))+ configured = bool(status.get("configured"))+ if verified:+ source_label = status.get("auth_source") or "Copilot credentials detected"+ elif configured:+ found = status.get("resolved_command") or status.get("command") or "copilot"+ source_label = f"Managed by the GitHub Copilot CLI ({found})"+ else:+ source_label = "GitHub Copilot CLI not found on PATH"+ return {+ "logged_in": verified, "source": "copilot_cli", "source_label": source_label, "token_preview": None,+ "expires_at": None, "has_refresh_token": False, "configured": configured,+ }+++def model_flow_copilot_acp(config, current_model="", args=None):+ """GitHub Copilot ACP flow using the local Copilot CLI."""+ from hermes_cli.auth import (+ PROVIDER_REGISTRY, get_external_process_provider_status, resolve_api_key_provider_credentials,+ resolve_external_process_provider_credentials)+ from hermes_cli.model_setup_flows_common import _finish_model, _pick_model_or_prompt, _say+ from providers import get_provider_profile++ del config, args+ provider_id = "copilot-acp"+ pconfig = PROVIDER_REGISTRY[provider_id]+ status = get_external_process_provider_status(provider_id)+ resolved_command = status.get("resolved_command") or status.get("command") or "copilot"+ effective_base = status.get("base_url") or pconfig.inference_base_url++ _say(" GitHub Copilot ACP delegates Hermes turns to `copilot --acp`.",+ " Hermes currently starts its own ACP subprocess for each request.",+ " Hermes uses your selected model as a hint for the Copilot ACP session.",+ f" Command: {resolved_command}", f" Backend marker: {effective_base}", "")+ try:+ creds = resolve_external_process_provider_credentials(provider_id)+ except Exception as exc: # health: allow BLE001 -- shown to the user, then the flow stops (moved verbatim)+ _say(f" ⚠ {exc}", " Set HERMES_COPILOT_ACP_COMMAND or COPILOT_CLI_PATH if Copilot CLI is installed elsewhere.")+ return+ effective_base = creds.get("base_url") or effective_base++ catalog_api_key = ""+ with contextlib.suppress(Exception):+ catalog_api_key = resolve_api_key_provider_credentials("copilot").get("api_key", "")+ # The GitHub catalog helpers belong to the sibling ``copilot`` profile (one plugin in the labs repo).+ copilot_setup = _sibling_setup_module(get_provider_profile("copilot"))+ _catalog, catalog_ids, _normalize = copilot_setup._copilot_catalog(catalog_api_key)+ selected = _pick_model_or_prompt(+ copilot_setup._copilot_model_list(catalog_ids), "Model name: ", current_model=_normalize(current_model),+ confirm_provider=provider_id, confirm_base_url=effective_base, confirm_api_key=catalog_api_key)+ if selected:+ selected = _normalize(selected)+ _finish_model(selected, provider_id, f"Default model set to: {selected} (via {pconfig.name})",+ base_url=effective_base, api_mode="chat_completions")+++def _sibling_setup_module(profile) -> Any:+ """The ``setup`` module next to *profile*'s plugin package (it registered under its own import name)."""+ import importlib+ return importlib.import_module(f"{type(profile).__module__}.setup")+++SETUP_FIELDS: dict[str, Any] = {+ "model_setup_flow": model_flow_copilot_acp,+ # `copilot login` is the non-interactive subcommand; `copilot /login` is not valid+ # (slash-commands only exist inside an interactive session).+ "account_card": {"name": "GitHub Copilot (ACP)", "flow": "external", "cli_command": "copilot login",+ "docs_url": "https://docs.github.com/en/copilot"},+ "account_status": account_status,+}diff --git a/plugins/model-providers/copilot/__init__.py b/plugins/model-providers/copilot/__init__.pyindex 745ee4a2814..f4305a56c25 100644--- a/plugins/model-providers/copilot/__init__.py+++ b/plugins/model-providers/copilot/__init__.py@@ -10,6 +10,8 @@ from typing import Anyfrom providers import register_providerfrom providers.base import ProviderProfile+from .setup import SETUP_FIELDS+class CopilotProfile(ProviderProfile):"""GitHub Copilot / GitHub Models — editor headers + reasoning."""@@ -38,7 +40,7 @@ class CopilotProfile(ProviderProfile):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",+ auth_type="copilot", **SETUP_FIELDS,)register_provider(copilot)diff --git a/plugins/model-providers/copilot/setup.py b/plugins/model-providers/copilot/setup.pynew file mode 100644index 00000000000..61fb219d135--- /dev/null+++ b/plugins/model-providers/copilot/setup.py@@ -0,0 +1,219 @@+"""GitHub Copilot setup and sign-in surfaces: the ``hermes model`` flow, the setup effort picker,+and the Desktop Accounts card with its in-app GitHub device-code login.++Core reaches these only through the generic ``ProviderProfile`` setup fields (``SETUP_FIELDS``).+"""++from __future__ import annotations++import contextlib+from typing import Any++# Device-code endpoints live on the GitHub web host; tests point this at a local fake.+_DEVICE_LOGIN_BASE = "https://github.com"+_DEVICE_VERIFICATION_URL = "https://github.com/login/device"+_DEVICE_CODE_EXPIRES_IN = 900 # GitHub's documented device-code lifetime when the reply omits it+_TOKEN_ENV_VAR = "COPILOT_GITHUB_TOKEN"+_DEVICE_ERRORS = {"expired_token": ("expired", "Device code expired. Please try again."),+ "access_denied": ("denied", "Authorization was denied.")}+++def _copilot_model_list(live_ids) -> list:+ """Live GitHub Copilot ids, or the curated fallback with a warning."""+ from hermes_cli.model_setup_flows_common import _say+ from hermes_cli.models import _PROVIDER_MODELS+ if live_ids:+ model_list = [model_id for model_id in live_ids if model_id]+ print(f" Found {len(model_list)} model(s) from GitHub Copilot")+ return model_list+ model_list = _PROVIDER_MODELS.get("copilot", [])+ if model_list:+ _say(" ⚠ Could not auto-detect models from GitHub Copilot — showing defaults.",+ ' Use "Enter custom model name" if you do not see your model.')+ return model_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+ catalog = fetch_github_model_catalog(api_key)+ ids = [item.get("id", "") for item in catalog if item.get("id")] if catalog else []++ def _normalize(mid):+ return normalize_copilot_model_id(mid, catalog=catalog, api_key=api_key) or mid++ return catalog, ids, _normalize+++def _copilot_obtain_token() -> bool:+ """No Copilot token yet: offer device-code login or manual entry. False = stop."""+ from hermes_cli.config import save_env_value+ from hermes_cli.model_setup_flows_common import _ask, _note_setup_failure, _say+ _say("No GitHub token configured for GitHub Copilot.", "", " Supported token types:",+ " → OAuth token (gho_*) via `copilot login` or device code flow",+ " → Fine-grained PAT (github_pat_*) with Copilot Requests permission",+ " → GitHub App token (ghu_*) via environment variable",+ " ✗ Classic PAT (ghp_*) NOT supported by Copilot API", "", " Options:",+ " 1. Login with GitHub (OAuth device code flow)", " 2. Enter a token manually", " 3. Cancel", "")+ choice = _ask(" Choice [1-3]: ", raw=True, cancel_msg="")+ if choice is None:+ return False+ if choice == "1":+ try:+ from hermes_cli.copilot_auth import copilot_device_code_login+ token = copilot_device_code_login()+ if not token:+ print(" Login cancelled or failed.")+ return False+ save_env_value(_TOKEN_ENV_VAR, token)+ _say(" Copilot token saved.", "")+ except Exception as exc:+ print(f" Login failed: {exc}")+ _note_setup_failure("auth")+ return False+ return True+ if choice == "2":+ new_key = _ask(" Token (COPILOT_GITHUB_TOKEN): ", secret=True, cancel_msg="")+ if new_key is None:+ return False+ if not new_key:+ print(" Cancelled.")+ return False+ # Validate token type+ with contextlib.suppress(ImportError):+ from hermes_cli.copilot_auth import validate_copilot_token+ valid, msg = validate_copilot_token(new_key)+ if not valid:+ print(f" ✗ {msg}")+ return False+ save_env_value(_TOKEN_ENV_VAR, new_key)+ _say(" Token saved.", "")+ return True+ print(" Cancelled.")+ return False+++def model_flow_copilot(config, current_model="", args=None):+ """GitHub Copilot flow using env vars, gh CLI, or OAuth device code. The reasoning-effort step+ is the shared post-pick one in ``select_provider_and_model`` (Copilot's per-model level set+ comes from ``setup_reasoning_efforts`` there)."""+ from hermes_cli.auth import PROVIDER_REGISTRY, resolve_api_key_provider_credentials+ from hermes_cli.model_setup_flows_common import _persist_model, _pick_model_or_prompt, _say+ from hermes_cli.models import fetch_api_models, copilot_model_api_mode+ del config, args+ provider_id = "copilot"+ pconfig = PROVIDER_REGISTRY[provider_id]+ creds = resolve_api_key_provider_credentials(provider_id)+ api_key = creds.get("api_key", "")+ source = creds.get("source", "")+ if not api_key:+ if not _copilot_obtain_token():+ return+ creds = resolve_api_key_provider_credentials(provider_id)+ api_key = creds.get("api_key", "")+ else:+ if source in {"GITHUB_TOKEN", "GH_TOKEN"}:+ from hermes_cli.env_loader import format_secret_source_suffix+ _say(f" GitHub token: {api_key[:8]}... ✓ ({source}{format_secret_source_suffix(source)})", "")+ else:+ _say(" GitHub token: ✓ (from `gh auth token`)" if source == "gh auth token" else " GitHub token: ✓", "")++ effective_base = pconfig.inference_base_url+ catalog, live_models, _normalize = _copilot_catalog(api_key)+ if not catalog:+ live_models = fetch_api_models(api_key, effective_base)++ selected = _pick_model_or_prompt(+ _copilot_model_list(live_models), "Model name: ", current_model=_normalize(current_model),+ confirm_provider=provider_id, confirm_base_url=effective_base, confirm_api_key=api_key)+ if not selected:+ print("No change.")+ return+ selected = _normalize(selected)+ _persist_model(selected, provider_id, base_url=effective_base,+ api_mode=copilot_model_api_mode(selected, catalog=catalog, api_key=api_key))+ print(f"Default model set to: {selected} (via {pconfig.name})")+++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+ return tuple(github_model_reasoning_efforts(model) or ())+++# ── Desktop Accounts card + in-app device-code login ──────────────────────────+++def account_status() -> dict[str, Any]:+ """Card status from the env-token ladder only (no ``gh`` subprocess, no token exchange: this runs+ on every Accounts list). A token here is managed on the Keys tab, so it reads as ``env_var``."""+ from hermes_cli.config import get_env_value+ from hermes_cli.copilot_auth import COPILOT_ENV_VARS, validate_copilot_token+ from hermes_cli.env_loader import format_secret_source_suffix+ for var in COPILOT_ENV_VARS:+ token = (get_env_value(var) or "").strip()+ if token and validate_copilot_token(token)[0]:+ return {"logged_in": True, "source": "env_var", "source_label": f"{var}{format_secret_source_suffix(var)}",+ "token_preview": None, "expires_at": None, "has_refresh_token": False}+ return {"logged_in": False, "source": None}+++def start_device_login() -> dict[str, Any]:+ """Ask GitHub for a device code (the same OAuth app as ``copilot_device_code_login``)."""+ from hermes_cli.copilot_auth import (+ COPILOT_OAUTH_CLIENT_ID, _DEVICE_CODE_POLL_INTERVAL, _DEVICE_CODE_POLL_SAFETY_MARGIN, _post_form)+ data = _post_form(f"{_DEVICE_LOGIN_BASE}/login/device/code",+ {"client_id": COPILOT_OAUTH_CLIENT_ID, "scope": "read:user"}, 15)+ device_code, user_code = data.get("device_code", ""), data.get("user_code", "")+ if not device_code or not user_code:+ raise RuntimeError("GitHub did not return a device code.")+ interval = max(int(data.get("interval") or _DEVICE_CODE_POLL_INTERVAL), 1)+ return {"user_code": user_code, "verification_url": data.get("verification_uri") or _DEVICE_VERIFICATION_URL,+ "expires_in": int(data.get("expires_in") or _DEVICE_CODE_EXPIRES_IN),+ "interval": interval + _DEVICE_CODE_POLL_SAFETY_MARGIN,+ "state": {"device_code": device_code, "interval": interval}}+++def poll_device_login(state: dict[str, Any]) -> dict[str, Any]:+ """One token poll. A transport blip is just another pending tick, as in the terminal flow."""+ from hermes_cli.copilot_auth import COPILOT_OAUTH_CLIENT_ID, _DEVICE_CODE_POLL_SAFETY_MARGIN, _post_form+ fields = {"client_id": COPILOT_OAUTH_CLIENT_ID, "device_code": state["device_code"],+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code"}+ try:+ result = _post_form(f"{_DEVICE_LOGIN_BASE}/login/oauth/access_token", fields, 10)+ except (OSError, ValueError): # URLError/timeouts are OSError; a garbled body is ValueError+ return {"status": "pending"}+ if result.get("access_token"):+ return {"status": "approved", "credential": result["access_token"]}+ error = result.get("error", "")+ if error == "slow_down":+ # RFC 8628: add 5 seconds to polling interval (or honor a server-supplied one)+ server_interval = result.get("interval")+ if isinstance(server_interval, (int, float)) and server_interval > 0:+ interval = int(server_interval)+ else:+ interval = int(state.get("interval") or 1) + 5+ return {"status": "pending", "interval": interval + _DEVICE_CODE_POLL_SAFETY_MARGIN,+ "state": {**state, "interval": interval}}+ if not error or error == "authorization_pending":+ return {"status": "pending"}+ status, message = _DEVICE_ERRORS.get(error, ("error", f"Authorization failed: {error}"))+ return {"status": status, "message": message}+++def save_device_login(token: str) -> None:+ """Persist the GitHub OAuth token where the terminal device-code login puts it."""+ from hermes_cli.config import save_env_value+ save_env_value(_TOKEN_ENV_VAR, token)+++SETUP_FIELDS: dict[str, Any] = {+ "model_setup_flow": model_flow_copilot,+ "setup_reasoning_efforts": setup_reasoning_efforts,+ "account_card": {"name": "GitHub Copilot", "docs_url": "https://docs.github.com/en/copilot"},+ "account_status": account_status,+ "start_device_login": start_device_login,+ "poll_device_login": poll_device_login,+ "save_device_login": save_device_login,+}diff --git a/providers/base.py b/providers/base.pyindex 90f9f8e15a9..d93c86f9531 100644--- a/providers/base.py+++ b/providers/base.py@@ -252,6 +252,28 @@ class ProviderProfile:# patch catalog metadata; explicit user overrides still win. Exact model IDs.model_capabilities: dict[str, dict[str, Any]] = field(default_factory=dict)+ # ── L6: provider-owned setup + sign-in surfaces (all optional; None/empty = core's generic path) ──+ # ``account_card``: Accounts-tab card overrides ``{name, flow, cli_command, docs_url}`` for the+ # Desktop/dashboard (``/api/providers/oauth``); non-empty also lists a Keys-tab profile there.+ account_card: dict[str, str] = field(default_factory=dict)+ # ``account_status() -> Mapping``: that card's live status (``logged_in``, ``source``, ``source_label``…);+ # subprocess- and network-free, it runs on every Accounts list. None = ``auth.get_auth_status(name)``.+ account_status: Callable[[], Any] | None = None+ # In-app device-code sign-in (Desktop "Login" button; the card's flow becomes ``device_code``):+ # ``start_device_login() -> {user_code, verification_url, expires_in, interval, state}`` asks the+ # provider for a code; ``poll_device_login(state) -> {status: pending|approved|denied|expired,+ # interval?, credential?, message?}`` makes ONE poll; ``save_device_login(credential)`` persists it.+ # Core owns the wait loop and cancellation and calls save inside the session's profile scope.+ start_device_login: Callable[[], Any] | None = None+ poll_device_login: Callable[[Any], Any] | None = None+ save_device_login: Callable[[Any], None] | None = None+ # ``model_setup_flow(config, current_model, args)``: this provider's own ``hermes model`` step+ # (credential prompt, catalog, persist); None = the generic flow for its auth_type.+ model_setup_flow: Callable[[Any, str, Any], Any] | None = None+ # ``setup_reasoning_efforts(model) -> tuple | None``: levels the setup effort picker offers for+ # *model*; ``()`` = no reasoning control, None = the generic ladder gated by models.dev.+ setup_reasoning_efforts: Callable[[str], Any] | None = None+# ── Hooks (override in subclass for complex providers) ───def fetch_account_usage(diff --git a/tests/hermes_cli/test_profile_setup_login_seams.py b/tests/hermes_cli/test_profile_setup_login_seams.pynew file mode 100644index 00000000000..44837970d56--- /dev/null+++ b/tests/hermes_cli/test_profile_setup_login_seams.py@@ -0,0 +1,177 @@+"""Provider-profile setup/sign-in seams (``providers.base`` L6 block) through the real routes.++A model-provider plugin installed in ONE profile's home declares an in-app device-code login, an+Accounts card and a ``hermes model`` step; core drives them with no provider-specific code:+ * ``/api/providers/oauth`` lists the card as ``device_code`` for that profile only;+ * ``/start`` + ``/poll`` run the profile's start/poll hooks and save inside that profile's scope;+ * a cancel before approval never saves;+ * ``hermes model`` dispatch and the effort picker consult the profile.+"""++from __future__ import annotations++import json+import sys+import threading+import time++import pytest+from fastapi.testclient import TestClient++from hermes_cli.web_server import _SESSION_TOKEN, app+from tests.waiting import wait_until++client = TestClient(app)+HEADERS = {"X-Hermes-Session-Token": _SESSION_TOKEN}+NAME = "acme-device"++_PLUGIN_SOURCE = '''+import json, os+from providers import register_provider+from providers.base import ProviderProfile++def _log(event, **kw):+ with open(os.environ["ACME_DEVICE_LOG"], "a", encoding="utf-8") as fh:+ fh.write(json.dumps({"event": event, **kw}) + "\\n")++def start():+ _log("start")+ return {"user_code": "ACME-1234", "verification_url": "https://acme.example/device",+ "expires_in": 60, "interval": 1, "state": {"polls": 0}}++def poll(state):+ polls = state["polls"] + 1+ _log("poll", polls=polls)+ if polls < int(os.environ.get("ACME_APPROVE_AT", "2")):+ return {"status": "pending", "state": {"polls": polls}}+ if os.environ.get("ACME_DENY"):+ return {"status": "denied", "message": "nope"}+ return {"status": "approved", "credential": "acme-secret"}++def save(credential):+ from hermes_constants import get_hermes_home+ _log("save", home=str(get_hermes_home()), credential=credential)++def flow(config, current_model, args):+ _log("flow", current_model=current_model)++register_provider(ProviderProfile(+ name="acme-device", display_name="Acme Device", base_url="https://acme.example/v1",+ env_vars=("ACME_DEVICE_KEY",), account_card={"name": "Acme Account", "docs_url": "https://acme.example/docs"},+ start_device_login=start, poll_device_login=poll, save_device_login=save,+ model_setup_flow=flow, setup_reasoning_efforts=lambda model: () if model == "plain" else ("low", "high"),+))+'''+++def _rediscover() -> None:+ import providers as _pkg+ _pkg._discovered = False+ for mod in [m for m in sys.modules if m.startswith("_hermes_user_provider")]:+ del sys.modules[mod]+++def acme(tmp_path, monkeypatch):+ """Install the fixture plugin into profile ``coder`` only; return (coder home, log reader)."""+ root = tmp_path / "hermes"+ coder = root / "profiles" / "coder"+ plugin_dir = coder / "plugins" / "model-providers" / NAME+ plugin_dir.mkdir(parents=True)+ (coder / "config.yaml").write_text("{}\n") # identity marker: a bare dir is not a profile+ (plugin_dir / "plugin.yaml").write_text(+ f"name: {NAME}\nkind: model-provider\nversion: 0.0.1\ndescription: device login seam fixture\n")+ (plugin_dir / "__init__.py").write_text(_PLUGIN_SOURCE)+ log = tmp_path / "acme.jsonl"+ monkeypatch.setenv("HERMES_HOME", str(root))+ monkeypatch.setenv("ACME_DEVICE_LOG", str(log))+ _rediscover()++ def events() -> list[dict]:+ return [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else []++ yield coder, events+ import providers as _pkg+ _pkg._PROVIDER_LIST_CACHE = None+ _rediscover()+++def _cards(profile: str | None = None) -> dict[str, dict]:+ url = "/api/providers/oauth" + (f"?profile={profile}" if profile else "")+ resp = client.get(url, headers=HEADERS)+ assert resp.status_code == 200, resp.text+ return {p["id"]: p for p in resp.json()["providers"]}+++def _wait(session_id: str, profile: str) -> dict:+ deadline = time.monotonic() + 20+ while time.monotonic() < deadline:+ body = client.get(f"/api/providers/oauth/{NAME}/poll/{session_id}?profile={profile}&wait=2",+ headers=HEADERS).json()+ if body["status"] != "pending":+ return body+ raise AssertionError("device login never settled")+++def test_profile_device_login_lists_starts_and_saves_in_the_owning_profile(acme):+ coder, events = acme+ card = _cards("coder")[NAME]+ assert {k: card[k] for k in ("name", "flow", "docs_url")} == {+ "name": "Acme Account", "flow": "device_code", "docs_url": "https://acme.example/docs"}+ assert NAME not in _cards() # the plugin lives in coder's home only++ start = client.post(f"/api/providers/oauth/{NAME}/start?profile=coder", headers=HEADERS)+ assert start.status_code == 200, start.text+ body = start.json()+ assert {k: body[k] for k in ("flow", "user_code", "verification_url", "expires_in", "poll_interval")} == {+ "flow": "device_code", "user_code": "ACME-1234", "verification_url": "https://acme.example/device",+ "expires_in": 60, "poll_interval": 1}++ assert _wait(body["session_id"], "coder")["status"] == "approved"+ saves = [e for e in events() if e["event"] == "save"]+ assert saves == [{"event": "save", "home": str(coder), "credential": "acme-secret"}]+ assert [e["polls"] for e in events() if e["event"] == "poll"] == [1, 2]+++def test_profile_device_login_cancel_before_approval_never_saves(acme, monkeypatch):+ _coder, events = acme+ monkeypatch.setenv("ACME_APPROVE_AT", "1") # the very first poll would approve and save+ body = client.post(f"/api/providers/oauth/{NAME}/start?profile=coder", headers=HEADERS).json()+ resp = client.delete(f"/api/providers/oauth/sessions/{body['session_id']}?profile=coder", headers=HEADERS)+ assert resp.json()["ok"] is True+ poller = f"oauth-poll-{body['session_id'][:6]}"+ wait_until(lambda: not any(t.name == poller for t in threading.enumerate()), timeout=10, what="poller exit")+ assert [e["event"] for e in events()] == ["start"] # cancelled inside the first wait: no poll, no save+++def test_profile_device_login_denied_ends_the_session_with_the_profile_message(acme, monkeypatch):+ _coder, events = acme+ monkeypatch.setenv("ACME_APPROVE_AT", "1")+ monkeypatch.setenv("ACME_DENY", "1")+ body = client.post(f"/api/providers/oauth/{NAME}/start?profile=coder", headers=HEADERS).json()+ result = _wait(body["session_id"], "coder")+ assert (result["status"], result["error_message"]) == ("denied", "nope")+ assert not [e for e in events() if e["event"] == "save"]+++def test_provider_without_device_login_cannot_start_one(acme):+ # A built-in external card is still refused; an unknown id is still unknown.+ resp = client.post("/api/providers/oauth/claude-code/start", headers=HEADERS)+ assert resp.status_code == 400 and "external CLI" in resp.json()["detail"]+ assert client.post("/api/providers/oauth/no-such-provider/start", headers=HEADERS).status_code == 400+++def test_hermes_model_dispatch_and_effort_picker_consult_the_profile(acme, monkeypatch):+ coder, events = acme+ monkeypatch.setenv("HERMES_HOME", str(coder))+ _rediscover()+ from hermes_cli.main_provider_setup import _main_model_reasoning_efforts+ from hermes_cli.model_setup_flows import _profile_model_setup_flow++ flow = _profile_model_setup_flow(NAME)+ assert flow is not None+ flow({}, "acme-1", None)+ assert [e for e in events() if e["event"] == "flow"] == [{"event": "flow", "current_model": "acme-1"}]+ assert _main_model_reasoning_efforts("acme-1", NAME) == ["low", "high"]+ assert _main_model_reasoning_efforts("plain", NAME) is None+ assert _profile_model_setup_flow("openrouter") is None # no bespoke step: the generic dispatchdiff --git a/tests/plugins/model_providers/test_copilot_setup.py b/tests/plugins/model_providers/test_copilot_setup.pynew file mode 100644index 00000000000..696ef5beccd--- /dev/null+++ b/tests/plugins/model_providers/test_copilot_setup.py@@ -0,0 +1,88 @@+"""Copilot's in-app device-code login hooks (``plugins/model-providers/copilot/setup.py``) against a+local fake of GitHub's device endpoints: the codes, the RFC 8628 poll answers and where the token lands."""++from __future__ import annotations++import json+import sys+import threading+from http.server import BaseHTTPRequestHandler, HTTPServer+from urllib.parse import parse_qs++import pytest++import providers+++class _FakeGitHub(BaseHTTPRequestHandler):+ replies: list[dict] = []+ seen: list[dict] = []++ def log_message(self, *args):+ pass++ def do_POST(self):+ fields = parse_qs(self.rfile.read(int(self.headers["Content-Length"])).decode())+ type(self).seen.append({"path": self.path, **{k: v[0] for k, v in fields.items()}})+ body = json.dumps(type(self).replies.pop(0)).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.end_headers()+ self.wfile.write(body)+++def github(monkeypatch, tmp_path):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ for var in ("COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"):+ monkeypatch.delenv(var, raising=False)+ server = HTTPServer(("127.0.0.1", 0), _FakeGitHub)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ _FakeGitHub.replies, _FakeGitHub.seen = [], []+ profile = providers.get_provider_profile("copilot")+ setup = sys.modules[f"{type(profile).__module__}.setup"]+ monkeypatch.setattr(setup, "_DEVICE_LOGIN_BASE", f"http://127.0.0.1:{server.server_port}")+ yield profile, _FakeGitHub+ server.shutdown()+++def test_start_and_poll_follow_the_terminal_flow(github):+ profile, fake = github+ fake.replies = [+ {"device_code": "dev-1", "user_code": "ABCD-1234", "verification_uri": "https://github.com/login/device",+ "expires_in": 900, "interval": 5},+ {"error": "authorization_pending"},+ {"error": "slow_down", "interval": 12},+ {"error": "slow_down"},+ {"access_token": "gho_fake"},+ ]+ login = profile.start_device_login()+ assert {k: login[k] for k in ("user_code", "verification_url", "expires_in", "interval")} == {+ "user_code": "ABCD-1234", "verification_url": "https://github.com/login/device",+ "expires_in": 900, "interval": 8} # GitHub's interval + the terminal flow's 3 s safety margin+ state = login["state"]+ assert profile.poll_device_login(state) == {"status": "pending"}+ slowed = profile.poll_device_login(state)+ assert (slowed["status"], slowed["interval"]) == ("pending", 15) # server-supplied interval honoured+ state = slowed["state"]+ assert profile.poll_device_login(state)["interval"] == 20 # +5 s without one (RFC 8628)+ assert profile.poll_device_login(state) == {"status": "approved", "credential": "gho_fake"}+ assert [s["path"] for s in fake.seen] == ["/login/device/code"] + ["/login/oauth/access_token"] * 4+ assert {s["device_code"] for s in fake.seen[1:]} == {"dev-1"}++[email protected](("error", "status"), [("expired_token", "expired"), ("access_denied", "denied"),+ ("unsupported_grant_type", "error")])+def test_terminal_poll_errors_end_the_login(github, error, status):+ profile, fake = github+ fake.replies = [{"error": error}]+ assert profile.poll_device_login({"device_code": "dev-1", "interval": 5})["status"] == status+++def test_saved_token_is_what_the_card_reports(github, tmp_path):+ profile, _fake = github+ assert profile.account_status()["logged_in"] is False+ profile.save_device_login("gho_saved")+ assert "COPILOT_GITHUB_TOKEN=gho_saved" in (tmp_path / ".env").read_text()+ status = profile.account_status()+ assert (status["logged_in"], status["source"], status["source_label"]) == (True, "env_var", "COPILOT_GITHUB_TOKEN")diff --git a/tui_gateway/methods_voice.py b/tui_gateway/methods_voice.pyindex 08520f95076..fec946b5cf6 100644--- a/tui_gateway/methods_voice.py+++ b/tui_gateway/methods_voice.py@@ -363,7 +363,7 @@ def _voice_cfg_dict() -> dict:``_load_cfg()`` does not deep-merge DEFAULT_CONFIG, so both the root AND ``voice`` may be any YAMLscalar / list / None. A hand-edit like ``voice: true`` or a malformed top-level config that parses to a- scalar would otherwise break ``.get("…")`` and take every ``voice.*`` branch down with it (Copilot+ scalar would otherwise break ``.get("…")`` and take every ``voice.*`` branch down with it (reviewround-3..7 review on 19835). Coerce through ``isinstance`` at every level so malformed config falls backto an empty dict instead of crashing /voice. See #19835."""@@ -848,7 +848,7 @@ def _(rid, params: dict) -> dict:# Shape-safe lookups: malformed ``voice:`` YAML (bool/scalar/list) must not crash /voice with a 5025# — fall back to VAD defaults. Exclude ``bool`` from the numeric check since Python's bool is a# subclass of int — a hand-edit like ``silence_threshold: true`` would otherwise forward as ``1``- # instead of falling back to the documented 200 / 3.0 defaults (Copilot round-12 on #19835).+ # instead of falling back to the documented 200 / 3.0 defaults (review round-12 on #19835).voice_cfg = _voice_cfg_dict()max_rec = _voice_cfg_number(voice_cfg.get("max_recording_seconds"), 120.0)# Hand the mic to STT if the wake detector holds it; a terminal capture event resumes it.