From 77df8016a0d692bb4fa24a23812ac9819fb0046e Mon Sep 17 00:00:00 2001 From: "Prompt. Click. Run." <59135406+promptclickrun@users.noreply.github.com> Date: Wed, 30 Sep 2026 16:04:05 -0500 Subject: [PATCH 1/2] Sign in to terminal-only provider accounts from the bighelp app Some accounts only sign in from a terminal on the host: GitHub's Copilot CLI, Claude Code, and the GitHub login `hermes model` runs for Copilot. The new native-provider-sign-in-v1 routes run the provider's own tool in a private terminal and pass the phone only its sign-in link, the one-time code, and whether it worked; a code the provider's page shows goes back into the tool. - Recipes (one table in provider_sign_in.py) for copilot-acp, copilot, claude-code, claude-subscription-directsdk-experimental and anthropic. Qwen OAuth is listed as retired (Qwen ended it in April 2026), pointing to the Qwen Cloud key. - The provider's own client always does the sign-in; Hermes' own Claude login stays in the terminal. Commands are fixed per provider, no shell. - Links only on the provider's own https domains. Terminal output never leaves memory or reaches logs. `claude setup-token`'s token is saved to the profile's env with Hermes' credential helper and dropped. - A browser the tool tries to open on the host does nothing. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/runtime-compatibility.yml | 1 + README.md | 1 + docs/PROVIDER_SIGN_IN.md | 111 ++++ loopdy_plugin/native_api.py | 59 ++ loopdy_plugin/native_context.py | 5 + loopdy_plugin/provider_sign_in.py | 621 ++++++++++++++++++++ loopdy_plugin/provider_sign_in_helper.py | 35 ++ tests/test_native_api.py | 3 + tests/test_native_startup_logging.py | 7 +- tests/test_provider_sign_in.py | 404 +++++++++++++ 10 files changed, 1245 insertions(+), 2 deletions(-) create mode 100644 docs/PROVIDER_SIGN_IN.md create mode 100644 loopdy_plugin/provider_sign_in.py create mode 100644 loopdy_plugin/provider_sign_in_helper.py create mode 100644 tests/test_provider_sign_in.py diff --git a/.github/workflows/runtime-compatibility.yml b/.github/workflows/runtime-compatibility.yml index e705849..05fc476 100644 --- a/.github/workflows/runtime-compatibility.yml +++ b/.github/workflows/runtime-compatibility.yml @@ -51,5 +51,6 @@ jobs: python -m unittest discover -s tests -p test_direct_adapter_integration.py -v python -m unittest discover -s tests -p test_native_voice.py -v python -m unittest discover -s tests -p test_native_api.py -v + python -m unittest discover -s tests -p test_provider_sign_in.py -v python -m unittest discover -s tests -p test_adapter.py -v python -m unittest discover -s tests -p test_registration.py -v diff --git a/README.md b/README.md index ad9f706..4f8d5e8 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ systemd and Hermes Desktop keep supervising it; chats running on that process st | Group chat activity | See which tools each agent in a group chat is using, live. Needs a Hermes host with the `on_room_member_activity` hook. | [Room activity](docs/NATIVE_ROOM_ACTIVITY.md) | | Context usage | How much of the model's context the last request used. | [Context usage](docs/CONTEXT_USAGE.md) | | Provider usage | How much of each AI plan or balance you've used: Claude, Codex, GitHub Copilot, OpenCode, OpenRouter, DeepSeek, Nous Portal and more. Found automatically from the tools installed on the computer and the providers set up in Hermes. Read-only. | [Provider usage](docs/PROVIDER_USAGE.md) | +| Provider sign-in | Sign in to accounts that otherwise need a terminal on the computer (GitHub Copilot, Claude Code, Claude subscriptions) from the phone. The provider's own sign-in tool runs on the computer; the phone gets only its link and code. | [Provider sign-in](docs/PROVIDER_SIGN_IN.md) | | Generated media and files | Agent-made images, videos and files show up in chat. Hermes' own media rules decide what can be shared, and host paths are never exposed. | [Agent attachments](docs/AGENT_ATTACHMENTS.md) | | Model names | `model-names.json` gives friendly model names. The app can refresh it without a plugin update. | | diff --git a/docs/PROVIDER_SIGN_IN.md b/docs/PROVIDER_SIGN_IN.md new file mode 100644 index 0000000..c538d5e --- /dev/null +++ b/docs/PROVIDER_SIGN_IN.md @@ -0,0 +1,111 @@ +# Provider sign-in + +Some AI accounts only sign in from a terminal on the Hermes computer. With this feature, bighelp's Provider Keys +screen signs in to them from the phone: the plugin runs the provider's own sign-in tool on the computer, and the +phone shows its link and code. Accounts Hermes already signs in to itself (Nous Portal, ChatGPT/Codex, MiniMax, +xAI Grok) keep using Hermes' own sign-in. + +## What it signs in to + +| Account in Hermes | Tool that signs in | How it goes on the phone | +| --- | --- | --- | +| GitHub Copilot (ACP) (`copilot-acp`) | GitHub Copilot CLI: `copilot login --device-code` | Code and link; GitHub confirms on its own | +| GitHub Copilot (`copilot`) | Hermes' own GitHub login, the same one `hermes model` runs. The token goes to the profile's env as `COPILOT_GITHUB_TOKEN` | Code and link; GitHub confirms on its own | +| Claude Code (`claude-code`) | Claude Code: `claude auth login --claudeai` | Link; paste the code Claude shows back into bighelp | +| Claude Subscription DirectSDK (`claude-subscription-directsdk-experimental`) | Claude Code, with the plugin's `CLAUDE_SUBSCRIPTION_DIRECTSDK_COMMAND` and `CLAUDE_SUBSCRIPTION_DIRECTSDK_CONFIG_DIR` | Link; paste the code back | +| Anthropic Account (`anthropic`) | Claude Code: `claude setup-token`. Its long-lived token goes to the profile's env as `CLAUDE_CODE_OAUTH_TOKEN`, the route Hermes documents for Claude subscriptions | Link; paste the code back | +| Qwen OAuth (`qwen-oauth`) | None. Qwen stopped offering this sign-in in April 2026 | Listed as retired, with Qwen Cloud's API key as the replacement | + +If the tool isn't installed, the app says so and shows the install command. Nothing is installed for you. + +## Respecting provider terms + +- The provider's own client does every sign-in. bighelp never contacts a sign-in service, never builds its own + OAuth request, and never reads or copies another tool's saved login. +- Hermes keeps its own Claude sign-in (`hermes auth add anthropic`) in the terminal on purpose, so bighelp never + runs it. Claude accounts sign in through Claude Code, Anthropic's own client. +- A sign-in a provider ends is marked retired instead of started. + +## Safety and privacy + +- Commands are fixed per provider in `loopdy_plugin/provider_sign_in.py`. The phone only names a provider; it can't + pass arguments, and nothing runs through a shell. +- The tool runs in a private terminal on the computer. Its attempts to open a browser there do nothing. +- Only three things reach the phone: an `https` link on the provider's own domains, the one-time code to enter + there, and whether it worked. Terminal output stays in memory for that one sign-in and is never logged. +- A token a tool prints for you to keep is saved straight to the profile's env with Hermes' credential helper, + then dropped. It never reaches the phone or the logs. +- A pasted code must be one line of visible text, up to 2,048 characters. +- A sign-in stops after 15 minutes. At most four run at once, and starting one again replaces the unfinished one. +- Linux and macOS only (it needs a POSIX terminal). + +## Adding a provider + +Add a `Recipe` to `RECIPES` in `loopdy_plugin/provider_sign_in.py`: + +- `provider_id`: the account's id in Hermes' `/api/providers/oauth` list. The app matches on it. +- `command`: the provider's own CLI and fixed arguments, usually `_cli("tool", override=(...settings))`. +- `flow`: `DEVICE` when the provider's page confirms by itself, `PASTE` when it shows a code to paste back. +- `link_hosts`: the provider's own domains. Links anywhere else are never shown. +- `code`: for device flows, the pattern of the code the tool prints. +- `rejected`: what the tool prints when a pasted code doesn't work, if it doesn't exit. +- `signed_in`: an optional local check (no network) that the account is signed in. +- `retired`: a message, when the provider has ended the sign-in. + +Only add a provider when its own client does the sign-in, and add tests with a fake of its CLI that prints what +the real one prints. The app needs no update for a new provider. + +## For the app + +`native-provider-sign-in-v1` in `/native/context` features. + +`POST /api/plugins/loopdy/native/provider-sign-in/` with the usual native headers (`If-Match` context +ETag and `X-Loopdy-Request-ID`). Every body has `agentId`, the profile. + +| Operation | Body | Answer | +| --- | --- | --- | +| `list` | `{"agentId"}` | `{"agentId", "providers": [provider]}` | +| `start` | `{"agentId", "providerId"}` | a session, after waiting up to 12 seconds for the link | +| `status` | `{"agentId", "sessionId"}` | a session | +| `submit` | `{"agentId", "sessionId", "code"}` | a session (`finishing`) | +| `cancel` | `{"agentId", "sessionId"}` | a session (`cancelled`) | + +A provider: + +```json +{ + "providerId": "claude-code", + "name": "Claude Code", + "client": "Claude Code", + "flow": "paste", + "state": "ready", + "signedIn": false, + "docsURL": "https://docs.claude.com/en/docs/claude-code/setup" +} +``` + +`state` is `ready`, `notInstalled` (with `message` and `installCommand`) or `retired` (with `message` and, when +there is one, `replacementKey`, the Hermes env name of the key to use instead). `signedIn` is present only when the +tool can say. + +A session: + +```json +{ + "sessionId": "5f0c3c52-3a8e-4b8f-9d37-0d3c0e6f1a2b", + "providerId": "copilot-acp", + "flow": "device", + "status": "waiting", + "link": "https://github.com/login/device", + "code": "WDJB-MJHT", + "expiresInSeconds": 890 +} +``` + +`status` is `starting`, `waiting` (device: open the link, enter the code), `needsCode` (paste: open the link, then +send the page's code), `finishing`, `signedIn`, `failed`, `expired` or `cancelled`. `link` and `code` are dropped +once it ends. `message` says what went wrong in plain words. + +Errors use the usual native error body. Codes: `sign_in_unavailable` (404, no sign-in for that provider), +`sign_in_not_found` (404), `sign_in_tool_missing` (409), `sign_in_not_waiting` (409), `sign_in_retired` (410), +`sign_in_code_invalid` (422), `sign_in_busy` (429), `sign_in_start_failed` (503) and `sign_in_host_unavailable` (503). diff --git a/loopdy_plugin/native_api.py b/loopdy_plugin/native_api.py index aab188e..279daae 100644 --- a/loopdy_plugin/native_api.py +++ b/loopdy_plugin/native_api.py @@ -517,3 +517,62 @@ async def provider_usage(request: Request) -> Response: if native_context(request) != owner: raise NativeAPIError(412, "context_changed", "The native context changed; refresh before retrying.") return _response({"agentId": body.agentId, **value}, owner, request_id) + + +_SESSION_ID = r"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" + + +class _SignInStart(_Body): + providerId: str = Field(pattern=r"^[a-z0-9][a-z0-9._-]{0,63}$") + + +class _SignInSession(_Body): + sessionId: str = Field(pattern=_SESSION_ID) + + +class _SignInCode(_SignInSession): + code: str = Field(min_length=1, max_length=2048) + + +_SIGN_IN_BODIES: dict[str, type[_Body]] = { + "list": _Body, "start": _SignInStart, "status": _SignInSession, "submit": _SignInCode, "cancel": _SignInSession, +} +_SIGN_IN_STATUS = { + "sign_in_unavailable": 404, "sign_in_not_found": 404, "sign_in_tool_missing": 409, "sign_in_not_waiting": 409, + "sign_in_retired": 410, "sign_in_code_invalid": 422, "sign_in_busy": 429, "sign_in_start_failed": 503, +} + + +def _sign_in(operation: str, body: _Body) -> dict: + from hermes_cli.profiles import profile_exists + from . import provider_sign_in as sign_in + if not profile_exists(body.agentId): + raise NativeAPIError(404, "profile_not_found", "The selected profile no longer exists.") + try: + if operation == "list": + return {"providers": sign_in.providers()} + if operation == "start": + return sign_in.start(body.agentId, body.providerId) + if operation == "status": + return sign_in.status(body.agentId, body.sessionId) + if operation == "submit": + return sign_in.submit(body.agentId, body.sessionId, body.code) + return sign_in.cancel(body.agentId, body.sessionId) + except sign_in.SignInError as error: + raise NativeAPIError(_SIGN_IN_STATUS.get(error.code, 409), error.code, error.message) from None + + +@router.post("/provider-sign-in/{operation}") +async def provider_sign_in(operation: str, request: Request) -> Response: + """Sign in to a provider account with that provider's own sign-in tool (bighelp app: Provider Keys).""" + from .provider_sign_in import CAPABILITY + model = _SIGN_IN_BODIES.get(operation) + if model is None: + raise NativeAPIError(404, "unknown_operation", "The sign-in operation is unknown.") + owner = native_context(request) + request_id = _precondition(request, owner) + if CAPABILITY not in owner.features: + raise NativeAPIError(503, "sign_in_host_unavailable", "This host can't run sign-ins for the app.") + body = await _body(request, model) + value = await run_in_threadpool(_sign_in, operation, body) + return _response({"agentId": body.agentId, **value}, owner, request_id) diff --git a/loopdy_plugin/native_context.py b/loopdy_plugin/native_context.py index 2c531bc..4c8a2d7 100644 --- a/loopdy_plugin/native_context.py +++ b/loopdy_plugin/native_context.py @@ -274,4 +274,9 @@ def skip(feature: str, reason: str) -> None: features.append(usage_capability) else: skip(usage_capability, "public profile helpers are unimportable.") + from .provider_sign_in import CAPABILITY as sign_in_capability, available as sign_in_available + if sign_in_available(): + features.append(sign_in_capability) + else: + skip(sign_in_capability, "sign-ins need a POSIX terminal and public profile helpers.") return profile, tuple(features) diff --git a/loopdy_plugin/provider_sign_in.py b/loopdy_plugin/provider_sign_in.py new file mode 100644 index 0000000..739d9b2 --- /dev/null +++ b/loopdy_plugin/provider_sign_in.py @@ -0,0 +1,621 @@ +"""Sign in to AI provider accounts from the bighelp app, with each provider's own sign-in tool. + +Some accounts only sign in from a terminal on this computer: GitHub's Copilot CLI, Anthropic's +Claude Code, and the GitHub login `hermes model` runs for Copilot. From the app's Provider Keys +screen, this module runs that same command in a private terminal here and passes back only what a +person needs: the provider's sign-in link, the one-time code to enter there, and whether it worked. +When the tool asks for a code from the provider's page, the app sends it back and it's typed in. + +Provider terms: the provider's own client does every sign-in (Claude Code for Claude accounts, +GitHub's Copilot CLI or Hermes' own `hermes model` login for Copilot). bighelp never contacts a +sign-in service, never builds an OAuth request and never reads another tool's credential store. A +sign-in its provider has ended is listed as retired instead of started. + +Adding a provider: add a ``Recipe`` to ``RECIPES`` with the provider's Hermes id, its own CLI and +arguments, the domains its links may use, and whether its page approves by itself (``DEVICE``) or +shows a code to paste back (``PASTE``). Commands are fixed here; the phone only names a provider. + +Privacy: terminal output stays in memory for one sign-in and is never logged or returned. A token a +tool prints for the person to keep (``claude setup-token``) is saved straight to this profile's +Hermes env, as the person would, and dropped. +""" +from __future__ import annotations + +from dataclasses import dataclass +import json +import logging +import os +from pathlib import Path +import re +import select +import signal +import struct +import subprocess +import sys +import tempfile +import threading +import time +from typing import Callable +from urllib.parse import urlsplit +import uuid + +from .provider_usage import find_cli, _search_path + +CAPABILITY = "native-provider-sign-in-v1" +DEVICE, PASTE = "device", "paste" +STARTING, WAITING, NEEDS_CODE, FINISHING = "starting", "waiting", "needsCode", "finishing" +SIGNED_IN, FAILED, EXPIRED, CANCELLED = "signedIn", "failed", "expired", "cancelled" +_ENDED = frozenset({SIGNED_IN, FAILED, EXPIRED, CANCELLED}) + +SESSION_SECONDS = 15 * 60 +START_WAIT_SECONDS = 12.0 +_KEEP_ENDED_SECONDS = 5 * 60 +_MAX_OUTPUT = 256 * 1024 +_MAX_SESSIONS = 4 +_MAX_CODE = 2048 +_STATUS_CACHE_SECONDS = 60.0 +_HELPER = Path(__file__).with_name("provider_sign_in_helper.py") + +logger = logging.getLogger("hermes.plugins.bighelp") + + +class SignInError(Exception): + """An expected refusal; ``code`` is a fixed string the route maps to a status.""" + + def __init__(self, code: str, message: str): + super().__init__(code) + self.code = code + self.message = message + + +@dataclass(frozen=True) +class Recipe: + provider_id: str + name: str + client: str + flow: str + link_hosts: tuple[str, ...] + command: Callable[[], list[str] | None] + install: str = "" + docs: str = "" + code: re.Pattern[str] | None = None + rejected: re.Pattern[str] | None = None + env: Callable[[str], dict[str, str]] | None = None + drop_env: tuple[str, ...] = () + keep_token: tuple[re.Pattern[str], str] | None = None + signed_in: Callable[[], bool | None] | None = None + retired: str = "" + replacement_key: str = "" + + +def available() -> bool: + """A private terminal needs POSIX; profile helpers scope saved tokens to the chosen profile.""" + if os.name != "posix": + return False + try: + import pty + from hermes_cli.profiles import get_profile_dir, profile_exists + except ImportError: + return False + return all(map(callable, (pty.openpty, get_profile_dir, profile_exists))) + + +# ---- Commands --------------------------------------------------------------------------------- + +def _cli(name: str, *arguments: str, override: tuple[str, ...] = ()) -> Callable[[], list[str] | None]: + """The provider's CLI from an override setting (absolute path or bare name), else PATH.""" + def command() -> list[str] | None: + for variable in override: + value = os.environ.get(variable, "").strip() + if not value: + continue + if os.path.isabs(value): + if os.path.isfile(value) and os.access(value, os.X_OK): + return [value, *arguments] + continue + if re.fullmatch(r"[A-Za-z0-9._-]{1,64}", value) and (found := find_cli(value)): + return [found, *arguments] + found = find_cli(name) + return [found, *arguments] if found else None + return command + + +def _hermes_helper(flow: str, module: str) -> Callable[[], list[str] | None]: + """A Hermes login run by ``provider_sign_in_helper.py`` with this Python, when Hermes has it.""" + def command() -> list[str] | None: + try: + __import__(module) + except ImportError: + return None + return [sys.executable, str(_HELPER), flow] + return command + + +def _profile_home(agent_id: str) -> dict[str, str]: + from hermes_cli.profiles import get_profile_dir + # The helper imports Hermes from this process's path and saves into the chosen profile. + return {"HERMES_HOME": str(get_profile_dir(agent_id)), + "PYTHONPATH": os.pathsep.join(path for path in sys.path if path), + "HERMES_DISABLE_LAZY_INSTALLS": "1"} + + +def _claude_env(config_variable: str = "") -> Callable[[str], dict[str, str]]: + def env(_: str) -> dict[str, str]: + extra = {"DISABLE_TELEMETRY": "1", "DISABLE_ERROR_REPORTING": "1"} + if config_variable and (config := os.environ.get(config_variable, "").strip()): + extra["CLAUDE_CONFIG_DIR"] = config + return extra + return env + + +_status_cache: dict[tuple[str, ...], tuple[float, bool | None]] = {} +_status_lock = threading.Lock() + + +def _claude_signed_in(command: Callable[[], list[str] | None], config_variable: str = "") -> Callable[[], bool | None]: + """Claude Code's own ``auth status`` (local, no network); None when it can't say.""" + def signed_in() -> bool | None: + argv = command() + if argv is None: + return None + env = {**os.environ, "PATH": _search_path(), **_claude_env(config_variable)("")} + key = (*argv, env.get("CLAUDE_CONFIG_DIR", "")) + now = time.monotonic() + with _status_lock: + cached = _status_cache.get(key) + if cached and now - cached[0] < _STATUS_CACHE_SECONDS: + return cached[1] + try: + result = subprocess.run([*argv, "auth", "status", "--json"], capture_output=True, text=True, + encoding="utf-8", errors="replace", timeout=8, env=env, + stdin=subprocess.DEVNULL, cwd=str(Path.home()), check=False) + value = json.loads(result.stdout) if result.stdout.strip().startswith("{") else {} + state = value.get("loggedIn") if isinstance(value.get("loggedIn"), bool) else None + except (OSError, ValueError, subprocess.SubprocessError): + state = None + with _status_lock: + _status_cache[key] = (now, state) + return state + return signed_in + + +_GITHUB_CODE = re.compile(r"\b([A-Z0-9]{4}-[A-Z0-9]{4})\b") +_CLAUDE_HOSTS = ("claude.com", "claude.ai", "anthropic.com") +_CLAUDE_INSTALL = "npm install -g @anthropic-ai/claude-code" +_CLAUDE_DOCS = "https://docs.claude.com/en/docs/claude-code/setup" +# `claude setup-token` prints a long-lived token for the person to keep; this is its shape. +_SETUP_TOKEN = re.compile(r"(sk-ant-oat01-[A-Za-z0-9_-]{16,512})(?=[^A-Za-z0-9_-])") +# What Claude Code prints when the pasted code doesn't work; `setup-token` then waits for Enter. +_CLAUDE_REJECTED = re.compile(r"OAuth error|Press Enter to retry|Invalid code", re.IGNORECASE) +_claude = _cli("claude") +_directsdk = _cli("claude", override=("CLAUDE_SUBSCRIPTION_DIRECTSDK_COMMAND",)) +_copilot = _cli("copilot", override=("HERMES_COPILOT_ACP_COMMAND", "COPILOT_CLI_PATH")) + +RECIPES: tuple[Recipe, ...] = ( + Recipe( + provider_id="copilot-acp", name="GitHub Copilot (ACP)", client="GitHub Copilot CLI", flow=DEVICE, + link_hosts=("github.com",), command=lambda: (argv + ["login", "--device-code"]) if (argv := _copilot()) else None, + install="npm install -g @github/copilot", + docs="https://docs.github.com/en/copilot/how-tos/set-up/install-copilot-cli", code=_GITHUB_CODE, + # A token in the environment would stand in for the account the person signs in to. + drop_env=("COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN")), + Recipe( + provider_id="copilot", name="GitHub Copilot", client="Hermes", flow=DEVICE, link_hosts=("github.com",), + command=_hermes_helper("copilot", "hermes_cli.copilot_auth"), + docs="https://docs.github.com/en/copilot", code=_GITHUB_CODE, env=_profile_home), + Recipe( + provider_id="claude-code", name="Claude Code", client="Claude Code", flow=PASTE, link_hosts=_CLAUDE_HOSTS, + command=lambda: (argv + ["auth", "login", "--claudeai"]) if (argv := _claude()) else None, + install=_CLAUDE_INSTALL, docs=_CLAUDE_DOCS, rejected=_CLAUDE_REJECTED, env=_claude_env(), + signed_in=_claude_signed_in(_claude)), + Recipe( + provider_id="claude-subscription-directsdk-experimental", name="Claude Subscription DirectSDK", + client="Claude Code", flow=PASTE, link_hosts=_CLAUDE_HOSTS, + command=lambda: (argv + ["auth", "login", "--claudeai"]) if (argv := _directsdk()) else None, + install=_CLAUDE_INSTALL, docs=_CLAUDE_DOCS, rejected=_CLAUDE_REJECTED, + env=_claude_env("CLAUDE_SUBSCRIPTION_DIRECTSDK_CONFIG_DIR"), + signed_in=_claude_signed_in(_directsdk, "CLAUDE_SUBSCRIPTION_DIRECTSDK_CONFIG_DIR")), + # Hermes keeps its own Claude login in the terminal on purpose; Claude Code's long-lived token + # is the route Hermes documents for Claude subscriptions, and Claude Code mints it. + Recipe( + provider_id="anthropic", name="Anthropic Account", client="Claude Code", flow=PASTE, + link_hosts=_CLAUDE_HOSTS, command=lambda: (argv + ["setup-token"]) if (argv := _claude()) else None, + install=_CLAUDE_INSTALL, docs=_CLAUDE_DOCS, rejected=_CLAUDE_REJECTED, env=_claude_env(), + keep_token=(_SETUP_TOKEN, "CLAUDE_CODE_OAUTH_TOKEN")), + Recipe( + provider_id="qwen-oauth", name="Qwen OAuth", client="Qwen Code", flow=DEVICE, link_hosts=("qwen.ai",), + command=lambda: None, docs="https://github.com/QwenLM/qwen-code", + retired="Qwen stopped offering Qwen OAuth sign-in in April 2026. Use a Qwen Cloud API key instead.", + replacement_key="DASHSCOPE_API_KEY"), +) +_BY_ID = {recipe.provider_id: recipe for recipe in RECIPES} + + +def recipe(provider_id: str) -> Recipe | None: + return _BY_ID.get(provider_id) + + +def providers() -> list[dict]: + """Every sign-in this host can run, or why it can't, for the app's Provider Keys screen.""" + rows = [] + for item in RECIPES: + row: dict = {"providerId": item.provider_id, "name": item.name, "client": item.client, "flow": item.flow} + if item.docs: + row["docsURL"] = item.docs + if item.retired: + row.update(state="retired", message=item.retired) + if item.replacement_key: + row["replacementKey"] = item.replacement_key + elif item.command() is None: + row.update(state="notInstalled", message=f"{item.client} isn't installed on this computer.") + if item.install: + row["installCommand"] = item.install + else: + row["state"] = "ready" + if item.signed_in is not None and (state := item.signed_in()) is not None: + row["signedIn"] = state + rows.append(row) + return rows + + +# ---- Terminal output -------------------------------------------------------------------------- + +_OSC = re.compile(r"\x1b\]([^\x07\x1b]*)(?:\x07|\x1b\\)") +_CURSOR_MOVE = re.compile(r"\x1b\[\d*[CG]") +_CSI = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]") +_ESCAPE = re.compile(r"\x1b[()][0-9A-Za-z]|\x1b[@-_]") +_URL = re.compile(r"https://[^\s\"'<>\\\x00-\x1f\x7f]+") + + +def _visible(raw: str) -> tuple[str, list[str]]: + """Terminal output as plain text, plus the targets of any hyperlinks it drew.""" + links = [] + for body in _OSC.findall(raw): + parts = body.split(";", 2) + if len(parts) == 3 and parts[0] == "8" and parts[2]: + links.append(parts[2]) + text = _OSC.sub("", raw) + text = _CURSOR_MOVE.sub(" ", text) + text = _ESCAPE.sub("", _CSI.sub("", text)) + return text.replace("\r", ""), links + + +def allowed_link(url: str, hosts: tuple[str, ...]) -> bool: + """An https link on one of the provider's own domains, nothing else.""" + if len(url) > 4096: + return False + try: + parts = urlsplit(url) + port = parts.port + except ValueError: + return False + host = (parts.hostname or "").lower() + return (parts.scheme == "https" and parts.username is None and parts.password is None + and port in (None, 443) and any(host == item or host.endswith("." + item) for item in hosts)) + + +def valid_code(code: str) -> bool: + """A code copied from a provider's page: one line of visible ASCII.""" + return 0 < len(code) <= _MAX_CODE and all(0x21 <= ord(character) <= 0x7e for character in code) + + +# ---- Sessions --------------------------------------------------------------------------------- + +_BROWSER_NAMES = ("open", "xdg-open", "sensible-browser", "x-www-browser", "www-browser", "wslview", + "gnome-open", "kde-open") + + +class _Session: + """One sign-in running in a private terminal.""" + + def __init__(self, item: Recipe, agent_id: str, argv: list[str]): + self.id = str(uuid.uuid4()) + self.recipe = item + self.agent_id = agent_id + self.status = STARTING + self.link: str | None = None + self.code: str | None = None + self.message = "" + self.started = time.monotonic() + self.ended: float | None = None + self._argv = argv + # How much output there was when the code went in; only later output can reject it. + self._seen = 0 + self._submitted_at: int | None = None + self._condition = threading.Condition() + self._process: subprocess.Popen | None = None + self._terminal: int | None = None + self._shims: tempfile.TemporaryDirectory | None = None + + # The person opens links on the phone, so the tool's attempt to open a browser here does nothing. + def _environment(self) -> dict[str, str]: + self._shims = tempfile.TemporaryDirectory(prefix="bighelp-sign-in-") + for name in _BROWSER_NAMES: + path = Path(self._shims.name, name) + path.write_text("#!/bin/sh\nexit 0\n") + path.chmod(0o700) + env = {key: value for key, value in os.environ.items() if key not in self.recipe.drop_env} + env.update(PATH=os.pathsep.join((self._shims.name, _search_path())), + BROWSER=str(Path(self._shims.name, "xdg-open")), TERM="xterm-256color", + COLUMNS="1000", LINES="50") + for key in ("CI", "NO_COLOR"): + env.pop(key, None) + if self.recipe.env is not None: + env.update(self.recipe.env(self.agent_id)) + return env + + def start(self) -> None: + import fcntl + import pty + import termios + terminal, child = pty.openpty() + # A wide terminal keeps long links and tokens on one line. + fcntl.ioctl(child, termios.TIOCSWINSZ, struct.pack("HHHH", 50, 1000, 0, 0)) + try: + self._process = subprocess.Popen( + self._argv, stdin=child, stdout=child, stderr=child, env=self._environment(), + cwd=str(Path.home()), start_new_session=True, close_fds=True) + except (OSError, ValueError): + os.close(terminal) + self._cleanup() + raise SignInError("sign_in_start_failed", f"{self.recipe.client} couldn't start on this computer.") + finally: + os.close(child) + self._terminal = terminal + threading.Thread(target=self._read, daemon=True, name="bighelp-sign-in").start() + + def _read(self) -> None: + raw = "" + terminal = self._terminal + while True: + if time.monotonic() - self.started > SESSION_SECONDS: + self._end(EXPIRED, "The sign-in took too long. Try again.") + break + try: + ready, _, _ = select.select([terminal], [], [], 0.5) + chunk = os.read(terminal, 65536) if ready else None + except OSError: + chunk = b"" + if chunk is None: + if self._process is not None and self._process.poll() is not None and not ready: + chunk = b"" + else: + continue + if not chunk: + break + raw += chunk.decode("utf-8", "replace") + if len(raw) > _MAX_OUTPUT: + self._end(FAILED, f"{self.recipe.client} printed more than expected. Try again.") + break + self._scan(raw) + with self._condition: + if self.status in _ENDED: + break + self._finish() + + def _scan(self, raw: str) -> None: + text, hyperlinks = _visible(raw) + with self._condition: + self._seen = len(text) + if self.status in _ENDED: + return + if self.link is None: + self.link = next((url for url in (*hyperlinks, *_URL.findall(text)) + if allowed_link(url, self.recipe.link_hosts)), None) + if self.recipe.code is not None and self.code is None and (match := self.recipe.code.search(text)): + self.code = match.group(1) + ready = self.link is not None and (self.recipe.code is None or self.code is not None) + if ready and self.status == STARTING: + self.status = NEEDS_CODE if self.recipe.flow == PASTE else WAITING + self._condition.notify_all() + keep = self.recipe.keep_token + token = keep[0].search(text) if keep is not None and self.status == FINISHING else None + after = text[self._submitted_at:] if self._submitted_at is not None else "" + rejected = (token is None and self.status == FINISHING and self.recipe.rejected is not None + and self.recipe.rejected.search(after) is not None) + if token is not None: + self._keep(keep[1], token.group(1)) + elif rejected: + self._end(FAILED, f"{self.recipe.client} didn't accept that code. Try again.") + self._stop() + + def _keep(self, variable: str, token: str) -> None: + """Save a printed token where the person would put it, then stop the tool.""" + from .workspace_capabilities import profile_scope + try: + with profile_scope(self.agent_id): + try: + from hermes_cli.config import save_env_value_secure as save + except ImportError: + from hermes_cli.config import save_env_value as save + save(variable, token) + except Exception as error: # noqa: BLE001 - the class name is safe to log, the text isn't + logger.warning("bighelp sign-in: saving %s failed (%s)", self.recipe.provider_id, type(error).__name__) + self._end(FAILED, "Hermes couldn't save the sign-in. Try again.") + else: + self._end(SIGNED_IN, "") + self._stop() + + def _finish(self) -> None: + process = self._process + code = None + if process is not None: + try: + code = process.wait(timeout=5) + except subprocess.TimeoutExpired: + self._stop() + with self._condition: + done = self.status in _ENDED + if not done: + if code == 0 and self.recipe.keep_token is None: + with _status_lock: + _status_cache.clear() + verified = self.recipe.signed_in() if self.recipe.signed_in is not None else None + if verified is False: + self._end(FAILED, f"{self.recipe.client} didn't finish signing in. Try again.") + else: + self._end(SIGNED_IN, "") + elif self.status == FINISHING and self.recipe.flow == PASTE: + self._end(FAILED, f"{self.recipe.client} didn't accept that code. Try again.") + else: + self._end(FAILED, f"{self.recipe.client} didn't finish signing in. Try again.") + self._cleanup() + + def _end(self, status: str, message: str) -> None: + with self._condition: + if self.status in _ENDED: + return + self.status = status + self.message = message + self.ended = time.monotonic() + self._condition.notify_all() + if status == SIGNED_IN: + with _status_lock: + _status_cache.clear() + logger.info("bighelp sign-in: %s %s", self.recipe.provider_id, status) + + def _stop(self) -> None: + process = self._process + if process is None or process.poll() is not None: + return + for sent in (signal.SIGTERM, signal.SIGKILL): + try: + os.killpg(process.pid, sent) + except (OSError, ProcessLookupError): + return + try: + process.wait(timeout=3) + return + except subprocess.TimeoutExpired: + continue + + def _cleanup(self) -> None: + if self._terminal is not None: + try: + os.close(self._terminal) + except OSError: + pass + self._terminal = None + if self._shims is not None: + self._shims.cleanup() + self._shims = None + + def wait_for_start(self, seconds: float) -> None: + with self._condition: + timed_out = not self._condition.wait_for(lambda: self.status != STARTING, timeout=seconds) + if timed_out: + self._end(FAILED, f"{self.recipe.client} didn't show a sign-in link. Try again.") + self._stop() + + def submit(self, code: str) -> None: + with self._condition: + if self.status != NEEDS_CODE or self._terminal is None: + raise SignInError("sign_in_not_waiting", "This sign-in isn't waiting for a code.") + self.status = FINISHING + self._submitted_at = self._seen + terminal = self._terminal + try: + os.write(terminal, code.encode("ascii")) + # A pause lets full-screen tools take the typed code before Return submits it. + time.sleep(0.3) + os.write(terminal, b"\r") + except OSError: + self._end(FAILED, f"{self.recipe.client} stopped before it got the code. Try again.") + + def cancel(self) -> None: + self._end(CANCELLED, "") + self._stop() + + def snapshot(self) -> dict: + with self._condition: + value = {"sessionId": self.id, "providerId": self.recipe.provider_id, "flow": self.recipe.flow, + "status": self.status, + "expiresInSeconds": max(0, int(SESSION_SECONDS - (time.monotonic() - self.started)))} + if self.status not in _ENDED: + if self.link: + value["link"] = self.link + if self.code: + value["code"] = self.code + if self.message: + value["message"] = self.message + return value + + +_sessions: dict[str, _Session] = {} +_sessions_lock = threading.Lock() + + +def _sweep() -> None: + now = time.monotonic() + with _sessions_lock: + for key, session in list(_sessions.items()): + if session.ended is not None and now - session.ended > _KEEP_ENDED_SECONDS: + del _sessions[key] + + +def start(agent_id: str, provider_id: str, *, wait: float = START_WAIT_SECONDS) -> dict: + """Start one provider's sign-in and wait briefly for its link.""" + _sweep() + item = recipe(provider_id) + if item is None: + raise SignInError("sign_in_unavailable", "This provider can't sign in from the app.") + if item.retired: + raise SignInError("sign_in_retired", item.retired) + argv = item.command() + if argv is None: + raise SignInError("sign_in_tool_missing", f"{item.client} isn't installed on this computer.") + with _sessions_lock: + # A new sign-in for the same account replaces an unfinished one. + replaced = [session for session in _sessions.values() + if session.agent_id == agent_id and session.recipe.provider_id == provider_id + and session.status not in _ENDED] + running = sum(1 for session in _sessions.values() if session.status not in _ENDED) - len(replaced) + if running >= _MAX_SESSIONS: + raise SignInError("sign_in_busy", "Too many sign-ins are running. Finish or cancel one first.") + session = _Session(item, agent_id, argv) + _sessions[session.id] = session + for old in replaced: + old.cancel() + try: + session.start() + except SignInError: + with _sessions_lock: + _sessions.pop(session.id, None) + raise + session.wait_for_start(wait) + return session.snapshot() + + +def _session(agent_id: str, session_id: str) -> _Session: + with _sessions_lock: + session = _sessions.get(session_id) + if session is None or session.agent_id != agent_id: + raise SignInError("sign_in_not_found", "That sign-in is no longer running. Start it again.") + return session + + +def status(agent_id: str, session_id: str) -> dict: + _sweep() + return _session(agent_id, session_id).snapshot() + + +def submit(agent_id: str, session_id: str, code: str) -> dict: + code = code.strip() + if not valid_code(code): + raise SignInError("sign_in_code_invalid", "That doesn't look like a sign-in code. Copy it again.") + session = _session(agent_id, session_id) + session.submit(code) + return session.snapshot() + + +def cancel(agent_id: str, session_id: str) -> dict: + session = _session(agent_id, session_id) + session.cancel() + return session.snapshot() + + +def cancel_all() -> None: + with _sessions_lock: + running = list(_sessions.values()) + for session in running: + session.cancel() diff --git a/loopdy_plugin/provider_sign_in_helper.py b/loopdy_plugin/provider_sign_in_helper.py new file mode 100644 index 0000000..a14eb33 --- /dev/null +++ b/loopdy_plugin/provider_sign_in_helper.py @@ -0,0 +1,35 @@ +"""Hermes' own GitHub Copilot login, run by ``provider_sign_in.py`` in a private terminal. + +It prints the link and code `hermes model` prints, waits for GitHub, and saves the token where +`hermes model` does (``COPILOT_GITHUB_TOKEN`` in the profile's env, from ``HERMES_HOME``). The token +is never printed. Exit status 0 means signed in. +""" +from __future__ import annotations + +import sys + + +def copilot() -> int: + from hermes_cli.copilot_auth import copilot_device_code_login + try: + from hermes_cli.config import save_env_value_secure as save + except ImportError: + from hermes_cli.config import save_env_value as save + token = copilot_device_code_login() + if not token: + return 1 + save("COPILOT_GITHUB_TOKEN", token) + return 0 + + +FLOWS = {"copilot": copilot} + + +def main(arguments: list[str]) -> int: + if len(arguments) != 1 or arguments[0] not in FLOWS: + return 2 + return FLOWS[arguments[0]]() + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tests/test_native_api.py b/tests/test_native_api.py index 29fcfd4..24d1808 100644 --- a/tests/test_native_api.py +++ b/tests/test_native_api.py @@ -155,6 +155,9 @@ def test_context_exact_safe_identity_cookie_and_no_unimplemented_features(self): if people_available(): expected.append("native-people-v1") expected.append("native-provider-usage-v1") + from loopdy_plugin.provider_sign_in import available as sign_in_available + if sign_in_available(): + expected.append("native-provider-sign-in-v1") self.assertEqual(value["features"], expected) self.assertEqual(value["servingProfileId"], "default") self.assertEqual(result.headers["cache-control"], "no-store") diff --git a/tests/test_native_startup_logging.py b/tests/test_native_startup_logging.py index c9c0391..ed80397 100644 --- a/tests/test_native_startup_logging.py +++ b/tests/test_native_startup_logging.py @@ -21,7 +21,7 @@ "native-voice-v1", "native-device-tools-v1", "native-room-activity-v1", "native-project-git-read-v1", "native-agent-templates-v1", "native-workspace-files-v1", "native-workspace-recent-v1", "native-host-restart-v1", - "native-provider-usage-v1", + "native-provider-usage-v1", "native-provider-sign-in-v1", ) WIKI_FEATURES = ("native-wiki-v1", "native-wiki-disconnect-v1") @@ -63,8 +63,10 @@ def setUp(self): available=Mock(return_value=True)) self.usage = module("loopdy_plugin.provider_usage", CAPABILITY=PROCESS_FEATURES[11], available=Mock(return_value=True)) + self.sign_in = module("loopdy_plugin.provider_sign_in", CAPABILITY=PROCESS_FEATURES[12], + available=Mock(return_value=True)) modules = [self.constants, self.profiles, self.device, self.room, self.git, - self.templates, self.files, self.wiki, self.restart, self.usage, + self.templates, self.files, self.wiki, self.restart, self.usage, self.sign_in, module("hermes_cli.dashboard_auth.base", Session=Session)] self.stack.enter_context(patch.dict(sys.modules, {value.__name__: value for value in modules})) self.stack.enter_context(patch.object(native_context, "_startup_advertisement_logged", False)) @@ -107,6 +109,7 @@ def test_unavailable_capabilities_are_omitted_and_each_is_warned(self): self.files.available.return_value = False self.restart.available.return_value = False self.usage.available.return_value = False + self.sign_in.available.return_value = False with self.assertLogs(LOG, level="INFO") as logs: native_context.log_native_feature_startup("research") expected = PROCESS_FEATURES[:2] diff --git a/tests/test_provider_sign_in.py b/tests/test_provider_sign_in.py new file mode 100644 index 0000000..d182f8f --- /dev/null +++ b/tests/test_provider_sign_in.py @@ -0,0 +1,404 @@ +"""Signing in to provider accounts from the app with each provider's own CLI, in a private terminal. + +The fake CLIs print what the real ones print (captured from Copilot CLI 1.0 and Claude Code 2.1): +a device link and code, an OSC 8 hyperlink and a paste prompt, or a full-screen token screen. +""" +from __future__ import annotations + +import os +from pathlib import Path +import stat +import sys +import tempfile +import textwrap +import time +import unittest +from unittest.mock import patch +import uuid + +from loopdy_plugin import provider_sign_in as si + + +FAKE_TOKEN = "sk-ant-oat01-" + "Fake0Token_" * 6 + + +def executable(directory: Path, name: str, body: str) -> str: + path = directory / name + path.write_text(f"#!{sys.executable}\n" + textwrap.dedent(body)) + path.chmod(path.stat().st_mode | stat.S_IXUSR) + return str(path) + + +COPILOT = """ + import os, sys, time + assert sys.argv[1:] == ["login", "--device-code"], sys.argv + assert sys.stdin.isatty() + leaked = [name for name in ("COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN") if name in os.environ] + print("To authenticate, visit https://github.com/login/device and enter code WDJB-MJHT", flush=True) + print("Waiting for authorization...", flush=True) + sys.stdout.write("\\x1b]52;c;V0RKQi1NSkhU\\x07") + sys.stdout.flush() + time.sleep(float(os.environ.get("FAKE_APPROVE_AFTER", "0.6"))) + sys.exit(3 if leaked else int(os.environ.get("FAKE_EXIT", "0"))) +""" + +# `claude auth login`, `claude auth status --json` and `claude setup-token`. +CLAUDE = """ + import json, os, sys, time + state = os.path.join(os.environ["FAKE_STATE"], "claude-signed-in") + link = ("https://claude.com/cai/oauth/authorize?code=true&client_id=fixture&response_type=code" + "&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback&state=fixture") + if sys.argv[1:] == ["auth", "status", "--json"]: + print(json.dumps({"loggedIn": os.path.exists(state), "authMethod": "claude.ai"})) + sys.exit(0) + if sys.argv[1:] == ["auth", "login", "--claudeai"]: + sys.stdout.write("Opening browser to sign in\\u2026\\r\\nIf the browser didn't open, visit: " + "\\x1b]8;;" + link + "\\x07\\x1b[94m" + link + "\\x1b[39m\\x1b]8;;\\x07\\r\\n" + "Paste code here if prompted > ") + sys.stdout.flush() + code = sys.stdin.readline().strip() + if code == "good#code": + open(state, "w").close() + print("Login successful.") + sys.exit(0) + print("OAuth error: Invalid code") + sys.exit(1) + if sys.argv[1:] == ["setup-token"]: + sys.stdout.write("\\x1b[?2004h\\x1b[38;5;174mWelcome\\x1b[9Gto\\x1b[12GClaude\\x1b[19GCode\\x1b[39m\\r\\r\\n" + "\\x1b]8;id=1;" + link + "\\x07\\x1b[38;5;246m" + link[:60] + "\\x1b[39m\\x1b]8;;\\x07\\r\\r\\n" + "\\x1b]8;id=1;" + link + "\\x07\\x1b[38;5;246m" + link[60:] + "\\x1b[39m\\x1b]8;;\\x07\\r\\r\\n" + "Paste code here if prompted >") + sys.stdout.flush() + code = sys.stdin.readline().strip() + if code != "good#code": + # The real screen stays up after a bad code. + sys.stdout.write("\\x1b[2G\\x1b[31mOAuth\\x1b[8Gerror:\\x1b[15GRequest failed with status code 400" + "\\x1b[39m Press Enter to retry.\\r\\r\\n") + sys.stdout.flush() + time.sleep(60) + sys.stdout.write("\\x1b[2G\\x1b[32m\\u2713\\x1b[39m Long-lived authentication token created successfully!\\r\\r\\n" + "\\x1b[2GYour OAuth token (valid for 1 year):\\r\\r\\n\\r\\r\\n\\x1b[2G" + os.environ["FAKE_TOKEN"] + + "\\r\\r\\n\\r\\r\\n\\x1b[2GStore this token securely.\\r\\r\\n") + sys.stdout.flush() + time.sleep(60) + sys.exit(9) +""" + + +class Base(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory(prefix="bighelp-sign-in-test-") + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() + (self.root / "bin").mkdir() + (self.root / "state").mkdir() + self.home = self.root / "home" + self.home.mkdir() + environment = patch.dict(os.environ, { + "HERMES_HOME": str(self.home), "HOME": str(self.home), "FAKE_STATE": str(self.root / "state"), + "FAKE_TOKEN": FAKE_TOKEN, "GH_TOKEN": "fixture-env-token", + }) + environment.start() + self.addCleanup(environment.stop) + self.copilot = executable(self.root / "bin", "copilot", COPILOT) + self.claude = executable(self.root / "bin", "claude", CLAUDE) + tools = {"copilot": self.copilot, "claude": self.claude} + finder = patch.object(si, "find_cli", side_effect=lambda name: tools.get(name)) + finder.start() + self.addCleanup(finder.stop) + self.addCleanup(si.cancel_all) + self.addCleanup(si._sessions.clear) + si._status_cache.clear() + + def wait_for(self, session_id, statuses, seconds=10.0): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + value = si.status("default", session_id) + if value["status"] in statuses: + return value + time.sleep(0.05) + self.fail(f"still {si.status('default', session_id)}") + + +class DeviceSignInTests(Base): + def test_copilot_cli_shows_its_link_and_code_then_finishes_on_its_own(self): + started = si.start("default", "copilot-acp") + self.assertEqual(started["status"], si.WAITING, started) + self.assertEqual((started["link"], started["code"], started["flow"]), + ("https://github.com/login/device", "WDJB-MJHT", si.DEVICE)) + done = self.wait_for(started["sessionId"], {si.SIGNED_IN, si.FAILED}) + # The fake exits 3 if a token from the environment reached it. + self.assertEqual(done["status"], si.SIGNED_IN, done) + self.assertNotIn("link", done) + self.assertNotIn("code", done) + + def test_a_tool_that_exits_with_an_error_fails_without_its_output(self): + with patch.dict(os.environ, {"FAKE_EXIT": "1"}): + started = si.start("default", "copilot-acp") + done = self.wait_for(started["sessionId"], {si.SIGNED_IN, si.FAILED}) + self.assertEqual(done["status"], si.FAILED) + self.assertEqual(done["message"], "GitHub Copilot CLI didn't finish signing in. Try again.") + + def test_cancel_stops_the_tool(self): + with patch.dict(os.environ, {"FAKE_APPROVE_AFTER": "30"}): + started = si.start("default", "copilot-acp") + session = si._sessions[started["sessionId"]] + self.assertEqual(si.cancel("default", started["sessionId"])["status"], si.CANCELLED) + deadline = time.monotonic() + 5 + while session._process.poll() is None and time.monotonic() < deadline: + time.sleep(0.05) + self.assertIsNotNone(session._process.poll()) + + def test_a_new_sign_in_replaces_an_unfinished_one(self): + with patch.dict(os.environ, {"FAKE_APPROVE_AFTER": "30"}): + first = si.start("default", "copilot-acp") + second = si.start("default", "copilot-acp") + self.assertEqual(si.status("default", first["sessionId"])["status"], si.CANCELLED) + self.assertEqual(si.status("default", second["sessionId"])["status"], si.WAITING) + + def test_links_off_the_providers_domains_are_never_passed_on(self): + executable(self.root / "bin", "copilot", """ + import sys, time + print("To authenticate, visit https://github.com.evil.example/login/device and enter code WDJB-MJHT", + flush=True) + time.sleep(30) + """) + started = si.start("default", "copilot-acp", wait=1.0) + self.assertEqual(started["status"], si.FAILED) + self.assertNotIn("link", started) + self.assertEqual(started["message"], "GitHub Copilot CLI didn't show a sign-in link. Try again.") + + def test_sessions_belong_to_their_profile(self): + with patch.dict(os.environ, {"FAKE_APPROVE_AFTER": "30"}): + started = si.start("default", "copilot-acp") + with self.assertRaises(si.SignInError) as refused: + si.status("research", started["sessionId"]) + self.assertEqual(refused.exception.code, "sign_in_not_found") + + +class PasteSignInTests(Base): + def test_claude_code_takes_the_code_from_the_page(self): + started = si.start("default", "claude-code") + self.assertEqual(started["status"], si.NEEDS_CODE, started) + self.assertTrue(started["link"].startswith("https://claude.com/cai/oauth/authorize?"), started["link"]) + self.assertNotIn("code", started) + self.assertIs(si.recipe("claude-code").signed_in(), False) + self.assertEqual(si.submit("default", started["sessionId"], " good#code ")["status"], si.FINISHING) + done = self.wait_for(started["sessionId"], {si.SIGNED_IN, si.FAILED}) + self.assertEqual(done["status"], si.SIGNED_IN, done) + # The status cache is dropped once a sign-in lands. + self.assertIs(si.recipe("claude-code").signed_in(), True) + + def test_a_wrong_code_says_so(self): + started = si.start("default", "claude-code") + si.submit("default", started["sessionId"], "wrong#code") + done = self.wait_for(started["sessionId"], {si.SIGNED_IN, si.FAILED}) + self.assertEqual((done["status"], done["message"]), + (si.FAILED, "Claude Code didn't accept that code. Try again.")) + + def test_a_wrong_code_on_the_token_screen_says_so_and_closes_it(self): + started = si.start("default", "anthropic") + si.submit("default", started["sessionId"], "wrong#code") + done = self.wait_for(started["sessionId"], {si.SIGNED_IN, si.FAILED}) + self.assertEqual((done["status"], done["message"]), + (si.FAILED, "Claude Code didn't accept that code. Try again.")) + self.assertFalse((self.home / ".env").exists()) + + def test_codes_are_one_line_of_visible_text(self): + started = si.start("default", "claude-code") + for code in ("", "two\nlines", "tab\there", "x" * 2049, "café"): + with self.assertRaises(si.SignInError) as refused: + si.submit("default", started["sessionId"], code) + self.assertEqual(refused.exception.code, "sign_in_code_invalid", code) + self.assertEqual(si.status("default", started["sessionId"])["status"], si.NEEDS_CODE) + + def test_a_code_is_only_taken_when_the_tool_asks(self): + with patch.dict(os.environ, {"FAKE_APPROVE_AFTER": "30"}): + started = si.start("default", "copilot-acp") + with self.assertRaises(si.SignInError) as refused: + si.submit("default", started["sessionId"], "good#code") + self.assertEqual(refused.exception.code, "sign_in_not_waiting") + + def test_setup_token_is_saved_to_the_profile_and_never_returned_or_logged(self): + started = si.start("default", "anthropic") + self.assertEqual(started["status"], si.NEEDS_CODE, started) + # The full link comes from the hyperlink, not the wrapped text. + self.assertTrue(started["link"].endswith("&state=fixture"), started["link"]) + with self.assertLogs("hermes.plugins.bighelp", level="INFO") as logs: + si.submit("default", started["sessionId"], "good#code") + done = self.wait_for(started["sessionId"], {si.SIGNED_IN, si.FAILED}) + self.assertEqual(done["status"], si.SIGNED_IN, done) + self.assertNotIn(FAKE_TOKEN, repr(done)) + self.assertFalse(any(FAKE_TOKEN in record.getMessage() for record in logs.records)) + self.assertIn(f"CLAUDE_CODE_OAUTH_TOKEN={FAKE_TOKEN}", (self.home / ".env").read_text()) + session = si._sessions[started["sessionId"]] + deadline = time.monotonic() + 5 + while session._process.poll() is None and time.monotonic() < deadline: + time.sleep(0.05) + self.assertIsNotNone(session._process.poll(), "the token screen is closed once the token is saved") + + +class CatalogTests(Base): + def test_lists_ready_missing_and_retired_sign_ins(self): + rows = {row["providerId"]: row for row in si.providers()} + self.assertEqual(rows["copilot-acp"]["state"], "ready") + self.assertEqual(rows["claude-code"], { + "providerId": "claude-code", "name": "Claude Code", "client": "Claude Code", "flow": si.PASTE, + "docsURL": "https://docs.claude.com/en/docs/claude-code/setup", "state": "ready", "signedIn": False}) + self.assertEqual(rows["qwen-oauth"]["state"], "retired") + self.assertEqual(rows["qwen-oauth"]["replacementKey"], "DASHSCOPE_API_KEY") + with patch.object(si, "find_cli", return_value=None): + missing = {row["providerId"]: row for row in si.providers()} + self.assertEqual((missing["claude-code"]["state"], missing["claude-code"]["installCommand"]), + ("notInstalled", "npm install -g @anthropic-ai/claude-code")) + self.assertEqual(missing["claude-code"]["message"], "Claude Code isn't installed on this computer.") + + def test_refuses_unknown_retired_and_missing_tools(self): + for provider, code in (("nope", "sign_in_unavailable"), ("qwen-oauth", "sign_in_retired")): + with self.assertRaises(si.SignInError) as refused: + si.start("default", provider) + self.assertEqual(refused.exception.code, code) + with patch.object(si, "find_cli", return_value=None), self.assertRaises(si.SignInError) as refused: + si.start("default", "claude-code") + self.assertEqual(refused.exception.code, "sign_in_tool_missing") + + def test_override_settings_pick_the_configured_cli(self): + other = executable(self.root / "bin", "claude-other", "print('x')\n") + with patch.dict(os.environ, {"CLAUDE_SUBSCRIPTION_DIRECTSDK_COMMAND": other}): + self.assertEqual(si.recipe("claude-subscription-directsdk-experimental").command(), + [other, "auth", "login", "--claudeai"]) + with patch.dict(os.environ, {"CLAUDE_SUBSCRIPTION_DIRECTSDK_COMMAND": "/no/such/claude"}): + self.assertEqual(si.recipe("claude-subscription-directsdk-experimental").command()[0], self.claude) + with patch.dict(os.environ, {"HERMES_COPILOT_ACP_COMMAND": "copilot --acp; echo other"}): + self.assertEqual(si.recipe("copilot-acp").command(), [self.copilot, "login", "--device-code"]) + + def test_hermes_copilot_login_runs_the_helper_with_this_python(self): + self.assertEqual(si.recipe("copilot").command(), [sys.executable, str(si._HELPER), "copilot"]) + self.assertEqual(si._profile_home("default")["HERMES_HOME"], str(self.home)) + + def test_too_many_sign_ins_at_once(self): + with patch.dict(os.environ, {"FAKE_APPROVE_AFTER": "30"}), patch.object(si, "_MAX_SESSIONS", 1): + si.start("default", "copilot-acp") + with self.assertRaises(si.SignInError) as refused: + si.start("default", "claude-code") + self.assertEqual(refused.exception.code, "sign_in_busy") + + +class HelperTests(unittest.TestCase): + def test_saves_the_token_where_hermes_model_does_and_never_prints_it(self): + from loopdy_plugin import provider_sign_in_helper as helper + saved = {} + with patch("hermes_cli.copilot_auth.copilot_device_code_login", return_value="gho_fixture"), \ + patch("hermes_cli.config.save_env_value_secure", side_effect=saved.__setitem__), \ + patch("builtins.print") as printed: + self.assertEqual(helper.main(["copilot"]), 0) + self.assertEqual(saved, {"COPILOT_GITHUB_TOKEN": "gho_fixture"}) + printed.assert_not_called() + with patch("hermes_cli.copilot_auth.copilot_device_code_login", return_value=None): + self.assertEqual(helper.main(["copilot"]), 1) + self.assertEqual(helper.main(["other"]), 2) + + +class OutputTests(unittest.TestCase): + def test_reads_links_from_hyperlinks_and_text(self): + text, links = si._visible("\x1b]8;id=1;https://claude.com/a?b=c\x07\x1b[94mhttps://claude.com/a\x1b[39m" + "\x1b]8;;\x07\r\nWelcome\x1b[9Gto\x1b]52;c;Zm9v\x07") + self.assertEqual(links, ["https://claude.com/a?b=c"]) + self.assertEqual(text, "https://claude.com/a\nWelcome to") + + def test_only_https_links_on_the_providers_domains(self): + hosts = ("github.com",) + self.assertTrue(si.allowed_link("https://github.com/login/device", hosts)) + self.assertTrue(si.allowed_link("https://www.github.com/login/device", hosts)) + for url in ("http://github.com/login/device", "https://github.com.evil.example/", "https://evilgithub.com/", + "https://user@github.com/", "https://github.com:8443/", "https://github.com/" + "a" * 4096): + self.assertFalse(si.allowed_link(url, hosts), url) + + +class RouteTests(unittest.TestCase): + """POST /native/provider-sign-in/* through Hermes' real auth middleware.""" + + def setUp(self): + from fastapi import FastAPI + from fastapi.testclient import TestClient + from hermes_cli.dashboard_auth.middleware import gated_auth_middleware + from hermes_cli.dashboard_auth.registry import register_provider, unregister_global_provider + from loopdy_plugin import native_api, room_activity + from test_native_api import FixtureProvider + + hub = patch.object(room_activity, "_HUB", room_activity.RoomActivityHub()) + hub.start() + self.addCleanup(hub.stop) + temporary = tempfile.TemporaryDirectory(prefix="bighelp-sign-in-route-") + self.addCleanup(temporary.cleanup) + home = Path(temporary.name).resolve() + environment = patch.dict(os.environ, {"HERMES_HOME": str(home), "HOME": str(home)}) + environment.start() + self.addCleanup(environment.stop) + self.provider = FixtureProvider() + register_provider(self.provider) + self.addCleanup(unregister_global_provider, self.provider.name, self.provider) + app = FastAPI() + app.state.auth_required = True + app.middleware("http")(gated_auth_middleware) + app.include_router(native_api.router, prefix="/api/plugins/loopdy") + self.client = TestClient(app) + self.addCleanup(self.client.close) + self.addCleanup(si._sessions.clear) + + def headers(self): + context = self.client.get("/api/plugins/loopdy/native/context", headers={"Authorization": "Bearer fixture-alice"}) + self.assertIn(si.CAPABILITY, context.json()["features"]) + return {"Authorization": "Bearer fixture-alice", "If-Match": context.headers["etag"], + "X-Loopdy-Request-ID": str(uuid.uuid4())} + + def post(self, operation, body): + return self.client.post(f"/api/plugins/loopdy/native/provider-sign-in/{operation}", headers=self.headers(), + json=body) + + def test_runs_each_operation_for_the_profile(self): + snapshot = {"sessionId": str(uuid.uuid4()), "providerId": "copilot-acp", "status": si.WAITING} + with patch.object(si, "providers", return_value=[{"providerId": "copilot-acp", "state": "ready"}]), \ + patch.object(si, "start", return_value=snapshot) as start, \ + patch.object(si, "status", return_value=snapshot) as status, \ + patch.object(si, "submit", return_value=snapshot) as submit, \ + patch.object(si, "cancel", return_value=snapshot) as cancel: + listed = self.post("list", {"agentId": "default"}) + self.assertEqual(listed.status_code, 200, listed.text) + self.assertEqual(listed.json(), {"agentId": "default", + "providers": [{"providerId": "copilot-acp", "state": "ready"}]}) + self.assertEqual(listed.headers["cache-control"], "no-store") + session = {"agentId": "default", "sessionId": snapshot["sessionId"]} + self.assertEqual(self.post("start", {"agentId": "default", "providerId": "copilot-acp"}).json(), + {"agentId": "default", **snapshot}) + self.assertEqual(self.post("status", session).status_code, 200) + self.assertEqual(self.post("submit", {**session, "code": "good#code"}).status_code, 200) + self.assertEqual(self.post("cancel", session).status_code, 200) + start.assert_called_once_with("default", "copilot-acp") + status.assert_called_once_with("default", snapshot["sessionId"]) + submit.assert_called_once_with("default", snapshot["sessionId"], "good#code") + cancel.assert_called_once_with("default", snapshot["sessionId"]) + + def test_refusals_carry_their_code(self): + response = self.post("start", {"agentId": "default", "providerId": "qwen-oauth"}) + self.assertEqual(response.status_code, 410) + self.assertEqual(response.json()["error"]["code"], "sign_in_retired") + response = self.post("status", {"agentId": "default", "sessionId": str(uuid.uuid4())}) + self.assertEqual((response.status_code, response.json()["error"]["code"]), (404, "sign_in_not_found")) + + def test_rejects_bad_bodies_unknown_operations_profiles_and_missing_auth(self): + self.assertEqual(self.post("list", {"agentId": "ghost"}).status_code, 404) + self.assertEqual(self.post("run", {"agentId": "default"}).status_code, 404) + self.assertEqual(self.post("start", {"agentId": "default", "providerId": "../x"}).status_code, 422) + self.assertEqual(self.post("start", {"agentId": "default", "providerId": "x", "argv": ["sh"]}).status_code, 422) + self.assertEqual(self.post("submit", {"agentId": "default", "sessionId": "x", "code": "c"}).status_code, 422) + self.assertEqual(self.client.post("/api/plugins/loopdy/native/provider-sign-in/list", + json={"agentId": "default"}).status_code, 401) + headers = self.headers() + del headers["If-Match"] + self.assertEqual(self.client.post("/api/plugins/loopdy/native/provider-sign-in/list", headers=headers, + json={"agentId": "default"}).status_code, 428) + + +if __name__ == "__main__": + unittest.main() From f1a386015ff3a8887f9e66b762ca2b5fbfe5a312 Mon Sep 17 00:00:00 2001 From: "Prompt. Click. Run." <59135406+promptclickrun@users.noreply.github.com> Date: Wed, 30 Sep 2026 16:19:26 -0500 Subject: [PATCH 2/2] GitHub Copilot's main sign-in is offered even though Hermes keeps it as a key Hermes files GitHub Copilot (`copilot`) under API keys because it stores a token, so it never appears in Hermes' account list. The sign-in list now includes every recipe whose provider this Hermes has (from its provider catalog), reports Copilot as signed in from Hermes' own read-only status, and still skips recipes for provider plugins the host doesn't have. Co-Authored-By: Claude Opus 5.5 --- docs/PROVIDER_SIGN_IN.md | 3 ++ loopdy_plugin/native_api.py | 2 +- loopdy_plugin/provider_sign_in.py | 75 ++++++++++++++++++++++--------- tests/test_provider_sign_in.py | 30 ++++++++++++- 4 files changed, 85 insertions(+), 25 deletions(-) diff --git a/docs/PROVIDER_SIGN_IN.md b/docs/PROVIDER_SIGN_IN.md index c538d5e..a654730 100644 --- a/docs/PROVIDER_SIGN_IN.md +++ b/docs/PROVIDER_SIGN_IN.md @@ -16,6 +16,9 @@ xAI Grok) keep using Hermes' own sign-in. | Anthropic Account (`anthropic`) | Claude Code: `claude setup-token`. Its long-lived token goes to the profile's env as `CLAUDE_CODE_OAUTH_TOKEN`, the route Hermes documents for Claude subscriptions | Link; paste the code back | | Qwen OAuth (`qwen-oauth`) | None. Qwen stopped offering this sign-in in April 2026 | Listed as retired, with Qwen Cloud's API key as the replacement | +A sign-in is listed only when this Hermes has that provider. That includes GitHub Copilot, which Hermes files under +API keys because it keeps a token, but which signs in with GitHub like an account. + If the tool isn't installed, the app says so and shows the install command. Nothing is installed for you. ## Respecting provider terms diff --git a/loopdy_plugin/native_api.py b/loopdy_plugin/native_api.py index 279daae..8c70661 100644 --- a/loopdy_plugin/native_api.py +++ b/loopdy_plugin/native_api.py @@ -550,7 +550,7 @@ def _sign_in(operation: str, body: _Body) -> dict: raise NativeAPIError(404, "profile_not_found", "The selected profile no longer exists.") try: if operation == "list": - return {"providers": sign_in.providers()} + return {"providers": sign_in.providers(body.agentId)} if operation == "start": return sign_in.start(body.agentId, body.providerId) if operation == "status": diff --git a/loopdy_plugin/provider_sign_in.py b/loopdy_plugin/provider_sign_in.py index 739d9b2..9f4753c 100644 --- a/loopdy_plugin/provider_sign_in.py +++ b/loopdy_plugin/provider_sign_in.py @@ -14,6 +14,8 @@ Adding a provider: add a ``Recipe`` to ``RECIPES`` with the provider's Hermes id, its own CLI and arguments, the domains its links may use, and whether its page approves by itself (``DEVICE``) or shows a code to paste back (``PASTE``). Commands are fixed here; the phone only names a provider. +A sign-in is listed only when this Hermes has that provider, including ones Hermes files under API +keys (GitHub Copilot keeps its token as a key but signs in with GitHub). Privacy: terminal output stays in memory for one sign-in and is never logged or returned. A token a tool prints for the person to keep (``claude setup-token``) is saved straight to this profile's @@ -86,6 +88,8 @@ class Recipe: signed_in: Callable[[], bool | None] | None = None retired: str = "" replacement_key: str = "" + # Listed only when this Hermes has the provider; Hermes' own status rows (claude-code) always are. + needs_hermes_provider: bool = True def available() -> bool: @@ -179,6 +183,27 @@ def signed_in() -> bool | None: return signed_in +def _hermes_signed_in(provider_id: str) -> Callable[[], bool | None]: + """Hermes' own read-only status for a provider it keeps the credential for (in the profile scope).""" + def signed_in() -> bool | None: + try: + from hermes_cli.auth import get_auth_status + state = get_auth_status(provider_id).get("logged_in") + except Exception: # noqa: BLE001 - a status Hermes can't give is "unknown", never a failure + return None + return state if isinstance(state, bool) else None + return signed_in + + +def _hermes_providers() -> set[str] | None: + """Every provider this Hermes has (keys and accounts, plugins included); None if it can't say.""" + try: + from hermes_cli.provider_catalog import provider_catalog + return {descriptor.slug for descriptor in provider_catalog()} + except Exception: # noqa: BLE001 - list every sign-in rather than none + return None + + _GITHUB_CODE = re.compile(r"\b([A-Z0-9]{4}-[A-Z0-9]{4})\b") _CLAUDE_HOSTS = ("claude.com", "claude.ai", "anthropic.com") _CLAUDE_INSTALL = "npm install -g @anthropic-ai/claude-code" @@ -202,12 +227,13 @@ def signed_in() -> bool | None: Recipe( provider_id="copilot", name="GitHub Copilot", client="Hermes", flow=DEVICE, link_hosts=("github.com",), command=_hermes_helper("copilot", "hermes_cli.copilot_auth"), - docs="https://docs.github.com/en/copilot", code=_GITHUB_CODE, env=_profile_home), + docs="https://docs.github.com/en/copilot", code=_GITHUB_CODE, env=_profile_home, + signed_in=_hermes_signed_in("copilot")), Recipe( provider_id="claude-code", name="Claude Code", client="Claude Code", flow=PASTE, link_hosts=_CLAUDE_HOSTS, command=lambda: (argv + ["auth", "login", "--claudeai"]) if (argv := _claude()) else None, install=_CLAUDE_INSTALL, docs=_CLAUDE_DOCS, rejected=_CLAUDE_REJECTED, env=_claude_env(), - signed_in=_claude_signed_in(_claude)), + signed_in=_claude_signed_in(_claude), needs_hermes_provider=False), Recipe( provider_id="claude-subscription-directsdk-experimental", name="Claude Subscription DirectSDK", client="Claude Code", flow=PASTE, link_hosts=_CLAUDE_HOSTS, @@ -235,27 +261,32 @@ def recipe(provider_id: str) -> Recipe | None: return _BY_ID.get(provider_id) -def providers() -> list[dict]: +def providers(agent_id: str) -> list[dict]: """Every sign-in this host can run, or why it can't, for the app's Provider Keys screen.""" - rows = [] - for item in RECIPES: - row: dict = {"providerId": item.provider_id, "name": item.name, "client": item.client, "flow": item.flow} - if item.docs: - row["docsURL"] = item.docs - if item.retired: - row.update(state="retired", message=item.retired) - if item.replacement_key: - row["replacementKey"] = item.replacement_key - elif item.command() is None: - row.update(state="notInstalled", message=f"{item.client} isn't installed on this computer.") - if item.install: - row["installCommand"] = item.install - else: - row["state"] = "ready" - if item.signed_in is not None and (state := item.signed_in()) is not None: - row["signedIn"] = state - rows.append(row) - return rows + from .workspace_capabilities import profile_scope + with profile_scope(agent_id): + known = _hermes_providers() + return [_row(item) for item in RECIPES + if not item.needs_hermes_provider or known is None or item.provider_id in known] + + +def _row(item: Recipe) -> dict: + row: dict = {"providerId": item.provider_id, "name": item.name, "client": item.client, "flow": item.flow} + if item.docs: + row["docsURL"] = item.docs + if item.retired: + row.update(state="retired", message=item.retired) + if item.replacement_key: + row["replacementKey"] = item.replacement_key + elif item.command() is None: + row.update(state="notInstalled", message=f"{item.client} isn't installed on this computer.") + if item.install: + row["installCommand"] = item.install + else: + row["state"] = "ready" + if item.signed_in is not None and (state := item.signed_in()) is not None: + row["signedIn"] = state + return row # ---- Terminal output -------------------------------------------------------------------------- diff --git a/tests/test_provider_sign_in.py b/tests/test_provider_sign_in.py index d182f8f..5d2e072 100644 --- a/tests/test_provider_sign_in.py +++ b/tests/test_provider_sign_in.py @@ -240,7 +240,7 @@ def test_setup_token_is_saved_to_the_profile_and_never_returned_or_logged(self): class CatalogTests(Base): def test_lists_ready_missing_and_retired_sign_ins(self): - rows = {row["providerId"]: row for row in si.providers()} + rows = {row["providerId"]: row for row in si.providers("default")} self.assertEqual(rows["copilot-acp"]["state"], "ready") self.assertEqual(rows["claude-code"], { "providerId": "claude-code", "name": "Claude Code", "client": "Claude Code", "flow": si.PASTE, @@ -248,11 +248,37 @@ def test_lists_ready_missing_and_retired_sign_ins(self): self.assertEqual(rows["qwen-oauth"]["state"], "retired") self.assertEqual(rows["qwen-oauth"]["replacementKey"], "DASHSCOPE_API_KEY") with patch.object(si, "find_cli", return_value=None): - missing = {row["providerId"]: row for row in si.providers()} + missing = {row["providerId"]: row for row in si.providers("default")} self.assertEqual((missing["claude-code"]["state"], missing["claude-code"]["installCommand"]), ("notInstalled", "npm install -g @anthropic-ai/claude-code")) self.assertEqual(missing["claude-code"]["message"], "Claude Code isn't installed on this computer.") + def test_github_copilot_is_listed_though_hermes_files_it_under_keys(self): + from hermes_cli.provider_catalog import provider_catalog + tabs = {descriptor.slug: descriptor.tab for descriptor in provider_catalog()} + self.assertEqual(tabs.get("copilot"), "keys", "Hermes keeps Copilot's token as a key") + listed = [row["providerId"] for row in si.providers("default")] + self.assertIn("copilot", listed) + self.assertIn("copilot-acp", listed) + # Hermes' own Claude Code status row is always there; a provider plugin this host lacks isn't. + self.assertIn("claude-code", listed) + self.assertNotIn("claude-subscription-directsdk-experimental", listed) + with patch.object(si, "_hermes_providers", return_value=None): + self.assertIn("claude-subscription-directsdk-experimental", + [row["providerId"] for row in si.providers("default")]) + + def test_github_copilot_is_signed_in_once_hermes_has_its_token(self): + from hermes_cli import copilot_auth + from hermes_cli.config import save_env_value + environment = {key: value for key, value in os.environ.items() + if key not in ("GH_TOKEN", "GITHUB_TOKEN", "COPILOT_GITHUB_TOKEN")} + with patch.dict(os.environ, environment, clear=True), \ + patch.object(copilot_auth, "_try_gh_cli_token", return_value=None): + copilot = lambda: next(row for row in si.providers("default") if row["providerId"] == "copilot") + self.assertEqual(copilot()["signedIn"], False) + save_env_value("COPILOT_GITHUB_TOKEN", "gho_" + "f" * 36) + self.assertEqual(copilot()["signedIn"], True) + def test_refuses_unknown_retired_and_missing_tools(self): for provider, code in (("nope", "sign_in_unavailable"), ("qwen-oauth", "sign_in_retired")): with self.assertRaises(si.SignInError) as refused: