The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(web_server): extract oauth pollers/status probes and messaging catalog/onboarding to web_server_oauth, web_server_messaging
Tekniumf5a04375ccaf
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex e8405ff68d1..fcacd3d2647 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -12,13 +12,10 @@ Usage:from contextlib import asynccontextmanager, contextmanagerimport asyncio-import functoolsfrom collections import dequefrom dataclasses import dataclass-from datetime import datetime, timezoneimport hashlibimport hmac-import inspectimport ipaddressimport jsonimport logging@@ -54,7 +51,6 @@ from hermes_cli.config import (build_cron_model_impact,cfg_get,DEFAULT_CONFIG,- OPTIONAL_ENV_VARS,clear_model_endpoint_credentials,get_hermes_home,get_process_hermes_home,@@ -70,7 +66,6 @@ from hermes_cli.config import (find_provider_entry,detect_install_method,redact_key,- write_platform_config_field,)from gateway.status import ( # noqa: F401 — late-bound by web_routers/status + tests monkeypatch web_server.<name>get_running_pid,@@ -97,7 +92,6 @@ except ImportError:)from fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse- from starlette.concurrency import run_in_threadpoolexcept Exception:raise SystemExit("Web UI requires fastapi and uvicorn.\n"@@ -4101,470 +4095,28 @@ def _parse_model_ids(resp: "Any") -> List[str]:return ids-# Entries omit fields they don't need to override; the catalog builder fills-# in env_vars from OPTIONAL_ENV_VARS via prefix matching when not specified,-# and pulls required_env from a plugin's PlatformEntry when available.-_PLATFORM_OVERRIDES: dict[str, dict[str, Any]] = {- "telegram": {- "name": "Telegram",- "description": "Run Hermes from Telegram DMs, groups, and topics.",- "docs_url": "https://core.telegram.org/bots/features#botfather",- "env_vars": ("TELEGRAM_BOT_TOKEN", "TELEGRAM_ALLOWED_USERS", "TELEGRAM_PROXY"),- "required_env": ("TELEGRAM_BOT_TOKEN",),- },- "discord": {- "name": "Discord",- "description": "Connect Hermes to Discord DMs, channels, and threads.",- "docs_url": "https://discord.com/developers/applications",- "env_vars": (- "DISCORD_BOT_TOKEN",- "DISCORD_ALLOWED_USERS",- ),- "required_env": ("DISCORD_BOT_TOKEN",),- },- "slack": {- "name": "Slack",- "description": "Use Hermes from Slack via Socket Mode. Add allowed Slack member IDs so connected bots can respond.",- "docs_url": "https://api.slack.com/apps",- "env_vars": ("SLACK_BOT_TOKEN", "SLACK_APP_TOKEN", "SLACK_ALLOWED_USERS"),- "required_env": ("SLACK_BOT_TOKEN", "SLACK_APP_TOKEN"),- },- "mattermost": {- "name": "Mattermost",- "description": "Connect Hermes to Mattermost channels and direct messages.",- "docs_url": "https://mattermost.com/deploy/",- "env_vars": ("MATTERMOST_URL", "MATTERMOST_TOKEN", "MATTERMOST_ALLOWED_USERS"),- "required_env": ("MATTERMOST_URL", "MATTERMOST_TOKEN"),- },- "matrix": {- "name": "Matrix",- "description": "Use Hermes in Matrix rooms and direct messages.",- "docs_url": "https://matrix.org/ecosystem/servers/",- "env_vars": (- "MATRIX_HOMESERVER",- "MATRIX_ACCESS_TOKEN",- "MATRIX_USER_ID",- "MATRIX_ALLOWED_USERS",- ),- "required_env": ("MATRIX_HOMESERVER", "MATRIX_ACCESS_TOKEN", "MATRIX_USER_ID"),- },- "signal": {- "name": "Signal",- "description": "Connect through a signal-cli REST bridge.",- "docs_url": "https://github.com/bbernhard/signal-cli-rest-api",- "env_vars": ("SIGNAL_HTTP_URL", "SIGNAL_ACCOUNT", "SIGNAL_ALLOWED_USERS"),- "required_env": ("SIGNAL_HTTP_URL", "SIGNAL_ACCOUNT"),- },- "whatsapp": {- "name": "WhatsApp",- "description": "Use Hermes through the bundled WhatsApp bridge with QR-based auth.",- "docs_url": "https://github.com/tulir/whatsmeow",- "env_vars": (- "WHATSAPP_ENABLED",- "WHATSAPP_MODE",- "WHATSAPP_DM_POLICY",- "WHATSAPP_ALLOWED_USERS",- ),- "required_env": (),- },- "homeassistant": {- "name": "Home Assistant",- "description": "Control your smart home from Hermes via Home Assistant.",- "docs_url": "https://www.home-assistant.io/docs/authentication/",- "env_vars": ("HASS_URL", "HASS_TOKEN"),- "required_env": ("HASS_URL", "HASS_TOKEN"),- },- "email": {- "name": "Email",- "description": "Talk to Hermes through an IMAP/SMTP mailbox.",- "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/",- "env_vars": (- "EMAIL_ADDRESS",- "EMAIL_PASSWORD",- "EMAIL_IMAP_HOST",- "EMAIL_SMTP_HOST",- ),- "required_env": (- "EMAIL_ADDRESS",- "EMAIL_PASSWORD",- "EMAIL_IMAP_HOST",- "EMAIL_SMTP_HOST",- ),- },- "sms": {- "name": "SMS (Twilio)",- "description": "Send and receive text messages via Twilio.",- "docs_url": "https://www.twilio.com/console",- "env_vars": ("TWILIO_ACCOUNT_SID", "TWILIO_AUTH_TOKEN"),- "required_env": ("TWILIO_ACCOUNT_SID", "TWILIO_AUTH_TOKEN"),- },- "dingtalk": {- "name": "DingTalk",- "description": "Connect Hermes to DingTalk groups (钉钉).",- "docs_url": "https://open.dingtalk.com/document/orgapp/the-robot-development-process",- "env_vars": ("DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"),- "required_env": ("DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"),- },- "feishu": {- "name": "Feishu / Lark",- "description": "Use Hermes inside Feishu / Lark.",- "docs_url": "https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/intro",- "env_vars": (- "FEISHU_APP_ID",- "FEISHU_APP_SECRET",- "FEISHU_ENCRYPT_KEY",- "FEISHU_VERIFICATION_TOKEN",- ),- "required_env": ("FEISHU_APP_ID", "FEISHU_APP_SECRET"),- },- "google_chat": {- "name": "Google Chat",- "description": "Connect Hermes to Google Chat via Cloud Pub/Sub.",- "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/google_chat",- },- "wecom": {- "name": "WeCom (group bot)",- "description": "Send-only WeCom group bot via webhook.",- "docs_url": "https://developer.work.weixin.qq.com/document/path/91770",- "env_vars": ("WECOM_BOT_ID", "WECOM_SECRET"),- "required_env": ("WECOM_BOT_ID",),- },- "wecom_callback": {- "name": "WeCom (app)",- "description": "Two-way WeCom integration via callback app.",- "docs_url": "https://developer.work.weixin.qq.com/document/path/90930",- "env_vars": (- "WECOM_CALLBACK_CORP_ID",- "WECOM_CALLBACK_CORP_SECRET",- "WECOM_CALLBACK_AGENT_ID",- "WECOM_CALLBACK_TOKEN",- "WECOM_CALLBACK_ENCODING_AES_KEY",- ),- "required_env": (- "WECOM_CALLBACK_CORP_ID",- "WECOM_CALLBACK_CORP_SECRET",- "WECOM_CALLBACK_AGENT_ID",- ),- },- "weixin": {- "name": "Weixin / WeChat (Personal)",- "description": "Connect a personal WeChat account through Tencent's iLink Bot API.",- "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/weixin/",- "env_vars": ("WEIXIN_ACCOUNT_ID", "WEIXIN_TOKEN", "WEIXIN_BASE_URL"),- "required_env": ("WEIXIN_ACCOUNT_ID", "WEIXIN_TOKEN"),- },- "bluebubbles": {- "name": "BlueBubbles (iMessage)",- "description": "Use Hermes through iMessage via a BlueBubbles server.",- "docs_url": "https://bluebubbles.app/",- "env_vars": (- "BLUEBUBBLES_SERVER_URL",- "BLUEBUBBLES_PASSWORD",- "BLUEBUBBLES_ALLOWED_USERS",- ),- "required_env": ("BLUEBUBBLES_SERVER_URL", "BLUEBUBBLES_PASSWORD"),- },- "qqbot": {- "name": "QQ Bot",- "description": "Connect Hermes to a QQ Bot from the QQ Open Platform.",- "docs_url": "https://q.qq.com",- "env_vars": ("QQ_APP_ID", "QQ_CLIENT_SECRET", "QQ_ALLOWED_USERS"),- "required_env": ("QQ_APP_ID", "QQ_CLIENT_SECRET"),- },- # Teams ships as a platform plugin, so its name/env vars come from the- # plugin registry. Only the docs link needs an override here so the- # Channels page can point at the Microsoft Teams setup guide.- "teams": {- "description": "Connect Hermes to Microsoft Teams chats via the Bot Framework.",- "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/teams",- },- # Bundled platform plugins: name comes from the plugin registry label;- # give each a human description (the registry's install_hint is a- # dependency note, not a description) and a docs link.- "irc": {- "description": "Relay messages between an IRC channel (or DMs) and Hermes.",- "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/irc",- },- "line": {- "description": "Use Hermes from LINE via the LINE Messaging API webhook.",- "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/line",- },- "ntfy": {- "description": "Chat with Hermes over ntfy push topics (ntfy.sh or self-hosted).",- "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/ntfy",- },- "photon": {- "description": "Use Hermes through iMessage via Photon's managed Spectrum platform.",- "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/photon",- },- "raft": {- "description": "Join a Raft workspace as an external agent.",- "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/raft",- },- "simplex": {- "description": "Talk to Hermes over SimpleX Chat via a local simplex-chat daemon.",- "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/simplex",- },- "yuanbao": {- "name": "Yuanbao (元宝)",- "description": "Connect Hermes to Tencent Yuanbao.",- "docs_url": "",- "required_env": (),- },- "api_server": {- "name": "API server",- "description": "Expose Hermes as an OpenAI-compatible HTTP API for tools like Open WebUI.",- "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/",- "env_vars": (- "API_SERVER_ENABLED",- "API_SERVER_KEY",- "API_SERVER_PORT",- "API_SERVER_HOST",- "API_SERVER_MODEL_NAME",- ),- "required_env": (),- },- "webhook": {- "name": "Webhooks",- "description": "Receive events from GitHub, GitLab, and other webhook sources.",- "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/webhooks/",- "env_vars": ("WEBHOOK_ENABLED", "WEBHOOK_PORT", "WEBHOOK_SECRET"),- "required_env": (),- },- "msgraph_webhook": {- "name": "Microsoft Graph Webhook",- "description": "Receive Microsoft Graph change notifications (Teams meetings, Outlook, …).",- "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/msgraph-webhook",- "required_env": (),- },- "whatsapp_cloud": {- "name": "WhatsApp Cloud API",- "description": "Use Hermes via Meta's hosted WhatsApp Cloud API (no local bridge).",- "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/whatsapp-cloud",- },- "relay": {- "name": "Relay (experimental)",- "description": "Generic relay adapter fronted by the Hermes Relay connector.",- "docs_url": "",- "required_env": (),- },-}--# Display order: well-known platforms surface first; unknown plugins fall to-# the end alphabetically.-_PLATFORM_ORDER: tuple[str, ...] = (- "telegram",- "discord",- "slack",- "mattermost",- "matrix",- "whatsapp",- "signal",- "bluebubbles",- "homeassistant",- "email",- "sms",- "dingtalk",- "feishu",- "google_chat",- "wecom",- "wecom_callback",- "weixin",- "qqbot",- "yuanbao",- "api_server",- "webhook",+from hermes_cli.web_server_messaging import ( # noqa: E402,F401 — re-exported; routers/tests reach these via web_server.<name>+ _MESSAGING_KEYS_PAGE_KEYS,+ _TelegramOnboardingPairing,+ _WhatsAppOnboardingSession,+ _build_catalog_entry,+ _channel_managed_env_keys,+ _messaging_platform_catalog,+ _restart_gateway_after_whatsapp_onboarding,+ _telegram_onboarding_error_message,+ _telegram_onboarding_lock,+ _telegram_onboarding_pairings,+ _telegram_onboarding_request_sync,+ _whatsapp_onboarding_payload,+ _whatsapp_onboarding_sessions,+ _whatsapp_session_path,+ _write_platform_enabled,)-def _messaging_platform_catalog() -> tuple[dict[str, Any], ...]:- """Build the messaging catalog from the gateway's Platform enum + plugin registry.-- Built-in platforms come from ``gateway.config.Platform`` (LOCAL is excluded).- Plugin platforms come from ``gateway.platform_registry.plugin_entries()``,- which lets newly installed adapters (e.g. IRC) appear without a code change- here. Per-platform UI metadata (description, docs URL, env-var picks) lives- in :data:`_PLATFORM_OVERRIDES`; anything not overridden gets reasonable- defaults derived from the platform id and required_env.- """- from gateway.config import Platform-- # Resolve plugin entries FIRST. Plugin platforms (irc, ntfy, photon, …)- # leak into ``Platform.__members__`` as pseudo-members the moment any- # earlier code path calls ``Platform("<plugin id>")`` — and iterating the- # enum first would then claim them with no plugin metadata, rendering- # nameless "Irc"/"Ntfy" cards with empty descriptions on the Channels- # page while the real label/install-hint sat unused in the registry.- plugin_map: dict[str, Any] = {}- try:- # Plugin discovery only runs as a side effect of importing- # model_tools; this server process doesn't do that, so trigger it- # explicitly (idempotent) or plugin_entries() is empty here and- # every plugin platform renders nameless.- from hermes_cli.plugins import discover_plugins-- discover_plugins()- from gateway.platform_registry import platform_registry-- for plugin_entry in platform_registry.plugin_entries():- plugin_map[plugin_entry.name] = plugin_entry- except Exception:- _log.debug("plugin platform registry unavailable", exc_info=True)-- seen: set[str] = set()- entries: list[dict[str, Any]] = []-- for member in Platform.__members__.values():- if member.value == "local":- continue- if member.value in seen:- continue- seen.add(member.value)- entries.append(- _build_catalog_entry(member.value, plugin_map.get(member.value))- )-- for name, plugin_entry in plugin_map.items():- if name in seen:- continue- seen.add(name)- entries.append(_build_catalog_entry(name, plugin_entry))-- order = {pid: idx for idx, pid in enumerate(_PLATFORM_ORDER)}- entries.sort(- key=lambda e: (order.get(e["id"], len(_PLATFORM_ORDER)), e["name"].lower())- )- return tuple(entries)---def _channel_managed_env_keys() -> frozenset[str]:- """Env-var keys owned by a Channels page platform card.-- The Channels page is the canonical surface for configuring messaging- platform credentials (with connection status, test, enable toggle and- gateway restart). The Keys/Env page consults this set to hide those vars- so the same fields aren't duplicated in a plainer UI. Best-effort: if the- gateway catalog can't be built, nothing is flagged and Keys shows it all.- """- try:- keys: set[str] = set()- for entry in _messaging_platform_catalog():- keys.update(entry.get("env_vars", ()))- return frozenset(keys)- except Exception:- _log.debug("could not build channel-managed env key set", exc_info=True)- return frozenset()---# Cross-cutting gateway / relay knobs stay on the Keys → Settings tab even though-# they use the ``messaging`` category in OPTIONAL_ENV_VARS. Platform-scoped vars-# (``DISCORD_*``, ``MATRIX_*``, …) are owned by the Messaging UI instead.-_MESSAGING_KEYS_PAGE_KEYS = frozenset({- "GATEWAY_ALLOW_ALL_USERS",- "GATEWAY_PROXY_KEY",- "GATEWAY_PROXY_URL",-})---def _platform_env_prefixes(platform_id: str) -> tuple[str, ...]:- """Env-var prefixes owned by a messaging platform card."""- aliases: dict[str, tuple[str, ...]] = {- "email": ("EMAIL_",),- "homeassistant": ("HASS_",),- "qqbot": ("QQ_", "QQBOT_"),- "sms": ("TWILIO_",),- "wecom": ("WECOM_BOT_", "WECOM_SECRET"),- "wecom_callback": ("WECOM_CALLBACK_",),- }- if platform_id in aliases:- return aliases[platform_id]- return (platform_id.upper().replace("-", "_") + "_",)--# Which per-platform knobs the setup UI hides, and why: see# hermes_cli/setup_hidden_env.py. Shared with the `hermes setup gateway`# wizard so the surfaces ask for the same things.-from hermes_cli.setup_hidden_env import ( # noqa: E402- is_setup_hidden_env as _is_setup_hidden_env,-)---def _discover_platform_env_vars(platform_id: str) -> tuple[str, ...]:- """All messaging-category env vars for a platform (override + plugin + prefix)."""- prefixes = _platform_env_prefixes(platform_id)- keys: list[str] = []- for name, info in OPTIONAL_ENV_VARS.items():- if info.get("category") != "messaging":- continue- if name in _MESSAGING_KEYS_PAGE_KEYS:- continue- if _is_setup_hidden_env(name):- continue- if not any(name.startswith(prefix) for prefix in prefixes):- continue- keys.append(name)- return tuple(sorted(set(keys)))---def _merge_platform_env_vars(- platform_id: str,- override: dict[str, Any],- plugin_entry: Any | None,-) -> tuple[str, ...]:- """Canonical env-var list for a messaging platform card.-- Required credentials always survive: a platform that genuinely needs one of- the hidden-suffix vars to connect keeps it, since hiding a required field- would make the platform unconfigurable.- """- discovered = _discover_platform_env_vars(platform_id)- if "env_vars" in override:- explicit = tuple(- key for key in override["env_vars"] if not _is_setup_hidden_env(key)- )- return tuple(dict.fromkeys((*explicit, *discovered)))- if plugin_entry is not None and plugin_entry.required_env:- return tuple(dict.fromkeys((*tuple(plugin_entry.required_env), *discovered)))- return discovered---def _build_catalog_entry(- platform_id: str, plugin_entry: Any | None = None-) -> dict[str, Any]:- override = _PLATFORM_OVERRIDES.get(platform_id, {})-- env_vars = _merge_platform_env_vars(platform_id, override, plugin_entry)-- if "required_env" in override:- required_env = tuple(override["required_env"])- elif plugin_entry is not None:- required_env = tuple(plugin_entry.required_env or ())- else:- required_env = ()-- if override.get("name"):- name = override["name"]- elif plugin_entry is not None and plugin_entry.label:- name = plugin_entry.label- else:- name = platform_id.replace("_", " ").title()-- description = override.get("description")- if not description and plugin_entry is not None:- description = plugin_entry.install_hint or ""-- return {- "id": platform_id,- "name": name,- "description": description or "",- "docs_url": override.get("docs_url", ""),- "env_vars": env_vars,- "required_env": required_env,- }---def _write_platform_enabled(platform_id: str, enabled: bool) -> None:- write_platform_config_field(platform_id, "enabled", enabled)from hermes_cli.web_routers import messaging as _messaging_routes # noqa: E402@@ -4576,452 +4128,17 @@ from hermes_cli.web_routers.messaging import ( # noqa: E402,F401 — legacy re-)-@dataclass-class _WhatsAppOnboardingSession:- proc: subprocess.Popen | None- mode: str- allowed_users: str- session_path: str- expires_at: str- expires_at_ts: float- profile: str | None = None- status: str = "starting"- qr_payload: str | None = None- account_id: str | None = None- account_name: str | None = None- account_phone: str | None = None- error: str | None = None---_whatsapp_onboarding_sessions: dict[str, _WhatsAppOnboardingSession] = {}---def _whatsapp_session_path() -> Path:- from hermes_constants import get_hermes_dir-- return get_hermes_dir("platforms/whatsapp/session", "whatsapp/session")---def _whatsapp_onboarding_payload(pairing_id: str, record: _WhatsAppOnboardingSession) -> dict[str, Any]:- return {- "pairing_id": pairing_id,- "status": record.status,- "qr_payload": record.qr_payload,- "expires_at": record.expires_at,- "mode": record.mode,- "allowed_users": record.allowed_users,- "account_id": record.account_id,- "account_name": record.account_name,- "account_phone": record.account_phone,- "error": record.error,- }---def _restart_gateway_after_whatsapp_onboarding(profile: Optional[str] = None) -> dict[str, Any]:- return _restart_gateway_after(profile, what="WhatsApp onboarding", label="WhatsApp onboarding")---_TELEGRAM_ONBOARDING_DEFAULT_URL = "https://setup.hermes-agent.nousresearch.com"-_TELEGRAM_ONBOARDING_USER_AGENT = f"HermesDashboard/{__version__}"-@dataclass-class _TelegramOnboardingPairing:- poll_token: str- expires_at: str- expires_at_ts: float- bot_token: str | None = None- bot_username: str | None = None- owner_user_id: str | None = None---_telegram_onboarding_pairings: dict[str, _TelegramOnboardingPairing] = {}-_telegram_onboarding_lock = threading.RLock()---def _telegram_onboarding_base_url() -> str:- return (- os.getenv("TELEGRAM_ONBOARDING_URL", _TELEGRAM_ONBOARDING_DEFAULT_URL)- .strip()- .rstrip("/")- )---def _telegram_onboarding_error_message(error: str, fallback: str) -> str:- return {- "not_found": "Telegram pairing was not found. Start a new setup.",- "expired": "Telegram setup expired. Start a new setup.",- "claimed": "Telegram setup was already claimed. Start a new setup.",- "unauthorized": "Telegram setup service rejected this request.",- "telegram_manager_bot_token_not_configured": "Telegram setup service is not configured.",- "telegram_token_fetch_failed": "Telegram could not finish bot setup. Try again.",- }.get(error, fallback)---def _telegram_onboarding_request_sync(- method: str,- path: str,- *,- body: dict[str, Any] | None = None,- bearer_token: str | None = None,-) -> dict[str, Any]:- import httpx-- headers = {- "Accept": "application/json",- "User-Agent": _TELEGRAM_ONBOARDING_USER_AGENT,- }- request_kwargs: dict[str, Any] = {}- if body is not None:- headers["Content-Type"] = "application/json"- request_kwargs["json"] = body- if bearer_token:- headers["Authorization"] = f"Bearer {bearer_token}"-- url = f"{_telegram_onboarding_base_url()}{path}"- try:- with httpx.Client(timeout=httpx.Timeout(10.0)) as client:- response = client.request(- method,- url,- headers=headers,- **request_kwargs,- )- response.raise_for_status()- except httpx.HTTPStatusError as exc:- try:- parsed = exc.response.json()- except Exception:- parsed = {}- error = str(parsed.get("error") or parsed.get("status") or "")- detail = _telegram_onboarding_error_message(- error,- "Telegram setup service returned an error.",- )- status_code = 404 if exc.response.status_code == 404 else 502- if error in {"expired", "claimed"}:- status_code = 410- raise HTTPException(status_code=status_code, detail=detail) from exc- except httpx.RequestError as exc:- raise HTTPException(- status_code=502,- detail="Telegram setup service is unavailable. Try again shortly.",- ) from exc- except Exception as exc:- raise HTTPException(- status_code=502,- detail="Telegram setup service is unavailable. Try again shortly.",- ) from exc-- try:- parsed = response.json()- except Exception as exc:- raise HTTPException(- status_code=502,- detail="Telegram setup service returned an invalid response.",- ) from exc- if not isinstance(parsed, dict):- raise HTTPException(- status_code=502,- detail="Telegram setup service returned an invalid response.",- )- return parsed---# ----------------------------------------------------------------------------# OAuth provider endpoints — status + disconnect (Phase 1)-# ----------------------------------------------------------------------------#-# Phase 1 surfaces *which OAuth providers exist* and whether each is-# connected, plus a disconnect button. Anthropic subscription OAuth is-# deliberately delegated away from the dashboard: its card is external and-# points to the supported terminal path. Phase 2 adds in-browser device-code-# flows for providers that support them. For unconnected providers we return-# the canonical ``hermes auth add <provider>`` command so the dashboard can-# surface a one-click copy.---def _truncate_token(value: Optional[str], visible: int = 6) -> str:- """Return ``...XXXXXX`` (last N chars) for safe display in the UI.-- We never expose more than the trailing ``visible`` characters of an- OAuth access token. JWT prefixes (the part before the first dot) are- stripped first when present so the visible suffix is always part of- the signing region rather than a meaningless header chunk.-- Returns the Entra-ID placeholder when handed a callable (Azure Foundry- bearer provider) — the callable is NEVER invoked here.- """- if not value:- return ""- if callable(value) and not isinstance(value, str):- # Entra ID bearer provider — never reveal a minted token in the UI.- return "<entra-id-bearer>"- s = str(value)- if "." in s and s.count(".") >= 2:- # Looks like a JWT — show the trailing piece of the signature only.- s = s.rsplit(".", 1)[-1]- if len(s) <= visible:- return s- return f"…{s[-visible:]}"---def _anthropic_oauth_status() -> Dict[str, Any]:- """Status for the "Anthropic API Key" catalog entry.-- Two sources, in priority order:- 1. ``~/.hermes/.anthropic_oauth.json`` — Hermes-managed terminal PKCE- credentials (the dashboard no longer has a Connect button for this)- 2. ``ANTHROPIC_API_KEY`` → ``ANTHROPIC_TOKEN`` → ``CLAUDE_CODE_OAUTH_TOKEN``- env vars (registry order) — from ``.env``, the shell, or an external- secret source like Bitwarden (whose keys are injected into the process- env during ``load_hermes_dotenv()``, so the same check covers them)-- Claude Code's ``~/.claude/.credentials.json`` is deliberately NOT read- here — it has its own dedicated catalog entry (``claude-code`` →- ``_claude_code_only_status``). Reporting it under the API-key entry- double-counts the token and shadows a real ANTHROPIC_API_KEY.- """- try:- from agent.anthropic_adapter import (- read_hermes_oauth_credentials,- _get_hermes_oauth_file,- )- except ImportError:- read_hermes_oauth_credentials = None # type: ignore- _get_hermes_oauth_file = None # type: ignore-- hermes_creds = None- if read_hermes_oauth_credentials:- try:- hermes_creds = read_hermes_oauth_credentials()- except Exception:- hermes_creds = None- if hermes_creds and hermes_creds.get("accessToken"):- return {- "logged_in": True,- "source": "hermes_pkce",- "source_label": f"Hermes PKCE ({_get_hermes_oauth_file() if _get_hermes_oauth_file else None})",- "token_preview": _truncate_token(hermes_creds.get("accessToken")),- "expires_at": hermes_creds.get("expiresAt"),- "has_refresh_token": bool(hermes_creds.get("refreshToken")),- }-- # Env-var / secret-source path. ``get_env_value`` checks the process- # environment first (where Bitwarden-sourced secrets land) then .env.- env_var_order: tuple = ("ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN")- try:- from hermes_cli.auth import PROVIDER_REGISTRY- env_var_order = PROVIDER_REGISTRY["anthropic"].api_key_env_vars- except (ImportError, KeyError):- pass- try:- from hermes_cli.config import get_env_value- except ImportError:- get_env_value = None # type: ignore- try:- from hermes_cli.env_loader import format_secret_source_suffix- except ImportError:- format_secret_source_suffix = None # type: ignore-- for var in env_var_order:- value = (get_env_value(var) if get_env_value else None) or os.getenv(var)- if not value:- continue- suffix = format_secret_source_suffix(var) if format_secret_source_suffix else ""- return {- "logged_in": True,- "source": "env_var",- "source_label": f"{var}{suffix}",- "token_preview": _truncate_token(value),- "expires_at": None,- "has_refresh_token": False,- }- return {"logged_in": False, "source": None}---def _claude_code_only_status() -> Dict[str, Any]:- """Surface Claude Code CLI credentials as their own provider entry.-- Independent of the Anthropic entry above so users can see whether their- Claude Code subscription tokens are actively flowing into Hermes even- when they also have a separate Hermes-managed PKCE login.- """- try:- from agent.anthropic_adapter import read_claude_code_credentials- creds = read_claude_code_credentials()- except Exception:- creds = None- if creds and creds.get("accessToken"):- return {- "logged_in": True,- "source": "claude_code_cli",- "source_label": "~/.claude/.credentials.json",- "token_preview": _truncate_token(creds.get("accessToken")),- "expires_at": creds.get("expiresAt"),- "has_refresh_token": bool(creds.get("refreshToken")),- }- return {"logged_in": False, "source": None}---def _copilot_acp_status() -> Dict[str, Any]:- """Status for copilot-acp — credentials are owned by the Copilot CLI.-- ``logged_in`` is claimed only on positive evidence (a supported env token- or a known on-disk GitHub Copilot credential store, via- ``auth.get_external_process_provider_status``). The Copilot CLI may also- hold its session in an OS keychain Hermes can't read, so the unverified- state is presented as "managed by the Copilot CLI" — never as 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 the- user actually has configured.-- The static catalog assumes the default executable name; users who point- Hermes at a custom binary (``HERMES_COPILOT_ACP_COMMAND`` /- ``COPILOT_CLI_PATH``) would otherwise be told to run a command that isn't- the one Hermes spawns. Non-external-process providers get ``default`` back- untouched.- """- try:- from hermes_cli.auth import PROVIDER_REGISTRY, get_external_process_provider_status- pconfig = PROVIDER_REGISTRY.get(provider_id)- if not pconfig or pconfig.auth_type != "external_process":- return default- status = get_external_process_provider_status(provider_id) or {}- command = str(status.get("command") or "").strip()- if command:- parts = default.split(" ", 1)- tail = f" {parts[1]}" if len(parts) > 1 else ""- return f"{command}{tail}"- except Exception:- pass- return default---# Explicit, hand-tuned OAuth/account provider cards. These carry the bits that-# can't be derived from the unified provider catalog: the OAuth ``flow`` shape,-# the per-provider ``status_fn``, the ``cli_command`` fallback, and curated-# display order. They are the OVERRIDE BASE for ``_build_oauth_catalog()``,-# which unions them with every accounts-tab provider in ``provider_catalog()``-# so newly-added OAuth/external providers appear automatically (no hand edit).-# This tuple also still includes two entries that are NOT catalog providers but-# must show on the Accounts tab: the Anthropic credential-status card and the-# synthetic ``claude-code`` subscription row.-# ``flow`` describes the account-management shape so the UI can pick the right-# behavior: ``device_code`` = show code + verification URL + poll, and-# ``external`` = read-only/delegated to a terminal or third-party CLI.-_OAUTH_PROVIDER_CATALOG: tuple[Dict[str, Any], ...] = (- {- "id": "nous",- "name": "Nous Portal",- "flow": "device_code",- "cli_command": "hermes auth add nous",- "docs_url": "https://portal.nousresearch.com",- "status_fn": None, # dispatched via auth.get_nous_auth_status- },- {- "id": "openai-codex",- "name": "ChatGPT or Codex Subscription",- "flow": "device_code",- "cli_command": "hermes auth add openai-codex",- "docs_url": "https://platform.openai.com/docs",- "status_fn": None, # dispatched via auth.get_codex_auth_status- },- {- "id": "qwen-oauth",- "name": "Qwen (via Qwen CLI)",- "flow": "external",- "cli_command": "hermes auth add qwen-oauth",- "docs_url": "https://github.com/QwenLM/qwen-code",- "status_fn": None, # dispatched via auth.get_qwen_auth_status- },- {- "id": "minimax-oauth",- "name": "MiniMax (OAuth)",- # MiniMax's flow is structurally device-code (verification URI +- # user code, backend polls the token endpoint) with a PKCE- # extension for code-binding. The dashboard renders the same UX- # as Nous's device-code flow; the PKCE bit is a security- # extension that doesn't change the operator experience.- "flow": "device_code",- "cli_command": "hermes auth add minimax-oauth",- "docs_url": "https://www.minimax.io",- "status_fn": None, # dispatched via auth.get_minimax_oauth_auth_status- },- {- "id": "xai-oauth",- "name": "xAI Grok OAuth (SuperGrok / Premium+)",- # Device code is the default because it works in remote shells,- # containers, and desktop installs without requiring a reachable- # 127.0.0.1 callback.- "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, # dispatched via auth.get_xai_oauth_auth_status- },- {- "id": "copilot-acp",- "name": "GitHub Copilot (ACP)",- "flow": "external",- # `copilot login` is the CLI's non-interactive device-code login- # subcommand; the previous `copilot /login` form is not a valid- # invocation (slash-commands only exist inside an interactive- # session, reachable as `copilot -i /login`).- "cli_command": "copilot login",- "docs_url": "https://docs.github.com/en/copilot",- "status_fn": _copilot_acp_status,- },- # ── Anthropic / Claude entries sit at the bottom.- #- # This card is deliberately flow == "external" (no in-dashboard "Connect"- # button walking the user through claude.ai/oauth/authorize from the web- # server). Hermes previously reimplemented that subscription-OAuth PKCE- # dance itself for the dashboard (issues #87887/#87888); that surface was- # removed because it lets an unattended, scriptable HTTP endpoint mint- # Claude Pro/Max subscription tokens outside Anthropic's own client,- # which sits on the wrong side of Anthropic's usage policies for OAuth- # credentials. Login still works via the terminal (`hermes auth add- # anthropic`, unaffected by this change) or a plain API key below.- {- "id": "anthropic",- "name": "Anthropic API Key",- "flow": "external",- "cli_command": "hermes auth add anthropic",- "docs_url": "https://docs.claude.com/en/api/getting-started",- "status_fn": _anthropic_oauth_status,- },- {- "id": "claude-code",- "name": "Anthropic OAuth: Required Extra Usage Credits to Use Subscription",- "flow": "external",- "cli_command": "claude setup-token",- "docs_url": "https://docs.claude.com/en/docs/claude-code",- "status_fn": _claude_code_only_status,- },+from hermes_cli.web_server_oauth import ( # noqa: E402,F401 — re-exported; routers/tests reach these via web_server.<name>+ _OAUTH_PROVIDER_CATALOG,+ _external_process_cli_command,+ _minimax_poller,+ _nous_poller,+ _oauth_profile_name,+ _oauth_session_profile,+ _oauth_sessions,+ _oauth_sessions_lock,+ _truncate_token,+ _xai_device_poller,)@@ -5036,239 +4153,6 @@ from hermes_cli.web_routers.oauth import ( # noqa: E402,F401 — legacy re-expo)-_oauth_sessions: Dict[str, Dict[str, Any]] = {}-_oauth_sessions_lock = threading.Lock()---def _oauth_profile_name(profile: Optional[str]) -> Optional[str]:- requested = (profile or "").strip()- if not requested or requested.lower() == "current":- return None- return requested---def _oauth_session_profile(- session_id: str,- fallback: Optional[str] = None,-) -> Optional[str]:- """Return the profile that owns an OAuth session, if one was provided."""- with _oauth_sessions_lock:- sess = _oauth_sessions.get(session_id)- profile = sess.get("profile") if sess else None- return profile or _oauth_profile_name(fallback)---def _oauth_poller(label: str):- """Wrap a background device-code poller body ``fn(session_id, sess)``.-- Looks up the session (a vanished session is a no-op), marks it- ``approved`` when the body returns, and on any exception records- ``error`` + ``error_message`` on the session instead of raising — the- thread has no caller to report to; the dashboard reads the status.- """- def deco(fn):- @functools.wraps(fn)- def poller(session_id: str) -> None:- with _oauth_sessions_lock:- sess = _oauth_sessions.get(session_id)- if not sess:- return- try:- fn(session_id, sess)- with _oauth_sessions_lock:- sess["status"] = "approved"- _log.info("oauth/device: %s login completed (session=%s)", label, session_id)- except Exception as e:- _log.warning("%s device-code poll failed (session=%s): %s", label, session_id, e)- with _oauth_sessions_lock:- sess["status"] = "error"- sess["error_message"] = str(e)- return poller- return deco--@_oauth_poller("nous")-def _nous_poller(session_id: str, sess: Dict[str, Any]) -> None:- """Background poller that drives a Nous device-code flow to completion."""- from hermes_cli.auth import (- _poll_for_token,- refresh_nous_oauth_from_state,- )- from datetime import datetime, timezone- import httpx- portal_base_url = sess["portal_base_url"]- client_id = sess["client_id"]- device_code = sess["device_code"]- interval = sess["interval"]- scope = sess.get("scope")- expires_in = max(60, int(sess["expires_at"] - time.time()))- with httpx.Client(timeout=httpx.Timeout(15.0), headers={"Accept": "application/json"}) as client:- token_data = _poll_for_token(- client=client,- portal_base_url=portal_base_url,- client_id=client_id,- device_code=device_code,- expires_in=expires_in,- poll_interval=interval,- )- # Same post-processing as _nous_device_code_login (validate/refresh JWT)- now = datetime.now(timezone.utc)- token_ttl = int(token_data.get("expires_in") or 0)- auth_state = {- "portal_base_url": portal_base_url,- "inference_base_url": token_data.get("inference_base_url"),- "client_id": client_id,- "scope": token_data.get("scope") or scope,- "token_type": token_data.get("token_type", "Bearer"),- "access_token": token_data["access_token"],- "refresh_token": token_data.get("refresh_token"),- "obtained_at": now.isoformat(),- "expires_at": (- datetime.fromtimestamp(now.timestamp() + token_ttl, tz=timezone.utc).isoformat()- if token_ttl else None- ),- "expires_in": token_ttl,- }- with _profile_scope(_oauth_session_profile(session_id)):- full_state = refresh_nous_oauth_from_state(- auth_state,- timeout_seconds=15.0,- force_refresh=False,- )- from hermes_cli.auth import persist_nous_credentials- persist_nous_credentials(full_state)---@_oauth_poller("minimax")-def _minimax_poller(session_id: str, sess: Dict[str, Any]) -> None:- """Background poller that drives a MiniMax OAuth flow to completion.-- Mirrors `_nous_poller` but calls the MiniMax-specific token endpoint,- which uses a PKCE-style ``code_verifier`` + ``user_code`` rather than- the ``device_code`` field used by Nous. On success, builds the same- auth_state dict that ``_minimax_oauth_login`` (the CLI flow) builds- and persists via ``_minimax_save_auth_state`` — so the dashboard- path leaves the system in the same state as- ``hermes auth add minimax-oauth``.- """- from hermes_cli.auth import (- _minimax_poll_token,- _minimax_resolve_token_expiry_unix,- _minimax_save_auth_state,- MINIMAX_OAUTH_GLOBAL_INFERENCE,- MINIMAX_OAUTH_SCOPE,- )- from datetime import datetime, timezone- import httpx- portal_base_url = sess["portal_base_url"]- client_id = sess["client_id"]- user_code = sess["user_code"]- code_verifier = sess["code_verifier"]- interval_ms = sess.get("interval_ms")- expired_in_raw = sess["expired_in_raw"]- with httpx.Client(- timeout=httpx.Timeout(15.0),- headers={"Accept": "application/json"},- follow_redirects=True,- ) as client:- token_data = _minimax_poll_token(- client=client,- portal_base_url=portal_base_url,- client_id=client_id,- user_code=user_code,- code_verifier=code_verifier,- expired_in=expired_in_raw,- interval_ms=interval_ms,- )- # Build the auth_state dict in the same shape as the CLI flow's- # `_minimax_oauth_login` so `_minimax_save_auth_state` writes- # the canonical record. Region is fixed to "global" for the- # dashboard path; cn-region operators can still use the CLI- # flow which supports `--region cn`.- now = datetime.now(timezone.utc)- expires_at_ts = _minimax_resolve_token_expiry_unix(- int(token_data["expired_in"]), now=now,- )- expires_in_s = max(0, int(expires_at_ts - now.timestamp()))- auth_state = {- "provider": "minimax-oauth",- "region": sess.get("region", "global"),- "portal_base_url": portal_base_url,- "inference_base_url": MINIMAX_OAUTH_GLOBAL_INFERENCE,- "client_id": client_id,- "scope": MINIMAX_OAUTH_SCOPE,- "token_type": token_data.get("token_type", "Bearer"),- "access_token": token_data["access_token"],- "refresh_token": token_data["refresh_token"],- "resource_url": token_data.get("resource_url"),- "obtained_at": now.isoformat(),- "expires_at": datetime.fromtimestamp(- expires_at_ts, tz=timezone.utc- ).isoformat(),- "expires_in": expires_in_s,- }- with _profile_scope(_oauth_session_profile(session_id)):- _minimax_save_auth_state(auth_state)---@_oauth_poller("xai")-def _xai_device_poller(session_id: str, sess: Dict[str, Any]) -> None:- """Background poller for xAI's OAuth device-code flow."""- import httpx- from hermes_cli.auth import (- _save_xai_oauth_tokens,- _xai_oauth_discovery,- _xai_oauth_poll_device_token,- mark_provider_active_if_unset,- unsuppress_credential_source,- )-- device_code = sess["device_code"]- interval = int(sess["interval"])- expires_in = max(60, int(sess["expires_at"] - time.time()))- discovery = _xai_oauth_discovery(20.0)- with httpx.Client(- timeout=httpx.Timeout(20.0),- headers={"Accept": "application/json"},- ) as client:- token_data = _xai_oauth_poll_device_token(- client,- token_endpoint=discovery["token_endpoint"],- device_code=device_code,- expires_in=expires_in,- poll_interval=interval,- )- tokens = {- "access_token": str(token_data.get("access_token", "") or "").strip(),- "refresh_token": str(token_data.get("refresh_token", "") or "").strip(),- "id_token": str(token_data.get("id_token", "") or "").strip(),- "expires_in": token_data.get("expires_in"),- "token_type": str(token_data.get("token_type") or "Bearer").strip() or "Bearer",- }- with _profile_scope(_oauth_session_profile(session_id)):- _save_xai_oauth_tokens(- tokens,- discovery=discovery,- last_refresh=datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),- auth_mode="oauth_device_code",- # Persist credentials without hijacking an existing active- # chat provider.- set_active=False,- )- # Mirror `hermes auth add xai-oauth`: first credential may become- # active when none is set yet; never overwrite an existing choice.- mark_provider_active_if_unset("xai-oauth")- # The singleton write above is the single source of truth: the- # credential-pool load seeds it as the canonical ``device_code``- # entry. Do NOT also insert a parallel ``manual:dashboard_*`` pool- # entry — that duplicates the single-use refresh token across two- # entries and triggers rotation churn / ``refresh_token_reused``.- # An interactive dashboard login is also an explicit re-enable- # signal, so clear any ``device_code`` suppression left by a- # prior ``hermes auth remove xai-oauth`` (mirrors auth_add_command- # and the ``hermes model`` re-login path in _login_xai_oauth).- unsuppress_credential_source("xai-oauth", "device_code")--from hermes_cli.web_server_sessions import ( # noqa: E402,F401 — re-exported; routers/tests reach these via web_server.<name>_auto_archive_ticker_loop,_last_auto_archive_check,diff --git a/hermes_cli/web_server_messaging.py b/hermes_cli/web_server_messaging.pynew file mode 100644index 00000000000..b898f3b21a1--- /dev/null+++ b/hermes_cli/web_server_messaging.py@@ -0,0 +1,632 @@+"""Messaging-platform catalog and onboarding helpers: platform overrides/env discovery, WhatsApp and Telegram onboarding state.++Split out of ``hermes_cli.web_server``; every externally used name is re-imported+there, so ``web_server.<name>`` keeps resolving (and monkeypatching) as before.+Helpers that tests patch on ``web_server`` are reached lazily through it.+"""++import logging+import os+import subprocess+import threading+from dataclasses import dataclass+from fastapi import HTTPException+from pathlib import Path+from typing import Any, Optional+from hermes_cli import __version__+from hermes_cli.config import OPTIONAL_ENV_VARS, write_platform_config_field+from hermes_cli.setup_hidden_env import is_setup_hidden_env as _is_setup_hidden_env++# Same logger the code used before extraction (record parity).+_log = logging.getLogger("hermes_cli.web_server")+++# Entries omit fields they don't need to override; the catalog builder fills+# in env_vars from OPTIONAL_ENV_VARS via prefix matching when not specified,+# and pulls required_env from a plugin's PlatformEntry when available.+_PLATFORM_OVERRIDES: dict[str, dict[str, Any]] = {+ "telegram": {+ "name": "Telegram",+ "description": "Run Hermes from Telegram DMs, groups, and topics.",+ "docs_url": "https://core.telegram.org/bots/features#botfather",+ "env_vars": ("TELEGRAM_BOT_TOKEN", "TELEGRAM_ALLOWED_USERS", "TELEGRAM_PROXY"),+ "required_env": ("TELEGRAM_BOT_TOKEN",),+ },+ "discord": {+ "name": "Discord",+ "description": "Connect Hermes to Discord DMs, channels, and threads.",+ "docs_url": "https://discord.com/developers/applications",+ "env_vars": (+ "DISCORD_BOT_TOKEN",+ "DISCORD_ALLOWED_USERS",+ ),+ "required_env": ("DISCORD_BOT_TOKEN",),+ },+ "slack": {+ "name": "Slack",+ "description": "Use Hermes from Slack via Socket Mode. Add allowed Slack member IDs so connected bots can respond.",+ "docs_url": "https://api.slack.com/apps",+ "env_vars": ("SLACK_BOT_TOKEN", "SLACK_APP_TOKEN", "SLACK_ALLOWED_USERS"),+ "required_env": ("SLACK_BOT_TOKEN", "SLACK_APP_TOKEN"),+ },+ "mattermost": {+ "name": "Mattermost",+ "description": "Connect Hermes to Mattermost channels and direct messages.",+ "docs_url": "https://mattermost.com/deploy/",+ "env_vars": ("MATTERMOST_URL", "MATTERMOST_TOKEN", "MATTERMOST_ALLOWED_USERS"),+ "required_env": ("MATTERMOST_URL", "MATTERMOST_TOKEN"),+ },+ "matrix": {+ "name": "Matrix",+ "description": "Use Hermes in Matrix rooms and direct messages.",+ "docs_url": "https://matrix.org/ecosystem/servers/",+ "env_vars": (+ "MATRIX_HOMESERVER",+ "MATRIX_ACCESS_TOKEN",+ "MATRIX_USER_ID",+ "MATRIX_ALLOWED_USERS",+ ),+ "required_env": ("MATRIX_HOMESERVER", "MATRIX_ACCESS_TOKEN", "MATRIX_USER_ID"),+ },+ "signal": {+ "name": "Signal",+ "description": "Connect through a signal-cli REST bridge.",+ "docs_url": "https://github.com/bbernhard/signal-cli-rest-api",+ "env_vars": ("SIGNAL_HTTP_URL", "SIGNAL_ACCOUNT", "SIGNAL_ALLOWED_USERS"),+ "required_env": ("SIGNAL_HTTP_URL", "SIGNAL_ACCOUNT"),+ },+ "whatsapp": {+ "name": "WhatsApp",+ "description": "Use Hermes through the bundled WhatsApp bridge with QR-based auth.",+ "docs_url": "https://github.com/tulir/whatsmeow",+ "env_vars": (+ "WHATSAPP_ENABLED",+ "WHATSAPP_MODE",+ "WHATSAPP_DM_POLICY",+ "WHATSAPP_ALLOWED_USERS",+ ),+ "required_env": (),+ },+ "homeassistant": {+ "name": "Home Assistant",+ "description": "Control your smart home from Hermes via Home Assistant.",+ "docs_url": "https://www.home-assistant.io/docs/authentication/",+ "env_vars": ("HASS_URL", "HASS_TOKEN"),+ "required_env": ("HASS_URL", "HASS_TOKEN"),+ },+ "email": {+ "name": "Email",+ "description": "Talk to Hermes through an IMAP/SMTP mailbox.",+ "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/",+ "env_vars": (+ "EMAIL_ADDRESS",+ "EMAIL_PASSWORD",+ "EMAIL_IMAP_HOST",+ "EMAIL_SMTP_HOST",+ ),+ "required_env": (+ "EMAIL_ADDRESS",+ "EMAIL_PASSWORD",+ "EMAIL_IMAP_HOST",+ "EMAIL_SMTP_HOST",+ ),+ },+ "sms": {+ "name": "SMS (Twilio)",+ "description": "Send and receive text messages via Twilio.",+ "docs_url": "https://www.twilio.com/console",+ "env_vars": ("TWILIO_ACCOUNT_SID", "TWILIO_AUTH_TOKEN"),+ "required_env": ("TWILIO_ACCOUNT_SID", "TWILIO_AUTH_TOKEN"),+ },+ "dingtalk": {+ "name": "DingTalk",+ "description": "Connect Hermes to DingTalk groups (钉钉).",+ "docs_url": "https://open.dingtalk.com/document/orgapp/the-robot-development-process",+ "env_vars": ("DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"),+ "required_env": ("DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"),+ },+ "feishu": {+ "name": "Feishu / Lark",+ "description": "Use Hermes inside Feishu / Lark.",+ "docs_url": "https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/im-v1/intro",+ "env_vars": (+ "FEISHU_APP_ID",+ "FEISHU_APP_SECRET",+ "FEISHU_ENCRYPT_KEY",+ "FEISHU_VERIFICATION_TOKEN",+ ),+ "required_env": ("FEISHU_APP_ID", "FEISHU_APP_SECRET"),+ },+ "google_chat": {+ "name": "Google Chat",+ "description": "Connect Hermes to Google Chat via Cloud Pub/Sub.",+ "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/google_chat",+ },+ "wecom": {+ "name": "WeCom (group bot)",+ "description": "Send-only WeCom group bot via webhook.",+ "docs_url": "https://developer.work.weixin.qq.com/document/path/91770",+ "env_vars": ("WECOM_BOT_ID", "WECOM_SECRET"),+ "required_env": ("WECOM_BOT_ID",),+ },+ "wecom_callback": {+ "name": "WeCom (app)",+ "description": "Two-way WeCom integration via callback app.",+ "docs_url": "https://developer.work.weixin.qq.com/document/path/90930",+ "env_vars": (+ "WECOM_CALLBACK_CORP_ID",+ "WECOM_CALLBACK_CORP_SECRET",+ "WECOM_CALLBACK_AGENT_ID",+ "WECOM_CALLBACK_TOKEN",+ "WECOM_CALLBACK_ENCODING_AES_KEY",+ ),+ "required_env": (+ "WECOM_CALLBACK_CORP_ID",+ "WECOM_CALLBACK_CORP_SECRET",+ "WECOM_CALLBACK_AGENT_ID",+ ),+ },+ "weixin": {+ "name": "Weixin / WeChat (Personal)",+ "description": "Connect a personal WeChat account through Tencent's iLink Bot API.",+ "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/weixin/",+ "env_vars": ("WEIXIN_ACCOUNT_ID", "WEIXIN_TOKEN", "WEIXIN_BASE_URL"),+ "required_env": ("WEIXIN_ACCOUNT_ID", "WEIXIN_TOKEN"),+ },+ "bluebubbles": {+ "name": "BlueBubbles (iMessage)",+ "description": "Use Hermes through iMessage via a BlueBubbles server.",+ "docs_url": "https://bluebubbles.app/",+ "env_vars": (+ "BLUEBUBBLES_SERVER_URL",+ "BLUEBUBBLES_PASSWORD",+ "BLUEBUBBLES_ALLOWED_USERS",+ ),+ "required_env": ("BLUEBUBBLES_SERVER_URL", "BLUEBUBBLES_PASSWORD"),+ },+ "qqbot": {+ "name": "QQ Bot",+ "description": "Connect Hermes to a QQ Bot from the QQ Open Platform.",+ "docs_url": "https://q.qq.com",+ "env_vars": ("QQ_APP_ID", "QQ_CLIENT_SECRET", "QQ_ALLOWED_USERS"),+ "required_env": ("QQ_APP_ID", "QQ_CLIENT_SECRET"),+ },+ # Teams ships as a platform plugin, so its name/env vars come from the+ # plugin registry. Only the docs link needs an override here so the+ # Channels page can point at the Microsoft Teams setup guide.+ "teams": {+ "description": "Connect Hermes to Microsoft Teams chats via the Bot Framework.",+ "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/teams",+ },+ # Bundled platform plugins: name comes from the plugin registry label;+ # give each a human description (the registry's install_hint is a+ # dependency note, not a description) and a docs link.+ "irc": {+ "description": "Relay messages between an IRC channel (or DMs) and Hermes.",+ "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/irc",+ },+ "line": {+ "description": "Use Hermes from LINE via the LINE Messaging API webhook.",+ "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/line",+ },+ "ntfy": {+ "description": "Chat with Hermes over ntfy push topics (ntfy.sh or self-hosted).",+ "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/ntfy",+ },+ "photon": {+ "description": "Use Hermes through iMessage via Photon's managed Spectrum platform.",+ "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/photon",+ },+ "raft": {+ "description": "Join a Raft workspace as an external agent.",+ "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/raft",+ },+ "simplex": {+ "description": "Talk to Hermes over SimpleX Chat via a local simplex-chat daemon.",+ "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/simplex",+ },+ "yuanbao": {+ "name": "Yuanbao (元宝)",+ "description": "Connect Hermes to Tencent Yuanbao.",+ "docs_url": "",+ "required_env": (),+ },+ "api_server": {+ "name": "API server",+ "description": "Expose Hermes as an OpenAI-compatible HTTP API for tools like Open WebUI.",+ "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/",+ "env_vars": (+ "API_SERVER_ENABLED",+ "API_SERVER_KEY",+ "API_SERVER_PORT",+ "API_SERVER_HOST",+ "API_SERVER_MODEL_NAME",+ ),+ "required_env": (),+ },+ "webhook": {+ "name": "Webhooks",+ "description": "Receive events from GitHub, GitLab, and other webhook sources.",+ "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/webhooks/",+ "env_vars": ("WEBHOOK_ENABLED", "WEBHOOK_PORT", "WEBHOOK_SECRET"),+ "required_env": (),+ },+ "msgraph_webhook": {+ "name": "Microsoft Graph Webhook",+ "description": "Receive Microsoft Graph change notifications (Teams meetings, Outlook, …).",+ "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/msgraph-webhook",+ "required_env": (),+ },+ "whatsapp_cloud": {+ "name": "WhatsApp Cloud API",+ "description": "Use Hermes via Meta's hosted WhatsApp Cloud API (no local bridge).",+ "docs_url": "https://hermes-agent.nousresearch.com/docs/user-guide/messaging/whatsapp-cloud",+ },+ "relay": {+ "name": "Relay (experimental)",+ "description": "Generic relay adapter fronted by the Hermes Relay connector.",+ "docs_url": "",+ "required_env": (),+ },+}++# Display order: well-known platforms surface first; unknown plugins fall to+# the end alphabetically.+_PLATFORM_ORDER: tuple[str, ...] = (+ "telegram",+ "discord",+ "slack",+ "mattermost",+ "matrix",+ "whatsapp",+ "signal",+ "bluebubbles",+ "homeassistant",+ "email",+ "sms",+ "dingtalk",+ "feishu",+ "google_chat",+ "wecom",+ "wecom_callback",+ "weixin",+ "qqbot",+ "yuanbao",+ "api_server",+ "webhook",+)+++def _messaging_platform_catalog() -> tuple[dict[str, Any], ...]:+ """Build the messaging catalog from the gateway's Platform enum + plugin registry.++ Built-in platforms come from ``gateway.config.Platform`` (LOCAL is excluded).+ Plugin platforms come from ``gateway.platform_registry.plugin_entries()``,+ which lets newly installed adapters (e.g. IRC) appear without a code change+ here. Per-platform UI metadata (description, docs URL, env-var picks) lives+ in :data:`_PLATFORM_OVERRIDES`; anything not overridden gets reasonable+ defaults derived from the platform id and required_env.+ """+ from gateway.config import Platform++ # Resolve plugin entries FIRST. Plugin platforms (irc, ntfy, photon, …)+ # leak into ``Platform.__members__`` as pseudo-members the moment any+ # earlier code path calls ``Platform("<plugin id>")`` — and iterating the+ # enum first would then claim them with no plugin metadata, rendering+ # nameless "Irc"/"Ntfy" cards with empty descriptions on the Channels+ # page while the real label/install-hint sat unused in the registry.+ plugin_map: dict[str, Any] = {}+ try:+ # Plugin discovery only runs as a side effect of importing+ # model_tools; this server process doesn't do that, so trigger it+ # explicitly (idempotent) or plugin_entries() is empty here and+ # every plugin platform renders nameless.+ from hermes_cli.plugins import discover_plugins++ discover_plugins()+ from gateway.platform_registry import platform_registry++ for plugin_entry in platform_registry.plugin_entries():+ plugin_map[plugin_entry.name] = plugin_entry+ except Exception:+ _log.debug("plugin platform registry unavailable", exc_info=True)++ seen: set[str] = set()+ entries: list[dict[str, Any]] = []++ for member in Platform.__members__.values():+ if member.value == "local":+ continue+ if member.value in seen:+ continue+ seen.add(member.value)+ entries.append(+ _build_catalog_entry(member.value, plugin_map.get(member.value))+ )++ for name, plugin_entry in plugin_map.items():+ if name in seen:+ continue+ seen.add(name)+ entries.append(_build_catalog_entry(name, plugin_entry))++ order = {pid: idx for idx, pid in enumerate(_PLATFORM_ORDER)}+ entries.sort(+ key=lambda e: (order.get(e["id"], len(_PLATFORM_ORDER)), e["name"].lower())+ )+ return tuple(entries)+++def _channel_managed_env_keys() -> frozenset[str]:+ """Env-var keys owned by a Channels page platform card.++ The Channels page is the canonical surface for configuring messaging+ platform credentials (with connection status, test, enable toggle and+ gateway restart). The Keys/Env page consults this set to hide those vars+ so the same fields aren't duplicated in a plainer UI. Best-effort: if the+ gateway catalog can't be built, nothing is flagged and Keys shows it all.+ """+ try:+ keys: set[str] = set()+ for entry in _messaging_platform_catalog():+ keys.update(entry.get("env_vars", ()))+ return frozenset(keys)+ except Exception:+ _log.debug("could not build channel-managed env key set", exc_info=True)+ return frozenset()+++# Cross-cutting gateway / relay knobs stay on the Keys → Settings tab even though+# they use the ``messaging`` category in OPTIONAL_ENV_VARS. Platform-scoped vars+# (``DISCORD_*``, ``MATRIX_*``, …) are owned by the Messaging UI instead.+_MESSAGING_KEYS_PAGE_KEYS = frozenset({+ "GATEWAY_ALLOW_ALL_USERS",+ "GATEWAY_PROXY_KEY",+ "GATEWAY_PROXY_URL",+})+++def _platform_env_prefixes(platform_id: str) -> tuple[str, ...]:+ """Env-var prefixes owned by a messaging platform card."""+ aliases: dict[str, tuple[str, ...]] = {+ "email": ("EMAIL_",),+ "homeassistant": ("HASS_",),+ "qqbot": ("QQ_", "QQBOT_"),+ "sms": ("TWILIO_",),+ "wecom": ("WECOM_BOT_", "WECOM_SECRET"),+ "wecom_callback": ("WECOM_CALLBACK_",),+ }+ if platform_id in aliases:+ return aliases[platform_id]+ return (platform_id.upper().replace("-", "_") + "_",)+++def _discover_platform_env_vars(platform_id: str) -> tuple[str, ...]:+ """All messaging-category env vars for a platform (override + plugin + prefix)."""+ prefixes = _platform_env_prefixes(platform_id)+ keys: list[str] = []+ for name, info in OPTIONAL_ENV_VARS.items():+ if info.get("category") != "messaging":+ continue+ if name in _MESSAGING_KEYS_PAGE_KEYS:+ continue+ if _is_setup_hidden_env(name):+ continue+ if not any(name.startswith(prefix) for prefix in prefixes):+ continue+ keys.append(name)+ return tuple(sorted(set(keys)))+++def _merge_platform_env_vars(+ platform_id: str,+ override: dict[str, Any],+ plugin_entry: Any | None,+) -> tuple[str, ...]:+ """Canonical env-var list for a messaging platform card.++ Required credentials always survive: a platform that genuinely needs one of+ the hidden-suffix vars to connect keeps it, since hiding a required field+ would make the platform unconfigurable.+ """+ discovered = _discover_platform_env_vars(platform_id)+ if "env_vars" in override:+ explicit = tuple(+ key for key in override["env_vars"] if not _is_setup_hidden_env(key)+ )+ return tuple(dict.fromkeys((*explicit, *discovered)))+ if plugin_entry is not None and plugin_entry.required_env:+ return tuple(dict.fromkeys((*tuple(plugin_entry.required_env), *discovered)))+ return discovered+++def _build_catalog_entry(+ platform_id: str, plugin_entry: Any | None = None+) -> dict[str, Any]:+ override = _PLATFORM_OVERRIDES.get(platform_id, {})++ env_vars = _merge_platform_env_vars(platform_id, override, plugin_entry)++ if "required_env" in override:+ required_env = tuple(override["required_env"])+ elif plugin_entry is not None:+ required_env = tuple(plugin_entry.required_env or ())+ else:+ required_env = ()++ if override.get("name"):+ name = override["name"]+ elif plugin_entry is not None and plugin_entry.label:+ name = plugin_entry.label+ else:+ name = platform_id.replace("_", " ").title()++ description = override.get("description")+ if not description and plugin_entry is not None:+ description = plugin_entry.install_hint or ""++ return {+ "id": platform_id,+ "name": name,+ "description": description or "",+ "docs_url": override.get("docs_url", ""),+ "env_vars": env_vars,+ "required_env": required_env,+ }+++def _write_platform_enabled(platform_id: str, enabled: bool) -> None:+ write_platform_config_field(platform_id, "enabled", enabled)+++@dataclass+class _WhatsAppOnboardingSession:+ proc: subprocess.Popen | None+ mode: str+ allowed_users: str+ session_path: str+ expires_at: str+ expires_at_ts: float+ profile: str | None = None+ status: str = "starting"+ qr_payload: str | None = None+ account_id: str | None = None+ account_name: str | None = None+ account_phone: str | None = None+ error: str | None = None+++_whatsapp_onboarding_sessions: dict[str, _WhatsAppOnboardingSession] = {}+++def _whatsapp_session_path() -> Path:+ from hermes_constants import get_hermes_dir++ return get_hermes_dir("platforms/whatsapp/session", "whatsapp/session")+++def _whatsapp_onboarding_payload(pairing_id: str, record: _WhatsAppOnboardingSession) -> dict[str, Any]:+ return {+ "pairing_id": pairing_id,+ "status": record.status,+ "qr_payload": record.qr_payload,+ "expires_at": record.expires_at,+ "mode": record.mode,+ "allowed_users": record.allowed_users,+ "account_id": record.account_id,+ "account_name": record.account_name,+ "account_phone": record.account_phone,+ "error": record.error,+ }+++def _restart_gateway_after_whatsapp_onboarding(profile: Optional[str] = None) -> dict[str, Any]:+ from hermes_cli.web_server import _restart_gateway_after+ return _restart_gateway_after(profile, what="WhatsApp onboarding", label="WhatsApp onboarding")+++_TELEGRAM_ONBOARDING_DEFAULT_URL = "https://setup.hermes-agent.nousresearch.com"+_TELEGRAM_ONBOARDING_USER_AGENT = f"HermesDashboard/{__version__}"+++@dataclass+class _TelegramOnboardingPairing:+ poll_token: str+ expires_at: str+ expires_at_ts: float+ bot_token: str | None = None+ bot_username: str | None = None+ owner_user_id: str | None = None+++_telegram_onboarding_pairings: dict[str, _TelegramOnboardingPairing] = {}+_telegram_onboarding_lock = threading.RLock()+++def _telegram_onboarding_base_url() -> str:+ return (+ os.getenv("TELEGRAM_ONBOARDING_URL", _TELEGRAM_ONBOARDING_DEFAULT_URL)+ .strip()+ .rstrip("/")+ )+++def _telegram_onboarding_error_message(error: str, fallback: str) -> str:+ return {+ "not_found": "Telegram pairing was not found. Start a new setup.",+ "expired": "Telegram setup expired. Start a new setup.",+ "claimed": "Telegram setup was already claimed. Start a new setup.",+ "unauthorized": "Telegram setup service rejected this request.",+ "telegram_manager_bot_token_not_configured": "Telegram setup service is not configured.",+ "telegram_token_fetch_failed": "Telegram could not finish bot setup. Try again.",+ }.get(error, fallback)+++def _telegram_onboarding_request_sync(+ method: str,+ path: str,+ *,+ body: dict[str, Any] | None = None,+ bearer_token: str | None = None,+) -> dict[str, Any]:+ import httpx++ headers = {+ "Accept": "application/json",+ "User-Agent": _TELEGRAM_ONBOARDING_USER_AGENT,+ }+ request_kwargs: dict[str, Any] = {}+ if body is not None:+ headers["Content-Type"] = "application/json"+ request_kwargs["json"] = body+ if bearer_token:+ headers["Authorization"] = f"Bearer {bearer_token}"++ url = f"{_telegram_onboarding_base_url()}{path}"+ try:+ with httpx.Client(timeout=httpx.Timeout(10.0)) as client:+ response = client.request(+ method,+ url,+ headers=headers,+ **request_kwargs,+ )+ response.raise_for_status()+ except httpx.HTTPStatusError as exc:+ try:+ parsed = exc.response.json()+ except Exception:+ parsed = {}+ error = str(parsed.get("error") or parsed.get("status") or "")+ detail = _telegram_onboarding_error_message(+ error,+ "Telegram setup service returned an error.",+ )+ status_code = 404 if exc.response.status_code == 404 else 502+ if error in {"expired", "claimed"}:+ status_code = 410+ raise HTTPException(status_code=status_code, detail=detail) from exc+ except httpx.RequestError as exc:+ raise HTTPException(+ status_code=502,+ detail="Telegram setup service is unavailable. Try again shortly.",+ ) from exc+ except Exception as exc:+ raise HTTPException(+ status_code=502,+ detail="Telegram setup service is unavailable. Try again shortly.",+ ) from exc++ try:+ parsed = response.json()+ except Exception as exc:+ raise HTTPException(+ status_code=502,+ detail="Telegram setup service returned an invalid response.",+ ) from exc+ if not isinstance(parsed, dict):+ raise HTTPException(+ status_code=502,+ detail="Telegram setup service returned an invalid response.",+ )+ return parseddiff --git a/hermes_cli/web_server_oauth.py b/hermes_cli/web_server_oauth.pynew file mode 100644index 00000000000..223671be714--- /dev/null+++ b/hermes_cli/web_server_oauth.py@@ -0,0 +1,551 @@+"""Dashboard OAuth/login-status helpers: provider catalog, per-provider device pollers, Anthropic/Copilot/Claude-Code status probes.++Split out of ``hermes_cli.web_server``; every externally used name is re-imported+there, so ``web_server.<name>`` keeps resolving (and monkeypatching) as before.+Helpers that tests patch on ``web_server`` are reached lazily through it.+"""++import logging+import functools+import os+import threading+import time+from datetime import datetime, timezone+from typing import Any, Dict, Optional++# Same logger the code used before extraction (record parity).+_log = logging.getLogger("hermes_cli.web_server")+++# ---------------------------------------------------------------------------+# OAuth provider endpoints — status + disconnect (Phase 1)+# ---------------------------------------------------------------------------+#+# Phase 1 surfaces *which OAuth providers exist* and whether each is+# connected, plus a disconnect button. Anthropic subscription OAuth is+# deliberately delegated away from the dashboard: its card is external and+# points to the supported terminal path. Phase 2 adds in-browser device-code+# flows for providers that support them. For unconnected providers we return+# the canonical ``hermes auth add <provider>`` command so the dashboard can+# surface a one-click copy.+++def _truncate_token(value: Optional[str], visible: int = 6) -> str:+ """Return ``...XXXXXX`` (last N chars) for safe display in the UI.++ We never expose more than the trailing ``visible`` characters of an+ OAuth access token. JWT prefixes (the part before the first dot) are+ stripped first when present so the visible suffix is always part of+ the signing region rather than a meaningless header chunk.++ Returns the Entra-ID placeholder when handed a callable (Azure Foundry+ bearer provider) — the callable is NEVER invoked here.+ """+ if not value:+ return ""+ if callable(value) and not isinstance(value, str):+ # Entra ID bearer provider — never reveal a minted token in the UI.+ return "<entra-id-bearer>"+ s = str(value)+ if "." in s and s.count(".") >= 2:+ # Looks like a JWT — show the trailing piece of the signature only.+ s = s.rsplit(".", 1)[-1]+ if len(s) <= visible:+ return s+ return f"…{s[-visible:]}"+++def _anthropic_oauth_status() -> Dict[str, Any]:+ """Status for the "Anthropic API Key" catalog entry.++ Two sources, in priority order:+ 1. ``~/.hermes/.anthropic_oauth.json`` — Hermes-managed terminal PKCE+ credentials (the dashboard no longer has a Connect button for this)+ 2. ``ANTHROPIC_API_KEY`` → ``ANTHROPIC_TOKEN`` → ``CLAUDE_CODE_OAUTH_TOKEN``+ env vars (registry order) — from ``.env``, the shell, or an external+ secret source like Bitwarden (whose keys are injected into the process+ env during ``load_hermes_dotenv()``, so the same check covers them)++ Claude Code's ``~/.claude/.credentials.json`` is deliberately NOT read+ here — it has its own dedicated catalog entry (``claude-code`` →+ ``_claude_code_only_status``). Reporting it under the API-key entry+ double-counts the token and shadows a real ANTHROPIC_API_KEY.+ """+ try:+ from agent.anthropic_adapter import (+ read_hermes_oauth_credentials,+ _get_hermes_oauth_file,+ )+ except ImportError:+ read_hermes_oauth_credentials = None # type: ignore+ _get_hermes_oauth_file = None # type: ignore++ hermes_creds = None+ if read_hermes_oauth_credentials:+ try:+ hermes_creds = read_hermes_oauth_credentials()+ except Exception:+ hermes_creds = None+ if hermes_creds and hermes_creds.get("accessToken"):+ return {+ "logged_in": True,+ "source": "hermes_pkce",+ "source_label": f"Hermes PKCE ({_get_hermes_oauth_file() if _get_hermes_oauth_file else None})",+ "token_preview": _truncate_token(hermes_creds.get("accessToken")),+ "expires_at": hermes_creds.get("expiresAt"),+ "has_refresh_token": bool(hermes_creds.get("refreshToken")),+ }++ # Env-var / secret-source path. ``get_env_value`` checks the process+ # environment first (where Bitwarden-sourced secrets land) then .env.+ env_var_order: tuple = ("ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN")+ try:+ from hermes_cli.auth import PROVIDER_REGISTRY+ env_var_order = PROVIDER_REGISTRY["anthropic"].api_key_env_vars+ except (ImportError, KeyError):+ pass+ try:+ from hermes_cli.config import get_env_value+ except ImportError:+ get_env_value = None # type: ignore+ try:+ from hermes_cli.env_loader import format_secret_source_suffix+ except ImportError:+ format_secret_source_suffix = None # type: ignore++ for var in env_var_order:+ value = (get_env_value(var) if get_env_value else None) or os.getenv(var)+ if not value:+ continue+ suffix = format_secret_source_suffix(var) if format_secret_source_suffix else ""+ return {+ "logged_in": True,+ "source": "env_var",+ "source_label": f"{var}{suffix}",+ "token_preview": _truncate_token(value),+ "expires_at": None,+ "has_refresh_token": False,+ }+ return {"logged_in": False, "source": None}+++def _claude_code_only_status() -> Dict[str, Any]:+ """Surface Claude Code CLI credentials as their own provider entry.++ Independent of the Anthropic entry above so users can see whether their+ Claude Code subscription tokens are actively flowing into Hermes even+ when they also have a separate Hermes-managed PKCE login.+ """+ try:+ from agent.anthropic_adapter import read_claude_code_credentials+ creds = read_claude_code_credentials()+ except Exception:+ creds = None+ if creds and creds.get("accessToken"):+ return {+ "logged_in": True,+ "source": "claude_code_cli",+ "source_label": "~/.claude/.credentials.json",+ "token_preview": _truncate_token(creds.get("accessToken")),+ "expires_at": creds.get("expiresAt"),+ "has_refresh_token": bool(creds.get("refreshToken")),+ }+ return {"logged_in": False, "source": None}+++def _copilot_acp_status() -> Dict[str, Any]:+ """Status for copilot-acp — credentials are owned by the Copilot CLI.++ ``logged_in`` is claimed only on positive evidence (a supported env token+ or a known on-disk GitHub Copilot credential store, via+ ``auth.get_external_process_provider_status``). The Copilot CLI may also+ hold its session in an OS keychain Hermes can't read, so the unverified+ state is presented as "managed by the Copilot CLI" — never as 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 the+ user actually has configured.++ The static catalog assumes the default executable name; users who point+ Hermes at a custom binary (``HERMES_COPILOT_ACP_COMMAND`` /+ ``COPILOT_CLI_PATH``) would otherwise be told to run a command that isn't+ the one Hermes spawns. Non-external-process providers get ``default`` back+ untouched.+ """+ try:+ from hermes_cli.auth import PROVIDER_REGISTRY, get_external_process_provider_status+ pconfig = PROVIDER_REGISTRY.get(provider_id)+ if not pconfig or pconfig.auth_type != "external_process":+ return default+ status = get_external_process_provider_status(provider_id) or {}+ command = str(status.get("command") or "").strip()+ if command:+ parts = default.split(" ", 1)+ tail = f" {parts[1]}" if len(parts) > 1 else ""+ return f"{command}{tail}"+ except Exception:+ pass+ return default+++# Explicit, hand-tuned OAuth/account provider cards. These carry the bits that+# can't be derived from the unified provider catalog: the OAuth ``flow`` shape,+# the per-provider ``status_fn``, the ``cli_command`` fallback, and curated+# display order. They are the OVERRIDE BASE for ``_build_oauth_catalog()``,+# which unions them with every accounts-tab provider in ``provider_catalog()``+# so newly-added OAuth/external providers appear automatically (no hand edit).+# This tuple also still includes two entries that are NOT catalog providers but+# must show on the Accounts tab: the Anthropic credential-status card and the+# synthetic ``claude-code`` subscription row.+# ``flow`` describes the account-management shape so the UI can pick the right+# behavior: ``device_code`` = show code + verification URL + poll, and+# ``external`` = read-only/delegated to a terminal or third-party CLI.+_OAUTH_PROVIDER_CATALOG: tuple[Dict[str, Any], ...] = (+ {+ "id": "nous",+ "name": "Nous Portal",+ "flow": "device_code",+ "cli_command": "hermes auth add nous",+ "docs_url": "https://portal.nousresearch.com",+ "status_fn": None, # dispatched via auth.get_nous_auth_status+ },+ {+ "id": "openai-codex",+ "name": "ChatGPT or Codex Subscription",+ "flow": "device_code",+ "cli_command": "hermes auth add openai-codex",+ "docs_url": "https://platform.openai.com/docs",+ "status_fn": None, # dispatched via auth.get_codex_auth_status+ },+ {+ "id": "qwen-oauth",+ "name": "Qwen (via Qwen CLI)",+ "flow": "external",+ "cli_command": "hermes auth add qwen-oauth",+ "docs_url": "https://github.com/QwenLM/qwen-code",+ "status_fn": None, # dispatched via auth.get_qwen_auth_status+ },+ {+ "id": "minimax-oauth",+ "name": "MiniMax (OAuth)",+ # MiniMax's flow is structurally device-code (verification URI ++ # user code, backend polls the token endpoint) with a PKCE+ # extension for code-binding. The dashboard renders the same UX+ # as Nous's device-code flow; the PKCE bit is a security+ # extension that doesn't change the operator experience.+ "flow": "device_code",+ "cli_command": "hermes auth add minimax-oauth",+ "docs_url": "https://www.minimax.io",+ "status_fn": None, # dispatched via auth.get_minimax_oauth_auth_status+ },+ {+ "id": "xai-oauth",+ "name": "xAI Grok OAuth (SuperGrok / Premium+)",+ # Device code is the default because it works in remote shells,+ # containers, and desktop installs without requiring a reachable+ # 127.0.0.1 callback.+ "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, # dispatched via auth.get_xai_oauth_auth_status+ },+ {+ "id": "copilot-acp",+ "name": "GitHub Copilot (ACP)",+ "flow": "external",+ # `copilot login` is the CLI's non-interactive device-code login+ # subcommand; the previous `copilot /login` form is not a valid+ # invocation (slash-commands only exist inside an interactive+ # session, reachable as `copilot -i /login`).+ "cli_command": "copilot login",+ "docs_url": "https://docs.github.com/en/copilot",+ "status_fn": _copilot_acp_status,+ },+ # ── Anthropic / Claude entries sit at the bottom.+ #+ # This card is deliberately flow == "external" (no in-dashboard "Connect"+ # button walking the user through claude.ai/oauth/authorize from the web+ # server). Hermes previously reimplemented that subscription-OAuth PKCE+ # dance itself for the dashboard (issues #87887/#87888); that surface was+ # removed because it lets an unattended, scriptable HTTP endpoint mint+ # Claude Pro/Max subscription tokens outside Anthropic's own client,+ # which sits on the wrong side of Anthropic's usage policies for OAuth+ # credentials. Login still works via the terminal (`hermes auth add+ # anthropic`, unaffected by this change) or a plain API key below.+ {+ "id": "anthropic",+ "name": "Anthropic API Key",+ "flow": "external",+ "cli_command": "hermes auth add anthropic",+ "docs_url": "https://docs.claude.com/en/api/getting-started",+ "status_fn": _anthropic_oauth_status,+ },+ {+ "id": "claude-code",+ "name": "Anthropic OAuth: Required Extra Usage Credits to Use Subscription",+ "flow": "external",+ "cli_command": "claude setup-token",+ "docs_url": "https://docs.claude.com/en/docs/claude-code",+ "status_fn": _claude_code_only_status,+ },+)+_oauth_sessions: Dict[str, Dict[str, Any]] = {}+_oauth_sessions_lock = threading.Lock()+++def _oauth_profile_name(profile: Optional[str]) -> Optional[str]:+ requested = (profile or "").strip()+ if not requested or requested.lower() == "current":+ return None+ return requested+++def _oauth_session_profile(+ session_id: str,+ fallback: Optional[str] = None,+) -> Optional[str]:+ """Return the profile that owns an OAuth session, if one was provided."""+ with _oauth_sessions_lock:+ sess = _oauth_sessions.get(session_id)+ profile = sess.get("profile") if sess else None+ return profile or _oauth_profile_name(fallback)+++def _oauth_poller(label: str):+ """Wrap a background device-code poller body ``fn(session_id, sess)``.++ Looks up the session (a vanished session is a no-op), marks it+ ``approved`` when the body returns, and on any exception records+ ``error`` + ``error_message`` on the session instead of raising — the+ thread has no caller to report to; the dashboard reads the status.+ """+ def deco(fn):+ @functools.wraps(fn)+ def poller(session_id: str) -> None:+ with _oauth_sessions_lock:+ sess = _oauth_sessions.get(session_id)+ if not sess:+ return+ try:+ fn(session_id, sess)+ with _oauth_sessions_lock:+ sess["status"] = "approved"+ _log.info("oauth/device: %s login completed (session=%s)", label, session_id)+ except Exception as e:+ _log.warning("%s device-code poll failed (session=%s): %s", label, session_id, e)+ with _oauth_sessions_lock:+ sess["status"] = "error"+ sess["error_message"] = str(e)+ return poller+ return deco+++@_oauth_poller("nous")+def _nous_poller(session_id: str, sess: Dict[str, Any]) -> None:+ """Background poller that drives a Nous device-code flow to completion."""+ from hermes_cli.web_server import _profile_scope+ from hermes_cli.auth import (+ _poll_for_token,+ refresh_nous_oauth_from_state,+ )+ from datetime import datetime, timezone+ import httpx+ portal_base_url = sess["portal_base_url"]+ client_id = sess["client_id"]+ device_code = sess["device_code"]+ interval = sess["interval"]+ scope = sess.get("scope")+ expires_in = max(60, int(sess["expires_at"] - time.time()))+ with httpx.Client(timeout=httpx.Timeout(15.0), headers={"Accept": "application/json"}) as client:+ token_data = _poll_for_token(+ client=client,+ portal_base_url=portal_base_url,+ client_id=client_id,+ device_code=device_code,+ expires_in=expires_in,+ poll_interval=interval,+ )+ # Same post-processing as _nous_device_code_login (validate/refresh JWT)+ now = datetime.now(timezone.utc)+ token_ttl = int(token_data.get("expires_in") or 0)+ auth_state = {+ "portal_base_url": portal_base_url,+ "inference_base_url": token_data.get("inference_base_url"),+ "client_id": client_id,+ "scope": token_data.get("scope") or scope,+ "token_type": token_data.get("token_type", "Bearer"),+ "access_token": token_data["access_token"],+ "refresh_token": token_data.get("refresh_token"),+ "obtained_at": now.isoformat(),+ "expires_at": (+ datetime.fromtimestamp(now.timestamp() + token_ttl, tz=timezone.utc).isoformat()+ if token_ttl else None+ ),+ "expires_in": token_ttl,+ }+ with _profile_scope(_oauth_session_profile(session_id)):+ full_state = refresh_nous_oauth_from_state(+ auth_state,+ timeout_seconds=15.0,+ force_refresh=False,+ )+ from hermes_cli.auth import persist_nous_credentials+ persist_nous_credentials(full_state)+++@_oauth_poller("minimax")+def _minimax_poller(session_id: str, sess: Dict[str, Any]) -> None:+ """Background poller that drives a MiniMax OAuth flow to completion.++ Mirrors `_nous_poller` but calls the MiniMax-specific token endpoint,+ which uses a PKCE-style ``code_verifier`` + ``user_code`` rather than+ the ``device_code`` field used by Nous. On success, builds the same+ auth_state dict that ``_minimax_oauth_login`` (the CLI flow) builds+ and persists via ``_minimax_save_auth_state`` — so the dashboard+ path leaves the system in the same state as+ ``hermes auth add minimax-oauth``.+ """+ from hermes_cli.web_server import _profile_scope+ from hermes_cli.auth import (+ _minimax_poll_token,+ _minimax_resolve_token_expiry_unix,+ _minimax_save_auth_state,+ MINIMAX_OAUTH_GLOBAL_INFERENCE,+ MINIMAX_OAUTH_SCOPE,+ )+ from datetime import datetime, timezone+ import httpx+ portal_base_url = sess["portal_base_url"]+ client_id = sess["client_id"]+ user_code = sess["user_code"]+ code_verifier = sess["code_verifier"]+ interval_ms = sess.get("interval_ms")+ expired_in_raw = sess["expired_in_raw"]+ with httpx.Client(+ timeout=httpx.Timeout(15.0),+ headers={"Accept": "application/json"},+ follow_redirects=True,+ ) as client:+ token_data = _minimax_poll_token(+ client=client,+ portal_base_url=portal_base_url,+ client_id=client_id,+ user_code=user_code,+ code_verifier=code_verifier,+ expired_in=expired_in_raw,+ interval_ms=interval_ms,+ )+ # Build the auth_state dict in the same shape as the CLI flow's+ # `_minimax_oauth_login` so `_minimax_save_auth_state` writes+ # the canonical record. Region is fixed to "global" for the+ # dashboard path; cn-region operators can still use the CLI+ # flow which supports `--region cn`.+ now = datetime.now(timezone.utc)+ expires_at_ts = _minimax_resolve_token_expiry_unix(+ int(token_data["expired_in"]), now=now,+ )+ expires_in_s = max(0, int(expires_at_ts - now.timestamp()))+ auth_state = {+ "provider": "minimax-oauth",+ "region": sess.get("region", "global"),+ "portal_base_url": portal_base_url,+ "inference_base_url": MINIMAX_OAUTH_GLOBAL_INFERENCE,+ "client_id": client_id,+ "scope": MINIMAX_OAUTH_SCOPE,+ "token_type": token_data.get("token_type", "Bearer"),+ "access_token": token_data["access_token"],+ "refresh_token": token_data["refresh_token"],+ "resource_url": token_data.get("resource_url"),+ "obtained_at": now.isoformat(),+ "expires_at": datetime.fromtimestamp(+ expires_at_ts, tz=timezone.utc+ ).isoformat(),+ "expires_in": expires_in_s,+ }+ with _profile_scope(_oauth_session_profile(session_id)):+ _minimax_save_auth_state(auth_state)+++@_oauth_poller("xai")+def _xai_device_poller(session_id: str, sess: Dict[str, Any]) -> None:+ """Background poller for xAI's OAuth device-code flow."""+ from hermes_cli.web_server import _profile_scope+ import httpx+ from hermes_cli.auth import (+ _save_xai_oauth_tokens,+ _xai_oauth_discovery,+ _xai_oauth_poll_device_token,+ mark_provider_active_if_unset,+ unsuppress_credential_source,+ )++ device_code = sess["device_code"]+ interval = int(sess["interval"])+ expires_in = max(60, int(sess["expires_at"] - time.time()))+ discovery = _xai_oauth_discovery(20.0)+ with httpx.Client(+ timeout=httpx.Timeout(20.0),+ headers={"Accept": "application/json"},+ ) as client:+ token_data = _xai_oauth_poll_device_token(+ client,+ token_endpoint=discovery["token_endpoint"],+ device_code=device_code,+ expires_in=expires_in,+ poll_interval=interval,+ )+ tokens = {+ "access_token": str(token_data.get("access_token", "") or "").strip(),+ "refresh_token": str(token_data.get("refresh_token", "") or "").strip(),+ "id_token": str(token_data.get("id_token", "") or "").strip(),+ "expires_in": token_data.get("expires_in"),+ "token_type": str(token_data.get("token_type") or "Bearer").strip() or "Bearer",+ }+ with _profile_scope(_oauth_session_profile(session_id)):+ _save_xai_oauth_tokens(+ tokens,+ discovery=discovery,+ last_refresh=datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),+ auth_mode="oauth_device_code",+ # Persist credentials without hijacking an existing active+ # chat provider.+ set_active=False,+ )+ # Mirror `hermes auth add xai-oauth`: first credential may become+ # active when none is set yet; never overwrite an existing choice.+ mark_provider_active_if_unset("xai-oauth")+ # The singleton write above is the single source of truth: the+ # credential-pool load seeds it as the canonical ``device_code``+ # entry. Do NOT also insert a parallel ``manual:dashboard_*`` pool+ # entry — that duplicates the single-use refresh token across two+ # entries and triggers rotation churn / ``refresh_token_reused``.+ # An interactive dashboard login is also an explicit re-enable+ # signal, so clear any ``device_code`` suppression left by a+ # prior ``hermes auth remove xai-oauth`` (mirrors auth_add_command+ # and the ``hermes model`` re-login path in _login_xai_oauth).+ unsuppress_credential_source("xai-oauth", "device_code")diff --git a/tests/test_web_server_sessiondb_eventloop.py b/tests/test_web_server_sessiondb_eventloop.pyindex 818d540225f..e5db9c5f37d 100644--- a/tests/test_web_server_sessiondb_eventloop.py+++ b/tests/test_web_server_sessiondb_eventloop.py@@ -4,6 +4,7 @@ import threadingfrom pathlib import Pathfrom hermes_cli import web_server+from hermes_cli import web_server_sessionsfrom hermes_cli.web_routers import analytics as web_analyticsfrom hermes_cli.web_routers import sessions as web_sessions@@ -32,11 +33,12 @@ def _call_name(call: ast.Call) -> str | None:def test_sessiondb_handlers_open_connections_inside_executor_helpers():# The session and analytics route handlers were extracted to- # web_routers/{sessions,analytics}.py; the executor helpers still live in- # web_server.py — scan all three modules' top-level bodies.+ # web_routers/{sessions,analytics}.py; the executor helpers live in+ # web_server_sessions.py (and any left in web_server.py) — scan all+ # four modules' top-level bodies.handlers: dict[str, ast.AsyncFunctionDef] = {}top_level_helpers: dict[str, ast.FunctionDef] = {}- for mod in (web_server, web_sessions, web_analytics):+ for mod in (web_server, web_server_sessions, web_sessions, web_analytics):tree = ast.parse(Path(mod.__file__).read_text(encoding="utf-8"))for node in tree.body:if isinstance(node, ast.AsyncFunctionDef) and node.name in TARGET_HANDLERS:@@ -76,7 +78,7 @@ def test_sessiondb_handlers_open_connections_inside_executor_helpers():def test_sessiondb_opens_declare_access_mode():- for mod in (web_server, web_sessions):+ for mod in (web_server_sessions, web_sessions):tree = ast.parse(Path(mod.__file__).read_text(encoding="utf-8"))calls = [node