activation.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. """When the plugin may talk to GitHub: only for a home that chose Copilot, or while the user is in a
  2. Copilot flow they started.
  3. GH_TOKEN / GITHUB_TOKEN are general-purpose GitHub variables (gh, git hosting tools, CI), so their
  4. presence alone is not a choice of Copilot. Without this gate, any surface that lists providers
  5. (``hermes status``, the model picker, Desktop's model options) warmed the Copilot catalog for every
  6. home holding such a token: the token went to the Copilot exchange at api.github.com and the result
  7. fetched Copilot ``/models``. Core's ``is_provider_explicitly_configured`` cannot answer this for
  8. Copilot (it counts every profile ``env_vars`` entry, GH_TOKEN included), so the plugin decides.
  9. """
  10. from __future__ import annotations
  11. import contextlib
  12. import contextvars
  13. import logging
  14. from typing import Any, Iterator
  15. logger = logging.getLogger(__name__)
  16. # The provider ids that select this plugin's Copilot API profile (name + aliases in copilot/__init__.py).
  17. COPILOT_PROVIDER_IDS = frozenset({"copilot", "github-copilot", "github-models", "github-model", "github"})
  18. # Written only by Hermes' own Copilot sign-in (``hermes model``, Desktop) or pasted for Copilot.
  19. _COPILOT_ONLY_ENV_VAR = "COPILOT_GITHUB_TOKEN"
  20. # Pool rows a user created through a Hermes flow (``hermes auth add copilot``, with or without --api-key).
  21. _EXPLICIT_POOL_SOURCES = frozenset({"manual", "device_code"})
  22. _user_flow: contextvars.ContextVar[bool] = contextvars.ContextVar("copilot_user_flow", default=False)
  23. @contextlib.contextmanager
  24. def copilot_user_flow() -> Iterator[None]:
  25. """Mark a Copilot flow the user started (``hermes model`` → Copilot, ``hermes auth add copilot``):
  26. GitHub calls inside it are the user's request even before anything is configured."""
  27. token = _user_flow.set(True)
  28. try:
  29. yield
  30. finally:
  31. _user_flow.reset(token)
  32. def _selects(slot: Any) -> bool:
  33. return isinstance(slot, dict) and str(slot.get("provider") or "").strip().lower() in COPILOT_PROVIDER_IDS
  34. def _chain(value: Any) -> list:
  35. return value if isinstance(value, list) else [value]
  36. def _config_slots(cfg: dict) -> Iterator[Any]:
  37. """Every config.yaml slot that can route a request to a provider."""
  38. yield cfg.get("model")
  39. for key in ("fallback_model", "fallback_providers"):
  40. yield from _chain(cfg.get(key))
  41. delegation = cfg.get("delegation")
  42. if isinstance(delegation, dict):
  43. yield delegation
  44. yield from _chain(delegation.get("fallback_providers"))
  45. aux = cfg.get("auxiliary")
  46. if isinstance(aux, dict):
  47. yield from aux.values()
  48. moa = cfg.get("moa")
  49. if isinstance(moa, dict):
  50. presets = moa.get("presets")
  51. for block in (moa, *(presets.values() if isinstance(presets, dict) else ())):
  52. if isinstance(block, dict):
  53. yield from _chain(block.get("reference_models") or [])
  54. yield block.get("aggregator")
  55. def _config_selects_copilot() -> bool:
  56. from hermes_cli.config import load_config
  57. cfg = load_config() or {}
  58. return any(_selects(slot) for slot in _config_slots(cfg))
  59. def _pool_has_explicit_row() -> bool:
  60. from agent.credential_pool import read_credential_pool
  61. for entry in read_credential_pool("copilot") or ():
  62. source = str(entry.get("source") or "").strip().lower() if isinstance(entry, dict) else ""
  63. if source in _EXPLICIT_POOL_SOURCES or source.startswith("manual:"):
  64. return True
  65. return False
  66. def _copilot_env_token_set() -> bool:
  67. from agent.secret_scope import get_secret
  68. return bool((get_secret(_COPILOT_ONLY_ENV_VAR) or "").strip())
  69. _CHECKS = (_copilot_env_token_set, _config_selects_copilot, _pool_has_explicit_row)
  70. def copilot_explicitly_configured() -> bool:
  71. """True when this home chose Copilot: COPILOT_GITHUB_TOKEN, a config slot naming copilot (model,
  72. fallback, delegation, auxiliary task, MoA), or a pool row from ``hermes auth add copilot``."""
  73. for check in _CHECKS:
  74. try:
  75. if check():
  76. return True
  77. except Exception as exc: # a broken config/auth store reads as "not chosen": no GitHub call
  78. logger.debug("copilot explicit-config check %s failed: %s", check.__name__, exc)
  79. return False
  80. def github_calls_allowed() -> bool:
  81. """Whether the plugin may exchange a token at GitHub or fetch the Copilot catalog right now."""
  82. return _user_flow.get() or copilot_explicitly_configured()