Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(sandbox): OSWorld disks on Fleet via agent_type="osworld" + "Run OSWorld on Fleet" guide (#3686)

ddupontdb8ba214b6fb
diff --git a/docs/content/docs/how-to-guides/sandbox/meta.json b/docs/content/docs/how-to-guides/sandbox/meta.json
index 38ca4ec765..867fea0e4c 100644
--- a/docs/content/docs/how-to-guides/sandbox/meta.json
+++ b/docs/content/docs/how-to-guides/sandbox/meta.json
@@ -23,6 +23,7 @@
"run-openclaw-on-cloud-fleet",
"run-omarchy-on-cloud-fleet",
"connect-to-omarchy-with-novnc",
+ "run-osworld-on-cloud-fleet",
"minecraft",
"---Cua Fleets: Images---",
"prepare-and-reference-a-fleet-image",
diff --git a/docs/content/docs/how-to-guides/sandbox/run-osworld-on-cloud-fleet.mdx b/docs/content/docs/how-to-guides/sandbox/run-osworld-on-cloud-fleet.mdx
new file mode 100644
index 0000000000..b07d6bf31e
--- /dev/null
+++ b/docs/content/docs/how-to-guides/sandbox/run-osworld-on-cloud-fleet.mdx
@@ -0,0 +1,192 @@
+---
+title: Run OSWorld on Fleet
+description: Turn the official OSWorld image into a Fleet containerDisk with Cua Driver inside, claim it from the Sandbox SDK, and run OSWorld tasks against it.
+---
+
+import { Callout } from 'fumadocs-ui/components/callout';
+
+You start from the official [OSWorld](https://osworld-v1.xlang.ai/) Ubuntu disk,
+add the Cua Driver MCP server to it, publish it as a Fleet containerDisk, and
+drive it with the Sandbox SDK. The same script runs the disk locally under QEMU.
+
+<Callout type="info">
+ Needs `Image.from_registry(..., agent_type="osworld")`, available in
+ `cua-sandbox` on `main` after 0.5.0. Until it is released, run scripts with
+ `uv run --with /path/to/cua/libs/python/cua-sandbox`.
+</Callout>
+
+## Before you start
+
+- Python `>=3.11,<3.14`, [`uv`](https://docs.astral.sh/uv/), and Docker.
+- About 60 GB of free disk.
+- [Fleet credentials](/how-to-guides/sandbox/set-up-fleet-credentials) exported
+ as `CUA_CLIENT_ID`, `CUA_CLIENT_SECRET`, and `CUA_TOKEN_URL`.
+- A checkout of the Cua repository, for `samples/python/osworld-image/` and
+ `samples/python/3_osworld_fleet.py`.
+
+## 1. Get the OSWorld image
+
+```bash
+mkdir -p ~/osworld-cua && cd ~/osworld-cua
+curl -fSL --retry 5 -o Ubuntu.qcow2.zip \
+ https://huggingface.co/datasets/xlangai/ubuntu_osworld/resolve/main/Ubuntu.qcow2.zip
+unzip Ubuntu.qcow2.zip && mv Ubuntu.qcow2 base.qcow2
+```
+
+The disk ships Ubuntu 22.04, the auto-login user `user` (password `password`),
+the OSWorld control server on port `5000`, and the benchmark applications. The
+recipe below does not change any of that.
+
+## 2. Add Cua Driver to the image
+
+Download the Linux driver release and copy the `osworld-image/` folder next to it:
+
+```bash
+V=0.26.1
+curl -fsSL -o cua-driver-rs-$V-linux-x86_64-binary.tar.gz \
+ https://github.com/trycua/cua/releases/download/cua-driver-rs-v$V/cua-driver-rs-$V-linux-x86_64-binary.tar.gz
+cp -r /path/to/cua/samples/python/osworld-image .
+```
+
+The folder holds a systemd unit that runs `cua-driver mcp` behind
+[supergateway](https://github.com/supercorp-ai/supergateway) on
+`0.0.0.0:3000/mcp`, a netplan file that gives the guest a DHCP lease under
+KubeVirt, a udev rule that makes `/dev/uinput` writable (needed by the
+driver's isolated-input route), the `virt-customize` recipe, and the
+containerDisk `Dockerfile`.
+
+Build the helper container and run the recipe. It works on an overlay, so
+`base.qcow2` is never modified, and it needs no network inside the guest:
+
+```bash
+docker build -t osworld-guestfs:local osworld-image/guestfs
+docker run --rm --device /dev/kvm -v "$PWD:/work" osworld-guestfs:local \
+ bash /work/osworld-image/build-osworld-cua.sh
+```
+
+Drop `--device /dev/kvm` on hosts without KVM. The result is `disk.img`, a
+compressed qcow2.
+
+## 3. Publish the containerDisk
+
+Fleet boots an OCI image whose only content is the guest disk at
+`/disk/disk.img`. Push it and keep the digest:
+
+```bash
+mkdir ctx && cp disk.img osworld-image/Dockerfile ctx/
+REPO=<registry>/<repo>
+docker build -t $REPO:osworld-cua-driver -f ctx/Dockerfile ctx
+docker push $REPO:osworld-cua-driver
+docker inspect --format '{{index .RepoDigests 0}}' $REPO:osworld-cua-driver
+```
+
+Fleet pulls public registries anonymously and private ECR only for
+allowlisted repositories; a repository outside the allowlist fails at
+`Pool.apply` with `PoolAccessDenied ... k8s request is not allowed`. See
+[Prepare and reference a Fleet image](/how-to-guides/sandbox/prepare-and-reference-a-fleet-image).
+
+## 4. Claim it
+
+`3_osworld_fleet.py` claims the image, takes a screenshot through the OSWorld
+server, and calls a few Cua Driver MCP tools:
+
+```bash
+export OSWORLD_IMAGE="<registry>/<repo>@sha256:<digest>"
+uv run samples/python/3_osworld_fleet.py
+```
+
+The image is declared once; everything else is the normal Sandbox surface.
+`agent_type="osworld"` makes `screenshot()`, `get_dimensions()`, and
+`shell.run()` talk to the OSWorld server on `5000`, and defaults the Fleet
+`server` service to that port. Expose the ports OSWorld's own tooling uses:
+
+```python
+image = Image.from_registry(IMAGE_REF, os_type="linux", kind="vm", agent_type="osworld")
+image = image.expose(5000).expose(3000).expose(8080).expose(9222) # OSWorld, MCP, VLC, Chrome CDP
+
+async with Sandbox.ephemeral(image, cpu=4, memory_mb=8192) as sb:
+ png = await sb.screenshot()
+ r = await sb.services.request("port-3000", method="POST", path="/mcp", json=..., headers=...)
+```
+
+`Sandbox.ephemeral` creates a pool and a claim, then deletes both on exit. For
+a loop over many tasks, create one pool with `Pool.apply(image, name=...,
+replicas=N, services={...})` and claim from it per task instead; a fresh claim
+is how you get a clean desktop, since Fleet has no snapshot revert.
+
+To connect an MCP client (for example the Claude Agent SDK) rather than
+sending single requests, create a signed URL for the `port-3000` service
+([Share a service with a signed URL](/how-to-guides/sandbox/share-service-with-signed-url))
+and pass it as an HTTP MCP server.
+
+### Run an OSWorld task
+
+OSWorld's `SetupController` and evaluators only need an HTTP endpoint for the
+control server plus the two application ports, so point them at the claim:
+
+```python
+from types import SimpleNamespace
+from desktop_env.controllers.python import PythonController
+from desktop_env.controllers.setup import SetupController
+from desktop_env.evaluators import getters, metrics
+
+host, port = "127.0.0.1", sb.exposed_ports[5000] # local; on Fleet use a signed service URL
+env = SimpleNamespace(
+ vm_ip=host, server_port=port, chromium_port=sb.exposed_ports[9222], vlc_port=sb.exposed_ports[8080],
+ cache_dir="cache/" + task["id"], vm_platform="Ubuntu", vm_machine="amd", current_use_proxy=False,
+ getters=getters, action_history=[],
+)
+env.controller = PythonController(host, port)
+env.setup_controller = SetupController(vm_ip=host, server_port=port, chromium_port=env.chromium_port,
+ vlc_port=env.vlc_port, cache_dir=env.cache_dir, client_password="password")
+env.setup_controller.setup(task["config"], False) # downloads happen on your machine and are uploaded
+... run your agent ...
+score = metrics_func(getters_func(env, task["evaluator"]["result"]), ...) # mirror DesktopEnv.evaluate
+```
+
+Wrap setup and evaluation in timeouts: the OSWorld controller has none, and a
+hung desktop otherwise hangs your loop. Agents that work from screenshots
+should downscale the 1920x1080 capture to about 1280 px and scale coordinates
+back, or the model's own image resizing will skew clicks.
+
+## Run it locally
+
+Needs `qemu-system-x86_64` with KVM (on Windows, inside WSL2). Boot an overlay
+so `disk.img` stays clean:
+
+```bash
+qemu-img create -f qcow2 -F qcow2 -b "$PWD/disk.img" osworld-local.qcow2
+OSWORLD_LOCAL=1 OSWORLD_QCOW2="$PWD/osworld-local.qcow2" uv run samples/python/3_osworld_fleet.py
+```
+
+Locally the only code difference is `Image.from_file(QCOW2, os_type="linux",
+agent_type="osworld")`; exposed guest ports appear in `sb.exposed_ports`. The
+local guest has no outbound network, so tasks that need internet inside the
+VM (Chrome, Thunderbird, anything that `apt-get`s during evaluation) only run
+on Fleet.
+
+## Iterate on the image without rebuilding
+
+Upload a new file through the OSWorld server and install it with `sudo`; the
+driver's MCP service restarts in seconds:
+
+```python
+requests.post(f"http://{host}:{port}/setup/upload",
+ data={"file_path": "/home/user/cua-driver.new"}, files={"file_data": open("cua-driver", "rb")})
+await sb.shell.run("echo password | sudo -S bash -c 'install -m755 /home/user/cua-driver.new "
+ "/usr/local/bin/cua-driver && systemctl restart cua-driver-mcp'")
+```
+
+## Troubleshooting
+
+- **Claim never binds, pool stays at `ready_replicas: 0`.** The probe is a TCP
+ check on `5000`. The image is still pulling, or the guest has no lease (the
+ netplan file is missing). Poll `list_pools`/`list_claims` for the namespace;
+ Fleet does not surface VM events. To separate a pull problem from a boot
+ problem, push a known-good containerDisk to the same repository and claim it.
+- **`Fleet cloud supports registry images with optional exposed services only`.**
+ Builder layers are local-only; bake changes into the disk in step 2.
+- **Local boot times out.** The local runtime waits 120 s; the QEMU process is
+ left running, so kill it before retrying.
+- **Port 3000 answers 502.** The MCP unit waits for the X session; read
+ `journalctl -u cua-driver-mcp` through `sb.shell.run()`.
diff --git a/docs/content/docs/reference/sandbox-sdk/image.mdx b/docs/content/docs/reference/sandbox-sdk/image.mdx
index 119e57e985..264c83f99c 100644
--- a/docs/content/docs/reference/sandbox-sdk/image.mdx
+++ b/docs/content/docs/reference/sandbox-sdk/image.mdx
@@ -98,7 +98,7 @@ Android image specification. This constructor does not establish Fleet support.
```python
@classmethod
-def from_registry(cls, ref: str, *, os_type: str = 'linux', kind: Optional[str] = None) -> Image
+def from_registry(cls, ref: str, *, os_type: str = 'linux', kind: Optional[str] = None, agent_type: Optional[str] = None) -> Image
```
Image from an OCI registry reference. `os_type` identifies the guest operating
@@ -110,6 +110,7 @@ until image resolution.
| `ref` | `str` | required | OCI reference for an image appropriate to the selected backend |
| `os_type` | `str` | `'linux'` | Guest OS; use `'windows'` for a Windows disk |
| `kind` | `str or None` | `None` | Explicit `'vm'` or `'container'` kind |
+| `agent_type` | `str or None` | `None` | Guest control server the disk already runs; `'osworld'` selects the OSWorld server on port 5000 (local QEMU and Fleet) instead of computer-server on 8000 |
### Image.from_file
diff --git a/libs/python/cua-sandbox/cua_sandbox/image.py b/libs/python/cua-sandbox/cua_sandbox/image.py
index a186014636..ab5af21251 100644
--- a/libs/python/cua-sandbox/cua_sandbox/image.py
+++ b/libs/python/cua-sandbox/cua_sandbox/image.py
@@ -182,12 +182,17 @@ class Image:
*,
os_type: str = "linux",
kind: Optional[str] = None,
+ agent_type: Optional[str] = None,
) -> Image:
"""Create an image from a registry reference.
os_type selects the firmware: Windows guest disks are built UEFI-only,
so a Windows containerDisk pulled from a registry must say so or it is
handed BIOS and will not boot. kind is resolved after pull when omitted.
+ agent_type names the guest control server the disk already runs, the
+ same hint as ``from_file``: ``"osworld"`` selects the OSWorld Flask
+ server on port 5000 instead of the computer-server on 8000, both for
+ local QEMU and for Fleet pools.
"""
return cls(
os_type=os_type,
@@ -195,6 +200,7 @@ class Image:
version="latest",
kind=kind,
_registry=ref,
+ _agent_type=agent_type,
)
@classmethod
@@ -239,6 +245,7 @@ class Image:
version=data["version"],
kind=data.get("kind"),
_registry=data.get("registry"),
+ _agent_type=data.get("agent_type"),
)
# Replay layers
for layer in data.get("layers", []):
@@ -511,6 +518,8 @@ class Image:
d["files"] = [list(f) for f in self._files]
if self._registry:
d["registry"] = self._registry
+ if self._agent_type:
+ d["agent_type"] = self._agent_type
return d
def to_cloud_init(self) -> str:
diff --git a/libs/python/cua-sandbox/cua_sandbox/pool.py b/libs/python/cua-sandbox/cua_sandbox/pool.py
index 849366659f..1d3a357042 100644
--- a/libs/python/cua-sandbox/cua_sandbox/pool.py
+++ b/libs/python/cua-sandbox/cua_sandbox/pool.py
@@ -7,13 +7,14 @@ from typing import Any, Callable, Coroutine, Generic, TypeVar, cast
from cua_sandbox.image import Image
from cua_sandbox.sandbox import Sandbox
-from cua_sandbox.transport.fleet import FleetTransport
+from cua_sandbox.transport.fleet import fleet_transport_for
from cua_sandbox.transport.fleet_cloud import (
_NATIVE_POOL_ACCESS_DENIED,
FleetCloudTransport,
_canonicalize_pool_access_denied,
_FleetClient,
_pool_access_denied,
+ default_server_port,
validate_ttl_seconds_after_created,
)
from fleet_sdk import (
@@ -120,11 +121,13 @@ class _ClaimHandle:
pool_name: str | None = None,
service: str = "server",
client: Any = None,
+ agent_type: str | None = None,
) -> None:
self.namespace = namespace
self.name = name
self.pool_name = pool_name or namespace
self.service = service
+ self.agent_type = agent_type
self._client = client
def to_dict(self) -> dict[str, Any]:
@@ -135,6 +138,7 @@ class _ClaimHandle:
"pool": self.pool_name,
"claim": self.name,
"service": self.service,
+ **({"agent_type": self.agent_type} if self.agent_type else {}),
}
@classmethod
@@ -146,6 +150,7 @@ class _ClaimHandle:
pool_name=data["pool"],
name=data["claim"],
service=data.get("service", "server"),
+ agent_type=data.get("agent_type"),
)
def _operation_client(self) -> tuple[Any, bool]:
@@ -170,8 +175,9 @@ class _ClaimHandle:
if bound.namespace != self.namespace or bound.claim != self.name:
raise RuntimeError("Fleet returned a sandbox bound to a different claim")
await client.wait_service_ready(bound, service, time_to_start)
+ transport_cls = fleet_transport_for(self.agent_type)
sandbox = Sandbox(
- FleetTransport(sdk=client, bound=bound, service_name=service, owns_sdk=True),
+ transport_cls(sdk=client, bound=bound, service_name=service, owns_sdk=True),
name=bound.name,
)
sandbox._claim_handle = self
@@ -208,9 +214,14 @@ class _ClaimHandle:
class Pool:
"""A Fleet warm pool that can provide durable Sandbox claims."""
- def __init__(self, resource: Any, *, owned_template: Any = None) -> None:
+ def __init__(
+ self, resource: Any, *, owned_template: Any = None, agent_type: str | None = None
+ ) -> None:
self._resource = resource
self._owned_template = owned_template
+ # Guest control-server flavour of the pool's image ("osworld" or None).
+ # Claims need it to pick a transport that speaks the guest's API.
+ self._agent_type = agent_type
@property
def name(self) -> str:
@@ -264,9 +275,10 @@ class Pool:
"names are globally unique across accounts"
)
FleetCloudTransport._validate_image(image)
+ server_port = default_server_port(image)
effective_services = services or {
- "server": 8000,
- **{f"port-{port}": port for port in image._ports if port != 8000},
+ "server": server_port,
+ **{f"port-{port}": port for port in image._ports if port != server_port},
}
transport = FleetCloudTransport(
image=image,
@@ -277,8 +289,10 @@ class Pool:
services=effective_services,
autoscaling=autoscaling,
ttl_seconds_after_created=ttl_seconds_after_created,
+ server_port=server_port,
)
pool = await cls.reconcile(transport._pool_request())
+ pool._agent_type = image._agent_type
try:
template = await Template.reconcile(transport._template_request())
except BaseException:
@@ -337,6 +351,7 @@ class Pool:
namespace=claim.metadata.namespace,
name=claim.metadata.name,
pool_name=self.name,
+ agent_type=self._agent_type,
)
finally:
await client.close()
@@ -349,8 +364,12 @@ class Pool:
service: str = "server",
time_to_start: float | None = None,
ttl_seconds_after_created: int | None = None,
+ agent_type: str | None = None,
) -> _ClaimResult[Sandbox]:
+ """Claim a sandbox. ``agent_type="osworld"`` selects the OSWorld transport
+ for pools fetched with ``Pool.get`` (pools from ``Pool.apply`` remember it)."""
spec = self._claim_spec(spec, ttl_seconds_after_created)
+ claim_agent_type = agent_type or self._agent_type
async def acquire() -> Sandbox:
client = _FleetClient()
@@ -379,6 +398,7 @@ class Pool:
pool_name=self.name,
service=service,
client=client,
+ agent_type=claim_agent_type,
)
return await handle.wait(service=service, time_to_start=time_to_start)
except BaseException:
diff --git a/libs/python/cua-sandbox/cua_sandbox/sandbox.py b/libs/python/cua-sandbox/cua_sandbox/sandbox.py
index 76997034bf..1b9b43bc61 100644
--- a/libs/python/cua-sandbox/cua_sandbox/sandbox.py
+++ b/libs/python/cua-sandbox/cua_sandbox/sandbox.py
@@ -80,7 +80,11 @@ from cua_sandbox.interfaces import (
from cua_sandbox.interfaces.driver import Driver
from cua_sandbox.transport.base import Transport
from cua_sandbox.transport.cloud import CloudTransport
-from cua_sandbox.transport.fleet_cloud import FleetCloudTransport
+from cua_sandbox.transport.fleet_cloud import (
+ FleetCloudTransport,
+ OSWorldFleetCloudTransport,
+ default_server_port,
+)
from cua_sandbox.transport.http import HTTPTransport
from cua_sandbox.transport.websocket import WebSocketTransport
@@ -852,6 +856,7 @@ class Sandbox:
or server_port > 65535
):
raise ValueError("server_port must be an integer between 1 and 65535")
+ server_port = default_server_port(image, server_port)
services = {
"server": server_port,
**{f"port-{port}": port for port in image._ports if port != server_port},
@@ -1478,7 +1483,12 @@ class Sandbox:
if image and not runtime and not local:
# image without runtime and not local → cloud creation
if not any([ws_url, http_url]) and cls._uses_fleet(api_key):
- transport = FleetCloudTransport(
+ transport_cls = (
+ OSWorldFleetCloudTransport
+ if image._agent_type == "osworld"
+ else FleetCloudTransport # module attribute, so tests can patch it
+ )
+ transport = transport_cls(
image=image,
name=name or _random_name(),
cpu=cpu,
@@ -1487,7 +1497,7 @@ class Sandbox:
region=region,
time_to_start=time_to_start,
request_timeout=request_timeout,
- server_port=server_port,
+ server_port=default_server_port(image, server_port),
)
sb = cls(
transport, name=name, _ephemeral=ephemeral, _telemetry_enabled=telemetry_enabled
@@ -1534,7 +1544,16 @@ class Sandbox:
runtime = _auto_runtime(image)
if image and runtime:
sb_name = name or _random_name()
- rt_info = await runtime.start(image, sb_name, ephemeral=bool(ephemeral))
+ # Forward the sizing knobs the caller gave Sandbox.create/ephemeral so a
+ # local VM honours cpu= and memory_mb= the same way a Fleet pool does.
+ start_opts: dict = {}
+ if cpu is not None:
+ start_opts["cpu_count"] = cpu
+ if memory_mb is not None:
+ start_opts["memory_mb"] = memory_mb
+ if disk_gb is not None:
+ start_opts["disk_size_gb"] = disk_gb
+ rt_info = await runtime.start(image, sb_name, ephemeral=bool(ephemeral), **start_opts)
if rt_info.environment == "android" and not rt_info.qmp_port:
if rt_info.grpc_port:
from cua_sandbox.transport.grpc_emulator import (
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/fleet.py b/libs/python/cua-sandbox/cua_sandbox/transport/fleet.py
index ada6c0b4bf..60e2aa1c07 100644
--- a/libs/python/cua-sandbox/cua_sandbox/transport/fleet.py
+++ b/libs/python/cua-sandbox/cua_sandbox/transport/fleet.py
@@ -14,6 +14,7 @@ from cua_sandbox.transport.computer_server import (
normalize_screen_size,
parse_command_response,
)
+from cua_sandbox.transport.osworld import OSWorldOverServiceMixin
from fleet_sdk import HttpHeader, HttpRequest, HttpRequestBuilder
_CMD_MAX_RETRIES = 3
@@ -250,3 +251,12 @@ class FleetTransport(Transport):
return None
response.raise_for_status()
return response.json()
+
+
+class OSWorldFleetTransport(OSWorldOverServiceMixin, FleetTransport):
+ """``FleetTransport`` for a claim whose ``server`` service is the OSWorld Flask API."""
+
+
+def fleet_transport_for(agent_type: Optional[str]) -> type[FleetTransport]:
+ """Pick the Fleet transport class matching an image's ``agent_type`` hint."""
+ return OSWorldFleetTransport if agent_type == "osworld" else FleetTransport
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py b/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
index eb88fdb9c8..0cdf047fc5 100644
--- a/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
+++ b/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
@@ -22,6 +22,7 @@ from cua_sandbox._config import (
from cua_sandbox.image import Image, cloud_registry_image
from cua_sandbox.transport.cyclops_http_client import CyclopsHttpClient
from cua_sandbox.transport.fleet import FleetTransport, build_http_request
+from cua_sandbox.transport.osworld import OSWORLD_SERVER_PORT, OSWorldOverServiceMixin
from fleet_sdk import (
AccessTokenProvider,
AccessTokenProviderError,
@@ -836,3 +837,25 @@ class FleetCloudTransport(FleetTransport):
raise NotImplementedError(
"Fleet cloud supports registry images with optional exposed services only"
)
+
+
+class OSWorldFleetCloudTransport(OSWorldOverServiceMixin, FleetCloudTransport):
+ """``FleetCloudTransport`` whose guest control server is the OSWorld Flask API."""
+
+
+def fleet_cloud_transport_for(image: Optional[Image]) -> type[FleetCloudTransport]:
+ """Pick the provisioning transport class matching an image's ``agent_type`` hint."""
+ if image is not None and image._agent_type == "osworld":
+ return OSWorldFleetCloudTransport
+ return FleetCloudTransport
+
+
+def default_server_port(image: Optional[Image], server_port: int = 8000) -> int:
+ """Resolve the guest control-server port for an image.
+
+ ``server_port`` wins when the caller changed it from the default; otherwise an
+ OSWorld image (``agent_type="osworld"``) selects the OSWorld server on 5000.
+ """
+ if server_port == 8000 and image is not None and image._agent_type == "osworld":
+ return OSWORLD_SERVER_PORT
+ return server_port
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/osworld.py b/libs/python/cua-sandbox/cua_sandbox/transport/osworld.py
index e6dfbde8a4..1553d4f065 100644
--- a/libs/python/cua-sandbox/cua_sandbox/transport/osworld.py
+++ b/libs/python/cua-sandbox/cua_sandbox/transport/osworld.py
@@ -15,6 +15,71 @@ from typing import Any, Dict, Optional
import httpx
from cua_sandbox.transport.base import Transport
+OSWORLD_SERVER_PORT = 5000
+"""Port the OSWorld Flask control server listens on inside the guest."""
+
+
+def normalize_execute_result(payload: Dict[str, Any]) -> Dict[str, Any]:
+ """Shape an OSWorld ``/execute`` (or ``/run_bash_script``) reply like a computer-server result."""
+ returncode = payload.get("returncode")
+ if returncode is None:
+ returncode = 0 if payload.get("status") == "success" else 1
+ return {
+ "stdout": payload.get("output", "") or "",
+ "stderr": payload.get("error", payload.get("message", "")) or "",
+ "returncode": returncode,
+ }
+
+
+class OSWorldOverServiceMixin:
+ """OSWorld Flask API spoken through a Fleet named service.
+
+ Mixed into a ``FleetTransport`` (whose ``_request`` routes HTTP through the
+ Fleet service proxy) so a Fleet claim on an OSWorld disk offers the same
+ ``Sandbox`` surface as the local :class:`OSWorldTransport`: screenshots,
+ screen size, shell commands, and the raw OSWorld actions.
+ """
+
+ async def send(self, action: str, **params: Any) -> Any:
+ if action == "run_command":
+ timeout = float(params.get("timeout", 30))
+ resp = await self._request(
+ "POST",
+ "/execute",
+ json_body={"command": params["command"], "shell": True},
+ timeout=timeout + 5,
+ )
+ resp.raise_for_status()
+ return normalize_execute_result(resp.json())
+ if action in ("execute", "run_bash_script", "run_python"):
+ resp = await self._request("POST", f"/{action}", json_body=params)
+ resp.raise_for_status()
+ return resp.json()
+ if action in ("accessibility", "terminal"):
+ resp = await self._request("GET", f"/{action}")
+ resp.raise_for_status()
+ return resp.json()
+ raise ValueError(f"Unknown action: {action}")
+
+ async def screenshot(self, format: str = "png", quality: int = 95) -> bytes:
+ resp = await self._request("GET", "/screenshot")
+ resp.raise_for_status()
+ from cua_sandbox.transport.base import convert_screenshot
+
+ return convert_screenshot(resp.content, format, quality)
+
+ async def get_screen_size(self) -> Dict[str, int]:
+ resp = await self._request("POST", "/screen_size", json_body={})
+ resp.raise_for_status()
+ data = resp.json()
+ return {"width": int(data["width"]), "height": int(data["height"])}
+
+ async def get_environment(self) -> str:
+ return "linux"
+
+ async def pty_create(self, *args: Any, **kwargs: Any) -> Dict[str, Any]:
+ raise NotImplementedError("the OSWorld server has no PTY endpoint")
+
class OSWorldTransport(Transport):
"""Transport for VMs running the OSWorld Flask server (pyautogui-based)."""
@@ -42,6 +107,19 @@ class OSWorldTransport(Transport):
async def send(self, action: str, **params: Any) -> Any:
assert self._client is not None, "Transport not connected"
+ if action == "run_command":
+ # Sandbox.shell.run() speaks the computer-server vocabulary; map it
+ # onto the OSWorld server's /execute (shell=true), which every
+ # OSWorld server generation exposes (the golden image predates
+ # /run_bash_script).
+ timeout = float(params.get("timeout", 30))
+ resp = await self._client.post(
+ "/execute",
+ json={"command": params["command"], "shell": True},
+ timeout=max(self._timeout, timeout + 5),
+ )
+ resp.raise_for_status()
+ return normalize_execute_result(resp.json())
if action in ("execute", "run_bash_script", "run_python"):
resp = await self._client.post(f"/{action}", json=params)
resp.raise_for_status()
diff --git a/libs/python/cua-sandbox/tests/test_osworld_fleet.py b/libs/python/cua-sandbox/tests/test_osworld_fleet.py
new file mode 100644
index 0000000000..72aba7f9c3
--- /dev/null
+++ b/libs/python/cua-sandbox/tests/test_osworld_fleet.py
@@ -0,0 +1,123 @@
+"""OSWorld disks on Fleet: ``agent_type="osworld"`` selects the OSWorld server."""
+
+import json
+
+import pytest
+from cua_sandbox import Image
+from cua_sandbox.pool import _ClaimHandle
+from cua_sandbox.transport.fleet import (
+ FleetTransport,
+ OSWorldFleetTransport,
+ fleet_transport_for,
+)
+from cua_sandbox.transport.fleet_cloud import (
+ FleetCloudTransport,
+ OSWorldFleetCloudTransport,
+ default_server_port,
+ fleet_cloud_transport_for,
+)
+from cua_sandbox.transport.osworld import normalize_execute_result
+from fleet_sdk import HttpResponse, Sandbox
+
+REF = "registry.example/osworld@sha256:" + "0" * 64
+
+
+class FakeSDK:
+ def __init__(self, responses):
+ self.responses = list(responses)
+ self.calls = []
+
+ async def service_request(self, sandbox, service, path, request):
+ self.calls.append((service, path, request))
+ return self.responses.pop(0)
+
+
+def response(status=200, body=b"{}", headers=()):
+ return HttpResponse(status=status, headers=list(headers), body=body)
+
+
+def bound():
+ return Sandbox(namespace="demo", claim="claim", name="sb", services=["server", "port-3000"])
+
+
+def test_from_registry_carries_agent_type_and_round_trips():
+ image = Image.from_registry(REF, os_type="linux", kind="vm", agent_type="osworld")
+ assert image._agent_type == "osworld"
+ assert Image.from_dict(image.to_dict())._agent_type == "osworld"
+ assert "agent_type" not in Image.from_registry(REF).to_dict()
+
+
+def test_osworld_images_default_to_the_flask_port():
+ osworld = Image.from_registry(REF, os_type="linux", kind="vm", agent_type="osworld")
+ plain = Image.from_registry(REF, os_type="linux", kind="vm")
+ assert default_server_port(osworld) == 5000
+ assert default_server_port(plain) == 8000
+ assert default_server_port(osworld, 5555) == 5555
+ assert default_server_port(None) == 8000
+
+
+def test_transport_classes_follow_agent_type():
+ osworld = Image.from_registry(REF, os_type="linux", kind="vm", agent_type="osworld")
+ assert fleet_transport_for("osworld") is OSWorldFleetTransport
+ assert fleet_transport_for(None) is FleetTransport
+ assert fleet_cloud_transport_for(osworld) is OSWorldFleetCloudTransport
+ assert fleet_cloud_transport_for(Image.from_registry(REF)) is FleetCloudTransport
+ assert fleet_cloud_transport_for(None) is FleetCloudTransport
+
+
+def test_claim_handle_serializes_agent_type():
+ handle = _ClaimHandle(namespace="ns", name="claim", agent_type="osworld")
+ restored = _ClaimHandle.from_dict(handle.to_dict())
+ assert restored.agent_type == "osworld"
+ assert (
+ _ClaimHandle.from_dict(
+ {"version": 1, "provider": "fleet", "namespace": "ns", "claim": "c", "pool": "ns"}
+ ).agent_type
+ is None
+ )
+
+
+def test_execute_result_normalization():
+ assert normalize_execute_result(
+ {"status": "success", "output": "hi\n", "error": "", "returncode": 0}
+ ) == {"stdout": "hi\n", "stderr": "", "returncode": 0}
+ assert normalize_execute_result({"status": "error", "output": None, "error": "boom"}) == {
+ "stdout": "",
+ "stderr": "boom",
+ "returncode": 1,
+ }
+
+
+async def test_osworld_fleet_transport_speaks_the_flask_api():
+ png = b"\x89PNG\r\n\x1a\n" + b"x" * 16
+ sdk = FakeSDK(
+ [
+ response(body=png),
+ response(body=b'{"width": 1920, "height": 1080}'),
+ response(
+ body=b'{"status": "success", "output": "user\\n", "error": "", "returncode": 0}'
+ ),
+ response(body=b'{"AT": "<tree/>"}'),
+ ]
+ )
+ transport = OSWorldFleetTransport(sdk=sdk, bound=bound(), service_name="server")
+ await transport.connect()
+
+ assert await transport.screenshot() == png
+ assert await transport.get_screen_size() == {"width": 1920, "height": 1080}
+ result = await transport.send("run_command", command="whoami", timeout=10)
+ assert result == {"stdout": "user\n", "stderr": "", "returncode": 0}
+ assert await transport.send("accessibility") == {"AT": "<tree/>"}
+ assert await transport.get_environment() == "linux"
+
+ services_and_paths = [(service, path, request.method) for service, path, request in sdk.calls]
+ assert services_and_paths == [
+ ("server", "/screenshot", "GET"),
+ ("server", "/screen_size", "POST"),
+ ("server", "/execute", "POST"),
+ ("server", "/accessibility", "GET"),
+ ]
+ assert json.loads(sdk.calls[2][2].body) == {"command": "whoami", "shell": True}
+ with pytest.raises(ValueError):
+ await transport.send("mouse.click", x=1, y=2)
diff --git a/samples/python/3_osworld_fleet.py b/samples/python/3_osworld_fleet.py
new file mode 100644
index 0000000000..07cdedc294
--- /dev/null
+++ b/samples/python/3_osworld_fleet.py
@@ -0,0 +1,143 @@
+# /// script
+# requires-python = ">=3.11,<3.14"
+# dependencies = ["cua-sandbox", "httpx>=0.27,<1"]
+# ///
+"""
+Demo 3: OSWorld desktop on Fleet (or local QEMU) with the Cua Driver MCP.
+Claims an OSWorld disk, screenshots it through the OSWorld control server, then
+drives it over the cua-driver MCP endpoint baked into the image.
+
+Usage:
+ export OSWORLD_IMAGE="<registry>/<repo>@sha256:<digest>" # containerDisk you published
+ uv run samples/python/3_osworld_fleet.py # Fleet
+ OSWORLD_LOCAL=1 OSWORLD_QCOW2=/path/to/overlay.qcow2 uv run samples/python/3_osworld_fleet.py # local
+
+See docs/content/docs/how-to-guides/sandbox/run-osworld-on-cloud-fleet.mdx.
+"""
+
+import asyncio
+import json
+import os
+import re
+import sys
+import time
+from pathlib import Path
+
+import httpx
+from cua_sandbox import Image, Sandbox
+
+sys.stdout.reconfigure(encoding="utf-8") # tool results contain emoji; keep Windows consoles happy
+
+LOCAL = os.environ.get("OSWORLD_LOCAL") == "1"
+IMAGE_REF = os.environ["OSWORLD_IMAGE"] if not os.environ.get("OSWORLD_LOCAL") else ""
+QCOW2 = os.environ.get("OSWORLD_QCOW2", str(Path.home() / "osworld-cua" / "osworld-cua.qcow2"))
+MCP_PORT = 3000
+
+# The only line that differs between Fleet and local: where the disk comes from.
+image = (
+ Image.from_file(QCOW2, os_type="linux", agent_type="osworld")
+ if LOCAL
+ else Image.from_registry(IMAGE_REF, os_type="linux", kind="vm", agent_type="osworld")
+).expose(5000).expose(MCP_PORT).expose(8080).expose(9222) # OSWorld server, MCP, VLC, Chrome CDP
+
+
+class Mcp:
+ """Minimal MCP Streamable-HTTP client over the sandbox's port-3000 service."""
+
+ def __init__(self, sb: Sandbox):
+ self.sb, self.session, self.next_id = sb, None, 1
+
+ async def _post(self, payload: dict) -> httpx.Response:
+ headers = {
+ "content-type": "application/json",
+ "accept": "application/json, text/event-stream",
+ }
+ if self.session:
+ headers["mcp-session-id"] = self.session
+ if LOCAL: # bare-metal QEMU forwards exposed guest ports to localhost
+ host_port = self.sb.exposed_ports[MCP_PORT]
+ async with httpx.AsyncClient(timeout=120) as c:
+ return await c.post(
+ f"http://127.0.0.1:{host_port}/mcp", headers=headers, json=payload
+ )
+ return await self.sb.services.request( # Fleet: authenticated service proxy
+ f"port-{MCP_PORT}", method="POST", path="/mcp", headers=headers, json=payload
+ )
+
+ async def call(self, method: str, params: dict | None = None) -> dict:
+ payload = {"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params or {}}
+ self.next_id += 1
+ r = await self._post(payload)
+ r.raise_for_status()
+ self.session = r.headers.get("mcp-session-id", self.session)
+ body = r.text
+ if r.headers.get("content-type", "").startswith("text/event-stream"):
+ body = [ln[5:] for ln in body.splitlines() if ln.startswith("data:")][-1]
+ msg = json.loads(body)
+ if "error" in msg:
+ raise RuntimeError(msg["error"])
+ return msg["result"]
+
+ async def notify(self, method: str) -> None:
+ await self._post({"jsonrpc": "2.0", "method": method})
+
+ async def tool(self, tool_name: str, **arguments) -> str:
+ result = await self.call("tools/call", {"name": tool_name, "arguments": arguments})
+ return "\n".join(c.get("text", "") for c in result.get("content", []))
+
+
+async def main() -> None:
+ t0 = time.time()
+ async with Sandbox.ephemeral(
+ image, local=LOCAL, cpu=4, memory_mb=8192, time_to_start=1500
+ ) as sb:
+ print(
+ f"[{time.time() - t0:.0f}s] sandbox {sb.name} ready ({'local' if LOCAL else 'fleet'})"
+ )
+
+ # 1. OSWorld control server (:5000) through the normal Sandbox surface.
+ print("screen:", await sb.get_dimensions())
+ r = await sb.shell.run("whoami; hostname; cua-driver --version", timeout=30)
+ print("shell:", r.stdout.strip().replace("\n", " | "), "rc", r.returncode)
+ Path("osworld.png").write_bytes(await sb.screenshot())
+ print("saved osworld.png")
+
+ # 2. cua-driver MCP (:3000/mcp) baked into the image.
+ mcp = Mcp(sb)
+ info = await mcp.call(
+ "initialize",
+ {
+ "protocolVersion": "2025-03-26",
+ "capabilities": {},
+ "clientInfo": {"name": "osworld-tutorial", "version": "0.1"},
+ },
+ )
+ await mcp.notify("notifications/initialized")
+ print("mcp server:", info["serverInfo"])
+ tools = [t["name"] for t in (await mcp.call("tools/list"))["tools"]]
+ print(f"mcp tools: {len(tools)} e.g. {tools[:8]}")
+ await mcp.tool("start_session", session="osworld-tutorial")
+ print("screen size via MCP:", await mcp.tool("get_screen_size"))
+ print("apps via MCP:", (await mcp.tool("list_apps"))[:300])
+ launched = await mcp.tool("launch_app", name="gnome-calculator", session="osworld-tutorial")
+ print("launch_app:", launched[:300])
+ await asyncio.sleep(3)
+ if pid := re.search(r"pid (\d+)", launched):
+ print(
+ "bring_to_front:",
+ await mcp.tool("bring_to_front", pid=int(pid.group(1)), session="osworld-tutorial"),
+ )
+ await asyncio.sleep(1)
+ print("windows via MCP:", (await mcp.tool("list_windows"))[:400])
+ await mcp.tool("end_session", session="osworld-tutorial")
+ Path("osworld-after.png").write_bytes(await sb.screenshot())
+ print("saved osworld-after.png")
+ print(
+ f"[{time.time() - t0:.0f}s] released; pool deleted"
+ if not LOCAL
+ else f"[{time.time() - t0:.0f}s] VM stopped"
+ )
+
+
+if __name__ == "__main__":
+ sys.exit(asyncio.run(main()))
diff --git a/samples/python/osworld-image/99-cua-dhcp.yaml b/samples/python/osworld-image/99-cua-dhcp.yaml
new file mode 100644
index 0000000000..257d422e80
--- /dev/null
+++ b/samples/python/osworld-image/99-cua-dhcp.yaml
@@ -0,0 +1,13 @@
+# DHCP on whatever NIC the hypervisor presents (enp1s0 under KubeVirt,
+# ens3/enp0s3 under plain QEMU). Without it the guest never gets a lease on Fleet.
+network:
+ version: 2
+ ethernets:
+ all-en:
+ match: {name: "en*"}
+ dhcp4: true
+ dhcp-identifier: mac
+ all-eth:
+ match: {name: "eth*"}
+ dhcp4: true
+ dhcp-identifier: mac
diff --git a/samples/python/osworld-image/99-cua-uinput.rules b/samples/python/osworld-image/99-cua-uinput.rules
new file mode 100644
index 0000000000..bc1a5ed819
--- /dev/null
+++ b/samples/python/osworld-image/99-cua-uinput.rules
@@ -0,0 +1,4 @@
+# cua-driver's X11 background input route creates a virtual keyboard/pointer via
+# uinput and attaches it to its own XI2 master pair, so the user's focus and
+# pointer are never touched. The driver runs as the desktop user.
+KERNEL=="uinput", MODE="0660", GROUP="input", OPTIONS+="static_node=uinput"
diff --git a/samples/python/osworld-image/Dockerfile b/samples/python/osworld-image/Dockerfile
new file mode 100644
index 0000000000..e1f5753312
--- /dev/null
+++ b/samples/python/osworld-image/Dockerfile
@@ -0,0 +1,3 @@
+# KubeVirt containerDisk: the only content Fleet needs is the guest disk at /disk/disk.img.
+FROM scratch
+ADD disk.img /disk/disk.img
diff --git a/samples/python/osworld-image/build-osworld-cua.sh b/samples/python/osworld-image/build-osworld-cua.sh
new file mode 100644
index 0000000000..0bfbb3f2bf
--- /dev/null
+++ b/samples/python/osworld-image/build-osworld-cua.sh
@@ -0,0 +1,46 @@
+#!/usr/bin/env bash
+# Patch the official OSWorld Ubuntu qcow2 with cua-driver + an MCP HTTP endpoint,
+# then flatten it into disk.img ready to wrap as a KubeVirt containerDisk.
+# Runs inside the libguestfs helper container; /work is the build directory and
+# contains base.qcow2, the cua-driver release tarball, and this osworld-image/ folder.
+# Nothing is downloaded inside the guest: Node and supergateway are fetched here
+# and copied in, so the recipe works with libguestfs' network disabled.
+set -euxo pipefail
+cd /work
+: "${DRIVER_TGZ:=cua-driver-rs-0.26.1-linux-x86_64-binary.tar.gz}"
+: "${SUPERGATEWAY_VERSION:=3.4.3}"
+: "${NODE_VERSION:=22.12.0}"
+
+# 1. Inputs: cua-driver release binary, Node.js, supergateway (npm package).
+rm -rf drv && mkdir drv && tar -xzf "$DRIVER_TGZ" -C drv cua-driver
+if [ ! -x node/bin/node ]; then
+ curl -fsSL -o node.tar.xz "https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.xz"
+ rm -rf node && mkdir node && tar -xJf node.tar.xz -C node --strip-components=1 && rm node.tar.xz
+fi
+rm -rf supergateway && mkdir supergateway
+PATH="/work/node/bin:$PATH" npm install --prefix /work/supergateway --omit=dev "supergateway@${SUPERGATEWAY_VERSION}"
+
+# 2. Customize an overlay of the official disk (base.qcow2 is never modified).
+rm -f work.qcow2 && qemu-img create -f qcow2 -b base.qcow2 -F qcow2 work.qcow2
+virt-customize -a work.qcow2 --no-network --smp 4 --memsize 4096 \
+ --mkdir /opt/cua \
+ --copy-in drv/cua-driver:/usr/local/bin \
+ --chmod 0755:/usr/local/bin/cua-driver \
+ --copy-in node:/opt \
+ --copy-in supergateway:/opt \
+ --run-command 'ln -sf /opt/node/bin/node /usr/local/bin/node && ln -sf /opt/supergateway/node_modules/.bin/supergateway /usr/local/bin/supergateway' \
+ --copy-in osworld-image/start-cua-mcp.sh:/opt/cua \
+ --chmod 0755:/opt/cua/start-cua-mcp.sh \
+ --copy-in osworld-image/cua-driver-mcp.service:/etc/systemd/system \
+ --copy-in osworld-image/99-cua-dhcp.yaml:/etc/netplan \
+ --copy-in osworld-image/99-cua-uinput.rules:/etc/udev/rules.d \
+ --copy-in osworld-image/uinput.conf:/etc/modules-load.d \
+ --run-command 'usermod -aG input user' \
+ --chmod 0600:/etc/netplan/99-cua-dhcp.yaml \
+ --run-command 'mkdir -p /etc/cloud/cloud.cfg.d && printf "network: {config: disabled}\n" > /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg' \
+ --run-command 'export PATH=/usr/local/bin:/opt/node/bin:$PATH; cua-driver --version && node --version && supergateway --help >/dev/null' \
+ --run-command 'systemctl enable cua-driver-mcp.service'
+
+# 3. Flatten the overlay onto its base and compress: this is the containerDisk payload.
+qemu-img convert -O qcow2 -c -p -m 8 -W work.qcow2 disk.img
+qemu-img info disk.img
diff --git a/samples/python/osworld-image/cua-driver-mcp.service b/samples/python/osworld-image/cua-driver-mcp.service
new file mode 100644
index 0000000000..4175c400ef
--- /dev/null
+++ b/samples/python/osworld-image/cua-driver-mcp.service
@@ -0,0 +1,15 @@
+[Unit]
+Description=cua-driver MCP server over Streamable HTTP (:3000/mcp)
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+Type=simple
+User=user
+Environment=HOME=/home/user
+ExecStart=/opt/cua/start-cua-mcp.sh
+Restart=always
+RestartSec=3
+
+[Install]
+WantedBy=multi-user.target
diff --git a/samples/python/osworld-image/guestfs/Dockerfile b/samples/python/osworld-image/guestfs/Dockerfile
new file mode 100644
index 0000000000..2358734c31
--- /dev/null
+++ b/samples/python/osworld-image/guestfs/Dockerfile
@@ -0,0 +1,7 @@
+FROM ubuntu:24.04
+ENV DEBIAN_FRONTEND=noninteractive
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ libguestfs-tools linux-image-generic qemu-utils ca-certificates curl unzip \
+ && rm -rf /var/lib/apt/lists/*
+ENV LIBGUESTFS_BACKEND=direct
+WORKDIR /work
diff --git a/samples/python/osworld-image/start-cua-mcp.sh b/samples/python/osworld-image/start-cua-mcp.sh
new file mode 100644
index 0000000000..d469543a87
--- /dev/null
+++ b/samples/python/osworld-image/start-cua-mcp.sh
@@ -0,0 +1,17 @@
+#!/usr/bin/env bash
+# Expose `cua-driver mcp` (stdio) as MCP Streamable HTTP on 0.0.0.0:3000/mcp,
+# driving the OSWorld image's auto-login Xorg session (user `user`).
+set -euo pipefail
+DISPLAY_NUM=""
+for _ in $(seq 1 120); do
+ SOCK=$(ls /tmp/.X11-unix/ 2>/dev/null | head -n 1 || true)
+ if [ -n "$SOCK" ]; then DISPLAY_NUM=":${SOCK#X}"; break; fi
+ sleep 1
+done
+export DISPLAY="${DISPLAY_NUM:-:0}"
+export XAUTHORITY="${XAUTHORITY:-$HOME/.Xauthority}"
+export PATH="/usr/local/bin:/opt/node/bin:$PATH"
+exec /usr/local/bin/supergateway \
+ --stdio "/usr/local/bin/cua-driver mcp" \
+ --outputTransport streamableHttp --stateful --sessionTimeout 3600000 \
+ --port 3000 --streamableHttpPath /mcp --healthEndpoint /healthz --cors
diff --git a/samples/python/osworld-image/uinput.conf b/samples/python/osworld-image/uinput.conf
new file mode 100644
index 0000000000..42bc0053c7
--- /dev/null
+++ b/samples/python/osworld-image/uinput.conf
@@ -0,0 +1 @@
+uinput