Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agent-runtimes): run Hermes and OpenClaw agents on the ChatGPT subscription
rubenluetke10-beepeeb4800ecbc6
diff --git a/docs/agent-runtimes.md b/docs/agent-runtimes.mdindex abda26eaeb..5bcfea5cd7 100644--- a/docs/agent-runtimes.md+++ b/docs/agent-runtimes.md@@ -39,12 +39,42 @@ None of this calls a model, so setup and updates never spend a key.## Models-An agent on Hermes or OpenClaw runs on any Jarvis provider with an API key or-a local server (`model_map.py`); the dialog lists the ones connected right now.-Subscription seats (Claude Code, Codex, …) are not offered. A Claude-subscription login (`sk-ant-oat…`) saved in the Anthropic API-key slot is-not an API key either: Anthropic's API refuses it from these runtimes-("OAuth access token is invalid"), so `route_for` treats that slot as empty.+An agent on Hermes or OpenClaw runs on the ChatGPT subscription, on any+Jarvis provider with an API key, or on a local server (`model_map.py`); the+dialog lists the ones connected right now, subscriptions first.++**ChatGPT subscription: Jarvis' model gateway** (`gateway.py`,+`ui/web/runtime_gateway_routes.py`). Handing the subscription login to the+runtime would make a second program refresh it, and OAuth refresh tokens are+single-use: whichever refreshed first would break the other, including the+person's own Codex login. So the runtime never gets the login. Jarvis+configures it with a custom provider in the OpenAI Responses shape+(Hermes `transport: responses`, OpenClaw `api: openai-responses`) whose base+URL is `/api/runtime-gateway/v1` on Jarvis' loopback server, and a per-agent+token Jarvis mints (`jrg_…`, process environment only). The gateway rebuilds+each request field by field (model, input, instructions, function tools,+reasoning effort) and answers it with Jarvis' own subscription client on the+agent's Codex account, whose refresh is coordinated in one place+(`live/subscription_auth.py`). Events stream back unchanged; a failure+mid-stream arrives as `response.failed` with a plain message.+`SurfaceSecurity` accepts a gateway token on `/api/runtime-gateway/` and+nowhere else. Hermes finds the key again on session restore through+`OPENAI_BASE_URL` = the gateway URL (it pairs `OPENAI_API_KEY` with exactly+that base URL).++**Claude subscription: not offered.** Its login works only inside Claude+Code, and Hermes would bill it as paid extra usage. A Claude login+(`sk-ant-oat…`) saved in the Anthropic API-key slot is refused by Anthropic's+API from these runtimes ("OAuth access token is invalid"), so `route_for`+treats that slot as empty.++`scripts/spikes/agent_runtimes_subscription_e2e.py hermes|openclaw` runs two+real turns through the gateway on the subscription (two model calls);+`--replay` answers from a stand-in in the subscription's event format instead,+for when the allowance is used up. Verified 2026-10-06 with `--replay` for+both runtimes (answer streamed, history carried into the second turn), and+against the live subscription up to its answer: the account had reached its+usage limit, and that error reached Hermes as `response.failed`.The runtime decides which agent loop, native tools and session store a turnuses. Everything that makes a Jarvis agent stays in Jarvis and is identicaldiff --git a/jarvis/agent_chat/runner_acp.py b/jarvis/agent_chat/runner_acp.pyindex 3f032a99f5..ad67f24c5a 100644--- a/jarvis/agent_chat/runner_acp.py+++ b/jarvis/agent_chat/runner_acp.py@@ -12,6 +12,7 @@ driver in ``jarvis.agent_runtimes``). The turn itself is driven over ACP byfrom __future__ import annotationsimport asyncio+import functoolsimport loggingfrom pathlib import Pathfrom typing import Any@@ -127,7 +128,16 @@ async def plan_runtime_turn(if agent is None:raise CliUnavailable(f"{runtime_name.title()} runs society agents only.")try:- route = await asyncio.to_thread(route_for, _config(), session.provider, session.model)+ route = await asyncio.to_thread(+ functools.partial(+ route_for,+ _config(),+ session.provider,+ session.model,+ agent_id=agent.agent_id,+ account_id=getattr(session, "account_id", "") or "",+ )+ )except RouteUnavailable as exc:raise CliUnavailable(str(exc)) from excplan_mode = session.permission_mode in ("plan", "read-only")diff --git a/jarvis/agent_runtimes/gateway.py b/jarvis/agent_runtimes/gateway.pynew file mode 100644index 0000000000..c01fdfef01--- /dev/null+++ b/jarvis/agent_runtimes/gateway.py@@ -0,0 +1,231 @@+"""Jarvis' model gateway: Hermes / OpenClaw agents on a ChatGPT subscription.++Handing the person's subscription login to Hermes or OpenClaw would put a+second program in charge of refreshing it, and OAuth refresh tokens are+single-use: whichever program refreshed first would break the other (and the+person's own Codex login with it). Instead the runtime talks to Jarvis. This+module answers an OpenAI Responses request on the app's own loopback server+(``/api/runtime-gateway/v1``) with Jarvis' subscription client+(``jarvis.live.subscription_reasoning``) on the agent's Codex account, whose+login refresh is coordinated in one place (``jarvis.live.subscription_auth``).+The runtime gets a per-agent token Jarvis minted, never the login, and both+runtimes only need the long-stable OpenAI Responses shape.++Only function tools pass through: Jarvis' subscription client accepts nothing+else, and the runtime executes its own tools. Requests are rebuilt field by+field, so a runtime option the subscription endpoint does not accept never+reaches it.+"""++from __future__ import annotations++import json+import logging+import secrets+import threading+from collections.abc import AsyncIterator+from dataclasses import dataclass+from typing import Any, Final++log = logging.getLogger(__name__)++#: Every gateway route lives under this path (``surface_security`` accepts a+#: gateway token there and nowhere else).+PATH_PREFIX: Final[str] = "/api/runtime-gateway"+BASE_PATH: Final[str] = f"{PATH_PREFIX}/v1"++#: The Jarvis provider whose agents run through this gateway.+SUBSCRIPTION_PROVIDER: Final[str] = "openai-codex"+++class GatewayError(Exception):+ """A request the gateway cannot answer; ``status`` is the HTTP code."""++ def __init__(self, message: str, *, status: int = 400, code: str = "invalid_request") -> None:+ super().__init__(message)+ self.status = status+ self.code = code+++@dataclass(frozen=True, slots=True)+class Grant:+ """Who a gateway token speaks for."""++ agent_id: str+ #: The Codex account (``jarvis.agent_accounts``); "" = the active one.+ account_id: str+++_LOCK = threading.Lock()+_GRANTS: dict[str, Grant] = {}+_TOKENS: dict[Grant, str] = {}+_CLIENTS: dict[str, Any] = {}+++def grant_token(agent_id: str, account_id: str = "") -> str:+ """The token one agent's runtime presents (stable for the app's lifetime,+ so a runtime that keeps a process between turns is not restarted)."""+ grant = Grant(agent_id, account_id)+ with _LOCK:+ token = _TOKENS.get(grant)+ if token is None:+ token = f"jrg_{secrets.token_urlsafe(32)}"+ _TOKENS[grant] = token+ _GRANTS[token] = grant+ return token+++def verify(token: str) -> Grant | None:+ """The grant behind ``token``; ``None`` for anything Jarvis did not mint."""+ if not token.startswith("jrg_"):+ return None+ with _LOCK:+ return _GRANTS.get(token)+++def base_url() -> str | None:+ """The gateway's URL on this app's server, or ``None`` before it bound."""+ from jarvis.core import runtime_refs++ base = runtime_refs.get_api_base_url()+ return f"{base.rstrip('/')}{BASE_PATH}" if base else None+++def subscription_ready(account_id: str = "") -> bool:+ """Whether the Codex login can answer (local metadata only, no network)."""+ from jarvis.live.subscription_auth import SubscriptionAuth++ return bool(SubscriptionAuth(account_id).status_snapshot()["connected"])+++def _client(account_id: str) -> Any:+ """One subscription client per Codex account, kept for the app's lifetime."""+ with _LOCK:+ found = _CLIENTS.get(account_id)+ if found is None:+ from jarvis.live.subscription_auth import SubscriptionAuth+ from jarvis.live.subscription_reasoning import SubscriptionReasoning++ auth = SubscriptionAuth(account_id)+ found = SubscriptionReasoning(credentials=auth.credentials)+ _CLIENTS[account_id] = found+ return found+++# ---------------------------------------------------------------- requests+++def _function_tool(tool: Any) -> dict[str, Any] | None:+ """A Responses function tool, from either the Responses or the Chat shape."""+ if not isinstance(tool, dict) or tool.get("type") != "function":+ return None+ spec = tool.get("function") if isinstance(tool.get("function"), dict) else tool+ name = spec.get("name")+ if not isinstance(name, str) or not name:+ return None+ out: dict[str, Any] = {"type": "function", "name": name}+ if isinstance(spec.get("description"), str):+ out["description"] = spec["description"]+ out["parameters"] = (+ spec["parameters"] if isinstance(spec.get("parameters"), dict) else {"type": "object"}+ )+ if isinstance(spec.get("strict"), bool):+ out["strict"] = spec["strict"]+ return out+++def request_args(body: Any) -> dict[str, Any]:+ """The subscription client's arguments for one Responses request body."""+ if not isinstance(body, dict):+ raise GatewayError("The request body must be a JSON object.")+ model = body.get("model")+ if not isinstance(model, str) or not model.strip():+ raise GatewayError("The request names no model.")+ raw_input = body.get("input", [])+ if isinstance(raw_input, str):+ items: list[dict[str, Any]] = [+ {"role": "user", "content": [{"type": "input_text", "text": raw_input}]}+ ]+ elif isinstance(raw_input, list) and all(isinstance(item, dict) for item in raw_input):+ items = list(raw_input)+ else:+ raise GatewayError("The request input must be text or a list of items.")+ instructions = body.get("instructions")+ tools = [found for tool in body.get("tools") or [] if (found := _function_tool(tool))]+ reasoning = body.get("reasoning") if isinstance(body.get("reasoning"), dict) else {}+ effort = reasoning.get("effort") if isinstance(reasoning.get("effort"), str) else ""+ return {+ "model": model.strip(),+ "input": items,+ "instructions": instructions if isinstance(instructions, str) else "",+ "tools": tools,+ "reasoning_effort": effort,+ }+++def _sse(event: dict[str, Any]) -> bytes:+ return f"event: {event['type']}\ndata: {json.dumps(event, ensure_ascii=False)}\n\n".encode()+++def _failed_event(message: str, code: str) -> dict[str, Any]:+ return {+ "type": "response.failed",+ "response": {"status": "failed", "error": {"code": code, "message": message}},+ }+++async def stream_response(grant: Grant, args: dict[str, Any]) -> AsyncIterator[bytes]:+ """The Responses event stream as server-sent events.++ Once streaming has begun a failure can only travel as an event, so it+ becomes ``response.failed`` with the plain message (never a provider+ body: the subscription client words its own errors).+ """+ from jarvis.live.subscription_auth import SubscriptionAuthError+ from jarvis.live.subscription_reasoning import SubscriptionReasoningError++ try:+ async for event in _client(grant.account_id).stream(**args):+ yield _sse(event)+ except (SubscriptionReasoningError, SubscriptionAuthError) as exc:+ log.info("runtime gateway: %s turn failed (%s)", grant.agent_id, type(exc).__name__)+ yield _sse(_failed_event(str(exc), getattr(exc, "code", "subscription_unavailable")))+++async def complete_response(grant: Grant, args: dict[str, Any]) -> dict[str, Any]:+ """The finished Responses object, for a runtime that did not ask to stream."""+ from jarvis.live.subscription_auth import SubscriptionAuthError+ from jarvis.live.subscription_reasoning import SubscriptionReasoningError++ try:+ async for event in _client(grant.account_id).stream(**args):+ finished = event.get("response")+ if event.get("type") == "response.completed" and isinstance(finished, dict):+ return dict(finished)+ except (SubscriptionReasoningError, SubscriptionAuthError) as exc:+ raise GatewayError(str(exc), status=502, code="subscription_unavailable") from exc+ raise GatewayError("ChatGPT ended without an answer.", status=502, code="incomplete")+++async def list_models(grant: Grant) -> list[dict[str, Any]]:+ """The account's ChatGPT models, in the OpenAI ``/models`` shape."""+ from jarvis.live.subscription_auth import SubscriptionAuthError+ from jarvis.live.subscription_reasoning import SubscriptionReasoningError++ try:+ rows = await _client(grant.account_id).list_models()+ except (SubscriptionReasoningError, SubscriptionAuthError) as exc:+ raise GatewayError(str(exc), status=502, code="subscription_unavailable") from exc+ return [+ {"id": row["id"], "object": "model", "owned_by": "openai"}+ for row in rows+ if isinstance(row.get("id"), str)+ ]+++def reset() -> None:+ """Forget every token and client (tests)."""+ with _LOCK:+ _GRANTS.clear()+ _TOKENS.clear()+ _CLIENTS.clear()diff --git a/jarvis/agent_runtimes/hermes.py b/jarvis/agent_runtimes/hermes.pyindex 364e77484b..14aab216d9 100644--- a/jarvis/agent_runtimes/hermes.py+++ b/jarvis/agent_runtimes/hermes.py@@ -282,6 +282,10 @@ def _restore_key_aliases(base_url: str, api_key: str | None) -> dict[str, str]:if not api_key:return {}host = (urlsplit(base_url).hostname or "").lower()+ if host in ("127.0.0.1", "localhost", "::1"):+ # Jarvis' own model gateway: Hermes pairs OPENAI_API_KEY with exactly+ # the OPENAI_BASE_URL it was issued for, and with no other host.+ return {"OPENAI_BASE_URL": base_url, "OPENAI_API_KEY": api_key}if not host or host[-1].isdigit() or "." not in host:return {}if host == "openai.com" or host.endswith(".openai.com"):diff --git a/jarvis/agent_runtimes/model_map.py b/jarvis/agent_runtimes/model_map.pyindex a26dce4c78..221a02d11e 100644--- a/jarvis/agent_runtimes/model_map.py+++ b/jarvis/agent_runtimes/model_map.py@@ -9,10 +9,12 @@ is expressed through it: the endpoint comes fromproxy included) and the key travels only in the runtime process' environmentas :data:`KEY_ENV_VAR` — never in a file (AP-12).-Subscription seats (Claude Code, Codex, …) are not offered: driving those-logins from another vendor's agent loop is not a path Jarvis can keep-working across updates, and Hermes would bill a Claude Max login as paid-extra usage. Vertex needs service-account auth neither runtime receives here.+The ChatGPT subscription (``openai-codex``) runs through Jarvis' own model+gateway (``gateway.py``): the runtime gets a Responses endpoint on Jarvis'+loopback server and a per-agent token, never the login. A Claude+subscription is not offered: its login works only inside Claude Code, and+Hermes would bill it as paid extra usage. Vertex needs service-account auth+neither runtime receives here."""from __future__ import annotations@@ -23,7 +25,7 @@ from typing import Any, Final, Literallog = logging.getLogger(__name__)-Transport = Literal["chat_completions", "anthropic_messages"]+Transport = Literal["chat_completions", "anthropic_messages", "responses"]#: The environment variable both runtimes read the model key from.KEY_ENV_VAR: Final[str] = "JARVIS_RUNTIME_API_KEY"@@ -43,6 +45,8 @@ class _Endpoint:keyless: bool = False#: Appended to a configured server root (local servers store the root).path_suffix: str = ""+ #: Served by Jarvis' own model gateway on the person's subscription.+ subscription: bool = False#: Jarvis provider id (``agent_chat.catalog`` / ``core.config``) -> endpoint.@@ -57,6 +61,7 @@ _ENDPOINTS: Final[dict[str, _Endpoint]] = {),"ollama": _Endpoint("chat_completions", None, keyless=True, path_suffix="/v1"),"local-openai": _Endpoint("chat_completions", None, keyless=True, path_suffix="/v1"),+ "openai-codex": _Endpoint("responses", None, subscription=True),}@@ -85,6 +90,11 @@ def supported_providers() -> frozenset[str]:return frozenset(_ENDPOINTS)+def subscription_providers() -> frozenset[str]:+ """Providers served by Jarvis' model gateway on the person's subscription."""+ return frozenset(name for name, endpoint in _ENDPOINTS.items() if endpoint.subscription)++def supports(provider: str) -> bool:return provider in _ENDPOINTS@@ -97,8 +107,16 @@ def usable_providers(config: Any) -> list[str]:subscription without an Anthropic API key never looks like a choice."""usable: list[str] = []- for provider in sorted(_ENDPOINTS):+ # Subscriptions first: they spend no API key.+ for provider in sorted(_ENDPOINTS, key=lambda name: (not _ENDPOINTS[name].subscription, name)):try:+ if _ENDPOINTS[provider].subscription:+ from jarvis.agent_runtimes import gateway++ if not gateway.subscription_ready():+ continue+ usable.append(provider)+ continueroute_for(config, provider, "probe")except RouteUnavailable: # not connected: the provider is simply not offeredcontinue@@ -131,13 +149,53 @@ def _local_root(provider: str, configured: str | None) -> str | None:return None-def route_for(config: Any, provider: str, model: str) -> ModelRoute:- """Resolve the endpoint, key and model. Blocking (keyring): call in a thread."""+def _subscription_route(+ config: Any, provider: str, model: str, *, agent_id: str, account_id: str+) -> ModelRoute:+ from jarvis.agent_runtimes import gateway++ base_url = gateway.base_url()+ if not base_url:+ raise RouteUnavailable("Jarvis' model gateway is not up yet. Try again in a moment.")+ if not gateway.subscription_ready(account_id):+ raise RouteUnavailable(+ "The ChatGPT subscription is not signed in. Connect it in Settings → API keys first."+ )+ chosen = model.strip() or _default_model(config, provider)+ if not chosen:+ # The agent was created without a model: Codex's own first pick.+ from jarvis.agent_chat.catalog import CODEX_FALLBACK_MODELS++ chosen = CODEX_FALLBACK_MODELS[0].id if CODEX_FALLBACK_MODELS else ""+ if not chosen:+ raise RouteUnavailable("Choose a ChatGPT model for this agent first.")+ return ModelRoute(+ provider=provider,+ model=chosen,+ base_url=base_url,+ transport="responses",+ api_key=gateway.grant_token(agent_id, account_id),+ )+++def route_for(+ config: Any, provider: str, model: str, *, agent_id: str = "", account_id: str = ""+) -> ModelRoute:+ """Resolve the endpoint, key and model. Blocking (keyring): call in a thread.++ ``agent_id`` / ``account_id`` matter only for the subscription route: the+ gateway token speaks for that agent on that Codex account.+ """endpoint = _ENDPOINTS.get(provider)if endpoint is None:raise RouteUnavailable(f"The {provider or 'selected'} seat cannot drive Hermes or OpenClaw. "- "Pick a model that runs on an API key or a local server."+ "Pick a model that runs on an API key, a local server or the ChatGPT "+ "subscription."+ )+ if endpoint.subscription:+ return _subscription_route(+ config, provider, model, agent_id=agent_id, account_id=account_id)from jarvis.core.config import resolve_provider_endpointdiff --git a/jarvis/agent_runtimes/openclaw.py b/jarvis/agent_runtimes/openclaw.pyindex 39a10052df..0da43a9833 100644--- a/jarvis/agent_runtimes/openclaw.py+++ b/jarvis/agent_runtimes/openclaw.py@@ -264,11 +264,10 @@ class OpenClawRuntime:"baseUrl": route.base_url,# A keyless local server still needs a non-empty value."apiKey": f"${{{KEY_ENV_VAR}}}" if route.api_key else "local",- "api": (- "anthropic-messages"- if route.transport == "anthropic_messages"- else "openai-completions"- ),+ "api": {+ "anthropic_messages": "anthropic-messages",+ "responses": "openai-responses",+ }.get(route.transport, "openai-completions"),"models": [{"id": route.model,diff --git a/jarvis/ui/web/agent_runtime_routes.py b/jarvis/ui/web/agent_runtime_routes.pyindex 4b1a6673b3..533a63fa44 100644--- a/jarvis/ui/web/agent_runtime_routes.py+++ b/jarvis/ui/web/agent_runtime_routes.py@@ -15,7 +15,11 @@ from typing import Any, Literalfrom fastapi import APIRouter, HTTPException, Requestfrom jarvis.agent_runtimes import RUNTIME_NAMES, manager-from jarvis.agent_runtimes.model_map import supported_providers, usable_providers+from jarvis.agent_runtimes.model_map import (+ subscription_providers,+ supported_providers,+ usable_providers,+)router = APIRouter(prefix="/api/agent-runtimes", tags=["agent-runtimes"])@@ -43,6 +47,7 @@ async def list_agent_runtimes(request: Request, refresh: bool = False) -> dict[s"runtimes": await manager.statuses(refresh=refresh),"supported_providers": list(_USABLE_CACHE[1]),"all_providers": sorted(supported_providers()),+ "subscription_providers": sorted(subscription_providers()),}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsxindex 6e9d928268..348a4b7fda 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx@@ -62,21 +62,25 @@ export function AgentModelPicker({ agent, busy, onSavingChange }: {const runtimes = useAgentRuntimes();const external = Boolean(agent.runtime && agent.runtime !== "jarvis");const supportedKey = (Array.isArray(runtimes.data?.supported_providers) ? runtimes.data.supported_providers : []).join(",");+ const gatewayKey = (Array.isArray(runtimes.data?.subscription_providers) ? runtimes.data.subscription_providers : []).join(",");const seats = useMemo(() => {const all = modelSeats(options, providers ?? [], live, defaultModelLabel);- // Hermes / OpenClaw run on an API key or a local model, never a subscription CLI.+ // Hermes / OpenClaw run on an API key, a local model or a subscription+ // Jarvis' model gateway serves; never a subscription CLI's own loop.if (!external || !supportedKey) return all;const supported = new Set(supportedKey.split(","));+ const gateway = new Set(gatewayKey.split(",").filter(Boolean));// A dual row (Claude: subscription CLI or API key) runs on its API key here,// so the CLI's own aliases ("opusplan", "default") are not models to offer.+ // A gateway subscription keeps its accounts: the login decides who pays.return all.filter((seat) => supported.has(seat.provider.id))- .map((seat) => seat.kind === "subscription" ? {+ .map((seat) => seat.kind === "subscription" && !gateway.has(seat.provider.id) ? {...seat,kind: "api" as const,accounts: [],provider: { ...seat.provider, curated_models: seat.provider.curated_models.filter((model) => /\d/.test(model.id)) },} : seat);- }, [options, providers, live, defaultModelLabel, external, supportedKey]);+ }, [options, providers, live, defaultModelLabel, external, supportedKey, gatewayKey]);const currentAccount = (seat: BrainSeat) => accounts[seat.provider.id] ?? (agent.provider === seat.provider.id ? agent.accountId ?? "" : "");const preferredEffort = (seat: BrainSeat, model: CuratedModel) => modelEffort(seat, model.id, seat.provider.id === agent.provider ? agent.effort : seat.provider.default_effort);// useT returns a new function each render; memoize by its actual labels.diff --git a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsxindex 4c87432e68..fb021e3c30 100644--- a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx+++ b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx@@ -25,6 +25,7 @@ const CompanionEditor = lazy(() =>/** Provider ids the runtimes route (`jarvis/agent_runtimes/model_map.py`). */const PROVIDER_NAMES: Record<string, string> = {+ "openai-codex": "OpenAI Codex","claude-api": "Anthropic Claude",openai: "OpenAI",gemini: "Google Gemini",diff --git a/jarvis/ui/web/frontend/src/components/society/data.ts b/jarvis/ui/web/frontend/src/components/society/data.tsindex 7f8c10fbf0..5682259047 100644--- a/jarvis/ui/web/frontend/src/components/society/data.ts+++ b/jarvis/ui/web/frontend/src/components/society/data.ts@@ -199,6 +199,7 @@ const PROVIDER_LABELS: Record<string, string> = {ollama: "Ollama (local)","local-openai": "Local server","claude-api": "Anthropic Claude",+ "openai-codex": "OpenAI Codex",grok: "xAI Grok",openrouter: "OpenRouter",nvidia: "NVIDIA NIM",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex bf0b7a06ef..e46caea873 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -5762,8 +5762,8 @@"type_label": "Agent-Typ","type_fixed": "Der Typ lässt sich nach dem Erstellen nicht mehr ändern.","provider_label": "Modell-Anbieter",- "provider_hint": "Hermes und OpenClaw laufen mit einem API-Schlüssel oder einem lokalen Modell. Das Modell kannst du später im Chat ändern.",- "no_provider": "Noch kein API-Schlüssel und kein lokales Modell verbunden. Füge eines unter Einstellungen → API-Schlüssel hinzu.",+ "provider_hint": "Hermes und OpenClaw laufen mit deinem ChatGPT-Abo, einem API-Schlüssel oder einem lokalen Modell. Das Modell kannst du später im Chat ändern.",+ "no_provider": "Noch kein ChatGPT-Abo, kein API-Schlüssel und kein lokales Modell verbunden. Verbinde eines unter Einstellungen → API-Schlüssel.","companion_label": "Begleiter","cancel": "Abbrechen","create": "Agent erstellen",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex d6e0d2936a..ba7a432472 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -5762,8 +5762,8 @@"type_label": "Agent type","type_fixed": "The type is fixed once the agent exists.","provider_label": "Model provider",- "provider_hint": "Hermes and OpenClaw run on an API key or a local model. The model can be changed later in the chat.",- "no_provider": "No API key or local model is connected yet. Add one in Settings → API keys.",+ "provider_hint": "Hermes and OpenClaw run on your ChatGPT subscription, an API key or a local model. The model can be changed later in the chat.",+ "no_provider": "No ChatGPT subscription, API key or local model is connected yet. Connect one in Settings → API keys.","companion_label": "Companion","cancel": "Cancel","create": "Create agent",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 3be782d896..68b88e6642 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -5762,8 +5762,8 @@"type_label": "Tipo de agente","type_fixed": "El tipo no se puede cambiar una vez creado el agente.","provider_label": "Proveedor del modelo",- "provider_hint": "Hermes y OpenClaw funcionan con una clave de API o un modelo local. El modelo se puede cambiar después en el chat.",- "no_provider": "Aún no hay ninguna clave de API ni modelo local conectados. Añade uno en Ajustes → Claves de API.",+ "provider_hint": "Hermes y OpenClaw funcionan con tu suscripción de ChatGPT, una clave de API o un modelo local. El modelo se puede cambiar después en el chat.",+ "no_provider": "Aún no hay ninguna suscripción de ChatGPT, clave de API ni modelo local conectados. Conecta uno en Ajustes → Claves de API.","companion_label": "Acompañante","cancel": "Cancelar","create": "Crear agente",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.jsonindex 252a9e092e..6de09fbcaa 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json@@ -5760,8 +5760,8 @@"type_label": "智能体类型","type_fixed": "智能体创建后类型不可更改。","provider_label": "模型提供方",- "provider_hint": "Hermes 和 OpenClaw 使用 API 密钥或本地模型运行。之后可以在聊天中更换模型。",- "no_provider": "尚未连接 API 密钥或本地模型。请在 设置 → API 密钥 中添加。",+ "provider_hint": "Hermes 和 OpenClaw 可使用你的 ChatGPT 订阅、API 密钥或本地模型运行。之后可以在聊天中更换模型。",+ "no_provider": "尚未连接 ChatGPT 订阅、API 密钥或本地模型。请在 设置 → API 密钥 中连接。","companion_label": "小伙伴","cancel": "取消","create": "创建智能体",diff --git a/jarvis/ui/web/frontend/src/lib/agentRuntimesApi.ts b/jarvis/ui/web/frontend/src/lib/agentRuntimesApi.tsindex f28bb16cfc..43cc24a051 100644--- a/jarvis/ui/web/frontend/src/lib/agentRuntimesApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agentRuntimesApi.ts@@ -41,6 +41,9 @@ export interface AgentRuntimesResponse {supported_providers: string[];/** Every provider the runtimes can drive once it is connected. */all_providers?: string[];+ /** Providers that run through Jarvis' model gateway on a subscription+ * (the account still matters there). */+ subscription_providers?: string[];}async function json<T>(url: string, init?: RequestInit): Promise<T> {diff --git a/jarvis/ui/web/runtime_gateway_routes.py b/jarvis/ui/web/runtime_gateway_routes.pynew file mode 100644index 0000000000..d8b97a157a--- /dev/null+++ b/jarvis/ui/web/runtime_gateway_routes.py@@ -0,0 +1,64 @@+"""``/api/runtime-gateway/v1`` — the model endpoint Hermes / OpenClaw agents+on a ChatGPT subscription talk to (``jarvis.agent_runtimes.gateway``).++OpenAI Responses shape (``POST /responses``, ``GET /models``) behind a+per-agent Bearer token Jarvis minted. Not part of the Control API: no person+or CLI calls it, so it stays out of the OpenAPI schema.+"""++from __future__ import annotations++from typing import Any++from fastapi import APIRouter, HTTPException, Request+from fastapi.responses import JSONResponse, StreamingResponse++from jarvis.agent_runtimes import gateway++router = APIRouter(prefix=gateway.BASE_PATH, tags=["runtime-gateway"], include_in_schema=False)+++def _grant(request: Request) -> gateway.Grant:+ scheme, _, token = (request.headers.get("authorization") or "").partition(" ")+ found = gateway.verify(token.strip()) if scheme.lower() == "bearer" else None+ if found is None:+ raise HTTPException(401, "Unknown runtime gateway token.")+ return found+++def _error(exc: gateway.GatewayError) -> JSONResponse:+ return JSONResponse(+ {"error": {"message": str(exc), "type": exc.code, "code": exc.code}},+ status_code=exc.status,+ )++[email protected]("/responses")+async def runtime_gateway_responses(request: Request) -> Any:+ """One model turn for a Hermes / OpenClaw agent, on its ChatGPT subscription."""+ grant = _grant(request)+ try:+ body = await request.json()+ except ValueError:+ return _error(gateway.GatewayError("The request body is not JSON."))+ try:+ args = gateway.request_args(body)+ if body.get("stream") is True:+ return StreamingResponse(+ gateway.stream_response(grant, args),+ media_type="text/event-stream",+ headers={"Cache-Control": "no-cache"},+ )+ return await gateway.complete_response(grant, args)+ except gateway.GatewayError as exc:+ return _error(exc)++[email protected]("/models")+async def runtime_gateway_models(request: Request) -> Any:+ """The ChatGPT models the agent's account offers."""+ grant = _grant(request)+ try:+ return {"object": "list", "data": await gateway.list_models(grant)}+ except gateway.GatewayError as exc:+ return _error(exc)diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 31d7990830..5086459152 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -478,6 +478,7 @@ class WebServer:from .agent_chat_routes import router as agent_chat_routerfrom .agent_mcp_routes import router as agent_mcp_routerfrom .agent_runtime_routes import router as agent_runtime_router+ from .runtime_gateway_routes import router as runtime_gateway_routerfrom .agentic_ide_git_routes import router as agentic_ide_git_routerfrom .agentic_ide_routes import router as agentic_ide_routerfrom .antigravity_routes import router as antigravity_router@@ -765,6 +766,7 @@ class WebServer:set_society_factory(self._build_society_runtime)app.include_router(society_router)app.include_router(agent_runtime_router)+ app.include_router(runtime_gateway_router)from .mars_routes import router as mars_routerapp.include_router(mars_router)diff --git a/jarvis/ui/web/surface_security.py b/jarvis/ui/web/surface_security.pyindex 5388f6f34e..21628db2dc 100644--- a/jarvis/ui/web/surface_security.py+++ b/jarvis/ui/web/surface_security.py@@ -43,7 +43,7 @@ Receive = Callable[[], Awaitable[dict[str, Any]]]Send = Callable[[dict[str, Any]], Awaitable[None]]ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]CredentialValidator = Callable[[str], bool]-AuthKind = Literal["control", "session", "open", "mcp"]+AuthKind = Literal["control", "session", "open", "mcp", "gateway"]Origin = tuple[str, str, int | None]_BOOTSTRAP_TOKEN_LOCK = threading.Lock()@@ -889,6 +889,22 @@ class SurfaceSecurity:log.debug("surface security: MCP token check failed", exc_info=True)return False+ #: Where a runtime gateway token counts as a credential (and nowhere else):+ #: the model endpoint Hermes / OpenClaw agents on a subscription call.+ _RUNTIME_GATEWAY_PREFIX: ClassVar[str] = "/api/runtime-gateway/"++ def _gateway_token_accepted(self, scope: Scope, bearer: str) -> bool:+ """Whether ``bearer`` is a token Jarvis minted for an agent runtime AND+ this is a gateway path. It grants one agent's model turns, never the+ Control API or the UI routes."""+ if not str(scope.get("path", "") or "").startswith(self._RUNTIME_GATEWAY_PREFIX):+ return False+ try:+ from jarvis.agent_runtimes import gateway+ except Exception: # noqa: BLE001 — no gateway module → no such credential+ return False+ return gateway.verify(bearer) is not None+def _authenticate(self, scope: Scope) -> AuthKind | None:bearer_present, bearer = _presented_bearer(scope)if bearer_present:@@ -903,6 +919,8 @@ class SurfaceSecurity:return Noneif self._mcp_token_accepted(scope, bearer):return "mcp"+ if self._gateway_token_accepted(scope, bearer):+ return "gateway"try:return "session" if self._session_validator(bearer) else Noneexcept Exception:diff --git a/scripts/spikes/agent_runtimes_subscription_e2e.py b/scripts/spikes/agent_runtimes_subscription_e2e.pynew file mode 100644index 0000000000..07afdea579--- /dev/null+++ b/scripts/spikes/agent_runtimes_subscription_e2e.py@@ -0,0 +1,210 @@+"""Live check: a Hermes / OpenClaw agent on the ChatGPT subscription.++Starts Jarvis' model gateway (``jarvis.ui.web.runtime_gateway_routes``) behind+the real ``SurfaceSecurity`` guard on a free loopback port, then runs two+turns of a real runtime through Jarvis' own driver against it. The model+calls go to the person's ChatGPT subscription through the selected Codex+account — no API key is used and the runtime never sees the login. Two+model calls per run; all runtime state lands in a temporary folder.++ python scripts/spikes/agent_runtimes_subscription_e2e.py hermes [model]+ python scripts/spikes/agent_runtimes_subscription_e2e.py openclaw [model]+ python scripts/spikes/agent_runtimes_subscription_e2e.py hermes --replay++``--replay`` keeps ChatGPT out of it (no allowance used): the gateway answers+from a stand-in in the subscription's own event format.+"""++from __future__ import annotations++import asyncio+import socket+import sys+import tempfile+import threading+import time+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT))+sys.path.insert(0, str(ROOT / "scripts" / "spikes"))++from agent_runtimes_e2e import _run # noqa: E402++from jarvis.agent_runtimes import base, driver, gateway # noqa: E402+from jarvis.agent_runtimes.base import RuntimeTurn # noqa: E402+from jarvis.agent_runtimes.model_map import ModelRoute # noqa: E402+from jarvis.core import runtime_refs # noqa: E402+++def _free_port() -> int:+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ return int(sock.getsockname()[1])+++def _serve(port: int) -> None:+ import uvicorn+ from fastapi import FastAPI++ from jarvis.ui.web.runtime_gateway_routes import router+ from jarvis.ui.web.surface_security import SurfaceSecurity++ app = FastAPI()+ app.include_router(router)+ guarded = SurfaceSecurity(app, control_key_validator=lambda token: False)+ config = uvicorn.Config(guarded, host="127.0.0.1", port=port, log_level="warning")+ threading.Thread(target=uvicorn.Server(config).run, daemon=True).start()+ for _ in range(100):+ with socket.socket() as sock:+ if sock.connect_ex(("127.0.0.1", port)) == 0:+ return+ time.sleep(0.05)+ raise RuntimeError("the gateway did not start")+++class _ReplayUpstream:+ """``--replay``: answers in the subscription's Responses event format+ without calling ChatGPT, to check the runtime side when the allowance is+ used up. It remembers a word the way a model reading its history would."""++ @staticmethod+ def _texts(items: list[dict], role: str = "") -> list[str]:+ out: list[str] = []+ for item in items:+ if role and item.get("role") != role:+ continue+ content = item.get("content")+ if isinstance(content, str):+ out.append(content)+ continue+ for part in content or []:+ if isinstance(part, dict) and isinstance(part.get("text"), str):+ out.append(part["text"])+ return out++ async def stream(self, **kwargs): # noqa: ANN003, ANN201 — mirrors SubscriptionReasoning+ texts = self._texts(kwargs["input"])+ # The first turn has no earlier answer in its history; the second+ # must find the word there.+ if not self._texts(kwargs["input"], "assistant"):+ answer = "READY"+ else:+ answer = "PELICAN" if any("PELICAN" in text for text in texts) else "UNKNOWN"+ message = {+ "id": "msg_1",+ "type": "message",+ "role": "assistant",+ "status": "completed",+ "content": [{"type": "output_text", "text": answer, "annotations": []}],+ }+ response = {"id": "resp_1", "object": "response", "model": kwargs["model"]}+ yield {"type": "response.created", "response": {**response, "status": "in_progress"}}+ yield {+ "type": "response.output_item.added",+ "output_index": 0,+ "item": {**message, "status": "in_progress", "content": []},+ }+ yield {+ "type": "response.content_part.added",+ "item_id": "msg_1",+ "output_index": 0,+ "content_index": 0,+ "part": {"type": "output_text", "text": "", "annotations": []},+ }+ yield {+ "type": "response.output_text.delta",+ "item_id": "msg_1",+ "output_index": 0,+ "content_index": 0,+ "delta": answer,+ }+ yield {+ "type": "response.output_text.done",+ "item_id": "msg_1",+ "output_index": 0,+ "content_index": 0,+ "text": answer,+ }+ yield {"type": "response.output_item.done", "output_index": 0, "item": message}+ yield {+ "type": "response.completed",+ "response": {+ **response,+ "status": "completed",+ "output": [message],+ "usage": {"input_tokens": 10, "output_tokens": 2, "total_tokens": 12},+ },+ }++ async def list_models(self) -> list[dict]:+ return [{"id": "gpt-replay", "label": "Replay"}]+++async def _pick_model(wanted: str) -> str:+ if wanted:+ return wanted+ rows = await gateway._client("").list_models() # noqa: SLF001 — a catalog call, no inference+ ids = [row["id"] for row in rows]+ light = [model for model in ids if any(word in model for word in ("luna", "mini", "spark"))]+ return (light or ids)[0]+++async def main(name: str, wanted: str) -> int:+ replay = wanted == "--replay"+ if replay:+ wanted = "gpt-replay"+ upstream = _ReplayUpstream()+ gateway._client = lambda account_id: upstream # noqa: SLF001 — the spike's stand-in+ elif not gateway.subscription_ready():+ print("The ChatGPT subscription is not signed in on this computer.")+ return 2+ tmp = Path(tempfile.mkdtemp(prefix=f"jarvis-{name}-sub-e2e-"))+ base.runtimes_root = lambda: tmp / "agent_runtimes"+ workspace = tmp / "workspace"+ workspace.mkdir()+ status = driver(name).detect(refresh=True)+ print("detect:", status.ready, status.problem)+ if not status.ready:+ return 2+ port = _free_port()+ _serve(port)+ runtime_refs.set_api_base_url(f"http://127.0.0.1:{port}")+ model = await _pick_model(wanted)+ print("model:", model)+ route = ModelRoute(+ "openai-codex",+ model,+ gateway.base_url() or "",+ "responses",+ gateway.grant_token("sub-e2e-agent"),+ )+ turn = RuntimeTurn(+ agent_id="sub-e2e-agent",+ agent_name="Probe",+ session_id="society:sub-e2e-agent",+ workspace=workspace,+ route=route,+ resume=None,+ auto_approve=True,+ mcp_url=None,+ control_key=None,+ )+ first, _io1 = await _run(name, turn, "Remember the word PELICAN. Reply with exactly: READY")+ print("turn 1:", first.status, first.error, repr(first.result_text[:120]))+ turn.resume = first.vendor_session+ second, _io2 = await _run(name, turn, "Which word did I ask you to remember? One word.")+ print("turn 2:", second.status, second.error, repr(second.result_text[:120]))+ await driver(name).stop()+ ok = (+ first.status == "done"+ and second.status == "done"+ and "pelican" in second.result_text.lower()+ )+ print("RESULT:", "PASS" if ok else "FAIL")+ return 0 if ok else 1+++if __name__ == "__main__":+ runtime = sys.argv[1] if len(sys.argv) > 1 else "hermes"+ sys.exit(asyncio.run(main(runtime, sys.argv[2] if len(sys.argv) > 2 else "")))diff --git a/tests/unit/agent_runtimes/test_runtime_configs.py b/tests/unit/agent_runtimes/test_runtime_configs.pyindex b08f4bd44e..41fff6d1f4 100644--- a/tests/unit/agent_runtimes/test_runtime_configs.py+++ b/tests/unit/agent_runtimes/test_runtime_configs.py@@ -169,6 +169,12 @@ def test_openclaw_anthropic_route_uses_the_messages_adapter(tmp_path):assert config["models"]["providers"]["jarvis"]["api"] == "anthropic-messages"+def test_openclaw_subscription_route_uses_the_responses_adapter(tmp_path):+ route = _route(transport="responses")+ config = OpenClawRuntime().config_for(_turn(tmp_path, route=route), port=1, token=_TOKEN)+ assert config["models"]["providers"]["jarvis"]["api"] == "openai-responses"++def test_openclaw_without_tools_writes_no_mcp_server(tmp_path):config = OpenClawRuntime().config_for(_turn(tmp_path, mcp_url=None, control_key=None), port=1, token=_TOKEN@@ -224,11 +230,23 @@ def _cfg(**providers) -> SimpleNamespace:)-def test_subscription_seats_are_not_offered():+def test_only_the_chatgpt_subscription_runs_through_jarvis_gateway(monkeypatch):+ from jarvis.agent_runtimes import gateway+assert supports("openai") and supports("claude-api") and supports("ollama")- assert not supports("openai-codex") and not supports("grok-build")- with pytest.raises(RouteUnavailable):- route_for(_cfg(), "openai-codex", "gpt-5.5")+ assert supports("openai-codex") and not supports("grok-build")+ monkeypatch.setattr(gateway, "base_url", lambda: "http://127.0.0.1:47821/api/runtime-gateway/v1")+ monkeypatch.setattr(gateway, "subscription_ready", lambda account_id="": False)+ with pytest.raises(RouteUnavailable, match="not signed in"):+ route_for(_cfg(), "openai-codex", "gpt-5.5", agent_id="agent-1")+ monkeypatch.setattr(gateway, "subscription_ready", lambda account_id="": True)+ gateway.reset()+ route = route_for(_cfg(), "openai-codex", "gpt-5.5", agent_id="agent-1", account_id="acct")+ assert route.transport == "responses"+ assert route.base_url == "http://127.0.0.1:47821/api/runtime-gateway/v1"+ # The runtime holds a token for this agent, never the subscription login.+ assert gateway.verify(route.api_key or "") == gateway.Grant("agent-1", "acct")+ gateway.reset()def test_an_api_key_provider_routes_with_its_saved_key():@@ -261,7 +279,12 @@ def test_hermes_restore_finds_the_key_under_its_host_name():assert _restore_key_aliases("https://integrate.api.nvidia.com/v1", "k") == {"NVIDIA_API_KEY": "k"}- assert _restore_key_aliases("http://127.0.0.1:11434/v1", "k") == {}+ # Jarvis' own gateway: the key pairs with exactly that base URL.+ assert _restore_key_aliases("http://127.0.0.1:47821/api/runtime-gateway/v1", "k") == {+ "OPENAI_BASE_URL": "http://127.0.0.1:47821/api/runtime-gateway/v1",+ "OPENAI_API_KEY": "k",+ }+ assert _restore_key_aliases("http://127.0.0.1:11434/v1", None) == {}assert _restore_key_aliases("https://api.openai.com/v1", None) == {}diff --git a/tests/unit/agent_runtimes/test_runtime_gateway.py b/tests/unit/agent_runtimes/test_runtime_gateway.pynew file mode 100644index 0000000000..f8e410d4d5--- /dev/null+++ b/tests/unit/agent_runtimes/test_runtime_gateway.py@@ -0,0 +1,163 @@+"""Jarvis' model gateway: Hermes / OpenClaw agents on the ChatGPT subscription.++The gateway is reached the way a runtime reaches it — through the real+``SurfaceSecurity`` guard with a Bearer and no Origin — because a credential+the guard does not know would be refused before any route ran.+"""++from __future__ import annotations++import json+from collections.abc import AsyncIterator+from typing import Any++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.agent_runtimes import gateway+from jarvis.live.subscription_reasoning import SubscriptionReasoningError+from jarvis.ui.web.runtime_gateway_routes import router+from jarvis.ui.web.surface_security import SurfaceSecurity++_EVENTS = [+ {"type": "response.created", "response": {"id": "r1"}},+ {"type": "response.output_text.delta", "delta": "Hello"},+ {+ "type": "response.completed",+ "response": {"id": "r1", "status": "completed", "output": [{"type": "message"}]},+ },+]+++class FakeSubscription:+ """Stands in for ``SubscriptionReasoning``: records the call, replays events."""++ def __init__(self, *, fail_after: int | None = None) -> None:+ self.calls: list[dict[str, Any]] = []+ self.fail_after = fail_after++ async def stream(self, **kwargs: Any) -> AsyncIterator[dict[str, Any]]:+ self.calls.append(kwargs)+ for index, event in enumerate(_EVENTS):+ if self.fail_after is not None and index == self.fail_after:+ raise SubscriptionReasoningError("The ChatGPT login expired.", code="login")+ yield event++ async def list_models(self) -> list[dict[str, Any]]:+ return [{"id": "gpt-5.6-sol", "label": "GPT-5.6 Sol"}]+++def fake(monkeypatch: pytest.MonkeyPatch) -> FakeSubscription:+ gateway.reset()+ client = FakeSubscription()+ monkeypatch.setattr(gateway, "_client", lambda account_id: client)+ yield client+ gateway.reset()+++def guarded() -> TestClient:+ app = FastAPI()+ app.include_router(router)++ @app.post("/api/settings/danger")+ def _settings() -> dict[str, str]:+ return {"changed": "yes"}++ return TestClient(SurfaceSecurity(app, control_key_validator=lambda token: False))+++def _post(client: TestClient, token: str, body: dict[str, Any], path: str = "/responses") -> Any:+ return client.post(+ f"{gateway.BASE_PATH}{path}", headers={"Authorization": f"Bearer {token}"}, json=body+ )+++def test_tokens_are_per_agent_and_stable() -> None:+ gateway.reset()+ first = gateway.grant_token("agent-1", "acct")+ assert gateway.grant_token("agent-1", "acct") == first+ assert gateway.grant_token("agent-2", "acct") != first+ assert gateway.verify(first) == gateway.Grant("agent-1", "acct")+ assert gateway.verify("jrg_made-up") is None+ assert gateway.verify("sk-anything") is None+++def test_a_request_is_rebuilt_field_by_field() -> None:+ args = gateway.request_args(+ {+ "model": "gpt-5.6-sol",+ "input": "Hi",+ "instructions": "Be brief.",+ "tools": [+ {"type": "function", "function": {"name": "a", "parameters": {"type": "object"}}},+ {"type": "function", "name": "b", "description": "B"},+ {"type": "web_search"},+ ],+ "reasoning": {"effort": "high"},+ "store": True,+ "temperature": 0.2,+ "previous_response_id": "r0",+ }+ )+ assert args["model"] == "gpt-5.6-sol"+ assert args["input"] == [{"role": "user", "content": [{"type": "input_text", "text": "Hi"}]}]+ assert [tool["name"] for tool in args["tools"]] == ["a", "b"]+ assert all(tool["type"] == "function" for tool in args["tools"])+ assert args["reasoning_effort"] == "high"+ assert set(args) == {"model", "input", "instructions", "tools", "reasoning_effort"}+ with pytest.raises(gateway.GatewayError):+ gateway.request_args({"input": "no model"})+++def test_a_runtime_streams_through_the_guard_without_an_origin(fake, guarded) -> None:+ token = gateway.grant_token("agent-1")+ answer = _post(guarded, token, {"model": "gpt-5.6-sol", "input": "Hi", "stream": True})+ assert answer.status_code == 200, answer.text+ assert answer.headers["content-type"].startswith("text/event-stream")+ frames = [json.loads(line[5:]) for line in answer.text.splitlines() if line.startswith("data:")]+ assert [frame["type"] for frame in frames] == [event["type"] for event in _EVENTS]+ assert fake.calls[0]["model"] == "gpt-5.6-sol"+++def test_a_runtime_that_does_not_stream_gets_the_finished_response(fake, guarded) -> None:+ token = gateway.grant_token("agent-1")+ answer = _post(guarded, token, {"model": "gpt-5.6-sol", "input": "Hi"})+ assert answer.status_code == 200+ assert answer.json()["id"] == "r1"+++def test_a_failure_mid_stream_arrives_as_response_failed(fake, guarded) -> None:+ fake.fail_after = 2+ token = gateway.grant_token("agent-1")+ answer = _post(guarded, token, {"model": "gpt-5.6-sol", "input": "Hi", "stream": True})+ frames = [json.loads(line[5:]) for line in answer.text.splitlines() if line.startswith("data:")]+ assert frames[-1]["type"] == "response.failed"+ assert "login expired" in frames[-1]["response"]["error"]["message"]+++def test_models_are_listed_in_the_openai_shape(fake, guarded) -> None:+ token = gateway.grant_token("agent-1")+ answer = guarded.get(+ f"{gateway.BASE_PATH}/models", headers={"Authorization": f"Bearer {token}"}+ )+ assert answer.json() == {+ "object": "list",+ "data": [{"id": "gpt-5.6-sol", "object": "model", "owned_by": "openai"}],+ }+++def test_an_unknown_token_is_refused(fake, guarded) -> None:+ answer = _post(guarded, "jrg_not-minted", {"model": "m", "input": "Hi"})+ assert answer.status_code == 401+ assert fake.calls == []+++def test_a_gateway_token_opens_nothing_but_the_gateway(fake, guarded) -> None:+ token = gateway.grant_token("agent-1")+ answer = guarded.post(+ "/api/settings/danger", headers={"Authorization": f"Bearer {token}"}, json={}+ )+ assert answer.status_code == 401diff --git a/tests/unit/agent_runtimes/test_runtime_manager.py b/tests/unit/agent_runtimes/test_runtime_manager.pyindex 02932c479f..15d57e53dd 100644--- a/tests/unit/agent_runtimes/test_runtime_manager.py+++ b/tests/unit/agent_runtimes/test_runtime_manager.py@@ -156,7 +156,8 @@ def test_routes_list_status_and_start_jobs(fakes):assert "openai" in body["supported_providers"]assert "claude-api" not in body["supported_providers"]assert "claude-api" in body["all_providers"]- assert "openai-codex" not in body["all_providers"]+ assert "openai-codex" in body["all_providers"]+ assert body["subscription_providers"] == ["openai-codex"]rows = body["runtimes"]assert [row["runtime"] for row in rows] == ["hermes", "openclaw"]assert rows[0]["ready"] is True and rows[0]["job"] is None