Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions github-copilot/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ hermes plugins install github-copilot
```

Needs a Hermes release in which Copilot has left core
([hermes-agent#144788](https://github.com/NousResearch/hermes-agent/pull/144788)). On an older Hermes the
plugin stays inactive and logs one warning: that Hermes still ships its own Copilot support, which keeps
working.
([hermes-agent#144788](https://github.com/NousResearch/hermes-agent/pull/144788)) and the generic
credential-pool runtime SDK: `providers.base.PoolRuntimeCredential`,
`ProviderProfile.prepare_pool_entry`, `refresh_pool_runtime_credentials`, and
`credential_pool_base_urls`. On a core missing these seams the plugin stays inactive and logs one
warning; upgrade core before using this plugin revision.

## Sign in

Expand Down Expand Up @@ -61,6 +63,27 @@ Copilot list.
starts `copilot --acp --stdio` per request; point it elsewhere with `HERMES_COPILOT_ACP_COMMAND` (or
`COPILOT_CLI_PATH`) and `HERMES_COPILOT_ACP_ARGS`.

## Credential-pool recovery

Pool rows retain the durable GitHub grant. After a row is selected, its exchanged Copilot bearer
and account endpoint are transient runtime credentials, never replacements in `auth.json`.
On a 401 or a stale-credential refusal (400 integrator, bare 403), Hermes renews only the row that
supplied the failed request: its memory, disk and failure-cache entries are evicted before a fresh
exchange of that same grant. A fine-grained PAT is never exchanged, so its row is not renewed.
Failed forced renewal returns no replacement; it never substitutes an ambient account or raw token.
Normal initial resolution still permits the existing same-account raw-token fallback.

Runtime endpoint changes are restricted to these exact HTTPS origins:
`https://api.githubcopilot.com`, `https://api.individual.githubcopilot.com`,
`https://api.business.githubcopilot.com`, and `https://api.enterprise.githubcopilot.com`.
Custom relays, alternate ports, path-prefixed URLs and lookalike domains are not authorized account
endpoint transitions. Catalog source ordering and fallback policy are unchanged.

GitHub Enterprise Cloud (`copilot-api.<enterprise>.ghe.com`) is not one of these origins yet: core
cannot admit a per-profile enterprise origin for pool rows. An env token with `COPILOT_GH_HOST` and
`COPILOT_API_BASE_URL` set as above keeps working through core's env resolution, which re-exchanges
it after a 401, but without pool rotation. `hermes auth add copilot` rows are not supported on GHEC.

## Premium requests

Copilot reads the `x-initiator` header to tell a request you started (`user`) from an agent follow-up
Expand Down
11 changes: 7 additions & 4 deletions github-copilot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"api_mode_for_model", "client_headers", "request_headers", "max_tokens_param",
"seed_pool_credentials", "refresh_runtime_credentials", "external_auth_evidence",
"live_context_length", "replay_message_carriers", "start_device_login", "picker_catalog",
"prepare_pool_entry", "refresh_pool_runtime_credentials", "credential_pool_base_urls",
)


Expand All @@ -37,20 +38,22 @@ def _bundled_copilot_dirs() -> list[Path]:

def inert_reason() -> str | None:
"""Why this core must not get these profiles, or None when it should."""
from providers.base import ProviderProfile
from providers import base

if bundled := _bundled_copilot_dirs():
return f"this Hermes core still bundles GitHub Copilot ({bundled[0]})"
if missing := [name for name in _REQUIRED_SEAMS if not hasattr(ProviderProfile, name)]:
if not hasattr(base, "PoolRuntimeCredential"):
return "this Hermes core lacks the PoolRuntimeCredential provider SDK"
if missing := [name for name in _REQUIRED_SEAMS if not hasattr(base.ProviderProfile, name)]:
return f"this Hermes core lacks the provider seams the plugin needs ({', '.join(missing)})"
return None


def _register() -> bool:
reason = inert_reason()
if reason:
logger.warning("github-copilot plugin is inactive: %s. Update Hermes; until then the core's "
"own Copilot support is used.", reason)
logger.warning("github-copilot plugin is inactive: %s. Update Hermes before using this "
"plugin revision.", reason)
return False
from providers import register_provider

