Skip to content

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.

feat(agent-runtimes): route every Hermes and OpenClaw model call through Jarvis

rubenluetke10-beep9211273e517c
diff --git a/docs/agent-runtimes.md b/docs/agent-runtimes.md
index 5bcfea5cd7..6214276c90 100644
--- a/docs/agent-runtimes.md
+++ b/docs/agent-runtimes.md
@@ -37,44 +37,63 @@ Nobody installs Hermes or OpenClaw by hand (`jarvis/agent_runtimes/manager.py`):
None of this calls a model, so setup and updates never spend a key.
-## Models
-
-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`.
+## Models: Jarvis' model gateway
+
+An agent on Hermes or OpenClaw never talks to a model vendor. Its runtime is
+configured with exactly one provider — Jarvis — and Jarvis answers every model
+call with its own provider plugins (`gateway.py`,
+`ui/web/runtime_gateway_routes.py`, routes in `model_map.py`):
+
+- **One endpoint, two long-stable shapes.** `/api/runtime-gateway/v1` on
+ Jarvis' loopback server: `POST /chat/completions` for every API-key and
+ local provider (Hermes `transport: chat_completions`, OpenClaw
+ `api: openai-completions`), `POST /responses` for the ChatGPT subscription
+ (Hermes `transport: responses`, OpenClaw `api: openai-responses`),
+ `GET /models` from Jarvis' catalog (the subscription asks its account). The
+ runtime config is the same for every provider, which is what keeps it
+ working across Hermes and OpenClaw updates.
+- **Every connected provider works.** The dialog lists what can answer right
+ now — a signed-in subscription first, then each provider with a saved key
+ (the Agents-tier key wins, as for Jarvis' own agents) or a local server
+ with an address. A new provider plugin in Jarvis is new to the runtimes too.
+- **Keys and logins stay in Jarvis.** The runtime gets a per-agent token
+ (`jrg_…`, process environment only); `SurfaceSecurity` accepts it on
+ `/api/runtime-gateway/` and nowhere else. Hermes finds it again on session
+ restore through `OPENAI_BASE_URL` = the gateway URL.
+- **Translation.** A Chat Completions request becomes a `BrainRequest`
+ (system text, messages with tool calls and results, function tools, max
+ tokens, effort); the plugin's stream becomes Chat Completions chunks with
+ tool calls and usage. Gemini's thought signature, which the OpenAI shape has
+ no field for, is kept per tool-call id and sent back with the call. The
+ plugin runs in a task of its own and hands deltas over a queue: its key
+ override and cost caller are context variables, and a streamed response is
+ read by another task.
+- **Failures.** A provider error before the first token becomes an HTTP
+ status the runtime backs off on (429 rate limit, 401 refused key, 502
+ otherwise); after streaming began it is an `error` chunk. Either way the
+ message is Jarvis' own, never the provider's body.
+- **Costs.** Every call goes through the plugin, so it lands in the cost
+ ledger (caller `agent-runtime`).
+- **ChatGPT subscription.** Handing the 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. The gateway answers with Jarvis' subscription client on the
+ agent's Codex account, whose refresh is coordinated in one place
+ (`live/subscription_auth.py`); a failure mid-stream is `response.failed`.
+- **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 not an API key, so
+ that slot counts as empty.
+
+`scripts/spikes/agent_runtimes_gateway_e2e.py <runtime> <provider> [model]`
+runs two real turns through the gateway (route built by `route_for`, the real
+guard in front); `--replay` answers the subscription from a stand-in in its
+event format. Verified 2026-10-06: Hermes and OpenClaw on a local Ollama model
+(`qwen3.5:9b`) and on the subscription with `--replay` — answer streamed,
+history carried into the second turn, no error chunk. Against the live
+subscription the account was at its usage limit; that error reached Hermes as
+`response.failed`. API-key providers share the plugin path with Ollama but
+were not called live (no paid test calls).
The runtime decides which agent loop, native tools and session store a turn
uses. Everything that makes a Jarvis agent stays in Jarvis and is identical
@@ -123,7 +142,8 @@ replayed during `session/load` is swallowed because the chat already shows it.
- **Config Jarvis writes** (`config.yaml`): `model.provider` / `model.default` /
`model.base_url`, `terminal.cwd` = the agent workspace, Hermes' own memory
and skill nudges off (Jarvis owns memory and skills), and `SOUL.md` = the
- agent's Jarvis briefing. Provider keys go into the process environment only.
+ agent's Jarvis briefing. The only key is the gateway token, in the process
+ environment.
- **Jarvis tools:** passed per session in `session/new` / `session/load`
`mcpServers` (HTTP with headers); `HERMES_ACP_SKIP_CONFIGURED_MCP=1` keeps
any configured servers out. Hermes names them `mcp__jarvis__<tool>`.
@@ -133,10 +153,9 @@ replayed during `session/load` is swallowed because the chat already shows it.
retries fresh with the transcript in front.
- **Session restore and the key:** Hermes rebuilds a reopened session from the
stored `custom` provider and base URL, without the named provider's
- `key_env`. Jarvis therefore also writes `model.base_url` and passes the key
- under the name that path reads (`OPENAI_API_KEY`, `OPENROUTER_API_KEY`, or
- `<VENDOR>_API_KEY` derived from the host), in that one process' environment
- only. A keyless local server gets Hermes' `no-key-required` placeholder.
+ `key_env`. Jarvis therefore also writes `model.base_url` and passes the
+ gateway token as `OPENAI_API_KEY` with `OPENAI_BASE_URL` = the gateway URL,
+ the pair that path reads, in that one process' environment only.
- **Tool search:** Hermes defers MCP schemas behind its own `tool_search` by
default; OpenClaw does the same for local models. Both are switched off for
agent profiles (`tools.tool_search: false`, `tools.toolSearch: false`): in a
diff --git a/jarvis/agent_runtimes/gateway.py b/jarvis/agent_runtimes/gateway.py
index c01fdfef01..d02aaa3820 100644
--- a/jarvis/agent_runtimes/gateway.py
+++ b/jarvis/agent_runtimes/gateway.py
@@ -1,28 +1,42 @@
-"""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.
+"""Jarvis' model gateway: the one model provider Hermes / OpenClaw agents see.
+
+A Hermes or OpenClaw agent never talks to a model vendor itself. Its runtime
+is configured with exactly one provider — Jarvis, on the app's own loopback
+server (``/api/runtime-gateway/v1``) — and a per-agent token Jarvis minted.
+Jarvis answers with the same provider plugins its own agents use
+(``jarvis.plugins.brain.*``), so every provider connected in Jarvis works on
+every runtime, keys never leave the Jarvis process, every call lands in the
+cost ledger, and a runtime update can only ever meet the long-stable OpenAI
+wire shapes:
+
+* ``POST /chat/completions`` — every API-key and local provider. The request
+ is translated into a ``BrainRequest`` (system text, messages, function
+ tools, effort) and the plugin's stream back into Chat Completions chunks.
+* ``POST /responses`` — the ChatGPT subscription. Handing the 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, and the
+ person's own Codex login with it). Jarvis' subscription client
+ (``jarvis.live.subscription_reasoning``) answers on the agent's Codex
+ account, whose refresh is coordinated in one place.
+* ``GET /models`` — the models the agent's provider offers.
+
+Only function tools pass through, and the runtime executes its own tools.
+Requests are rebuilt field by field, so a runtime option a provider does not
+accept never reaches it. Provider failures reach the runtime as a plain
+message and an HTTP status it can back off on, never as a provider's body.
"""
from __future__ import annotations
+import asyncio
+import contextlib
import json
import logging
import secrets
import threading
+import time
+import uuid
+from collections import OrderedDict
from collections.abc import AsyncIterator
from dataclasses import dataclass
from typing import Any, Final
@@ -49,11 +63,12 @@ class GatewayError(Exception):
@dataclass(frozen=True, slots=True)
class Grant:
- """Who a gateway token speaks for."""
+ """Who a gateway token speaks for, and on which Jarvis provider."""
agent_id: str
- #: The Codex account (``jarvis.agent_accounts``); "" = the active one.
- account_id: str
+ provider: str
+ #: The provider account (``jarvis.agent_accounts``); "" = the active one.
+ account_id: str = ""
_LOCK = threading.Lock()
@@ -61,11 +76,23 @@ _GRANTS: dict[str, Grant] = {}
_TOKENS: dict[Grant, str] = {}
_CLIENTS: dict[str, Any] = {}
+#: Gemini's thought signature per tool call id: the OpenAI wire shape has no
+#: field for it, and the next request must carry it back with the call.
+_SIGNATURES: OrderedDict[str, str] = OrderedDict()
+_SIGNATURES_MAX: Final[int] = 4096
-def grant_token(agent_id: str, account_id: str = "") -> str:
+#: The finish reasons a Chat Completions client knows.
+_FINISH: Final[dict[str, str]] = {"max_tokens": "length", "length": "length"}
+
+_EFFORTS: Final[frozenset[str]] = frozenset(
+ {"none", "minimal", "low", "medium", "high", "xhigh", "max"}
+)
+
+
+def grant_token(agent_id: str, provider: 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)
+ grant = Grant(agent_id, provider, account_id)
with _LOCK:
token = _TOKENS.get(grant)
if token is None:
@@ -208,7 +235,17 @@ async def complete_response(grant: Grant, args: dict[str, Any]) -> dict[str, Any
async def list_models(grant: Grant) -> list[dict[str, Any]]:
- """The account's ChatGPT models, in the OpenAI ``/models`` shape."""
+ """The models the grant's provider offers, in the OpenAI ``/models`` shape.
+
+ The subscription asks its account; every other provider answers from
+ Jarvis' own catalog, so listing never spends a call.
+ """
+ if grant.provider != SUBSCRIPTION_PROVIDER:
+ from jarvis.agent_chat.catalog import provider_row
+
+ row = provider_row(grant.provider)
+ models = [model.id for model in row.curated_models] if row is not None else []
+ return [{"id": model, "object": "model", "owned_by": grant.provider} for model in models]
from jarvis.live.subscription_auth import SubscriptionAuthError
from jarvis.live.subscription_reasoning import SubscriptionReasoningError
@@ -223,9 +260,352 @@ async def list_models(grant: Grant) -> list[dict[str, Any]]:
]
+# ------------------------------------------------- chat completions (API keys)
+
+
+def _parts(content: Any) -> list[dict[str, Any]]:
+ if isinstance(content, str):
+ return [{"type": "text", "text": content}]
+ return [part for part in content or [] if isinstance(part, dict)]
+
+
+def _text(content: Any) -> str:
+ return "".join(
+ str(part.get("text") or "")
+ for part in _parts(content)
+ if part.get("type") in ("text", "input_text", "output_text")
+ )
+
+
+def _images(content: Any) -> tuple[Any, ...]:
+ """Inline images (``data:`` URLs); a remote URL is not fetched."""
+ from jarvis.core.protocols import ImageBlock
+
+ out: list[ImageBlock] = []
+ for part in _parts(content):
+ if part.get("type") != "image_url":
+ continue
+ url = part.get("image_url")
+ url = url.get("url") if isinstance(url, dict) else url
+ if isinstance(url, str) and url.startswith("data:") and ";base64," in url:
+ mime, _, data = url[5:].partition(";base64,")
+ out.append(ImageBlock(mime=mime or "image/png", data_b64=data))
+ return tuple(out)
+
+
+def _arguments(raw: Any) -> dict[str, Any]:
+ if isinstance(raw, dict):
+ return raw
+ try:
+ parsed = json.loads(raw) if isinstance(raw, str) and raw.strip() else {}
+ except ValueError:
+ return {}
+ return parsed if isinstance(parsed, dict) else {}
+
+
+def _remember_signature(call_id: str, signature: str) -> None:
+ with _LOCK:
+ _SIGNATURES[call_id] = signature
+ _SIGNATURES.move_to_end(call_id)
+ while len(_SIGNATURES) > _SIGNATURES_MAX:
+ _SIGNATURES.popitem(last=False)
+
+
+def _signature(call_id: str) -> str:
+ with _LOCK:
+ return _SIGNATURES.get(call_id, "")
+
+
+def chat_request(body: Any) -> tuple[str, Any]:
+ """``(model, BrainRequest)`` for one Chat Completions request body."""
+ from jarvis.core.protocols import BrainMessage, BrainRequest
+
+ 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_messages = body.get("messages")
+ if not isinstance(raw_messages, list) or not raw_messages:
+ raise GatewayError("The request has no messages.")
+ system: list[str] = []
+ messages: list[BrainMessage] = []
+ for message in raw_messages:
+ if not isinstance(message, dict):
+ raise GatewayError("Every message must be a JSON object.")
+ role = message.get("role")
+ content = message.get("content")
+ if role in ("system", "developer"):
+ if text := _text(content):
+ system.append(text)
+ elif role == "user":
+ messages.append(BrainMessage("user", _text(content), images=_images(content)))
+ elif role == "assistant":
+ blocks: list[dict[str, Any]] = []
+ if text := _text(content):
+ blocks.append({"type": "text", "text": text})
+ for call in message.get("tool_calls") or []:
+ if not isinstance(call, dict):
+ continue
+ function = call.get("function") if isinstance(call.get("function"), dict) else {}
+ call_id = str(call.get("id") or f"call_{uuid.uuid4().hex[:8]}")
+ block: dict[str, Any] = {
+ "type": "tool_use",
+ "id": call_id,
+ "name": str(function.get("name") or ""),
+ "input": _arguments(function.get("arguments")),
+ }
+ if signature := _signature(call_id):
+ block["thought_signature"] = signature
+ blocks.append(block)
+ if blocks:
+ only_text = all(block["type"] == "text" for block in blocks)
+ folded = "".join(b["text"] for b in blocks) if only_text else blocks
+ messages.append(BrainMessage("assistant", folded))
+ elif role == "tool":
+ messages.append(
+ BrainMessage(
+ "tool",
+ _text(content) if not isinstance(content, str) else content,
+ tool_call_id=str(message.get("tool_call_id") or ""),
+ name=message.get("name") if isinstance(message.get("name"), str) else None,
+ )
+ )
+ tools: list[dict[str, Any]] = []
+ for tool in body.get("tools") or []:
+ found = _function_tool(tool)
+ if found is not None:
+ tools.append(
+ {
+ "name": found["name"],
+ "description": found.get("description", ""),
+ "input_schema": found["parameters"],
+ }
+ )
+ limit = body.get("max_completion_tokens") or body.get("max_tokens") or 8192
+ temperature = body.get("temperature")
+ reasoning = body.get("reasoning") if isinstance(body.get("reasoning"), dict) else {}
+ effort = body.get("reasoning_effort") or reasoning.get("effort")
+ return model.strip(), BrainRequest(
+ messages=tuple(messages),
+ tools=tuple(tools),
+ system="\n\n".join(system) or None,
+ temperature=float(temperature) if isinstance(temperature, int | float) else 0.7,
+ max_tokens=max(1, min(int(limit) if isinstance(limit, int) else 8192, 128_000)),
+ stream=True,
+ reasoning_effort=effort if effort in _EFFORTS else None,
+ )
+
+
+def _failure(provider: str, exc: Exception) -> GatewayError:
+ """A provider error as a status the runtime can back off on, and a plain
+ message — never the provider's own response body."""
+ status = getattr(exc, "status_code", None) or getattr(exc, "status", None)
+ if not isinstance(status, int):
+ response = getattr(exc, "response", None)
+ status = getattr(response, "status_code", None)
+ if status == 429:
+ return GatewayError(
+ f"{provider} is rate-limiting this key; try again shortly.",
+ status=429,
+ code="rate_limited",
+ )
+ if status in (401, 403):
+ return GatewayError(
+ f"{provider} refused the saved key. Check it in Settings → API keys.",
+ status=401,
+ code="provider_auth",
+ )
+ return GatewayError(
+ f"{provider} could not answer ({type(exc).__name__}).",
+ status=502,
+ code="provider_error",
+ )
+
+
+_DONE: Final = object()
+
+
+async def _deltas(grant: Grant, model: str, request: Any) -> AsyncIterator[Any]:
+ """The provider plugin's stream, with the Agents-tier key and cost caller.
+
+ The plugin runs in a task of its own and hands its deltas over a queue:
+ the key override and the cost caller are context variables, and a
+ streamed response is read by a different task than the one that opened
+ it — a context variable set there could not be reset (``ValueError``).
+ """
+ from jarvis.agent_chat.runner_api import build_brain
+ from jarvis.core.config import get_jarvis_agent_secret, override_provider_secrets
+ from jarvis.costs.ledger import usage_context
+
+ queue: asyncio.Queue[Any] = asyncio.Queue(maxsize=256)
+
+ async def pump() -> None:
+ try:
+ secret = get_jarvis_agent_secret(grant.provider)
+ overrides = {grant.provider: secret} if secret else {}
+ with override_provider_secrets(overrides), usage_context("agent-runtime"):
+ brain = build_brain(grant.provider, model)
+ async for delta in brain.complete(request):
+ await queue.put(delta)
+ await queue.put(_DONE)
+ except Exception as exc: # noqa: BLE001 — handed to the reader, which reports it
+ await queue.put(exc)
+
+ task = asyncio.get_running_loop().create_task(pump())
+ try:
+ while True:
+ item = await queue.get()
+ if item is _DONE:
+ return
+ if isinstance(item, Exception):
+ raise item
+ yield item
+ finally:
+ task.cancel()
+ with contextlib.suppress(asyncio.CancelledError, Exception):
+ await task
+
+
+def _chunk(chat_id: str, model: str, delta: dict[str, Any], **extra: Any) -> bytes:
+ body: dict[str, Any] = {
+ "id": chat_id,
+ "object": "chat.completion.chunk",
+ "created": int(time.time()),
+ "model": model,
+ "choices": [{"index": 0, "delta": delta, "finish_reason": extra.pop("finish", None)}],
+ **extra,
+ }
+ return f"data: {json.dumps(body, ensure_ascii=False)}\n\n".encode()
+
+
+def _openai_usage(usage: dict[str, int]) -> dict[str, int]:
+ prompt = int(usage.get("input_tokens", 0))
+ completion = int(usage.get("output_tokens", 0))
+ return {
+ "prompt_tokens": prompt,
+ "completion_tokens": completion,
+ "total_tokens": prompt + completion,
+ }
+
+
+def _tool_call(index: int, call: dict[str, Any]) -> dict[str, Any]:
+ call_id = str(call.get("id") or f"call_{uuid.uuid4().hex[:12]}")
+ if call.get("thought_signature"):
+ _remember_signature(call_id, str(call["thought_signature"]))
+ raw = call.get("input")
+ return {
+ "index": index,
+ "id": call_id,
+ "type": "function",
+ "function": {
+ "name": str(call.get("name") or ""),
+ "arguments": raw if isinstance(raw, str) else json.dumps(raw or {}),
+ },
+ }
+
+
+async def open_chat_stream(grant: Grant, model: str, request: Any) -> AsyncIterator[bytes]:
+ """The answer as Chat Completions chunks.
+
+ The provider's first delta is awaited before this returns, so a failure
+ up front (bad key, rate limit) becomes an HTTP status the runtime can act
+ on; a failure after streaming began arrives as an ``error`` chunk.
+ """
+ stream = _deltas(grant, model, request)
+ started = time.monotonic()
+ try:
+ first = await anext(stream, None)
+ except Exception as exc: # noqa: BLE001 — becomes the runtime's HTTP error, logged below
+ log.info("runtime gateway: %s on %s failed up front (%s)", grant.agent_id,
+ grant.provider, type(exc).__name__)
+ raise _failure(grant.provider, exc) from exc
+ return _chat_chunks(grant, model, stream, first, started)
+
+
+async def _chat_chunks(
+ grant: Grant, model: str, stream: AsyncIterator[Any], first: Any, started: float
+) -> AsyncIterator[bytes]:
+ chat_id = f"chatcmpl-{uuid.uuid4().hex}"
+ usage: dict[str, int] = {}
+ calls = 0
+ finish = "stop"
+ yield _chunk(chat_id, model, {"role": "assistant", "content": ""})
+ delta = first
+ try:
+ while delta is not None:
+ if delta.content:
+ yield _chunk(chat_id, model, {"content": delta.content})
+ if delta.tool_call:
+ yield _chunk(chat_id, model, {"tool_calls": [_tool_call(calls, delta.tool_call)]})
+ calls += 1
+ if delta.usage:
+ for key, value in delta.usage.items():
+ usage[key] = usage.get(key, 0) + int(value or 0)
+ if delta.finish_reason:
+ finish = _FINISH.get(delta.finish_reason, "stop")
+ delta = await anext(stream, None)
+ except Exception as exc: # noqa: BLE001 — the stream already began: an error chunk tells the runtime
+ failure = _failure(grant.provider, exc)
+ log.info("runtime gateway: %s on %s failed mid-stream (%s)", grant.agent_id,
+ grant.provider, type(exc).__name__)
+ payload = {"error": {"message": str(failure), "type": failure.code, "code": failure.code}}
+ yield f"data: {json.dumps(payload)}\n\n".encode()
+ return
+ yield _chunk(
+ chat_id,
+ model,
+ {},
+ finish="tool_calls" if calls else finish,
+ usage=_openai_usage(usage),
+ )
+ yield b"data: [DONE]\n\n"
+ log.info(
+ "runtime gateway: %s on %s/%s answered in %.1f s (%s in, %s out, %d tool calls)",
+ grant.agent_id, grant.provider, model, time.monotonic() - started,
+ usage.get("input_tokens", 0), usage.get("output_tokens", 0), calls,
+ )
+
+
+async def complete_chat(grant: Grant, model: str, request: Any) -> dict[str, Any]:
+ """The finished ``chat.completion`` for a runtime that did not ask to stream."""
+ stream = _deltas(grant, model, request)
+ text: list[str] = []
+ calls: list[dict[str, Any]] = []
+ usage: dict[str, int] = {}
+ finish = "stop"
+ try:
+ async for delta in stream:
+ if delta.content:
+ text.append(delta.content)
+ if delta.tool_call:
+ calls.append(_tool_call(len(calls), delta.tool_call))
+ if delta.usage:
+ for key, value in delta.usage.items():
+ usage[key] = usage.get(key, 0) + int(value or 0)
+ if delta.finish_reason:
+ finish = _FINISH.get(delta.finish_reason, "stop")
+ except Exception as exc: # noqa: BLE001 — becomes the runtime's HTTP error
+ raise _failure(grant.provider, exc) from exc
+ message: dict[str, Any] = {"role": "assistant", "content": "".join(text) or None}
+ if calls:
+ message["tool_calls"] = [{k: v for k, v in call.items() if k != "index"} for call in calls]
+ return {
+ "id": f"chatcmpl-{uuid.uuid4().hex}",
+ "object": "chat.completion",
+ "created": int(time.time()),
+ "model": model,
+ "choices": [
+ {"index": 0, "message": message, "finish_reason": "tool_calls" if calls else finish}
+ ],
+ "usage": _openai_usage(usage),
+ }
+
+
def reset() -> None:
- """Forget every token and client (tests)."""
+ """Forget every token, client and remembered signature (tests)."""
with _LOCK:
_GRANTS.clear()
_TOKENS.clear()
_CLIENTS.clear()
+ _SIGNATURES.clear()
diff --git a/jarvis/agent_runtimes/model_map.py b/jarvis/agent_runtimes/model_map.py
index 221a02d11e..72df3925b4 100644
--- a/jarvis/agent_runtimes/model_map.py
+++ b/jarvis/agent_runtimes/model_map.py
@@ -1,20 +1,17 @@
"""Map a society agent's Jarvis provider + model onto an external runtime.
-Hermes and OpenClaw both accept any OpenAI-compatible endpoint and any
-Anthropic Messages endpoint as a named custom provider, with the key read
-from an environment variable. That one shape is the most basic and longest
-stable configuration either project has, so every supported Jarvis provider
-is expressed through it: the endpoint comes from
-``jarvis.core.config.resolve_provider_endpoint`` (overrides and the team
-proxy included) and the key travels only in the runtime process' environment
-as :data:`KEY_ENV_VAR` — never in a file (AP-12).
-
-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.
+Every agent on Hermes or OpenClaw reaches its model through Jarvis' own model
+gateway (``gateway.py``): the runtime is configured with one provider —
+Jarvis, on the app's loopback server — and a per-agent token in its process
+environment (:data:`KEY_ENV_VAR`). Jarvis answers with its own provider
+plugins, so the runtime never holds a vendor key or login and its config is
+the same for every provider. API-key and local providers speak Chat
+Completions; the ChatGPT subscription (``openai-codex``) speaks Responses.
+
+This module decides which providers an agent can use right now (a saved key,
+a local server with an address, a signed-in subscription) and builds the
+route. A Claude subscription is not offered: its login works only inside
+Claude Code, and Hermes would bill it as paid extra usage.
"""
from __future__ import annotations
@@ -39,29 +36,26 @@ RUNTIME_PROVIDER_NAME: Final[str] = "jarvis"
@dataclass(frozen=True, slots=True)
class _Endpoint:
- transport: Transport
#: Vendor default base URL; ``None`` = the person must configure one.
default_base_url: str | None
keyless: bool = False
- #: Appended to a configured server root (local servers store the root).
- path_suffix: str = ""
+ #: A local server: it needs a server address the person configured.
+ local_server: bool = False
#: Served by Jarvis' own model gateway on the person's subscription.
subscription: bool = False
#: Jarvis provider id (``agent_chat.catalog`` / ``core.config``) -> endpoint.
_ENDPOINTS: Final[dict[str, _Endpoint]] = {
- "claude-api": _Endpoint("anthropic_messages", "https://api.anthropic.com"),
- "openai": _Endpoint("chat_completions", "https://api.openai.com/v1"),
- "grok": _Endpoint("chat_completions", "https://api.x.ai/v1"),
- "openrouter": _Endpoint("chat_completions", "https://openrouter.ai/api/v1"),
- "nvidia": _Endpoint("chat_completions", "https://integrate.api.nvidia.com/v1"),
- "gemini": _Endpoint(
- "chat_completions", "https://generativelanguage.googleapis.com/v1beta/openai"
- ),
- "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),
+ "claude-api": _Endpoint("https://api.anthropic.com"),
+ "openai": _Endpoint("https://api.openai.com/v1"),
+ "grok": _Endpoint("https://api.x.ai/v1"),
+ "openrouter": _Endpoint("https://openrouter.ai/api/v1"),
+ "nvidia": _Endpoint("https://integrate.api.nvidia.com/v1"),
+ "gemini": _Endpoint("https://generativelanguage.googleapis.com/v1beta/openai"),
+ "ollama": _Endpoint(None, keyless=True, local_server=True),
+ "local-openai": _Endpoint(None, keyless=True, local_server=True),
+ "openai-codex": _Endpoint(None, subscription=True),
}
@@ -100,24 +94,14 @@ def supports(provider: str) -> bool:
def usable_providers(config: Any) -> list[str]:
- """Supported providers that can run right now: a saved key, or a keyless
- local server with an address. Blocking (keyring): call it in a thread.
-
- The model picker offers only these on Hermes / OpenClaw, so a Claude
- subscription without an Anthropic API key never looks like a choice.
+ """Supported providers that can run right now: a saved key, a keyless
+ local server with an address, or a signed-in subscription (listed
+ first: it spends no API key). Blocking (keyring): call it in a thread.
"""
usable: list[str] = []
- # 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)
- continue
- route_for(config, provider, "probe")
+ _checked_model(config, provider, "probe")
except RouteUnavailable: # not connected: the provider is simply not offered
continue
except Exception: # noqa: BLE001 — one unreadable provider must not empty the list
@@ -149,43 +133,9 @@ def _local_root(provider: str, configured: str | None) -> str | None:
return None
-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.
- """
+def _checked_model(config: Any, provider: str, model: str, *, account_id: str = "") -> str:
+ """The model the agent runs on, once the provider is known to be able to
+ answer; raises :class:`RouteUnavailable` with the reason in plain words."""
endpoint = _ENDPOINTS.get(provider)
if endpoint is None:
raise RouteUnavailable(
@@ -194,27 +144,40 @@ def route_for(
"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_endpoint
+ from jarvis.agent_runtimes import gateway
+
+ 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 chosen
+ from jarvis.core.config import get_jarvis_agent_secret, resolve_provider_endpoint
resolved = resolve_provider_endpoint(
provider, vendor_default_base_url=endpoint.default_base_url
)
base_url = resolved.base_url
- if endpoint.path_suffix and not resolved.via_proxy:
- root = _local_root(provider, base_url)
- base_url = f"{root}{endpoint.path_suffix}" if root else None
+ if endpoint.local_server and not resolved.via_proxy:
+ base_url = _local_root(provider, base_url)
if not base_url:
raise RouteUnavailable(
f"{provider} has no server address yet. Add it on the provider's card first."
)
- key = (resolved.credential or "").strip() or None
+ # The Agents-tier key wins over the shared one, exactly as the gateway uses it.
+ key = (get_jarvis_agent_secret(provider) or resolved.credential or "").strip() or None
if key is not None and provider == "claude-api" and key.startswith(_CLAUDE_LOGIN_PREFIX):
# A Claude subscription login saved in the API-key slot. Jarvis' own
- # seats can use it; Anthropic's API refuses it from Hermes / OpenClaw
- # ("OAuth access token is invalid"), so it is not an API key here.
+ # Claude Code seats can use it; Anthropic's API refuses it ("OAuth
+ # access token is invalid"), so it is not an API key here.
raise RouteUnavailable(
"The saved Anthropic credential is a Claude subscription login, not an "
"API key. Hermes and OpenClaw need an Anthropic API key, or pick another "
@@ -227,10 +190,25 @@ def route_for(
chosen = model.strip() or _default_model(config, provider)
if not chosen:
raise RouteUnavailable(f"Choose a model for {provider} first.")
+ return chosen
+
+
+def route_for(
+ config: Any, provider: str, model: str, *, agent_id: str = "", account_id: str = ""
+) -> ModelRoute:
+ """The agent's route through Jarvis' gateway. Blocking (keyring): call it
+ in a thread. The token speaks for ``agent_id`` on ``provider`` (and, for
+ the subscription, on that Codex ``account_id``)."""
+ chosen = _checked_model(config, provider, model, account_id=account_id)
+ 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.")
return ModelRoute(
provider=provider,
model=chosen,
- base_url=base_url.rstrip("/"),
- transport=endpoint.transport,
- api_key=key,
+ base_url=base_url,
+ transport="responses" if _ENDPOINTS[provider].subscription else "chat_completions",
+ api_key=gateway.grant_token(agent_id, provider, account_id),
)
diff --git a/jarvis/ui/web/runtime_gateway_routes.py b/jarvis/ui/web/runtime_gateway_routes.py
index d8b97a157a..921392d86d 100644
--- a/jarvis/ui/web/runtime_gateway_routes.py
+++ b/jarvis/ui/web/runtime_gateway_routes.py
@@ -1,9 +1,11 @@
-"""``/api/runtime-gateway/v1`` — the model endpoint Hermes / OpenClaw agents
-on a ChatGPT subscription talk to (``jarvis.agent_runtimes.gateway``).
+"""``/api/runtime-gateway/v1`` — the one model endpoint Hermes / OpenClaw
+agents 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.
+OpenAI wire shapes behind a per-agent Bearer token Jarvis minted:
+``POST /chat/completions`` for every API-key and local provider,
+``POST /responses`` for the ChatGPT subscription, ``GET /models``. Not part
+of the Control API: no person or CLI calls it, so it stays out of the
+OpenAPI schema.
"""
from __future__ import annotations
@@ -33,15 +35,40 @@ def _error(exc: gateway.GatewayError) -> JSONResponse:
)
+async def _body(request: Request) -> Any:
+ try:
+ return await request.json()
+ except ValueError as exc:
+ raise gateway.GatewayError("The request body is not JSON.") from exc
+
+
[email protected]("/chat/completions")
+async def runtime_gateway_chat(request: Request) -> Any:
+ """One model call for a Hermes / OpenClaw agent, on its Jarvis provider."""
+ grant = _grant(request)
+ try:
+ if grant.provider == gateway.SUBSCRIPTION_PROVIDER:
+ raise gateway.GatewayError("This agent's subscription answers on /responses.")
+ body = await _body(request)
+ model, brain_request = gateway.chat_request(body)
+ if body.get("stream") is True:
+ chunks = await gateway.open_chat_stream(grant, model, brain_request)
+ return StreamingResponse(
+ chunks, media_type="text/event-stream", headers={"Cache-Control": "no-cache"}
+ )
+ return await gateway.complete_chat(grant, model, brain_request)
+ except gateway.GatewayError as exc:
+ return _error(exc)
+
+
@router.post("/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:
+ if grant.provider != gateway.SUBSCRIPTION_PROVIDER:
+ raise gateway.GatewayError("This agent's provider answers on /chat/completions.")
+ body = await _body(request)
args = gateway.request_args(body)
if body.get("stream") is True:
return StreamingResponse(
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 5086459152..4c77580b82 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -478,7 +478,6 @@ class WebServer:
from .agent_chat_routes import router as agent_chat_router
from .agent_mcp_routes import router as agent_mcp_router
from .agent_runtime_routes import router as agent_runtime_router
- from .runtime_gateway_routes import router as runtime_gateway_router
from .agentic_ide_git_routes import router as agentic_ide_git_router
from .agentic_ide_routes import router as agentic_ide_router
from .antigravity_routes import router as antigravity_router
@@ -544,6 +543,7 @@ class WebServer:
from .provider_routes import router as provider_router
from .review_routes import router as review_router
from .routine_hooks_routes import router as routine_hooks_router
+ from .runtime_gateway_routes import router as runtime_gateway_router
from .screen_context_routes import router as screen_context_router
from .self_mod_routes import router as self_mod_router
from .sessions_routes import router as sessions_router
diff --git a/scripts/spikes/agent_runtimes_subscription_e2e.py b/scripts/spikes/agent_runtimes_gateway_e2e.py
similarity index 79%
rename from scripts/spikes/agent_runtimes_subscription_e2e.py
rename to scripts/spikes/agent_runtimes_gateway_e2e.py
index 07afdea579..8a6fa99b39 100644
--- a/scripts/spikes/agent_runtimes_subscription_e2e.py
+++ b/scripts/spikes/agent_runtimes_gateway_e2e.py
@@ -1,18 +1,20 @@
-"""Live check: a Hermes / OpenClaw agent on the ChatGPT subscription.
+"""Live check: a Hermes / OpenClaw agent through Jarvis' model gateway.
-Starts Jarvis' model gateway (``jarvis.ui.web.runtime_gateway_routes``) behind
-the real ``SurfaceSecurity`` guard on a free loopback port, then runs two
+Starts the gateway (``jarvis.ui.web.runtime_gateway_routes``) behind the
+real ``SurfaceSecurity`` guard on a free loopback port, builds the agent's
+route exactly as a chat turn does (``model_map.route_for``), and 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.
+calls go to the named Jarvis provider through Jarvis' own plugin (or, for
+``openai-codex``, the ChatGPT subscription); the runtime only ever sees the
+gateway token. Two model calls per run (a runtime may retry); 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
+ python scripts/spikes/agent_runtimes_gateway_e2e.py hermes ollama qwen3.5:9b
+ python scripts/spikes/agent_runtimes_gateway_e2e.py openclaw openai-codex
+ python scripts/spikes/agent_runtimes_gateway_e2e.py hermes openai-codex --replay
-``--replay`` keeps ChatGPT out of it (no allowance used): the gateway answers
-from a stand-in in the subscription's own event format.
+``--replay`` keeps ChatGPT out of it (no allowance used): the subscription
+answers from a stand-in in its own event format.
"""
from __future__ import annotations
@@ -33,8 +35,9 @@ 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.agent_runtimes.model_map import route_for # noqa: E402
from jarvis.core import runtime_refs # noqa: E402
+from jarvis.core.config import load_config # noqa: E402
def _free_port() -> int:
@@ -150,15 +153,12 @@ async def _pick_model(wanted: str) -> str:
return (light or ids)[0]
-async def main(name: str, wanted: str) -> int:
- replay = wanted == "--replay"
- if replay:
+async def main(name: str, provider: str, wanted: str) -> int:
+ if wanted == "--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
+ gateway.subscription_ready = lambda account_id="": True
tmp = Path(tempfile.mkdtemp(prefix=f"jarvis-{name}-sub-e2e-"))
base.runtimes_root = lambda: tmp / "agent_runtimes"
workspace = tmp / "workspace"
@@ -170,15 +170,11 @@ async def main(name: str, wanted: str) -> int:
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"),
+ model = await _pick_model(wanted) if provider == "openai-codex" else wanted
+ route = await asyncio.to_thread(
+ route_for, load_config(), provider, model, agent_id="sub-e2e-agent"
)
+ print("route:", route.provider, route.model, route.transport, route.base_url)
turn = RuntimeTurn(
agent_id="sub-e2e-agent",
agent_name="Probe",
@@ -206,5 +202,5 @@ async def main(name: str, wanted: str) -> int:
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 "")))
+ args = [*sys.argv[1:], "", "", ""]
+ sys.exit(asyncio.run(main(args[0] or "hermes", args[1] or "openai-codex", args[2])))
diff --git a/tests/unit/agent_runtimes/test_runtime_configs.py b/tests/unit/agent_runtimes/test_runtime_configs.py
index 41fff6d1f4..7ab32f2863 100644
--- a/tests/unit/agent_runtimes/test_runtime_configs.py
+++ b/tests/unit/agent_runtimes/test_runtime_configs.py
@@ -28,6 +28,20 @@ from jarvis.core.config import override_provider_secrets
_SECRET = "sk-test-" + "123" # a fake key for assertions
_TOKEN = "gw-" + "token"
+_GATEWAY = "http://127.0.0.1:47821/api/runtime-gateway/v1"
+
+
+def gateway_up(monkeypatch):
+ """Jarvis' gateway is listening, and this machine's Agents-tier keys stay out."""
+ import jarvis.core.config as config
+ from jarvis.agent_runtimes import gateway
+
+ monkeypatch.setattr(gateway, "base_url", lambda: _GATEWAY)
+ monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: None)
+ gateway.reset()
+ yield gateway
+ gateway.reset()
def _route(*, key: str | None = _SECRET, transport: str = "chat_completions") -> ModelRoute:
@@ -230,43 +244,48 @@ def _cfg(**providers) -> SimpleNamespace:
)
-def test_only_the_chatgpt_subscription_runs_through_jarvis_gateway(monkeypatch):
- from jarvis.agent_runtimes import gateway
-
+def test_every_provider_runs_through_jarvis_gateway(gateway_up, monkeypatch):
+ gateway = gateway_up
assert supports("openai") and supports("claude-api") and supports("ollama")
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")
+ with override_provider_secrets({"openai": _SECRET}):
+ route = route_for(_cfg(), "openai", "gpt-5.2", agent_id="agent-1")
+ # The runtime gets Jarvis' address and a token for this agent, never the key.
+ assert route.base_url == _GATEWAY and route.transport == "chat_completions"
+ assert route.api_key != _SECRET
+ assert gateway.verify(route.api_key or "") == gateway.Grant("agent-1", "openai")
+ assert route.env() == {KEY_ENV_VAR: route.api_key}
+
+
+def test_the_chatgpt_subscription_speaks_responses(gateway_up, monkeypatch):
+ gateway = gateway_up
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()
+ assert route.transport == "responses" and route.base_url == _GATEWAY
+ assert gateway.verify(route.api_key or "") == gateway.Grant("agent-1", "openai-codex", "acct")
-def test_an_api_key_provider_routes_with_its_saved_key():
- with override_provider_secrets({"openai": _SECRET}):
- route = route_for(_cfg(), "openai", "gpt-5.2")
- assert route.base_url == "https://api.openai.com/v1"
- assert route.api_key == _SECRET and route.env() == {KEY_ENV_VAR: _SECRET}
-
-
-def test_a_missing_key_is_reported_in_plain_words():
+def test_a_missing_key_is_reported_in_plain_words(gateway_up):
with override_provider_secrets({"openrouter": None}), pytest.raises(RouteUnavailable) as err:
route_for(_cfg(), "openrouter", "some/model")
assert "API key" in str(err.value)
-def test_claude_routes_over_the_messages_api():
+def test_a_claude_login_is_not_an_api_key(gateway_up):
+ login = "sk-ant-" + "oat01-" + "x" * 20
+ with override_provider_secrets({"claude-api": login}), pytest.raises(RouteUnavailable):
+ route_for(_cfg(), "claude-api", "claude-sonnet-5")
with override_provider_secrets({"claude-api": _SECRET}):
- route = route_for(_cfg(), "claude-api", "claude-sonnet-5")
- assert route.transport == "anthropic_messages"
- assert route.base_url == "https://api.anthropic.com"
+ assert route_for(_cfg(), "claude-api", "claude-sonnet-5").transport == "chat_completions"
+
+
+def test_no_route_before_the_gateway_is_up(gateway_up, monkeypatch):
+ monkeypatch.setattr(gateway_up, "base_url", lambda: None)
+ with override_provider_secrets({"openai": _SECRET}), pytest.raises(RouteUnavailable):
+ route_for(_cfg(), "openai", "gpt-5.2")
def test_hermes_restore_finds_the_key_under_its_host_name():
diff --git a/tests/unit/agent_runtimes/test_runtime_gateway.py b/tests/unit/agent_runtimes/test_runtime_gateway.py
index f8e410d4d5..4fdb554aa6 100644
--- a/tests/unit/agent_runtimes/test_runtime_gateway.py
+++ b/tests/unit/agent_runtimes/test_runtime_gateway.py
@@ -77,10 +77,11 @@ def _post(client: TestClient, token: str, body: dict[str, Any], path: str = "/re
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")
+ first = gateway.grant_token("agent-1", "openai-codex", "acct")
+ assert gateway.grant_token("agent-1", "openai-codex", "acct") == first
+ assert gateway.grant_token("agent-2", "openai-codex", "acct") != first
+ assert gateway.grant_token("agent-1", "openai") != first
+ assert gateway.verify(first) == gateway.Grant("agent-1", "openai-codex", "acct")
assert gateway.verify("jrg_made-up") is None
assert gateway.verify("sk-anything") is None
@@ -113,7 +114,7 @@ def test_a_request_is_rebuilt_field_by_field() -> None:
def test_a_runtime_streams_through_the_guard_without_an_origin(fake, guarded) -> None:
- token = gateway.grant_token("agent-1")
+ token = gateway.grant_token("agent-1", "openai-codex")
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")
@@ -123,7 +124,7 @@ def test_a_runtime_streams_through_the_guard_without_an_origin(fake, guarded) ->
def test_a_runtime_that_does_not_stream_gets_the_finished_response(fake, guarded) -> None:
- token = gateway.grant_token("agent-1")
+ token = gateway.grant_token("agent-1", "openai-codex")
answer = _post(guarded, token, {"model": "gpt-5.6-sol", "input": "Hi"})
assert answer.status_code == 200
assert answer.json()["id"] == "r1"
@@ -131,7 +132,7 @@ def test_a_runtime_that_does_not_stream_gets_the_finished_response(fake, guarded
def test_a_failure_mid_stream_arrives_as_response_failed(fake, guarded) -> None:
fake.fail_after = 2
- token = gateway.grant_token("agent-1")
+ token = gateway.grant_token("agent-1", "openai-codex")
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"
@@ -139,7 +140,7 @@ def test_a_failure_mid_stream_arrives_as_response_failed(fake, guarded) -> None:
def test_models_are_listed_in_the_openai_shape(fake, guarded) -> None:
- token = gateway.grant_token("agent-1")
+ token = gateway.grant_token("agent-1", "openai-codex")
answer = guarded.get(
f"{gateway.BASE_PATH}/models", headers={"Authorization": f"Bearer {token}"}
)
@@ -156,8 +157,222 @@ def test_an_unknown_token_is_refused(fake, guarded) -> None:
def test_a_gateway_token_opens_nothing_but_the_gateway(fake, guarded) -> None:
- token = gateway.grant_token("agent-1")
+ token = gateway.grant_token("agent-1", "openai-codex")
answer = guarded.post(
"/api/settings/danger", headers={"Authorization": f"Bearer {token}"}, json={}
)
assert answer.status_code == 401
+
+
+# ------------------------------------------------- chat completions (API keys)
+
+
+class _ProviderError(Exception):
+ def __init__(self, status: int) -> None:
+ super().__init__("provider body that must never reach the runtime")
+ self.status_code = status
+
+
+def brain(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
+ """Stands in for the provider plugin behind ``gateway._deltas``."""
+ from jarvis.core.protocols import BrainDelta
+
+ state: dict[str, Any] = {"requests": [], "fail": None, "fail_late": None}
+
+ async def deltas(grant: gateway.Grant, model: str, request: Any) -> AsyncIterator[Any]:
+ state["requests"].append((grant, model, request))
+ if state["fail"] is not None:
+ raise _ProviderError(state["fail"])
+ yield BrainDelta(content="Looking")
+ if state["fail_late"] is not None:
+ raise _ProviderError(state["fail_late"])
+ yield BrainDelta(
+ tool_call={
+ "id": "call_1",
+ "name": "read_file",
+ "input": {"path": "a.txt"},
+ "thought_signature": "sig-1",
+ }
+ )
+ yield BrainDelta(usage={"input_tokens": 12, "output_tokens": 3}, finish_reason="stop")
+
+ monkeypatch.setattr(gateway, "_deltas", deltas)
+ gateway.reset()
+ yield state
+ gateway.reset()
+
+
+_CHAT = {
+ "model": "gpt-5.2",
+ "messages": [
+ {"role": "system", "content": "You are Probe."},
+ {"role": "user", "content": [{"type": "text", "text": "Read a.txt"}]},
+ ],
+ "tools": [
+ {
+ "type": "function",
+ "function": {
+ "name": "read_file",
+ "description": "Read a file",
+ "parameters": {"type": "object", "properties": {"path": {"type": "string"}}},
+ },
+ }
+ ],
+ "max_tokens": 1000,
+ "reasoning_effort": "low",
+}
+
+
+def _chat(client: TestClient, token: str, body: dict[str, Any]) -> Any:
+ return client.post(
+ f"{gateway.BASE_PATH}/chat/completions",
+ headers={"Authorization": f"Bearer {token}"},
+ json=body,
+ )
+
+
+def test_a_chat_request_becomes_a_jarvis_brain_request() -> None:
+ model, request = gateway.chat_request(
+ {
+ **_CHAT,
+ "messages": [
+ *_CHAT["messages"],
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_0",
+ "type": "function",
+ "function": {"name": "read_file", "arguments": '{"path": "b"}'},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_0", "content": "file body"},
+ ],
+ }
+ )
+ assert model == "gpt-5.2"
+ assert request.system == "You are Probe."
+ assert [m.role for m in request.messages] == ["user", "assistant", "tool"]
+ assert request.messages[1].content == [
+ {"type": "tool_use", "id": "call_0", "name": "read_file", "input": {"path": "b"}}
+ ]
+ assert request.messages[2].tool_call_id == "call_0"
+ assert request.tools[0]["name"] == "read_file" and "input_schema" in request.tools[0]
+ assert request.max_tokens == 1000 and request.reasoning_effort == "low"
+
+
+def test_chat_streams_text_and_tool_calls_in_the_openai_shape(brain, guarded) -> None:
+ token = gateway.grant_token("agent-1", "openai")
+ answer = _chat(guarded, token, {**_CHAT, "stream": True})
+ assert answer.status_code == 200, answer.text
+ lines = [line[5:].strip() for line in answer.text.splitlines() if line.startswith("data:")]
+ assert lines[-1] == "[DONE]"
+ chunks = [json.loads(line) for line in lines[:-1]]
+ deltas = [chunk["choices"][0]["delta"] for chunk in chunks]
+ assert deltas[0]["role"] == "assistant"
+ assert "".join(d.get("content") or "" for d in deltas) == "Looking"
+ calls = [call for d in deltas for call in d.get("tool_calls") or []]
+ assert calls[0]["function"] == {"name": "read_file", "arguments": '{"path": "a.txt"}'}
+ assert chunks[-1]["choices"][0]["finish_reason"] == "tool_calls"
+ assert chunks[-1]["usage"] == {"prompt_tokens": 12, "completion_tokens": 3, "total_tokens": 15}
+ grant, model, _request = brain["requests"][0]
+ assert grant.provider == "openai" and model == "gpt-5.2"
+
+
+def test_a_gemini_signature_comes_back_with_its_tool_call(brain, guarded) -> None:
+ token = gateway.grant_token("agent-1", "gemini")
+ _chat(guarded, token, {**_CHAT, "stream": True})
+ _model, request = gateway.chat_request(
+ {
+ "model": "gemini-3",
+ "messages": [
+ {"role": "user", "content": "Read a.txt"},
+ {
+ "role": "assistant",
+ "tool_calls": [
+ {"id": "call_1", "function": {"name": "read_file", "arguments": "{}"}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "x"},
+ ],
+ }
+ )
+ assert request.messages[1].content[0]["thought_signature"] == "sig-1"
+
+
+def test_chat_without_streaming_returns_a_completion(brain, guarded) -> None:
+ token = gateway.grant_token("agent-1", "openai")
+ body = _chat(guarded, token, _CHAT).json()
+ message = body["choices"][0]["message"]
+ assert message["content"] == "Looking"
+ assert message["tool_calls"][0]["id"] == "call_1"
+ assert body["choices"][0]["finish_reason"] == "tool_calls"
+
+
+def test_a_rate_limit_up_front_is_a_429_without_the_provider_body(brain, guarded) -> None:
+ brain["fail"] = 429
+ token = gateway.grant_token("agent-1", "openai")
+ answer = _chat(guarded, token, {**_CHAT, "stream": True})
+ assert answer.status_code == 429
+ assert "never reach" not in answer.text
+
+
+def test_a_failure_mid_stream_is_an_error_chunk(brain, guarded) -> None:
+ brain["fail_late"] = 500
+ token = gateway.grant_token("agent-1", "openai")
+ answer = _chat(guarded, token, {**_CHAT, "stream": True})
+ assert '"error"' in answer.text and "[DONE]" not in answer.text
+ assert "never reach" not in answer.text
+
+
+def test_each_shape_answers_only_its_own_providers(brain, guarded) -> None:
+ subscription = gateway.grant_token("agent-1", "openai-codex")
+ assert _chat(guarded, subscription, _CHAT).status_code == 400
+ api_key = gateway.grant_token("agent-1", "openai")
+ assert _post(guarded, api_key, {"model": "m", "input": "Hi"}).status_code == 400
+
+
+def test_api_key_models_come_from_jarvis_catalog(guarded) -> None:
+ gateway.reset()
+ from jarvis.agent_chat.catalog import provider_row
+
+ with_catalog = next(
+ name for name in ("claude-api", "openai", "gemini", "grok")
+ if (row := provider_row(name)) is not None and row.curated_models
+ )
+ token = gateway.grant_token("agent-1", with_catalog)
+ data = guarded.get(
+ f"{gateway.BASE_PATH}/models", headers={"Authorization": f"Bearer {token}"}
+ ).json()["data"]
+ assert [row["id"] for row in data] == [m.id for m in provider_row(with_catalog).curated_models]
+ gateway.reset()
+
+
+def test_a_streamed_answer_ends_cleanly_with_the_real_key_and_cost_context(
+ monkeypatch: pytest.MonkeyPatch, guarded
+) -> None:
+ """The plugin runs under context variables (key override, cost caller).
+ The streamed response is read by another task than the one that opened
+ it; the plugin's own task keeps them from failing at the end
+ (live 2026-10-06: every Ollama answer ended in an error chunk)."""
+ import jarvis.agent_chat.runner_api as runner_api
+ import jarvis.core.config as config
+ from jarvis.core.protocols import BrainDelta
+
+ class Brain:
+ async def complete(self, request: Any) -> AsyncIterator[BrainDelta]:
+ yield BrainDelta(content="OK")
+ yield BrainDelta(finish_reason="stop", usage={"input_tokens": 2, "output_tokens": 1})
+
+ monkeypatch.setattr(runner_api, "build_brain", lambda provider, model: Brain())
+ monkeypatch.setattr(config, "get_jarvis_agent_secret", lambda provider: "sk-agents-tier")
+ gateway.reset()
+ token = gateway.grant_token("agent-1", "ollama")
+ answer = _chat(guarded, token, {**_CHAT, "stream": True})
+ gateway.reset()
+ assert answer.status_code == 200
+ assert '"error"' not in answer.text
+ assert answer.text.rstrip().endswith("data: [DONE]")