Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

Azure connections can sign in with Microsoft Entra; the relay waits 180 s; a build is active before it says ready (#405)

github-actions[bot]3f01187eb9bf
diff --git a/docs/self-hosting-guide.md b/docs/self-hosting-guide.md
index 8937cdf6..7a570e67 100644
--- a/docs/self-hosting-guide.md
+++ b/docs/self-hosting-guide.md
@@ -370,6 +370,48 @@ offers you providers that work.
</details>
+<details>
+<summary>An Azure connection without an API key (Microsoft Entra)</summary>
+
+For an organization that issues no API keys for its Azure resources. The connection is an application
+in your own Entra directory, and tasks sign in as that application.
+
+Register it once and give it a role on the resource it may call:
+
+```bash
+APP=$(az ad app create --display-name "HarnessRouter models" --sign-in-audience AzureADMyOrg --query appId -o tsv)
+az ad sp create --id "$APP" >/dev/null
+RESOURCE=$(az cognitiveservices account show -g <resource group> -n <resource name> --query id -o tsv)
+az role assignment create --assignee "$APP" --role "Cognitive Services OpenAI User" --scope "$RESOURCE"
+az ad app credential reset --id "$APP" --append --display-name harnessrouter --years 1 --query password -o tsv
+```
+
+The last line prints the client secret once. On the **Integrations** page add an **Azure OpenAI**
+connection, set **Sign in with** to **Microsoft Entra**, and enter the endpoint URL, the directory
+(tenant) ID, the application (client) ID and the client secret. A role assignment can take a few
+minutes to take effect.
+
+What happens on a task: the gateway asks Microsoft Entra for a token as the application, keeps it
+until shortly before it expires, and presents it on each model call in place of an API key. The agent
+holds neither the secret nor the token. That is true even though this image hands an API key
+connection straight to the agent (`HR_SANDBOX_TRUST=owner`): a token lives for about an hour and a
+task can run for longer, so a connection of this kind always goes through the gateway, which asks
+again as the token ages.
+
+When the sign-in is refused, the task fails with Entra's own reason, for example
+`Your azure connection was refused: ... Microsoft Entra refused this connection's sign-in: AADSTS90002: Tenant '...' not found`.
+When the application has no role on the resource, the reason is Azure's:
+`The principal ... lacks the required data action Microsoft.CognitiveServices/accounts/OpenAI/responses/write`.
+A directory or application ID that is not a GUID, or a missing secret, is refused when you save.
+
+The same role serves a Foundry resource (kind `AIServices`); its endpoint is
+`https://<resource>.services.ai.azure.com`. A connection reaches the models deployed on the resource
+under the names this instance knows them by.
+
+A sovereign cloud sets `HR_ENTRA_AUTHORITY` (default `https://login.microsoftonline.com`).
+
+</details>
+
<details>
<summary>What a backend with nothing connected says</summary>
@@ -906,6 +948,9 @@ docker build -t harnessrouter --build-arg WITH_BROWSER=1 .
| `HR_SANDBOX_TRUST` | `owner` | You own the box, the agent and the key, so the key is handed over directly rather than brokered. |
| `HARNESS_WORKSPACE` | `/data/workspaces` | One directory per session, on the volume, so a restart doesn't discard work in flight. |
| `HR_WORKSPACE_TTL_HOURS` | `72` | Idle session workspaces are removed after this. They rehydrate from their checkpoint, so this costs time, not work. `0` keeps them forever. |
+| `HR_RELAY_UPSTREAM_TIMEOUT_S` | `180` | How long one model call may go without sending anything before the turn is told the provider did not answer. Raise it (it was 600 before 0.31.0) if you run models that think for minutes without streaming: a few do at their highest thinking level. |
+| `HR_ENTRA_AUTHORITY` | `https://login.microsoftonline.com` | Where an Azure connection that signs in with Microsoft Entra asks for its token. A sovereign cloud names its own. |
+| `HARNESS_RESP_HOLD_S` | `3` | How long the gateway lets the runner hold a request for a turn's events. `0` asks every 1.2 s as before 0.30.1. |
| `HARNESS_INTERNAL_KEY` | generated | Per-container; never leaves the process tree. |
</details>
diff --git a/docs/support-matrix-notes.md b/docs/support-matrix-notes.md
index 683f13bf..55f724f7 100644
--- a/docs/support-matrix-notes.md
+++ b/docs/support-matrix-notes.md
@@ -2862,3 +2862,138 @@ gpt-5.4 unless said; thinking tokens at none, low, high):
here for every keyed turn), so the relay never saw their calls; there they now take the relay for a
turn that asks for a level. That difference between the trees is the hosted one's and is recorded
here because the column is shared.
+
+With that change the hosted session ran the column again and reported 11 of 11, these rows among
+them (thinking tokens at none, low, high):
+
+| base | none | low | high | |
+|---|---:|---:|---:|---|
+| pi | 0 | 243 | 516 | |
+| omp | 0 | 252 | 456 | |
+| opencode | 0 | 272 | 804 | |
+| codex | 12 out | 233 out | 530 out | output tokens, as above |
+
+Not run on the hosted service at the time of writing: the Gemini CLI base, and most bases at more
+than one model.
+
+## How long a thinking model says nothing, and the relay's wait (2026-10-06, 0.31.0)
+
+The relay ends a model call that sends no event for `HR_RELAY_UPSTREAM_TIMEOUT_S`. The default was
+600 s and is 180 s from 0.31.0, the value the hosted service runs. Before changing it the cost was
+measured, because the old default had been chosen for it: a model that thinks without sending
+anything looks, on the wire, like a provider that has stopped.
+
+One hard three-part counting problem, streamed, at each model's highest thinking level, straight at
+the provider through a connection of hr-test, with the relay's own wait raised to 1,200 s so it could
+not interfere. An event is a `data:` line; a keep-alive comment line is not one, here as in the relay.
+One sample per cell. The longest run with no event:
+
+| model, level | TokenRouter | Vercel |
+|---|---:|---:|
+| gpt-5.5, xhigh, Chat Completions | 201 s | 11 s |
+| gpt-5.5, xhigh, Responses | 30 s | 61 s |
+| gpt-6.1-sol, xhigh | 19 s (Responses) | 15 s (Chat Completions) |
+| gpt-6-sol, xhigh, Chat Completions | no answer in 1,200 s | |
+| gemini-3.1-pro-preview, high | 205 s | 4.5 s |
+| claude-opus-5, xhigh | 35 s | |
+| claude-opus-5.5, xhigh | | 211 s |
+| grok-4.6, xhigh | 13 s | 12 s |
+| deepseek-v4-pro, xhigh | 2 s | |
+| kimi-k3, high | | 0.7 s |
+| qwen3.7-max, high | | 2 s |
+
+Whether thinking shows on the wire is a property of the route and the request shape, not of the
+model. Where a route forwards reasoning as it happens the stream is never quiet for long, and that
+was 13 of the 16 cells. Three were silent for over 200 s and then answered: OpenAI's Chat Completions
+through TokenRouter sends nothing until the first token of the answer (the same model on the
+Responses API, or through Vercel, streams throughout), TokenRouter's Gemini channel likewise, and
+Claude Opus 5.5 through Vercel sent one event and then keep-alive lines for 211 s. One call never
+answered at all.
+
+So the two waits buy different things. At 600 s the three silent answers complete and the call that
+never answers holds its turn for ten minutes. At 180 s that call ends in three minutes and the three
+answers are cut off as "the provider did not answer". Richard chose 180 s for both the hosted service
+and this default with these numbers in front of him. An operator who runs such models at such levels
+on such routes raises the variable; the bases that speak the Responses API to OpenAI models (Codex,
+hermes, opencode, kilo) were not exposed in any cell.
+
+## An Azure connection that signs in with Microsoft Entra (2026-10-06, 0.31.0)
+
+For an organization that issues no API keys for its Azure resources: the connection is an application
+in the organization's own Entra directory (tenant ID, client ID, client secret), and the gateway's
+broker asks Entra for a token by the client-credentials grant and presents it as the bearer where a
+key connection sends `api-key`. Built on the hosted service and taken from there with its tests.
+
+What this tree adds is one rule. In owner trust, the image's default, a connection's key is handed
+to the agent. This connection has no key to hand, only a secret that buys a token good for about an
+hour, and a turn may run for six. So a connection of this kind goes through the gateway's broker in
+every trust mode, and the broker asks again as the token ages.
+
+Measured on the release's candidates in side containers on the test VM, in owner trust, with a test
+application in our own directory holding the "Cognitive Services OpenAI User" role on one Azure
+OpenAI resource and one Foundry resource:
+
+- **Four bases completed on the Entra connection**: pi and goose and hermes with gpt-5.4-mini, Codex
+ with gpt-5.4, each served by that connection. The gateway signed in once for all four
+ (`[entra] signed in as application ••••1234; asking again in 3299 s`, one line per sign-in).
+- **The agent holds neither the secret nor a token.** Checked while a pi turn was running a shell
+ command: none of the container's processes (the agent's and its shell's among them, read with the
+ rights to read every process's environment and command line) and none of 5,995 workspace files
+ held the client secret or an access token for Azure. The secret itself is not readable as text
+ anywhere on the data volume.
+- **The sign-in is renewed inside a running turn.** A token is good for 3,599 s and the gateway asks
+ again 300 s before that. One pi turn with gpt-5.4 was started 119 s before a sign-in was due for
+ renewal and ran six 85 s shell commands, one model call after each: 04:40:39 to 04:49:17 UTC. The
+ sign-in it began on was made at 03:47:37 (due again at 04:42:36, dead at 04:47:36). Its first two
+ model calls went out on that token; the third, at 04:43:32, made the gateway sign in again (the
+ log's line is at 04:43:32.7); the last two came after the first token's own expiry. The turn
+ completed with six tool calls and the six times. Before that, with the instance idle for an hour
+ and forty minutes past a token's expiry, the next turn signed in again by itself and completed.
+- **No role on the resource**: the same application pointed at a resource it has no role on. Azure's
+ own 401 reaches the turn: `Your azure connection was refused: ... {"code":"PermissionDenied",
+ "message":"The principal ... lacks the required data action
+ Microsoft.CognitiveServices/accounts/OpenAI/responses/write ..."}`.
+- **A directory Entra does not know**: the turn fails in 2 s on pi with `Your azure connection was
+ refused: ... Microsoft Entra refused this connection's sign-in: AADSTS90002: Tenant '...' not
+ found. ...`. Nothing is remembered of a refusal: the next call asks again.
+- **A key connection is untouched**: pi and Codex on the same Azure resource by API key completed,
+ handed the key as before.
+- **The form** on the Integrations page at 1440, 1024, 768 and 390 wide: "Sign in with" offers API
+ key and Microsoft Entra, the fields change to the directory ID, the application ID and the client
+ secret, a directory written as a name is refused with the field's own label, a saved connection
+ comes back with the secret masked and no key.
+
+Two defects came out of the measuring and are fixed in the release, here and on the hosted service:
+
+1. A sign-in Entra refuses came back from the broker as a 502. Codex reconnected five times before
+ giving up (28 s), and a 502 is not a refusal to the gateway, so the turn was free to try its next
+ connection, which is what the refused-key rule exists to prevent. A sign-in Entra answers with
+ 400, 401 or 403 is now a 401 from the broker, as a refused API key is. Codex still makes its
+ reconnect attempts on a 401, as it does on a refused key, and now fails in 8 s. Entra throttling
+ or failing stays a 502.
+2. The turn said "Your azure key was refused" on a connection that has no key. It says "connection".
+
+Not measured here:
+
+- **A completed turn on a Foundry resource.** This tree's catalog has no model that the one Foundry
+ resource we could use has deployed, and only a custom connection may name a model outside the
+ catalog. What was observed is the next thing down: a catalog model asked of that resource came back
+ `404 DeploymentNotFound`, not a refusal, so the resource accepted the application's token. The
+ hosted service completed a pi turn on that resource through the same code.
+- A sovereign cloud (`HR_ENTRA_AUTHORITY`), and a client secret that expires or is rotated while a
+ turn runs.
+
+## A build said ready before its version was active (2026-10-06, 0.31.0)
+
+Issue #401: `test_the_turn_gets_the_path_the_variables_and_the_instructions` failed once in CI with
+"409: the environment has no built version" and passed on the rerun. It was not a flake. A build
+wrote its record as `ready` and made the version active in the next statement, and the record is what
+every reader waits on: the test, the console's build view, a script polling the API. A turn started
+in between was refused. On a normal disk the window is too short to meet; a slow CI disk met it.
+
+The version is now made active, and its mount made, before the record is written, and if any of the
+three steps fails the active version goes back to what it was (a failed build never becomes active,
+as before). A test asks the question at the instant the ready record is written and fails on the old
+order. On the candidate: an environment with a pip, an npm and an apt package built in 9 s, a turn
+started in the same instant its record read ready completed using the environment's package, and the
+environments column passed on pi, Codex and Claude Code, 9 of 9 tasks.
diff --git a/gateway/app.py b/gateway/app.py
index beafcf8d..78080b32 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -1098,7 +1098,12 @@ def _auth_from_conn(conn: dict, sid: str = "", effort: str = "") -> dict | None:
# exactly that shape: any condition that made brokering fail silently shipped the raw key.
# Keeping pass-through as its own declared mode means a hosted deployment that leaves the
# variable unset still fails CLOSED on every broker failure, as before.
- if SANDBOX_TRUST == "owner":
+ #
+ # One connection is brokered even here: an Azure connection that signs in with Microsoft Entra
+ # (see _entra_token). What it holds is not a key to hand over but an application's secret that
+ # buys a token good for about an hour, and a turn may run for six: the broker asks again when
+ # the token ages, on every call, and the agent never holds the token or the secret.
+ if SANDBOX_TRUST == "owner" and not _entra_conn(conn):
for field in _SECRET_AUTH_FIELDS:
if conn.get(field) is not None:
out[field] = conn[field]
@@ -1111,7 +1116,10 @@ def _auth_from_conn(conn: dict, sid: str = "", effort: str = "") -> dict | None:
return None
# Normalised: a connection saved as "TokenRouter" must not skip brokering on a casing mismatch.
provider = str(conn.get("provider") or "").strip().lower()
- if provider not in _BROKERABLE_PROVIDERS or not sid or not PUBLIC_BASE_URL:
+ # Where the sandbox reaches the broker: this gateway's own door beside a local runner, else the
+ # public base (see _sandbox_broker_origin). A self-hosted instance has the first without ever
+ # setting the second, and an Entra connection there is brokered all the same.
+ if provider not in _BROKERABLE_PROVIDERS or not sid or not _sandbox_broker_origin():
log_reason = ("provider not brokerable" if provider not in _BROKERABLE_PROVIDERS
else "no session id" if not sid else "HARNESS_PUBLIC_BASE_URL unset")
print(f"[broker] refusing to build sandbox auth for provider={provider!r}: {log_reason}",
@@ -1165,7 +1173,8 @@ _IMAGE_MODEL_MAP_KEY = "harness-image-model-map"
# measurement, this is policy, and one must not overwrite the other.
_MEDIA_POLICY_KEY = "harness-media-policy"
_IMAGE_MODEL_MAP_PREV_KEY = "harness-image-model-map.prev"
-_INTEGRATION_SECRET_FIELDS = ("api_key", "aws_bearer_token", "aws_secret_access_key", "aws_session_token")
+_INTEGRATION_SECRET_FIELDS = ("api_key", "aws_bearer_token", "aws_secret_access_key", "aws_session_token",
+ "client_secret") # an Entra application's secret (see _entra_token)
# The hosted HarnessRouter service as a model provider. One origin, three routes: the provider
# front door the runners call (OpenAI and Anthropic shapes and Gemini's native path, all under one
# base), the model list it serves, and the connect flow that hands a key to this instance.
@@ -3905,6 +3914,15 @@ 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."""
+ provider = str((conn or {}).get("provider") or "your provider")
+ what = "connection" if str((conn or {}).get("auth") or "").strip().lower() == "entra" else "key"
+ return f"Your {provider} {what} was refused: {err or 'the provider returned an error'}"
+
+
def _turn_failure_message(rec: dict) -> str:
"""What a failed turn says: the org's own key's refusal in plain words when that is why, else
the last connection's reason in words. Never the tried list itself: its JSON, with our
@@ -3975,6 +3993,95 @@ def _provider_base_url(provider: str, base_url: str) -> str:
return base
+# ── an Azure connection that signs in with Microsoft Entra instead of an API key ────────────────
+# An organization that does not issue API keys reaches Azure OpenAI and Foundry as an application
+# registered in its own directory: a tenant id, a client id and a client secret, held where a key is
+# held today and never handed to a sandbox. The broker asks Entra for a token for the Azure AI scope
+# (the client-credentials grant), keeps it until shortly before it expires, and presents it as the
+# bearer in place of the `api-key` header. Built on the hosted service first (2026-10-06) and taken
+# from there as it is; what differs here is only that such a connection is brokered in owner trust
+# too (see _auth_from_conn).
+_ENTRA_PROVIDERS = ("azure", "azure-foundry")
+_ENTRA_AUTHORITY = os.environ.get("HR_ENTRA_AUTHORITY", "https://login.microsoftonline.com").rstrip("/")
+_ENTRA_SCOPE = "https://cognitiveservices.azure.com/.default"
+_ENTRA_FIELDS = ("tenant_id", "client_id", "client_secret")
+_ENTRA_LABELS = {"tenant_id": "Directory (tenant) ID", "client_id": "Application (client) ID",
+ "client_secret": "Client secret"}
+_ENTRA_ID_RE = re.compile(r"^[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$")
+_ENTRA_EARLY_S = 300 # a token is replaced this long before Entra would refuse it
+_entra_tokens: dict[str, tuple[str, float]] = {}
+_entra_locks: dict[str, asyncio.Lock] = {}
+
+
+def _entra_conn(conn: dict | None) -> bool:
+ return str((conn or {}).get("auth") or "").strip().lower() == "entra"
+
+
+def _entra_config_error(provider: str, cfg: dict) -> str:
+ """Why an integration's Entra settings cannot be saved, "" when they can."""
+ if provider not in _ENTRA_PROVIDERS:
+ return "Microsoft Entra sign-in is available for Azure OpenAI and Azure AI Foundry connections"
+ # In the words the form uses, since a person reads this beside the form.
+ missing = [_ENTRA_LABELS[f] for f in _ENTRA_FIELDS if not str(cfg.get(f) or "").strip()]
+ if missing:
+ return "missing the " + ", the ".join(missing)
+ for f in ("tenant_id", "client_id"):
+ if not _ENTRA_ID_RE.match(str(cfg[f]).strip()):
+ return f"the {_ENTRA_LABELS[f]} is written as a GUID, like 00000000-0000-0000-0000-000000000000"
+ if not str(cfg.get("base_url") or "").strip():
+ return "missing the Endpoint URL of the Azure resource"
+ return ""
+
+
+async def _entra_token(conn: dict) -> str:
+ """A bearer token for this connection's application, from Entra or from this process's memory."""
+ tenant, client, secret = (str(conn.get(f) or "").strip() for f in _ENTRA_FIELDS)
+ scope = str(conn.get("entra_scope") or _ENTRA_SCOPE).strip()
+ if not (tenant and client and secret):
+ raise HTTPException(502, "this connection signs in with Microsoft Entra and is missing its tenant id, client id or client secret")
+ k = hashlib.sha256(f"{tenant}|{client}|{scope}|{secret}".encode()).hexdigest()
+ hit = _entra_tokens.get(k)
+ if hit and hit[1] > time.time():
+ return hit[0]
+ async with _entra_locks.setdefault(k, asyncio.Lock()):
+ hit = _entra_tokens.get(k)
+ if hit and hit[1] > time.time():
+ return hit[0]
+ try:
+ r = await _client().post(f"{_ENTRA_AUTHORITY}/{tenant}/oauth2/v2.0/token", timeout=20.0,
+ data={"grant_type": "client_credentials", "client_id": client,
+ "client_secret": secret, "scope": scope})
+ doc = r.json() if r.content else {}
+ except Exception as e: # noqa: BLE001
+ raise HTTPException(502, f"Microsoft Entra could not be reached for this connection's sign-in: {type(e).__name__}")
+ token = str((doc or {}).get("access_token") or "")
+ if r.status_code != 200 or not token:
+ # Entra's own code and first sentence (AADSTS7000215: Invalid client secret provided...)
+ # are what the person fixing the connection needs; neither carries the secret. Its
+ # trace and correlation ids follow on new lines or, for some codes, on the same one.
+ why = re.split(r"\s*(?:\r?\n|Trace ID:)", str((doc or {}).get("error_description") or (doc or {}).get("error")
+ or f"HTTP {r.status_code}"), maxsplit=1)[0][:300]
+ if r.status_code in (400, 401, 403):
+ # A directory, application or secret Entra does not accept is this connection's own
+ # credentials being wrong: the same thing as a provider refusing an API key, and
+ # answered the same way. On a 502 Codex reconnected five times before giving up and
+ # a turn was free to try its next connection (measured 2026-10-06); on a 401 the
+ # agent stops and the turn says the connection was refused.
+ raise HTTPException(401, f"Microsoft Entra refused this connection's sign-in: {why}")
+ # Entra throttling or failing is not a refusal: a bad gateway, which may pass.
+ raise HTTPException(502, f"Microsoft Entra did not sign this connection in: {why}")
+ try:
+ life = max(60.0, float(doc.get("expires_in") or 3600) - _ENTRA_EARLY_S)
+ except (TypeError, ValueError):
+ life = 3000.0
+ _entra_tokens[k] = (token, time.time() + life)
+ # One line per sign-in (about one an hour per connection): what an operator looks for when a
+ # task says Entra refused it or a long task fails an hour in. The application's id is not a
+ # secret; nothing of the secret or the token is written.
+ print(f"[entra] signed in as application ••••{client[-4:]}; asking again in {int(life)} s", flush=True)
+ return token
+
+
@app.api_route("/v1/llm/{path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE"])
async def llm_broker(path: str, request: Request):
claims = _verify_turn_cred(_broker_token(request))
@@ -4006,7 +4113,10 @@ async def llm_broker(path: str, request: Request):
provider = str(conn.get("provider") or "")
# Present the real credential the way THIS provider expects it.
if provider in ("azure", "azure-foundry"):
- headers["api-key"] = key
+ if _entra_conn(conn):
+ headers["authorization"] = f"Bearer {await _entra_token(conn)}"
+ else:
+ headers["api-key"] = key
elif provider == "anthropic":
headers["x-api-key"] = key
else:
@@ -5007,6 +5117,14 @@ _PROVIDER_CATALOG: dict[str, dict] = {
"placeholder": "https://<resource>.openai.azure.com/openai/v1"}],
"secret": "api_key",
"secret_label": "API Key",
+ # The other way in: as an application in the organization's own Microsoft Entra directory,
+ # for an organization that issues no API keys (see _entra_token). The form offers the choice
+ # and asks for these in place of the key.
+ "entra": {"fields": [{"key": "tenant_id", "label": "Directory (tenant) ID",
+ "placeholder": "00000000-0000-0000-0000-000000000000"},
+ {"key": "client_id", "label": "Application (client) ID",
+ "placeholder": "00000000-0000-0000-0000-000000000000"}],
+ "secret": "client_secret", "secret_label": "Client secret"},
},
"bedrock": {
"label": "AWS Bedrock",
@@ -5162,6 +5280,7 @@ def _provider_catalog_public() -> list[dict]:
"secret": meta["secret"],
"secret_label": meta["secret_label"],
"key_hint": meta.get("key_hint", ""),
+ **({"entra": meta["entra"]} if meta.get("entra") else {}),
"models": [{"canonical": c, "provider_id": v}
for c, v in _VENDOR_MODELS.get(pid, {}).items()],
# The custom provider's rows name any canonical; the form offers this list.
@@ -5389,6 +5508,20 @@ async def admin_integrations_put(body: IntegrationsBody, request: Request) -> di
if not prior_cfg.get(k):
raise HTTPException(400, f"integration '{name}': missing {k}")
cfg[k] = prior_cfg[k]
+ # How the connection signs in: an API key (nothing said, as before) or Microsoft Entra.
+ how = str(cfg.get("auth") or "").strip().lower()
+ if how in ("", "key", "api_key"):
+ # ...and a connection switched back to a key keeps nothing of the application it was
+ for k in ("auth", *_ENTRA_FIELDS, "entra_scope"):
+ cfg.pop(k, None)
+ elif how == "entra":
+ cfg = {**{k: (str(v).strip() if isinstance(v, str) else v) for k, v in cfg.items()}, "auth": "entra"}
+ cfg.pop("api_key", None) # one way in per connection: a key left beside it would never be used
+ why = _entra_config_error(provider, cfg)
+ if why:
+ raise HTTPException(400, f"integration '{name}': {why}")
+ else:
+ raise HTTPException(400, f"integration '{name}': auth is \"key\" or \"entra\"")
# A provider whose endpoint we know supplies its own base_url. Asking the user for a
# value we can look up is a question with exactly one right answer and many wrong ones.
known_base = (_PROVIDER_CATALOG.get(provider) or {}).get("base_url")
@@ -7858,8 +7991,7 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
# 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.
- provider = str(conn.get("provider") or "your provider")
- rec["error_message"] = f"Your {provider} key was refused: {_last_err or 'the provider returned an error'}"
+ rec["error_message"] = _refusal_message(conn, _last_err)
status = "failed"
rec["status"] = "failed"
await _vertex_upsert(sid, {"status": "failed", "turn_status": "failed", "last_connection": name})
@@ -13990,7 +14122,8 @@ _PLUG_GUIDES: dict[str, str] = {
"## Vercel\n"
"This task deploys the company's Vercel project through the `plugs` server. Its tools: "
"{tools}. To deploy: put the code in the linked GitHub repository, then call "
- "vercel_deploy_from_repo (name a ref for a preview; production true for production) and "
+ "vercel_deploy_from_repo (name a ref for a preview; production true for production; a "
+ "project's first deployment is production whatever is asked, and the tool says so) and "
"report the url it returns; vercel_get_deployment and vercel_get_deployment_logs say how a "
"deployment went, vercel_set_env sets an environment variable. There is no VERCEL_TOKEN, "
"project id or team id in the environment and the `vercel` CLI is not signed in: do not "
diff --git a/gateway/plugs_plane.py b/gateway/plugs_plane.py
index 102a3789..ea08f04b 100644
--- a/gateway/plugs_plane.py
+++ b/gateway/plugs_plane.py
@@ -953,7 +953,9 @@ async def _vc_link(c, f, cfg) -> dict:
@_tool("vercel", "deploy_from_repo", "write",
"Create a deployment from the linked GitHub repository at a ref, then watch it for up to two minutes. "
- "Returns the deployment's id, state and url; call get_deployment to keep watching a slow build.",
+ "Returns the deployment's id, state, target and url; call get_deployment to keep watching a slow build. "
+ "Vercel makes a project's FIRST deployment a production one whatever is asked; a preview is what "
+ "the same call gives from the second deployment on.",
_obj({"ref": _s("Branch, tag or commit; the production branch when omitted"),
"production": _b("Deploy to production rather than as a preview"),
"repo": _s("owner/name, when the project is not linked yet")}))
@@ -980,7 +982,16 @@ async def _(c, f, cfg, a):
break
await asyncio.sleep(DEPLOY_POLL_S)
d = await _vc(c, f, cfg, "GET", f"/v13/deployments/{did}")
- return _deploy_out(d)
+ out = _deploy_out(d)
+ if not a.get("production") and str(d.get("target") or "") == "production":
+ # Seen twice on the hosted service, 2026-10-05, the second time on a branch that is not the
+ # production branch: a project with no deployment yet gets a production one, and an agent
+ # that asked for a preview reported its task blocked. The answer says what happened and
+ # what to do.
+ out["note"] = ("A preview was asked for and Vercel made this a production deployment, as it does for a "
+ "project's first deployment. It is live on the project's production address. Call "
+ "deploy_from_repo again with the same ref for a preview.")
+ return out
@_tool("vercel", "link_repo", "write", "Link the project to a GitHub repository (owner/name).",
diff --git a/gateway/tests/test_entra_connection.py b/gateway/tests/test_entra_connection.py
new file mode 100644
index 00000000..9285e540
--- /dev/null
+++ b/gateway/tests/test_entra_connection.py
@@ -0,0 +1,258 @@
+"""An Azure connection that signs in with Microsoft Entra instead of an API key.
+
+An organization that issues no API keys reaches Azure OpenAI and Foundry as an application in its own
+directory (tenant id, client id, client secret). The broker asks Entra for a token by the
+client-credentials grant, keeps it until shortly before it expires, and presents it as the bearer.
+Built and first tested on the hosted service; the last three tests are this tree's own, where such a
+connection is brokered in owner trust too.
+"""
+import asyncio
+import sys
+from pathlib import Path
+
+import pytest
+from fastapi import HTTPException
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import app as gw # noqa: E402
+
+TENANT, CLIENT = "11111111-2222-3333-4444-555555555555", "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
+CONN = {"provider": "azure", "auth": "entra", "tenant_id": TENANT, "client_id": CLIENT,
+ "client_secret": "s3cret-value", "base_url": "https://res.openai.azure.com"}
+
+
+class _Resp:
+ def __init__(self, status, doc):
+ self.status_code, self._doc, self.content = status, doc, b"x"
+
+ def json(self):
+ return self._doc
+
+
+class _Entra:
+ """Stands in for Entra's token endpoint; records what it was asked."""
+ def __init__(self, answers):
+ self.answers, self.calls = list(answers), []
+
+ async def post(self, url, data=None, timeout=None):
+ self.calls.append((url, dict(data or {})))
+ return self.answers.pop(0)
+
+
[email protected](autouse=True)
+def _fresh():
+ gw._entra_tokens.clear()
+ gw._entra_locks.clear()
+ yield
+
+
+def test_the_token_is_asked_for_once_and_kept_until_shortly_before_it_expires(monkeypatch):
+ entra = _Entra([_Resp(200, {"access_token": "tok-1", "expires_in": 3600}),
+ _Resp(200, {"access_token": "tok-2", "expires_in": 3600})])
+ monkeypatch.setattr(gw, "_client", lambda: entra)
+ now = [1000.0]
+ monkeypatch.setattr(gw.time, "time", lambda: now[0])
+
+ async def run():
+ a = await gw._entra_token(CONN)
+ b = await gw._entra_token(dict(CONN))
+ now[0] += 3600 - gw._ENTRA_EARLY_S + 1 # inside the last minutes of the token's life
+ c = await gw._entra_token(CONN)
+ return a, b, c
+ assert asyncio.run(run()) == ("tok-1", "tok-1", "tok-2")
+ url, form = entra.calls[0]
+ assert url == f"https://login.microsoftonline.com/{TENANT}/oauth2/v2.0/token" and len(entra.calls) == 2
+ assert form == {"grant_type": "client_credentials", "client_id": CLIENT, "client_secret": "s3cret-value",
+ "scope": "https://cognitiveservices.azure.com/.default"}
+
+
+def test_a_sign_in_leaves_one_log_line_with_the_applications_id_and_nothing_secret(monkeypatch, capsys):
+ monkeypatch.setattr(gw, "_client", lambda: _Entra([_Resp(200, {"access_token": "tok-LOGGED", "expires_in": 3599})]))
+ for _ in range(3):
+ asyncio.run(gw._entra_token(CONN))
+ lines = [ln for ln in capsys.readouterr().out.splitlines() if ln.startswith("[entra]")]
+ assert lines == [f"[entra] signed in as application ••••{CLIENT[-4:]}; asking again in 3299 s"]
+ assert "tok-LOGGED" not in lines[0] and CONN["client_secret"] not in lines[0]
+
+
+def test_two_calls_at_once_ask_entra_once(monkeypatch):
+ entra = _Entra([_Resp(200, {"access_token": "tok-1", "expires_in": 3600})])
+ monkeypatch.setattr(gw, "_client", lambda: entra)
+
+ async def run():
+ return await asyncio.gather(gw._entra_token(CONN), gw._entra_token(CONN), gw._entra_token(CONN))
+ assert asyncio.run(run()) == ["tok-1"] * 3 and len(entra.calls) == 1
+
+
+def test_a_refused_sign_in_says_what_entra_said_and_never_the_secret(monkeypatch):
+ entra = _Entra([_Resp(401, {"error": "invalid_client",
+ "error_description": "AADSTS7000215: Invalid client secret provided. Ensure the secret is the value.\r\nTrace ID: abc"})])
+ monkeypatch.setattr(gw, "_client", lambda: entra)
+ with pytest.raises(HTTPException) as e:
+ asyncio.run(gw._entra_token(CONN))
+ # 401, as a provider refusing an API key answers: the agent stops and the turn says so
+ assert e.value.status_code == 401 and "AADSTS7000215" in e.value.detail
+ assert e.value.detail.startswith("Microsoft Entra refused this connection's sign-in: ")
+ assert "Trace ID" not in e.value.detail and "s3cret-value" not in e.value.detail
+ assert not gw._entra_tokens # a refusal is not remembered: the next call asks again
+ # an unknown directory's description carries its trace id on the same line (seen 2026-10-06)
+ monkeypatch.setattr(gw, "_client", lambda: _Entra([_Resp(400, {"error": "invalid_request", "error_description":
+ "AADSTS90002: Tenant 'x' not found. Check with your subscription administrator. Trace ID: 62635bf8 Correlation ID: 9a"})]))
+ with pytest.raises(HTTPException) as e:
+ asyncio.run(gw._entra_token(CONN))
+ assert e.value.status_code == 401
+ assert e.value.detail == "Microsoft Entra refused this connection's sign-in: AADSTS90002: Tenant 'x' not found. Check with your subscription administrator."
+
+
+def test_entra_failing_is_not_a_refusal_of_the_connection(monkeypatch):
+ for status, doc in ((429, {"error": "temporarily_unavailable", "error_description": "AADSTS90055: Too many requests."}),
+ (503, {}), (200, {"token_type": "Bearer"})):
+ gw._entra_tokens.clear()
+ monkeypatch.setattr(gw, "_client", lambda status=status, doc=doc: _Entra([_Resp(status, doc)]))
+ with pytest.raises(HTTPException) as e:
+ asyncio.run(gw._entra_token(CONN))
+ assert e.value.status_code == 502 and e.value.detail.startswith("Microsoft Entra did not sign this connection in: "), status
+ assert not gw._provider_refused(f"hr API error (502): {e.value.detail}"), status
+
+
+def test_a_turn_refused_on_an_entra_connection_does_not_speak_of_a_key():
+ entra = "hr API error (401): Microsoft Entra refused this connection's sign-in: AADSTS7000215: Invalid client secret provided."
+ role = 'hr API error (401): {"code":"PermissionDenied","message":"The principal lacks the required data action"}'
+ 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"
+
+
+def test_another_secret_or_scope_is_another_token(monkeypatch):
+ entra = _Entra([_Resp(200, {"access_token": "tok-1", "expires_in": 3600}),
+ _Resp(200, {"access_token": "tok-2", "expires_in": 3600}),
+ _Resp(200, {"access_token": "tok-3", "expires_in": 3600})])
+ monkeypatch.setattr(gw, "_client", lambda: entra)
+
+ async def run():
+ return (await gw._entra_token(CONN), await gw._entra_token({**CONN, "client_secret": "rotated"}),
+ await gw._entra_token({**CONN, "entra_scope": "https://ai.azure.com/.default"}))
+ assert asyncio.run(run()) == ("tok-1", "tok-2", "tok-3")
+ assert entra.calls[2][1]["scope"] == "https://ai.azure.com/.default"
+
+
+def test_what_can_be_saved_as_an_entra_connection():
+ ok = {k: v for k, v in CONN.items() if k != "provider"}
+ assert gw._entra_config_error("azure", ok) == "" == gw._entra_config_error("azure-foundry", ok)
+ assert "Azure" in gw._entra_config_error("openai", ok)
+ assert gw._entra_config_error("azure", {**ok, "client_secret": ""}) == "missing the Client secret"
+ assert gw._entra_config_error("azure", {**ok, "client_secret": "", "tenant_id": ""}) == \
+ "missing the Directory (tenant) ID, the Client secret"
+ why = gw._entra_config_error("azure", {**ok, "tenant_id": "contoso.onmicrosoft.com"})
+ assert why.startswith("the Directory (tenant) ID is written as a GUID") and "tenant_id" not in why
+ assert "Endpoint URL" in gw._entra_config_error("azure", {**ok, "base_url": ""})
+ assert gw._entra_conn(CONN) and not gw._entra_conn({"provider": "azure", "api_key": "k"}) and not gw._entra_conn(None)
+
+
+def test_the_secret_is_one_of_the_fields_the_console_never_gets_back_and_a_sandbox_never_sees():
+ assert "client_secret" in gw._INTEGRATION_SECRET_FIELDS
+ shown = gw._integration_public({"name": "Azure", "provider": "azure-foundry", "config": dict(CONN)})
+ assert shown["config"]["client_secret"] == gw._SECRET_SENTINEL and shown["config"]["tenant_id"] == TENANT
+ for f in ("client_secret", "tenant_id", "client_id", "auth"):
+ assert f not in gw._AUTH_FIELDS
+
+
+def test_in_owner_trust_an_entra_connection_is_still_brokered(monkeypatch):
+ """Owner trust hands a connection's key to the agent. An Entra connection has no key to hand: it
+ has a secret that buys a token good for about an hour, and a turn may run for six. The broker
+ asks again as the token ages, and the agent holds neither."""
+ monkeypatch.setattr(gw, "SANDBOX_TRUST", "owner")
+ monkeypatch.setattr(gw, "PUBLIC_BASE_URL", "")
+ monkeypatch.setattr(gw, "INTERNAL_KEY", "k-test")
+ monkeypatch.setenv("HARNESS_GATEWAY_URL", "http://127.0.0.1:8080")
+ monkeypatch.setattr(gw, "_pool_is_local", lambda: True)
+ entra = {"name": "integration:Azure Entra", "backend": "codex", **CONN}
+ auth = gw._auth_from_conn(entra, "hsess1")
+ assert auth and auth["base_url"] == "http://127.0.0.1:8080/v1/llm"
+ assert gw._verify_turn_cred(auth["api_key"]) == ("hsess1", "integration:Azure Entra")
+ assert "s3cret-value" not in str(auth) and "client_secret" not in auth and "tenant_id" not in auth
+ # a connection with a key is handed over in owner trust, as it always was
+ keyed = gw._auth_from_conn({"name": "integration:Azure", "backend": "codex", "provider": "azure",
+ "api_key": "az-key", "base_url": "https://res.openai.azure.com"}, "hsess1")
+ assert keyed["api_key"] == "az-key" and keyed["base_url"] == "https://res.openai.azure.com/openai/v1"
+
+
+def test_the_broker_presents_the_token_as_the_bearer_and_a_key_as_the_api_key_header():
+ import os
+ src = open(os.path.join(os.path.dirname(__file__), "..", "app.py")).read()
+ i = src.index("async def llm_broker(")
+ body = src[i:src.index("body = _strip_unsupported(", i)]
+ assert 'if _entra_conn(conn):\n headers["authorization"] = f"Bearer {await _entra_token(conn)}"' in body
+ assert 'else:\n headers["api-key"] = key' in body
+
+
+def _save(monkeypatch, integrations, stored=()):
+ """PUT /v1/admin/integrations with its storage stood in for; → what was written."""
+ written = {}
+
+ async def allow(request):
+ return None
+
+ async def doc():
+ return list(stored)
+
+ async def vget(tenant, key):
+ return None
+
+ async def vput(tenant, key, value):
+ written[key] = value
+ return True
+ monkeypatch.setattr(gw, "_require_integrations_admin", allow)
+ monkeypatch.setattr(gw, "_integrations_doc", doc)
+ monkeypatch.setattr(gw, "_vault_get", vget)
+ monkeypatch.setattr(gw, "_vault_put", vput)
+ asyncio.run(gw.admin_integrations_put(gw.IntegrationsBody(integrations=list(integrations)), None))
+ import json
+ return {i["name"]: i for i in json.loads(written[gw._INTEGRATIONS_KEY])}
+
+
+def test_saving_takes_a_key_or_entra_and_never_both(monkeypatch):
+ entra_cfg = {"auth": "entra", "tenant_id": f" {TENANT} ", "client_id": CLIENT, "client_secret": "s3cret-value",
+ "base_url": "https://res.openai.azure.com", "api_key": "left-over-key"}
+ out = _save(monkeypatch, [{"name": "Azure Entra", "provider": "azure-foundry", "config": entra_cfg},
+ {"name": "Azure Key", "provider": "azure-foundry",
+ "config": {"auth": "key", "api_key": "az-key", "base_url": "https://res.openai.azure.com"}}])
+ cfg = out["Azure Entra"]["config"]
+ assert cfg["auth"] == "entra" and cfg["tenant_id"] == TENANT and cfg["client_secret"] == "s3cret-value"
+ assert "api_key" not in cfg # one way in per connection
+ assert "auth" not in out["Azure Key"]["config"] and out["Azure Key"]["config"]["api_key"] == "az-key"
+ # an unchanged edit sends the sentinel back and the stored secret is carried through
+ again = _save(monkeypatch, [{"name": "Azure Entra", "provider": "azure-foundry",
+ "config": {**cfg, "client_secret": gw._SECRET_SENTINEL}}],
+ stored=[out["Azure Entra"]])
+ assert again["Azure Entra"]["config"]["client_secret"] == "s3cret-value"
+ for bad, why in (({**entra_cfg, "client_secret": ""}, "missing the Client secret"),
+ ({**entra_cfg, "tenant_id": "contoso.onmicrosoft.com"}, "GUID"),
+ ({**entra_cfg, "auth": "certificate"}, 'auth is "key" or "entra"')):
+ with pytest.raises(HTTPException) as e:
+ _save(monkeypatch, [{"name": "Azure Entra", "provider": "azure-foundry", "config": bad}])
+ assert e.value.status_code == 400 and why in e.value.detail, e.value.detail
+ with pytest.raises(HTTPException) as e: # Entra is for the two Azure kinds
+ _save(monkeypatch, [{"name": "TR", "provider": "tokenrouter", "config": {**entra_cfg}}])
+ assert "Azure OpenAI and Azure AI Foundry" in e.value.detail
+
+
+def test_a_connection_switched_back_to_a_key_keeps_nothing_of_the_application(monkeypatch):
+ out = _save(monkeypatch, [{"name": "Azure", "provider": "azure-foundry",
+ "config": {"auth": "", "api_key": "az-key", "base_url": "https://res.openai.azure.com",
+ "tenant_id": TENANT, "client_id": CLIENT, "client_secret": "s3cret-value"}}])
+ assert out["Azure"]["config"] == {"api_key": "az-key", "base_url": "https://res.openai.azure.com"}
+
+
+def test_the_form_is_told_which_provider_offers_entra_and_what_to_ask():
+ by_id = {p["id"]: p for p in gw._provider_catalog_public()}
+ entra = by_id["azure-foundry"]["entra"]
+ assert [f["key"] for f in entra["fields"]] == ["tenant_id", "client_id"] and entra["secret"] == "client_secret"
+ assert entra["secret"] in gw._INTEGRATION_SECRET_FIELDS
+ assert all("entra" not in p for pid, p in by_id.items() if pid != "azure-foundry")
+ # the words a refusal uses are the form's own labels
+ labels = {f["key"]: f["label"] for f in entra["fields"]} | {entra["secret"]: entra["secret_label"]}
+ assert labels == gw._ENTRA_LABELS
diff --git a/gateway/tests/test_plugs.py b/gateway/tests/test_plugs.py
index e8b636c2..7b417b76 100644
--- a/gateway/tests/test_plugs.py
+++ b/gateway/tests/test_plugs.py
@@ -109,7 +109,8 @@ class Vendor:
assert body["gitSource"] == {"type": "github", "repoId": 42, "ref": "main"}
return httpx.Response(200, json={"id": "dpl_1", "url": "site-abc.vercel.app", "readyState": "QUEUED"})
if path == "/v13/deployments/dpl_1":
- return httpx.Response(200, json={"id": "dpl_1", "url": "site-abc.vercel.app", "readyState": "READY", "target": "production"})
+ return httpx.Response(200, json={"id": "dpl_1", "url": "site-abc.vercel.app", "readyState": "READY",
+ "target": getattr(self, "target", "production")})
return httpx.Response(404, json={"error": {"message": f"no mock for {path}"}})
if host == "acme.insforge.app":
assert r.headers.get("Authorization") == f"Bearer {INF_KEY}"
@@ -434,6 +435,19 @@ def test_push_files_deploy_and_insert_drive_the_vendors_as_documented(world):
{"token": VC_TOKEN}, _record("vercel")["config"])))
assert out["id"] == "dpl_1" and out["readyState"] == "READY"
assert json.loads(ven.calls[1].content)["target"] == "production"
+ assert "note" not in out # production was asked for and given: nothing to say
+ # A project's first deployment is production at Vercel whatever is asked (seen twice on the
+ # hosted service, 2026-10-05): a preview request answered with a production deployment says so
+ # and what to do.
+ out = json.loads(asyncio.run(plugs_plane.call("vercel", "deploy_from_repo", {},
+ {"token": VC_TOKEN}, _record("vercel")["config"])))
+ assert out["target"] == "production" and "first deployment" in out["note"] and "again" in out["note"]
+ ven.target = None # the second deployment on: a preview, as asked
+ out = json.loads(asyncio.run(plugs_plane.call("vercel", "deploy_from_repo", {},
+ {"token": VC_TOKEN}, _record("vercel")["config"])))
+ assert "note" not in out and out.get("target") != "production"
+ ven.target = "production"
+ assert "FIRST deployment" in plugs_plane.find("vercel", "deploy_from_repo")["description"]
out = json.loads(asyncio.run(plugs_plane.call("vercel", "get_project", {}, {"token": VC_TOKEN}, _record("vercel")["config"])))
assert out["domains"] == ["site.vercel.app"] and out["link"]["repo"] == "site"
diff --git a/runner/dsh_driver.py b/runner/dsh_driver.py
index c0925df4..8e18f446 100644
--- a/runner/dsh_driver.py
+++ b/runner/dsh_driver.py
@@ -40,12 +40,13 @@ _effort_refused: set = set() # models whose provider refused the level on this
def _upstream_wait() -> float:
"""How long this relay waits on the provider: for the answer to begin, and in a stream for the
next EVENT. The runner's own figure (HR_RELAY_UPSTREAM_TIMEOUT_S, handed over by _build_dsh),
- 600 s when it is absent or not a positive number."""
+ 180 s when it is absent or not a positive number (the runner's default; see
+ _relay_upstream_timeout in server.py for what that costs and buys)."""
try:
- v = float(os.environ.get("HR_RELAY_UPSTREAM_TIMEOUT_S") or 600)
+ v = float(os.environ.get("HR_RELAY_UPSTREAM_TIMEOUT_S") or 180)
except ValueError:
- return 600.0
- return v if v > 0 else 600.0
+ return 180.0
+ return v if v > 0 else 180.0
UPSTREAM_WAIT_S = _upstream_wait()
diff --git a/runner/environments.py b/runner/environments.py
index 166748a9..6e133878 100644
--- a/runner/environments.py
+++ b/runner/environments.py
@@ -851,9 +851,21 @@ def _build(env_id: str, n: int, slug: str, activate: bool, spec: dict | None = N
rec["files"], rec["bytes"] = _size(dst)
rec["status"], rec["finished_at"], rec["stage"] = "ready", int(time.time()), ""
log.append(f"ready: {rec['files']} files, {len(rec['packages'])} packages, {int(time.time()) - started}s")
- _write_record(dst, rec)
if activate:
- activate_version(env_id, n, slug)
+ # The record is the build's last word, so what the build promised is in place before it
+ # says ready. It used to be written first: a reader that waited for "ready" and started
+ # a turn at once found no active version in between (issue #401; a CI run met it on a
+ # slow disk, 2026-10-05). If the last steps fail, the active version is what it was.
+ was = active_version(env_id)
+ try:
+ _point_active(env_id, n)
+ ensure_mount(env_id, slug)
+ _write_record(dst, rec)
+ except Exception:
+ _point_active(env_id, was)
+ raise
+ else:
+ _write_record(dst, rec)
except Exception as e: # noqa: BLE001 — the record IS the report; nothing else sees this thread
rec["status"], rec["finished_at"], rec["error"], rec["stage"] = "failed", int(time.time()), str(e)[:500], ""
log.append(f"failed: {e}")
@@ -882,17 +894,25 @@ def start_build(env_id: str, n: int, slug: str, activate: bool = True, spec: dic
return {"version": n, "status": "building"}
-def activate_version(env_id: str, n: int, slug: str) -> dict:
- dst = version_dir(env_id, n)
- rec = build_record(env_id, n)
- if not dst.is_dir() or not rec or rec.get("status") != "ready":
- raise HTTPException(409, f"version {n} is not a finished build")
+def _point_active(env_id: str, n: int | None) -> None:
+ """Make version n the environment's active one; None leaves it with none."""
link = active_link(env_id)
+ if n is None:
+ link.unlink(missing_ok=True)
+ return
tmp = link.with_name("active.tmp")
if tmp.is_symlink() or tmp.exists():
tmp.unlink()
os.symlink(os.path.join("versions", str(n)), tmp)
os.replace(tmp, link) # atomic: a session mid-turn sees the old or the new, never neither
+
+
+def activate_version(env_id: str, n: int, slug: str) -> dict:
+ dst = version_dir(env_id, n)
+ rec = build_record(env_id, n)
+ if not dst.is_dir() or not rec or rec.get("status") != "ready":
+ raise HTTPException(409, f"version {n} is not a finished build")
+ _point_active(env_id, n)
ensure_mount(env_id, slug)
return {"version": n, "status": "ready", "path": mount_path(slug)}
diff --git a/runner/server.py b/runner/server.py
index b0c586b0..2b52006c 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -4956,18 +4956,27 @@ def _adapt_custom_auth(auth):
# and every later read; and, in a stream, the longest run of keep-alive lines with no event between
# them, since those keep the socket from ever timing out). It must stay BELOW the turn cap above it, or a provider that accepts a
# request and then goes silent is indistinguishable from a working turn: the cap fires first and the
-# turn is cancelled with no served model, no tool call and no reason. The default is the 600 s this
-# relay has always waited, far under MAX_TURN_SECONDS: a reasoning model answering a non-streaming
-# call can be silent for minutes and that is an answer on its way, not a failure. An instance whose
-# own cap is shorter sets this lower: the support-matrix suite caps a turn at 600 s, so the instance
-# it measures runs with HR_RELAY_UPSTREAM_TIMEOUT_S=180 (seven of fourteen tour families were "not
-# settled in 600s" on 2026-09-29 with the two equal). A value that is not a positive number is ignored.
+# turn is cancelled with no served model, no tool call and no reason.
+#
+# The default is 180 s since 2026-10-06 (it was 600 s), the hosted service's value and Richard's
+# decision for both, made with this cost in front of him: a model that thinks without sending
+# anything is cut off. Measured that day, one hard problem at each model's highest level, streamed:
+# on most routes thinking arrives as events and the longest gap was seconds (13 of 16 cells, 0.7 to
+# 61 s), but three cells sent nothing for over 200 s before answering: gpt-5.5 and gemini-3.1-pro
+# on Chat Completions through TokenRouter (201 s and 205 s, not one byte), and claude-opus-5.5
+# through Vercel (211 s of keep-alive lines). Those end here as a timeout the turn reports. What the
+# shorter wait buys is the other case measured the same hour: a call that never answered at all in
+# 1,200 s now ends in three minutes. An operator who runs such models at such levels raises
+# HR_RELAY_UPSTREAM_TIMEOUT_S. A value that is not a positive number is ignored.
+_RELAY_WAIT_DEFAULT_S = 180.0
+
+
def _relay_upstream_timeout() -> float:
try:
- v = float(os.environ.get("HR_RELAY_UPSTREAM_TIMEOUT_S") or 600)
+ v = float(os.environ.get("HR_RELAY_UPSTREAM_TIMEOUT_S") or _RELAY_WAIT_DEFAULT_S)
except ValueError:
- return 600.0
- return v if v > 0 else 600.0
+ return _RELAY_WAIT_DEFAULT_S
+ return v if v > 0 else _RELAY_WAIT_DEFAULT_S
HR_RELAY_UPSTREAM_TIMEOUT_S = _relay_upstream_timeout()
diff --git a/runner/tests/test_dsh_driver_stream_liveness.py b/runner/tests/test_dsh_driver_stream_liveness.py
index 1a547249..b474484c 100644
--- a/runner/tests/test_dsh_driver_stream_liveness.py
+++ b/runner/tests/test_dsh_driver_stream_liveness.py
@@ -108,11 +108,11 @@ def test_keep_alive_lines_alone_end_the_call_with_the_reason(monkeypatch):
assert b'"code": "upstream_unavailable"' in body and b"no data" in body
-def test_the_wait_is_the_runners_figure_and_600_without_it(monkeypatch):
+def test_the_wait_is_the_runners_figure_and_180_without_it(monkeypatch):
monkeypatch.delenv("HR_RELAY_UPSTREAM_TIMEOUT_S", raising=False)
- assert dsh_driver._upstream_wait() == 600
- monkeypatch.setenv("HR_RELAY_UPSTREAM_TIMEOUT_S", "180")
assert dsh_driver._upstream_wait() == 180
+ monkeypatch.setenv("HR_RELAY_UPSTREAM_TIMEOUT_S", "600")
+ assert dsh_driver._upstream_wait() == 600
for junk in ("", "0", "-1", "soon"):
monkeypatch.setenv("HR_RELAY_UPSTREAM_TIMEOUT_S", junk)
- assert dsh_driver._upstream_wait() == 600, junk
+ assert dsh_driver._upstream_wait() == 180, junk
diff --git a/runner/tests/test_environments.py b/runner/tests/test_environments.py
index 5785ed6d..f64bca46 100644
--- a/runner/tests/test_environments.py
+++ b/runner/tests/test_environments.py
@@ -138,6 +138,51 @@ def test_a_failed_build_records_why_and_never_becomes_active(store):
assert e.value.status_code == 409
+def test_when_the_record_says_ready_the_version_is_already_the_active_one(store, monkeypatch):
+ """The record is what a reader waits on. It was written before the version became active, and a
+ turn started the moment it read "ready" was refused with "the environment has no built version"
+ (issue #401). Asked here at the instant the ready record is written, not after it."""
+ seen = []
+ real = E._write_record
+
+ def spy(dst, rec):
+ if rec.get("status") == "ready":
+ seen.append((E.active_version("henv_o"), E.resolve({"id": "henv_o", "slug": "ordered"})["version"]))
+ real(dst, rec)
+ monkeypatch.setattr(E, "_write_record", spy)
+ E.write_file("henv_o", "setup.sh", b"#!/bin/sh\necho preparing\n")
+ E.start_build("henv_o", 1, "ordered")
+ assert _wait("henv_o", 1)["status"] == "ready"
+ assert seen == [(1, 1)]
+
+
+def test_a_build_whose_last_write_fails_leaves_the_active_version_as_it_was(store, monkeypatch):
+ E.write_file("henv_l", "setup.sh", b"#!/bin/sh\necho preparing\n")
+ E.start_build("henv_l", 1, "last")
+ assert _wait("henv_l", 1)["status"] == "ready" and E.active_version("henv_l") == 1
+ real = E._write_record
+ failed_once = []
+
+ def refuse_ready(dst, rec):
+ if rec.get("status") == "ready" and rec.get("version") == 2 and not failed_once:
+ failed_once.append(1)
+ raise OSError("no space left on device")
+ real(dst, rec)
+ monkeypatch.setattr(E, "_write_record", refuse_ready)
+ E.start_build("henv_l", 2, "last")
+ rec = _wait("henv_l", 2)
+ assert rec["status"] == "failed" and "no space" in rec["error"]
+ assert E.active_version("henv_l") == 1 # version 1 still serves
+ assert E.resolve({"id": "henv_l", "slug": "last"})["version"] == 1
+ # and a first build that fails the same way leaves the environment with no version at all
+ failed_once.clear()
+ monkeypatch.setattr(E, "_write_record", lambda dst, rec: (_ for _ in ()).throw(OSError("no space left on device"))
+ if rec.get("status") == "ready" else real(dst, rec))
+ E.write_file("henv_n", "setup.sh", b"#!/bin/sh\necho preparing\n")
+ E.start_build("henv_n", 1, "none")
+ assert _wait("henv_n", 1)["status"] == "failed" and E.active_version("henv_n") is None
+
+
def test_the_turn_gets_the_path_the_variables_and_the_instructions(store):
E.write_file("henv_t", "requirements.txt", b"")
E.write_file("henv_t", "package.json", json.dumps({"name": "p", "version": "1.0.0", "private": True}).encode())
diff --git a/runner/tests/test_relay_upstream_failure.py b/runner/tests/test_relay_upstream_failure.py
index 29afd7d2..e475cf70 100644
--- a/runner/tests/test_relay_upstream_failure.py
+++ b/runner/tests/test_relay_upstream_failure.py
@@ -198,19 +198,20 @@ def test_a_provider_that_goes_silent_is_reported_as_a_timeout_not_waited_on_fore
assert up.requests == 1, "a timeout is not retried: the provider may be generating, and billing"
-def test_the_upstream_wait_is_bounded_below_the_turn_cap_and_no_shorter_than_it_ever_was(monkeypatch):
- """Under the cap, so a silent provider is reported by the relay rather than discovered by the
- cap; and not under the 600 s this relay always waited, because a reasoning model answering a
- non-streaming call is silent for minutes and that is an answer on its way. An instance with a
- shorter cap of its own (the support-matrix suite's 600 s) sets the variable."""
+def test_the_upstream_wait_is_three_minutes_unless_the_operator_says_otherwise(monkeypatch):
+ """Under the turn cap, so a silent provider is reported by the relay rather than discovered by
+ the cap. 180 s since 2026-10-06, decided with its cost measured: three model and route cells
+ were silent for 201, 205 and 211 s before answering a hard problem at their highest thinking
+ level, and those end as a timeout at this default; a call that never answered at all ends in
+ three minutes instead of ten. An operator who runs such models raises the variable."""
monkeypatch.delenv("HR_RELAY_UPSTREAM_TIMEOUT_S", raising=False)
- assert rs._relay_upstream_timeout() == 600
- assert rs._relay_upstream_timeout() < rs.MAX_TURN_SECONDS
- monkeypatch.setenv("HR_RELAY_UPSTREAM_TIMEOUT_S", "180")
assert rs._relay_upstream_timeout() == 180
+ assert rs._relay_upstream_timeout() < rs.MAX_TURN_SECONDS
+ monkeypatch.setenv("HR_RELAY_UPSTREAM_TIMEOUT_S", "600")
+ assert rs._relay_upstream_timeout() == 600
for junk in ("", "0", "-5", "soon"):
monkeypatch.setenv("HR_RELAY_UPSTREAM_TIMEOUT_S", junk)
- assert rs._relay_upstream_timeout() == 600, junk
+ assert rs._relay_upstream_timeout() == 180, junk
def test_a_stream_that_stalls_is_not_ended_as_a_complete_answer(monkeypatch):
diff --git a/ui/src/app/(app)/integrations/page.tsx b/ui/src/app/(app)/integrations/page.tsx
index eb14f819..6bd8799d 100644
--- a/ui/src/app/(app)/integrations/page.tsx
+++ b/ui/src/app/(app)/integrations/page.tsx
@@ -40,6 +40,9 @@ interface ProviderMeta {
secret: string;
secret_label: string;
key_hint?: string;
+ /** The provider can also be reached as an application in the organization's own Microsoft Entra
+ * directory, in place of a key: the fields that asks for, and the name of its secret. */
+ entra?: { fields: ProviderField[]; secret: string; secret_label: string };
models: ModelRow[];
/** For the custom provider: every canonical id a harness can ask for, the choices of its rows. */
canonicals?: string[];
@@ -370,13 +373,35 @@ export default function IntegrationsPage() {
const isCustom = editing.provider === 'custom';
// Only what varies by deployment. A provider with a known endpoint never
// shows a Base URL field — the server fills it in.
- const fields = [...meta.fields,
- { key: meta.secret, label: meta.secret_label,
- placeholder: meta.key_hint }];
+ // A connection signs in with a key, or, where the provider offers it, as an
+ // application in the organization's own Microsoft Entra directory.
+ const entra = meta.entra && editing.config.auth === 'entra' ? meta.entra : null;
+ const secretKey = entra ? entra.secret : meta.secret;
+ const fields: ProviderField[] = entra
+ ? [...meta.fields, ...entra.fields, { key: entra.secret, label: entra.secret_label }]
+ : [...meta.fields,
+ { key: meta.secret, label: meta.secret_label,
+ placeholder: meta.key_hint }];
return (
<div className="field-stack">
+ {meta.entra && (
+ <div className="field">
+ <label htmlFor="itg-auth">Sign in with</label>
+ <select id="itg-auth" value={entra ? 'entra' : 'key'}
+ onChange={(e) => setEditing({
+ ...editing,
+ config: { ...editing.config, auth: e.target.value === 'entra' ? 'entra' : '' },
+ })}>
+ <option value="key">API key</option>
+ <option value="entra">Microsoft Entra</option>
+ </select>
+ {entra && (
+ <span className="field-help">Tasks sign in to Microsoft Entra as this application. Give the application a role on your Azure resource.</span>
+ )}
+ </div>
+ )}
{fields.map((f) => {
- const secret = f.key === meta.secret;
+ const secret = f.key === secretKey;
const saved = secret && editing.config[f.key] === SECRET;
// Special rendering for custom provider fields
if (isCustom && f.key === 'api_format') {