Expand Down
6 changes: 6 additions & 0 deletions github-copilot/copilot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ def fetch_account_usage(
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,
credential_pool_base_urls=(
"https://api.githubcopilot.com",
"https://api.individual.githubcopilot.com",
"https://api.business.githubcopilot.com",
"https://api.enterprise.githubcopilot.com",
),
hostnames=HOSTNAMES, metadata_hostnames=METADATA_HOSTNAMES, models_dev_id=MODELS_DEV_ID, **CATALOG_FIELDS,
**PICKER_FIELDS, **AUTH_ROW_FIELDS,
)
57 changes: 29 additions & 28 deletions github-copilot/copilot/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from typing import Any, Optional

from agent.secret_scope import get_secret
from providers.base import PoolRuntimeCredential
from utils import atomic_json_write

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -410,7 +411,7 @@ def _fetch_exchange_with_retry(req, timeout: float, fp: str) -> dict:
if attempt < _EXCHANGE_MAX_ATTEMPTS:
sleep_s = _EXCHANGE_BACKOFF_BASE_SECONDS * attempt
logger.debug("Copilot token exchange attempt %d/%d failed (%s); retrying in %.1fs",
attempt, _EXCHANGE_MAX_ATTEMPTS, exc, sleep_s)
attempt, _EXCHANGE_MAX_ATTEMPTS, type(exc).__name__, sleep_s)
time.sleep(sleep_s)
_exchange_failure_cache[fp] = time.time() + (
_EXCHANGE_FAILURE_TTL_PERMANENT_SECONDS if permanent_failure
Expand Down Expand Up @@ -667,6 +668,8 @@ def _pool_token() -> tuple[str, str]:
class CopilotCredentialsMixin:
"""Fills the generic credential seams of ``providers.base.ProviderProfile`` for Copilot."""

base_url: str # supplied by ProviderProfile in the concrete CopilotProfile

def resolve_api_key_secret(self) -> tuple[str, str]:
"""The exchanged Copilot token. A home that never chose Copilot gets the raw env token (it
still reads as present) and GitHub is not called: provider listings resolve this for every
Expand Down Expand Up @@ -708,22 +711,35 @@ def runtime_base_url(self, *, api_key: str, default: str, env_url: str) -> str:
logger.debug("Copilot base URL resolution fell back to default: %s", exc)
return base_url

def prepare_pool_entry(self, entry: Any, api_key: str) -> str:
"""A pool row may still carry the RAW GitHub token: the seeder skips the exchange while
copilot is merely discovered (ambient gh login, not in config). Here copilot IS the runtime
target, and a raw token routes to the language-server integrator whose allowlist omits
enterprise-only models (400 model_not_available_for_integrator)."""
def prepare_pool_entry(self, entry: Any, api_key: str) -> str | PoolRuntimeCredential:
"""Exchange the selected GitHub grant without changing its durable pool row."""
if not api_key or not validate_copilot_token(api_key)[0]:
return api_key # already an exchanged API token
api_token, enterprise_base_url = get_copilot_api_token(api_key)
if api_token == api_key and not enterprise_base_url:
if not _is_fine_grained_pat(api_key):
_warn_raw_degradation_once(api_key)
return api_key
entry.access_token = api_token
if enterprise_base_url:
entry.base_url = enterprise_base_url
return api_token
return PoolRuntimeCredential(api_key=api_token, base_url=enterprise_base_url or self.base_url)

def refresh_pool_runtime_credentials(self, entry: Any, *, reason: str) -> Optional[PoolRuntimeCredential]:
"""Force renewal for this failed row only; never consult ambient credentials or fall back."""
if reason not in _RUNTIME_REFRESHERS:
return None
raw_token = entry.access_token
if not isinstance(raw_token, str) or not validate_copilot_token(raw_token)[0]:
return None
if _is_fine_grained_pat(raw_token):
return None # never exchanged by design: the PAT is the bearer, nothing to renew
try:
evict_cached_exchanged_token(raw_token)
api_token, _expires_at, base_url = exchange_copilot_token(raw_token)
except Exception as exc:
logger.debug("Copilot pool credential renewal failed (%s)", type(exc).__name__)
return None
if api_token == raw_token:
return None
return PoolRuntimeCredential(api_key=api_token, base_url=base_url or self.base_url)

def seed_pool_credentials(self, *, suppressed_sources: frozenset,
explicitly_configured: bool) -> list[dict]:
Expand All @@ -739,24 +755,9 @@ def seed_pool_credentials(self, *, suppressed_sources: frozenset,
source_name = f"env:{source}"
if source_name in suppressed_sources: # per-source gate BEFORE the network exchange
return []
from .activation import github_calls_allowed

# Core's ``explicitly_configured`` counts any profile env var, so a GH_TOKEN kept for
# other tools would pass it; the plugin's own check does not (``activation``).
del explicitly_configured
if not github_calls_allowed():
# Only discovered here (an ambient env token), not selected anywhere: no model is
# routed to it, so the exchange — and its degradation warning on every pool load —
# buys nothing (#114740). Seed the raw token; selecting copilot re-seeds and exchanges.
api_token, enterprise_base_url = token, None
else:
api_token, enterprise_base_url = get_copilot_api_token(token)
# A failed exchange falls back to the RAW token, which the Copilot API routes to the
# "copilot-language-server" integrator whose allowlist omits enterprise-only models
# -> HTTP 400 on every turn. Surface it once. A fine-grained PAT is raw by design.
if api_token == token and not enterprise_base_url and not _is_fine_grained_pat(token):
_warn_raw_degradation_once(token)
return [{"source": source_name, "access_token": api_token, "base_url": enterprise_base_url,
# The durable pool row holds the GitHub grant. Exchange only after selection;
# an expiring bearer must never become the persisted account credential.
return [{"source": source_name, "access_token": token, "base_url": None,
"label": source}]
except Exception as exc: # health: allow BLE001 -- moved verbatim from core (hermes_cli/copilot_auth.py, credential_pool, client_lifecycle, auth.py)
logger.debug("Copilot token seed failed: %s", exc)
Expand Down
13 changes: 11 additions & 2 deletions github-copilot/copilot/wire.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

Fills the generic ProviderProfile wire seams (``providers/base.py`` L1 block). Every hook here is
pure and answers from the arguments alone, except ``api_mode_for_model`` with an ``api_key``, which
may read the account's cached live catalog to normalize the model id and choose its HTTP wire.
may read the account's cached live catalog to normalize the model id and choose its HTTP wire (a
pooled GitHub grant reads it through its exchanged bearer).
"""

from __future__ import annotations
Expand Down Expand Up @@ -99,7 +100,15 @@ class CopilotWireMixin:

def api_mode_for_model(self, model: str, *, api_key: str | None = None) -> str | None:
# Keyless init/aux/fallback hooks are pure: normalize IDs but never borrow another account's cache.
return model_api_mode(model, catalog=[] if api_key is None else None, api_key=api_key)
if api_key is None:
return model_api_mode(model, catalog=[])
from .credentials import get_copilot_api_token, validate_copilot_token

# A pool row reaches this hook with its durable GitHub grant before core prepares the row. Read
# the catalog with the bearer the request will carry (the same cached exchange preparation uses).
if validate_copilot_token(api_key)[0]:
api_key = get_copilot_api_token(api_key)[0]
return model_api_mode(model, api_key=api_key)

def client_headers(
self, *, base_url: str, api_key: str = "", has_images: bool = False,
Expand Down
4 changes: 3 additions & 1 deletion github-copilot/plugin.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ description: >
providers: copilot (the Copilot API with your GitHub account, signed in with
`hermes auth add copilot` or a COPILOT_GITHUB_TOKEN / GH_TOKEN / GITHUB_TOKEN token) and
copilot-acp (drives your installed GitHub Copilot CLI over ACP). Needs a Hermes core
without bundled Copilot; on older cores it stays inactive.
without bundled Copilot and with the generic credential-pool runtime SDK
(PoolRuntimeCredential, refresh_pool_runtime_credentials, credential_pool_base_urls);
on older cores it stays inactive.
author: "Nous Research"
homepage: https://github.com/NousResearch/hermes-labs-plugins/tree/main/github-copilot
Loading
Loading