The first exam for code agents in the physical world: frozen robot tasks from many benchmark suites, each answered with a program and verified in a separate sandbox. Runs on Harbor.
Python ai-agentsbenchmarkcoding-agentsembodied-aievaluationharborllm-agentsrobot-learningroboticssimulation
Merge pull request #28 from JamesKrW/feat/usage-gateway
Kangrui Wangfac61739bbb0
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERSindex 530ffdf2c4..dcee5d6964 100644--- a/.github/CODEOWNERS+++ b/.github/CODEOWNERS@@ -16,3 +16,5 @@/scripts/task_conventions.py @JamesKrW @williamzhangNU @QinengWang-Aiden @changhechen @CHIGUI0/scripts/task_names.py @JamesKrW @williamzhangNU @QinengWang-Aiden @changhechen @CHIGUI0/tasks/dataset.toml @JamesKrW @williamzhangNU @QinengWang-Aiden @changhechen @CHIGUI0+/scripts/usage_gateway/ @JamesKrW @williamzhangNU @QinengWang-Aiden @changhechen @CHIGUI0+/scripts/run_agent_batch.sh @JamesKrW @williamzhangNU @QinengWang-Aiden @changhechen @CHIGUI0diff --git a/AGENTS.md b/AGENTS.mdindex 705a719c01..5386eb1aef 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -23,7 +23,9 @@ Read `README.md`, `docs/PROTOCOL.md` (the contract, v1.0.1) and `CONTRIBUTING.md- Local docker sandbox has no `[environment].gpus`. robosuite tasks don't need a GPU; RoboTwin and MuJoCo tasks pass one throughwith `environment/docker-compose.yaml` (service `main`, nvidia device reservation; `sim` in standard mode) — copy itfrom `tasks/robotwin_2_0_stack_blocks_two-privileged/`.-- Run agents with Harbor's native agents only (`-a codex`, `-a claude-code`); no custom gateways or adapters.+- Run agents with Harbor's native agents only (`-a codex`, `-a claude-code`); no adapters, and no gateway that holds+ credentials or changes requests. The optional usage gateway (`scripts/usage_gateway/`, `GATEWAY=1` in+ `run_agent_batch.sh`, off by default) only forwards and records token usage (PROTOCOL D11, docs/RUNNING.md).Unattended batches: `scripts/run_agent_batch.sh` (lanes with per-job claims; configured by environment variables,docs/RUNNING.md); its runner-side tools (`log_mirror.py`, `mem_guard.py`, `scan_secrets.py`, `account_failure_check.py`)are not task code.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 28ce7cb8e1..66080b2330 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -36,7 +36,8 @@ the expected size of the pull request.3. Base images: `images/<sim>/Dockerfile`, versioned in `images/<sim>/VERSION`, built and pushed with`scripts/build_images.sh` / `scripts/push_images.sh`. Images that cannot be published carry `images/<sim>/BUILD_ONLY`and build instructions.-4. Run agents with Harbor's native agents only (`-a codex`, `-a claude-code`, …). No custom gateways or adapters.+4. Run agents with Harbor's native agents only (`-a codex`, `-a claude-code`, …). No adapters, and no gateway that+ holds credentials or changes requests; the optional usage gateway that only records token usage is allowed (PROTOCOL D11).## Before opening the pull request```bashdiff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.mdindex 6f4001472b..cd92615ca0 100644--- a/docs/PROTOCOL.md+++ b/docs/PROTOCOL.md@@ -52,7 +52,7 @@ Unchanged: the task name prefix `robot-coding-bench/`, the client and tool file| D8 | Agent time budget | 3600 s by default; longer budgets are justified, uniform within a benchmark, and results are grouped by budget. || D9 | Shared code | Shared sources are copied into tasks by the generator; nothing at run time imports repository code outside the task directory. || D10 | Token budget | Per trial: **100M input tokens, 10M output tokens** by default; exceeding either fails the trial. |-| D11 | Harness | Official results use Harbor's native agents only; no custom LLM gateways or agent adapters. |+| D11 | Harness | Official results use Harbor's native agents only; no agent adapters, and no gateway that holds credentials or changes requests. A transparent usage gateway that forwards requests unchanged and only records token usage (`scripts/usage_gateway/`) is allowed. || D12 | Mode naming | `mode ∈ {privileged, standard}`; the `tier` field is removed; every task directory ends in `-privileged` or `-standard`. |## 1. Checklist (every task)@@ -71,7 +71,7 @@ Unchanged: the task name prefix `robot-coding-bench/`, the client and tool file12. A published task's `environment/` and `tests/` inputs never change; a change is a new task. [current]13. The directory name ends in `-privileged` or `-standard`, matching `mode` (§2.2); no `results/` directory (D3). [CI]14. `README.md` in the standard layout (§2.1). [CI] (sections and key rows; `scripts/task_conventions.py --check` for the rest)-15. Runs with Harbor's native agents; no custom runner, gateway or adapter. [new]+15. Runs with Harbor's native agents; no custom runner or adapter, and no gateway beyond the recording-only usage gateway (D11). [new]16. Standard-mode tasks also satisfy every MUST in §4.## 2. Task contract@@ -341,7 +341,8 @@ affecting the verdict.Harbor 0.23 has no token cap, so the budget is applied after the run to the counts Harbor records for each trial(`result.json`); the results pipeline marks trials over budget as failed and records `over_token_budget = 1` in the-results metadata.+results metadata. That check is not implemented yet (§7 Open 3). The optional usage gateway (`scripts/usage_gateway/`,+D11) records each trial's tokens per request while it runs; it does not enforce the budget.## 6. Versioning and extensions| Item | Level | Basis |diff --git a/docs/REVIEWING.md b/docs/REVIEWING.mdindex 71dc85e42a..7f5fd9966d 100644--- a/docs/REVIEWING.md+++ b/docs/REVIEWING.md@@ -26,7 +26,8 @@ Guide for maintainers. The contract is [PROTOCOL.md](PROTOCOL.md); contributors- Is the predicate checked at the end of the replay, and can it be true without doing the task?- Standard mode: four endpoints only, RCB1 responses, no reset (unless the optional capability is declared and itsresults are reported separately), crash recovery, `success = replay_success ∧ deterministic`.-- Does the task run with Harbor's native agents, without custom adapters, runners or gateways?+- Does the task run with Harbor's native agents, without custom adapters or runners, and without any gateway other than+ the recording-only usage gateway (PROTOCOL D11)?- Are images pinned, published (or marked `BUILD_ONLY`), and shared with the other tasks of the same simulator?- Names end in `-privileged` / `-standard`; README in the standard layout; no `results/` in task directories.diff --git a/docs/RUNNING.md b/docs/RUNNING.mdindex dc8a6c3d72..0e1d198d95 100644--- a/docs/RUNNING.md+++ b/docs/RUNNING.md@@ -75,3 +75,26 @@ docker push $REG/eai-<sim>:$(cat images/<sim>/VERSION) # public images only```An image with `images/<sim>/BUILD_ONLY` (Isaac Sim inside: RoboLab, BEHAVIOR-1K) is never pushed: `push_images.sh` skipsit and prints why, and every host builds it locally (the marker file says how, and what licences and data it needs).++## Usage gateway (token usage per request, optional)+Off by default: the agent calls its API directly, as Harbor runs it. With `GATEWAY=1`, `scripts/run_agent_batch.sh` starts `scripts/usage_gateway/gateway.py` on the docker bridge (`GATEWAY_BIND`, 172.17.0.1)+and points the agent's base URL at it (`--ae ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL`; a copy of `AGENT_CONFIG` with its+provider `base_url`s rewritten and `supports_websockets = false`). The agent is still Harbor's own `codex` /+`claude-code` with its own credentials: the gateway forwards every request unchanged to the same API, never stores a key,+and refuses any host that is not a model API (`scripts/set_agent_egress.py` HOSTS), so it is no way around an egress+allowlist. Under an allowlist the runner adds `--allow-agent-host 172.17.0.1`.++Per trial, next to Harbor's `agent/` and `verifier/` (outside the agent's mounts):+```+<trial>/gateway/usage.jsonl one line per request: time, duration, host, path, status, model, input / cached / output tokens+<trial>/gateway/totals.json running totals, rewritten after every request+<trial>/gateway/raw/ GATEWAY_RAW=1 only: every request and response body, gzipped JSON (headers without credentials)+```+Input counts what the model read (Anthropic: input + cache read + cache creation; OpenAI: `input_tokens`, cached+included); output includes reasoning: the same convention as Harbor's `n_input_tokens` / `n_output_tokens`, which the batch+summary shows side by side. They agree exactly when the agent ends by itself; when it is stopped at its time limit, the+gateway is higher by the requests the provider completed (and billed) after Harbor's cut-off or that the agent was killed+before logging (measured 2026-10-01 on 9 benchmarks: the difference is exactly those requests). Switches: `GATEWAY=1` (record usage), `GATEWAY_RAW=1` (raw bodies; private, they hold the+whole conversation). Known limits: no WebSocket (Codex's built-in provider falls back to HTTPS after a few refused+attempts); Codex request bodies are zstd-compressed and are stored as base64 unless `zstandard` is installed; OpenAI+reasoning arrives encrypted. Requests no trial can be matched to go to `<jobs>/.gateway/unattributed.jsonl`.diff --git a/scripts/run_agent_batch.sh b/scripts/run_agent_batch.shindex c5dcd4d5e3..a74bf7cc16 100755--- a/scripts/run_agent_batch.sh+++ b/scripts/run_agent_batch.sh@@ -2,7 +2,8 @@# Run one Harbor-native agent over tasks in both modes (<base>-privileged and <base>-standard), unattended; meant to be# started in the background (inside `sg docker -c` if docker needs the group):# scripts/run_agent_batch.sh <batch-name> <base> [<base> ...] # <base> = a task name without its -privileged / -standard-# Official runs use Harbor's native agents only (PROTOCOL D11): no gateway, no adapter. Env (defaults):+# Official runs use Harbor's native agents only (PROTOCOL D11): no adapter; the transparent usage gateway below only+# records and is off by default. Env (defaults):# AGENT codex | claude-code (codex) MODEL the -m model (openai/gpt-6-luna)# EFFORT reasoning effort, --ak reasoning_effort=<EFFORT> (xhigh); `default` passes none# AK more agent options, e.g. "--ak web_search=disabled --ak reasoning_summary=detailed"@@ -30,6 +31,13 @@# for the results site there, <RESULTS>/<batch>/<task>/<RUN_ID>/ (PROTOCOL D3: no results in the repository);# default <repo>/../rcb_results; "" = skip# LOG_MIRROR / MEM_GUARD 1 (default) = start the agent-record mirror / the memory guard below if none runs; 0 = not+# GATEWAY 0 (default) = the agent calls its API directly, as Harbor runs it; 1 = route the agent's model API+# calls through scripts/usage_gateway/gateway.py, which forwards+# them unchanged (the agent keeps its own credentials) and records each trial's tokens per request in+# <trial>/gateway/ (usage.jsonl, totals.json)+# GATEWAY_RAW 0 (default); 1 = the gateway also keeps every request and response body (<trial>/gateway/raw/;+# private: it holds the whole conversation)+# GATEWAY_BIND the docker bridge address the trial containers reach the host by (172.17.0.1)# Runner-side tools (not task code): while trials run, the container rcb-log-mirror copies every trial's agent/ directory# append-only into ${JOBS}_mirror/ (scripts/log_mirror.py; root-owned: neither the agent nor the host user can delete it),# and scripts/mem_guard.py keeps 2 GiB of host memory available. After each job: a key scan with redaction@@ -44,6 +52,7 @@ AGENT_CONFIG="${AGENT_CONFIG:-}"; ENV_FILE="${ENV_FILE:-}"MODES="${MODES:-privileged standard}"; SEQ="${SEQ:-1}"; N_P="${N_P:-2}"; N_S="${N_S:-2}"; K="${K:-1}"; WAIT_FOR="${WAIT_FOR:-}"JOBS="${JOBS:-$R/jobs/agents}"; RESULTS="${RESULTS-$(dirname "$R")/rcb_results}"; LABEL="${LABEL:-$AGENT + $MODEL ($EFFORT)}"LOG_MIRROR="${LOG_MIRROR:-1}"; MEM_GUARD="${MEM_GUARD:-1}"+GATEWAY="${GATEWAY:-0}"; GATEWAY_RAW="${GATEWAY_RAW:-0}"; GATEWAY_BIND="${GATEWAY_BIND:-172.17.0.1}"case "$AGENT" in codex|claude-code) ;; *) echo "AGENT must be a Harbor native agent: codex or claude-code (PROTOCOL D11)" >&2; exit 2 ;; esac# Run id (D4): harness = the agent name with - -> _; model = MODEL's last path segment, lower case, gpt-<n> joined# (gpt-6-luna -> gpt6_luna), a leading claude- dropped (claude-fable-5-1 -> fable_5_1), every other@@ -86,6 +95,45 @@ if [ "$MEM_GUARD" = 1 ] && ! grep -qs mem_guard.py "/proc/${pid:-0}/cmdline"; thlog "started mem_guard (2 GiB red line; log jobs/journal/mem_guard.log)"fi+# transparent usage gateway (one per runner, stopped with it): the agent's base URL points at it, it forwards unchanged+if [ "$GATEWAY" = 1 ]; then+ mkdir -p "$JOBS/.gateway"; ready="$JOBS/.gateway/port.$$"; rm -f "$ready"+ gw_args=(--jobs "$JOBS" --bind "$GATEWAY_BIND" --ready-file "$ready"); [ "$GATEWAY_RAW" = 1 ] && gw_args+=(--raw)+ setsid python3 "$R/scripts/usage_gateway/gateway.py" "${gw_args[@]}" >>"$JOBS/.gateway/gateway.$$.err" 2>&1 </dev/null &+ gw_pid=$!; trap 'kill "$gw_pid" 2>/dev/null' EXIT+ for _ in $(seq 50); do [ -s "$ready" ] && break; sleep 0.2; done+ [ -s "$ready" ] || { log "usage gateway did not start (see $JOBS/.gateway/gateway.$$.err); unset GATEWAY to run without it"; exit 2; }+ GW="http://$GATEWAY_BIND:$(cat "$ready")"+ # the upstream each base URL would have used: this environment, else the env file, else the API's default+ upstream() { # <VAR> <default>+ local v="${!1:-}"+ [ -z "$v" ] && [ -n "$ENV_FILE" ] && v=$(sed -n "s/^[[:space:]]*\(export[[:space:]]\+\)\?$1=//p" "$ENV_FILE" | tail -1 | tr -d "\"'")+ printf '%s' "${v:-$2}"+ }+ via_gw() { sed -E "s#^https://([^/]+)#$GW/u/\1#" <<< "$1"; } # https://host/path -> $GW/u/host/path+ if [ "$AGENT" = claude-code ]; then+ AGENT_ARGS+=(--ae "ANTHROPIC_BASE_URL=$(via_gw "$(upstream ANTHROPIC_BASE_URL https://api.anthropic.com)")")+ else+ case "${CODEX_FORCE_AUTH_JSON:-}" in+ 1|true|TRUE|yes) AGENT_ARGS+=(--ae "OPENAI_BASE_URL=$(via_gw https://chatgpt.com/backend-api/codex)") ;;+ *) AGENT_ARGS+=(--ae "OPENAI_BASE_URL=$(via_gw "$(upstream OPENAI_BASE_URL https://api.openai.com/v1)")") ;;+ esac+ fi+ # a native config with its own provider URLs (Codex config.toml, Claude Code settings): a copy that points at the gateway+ if [ -n "$AGENT_CONFIG" ]; then+ cfg="$JOBS/.gateway/$(basename "$AGENT_CONFIG").$$"+ sed -E -e "s#^([[:space:]]*base_url[[:space:]]*=[[:space:]]*\")https://([^/\"]+)#\1$GW/u/\2#" \+ -e "s#(\"(ANTHROPIC|OPENAI)_BASE_URL\"[[:space:]]*:[[:space:]]*\")https://([^/\"]+)#\1$GW/u/\3#" "$AGENT_CONFIG" > "$cfg"+ # Codex reaches a provider by WebSocket first; the gateway speaks HTTPS only+ grep -q '^[[:space:]]*base_url[[:space:]]*=' "$cfg" && ! grep -q supports_websockets "$cfg" \+ && sed -i -E "s#^([[:space:]]*)(base_url[[:space:]]*=.*)#\1\2\n\1supports_websockets = false#" "$cfg"+ for i in "${!AGENT_ARGS[@]}"; do [ "${AGENT_ARGS[$i]}" = "config=$AGENT_CONFIG" ] && AGENT_ARGS[$i]="config=$cfg"; done+ fi+ # an egress allowlist must let the agent reach the gateway (ignored where egress is public)+ AGENT_ARGS+=(--allow-agent-host "$GATEWAY_BIND")+ log "usage gateway $GW (pid $gw_pid, raw bodies: $GATEWAY_RAW); per-trial records in <trial>/gateway/"+fi+wait_for() { # <mode>: block until every WAIT_FOR file of this mode existslocal wfor w in $WAIT_FOR; do@@ -106,8 +154,8 @@ summary() { # one table over every job of this batch, rewritten after each jobpython3 - "$JOBS" "$batch" > "$JOBS/$batch.summary.md.$$" <<'PY'import json, pathlib, sys, datetime as dtjobs, batch = pathlib.Path(sys.argv[1]), sys.argv[2]-print(f"# {batch}\n\n| task | mode | success | reward fields | actions | agent wall s | input tok | cached | output tok | cost $ | exception |")-print("|---|---|---|---|---|---|---|---|---|---|---|")+print(f"# {batch}\n\n| task | mode | success | reward fields | actions | agent wall s | input tok | cached | output tok | gateway in / out | cost $ | exception |")+print("|---|---|---|---|---|---|---|---|---|---|---|---|")f = lambda s: dt.datetime.fromisoformat(s.replace("Z", "+00:00"))rows = []for trial in jobs.glob(f"{batch}-*/*__*"):@@ -117,6 +165,8 @@ for trial in jobs.glob(f"{batch}-*/*__*"):rw = json.loads((trial / "verifier/reward.json").read_text()) if (trial / "verifier/reward.json").exists() else {}ar = r.get("agent_result") or {}; ex = (r.get("exception_info") or {}).get("exception_type") or ""ae = r.get("agent_execution") or {}+ gw = json.loads((trial / "gateway/totals.json").read_text()) if (trial / "gateway/totals.json").exists() else {}+ gw_cell = f"{gw['input']} / {gw['output']}" if gw else "-"try:wall = round((f(ae["finished_at"]) - f(ae["started_at"])).total_seconds())except Exception:@@ -127,7 +177,7 @@ for trial in jobs.glob(f"{batch}-*/*__*"):"infra_error", "resumes") if k in rw}rows.append((r.get("started_at") or "~", f"| {task} | {mode} | {rw.get('success', '-')} | {json.dumps(keys)} | "f"{rw.get('n_actions', '-')} | {wall} | {ar.get('n_input_tokens', '-')} | {ar.get('n_cache_tokens', '-')} | "- f"{ar.get('n_output_tokens', '-')} | {round(ar['cost_usd'], 4) if ar.get('cost_usd') is not None else '-'} | {ex} |"))+ f"{ar.get('n_output_tokens', '-')} | {gw_cell} | {round(ar['cost_usd'], 4) if ar.get('cost_usd') is not None else '-'} | {ex} |"))for _, row in sorted(rows):print(row)PYdiff --git a/scripts/usage_gateway/gateway.py b/scripts/usage_gateway/gateway.pynew file mode 100755index 0000000000..00a18c48a8--- /dev/null+++ b/scripts/usage_gateway/gateway.py@@ -0,0 +1,344 @@+#!/usr/bin/env python3+"""Transparent usage gateway: forwards an agent's model-API requests unchanged and records, per trial, the tokens each+request used, as it happens. Runner-side tooling (not task code, not an agent adapter): the agent is Harbor's own+`codex` / `claude-code`, pointed here by its base URL; it keeps its own credentials, which the gateway passes through+and never logs or stores.++ scripts/usage_gateway/gateway.py --jobs <harbor -o dir> [--bind 172.17.0.1] [--port 0] [--raw] [--ready-file F]++Routes: /u/<host>/<path> -> https://<host>/<path>. <host> must be a model API (MODEL_HOSTS below, the hosts+scripts/set_agent_egress.py allows), so the gateway can never carry an agent past its egress allowlist.++Attribution: a request's source IP is the trial's container (or, under an egress allowlist, its egress sidecar). Harbor+names a trial's compose project `<trial>__env`, so `docker inspect` maps the IP to the project and the project to the+trial directory <jobs>/<job>/<trial>/. Everything a trial's requests produce goes to <trial>/gateway/, next to Harbor's+own agent/ and verifier/ (not inside agent/, which the agent's container mounts and could rewrite):++ usage.jsonl one line per request: time, duration, host, path, status, model, normalized and raw usage+ totals.json running totals (rewritten after every request): requests, input / cached / output tokens+ raw/NNNNNN.json.gz with --raw: the request body and the response body (SSE text) as sent and received;+ credentials, cookies and account ids are removed from the recorded headers++Token counts are normalized the way Harbor counts them: input = everything the model read (Anthropic: input ++cache_read + cache_creation; OpenAI: input_tokens, which include cached ones), output = output_tokens (reasoning+included). Requests from an address no trial owns go to <jobs>/.gateway/unattributed.jsonl.+"""+from __future__ import annotations++import argparse+import ast+import base64+import fnmatch+import gzip+import http.client+import json+import os+import pathlib+import re+import subprocess+import sys+import threading+import time+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++ROOT = pathlib.Path(__file__).resolve().parents[2]+++def _model_hosts() -> list[str]:+ """HOSTS from scripts/set_agent_egress.py (read, not imported: that script acts on import)."""+ src = (ROOT / "scripts" / "set_agent_egress.py").read_text()+ m = re.search(r"^HOSTS\s*=\s*(\[.*?\])", src, re.M | re.S)+ return ast.literal_eval(m.group(1)) if m else []+++MODEL_HOSTS = _model_hosts()+HOP = {"connection", "keep-alive", "proxy-connection", "te", "trailers", "transfer-encoding", "upgrade", "host",+ "content-length", "accept-encoding"}+SECRET = {"authorization", "x-api-key", "api-key", "cookie", "set-cookie", "chatgpt-account-id", "openai-organization",+ "openai-project", "x-goog-api-key"}+LOCK = threading.Lock()+++# --------------------------------------------------------------------------- usage+def usage_from(obj, acc: dict) -> None:+ """Merge the usage found in one JSON object (a response body or one SSE event) into acc."""+ if not isinstance(obj, dict):+ return+ t = obj.get("type")+ if t == "message_start": # Anthropic Messages stream+ msg = obj.get("message") or {}+ acc.setdefault("model", msg.get("model"))+ acc.setdefault("raw", {}).update(msg.get("usage") or {})+ elif t == "message_delta":+ acc.setdefault("raw", {}).update({k: v for k, v in (obj.get("usage") or {}).items() if v is not None})+ elif t in ("response.completed", "response.done", "response.incomplete", "response.failed"): # OpenAI Responses+ resp = obj.get("response") or {}+ acc.setdefault("model", resp.get("model"))+ if resp.get("usage"):+ acc["raw"] = resp["usage"]+ elif isinstance(obj.get("usage"), dict): # non-streamed bodies; Chat Completions chunks+ acc.setdefault("model", obj.get("model"))+ acc["raw"] = obj["usage"]+++def normalize(raw: dict) -> dict:+ """{input, cached, output} in Harbor's convention (see the module doc)."""+ if not raw:+ return {}+ if "cache_read_input_tokens" in raw or "cache_creation_input_tokens" in raw: # Anthropic+ cached = int(raw.get("cache_read_input_tokens") or 0)+ return {"input": int(raw.get("input_tokens") or 0) + cached + int(raw.get("cache_creation_input_tokens") or 0),+ "cached": cached, "output": int(raw.get("output_tokens") or 0)}+ if "input_tokens" in raw: # OpenAI Responses+ return {"input": int(raw.get("input_tokens") or 0),+ "cached": int((raw.get("input_tokens_details") or {}).get("cached_tokens") or 0),+ "output": int(raw.get("output_tokens") or 0)}+ if "prompt_tokens" in raw: # Chat Completions+ return {"input": int(raw.get("prompt_tokens") or 0),+ "cached": int((raw.get("prompt_tokens_details") or {}).get("cached_tokens") or 0),+ "output": int(raw.get("completion_tokens") or 0)}+ return {}+++def parse_body(body: bytes, acc: dict) -> None:+ """Usage from a whole response: SSE (`data:` lines) or one JSON document."""+ found = False+ for line in body.split(b"\n"):+ if line.startswith(b"data:"):+ try:+ usage_from(json.loads(line[5:].strip()), acc); found = True+ except ValueError:+ pass+ if not found:+ try:+ usage_from(json.loads(body), acc)+ except ValueError:+ pass+++def decode_request(body: bytes, encoding: str) -> tuple[str | None, str]:+ """(text, how): the request body as text when it can be decoded, else None (it is kept as base64)."""+ enc = (encoding or "").lower().strip()+ try:+ if enc in ("", "identity"):+ data = body+ elif enc == "gzip":+ data = gzip.decompress(body)+ elif enc == "zstd":+ import zstandard # optional: pip install zstandard+ data = zstandard.ZstdDecompressor().decompressobj().decompress(body)+ else:+ return None, f"undecoded {enc}"+ return data.decode("utf-8"), "text"+ except Exception as exc: # noqa: BLE001 -- a body we cannot decode is still recorded, as base64+ return None, f"undecoded {enc}: {type(exc).__name__}"+++# --------------------------------------------------------------------------- trials+def sanitize(name: str) -> str:+ """Harbor's docker compose project name (harbor/environments/docker/docker.py)."""+ name = name.lower()+ if not re.match(r"^[a-z0-9]", name):+ name = "0" + name+ return re.sub(r"[^a-z0-9_-]", "-", name)+++class Trials:+ """Source IP -> trial directory, from docker's compose labels. Docker reuses subnets and addresses once a trial's+ network is gone, so a mapping is trusted for TTL seconds only and every scan replaces the whole table; a new trial+ needs far longer than that (image build, agent install) before its first model call."""+ TTL = 5.0++ def __init__(self, jobs: pathlib.Path):+ self.jobs, self.by_ip, self.last_scan = jobs, {}, 0.0+ self.lock = threading.Lock()++ def _scan(self) -> None:+ ids = subprocess.run(["docker", "ps", "-q"], capture_output=True, text=True, timeout=30).stdout.split()+ if not ids:+ self.by_ip = {}+ return+ fmt = '{{index .Config.Labels "com.docker.compose.project"}}{{range .NetworkSettings.Networks}} {{.IPAddress}}{{end}}'+ out = subprocess.run(["docker", "inspect", "-f", fmt, *ids], capture_output=True, text=True, timeout=30).stdout+ projects = {}+ for line in out.splitlines():+ proj, *ips = line.split()+ if proj.endswith("__env"):+ for ip in ips:+ projects[ip] = proj[: -len("__env")]+ dirs = {}+ for job in self.jobs.iterdir():+ if job.is_dir() and not job.name.startswith("."):+ for trial in job.iterdir():+ if trial.is_dir() and "__" in trial.name:+ dirs[sanitize(trial.name)] = trial+ self.by_ip = {ip: dirs[proj] for ip, proj in projects.items() if proj in dirs}++ def lookup(self, ip: str) -> pathlib.Path | None:+ with self.lock:+ if time.time() - self.last_scan > self.TTL or (ip not in self.by_ip and time.time() - self.last_scan > 1):+ self.last_scan = time.time()+ try:+ self._scan()+ except Exception as exc: # noqa: BLE001 -- attribution failure must not break the agent's request+ log(f"docker scan failed: {exc}")+ self.by_ip = {}+ return self.by_ip.get(ip)+++# --------------------------------------------------------------------------- server+ARGS: argparse.Namespace+TRIALS: Trials+SEQ = {"n": 0}+++def log(msg: str) -> None:+ with LOCK, open(ARGS.jobs / ".gateway" / f"gateway-{os.getpid()}.log", "a") as f:+ f.write(f"[{time.strftime('%F %T')}] {msg}\n")+++def record(trial: pathlib.Path | None, rec: dict, raw: dict | None) -> None:+ with LOCK:+ SEQ["n"] += 1+ seq = SEQ["n"]+ if trial is None:+ with open(ARGS.jobs / ".gateway" / "unattributed.jsonl", "a") as f:+ f.write(json.dumps({**rec, "seq": seq}) + "\n")+ return+ d = trial / "gateway"+ d.mkdir(exist_ok=True)+ if raw is not None:+ (d / "raw").mkdir(exist_ok=True)+ n = sum(1 for _ in (d / "raw").glob("*.json.gz")) + 1+ rec["raw_file"] = f"raw/{n:06d}.json.gz"+ with gzip.open(d / rec["raw_file"], "wt", encoding="utf-8") as f:+ json.dump(raw, f)+ with open(d / "usage.jsonl", "a") as f:+ f.write(json.dumps(rec) + "\n")+ tp = d / "totals.json"+ tot = json.loads(tp.read_text()) if tp.exists() else {"requests": 0, "input": 0, "cached": 0, "output": 0,+ "no_usage": 0}+ tot["requests"] += 1+ u = rec.get("usage") or {}+ if u:+ for k in ("input", "cached", "output"):+ tot[k] += u.get(k, 0)+ else:+ tot["no_usage"] += 1+ tot["updated"] = rec["ts"]+ tmp = tp.with_suffix(".tmp")+ tmp.write_text(json.dumps(tot, indent=1))+ tmp.replace(tp)+++class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, *a):+ pass++ def do_GET(self):+ self.forward()++ def do_POST(self):+ self.forward()++ def _reply(self, code: int, obj: dict) -> None:+ body = json.dumps(obj).encode()+ self.send_response(code)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def forward(self) -> None:+ if self.path == "/_gateway/health":+ return self._reply(200, {"ok": True})+ m = re.match(r"^/u/([A-Za-z0-9.-]+)(/.*)?$", self.path)+ if not m or not any(fnmatch.fnmatch(m.group(1).lower(), h) for h in MODEL_HOSTS):+ return self._reply(403, {"error": "usage gateway: not a model API host (scripts/set_agent_egress.py HOSTS)"})+ if (self.headers.get("Upgrade") or "").lower() == "websocket":+ return self._reply(405, {"error": "usage gateway: no WebSocket; use HTTPS (supports_websockets = false)"})+ host, path = m.group(1), m.group(2) or "/"+ t0 = time.time()+ ip = self.client_address[0]+ trial = TRIALS.lookup(ip) # now: a request that outlives its trial (a timeout) still counts for it+ body = self.rfile.read(int(self.headers.get("Content-Length") or 0))+ hdrs = {k: v for k, v in self.headers.items() if k.lower() not in HOP}+ hdrs["Host"] = host+ if body:+ hdrs["Content-Length"] = str(len(body))+ acc, chunks, client_gone = {}, [], False+ try:+ conn = http.client.HTTPSConnection(host, timeout=ARGS.timeout)+ conn.request(self.command, path, body=body or None, headers=hdrs)+ r = conn.getresponse()+ except Exception as exc: # noqa: BLE001 -- the agent sees an upstream error, as it would without the gateway+ log(f"upstream {host}: {exc!r}")+ return self._reply(502, {"error": f"usage gateway: upstream {host} unreachable: {type(exc).__name__}"})+ self.send_response(r.status)+ for k, v in r.getheaders():+ if k.lower() not in HOP:+ self.send_header(k, v)+ self.send_header("Transfer-Encoding", "chunked")+ self.end_headers()+ while True:+ chunk = r.read1(65536)+ if not chunk:+ break+ chunks.append(chunk)+ if not client_gone: # the agent hung up: keep reading, the request is billed anyway+ try:+ self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk)); self.wfile.flush()+ except OSError:+ client_gone = True+ if not client_gone:+ try:+ self.wfile.write(b"0\r\n\r\n"); self.wfile.flush()+ except OSError:+ client_gone = True+ resp = b"".join(chunks)+ parse_body(resp, acc)+ trial = trial or TRIALS.lookup(ip)+ rec = {"ts": round(t0, 3), "dur_s": round(time.time() - t0, 2), "client_ip": ip, "host": host,+ "method": self.command, "path": path.split("?")[0], "status": r.status, "model": acc.get("model"),+ "usage": normalize(acc.get("raw") or {}), "usage_raw": acc.get("raw") or {},+ "request_bytes": len(body), "response_bytes": len(resp), "client_gone": client_gone,+ "session": {k.lower(): v for k, v in self.headers.items() if "session" in k.lower()}}+ raw = None+ if ARGS.raw:+ text, how = decode_request(body, self.headers.get("Content-Encoding", ""))+ raw = {"request": {"method": self.command, "host": host, "path": path,+ "headers": {k: v for k, v in self.headers.items() if k.lower() not in SECRET},+ "body": text if text is not None else base64.b64encode(body).decode(), "body_as": how},+ "response": {"status": r.status,+ "headers": {k: v for k, v in r.getheaders() if k.lower() not in SECRET},+ "body": resp.decode("utf-8", "replace")}}+ record(trial, rec, raw)+++def main() -> int:+ global ARGS, TRIALS+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ p.add_argument("--jobs", type=pathlib.Path, required=True, help="Harbor's -o directory")+ p.add_argument("--bind", default="172.17.0.1", help="the docker bridge address containers reach the host by")+ p.add_argument("--port", type=int, default=0, help="0 = any free port (written to --ready-file)")+ p.add_argument("--raw", action="store_true", help="also record request and response bodies (raw/)")+ p.add_argument("--ready-file", type=pathlib.Path, help="written with the port once the gateway listens")+ p.add_argument("--timeout", type=float, default=900.0, help="upstream socket timeout, seconds")+ ARGS = p.parse_args()+ ARGS.jobs = ARGS.jobs.resolve()+ (ARGS.jobs / ".gateway").mkdir(parents=True, exist_ok=True)+ TRIALS = Trials(ARGS.jobs)+ srv = ThreadingHTTPServer((ARGS.bind, ARGS.port), Handler)+ srv.daemon_threads = True+ port = srv.server_address[1]+ log(f"listening on {ARGS.bind}:{port}, jobs {ARGS.jobs}, raw={ARGS.raw}, hosts {MODEL_HOSTS}")+ if ARGS.ready_file:+ ARGS.ready_file.write_text(str(port))+ srv.serve_forever()+ return 0+++if __name__ == "__main__":+ sys.exit(main())