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.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
harness env: a per-turn environment for the agent's shell and tools, and the API described (#238)
github-actions[bot]793b04270a57
diff --git a/README.md b/README.mdindex 38765066..7c4b3e52 100644--- a/README.md+++ b/README.md@@ -207,6 +207,10 @@ curl --fail-with-body -sS "$HARNESSROUTER_BASE_URL/v1/responses" \The task and its transcript appear in the same workspace in the Console. Set `"stream": true` to receive server-sent events.+Never put a long exact value such as a token, an id or a hash in the prompt: the agent retypes what it reads, and a model drops and swaps characters in strings like that. Attach it as a file (`POST /v1/files`, then an `input_file` block; the file lands in the agent's working directory under its filename before every turn that carries it) or hand it to the agent through the harness's environment. A harness takes an `env` map whose values resolve on every turn: `$headers.X-Name` takes that header from the request (declare it in `additional_headers`), `vault:name` takes a stored secret, anything else is used as written. The agent's shell and tools start with those variables set, so a task can say "the token is in $DEPLOY_TOKEN", and a value that came through a reference is redacted from everything that leaves the sandbox, the response, the stream, the trace and the stored record, even when the agent prints it. A `vault:` reference reads only a secret your own workspace stored through `PUT /v1/mcp-secrets/{ref}`. The redaction protects the record, not the agent: a value the agent can read it can also send elsewhere if a prompt or a page tells it to, so hand it a token scoped to the user and the task, short-lived and least privilege.++The whole API is described at `$HARNESSROUTER_BASE_URL/v1/openapi.json`, generated from the routes, with a browsable copy at `/v1/docs`.+The default URL works when your backend and CE run on the same computer. From another machine or container, use a reachable URL for the CE instance. [Read the complete self-hosted API and networking guide →](docs/self-hosting-guide.md#using-the-api)<a id="one-interface-for-the-agent-lifecycle"></a>diff --git a/gateway/app.py b/gateway/app.pyindex 33dd8c36..012992f2 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -787,10 +787,27 @@ def _vault_tenant_ok(org: str | None) -> bool:return bool(org) and org != GLOBAL_TENANT and "--" not in org and bool(_VAULT_TENANT_RE.match(org))+def _org_tenant(org: str | None) -> str | None:+ """The vault tenant that holds an org's own secrets (its provider keys, connections, policies).++ Org ids are dotted (org.acme.example.com) and a vault tenant cannot be, so a customer org+ used to have NO tenant at all: every lookup fell straight through to the platform pool and+ "bring your own key" was unreachable. The tenant is the id's alphanumeric runs joined by+ single hyphens plus a short digest of the exact id: readable in the vault, and two ids that+ differ only in punctuation cannot share one. An id that is already a valid tenant (self-host+ style) keeps its name, so nothing stored under it moves."""+ if not org or org == GLOBAL_TENANT:+ return None+ if _vault_tenant_ok(org):+ return org+ slug = re.sub(r"[^a-z0-9]+", "-", org.lower()).strip("-")[:60].strip("-") or "org"+ return f"{slug}-{hashlib.sha1(org.encode()).hexdigest()[:8]}"++def _tenants_for(org: str | None) -> list[str]:- """Resolution order: the org's own keys first (bill to the org), then the shared pool.- Skip the org tenant if it isn't a valid vault tenant (e.g. dotted ids) -> straight to global."""- return ([org] if _vault_tenant_ok(org) else []) + [GLOBAL_TENANT]+ """Resolution order: the org's own keys first (bill to the org), then the shared pool."""+ t = _org_tenant(org)+ return ([t] if t else []) + [GLOBAL_TENANT]async def _get_connection(org: str | None, name: str) -> tuple[dict | None, str | None]:@@ -2952,24 +2969,27 @@ def _vault_key(auth) -> str:return auth[len("vault:"):] if isinstance(auth, str) and auth.startswith("vault:") else ""+_MCP_SECRET_PREFIX = "harness-mcp-"++async def _resolve_mcp_auth(org: str, auth: str) -> str:- """Resolve an MCP server auth value. 'vault:<key>' → the secret from the org/global vault- (token never sits in the graph). Anything else is treated as a literal bearer token."""+ """Resolve an MCP server auth value or an environment value. 'vault:<key>' is the secret the+ org stored through PUT /v1/mcp-secrets (the key that call returned, under harness-mcp-),+ read from the org's OWN vault tenant and nowhere else. Anything else is the literal.++ Two doors are shut here on purpose. The platform pool is never consulted: a reference is+ written by a customer and resolved into that customer's sandbox, and until 2026-09-22 the+ lookup fell through to the shared tenant, so a harness naming a platform connection document+ would have been handed the platform's provider key. And only the MCP-secrets namespace+ resolves: the org's tenant also holds its connection documents and policies, which a member+ who can edit a harness must not be able to read out through an agent."""if isinstance(auth, str) and auth.startswith("vault:"):key = auth[len("vault:"):]- if key.startswith(_HOSTED_SECRET_PREFIX):- # A record we hold for a server we host. It is not a bearer token for anybody, and- # this is the one place a stored secret becomes a literal on an outbound request — so- # refusing HERE is what makes "the connection string never leaves this process" true- # for callers that do not exist yet, including an entry that names this ref and points- # somewhere else on purpose.- print(f"[mcp] refusing to resolve {key} as a bearer token", flush=True)+ tenant = _org_tenant(org)+ if not tenant or not key.startswith(_MCP_SECRET_PREFIX) or key.startswith(_HOSTED_SECRET_PREFIX):+ print(f"[mcp] refusing to resolve {key[:40]!r} for {org}: not an MCP secret of this org", flush=True)return ""- for tenant in _tenants_for(org):- v = await _vault_get(tenant, key)- if v:- return v- return ""+ return await _vault_get(tenant, key) or ""return auth or ""@@ -2997,6 +3017,68 @@ def _mcp_name(s: str) -> str:_HDR_REF = re.compile(r"\$headers\.([A-Za-z0-9_-]+)")+_ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")+# Names the runner sets for the agent process itself (its credentials, its paths); a harness may not+# take them over. The runner also gives its own values precedence, so this is the message, not the wall.+_ENV_RESERVED_PREFIX = ("HR_", "HARNESS_", "OPENAI_", "ANTHROPIC_", "GEMINI_", "GOOGLE_", "AWS_", "AZURE_", "LD_", "DYLD_")+# The shell's own, the interpreters' import paths, the trust roots and the network path: a+# harness gets its variables, not the runtime's.+_ENV_RESERVED = {"PATH", "HOME", "USER", "SHELL", "TERM", "LANG", "PWD", "TMPDIR",+ "PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP", "NODE_OPTIONS", "NODE_EXTRA_CA_CERTS",+ "SSL_CERT_FILE", "SSL_CERT_DIR", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE",+ "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY"}+_ENV_MAX = 64+++def _env_clean(env: dict | None) -> dict[str, str]:+ """The environment map as stored: shell-safe names, none the runner owns, values as strings."""+ out: dict[str, str] = {}+ for k, v in (env or {}).items():+ name = str(k or "").strip()+ if not _ENV_NAME_RE.match(name):+ raise uhp_error(400, "invalid_env_name", f"'{name}' is not a valid environment variable name.", "env")+ if name.upper() in _ENV_RESERVED or name.upper().startswith(_ENV_RESERVED_PREFIX):+ raise uhp_error(400, "reserved_env_name", f"'{name}' is set by the runtime and cannot be overridden.", "env")+ if v is None:+ continue+ out[name] = str(v)+ if len(out) > _ENV_MAX:+ raise uhp_error(400, "too_many_env", f"At most {_ENV_MAX} environment variables per harness.", "env")+ return out+++def _parse_env(raw) -> dict[str, str]:+ try:+ d = json.loads(raw) if raw else {}+ return {str(k): str(v) for k, v in d.items()} if isinstance(d, dict) else {}+ except Exception: # noqa: BLE001+ return {}+++async def _harness_env(hv: dict | None, org: str, hdr_vals: dict[str, str]) -> tuple[dict[str, str], list[str]]:+ """The environment a turn's processes start with, resolved the way MCP auth is: a $headers+ reference takes the request's declared header, a vault reference the stored secret, anything+ else is the literal. Resolved here and handed to the runner as values; the model never sees a+ reference or a value in its prompt. Returns the map and the NAMES whose values came through a+ reference: the runner redacts those values from everything it hands back (events, result,+ error), so no record, stream or response carries them. A literal is not a secret: it is stored+ in the harness for anyone who can read the harness, and redacting "us-east-1" from a transcript+ only mangles the record. A reference that resolves to nothing is left out rather than set to+ an empty string, so a shell test for the variable says what happened."""+ out: dict[str, str] = {}+ secret: list[str] = []+ for name, ref in _parse_env((hv or {}).get("env")).items():+ val = _sub_headers(ref, hdr_vals) if "$headers." in ref else ref+ if isinstance(val, str) and val.startswith("vault:"):+ val = await _resolve_mcp_auth(org, val)+ if not val:+ continue+ out[name] = str(val)+ if val != ref:+ secret.append(name)+ return out, secret++def _sub_headers(value: str, hdr_vals: dict[str, str]) -> str:"""Substitute $headers.{Name} references with the per-request header values captured onPOST /v1/responses (names matched case-insensitively — HTTP headers arrive lowercased).@@ -6944,6 +7026,7 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s# instead of re-reading it twice more here. Beyond cutting reads, a same-request snapshot means# _harness_plugins and agent_doc can't observe a mid-turn config edit inconsistently.mcp_servers, skills, skills_suppressed, tools_disabled, plugin_pkgs = await _harness_plugins(harness_id, org, hdr_vals, hv=hv, sid=sid)+ turn_env, turn_secret = await _harness_env(hv, org, hdr_vals)if mcp_servers or skills or skills_suppressed or tools_disabled:rec["plugins"] = {"mcp": [m.get("name") for m in mcp_servers], "skills": [s.get("name") for s in skills],"skills_off": skills_suppressed, "tools_off": tools_disabled}@@ -7038,7 +7121,9 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s"image_auth": image_auth,# A harness that drives another one: the platform's own API and a credential# scoped to that harness, for this turn (see _calibration_env).- "env": _calibration_env(hv, org, sid, timeout_s),+ # The harness's own variables, then the platform's HR_ names for a harness that drives+ # another one; the platform's win.+ "env": {**turn_env, **(_calibration_env(hv, org, sid, timeout_s) or {})}, "env_secret": turn_secret,# A probe (docs/dual-loop.md, Appendix B): `metadata.systemone.script` names the# actions a scripted provider answers instead of the model. The additive# extension point of the protocol; nothing else of the metadata reaches the runner.@@ -9644,18 +9729,28 @@ class McpTestBody(BaseModel):auth: str | None = None # literal bearer OR vault:<ref> (left blank → no auth)+async def _mcp_secret_store(org: str, ref: str, token: str) -> dict:+ """Store a secret under a stable ref in the org's own vault tenant, so a harness config+ carries only 'vault:<key>' and the live token never lands in the graph. The org's tenant+ and nothing else: a dotted org id used to fall to the shared pool, where every org's+ reference could read every other org's secret."""+ tenant = _org_tenant(org)+ if not tenant:+ raise HTTPException(400, "no org to store the secret for")+ # vault key names allow only [a-z0-9-] (same charset as harness-conn-/harness-policy- keys)+ safe = re.sub(r"[^a-z0-9]+", "-", ref.lower()).strip("-") or "mcp"+ key = f"{_MCP_SECRET_PREFIX}{safe}"+ await _vault_put(tenant, key, token)+ return {"ref": f"vault:{key}", "tenant": tenant}++@app.put("/v1/orgs/{org}/mcp-secrets/{ref}")async def put_mcp_secret(org: str, ref: str, body: McpSecretBody, request: Request) -> dict:await _owned_org(request, org)"""Store an MCP server bearer token in the vault under a stable ref, so the harness configstores only 'vault:<ref>' and the live token never lands in the graph. Stored in the org'sown vault tenant when valid, else the global pool (dotted org ids aren't valid vault tenants)."""- tenant = org if _vault_tenant_ok(org) else GLOBAL_TENANT- # vault key names allow only [a-z0-9-] (same charset as harness-conn-/harness-policy- keys)- safe = re.sub(r"[^a-z0-9]+", "-", ref.lower()).strip("-") or "mcp"- key = f"harness-mcp-{safe}"- await _vault_put(tenant, key, body.token)- return {"ref": f"vault:{key}", "tenant": tenant}+ return await _mcp_secret_store(org, ref, body.token)@app.post("/v1/orgs/{org}/mcp-test")@@ -9675,11 +9770,7 @@ async def test_mcp(org: str, body: McpTestBody, request: Request) -> dict:@app.put("/v1/mcp-secrets/{ref}")async def put_mcp_secret_public(ref: str, body: McpSecretBody, request: Request) -> dict:org, _ = await _pub_org_member(request)- tenant = org if _vault_tenant_ok(org) else GLOBAL_TENANT- safe = re.sub(r"[^a-z0-9]+", "-", ref.lower()).strip("-") or "mcp"- key = f"harness-mcp-{safe}"- await _vault_put(tenant, key, body.token)- return {"ref": f"vault:{key}", "tenant": tenant}+ return await _mcp_secret_store(org, ref, body.token)@app.post("/v1/mcp-test")@@ -13785,6 +13876,8 @@ class HarnessBody(BaseModel):max_step: int | None = _either("max_step") # default agent step budget for this harness's turnstimeout_seconds: int | None = _either("timeout_seconds") # default per-turn wall-clock capadditional_headers: list | None = _either("additional_headers") # header NAMES callers may pass per request+ env: dict | None = None # variables every turn's shell and tools start with: name -> literal,+ # $headers.X-Name (a declared request header) or vault:ref# The one harness this harness may drive through the platform's own API, by id: a Calibrator# names the harness it calibrates. Every turn of a harness that names one is handed HR_API_URL# and HR_CALIBRATION_TOKEN, a credential scoped to that harness and expiring with the turn@@ -13818,6 +13911,7 @@ def _harness_out(v: dict) -> dict:"plugins": _plugins_of(v),"disabledTools": [t for t in _parse(v.get("disabled_tools")) if isinstance(t, str)],"additionalHeaders": [h for h in _parse(v.get("additional_headers")) if isinstance(h, str) and h.strip()],+ "env": _parse_env(v.get("env")),"maxStep": int(v.get("max_step")) if str(v.get("max_step") or "").isdigit() else None,"timeoutSeconds": int(v.get("timeout_seconds")) if str(v.get("timeout_seconds") or "").isdigit() else None,"calibrates": str(v.get("calibrates") or ""),@@ -13837,6 +13931,7 @@ def _harness_props(body: HarnessBody) -> dict:"disabled_tools": json.dumps(body.disabled_tools or []),"additional_headers": json.dumps([str(h).strip() for h in (body.additional_headers or [])if isinstance(h, str) and str(h).strip()]),+ "env": json.dumps(_env_clean(body.env)),"calibrates": str(body.calibrates or "").strip(),"max_step": str(body.max_step) if body.max_step else "","timeout_seconds": str(body.timeout_seconds) if body.timeout_seconds else ""}@@ -15443,6 +15538,49 @@ async def get_harness_public(hid: str, request: Request) -> dict:return _harness_out(await _mcp_migrate(org, hid, v))+# ── the API, described ────────────────────────────────────────────────────────────────────────+# The public surface as an OpenAPI document, generated from the routes themselves so it cannot+# drift from what is served. Only the routes a customer calls with a login or an API key: the+# org-addressed twins the console uses, the admin pages, the console's own features (kits, cloud+# upload, workspaces) and every route behind the internal key stay out. Served on the same host as the API, and once per process.+_OPENAPI_PUBLIC_PREFIXES = ("/v1/responses", "/v1/files", "/v1/sessions", "/v1/harnesses", "/v1/bases",+ "/v1/models", "/v1/mcp-secrets", "/v1/mcp-test", "/v1/containers", "/v1/traces",+ "/v1/uhp", "/v1/openapi.json")+_openapi_doc: dict | None = None+++def _openapi_public() -> dict:+ global _openapi_doc+ if _openapi_doc is None:+ from fastapi.openapi.utils import get_openapi+ from fastapi.routing import APIRoute+ routes = []+ for r in app.routes:+ if not isinstance(r, APIRoute) or not r.path.startswith(_OPENAPI_PUBLIC_PREFIXES):+ continue+ if any(getattr(d, "dependency", None) is _internal_only for d in (r.dependencies or [])):+ continue+ routes.append(r)+ doc = get_openapi(title="HarnessRouter API", version="1", routes=routes,+ description=("The HarnessRouter API: run a harness (an OpenAI Responses-compatible surface "+ "at /v1/responses), attach files, read sessions, turns and produced files, "+ "manage harnesses, keys and provider connections. Authenticate with an API "+ "key or a login token as a bearer."))+ _openapi_doc = doc+ return _openapi_doc++[email protected]("/v1/openapi.json", include_in_schema=False)+async def openapi_public() -> dict:+ return _openapi_public()++[email protected]("/v1/docs", include_in_schema=False)+async def openapi_docs():+ from fastapi.openapi.docs import get_swagger_ui_html+ return get_swagger_ui_html(openapi_url="/v1/openapi.json", title="HarnessRouter API")++@app.get("/v1/bases")async def list_bases(request: Request) -> dict:"""What each base harness is, and what it can actually do here.diff --git a/gateway/tests/test_harness_env.py b/gateway/tests/test_harness_env.pynew file mode 100644index 00000000..22a05cd4--- /dev/null+++ b/gateway/tests/test_harness_env.py@@ -0,0 +1,110 @@+"""A harness's environment: variables every turn's shell and tools start with.++Resolved on the gateway the way MCP auth already is (a `$headers.X` reference takes the request's+declared header, `vault:ref` the stored secret, anything else the literal), handed to the runner as+values, and scrubbed from everything the turn records. The public OpenAPI document is pinned here+too: it must describe the customer surface and nothing behind the internal key."""+from __future__ import annotations++import asyncio+import json+import sys+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+import app as gw # noqa: E402++SECRET = "sk-live-0123456789abcdef"+++def test_env_clean_keeps_shell_safe_names_and_refuses_the_runtimes_own():+ assert gw._env_clean({"API_KEY": "$headers.X-Api-Key", "n": 1, "gone": None}) == {"API_KEY": "$headers.X-Api-Key", "n": "1"}+ for bad in ("1ABC", "A-B", "", "A B"):+ with pytest.raises(gw.HTTPException) as e:+ gw._env_clean({bad: "x"})+ assert e.value.status_code == 400+ for reserved in ("HR_TOKEN", "OPENAI_API_KEY", "anthropic_api_key", "PATH", "home"):+ with pytest.raises(gw.HTTPException) as e:+ gw._env_clean({reserved: "x"})+ assert e.value.status_code == 400 and "reserved_env_name" in json.dumps(e.value.detail)+ with pytest.raises(gw.HTTPException):+ gw._env_clean({f"V{i}": "x" for i in range(gw._ENV_MAX + 1)})+++def test_harness_env_resolves_header_vault_and_literal_and_names_the_secrets(monkeypatch):+ async def _vault(org, auth):+ assert org == "org.a" and auth == "vault:harness-mcp-deploy-key"+ return "from-the-vault"+ monkeypatch.setattr(gw, "_resolve_mcp_auth", _vault)+ hv = {"env": json.dumps({"TOKEN": "$headers.X-App-Token", "DEPLOY": "vault:harness-mcp-deploy-key",+ "REGION": "us-east-1", "MISSING": "$headers.X-Absent"})}+ out, secret = asyncio.run(gw._harness_env(hv, "org.a", {"x-app-token": SECRET}))+ assert out == {"TOKEN": SECRET, "DEPLOY": "from-the-vault", "REGION": "us-east-1"} # the absent header is left unset+ assert secret == ["TOKEN", "DEPLOY"] # the literal is not a secret+++def test_a_vault_reference_reads_only_the_orgs_own_mcp_secrets(monkeypatch):+ """The platform pool is never consulted, and only the MCP-secrets namespace resolves: a+ customer's reference is resolved into that customer's sandbox."""+ asked = []++ async def _vault_get(tenant, key):+ asked.append((tenant, key))+ return f"<{tenant}>:{key}"+ monkeypatch.setattr(gw, "_vault_get", _vault_get)+ mine = gw._org_tenant("org.attacker.example")+ assert asyncio.run(gw._resolve_mcp_auth("org.attacker.example", "vault:harness-mcp-github")) == f"<{mine}>:harness-mcp-github"+ for ref in ("vault:harness-conn-OpenRouter", "vault:harness-integrations", "vault:harness-media-access",+ "vault:harness-policy-x", "vault:" + gw._HOSTED_SECRET_PREFIX + "x", "vault:anything"):+ assert asyncio.run(gw._resolve_mcp_auth("org.attacker.example", ref)) == "", ref+ assert all(t == mine for t, _ in asked) and gw.GLOBAL_TENANT not in {t for t, _ in asked}+ assert asyncio.run(gw._resolve_mcp_auth("", "vault:harness-mcp-github")) == "" # no org, nothing resolves+ assert asyncio.run(gw._resolve_mcp_auth("org.a", "literal-bearer")) == "literal-bearer"+++def test_an_mcp_secret_is_stored_in_the_orgs_own_tenant(monkeypatch):+ put = []++ async def _vault_put(tenant, key, value):+ put.append((tenant, key, value))+ monkeypatch.setattr(gw, "_vault_put", _vault_put)+ out = asyncio.run(gw._mcp_secret_store("org.songrenchu.example.com", "GitHub token", "ghp_x"))+ assert put == [(gw._org_tenant("org.songrenchu.example.com"), "harness-mcp-github-token", "ghp_x")]+ assert out["ref"] == "vault:harness-mcp-github-token" and out["tenant"] != gw.GLOBAL_TENANT+ with pytest.raises(gw.HTTPException):+ asyncio.run(gw._mcp_secret_store("", "x", "y"))+++def test_env_clean_refuses_the_loader_the_import_paths_the_trust_roots_and_the_proxies():+ for name in ("LD_PRELOAD", "DYLD_INSERT_LIBRARIES", "PYTHONPATH", "NODE_OPTIONS", "SSL_CERT_FILE", "HTTPS_PROXY", "no_proxy"):+ with pytest.raises(gw.HTTPException):+ gw._env_clean({name: "x"})+++def test_the_runner_is_told_which_values_are_secret():+ """The turn body names the secret variables; the runner redacts them where the gateway reads+ the turn, so the gateway has no scrub of its own (one mechanism, every sink)."""+ src = open(Path(gw.__file__)).read()+ assert '"env_secret": turn_secret,' in src+ assert "_scrub_secrets" not in src+++def test_harness_body_stores_env_and_reads_it_back():+ body = gw.HarnessBody(name="n", base="codex", env={"TOKEN": "$headers.X-App-Token"})+ props = gw._harness_props(body)+ assert json.loads(props["env"]) == {"TOKEN": "$headers.X-App-Token"}+ assert gw._harness_out(dict(props, id="chrn_" + "a" * 32))["env"] == {"TOKEN": "$headers.X-App-Token"}+++def test_openapi_describes_the_customer_surface_only():+ doc = gw._openapi_public()+ paths = set(doc["paths"])+ for p in ("/v1/responses", "/v1/files", "/v1/harnesses", "/v1/harnesses/{hid}", "/v1/sessions/{sid}/turns", "/v1/models"):+ assert p in paths, p+ assert not [p for p in paths if p.startswith(("/v1/admin", "/v1/orgs", "/v1/mcp/", "/v1/kits", "/v1/cloud-upload", "/v1/hr", "/internal", "/share"))]+ assert "env" in doc["components"]["schemas"]["HarnessBody"]["properties"]+ assert asyncio.run(gw.openapi_public()) is doc # built once per process+ html = asyncio.run(gw.openapi_docs())+ assert html.status_code == 200 and b"/v1/openapi.json" in html.bodydiff --git a/runner/server.py b/runner/server.pyindex 67bc2c87..750e1c23 100644--- a/runner/server.py+++ b/runner/server.py@@ -361,6 +361,51 @@ def _isolate_session(ws: str) -> None:_own_tree(ws, uid, previous)+_CALLER_ENV_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")+# Prefixes the runner sets for the agent's own credentials, and the dynamic loader's; names that+# would redirect an interpreter's imports, a process's trust roots or its network path.+_CALLER_ENV_RESERVED = ("HR_", "HARNESS_", "OPENAI_", "ANTHROPIC_", "GEMINI_", "GOOGLE_", "AWS_", "AZURE_", "LD_", "DYLD_")+_CALLER_ENV_RESERVED_NAMES = {"PATH", "HOME", "USER", "SHELL", "TERM", "LANG", "PWD", "TMPDIR",+ "PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP", "NODE_OPTIONS", "NODE_EXTRA_CA_CERTS",+ "SSL_CERT_FILE", "SSL_CERT_DIR", "REQUESTS_CA_BUNDLE", "CURL_CA_BUNDLE",+ "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY"}+++def _caller_env(env: dict | None) -> dict:+ """A harness's environment variables as the gateway resolved them: shell-safe names only, and+ none under a prefix the runner uses for the agent's own credentials and paths."""+ out = {}+ for k, v in (env or {}).items():+ name = str(k or "")+ if not _CALLER_ENV_NAME.match(name) or name.upper().startswith(_CALLER_ENV_RESERVED) \+ or name.upper() in _CALLER_ENV_RESERVED_NAMES:+ continue+ if v is None:+ continue+ out[name] = str(v)+ return out+++_SCRUB_MIN = 8 # shorter values are not scrubbed: replacing "yes" everywhere would mangle the record+++def _turn_secrets(env: dict, names: list | None) -> list[str]:+ """The values of a turn's environment that came through a reference (the gateway names them):+ what the agent may read but the record may not carry. Longest first, so a value that contains+ another is replaced whole."""+ vals = {str(env[n]) for n in (names or []) if isinstance(n, str) and env.get(n) and len(str(env[n])) >= _SCRUB_MIN}+ return sorted(vals, key=len, reverse=True)+++def _scrub_secrets(text: str, secrets: list[str] | None) -> str:+ """Every occurrence of a turn's secret values replaced in a serialized record. Applied where+ the gateway reads the turn, so no event, result or error leaves the sandbox with one."""+ for sec in secrets or []:+ if sec and sec in text:+ text = text.replace(sec, "[redacted]")+ return text++def _child_env() -> dict:"""The environment an agent process starts from: the runner's, minus anything secret-shaped.On the self-hosted box the runner's environment is the container's, and that carried the@@ -7201,8 +7246,11 @@ class TurnReq(BaseModel):skills_suppressed: list[str] | None = None # built-in skill names to NOT mount (harness disabled them)tools_disabled: list[str] | None = None # built-in tool names to disable (claude: --disallowedTools)image_auth: dict | None = None # {base_url, api_key, model} for image generation via the broker- env: dict | None = None # names for the turn process, HR_-prefixed only (a harness that- # drives another one gets HR_API_URL + HR_CALIBRATION_TOKEN)+ env: dict | None = None # variables for the turn process: the harness's own (resolved by the+ # gateway, see _caller_env) and the platform's HR_ names (a harness+ # that drives another one gets HR_API_URL + HR_CALIBRATION_TOKEN)+ env_secret: list[str] | None = None # the names in env whose values came through a reference: never+ # in anything the gateway reads back (see _turn_secrets)metadata: dict | None = None # systemone: {"systemone": {"script": [...]}} selects a scripted provider (a probe)idempotency_key: str = "" # dedup a retried /turn: same key -> same turn, no re-execpartial_messages: bool = False # claude: stream token-level deltas (--include-partial-messages)@@ -7282,7 +7330,9 @@ def turn(req: TurnReq, identifier: str = "") -> dict:agent_doc = ((agent_doc + "\n\n") if agent_doc.strip() else "") + \f"## Disabled tools\n\nDo NOT use these tools — they are disabled for this harness: {_off}."_write_agent_doc(cwd, backend, agent_doc, installed_skills)- env = _child_env()+ # The harness's own variables under the runner's, so nothing a caller names shadows the+ # runner's credentials or paths; the platform's HR_ names come after and win (below).+ env = {**_caller_env(req.env), **_child_env()}# Image generation. Deliberately NOT the OPENAI_* names: on a codex harness those already# point at the CHAT connection, which is often a different provider, and one env pair can# only carry one credential. The imagegen skill's wrapper reads these and passes them to the@@ -7453,7 +7503,9 @@ def turn(req: TurnReq, identifier: str = "") -> dict:"backend": r.get("backend", ""), "model": r.get("model", ""),"host": socket.gethostname(), "deduplicated": True, "max_seconds": MAX_TURN_SECONDS}_turns[turn_id] = {"status": "running", "events": [], "result": "", "done": False,- "backend": backend, "model": model, "started": time.time()}+ "backend": backend, "model": model, "started": time.time(),+ # the values the record may not carry (see get_turn)+ "secrets": _turn_secrets(_caller_env(req.env), req.env_secret)}if codex_note: # the follow-up's Codex history was not here: the transcript says so first_turns[turn_id]["events"].append({"type": "assistant", "_ts": time.time(),"message": {"content": [{"type": "text", "text": codex_note}]}})@@ -7544,9 +7596,11 @@ def get_turn(turn_id: str, since: int = 0) -> dict:with _turns_lock:evs = rec["events"][since:]n = len(rec["events"])- return {"turn_id": turn_id, "status": rec["status"], "done": rec["done"],- "result": rec.get("result", ""), "exit_code": rec.get("exit_code"),- "error": rec.get("error"), "backend": rec["backend"], "model": rec["model"],- "session_id": rec.get("session_id"), "reason": rec.get("reason") or "",- "handoff": rec.get("handoff"),- "events": evs, "n_total": n, "elapsed": round(time.time() - rec["started"], 1)}+ out = {"turn_id": turn_id, "status": rec["status"], "done": rec["done"],+ "result": rec.get("result", ""), "exit_code": rec.get("exit_code"),+ "error": rec.get("error"), "backend": rec["backend"], "model": rec["model"],+ "session_id": rec.get("session_id"), "reason": rec.get("reason") or "",+ "handoff": rec.get("handoff"),+ "events": evs, "n_total": n, "elapsed": round(time.time() - rec["started"], 1)}+ sec = rec.get("secrets")+ return json.loads(_scrub_secrets(json.dumps(out, default=str), sec)) if sec else outdiff --git a/runner/tests/test_caller_env.py b/runner/tests/test_caller_env.pynew file mode 100644index 00000000..c9e9238d--- /dev/null+++ b/runner/tests/test_caller_env.py@@ -0,0 +1,45 @@+"""A harness's environment reaches the agent's processes under the runner's own: a caller names+variables, never one the runner sets, and never with a name a shell would refuse."""+from __future__ import annotations+import os+import pathlib+import sys++sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))+import server # noqa: E402+++def test_caller_env_is_filtered_and_the_runner_wins(monkeypatch):+ got = server._caller_env({"API_KEY": "sk-x", "R2_URL": "https://r2/x", "HR_TURN_ID": "no", "OPENAI_API_KEY": "no",+ "PATH": "/evil", "bad-name": "no", "EMPTY": None})+ assert got == {"API_KEY": "sk-x", "R2_URL": "https://r2/x"} # PATH is the runner's, refused by name+ monkeypatch.setenv("PATH", "/usr/bin")+ env = {**server._caller_env({"PATH": "/evil", "API_KEY": "sk-x"}), **server._child_env()}+ assert env["PATH"] == os.environ["PATH"] and env["API_KEY"] == "sk-x"+++def test_turn_request_accepts_the_env_map():+ req = server.TurnReq(prompt="hi", env={"A": "1"})+ assert req.env == {"A": "1"}+++def test_the_runtimes_own_names_are_refused():+ out = server._caller_env({"LD_PRELOAD": "/x.so", "PYTHONPATH": "/p", "HTTPS_PROXY": "http://x", "NODE_OPTIONS": "-r x",+ "SSL_CERT_FILE": "/c", "ld_library_path": "/l", "DEPLOY_TOKEN": "abc"})+ assert out == {"DEPLOY_TOKEN": "abc"}+++def test_a_turn_is_read_back_without_its_secret_values(monkeypatch):+ env = {"TOKEN": "tok_0123456789abcdef", "REGION": "us-east-1", "SHORT": "abc"}+ secrets = server._turn_secrets(env, ["TOKEN", "REGION", "SHORT", "MISSING"])+ assert secrets == ["tok_0123456789abcdef", "us-east-1"] # a short value is left alone+ monkeypatch.setitem(server._turns, "turn_x", {+ "status": "completed", "done": True, "backend": "claude", "model": "m", "started": 0.0,+ "result": "the token is tok_0123456789abcdef in us-east-1", "error": "bad tok_0123456789abcdef",+ "events": [{"type": "assistant", "message": {"content": [{"type": "text", "text": "echo tok_0123456789abcdef"}]}}],+ "secrets": secrets})+ out = server.get_turn("turn_x")+ dumped = __import__("json").dumps(out)+ assert "tok_0123456789abcdef" not in dumped and "us-east-1" not in dumped+ assert out["result"] == "the token is [redacted] in [redacted]" and out["error"] == "bad [redacted]"+ assert out["events"][0]["message"]["content"][0]["text"] == "echo [redacted]"diff --git a/ui/src/app/revamp.css b/ui/src/app/revamp.cssindex 10baa2d3..5133d127 100644--- a/ui/src/app/revamp.css+++ b/ui/src/app/revamp.css@@ -752,6 +752,7 @@.header-row { display: grid; grid-template-columns: minmax(0,.8fr) minmax(0,1.2fr) auto; gap: 8px; align-items: end; }.header-row .field input { min-height: 36px; }.header-row .icon-button { margin-bottom: 1px; }+ .header-row + .header-row { margin-top: 10px; } /* a second mapping or variable stands apart from the first */.settings-form-footer { position: sticky; bottom: 0; z-index: 2; display: flex; justify-content: flex-end; gap: 12px; padding: 14px 0; border-top: 1px solid var(--line); background: rgba(251,251,252,.94); backdrop-filter: blur(8px); }.save-state { color: var(--muted); font-size: 11.5px; }.modal-backdrop {diff --git a/ui/src/components/HarnessSettings.tsx b/ui/src/components/HarnessSettings.tsxindex ca751f65..d1c3992d 100644--- a/ui/src/components/HarnessSettings.tsx+++ b/ui/src/components/HarnessSettings.tsx@@ -41,6 +41,14 @@ export function HarnessSettings({ id, embedded = false, onNavigate }: {const [loaded, setLoaded] = useState(false);const [busy, setBusy] = useState(false);const [err, setErr] = useState<string | null>(null);+ // The environment as rows, so a half-typed name does not vanish from a map keyed by name.+ const [envRows, setEnvRows] = useState<{ name: string; value: string }[]>([]);+ useEffect(() => { setEnvRows(Object.entries(draft?.env || {}).map(([name, value]) => ({ name, value }))); }, [draft?.id]); // eslint-disable-line react-hooks/exhaustive-deps+ const setEnvRow = (idx: number, patch: Partial<{ name: string; value: string }>) => setEnvRows((rows) => {+ const next = rows.map((r, k) => (k === idx ? { ...r, ...patch } : r));+ upd({ env: Object.fromEntries(next.filter((r) => r.name).map((r) => [r.name, r.value])) });+ return next;+ });const [editSkillIdx, setEditSkillIdx] = useState<number | null>(null);const [mcpModal, setMcpModal] = useState<{ idx: number | null } | null>(null);const [confirmDelete, setConfirmDelete] = useState(false);@@ -511,6 +519,27 @@ export function HarnessSettings({ id, embedded = false, onNavigate }: {</div></section>+ <section className="form-section">+ <div><h3>Environment</h3><p>Variables every Task's shell and tools start with. Put a secret behind a request header or a stored secret, never as a literal; the agent never sees the value in its prompt, and anything it prints is redacted from the record.</p></div>+ <div className="field-stack">+ <div className="section-actions"><strong>{Object.keys(draft?.env || {}).length} variables</strong>+ {!readOnly && <button className="button small" type="button" onClick={() => setEnvRows((r) => [...r, { name: '', value: '' }])}><iconify-icon icon="tabler:plus"></iconify-icon>Add variable</button>}</div>+ <div>+ {envRows.map((row, idx) => (+ <div key={idx} className="header-row">+ <div className="field"><label>Name</label>+ <input value={row.name} placeholder="API_KEY" disabled={readOnly} onChange={(e) => setEnvRow(idx, { name: e.target.value.toUpperCase().replace(/[^A-Z0-9_]/g, '_') })} /></div>+ <div className="field"><label>Value or reference</label>+ <input value={row.value} placeholder="$headers.X-Api-Key or vault:my-secret" disabled={readOnly} onChange={(e) => setEnvRow(idx, { value: e.target.value })} /></div>+ {!readOnly && <button className="icon-button" type="button" aria-label="Remove variable" onClick={() => setEnvRows((r) => r.filter((_, k) => k !== idx))}><iconify-icon icon="tabler:trash"></iconify-icon></button>}+ </div>+ ))}+ {!envRows.length && <span className="field-help">No variables set.</span>}+ </div>+ <span className="field-help">A reference like $headers.X-Api-Key takes the header a Task request sends (declare it above); vault:name takes a secret stored with the service. A shell in the Task reads the variable by name.</span>+ </div>+ </section>+{err && <div className="notice"><iconify-icon icon="tabler:alert-triangle"></iconify-icon><div><strong>Save failed</strong>{err}</div></div>}</form>diff --git a/ui/src/lib/harness.ts b/ui/src/lib/harness.tsindex e1eacd18..48159404 100644--- a/ui/src/lib/harness.ts+++ b/ui/src/lib/harness.ts@@ -49,6 +49,9 @@ export interface CustomHarness {maxStep?: number | null; // default agent step budget per turn (blank = 40)timeoutSeconds?: number | null; // default per-turn wall-clock cap (blank = server default)additionalHeaders?: string[]; // declared header NAMES callers pass per request (app-level auth)+ // Variables every Task's shell and tools start with. A value is `$headers.X-Name` (a declared+ // request header), `vault:ref` (a stored secret) or a literal. Resolved by the service per turn.+ env?: Record<string, string>;// Installed plugins (UHP Plugins chapter). The server derives manifest, mcpServers, skills and// skipped from the package on every save; a saved plugin round-trips as {name, enabled, blob}// plus those derived fields, and a freshly picked one carries its `files` until it is saved.@@ -402,6 +405,7 @@ function harnessBody(input: Partial<CustomHarness> & { name: string; base: strinmax_step: input.maxStep || null,timeout_seconds: input.timeoutSeconds || null,additional_headers: input.additionalHeaders || [],+ env: input.env || {},};}