diff --git a/gateway/app.py b/gateway/app.py index 22c4c990..b8b0d923 100644 --- a/gateway/app.py +++ b/gateway/app.py @@ -5254,8 +5254,10 @@ def _with_provider_base(conn: dict | None) -> dict | None: return conn -_PROVIDER_REFUSAL_RE = re.compile(r"\b(401|403|429)\b|unauthori[sz]ed|incorrect api key|invalid_api_key|invalid api key|" - r"insufficient_quota|rate[ _-]?limit|quota|forbidden", re.IGNORECASE) +_PROVIDER_REFUSAL_RE = re.compile(r"\b(401|402|403|429)\b|unauthori[sz]ed|incorrect api key|invalid_api_key|invalid api key|" + r"insufficient_quota|rate[ _-]?limit|quota|forbidden|payment required|" + r"credit balance is too low|insufficient (?:credits?|balance|funds)|out of credits?", + re.IGNORECASE) # ("too many requests" alone is not on it: Entra's own throttling answers a 502 with "AADSTS90055: Too many # requests.", which is the sign-in failing, not the provider turning the key down, and moves on as before.) # Of the provider's answers that match above, three are not the key being refused, and saying they were sends people @@ -5266,6 +5268,13 @@ def _with_provider_base(conn: dict | None) -> dict | None: # and passes in 41 seconds. So the signals are read strongest first (_provider_failure_kind). _PROVIDER_NO_CREDIT_RE = re.compile(r"insufficient_(?:\w+_)?quota|out of credits?|credit balance is too low|" r"insufficient (?:credits?|balance|funds)", re.I) +# HTTP's own word for an account that has to pay first: read on the first line only (a status there is the answer's). +_PROVIDER_PAYMENT_RE = re.compile(r"\b402\b|payment required", re.I) +# How far past the first line a no-credit code is read: the runner's reason is often the CLI's "Error code: 429" (or 403) +# line with the provider's JSON body on the lines under it, and TokenRouter's member cap (insufficient_user_quota) or +# OpenAI's empty account (insufficient_quota) is only in that body. Only a no-credit code is read there, +# and only when the first line is the provider refusing: a diagnostic further down never makes a refusal. +_PROVIDER_NO_CREDIT_SPAN = 2000 _PROVIDER_PLAN_QUOTA_RE = re.compile(r"exceeded your (?:current )?quota|check your plan and billing", re.I) _PROVIDER_NO_QUOTA_RE = re.compile(r"\bquota\b", re.I) _PROVIDER_RATE_LIMIT_RE = re.compile(r"\b429\b|rate[ _-]?limit|too many requests|throttl|resource[ _]exhausted", re.I) @@ -5296,8 +5305,8 @@ def _provider_failure_kind(err: str) -> str: # '401 {"error": "unknown relay token"}' on a 127.0.0.1 address, which is never the provider and never the key. if "/hr-mcp-" in first or "unknown relay token" in first.lower() or not _PROVIDER_REFUSAL_RE.search(first): return "" - if _PROVIDER_NO_CREDIT_RE.search(first): # a code or sentence that can only mean no credit - return "quota" + if _PROVIDER_PAYMENT_RE.search(first) or _PROVIDER_NO_CREDIT_RE.search((err or "")[:_PROVIDER_NO_CREDIT_SPAN]): + return "quota" # a status or code that can only mean no credit if _PROVIDER_RETRY_AFTER_RE.search(first): # a provider names a wait only when waiting helps return "rate_limit" if _PROVIDER_PLAN_QUOTA_RE.search(first): # the plan's quota, with no wait named @@ -5326,21 +5335,77 @@ def _provider_retry_after(err: str) -> float | None: return n / 1000 if unit.startswith("ms") or unit.startswith("milli") else n * 60 if unit.startswith("m") else n -def _provider_failure_detail(err: str) -> dict: +def _provider_failure_detail(err: str, kind: str = "", extra: dict | None = None) -> dict: """The error.detail fields that say why the provider turned the turn down and whether a retry can succeed, so a client with automatic retries stops on a refused key or an empty account instead of matching words - in the message. Empty when the provider's line is not one of the four. None of the provider's text.""" - kind = _provider_failure_kind(err) - if not kind: + in the message. Empty when the provider's line is not one of the four. None of the provider's text. + `kind` is the model-call door's own reading of the provider's answer when it saw one (_relay_refusal_kind), + which wins over reading the runner's line; `extra` adds what that door knew of the call (_relay_refusal_extra): + the provider's name, the HTTP status it answered, the model it refused and the name of the connection.""" + kind = kind or _provider_failure_kind(err) + if kind not in _PROVIDER_FAILURE_REASONS: return {} reason, retryable = _PROVIDER_FAILURE_REASONS[kind] out: dict = {"reason": reason, "retryable": retryable} wait = _provider_retry_after(err) if kind == "rate_limit" else None if wait is not None: out["retry_after_seconds"] = wait + out.update({k: val for k, val in (extra or {}).items() if val not in (None, "") and k not in out}) return out +# The key's own characters a provider's words may echo ("Incorrect API key provided: sk-…") are taken out before those +# words are shown: the person who reads a failed task need not be one who may read the instance's keys (the +# hosted twin's _without_key). Any run of _SCRUB_MIN or more of the key's characters is caught as the key is. +_SCRUB_MIN = 8 + + +def _without_key(text: str, key: str) -> str: + """`text` with the connection's key, and any run of _SCRUB_MIN or more of its characters, replaced by "…". Every + _SCRUB_MIN-character window of the key is found and the runs they cover are replaced whole.""" + text, key = str(text or ""), str(key or "") + if text and len(key) >= _SCRUB_MIN: + hit = bytearray(len(text)) + for w in {key[i:i + _SCRUB_MIN] for i in range(len(key) - _SCRUB_MIN + 1)}: + at = text.find(w) + while at != -1: + hit[at:at + _SCRUB_MIN] = b"\x01" * _SCRUB_MIN + at = text.find(w, at + 1) + if any(hit): + out, i = [], 0 + while i < len(text): + if hit[i]: + while i < len(text) and hit[i]: + i += 1 + out.append("…") + else: + out.append(text[i]) + i += 1 + text = "".join(out) + return text + + +# The names a person knows each provider by, as Bring Your Own Key lists them (ui/src/lib/providers.ts), for the +# provider ids a connection carries: "Your tokenrouter key was refused" named the provider by its wiring's id (a +# hosted customer's failed tasks, 11-28). A name not here (a custom endpoint's, which the operator chose) is said as it is. +_PROVIDER_BRANDS = {"anthropic": "Anthropic", "openai": "OpenAI", "openai-api": "OpenAI", "google": "Google AI", + "gemini": "Google AI", "typesafe": "TypeSafe AI", "qoder": "Qoder", "openrouter": "OpenRouter", + "tokenrouter": "TokenRouter", "vercel": "Vercel AI Gateway", "llmtr": "LLMTR", + "elevenlabs": "ElevenLabs", "azure-foundry": "Azure OpenAI", "azure": "Azure OpenAI", + "bedrock": "AWS Bedrock", "deepseek": "DeepSeek"} + + +def _provider_brand(label: str) -> str: + """A provider's name as a person knows it (_PROVIDER_BRANDS), or the label as it is.""" + return _PROVIDER_BRANDS.get(str(label or "").strip().lower(), str(label or "").strip() or "your provider") + + +def _as_sentence(text: str) -> str: + """`text` ended as a sentence, so the next step reads as its own sentence after the provider's words.""" + t = str(text or "").strip() + return t if t.endswith((".", "!", "?")) else f"{t}." + + # A Responses provider refusing a replayed history: OpenAI's encrypted reasoning items are opened # only by the account that produced them, and a route served from more than one upstream account # hands the next turn items its upstream cannot open. Measured on TokenRouter's gpt-5.4 route: a @@ -5365,34 +5430,42 @@ def _history_refusal(rec: dict, reason: str) -> str: f"produced under another route). Start a new task for {model}{keep}.") -def _refusal_message(conn: dict | None, err: str) -> str: - """What a turn says when the provider refused the org's own connection. A connection that signs - in with Microsoft Entra has no key: what was refused is the application, by Entra (a wrong - directory, id or secret) or by the resource (no role on it), and the provider's words say which.""" - # The vendor the operator connected, not the name the runner speaks it as: an integration's - # connection carries the runner's wiring (`provider`, e.g. "tokenrouter" for any OpenAI-format - # custom endpoint on some bases) and keeps the vendor in `_vendor`. +def _conn_vendor_label(conn: dict | None) -> str: + """The provider a person knows a connection by. The vendor the operator connected, not the name the runner speaks it + as: an integration's connection carries the runner's wiring (`provider`, e.g. "tokenrouter" for any OpenAI-format + custom endpoint on some bases) and keeps the vendor in `_vendor`. A custom endpoint has no vendor's name to give, and + "add credit with custom" names nobody: it is called by the name the person gave the connection.""" provider = str((conn or {}).get("_vendor") or (conn or {}).get("provider") or "your provider") - # A custom endpoint has no vendor's name to give, and "add credit with custom" names nobody: it is called by the - # name the person gave the connection. if provider == "custom": cname = str((conn or {}).get("name") or "") provider = (cname.split(":", 1)[1] if cname.startswith("integration:") else cname).strip() or "custom endpoint" + return provider + + +def _refusal_message(conn: dict | None, err: str, kind: str = "") -> str: + """What a turn says when the provider refused the org's own connection. A connection that signs + in with Microsoft Entra has no key: what was refused is the application, by Entra (a wrong + directory, id or secret) or by the resource (no role on it), and the provider's words say which. + It says what the provider answered, then what the person can do about it: a task that names its failure and not its + way out left a hosted customer's scheduled runs failing for a week (11-28). `kind` is the model-call door's + own reading of the provider's answer (_relay_refusal_kind) when it saw one.""" + p = _provider_brand(_conn_vendor_label(conn)) what = "connection" if str((conn or {}).get("auth") or "").strip().lower() == "entra" else "key" - said = err or "the provider returned an error" - kind = _provider_failure_kind(err) + said = _as_sentence(err or "the provider returned an error") + kind = kind or _provider_failure_kind(err) if kind == "rate_limit": wait = _provider_retry_after(err) when = (f"It asked to wait {wait:g} s before trying again." if wait is not None and wait < 120 else f"It asked to wait {wait / 60:.0f} min before trying again." if wait is not None else "Wait a minute and try again.") - return f"{provider} rate-limited this task (too many requests for now; your {what} was not refused). {when} {said}" + return f"{p} rate-limited this task (too many requests for now; your {what} was not refused). {when} {said}" if kind == "quota": - return f"Your {provider} account has no quota or credit left for this {what}; add credit with {provider}, then try again: {said}" + return (f"Your {p} account has no quota or credit left for this {what}: {said} Add credit with {p}, " + f"or replace or remove this {what} under Bring Your Own Key.") if kind == "model": - return (f"{provider} refused this model for your {what} (the {what} itself was accepted). Choose another model, " - f"or enable this one for your account with {provider}: {said}") - return f"Your {provider} {what} was refused: {said}" + return (f"{p} refused this model for your {what} (the {what} itself was accepted): {said} " + f"Choose another model, or enable this one for your account with {p}.") + return f"Your {p} {what} was refused: {said} Check this {what} with {p}, or replace or remove it under Bring Your Own Key." def _failure_detail(rec: dict) -> dict: @@ -5719,6 +5792,178 @@ async def _broker_send(rc: httpx.AsyncClient, req: httpx.Request, org_supplied: raise HTTPException(403, f"This connection's address can't be used: {why.removeprefix('that address cannot be used: ')}.") from None +# ── a provider's refusal of the instance's own connection, read where the agent's model calls pass ────────────────────── +# Every model call a sandbox makes passes this door, so here a provider's answer is known as it was given: its HTTP status +# and its own error body. A turn's failure used to be read from the agent's account of it instead (the runner's line from +# the CLI's output), so its reason was whatever each CLI printed, and an agent that retried, stopped quietly or answered +# "I couldn't reach the model" left the task's top-level error saying nothing of the key. A hosted customer's scheduled +# runs failed for a week on a TokenRouter key that answered 403, each reading only "the model provider refused the +# request" (11-21..11-28). So a refusal no retry can change is recorded here, on the task, for the turn to stop on and +# say (_turn_relay_refusal): the key refused (401, 403), no credit left (402, an empty account's code on 400/403/429), or +# this model refused for the key (a model-not-found code). A rate limit is not recorded: it passes on its own, and the +# agent's own backoff is the right answer to it. On a self-hosted install every key is the operator's own. +_RELAY_REFUSAL_STATUSES = frozenset({400, 401, 402, 403, 404, 429}) +_relay_refusals: dict[str, dict] = {} # sid -> the last refusal this process recorded for that task +_RELAY_REFUSALS_KEEP = 5000 +_relay_refusal_counts = _OpsDrops("relay_refusals", 300, ("refused", "model", "quota", "unshared", "turn_stopped", + "turn_said")) +# A provider's own code for a model it does not serve this key (the hosted twin's save-time model check reads the same). +_OWN_KEY_MODEL_GONE_RE = re.compile(r"model_not_found|model_not_allowed|model_access_denied|" + r"does not exist or you do not have access", re.I) +_VERSION_SUFFIX_RE = re.compile(r"^(-(\d{2,}|v\d+|preview|latest))+$") # -20251001, -001, -v2, -preview-05-20; never -lite + + +def _same_model(asked: str, served: str) -> bool: + """Whether two names are one model, allowing the vendor prefix an aggregator adds or drops (google/gemini-3.8-flash + is gemini-3.8-flash) and a dated or versioned suffix a provider appends (claude-haiku-4-5-20251001, gemini-3.5-flash-001).""" + def norm(m: str) -> str: + m = (m or "").strip().lower().split("/")[-1] + return m.replace(".", "-") + a, s = norm(asked), norm(served) + if not a or not s: + return False + if a == s: + return True + long, short = (s, a) if len(s) > len(a) else (a, s) + return long.startswith(short + "-") and _VERSION_SUFFIX_RE.match(long[len(short):]) is not None + + +def _provider_error_said(body: bytes) -> str: + """The provider's own words for a refusal, from its error body: `error.message` with its code or type in front when + it names one (OpenAI, Anthropic, TokenRouter, OpenRouter, Google's `error.status`), a top-level `message`, `detail` + or `error` string, else the body's text. One line, at most 400 characters; the key is taken out by the caller.""" + raw = (body or b"")[:20000].decode("utf-8", "replace") + text = "" + try: + doc = json.loads(raw) + except Exception: # noqa: BLE001 — not JSON: the text itself + doc = None + if isinstance(doc, list) and doc and isinstance(doc[0], dict): # Google answers some errors as a one-item list + doc = doc[0] + if isinstance(doc, dict): + err = doc.get("error") + if isinstance(err, dict): + msg = str(err.get("message") or "").strip() + code = str(err.get("code") or err.get("type") or err.get("status") or "").strip() + text = f"{code}: {msg}" if code and msg and code not in msg else (msg or code) + elif isinstance(err, str): + text = err + if not text: + text = str(doc.get("message") or doc.get("detail") or doc.get("error_description") or "") + return " ".join((text or raw).split())[:400] + + +def _relay_refusal_kind(status: int, said: str) -> str: + """What a provider's answer to a model call says no retry can change: "refused" (the key), "quota" (no credit or + quota left), "model" (this model, for this key), or "" (anything else, a rate limit among them). Read from the status + the provider answered and its own words (_provider_error_said), never a CLI's.""" + line = f"{status} {said}" + if status == 402: + return "quota" + if status in (400, 404): + if _PROVIDER_NO_CREDIT_RE.search(line): # Anthropic answers an empty account 400 "credit balance is too low" + return "quota" + return "model" if _OWN_KEY_MODEL_GONE_RE.search(line) else "" + kind = _provider_failure_kind(line) + if status == 429: + return "quota" if kind == "quota" else "" # a rate limit passes; only an account with nothing left is final + if status in (401, 403): + return "" if kind == "rate_limit" else (kind or "refused") + return "" + + +async def _note_relay_refusal(sid: str, conn: dict, conn_name: str, provider: str, native: str, status: int, + body: bytes) -> dict | None: + """Record, for the task `sid`, a provider's refusal of a model call that no retry can change (_relay_refusal_kind); + None when the answer is not one. Kept in this process and in the control store, so the turn's own loop sees it on + whichever replica it runs (_turn_relay_refusal). The provider's words go without the connection's key + (_without_key). Never raises: the answer goes back to the agent as it came either way.""" + try: + said = _provider_error_said(body) + kind = _relay_refusal_kind(int(status), said) + if not kind: + return None + rec = {"at": time.time(), "kind": kind, "status": int(status), "provider": str(provider or ""), + "conn": str(conn_name or ""), "model": str(native or ""), + "said": _without_key(f"{int(status)}: {said}" if said else str(int(status)), str(conn.get("api_key") or ""))[:400]} + if len(_relay_refusals) >= _RELAY_REFUSALS_KEEP: + _relay_refusals.clear() + _relay_refusals[sid] = rec + _relay_refusal_counts.bump(kind) + print(f"[broker] the provider refused the connection provider={provider} status={int(status)} kind={kind} " + f"model={native!r} sid={sid}", flush=True) + if control_store.enabled(): + try: + await control_store.refusal_put(sid, rec) + except Exception as e: # noqa: BLE001 — this process still has it; the turn's end reads the agent's own account + _relay_refusal_counts.bump("unshared") + print(f"[broker] refusal not shared ({type(e).__name__}) sid={sid}", flush=True) + return rec + except Exception as e: # noqa: BLE001 + print(f"[broker] refusal not recorded ({type(e).__name__}) sid={sid}", flush=True) + return None + + +_FINAL_REFUSALS = ("refused", "model", "quota") + + +async def _turn_relay_refusal(sid: str, conn_name: str, models: tuple[str, ...], since: float, *, + check_store: bool = True) -> dict | None: + """The refusal (_note_relay_refusal) a turn stops on and says, or None: one made since the turn started, on the + connection the turn runs on, of the model it runs, by any name it goes by (the one asked for, the one the connection + calls it; _same_model allows an aggregator's vendor prefix). A refusal of another model (an agent's side call to a small + model the key may not reach) is not the turn's: it goes on. This process's record first, the control store's when + `check_store`; a store that can't be read is no refusal (the agent's own account stands, as before).""" + def fits(r) -> bool: + return (isinstance(r, dict) and str(r.get("kind") or "") in _FINAL_REFUSALS + and float(r.get("at") or 0) >= since and str(r.get("conn") or "") == conn_name + and any(_same_model(str(r.get("model") or ""), m) for m in models)) + r = _relay_refusals.get(sid) + if fits(r): + return r + if check_store and control_store.enabled(): + try: + r = await control_store.refusal_get(sid) + except Exception: # noqa: BLE001 + return None + if fits(r): + return r + return None + + +def _turn_had_output(translator: "_RespTranslator") -> bool: + """Whether a turn that says it completed had anything from the model: output tokens when the agent reported its usage, + else any words of the agent's own. An agent that "completed" with neither, after the provider refused its model, + completed nothing. Words with no usage are taken as an answer: an answered turn is never overruled on a guess.""" + usage = getattr(translator, "usage", None) or {} + if isinstance(usage, dict) and usage: + try: + return int(usage.get("output_tokens") or 0) > 0 + except (TypeError, ValueError): + return True + return bool(getattr(translator, "any_text", False) or getattr(translator, "output", None)) + + +def _relay_refusal_extra(ref: dict, provider: str, conn_name: str) -> dict: + """error.detail's account of whose and which call it was, beside its reason: the provider by the name a person knows + it by, the connection's own name (an integration's, without its "integration:"), and, when the model-call door saw the + answer, the HTTP status the provider gave and the model it refused. None of its words.""" + name = str(conn_name or "") + out: dict = {"provider": _provider_brand(provider), "connection": name.split(":", 1)[1] if name.startswith("integration:") else name} + if ref: + out["status"] = ref.get("status") + out["model"] = str(ref.get("model") or "") + return out + + +def _unread(up: httpx.Response, data: bytes) -> httpx.Response: + """An answer whose body was read here, as if unread, so the pass-through below hands it on exactly as it came. + aread() returns the decoded body, so the encoding and length headers do not travel with it.""" + headers = [(k, val) for k, val in up.headers.items() if k.lower() not in ("content-encoding", "content-length")] + return httpx.Response(up.status_code, headers=headers, stream=httpx.ByteStream(data), request=up.request, + extensions=up.extensions) + + @app.api_route("/v1/llm/{path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE"]) async def llm_broker(path: str, request: Request): if _broker_token(request).startswith(memory_relay.PREFIX): @@ -5776,6 +6021,19 @@ async def llm_broker(path: str, request: Request): rc = _relay_checked_client() if org_supplied else _relay_client() req = rc.build_request(request.method, url, headers=headers, content=body or None) up = await _broker_send(rc, req, org_supplied, sid) + # a refusal no retry can change is recorded for the task's turn to stop on and say: every key here is the + # operator's own, and only a model call (a POST that names its model) is one + native = _body_model_name(body) if request.method == "POST" else "" + notes_refusal = bool(native) + + async def handed_back(resp: httpx.Response, refused: bytes) -> Response: + """A provider's 400 handed back to the agent as read, recorded first when it is one no retry can change.""" + if notes_refusal: + await _note_relay_refusal(sid, conn, conn_name, provider, native, resp.status_code, refused) + return Response(content=refused, status_code=400, media_type=resp.headers.get("content-type"), + headers={k: val for k, val in resp.headers.items() + if k.lower() not in ("content-length", "transfer-encoding", "connection", + "content-encoding")}) if provider == "google" and up.status_code == 400: # Google's OpenAI-compatible endpoint refuses a request that names any field it does not # know ("Unknown name \"store\": Cannot find field."), and the harnesses send OpenAI's @@ -5801,10 +6059,7 @@ async def llm_broker(path: str, request: Request): # aread() hands back the DECODED body; passing Google's content-encoding header along with # it made the harness fail on the error itself ("Response decompression failed", "Failed # to process error response") instead of reading the refusal, 2026-09-06. - return Response(content=refused, status_code=400, media_type=up.headers.get("content-type"), - headers={k: val for k, val in up.headers.items() - if k.lower() not in ("content-length", "transfer-encoding", "connection", - "content-encoding")}) + return await handed_back(up, refused) if up.status_code == 400 and body and b"reasoning_effort" in body: # An aggregator that turns `reasoning_effort` into Anthropic's legacy thinking block is # refused by the newer Claude models; the request goes again without the effort, at the @@ -5818,10 +6073,12 @@ async def llm_broker(path: str, request: Request): req = rc.build_request(request.method, url, headers=headers, content=body or None) up = await _broker_send(rc, req, org_supplied, sid) else: - return Response(content=refused, status_code=400, media_type=up.headers.get("content-type"), - headers={k: val for k, val in up.headers.items() - if k.lower() not in ("content-length", "transfer-encoding", "connection", - "content-encoding")}) + return await handed_back(up, refused) + if notes_refusal and up.status_code in _RELAY_REFUSAL_STATUSES: + # the provider's own answer, read once and passed on unchanged (_unread), recorded when no retry can change it + refused = await up.aread() + up = _unread(up, refused) + await _note_relay_refusal(sid, conn, conn_name, provider, native, up.status_code, refused) # A Google answer's tool calls carry the signatures the next request must replay. tap = _GoogleSigTap(up.headers.get("content-type", "")) if (provider == "google" and up.status_code < 400) else None @@ -6080,6 +6337,7 @@ async def readyz(response: Response) -> dict: checks["redis"] = {"configured": bool(REDIS_URL), **_redis_ok} # reported, not gating checks["bus_drops"] = dict(_bus_drops.counts) # cumulative live-event drops (HR-INF-018 visibility) checks["billing_drops"] = dict(_billing_drops.counts) # lost usage reports (HR-INF-023 visibility) + checks["relay_refusals"] = dict(_relay_refusal_counts.counts) # connections the provider refused, turns stopped on it checks["turns_reads"] = dict(_turns_reads.counts) # conversation reads that failed; turns taken from their session checks["identity"] = {"mode": HR_IDENTITY_MODE, **_identity_obs.counts} # LIVE-B rollout visibility checks["credit"] = {"mode": HR_CREDIT_GATE, **_credit_obs.counts} # HR-INF-023 admission-gate rollout @@ -8200,7 +8458,10 @@ def fail(self, message: str, error: dict | None = None) -> list[dict]: # 2026-08-20). The error EVENT mirrors error.code, so the two never disagree. self.error = error or {"type": "harness_error", "code": "turn_failed", "message": message} evs = self._close_cur() - evs.append(self._ev("error", code=self.error["code"], message=self.error["message"], param=None)) + # The error event carries the error's detail too (why, whether a retry can succeed, whose call): a client reading + # the stream knew only the code and the words, and had to wait for the response to know what to do. + evs.append(self._ev("error", code=self.error["code"], message=self.error["message"], param=None, + **({"detail": self.error["detail"]} if self.error.get("detail") else {}))) evs.append(self._ev("response.failed", response=self._response_obj("failed"))) return evs @@ -11796,6 +12057,12 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s rec["status"] = "cancelled" await _vertex_upsert(sid, {"status": "cancelled", "turn_status": "cancelled"}) break + # The refusals this turn stops on and says (_turn_relay_refusal): on this connection (the name its credential + # carries), for the model the turn runs by any name it goes by, and made after this moment, so an earlier turn's + # refusal never stops this one (one made before a key was fixed). Every key here is the operator's own. + refusal_conn = str(conn.get("name") or "") # what _auth_from_conn put in the turn's credential, exactly + refusal_models = tuple(str(m) for m in (body.get("model"), body.get("native_model"), model_req) if m) + refusal_since = time.time() try: started = await _sandbox_json("/turn", sid, body=body) # retries cold-start / transient empties except _SandboxRefused as e: @@ -11885,6 +12152,22 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s except Exception: # noqa: BLE001 terminal = "cancelled" # sandbox unreachable — settle the turn terminally anyway break + # The provider refused this turn's own model, as its model-call door saw it: no retry the agent + # makes can change that, so the turn stops here and says it, at the top, in place of the agent's retries and + # its own account of them. This process's record at once; the control store's every third interval. + if (not kill_sent + and (ref := await _turn_relay_refusal(sid, refusal_conn, refusal_models, refusal_since, + check_store=every("refusal", 3)))): + kill_sent = True + try: + await _sandbox_json(f"/turn/{rt}/cancel", sid, "POST", attempts=2) + except Exception: # noqa: BLE001 — the turn ends failed on the refusal whether or not the agent heard + pass + rec["relay_refusal"] = ref + _relay_refusal_counts.bump("turn_stopped") + print(f"[turn] stopped on the provider's refusal sid={sid} status={ref.get('status')} " + f"kind={ref.get('kind')}", flush=True) + break # terminal stays None: the turn fails, with the refusal as its reason try: s = await _sandbox_json(f"/turn/{rt}", sid, "GET", attempts=3, base=2.0, params={"since": fed_upto, **({"wait": RESP_HOLD_S} if RESP_HOLD_S > 0 else {})}) @@ -11977,16 +12260,34 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s break if pending: # the loop was left between two writes (a cancel, a poll that kept failing) await _trace_flush(tr, {"events": pending, "n_total": fed_upto}) + # The model-call door's record of the provider's refusal is the turn's reason when there is one: the + # turn stopped on it above, or the agent ended first, failed in its own words or "completed" with nothing from the + # model (an apology the CLI wrote itself). Read once more here, the control store's included, before it settles. + if terminal in (None, "completed") and not rec.get("relay_refusal"): + ref = await _turn_relay_refusal(sid, refusal_conn, refusal_models, refusal_since, check_store=True) + if ref and (terminal is None or not _turn_had_output(translator)): + rec["relay_refusal"] = ref + terminal = None + _relay_refusal_counts.bump("turn_said") + _ref = rec.get("relay_refusal") or {} + if not terminal and _ref: + # what the provider answered, as the door read it, is the last word on this connection + rec["tried"].append({"connection": name, "status": f"refused {_ref.get('status')}", + "error": str(_ref.get("said") or "")}) _last_err = str(rec["tried"][-1].get("error") or "") if rec["tried"] else "" if (not terminal and rec["tried"] and rec["tried"][-1].get("connection") == name - and rec["tried"][-1].get("status") and _provider_refused(_last_err)): + and rec["tried"][-1].get("status") and (_ref or _provider_refused(_last_err))): # The provider refused this key. That is configuration, not an outage to route around: # falling through to the next connection ran the task on another key while the user # believed this one worked. On a self-hosted install every key is the operator's own, # so the rule is the refusal itself, not which store the key came from. Other failures # (a transient error, a timeout) still move on to the next connection. - rec["error_message"] = _refusal_message(conn, _last_err) - rec["provider_failure"] = _provider_failure_detail(_last_err) + # The provider's words go without the key: some echo it in a refusal ("Incorrect API key provided: sk-…"). + _last_err = _without_key(_last_err, str(conn.get("api_key") or "")) + _kind = str(_ref.get("kind") or "") # the door's reading of the provider's answer, when it saw one + rec["error_message"] = _refusal_message(conn, _last_err, _kind) + rec["provider_failure"] = _provider_failure_detail(_last_err, _kind, + _relay_refusal_extra(_ref, _conn_vendor_label(conn), name)) status = "failed" rec["status"] = "failed" await _vertex_upsert(sid, {"status": "failed", "turn_status": "failed", "last_connection": name}) diff --git a/gateway/control_store.py b/gateway/control_store.py index 41f86c1f..5ab376a2 100644 --- a/gateway/control_store.py +++ b/gateway/control_store.py @@ -539,6 +539,36 @@ async def resp_is_cancelled(org: str, rid: str) -> bool: return False +# ── a provider's refusal of a task's connection, seen where its model calls pass ──────────────────────────────────── +# The process that saw it may not be the one whose turn loop must stop on it. Keyed by the task alone (every caller knows +# the session id), one item per task, the last refusal written over the one before. An hour is longer than any turn waits +# to read it; the turn takes only a refusal made after it started. +REFUSAL_TTL_S = 3600 + + +def _refusal_id(sid: str) -> str: + return f"refusal::{sid}" + + +async def refusal_put(sid: str, rec: dict) -> None: + """Record the task's latest refusal (the model-call door's _note_relay_refusal). Raises on a store error: the caller + counts it.""" + cont = await _container() + doc_id = _refusal_id(sid) + await _retryable(lambda: cont.upsert_item({**rec, "id": doc_id, "pk": doc_id, "ts": time.time(), "ttl": REFUSAL_TTL_S})) + + +async def refusal_get(sid: str) -> dict | None: + """The task's latest refusal, or None when none was recorded. Raises on a store error.""" + cont = await _container() + cex = _exceptions() + try: + doc = await cont.read_item(_refusal_id(sid), partition_key=_refusal_id(sid)) + except cex.CosmosResourceNotFoundError: + return None + return {k: doc.get(k) for k in ("at", "kind", "status", "provider", "conn", "model", "said")} + + async def try_lock(name: str, ttl_s: int) -> bool: """One-shot distributed mutex via atomic create_item: returns True iff WE created the lock doc (nobody else holds it), False if it already exists (another holder — skip this cycle). Per-item diff --git a/gateway/tests/test_entra_connection.py b/gateway/tests/test_entra_connection.py index b3da61e5..ae6e6b8c 100644 --- a/gateway/tests/test_entra_connection.py +++ b/gateway/tests/test_entra_connection.py @@ -121,9 +121,15 @@ def test_a_turn_refused_on_an_entra_connection_does_not_speak_of_a_key(): for err in (entra, role): assert gw._provider_refused(err) # so the turn stops here and does not try another connection said = gw._refusal_message({"provider": "azure", "auth": "entra"}, err) - assert said == f"Your azure connection was refused: {err}" and " key " not in said - assert gw._refusal_message({"provider": "azure"}, role) == f"Your azure key was refused: {role}" - assert gw._refusal_message({"provider": "openai"}, "") == "Your openai key was refused: the provider returned an error" + assert said == (f"Your Azure OpenAI connection was refused: {gw._as_sentence(err)} " + "Check this connection with Azure OpenAI, or replace or remove it under Bring Your Own Key.") + assert " key " not in said + assert gw._refusal_message({"provider": "azure"}, role) == ( + f"Your Azure OpenAI key was refused: {role}. Check this key with Azure OpenAI, or replace or remove it under " + "Bring Your Own Key.") + assert gw._refusal_message({"provider": "openai"}, "") == ( + "Your OpenAI key was refused: the provider returned an error. Check this key with OpenAI, or replace or remove it " + "under Bring Your Own Key.") def test_another_secret_or_scope_is_another_token(monkeypatch): diff --git a/gateway/tests/test_provider_failure_reason.py b/gateway/tests/test_provider_failure_reason.py index edb14328..e29dad87 100644 --- a/gateway/tests/test_provider_failure_reason.py +++ b/gateway/tests/test_provider_failure_reason.py @@ -71,8 +71,8 @@ def test_a_quota_that_passes_with_a_wait_is_a_rate_limit_and_an_empty_account_is def test_a_rate_limit_says_the_key_was_not_refused_and_to_wait(): err = "tokenrouter: 429 Too Many Requests" said = gw._refusal_message(CONN, err) - assert said.startswith("tokenrouter rate-limited this task (too many requests for now; your key was not refused).") - assert "Wait a minute and try again." in said and said.endswith(err) + assert said.startswith("TokenRouter rate-limited this task (too many requests for now; your key was not refused).") + assert "Wait a minute and try again." in said and said.endswith(err + ".") @pytest.mark.parametrize("err,wait", [ @@ -88,9 +88,11 @@ def test_the_wait_the_provider_names_is_passed_on(err, wait): def test_an_empty_account_and_a_refused_model_say_what_to_do(): quota = gw._refusal_message(CONN, "Error code: 429 - {'error': {'code': 'insufficient_quota'}}") - assert quota.startswith("Your tokenrouter account has no quota or credit left for this key; add credit with tokenrouter") + assert quota.startswith("Your TokenRouter account has no quota or credit left for this key: Error code: 429") + assert quota.endswith("Add credit with TokenRouter, or replace or remove this key under Bring Your Own Key.") model = gw._refusal_message(CONN, "tokenrouter 403: your key is not allowed to use model claude-opus-5") - assert model.startswith("tokenrouter refused this model for your key (the key itself was accepted). Choose another model") + assert model.startswith("TokenRouter refused this model for your key (the key itself was accepted): tokenrouter 403") + assert model.endswith("Choose another model, or enable this one for your account with TokenRouter.") for said in (quota, model): assert "was refused:" not in said @@ -102,14 +104,16 @@ def test_a_custom_endpoint_is_called_by_the_connections_name(): said = gw._refusal_message(custom, "429: Rate limit reached. Please try again in 2s.") assert said.startswith("My DeepSeek rate-limited this task (too many requests for now; your key was not refused).") said = gw._refusal_message(custom, "Error code: 429 - insufficient_quota") - assert said.startswith("Your My DeepSeek account has no quota or credit left for this key; add credit with My DeepSeek") + assert said.startswith("Your My DeepSeek account has no quota or credit left for this key: ") + assert said.endswith("Add credit with My DeepSeek, or replace or remove this key under Bring Your Own Key.") assert gw._refusal_message({"_vendor": "custom"}, "401 invalid api key").startswith("Your custom endpoint key was refused") - assert gw._refusal_message({**CONN, "name": "integration:My TR"}, "401 invalid api key").startswith("Your tokenrouter key was refused") + assert gw._refusal_message({**CONN, "name": "integration:My TR"}, "401 invalid api key").startswith("Your TokenRouter key was refused") def test_a_refused_key_reads_as_before_and_an_entra_connection_is_never_a_key(): assert gw._refusal_message(CONN, "OpenAI API error (401): invalid api key") == \ - "Your tokenrouter key was refused: OpenAI API error (401): invalid api key" + ("Your TokenRouter key was refused: OpenAI API error (401): invalid api key. " + "Check this key with TokenRouter, or replace or remove it under Bring Your Own Key.") entra = {"provider": "azure", "auth": "entra"} for err in ("hr API error (401): x", "429 rate limit", "429 insufficient_quota", "403: not allowed to use model gpt-5.4"): assert "key" not in gw._refusal_message(entra, err).replace(err, "") @@ -143,5 +147,7 @@ def test_the_detail_carries_none_of_the_providers_text_and_other_failures_add_no def test_the_refusal_branch_sets_the_message_and_the_detail_together(): src = (pathlib.Path(__file__).resolve().parents[1] / "app.py").read_text() - i = src.index('rec["error_message"] = _refusal_message(conn, _last_err)') - assert 'rec["provider_failure"] = _provider_failure_detail(_last_err)' in src[i:i + 200] + i = src.index('rec["error_message"] = _refusal_message(conn, _last_err, _kind)') + assert 'rec["provider_failure"] = _provider_failure_detail(_last_err, _kind,' in src[i:i + 200] + # the provider's words reach both without the key + assert '_last_err = _without_key(_last_err, str(conn.get("api_key") or ""))' in src[i - 400:i] diff --git a/gateway/tests/test_relay_refusal.py b/gateway/tests/test_relay_refusal.py new file mode 100644 index 00000000..65f51d56 --- /dev/null +++ b/gateway/tests/test_relay_refusal.py @@ -0,0 +1,305 @@ +"""A provider's refusal of the instance's own key is read where it happens, at the door the agent's model calls +pass through, and the turn stops on it and says it at the top. + +A hosted customer's scheduled runs failed for a week on a TokenRouter key that answered 403 to every call. Each task's +error was the runner's reading of what the agent printed ("The model provider refused the request (403: Forbidden.)"), +named the provider by its wiring's id ("Your tokenrouter key"), and said nothing of what to do. An agent that retried, +stopped quietly or answered in its own words left less. What these pin: + the door reads the provider's own error body and classifies it from the status and the provider's code, not a CLI's + line: a refused key, an account with no credit, a refused model; a rate limit is not final and is not recorded; + the refusal is recorded for the task without the connection's key, in this process and in the control store; + a turn takes only a refusal on its own connection, of its own model, made after it started; + the turn stops on it at once (the runner told to cancel) and fails with the refusal as its reason and detail, and the + stream's error event carries that detail; + an agent that ended before the loop saw it (failed in its own words, or "completed" with nothing from the model) still + fails with it; one that answered, or a refusal of another model, is left as it was; + the agent gets the provider's answer exactly as it came; + the runner's line is read better too: 402, an empty account's sentence and a credit body under the first line. +""" +import asyncio +import json +import os +import pathlib +import sys +import time + +import httpx +import pytest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +os.environ.setdefault("HR_BACKING", "local") +import app as gw # noqa: E402 + +KEY = "sk-own-0123456789abcdefghijklmnop" +ORG = "org_refused" +MODEL = "claude-opus-5.5" + + +# ── the provider's own words ─────────────────────────────────────────────────────────────────────────────────────────── +@pytest.mark.parametrize("body,said", [ + (b'{"error":{"message":"Forbidden. (request id: 2026112813)","type":"new_api_error"}}', + "new_api_error: Forbidden. (request id: 2026112813)"), + (b'{"error":{"message":"You exceeded your current quota","type":"insufficient_quota","code":"insufficient_quota"}}', + "insufficient_quota: You exceeded your current quota"), + (b'{"type":"error","error":{"type":"invalid_request_error","message":"Your credit balance is too low to access the API."}}', + "invalid_request_error: Your credit balance is too low to access the API."), + (b'[{"error":{"code":403,"message":"Permission denied","status":"PERMISSION_DENIED"}}]', "403: Permission denied"), + (b'{"message":"Insufficient credits"}', "Insufficient credits"), + (b"Forbidden", "Forbidden"), + (b"", ""), +]) +def test_the_providers_words_are_read_from_its_own_body(body, said): + assert gw._provider_error_said(body) == said + + +# ── what no retry can change ────────────────────────────────────────────────────────────────────────────────────────── +@pytest.mark.parametrize("status,said,kind", [ + (403, "new_api_error: Forbidden. (request id: 1)", "refused"), + (401, "invalid_api_key: Incorrect API key provided", "refused"), + (402, "Insufficient credits", "quota"), + (403, "insufficient_user_quota: Your account quota is running low ($0.00)", "quota"), # TokenRouter's member cap + (429, "insufficient_quota: You exceeded your current quota", "quota"), + (400, "invalid_request_error: Your credit balance is too low to access the API.", "quota"), + (404, "model_not_found: The model `gpt-9` does not exist", "model"), + (403, "your key is not allowed to use model claude-opus-5", "model"), + (429, "rate_limit_exceeded: Rate limit reached, try again in 20s", ""), # passes on its own: not recorded + (403, "rate limit exceeded for this key", ""), + (400, "Unknown name \"store\": Cannot find field.", ""), + (500, "upstream exploded", ""), +]) +def test_a_final_refusal_is_read_from_the_status_and_the_providers_code(status, said, kind): + assert gw._relay_refusal_kind(status, said) == kind + + +def _note(sid, status, body, monkeypatch, store): + async def put(s, rec): + if store is None: + raise RuntimeError("store down") + store[s] = rec + monkeypatch.setattr(gw.control_store, "enabled", lambda: True) + monkeypatch.setattr(gw.control_store, "refusal_put", put) + return asyncio.run(gw._note_relay_refusal(sid, {"api_key": KEY}, "integration:TR", "tokenrouter", MODEL, status, body)) + + +def test_a_refusal_is_recorded_for_the_task_without_the_key_here_and_in_the_control_store(monkeypatch): + store: dict = {} + body = json.dumps({"error": {"message": f"Incorrect API key provided: {KEY}", "code": "invalid_api_key"}}).encode() + rec = _note("sess_rr1", 401, body, monkeypatch, store) + assert rec["kind"] == "refused" and rec["status"] == 401 and rec["conn"] == "integration:TR" and rec["model"] == MODEL + assert KEY not in rec["said"] and KEY[:12] not in rec["said"] and rec["said"].startswith("401: invalid_api_key") + assert gw._relay_refusals["sess_rr1"] is rec and store["sess_rr1"] == rec + + +def test_a_rate_limit_is_not_recorded_and_a_store_that_fails_never_fails_the_call(monkeypatch): + assert _note("sess_rr2", 429, b'{"error":{"message":"Rate limit reached, try again in 2s"}}', monkeypatch, {}) is None + assert "sess_rr2" not in gw._relay_refusals + before = gw._relay_refusal_counts.counts["unshared"] + rec = _note("sess_rr3", 403, b"Forbidden", monkeypatch, None) + assert rec["kind"] == "refused" and gw._relay_refusal_counts.counts["unshared"] == before + 1 + + +def test_the_control_store_keeps_the_refusal_for_another_process(monkeypatch, tmp_path): + monkeypatch.setenv("HR_DATA_DIR", str(tmp_path)) + monkeypatch.setattr(gw.control_store, "_cont", None) + rec = {"at": 1.0, "kind": "quota", "status": 402, "provider": "tokenrouter", "conn": "c", "model": MODEL, "said": "402: x"} + asyncio.run(gw.control_store.refusal_put("sess_rr_store", rec)) + assert asyncio.run(gw.control_store.refusal_get("sess_rr_store")) == rec + assert asyncio.run(gw.control_store.refusal_get("sess_rr_none")) is None + monkeypatch.setattr(gw.control_store, "_cont", None) + + +# ── which refusal is a turn's ───────────────────────────────────────────────────────────────────────────────────────── +def test_a_turn_takes_only_its_own_connection_and_model_since_it_started(monkeypatch): + monkeypatch.setattr(gw.control_store, "enabled", lambda: False) + since = time.time() + gw._relay_refusals["sess_rr4"] = {"at": since + 1, "kind": "refused", "status": 403, "conn": "anthropic", + "model": "anthropic/claude-opus-5.5", "said": "403: Forbidden."} + + def take(conn="anthropic", models=(MODEL,), at=since): + return asyncio.run(gw._turn_relay_refusal("sess_rr4", conn, models, at)) + assert take()["status"] == 403 # an aggregator's vendor prefix is the same model + assert take(conn="other") is None # another connection's + assert take(models=("claude-haiku-4.5",)) is None # a side call to another model is not the turn's + assert take(at=since + 5) is None # an earlier turn's (a key fixed since) + + +# ── the turn stops on it and says it ───────────────────────────────────────────────────────────────────────────────── +class _Refused: + """A runner whose agent's model call the provider refuses: the door records the refusal as the turn starts (or as + the agent ends, `when="end"`), and the agent goes on working (retrying) unless told to cancel.""" + + def __init__(self, *, refusal=True, model=MODEL, end="running", answer="", when="start"): + self.refusal, self.model, self.end, self.answer, self.when = refusal, model, end, answer, when + self.cancels, self.polls = 0, 0 + + def _recorded(self, sid): + gw._relay_refusals[sid] = {"at": time.time(), "kind": "refused", "status": 403, "conn": "anthropic", + "provider": "anthropic", "model": self.model, + "said": "403: new_api_error: Forbidden. (request id: 1)"} + + async def __call__(self, path, sid, method="POST", body=None, **kw): + if path == "/turn": + if self.refusal and self.when == "start": + self._recorded(sid) + return {"turn_id": "t1", "status": "running"} + if path.endswith("/cancel"): + self.cancels += 1 + return {} + if path.startswith("/turn/"): + self.polls += 1 + if self.refusal and self.when == "end": + self._recorded(sid) + if self.end == "running" and self.polls < 50: + return {"done": False, "status": "running", "events": [], "n_total": 0} + if self.end == "completed": + evs = ([{"type": "assistant", "message": {"content": [{"type": "text", "text": self.answer}]}}] + if self.answer else []) + return {"done": True, "status": "done", "events": evs, "n_total": len(evs)} + return {"done": True, "status": "failed", "error": "The model provider refused the request (403)", + "events": [], "n_total": 0} + return {} + + +def _turn(monkeypatch, sid, runner): + async def _nothing(*a, **kw): + return None + + async def _get_connection(org, name): + return ({"name": "anthropic", "provider": "anthropic", "base_url": "https://api.anthropic.example/v1", + "api_key": KEY}, "tenant-1") + + async def _plugins(*a, **kw): + return ([], [], [], [], []) + + async def _env(*a, **kw): + return ({}, []) + + async def _false(*a, **kw): + return False + + async def _empty(*a, **kw): + return [] + + async def _flushed(tr, s): + return True + for name, fn in (("_sandbox_json", runner), ("_vertex_get", _nothing), ("_vertex_upsert", _nothing), + ("_hydrate", _nothing), ("_harness_plugins", _plugins), ("_harness_env", _env), + ("_image_auth", _nothing), ("_get_connection", _get_connection), + ("_auth_from_conn", lambda *a, **kw: {"token": "t", "base_url": "https://gw.test/v1/llm"}), + ("_turn_cancelled", _false), ("_collect_produced", _empty), ("_blob_put", _nothing), + ("_checkpoint", _nothing), ("_trace_finalize", _nothing), ("_browser_close", _nothing), + ("_recover_trace_cursor", _nothing), ("_trace_flush", _flushed), + # the turn runs on the chain's connection: no model mapping another test left behind stands first + ("_mapped_integration_conn", _nothing)): + monkeypatch.setattr(gw, name, fn) + monkeypatch.setattr(gw, "RESP_POLL_S", 0) + monkeypatch.setattr(gw.control_store, "enabled", lambda: False) + gw._relay_refusals.pop(sid, None) + tr = gw._RespTranslator("resp_" + sid, MODEL, None, True, time.time()) + status, _produced, rec = asyncio.run(gw._resp_execute( + tr, org=ORG, member="me@local", sid=sid, backend="claude", chain=["anthropic"], prompt="hi", files_in=[], + resume=None, emit=lambda ev: asyncio.sleep(0), model_req=MODEL)) + return status, rec, tr + + +def test_the_turn_stops_on_the_refusal_and_says_it_at_the_top(monkeypatch): + runner = _Refused() + status, rec, tr = _turn(monkeypatch, "sess_rr6", runner) + assert status == "failed" and runner.cancels == 1 and runner.polls <= 1, "stopped at once, not after the agent's retries" + assert rec["error_message"] == ("Your Anthropic key was refused: 403: new_api_error: Forbidden. (request id: 1). " + "Check this key with Anthropic, or replace or remove it under Bring Your Own Key.") + assert rec["provider_failure"] == {"reason": "provider_key_refused", "retryable": False, "provider": "Anthropic", + "connection": "anthropic", "status": 403, "model": MODEL} + evs = gw._fail_events(tr, rec) + err = next(e for e in evs if e["type"] == "error") + assert err["code"] == "turn_failed" and err["detail"]["reason"] == "provider_key_refused", "the stream says why too" + assert tr.error["detail"]["status"] == 403 and tr.error["message"] == rec["error_message"] + + +def test_an_agent_that_ended_before_the_loop_saw_the_refusal_still_fails_with_it(monkeypatch): + runner = _Refused(end="completed", when="end") + status, rec, _tr = _turn(monkeypatch, "sess_rr7", runner) + assert runner.cancels == 0, "the agent had ended: nothing to stop" + assert status == "failed" and rec["provider_failure"]["reason"] == "provider_key_refused" + assert rec["error_message"].startswith("Your Anthropic key was refused: 403: new_api_error: Forbidden.") + status, rec, _tr = _turn(monkeypatch, "sess_rr7b", _Refused(end="failed", when="end")) + assert status == "failed" and "new_api_error: Forbidden." in rec["error_message"] + assert rec["provider_failure"]["status"] == 403 + + +def test_an_answer_or_another_models_refusal_is_left_as_it_was(monkeypatch): + status, _rec, _tr = _turn(monkeypatch, "sess_rr8", _Refused(end="completed", answer="done", when="end")) + assert status == "completed", "the model answered after all: the agent's account stands" + runner = _Refused(model="claude-haiku-4.5", end="completed", answer="done") + status, _rec, _tr = _turn(monkeypatch, "sess_rr8b", runner) + assert status == "completed" and runner.cancels == 0, "a side call's refusal is not the turn's" + status, rec, _tr = _turn(monkeypatch, "sess_rr9", _Refused(refusal=False, end="failed")) + assert status == "failed" and "relay_refusal" not in rec + assert rec["error_message"].startswith("Your Anthropic key was refused: The model provider refused the request (403)") + + +# ── through the door itself ─────────────────────────────────────────────────────────────────────────────────────────── +def _brokered_403(monkeypatch, path="/v1/llm/v1/chat/completions"): + body = json.dumps({"error": {"message": f"Forbidden. key {KEY} (request id: 9)", "type": "new_api_error"}}).encode() + conn = {"name": "integration:TR", "provider": "tokenrouter", "api_key": KEY, "base_url": "https://up.test/v1"} + + async def resolve(name, org): + return gw._with_provider_base(dict(conn)) + + async def vertex_get(sid): + return {} + + def handler(req): + return httpx.Response(403, stream=httpx.ByteStream(body), headers={"content-type": "application/json"}) + monkeypatch.setattr(gw, "INTERNAL_KEY", "k-test-internal-key") + monkeypatch.setattr(gw, "_broker_resolve", resolve) + monkeypatch.setattr(gw, "_vertex_get", vertex_get) + monkeypatch.setattr(gw, "_relay_client", lambda: httpx.AsyncClient(transport=httpx.MockTransport(handler))) + monkeypatch.setattr(gw.control_store, "enabled", lambda: False) + cred = gw._mint_turn_cred("sess-door", "integration:TR", "") + gw._relay_refusals.pop("sess-door", None) + + async def run(): + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=gw.app), base_url="http://gw.test") as c: + return await c.post(path, headers={"authorization": f"Bearer {cred}"}, + json={"model": "deepseek/deepseek-v4.1-flash", + "messages": [{"role": "user", "content": "hi"}]}) + return asyncio.run(run()), body + + +def test_the_door_hands_the_agent_the_providers_answer_and_records_it_for_the_task(monkeypatch): + r, body = _brokered_403(monkeypatch) + assert r.status_code == 403 and r.content == body, "the agent gets the provider's answer as it came" + rec = gw._relay_refusals["sess-door"] + assert (rec["kind"], rec["status"], rec["conn"], rec["model"]) == ("refused", 403, "integration:TR", + "deepseek/deepseek-v4.1-flash") + assert rec["said"].startswith("403: new_api_error: Forbidden.") and KEY not in rec["said"] and KEY[:10] not in rec["said"] + + +# ── the runner's line, read better (BC-001) ─────────────────────────────────────────────────────────────────────────── +@pytest.mark.parametrize("err,kind", [ + ("402: Insufficient credits", "quota"), + ("Request failed with status code 402", "quota"), + ("400: Your credit balance is too low to access the Anthropic API.", "quota"), + ("Credit balance is too low", "quota"), + ('Error code: 429\n{"error": {"code": "insufficient_quota", "message": "You exceeded your current quota"}}', "quota"), + ('403 Forbidden\n{"error": {"code": "insufficient_user_quota"}}', "quota"), + ("Error code: 429 - rate limit, try again in 20s", "rate_limit"), + ("403: Forbidden.", "refused"), + ("codex: compaction failed\n429 insufficient_quota further down", ""), # a diagnostic below never makes a refusal +]) +def test_the_runners_line_covers_402_an_empty_accounts_sentence_and_a_body_under_it(err, kind): + assert gw._provider_failure_kind(err) == kind + + +def test_a_provider_is_said_by_the_name_a_person_knows_it_by(): + assert gw._provider_brand("tokenrouter") == "TokenRouter" and gw._provider_brand("openai-api") == "OpenAI" + assert gw._provider_brand("azure-foundry") == "Azure OpenAI" # as ui/src/lib/providers.ts names it + assert gw._provider_brand("My DeepSeek") == "My DeepSeek" and gw._provider_brand("") == "your provider" + + +def test_the_key_never_reaches_the_message_when_the_provider_echoes_it(): + said = gw._refusal_message({"provider": "openai"}, gw._without_key(f"401 Incorrect API key provided: {KEY}", KEY)) + assert "key was refused" in said and KEY[:8] not in said and KEY[-8:] not in said + assert gw._without_key("nothing of it here, sk-own", KEY) == "nothing of it here, sk-own" + assert gw._without_key("x", "") == "x" and gw._without_key("", KEY) == "" diff --git a/gateway/tests/test_turn_failure_message.py b/gateway/tests/test_turn_failure_message.py index 2997c5c1..7e52240c 100644 --- a/gateway/tests/test_turn_failure_message.py +++ b/gateway/tests/test_turn_failure_message.py @@ -84,5 +84,7 @@ def test_a_refused_integration_is_named_by_its_vendor_not_the_runners_wiring(): custom connection). A custom endpoint has no vendor name, so it is called by the connection's own name (0.41.26: "add credit with custom" named nobody).""" conn = {"name": "integration:My endpoint", "provider": "tokenrouter", "_vendor": "custom"} - assert gw._refusal_message(conn, "401: bad key") == "Your My endpoint key was refused: 401: bad key" - assert gw._refusal_message({"provider": "openai"}, "") == "Your openai key was refused: the provider returned an error" + assert gw._refusal_message(conn, "401: bad key") == ("Your My endpoint key was refused: 401: bad key. Check this key " + "with My endpoint, or replace or remove it under Bring Your Own Key.") + assert gw._refusal_message({"provider": "openai"}, "").startswith( + "Your OpenAI key was refused: the provider returned an error. Check this key with OpenAI") diff --git a/protocol/CHANGELOG.md b/protocol/CHANGELOG.md index 7bed2ded..2386d530 100644 --- a/protocol/CHANGELOG.md +++ b/protocol/CHANGELOG.md @@ -2,6 +2,20 @@ All notable changes to the Unified Harness Protocol. +## 2026-10-19, addition: a provider's refusal says why in `error.detail` + +A task that failed because the model provider refused its connection looked like any other failed +task: the cause was only in the wording of `message`, so clients with automatic retries matched +phrases, or retried failures that could not succeed. [Errors §3.4](versions/2026-10-19/errors.md#34-a-providers-refusal) +now describes the `error.detail` a server reports for one: `reason` (`provider_key_refused`, +`provider_quota_exhausted`, `provider_model_refused`, `provider_rate_limited`), `retryable`, and, when +known, `retry_after_seconds`, `provider`, `status`, `model` and `connection`. The stream's `error` +event carries the same `detail`. A server that relays the harness's model calls SHOULD end the task +as soon as the provider refuses the task's model in a way no retry changes. Under +[VERSIONING](VERSIONING.md), fields added to a response object and to an event fit within a version: +`Error.detail` and `Event` already accept them, no code or event changes, and a client that ignores +the new fields reads what it read before. + ## 2026-10-19, addition: a call's voice, chosen per model A model that speaks had no way to say which voices it has, and the reference server's route that diff --git a/protocol/versions/2026-10-19/errors.md b/protocol/versions/2026-10-19/errors.md index b4e3ae63..7b2b365a 100644 --- a/protocol/versions/2026-10-19/errors.md +++ b/protocol/versions/2026-10-19/errors.md @@ -132,6 +132,33 @@ to fix the harness, the second to send the task with another model. | `preview_unavailable` | 501 | This server does not render previews. | | `preview_failed` | 502 | Conversion of this file failed. | +### 3.4 A provider's refusal + +When a task fails because the model provider turned down the connection the harness ran on, a +server SHOULD say why in `error.detail`, so that a client with automatic retries can stop on the +failures no retry will change instead of matching words in `message`: + +| Field | Type | Meaning | +|---|---|---| +| `reason` | string | `provider_key_refused` (the key), `provider_quota_exhausted` (no credit or quota left on the provider's account), `provider_model_refused` (the key was accepted, this model was not) or `provider_rate_limited` | +| `retryable` | boolean | `true` only for `provider_rate_limited`. The others fail again until the key, the account or the model changes | +| `retry_after_seconds` | number | The wait the provider named, when it named one | +| `provider` | string | The provider, by the name a person knows it by | +| `status` | integer | The HTTP status the provider answered, when the server saw that answer itself | +| `model` | string | The model the provider refused, by the provider's own name for it, when the server saw the answer itself | +| `connection` | string | The connection that was refused, by the name it was given | + +Every field but `reason` and `retryable` is optional. `detail` carries none of the provider's own +words. `message` may quote them, and then MUST NOT carry the credential: a server removes any part +of the key a provider echoes back. A server MAY report these failures with `provider_error` (§3.3) or +with the code it uses for any failed task, as the reference server does; either way the cause is +`detail.reason`, so a client branches on that and not on `code`. + +A server that relays the harness's model calls sees the provider's answer before the harness does. +It SHOULD end the task as soon as a refusal no retry can change arrives for the model the task runs, +rather than wait for the harness to retry and give up, and SHOULD take the reason from that answer +rather than from the harness's own account of it. + ## 4. Retrying | Situation | Retry? | @@ -146,6 +173,7 @@ to fix the harness, the second to send the task with another model. | `precondition_failed` | Yes, after reading the harness again and redoing the change on what was read | | Any other `invalid_request_error` | No — fix the request | | `authentication_error` | No — fix the credential | +| A task that reached `failed` with `error.detail.retryable` `false` | No — fix the key, the provider account or the model first (§3.4) | | A task that reached `failed` | Only with the client's own judgment; it consumed real resources | **Retries of `POST /v1/responses` MUST carry an `Idempotency-Key`.** Without one, a retry after a diff --git a/protocol/versions/2026-10-19/streaming.md b/protocol/versions/2026-10-19/streaming.md index d30594bd..cd8ab710 100644 --- a/protocol/versions/2026-10-19/streaming.md +++ b/protocol/versions/2026-10-19/streaming.md @@ -101,7 +101,7 @@ The tool call itself arrives as an `output_item` of type `function_call`, and it | Event | Payload | |---|---| -| `error` | `code`, `message`, `param` — an error that did not end the task | +| `error` | `code`, `message`, `param`, and the error's `detail` when it has one ([Errors §3.4](errors.md#34-a-providers-refusal)) — an error that did not end the task | An `error` event MUST be followed by a terminal event. A stream that emits `error` and then stops without a terminal event is malformed: the client cannot tell whether the task died or the