Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
Make benchmark authentication selectable (#5750)
injaneity24d1ed10348e
diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/RUNNER.md b/libs/cua-driver-bench/automated-eval/macos_bench/RUNNER.mdindex 4b0cf266b4..3b12b2cddc 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/RUNNER.md+++ b/libs/cua-driver-bench/automated-eval/macos_bench/RUNNER.md@@ -19,6 +19,42 @@ invocation, isolation, schedule, gates and output. The method is inArms `codex-native-cu` and `codex-cua-driver` (`codex exec --json`, from`run_pilot.py`) exist behind `--allow-codex-arms` and are not part of Bench v2.+## Codex authentication++`CDB_CODEX_AUTH=gateway` is the default and retains the LiteLLM route.+Set `CDB_CODEX_AUTH=chatgpt` for direct ChatGPT-login authentication on the+three `cx-*` arms and the Codex fallback/pilot arms; no gateway or gateway key+is needed. Other values are rejected.++```bash+export CDB_CODEX_AUTH=chatgpt+# Optional; defaults to the runner user's ~/.codex/auth.json:+export CDB_CODEX_AUTH_FILE="$HOME/.codex/auth.json"+python3 run_bench.py preflight --only-arm cx-cua-driver+```++Log in to Codex with ChatGPT beforehand. Each trial's `CODEX_HOME/auth.json`+is a symlink to that existing file, never a credential copy. The harness does+not read or log its contents or perform login. ChatGPT mode sets+`cli_auth_credentials_store = "file"`; gateway configuration is unchanged.+**The ChatGPT auth file is shared with the host and its clones; refresh-token+rotation can sign out the other copies.**+The harness removes each trial/preflight symlink after use and flags a symlink+replaced with a regular file as an infrastructure failure. Gateway key+forwarding (`CDB_PILOT_PASS_GATEWAY_KEY=1`) applies only in gateway mode.++ChatGPT preflight uses only app-server metadata (`initialize`, `account/read`+with refresh disabled, and paginated `model/list`), not a model call. It requires+a ChatGPT account and the configured model, checks the credential link remains+a symlink, and is skipped offline. The metadata probe runs once per run, even+with `--no-model-preflight`. Gateway preflight is unchanged; the pilot does not+add a live authentication probe.+Model and effort are unchanged: native arms retain `gpt-6.1-sol` at its catalog+default `low` effort; pilot defaults remain independent. Native rows/manifests+record `codex_native.codex_auth` and omit the gateway URL in ChatGPT mode; pilot+rows/manifests record `codex_auth`. The fallback native-CU `notify` setting+is now root-level TOML in both modes, rather than inside the provider table.+## Files| File | What it does |diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/arms.py b/libs/cua-driver-bench/automated-eval/macos_bench/arms.pyindex 65950dff8a..639aa8c0d9 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/arms.py+++ b/libs/cua-driver-bench/automated-eval/macos_bench/arms.py@@ -13,8 +13,8 @@ Only the computer-use tool layer differs:ChatGPT/Codex app with the `@oai/sky` service) plus the computer-use skill andAPI reference that ship in the same app bundle.-Nothing here reads credentials. The model route is the local LiteLLM gateway-already configured for Codex (see `provider_block`).+Nothing here reads credentials. CDB_CODEX_AUTH selects the local LiteLLM gateway+(default) or ChatGPT login through a shared auth.json symlink."""from __future__ import annotations@@ -22,8 +22,10 @@ from __future__ import annotationsimport jsonimport osimport shutil+import statfrom dataclasses import dataclassfrom pathlib import Path+from typing import LiteralARMS = ("cua-driver-mcp", "codex-native-cu") # the Codex-CLI pilot arms (run_pilot.py)# Claude Code arms (run_bench.py): same model, same harness, only the MCP tools differ.@@ -105,12 +107,58 @@ def _sh(value: str) -> str:return "'" + value.replace("'", "'\\''") + "'"-def provider_block() -> str:- """The LiteLLM provider block used for every arm (identical text)."""+CodexAuth = Literal["gateway", "chatgpt"]+++def codex_auth() -> CodexAuth:+ mode = os.environ.get("CDB_CODEX_AUTH", "gateway")+ if mode == "gateway":+ return "gateway"+ if mode == "chatgpt":+ return "chatgpt"+ raise ValueError("CDB_CODEX_AUTH must be gateway or chatgpt")+++def link_chatgpt_auth(codex_home: Path) -> None:+ if codex_auth() == "gateway":+ return+ source = (+ Path(os.environ.get("CDB_CODEX_AUTH_FILE") or "~/.codex/auth.json").expanduser().absolute()+ )+ try:+ source.lstat()+ except OSError:+ raise FileNotFoundError("ChatGPT auth file is missing") from None+ link = codex_home / "auth.json"+ if link.is_symlink() and link.readlink() == source:+ return+ try:+ link.symlink_to(source)+ except OSError as error:+ raise type(error)("cannot provision shared ChatGPT authentication") from None+++def unlink_chatgpt_auth(codex_home: Path) -> None:+ if codex_auth() == "gateway":+ return+ link = codex_home / "auth.json"+ try:+ mode = link.lstat().st_mode+ except FileNotFoundError:+ raise RuntimeError("shared ChatGPT credential symlink missing") from None+ if not stat.S_ISLNK(mode):+ raise RuntimeError("shared ChatGPT credential symlink replaced")+ link.unlink()+++def provider_block(url: str = "http://127.0.0.1:4000/v1") -> str:+ """The LiteLLM provider block, omitted for built-in ChatGPT authentication."""+ if codex_auth() == "chatgpt":+ return ""return ("[model_providers.litellm]\n"'name = "LiteLLM"\n'- 'base_url = "http://127.0.0.1:4000/v1"\n'+ f"base_url = {_q(url)}\n"'wire_api = "responses"\n'"requires_openai_auth = false\n""request_max_retries = 2\n"@@ -122,15 +170,16 @@ def provider_block() -> str:def common_config(model: str, effort: str) -> str:return (f"model = {_q(model)}\n"- 'model_provider = "litellm"\n'- f"model_reasoning_effort = {_q(effort)}\n"+ + (+ 'model_provider = "litellm"\n'+ if codex_auth() == "gateway"+ else 'cli_auth_credentials_store = "file"\n'+ )+ + f"model_reasoning_effort = {_q(effort)}\n"'approval_policy = "never"\n''sandbox_mode = "workspace-write"\n'"mcp_optional_startup_grace_ms = 30000\n""\n"- "[sandbox_workspace_write]\n"- "network_access = true\n"- "\n" + provider_block())@@ -155,8 +204,6 @@ def codex_cu_config() -> str:"SKY_CUA_SERVICE_PATH": str(CODEX_CU_APP),}lines = [- "",- f'notify = [{_q(str(CODEX_CU_CLIENT))}, "turn-ended"]',"","[mcp_servers.node_repl]",f"command = {_q(str(node_dir / 'bin/node_repl'))}",@@ -177,7 +224,11 @@ def render_home(arm: str, home: Path, model: str, effort: str) -> dict[str, str]raise ValueError(f"unknown arm: {arm}")codex_home = home / ".codex"codex_home.mkdir(parents=True, exist_ok=True)+ link_chatgpt_auth(codex_home)config = common_config(model, effort)+ if arm == "codex-native-cu":+ config += f'notify = [{_q(str(CODEX_CU_CLIENT))}, "turn-ended"]\n'+ config += "\n[sandbox_workspace_write]\nnetwork_access = true\n\n" + provider_block()skills = home / ".agents" / "skills"path = CLOSED_PATHif arm == "cua-driver-mcp":@@ -213,7 +264,11 @@ def render_home(arm: str, home: Path, model: str, effort: str) -> dict[str, str]}(home / "tmp").mkdir(exist_ok=True)gateway_key = os.environ.get("LITELLM_MASTER_KEY")- if gateway_key and os.environ.get("CDB_PILOT_PASS_GATEWAY_KEY") == "1":+ if (+ codex_auth() == "gateway"+ and gateway_key+ and os.environ.get("CDB_PILOT_PASS_GATEWAY_KEY") == "1"+ ):env["LITELLM_MASTER_KEY"] = gateway_keyreturn envdiff --git a/libs/cua-driver-bench/automated-eval/macos_bench/codex_native.py b/libs/cua-driver-bench/automated-eval/macos_bench/codex_native.pyindex 996715bced..7d5b713654 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/codex_native.py+++ b/libs/cua-driver-bench/automated-eval/macos_bench/codex_native.py@@ -34,15 +34,16 @@ Claude Code's assistant turns; the 45-turn cap stops the turn when the cap-th relist price is pinned for ``gpt-6-astra`` through the subscription gateway, so cost is not reported for this arm(tokens are).-Nothing here reads credentials. The model is reached through the LiteLLM gateway at ``CDB_CODEX_GATEWAY``-(default ``http://127.0.0.1:4000/v1``), which in the bench VM is a local port forwarded to the owner's gateway for-the run only; no key is placed in the VM.+Nothing here reads credentials. CDB_CODEX_AUTH selects the LiteLLM gateway at+``CDB_CODEX_GATEWAY`` (default ``http://127.0.0.1:4000/v1``) or built-in ChatGPT login+through a shared auth.json symlink."""from __future__ import annotationsimport jsonimport os+import selectorsimport signalimport subprocessimport threading@@ -50,6 +51,8 @@ import timefrom pathlib import Pathfrom typing import Any, Callable+import arms+ARM = "cx-codex-cu"# cx-cua-driver and cx-claude-cu-helper: Amendment 23, Cua Driver's MCP server and Cua's helper adapter under the# same Codex host@@ -73,7 +76,7 @@ ENABLED_TOOLS = (CODEX_CLI = Path("/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex")-# Amendment 23: GPT-6.1 Sol (`gpt-6.1-sol`, served through the gateway), at its catalog default effort+# Amendment 23: GPT-6.1 Sol (`gpt-6.1-sol`), at its catalog default effort# (`low`), as the Claude arms use Claude's default. A20's smoke used gpt-6-astra (`medium`). The model and effort are# recorded in every row and named in the setup's label.MODEL_DEFAULT_EFFORT = {"gpt-6-astra": "medium", "gpt-6.1-sol": "low"}@@ -169,7 +172,11 @@ def config_toml() # unchanged from arm B: Sky's service and pipe live under the user's own homelines = [f"model = {_q(model)}",- 'model_provider = "litellm"',+ (+ 'model_provider = "litellm"'+ if arms.codex_auth() == "gateway"+ else 'cli_auth_credentials_store = "file"'+ ),f"model_reasoning_effort = {_q(effort)}",'approval_policy = "on-request"', # elicitations reach the host only with on-request'sandbox_mode = "read-only"',@@ -180,14 +187,7 @@ def config_toml("[features]",*[f"{name} = false" for name in DISABLED_FEATURES],"",- "[model_providers.litellm]",- 'name = "LiteLLM"',- f"base_url = {_q(gateway())}",- 'wire_api = "responses"',- "requires_openai_auth = false",- "request_max_retries = 2",- "stream_max_retries = 2",- "stream_idle_timeout_ms = 120000",+ *([arms.provider_block(gateway()).rstrip()] if arms.codex_auth() == "gateway" else []),"",f"[mcp_servers.{server}]",f"command = {_q(entry['command'])}",@@ -212,6 +212,7 @@ def render_home("""Write a fresh CODEX_HOME for one trial; return the closed environment for `codex exec`."""codex_home = home / ".codex"codex_home.mkdir(parents=True, exist_ok=True)+ arms.link_chatgpt_auth(codex_home)(home / "tmp").mkdir(exist_ok=True)(codex_home / "config.toml").write_text(config_toml(server_entry(mcp_json, arm), model, effort, instructions, codex_home, arm),@@ -377,6 +378,86 @@ def _kill_group(pid: int, grace: float = 1.0) -> None:time.sleep(grace)+CHATGPT_CHECK_TIMEOUT = 30.0+++def chatgpt_checks(cli: Path, env: dict[str, str], model: str) -> list[tuple[str, str, str]]:+ checks: list[tuple[str, str, str]] = []+ label = "codex app-server initialize"+ proc = None+ deadline = time.monotonic() + CHATGPT_CHECK_TIMEOUT+ try:+ with selectors.DefaultSelector() as selector:+ proc = subprocess.Popen(+ argv(cli),+ env=env,+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ start_new_session=True,+ )+ assert proc.stdin is not None and proc.stdout is not None+ selector.register(proc.stdout, selectors.EVENT_READ)+ pending = b""+ rid = 0++ def send(message: dict[str, Any]) -> None:+ proc.stdin.write((json.dumps(message) + "\n").encode())+ proc.stdin.flush()++ def request(method: str, params: dict[str, Any]) -> dict[str, Any]:+ nonlocal pending, rid+ rid += 1+ send({"id": rid, "method": method, "params": params})+ while time.monotonic() < deadline:+ if b"\n" not in pending:+ if not selector.select(max(0, deadline - time.monotonic())):+ break+ chunk = os.read(proc.stdout.fileno(), 65536)+ if not chunk:+ raise RuntimeError+ pending += chunk+ continue+ line, pending = pending.split(b"\n", 1)+ reply = json.loads(line)+ if reply.get("id") != rid:+ continue+ if "error" in reply:+ raise RuntimeError+ return reply["result"]+ raise TimeoutError++ request("initialize", {"clientInfo": {"name": "cdb_preflight", "version": "1"}})+ send({"method": "initialized", "params": {}})+ checks.append((label, "pass", "initialized"))+ label = "codex ChatGPT account"+ account = request("account/read", {"refreshToken": False}).get("account")+ if not account or account.get("type") != "chatgpt":+ raise RuntimeError+ checks.append((label, "pass", "ChatGPT login present"))+ label = "codex lists the model"+ cursor = None+ while True:+ page = request("model/list", {"cursor": cursor})+ if any(item.get("model") == model for item in page["data"]):+ break+ cursor = page.get("nextCursor")+ if not cursor:+ raise RuntimeError+ checks.append((label, "pass", "configured model available"))+ except (OSError, ValueError, KeyError, TypeError, AttributeError, RuntimeError):+ checks.append((label, "fail", "metadata check failed"))+ finally:+ if proc is not None:+ _kill_group(proc.pid, grace=0.05)+ proc.wait(timeout=5)+ if proc.stdin:+ proc.stdin.close()+ if proc.stdout:+ proc.stdout.close()+ return checks++def run_codex(cmd: list[str],env: dict[str, str],@@ -585,6 +666,7 @@ def observed(cli: Path = CODEX_CLI) -> dict[str, Any]:"codex_cli_sha256": sha,"model": MODEL,"effort": EFFORT,- "gateway": gateway(),+ "codex_auth": arms.codex_auth(),+ **({"gateway": gateway()} if arms.codex_auth() == "gateway" else {}),"host": "codex app-server",}diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/launch/launch.env.example b/libs/cua-driver-bench/automated-eval/macos_bench/launch/launch.env.exampleindex 69ecacbc42..98ea740249 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/launch/launch.env.example+++ b/libs/cua-driver-bench/automated-eval/macos_bench/launch/launch.env.example@@ -4,6 +4,17 @@ RUN_ID=main# No new trial starts after this time (UTC). Set it before you launch.CUTOFF_UTC=2026-10-08T06:00:00ZEXTRA_ARGS=""+# Codex authentication: gateway (default) or chatgpt; model and effort are unchanged.+# ChatGPT mode needs an existing Codex ChatGPT login, not a gateway or key.+# Native preflight checks account/model metadata once, with no model call,+# including with --no-model-preflight; --offline skips this probe. No automatic login.+# export CDB_CODEX_AUTH=chatgpt+# export CDB_CODEX_AUTH_FILE="$HOME/.codex/auth.json" # optional override+# The ChatGPT auth file is shared with the host and its clones via symlinks.+# Refresh-token rotation can sign out the other copies. Links are removed after use;+# replacing a link with a regular file is flagged as an infrastructure failure.+# ChatGPT uses file credential storage. LITELLM_MASTER_KEY forwarding remains+# gateway-only, under the existing CDB_PILOT_PASS_GATEWAY_KEY=1 opt-in.# Inside the VM (Amendment 1 of the pre-registration) also export, in this file:# export CDB_BENCH_DISPOSABLE=1 # the runner may kill Electron, Chrome, LibreOffice and GnuCash by name# export CDB_TASKPACK=$HOME/cdb-runtime # agent-visible part of the private CDB task packdiff --git a/libs/cua-driver-bench/automated-eval/macos_bench/run_bench.py b/libs/cua-driver-bench/automated-eval/macos_bench/run_bench.pyindex 34ca469e4e..bb1bb77ecb 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/run_bench.py+++ b/libs/cua-driver-bench/automated-eval/macos_bench/run_bench.py@@ -956,6 +956,13 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]failure = {"kind": "harness_exception", "message": f"{type(error).__name__}: {error}"}note = failure["message"]finally:+ codex_home = trial_dir / "codex-home" / ".codex"+ if arm in cxn.ARMS and codex_home.is_dir():+ try:+ arms.unlink_chatgpt_auth(codex_home)+ except RuntimeError as error:+ failure = {"kind": "harness_exception", "message": str(error)}+ note = str(error)try:sentinel.stop()except Exception: # noqa: BLE001@@ -992,7 +999,7 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]if entry["arm"] in cxn.ARMS:cost, cost_source = (None,- "not priced (gpt-6-astra via the subscription gateway; tokens reported)",+ "not priced (Codex subscription; tokens reported)",)elif cost is None:cost = estimate_cost(tokens)@@ -1713,8 +1720,7 @@ def quota_probe(ctx: Ctx) -> tuple[bool, str]:def native_codex_checks(ctx: Ctx, arm: str, with_models: bool) -> list[tuple[str, str, str]]:- """Amendment 20: the Codex CLI build is the pinned one, the gateway serves the model, and one trivial- `codex exec` through the trial's own home answers without any tool call."""+ """Check CLI pins and authentication; only gateway mode optionally makes a model call."""out: list[tuple[str, str, str]] = []observed = ctx.versions.get("codex_native") or cxn.observed()want = ca.load_pins().get("codex_native") or {}@@ -1729,30 +1735,50 @@ def native_codex_checks(ctx: Ctx, arm: str, with_models: bool) -> list[tuple[strelse f"observed {observed.get(key)!r}, pinned {want.get(key)!r}",))- try:- import urllib.request+ chatgpt = arms.codex_auth() == "chatgpt"+ if chatgpt:+ if ctx.args.offline:+ return out+ if "codex_auth_checks" in ctx.versions:+ return out + ctx.versions["codex_auth_checks"]+ else:+ try:+ import urllib.request- with urllib.request.urlopen(cxn.gateway().rstrip("/") + "/models", timeout=10) as resp:- listed = [m.get("id") for m in json.load(resp).get("data", [])]- out.append(- (- "gateway lists the model",- "pass" if cxn.MODEL in listed else "fail",- f"{cxn.gateway()} {cxn.MODEL}",+ with urllib.request.urlopen(cxn.gateway().rstrip("/") + "/models", timeout=10) as resp:+ listed = [m.get("id") for m in json.load(resp).get("data", [])]+ out.append(+ (+ "gateway lists the model",+ "pass" if cxn.MODEL in listed else "fail",+ f"{cxn.gateway()} {cxn.MODEL}",+ ))- )- except Exception as error: # noqa: BLE001- out.append(- ("gateway reachable", "fail", f"{cxn.gateway()}: {type(error).__name__}: {error}")- )- if not with_models:- return out+ except Exception as error: # noqa: BLE001+ out.append(+ ("gateway reachable", "fail", f"{cxn.gateway()}: {type(error).__name__}: {error}")+ )+ if not with_models:+ return outmcp_path, _server = ctx.mcp[arm]home = ctx.run_dir / f"preflight-{arm}-home"shutil.rmtree(home, ignore_errors=True)- env = cxn.render_home(- home, mcp_path, cxn.MODEL, cxn.EFFORT, ca.system_prompt_for(cxn.SOURCE_ARM[arm]), arm- )+ checks: list[tuple[str, str, str]] = []+ try:+ env = cxn.render_home(+ home, mcp_path, cxn.MODEL, cxn.EFFORT, ca.system_prompt_for(cxn.SOURCE_ARM[arm]), arm+ )+ if chatgpt:+ checks.extend(cxn.chatgpt_checks(cxn.CODEX_CLI, env, cxn.MODEL))+ finally:+ if chatgpt:+ try:+ arms.unlink_chatgpt_auth(home / ".codex")+ except RuntimeError as error:+ checks.append(("codex shared auth symlink", "fail", str(error)))+ if chatgpt:+ ctx.versions["codex_auth_checks"] = checks+ return out + checkscwd = ca.prepare_cwd(arm)stream = ctx.run_dir / f"preflight-init-{arm}.tsv"result = cxn.run_codex(diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/run_pilot.py b/libs/cua-driver-bench/automated-eval/macos_bench/run_pilot.pyindex ca0b95daac..cec360b64d 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/run_pilot.py+++ b/libs/cua-driver-bench/automated-eval/macos_bench/run_pilot.py@@ -594,6 +594,7 @@ def run_trial("seed": seed,"order_index": order_index,"started_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),+ "codex_auth": arms.codex_auth(),"model": args.model,"reasoning_effort": args.effort,}@@ -676,6 +677,13 @@ def run_trial(status = "infra_error"note = f"{type(error).__name__}: {error}"finally:+ codex_home = trial_dir / "home" / ".codex"+ if codex_home.is_dir():+ try:+ arms.unlink_chatgpt_auth(codex_home)+ except RuntimeError as error:+ status = "infra_error"+ note = str(error)sentinel.stop()for proc in procs:kill_group(proc.pid)@@ -798,6 +806,7 @@ def environment_manifest(args: argparse.Namespace) -> dict[str, Any]:"CFBundleShortVersionString",),"bench_repo_commit": run("git", "-C", str(REPO), "rev-parse", "HEAD"),+ "codex_auth": arms.codex_auth(),"model": args.model,"reasoning_effort": args.effort,"price_assumed_usd_per_mtok": PRICE,diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_codex_native.py b/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_codex_native.pyindex 86d68e137c..a823406843 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_codex_native.py+++ b/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_codex_native.py@@ -5,12 +5,16 @@from __future__ import annotations+import contextlibimport json+import shutil+import osimport sysimport tempfileimport tomllibimport unittestfrom pathlib import Path+from unittest import mockHERE = Path(__file__).resolve().parent.parentsys.path.insert(0, str(HERE))@@ -47,6 +51,215 @@ def write_arm_b(folder: Path, surfaces: str = "computer") -> Path:class HomeTest(unittest.TestCase):+ def test_auth_modes_preserve_config_and_share_credentials(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ source = root / ".codex/auth.json"+ source.parent.mkdir()+ source.write_bytes(b"private")+ source.chmod(0o000)+ before = source.stat().st_mtime_ns+ mcp = write_arm_b(root)+ for arm in cxn.ARMS:+ configs = {}+ texts = {}+ for mode in ("gateway", "chatgpt"):+ with mock.patch.dict(+ os.environ, {"CDB_CODEX_AUTH": mode, "HOME": tmp}, clear=True+ ):+ env = cxn.render_home(+ root / f"{arm}-{mode}", mcp, cxn.MODEL, cxn.EFFORT, "SYSTEM", arm+ )+ home = Path(env["CODEX_HOME"])+ texts[mode] = (home / "config.toml").read_text()+ configs[mode] = tomllib.loads(texts[mode])+ link = home / "auth.json"+ self.assertEqual(link.is_symlink(), mode == "chatgpt")+ if mode == "chatgpt":+ self.assertEqual(os.readlink(link), str(source))+ arms.link_chatgpt_auth(home)+ link.unlink()+ link.symlink_to(root / "other")+ with self.assertRaises(FileExistsError):+ arms.link_chatgpt_auth(home)+ link.unlink()+ link.write_text("conflict")+ with self.assertRaises(FileExistsError) as conflict:+ arms.link_chatgpt_auth(home)+ self.assertNotIn(str(source), str(conflict.exception))+ expected = texts["gateway"].replace(+ 'model_provider = "litellm"', 'cli_auth_credentials_store = "file"'+ )+ start = expected.index("[model_providers.litellm]")+ end = expected.index("\n\n", start)+ self.assertEqual(texts["chatgpt"], expected[:start] + expected[end + 1 :])+ gateway = configs["gateway"]+ self.assertEqual(gateway.pop("model_provider"), "litellm")+ self.assertIn("litellm", gateway.pop("model_providers"))+ self.assertNotIn("cli_auth_credentials_store", gateway)+ self.assertEqual(configs["chatgpt"].pop("cli_auth_credentials_store"), "file")+ self.assertEqual(gateway, configs["chatgpt"])+ self.assertEqual(gateway["model"], "gpt-6.1-sol")+ self.assertEqual(gateway["model_reasoning_effort"], "low")+ with mock.patch.dict(+ os.environ, {"CDB_CODEX_AUTH": "chatgpt", "CDB_CODEX_AUTH_FILE": str(source)}+ ):+ env = cxn.render_home(root / "override", mcp, cxn.MODEL, cxn.EFFORT, "SYSTEM")+ self.assertEqual(os.readlink(Path(env["CODEX_HOME"]) / "auth.json"), str(source))+ self.assertEqual(source.stat().st_mtime_ns, before)+ source.chmod(0o600)+ self.assertEqual(source.read_bytes(), b"private")+ source.unlink()+ with self.assertRaises(FileNotFoundError):+ cxn.render_home(root / "missing", mcp, cxn.MODEL, cxn.EFFORT, "SYSTEM")++ def test_auth_identity_does_not_record_gateway_in_chatgpt_mode(self) -> None:+ with mock.patch.dict(os.environ, {"CDB_CODEX_AUTH": "chatgpt"}):+ identity = cxn.observed(Path("/nonexistent"))+ self.assertEqual(identity["codex_auth"], "chatgpt")+ self.assertNotIn("gateway", identity)+ with mock.patch.dict(os.environ, {"CDB_CODEX_AUTH": "gateway"}):+ identity = cxn.observed(Path("/nonexistent"))+ self.assertEqual(identity["codex_auth"], "gateway")+ self.assertEqual(identity["gateway"], cxn.gateway())++ def test_credentials_are_never_read_copied_or_stat_followed(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ source = root / "shared-auth.json"+ source.write_text("FAKE_REFRESH_TOKEN")+ mcp = write_arm_b(root)+ skill = root / "skill"+ skill.mkdir()+ (skill / "SKILL.md").write_text("skill")++ def protect(function):+ def guarded(path, *args, **kwargs):+ if Path(path) == source and kwargs.get("follow_symlinks", True):+ raise AssertionError("credential content accessed")+ return function(path, *args, **kwargs)++ return guarded++ with contextlib.ExitStack() as stack:+ stack.enter_context(+ mock.patch.dict(+ os.environ,+ {+ "CDB_CODEX_AUTH": "chatgpt",+ "CDB_CODEX_AUTH_FILE": str(source),+ "LITELLM_MASTER_KEY": "FAKE_GATEWAY_KEY",+ "CDB_PILOT_PASS_GATEWAY_KEY": "1",+ },+ )+ )+ stack.enter_context(mock.patch.object(arms, "CUA_DRIVER_SKILL", skill))+ for owner, name in (+ (__import__("builtins"), "open"),+ (Path, "read_text"),+ (Path, "read_bytes"),+ (Path, "stat"),+ (os, "open"),+ *(+ (shutil, name)+ for name in (+ "copy",+ "copy2",+ "copyfile",+ "copytree",+ "copymode",+ "copystat",+ )+ ),+ ):+ stack.enter_context(+ mock.patch.object(owner, name, protect(getattr(owner, name)))+ )+ for env in (+ cxn.render_home(root / "native", mcp, cxn.MODEL, cxn.EFFORT, "SYSTEM"),+ arms.render_home("codex-cua-driver", root / "fallback", "m", "high"),+ ):+ self.assertNotIn("LITELLM_MASTER_KEY", env)+ self.assertEqual((Path(env["CODEX_HOME"]) / "auth.json").readlink(), source)+ identity = json.dumps(cxn.observed(Path("/nonexistent")))+ for secret in (+ str(source),+ "FAKE_REFRESH_TOKEN",+ "FAKE_GATEWAY_KEY",+ cxn.gateway(),+ ):+ self.assertNotIn(secret, identity)++ def test_gateway_config_matches_original_text(self) -> None:+ with mock.patch.dict(+ os.environ,+ {"CDB_CODEX_AUTH": "gateway", "CDB_CODEX_GATEWAY": "http://127.0.0.1:4000/v1"},+ ):+ text = cxn.config_toml(+ {"command": "node", "args": [], "env": {}},+ "gpt-6.1-sol",+ "low",+ "SYSTEM",+ Path("/trial"),+ )+ self.assertEqual(+ text,+ """model = "gpt-6.1-sol"+model_provider = "litellm"+model_reasoning_effort = "low"+approval_policy = "on-request"+sandbox_mode = "read-only"+web_search = "disabled"+mcp_optional_startup_grace_ms = 30000+developer_instructions = "SYSTEM"++[features]+shell_tool = false+unified_exec = false+apps = false+browser_use = false+browser_use_external = false+in_app_browser = false+image_generation = false+multi_agent = false+multi_agent_v2 = false+goals = false+view_image = false+plugins = false+tool_suggest = false+skill_search = false++[model_providers.litellm]+name = "LiteLLM"+base_url = "http://127.0.0.1:4000/v1"+wire_api = "responses"+requires_openai_auth = false+request_max_retries = 2+stream_max_retries = 2+stream_idle_timeout_ms = 120000++[mcp_servers.cua_repl]+command = "node"+args = []+startup_timeout_sec = 120+default_tools_approval_mode = "approve"+enabled_tools = ["js", "js_reset"]++[mcp_servers.cua_repl.env]+""",+ )++ def test_invalid_auth_mode_is_rejected(self) -> None:+ with mock.patch.dict(os.environ, {"CDB_CODEX_AUTH": "invalid"}):+ with self.assertRaises(ValueError):+ cxn.config_toml(+ {"command": "node", "args": [], "env": {}},+ cxn.MODEL,+ cxn.EFFORT,+ "",+ Path("/tmp/home"),+ )+def test_config_uses_arm_b_launcher_and_switches_routes_off(self) -> None:with tempfile.TemporaryDirectory() as tmp:tmp_path = Path(tmp)@@ -146,6 +359,83 @@ class CuaDriverUnderCodexTest(unittest.TestCase):self.assertEqual(out[0]["mcp_servers"], [{"name": "cua", "status": "connected"}])+class ChatGPTPreflightTest(unittest.TestCase):+ def test_metadata_only_probe_handles_notifications_pages_and_failures(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ source = root / "auth.json"+ source.touch()+ home = root / "home"+ home.mkdir()+ (home / "auth.json").symlink_to(source)+ cli = root / "codex"+ requests = root / "requests"+ pid_file = root / "pid"+ for scenario in (+ "ok",+ "apiKey",+ "missing",+ "model",+ "rpc",+ "exit",+ "timeout",+ "malformed",+ ):+ cli.write_text(f"""#!{sys.executable}+import json, os, sys, time+from pathlib import Path+Path({str(pid_file)!r}).write_text(str(os.getpid()))+scenario = {scenario!r}+for line in sys.stdin:+ msg = json.loads(line)+ with open({str(requests)!r}, 'a') as log:+ log.write(line)+ if 'id' not in msg:+ continue+ method = msg['method']+ if scenario == 'exit':+ sys.exit(0)+ if scenario == 'malformed':+ print('[]', flush=True)+ continue+ if scenario == 'timeout':+ time.sleep(10)+ result = {{}}+ if method == 'account/read':+ assert msg['params']['refreshToken'] is False+ result = {{'account': None if scenario == 'missing' else {{'type': 'apiKey' if scenario == 'apiKey' else 'chatgpt', 'email': 'SECRET'}}}}+ if method == 'model/list':+ if not msg['params'].get('cursor'):+ result = {{'data': [], 'nextCursor': 'page2'}}+ else:+ result = {{'data': [{{'model': 'other' if scenario == 'model' else 'gpt-6.1-sol', 'id': 'catalog-id'}}], 'nextCursor': None}}+ print(json.dumps({{'method': 'notification', 'params': {{'private': 'SECRET'}}}}), flush=True)+ reply = {{'id': msg['id'], 'result': result}}+ if scenario == 'rpc':+ reply = {{'id': msg['id'], 'error': {{'message': 'SECRET'}}}}+ print(json.dumps(reply), flush=True)+""")+ cli.chmod(0o755)+ requests.write_text("")+ with mock.patch.object(cxn, "CHATGPT_CHECK_TIMEOUT", 0.3):+ checks = cxn.chatgpt_checks(cli, {"CODEX_HOME": str(home)}, cxn.MODEL)+ self.assertEqual(+ all(status == "pass" for _, status, _ in checks), scenario == "ok", scenario+ )+ self.assertNotIn("SECRET", str(checks))+ with self.assertRaises(ProcessLookupError):+ os.kill(int(pid_file.read_text()), 0)+ methods = [json.loads(line)["method"] for line in requests.read_text().splitlines()]+ self.assertTrue(+ set(methods) <= {"initialize", "initialized", "account/read", "model/list"}+ )+ if scenario == "ok":+ self.assertEqual(+ methods,+ ["initialize", "initialized", "account/read", "model/list", "model/list"],+ )++class TranslatorTest(unittest.TestCase):def run_events(self, events: list[tuple[str, dict]]) -> tuple[list[dict], cxn.Translator]:tr = cxn.Translator()diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_pilot_runner.py b/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_pilot_runner.pyindex 75faf30dd7..136c914bcc 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_pilot_runner.py+++ b/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_pilot_runner.py@@ -5,11 +5,15 @@from __future__ import annotations+import argparseimport json+import os+import tomllibimport sysimport tempfileimport unittestfrom pathlib import Path+from unittest import mockHERE = Path(__file__).resolve().parentsys.path.insert(0, str(HERE.parent))@@ -167,30 +171,85 @@ class CodexEventsTest(unittest.TestCase):self.assertIsNone(codex_events.rollout_usage(Path(tmp) / "missing"))-_CODEX_NODE_REPL_DOC = Path(- "/Applications/ChatGPT.app/Contents/Resources/plugins/openai-bundled/plugins/computer-use/.codex-plugin/computer-use-node-repl.md"-)+class ArmsTest(unittest.TestCase):+ def test_gateway_common_config_matches_original_text(self) -> None:+ with mock.patch.dict(os.environ, {"CDB_CODEX_AUTH": "gateway"}):+ self.assertEqual(+ arms.common_config("m", "high"),+ """model = "m"+model_provider = "litellm"+model_reasoning_effort = "high"+approval_policy = "never"+sandbox_mode = "workspace-write"+mcp_optional_startup_grace_ms = 30000+""",+ )-class ArmsTest(unittest.TestCase):- @unittest.skipUnless(- _CODEX_NODE_REPL_DOC.exists(), "needs the ChatGPT app's bundled computer-use plugin"- )def test_arm_homes_differ_only_in_tool_layer(self) -> None:with tempfile.TemporaryDirectory() as tmp:- cua = Path(tmp) / "cua"- native = Path(tmp) / "native"- arms.render_home("cua-driver-mcp", cua, "m", "high")- arms.render_home("codex-native-cu", native, "m", "high")- common = arms.common_config("m", "high")- for home in (cua, native):- text = (home / ".codex" / "config.toml").read_text("utf-8")- self.assertTrue(text.startswith(common))- self.assertIn('default_tools_approval_mode = "approve"', text)- self.assertIn("[mcp_servers.cua]", (cua / ".codex/config.toml").read_text("utf-8"))- self.assertIn(- "[mcp_servers.node_repl]", (native / ".codex/config.toml").read_text("utf-8")- )+ root = Path(tmp)+ for name in ("skills/computer-use/SKILL.md", ".codex-plugin/computer-use-node-repl.md"):+ path = root / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("fixture")+ source = root / ".codex/auth.json"+ source.parent.mkdir()+ source.write_bytes(b"private")+ source.chmod(0o000)+ before = source.stat().st_mtime_ns+ with mock.patch.multiple(+ arms,+ CODEX_APP_RESOURCES=root,+ CODEX_CU_PLUGIN=root,+ CUA_DRIVER_SKILL=root / "skills/computer-use",+ ):+ for arm in arms.ARMS:+ configs = {}+ for mode in ("gateway", "chatgpt"):+ home = root / f"{arm}-{mode}"+ with mock.patch.dict(+ os.environ,+ {+ "CDB_CODEX_AUTH": mode,+ "CDB_CODEX_AUTH_FILE": str(source),+ "LITELLM_MASTER_KEY": "secret",+ "CDB_PILOT_PASS_GATEWAY_KEY": "1",+ },+ ):+ env = arms.render_home(arm, home, "m", "high")+ text = (home / ".codex/config.toml").read_text()+ self.assertTrue(text.startswith(arms.common_config("m", "high")))+ self.assertEqual("LITELLM_MASTER_KEY" in env, mode == "gateway")+ link = home / ".codex/auth.json"+ self.assertEqual(link.is_symlink(), mode == "chatgpt")+ if mode == "chatgpt":+ self.assertEqual(os.readlink(link), str(source))+ configs[mode] = tomllib.loads(text)+ gateway = configs["gateway"]+ self.assertEqual(gateway.pop("model_provider"), "litellm")+ gateway.pop("model_providers")+ self.assertNotIn("cli_auth_credentials_store", gateway)+ self.assertEqual(configs["chatgpt"].pop("cli_auth_credentials_store"), "file")+ self.assertEqual(gateway, configs["chatgpt"])+ if arm == "codex-native-cu":+ self.assertIn("notify", gateway)+ with mock.patch.dict(+ os.environ, {"CDB_CODEX_AUTH": "chatgpt", "HOME": tmp}, clear=True+ ):+ env = arms.render_home("cua-driver-mcp", root / "default", "m", "high")+ link = Path(env["CODEX_HOME"]) / "auth.json"+ self.assertTrue(link.is_symlink())+ self.assertEqual(os.readlink(link), str(source))+ self.assertEqual(source.stat().st_mtime_ns, before)+ source.chmod(0o600)+ self.assertEqual(source.read_bytes(), b"private")+ source.unlink()+ with mock.patch.dict(+ os.environ, {"CDB_CODEX_AUTH": "chatgpt", "CDB_CODEX_AUTH_FILE": str(source)}+ ):+ with self.assertRaises(FileNotFoundError):+ arms.render_home("cua-driver-mcp", root / "missing", "m", "high")def test_exec_flags_are_identical_across_arms(self) -> None:argv = arms.codex_argv(Path("/w"), "m")@@ -202,6 +261,57 @@ class ArmsTest(unittest.TestCase):class ScheduleTest(unittest.TestCase):+ def test_pilot_rows_and_manifest_record_auth_mode(self) -> None:+ import run_pilot++ args = argparse.Namespace(+ model="m", effort="high", idle_min=0, max_idle_wait_h=1, no_sentinel=True+ )+ task = argparse.Namespace(id="T", group="bench", tags=[], timeout_s=60)+ for mode, replaced in (("gateway", False), ("chatgpt", False), ("chatgpt", True)):++ def fail_setup(compare, task, trial_dir, workspace):+ home = trial_dir / "home/.codex"+ home.mkdir(parents=True)+ arms.link_chatgpt_auth(home)+ if replaced:+ (home / "auth.json").unlink()+ (home / "auth.json").write_text("FAKE_TOKEN")+ raise RuntimeError("unavailable fixture")++ with (+ tempfile.TemporaryDirectory() as tmp,+ mock.patch.dict(+ os.environ,+ {+ "CDB_CODEX_AUTH": mode,+ "CDB_CODEX_AUTH_FILE": str(Path(tmp) / "shared-auth.json"),+ },+ ),+ mock.patch.object(run_pilot, "wait_for_idle", return_value=1000),+ mock.patch.object(run_pilot, "Sentinel") as sentinel,+ mock.patch.object(run_pilot, "prepare_bench", side_effect=fail_setup),+ mock.patch.object(run_pilot, "sweep_processes"),+ mock.patch.object(run_pilot.subprocess, "run") as command,+ ):+ source = Path(tmp) / "shared-auth.json"+ source.write_text("FAKE_TOKEN")+ sentinel.return_value.enabled = False+ sentinel.return_value.summary.return_value = {}+ command.return_value.stdout = "version"+ row = run_pilot.run_trial(+ args, None, task, "codex-native-cu", 1, 0, Path(tmp), None+ )+ manifest = run_pilot.environment_manifest(args)+ self.assertEqual(row["codex_auth"], mode)+ self.assertEqual(manifest["codex_auth"], mode)+ saved = json.loads(next((Path(tmp) / "trials").glob("*/trial.json")).read_text())+ self.assertEqual(saved["codex_auth"], mode)+ if replaced:+ self.assertIn("symlink replaced", row["notes"])+ for secret in (str(source), "FAKE_TOKEN", "http://127.0.0.1:4000/v1"):+ self.assertNotIn(secret, json.dumps([row, manifest, saved]))+def test_schedule_is_deterministic_and_balanced(self) -> None:sys.path.insert(0, str(HERE.parent))import run_pilotdiff --git a/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_runner_flow.py b/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_runner_flow.pyindex 0e79fba955..063b1a373d 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_runner_flow.py+++ b/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_runner_flow.py@@ -8,6 +8,7 @@ finalize. No GUI, no model."""from __future__ import annotationsimport argparse+import contextlibimport jsonimport sysimport tempfile@@ -50,6 +51,7 @@ def make_ctx(tmp: str, **overrides: object) -> rb.Ctx:phase2_runs=0,schedule_seed=1,build_dir=None,+ offline=False,)for key, value in overrides.items():setattr(args, key, value)@@ -67,6 +69,171 @@ def make_ctx(tmp: str, **overrides: object) -> rb.Ctx:return ctx+class CodexAuthPreflightTest(unittest.TestCase):+ def test_chatgpt_checks_metadata_not_gateway_or_model_and_skips_offline(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ ctx = make_ctx(tmp)+ arm = "cx-codex-cu"+ mcp = Path(tmp) / "mcp.json"+ mcp.write_text(+ json.dumps(+ {+ "mcpServers": {+ "sky": {+ "command": "node",+ "env": {"CUA_REPL_ENABLED_SURFACES": "computer"},+ }+ }+ }+ )+ )+ ctx.mcp[arm] = (mcp, "cua_repl")+ source = Path(tmp) / "auth.json"+ source.touch()+ with (+ mock.patch.dict(+ "os.environ", {"CDB_CODEX_AUTH": "chatgpt", "CDB_CODEX_AUTH_FILE": str(source)}+ ),+ mock.patch(+ "urllib.request.urlopen", side_effect=AssertionError("gateway called")+ ) as gateway,+ mock.patch.object(+ rb.cxn, "run_codex", side_effect=AssertionError("model called")+ ) as model,+ mock.patch.object(+ rb.cxn, "chatgpt_checks", return_value=[("metadata", "pass", "ok")]+ ) as probe,+ ):+ checks = rb.native_codex_checks(ctx, arm, with_models=True)+ self.assertIn(("metadata", "pass", "ok"), checks)+ env = probe.call_args.args[1]+ self.assertFalse((Path(env["CODEX_HOME"]) / "auth.json").is_symlink())+ probe.reset_mock()+ rb.native_codex_checks(ctx, "cx-cua-driver", with_models=False)+ probe.assert_not_called()+ ctx.versions.pop("codex_auth_checks")+ rb.native_codex_checks(ctx, arm, with_models=False)+ probe.assert_called_once()+ probe.reset_mock()+ ctx.args.offline = True+ rb.native_codex_checks(ctx, arm, with_models=False)+ probe.assert_not_called()+ gateway.assert_not_called()+ model.assert_not_called()+ ctx.args.offline = False+ ctx.versions.pop("codex_auth_checks")++ def replace_credentials(cli, env, model):+ link = Path(env["CODEX_HOME"]) / "auth.json"+ link.unlink()+ link.write_text("FAKE_TOKEN")+ return [("metadata", "pass", "ok")]++ probe.side_effect = replace_credentials+ checks = rb.native_codex_checks(ctx, arm, with_models=False)+ self.assertTrue(any(status == "fail" for _, status, _ in checks))+ for secret in (str(source), "FAKE_TOKEN", rb.cxn.gateway()):+ self.assertNotIn(secret, json.dumps(checks))++ def test_native_trial_removes_auth_link_and_flags_replacement(self) -> None:+ for replaced in (False, True):+ with tempfile.TemporaryDirectory() as tmp, contextlib.ExitStack() as stack:+ ctx = make_ctx(+ tmp,+ timeout_s=60,+ max_turns=3,+ effort="low",+ idle_min=0,+ no_sentinel=True,+ build_dir=tmp,+ check_occlusion=False,+ tell_budget=False,+ )+ ctx.tasks["MB-01"] = argparse.Namespace(id="MB-01", tags=[], timeout_s=60)+ arm = "cx-codex-cu"+ entry = {**ENTRY, "arm": arm}+ source = Path(tmp) / "shared-auth.json"+ source.write_text("FAKE_TOKEN")+ mcp = Path(tmp) / "mcp.json"+ mcp.write_text(+ json.dumps(+ {+ "mcpServers": {+ "sky": {+ "command": "node",+ "env": {"CUA_REPL_ENABLED_SURFACES": "computer"},+ }+ }+ }+ )+ )+ ctx.mcp[arm] = (mcp, "cua_repl")+ stack.enter_context(+ mock.patch.dict(+ "os.environ",+ {"CDB_CODEX_AUTH": "chatgpt", "CDB_CODEX_AUTH_FILE": str(source)},+ )+ )+ ctx.versions["codex_native"] = rb.cxn.observed(Path("/nonexistent"))+ for owner, name, result in (+ (rb, "task_spec", {}),+ (rb, "kill_bench_apps", None),+ (rb, "reset_needs_apps", None),+ (rb.subprocess, "run", None),+ (rb.pilot, "hid_idle_seconds", 1000),+ (rb.pilot, "sweep_processes", 0),+ (rb.pilot, "prepare_probe", ("BRIEF", {})),+ (rb.pilot, "launch_lab", None),+ (rb.ca, "prepare_cwd", Path(tmp)),+ (rb, "apps_running", {}),+ (rb, "evaluate_probe", {"passed": True}),+ (rb, "FrontWatcher", None),+ ):+ stack.enter_context(mock.patch.object(owner, name, return_value=result))+ sentinel = stack.enter_context(mock.patch.object(rb.pilot, "Sentinel"))+ sentinel.return_value.enabled = False+ sentinel.return_value.summary.return_value = {}+ stack.enter_context(mock.patch.object(rb.pilot, "IdleSampler"))++ def run_codex(cmd, env, *args, **kwargs):+ link = Path(env["CODEX_HOME"]) / "auth.json"+ self.assertTrue(link.is_symlink())+ if replaced:+ link.unlink()+ link.write_text("FAKE_TOKEN")+ return {"returncode": 0, "result_seen": True, "wall_s": 0}++ stack.enter_context(mock.patch.object(rb.cxn, "run_codex", side_effect=run_codex))+ row = rb.run_attempt(ctx, entry, 1)+ self.assertEqual(row["infra_failure"] == "harness_exception", replaced)+ if replaced:+ self.assertIn("symlink replaced", row["infra_message"])+ link = ctx.run_dir / "trials" / entry["trial_id"] / "a1/codex-home/.codex/auth.json"+ self.assertFalse(link.is_symlink())+ self.assertEqual(row["codex_native"]["codex_auth"], "chatgpt")+ saved = link.parents[2] / "trial.json"+ for secret in (str(source), "FAKE_TOKEN", rb.cxn.gateway()):+ self.assertNotIn(secret, saved.read_text())++ def test_gateway_retains_model_listing_even_offline(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ ctx = make_ctx(tmp)+ with (+ mock.patch.dict("os.environ", {"CDB_CODEX_AUTH": "gateway"}),+ mock.patch("urllib.request.urlopen") as fetch,+ ):+ fetch.return_value.__enter__.return_value.read.return_value = json.dumps(+ {"data": [{"id": rb.cxn.MODEL}]}+ ).encode()+ ctx.args.offline = True+ checks = rb.native_codex_checks(ctx, "cx-codex-cu", with_models=False)+ self.assertIn(+ "gateway lists the model",+ [label for label, status, _ in checks if status == "pass"],+ )+ fetch.assert_called_once()++def attempt_row(attempt: int,infra: str | None = None,