The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): core-made Codex requests so plugins never hold the token
Teknium4070f011a2bf
diff --git a/hermes_cli/plugin_provider_requests.py b/hermes_cli/plugin_provider_requests.pynew file mode 100644index 00000000000..62614f0bf24--- /dev/null+++ b/hermes_cli/plugin_provider_requests.py@@ -0,0 +1,158 @@+"""Signed-in provider requests that core makes FOR plugins; the token never reaches plugin code.++A plugin that needs the user's subscription sign-in (today: Codex / ChatGPT) must not read, refresh+or rewrite Hermes's auth store or ``~/.codex/auth.json``. Codex refresh tokens are single-use, so a+second refresher races Hermes's locked refresh and can sign the user out. Instead the plugin declares+``requires_auth: [openai-codex]`` in its ``plugin.yaml`` and calls :func:`credentialed_provider_request`.+Hermes resolves the credential through its own locked-refresh path, attaches ``Authorization``+itself, sends only to that provider's origins, never follows a redirect, and hands back+status, headers and body.++The caller is identified by file location: the nearest stack frame inside an installed plugin+directory. Like capabilities this is consent and visibility, not a sandbox. In-process plugin code+can still read any file the user can.+"""++from __future__ import annotations++import json as _json+import sys+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable, Mapping, Optional++from hermes_cli.urllib_security import url_origin+++class ProviderNotSignedIn(RuntimeError):+ """The user has no usable sign-in for the provider in this Hermes profile."""+++@dataclass(frozen=True)+class ProviderResponse:+ status: int+ headers: dict[str, str]+ body: bytes++ @property+ def text(self) -> str:+ return self.body.decode("utf-8", "replace")++ def json(self) -> Any:+ return _json.loads(self.body)+++def _codex_auth(url: str) -> tuple[dict[str, str], str]:+ """``(auth headers, credential base URL)`` from Hermes's own locked-refresh resolver."""+ from agent.codex_headers import codex_account_headers+ from agent.turn_failure_copy import oauth_relogin_command+ from hermes_cli.auth_codex import resolve_codex_runtime_credentials+ from hermes_cli.auth_constants import AuthError++ try:+ creds = resolve_codex_runtime_credentials()+ except AuthError as exc:+ if not exc.relogin_required:+ raise+ creds = {}+ token = str(creds.get("api_key") or "").strip()+ if not token:+ raise ProviderNotSignedIn(+ f"Not signed in to Codex in Hermes. Run `{oauth_relogin_command('openai-codex')}` "+ "or sign in to OpenAI Codex under Providers in the Hermes desktop app.")+ headers = codex_account_headers(token) if url_origin(url)[1] == "chatgpt.com" else {}+ headers["Authorization"] = f"Bearer {token}"+ return headers, str(creds.get("base_url") or "")+++# provider -> (origins its token may be sent to, auth resolver). chatgpt.com is the Codex backend+# core itself calls; api.openai.com hosts the Realtime client-secret endpoint Codex clients use.+_PROVIDERS: dict[str, tuple[frozenset, Callable[[str], tuple[dict[str, str], str]]]] = {+ "openai-codex": (frozenset({("https", "chatgpt.com", 443), ("https", "api.openai.com", 443)}), _codex_auth),+}+++def _calling_plugin_dir() -> Optional[Path]:+ """Directory of the plugin whose code is nearest on the calling stack, or None."""+ from hermes_cli.plugins import get_bundled_plugins_dir+ from hermes_constants import get_default_hermes_root, get_hermes_home, get_process_hermes_home++ bases = (get_hermes_home() / "plugins", get_process_hermes_home() / "plugins",+ get_default_hermes_root() / "plugins", get_bundled_plugins_dir())+ roots = {r for base in bases for r in (base.absolute(), base.resolve())}+ frame = sys._getframe(2)+ while frame is not None:+ raw = Path(frame.f_code.co_filename)+ for path in (raw.absolute(), raw.resolve()):+ root = next((r for r in roots if path.is_relative_to(r) and path != r), None)+ if root is None:+ continue+ for parent in path.parents:+ if parent == root:+ break+ if (parent / "plugin.yaml").is_file() or (parent / "plugin.yml").is_file():+ return parent+ return root / path.relative_to(root).parts[0]+ frame = frame.f_back+ return None+++def declared_auth_providers(manifest: Mapping[str, Any]) -> list[str]:+ """``requires_auth`` from a manifest dict: the providers whose sign-in the plugin uses."""+ raw = (manifest or {}).get("requires_auth")+ return [str(p).strip() for p in raw if str(p).strip()] if isinstance(raw, list) else []+++def requires_auth_notice(manifest: Mapping[str, Any]) -> str:+ """One line for install/show surfaces; empty when the plugin declares no sign-in use."""+ providers = declared_auth_providers(manifest)+ return (f"Uses your sign-in for: {', '.join(providers)} (Hermes sends the requests; "+ "the plugin never receives the token)") if providers else ""+++def _declared_providers(plugin_dir: Path) -> list[str]:+ from pm.plugin_declarations import native_manifest_file, read_native_manifest++ manifest = native_manifest_file(plugin_dir)+ return declared_auth_providers(read_native_manifest(manifest)) if manifest else []+++def credentialed_provider_request(+ provider: str, method: str, url: str, *, json: Any = None,+ headers: Optional[Mapping[str, str]] = None, timeout: float = 30.0,+) -> ProviderResponse:+ """Send ``method url`` with the user's *provider* sign-in attached by Hermes.++ Refuses (``PermissionError``) a caller outside an installed plugin, a plugin whose ``plugin.yaml``+ does not list *provider* under ``requires_auth``, and any origin outside the provider's+ allowlist; raises :class:`ProviderNotSignedIn` when this profile has no sign-in. Redirects are+ returned as-is, never followed. The result carries no credential.+ """+ spec = _PROVIDERS.get(provider)+ if spec is None:+ raise ValueError(f"No signed-in requests for provider {provider!r} (supported: {', '.join(_PROVIDERS)})")+ origins, resolve = spec+ plugin_dir = _calling_plugin_dir()+ if plugin_dir is None:+ raise PermissionError("credentialed_provider_request must be called from an installed plugin's code")+ if provider not in _declared_providers(plugin_dir):+ raise PermissionError(+ f"Plugin '{plugin_dir.name}' must declare `requires_auth: [{provider}]` in plugin.yaml")+ if url_origin(url) not in origins:+ raise PermissionError(f"Refusing to send the {provider} sign-in to {url_origin(url)[1] or url!r}")+ auth_headers, credential_base = resolve(url)+ if url_origin(credential_base) not in origins:+ # A pooled gateway key belongs to its own host only (#121486).+ raise PermissionError(f"This profile's {provider} credential routes to a custom endpoint; refusing")+ sent = {k: v for k, v in (headers or {}).items() if str(k).lower() not in {h.lower() for h in auth_headers}}+ import httpx++ with httpx.Client(timeout=timeout, follow_redirects=False) as client:+ response = client.request(method, url, json=json, headers={**sent, **auth_headers})+ return ProviderResponse(response.status_code, dict(response.headers), response.content)+++__all__ = [+ "ProviderNotSignedIn", "ProviderResponse", "credentialed_provider_request", "declared_auth_providers",+ "requires_auth_notice",+]diff --git a/hermes_cli/plugins_cmd_catalog.py b/hermes_cli/plugins_cmd_catalog.pyindex b20678ccc08..7dcf136c723 100644--- a/hermes_cli/plugins_cmd_catalog.py+++ b/hermes_cli/plugins_cmd_catalog.py@@ -481,7 +481,8 @@ class RepinResult(NamedTuple):# Surfaces a re-pin can widen without the user seeing a diff: each is a list of identifiers the# new manifest adds (``desktop`` = a Desktop half appeared). Compared as sets — removals are not consent events._SURFACE_LABELS = {"capabilities": "host capabilities", "tools": "tools", "hooks": "hooks",- "python_dependencies": "Python dependencies", "desktop": "Desktop UI half"}+ "python_dependencies": "Python dependencies", "desktop": "Desktop UI half",+ "requires_auth": "your sign-in for"}def plugin_surface(manifest: dict, tree: Path) -> dict[str, set]:@@ -499,7 +500,7 @@ def plugin_surface(manifest: dict, tree: Path) -> dict[str, set]:return {"capabilities": set(_declared_capabilities_from_manifest(manifest, str(manifest.get("name") or "?"))),"tools": _list("provides_tools"), "hooks": _list("provides_hooks", "hooks"),- "python_dependencies": _list("python_dependencies"),+ "python_dependencies": _list("python_dependencies"), "requires_auth": _list("requires_auth"),"desktop": {"desktop/plugin.js"} if (tree / "desktop" / "plugin.js").is_file() else set(),}diff --git a/hermes_cli/plugins_cmd_install.py b/hermes_cli/plugins_cmd_install.pyindex 29088a55529..2aee13fdd3f 100644--- a/hermes_cli/plugins_cmd_install.py+++ b/hermes_cli/plugins_cmd_install.py@@ -672,6 +672,9 @@ def cmd_install(f"[dim]Plugin installed but not enabled. "f"Run `hermes plugins enable {installed_name}` to activate.[/dim]")+ from hermes_cli.plugin_provider_requests import requires_auth_notice+ if notice := requires_auth_notice(installed_manifest):+ console.print(f"[yellow]{notice}[/yellow]")# Non-interactive installs and declines leave declared capabilities ungranted (fail closed).declared_caps = _pc()._declared_capabilities_from_manifest(installed_manifest, installed_name)if declared_caps:diff --git a/hermes_cli/plugins_cmd_listing.py b/hermes_cli/plugins_cmd_listing.pyindex c7dad8ec9d5..ac7fa0d9292 100644--- a/hermes_cli/plugins_cmd_listing.py+++ b/hermes_cli/plugins_cmd_listing.py@@ -142,6 +142,9 @@ def cmd_show(name: str) -> None:else "refused (plugins.isolation: host)" if isolation_mode() == ISOLATION_HOSTelse "Hermes process")console.print(f"[dim]Runs in:[/dim] {runs_in} [dim]— {audit.summary()}[/dim]")+ from hermes_cli.plugin_provider_requests import requires_auth_notice+ if notice := requires_auth_notice(manifest):+ console.print(f"[dim]Sign-in:[/dim] {notice}")console.print("[dim]Emits:[/dim] " + (", ".join(emits) if emits else "[dim](none)[/dim]"))console.print("[dim]Listens:[/dim] " + (", ".join(listens) if listens else "[dim](none)[/dim]"))console.print()diff --git a/hermes_cli/plugins_manifest.py b/hermes_cli/plugins_manifest.pyindex ec09ac3987e..576ba20e545 100644--- a/hermes_cli/plugins_manifest.py+++ b/hermes_cli/plugins_manifest.py@@ -35,7 +35,7 @@ _KNOWN_MANIFEST_FIELDS: set[str] = {"pip_dependencies", "provides_browser_providers", "provides_web_providers","manifest_version", "api_version", "requires_plugins", "python_dependencies", "config_schema","license", "homepage", "tags", "capabilities", "emits", "listens", "hermes", "depends",- "requires_hermes", "python_runtime", "provides_locales",+ "requires_hermes", "python_runtime", "provides_locales", "requires_auth",}# Highest manifest schema version this Hermes understands.diff --git a/tests/hermes_cli/test_plugin_provider_requests.py b/tests/hermes_cli/test_plugin_provider_requests.pynew file mode 100644index 00000000000..5f68895b85b--- /dev/null+++ b/tests/hermes_cli/test_plugin_provider_requests.py@@ -0,0 +1,145 @@+"""Core makes Codex-signed requests for plugins; the token never reaches plugin code.++Real loopback HTTP servers stand in for the provider; a real plugin directory under the test+HERMES_HOME makes the call, and a fake Codex sign-in is seeded in that home's auth store.+"""++import base64+import importlib.util+import json+import os+import threading+import time+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path++import pytest++from hermes_cli import plugin_provider_requests as ppr+++def _seg(d: dict) -> str:+ return base64.urlsafe_b64encode(json.dumps(d).encode()).rstrip(b"=").decode()+++def _jwt() -> str:+ seg = _seg+ return f"{seg({'alg': 'none'})}.{seg({'exp': int(time.time()) + 86400, 'sub': 'fake'})}.sig"+++TOKEN = _jwt()+++class _Stub:+ def __init__(self, status=200, location=""):+ self.seen: list[dict] = []+ stub = self++ class Handler(BaseHTTPRequestHandler):+ def _answer(self):+ length = int(self.headers.get("Content-Length") or 0)+ stub.seen.append({"path": self.path, "headers": dict(self.headers),+ "body": self.rfile.read(length)})+ self.send_response(status)+ if location:+ self.send_header("Location", location)+ self.send_header("Content-Type", "application/json")+ self.end_headers()+ self.wfile.write(b'{"value": "ek_ephemeral", "expires_at": 1}')++ do_GET = do_POST = _answer++ def log_message(self, *_):+ pass++ self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ self.url = f"http://127.0.0.1:{self.server.server_address[1]}"+ threading.Thread(target=self.server.serve_forever, daemon=True).start()++ def close(self):+ self.server.shutdown()+ self.server.server_close()+++def stubs(monkeypatch):+ allowed, other = _Stub(), _Stub()+ origins, resolve = ppr._PROVIDERS["openai-codex"]+ # Test-only: the loopback stub joins the real allowlist; ``other`` stays outside it.+ monkeypatch.setitem(ppr._PROVIDERS, "openai-codex",+ (origins | {("http", "127.0.0.1", allowed.server.server_address[1])}, resolve))+ yield allowed, other+ allowed.close()+ other.close()+++def _home() -> Path:+ return Path(os.environ["HERMES_HOME"])+++def _sign_in():+ (_home() / "auth.json").write_text(json.dumps({"version": 1, "providers": {"openai-codex": {+ "auth_mode": "chatgpt", "tokens": {"access_token": TOKEN, "refresh_token": "fake-rt"}}}}))+++def _plugin(declares: bool):+ """A dashboard-style plugin module (``dashboard/plugin_api.py``) loaded the way the dashboard does."""+ root = _home() / "plugins" / ("voice" if declares else "undeclared")+ (root / "dashboard").mkdir(parents=True)+ (root / "plugin.yaml").write_text("name: voice\n" + ("requires_auth: [openai-codex]\n" if declares else ""))+ (root / "dashboard" / "plugin_api.py").write_text(+ "from hermes_cli.plugin_provider_requests import credentialed_provider_request\n"+ "def mint(url):\n"+ " return credentialed_provider_request('openai-codex', 'POST', url, json={'session': {}})\n")+ spec = importlib.util.spec_from_file_location(f"hermes_dashboard_plugin_{root.name}", root / "dashboard" / "plugin_api.py")+ assert spec is not None and spec.loader is not None+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++def test_token_attached_for_allowlisted_origin_and_never_returned(stubs):+ allowed, _ = stubs+ _sign_in()+ result = _plugin(declares=True).mint(allowed.url + "/v1/realtime/client_secrets")++ assert result.status == 200 and result.json()["value"] == "ek_ephemeral"+ assert allowed.seen[0]["headers"]["Authorization"] == f"Bearer {TOKEN}"+ assert json.loads(allowed.seen[0]["body"]) == {"session": {}}+ assert TOKEN not in repr(result) and TOKEN not in json.dumps(result.headers)+++def test_disallowed_origin_and_redirect_never_carry_the_token(stubs, monkeypatch):+ _, other = stubs+ _sign_in()+ plugin = _plugin(declares=True)+ with pytest.raises(PermissionError, match="Refusing"):+ plugin.mint(other.url + "/steal")+ assert other.seen == []++ redirecting = _Stub(status=302, location=other.url + "/steal")+ origins, resolve = ppr._PROVIDERS["openai-codex"]+ monkeypatch.setitem(ppr._PROVIDERS, "openai-codex",+ (origins | {("http", "127.0.0.1", redirecting.server.server_address[1])}, resolve))+ try:+ result = plugin.mint(redirecting.url + "/v1/realtime/client_secrets")+ finally:+ redirecting.close()+ assert result.status == 302 and other.seen == []+++def test_undeclared_plugin_and_non_plugin_callers_are_refused(stubs):+ allowed, _ = stubs+ _sign_in()+ with pytest.raises(PermissionError, match="requires_auth"):+ _plugin(declares=False).mint(allowed.url)+ with pytest.raises(PermissionError, match="installed plugin"):+ ppr.credentialed_provider_request("openai-codex", "GET", allowed.url)+ assert allowed.seen == []+++def test_not_signed_in_names_the_sign_in_command(stubs):+ allowed, _ = stubs+ with pytest.raises(ppr.ProviderNotSignedIn, match="hermes auth add openai-codex"):+ _plugin(declares=True).mint(allowed.url)+ assert allowed.seen == []diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.mdindex aff9cf1cabc..89319fa2fa9 100644--- a/website/docs/developer-guide/plugins/index.md+++ b/website/docs/developer-guide/plugins/index.md@@ -348,6 +348,84 @@ Hermes reads these from installed metadata without importing your code, so`hermes plugins capabilities` and the consent flow stay accurate for pipinstalls.+### Use the user's Codex sign-in (core-made requests)++A plugin that needs the user's ChatGPT / Codex subscription (minting an OpenAI+Realtime client secret, calling a Codex backend endpoint) must **not** read,+refresh or rewrite `~/.codex/auth.json` or Hermes's `auth.json`. Codex refresh+tokens are single-use: a plugin that refreshes on its own races Hermes's locked+refresh, and the loser's rotation chain gets revoked, signing the user out.+Ask Hermes to make the request instead. Hermes resolves the credential through+its own refresh path, attaches `Authorization` itself and returns only the+response. Your code never sees the token.++Declare the sign-in in `plugin.yaml`:++```yaml+name: live-voice+requires_auth:+ - openai-codex+```++Then call the public helper. It is a plain function, so dashboard plugins+(`dashboard/plugin_api.py`) and vendored modules can import it as well as+`register(ctx)` code:++```python+from hermes_cli.plugin_provider_requests import ProviderNotSignedIn, credentialed_provider_request++def mint_client_secret(session: dict) -> dict:+ try:+ resp = credentialed_provider_request(+ "openai-codex", "POST", "https://api.openai.com/v1/realtime/client_secrets",+ json={"session": session}, timeout=15)+ except ProviderNotSignedIn as exc:+ return {"ok": False, "error": str(exc)} # tells the user how to sign in+ if resp.status != 200:+ return {"ok": False, "error": f"client secret failed ({resp.status}): {resp.text[:300]}"}+ return {"ok": True, **resp.json()}+```++This replaces a hand-rolled helper that read `~/.codex/auth.json`, POSTed to+`auth.openai.com/oauth/token` when the token was near expiry and wrote the+result back. Delete that code; there is no refresh step left for the plugin.++`credentialed_provider_request(provider, method, url, *, json=None, headers=None, timeout=30.0)`+returns a `ProviderResponse` (`status`, `headers`, `body`, `.text`, `.json()`).+The rules:++- **Declared plugins only.** The caller is the plugin whose file is on the call+ stack. Hermes finds it under the plugins directory and reads its+ `plugin.yaml`. A plugin that does not list the provider in `requires_auth`,+ and code outside any installed plugin, gets `PermissionError`. Call the helper+ from your own function. Handing the bare helper to `run_in_executor` leaves no+ plugin frame on the stack, so the call is refused.+- **Provider origins only.** For `openai-codex` the token is sent only to+ `https://chatgpt.com` and `https://api.openai.com`. Any other URL raises+ `PermissionError` before a request is made. A profile whose Codex credential+ routes to a custom gateway is refused too, because that key belongs to the+ gateway.+- **No redirects.** A 3xx response comes back as-is and is never followed, so+ the header cannot reach a third host.+- **Profile-scoped.** The credential is the active profile's Codex sign-in, the+ same one chat uses (`hermes auth add openai-codex`, or the Codex sign-in in the+ desktop app). When there is none you get `ProviderNotSignedIn`, whose message+ names the sign-in command.+- Your own `headers` are sent too, except any that would replace the+ `Authorization` (or account) headers Hermes attaches.++`requires_auth` appears in `hermes plugins show <name>` and at install time, and+a catalog re-pin that adds it asks the user before updating. Like capabilities,+this is consent and visibility. It is **not a sandbox**: in-process plugin code+can still read any file the user can, and reviewers reject plugins that do.++**Usage panels:** don't call the usage endpoints yourself. Use+`agent.account_usage.fetch_account_usage("openai-codex", read_only=True)`. It+returns an `AccountUsageSnapshot` (plan, session/weekly windows with+`used_percent` and `reset_at`) and never refreshes or rotates a credential.+**Sign-out** belongs to Hermes, not to a plugin: point users at+`hermes auth logout openai-codex` instead of deleting credential files.+### Manifest v2 reference`plugin.yaml` also supports an additive **v2 schema** (#64165). Every field is@@ -368,6 +446,7 @@ this Hermes understands still loads with a warning.| `homepage` | str | Project URL. || `tags` | list of str | Free-form discovery tags (e.g. `[gateway, telegram]`). || `provides_locales` | list | Language pack declaration: ids (`- pl`) or `{id, endonym, rtl}` mappings whose `locales/<id>[.tui\|.desktop].yaml` the loader registers automatically — see [Ship a language pack](#ship-a-language-pack). |+| `requires_auth` | list of str | Providers whose sign-in the plugin uses through Hermes (today: `openai-codex`). Required by `credentialed_provider_request`; shown at install and in `hermes plugins show`. See [Use the user's Codex sign-in](#use-the-users-codex-sign-in-core-made-requests). |```yaml# plugin.yaml — manifest v2 examplediff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex 2a6818c6fd9..bdf16ef0155 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -539,8 +539,8 @@ gracefully.granted, `hermes plugins update` surfaces the additions and asks again. Newcapabilities stay off until you consent — a plugin update can never silentlywiden its access. Catalog re-pins go one step further: when the new pin adds-tools, hooks, Python dependencies, host capabilities or a Desktop UI half the-installed version did not have, the CLI shows the delta and asks `y/N` before+tools, hooks, Python dependencies, host capabilities, a provider sign-in+(`requires_auth`) or a Desktop UI half the installed version did not have, the CLI shows the delta and asks `y/N` beforeanything moves, and the Desktop / dashboard **Update** button opens the sameconfirmation. Declining (or a non-interactive session) leaves the plugin atthe old pin.