setup.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. """GitHub Copilot setup and sign-in surfaces: the ``hermes model`` flow, the setup effort picker,
  2. and the Desktop Accounts card with its in-app GitHub device-code login.
  3. Core reaches these only through the generic ``ProviderProfile`` setup fields (``SETUP_FIELDS``).
  4. """
  5. from __future__ import annotations
  6. import contextlib
  7. import sys
  8. import uuid
  9. from typing import Any
  10. from .helpers import ask, get_json, say
  11. # Device-code endpoints live on the GitHub web host; tests point this at a local fake.
  12. _DEVICE_LOGIN_BASE = "https://github.com"
  13. _DEVICE_VERIFICATION_URL = "https://github.com/login/device"
  14. _DEVICE_CODE_EXPIRES_IN = 900 # GitHub's documented device-code lifetime when the reply omits it
  15. _TOKEN_ENV_VAR = "COPILOT_GITHUB_TOKEN"
  16. _DEVICE_ERRORS = {"expired_token": ("expired", "Device code expired. Please try again."),
  17. "access_denied": ("denied", "Authorization was denied.")}
  18. def _copilot_model_list(live_ids) -> list:
  19. """Live GitHub Copilot ids, or the curated fallback with a warning."""
  20. from .catalog import STATIC_MODELS
  21. if live_ids:
  22. model_list = [model_id for model_id in live_ids if model_id]
  23. print(f" Found {len(model_list)} model(s) from GitHub Copilot")
  24. return model_list
  25. model_list = list(STATIC_MODELS)
  26. if model_list:
  27. say(" ⚠ Could not auto-detect models from GitHub Copilot — showing defaults.",
  28. ' Use "Enter custom model name" if you do not see your model.')
  29. return model_list
  30. def _copilot_catalog(api_key: str):
  31. """``(catalog, catalog_ids, normalize)`` for a GitHub token; *normalize* canonicalizes a
  32. model id against the catalog (identity when unknown)."""
  33. from .catalog import fetch_github_model_catalog, normalize_copilot_model_id
  34. catalog = fetch_github_model_catalog(api_key)
  35. ids = [item.get("id", "") for item in catalog if item.get("id")] if catalog else []
  36. def _normalize(mid):
  37. return normalize_copilot_model_id(mid, catalog=catalog, api_key=api_key) or mid
  38. return catalog, ids, _normalize
  39. def copilot_api_key() -> tuple[str, str]:
  40. """``(Copilot API token, source env var)`` for a setup flow: the first supported env token,
  41. exchanged (the raw token when the exchange is unavailable); ``("", "")`` when there is none."""
  42. from .credentials import get_copilot_api_token, resolve_copilot_token
  43. raw, source = resolve_copilot_token()
  44. return (get_copilot_api_token(raw)[0], source) if raw else ("", "")
  45. def _raw_model_ids(api_key: str) -> list:
  46. """Every id ``/models`` lists for this token (no chat filtering): the last resort when the
  47. filtered catalog came back empty."""
  48. from .catalog import COPILOT_MODELS_URL, _payload_items
  49. try:
  50. items = _payload_items(get_json(COPILOT_MODELS_URL, timeout=5.0,
  51. headers={"Authorization": f"Bearer {api_key}"} if api_key else {}))
  52. except Exception: # the picker falls back to the curated list
  53. return []
  54. return [str(item.get("id")) for item in items if item.get("id")]
  55. def pick_model_or_prompt(model_list, prompt: str, **kwargs):
  56. """Hermes' radio picker when *model_list* is non-empty, else a free-text answer (None on Ctrl-C/EOF)."""
  57. if model_list:
  58. from hermes_cli.auth_model_picker import prompt_model_selection
  59. return prompt_model_selection(model_list, **kwargs)
  60. return ask(prompt, cancel_msg=None)
  61. def _copilot_obtain_token() -> bool:
  62. """No Copilot token yet: offer device-code login or manual entry. False = stop."""
  63. from hermes_cli.config import save_env_value
  64. from hermes_cli.model_setup import note_setup_failure
  65. say("No GitHub token configured for GitHub Copilot.", "", " Supported token types:",
  66. " → OAuth token (gho_*/ghu_*) via the device code flow below",
  67. " → Fine-grained PAT (github_pat_*) with Copilot Requests permission",
  68. " → GitHub App token (ghu_*) via environment variable",
  69. " ✗ Classic PAT (ghp_*) NOT supported by Copilot API", "", " Options:",
  70. " 1. Login with GitHub (OAuth device code flow)", " 2. Enter a token manually", " 3. Cancel", "")
  71. choice = ask(" Choice [1-3]: ", cancel_msg="")
  72. if choice is None:
  73. return False
  74. if choice == "1":
  75. try:
  76. from .credentials import copilot_device_code_login
  77. token = copilot_device_code_login()
  78. if not token:
  79. print(" Login cancelled or failed.")
  80. return False
  81. save_env_value(_TOKEN_ENV_VAR, token)
  82. say(" Copilot token saved.", "")
  83. except Exception as exc:
  84. print(f" Login failed: {exc}")
  85. note_setup_failure("auth")
  86. return False
  87. return True
  88. if choice == "2":
  89. new_key = ask(" Token (COPILOT_GITHUB_TOKEN): ", secret=True, cancel_msg="")
  90. if new_key is None:
  91. return False
  92. if not new_key:
  93. print(" Cancelled.")
  94. return False
  95. # Validate token type
  96. with contextlib.suppress(ImportError):
  97. from .credentials import validate_copilot_token
  98. valid, msg = validate_copilot_token(new_key)
  99. if not valid:
  100. print(f" ✗ {msg}")
  101. return False
  102. save_env_value(_TOKEN_ENV_VAR, new_key)
  103. say(" Token saved.", "")
  104. return True
  105. print(" Cancelled.")
  106. return False
  107. def model_flow_copilot(config, current_model="", args=None):
  108. """GitHub Copilot flow using env tokens or OAuth device code. The reasoning-effort step
  109. is the shared post-pick one in ``select_provider_and_model`` (Copilot's per-model level set
  110. comes from ``setup_reasoning_efforts`` there). The user picked Copilot here, so the flow may
  111. exchange their token and read the account catalog before anything is saved."""
  112. from .activation import copilot_user_flow
  113. del config, args
  114. with copilot_user_flow():
  115. _model_flow_copilot(current_model)
  116. def _model_flow_copilot(current_model):
  117. from hermes_cli.model_setup import persist_model_selection
  118. from .catalog import COPILOT_BASE_URL
  119. from .wire import model_api_mode
  120. provider_id = "copilot"
  121. api_key, source = copilot_api_key()
  122. if not api_key:
  123. if not _copilot_obtain_token():
  124. return
  125. api_key, source = copilot_api_key()
  126. else:
  127. if source in {"GITHUB_TOKEN", "GH_TOKEN"}:
  128. from agent.secret_scope import secret_source_label
  129. say(f" GitHub token: {api_key[:8]}... ✓ ({source}{secret_source_label(source)})", "")
  130. else:
  131. say(" GitHub token: ✓", "")
  132. effective_base = COPILOT_BASE_URL
  133. catalog, live_models, _normalize = _copilot_catalog(api_key)
  134. if not catalog:
  135. live_models = _raw_model_ids(api_key)
  136. selected = pick_model_or_prompt(
  137. _copilot_model_list(live_models), "Model name: ", current_model=_normalize(current_model),
  138. confirm_provider=provider_id, confirm_base_url=effective_base, confirm_api_key=api_key)
  139. if not selected:
  140. print("No change.")
  141. return
  142. selected = _normalize(selected)
  143. persist_model_selection(selected, provider_id, base_url=effective_base,
  144. api_mode=model_api_mode(selected, catalog=catalog, api_key=api_key))
  145. print(f"Default model set to: {selected} (via GitHub Copilot)")
  146. def setup_reasoning_efforts(model: str) -> tuple:
  147. """Copilot publishes a per-model effort set; ``()`` when the model takes none."""
  148. from .catalog import github_model_reasoning_efforts
  149. return tuple(github_model_reasoning_efforts(model) or ())
  150. # ── Desktop Accounts card + in-app device-code login ──────────────────────────
  151. def account_status() -> dict[str, Any]:
  152. """Card status from the env-token ladder only (no token exchange: this runs
  153. on every Accounts list). A token here is managed on the Keys tab, so it reads as ``env_var``."""
  154. from hermes_cli.config import get_env_value
  155. from .credentials import COPILOT_ENV_VARS, validate_copilot_token
  156. from agent.secret_scope import secret_source_label
  157. for var in COPILOT_ENV_VARS:
  158. token = (get_env_value(var) or "").strip()
  159. if token and validate_copilot_token(token)[0]:
  160. return {"logged_in": True, "source": "env_var", "source_label": f"{var}{secret_source_label(var)}",
  161. "token_preview": None, "expires_at": None, "has_refresh_token": False}
  162. return {"logged_in": False, "source": None}
  163. def start_device_login() -> dict[str, Any]:
  164. """Ask GitHub for a device code (the same OAuth app as ``copilot_device_code_login``)."""
  165. from .credentials import (
  166. COPILOT_OAUTH_CLIENT_ID, _DEVICE_CODE_POLL_INTERVAL, _DEVICE_CODE_POLL_SAFETY_MARGIN, _post_form)
  167. data = _post_form(f"{_DEVICE_LOGIN_BASE}/login/device/code",
  168. {"client_id": COPILOT_OAUTH_CLIENT_ID, "scope": "read:user"}, 15)
  169. device_code, user_code = data.get("device_code", ""), data.get("user_code", "")
  170. if not device_code or not user_code:
  171. raise RuntimeError("GitHub did not return a device code.")
  172. interval = max(int(data.get("interval") or _DEVICE_CODE_POLL_INTERVAL), 1)
  173. return {"user_code": user_code, "verification_url": data.get("verification_uri") or _DEVICE_VERIFICATION_URL,
  174. "expires_in": int(data.get("expires_in") or _DEVICE_CODE_EXPIRES_IN),
  175. "interval": interval + _DEVICE_CODE_POLL_SAFETY_MARGIN,
  176. "state": {"device_code": device_code, "interval": interval}}
  177. def poll_device_login(state: dict[str, Any]) -> dict[str, Any]:
  178. """One token poll. A transport blip is just another pending tick, as in the terminal flow."""
  179. from .credentials import COPILOT_OAUTH_CLIENT_ID, _DEVICE_CODE_POLL_SAFETY_MARGIN, _post_form
  180. fields = {"client_id": COPILOT_OAUTH_CLIENT_ID, "device_code": state["device_code"],
  181. "grant_type": "urn:ietf:params:oauth:grant-type:device_code"}
  182. try:
  183. result = _post_form(f"{_DEVICE_LOGIN_BASE}/login/oauth/access_token", fields, 10)
  184. except (OSError, ValueError): # URLError/timeouts are OSError; a garbled body is ValueError
  185. return {"status": "pending"}
  186. if result.get("access_token"):
  187. return {"status": "approved", "credential": result["access_token"]}
  188. error = result.get("error", "")
  189. if error == "slow_down":
  190. # RFC 8628: add 5 seconds to polling interval (or honor a server-supplied one)
  191. server_interval = result.get("interval")
  192. if isinstance(server_interval, (int, float)) and server_interval > 0:
  193. interval = int(server_interval)
  194. else:
  195. interval = int(state.get("interval") or 1) + 5
  196. return {"status": "pending", "interval": interval + _DEVICE_CODE_POLL_SAFETY_MARGIN,
  197. "state": {**state, "interval": interval}}
  198. if not error or error == "authorization_pending":
  199. return {"status": "pending"}
  200. status, message = _DEVICE_ERRORS.get(error, ("error", f"Authorization failed: {error}"))
  201. return {"status": status, "message": message}
  202. def save_device_login(token: str) -> None:
  203. """Persist the GitHub OAuth token where the terminal device-code login puts it."""
  204. from hermes_cli.config import save_env_value
  205. save_env_value(_TOKEN_ENV_VAR, token)
  206. # ── `hermes auth add copilot` ─────────────────────────────────────────────────
  207. def _has_terminal() -> bool:
  208. # Both ends: Windows reports a NUL stdin as a tty, so a piped run would otherwise block on the poll.
  209. return sys.stdin.isatty() and sys.stdout.isatty()
  210. def auth_handler(action: str, args: Any) -> bool:
  211. """``hermes auth add copilot`` signs in with GitHub (device code, the same OAuth app as setup) and
  212. pools the GitHub token; the exchange runs when a request needs it. ``--api-key`` / ``--type
  213. api-key``, every other action and runs without a terminal stay with core's built-in handling."""
  214. if action != "add" or getattr(args, "api_key", None):
  215. return False
  216. if str(getattr(args, "auth_type", "") or "").strip().lower() in ("api-key", "api_key") or not _has_terminal():
  217. return False
  218. from agent.credential_pool import AUTH_TYPE_API_KEY, PooledCredential, load_pool
  219. from .catalog import COPILOT_BASE_URL
  220. from .credentials import copilot_device_code_login, validate_copilot_token
  221. token = copilot_device_code_login()
  222. if not token:
  223. raise SystemExit("GitHub sign-in did not complete; nothing was saved.")
  224. valid, msg = validate_copilot_token(token)
  225. if not valid:
  226. raise SystemExit(msg)
  227. pool = load_pool("copilot")
  228. label = (getattr(args, "label", None) or "").strip() or f"github-device-{len(pool.entries()) + 1}"
  229. pool.add_entry(PooledCredential(
  230. provider="copilot", id=uuid.uuid4().hex[:6], label=label, auth_type=AUTH_TYPE_API_KEY, priority=0,
  231. source="manual:device_code", access_token=token, base_url=COPILOT_BASE_URL))
  232. print(f'Added copilot credential #{len(pool.entries())}: "{label}"')
  233. return True
  234. SETUP_FIELDS: dict[str, Any] = {
  235. "model_setup_flow": model_flow_copilot,
  236. "setup_reasoning_efforts": setup_reasoning_efforts,
  237. "account_card": {"name": "GitHub Copilot", "docs_url": "https://docs.github.com/en/copilot"},
  238. "account_status": account_status,
  239. "start_device_login": start_device_login,
  240. "poll_device_login": poll_device_login,
  241. "save_device_login": save_device_login,
  242. "auth_handler": auth_handler,
  243. }