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
feat(computer): support explicit api_base_url + headers for proxied computer-server (#1932)
r33drichards6bffa9873b52
diff --git a/libs/python/computer/computer/computer.py b/libs/python/computer/computer/computer.pyindex f73fa9d8d0..fb07c4db9f 100644--- a/libs/python/computer/computer/computer.py+++ b/libs/python/computer/computer/computer.py@@ -110,6 +110,8 @@ class Computer:storage: Optional[str] = None,ephemeral: bool = False,api_key: Optional[str] = None,+ api_base_url: Optional[str] = None,+ api_headers: Optional[Dict[str, str]] = None,experiments: Optional[List[str]] = None,timeout: int = 100,backend: Literal["native", "vnc"] = "native",@@ -145,6 +147,16 @@ class Computer:storage: Optional path for persistent VM storage (Lumier provider)ephemeral: Whether to use ephemeral storageapi_key: Optional API key for cloud providers (defaults to CUA_API_KEY environment variable)+ api_base_url: Optional explicit base URL of the computer-server to connect to+ directly, e.g. when it sits behind an authenticated, path-prefixed reverse+ proxy such as ``https://run.cua.ai/api/svc/<ns>/<sandbox>-api``. Only used+ with ``use_host_computer_server=True``. When set, the SDK derives the REST+ (``<base>/cmd``) and WebSocket (``wss://.../ws``) URLs from this base+ instead of building them from ``api_host`` + ``api_port``. Defaults to the+ ``CUA_API_BASE_URL`` environment variable.+ api_headers: Optional dict of extra HTTP headers (e.g.+ ``{"Authorization": "Bearer <token>"}``) sent on every REST request and on+ the WebSocket upgrade, for connecting through an authenticated proxy.experiments: Optional list of experimental features to enable (e.g. ["app-use"])timeout: Timeout in seconds for connecting to the computer interfacebackend: Handler backend for the computer-server: 'native' (OS-specific) or 'vnc'. Defaults to 'native'.@@ -168,6 +180,10 @@ class Computer:if api_key is None:api_key = os.environ.get("CUA_API_KEY")+ # Fall back to environment variable for api_base_url if not provided (mirrors api_key)+ if api_base_url is None:+ api_base_url = os.environ.get("CUA_API_BASE_URL")+if not image:if os_type == "macos":image = "macos-sequoia-cua:latest"@@ -182,6 +198,8 @@ class Computer:self.noVNC_port = noVNC_portself.api_port = api_portself.api_host = api_host+ self.api_base_url = api_base_url+ self.api_headers = api_headers or {}self.os_type = os_typeself.provider_type = provider_typeself.ephemeral = ephemeral@@ -358,23 +376,11 @@ class Computer:# If using host computer serverif self.use_host_computer_server:self.logger.info("Using host computer server")- # Set ip_address for host computer server mode+ # Set ip_address for host computer server mode; the interface is+ # created+connected by the unified block below (which threads+ # api_base_url/api_headers through), so we only resolve the target+ # here and avoid a redundant double-connect.ip_address = self.api_host if self.api_host else "localhost"- # Create the interface with explicit type annotation- from .interface.base import BaseComputerInterface-- interface = cast(- BaseComputerInterface,- InterfaceFactory.create_interface_for_os(- os=self.os_type, ip_address=ip_address, api_port=self.api_port # type: ignore[arg-type]- ),- )- self._interface = interface- self._original_interface = interface-- self.logger.info("Waiting for host computer server to be ready...")- await self._interface.wait_for_ready()- self.logger.info("Host computer server ready")else:# Start or connect to VMself.logger.info(f"Starting VM: {self.image}")@@ -637,13 +643,19 @@ class Computer:api_key=self.api_key,vm_name=self.config.name,api_port=self.api_port,+ api_base_url=self.api_base_url,+ api_headers=self.api_headers,),)else:interface = cast(BaseComputerInterface,InterfaceFactory.create_interface_for_os(- os=self.os_type, ip_address=ip_address, api_port=self.api_port+ os=self.os_type,+ ip_address=ip_address,+ api_port=self.api_port,+ api_base_url=self.api_base_url,+ api_headers=self.api_headers,),)diff --git a/libs/python/computer/computer/interface/android.py b/libs/python/computer/computer/interface/android.pyindex dbc5708a94..cf0ce9cfa6 100644--- a/libs/python/computer/computer/interface/android.py+++ b/libs/python/computer/computer/interface/android.py@@ -1,4 +1,4 @@-from typing import Optional+from typing import Dict, Optionalfrom .generic import GenericComputerInterface@@ -14,7 +14,17 @@ class AndroidComputerInterface(GenericComputerInterface):api_key: Optional[str] = None,vm_name: Optional[str] = None,api_port: Optional[int] = None,+ api_base_url: Optional[str] = None,+ api_headers: Optional[Dict[str, str]] = None,):super().__init__(- ip_address, username, password, api_key, vm_name, "computer.interface.android", api_port+ ip_address,+ username,+ password,+ api_key,+ vm_name,+ "computer.interface.android",+ api_port,+ api_base_url=api_base_url,+ api_headers=api_headers,)diff --git a/libs/python/computer/computer/interface/factory.py b/libs/python/computer/computer/interface/factory.pyindex e2f3b5316c..36dfa21239 100644--- a/libs/python/computer/computer/interface/factory.py+++ b/libs/python/computer/computer/interface/factory.py@@ -1,6 +1,6 @@"""Factory for creating computer interfaces."""-from typing import Literal, Optional+from typing import Dict, Literal, Optionalfrom .base import BaseComputerInterface@@ -17,6 +17,8 @@ class InterfaceFactory:api_port: Optional[int] = None,api_key: Optional[str] = None,vm_name: Optional[str] = None,+ api_base_url: Optional[str] = None,+ api_headers: Optional[Dict[str, str]] = None,) -> BaseComputerInterface:"""Create an interface for the specified OS.@@ -26,6 +28,11 @@ class InterfaceFactory:api_port: Optional API port of the computer to controlapi_key: Optional API key for cloud authenticationvm_name: Optional VM name for cloud authentication+ api_base_url: Optional explicit base URL for the computer-server, e.g. when+ it sits behind an authenticated, path-prefixed reverse proxy. When set,+ REST/WebSocket URIs are derived from it instead of ip_address + port.+ api_headers: Optional extra HTTP headers (e.g. ``Authorization: Bearer ...``)+ sent on every REST request and the WebSocket upgrade.Returns:BaseComputerInterface: The appropriate interface for the OS@@ -34,29 +41,29 @@ class InterfaceFactory:ValueError: If the OS type is not supported"""+ common_kwargs = dict(+ api_key=api_key,+ vm_name=vm_name,+ api_port=api_port,+ api_base_url=api_base_url,+ api_headers=api_headers,+ )+if os == "macos":from .macos import MacOSComputerInterface- return MacOSComputerInterface(- ip_address, api_key=api_key, vm_name=vm_name, api_port=api_port- )+ return MacOSComputerInterface(ip_address, **common_kwargs)elif os == "linux":from .linux import LinuxComputerInterface- return LinuxComputerInterface(- ip_address, api_key=api_key, vm_name=vm_name, api_port=api_port- )+ return LinuxComputerInterface(ip_address, **common_kwargs)elif os == "windows":from .windows import WindowsComputerInterface- return WindowsComputerInterface(- ip_address, api_key=api_key, vm_name=vm_name, api_port=api_port- )+ return WindowsComputerInterface(ip_address, **common_kwargs)elif os == "android":from .android import AndroidComputerInterface- return AndroidComputerInterface(- ip_address, api_key=api_key, vm_name=vm_name, api_port=api_port- )+ return AndroidComputerInterface(ip_address, **common_kwargs)else:raise ValueError(f"Unsupported OS type: {os}")diff --git a/libs/python/computer/computer/interface/generic.py b/libs/python/computer/computer/interface/generic.pyindex 2c12e15242..cc7d43176d 100644--- a/libs/python/computer/computer/interface/generic.py+++ b/libs/python/computer/computer/interface/generic.py@@ -32,6 +32,8 @@ class GenericComputerInterface(BaseComputerInterface):vm_name: Optional[str] = None,logger_name: str = "computer.interface.generic",api_port: Optional[int] = None,+ api_base_url: Optional[str] = None,+ api_headers: Optional[Dict[str, str]] = None,):super().__init__(ip_address, username, password, api_key, vm_name)self._ws = None@@ -52,6 +54,14 @@ class GenericComputerInterface(BaseComputerInterface):# Store custom portsself._api_port = api_port+ # Optional explicit base URL (e.g. behind an authenticated reverse proxy with a+ # path prefix) and arbitrary extra headers (e.g. ``Authorization: Bearer ...``).+ # When ``api_base_url`` is set, the REST/WebSocket URIs are derived from it+ # (preserving its scheme, host, port and path prefix) instead of being rebuilt+ # from ``ip_address`` + port.+ self._api_base_url = api_base_url.rstrip("/") if api_base_url else None+ self._api_headers = dict(api_headers) if api_headers else {}+# Optional default delay time between commands (in seconds)self.delay = 0.0@@ -67,13 +77,48 @@ class GenericComputerInterface(BaseComputerInterface):elif isinstance(self.delay, float) or isinstance(self.delay, int) and self.delay > 0:await asyncio.sleep(self.delay)+ @staticmethod+ def _ws_headers_kwarg() -> str:+ """Return the websockets.connect kwarg used to pass custom upgrade headers.++ websockets>=11 renamed ``extra_headers`` to ``additional_headers`` (the old+ name was removed in 14.0). Detect which one the installed version accepts.+ """+ import inspect++ try:+ params = inspect.signature(websockets.connect).parameters+ except (TypeError, ValueError):+ params = {}+ if "additional_headers" in params:+ return "additional_headers"+ return "extra_headers"++ @staticmethod+ def _base_url_to_ws(base_url: str) -> str:+ """Convert an http(s) base URL to its ws(s) equivalent, preserving the path prefix."""+ if base_url.startswith("https://"):+ return "wss://" + base_url[len("https://") :]+ if base_url.startswith("http://"):+ return "ws://" + base_url[len("http://") :]+ # No recognized scheme; assume it is already a ws(s) URL.+ return base_url+@propertydef ws_uri(self) -> str:- """Get the WebSocket URI using the current IP address.+ """Get the WebSocket URI for the Computer API Server.++ When an explicit ``api_base_url`` was provided (e.g. an authenticated,+ path-prefixed reverse proxy), the URI is derived from it by swapping the+ scheme to ws(s) and appending ``/ws`` to the full path prefix. Otherwise+ the URI is rebuilt from ``ip_address`` + port as before.Returns:WebSocket URI for the Computer API Server"""+ if self._api_base_url:+ return f"{self._base_url_to_ws(self._api_base_url)}/ws"+protocol = "wss" if self.api_key else "ws"# Use custom API port if provided, otherwise use defaults based on API keyport = (@@ -85,11 +130,18 @@ class GenericComputerInterface(BaseComputerInterface):@propertydef rest_uri(self) -> str:- """Get the REST URI using the current IP address.+ """Get the REST URI for the Computer API Server.++ When an explicit ``api_base_url`` was provided, the URI is derived from it+ by appending ``/cmd`` to the full path prefix. Otherwise the URI is rebuilt+ from ``ip_address`` + port as before.Returns:REST URI for the Computer API Server"""+ if self._api_base_url:+ return f"{self._api_base_url}/cmd"+protocol = "https" if self.api_key else "http"# Use custom API port if provided, otherwise use defaults based on API keyport = (@@ -764,9 +816,12 @@ class GenericComputerInterface(BaseComputerInterface):# Web searchawait interface.playwright_exec("web_search", {"query": "computer use agent"})"""- protocol = "https" if self.api_key else "http"- port = str(self._api_port) if self._api_port else ("8443" if self.api_key else "8000")- url = f"{protocol}://{self.ip_address}:{port}/playwright_exec"+ if self._api_base_url:+ url = f"{self._api_base_url}/playwright_exec"+ else:+ protocol = "https" if self.api_key else "http"+ port = str(self._api_port) if self._api_port else ("8443" if self.api_key else "8000")+ url = f"{protocol}://{self.ip_address}:{port}/playwright_exec"payload = {"command": command, "params": params or {}}headers = {"Content-Type": "application/json", **cua_version_headers()}@@ -774,6 +829,9 @@ class GenericComputerInterface(BaseComputerInterface):headers["X-API-Key"] = self.api_keyif self.vm_name:headers["X-Container-Name"] = self.vm_name+ # Merge arbitrary extra headers (e.g. ``Authorization: Bearer ...``) last so+ # callers can override defaults if needed.+ headers.update(self._api_headers)try:async with aiohttp.ClientSession() as session:@@ -821,16 +879,24 @@ class GenericComputerInterface(BaseComputerInterface):f"Attempting WebSocket connection to {self.ws_uri} (attempt {retry_count})")+ connect_kwargs = dict(+ max_size=1024 * 1024 * 10, # 10MB limit+ max_queue=32,+ ping_interval=self._ping_interval,+ ping_timeout=self._ping_timeout,+ close_timeout=5,+ compression=None, # Disable compression to reduce overhead+ )+ # Send arbitrary extra headers (e.g. ``Authorization: Bearer ...``)+ # on the WebSocket upgrade request so proxies that authenticate the+ # upgrade can accept the connection. Newer websockets versions use+ # ``additional_headers``; older ones use ``extra_headers``.+ if self._api_headers:+ connect_kwargs[self._ws_headers_kwarg()] = list(+ self._api_headers.items()+ )self._ws = await asyncio.wait_for(- websockets.connect(- self.ws_uri,- max_size=1024 * 1024 * 10, # 10MB limit- max_queue=32,- ping_interval=self._ping_interval,- ping_timeout=self._ping_timeout,- close_timeout=5,- compression=None, # Disable compression to reduce overhead- ),+ websockets.connect(self.ws_uri, **connect_kwargs),timeout=120,)self.logger.info("WebSocket connection established")@@ -1015,10 +1081,14 @@ class GenericComputerInterface(BaseComputerInterface):headers["X-API-Key"] = self.api_keyif self.vm_name:headers["X-Container-Name"] = self.vm_name+ # Merge arbitrary extra headers (e.g. ``Authorization: Bearer ...``).+ headers.update(self._api_headers)# Send the requestasync with aiohttp.ClientSession() as session:- async with session.post(self.rest_uri, json=payload, headers=headers) as response:+ async with session.post(+ self.rest_uri, json=payload, headers=headers+ ) as response:# Get the response textresponse_text = await response.text()@@ -1027,8 +1097,10 @@ class GenericComputerInterface(BaseComputerInterface):# Empty body: proxy cut off the streaming response; retryif not response_text and attempt < max_empty_retries - 1:- self.logger.warning(f"[REST] empty body for cmd={command} attempt={attempt}, retrying")- await asyncio.sleep(2 ** attempt)+ self.logger.warning(+ f"[REST] empty body for cmd={command} attempt={attempt}, retrying"+ )+ await asyncio.sleep(2**attempt)continue# Check if it starts with "data: "@@ -1038,14 +1110,18 @@ class GenericComputerInterface(BaseComputerInterface):try:return json.loads(json_str)except json.JSONDecodeError:- self.logger.warning(f"[REST] JSON decode error for cmd={command} body={response_text[:200]!r}")+ self.logger.warning(+ f"[REST] JSON decode error for cmd={command} body={response_text[:200]!r}"+ )return {"success": False,"error": "Server returned malformed response","message": response_text,}else:- self.logger.warning(f"[REST] unexpected response cmd={command} status={response.status} body={response_text[:300]!r}")+ self.logger.warning(+ f"[REST] unexpected response cmd={command} status={response.status} body={response_text[:300]!r}"+ )# Return error responsereturn {"success": False,@@ -1054,7 +1130,9 @@ class GenericComputerInterface(BaseComputerInterface):}except Exception as e:- self.logger.warning(f"[REST] exception cmd={command} attempt={attempt} {type(e).__name__}: {e}")+ self.logger.warning(+ f"[REST] exception cmd={command} attempt={attempt} {type(e).__name__}: {e}"+ )return {"success": False, "error": "Request failed", "message": str(e)}return {"success": False, "error": "Server returned malformed response", "message": ""}diff --git a/libs/python/computer/computer/interface/linux.py b/libs/python/computer/computer/interface/linux.pyindex 2dc2a5e737..51654af458 100644--- a/libs/python/computer/computer/interface/linux.py+++ b/libs/python/computer/computer/interface/linux.py@@ -1,4 +1,4 @@-from typing import Optional+from typing import Dict, Optionalfrom .generic import GenericComputerInterface@@ -14,7 +14,17 @@ class LinuxComputerInterface(GenericComputerInterface):api_key: Optional[str] = None,vm_name: Optional[str] = None,api_port: Optional[int] = None,+ api_base_url: Optional[str] = None,+ api_headers: Optional[Dict[str, str]] = None,):super().__init__(- ip_address, username, password, api_key, vm_name, "computer.interface.linux", api_port+ ip_address,+ username,+ password,+ api_key,+ vm_name,+ "computer.interface.linux",+ api_port,+ api_base_url=api_base_url,+ api_headers=api_headers,)diff --git a/libs/python/computer/computer/interface/macos.py b/libs/python/computer/computer/interface/macos.pyindex 10783c2f48..3a9b4ff979 100644--- a/libs/python/computer/computer/interface/macos.py+++ b/libs/python/computer/computer/interface/macos.py@@ -1,4 +1,4 @@-from typing import Optional+from typing import Dict, Optionalfrom .generic import GenericComputerInterface@@ -14,9 +14,19 @@ class MacOSComputerInterface(GenericComputerInterface):api_key: Optional[str] = None,vm_name: Optional[str] = None,api_port: Optional[int] = None,+ api_base_url: Optional[str] = None,+ api_headers: Optional[Dict[str, str]] = None,):super().__init__(- ip_address, username, password, api_key, vm_name, "computer.interface.macos", api_port+ ip_address,+ username,+ password,+ api_key,+ vm_name,+ "computer.interface.macos",+ api_port,+ api_base_url=api_base_url,+ api_headers=api_headers,)async def diorama_cmd(self, action: str, arguments: Optional[dict] = None) -> dict:diff --git a/libs/python/computer/computer/interface/windows.py b/libs/python/computer/computer/interface/windows.pyindex 918e7acea0..8b1bb3d4dc 100644--- a/libs/python/computer/computer/interface/windows.py+++ b/libs/python/computer/computer/interface/windows.py@@ -1,4 +1,4 @@-from typing import Optional+from typing import Dict, Optionalfrom .generic import GenericComputerInterface@@ -14,7 +14,17 @@ class WindowsComputerInterface(GenericComputerInterface):api_key: Optional[str] = None,vm_name: Optional[str] = None,api_port: Optional[int] = None,+ api_base_url: Optional[str] = None,+ api_headers: Optional[Dict[str, str]] = None,):super().__init__(- ip_address, username, password, api_key, vm_name, "computer.interface.windows", api_port+ ip_address,+ username,+ password,+ api_key,+ vm_name,+ "computer.interface.windows",+ api_port,+ api_base_url=api_base_url,+ api_headers=api_headers,)diff --git a/libs/python/computer/tests/test_interface_proxy.py b/libs/python/computer/tests/test_interface_proxy.pynew file mode 100644index 0000000000..9e2783edcf--- /dev/null+++ b/libs/python/computer/tests/test_interface_proxy.py@@ -0,0 +1,124 @@+"""Unit tests for direct-proxy support in the computer interface.++These tests verify that passing an explicit ``api_base_url`` (plus arbitrary+``api_headers``) makes the interface derive its REST/WebSocket/Playwright URLs+from that base URL -- preserving scheme, host, port and path prefix -- and sends+the extra headers. This is what allows connecting directly to a computer-server+behind an authenticated, path-prefixed reverse proxy (e.g. cyclops-cs) without a+localhost forwarder.++Following SRP: This file tests ONLY URL building and header propagation for the+interface layer.+"""++import pytest+from computer.interface.factory import InterfaceFactory+from computer.interface.windows import WindowsComputerInterface++PROXY_BASE = "https://run.cua.ai/api/svc/ns/sb-api"+++class TestApiBaseUrlBuilding:+ """api_base_url should fully drive REST/WS/Playwright URLs."""++ def test_rest_uri_uses_base_url(self):+ iface = WindowsComputerInterface(+ "ignored-ip", api_base_url=PROXY_BASE, api_headers={"Authorization": "Bearer t"}+ )+ assert iface.rest_uri == f"{PROXY_BASE}/cmd"++ def test_ws_uri_swaps_scheme_and_keeps_prefix(self):+ iface = WindowsComputerInterface("ignored-ip", api_base_url=PROXY_BASE)+ assert iface.ws_uri == "wss://run.cua.ai/api/svc/ns/sb-api/ws"++ def test_trailing_slash_is_stripped(self):+ iface = WindowsComputerInterface("ignored-ip", api_base_url=PROXY_BASE + "/")+ assert iface.rest_uri == f"{PROXY_BASE}/cmd"+ assert iface.ws_uri == "wss://run.cua.ai/api/svc/ns/sb-api/ws"++ def test_http_base_maps_to_ws(self):+ iface = WindowsComputerInterface("ignored-ip", api_base_url="http://localhost:9999/prefix")+ assert iface.rest_uri == "http://localhost:9999/prefix/cmd"+ assert iface.ws_uri == "ws://localhost:9999/prefix/ws"++ def test_api_headers_stored(self):+ headers = {"Authorization": "Bearer secret"}+ iface = WindowsComputerInterface("ignored-ip", api_base_url=PROXY_BASE, api_headers=headers)+ assert iface._api_headers == headers++ def test_factory_threads_params(self):+ iface = InterfaceFactory.create_interface_for_os(+ os="windows",+ ip_address="ignored-ip",+ api_base_url=PROXY_BASE,+ api_headers={"Authorization": "Bearer t"},+ )+ assert iface.rest_uri == f"{PROXY_BASE}/cmd"+ assert iface.ws_uri == "wss://run.cua.ai/api/svc/ns/sb-api/ws"+ assert iface._api_headers == {"Authorization": "Bearer t"}+++class TestBackwardCompatibility:+ """Without api_base_url, behavior is unchanged (ip_address + port)."""++ def test_no_base_url_local(self):+ iface = WindowsComputerInterface("192.168.1.5")+ assert iface.rest_uri == "http://192.168.1.5:8000/cmd"+ assert iface.ws_uri == "ws://192.168.1.5:8000/ws"+ assert iface._api_headers == {}++ def test_no_base_url_with_api_key(self):+ iface = WindowsComputerInterface("192.168.1.5", api_key="abc", vm_name="vm")+ assert iface.rest_uri == "https://192.168.1.5:8443/cmd"+ assert iface.ws_uri == "wss://192.168.1.5:8443/ws"++ def test_no_base_url_custom_port(self):+ iface = WindowsComputerInterface("192.168.1.5", api_port=1234)+ assert iface.rest_uri == "http://192.168.1.5:1234/cmd"+ assert iface.ws_uri == "ws://192.168.1.5:1234/ws"+++class TestRestHeaderMerging:+ """api_headers must be merged into REST requests."""++ @pytest.mark.asyncio+ async def test_send_command_rest_sends_headers(self, monkeypatch):+ captured = {}++ class FakeResp:+ status = 200++ async def __aenter__(self):+ return self++ async def __aexit__(self, *a):+ return False++ async def text(self):+ return 'data: {"success": true}'++ class FakeSession:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *a):+ return False++ def post(self, url, json=None, headers=None):+ captured["url"] = url+ captured["headers"] = headers+ return FakeResp()++ import aiohttp++ monkeypatch.setattr(aiohttp, "ClientSession", lambda *a, **k: FakeSession())++ iface = WindowsComputerInterface(+ "ignored-ip",+ api_base_url=PROXY_BASE,+ api_headers={"Authorization": "Bearer secret"},+ )+ result = await iface._send_command_rest("version", {})+ assert result.get("success") is True+ assert captured["url"] == f"{PROXY_BASE}/cmd"+ assert captured["headers"]["Authorization"] == "Bearer secret"