diff --git a/agent-adk/tests/test_conversation_contract.py b/agent-adk/tests/test_conversation_contract.py index 19969878e8..2fadafccb1 100644 --- a/agent-adk/tests/test_conversation_contract.py +++ b/agent-adk/tests/test_conversation_contract.py @@ -30,6 +30,7 @@ STANDING_ROLE, anthropic_environment, check_gateway_keys, + check_pass_refresh, conversation, fake_provider, missing_from, @@ -138,6 +139,8 @@ def app_for(environment): return importlib.reload(main).app check_gateway_keys(app_for, wire, token=TOKEN) + # A pass that runs out part way is renewed once and the call sent again. + check_pass_refresh(app_for, wire, token=TOKEN) @pytest.mark.parametrize("environment", [openai_environment, anthropic_environment]) diff --git a/agent-ag2/tests/test_conversation_contract.py b/agent-ag2/tests/test_conversation_contract.py index 13dd3878f2..aaea47507a 100644 --- a/agent-ag2/tests/test_conversation_contract.py +++ b/agent-ag2/tests/test_conversation_contract.py @@ -15,6 +15,7 @@ from harness_contract import ( anthropic_environment, check_gateway_keys, + check_pass_refresh, conversation, fake_provider, missing_from, @@ -66,6 +67,8 @@ def app_for(environment): return importlib.reload(main).app check_gateway_keys(app_for, wire, path="/", token=TOKEN) + # A pass that runs out part way is renewed once and the call sent again. + check_pass_refresh(app_for, wire, path="/", token=TOKEN) @pytest.mark.parametrize("environment", [openai_environment, anthropic_environment]) diff --git a/agent-agno/tests/test_conversation_contract.py b/agent-agno/tests/test_conversation_contract.py index f46f875766..697c2385a9 100644 --- a/agent-agno/tests/test_conversation_contract.py +++ b/agent-agno/tests/test_conversation_contract.py @@ -16,6 +16,7 @@ from harness_contract import ( anthropic_environment, check_gateway_keys, + check_pass_refresh, conversation, fake_provider, missing_from, @@ -67,6 +68,8 @@ def app_for(environment): return importlib.reload(main).app check_gateway_keys(app_for, wire, path="/agui", token=TOKEN) + # A pass that runs out part way is renewed once and the call sent again. + check_pass_refresh(app_for, wire, path="/agui", token=TOKEN) @pytest.mark.parametrize("environment", [openai_environment, anthropic_environment]) diff --git a/agent-claude-sdk/src/run_model_proxy.py b/agent-claude-sdk/src/run_model_proxy.py index 969a708662..f2005ef710 100644 --- a/agent-claude-sdk/src/run_model_proxy.py +++ b/agent-claude-sdk/src/run_model_proxy.py @@ -19,6 +19,12 @@ Only where the configured address is the gateway's (`/api/model-provider/`) and a run brought a token. Otherwise Claude Code is given what it always was. + +A query outlasts its pass too: one long query runs past the pass's ten minutes before any run steps +in. So the thread's slot keeps the run's pass whole, refresh credential and all (`RunPass`), and a +call the gateway refuses because the pass ran out (`x-openbot-pass: expired`) is renewed and sent +again once, as every Python harness's calls are (`send_on_pass` in shared/run_model_key.py, which +cites the OAuth practice it follows). The renewed pass is the slot's from then on. """ import os @@ -31,7 +37,7 @@ # The module every Python harness shares: beside this harness in the repository, at /shared in the # image the Dockerfile builds. sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) -from run_model_key import GATEWAY_PATH, run_key # noqa: E402 +from run_model_key import GATEWAY_PATH, RunPass, asend_on_pass, run_pass # noqa: E402 PROXY_PATH = "/_run-model/" # The header a query's model calls carry their secret in, set through Claude Code's @@ -44,13 +50,19 @@ class _Slot: - __slots__ = ("secret", "key", "at") + """A thread's way back in: its secret, and the pass of the newest run that brought one.""" + + __slots__ = ("secret", "run_pass", "at") - def __init__(self, secret: str, key: str): + def __init__(self, secret: str, run_pass: RunPass): self.secret = secret - self.key = key + self.run_pass = run_pass self.at = time.monotonic() + @property + def key(self) -> str: + return self.run_pass.token + _by_thread: dict[str, _Slot] = {} _by_secret: dict[str, _Slot] = {} @@ -73,17 +85,17 @@ def query_environment(thread_id: str | None) -> dict[str, str]: Empty where the run brought no token or the configured address is not the gateway's. """ - key = run_key() - if not key or not thread_id or not _gateway_base(): + holder = run_pass() + if holder is None or not holder.token or not thread_id or not _gateway_base(): return {} now = time.monotonic() _forget_old(now) slot = _by_thread.get(thread_id) if slot is None: - slot = _Slot(secrets.token_urlsafe(32), key) + slot = _Slot(secrets.token_urlsafe(32), holder) _by_thread[thread_id] = slot _by_secret[slot.secret] = slot - slot.key, slot.at = key, now + slot.run_pass, slot.at = holder, now port = (os.environ.get("PORT") or "4212").strip() # Headers the container already sends with its model calls go on being sent, as the SDK lays # a query's environment over the container's own. @@ -99,11 +111,14 @@ def query_environment(thread_id: str | None) -> dict[str, str]: def refresh(thread_id: str | None) -> None: - """A run of `thread_id` brought a newer token: the query it carries on sends that from now.""" - key = run_key() + """A run of `thread_id` brought a newer token: the query it carries on sends that from now. + + The run's pass itself, so a renewal made for the query is the run's too, and the other way round. + """ + holder = run_pass() slot = _by_thread.get(thread_id or "") - if key and slot is not None: - slot.key, slot.at = key, time.monotonic() + if holder is not None and holder.token and slot is not None: + slot.run_pass, slot.at = holder, time.monotonic() def slot_key(secret: str) -> str | None: @@ -111,6 +126,11 @@ def slot_key(secret: str) -> str | None: return slot.key if slot is not None else None +def _slot_pass(secret: str) -> RunPass | None: + slot = _by_secret.get(secret) + return slot.run_pass if slot is not None else None + + # What is not passed on to the gateway: how this hop was made, the key Claude Code was given, and # the secret that let it back in. _REQUEST_DROPPED = { @@ -130,17 +150,18 @@ def slot_key(secret: str) -> str | None: async def forward(request, path: str): """One of Claude Code's model calls, passed on to the gateway with its thread's newest token. - Turned away before its body is read when it names no query of this process. + Turned away before its body is read when it names no query of this process. A pass the gateway + refuses as run out is renewed and the call sent again once (`asend_on_pass`). """ import httpx from fastapi.responses import JSONResponse, StreamingResponse from starlette.background import BackgroundTask global _client - key = slot_key((request.headers.get(SECRET_HEADER) or "").strip()) + holder = _slot_pass((request.headers.get(SECRET_HEADER) or "").strip()) base = _gateway_base() client_host = request.client.host if request.client else "" - if not key or not base or client_host not in ("127.0.0.1", "::1"): + if holder is None or not holder.token or not base or client_host not in ("127.0.0.1", "::1"): return JSONResponse({"error": "not found"}, status_code=404) if _client is None: _client = httpx.AsyncClient(timeout=httpx.Timeout(None, connect=30.0)) @@ -152,11 +173,18 @@ async def forward(request, path: str): for name, value in request.headers.items() if name.lower() not in _REQUEST_DROPPED } - headers["x-api-key"] = key + # Swapped for the slot's pass as it is sent, and again if that pass is renewed. + headers["x-api-key"] = "" upstream = _client.build_request( request.method, target, headers=headers, content=await request.body() ) - response = await _client.send(upstream, stream=True) + client = _client + response = await asend_on_pass( + holder, + upstream, + lambda again: client.send(again, stream=True), + lambda renewal: client.send(renewal), + ) return StreamingResponse( response.aiter_raw(), status_code=response.status_code, diff --git a/agent-claude-sdk/tests/test_run_model_key.py b/agent-claude-sdk/tests/test_run_model_key.py index 10b66fe6ac..491653039c 100644 --- a/agent-claude-sdk/tests/test_run_model_key.py +++ b/agent-claude-sdk/tests/test_run_model_key.py @@ -28,7 +28,10 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) from harness_contract import ( DEPLOYMENT_KEY, + FRESH_KEY, + REFRESH_KEY, RUN_KEY, + PassGate, fake_provider, gateway_environment, run_events, @@ -56,10 +59,14 @@ def _serve(app, port): return server, thread -def _run(port, thread, key=None): +def _run(port, thread, key=None, *, refresh=None, finished=True): props = {"openbotSendOnce": True} if key: - props["openbotModelRoute"] = {"via": "anthropic", "token": key} + props["openbotModelRoute"] = { + "via": "anthropic", + "token": key, + **({"refresh": refresh} if refresh else {}), + } props["openbotOrganization"] = "contract-organization" response = httpx.post( f"http://127.0.0.1:{port}/", @@ -77,14 +84,21 @@ def _run(port, thread, key=None): ) assert response.status_code == 200 events = run_events(response.text) - assert events[-1]["type"] == "RUN_FINISHED", events + if finished: + assert events[-1]["type"] == "RUN_FINISHED", events return events @pytest.fixture -def harness(monkeypatch, tmp_path): +def gate(): + """No pass runs out, unless a test says which (`PassGate`).""" + return PassGate(expired=()) + + +@pytest.fixture +def harness(monkeypatch, tmp_path, gate): keys: list[str] = [] - with fake_provider(keys) as (base, bodies): + with fake_provider(keys, gate) as (base, bodies): for name, value in gateway_environment("anthropic")(base).items(): monkeypatch.setenv(name, value) monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False) @@ -238,3 +252,49 @@ def test_the_way_back_in_takes_nothing_it_does_not_know(harness): ) assert response.status_code == 404 assert keys == [] + + +@pytest.mark.parametrize("gate", [PassGate(engine=TOKEN)]) +def test_a_query_whose_pass_runs_out_renews_it_once_and_keeps_it(harness, gate): + """A query that outlasts its pass renews it once, and the thread's calls carry the fresh one. + + Found on staging: an unattended job ran past its ten-minute pass, its next model call got the + gateway's 401, and the run ended. The gateway now says a pass ran out (`x-openbot-pass: + expired`), and the harness renews it with the run's refresh credential and sends the call again. + """ + from src import run_model_proxy + + port, keys, bodies = harness + _run(port, "thread-renewed", RUN_KEY, refresh=REFRESH_KEY) + used = _messages_keys(keys, 0) + assert used and used[0] == RUN_KEY, keys + first_fresh = used.index(FRESH_KEY) + # Calls that ran out together waited on one renewal; every call after it carries the fresh pass. + assert set(used[:first_fresh]) == {RUN_KEY} and set(used[first_fresh:]) == {FRESH_KEY}, used + assert gate.passes == [REFRESH_KEY] + # The renewal carried the engine's own secret (`MANAGED_AGENT_TOKEN`); no model call did. + assert gate.engines == [TOKEN] and gate.leaked == [], (gate.engines, gate.leaked) + assert run_model_proxy._by_thread["thread-renewed"].key == FRESH_KEY + text = json.dumps(bodies) + assert REFRESH_KEY not in text and FRESH_KEY not in text + + +@pytest.mark.parametrize( + "gate", + [ + PassGate(engine=TOKEN, refuse_pass=True), + PassGate(engine=TOKEN, flagged=False), + # The gateway refuses a renewal that does not carry this engine's own secret. + PassGate(engine="another-engines-token"), + ], +) +def test_a_pass_the_gateway_will_not_renew_reaches_claude_code_as_the_gateway_said(harness, gate): + """A renewal refused, or a 401 that is not a pass running out: Claude Code gets the 401 as it came.""" + port, keys, _ = harness + events = _run(port, "thread-refused", RUN_KEY, refresh=REFRESH_KEY, finished=False) + used = _messages_keys(keys, 0) + assert used and set(used) == {RUN_KEY}, keys + assert set(gate.passes) <= {REFRESH_KEY} + assert bool(gate.passes) == gate.flagged + # The model never answered: the call was not sent again on a pass it does not hold. + assert not any(event.get("delta") == "ok" for event in events), events diff --git a/agent-claude-sdk/tests/test_run_model_pass.py b/agent-claude-sdk/tests/test_run_model_pass.py new file mode 100644 index 0000000000..7a670357fc --- /dev/null +++ b/agent-claude-sdk/tests/test_run_model_pass.py @@ -0,0 +1,237 @@ +"""A run's pass to the model gateway that runs out part way is renewed once, and the call sent again. + +The server gives each run a pass of about ten minutes (`openbotModelRoute.token`), and with it a +refresh credential (`refresh`). Found on staging: an unattended job ran past its pass, its next model +call got the gateway's 401, and the run ended. Every Python harness sends its model calls through the +`httpx` hook in `shared/run_model_key.py`, which now renews a pass the gateway refused as run out +(`x-openbot-pass: expired`) and sends the call again once (RFC 6750 §3.1; google-auth and Claude Code +do the same on a 401). + +Driven as a harness drives it: a run's body through `RunModelKey`, then the real Anthropic SDK's +clients, sync and async, against a stand-in for the gateway on loopback. +""" + +import asyncio +import contextvars +import logging +import sys +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +import anthropic +import pytest +from fastapi import FastAPI, Request +from fastapi.testclient import TestClient + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) +from harness_contract import ( + DEPLOYMENT_KEY, + EXPIRED_BODIES, + FRESH_KEY, + REFRESH_KEY, + RUN_KEY, + PassGate, + fake_provider, +) +from run_model_key import RunModelKey + +MODEL = "claude-sonnet-5-5" + + +def _ask(client): + return client.messages.create( + model=MODEL, max_tokens=8, messages=[{"role": "user", "content": "Hello?"}] + ) + + +def _outcome(call): + try: + reply = call() + return {"text": reply.content[0].text} + except anthropic.APIStatusError as error: + return { + "status": error.status_code, + "pass": error.response.headers.get("x-openbot-pass"), + "body": error.body, + } + + +def _harness(base: str, mode: str, calls: int) -> FastAPI: + """A harness's app in small: `calls` model calls a run, one after another or `together`.""" + gateway = f"{base}/api/model-provider/anthropic" + app = FastAPI() + + @app.post("/") + async def run(request: Request): + await request.body() + if mode == "async": + client = anthropic.AsyncAnthropic(base_url=gateway, api_key=DEPLOYMENT_KEY, max_retries=0) + + async def one(): + try: + reply = await _ask(client) + return {"text": reply.content[0].text} + except anthropic.APIStatusError as error: + return { + "status": error.status_code, + "pass": error.response.headers.get("x-openbot-pass"), + "body": error.body, + } + + if calls < 0: + return await asyncio.gather(*(one() for _ in range(-calls))) + return [await one() for _ in range(calls)] + client = anthropic.Anthropic(base_url=gateway, api_key=DEPLOYMENT_KEY, max_retries=0) + if calls < 0: + # Threads the run hands its work to, each with the run's context, as frameworks do. + with ThreadPoolExecutor(-calls) as pool: + futures = [ + pool.submit(contextvars.copy_context().run, _outcome, lambda: _ask(client)) + for _ in range(-calls) + ] + return [future.result() for future in futures] + return await asyncio.to_thread(lambda: [_outcome(lambda: _ask(client)) for _ in range(calls)]) + + return RunModelKey(app) + + +def _run(gate: PassGate, mode: str, calls: int, *, refresh: str | None = REFRESH_KEY): + keys: list[str] = [] + route = {"via": "anthropic", "token": RUN_KEY, **({"refresh": refresh} if refresh else {})} + with fake_provider(keys, gate) as (base, bodies): + response = TestClient(_harness(base, mode, calls)).post( + "/", json={"forwardedProps": {"openbotModelRoute": route}} + ) + assert response.status_code == 200, response.text + return response.json(), keys, bodies + + +OK = {"text": "ok"} +REFUSED = {"status": 401, "pass": "expired", "body": EXPIRED_BODIES["anthropic"]} +# The engine's own secret, which the gateway requires on a renewal (`PassGate`'s default). +ENGINE = "contract-token" + + +@pytest.fixture(autouse=True) +def engine_token(monkeypatch): + monkeypatch.setenv("MANAGED_AGENT_TOKEN", f" {ENGINE} ") + + +@pytest.mark.parametrize("mode", ["async", "sync"]) +def test_a_pass_that_ran_out_is_renewed_once_and_kept_for_the_run(mode): + gate = PassGate() + outcomes, keys, _ = _run(gate, mode, 2) + assert outcomes == [OK, OK] + assert gate.passes == [REFRESH_KEY] + # The renewal carried the engine's own secret, trimmed; no model call did. + assert gate.engines == [ENGINE] and gate.leaked == [] + # Refused, sent again on the fresh pass, and the run's next call on the fresh pass from the start. + assert keys == [RUN_KEY, FRESH_KEY, FRESH_KEY] + + +@pytest.mark.parametrize("mode", ["async", "sync"]) +@pytest.mark.parametrize("configured", [None, " "]) +def test_an_engine_without_its_own_secret_does_not_renew(mode, configured, monkeypatch): + """A refresh credential alone renews nothing (RFC 6749 §6): the 401, and no renewal asked.""" + if configured is None: + monkeypatch.delenv("MANAGED_AGENT_TOKEN") + else: + monkeypatch.setenv("MANAGED_AGENT_TOKEN", configured) + gate = PassGate() + outcomes, keys, _ = _run(gate, mode, 1) + assert outcomes == [REFUSED] + assert gate.passes == [] + assert keys == [RUN_KEY] + + +@pytest.mark.parametrize("mode", ["async", "sync"]) +def test_calls_that_run_out_together_wait_on_one_renewal(mode): + gate = PassGate(renew_delay=0.3) + outcomes, keys, _ = _run(gate, mode, -2) + assert outcomes == [OK, OK] + assert gate.passes == [REFRESH_KEY], "one renewal for the run, not one a call" + assert sorted(keys) == sorted([RUN_KEY, RUN_KEY, FRESH_KEY, FRESH_KEY]) + + +@pytest.mark.parametrize("mode", ["async", "sync"]) +def test_a_401_that_is_not_a_pass_running_out_is_handed_back_as_it_is(mode): + # A provider's own refusal of its key passes through the gateway as a 401 without the header. + gate = PassGate(flagged=False) + outcomes, keys, _ = _run(gate, mode, 1) + assert outcomes == [{**REFUSED, "pass": None}] + assert gate.passes == [] + assert keys == [RUN_KEY] + + +@pytest.mark.parametrize("mode", ["async", "sync"]) +def test_a_renewal_the_gateway_refuses_hands_back_the_original_401(mode, caplog): + gate = PassGate(refuse_pass=True) + with caplog.at_level(logging.DEBUG): + outcomes, keys, _ = _run(gate, mode, 1) + assert outcomes == [REFUSED] + assert gate.passes == [REFRESH_KEY] + assert keys == [RUN_KEY] + # Said in the log, without a credential. + assert "did not renew" in caplog.text + for secret in (RUN_KEY, REFRESH_KEY, FRESH_KEY, ENGINE): + assert secret not in caplog.text + + +@pytest.mark.parametrize("mode", ["async", "sync"]) +def test_a_run_with_no_refresh_credential_is_as_before(mode): + gate = PassGate() + outcomes, keys, _ = _run(gate, mode, 1, refresh=None) + assert outcomes == [REFUSED] + assert gate.passes == [] + assert keys == [RUN_KEY] + + +@pytest.mark.parametrize("mode", ["async", "sync"]) +def test_a_fresh_pass_refused_as_run_out_too_is_not_renewed_again(mode): + gate = PassGate(expired=(RUN_KEY, FRESH_KEY)) + outcomes, keys, _ = _run(gate, mode, 1) + assert outcomes == [REFUSED] + assert gate.passes == [REFRESH_KEY] + assert keys == [RUN_KEY, FRESH_KEY] + + +def test_a_renewal_that_cannot_reach_the_gateway_hands_back_the_original_401(): + """A network error on the renewal is no renewal: the 401 the call got, as it came.""" + import httpx + from run_model_key import RunPass, send_on_pass + + def send(request): + return httpx.Response( + 401, headers={"x-openbot-pass": "expired"}, json=EXPIRED_BODIES["openai"], request=request + ) + + asked = [] + + def ask(renewal): + asked.append(dict(renewal.headers)) + raise httpx.ConnectError("gateway unreachable") + + request = httpx.Request( + "POST", "http://openbot:4000/api/model-provider/v1/chat/completions", content=b"{}" + ) + holder = RunPass(RUN_KEY, REFRESH_KEY, ENGINE) + response = send_on_pass(holder, request, send, ask) + assert response.status_code == 401 and response.json() == EXPIRED_BODIES["openai"] + assert holder.token == RUN_KEY + assert [(h["authorization"], h["x-openbot-agent-token"]) for h in asked] == [ + (f"Bearer {REFRESH_KEY}", ENGINE) + ] + for secret in (RUN_KEY, REFRESH_KEY, ENGINE): + assert secret not in repr(holder) + + +def test_the_renewal_goes_to_the_gateway_root(): + import httpx + from run_model_key import _pass_url + + for base, expected in [ + ("http://openbot:4000/api/model-provider/v1/chat/completions", "http://openbot:4000/api/model-provider/pass"), + ("http://openbot:4000/api/model-provider/anthropic/v1/messages?beta=true", "http://openbot:4000/api/model-provider/pass"), + ("https://bot.example.test/proxy/api/model-provider/v1/responses", "https://bot.example.test/proxy/api/model-provider/pass"), + ]: + assert _pass_url(httpx.URL(base)) == expected diff --git a/agent-crewai/tests/test_conversation_contract.py b/agent-crewai/tests/test_conversation_contract.py index 4e26eb2d21..743fa00eba 100644 --- a/agent-crewai/tests/test_conversation_contract.py +++ b/agent-crewai/tests/test_conversation_contract.py @@ -15,6 +15,7 @@ from harness_contract import ( anthropic_environment, check_gateway_keys, + check_pass_refresh, conversation, fake_provider, missing_from, @@ -74,6 +75,8 @@ def app_for(environment): return importlib.import_module("src.main").app check_gateway_keys(app_for, wire, path="/", token=TOKEN) + # A pass that runs out part way is renewed once and the call sent again. + check_pass_refresh(app_for, wire, path="/", token=TOKEN) @pytest.mark.parametrize("environment", [openai_environment, anthropic_environment]) diff --git a/agent-langgraph-agui/tests/test_conversation_contract.py b/agent-langgraph-agui/tests/test_conversation_contract.py index e5c8290ed1..3905057c4f 100644 --- a/agent-langgraph-agui/tests/test_conversation_contract.py +++ b/agent-langgraph-agui/tests/test_conversation_contract.py @@ -25,6 +25,7 @@ STANDING_ROLE, anthropic_environment, check_gateway_keys, + check_pass_refresh, conversation, fake_provider, missing_from, @@ -106,6 +107,8 @@ def app_for(environment): return importlib.reload(main).app check_gateway_keys(app_for, wire, token=TOKEN) + # A pass that runs out part way is renewed once and the call sent again. + check_pass_refresh(app_for, wire, token=TOKEN) @pytest.mark.parametrize("environment", [openai_environment, anthropic_environment]) diff --git a/agent-langgraph-ts/Dockerfile b/agent-langgraph-ts/Dockerfile index a771a03ce6..8c8aea1c0a 100644 --- a/agent-langgraph-ts/Dockerfile +++ b/agent-langgraph-ts/Dockerfile @@ -8,7 +8,7 @@ WORKDIR /app COPY agent-langgraph-ts/package.json agent-langgraph-ts/package-lock.json ./ RUN npm ci --omit=dev --no-audit --no-fund && npm cache clean --force -COPY shared/context-window.ts shared/listen-port.ts shared/model-providers.ts shared/model-providers.json shared/recall-earlier-results.ts shared/tool-search.ts /shared/ +COPY shared/context-window.ts shared/listen-port.ts shared/model-pass.ts shared/model-providers.ts shared/model-providers.json shared/recall-earlier-results.ts shared/tool-search.ts /shared/ COPY agent-langgraph-ts/src ./src ENV NODE_ENV=production PORT=4215 diff --git a/agent-langgraph-ts/src/models.ts b/agent-langgraph-ts/src/models.ts index 437e6caca4..b6c48c9ca8 100644 --- a/agent-langgraph-ts/src/models.ts +++ b/agent-langgraph-ts/src/models.ts @@ -27,6 +27,7 @@ import type { BaseChatModel } from "@langchain/core/language_models/chat_models" import { ChatGoogle } from "@langchain/google"; import { ChatOpenAI } from "@langchain/openai"; import { clearTriggerFor } from "../../shared/context-window.ts"; +import { passFetch, RunPass } from "../../shared/model-pass.ts"; // The one rule every Bot in the box decides by, imported rather than copied, so a model OpenAI // moves to the Responses API moves here in the same change. Node loads it through the JSON hook in // json-modules.ts (see there for why and how). @@ -98,6 +99,8 @@ export type ModelRoute = { via: "openai" | "anthropic" | "chatgpt-plan" | "claude-plan"; /** The run's gateway token, for `openai` and `anthropic`. */ token?: string; + /** The credential that renews the token when it runs out, when the server sent one. */ + refresh?: string; }; /** `forwardedProps.openbotModelRoute`, as the server sends it. Anything else is no route. */ @@ -106,7 +109,11 @@ export function runRoute( ): ModelRoute | undefined { const route = props.openbotModelRoute; if (!route || typeof route !== "object") return undefined; - const { via, token } = route as { via?: unknown; token?: unknown }; + const { via, token, refresh } = route as { + via?: unknown; + token?: unknown; + refresh?: unknown; + }; if (typeof via !== "string" || !ROUTES.has(via as ModelRoute["via"])) return undefined; return { @@ -114,6 +121,9 @@ export function runRoute( ...(typeof token === "string" && token.trim() ? { token: token.trim() } : {}), + ...(typeof refresh === "string" && refresh.trim() + ? { refresh: refresh.trim() } + : {}), }; } @@ -243,7 +253,12 @@ function retries(_run: RunModel): number { return 0; } -function openAIModel(model: string, run: RunModel, env: Env): BaseChatModel { +function openAIModel( + model: string, + run: RunModel, + env: Env, + fetch?: typeof globalThis.fetch, +): BaseChatModel { const baseURL = env.OPENAI_BASE_URL?.trim() || undefined; // An endpoint that needs no key still needs a string for the SDK (Ollama, vLLM, LM Studio). const apiKey = @@ -253,7 +268,14 @@ function openAIModel(model: string, run: RunModel, env: Env): BaseChatModel { model, apiKey, maxRetries: retries(run), - ...(baseURL ? { configuration: { baseURL } } : {}), + ...(baseURL || fetch + ? { + configuration: { + ...(baseURL ? { baseURL } : {}), + ...(fetch ? { fetch } : {}), + }, + } + : {}), }; // THE MODEL DECIDES, NOT THE ADDRESS: a gateway in front of OpenAI cannot say which API a model // takes. An operator who set COPILOTKIT_OPENAI_API=chat has decided. @@ -288,7 +310,12 @@ function thinksByDefault(model: string): boolean { return !!generation && Number(generation[1]) >= 5; } -function anthropicModel(model: string, run: RunModel, env: Env): BaseChatModel { +function anthropicModel( + model: string, + run: RunModel, + env: Env, + fetch?: typeof globalThis.fetch, +): BaseChatModel { const baseUrl = env.ANTHROPIC_BASE_URL?.trim() || undefined; // Anthropic clears old tool results on its side, so a long run stays inside the window // (context-room.ts), a model that writes progress updates between tool calls is asked for @@ -303,6 +330,7 @@ function anthropicModel(model: string, run: RunModel, env: Env): BaseChatModel { apiKey: env.ANTHROPIC_API_KEY?.trim() || undefined, maxRetries: retries(run), ...(baseUrl ? { anthropicApiUrl: baseUrl } : {}), + ...(fetch ? { clientOptions: { fetch } } : {}), ...(ANTHROPIC_EFFORTS.has(run.effort) ? { outputConfig: { effort: run.effort as never } } : {}), @@ -454,15 +482,36 @@ function routedModel(run: RunModel, env: Env): BaseChatModel | undefined { ); const model = bareModel(run.model) || spec(env).providers[route.via]?.default_model || ""; + // The run's pass, renewed once and the call sent again inside the client's own fetch when the + // gateway says it ran out (shared/model-pass.ts). A renewed-and-resent call is one call to the + // client and to retry.ts. One pass for the run: the model is built once a run. The renewal carries + // this engine's own secret, and an engine without one does not renew. + const fetch = passFetch( + new RunPass( + route.token, + route.refresh ?? "", + env.MANAGED_AGENT_TOKEN ?? "", + ), + ); if (route.via === "anthropic") - return anthropicModel(model, run, { + return anthropicModel( + model, + run, + { + ...env, + ANTHROPIC_BASE_URL: `${gateway}/anthropic`, + ANTHROPIC_API_KEY: route.token, + }, + fetch, + ); + return openAIModel( + model, + run, + { ...env, - ANTHROPIC_BASE_URL: `${gateway}/anthropic`, - ANTHROPIC_API_KEY: route.token, - }); - return openAIModel(model, run, { - ...env, - OPENAI_BASE_URL: `${gateway}/v1`, - OPENAI_API_KEY: route.token, - }); + OPENAI_BASE_URL: `${gateway}/v1`, + OPENAI_API_KEY: route.token, + }, + fetch, + ); } diff --git a/agent-langgraph-ts/test/model-gateway.ts b/agent-langgraph-ts/test/model-gateway.ts index c69c90f299..708efe74d1 100644 --- a/agent-langgraph-ts/test/model-gateway.ts +++ b/agent-langgraph-ts/test/model-gateway.ts @@ -45,9 +45,53 @@ export type Gateway = { connect: (provider: Provider) => void; /** Mint a run token the gateway accepts. */ mint: (token: string) => void; + /** + * The pass `token` ran out: a call on it is refused with the gateway's 401 for that + * (`x-openbot-pass: expired`), or a bare 401 when not `flagged`, as a provider's own refusal of its + * key comes through. + */ + expire: (token: string, flagged?: boolean) => void; + /** + * `POST /api/model-provider/pass` with `refresh` as its bearer mints `fresh` and answers it, after + * `delayMs`; with `refuse`, it answers 401. As the server does, it renews only for the engine that + * holds the pass: the request must also carry `engine` (by default {@link ENGINE_TOKEN}), the + * engine's `MANAGED_AGENT_TOKEN`, as `x-openbot-agent-token`. + */ + renews: ( + refresh: string, + fresh: string, + options?: { refuse?: boolean; delayMs?: number; engine?: string }, + ) => void; + /** The credential each `POST /pass` was offered, in order. */ + passes: string[]; + /** The engine secret each `POST /pass` carried, in order. */ + engines: (string | undefined)[]; + /** Model requests that carried an engine secret, which only a renewal may. */ + leaked: string[]; close: () => Promise; }; +/** The engine secret the tests' engines hold (`withEngine`'s `MANAGED_AGENT_TOKEN`). */ +export const ENGINE_TOKEN = "engine-test-token"; + +/** The gateway's own 401 for a pass that ran out, on each wire. */ +export const EXPIRED_BODIES: Record = { + anthropic: { + type: "error", + error: { + type: "authentication_error", + message: "OpenBot couldn't tell who sent this model request.", + }, + }, + openai: { + error: { + message: "OpenBot couldn't tell who sent this model request.", + type: "authentication_error", + code: "openbot_gateway_401", + }, + }, +}; + const ROOT = "/api/model-provider"; const ROUTES: Record = { "/v1/chat/completions": { method: "POST", wire: "openai" }, @@ -99,12 +143,44 @@ export async function modelGateway( let connection: Provider = first; const tokens = new Set(); const requests: GatewayRequest[] = []; + const expired = new Map(); + const renewals = new Map< + string, + { fresh: string; refuse?: boolean; delayMs?: number; engine?: string } + >(); + const passes: string[] = []; + const engines: (string | undefined)[] = []; + const leaked: string[] = []; const server: Server = createServer(async (request, response) => { const chunks: Buffer[] = []; for await (const chunk of request) chunks.push(chunk as Buffer); const raw = Buffer.concat(chunks); const path = new URL(request.url ?? "/", "http://gateway").pathname; + const engine = request.headers["x-openbot-agent-token"] as + | string + | undefined; + if (path === `${ROOT}/pass` && request.method === "POST") { + const offered = offeredToken(request.headers)?.token ?? ""; + passes.push(offered); + engines.push(engine); + const renewal = renewals.get(offered); + if (renewal?.delayMs) + await new Promise((resolve) => setTimeout(resolve, renewal.delayMs)); + const renews = + renewal && + !renewal.refuse && + engine === (renewal.engine ?? ENGINE_TOKEN); + response.writeHead(renews ? 200 : 401, { + "content-type": "application/json", + }); + if (renewal && renews) { + tokens.add(renewal.fresh); + response.end(JSON.stringify({ token: renewal.fresh })); + } else response.end(JSON.stringify(EXPIRED_BODIES.openai)); + return; + } + if (engine !== undefined) leaked.push(path); const route = path.startsWith(ROOT) ? ROUTES[path.slice(ROOT.length)] : undefined; @@ -131,6 +207,16 @@ export async function modelGateway( errorBody("openai", "Not a model gateway route.", "not_found_error"), ); const auth = offeredToken(request.headers); + if (auth && expired.has(auth.token)) { + recorded.auth = auth; + recorded.status = 401; + response.writeHead(401, { + "content-type": "application/json", + ...(expired.get(auth.token) ? { "x-openbot-pass": "expired" } : {}), + }); + response.end(JSON.stringify(EXPIRED_BODIES[route.wire])); + return; + } if (!auth || !tokens.has(auth.token)) return answer( 401, @@ -229,6 +315,15 @@ export async function modelGateway( mint: (token) => { tokens.add(token); }, + expire: (token, flagged = true) => { + expired.set(token, flagged); + }, + renews: (refresh, fresh, options = {}) => { + renewals.set(refresh, { fresh, ...options }); + }, + passes, + engines, + leaked, close: () => new Promise((resolve) => { server.closeAllConnections(); diff --git a/agent-langgraph-ts/test/model-route.test.ts b/agent-langgraph-ts/test/model-route.test.ts index 48cae86efb..a1c5499645 100644 --- a/agent-langgraph-ts/test/model-route.test.ts +++ b/agent-langgraph-ts/test/model-route.test.ts @@ -13,7 +13,8 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { inspect } from "node:util"; -import { RETRIES, useRetryTiming } from "../src/retry.ts"; +import { chatModel } from "../src/models.ts"; +import { RECONNECTING, RETRIES, useRetryTiming } from "../src/retry.ts"; import { always, type FakeProvider, @@ -28,6 +29,7 @@ import { withEngine, } from "./helpers.ts"; import { + ENGINE_TOKEN, type Gateway, liveUpstreams, MISMATCH, @@ -752,3 +754,204 @@ test("A model's stream that keeps breaking part way through a call on the gatewa cut, ); }); + +/* + * A PASS THAT RUNS OUT PART WAY. Found on staging: an unattended job ran past its run's ten-minute + * pass, its next model call got the gateway's 401, and the run ended. The server now sends the + * credential that renews the pass (`openbotModelRoute.refresh`), and the gateway says when it + * refused a pass because it ran out (`x-openbot-pass: expired`). The engine renews it once, sends + * the call again inside the client's own fetch, and keeps the fresh pass for the rest of the run + * (shared/model-pass.ts). + */ +const PASS = { + run: "run-token-ran-out", + refresh: "obgr_refresh-credential", + fresh: "obgw_fresh-run-token", +}; + +const modelFor = (via: Provider) => + via === "anthropic" ? ANTHROPIC_MODEL : OPENAI_MODEL; + +/** + * The engine's own model for a run on `via`, as `runAgent` builds it, on the gateway: one model call + * of it at a time, streamed, as a run's step makes it. `engine` is its `MANAGED_AGENT_TOKEN`. + */ +const passModel = ( + gateway: Gateway, + via: Provider, + refresh?: string, + engine: string | null = ENGINE_TOKEN, +) => { + const model = chatModel( + { + model: modelFor(via), + effort: "", + sendOnce: true, + route: { via, token: PASS.run, ...(refresh ? { refresh } : {}) }, + }, + { + ...engineEnv(gateway.url), + ...(engine !== null ? { MANAGED_AGENT_TOKEN: engine } : {}), + }, + ); + return { + async invoke(question: string) { + let said = ""; + for await (const chunk of await model.stream(question)) + said += typeof chunk.content === "string" ? chunk.content : ""; + return said; + }, + }; +}; + +const seen = (gateway: Gateway) => + gateway.requests.map((request) => [request.auth?.token, request.status]); + +/** A model call that ended with the gateway's 401 (`EXPIRED_BODIES`), as it came. */ +function refusedAsItCame(error: unknown) { + const text = inspect(error, { depth: 6 }); + assert.match(text, /401/); + assert.match(text, /OpenBot couldn't tell who sent this model request/); + return true; +} + +for (const via of ["openai", "anthropic"] as const) { + test(`On the ${via} route a pass that runs out part way is renewed once, the call sent again, and the run answers`, async () => { + await withGateway(via, async (gateway) => { + gateway.expire(PASS.run); + gateway.renews(PASS.refresh, PASS.fresh); + const result = await withEngine({ env: engineEnv(gateway.url) }, (base) => + run( + base, + ask({ + forwardedProps: { + openbotModel: { model: modelFor(via) }, + openbotModelRoute: { + via, + token: PASS.run, + refresh: PASS.refresh, + }, + }, + }), + ), + ); + assert.equal( + result.events.at(-1)?.type, + "RUN_FINISHED", + inspect(result.events.at(-1)), + ); + assert.match(words(result.events), /pineapple/i); + assert.deepEqual(gateway.passes, [PASS.refresh]); + // The renewal carried the engine's own secret (`MANAGED_AGENT_TOKEN`); no model call did. + assert.deepEqual(gateway.engines, [ENGINE_TOKEN]); + assert.deepEqual(gateway.leaked, []); + assert.deepEqual(seen(gateway), [ + [PASS.run, 401], + [PASS.fresh, 200], + ]); + // One call to the engine's own retries: nothing to reconnect. + assert.ok( + !result.events.some( + (event) => + event.type === "CUSTOM" && + (event as { name?: string }).name === RECONNECTING, + ), + ); + const text = inspect(result.events, { depth: 12 }); + for (const secret of Object.values(PASS)) + assert.ok(!text.includes(secret), "no pass reaches the run's events"); + }); + }); + + test(`On the ${via} route the renewed pass is the run's: its next call carries it, and calls that run out together wait on one renewal`, async () => { + await withGateway(via, async (gateway) => { + gateway.expire(PASS.run); + gateway.renews(PASS.refresh, PASS.fresh, { delayMs: 200 }); + const model = passModel(gateway, via, PASS.refresh); + await Promise.all([ + model.invoke("Say pineapple."), + model.invoke("Say pineapple."), + ]); + assert.deepEqual( + gateway.passes, + [PASS.refresh], + "one renewal, not one a call", + ); + await model.invoke("Say pineapple."); + assert.deepEqual(gateway.passes, [PASS.refresh]); + assert.deepEqual(seen(gateway), [ + [PASS.run, 401], + [PASS.run, 401], + [PASS.fresh, 200], + [PASS.fresh, 200], + [PASS.fresh, 200], + ]); + }); + }); + + test(`On the ${via} route a 401 that is not a pass running out, a renewal refused, no refresh credential, and a fresh pass refused too are each handed back as the gateway said`, async () => { + // A provider's own refusal of its key: a 401 without the header. Never renewed. + await withGateway(via, async (gateway) => { + gateway.expire(PASS.run, false); + gateway.renews(PASS.refresh, PASS.fresh); + await assert.rejects( + passModel(gateway, via, PASS.refresh).invoke("Say pineapple."), + refusedAsItCame, + ); + assert.deepEqual(gateway.passes, []); + assert.deepEqual(seen(gateway), [[PASS.run, 401]]); + }); + // The gateway won't renew it: the original 401. + await withGateway(via, async (gateway) => { + gateway.expire(PASS.run); + gateway.renews(PASS.refresh, PASS.fresh, { refuse: true }); + await assert.rejects( + passModel(gateway, via, PASS.refresh).invoke("Say pineapple."), + refusedAsItCame, + ); + assert.deepEqual(gateway.passes, [PASS.refresh]); + assert.deepEqual(seen(gateway), [[PASS.run, 401]]); + }); + // An engine with no secret of its own configured, or a blank one: a refresh credential alone + // renews nothing (RFC 6749 §6), so the renewal is never asked. + for (const engine of [null, " "]) { + await withGateway(via, async (gateway) => { + gateway.expire(PASS.run); + gateway.renews(PASS.refresh, PASS.fresh); + await assert.rejects( + passModel(gateway, via, PASS.refresh, engine).invoke( + "Say pineapple.", + ), + refusedAsItCame, + ); + assert.deepEqual(gateway.passes, []); + assert.deepEqual(seen(gateway), [[PASS.run, 401]]); + }); + } + // No refresh credential, as from a server before it: as before. + await withGateway(via, async (gateway) => { + gateway.expire(PASS.run); + await assert.rejects( + passModel(gateway, via).invoke("Say pineapple."), + refusedAsItCame, + ); + assert.deepEqual(gateway.passes, []); + assert.deepEqual(seen(gateway), [[PASS.run, 401]]); + }); + // The fresh pass refused as run out too: no second renewal, no loop. + await withGateway(via, async (gateway) => { + gateway.expire(PASS.run); + gateway.expire(PASS.fresh); + gateway.renews(PASS.refresh, PASS.fresh); + await assert.rejects( + passModel(gateway, via, PASS.refresh).invoke("Say pineapple."), + refusedAsItCame, + ); + assert.deepEqual(gateway.passes, [PASS.refresh]); + assert.deepEqual(seen(gateway), [ + [PASS.run, 401], + [PASS.fresh, 401], + ]); + }); + }); +} diff --git a/agent-langroid/tests/test_conversation_contract.py b/agent-langroid/tests/test_conversation_contract.py index 83dc1aa15c..46fda1a548 100644 --- a/agent-langroid/tests/test_conversation_contract.py +++ b/agent-langroid/tests/test_conversation_contract.py @@ -15,6 +15,7 @@ from harness_contract import ( anthropic_environment, check_gateway_keys, + check_pass_refresh, conversation, fake_provider, missing_from, @@ -61,11 +62,19 @@ def app_for(environment): monkeypatch.setenv("MANAGED_AGENT_TOKEN", TOKEN) for key, value in environment.items(): monkeypatch.setenv(key, value) + # Langroid keeps one OpenAI client a key for the process, built with no address (the SDK + # reads `OPENAI_BASE_URL` itself), so a second gateway in one test would get the first's + # client, pointed at a server that has gone. A process has one gateway; a test, several. + from langroid.language_models import client_cache + + client_cache._clear_cache() from src import main return importlib.reload(main).app check_gateway_keys(app_for, wire, path="/", token=TOKEN) + # A pass that runs out part way is renewed once and the call sent again. + check_pass_refresh(app_for, wire, path="/", token=TOKEN) @pytest.mark.parametrize("environment", [openai_environment, anthropic_environment]) diff --git a/agent-llamaindex/tests/test_conversation_contract.py b/agent-llamaindex/tests/test_conversation_contract.py index 0d2446c703..1bc0b235a8 100644 --- a/agent-llamaindex/tests/test_conversation_contract.py +++ b/agent-llamaindex/tests/test_conversation_contract.py @@ -15,6 +15,7 @@ from harness_contract import ( anthropic_environment, check_gateway_keys, + check_pass_refresh, conversation, fake_provider, missing_from, @@ -66,6 +67,8 @@ def app_for(environment): return importlib.reload(main).app check_gateway_keys(app_for, wire, path="/run", token=TOKEN) + # A pass that runs out part way is renewed once and the call sent again. + check_pass_refresh(app_for, wire, path="/run", token=TOKEN) @pytest.mark.parametrize("environment", [openai_environment, anthropic_environment]) diff --git a/agent-mastra/Dockerfile b/agent-mastra/Dockerfile index 6acac4a27a..7e75baf2f8 100644 --- a/agent-mastra/Dockerfile +++ b/agent-mastra/Dockerfile @@ -7,6 +7,7 @@ COPY agent-mastra/package.json agent-mastra/bun.lock ./ RUN bun install --frozen-lockfile COPY shared/listen-port.ts /shared/listen-port.ts +COPY shared/model-pass.ts /shared/model-pass.ts COPY shared/model-providers.ts /shared/model-providers.ts COPY shared/model-providers.json /shared/model-providers.json COPY agent-mastra/src ./src diff --git a/agent-mastra/src/mastra/index.test.ts b/agent-mastra/src/mastra/index.test.ts index a0b16774b3..e4eae15d8e 100644 --- a/agent-mastra/src/mastra/index.test.ts +++ b/agent-mastra/src/mastra/index.test.ts @@ -386,6 +386,40 @@ describe("OpenBot Mastra receiver instructions", () => { ); }); + test("never shows the model the run's model route, its pass or the credential that renews it", () => { + // The route is for this process's model client only (`runRouteFrom`): its pass and refresh + // credential are credentials, and the model is never told them. + const route = JSON.stringify({ + via: "anthropic", + token: "obgw_route-pass-secret", + refresh: "obgr_route-refresh-secret", + }); + const instructions = buildOpenBotInstructions({ + requestContext: requestContextWith([ + { description: "OpenBot model route", value: route }, + { + description: "OpenBot standing role", + value: "Follow company policy.", + }, + { description: "Components you can draw", value: "CALLER_MARKER" }, + ]), + }); + + expect(instructions).toBe( + [ + openbotBaseInstructions, + "Follow company policy.", + "Components you can draw: CALLER_MARKER", + ].join("\n\n"), + ); + for (const hidden of [ + "OpenBot model route", + "obgw_route-pass-secret", + "obgr_route-refresh-secret", + ]) + expect(instructions).not.toContain(hidden); + }); + test("tells the model who the person is, after OpenBot's guidance and before the caller's context", () => { // Without it a Mastra Bot summarising the person's own meeting wrote about them by name. const instructions = buildOpenBotInstructions({ @@ -1636,3 +1670,276 @@ describe("OpenBot Mastra progress reminder", () => { 180_000, ); }); + +/** + * A PASS THAT RUNS OUT PART WAY. Found on staging: an unattended job ran past its run's ten-minute + * pass, its next model call got the gateway's 401, and the run ended. The server now sends the + * credential that renews the pass in the `OpenBot model route` entry (`"refresh"`), and the gateway + * says when it refused a pass because it ran out (`x-openbot-pass: expired`). The Bot renews it + * once, sends the call again, and every later call of the run carries the fresh pass + * (shared/model-pass.ts). The real Mastra Agent and AI SDK, against a gateway on loopback. + */ +describe("OpenBot Mastra renews a run's pass that ran out", () => { + const RUN = "obgw_run-token-ran-out"; + const REFRESH = "obgr_refresh-credential"; + const FRESH = "obgw_fresh-run-token"; + /** The engine's own secret (`MANAGED_AGENT_TOKEN`), which the gateway requires on a renewal. */ + const ENGINE = "test-managed-token"; + const EXPIRED = { + anthropic: { + type: "error", + error: { + type: "authentication_error", + message: "OpenBot couldn't tell who sent this model request.", + }, + }, + openai: { + error: { + message: "OpenBot couldn't tell who sent this model request.", + type: "authentication_error", + code: "openbot_gateway_401", + }, + }, + } as const; + + type Gate = { + /** Passes refused as run out; `flagged` false sends the 401 without the header. */ + expired: string[]; + flagged?: boolean; + refuse?: boolean; + delayMs?: number; + }; + + /** + * `calls` model calls of one run (`together` at once), its route carrying `refresh` when given, + * in a Bot whose `MANAGED_AGENT_TOKEN` is `engine` (none when undefined). Answers what each call + * ended with, the pass each model request carried, each renewal's credential and engine secret, + * and the model requests that carried an engine secret, which only a renewal may. As the server + * does, the gateway renews only for the engine's own secret. + */ + async function passRun( + wire: "openai" | "anthropic", + gate: Gate, + { + calls = 1, + together = false, + refresh = REFRESH, + engine = ENGINE as string | null, + } = {}, + ) { + const keys: string[] = []; + const passes: string[] = []; + const engines: (string | null)[] = []; + const leaked: string[] = []; + const sent: string[] = []; + const server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + async fetch(request) { + const path = new URL(request.url).pathname; + const offered = + request.headers.get("x-api-key") ?? + (request.headers.get("authorization") ?? "").replace(/^Bearer /, ""); + const secret = request.headers.get("x-openbot-agent-token"); + if (path === "/api/model-provider/pass") { + passes.push(offered); + engines.push(secret); + if (gate.delayMs) await Bun.sleep(gate.delayMs); + if (gate.refuse || offered !== REFRESH || secret !== ENGINE) + return Response.json(EXPIRED.openai, { status: 401 }); + return Response.json({ token: FRESH }); + } + if (secret !== null) leaked.push(path); + const body = await request.json(); + sent.push(JSON.stringify(body)); + keys.push(offered); + if (gate.expired.includes(offered)) + return Response.json(EXPIRED[wire], { + status: 401, + headers: + gate.flagged === false ? {} : { "x-openbot-pass": "expired" }, + }); + if (wire === "anthropic") + return Response.json({ + id: "msg", + type: "message", + role: "assistant", + model: body.model, + content: [{ type: "text", text: "hello" }], + stop_reason: "end_turn", + stop_sequence: null, + usage: { input_tokens: 1, output_tokens: 1 }, + }); + return Response.json({ + id: "chat", + object: "chat.completion", + created: 0, + model: body.model, + choices: [ + { + index: 0, + finish_reason: "stop", + message: { role: "assistant", content: "hello" }, + }, + ], + usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 }, + }); + }, + }); + const base = `${server.url.toString().replace(/\/+$/, "")}/api/model-provider${wire === "anthropic" ? "/anthropic" : "/v1"}`; + const route = JSON.stringify({ + via: wire, + token: RUN, + ...(refresh ? { refresh } : {}), + }); + try { + const { stdout, stderr, exitCode } = await runProbe( + [ + Bun.argv[0], + "--no-env-file", + "-e", + [ + 'const { RequestContext } = await import(Bun.resolveSync("@mastra/core/request-context", process.cwd() + "/agent-mastra/src/mastra"));', + 'const { mastra } = await import("./agent-mastra/src/mastra/index.ts");', + // One run: one request context, as Mastra's server builds one for each. + "const requestContext = new RequestContext();", + `requestContext.set("ag-ui", { context: [{ description: "OpenBot model route", value: ${JSON.stringify(route)} }] });`, + 'const agent = mastra.getAgent("openbot");', + "const one = async () => {", + ' try { const result = await agent.generate("Say hello", { requestContext, maxRetries: 0 });', + " return result.error ? { error: String(result.error?.message ?? result.error) } : { text: result.text }; }", + " catch (error) { return { error: String(error?.message ?? error) }; }", + "};", + `const calls = ${calls};`, + `const outcomes = ${together} ? await Promise.all(Array.from({ length: calls }, one)) : [];`, + `if (!${together}) for (let i = 0; i < calls; i += 1) outcomes.push(await one());`, + "console.log(JSON.stringify({ outcomes }));", + ].join("\n"), + ], + { + PATH: process.env.PATH ?? "/opt/homebrew/bin:/usr/bin:/bin", + MASTRA_TELEMETRY_DISABLED: "true", + DO_NOT_TRACK: "1", + NODE_ENV: "test", + BOT_PROVIDER: wire, + BOT_MODEL: wire === "anthropic" ? "claude-sonnet-5-5" : "gpt-5.5", + ANTHROPIC_API_KEY: + wire === "anthropic" ? "deployment-gateway-token" : "", + OPENAI_API_KEY: + wire === "anthropic" ? "" : "deployment-gateway-token", + ANTHROPIC_BASE_URL: wire === "anthropic" ? base : "", + OPENAI_BASE_URL: wire === "anthropic" ? "" : base, + ...(engine !== null ? { MANAGED_AGENT_TOKEN: engine } : {}), + }, + 15_000, + ); + if (exitCode !== 0) + throw new Error(`pass probe exited ${exitCode}\n${stdout}\n${stderr}`); + const line = stdout + .trim() + .split("\n") + .reverse() + .find((candidate: string) => candidate.startsWith("{")); + if (!line) throw new Error(`pass probe produced no JSON:\n${stdout}`); + const { outcomes } = JSON.parse(line) as { + outcomes: { text?: string; error?: string }[]; + }; + for (const secret of [RUN, REFRESH, FRESH, ENGINE]) { + expect(`${stdout}${stderr}`).not.toContain(secret); + // Nor is any of them, or the route entry itself, ever shown to the model. + expect(sent.join("\n")).not.toContain(secret); + } + expect(sent.join("\n")).not.toContain("OpenBot model route"); + return { outcomes, keys, passes, engines, leaked }; + } finally { + await server.stop(true); + } + } + + const refused = (outcome: { text?: string; error?: string }) => { + expect(outcome.text).toBeUndefined(); + expect(outcome.error).toContain( + "OpenBot couldn't tell who sent this model request.", + ); + }; + + for (const wire of ["openai", "anthropic"] as const) { + test(`${wire}: renewed once, the call sent again, and the run's next call on the fresh pass`, async () => { + const { outcomes, keys, passes, engines, leaked } = await passRun( + wire, + { expired: [RUN] }, + { calls: 2, engine: ` ${ENGINE} ` }, + ); + expect(outcomes).toEqual([{ text: "hello" }, { text: "hello" }]); + expect(passes).toEqual([REFRESH]); + // The renewal carried the engine's own secret, trimmed; no model call did. + expect(engines).toEqual([ENGINE]); + expect(leaked).toEqual([]); + expect(keys).toEqual([RUN, FRESH, FRESH]); + }, 20_000); + + for (const engine of [null, " "]) + test(`${wire}: a Bot ${engine === null ? "with no" : "with a blank"} MANAGED_AGENT_TOKEN does not renew, and hands back the 401`, async () => { + // A refresh credential alone renews nothing (RFC 6749 §6). + const { outcomes, keys, passes } = await passRun( + wire, + { expired: [RUN] }, + { engine }, + ); + refused(outcomes[0]!); + expect(passes).toEqual([]); + expect(keys).toEqual([RUN]); + }, 20_000); + + test(`${wire}: calls that run out together wait on one renewal`, async () => { + const { outcomes, keys, passes } = await passRun( + wire, + { expired: [RUN], delayMs: 200 }, + { calls: 2, together: true }, + ); + expect(outcomes).toEqual([{ text: "hello" }, { text: "hello" }]); + expect(passes).toEqual([REFRESH]); + expect(keys).toEqual([RUN, RUN, FRESH, FRESH]); + }, 20_000); + + test(`${wire}: a 401 that is not a pass running out is handed back as it is`, async () => { + const { outcomes, keys, passes } = await passRun(wire, { + expired: [RUN], + flagged: false, + }); + refused(outcomes[0]!); + expect(passes).toEqual([]); + expect(keys).toEqual([RUN]); + }, 20_000); + + test(`${wire}: a renewal the gateway refuses hands back the original 401`, async () => { + const { outcomes, keys, passes } = await passRun(wire, { + expired: [RUN], + refuse: true, + }); + refused(outcomes[0]!); + expect(passes).toEqual([REFRESH]); + expect(keys).toEqual([RUN]); + }, 20_000); + + test(`${wire}: a run with no refresh credential is as before`, async () => { + const { outcomes, keys, passes } = await passRun( + wire, + { expired: [RUN] }, + { refresh: "" }, + ); + refused(outcomes[0]!); + expect(passes).toEqual([]); + expect(keys).toEqual([RUN]); + }, 20_000); + + test(`${wire}: a fresh pass refused as run out too is not renewed again`, async () => { + const { outcomes, keys, passes } = await passRun(wire, { + expired: [RUN, FRESH], + }); + refused(outcomes[0]!); + expect(passes).toEqual([REFRESH]); + expect(keys).toEqual([RUN, FRESH]); + }, 20_000); + } +}); diff --git a/agent-mastra/src/mastra/index.ts b/agent-mastra/src/mastra/index.ts index 54df80b7c0..3cb73d4925 100644 --- a/agent-mastra/src/mastra/index.ts +++ b/agent-mastra/src/mastra/index.ts @@ -16,6 +16,7 @@ import { Agent } from "@mastra/core/agent"; import { Mastra } from "@mastra/core/mastra"; import { registerApiRoute } from "@mastra/core/server"; import { listenPort } from "../../../shared/listen-port"; +import { passFetch, RunPass } from "../../../shared/model-pass"; import { apiKeyOrPlaceholder, botSettings, @@ -39,7 +40,7 @@ const SUPPORTED_PROVIDERS = new Set(["openai", "anthropic"]); * and one it has that this harness has no module for, used to fall through to the OpenAI branch * below and answer with a model the deployment never chose. */ -async function buildModel(runKey?: string) { +async function buildModel(runPass?: RunPass) { const settings = botSettings("agent-mastra"); const providerName = settings.provider; const spec = providerSpec(providerName); @@ -60,8 +61,13 @@ async function buildModel(runKey?: string) { // Provider modules create default clients at import, which reject Compose's empty overrides. if (!baseURL) delete process.env[baseVariable]; - // The run's own gateway token, only where the address is OpenBot's model gateway. - const key = runKey && baseURL && onTheGateway(baseURL) ? runKey : undefined; + // The run's own gateway pass, only where the address is OpenBot's model gateway. Its fetch sends + // each call on the run's newest pass, and renews it once when the gateway says it ran out + // (shared/model-pass.ts). + const pass = + runPass && baseURL && onTheGateway(baseURL) ? runPass : undefined; + const key = pass?.token; + const passing = pass ? passFetch(pass) : undefined; if (spec.id === "anthropic") { const { createAnthropic } = await import("@ai-sdk/anthropic"); @@ -73,6 +79,7 @@ async function buildModel(runKey?: string) { createAnthropic({ baseURL: origin.endsWith("/v1") ? origin : `${origin}/v1`, ...(key ? { apiKey: key } : {}), + ...(passing ? { fetch: passing } : {}), })(model), origin, ); @@ -90,10 +97,13 @@ async function buildModel(runKey?: string) { : undefined), // A compatible address may stream tool calls without the index the SDK requires // (tool-call-index.ts), and may serve Gemini, which refuses a handed-back call without its - // thought signature (gemini-signatures.ts). OpenAI's own Responses path needs neither. + // thought signature (gemini-signatures.ts). OpenAI's own Responses path needs neither. The + // run's pass is the innermost, so a call sent again after a renewal is the signed one. ...(compatible - ? { fetch: withDefaultToolCallIndexes(signingFetch()) } - : {}), + ? { fetch: withDefaultToolCallIndexes(signingFetch(passing)) } + : passing + ? { fetch: passing } + : {}), }); // Compatible endpoints commonly expose Chat Completions; OpenAI keeps its Responses default. return compatible ? openai.chat(model) : openai(model); @@ -227,6 +237,15 @@ function onTheGateway(baseURL: string): boolean { export function runKeyFrom( requestContext?: OpenBotInstructionArgs["requestContext"], ): string | undefined { + return runRouteFrom(requestContext)?.token; +} + +/** + * The route's pass and, when the server sent one, the credential that renews it (`"refresh"`). + */ +function runRouteFrom( + requestContext?: OpenBotInstructionArgs["requestContext"], +): { token: string; refresh: string } | undefined { const entry = agUiContextEntries(requestContext).find( (candidate): candidate is ContextEntry => isContextEntry(candidate) && @@ -235,16 +254,44 @@ export function runKeyFrom( ); if (!entry) return undefined; try { - const route = JSON.parse(entry.value) as { via?: unknown; token?: unknown }; + const route = JSON.parse(entry.value) as { + via?: unknown; + token?: unknown; + refresh?: unknown; + }; if (route.via !== "openai" && route.via !== "anthropic") return undefined; - return typeof route.token === "string" && route.token.trim() - ? route.token.trim() - : undefined; + if (typeof route.token !== "string" || !route.token.trim()) + return undefined; + return { + token: route.token.trim(), + refresh: typeof route.refresh === "string" ? route.refresh.trim() : "", + }; } catch { return undefined; } } +/** Each run's pass, kept with its request context so every step of the run sends the newest. */ +const runPasses = new WeakMap(); + +function runPassFrom( + requestContext?: OpenBotInstructionArgs["requestContext"], +): RunPass | undefined { + const route = runRouteFrom(requestContext); + if (!route || !requestContext) return undefined; + let pass = runPasses.get(requestContext); + if (!pass) { + // The renewal carries this engine's own secret; an engine without one does not renew. + pass = new RunPass( + route.token, + route.refresh, + process.env.MANAGED_AGENT_TOKEN ?? "", + ); + runPasses.set(requestContext, pass); + } + return pass; +} + // Built at start, so a provider this Bot cannot drive is refused before it serves anything. const deploymentModel = await buildModel(); @@ -254,8 +301,8 @@ const openbot = new Agent({ instructions: buildOpenBotInstructions, // A run that brought its own gateway token answers on a model that calls with it. model: async ({ requestContext }) => { - const key = runKeyFrom(requestContext); - return key ? buildModel(key) : deploymentModel; + const pass = runPassFrom(requestContext); + return pass ? buildModel(pass) : deploymentModel; }, // A line now and then on a long job (progress-reminder.ts). An error processor, so the hook that // adds the reminder to a model call also sees that call refused; Mastra keeps its own stability diff --git a/agent-microsoft/tests/test_conversation_contract.py b/agent-microsoft/tests/test_conversation_contract.py index 68a00000bd..6aa40ab9c1 100644 --- a/agent-microsoft/tests/test_conversation_contract.py +++ b/agent-microsoft/tests/test_conversation_contract.py @@ -14,6 +14,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) from harness_contract import ( anthropic_environment, + check_pass_refresh, check_run_keys, conversation, fake_provider, @@ -80,3 +81,20 @@ def test_a_run_calls_the_gateway_with_its_own_key(monkeypatch, wire): if "openbotModelRoute" in body["forwardedProps"]: ran_with_token = len(keys) check_run_keys(keys, ran_with_token, bodies) + + +@pytest.mark.parametrize("wire", ["openai", "anthropic"]) +def test_a_pass_that_runs_out_part_way_is_renewed_once(monkeypatch, wire): + """See `check_pass_refresh` in shared/harness_contract.py.""" + + def app_for(environment): + monkeypatch.delenv("OPENAI_API_BASE", raising=False) + monkeypatch.delenv("ANTHROPIC_AUTH_TOKEN", raising=False) + monkeypatch.setenv("MANAGED_AGENT_TOKEN", TOKEN) + for key, value in environment.items(): + monkeypatch.setenv(key, value) + from src import main + + return importlib.reload(main).app + + check_pass_refresh(app_for, wire, token=TOKEN) diff --git a/agent-pydantic-ai/tests/test_conversation_contract.py b/agent-pydantic-ai/tests/test_conversation_contract.py index 350651c126..631c3bbab6 100644 --- a/agent-pydantic-ai/tests/test_conversation_contract.py +++ b/agent-pydantic-ai/tests/test_conversation_contract.py @@ -15,6 +15,7 @@ from harness_contract import ( anthropic_environment, check_gateway_keys, + check_pass_refresh, conversation, fake_provider, missing_from, @@ -68,6 +69,8 @@ def app_for(environment): return importlib.reload(main).app check_gateway_keys(app_for, wire, token=TOKEN) + # A pass that runs out part way is renewed once and the call sent again. + check_pass_refresh(app_for, wire, token=TOKEN) @pytest.mark.parametrize("environment", [openai_environment, anthropic_environment]) diff --git a/agent-strands/tests/test_conversation_contract.py b/agent-strands/tests/test_conversation_contract.py index 1def4299de..77e257c2cc 100644 --- a/agent-strands/tests/test_conversation_contract.py +++ b/agent-strands/tests/test_conversation_contract.py @@ -20,6 +20,7 @@ LATEST_QUESTION, STANDING_ROLE, anthropic_environment, + check_pass_refresh, check_run_keys, conversation, fake_provider, @@ -209,6 +210,14 @@ def test_a_run_calls_the_gateway_with_its_own_key(monkeypatch, wire): check_run_keys(keys, ran_with_token, bodies) +@pytest.mark.parametrize("wire", ["openai", "anthropic"]) +def test_a_pass_that_runs_out_part_way_is_renewed_once(monkeypatch, wire): + """See `check_pass_refresh` in shared/harness_contract.py.""" + check_pass_refresh( + lambda environment: _app(monkeypatch, lambda _base: environment, None), wire, token=TOKEN + ) + + def test_a_warm_process_takes_the_role_from_this_run_not_the_first(monkeypatch): first = conversation(run_id="run-1") second = conversation(run_id="run-2") diff --git a/api/client-boundary.allow.ts b/api/client-boundary.allow.ts index 033ebf3c95..ffbd0f12c5 100644 --- a/api/client-boundary.allow.ts +++ b/api/client-boundary.allow.ts @@ -418,6 +418,12 @@ export const ALLOWED: Allowed[] = [ rule: "machine-credential", why: "the model gateway Desktop gives every engine, which presents the gateway token", }, + { + file: "shared/model-pass.ts", + what: "/api/model-provider/", + rule: "machine-credential", + why: "the model gateway's root, where a TypeScript engine trades a run's refresh credential for a new pass (`/pass`)", + }, { file: "desktop/src-tauri/src/learning_model.rs", what: "/api/learning-model/v1", diff --git a/shared/harness_contract.py b/shared/harness_contract.py index 6916df2146..52b514d3bc 100644 --- a/shared/harness_contract.py +++ b/shared/harness_contract.py @@ -139,18 +139,135 @@ def environment(base: str, model: str = "contract-model") -> dict[str, str]: return environment -def with_run_key(body: dict, wire: str) -> dict: - """`body` as the server sends a harness it runs: with the run's own gateway token.""" +def with_run_key(body: dict, wire: str, refresh: str | None = None) -> dict: + """`body` as the server sends a harness it runs: with the run's own gateway token. + + With `refresh`, the route also carries the credential that renews the token when it runs out. + """ + route = {"via": wire, "token": RUN_KEY, **({"refresh": refresh} if refresh else {})} return { **body, "forwardedProps": { **(body.get("forwardedProps") or {}), - "openbotModelRoute": {"via": wire, "token": RUN_KEY}, + "openbotModelRoute": route, "openbotOrganization": "contract-organization", }, } +# A run's pass that runs out part way, the credential that renews it, and the pass it is renewed to. +REFRESH_KEY = "obgr_contract-refresh-credential" +FRESH_KEY = "obgw_contract-fresh-run-token" +# What the gateway answers a pass that ran out with, on each wire (and `x-openbot-pass: expired`). +EXPIRED_BODIES = { + "anthropic": { + "type": "error", + "error": { + "type": "authentication_error", + "message": "OpenBot couldn't tell who sent this model request.", + }, + }, + "openai": { + "error": { + "message": "OpenBot couldn't tell who sent this model request.", + "type": "authentication_error", + "code": "openbot_gateway_401", + } + }, +} + + +class PassGate: + """OpenBot's model gateway's passes, in front of `fake_provider`. + + A model call on a pass in `expired` is refused with the gateway's 401 for a pass that ran out + (`x-openbot-pass: expired`, unless not `flagged`: then a bare 401, as a provider's own refusal + of a key passes through). `POST /api/model-provider/pass` with `refresh` as its bearer answers + `fresh`, unless `refuse_pass`; every credential it was offered is in `passes`. As the server + does, it renews only for the engine that holds the pass: the request must also carry `engine`, + the engine's `MANAGED_AGENT_TOKEN`, as `x-openbot-agent-token` (each one offered is in + `engines`); a model call that carries it is in `leaked`. `renew_delay` holds each renewal that + long, so calls that ran out together are seen to wait on one. + """ + + def __init__( + self, + *, + expired: tuple[str, ...] = (RUN_KEY,), + refresh: str = REFRESH_KEY, + fresh: str = FRESH_KEY, + engine: str = "contract-token", + flagged: bool = True, + refuse_pass: bool = False, + renew_delay: float = 0.0, + ): + self.expired = set(expired) + self.refresh = refresh + self.fresh = fresh + self.engine = engine + self.flagged = flagged + self.refuse_pass = refuse_pass + self.renew_delay = renew_delay + self.passes: list[str] = [] + self.engines: list[str | None] = [] + self.leaked: list[str] = [] + + async def renew(self, bearer: str, engine: str | None): + import asyncio + + from fastapi.responses import JSONResponse + + self.passes.append(bearer) + self.engines.append(engine) + if self.renew_delay: + await asyncio.sleep(self.renew_delay) + if self.refuse_pass or bearer != self.refresh or engine != self.engine: + return JSONResponse(EXPIRED_BODIES["openai"], status_code=401) + return JSONResponse({"token": self.fresh}) + + def refusal(self, key: str, path: str): + from fastapi.responses import JSONResponse + + if key not in self.expired: + return None + wire = "anthropic" if path.endswith("/messages") else "openai" + headers = {"x-openbot-pass": "expired"} if self.flagged else {} + return JSONResponse(EXPIRED_BODIES[wire], status_code=401, headers=headers) + + +def check_pass_refresh(app_for, wire: str, *, path: str = "/", token: str = "contract-token") -> None: + """A run whose pass runs out part way renews it once and finishes with its answer. + + The run's first model call is refused because its pass ran out. The harness asks the gateway for + a fresh one with the run's refresh credential, once, sends the call again with it, and every + later call of the run carries the fresh pass. See `shared/run_model_key.py`. + """ + from fastapi.testclient import TestClient + + keys: list[str] = [] + gate = PassGate(engine=token) + with fake_provider(keys, gate) as (base, bodies): + with TestClient(app_for(gateway_environment(wire)(base))) as client: + started = len(keys) + response = client.post( + path, + json=with_run_key(conversation(), wire, refresh=REFRESH_KEY), + headers={"x-openbot-agent-token": token}, + ) + assert response.status_code == 200, response.text + types = [e["type"] for e in run_events(response.text)] + assert "RUN_FINISHED" in types and "RUN_ERROR" not in types, response.text + ran = keys[started:] + assert gate.passes == [REFRESH_KEY], gate.passes + # The renewal, and only the renewal, carried the engine's own secret. + assert gate.engines == [token] and gate.leaked == [], (gate.engines, gate.leaked) + assert ran[:1] == [RUN_KEY], ran + assert ran[1:] and set(ran[1:]) == {FRESH_KEY}, ran + assert bodies, "the model was never answered" + text = json.dumps(bodies) + assert REFRESH_KEY not in text and FRESH_KEY not in text and RUN_KEY not in text + + def check_run_keys(keys: list[str], ran_with_token: int, bodies: list[dict]) -> None: """The first `ran_with_token` model requests carried the run's token, the rest the environment's. @@ -193,13 +310,16 @@ def check_gateway_keys(app_for, wire: str, *, path: str = "/", token: str = "con @contextmanager -def fake_provider(keys: list[str] | None = None) -> Iterator[tuple[str, list[dict]]]: +def fake_provider( + keys: list[str] | None = None, gate: PassGate | None = None +) -> Iterator[tuple[str, list[dict]]]: """An OpenAI- and Anthropic-compatible model on localhost that answers "ok" and records bodies. Yields `(base_url, bodies)`: every request body in arrival order. Serves Chat Completions, Responses and Messages, streamed and not, since which one a framework uses is its own choice. - Given `keys`, also writes down the key each request presented, as OpenAI's SDK sends it - (`Authorization: Bearer`) or Anthropic's (`x-api-key`). + Given `keys`, also writes down the key each model request presented, as OpenAI's SDK sends it + (`Authorization: Bearer`) or Anthropic's (`x-api-key`). Given `gate`, the gateway's passes + stand in front of it (`PassGate`). """ from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, StreamingResponse @@ -207,17 +327,25 @@ def fake_provider(keys: list[str] | None = None) -> Iterator[tuple[str, list[dic bodies: list[dict] = [] app = FastAPI() - if keys is not None: + if keys is not None or gate is not None: @app.middleware("http") async def presented(request: Request, call_next): bearer = request.headers.get("authorization", "") - keys.append( + key = ( bearer[len("Bearer ") :] if bearer.startswith("Bearer ") else request.headers.get("x-api-key", "") ) - return await call_next(request) + engine = request.headers.get("x-openbot-agent-token") + if gate is not None and request.url.path == "/pass": + return await gate.renew(key, engine) + if gate is not None and engine is not None: + gate.leaked.append(request.url.path) + if keys is not None: + keys.append(key) + refused = gate.refusal(key, request.url.path) if gate is not None else None + return refused or await call_next(request) def sse(lines): async def stream(): diff --git a/shared/model-pass.ts b/shared/model-pass.ts new file mode 100644 index 0000000000..af4abd9913 --- /dev/null +++ b/shared/model-pass.ts @@ -0,0 +1,206 @@ +/** + * A run's pass to OpenBot's model gateway, renewed when it runs out, for the TypeScript engines. + * + * The server gives each run a pass of about ten minutes (`openbotModelRoute.token`; for Mastra, the + * `OpenBot model route` context entry), and may give it the credential that renews it + * (`"refresh": "obgr_..."`). Found on staging: an unattended job ran past its pass, its next model + * call got the gateway's 401, and the run ended. The server mints a fresh pass on every step it + * carries a run through, but inside one step a long call and its retries can outlast it. + * + * So the model client's `fetch` is this one. A call the gateway refuses because its pass ran out + * (a 401 with `x-openbot-pass: expired`, and never any other 401: a provider's own refusal of its + * key passes through as a 401 without it) gets a fresh pass from the gateway (`POST /pass`, the refresh credential as its bearer) and is sent again once with it, inside the one + * `fetch`, so the client and the engine's own retries see one call. The fresh pass is the run's + * from then on, calls that run out together wait on one renewal, and a renewal that fails or a + * second refusal hands back the gateway's 401 as it came. + * + * This is OAuth's own way with an expired token (RFC 6750 §3.1, + * https://www.rfc-editor.org/rfc/rfc6750.html), and what google-auth does on a 401 + * (https://raw.githubusercontent.com/googleapis/google-auth-library-python/main/google/auth/transport/requests.py) + * and Claude Code with its OAuth token (https://code.claude.com/docs/en/authentication, + * https://github.com/anthropics/claude-code/issues/54443): refresh, then retry the call once. The + * Python harnesses do the same in shared/run_model_key.py. + * + * THE ENGINE AUTHENTICATES ITS RENEWAL. A confidential client authenticates when it refreshes a + * token (RFC 6749 §6 and §10.4, https://www.rfc-editor.org/rfc/rfc6749.html; RFC 9700 §4.14, + * https://www.rfc-editor.org/rfc/rfc9700.html), so a refresh credential that leaked is no use alone. + * The engine's own secret is `MANAGED_AGENT_TOKEN`, the token it checks on the server's runs: the + * renewal, and only the renewal, carries it as `x-openbot-agent-token`. An engine without one does + * not renew, and the call gets the gateway's 401. + * + * No credential is ever logged, nor shown when this is inspected. + */ + +/** The gateway's wires are under this path on the server. */ +const GATEWAY_PATH = "/api/model-provider/"; +/** The header the gateway's 401 carries when the pass it refused ran out, and its value. */ +export const PASS_HEADER = "x-openbot-pass"; +const PASS_EXPIRED = "expired"; +/** How long a renewal may take. */ +const RENEW_TIMEOUT_MS = 20_000; +/** The header the engine's own secret goes in, on a renewal only. */ +export const ENGINE_HEADER = "x-openbot-agent-token"; + +type Fetch = typeof fetch; + +/** `POST /pass`, the root being the address up to `/api/model-provider`. */ +export function passUrl(url: string): string | undefined { + let parsed: URL; + try { + parsed = new URL(url); + } catch { + return undefined; + } + const at = parsed.pathname.indexOf(GATEWAY_PATH); + if (at < 0) return undefined; + return `${parsed.origin}${parsed.pathname.slice(0, at + GATEWAY_PATH.length - 1)}/pass`; +} + +/** + * A run's pass and the credential that renews it: one object for the whole run. `engine` is the + * engine's own secret (`MANAGED_AGENT_TOKEN`), which authenticates a renewal: none, no renewal. + */ +export class RunPass { + #token: string; + readonly #refresh: string; + readonly #engine: string; + #renewing: Promise | undefined; + + constructor(token: string, refresh = "", engine = "") { + this.#token = token; + this.#refresh = refresh.trim(); + this.#engine = engine.trim(); + } + + /** The pass the run's calls carry now. */ + get token(): string { + return this.#token; + } + + get renewable(): boolean { + return this.#refresh.length > 0 && this.#engine.length > 0; + } + + /** + * The pass to send a call again with after `failed` ran out: the one another call already renewed + * it to, or a fresh one from the gateway, asked once for every call that waits. Undefined when + * there is none. + */ + renewed( + failed: string, + url: string, + base: Fetch, + ): Promise { + if (this.#token !== failed) return Promise.resolve(this.#token); + if (!this.renewable) return Promise.resolve(undefined); + this.#renewing ??= this.#renew(url, base).finally(() => { + this.#renewing = undefined; + }); + return this.#renewing; + } + + async #renew(url: string, base: Fetch): Promise { + const target = passUrl(url); + if (!target) return undefined; + let answer: Response; + try { + answer = await base(target, { + method: "POST", + headers: { + authorization: `Bearer ${this.#refresh}`, + [ENGINE_HEADER]: this.#engine, + }, + signal: AbortSignal.timeout(RENEW_TIMEOUT_MS), + }); + } catch (error) { + // A network error is no renewal: the caller gets the 401 it had. + console.warn( + `The model gateway could not be asked to renew this run's pass (${(error as Error)?.name ?? "error"}).`, + ); + return undefined; + } + const body = (await answer.json().catch(() => undefined)) as + | { token?: unknown } + | undefined; + const token = + answer.status === 200 && typeof body?.token === "string" + ? body.token.trim() + : ""; + if (!token) { + console.warn( + `The model gateway did not renew this run's pass (HTTP ${answer.status}).`, + ); + return undefined; + } + this.#token = token; + return token; + } + + toJSON(): string { + return "RunPass"; + } + + [Symbol.for("nodejs.util.inspect.custom")](): string { + return `RunPass { renewable: ${this.renewable} }`; + } +} + +/** The gateway refused the pass because it ran out, and only that. */ +function ranOut(response: Response): boolean { + return ( + response.status === 401 && + (response.headers.get(PASS_HEADER) ?? "").trim().toLowerCase() === + PASS_EXPIRED + ); +} + +/** A body that can be sent a second time as it was: anything but a stream. */ +function replayable(body: unknown): boolean { + return !( + typeof ReadableStream !== "undefined" && body instanceof ReadableStream + ); +} + +/** `headers` with `key` in place of the key they carry: Anthropic's `x-api-key`, OpenAI's bearer. */ +function carrying(headers: Headers, key: string): Headers { + const next = new Headers(headers); + const hadApiKey = next.has("x-api-key"); + if (hadApiKey) next.set("x-api-key", key); + if (next.has("authorization") || !hadApiKey) + next.set("authorization", `Bearer ${key}`); + return next; +} + +/** + * A `fetch` that sends each call to the gateway on the run's pass, renews the pass once when the + * gateway says it ran out, and sends the call again with the fresh one. Anything not on the + * gateway's path is sent as it is. + */ +export function passFetch(pass: RunPass, base: Fetch = fetch): Fetch { + const passing = async ( + input: Parameters[0], + init?: Parameters[1], + ): Promise => { + const url = + input instanceof Request + ? input.url + : input instanceof URL + ? input.href + : String(input); + if (!url.includes(GATEWAY_PATH) || input instanceof Request) + return base(input, init); + const headers = new Headers(init?.headers); + const sent = pass.token; + const response = await base(input, { + ...init, + headers: carrying(headers, sent), + }); + if (!ranOut(response) || !replayable(init?.body)) return response; + const fresh = await pass.renewed(sent, url, base); + if (!fresh) return response; + await response.body?.cancel().catch(() => undefined); + return base(input, { ...init, headers: carrying(headers, fresh) }); + }; + return passing as Fetch; +} diff --git a/shared/run_model_key.py b/shared/run_model_key.py index 991a423de0..890ea9a628 100644 --- a/shared/run_model_key.py +++ b/shared/run_model_key.py @@ -17,15 +17,54 @@ ONLY TO THE GATEWAY. The token replaces a key only on a request whose path is the gateway's (`/api/model-provider/`). A harness given a provider key of its own sends that key to the provider as before, and a run that brought no token sends what it always sent. + +A PASS THAT RUNS OUT IS RENEWED, AND THE CALL ASKED AGAIN ONCE. The token is a pass of about ten +minutes. Found on staging: an unattended job ran past it, and its next model call got the gateway's +401, which ended the run. The server mints a fresh pass on every step it carries a run through, but +inside one step a harness's own tool loop can outlast it. So the route may also carry a refresh +credential (`"refresh": "obgr_..."`), and a call the gateway refuses because its pass ran out (a 401 +with `x-openbot-pass: expired`, never any other 401: a provider's own refusal of its key passes +through as a 401 without it) gets a fresh pass from the gateway (`POST /pass` with the +refresh credential as its bearer) and is sent again once with it. That pass is the run's from then +on, for every task and thread of the run, and calls that run out together wait for one renewal. +A renewal that fails, and a second refusal after one, hand the caller the gateway's 401 as it came. +This is OAuth's own way with an expired token (RFC 6750 §3.1, +https://www.rfc-editor.org/rfc/rfc6750.html), and what google-auth does on a 401 +(https://raw.githubusercontent.com/googleapis/google-auth-library-python/main/google/auth/transport/requests.py) +and Claude Code with its OAuth token (https://code.claude.com/docs/en/authentication, +https://github.com/anthropics/claude-code/issues/54443): refresh, then retry the call once. + +THE ENGINE AUTHENTICATES ITS RENEWAL. A confidential client authenticates when it refreshes a +token (RFC 6749 §6 and §10.4, https://www.rfc-editor.org/rfc/rfc6749.html; RFC 9700 §4.14, +https://www.rfc-editor.org/rfc/rfc9700.html), so a refresh credential that leaked is no use alone. +This engine's own secret is `MANAGED_AGENT_TOKEN`, the token it checks on the server's runs: the +renewal, and only the renewal, carries it as `x-openbot-agent-token`. An engine without one does +not renew, and its caller gets the gateway's 401. """ from __future__ import annotations +import asyncio import json +import logging +import os +import threading +from concurrent.futures import Future from contextvars import ContextVar -from typing import Any +from typing import Any, Awaitable, Callable GATEWAY_PATH = "/api/model-provider/" +# The header the gateway's 401 carries when the pass it refused ran out, and its value. +PASS_HEADER = "x-openbot-pass" +PASS_EXPIRED = "expired" +# How long a renewal may take, and how long a call waits on another's. +PASS_TIMEOUT = {"connect": 10.0, "read": 20.0, "write": 10.0, "pool": 10.0} +PASS_WAIT_SECONDS = 30.0 +# The engine's own secret, which authenticates a renewal, and the header it goes in. +ENGINE_TOKEN = "MANAGED_AGENT_TOKEN" +ENGINE_HEADER = "x-openbot-agent-token" + +_log = logging.getLogger("openbot.run_model_key") # The props only the server writes and only this module reads, taken out of every run. SERVER_PROPS = ( @@ -35,34 +74,104 @@ "openbot_organization", ) -_run_key: ContextVar[str | None] = ContextVar("openbot_run_model_key", default=None) + +class RunPass: + """A run's pass to the gateway, and the credential that renews it. + + One object for the whole run, kept in the context variable: every task the run starts, and + every thread it hands work to, holds this same one, so a pass one of them renewed is the pass + all of them send next. `engine` is the engine's own secret, which authenticates a renewal: none, + no renewal. Never shows a credential in a repr or a log. + """ + + __slots__ = ("token", "refresh", "engine", "_mutex", "_renewing") + + def __init__(self, token: str, refresh: str = "", engine: str = ""): + self.token = token + self.refresh = refresh + self.engine = engine + self._mutex = threading.Lock() + self._renewing: Future | None = None + + def __repr__(self) -> str: + return f"RunPass(renewable={self.renewable})" + + @property + def renewable(self) -> bool: + return bool(self.refresh and self.engine) + + def _claim(self, failed: str) -> tuple[str | None, Future | None, bool]: + """After `failed` ran out: the pass to send again with now, or the renewal to wait on. + + Answers `(pass, None, False)` when another call already renewed it, `(None, renewal, + True)` to the call that is to renew it, `(None, renewal, False)` to one that waits on + that, and `(None, None, False)` when there is nothing to renew it with. + """ + with self._mutex: + if self.token != failed: + return self.token, None, False + if not self.renewable: + return None, None, False + if self._renewing is not None: + return None, self._renewing, False + self._renewing = Future() + return None, self._renewing, True + + def _settle(self, fresh: str | None) -> None: + with self._mutex: + if fresh: + self.token = fresh + renewing, self._renewing = self._renewing, None + if renewing is not None: + renewing.set_result(fresh) + + +_run_key: ContextVar[RunPass | None] = ContextVar("openbot_run_model_key", default=None) + + +def run_pass() -> RunPass | None: + """The pass of the run in progress, with its refresh credential, or None.""" + return _run_key.get() def run_key() -> str | None: """The token of the run in progress, or None.""" - return _run_key.get() + holder = _run_key.get() + return holder.token if holder is not None else None -def key_from(props: Any) -> str: - """The token the server sent in a run's forwarded props, or an empty string.""" +def _route(props: Any) -> dict: if not isinstance(props, dict): - return "" + return {} route = props.get("openbotModelRoute") if not isinstance(route, dict) or route.get("via") not in ("openai", "anthropic"): - return "" - token = route.get("token") + return {} + return route + + +def key_from(props: Any) -> str: + """The token the server sent in a run's forwarded props, or an empty string.""" + token = _route(props).get("token") return token.strip() if isinstance(token, str) else "" -def with_run_key(headers: Any, path: str) -> None: - """The run's token in place of the key on a request to the gateway; nothing otherwise. +def engine_token() -> str: + """This engine's own secret (`MANAGED_AGENT_TOKEN`), which authenticates a renewal, or "".""" + return (os.environ.get(ENGINE_TOKEN) or "").strip() + + +def refresh_from(props: Any) -> str: + """The credential that renews the run's token, when the server sent one, or an empty string.""" + refresh = _route(props).get("refresh") + return refresh.strip() if isinstance(refresh, str) else "" + + +def _put(headers: Any, key: str) -> None: + """`key` in place of the key a request carries. OpenAI's SDK sends its key as `Authorization: Bearer`, Anthropic's as `x-api-key`. Each is replaced where it is; a request with neither is given the bearer the gateway reads first. """ - key = _run_key.get() - if not key or GATEWAY_PATH not in path: - return had_api_key = "x-api-key" in headers if had_api_key: headers["x-api-key"] = key @@ -70,6 +179,168 @@ def with_run_key(headers: Any, path: str) -> None: headers["authorization"] = f"Bearer {key}" +def with_run_key(headers: Any, path: str) -> None: + """The run's token in place of the key on a request to the gateway; nothing otherwise.""" + key = run_key() + if key and GATEWAY_PATH in path: + _put(headers, key) + + +def _ran_out(response) -> bool: + """The gateway refused the pass because it ran out, and only that.""" + return ( + response.status_code == 401 + and (response.headers.get(PASS_HEADER) or "").strip().lower() == PASS_EXPIRED + ) + + +def _pass_url(url) -> str | None: + """`POST /pass`, the root being the address up to `/api/model-provider`.""" + path = url.path + at = path.find(GATEWAY_PATH) + if at < 0: + return None + root = path[: at + len(GATEWAY_PATH) - 1] + return f"{url.scheme}://{url.netloc.decode('ascii')}{root}/pass" + + +def _pass_request(request, holder: RunPass): + """The renewal: the refresh credential as its bearer, and the engine's own secret beside it.""" + url = _pass_url(request.url) + if url is None: + return None + return type(request)( + "POST", + url, + headers={"authorization": f"Bearer {holder.refresh}", ENGINE_HEADER: holder.engine}, + extensions={"timeout": PASS_TIMEOUT}, + ) + + +def _fresh_from(status: int, body: bytes) -> str | None: + if status != 200: + _log.warning("The model gateway did not renew this run's pass (HTTP %s).", status) + return None + try: + token = json.loads(body).get("token") + except (ValueError, AttributeError): + token = None + if not isinstance(token, str) or not token.strip(): + _log.warning("The model gateway renewed this run's pass with no token in its answer.") + return None + return token.strip() + + +def _replayable(request) -> bool: + """Whether the request's body is held whole, so it can be sent again as it was.""" + try: + request.content + except Exception: # httpx's RequestNotRead: a streamed body, gone once sent. + return False + return True + + +def send_on_pass(holder: RunPass | None, request, send: Callable, ask: Callable): + """`send(request)` on the run's pass, renewed once and the call sent again if it ran out. + + `ask(request)` sends the renewal (`POST /pass`); both send unchanged, without this + module's swap. A request that is not the gateway's, or a run with no pass, is sent as it is. + """ + if holder is None or GATEWAY_PATH not in request.url.path: + return send(request) + sent = holder.token + _put(request.headers, sent) + response = send(request) + if not _ran_out(response) or not _replayable(request): + return response + fresh, renewing, mine = holder._claim(sent) + if mine: + try: + fresh = _renew(request, holder, ask) + finally: + holder._settle(fresh) + elif renewing is not None: + try: + fresh = renewing.result(timeout=PASS_WAIT_SECONDS) + except Exception: + fresh = None + if not fresh: + return response + response.close() + _put(request.headers, fresh) + return send(request) + + +async def asend_on_pass( + holder: RunPass | None, + request, + send: Callable[[Any], Awaitable[Any]], + ask: Callable[[Any], Awaitable[Any]], +): + """`send_on_pass` for an async client.""" + if holder is None or GATEWAY_PATH not in request.url.path: + return await send(request) + sent = holder.token + _put(request.headers, sent) + response = await send(request) + if not _ran_out(response) or not _replayable(request): + return response + fresh, renewing, mine = holder._claim(sent) + if mine: + try: + fresh = await _arenew(request, holder, ask) + finally: + holder._settle(fresh) + elif renewing is not None: + try: + fresh = await asyncio.wait_for(asyncio.wrap_future(renewing), PASS_WAIT_SECONDS) + except Exception: + fresh = None + if not fresh: + return response + await response.aclose() + _put(request.headers, fresh) + return await send(request) + + +def _renew(request, holder: RunPass, ask: Callable) -> str | None: + renewal = _pass_request(request, holder) + if renewal is None: + return None + try: + answer = ask(renewal) + try: + return _fresh_from(answer.status_code, answer.read()) + finally: + answer.close() + except Exception as error: # A network error is no renewal: the caller gets the 401. + _unreached(error) + return None + + +def _unreached(error: Exception) -> None: + """Said in the log by the error's kind alone: its message may hold the address and more.""" + _log.warning( + "The model gateway could not be asked to renew this run's pass (%s).", + type(error).__name__, + ) + + +async def _arenew(request, holder: RunPass, ask: Callable) -> str | None: + renewal = _pass_request(request, holder) + if renewal is None: + return None + try: + answer = await ask(renewal) + try: + return _fresh_from(answer.status_code, await answer.aread()) + finally: + await answer.aclose() + except Exception as error: # A network error is no renewal: the caller gets the 401. + _unreached(error) + return None + + _installed = False @@ -98,12 +369,20 @@ def _patch(client, async_client) -> None: async_send = async_client.send def send(self, request, *args, **kwargs): - with_run_key(request.headers, request.url.path) - return sync_send(self, request, *args, **kwargs) + return send_on_pass( + _run_key.get(), + request, + lambda again: sync_send(self, again, *args, **kwargs), + lambda renewal: sync_send(self, renewal), + ) async def asend(self, request, *args, **kwargs): - with_run_key(request.headers, request.url.path) - return await async_send(self, request, *args, **kwargs) + return await asend_on_pass( + _run_key.get(), + request, + lambda again: async_send(self, again, *args, **kwargs), + lambda renewal: async_send(self, renewal), + ) client.send = send async_client.send = asend @@ -146,7 +425,7 @@ async def __call__(self, scope, receive, send): if not message.get("more_body", False): break body = b"".join(chunks) - token = "" + token = refresh = "" try: parsed = json.loads(body) if body else None except ValueError: @@ -157,6 +436,7 @@ async def __call__(self, scope, receive, send): props = parsed.get("forwarded_props") if isinstance(props, dict): token = key_from(props) + refresh = refresh_from(props) if any(name in props for name in SERVER_PROPS): for name in SERVER_PROPS: props.pop(name, None) @@ -170,7 +450,8 @@ async def __call__(self, scope, receive, send): ] + [(b"content-length", str(len(body)).encode("ascii"))], } - reset = _run_key.set(token or None) + holder = RunPass(token, refresh, engine_token()) if token else None + reset = _run_key.set(holder) try: await self.app(scope, _replay(body, receive), send) finally: