Skip to content
Open
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
5 changes: 5 additions & 0 deletions hermes_cli/proxy/adapters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,20 @@
from typing import Dict, Type

from hermes_cli.proxy.adapters.base import UpstreamAdapter
from hermes_cli.proxy.adapters.codex import OpenAICodexAdapter
from hermes_cli.proxy.adapters.nous_portal import NousPortalAdapter
from hermes_cli.proxy.adapters.xai import XAIGrokAdapter

# Registry of available adapter classes keyed by provider name as used on
# the ``hermes proxy start --provider <name>`` CLI flag.
ADAPTERS: Dict[str, Type[UpstreamAdapter]] = {
"openai-codex": OpenAICodexAdapter,
"nous": NousPortalAdapter,
"xai": XAIGrokAdapter,
}

_ALIASES = {"codex": "openai-codex"}


def get_adapter(name: str) -> UpstreamAdapter:
"""Instantiate an adapter by provider name.
Expand All @@ -26,6 +30,7 @@ def get_adapter(name: str) -> UpstreamAdapter:
ValueError: if ``name`` is not a registered adapter.
"""
key = (name or "").strip().lower()
key = _ALIASES.get(key, key)
if key not in ADAPTERS:
available = ", ".join(sorted(ADAPTERS)) or "(none)"
raise ValueError(
Expand Down
21 changes: 21 additions & 0 deletions hermes_cli/proxy/adapters/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,27 @@ def get_credential(self) -> UpstreamCredential:
refresh fails. The proxy will return 401 to the client.
"""

@property
def loopback_only(self) -> bool:
"""Whether this credential must never bind beyond loopback."""
return False

def get_owned_upstream_header_names(self) -> frozenset[str]:
"""Headers whose inbound client values must always be removed."""
return frozenset()

def get_upstream_headers(
self,
credential: UpstreamCredential,
) -> dict[str, str]:
"""Return provider-required headers in addition to Authorization.

The server applies these after filtering inbound client headers, so an
untrusted loopback client cannot spoof provider identity/account fields.
"""
_ = credential
return {}

def get_retry_credential(
self,
*,
Expand Down
166 changes: 166 additions & 0 deletions hermes_cli/proxy/adapters/codex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
"""OpenAI Codex OAuth upstream adapter for the loopback Hermes proxy."""

from __future__ import annotations

import logging
import threading
from typing import FrozenSet, Optional

from agent.credential_pool import CredentialPool, PooledCredential, load_pool
from hermes_cli.auth import DEFAULT_CODEX_BASE_URL
from hermes_cli.proxy.adapters.base import UpstreamAdapter, UpstreamCredential

logger = logging.getLogger(__name__)

_POOL_PROVIDER = "openai-codex"
_ALLOWED_PATHS: FrozenSet[str] = frozenset({"/responses", "/models"})
_OWNED_HEADERS: FrozenSet[str] = frozenset(
{"User-Agent", "originator", "ChatGPT-Account-ID"}
)


class OpenAICodexAdapter(UpstreamAdapter):
"""Attach the main Hermes Codex OAuth credential to Responses requests."""

auth_hint = "hermes auth add openai-codex --type oauth"

def __init__(self) -> None:
self._lock = threading.Lock()
self._pool: Optional[CredentialPool] = None

@property
def name(self) -> str:
return "openai-codex"

@property
def display_name(self) -> str:
return "OpenAI Codex OAuth"

@property
def loopback_only(self) -> bool:
return True

@property
def allowed_paths(self) -> FrozenSet[str]:
return _ALLOWED_PATHS

def is_authenticated(self) -> bool:
"""Check local pool state only; never call the network."""
pool = self._load_pool()
return bool(pool and pool.has_available())

def get_credential(self) -> UpstreamCredential:
with self._lock:
pool = self._load_pool()
if pool is None or not pool.has_credentials():
raise RuntimeError(
"No OpenAI Codex OAuth credentials found. Run "
"`hermes auth add openai-codex --type oauth` first."
)
entry = pool.select()
if entry is None:
raise RuntimeError(
"No available OpenAI Codex OAuth credentials. Reset the "
"pool cooldown or re-authenticate."
)
self._pool = pool
return self._credential_from_entry(entry)

def get_retry_credential(
self,
*,
failed_credential: UpstreamCredential,
status_code: int,
) -> Optional[UpstreamCredential]:
if status_code not in {401, 429}:
return None

with self._lock:
pool = self._pool or self._load_pool()
if pool is None:
return None

if status_code == 401:
refreshed = pool.try_refresh_matching(
api_key_hint=failed_credential.bearer
)
if refreshed is None:
# A concurrent request may have queued behind the adapter
# lock with the same now-stale bearer. If the first request
# already refreshed/rotated the pool, coalesce onto that
# current credential instead of failing or exhausting the
# obsolete token a second time.
current = pool.select()
if (
current is not None
and str(current.runtime_api_key or "").strip()
!= failed_credential.bearer
):
refreshed = current
if refreshed is None:
refreshed = pool.mark_exhausted_and_rotate(
status_code=401,
api_key_hint=failed_credential.bearer,
)
else:
refreshed = pool.mark_exhausted_and_rotate(
status_code=429,
api_key_hint=failed_credential.bearer,
)

if refreshed is None:
return None
retry = self._credential_from_entry(refreshed)
if retry.bearer == failed_credential.bearer:
return None
logger.info(
"proxy: Codex upstream returned %s; retrying with refreshed/rotated credential",
status_code,
)
return retry

def get_owned_upstream_header_names(self) -> frozenset[str]:
return _OWNED_HEADERS

def get_upstream_headers(
self,
credential: UpstreamCredential,
) -> dict[str, str]:
# Reuse the native Codex request identity contract: originator and
# User-Agent avoid Cloudflare challenges on VPS traffic, while the
# account header is extracted from the JWT when present.
from agent.auxiliary_client import _codex_cloudflare_headers

return _codex_cloudflare_headers(credential.bearer)

def _load_pool(self) -> Optional[CredentialPool]:
try:
return load_pool(_POOL_PROVIDER)
except Exception:
logger.warning("proxy: failed to load Codex OAuth credential pool", exc_info=True)
return None

def _credential_from_entry(self, entry: PooledCredential) -> UpstreamCredential:
bearer = str(entry.runtime_api_key or "").strip()
if not bearer:
raise RuntimeError(
"Codex OAuth pool entry has no access token. Re-authenticate "
"with `hermes auth add openai-codex --type oauth`."
)
base_url = str(
entry.runtime_base_url or entry.base_url or DEFAULT_CODEX_BASE_URL
).strip().rstrip("/")
trusted_base = DEFAULT_CODEX_BASE_URL.rstrip("/")
if base_url != trusted_base:
raise RuntimeError(
"Refusing to attach OpenAI Codex OAuth credentials to untrusted "
f"upstream {base_url!r}; expected {trusted_base!r}."
)
return UpstreamCredential(
bearer=bearer,
base_url=trusted_base,
expires_at=entry.expires_at,
)


__all__ = ["OpenAICodexAdapter"]
10 changes: 9 additions & 1 deletion hermes_cli/proxy/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
AIOHTTP_AVAILABLE,
DEFAULT_HOST,
DEFAULT_PORT,
is_loopback_host,
run_server,
)

Expand Down Expand Up @@ -52,6 +53,13 @@ def cmd_proxy_start(args: Any) -> int:

host = getattr(args, "host", None) or DEFAULT_HOST
port = getattr(args, "port", None) or DEFAULT_PORT
if adapter.loopback_only and not is_loopback_host(host):
print(
f"Error: {adapter.display_name} proxy is loopback-only; "
f"refusing bind host {host!r}.",
file=sys.stderr,
)
return 2

print(
f"Starting Hermes proxy for {adapter.display_name}\n"
Expand Down Expand Up @@ -121,7 +129,7 @@ def cmd_proxy(args: Any) -> int:
"OAuth-authenticated provider credentials to outbound requests.\n"
"\n"
"Subcommands:\n"
" hermes proxy start [--provider nous|xai] [--host 127.0.0.1] [--port 8645]\n"
" hermes proxy start [--provider codex|nous|xai] [--host 127.0.0.1] [--port 8645]\n"
" Run the proxy in the foreground.\n"
" hermes proxy status\n"
" Show which upstream adapters are ready.\n"
Expand Down
Loading