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.

fix(python): cua-sandbox, cua-bench and the playground no longer depend on Fleet; remove cua-train (CUA-1834) (#5445)

Francesco Bonacci773328941ead
diff --git a/.github/releases/README.md b/.github/releases/README.md
index 6038534a03..8e2bb835d1 100644
--- a/.github/releases/README.md
+++ b/.github/releases/README.md
@@ -45,7 +45,6 @@ contributor notes** with the tag.
| cua-bench-ui (PyPI) | `libs/python/bench-ui` | `bench-ui-v*` | `cd-py-bench-ui.yml` |
| cua-som (PyPI) | `libs/python/som` | `som-v*` | `cd-py-som.yml` |
| cua-sandbox-apps (PyPI) | `libs/python/cua-sandbox-apps` | `sandbox-apps-v*` | `cd-py-sandbox-apps.yml` |
-| cua-train (PyPI) | `libs/python/cua-train` | `train-v*` | `cd-py-train.yml` |
| @trycua/core (npm) | `libs/typescript/core` | `npm-core-v*` | `cd-ts-core.yml` |
| @trycua/playground (npm) | `libs/typescript/playground` | `npm-playground-v*` | `cd-ts-playground.yml` |
| cuabot (npm) | `libs/cuabot` | `cuabot-v*` | `cd-ts-cuabot.yml` |
diff --git a/.github/scripts/merge_release_please_manifests.py b/.github/scripts/merge_release_please_manifests.py
index e9dc629efc..6dea50ff13 100644
--- a/.github/scripts/merge_release_please_manifests.py
+++ b/.github/scripts/merge_release_please_manifests.py
@@ -23,7 +23,6 @@ COMPONENT_PATHS = {
"bench-ui": "libs/python/bench-ui",
"som": "libs/python/som",
"sandbox-apps": "libs/python/cua-sandbox-apps",
- "train": "libs/python/cua-train",
"npm-core": "libs/typescript/core",
"npm-playground": "libs/typescript/playground",
"cuabot": "libs/cuabot",
diff --git a/.github/scripts/release_notes.py b/.github/scripts/release_notes.py
index 288a4c3b4a..970f30e923 100644
--- a/.github/scripts/release_notes.py
+++ b/.github/scripts/release_notes.py
@@ -53,7 +53,6 @@ DISPLAY_NAMES = {
"bench-ui": "Cua Bench UI",
"som": "Cua SOM",
"sandbox-apps": "Cua Sandbox Apps",
- "train": "Cua Train",
"npm-core": "@trycua/core",
"npm-playground": "@trycua/playground",
"cuabot": "CuaBot",
@@ -68,7 +67,6 @@ INSTALL = {
"bench-ui": (("pypi", "cua-bench-ui"),),
"som": (("pypi", "cua-som"),),
"sandbox-apps": (("pypi", "cua-sandbox-apps"),),
- "train": (("pypi", "cua-train"),),
"npm-core": (("npm", "@trycua/core"),),
"npm-playground": (("npm", "@trycua/playground"),),
"cuabot": (("npm", "cuabot"),),
@@ -88,7 +86,6 @@ LEGACY_BASELINE_TAGS = frozenset({
"bench-ui-v0.7.1",
"som-v0.1.4",
"sandbox-apps-v0.1.2",
- "train-v0.1.2",
"npm-core-v0.1.6",
"npm-playground-v0.3.0",
"cuabot-v1.0.16",
diff --git a/.github/scripts/resolve_release_please_request.py b/.github/scripts/resolve_release_please_request.py
index d29532391e..b7d293ebb3 100644
--- a/.github/scripts/resolve_release_please_request.py
+++ b/.github/scripts/resolve_release_please_request.py
@@ -24,7 +24,6 @@ COMPONENT_PATHS = {
"bench-ui": "libs/python/bench-ui",
"som": "libs/python/som",
"sandbox-apps": "libs/python/cua-sandbox-apps",
- "train": "libs/python/cua-train",
"npm-core": "libs/typescript/core",
"npm-playground": "libs/typescript/playground",
"cuabot": "libs/cuabot",
diff --git a/.github/scripts/tests/release_please_enrolled_preview.cjs b/.github/scripts/tests/release_please_enrolled_preview.cjs
index f2972cfa4b..14cf5c9e89 100644
--- a/.github/scripts/tests/release_please_enrolled_preview.cjs
+++ b/.github/scripts/tests/release_please_enrolled_preview.cjs
@@ -30,8 +30,6 @@ const PACKAGES = {
'libs/python/cua-sandbox-apps': ['sandbox-apps-v', 'cua_sandbox_apps/__init__.py',
['libs/python/cua-sandbox-apps/CHANGELOG.md', 'libs/python/cua-sandbox-apps/pyproject.toml',
'libs/python/cua-sandbox-apps/uv.lock']],
- 'libs/python/cua-train': ['train-v', 'src/cua_train/__init__.py',
- ['libs/python/cua-train/CHANGELOG.md', 'libs/python/cua-train/pyproject.toml']],
'libs/typescript/core': ['npm-core-v', 'src/index.ts',
['libs/typescript/core/CHANGELOG.md', 'libs/typescript/core/package.json']],
'libs/typescript/playground': ['npm-playground-v', 'src/index.ts',
diff --git a/.github/scripts/tests/test_release_notes.py b/.github/scripts/tests/test_release_notes.py
index fba736944e..01e8fc4924 100644
--- a/.github/scripts/tests/test_release_notes.py
+++ b/.github/scripts/tests/test_release_notes.py
@@ -25,7 +25,6 @@ ENROLLED = {
"libs/python/bench-ui": "bench-ui",
"libs/python/som": "som",
"libs/python/cua-sandbox-apps": "sandbox-apps",
- "libs/python/cua-train": "train",
"libs/typescript/core": "npm-core",
"libs/typescript/playground": "npm-playground",
"libs/cuabot": "cuabot",
@@ -111,7 +110,7 @@ def test_enrolled_packages_keep_their_legacy_tag_and_current_version():
def test_legacy_bump_workflows_no_longer_release_enrolled_packages():
services = ["pypi/agent", "pypi/bench", "pypi/bench-ui", "pypi/core", "pypi/sandbox-apps",
- "pypi/som", "pypi/train", "npm/core", "npm/playground", "npm/cuabot"]
+ "pypi/som", "npm/core", "npm/playground", "npm/cuabot"]
for workflow in ("release-bump-version.yml", "release-on-merge.yml",
"ci-release-reminder.yml", "release-unreleased-digest.yml"):
text = (WORKFLOWS / workflow).read_text()
diff --git a/.github/scripts/tests/test_validate_release_versions.py b/.github/scripts/tests/test_validate_release_versions.py
index 14d6f1c030..5f70e5a636 100644
--- a/.github/scripts/tests/test_validate_release_versions.py
+++ b/.github/scripts/tests/test_validate_release_versions.py
@@ -33,7 +33,6 @@ def copy_release_sources(destination: Path) -> None:
"libs/python/som/pyproject.toml",
"libs/python/cua-sandbox-apps/pyproject.toml",
"libs/python/cua-sandbox-apps/uv.lock",
- "libs/python/cua-train/pyproject.toml",
"libs/typescript/core/package.json",
"libs/typescript/playground/package.json",
"libs/cuabot/package.json",
diff --git a/.github/scripts/validate_release_versions.py b/.github/scripts/validate_release_versions.py
index 4594b3be89..b08a521e61 100644
--- a/.github/scripts/validate_release_versions.py
+++ b/.github/scripts/validate_release_versions.py
@@ -295,7 +295,6 @@ CONFIG_ONLY_PACKAGES = (
"libs/python/bench-ui",
"libs/python/som",
"libs/python/cua-sandbox-apps",
- "libs/python/cua-train",
"libs/typescript/core",
"libs/typescript/playground",
"libs/cuabot",
diff --git a/.github/workflows/cd-py-train.yml b/.github/workflows/cd-py-train.yml
deleted file mode 100644
index 4eedc34207..0000000000
--- a/.github/workflows/cd-py-train.yml
+++ /dev/null
@@ -1,69 +0,0 @@
-name: "CD: cua-train (PyPI)"
-
-on:
- push:
- tags:
- - "train-v*"
- workflow_dispatch:
- inputs:
- version:
- description: "Version to publish (without v prefix)"
- required: true
- default: "0.1.0"
- workflow_call:
- inputs:
- version:
- description: "Version to publish"
- required: true
- type: string
-
-permissions:
- contents: write
-
-jobs:
- prepare:
- runs-on: macos-latest
- outputs:
- version: ${{ steps.get-version.outputs.version }}
- steps:
- - uses: actions/checkout@v4
-
- - name: Determine version
- id: get-version
- run: |
- if [ -n "${{ inputs.version }}" ]; then
- VERSION=${{ inputs.version }}
- elif [ "${{ github.event_name }}" == "push" ]; then
- if [[ "${{ github.ref }}" =~ ^refs/tags/train-v([0-9]+\.[0-9]+\.[0-9]+) ]]; then
- VERSION=${BASH_REMATCH[1]}
- else
- echo "Invalid tag format for train"
- exit 1
- fi
- elif [ -n "${{ github.event.inputs.version }}" ]; then
- VERSION=${{ github.event.inputs.version }}
- else
- echo "ERROR: No version found!"
- exit 1
- fi
- echo "version=$VERSION" >> $GITHUB_OUTPUT
-
- publish:
- needs: prepare
- uses: ./.github/workflows/py-reusable-publish.yml
- with:
- package_name: "train"
- package_dir: "libs/python/cua-train"
- version: ${{ needs.prepare.outputs.version }}
- base_package_name: "cua-train"
- secrets:
- PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
-
- create-release:
- needs: [prepare, publish]
- uses: ./.github/workflows/release-github-reusable.yml
- with:
- tag_name: "train-v${{ needs.prepare.outputs.version }}"
- release_name: "cua-train v${{ needs.prepare.outputs.version }}"
- module_path: "libs/python/cua-train"
- body: ""
diff --git a/.github/workflows/ci-cua-driver-contract-clients.yml b/.github/workflows/ci-cua-driver-contract-clients.yml
index e7041a20b1..e4fee353ab 100644
--- a/.github/workflows/ci-cua-driver-contract-clients.yml
+++ b/.github/workflows/ci-cua-driver-contract-clients.yml
@@ -344,7 +344,6 @@ jobs:
PYTHONPATH=libs/python/cua-sandbox:libs/cua-driver/python/src \
python -m pytest \
libs/python/cua-sandbox/tests/test_typed_driver_native.py \
- libs/python/cua-sandbox/tests/test_typed_driver.py \
libs/python/cua-sandbox/tests/test_driver_mcp.py \
libs/python/cua-sandbox/tests/test_driver_mcp_shared.py \
libs/python/cua-sandbox/tests/test_driver_mcp_native.py \
diff --git a/.github/workflows/ci-public-containerdisk-refs.yml b/.github/workflows/ci-public-containerdisk-refs.yml
index c2e6efbdcf..6dd674c41f 100644
--- a/.github/workflows/ci-public-containerdisk-refs.yml
+++ b/.github/workflows/ci-public-containerdisk-refs.yml
@@ -7,8 +7,6 @@ on:
- "docs/content/docs/how-to-guides/sandbox/**"
- "infra/fleets-wif-smoke/**"
- "libs/fleet/backend/auth/**"
- - "libs/python/cua-sandbox/tests/live/test_fleet_ephemeral.py"
- - "libs/python/cua-sandbox/tests/live/test_fleet_pool_persistent.py"
- "tests/test_public_containerdisk_refs.py"
permissions:
diff --git a/.github/workflows/ci-test-python.yml b/.github/workflows/ci-test-python.yml
index 35fcf8554e..767566fe6c 100644
--- a/.github/workflows/ci-test-python.yml
+++ b/.github/workflows/ci-test-python.yml
@@ -142,7 +142,6 @@ jobs:
--ignore=tests/live
--ignore=tests/test_runtime.py
--ignore=tests/test_snapshots.py
- --ignore=tests/test_windows_cloud.py
--ignore=tests/test_windows_timing.py
--deselect tests/test_oci.py::TestLiveRegistry
diff --git a/.github/workflows/release-notes.yml b/.github/workflows/release-notes.yml
index 1a347d36ed..13d39ffb7c 100644
--- a/.github/workflows/release-notes.yml
+++ b/.github/workflows/release-notes.yml
@@ -25,7 +25,6 @@ on:
- "bench-ui-v*"
- "som-v*"
- "sandbox-apps-v*"
- - "train-v*"
- "npm-core-v*"
- "npm-playground-v*"
- "cuabot-v*"
diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml
index c6ac2cd81a..14938eec60 100644
--- a/.github/workflows/release-please.yml
+++ b/.github/workflows/release-please.yml
@@ -26,7 +26,6 @@ on:
- bench-ui
- som
- sandbox-apps
- - train
- npm-core
- npm-playground
- cuabot
diff --git a/.release-please-manifest.json b/.release-please-manifest.json
index ee314ea3a6..b42ec16abe 100644
--- a/.release-please-manifest.json
+++ b/.release-please-manifest.json
@@ -12,7 +12,6 @@
"libs/python/bench-ui": "0.7.1",
"libs/python/som": "0.1.4",
"libs/python/cua-sandbox-apps": "0.1.2",
- "libs/python/cua-train": "0.1.2",
"libs/typescript/core": "0.1.6",
"libs/typescript/playground": "0.3.0",
"libs/cuabot": "1.0.16"
diff --git a/TESTING.md b/TESTING.md
index 145aa2d126..2988bea8f6 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -33,8 +33,8 @@ uv sync --group test
CUA_TELEMETRY_ENABLED=false uv run pytest libs/python/<package>/tests -v
```
-Packages outside the root uv workspace (`cua-sandbox`, `cua-train`,
-`libs/cua-bench`, `libs/cua/python`) are installed from their own
+Packages outside the root uv workspace (`cua-sandbox`, `libs/cua-bench`,
+`libs/cua/python`) are installed from their own
`pyproject.toml`. cua-sandbox runs on the cua SDK, so build the native library
first and pass explicit ignores: several legacy files start real VMs.
@@ -47,7 +47,7 @@ cd ../python/cua-sandbox
uv sync --frozen --python 3.12
CUA_TELEMETRY_ENABLED=false uv run --frozen pytest tests --timeout=120 \
--ignore=tests/live --ignore=tests/test_runtime.py --ignore=tests/test_snapshots.py \
- --ignore=tests/test_windows_cloud.py --ignore=tests/test_windows_timing.py \
+ --ignore=tests/test_windows_timing.py \
--deselect tests/test_oci.py::TestLiveRegistry
```
diff --git a/docs/content/docs/cua-bench/reference/cli/run.mdx b/docs/content/docs/cua-bench/reference/cli/run.mdx
index 08fee56534..05159427eb 100644
--- a/docs/content/docs/cua-bench/reference/cli/run.mdx
+++ b/docs/content/docs/cua-bench/reference/cli/run.mdx
@@ -68,11 +68,10 @@ cb run task [OPTIONS] <task_path>
| <span id="cb-run-task--max-steps"></span>`--max-steps` | | integer | `100` | Maximum number of steps for agent execution (default: 100). |
| <span id="cb-run-task--on"></span>`--on` | | `local` \| `cloud` \| `e2b` \| `daytona` \| `modal` \| `cloudflare` \| `vercel` \| `morph` \| `runloop` \| `fly` \| `blaxel` \| `codesandbox` \| `northflank` \| `aws` \| `gcp` | | Where sandboxes run: local (this machine), your own cloud account (aws, gcp, modal; connect it first with `cua cloud connect <provider>`), or a contrib provider (e2b, daytona; needs a cua SDK built with contrib and the provider's key). Default: CUA_DEFAULT_ON, else `cua config set default.on`, else local. |
| <span id="cb-run-task--kind"></span>`--kind` | | `auto` \| `container` \| `vm` | | What kind of sandbox: container or vm. Default auto: Linux as a container unless the task or image says VM; Windows, macOS and Android are VM-only. Default: CUA_DEFAULT_KIND, else `cua config set default.kind`. |
-| <span id="cb-run-task--runtime"></span>`--runtime` | | `auto` \| `gvisor` \| `runc` \| `qemu` \| `lume` \| `kubevirt` | | Which engine: gvisor or runc (local containers), qemu or lume (local VMs), gvisor or kubevirt (cloud containers, VMs). Implies its kind. Default auto: the SDK picks (CUA_DEFAULT_RUNTIME, else `cua config set default.runtime`). |
-| <span id="cb-run-task--image"></span>`--image` | | string | | Image for every task (overrides the task's setup_config.image): an OS alias (linux, windows, macos:tahoe), ghcr.io/trycua/&lt;os&gt;, any registry ref or a digest, or pool:&lt;name&gt; for an existing Fleet pool. Env: CUA_BENCH_IMAGE. |
+| <span id="cb-run-task--runtime"></span>`--runtime` | | `auto` \| `gvisor` \| `runc` \| `qemu` \| `lume` \| `kubevirt` | | Which engine: gvisor or runc (containers), qemu or lume (VMs). Implies its kind. Default auto: the SDK picks (CUA_DEFAULT_RUNTIME, else `cua config set default.runtime`). |
+| <span id="cb-run-task--image"></span>`--image` | | string | | Image for every task (overrides the task's setup_config.image): an OS alias (linux, windows, macos:tahoe), ghcr.io/trycua/&lt;os&gt;, any registry ref or a digest. Env: CUA_BENCH_IMAGE. |
| <span id="cb-run-task--cpu"></span>`--cpu` | | integer | | vCPUs per sandbox. |
| <span id="cb-run-task--memory"></span>`--memory` | | string | | Memory per sandbox (e.g. 4096, 4G). |
-| <span id="cb-run-task--claim-ttl"></span>`--claim-ttl` | | string | | cloud: how long a claim outlives a crashed run (default 15m; renewed while running). |
| <span id="cb-run-task--output-dir"></span>`--output-dir` | | string | | Output directory for session results. |
| <span id="cb-run-task--attempts"></span>`--attempts` | | integer | `1` | Run every variant this many times (fresh sandbox each); summary.json reports pass@k (default: 1). |
| <span id="cb-run-task--retries"></span>`--retries` | | integer | `0` | Retry a variant that failed before evaluation (sandbox start, connection) up to this many times, with backoff (default: 0). |
@@ -81,7 +80,6 @@ cb run task [OPTIONS] <task_path>
| <span id="cb-run-task--max-results-size"></span>`--max-results-size` | | string | | After the run, delete the oldest runs until the runs directory fits in SIZE, e.g. 20G (env CUA_BENCH_MAX_RESULTS_SIZE). |
| <span id="cb-run-task--oracle"></span>`--oracle` | | boolean | `false` | Run the oracle solution (the default when no agent is given). |
| <span id="cb-run-task--noop"></span>`--noop` | | boolean | `false` | Set up and evaluate with no actions (the null baseline for eval parity). |
-| <span id="cb-run-task--warm"></span>`--warm` | | boolean | `false` | cloud: keep one replica ready when the managed pool is first created. |
| <span id="cb-run-task--detach"></span>`--detach` | `-d` | boolean | `false` | Run in the background and return (follow with cb run watch &lt;id&gt;). |
| <span id="cb-run-task--dry-run"></span>`--dry-run` | | boolean | `false` | Print each variant's image, kind, variant and backend, then exit without starting a sandbox. |
@@ -121,11 +119,10 @@ cb run dataset [OPTIONS] <dataset_path>
| <span id="cb-run-dataset--max-steps"></span>`--max-steps` | | integer | `100` | Maximum number of steps for agent execution (default: 100). |
| <span id="cb-run-dataset--on"></span>`--on` | | `local` \| `cloud` \| `e2b` \| `daytona` \| `modal` \| `cloudflare` \| `vercel` \| `morph` \| `runloop` \| `fly` \| `blaxel` \| `codesandbox` \| `northflank` \| `aws` \| `gcp` | | Where sandboxes run: local (this machine), your own cloud account (aws, gcp, modal; connect it first with `cua cloud connect <provider>`), or a contrib provider (e2b, daytona; needs a cua SDK built with contrib and the provider's key). Default: CUA_DEFAULT_ON, else `cua config set default.on`, else local. |
| <span id="cb-run-dataset--kind"></span>`--kind` | | `auto` \| `container` \| `vm` | | What kind of sandbox: container or vm. Default auto: Linux as a container unless the task or image says VM; Windows, macOS and Android are VM-only. Default: CUA_DEFAULT_KIND, else `cua config set default.kind`. |
-| <span id="cb-run-dataset--runtime"></span>`--runtime` | | `auto` \| `gvisor` \| `runc` \| `qemu` \| `lume` \| `kubevirt` | | Which engine: gvisor or runc (local containers), qemu or lume (local VMs), gvisor or kubevirt (cloud containers, VMs). Implies its kind. Default auto: the SDK picks (CUA_DEFAULT_RUNTIME, else `cua config set default.runtime`). |
-| <span id="cb-run-dataset--image"></span>`--image` | | string | | Image for every task (overrides the task's setup_config.image): an OS alias (linux, windows, macos:tahoe), ghcr.io/trycua/&lt;os&gt;, any registry ref or a digest, or pool:&lt;name&gt; for an existing Fleet pool. Env: CUA_BENCH_IMAGE. |
+| <span id="cb-run-dataset--runtime"></span>`--runtime` | | `auto` \| `gvisor` \| `runc` \| `qemu` \| `lume` \| `kubevirt` | | Which engine: gvisor or runc (containers), qemu or lume (VMs). Implies its kind. Default auto: the SDK picks (CUA_DEFAULT_RUNTIME, else `cua config set default.runtime`). |
+| <span id="cb-run-dataset--image"></span>`--image` | | string | | Image for every task (overrides the task's setup_config.image): an OS alias (linux, windows, macos:tahoe), ghcr.io/trycua/&lt;os&gt;, any registry ref or a digest. Env: CUA_BENCH_IMAGE. |
| <span id="cb-run-dataset--cpu"></span>`--cpu` | | integer | | vCPUs per sandbox. |
| <span id="cb-run-dataset--memory"></span>`--memory` | | string | | Memory per sandbox (e.g. 4096, 4G). |
-| <span id="cb-run-dataset--claim-ttl"></span>`--claim-ttl` | | string | | cloud: how long a claim outlives a crashed run (default 15m; renewed while running). |
| <span id="cb-run-dataset--output-dir"></span>`--output-dir` | | string | | Output directory for session results. |
| <span id="cb-run-dataset--attempts"></span>`--attempts` | | integer | `1` | Run every variant this many times (fresh sandbox each); summary.json reports pass@k (default: 1). |
| <span id="cb-run-dataset--retries"></span>`--retries` | | integer | `0` | Retry a variant that failed before evaluation (sandbox start, connection) up to this many times, with backoff (default: 0). |
@@ -134,7 +131,6 @@ cb run dataset [OPTIONS] <dataset_path>
| <span id="cb-run-dataset--max-results-size"></span>`--max-results-size` | | string | | After the run, delete the oldest runs until the runs directory fits in SIZE, e.g. 20G (env CUA_BENCH_MAX_RESULTS_SIZE). |
| <span id="cb-run-dataset--oracle"></span>`--oracle` | | boolean | `false` | Run the oracle solution (the default when no agent is given). |
| <span id="cb-run-dataset--noop"></span>`--noop` | | boolean | `false` | Set up and evaluate with no actions (the null baseline for eval parity). |
-| <span id="cb-run-dataset--warm"></span>`--warm` | | boolean | `false` | cloud: keep one replica ready when the managed pool is first created. |
| <span id="cb-run-dataset--detach"></span>`--detach` | `-d` | boolean | `false` | Run in the background and return (follow with cb run watch &lt;id&gt;). |
| <span id="cb-run-dataset--dry-run"></span>`--dry-run` | | boolean | `false` | Print each variant's image, kind, variant and backend, then exit without starting a sandbox. |
@@ -278,16 +274,14 @@ cb interact [OPTIONS] <env_path>
| <span id="cb-interact--trace-out"></span>`--trace-out` | string | | Record a trace and save it as a dataset to this path on exit. |
| <span id="cb-interact--on"></span>`--on` | `local` \| `cloud` \| `e2b` \| `daytona` \| `modal` \| `cloudflare` \| `vercel` \| `morph` \| `runloop` \| `fly` \| `blaxel` \| `codesandbox` \| `northflank` \| `aws` \| `gcp` | | Where sandboxes run: local (this machine), your own cloud account (aws, gcp, modal; connect it first with `cua cloud connect <provider>`), or a contrib provider (e2b, daytona; needs a cua SDK built with contrib and the provider's key). Default: CUA_DEFAULT_ON, else `cua config set default.on`, else local. |
| <span id="cb-interact--kind"></span>`--kind` | `auto` \| `container` \| `vm` | | What kind of sandbox: container or vm. Default auto: Linux as a container unless the task or image says VM; Windows, macOS and Android are VM-only. Default: CUA_DEFAULT_KIND, else `cua config set default.kind`. |
-| <span id="cb-interact--runtime"></span>`--runtime` | `auto` \| `gvisor` \| `runc` \| `qemu` \| `lume` \| `kubevirt` | | Which engine: gvisor or runc (local containers), qemu or lume (local VMs), gvisor or kubevirt (cloud containers, VMs). Implies its kind. Default auto: the SDK picks (CUA_DEFAULT_RUNTIME, else `cua config set default.runtime`). |
-| <span id="cb-interact--image"></span>`--image` | string | | Image for every task (overrides the task's setup_config.image): an OS alias (linux, windows, macos:tahoe), ghcr.io/trycua/&lt;os&gt;, any registry ref or a digest, or pool:&lt;name&gt; for an existing Fleet pool. Env: CUA_BENCH_IMAGE. |
+| <span id="cb-interact--runtime"></span>`--runtime` | `auto` \| `gvisor` \| `runc` \| `qemu` \| `lume` \| `kubevirt` | | Which engine: gvisor or runc (containers), qemu or lume (VMs). Implies its kind. Default auto: the SDK picks (CUA_DEFAULT_RUNTIME, else `cua config set default.runtime`). |
+| <span id="cb-interact--image"></span>`--image` | string | | Image for every task (overrides the task's setup_config.image): an OS alias (linux, windows, macos:tahoe), ghcr.io/trycua/&lt;os&gt;, any registry ref or a digest. Env: CUA_BENCH_IMAGE. |
| <span id="cb-interact--cpu"></span>`--cpu` | integer | | vCPUs per sandbox. |
| <span id="cb-interact--memory"></span>`--memory` | string | | Memory per sandbox (e.g. 4096, 4G). |
-| <span id="cb-interact--claim-ttl"></span>`--claim-ttl` | string | | cloud: how long a claim outlives a crashed run (default 15m; renewed while running). |
| <span id="cb-interact--oracle"></span>`--oracle` | boolean | `false` | Run the solution after setup. |
| <span id="cb-interact--view"></span>`--view` | boolean | `false` | Open the trace viewer when done. |
| <span id="cb-interact--no-wait"></span>`--no-wait` | boolean | `false` | Skip the interactive prompt (useful for SSH/CI testing). |
| <span id="cb-interact--no-browser"></span>`--no-browser` | boolean | `false` | Print the Display: URL without opening it (also CUA_BENCH_NO_BROWSER=1). |
-| <span id="cb-interact--warm"></span>`--warm` | boolean | `false` | cloud: keep one replica ready when the managed pool is first created. |
**Examples**
diff --git a/docs/content/docs/cua-bench/reference/results.mdx b/docs/content/docs/cua-bench/reference/results.mdx
index 786a8a9b60..15eefe8fb4 100644
--- a/docs/content/docs/cua-bench/reference/results.mdx
+++ b/docs/content/docs/cua-bench/reference/results.mdx
@@ -42,7 +42,7 @@ One variant's outcome: the cua-bench fields of its `result.json`.
| `on` | `str` | Where it ran: `local` or `cloud`. |
| `backend` | `str` | What ran it, `<location>-<engine>` (`local-gvisor`, `local-qemu`, `cloud-gvisor`, `cloud-kubevirt`, `cloud-pool:<name>`). |
| `image` | `str \| null` | The image as the task or `--image` named it. |
-| `pool` | `str \| null` | The Fleet pool that served the claim (cloud runs). |
+| `pool` | `str \| null` | The pool that served the sandbox (unused: always `None` since Cua Cloud ended). |
| `output_dir` | `str` | The variant's output directory. |
| `extra` | `dict` | Extra values the task or agent reported. |
| `kind` | `str \| null` | `container` or `vm`. |
@@ -98,7 +98,7 @@ One row of `summary.json` `results`: a variant's outcome.
| `results[].variant` | `int` | Variant index (`--variant-id`). |
| `results[].status` | `str` | `completed`, `failed` or `cancelled`. |
| `results[].reward` | `float \| null` | The mean of the evaluation's numbers (`true` counts as 1), or `null` when evaluation did not run. |
-| `results[].pool` | `str \| null` | The Fleet pool that served the claim (cloud runs). |
+| `results[].pool` | `str \| null` | The pool that served the sandbox (unused: always `None` since Cua Cloud ended). |
| `results[].duration_s` | `float` | Wall time of the variant in seconds. |
| `results[].error` | `str \| null` | The error message when the variant failed. |
| `results[].kind` | `str \| null` | `container` or `vm`. |
diff --git a/docs/content/docs/cua-bench/reference/task-definition.mdx b/docs/content/docs/cua-bench/reference/task-definition.mdx
index d733081fa2..1883b2c4e0 100644
--- a/docs/content/docs/cua-bench/reference/task-definition.mdx
+++ b/docs/content/docs/cua-bench/reference/task-definition.mdx
@@ -32,7 +32,7 @@ A task's `computer["setup_config"]`: the sandbox the task runs in. Every key is
| `os_type` | `string` | Guest OS: `linux` (the default; `ubuntu` is an alias), `windows` (`win11`, `win10` and older names are aliases), `macos` or `android`. macOS and Android run only with `--on local`. |
| `width` | `int` | Screen width in pixels. |
| `height` | `int` | Screen height in pixels. |
-| `image` | `str` | Registry image or OS alias (`linux`, `windows`, `macos:tahoe`), or `pool:<name>` for an existing Fleet pool. `--image` wins, then this, then `CUA_BENCH_IMAGE`, then the canonical image of `os_type`. |
+| `image` | `str` | Registry image or OS alias (`linux`, `windows`, `macos:tahoe`). `--image` wins, then this, then `CUA_BENCH_IMAGE`, then the canonical image of `os_type`. |
| `kind` | `str` | Preferred kind: `container` (Linux only) or `vm`. |
| `kinds` | `list[str]` | Kinds the task supports (a requirement, unlike `kind`): for example `["vm"]` for a task that needs its own kernel. |
| `requires` | `list[str]` | What the target must provide: `kvm`, `env:<NAME>` (a set environment variable), `openai` (`env:OPENAI_API_KEY`) or `hf-gated` (`env:HF_TOKEN`). |
@@ -43,7 +43,7 @@ A task's `computer["setup_config"]`: the sandbox the task runs in. Every key is
| `wallpaper` | `str` | Ignored (kept so older tasks still load). |
| `installed_apps` | `list[str]` | Ignored (kept so older tasks still load). |
| `storage` | `str` | Deprecated and ignored. |
-| `provider_type` | `str` | Deprecated: `"cloud"` runs on Fleet; use `--on cloud` instead. |
+| `provider_type` | `str` | Deprecated: `"cloud"` named Cua Cloud, which has ended (it raises). |
## Lifecycle decorators
diff --git a/docs/content/docs/cua-sdk/reference/python/configuration.mdx b/docs/content/docs/cua-sdk/reference/python/configuration.mdx
index cec603eed9..025e49585b 100644
--- a/docs/content/docs/cua-sdk/reference/python/configuration.mdx
+++ b/docs/content/docs/cua-sdk/reference/python/configuration.mdx
@@ -29,26 +29,12 @@ def configure(
) -> None
```
-Set global configuration for cloud sandboxes.
+Set global configuration.
-API-key cloud operations use `base_url`. Fleet uses `fleet_base_url` and
-OAuth client credentials.
-
-### fleet_auth_source
-
-```python
-def fleet_auth_source(*, read_session: bool = True) -> Optional[str]
-```
-
-Where Fleet credentials come from, in the order the SDK uses them.
-
-`"FLEETS_TOKEN"` (a workload token), `"client credentials"`
-(`CUA_CLIENT_ID`/`CUA_CLIENT_SECRET`), `"cua auth login session"`
-(the stored session, refreshed by the SDK while it is used) or `None`
-when nothing is configured. A stored session is only looked up when
-neither of the first two is set. `read_session=False` decides that from
-the non-secret session marker alone, without reading the OS credential
-vault (for dashboards and other implicit checks).
+`api_key` and `base_url` apply to the legacy `login()` and
+`whoami()` helpers. `fleet_base_url`, `token_url`, `client_id`,
+`client_secret` and `fleet_token` configured Cua Cloud, which has
+ended: they are accepted so existing calls keep working, and ignored.
### login
@@ -126,64 +112,7 @@ so older `except NotImplementedError` handlers still catch it.
class CloudTransport(Transport)
```
-Compatibility shim for the removed API-key cloud transport.
-
-Constructing it still works (and keeps the requested image), so code that
-builds one fails at `connect()` with a message pointing to Fleet.
-
-| Attribute | Type | Description |
-| --- | --- | --- |
-| `name` | `Optional[str]` | |
-
-#### CloudTransport.connect
-
-```python
-async def connect() -> None
-```
-
-#### CloudTransport.disconnect
-
-```python
-async def disconnect() -> None
-```
-
-#### CloudTransport.delete_vm
-
-```python
-async def delete_vm() -> None
-```
-
-Delete an existing API-key VM through the platform API.
-
-#### CloudTransport.create_snapshot
-
-```python
-async def create_snapshot(name: str | None = None, stateful: bool = False) -> dict
-```
-
-#### CloudTransport.send
-
-```python
-async def send(action: str, **params: Any) -> Any
-```
-
-#### CloudTransport.screenshot
-
-```python
-async def screenshot(format: str = 'png', quality: int = 95) -> bytes
-```
-
-#### CloudTransport.get_screen_size
-
-```python
-async def get_screen_size() -> Dict[str, int]
-```
-
-#### CloudTransport.get_environment
-
-```python
-async def get_environment() -> str
-```
+Retired: every Cua Cloud entry point raises `CloudEnded`.
### EnvTransport
@@ -195,9 +124,9 @@ Drives a sandbox through cua-spacesd.
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
-| `url` | `Optional[str]` | `None` | spacesd URL (`http://host:3211`, a relay or Fleet service URL). Ignored when `env_factory` is given. |
+| `url` | `Optional[str]` | `None` | spacesd URL (`http://host:3211` or a relay URL). Ignored when `env_factory` is given. |
| `token` | `Optional[str]` | `None` | spacesd token, if the driver requires one. |
-| `env_factory` | `Optional[EnvFactory]` | `None` | coroutine returning a `cua.SpacesdClient` (used by Fleet and local runtimes, which know how to reach the driver). |
+| `env_factory` | `Optional[EnvFactory]` | `None` | coroutine returning a `cua.SpacesdClient` (used by local runtimes, which know how to reach the driver). |
| `environment` | `Optional[str]` | `None` | OS hint (`linux`, `windows`, `mac`) used before the driver has been reached. |
| `fallback` | `Optional[Transport]` | `None` | an agentless transport (QMP/VNC/SSH/ADB) to use when the sandbox has no spacesd. |
| `ready_timeout` | `float` | `0.0` | how long to keep retrying the spacesd probe on first use (a freshly booted VM starts its driver late). `0` probes once. |
diff --git a/docs/content/docs/cua-sdk/reference/python/image.mdx b/docs/content/docs/cua-sdk/reference/python/image.mdx
index 13184816c9..d69c9e32aa 100644
--- a/docs/content/docs/cua-sdk/reference/python/image.mdx
+++ b/docs/content/docs/cua-sdk/reference/python/image.mdx
@@ -103,9 +103,9 @@ def windows(
Windows: the canonical `ghcr.io/trycua/windows:2022` containerDisk.
-Other versions, including `"11"`, have no canonical image: on Fleet
-they are unsupported, and locally they are installed from a downloaded
-evaluation ISO. `tier="slim"` names `2022-slim` once published.
+Other versions, including `"11"`, have no canonical image: they are
+installed from a downloaded evaluation ISO. `tier="slim"` names
+`2022-slim` once published.
#### Image.omarchy
@@ -157,8 +157,8 @@ 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.
+server on port 5000 instead of the computer-server on 8000, for local
+QEMU.
#### Image.from_file
diff --git a/docs/content/docs/cua-sdk/reference/python/interfaces.mdx b/docs/content/docs/cua-sdk/reference/python/interfaces.mdx
index 17e50abd64..5fe9eec414 100644
--- a/docs/content/docs/cua-sdk/reference/python/interfaces.mdx
+++ b/docs/content/docs/cua-sdk/reference/python/interfaces.mdx
@@ -683,7 +683,7 @@ mode (Standard by default). Remote clients cannot select its authority.
Use typed inputs with `session=None` where optional. For required session
fields, obtain the bound name with `sandbox.driver.session_name(driver)`. Creating or
rebinding trusted sessions is unsupported. Remote cleanup is best effort
-with a bounded timeout; failures warn and do not block claim release.
+with a bounded timeout; failures warn and do not block the sandbox's release.
#### Driver.session_name
@@ -708,13 +708,11 @@ async def connect(
Yield the canonical Driver; the receiver must support typed envelopes.
-With no arguments this uses the image's Fleet `driver` service when
-it publishes one (the private envelope HTTP carrier), and otherwise
-cua-spacesd's `/mcp` (`service="env"`, `transport="mcp"`)
-through the cua SDK. `service="mcp", transport="mcp"` selects a
-Fleet named MCP service instead. MCP selection verifies the
-`ai.cua.driver.envelopes` extension before opening a receiver. No
-fallback occurs.
+This uses cua-spacesd's `/mcp` (`service="env"`,
+`transport="mcp"`) through the cua SDK, and verifies the
+`ai.cua.driver.envelopes` extension before opening a receiver.
+Named Driver services were a Cua Cloud feature: any other `service`
+or `transport="envelope"` raises `DriverConnectionError`.
#### Driver.close
diff --git a/docs/content/docs/cua-sdk/reference/python/pool.mdx b/docs/content/docs/cua-sdk/reference/python/pool.mdx
index d0a3205385..63275c86d3 100644
--- a/docs/content/docs/cua-sdk/reference/python/pool.mdx
+++ b/docs/content/docs/cua-sdk/reference/python/pool.mdx
@@ -21,26 +21,17 @@ Pools and `CloudOptions` belonged to Cua Cloud, which has ended. Every call here
```python
class Pool
-Pool(
- resource: Any,
- *,
- owned_template: Any = None,
- agent_type: str | None = None,
-)
+Pool(*args: Any, **kwargs: Any)
```
-A Fleet warm pool that can provide durable Sandbox claims.
-
-| Attribute | Type | Description |
-| --- | --- | --- |
-| `name` | `str` | |
-| `resource` | `Any` | |
+A warm pool on Cua Cloud, which has ended. Every call raises
+`cua_sandbox._ended.CloudEnded`.
#### Pool.reconcile
```python
@classmethod
-async def reconcile(request: CreatePoolRequest) -> 'Pool'
+async def reconcile(request: Any) -> 'Pool'
```
#### Pool.get
@@ -57,22 +48,6 @@ async def get(name: str) -> 'Pool'
async def apply(*args: Any, **kwargs: Any) -> 'Pool'
```
-Reconcile a Fleet pool: `Pool.apply(name, spec, options)`.
-
-`spec` (`cua_sandbox.SandboxSpec`) is what the pool's
-sandboxes run and `options` (`cua_sandbox.PoolOptions`) how
-the pool keeps capacity for them. The pool, its namespace and its
-template share `name`, which is globally unique on Fleet. This is
-the SDK's one pool writer (`Fleet.apply`): the image is pinned to
-the variant the runtime runs, a new pool is rolled back if its
-template fails, and a runtime the image cannot run on raises
-`cua.CuaError.InvalidArgument` before anything is created.
-
-The old form `Pool.apply(image, *, name=..., replicas=..., cpu=...,
-memory_mb=..., services=..., autoscaling=..., ttl_seconds_after_created=...,
-runtime=...)` still works and is converted to the new one, with a
-`DeprecationWarning`.
-
#### Pool.export
```python
@@ -80,11 +55,6 @@ runtime=...)` still works and is converted to the new one, with a
async def export(name: str, *, terraform: bool = False) -> 'PoolExport | str'
```
-Read pool `name` back as the shared model (a `PoolExport`
-whose `spec` / `options` are the native records), or with
-`terraform=True` the equivalent Terraform `fleets_pool` block
-(attributes the provider lacks yet are commented).
-
#### Pool.check
```python
@@ -92,10 +62,6 @@ whose `spec` / `options` are the native records), or with
async def check(name: str, spec: SandboxSpec) -> None
```
-Raise `cua_sandbox.PoolSpecMismatch` (with a readable diff)
-when the set fields of `spec` differ from pool `name`'s
-template.
-
#### Pool.apply_template
```python
@@ -103,27 +69,21 @@ template.
async def apply_template(name: str, spec: SandboxSpec) -> None
```
-Lay the set fields of `spec` over pool `name`'s template and
-write it (the pool's capacity is kept; a no-op when nothing
-differs).
-
#### Pool.delete
```python
async def delete() -> None
```
-Delete this Fleet pool.
-
#### Pool.create_claim
```python
async def create_claim(
*,
- spec: ClaimSpec | None = None,
+ spec: Any = None,
name: str | None = None,
ttl_seconds_after_created: int | None = None,
-) -> _ClaimHandle
+) -> Any
```
#### Pool.claim
@@ -131,45 +91,32 @@ async def create_claim(
```python
def claim(
*,
- spec: ClaimSpec | None = None,
+ spec: Any = None,
name: str | None = None,
service: str = ENV_SERVICE,
time_to_start: float | None = None,
ttl_seconds_after_created: int | None = None,
agent_type: str | None = None,
claim_token: str | None = None,
-) -> _ClaimResult[Sandbox]
+) -> Any
```
-Claim a sandbox. `agent_type="osworld"` selects the OSWorld transport
-for pools fetched with `Pool.get` (pools from `Pool.apply` remember it).
-
-`claim_token` (see `generate_claim_token`) is delivered into the
-sandbox at `/run/cua/env-token` through the claim's Secret; the pool's
-spec must set `claim_secrets=True`. The claim waits (at most 90 s
-after it binds) until the sandbox has it, else it is released and
-`cua_sandbox.ClaimSecretsNotDelivered` is raised.
-
### Template
```python
class Template
-Template(resource: Any)
+Template(*args: Any, **kwargs: Any)
```
-A reconciled Fleet sandbox template.
-
-| Attribute | Type | Description |
-| --- | --- | --- |
-| `name` | `str` | |
-| `resource` | `Any` | |
+A sandbox template on Cua Cloud, which has ended. Every call raises
+`cua_sandbox._ended.CloudEnded`.
#### Template.reconcile
```python
@classmethod
-async def reconcile(request: CreateTemplateRequest) -> 'Template'
+async def reconcile(request: Any) -> 'Template'
```
## Managed pools (cua_sandbox.pools)
@@ -184,40 +131,27 @@ away in the next minor release.
### list_pools
```python
-async def list_pools(cfg: Optional[AutoPoolConfig] = None) -> list[ManagedPoolInfo]
+async def list_pools(*args: Any, **kwargs: Any) -> list[ManagedPoolInfo]
```
-This account's managed pools (`cua-auto-*` and legacy `cua-eph-*`).
-
### list_claims
```python
-async def list_claims(cfg: Optional[AutoPoolConfig] = None) -> list[ClaimInfo]
+async def list_claims(*args: Any, **kwargs: Any) -> list[ClaimInfo]
```
-Claims in every pool this account can see (managed and explicit).
-
### gc
```python
-async def gc(
- idle_after: Optional[Duration] = None,
- cfg: Optional[AutoPoolConfig] = None,
-) -> GcReport
+async def gc(*args: Any, **kwargs: Any) -> GcReport
```
-Delete idle managed pools and stuck managed claims now.
-
### gc_pools
```python
-async def gc_pools(names: list[str], idle_after: Duration = 0) -> GcReport
+async def gc_pools(*args: Any, **kwargs: Any) -> GcReport
```
-Delete the named managed pools once they have no claims and have been
-idle for `idle_after` (default: now). Pools with live claims are kept.
-Tests use this to remove exactly the pools they created.
-
### is_managed_pool_name
```python
@@ -320,21 +254,18 @@ SandboxSpec(
)
```
-What a sandbox runs. Unset fields keep Fleet's defaults (and are not
-compared against a named pool's template).
+What a sandbox in a pool ran. Pools belonged to Cua Cloud, which has
+ended; this data class is kept so existing imports keep working.
-* `image`: an `cua_sandbox.Image` (`Image.from_registry(ref,
- secret=...)` carries its registry secret) or a registry reference.
+* `image`: an `cua_sandbox.Image` or a registry reference.
* `command` / `args`: argv replacing the image ENTRYPOINT / CMD.
* `env`: plain environment variables (not secrets).
* `services`: named guest ports, `{"mcp": 8765}`.
-* `wait_for`: `tcp("mcp")` / `http("mcp", "/health")`: a replica
- binds a claim only once it passes.
+* `wait_for`: `tcp("mcp")` / `http("mcp", "/health")`.
* `cpu` / `memory_mb` (or `memory="4GB"`).
* `sidecars`: `cua_sandbox.Container` (or image strings).
-* `registry_secret`: a `cua_sandbox.RegistrySecret`, stored as
- the pool's `cua-registry-*` pull Secret; `registry_secret_name`
- references an existing one.
+* `registry_secret`: a `cua_sandbox.RegistrySecret`;
+ `registry_secret_name` references an existing one.
* `process_mode`: `"Legacy"` or `"Run"`.
* `claim_secrets`: claims may carry a per-claim env token.
@@ -356,22 +287,6 @@ compared against a named pool's template).
| `process_mode` | `Optional[str]` | |
| `claim_secrets` | `bool` | |
-#### SandboxSpec.reference
-
-```python
-def reference() -> str
-```
-
-The image's registry reference (`""` when unset).
-
-#### SandboxSpec.native
-
-```python
-def native() -> Any
-```
-
-The `cua.SandboxSpec` record.
-
### PoolOptions
```python
@@ -390,15 +305,16 @@ PoolOptions(
)
```
-How a pool keeps capacity for a `SandboxSpec`. Unset fields keep
-Fleet's defaults.
+How a pool kept capacity for a `SandboxSpec`. Pools belonged to
+Cua Cloud, which has ended; this data class is kept so existing imports
+keep working.
-* `runtime`: `"gvisor"` or `"kubevirt"` (unset: from the image).
-* `replicas`: size of a pool without autoscaling (default 1).
-* `warm`: keep one sandbox ready (`minPoolSize: 1`).
+* `runtime`: `"gvisor"` or `"kubevirt"`.
+* `replicas`: size of a pool without autoscaling.
+* `warm`: keep one sandbox ready.
* `min_pool_size` / `max_pool_size`: autoscaling floor / ceiling.
* `idle_ttl`: delete the pool after this long without claims.
-* `ttl_policy`: `"Retain"` or `"Cascade"` (what TTL expiry deletes).
+* `ttl_policy`: `"Retain"` or `"Cascade"`.
* `pool_ttl`: pool creation-age TTL.
* `claim_ttl`: default TTL of claims made on the pool.
@@ -416,14 +332,6 @@ Durations are seconds or a `timedelta`.
| `pool_ttl` | `Seconds` | |
| `claim_ttl` | `Seconds` | |
-#### PoolOptions.native
-
-```python
-def native() -> Any
-```
-
-The `cua.PoolOptions` record.
-
### PoolExport
```python
@@ -448,8 +356,7 @@ A pool read back as the shared model (`Pool.export`).
def generate_claim_token() -> str
```
-A fresh per-claim env token (64 hex characters) for
-`pool.claim(claim_token=...)`.
+A fresh per-claim env token (64 hex characters).
## Errors
@@ -460,9 +367,8 @@ class PoolSpecMismatch(InvalidArgument)
```
A named cloud pool's template differs from the sandbox fields given
-with it. The message holds a readable diff; pass
-`CloudOptions(pool=..., apply=True)` to update the pool's template
-instead, or omit the fields to use the pool as it is.
+with it. Pools belonged to Cua Cloud, which has ended; nothing raises this
+any more.
### ClaimSecretsNotDelivered
@@ -471,7 +377,8 @@ class ClaimSecretsNotDelivered(TimeoutError)
```
A claim bound, but its per-claim secrets (the env token) never reached
-the sandbox within the bounded wait (90 s); the claim was released.
+the sandbox. Claims belonged to Cua Cloud, which has ended; nothing raises
+this any more.
### PoolAccessDeniedError
@@ -479,12 +386,5 @@ the sandbox within the bounded wait (90 s); the claim was released.
class PoolAccessDeniedError(PermissionError)
```
-Fleet refused a pool or template operation for this credential.
-
-## Re-exported names
-
-`cua_sandbox` also re-exports these names from other packages; see their own documentation.
-
-| Module | Names |
-| --- | --- |
-| `fleet_sdk` | `ClaimSpec`, `CreatePoolRequest`, `CreatePoolRequestBuilder`, `CreateTemplateRequest`, `CreateTemplateRequestBuilder`, `Firmware`, `OsGymSandboxTemplateSpec`, `OsGymSandboxTemplateSpecBuilder`, `OsGymSandboxWarmPoolSpec`, `OsGymSandboxWarmPoolSpecBuilder`, `RuntimeKind`, `SandboxService`, `SandboxServiceBuilder`, `SandboxTemplateRef`, `SandboxTemplateRefBuilder`, `ServiceProtocol`, `TemplateResource`, `VmTemplate`, `VmTemplateBuilder`, `WarmPoolAutoscaling`, `WarmPoolAutoscalingBuilder` |
+A pool or template operation was refused for this credential. Pools
+belonged to Cua Cloud, which has ended; nothing raises this any more.
diff --git a/docs/content/docs/cua-sdk/reference/python/sandbox.mdx b/docs/content/docs/cua-sdk/reference/python/sandbox.mdx
index 1770052fc5..d2bd9e7fb1 100644
--- a/docs/content/docs/cua-sdk/reference/python/sandbox.mdx
+++ b/docs/content/docs/cua-sdk/reference/python/sandbox.mdx
@@ -60,7 +60,7 @@ async with Sandbox.ephemeral(Image.linux()) as sb:
| Attribute | Type | Description |
| --- | --- | --- |
-| `name` | `Optional[str]` | The sandbox name (`None` until a cloud sandbox is bound). |
+| `name` | `Optional[str]` | The sandbox name. |
| `telemetry_enabled` | `bool` | Whether this sandbox records anonymous usage events. |
| `screen` | `Screen` | Screenshots and screen size (cua-spacesd). |
| `mouse` | `Mouse` | Pointer input in screen pixels (cua-spacesd). |
@@ -76,11 +76,11 @@ async with Sandbox.ephemeral(Image.linux()) as sb:
| `driver` | `Driver` | Typed Cua Driver access (`cua-sandbox[driver]`). |
| `apps` | `Apps` | Install and launch catalog applications (cua-spacesd). |
| `exposed_ports` | `dict` | Map each Image.expose() port to the host port forwarding it. |
-| `image_info` | `Optional[ImageInfo]` | The image this sandbox runs, as resolved and pinned at create time (digest, variant, arch), or `None` when unknown: direct (URL) connections, images not resolved from a registry. A claim on a named Fleet pool reports its template's image (`pinned_ref`/`digest` empty when the registry could not be read). |
-| `claim_name` | `str \| None` | Fleet claim name, distinct from the bound sandbox name. |
-| `pool_name` | `str \| None` | Fleet pool that owns this claim (advanced; see `(await sb.info()).provider_details`). |
-| `location` | `str` | Where it runs: `local`, `cloud` or `direct`. |
-| `id` | `str \| None` | The qualified ref, the same kind of value local and in the cloud: `local:<name>`, `cloud:<name>` or `direct:<host:port>`. It is what `Sandbox.connect(id)` and `Sandbox.delete(id)` take, and what listings print. |
+| `image_info` | `Optional[ImageInfo]` | The image this sandbox runs, as resolved and pinned at create time (digest, variant, arch), or `None` when unknown: direct (URL) connections, images not resolved from a registry. |
+| `claim_name` | `str \| None` | Always `None`: claims belonged to Cua Cloud, which has ended. |
+| `pool_name` | `str \| None` | Always `None`: pools belonged to Cua Cloud, which has ended. |
+| `location` | `str` | Where it runs: `local` or `direct`. |
+| `id` | `str \| None` | The qualified ref: `local:<name>` or `direct:<host:port>`. It is what `Sandbox.connect(id)` and `Sandbox.delete(id)` take, and what listings print. |
#### Sandbox.disconnect
@@ -90,10 +90,6 @@ async def disconnect() -> None
Drop the transport connection. The sandbox keeps running.
-A claim on a managed Fleet pool stops being renewed and lives until
-its shutdown time (`claim_ttl`, or later if `keep_alive` was
-called).
-
#### Sandbox.overlay
```python
@@ -117,8 +113,8 @@ async def info() -> SandboxInfo
```
Portable info: `status` (provisioning, starting, ready, stopped),
-`location` (local, cloud or direct), `services` (name -&gt; guest
-port), `expires_at` (cloud) and `provider_details`.
+`location` (local or direct), `services` (name -&gt; guest port),
+`expires_at` and `provider_details`.
#### Sandbox.service
@@ -127,8 +123,7 @@ def service(name: str) -> 'ServiceHandle'
```
A named service (`services={"mcp": 8765}` at create):
-`request`, `url` and `public_url`, the same local and in the
-cloud.
+`request`, `url` and `public_url`.
#### Sandbox.public_url
@@ -142,9 +137,8 @@ async def public_url(
```
A shareable URL for `service` that stops working after `ttl`
-seconds (60 s to 24 h). Cloud: a signed service URL. Local: a
-loopback URL with its own token, served by the cua daemon (started
-if needed).
+seconds (60 s to 24 h): a loopback URL with its own token, served by
+the cua daemon (started if needed).
#### Sandbox.revoke_public_url
@@ -160,7 +154,8 @@ Revokes a URL from `public_url` (or its id).
def to_dict() -> dict[str, Any]
```
-Serialize a durable Fleet sandbox reference.
+Always raises `CloudEnded`: durable references were Cua Cloud
+claims.
#### Sandbox.from_dict
@@ -169,7 +164,8 @@ Serialize a durable Fleet sandbox reference.
def from_dict(data: dict[str, Any]) -> '_ConnectResult'
```
-Reconnect to a serialized Fleet claim reference.
+Always raises `CloudEnded`: durable references were Cua Cloud
+claims.
#### Sandbox.keep_alive
@@ -177,7 +173,8 @@ Reconnect to a serialized Fleet claim reference.
async def keep_alive(*, minutes: float) -> None
```
-Push a Fleet claim's controller-enforced shutdown time forward.
+Always raises `CloudEnded`: only Cua Cloud claims had a
+shutdown time to push back.
#### Sandbox.close
@@ -185,7 +182,8 @@ Push a Fleet claim's controller-enforced shutdown time forward.
async def close() -> None
```
-Release this Fleet claim; repeated calls are safe.
+Always raises `CloudEnded`: only Cua Cloud claims were
+released. `destroy()` deletes a local sandbox.
#### Sandbox.snapshot
@@ -193,17 +191,8 @@ Release this Fleet claim; repeated calls are safe.
async def snapshot(name: str | None = None, stateful: bool = False) -> 'Image'
```
-Snapshot this sandbox's current state. Returns an Image.
-
-The returned Image can be passed to Sandbox.create() or Sandbox.ephemeral()
-to boot a new sandbox from the snapshot (COW fork: instant on btrfs).
-
-| Parameter | Type | Default | Description |
-| --- | --- | --- | --- |
-| `name` | `str \| None` | `None` | Optional human-readable name for the snapshot. |
-| `stateful` | `bool` | `False` | Whether to capture memory state (VMs only). |
-
-**Returns:** An Image with _snapshot_source set, ready to pass to Sandbox.ephemeral().
+Always raises `CloudEnded`: snapshots were a Cua Cloud
+feature.
#### Sandbox.destroy
@@ -288,9 +277,9 @@ async with sb.mcp("mcp") as client:
result = await client.call_tool("add", {"a": 2, "b": 3})
```
-Requests go through the sandbox's service route (loopback locally, the
-Fleet gateway in the cloud), streamed both ways, so every protocol
-feature and content block works unchanged. No cua-spacesd needed.
+Requests go through the sandbox's service route (loopback), streamed
+both ways, so every protocol feature and content block works
+unchanged. No cua-spacesd needed.
#### Sandbox.mcp_config
@@ -300,7 +289,7 @@ async def mcp_config(service: str, *, path: str = '/mcp') -> dict
`{"url": ..., "headers": {...}}` of `service`'s MCP endpoint, for
any MCP client (Claude Code, Cursor, other SDKs). The headers can carry
-a short-lived Fleet bearer: fetch a fresh config per connection.
+a short-lived bearer: fetch a fresh config per connection.
#### Sandbox.spacesd
@@ -357,38 +346,35 @@ async def create(
) -> 'Sandbox'
```
-Provision or claim a persistent sandbox and return it connected.
+Provision a persistent local sandbox and return it connected.
Where, what kind and which engine are three separate choices:
-* `on`: `"local"` or `"cloud"`. `local=True`/`False` is the
- same switch; `on` and a contradicting `local` is an
- `InvalidArgument`, and so is `local=True` with `cloud=`.
- Unset, `cloud=` implies the cloud; a cloud-only argument (a
- Fleet `pool`, `warm`, `max_pool_size`, `claim_ttl`,
- `claim_spec`, `api_key`, ...) still implies it with a
- `DeprecationWarning`; otherwise the user default applies
- (`CUA_DEFAULT_ON`, else `cua config set default.on cloud` in
- `$CUA_HOME/config.toml`, else local, with a one-time notice that
- `CUA_QUIET_DEFAULT=1` hides).
+* `on`: `"local"`. `local=True` is the same switch; `on` and a
+ contradicting `local` is an `InvalidArgument`. Unset, the
+ user default applies (`CUA_DEFAULT_ON`, else `cua config set
+ default.on` in `$CUA_HOME/config.toml`, else local, with a
+ one-time notice that `CUA_QUIET_DEFAULT=1` hides). Cua Cloud has
+ ended: `on="cloud"`, `local=False`, `cloud=` and the other
+ Cua Cloud arguments (`pool`, `claim_spec`, `api_key`, ...)
+ raise `CloudEnded`.
* `kind`: `"auto"`, `"container"` or `"vm"`. Unset: the
image's `kind` when it has one, else `default.kind`, else auto
(macOS and Windows images are VMs, a container rootfs is a
container, a disk-only image is a VM).
* `runtime`: the engine, `"auto"` or one the location offers for
- the kind: locally `"gvisor"`/`"runc"` (containers) and
- `"qemu"`/`"lume"` (VMs); in the cloud `"gvisor"` and
- `"kubevirt"`. Unset: `default.runtime`, else auto. A local
- sandbox with `sidecars` needs `"runc"` where gVisor would run
+ the kind: `"gvisor"`/`"runc"` (containers) and
+ `"qemu"`/`"lume"` (VMs). Unset: `default.runtime`, else auto.
+ A sandbox with `sidecars` needs `"runc"` where gVisor would run
(separate gVisor containers cannot share a network namespace).
A `Runtime` object (`DockerRuntime()`, `TartRuntime()`,
...) still picks a local adapter, as before.
A combination that does not exist (`kind="container",
-runtime="qemu"`, or `runtime="kubevirt"` locally) raises
-`InvalidPlacement`, listing the valid values.
+runtime="qemu"`) raises `InvalidPlacement`, listing the valid
+values.
-The same options mean the same thing local and in the cloud:
+Options:
* `command`: argv replacing the image's entrypoint.
* `env`: environment variables.
@@ -397,15 +383,11 @@ The same options mean the same thing local and in the cloud:
`sb.tunnel.forward(8765)`.
* `wait_for`: `tcp("mcp")` / `http("mcp", "/health")` (or a
list); readiness otherwise is "the sandbox is running".
-* `cloud`: `CloudOptions` (warm capacity, limits, TTL, a
- dedicated pool). The flat `pool`, `warm`, `max_pool_size` and
- `claim_ttl` keywords are deprecated aliases.
* `memory`: `"4GB"` / `"512MB"` (or `memory_mb`).
* `network`: `"default"` (outbound network, like a Docker
container) or `"none"` (no egress; the SDK still reaches the
guest's published ports). `"none"` needs a local QEMU VM;
- containers, Lume and cloud sandboxes raise `Unsupported`.
-
+ containers and Lume raise `Unsupported`.
* `overlay`: binaries to inject once it is up, so tests run the
build under test and not the copy the image bundles:
`{"cua-driver": "./target/release/cua-driver"}` (`cua-driver` and
@@ -415,32 +397,14 @@ The same options mean the same thing local and in the cloud:
it is restarted. If it fails, the sandbox is deleted and the error
raised. See `overlay`.
-Supplying `pool` claims from an existing Fleet pool without changing
-its configuration.
-
-A Fleet registry image without `pool` is claimed from this
-account's managed pool for that image spec (`cua-auto-*`), created
-on first use and reused afterwards. The first start of an image can
-take a few minutes; later starts reuse its capacity. Fleet-only
-options:
-
-* `warm`: seed one ready replica when the pool is first created.
-* `max_pool_size`: autoscaling ceiling (default 10).
-* `claim_ttl`: seconds (or a timedelta) the claim outlives this
- process; it is renewed while the process holds it (default 15 min).
- Use `keep_alive(minutes=...)` to keep a sandbox longer.
-* `progress`: callback receiving `AcquireProgress` events.
-
-Without `on`/`local`, passing one of them keeps the sandbox in
-the cloud (deprecated: pass `local=False`); with `local=True` they
-are ignored. An existing `pool` keeps its own kind and runtime
-(`Pool.apply(..., runtime=)`).
-
-`server_port` names a port your image serves itself: it is exposed
-(Fleet: as the `server` service) and becomes the readiness probe.
-Leave it unset for the default, daemon-agnostic readiness (the
-provider reports the sandbox running; cua-spacesd on 3211 is used
-by the interfaces when the image has it).
+`warm`, `max_pool_size`, `claim_ttl`, `progress` and
+`keep_alive_minutes` configured Cua Cloud claims; a local sandbox
+ignores them.
+
+`server_port` names a port your image serves itself: it becomes the
+readiness probe. Leave it unset for the default, daemon-agnostic
+readiness (the provider reports the sandbox running; cua-spacesd on
+3211 is used by the interfaces when the image has it).
**Example**
@@ -507,15 +471,15 @@ async with Sandbox.connect("my-sandbox") as sb:
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
-| `name` | `Optional[str]` | `None` | A sandbox ref (`local:<name>`, `cloud:<name>`, `direct:<host:port>`, a legacy id) or a name. A bare name must be unique across locations, else `AmbiguousSandbox` lists the refs it matches. |
-| `local` | `Optional[bool]` | `None` | `None` (default): search every location. `True`/ `False` narrow a bare name to local or cloud. |
-| `url` | `Optional[str]` | `None` | A cua-spacesd URL to connect to directly (`http://host:3211`, a relay URL or a Fleet service URL). |
+| `name` | `Optional[str]` | `None` | A sandbox ref (`local:<name>`, `direct:<host:port>`, a legacy id) or a name. A `cloud:<name>` ref raises `CloudEnded`: Cua Cloud has ended. |
+| `local` | `Optional[bool]` | `None` | `None` (default): the local sandbox `name`. `False` raises `CloudEnded`. |
+| `url` | `Optional[str]` | `None` | A cua-spacesd URL to connect to directly (`http://host:3211` or a relay URL). |
| `token` | `Optional[str]` | `None` | The spacesd token for `url`. |
-| `api_key` | `Optional[str]` | `None` | Legacy CUA API key (API-key cloud VMs were removed; see `cua_sandbox.transport.cloud`). |
+| `api_key` | `Optional[str]` | `None` | Used as the spacesd token for `url` when `token` is not given. |
| `ws_url` | `Optional[str]` | `None` | Removed (the computer-server WebSocket protocol is gone). |
| `http_url` | `Optional[str]` | `None` | Base URL of a cua-spacesd (same as `url`). |
| `container_name` | `Optional[str]` | `None` | Unused; kept for compatibility. |
-| `region` | `str` | `'us-east-1'` | Cloud region (default `"us-east-1"`). |
+| `region` | `str` | `'us-east-1'` | Unused; kept for compatibility. |
**Example**
@@ -576,18 +540,12 @@ async def ephemeral(
) -> AsyncIterator['Sandbox']
```
-A sandbox that is released when the `async with` block exits.
+A local sandbox that is deleted when the `async with` block exits.
Takes the same `on`/`local`, `kind`, `runtime`, `command`,
`env`, `services`, `wait_for`, `cloud`, `memory` and
-`network` options as `create`.
-
-A Fleet registry image without `pool` is claimed from this
-account's reusable managed pool (see `create` for `warm`,
-`max_pool_size`, `claim_ttl` and `progress`). Exiting releases
-the claim; the pool stays for the next run and idle GC deletes it
-once unused. If the process dies, the claim expires after
-`claim_ttl`. `keep_pool` is deprecated and has no effect.
+`network` options as `create`. `keep_pool` is deprecated and
+has no effect.
#### Sandbox.list
@@ -602,20 +560,15 @@ async def list(
) -> 'list[SandboxInfo]'
```
-List sandboxes, each with its `location`, `kind` and
-`runtime`: local and cloud ones by default.
-
-The cloud part never fails the default listing: without cloud
-credentials it is left out silently, and when the cloud fails or does
-not answer within 5 s the local rows come back with a logged warning
-("cloud sandboxes not listed: ...").
+List the local sandboxes (containers, QEMU, Lume, Android), each
+with its `location`, `kind` and `runtime`.
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
-| `location` | `Optional[str]` | `None` | `None` (default): local and cloud. `"local"`: only the local ones (containers, QEMU, Lume, Android). `"cloud"`: only the cloud ones. |
+| `location` | `Optional[str]` | `None` | `None` (default) or `"local"`: the local sandboxes. `"cloud"` raises `CloudEnded`: Cua Cloud has ended. |
| `local` | `Optional[bool]` | `None` | The same switch as a bool (`True` is `"local"`, `False` is `"cloud"`). |
| `all` | `Optional[bool]` | `None` | Deprecated; everything is the default. |
-| `api_key` | `Optional[str]` | `None` | Legacy CUA API key for api.cua.ai VMs. |
+| `api_key` | `Optional[str]` | `None` | Unused; kept for compatibility. |
#### Sandbox.get_info
@@ -633,9 +586,9 @@ Get metadata for a specific sandbox.
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
-| `name` | `str` | required | Sandbox ref (`local:<name>`, `cloud:<name>`) or a name unique across locations. |
-| `local` | `Optional[bool]` | `None` | `True`/`False` narrow a bare name to local or cloud. `None` (default): the local sandbox `name` when one exists (and no cloud sandbox shares it), else the cloud. |
-| `api_key` | `Optional[str]` | `None` | CUA API key for cloud. |
+| `name` | `str` | required | Sandbox ref (`local:<name>`) or a name. A `cloud:<name>` ref raises `CloudEnded`: Cua Cloud has ended. |
+| `local` | `Optional[bool]` | `None` | `None` (default) or `True`: the local sandbox `name`. `False` raises `CloudEnded`. |
+| `api_key` | `Optional[str]` | `None` | Unused; kept for compatibility. |
#### Sandbox.suspend
@@ -649,20 +602,18 @@ async def suspend(
) -> None
```
-Suspend the sandbox `name`, keeping its state; `resume`
-continues it. Only that sandbox is affected.
+Suspend the local sandbox `name`, keeping its state;
+`resume` continues it. Only that sandbox is affected.
-Local: the SDK suspends it on its backend (a container is paused or
+The SDK suspends it on its backend (a container is paused or
checkpointed, a QEMU VM snapshotted, a Lume VM stopped with its
-disk). Cloud: a Fleet sandbox cannot be suspended on its own, so this
-raises `Unsupported`; keep it with `keep_alive()` or release
-it with `delete`. A legacy api.cua.ai VM (an API key) stops.
+disk).
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `str` | required | Sandbox name. |
-| `local` | `Optional[bool]` | `None` | `None` (default): the local sandbox `name` when one exists, else the cloud. `True`/`False` decide. |
-| `api_key` | `Optional[str]` | `None` | Legacy CUA API key (api.cua.ai VMs). |
+| `local` | `Optional[bool]` | `None` | `None` (default) or `True`: the local sandbox `name`. `False` raises `CloudEnded`: Cua Cloud has ended. |
+| `api_key` | `Optional[str]` | `None` | Unused; kept for compatibility. |
#### Sandbox.resume
@@ -676,18 +627,14 @@ async def resume(
) -> 'Sandbox'
```
-Resume the suspended sandbox `name` and return it connected.
-
-Local: the backend resumes it. Cloud: a running sandbox just
-reconnects (a Fleet sandbox is never suspended); one that is gone
-raises `Unsupported`. A legacy api.cua.ai VM (an API key)
-starts.
+Resume the suspended local sandbox `name` and return it
+connected. The backend resumes it.
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `str` | required | Sandbox name. |
-| `local` | `Optional[bool]` | `None` | `None` (default): the local sandbox `name` when one exists, else the cloud. |
-| `api_key` | `Optional[str]` | `None` | Legacy CUA API key (api.cua.ai VMs). |
+| `local` | `Optional[bool]` | `None` | `None` (default) or `True`: the local sandbox `name`. `False` raises `CloudEnded`: Cua Cloud has ended. |
+| `api_key` | `Optional[str]` | `None` | Unused; kept for compatibility. |
**Returns:** A connected Sandbox ready to use.
@@ -703,15 +650,14 @@ async def restart(
) -> 'Sandbox'
```
-Restart the sandbox `name` (suspend then resume) and return it
-connected. Local only (see `suspend`): a Fleet sandbox raises
-`Unsupported`.
+Restart the local sandbox `name` (suspend then resume) and return
+it connected (see `suspend`).
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `str` | required | Sandbox name. |
-| `local` | `Optional[bool]` | `None` | `None` (default): the local sandbox `name` when one exists, else the cloud. |
-| `api_key` | `Optional[str]` | `None` | Legacy CUA API key (api.cua.ai VMs). |
+| `local` | `Optional[bool]` | `None` | `None` (default) or `True`: the local sandbox `name`. `False` raises `CloudEnded`: Cua Cloud has ended. |
+| `api_key` | `Optional[str]` | `None` | Unused; kept for compatibility. |
**Returns:** A connected Sandbox ready to use.
@@ -727,16 +673,14 @@ async def delete(
) -> None
```
-Permanently delete a sandbox.
-
-For local sandboxes, stops the VM and removes the state file.
-For cloud sandboxes, calls DELETE /v1/vms/&#123;name&#125;.
+Permanently delete a local sandbox: stops the VM or container and
+removes the state file.
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `str` | required | Sandbox name. |
-| `local` | `Optional[bool]` | `None` | If True, delete a local sandbox. `None` (default): the local sandbox `name` when one exists, else the cloud. |
-| `api_key` | `Optional[str]` | `None` | CUA API key for cloud. |
+| `local` | `Optional[bool]` | `None` | `None` (default) or `True`: the local sandbox `name`. `False` raises `CloudEnded`: Cua Cloud has ended. |
+| `api_key` | `Optional[str]` | `None` | Unused; kept for compatibility. |
### sandbox
@@ -803,12 +747,12 @@ SandboxInfo(
)
```
-Metadata for a local or cloud sandbox.
+Metadata for a local sandbox.
`status` from `Sandbox.info` is portable: `provisioning`,
`starting`, `ready` or `stopped`. Listings keep the provider's word
-(`running`, `suspended`, ...). Provider internals (the cloud pool,
-namespace and claim; the local backend) are in `provider_details`.
+(`running`, `suspended`, ...). Provider internals (the local backend)
+are in `provider_details`.
| Attribute | Type | Description |
| --- | --- | --- |
@@ -844,24 +788,16 @@ CloudOptions(
)
```
-Advanced options for cloud sandboxes. Passing them implies the cloud;
-with `on="local"`/`local=True` they are an `InvalidArgument`. The
-engine is `Sandbox.create(runtime="gvisor"|"kubevirt")`, not a cloud
-option.
-
-* `warm`: keep one sandbox of this image ready (faster next start).
-* `max_pool_size`: most sandboxes of this image at once (default 10).
-* `claim_ttl`: how long the sandbox outlives this process without a
- `keep_alive` (seconds or a timedelta; renewed while held; default
- 15 min).
-* `pool`: dedicated capacity: claim from this existing pool. Sandbox
- fields given with it (`image`, `command`, `env`, `services`,
- `sidecars`, `cpu`, `memory`, a registry secret) must match the
- pool's template, else `cua_sandbox.PoolSpecMismatch` (with a
- readable diff) is raised; fields left unset are not compared.
-* `apply`: with `pool`, update the pool's template to the given
- fields instead (the pool's capacity is kept; managed `cua-auto-*`
- pools refuse it).
+Options for Cua Cloud sandboxes. Cua Cloud has ended: passing
+`cloud=` to `Sandbox.create` or `Sandbox.ephemeral` raises
+`cua_sandbox._ended.CloudEnded`, and the class goes away in the
+next minor release.
+
+* `warm`: keep one sandbox of this image ready.
+* `max_pool_size`: most sandboxes of this image at once.
+* `claim_ttl`: how long the sandbox outlived the process.
+* `pool`: claim from this existing pool.
+* `apply`: with `pool`, update the pool's template.
| Attribute | Type | Description |
| --- | --- | --- |
@@ -926,8 +862,8 @@ PublicUrl(
```
A shareable URL of a sandbox service that stops working at
-`expires_at`. Cloud: a signed service URL; local: a loopback URL with
-its own token, served by the cua daemon.
+`expires_at`: a loopback URL with its own token, served by the cua
+daemon.
| Attribute | Type | Description |
| --- | --- | --- |
diff --git a/libs/cua-bench-rl/uv.lock b/libs/cua-bench-rl/uv.lock
index 476b67d33a..55d73f78de 100644
--- a/libs/cua-bench-rl/uv.lock
+++ b/libs/cua-bench-rl/uv.lock
@@ -681,18 +681,6 @@ provides-extras = ["otel", "telemetry"]
[package.metadata.requires-dev]
dev = [{ name = "pytest", specifier = ">=8.3.5" }]
-[[package]]
-name = "cua-fleet"
-version = "0.1.17"
-source = { registry = "https://pypi.org/simple" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/55/2a/406cc8d9a6f79368cd9a78361ba45c98909498068c345d5a92d3b8b5788e/cua_fleet-0.1.17-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:a8908b5c7f0f3c75d09b908b58867d43270f69d3726bb0d90316443f2265d0e3", size = 2281312, upload-time = "2026-09-11T02:55:56.726Z" },
- { url = "https://files.pythonhosted.org/packages/6c/f5/7fc0160aa7b7f5c2ca110ba40d9c47acbdc76f4919e07621943403b39b4e/cua_fleet-0.1.17-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6aea577f21343326aeb06df03c07df65df8dd2f3b0097e02f25a7bc6b9d2c458", size = 2227112, upload-time = "2026-09-11T02:55:57.916Z" },
- { url = "https://files.pythonhosted.org/packages/cb/51/da3b0b7c6bfb22c0f1e5bdf016b120c9ba11d045a3e97ccb65234eda80a2/cua_fleet-0.1.17-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:bda49298c77c65eb349e8420f9237f6b7fb2fd25203747df98a9513b98fd5d73", size = 2596935, upload-time = "2026-09-11T02:55:59.122Z" },
- { url = "https://files.pythonhosted.org/packages/31/a4/5137ff02e053181ce23f10fe53f1cc6e97165e925e6a00f97919d904fc6f/cua_fleet-0.1.17-py3-none-manylinux_2_34_x86_64.whl", hash = "sha256:4cdbc89e850d841481713abf1e8bf9719b2e33b3c31f26bbea5f63e1ead3c6c0", size = 2531926, upload-time = "2026-09-11T02:56:00.117Z" },
- { url = "https://files.pythonhosted.org/packages/69/ab/cb222383d430cb6cef133e8b3f487e3482cb68823ef90047d1df2c9f3221/cua_fleet-0.1.17-py3-none-win_amd64.whl", hash = "sha256:ee4c139b1c0cebe1702114a34fd0fd60d216c5862d9fdc3472bb8b9879ac9eae", size = 2119057, upload-time = "2026-09-11T02:56:01.225Z" },
-]
-
[[package]]
name = "cua-sandbox"
version = "0.9.0"
@@ -700,7 +688,6 @@ source = { editable = "../python/cua-sandbox" }
dependencies = [
{ name = "cua" },
{ name = "cua-core" },
- { name = "cua-fleet" },
{ name = "grpcio" },
{ name = "httpx" },
{ name = "jsonschema" },
@@ -717,7 +704,6 @@ requires-dist = [
{ name = "cua", editable = "../cua/python" },
{ name = "cua-core", specifier = ">=0.1.18,<0.4.0" },
{ name = "cua-driver", marker = "extra == 'driver'", specifier = "==0.28.2" },
- { name = "cua-fleet", specifier = "==0.1.17" },
{ name = "grpcio", specifier = "==1.78.0" },
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "jsonschema", specifier = ">=4.23,<5.0" },
diff --git a/libs/cua-bench/README.md b/libs/cua-bench/README.md
index 7699cf073e..cef0073786 100644
--- a/libs/cua-bench/README.md
+++ b/libs/cua-bench/README.md
@@ -58,8 +58,8 @@ Results land in `~/.local/share/cua-bench/runs/<run id>/<task>_v<n>/` (`run.log`
`cb run list | info | watch | logs | stop` inspect runs; `cb dataset build <run dir>`
exports traces (aguvis-stage-1, gui-r1).
-- `result.json` records what ran (`on`, `backend` such as `local-gvisor` or
- `cloud-kubevirt`, the `sandbox` ref such as `local:<name>` or `cloud:<name>`,
+- `result.json` records what ran (`on`, `backend` such as `local-gvisor`, the
+ `sandbox` ref such as `local:<name>`,
`kind`, `runtime` (the engine, when one was chosen), `image_ref`,
`image_variant`, `image_digest` as the pinned `repo@sha256`, `arch`) and carries
Harbor's trial fields (`task_name`, `trial_name`, `verifier_result.rewards`,
@@ -143,7 +143,7 @@ task's agent log directory (`harness-events.jsonl`, `harness-result.json`).
Agents' Last Exam): `run_command` reports `return_code` 0 unless
`strict_exit_codes=True`, there is no shell timeout unless `timeout=` is set, `api_url`
sessions speak to computer-server (or cua-spacesd: port 3211 or a sandbox ref such as
- `local:<name>`, `cloud:<name>`, `direct:<host:port>`), and `session.interface`
+ `local:<name>`, `direct:<host:port>`), and `session.interface`
keeps the cua-computer method set. `scripts/ale_compat/check_ale.py` checks ALE against
a checkout.
@@ -156,7 +156,7 @@ uv run pytest -q cua_bench/tests --ignore=cua_bench/tests/live
The suite is hermetic: cua-sandbox is replaced by an in-memory sandbox
(`cua_bench/tests/fakes.py`) and a loopback computer-server stand-in, so nothing starts a
-container, VM or cloud claim. It includes the CLI parser golden
+container or VM. It includes the CLI parser golden
(`tests/golden/cli_tree.json`), export schema snapshots and the ALE compatibility tests.
After a deliberate, additive CLI or schema change, regenerate the goldens with
`CUA_BENCH_UPDATE_GOLDENS=1` and review the diff.
diff --git a/libs/cua-bench/cua_bench/adapters/base.py b/libs/cua-bench/cua_bench/adapters/base.py
index 687049b4cc..fb79415faf 100644
--- a/libs/cua-bench/cua_bench/adapters/base.py
+++ b/libs/cua-bench/cua_bench/adapters/base.py
@@ -31,7 +31,7 @@ What the base class does for every adapter:
kind selection (``--kind auto|container|vm``, VM-only OSes) and the
requirement check happen in ``cb run`` before any sandbox starts;
* :class:`Endpoints` (``ep``): the benchmark's own server and other guest
- ports, the same way locally and on Fleet;
+ ports;
* timeouts: setup, evaluate and the oracle are bounded (``timeouts``).
"""
@@ -61,7 +61,7 @@ class ServerSpec:
class Endpoints:
- """How an adapter reaches guest ports, the same locally and on Fleet.
+ """How an adapter reaches guest ports.
* ``await ep.url()`` / ``await ep.url("server")``: the benchmark server;
* ``await ep.url(9222)``: any exposed guest port;
@@ -69,8 +69,8 @@ class Endpoints:
request through the SDK's service API;
* ``await ep.host_port(9222)``: a ``(host, port)`` for code that builds
``http://{host}:{port}/...`` itself (upstream controllers). Locally that
- is the published port; when the service URL has a path prefix (Fleet
- signed URLs) it is a loopback :class:`~cua_bench.adapters.bridge.PathBridge`
+ is the published port; when the service URL has a path prefix (a
+ signed URL) it is a loopback :class:`~cua_bench.adapters.bridge.PathBridge`
to it, closed by ``await ep.aclose()``.
Sessions attached to a legacy computer-server by URL (no cua-sandbox
diff --git a/libs/cua-bench/cua_bench/adapters/bridge.py b/libs/cua-bench/cua_bench/adapters/bridge.py
index dd5308004e..433662a9fe 100644
--- a/libs/cua-bench/cua_bench/adapters/bridge.py
+++ b/libs/cua-bench/cua_bench/adapters/bridge.py
@@ -3,9 +3,9 @@
Upstream benchmark controllers (OSWorld's ``PythonController`` and
``SetupController``, CDP clients, BrowserGym ...) take a host and a port and
build ``http://{host}:{port}/path`` themselves. Locally a guest port is
-exactly that (``http://127.0.0.1:<published>``). On Fleet a service is a
-signed URL such as ``https://<gateway>/api/svc/<ns>/<sandbox>-<svc>?...``: a
-path prefix (and maybe a query) that such code cannot express.
+exactly that (``http://127.0.0.1:<published>``). A service behind a signed URL
+such as ``https://<gateway>/api/svc/<ns>/<sandbox>-<svc>?...`` has a path
+prefix (and maybe a query) that such code cannot express.
:class:`PathBridge` listens on ``127.0.0.1:<ephemeral>`` and forwards every
request to the URL:
diff --git a/libs/cua-bench/cua_bench/adapters/web.py b/libs/cua-bench/cua_bench/adapters/web.py
index 6948528bf6..ab4958286d 100644
--- a/libs/cua-bench/cua_bench/adapters/web.py
+++ b/libs/cua-bench/cua_bench/adapters/web.py
@@ -4,7 +4,7 @@
on :7000, a small HTTP API over the browser's DevTools (``POST /reset
{url}``, ``POST /navigate``, ``POST /eval {expression}``, ``GET /state``,
``GET /healthz``). Adapters talk to it through ``ep.request("server", ...)``,
-plain HTTP that works the same locally and through the Fleet gateway. The
+plain HTTP that works through the sandbox's service API. The
agent acts on the visible browser through cua-driver like on any desktop.
Answers: an agent that produces a final text answer sets
diff --git a/libs/cua-bench/cua_bench/cli/commands/env.py b/libs/cua-bench/cua_bench/cli/commands/env.py
index 5e49ae8032..e8067efda4 100644
--- a/libs/cua-bench/cua_bench/cli/commands/env.py
+++ b/libs/cua-bench/cua_bench/cli/commands/env.py
@@ -1,25 +1,21 @@
"""``cb env``: the sandboxes behind ``cb run``.
- cb env ls managed cloud pools (cua-auto-*) and their claims
cb env ls --local local sandboxes
- cb env gc [--idle 30m] delete idle managed pools and stuck claims now
+ cb env ls | gc managed cloud pools: Cua Cloud has ended, so they fail
-Managed pools are created and reused by cua-sandbox for ``--on cloud`` runs;
-they scale to zero when idle and are garbage collected after
-``CUA_FLEET_POOL_IDLE_GC`` (30 min) automatically. ``gc`` just does it now.
+Managed cloud pools belonged to Cua Cloud, which has ended: ``cb env ls``
+(without ``--local``) and ``cb env gc`` print the one "Cua Cloud has ended"
+error.
"""
from __future__ import annotations
+
+import asyncio
+
from cua_bench._ended import CLOUD_ENDED
from ._help import examples
-import asyncio
-import shutil
-import subprocess
-from datetime import datetime, timezone
-from typing import Any, Optional
-
RESET = "\033[0m"
BOLD = "\033[1m"
GREEN = "\033[92m"
@@ -58,43 +54,6 @@ def register_parser(subparsers) -> None:
gc.add_argument("--idle", default="30m", help="Delete pools unused for this long (default 30m)")
-def _age(value: Any) -> str:
- if value is None:
- return "-"
- if isinstance(value, str):
- try:
- value = datetime.fromisoformat(value.replace("Z", "+00:00"))
- except ValueError:
- return value
- if isinstance(value, datetime):
- if value.tzinfo is None:
- value = value.replace(tzinfo=timezone.utc)
- seconds = int((datetime.now(timezone.utc) - value).total_seconds())
- for unit, size in (("d", 86400), ("h", 3600), ("m", 60)):
- if seconds >= size:
- return f"{seconds // size}{unit} ago"
- return f"{max(seconds, 0)}s ago"
- return str(value)
-
-
-def _cua_passthrough(args_list: list[str]) -> Optional[int]:
- cua = shutil.which("cua")
- if cua is None:
- return None
- return subprocess.call([cua, "fleet", "pools", *args_list])
-
-
-def _require_auth() -> bool:
- from cua_bench.sandboxes import CloudAuthError, cloud_auth_source
-
- try:
- cloud_auth_source()
- except CloudAuthError as error:
- print(f"{RED}{error}{RESET}")
- return False
- return True
-
-
async def _list_local() -> int:
from cua_sandbox import Sandbox
@@ -109,43 +68,7 @@ async def _list_local() -> int:
return 0
-async def _list_cloud(autopool: Any) -> int:
- pools = await autopool.list_pools()
- claims = await autopool.list_claims()
- if not pools:
- print(f"{GREY}No managed pools. cb run <task> --on cloud creates one per image.{RESET}")
- else:
- print(f"{BOLD}{'POOL':<32} {'READY/REPLICAS':<14} {'CLAIMS':<6} LAST USED{RESET}")
- for pool in pools:
- ready = f"{pool.ready_replicas or 0}/{pool.replicas or 0}"
- print(f"{pool.name:<32} {ready:<14} {pool.claims:<6} {_age(pool.last_used)}")
- managed = [c for c in claims if c.managed]
- if managed:
- print(f"\n{BOLD}{'CLAIM':<40} {'POOL':<32} PHASE{RESET}")
- for claim in managed:
- print(f"{claim.name:<40} {claim.pool:<32} {claim.phase or '-'}")
- return 0
-
-
-async def _gc(autopool: Any, idle: str) -> int:
- from cua_bench.targets import parse_duration_s
-
- report = await autopool.gc(parse_duration_s(idle))
- for name in report.pools_deleted:
- print(f"{GREEN}deleted pool{RESET} {name}")
- for name in report.claims_deleted:
- print(f"{GREEN}deleted claim{RESET} {name}")
- for error in report.errors:
- print(f"{RED}error{RESET} {error}")
- if not (report.pools_deleted or report.claims_deleted or report.errors):
- print(f"{GREY}Nothing to collect.{RESET}")
- return 1 if report.errors else 0
-
-
def execute(args) -> int:
- from cua_bench.sandboxes import pools_module
- from cua_bench.targets import TargetError
-
command = getattr(args, "env_command", None)
if command in ("ls", "list") and getattr(args, "local", False):
return asyncio.run(_list_local())
@@ -155,25 +78,3 @@ def execute(args) -> int:
# Cua Cloud has ended: there are no managed pools to list or collect.
print(f"{RED}Error: {CLOUD_ENDED}{RESET}")
return 1
- if not _require_auth():
- return 1
- try:
- pools = pools_module()
- except ImportError:
- # An older cua-sandbox without the public pools API: the `cua` CLI.
- passthrough = ["gc", "--idle", args.idle] if command == "gc" else ["ls"]
- code = _cua_passthrough(passthrough)
- if code is None:
- print(
- f"{RED}Managed pools need cua-sandbox >= 0.9 (cua_sandbox.pools) or the `cua` "
- f"CLI on PATH (cua fleet pools {' '.join(passthrough)}).{RESET}"
- )
- return 1
- return code
- try:
- if command == "gc":
- return asyncio.run(_gc(pools, args.idle))
- return asyncio.run(_list_cloud(pools))
- except TargetError as error:
- print(f"{RED}Error: {error}{RESET}")
- return 1
diff --git a/libs/cua-bench/cua_bench/cli/commands/interact.py b/libs/cua-bench/cua_bench/cli/commands/interact.py
index 0d5aee1b21..777af1d74a 100644
--- a/libs/cua-bench/cua_bench/cli/commands/interact.py
+++ b/libs/cua-bench/cua_bench/cli/commands/interact.py
@@ -141,7 +141,7 @@ async def _execute_native_interactive(
"""Open the task's sandbox (local or cloud), run setup and hand it to the user."""
from cua_bench import make
from cua_bench.computers.remote import RemoteDesktopSession
- from cua_bench.sandboxes import CloudAuthError, cloud_auth_source, explain_error, open_sandbox
+ from cua_bench.sandboxes import explain_error, open_sandbox
from cua_bench.targets import TargetError, resolve_env_spec
from .run import target_from_args
@@ -167,9 +167,7 @@ async def _execute_native_interactive(
from cua_bench.targets import check_requirements
check_requirements([spec], target)
- if target.cloud:
- cloud_auth_source()
- except (TargetError, CloudAuthError) as error:
+ except TargetError as error:
print(f"{RED}{error}{RESET}")
return 1
diff --git a/libs/cua-bench/cua_bench/cli/commands/login.py b/libs/cua-bench/cua_bench/cli/commands/login.py
index 4cde94802b..962d9d3db1 100644
--- a/libs/cua-bench/cua_bench/cli/commands/login.py
+++ b/libs/cua-bench/cua_bench/cli/commands/login.py
@@ -1,38 +1,18 @@
-"""``cb login``: sign in for ``--on cloud`` through the ``cua`` CLI.
+"""``cb login``: removed with Cua Cloud.
-Cloud runs authenticate like every cua tool: ``cua auth login`` (a stored
-session), or ``CUA_CLIENT_ID``/``CUA_CLIENT_SECRET`` from
-``cua auth keys create``, or ``FLEETS_TOKEN``.
+``cb login`` signed in for ``--on cloud``. Cua Cloud has ended, so the command
+prints the one "Cua Cloud has ended" error.
"""
from __future__ import annotations
-import shutil
-import subprocess
-
from cua_bench._ended import CLOUD_ENDED
RESET = "\033[0m"
-GREEN = "\033[92m"
RED = "\033[91m"
-GREY = "\033[90m"
-
-INSTALL_HINT = "Install the cua CLI: curl -fsSL https://cua.ai/install.sh | sh"
def execute(args) -> int:
# Cua Cloud has ended: there is nothing to sign in to for --on cloud.
print(f"{RED}Error: {CLOUD_ENDED}{RESET}")
return 1
- cua = shutil.which("cua")
- if cua is None:
- print(f"{RED}The `cua` CLI is not on PATH.{RESET} {INSTALL_HINT}")
- print(f"{GREY}Or set CUA_CLIENT_ID and CUA_CLIENT_SECRET (or FLEETS_TOKEN).{RESET}")
- return 1
- cmd = [cua, "auth", "login"]
- if getattr(args, "no_browser", False):
- cmd.append("--no-browser")
- code = subprocess.call(cmd)
- if code == 0:
- print(f"{GREEN}✓ Signed in. Run tasks in the cloud with: cb run <task> --on cloud{RESET}")
- return code
diff --git a/libs/cua-bench/cua_bench/cli/commands/run.py b/libs/cua-bench/cua_bench/cli/commands/run.py
index 63bb0c6d5c..cb399969c0 100644
--- a/libs/cua-bench/cua_bench/cli/commands/run.py
+++ b/libs/cua-bench/cua_bench/cli/commands/run.py
@@ -7,7 +7,7 @@ Usage:
cb run list | info <id> | watch <id> | logs <id> | stop <id>
Both targets use the same runner: each variant gets a cua-sandbox sandbox
-(local gVisor container / QEMU / Lume, or a claim on a managed Fleet pool),
+(a local gVisor container / QEMU / Lume, or a machine of your own cloud),
the task's setup, the oracle or agent, and evaluate() run in this process,
and results land in ``$XDG_DATA_HOME/cua-bench/runs/<run id>/``.
"""
@@ -85,28 +85,21 @@ def add_target_args(parser) -> None:
"--runtime",
choices=["auto", "gvisor", "runc", "qemu", "lume", "kubevirt"],
default=None,
- help="Which engine: gvisor or runc (local containers), qemu or lume (local VMs), "
- "gvisor or kubevirt (cloud containers, VMs). Implies its kind. Default auto: the "
- "SDK picks (CUA_DEFAULT_RUNTIME, else `cua config set default.runtime`)",
+ help="Which engine: gvisor or runc (containers), qemu or lume (VMs). Implies its "
+ "kind. Default auto: the SDK picks (CUA_DEFAULT_RUNTIME, else "
+ "`cua config set default.runtime`)",
)
group.add_argument(
"--image",
help="Image for every task (overrides the task's setup_config.image): an OS alias "
- "(linux, windows, macos:tahoe), ghcr.io/trycua/<os>, any registry ref or a digest, "
- "or pool:<name> for an existing Fleet pool. Env: CUA_BENCH_IMAGE",
+ "(linux, windows, macos:tahoe), ghcr.io/trycua/<os>, any registry ref or a digest. "
+ "Env: CUA_BENCH_IMAGE",
)
group.add_argument("--cpu", type=int, help="vCPUs per sandbox")
group.add_argument("--memory", help="Memory per sandbox (e.g. 4096, 4G)")
- group.add_argument(
- "--warm",
- action="store_true",
- help="cloud: keep one replica ready when the managed pool is first created",
- )
- group.add_argument(
- "--claim-ttl",
- dest="claim_ttl",
- help="cloud: how long a claim outlives a crashed run (default 15m; renewed while running)",
- )
+ # Deprecated no-ops: they configured Cua Cloud's managed pools, which have ended.
+ group.add_argument("--warm", action="store_true", help=argparse.SUPPRESS)
+ group.add_argument("--claim-ttl", dest="claim_ttl", help=argparse.SUPPRESS)
# cua-bench 0.2.11 flags, deprecated (a notice names the new flags).
group.add_argument(
"--platform",
@@ -197,27 +190,16 @@ class ConsoleReporter:
pass
def plan(self, target, jobs, plans) -> None:
- sandboxed = sum(1 for job in jobs if job.spec.needs_sandbox)
backends = sorted({job.spec.backend(target.on) for job in jobs})
self.line(
f"{len(jobs)} variant(s) on {self._c(BOLD, target.on)} "
f"({', '.join(backends)}), up to {target.concurrency} at a time"
)
for plan in plans:
- where = "managed pool" if target.cloud else "local sandboxes"
self.line(
- f" {plan.spec.image_label} {plan.tasks} variant(s), {where} "
+ f" {plan.spec.image_label} {plan.tasks} variant(s), sandboxes "
f"max {plan.max_pool_size}"
)
- if target.cloud and sandboxed:
- self.line(
- self._c(
- GREY,
- " Managed pools autoscale from zero: an idle pool takes about a minute "
- "(VMs several) to start its first sandbox, and scales back down after "
- "the run.",
- )
- )
def started(self, job, index, total) -> None:
what = "acquiring sandbox" if job.spec.needs_sandbox else "no environment (dataset)"
@@ -426,7 +408,6 @@ def cmd_run_dataset(args) -> int:
def _cmd_execute(args, kind: str) -> int:
- from cua_bench.sandboxes import CloudAuthError, cloud_auth_source
from cua_bench.sessions import manager
from cua_bench.targets import TargetError
@@ -453,14 +434,6 @@ def _cmd_execute(args, kind: str) -> int:
if getattr(args, "dry_run", False):
return _print_dry_run(target, jobs)
- auth = None
- if target.cloud and any(job.spec.needs_sandbox for job in jobs):
- try:
- auth = cloud_auth_source()
- except CloudAuthError as error:
- print(f"{RED}{error}{RESET}")
- return 1
-
agent_display = opts.label
output_dir.mkdir(parents=True, exist_ok=True)
for job in jobs:
@@ -485,8 +458,6 @@ def _cmd_execute(args, kind: str) -> int:
print(f"\n {BOLD}Run ID:{RESET} {run_id}")
print(f" {BOLD}Output:{RESET} {output_dir}")
- if auth is not None:
- print(f" {BOLD}Auth:{RESET} {auth}")
if getattr(args, "detach", False):
return _spawn_detached(args, run_id, output_dir, jobs)
@@ -709,7 +680,7 @@ def _print_dry_run(target, jobs) -> int:
reporter.plan(
target, jobs, plan_claims(((j.session_id, j.spec) for j in jobs), target.concurrency)
)
- where = "Fleet" if target.cloud else "local"
+ where = target.on
for job in jobs:
spec = job.spec
note = {
diff --git a/libs/cua-bench/cua_bench/cli/commands/status.py b/libs/cua-bench/cua_bench/cli/commands/status.py
index 81c0309721..be3c9259a8 100644
--- a/libs/cua-bench/cua_bench/cli/commands/status.py
+++ b/libs/cua-bench/cua_bench/cli/commands/status.py
@@ -35,17 +35,6 @@ def _check(label: str, ok: bool, good: str, bad: str) -> None:
print(f" {label:<9}{mark}")
-def _cloud_auth() -> str:
- """The credential source, without reading the OS credential vault: a
- dashboard is not an explicit sign-in check (``cb run --on cloud`` is)."""
- try:
- from cua_sandbox import fleet_auth_source
-
- return fleet_auth_source(read_session=False) or ""
- except Exception: # noqa: BLE001 - SDK not loadable
- return ""
-
-
async def _execute_async(args) -> int:
"""Execute status command asynchronously."""
print("\ncua-bench Status")
diff --git a/libs/cua-bench/cua_bench/computers/base.py b/libs/cua-bench/cua_bench/computers/base.py
index 85887ded68..1388e13925 100644
--- a/libs/cua-bench/cua_bench/computers/base.py
+++ b/libs/cua-bench/cua_bench/computers/base.py
@@ -65,9 +65,9 @@ class DesktopSetupConfig(TypedDict, total=False):
width: int
#: Screen height in pixels.
height: int
- #: Registry image or OS alias (``linux``, ``windows``, ``macos:tahoe``), or
- #: ``pool:<name>`` for an existing Fleet pool. ``--image`` wins, then this,
- #: then ``CUA_BENCH_IMAGE``, then the canonical image of ``os_type``.
+ #: Registry image or OS alias (``linux``, ``windows``, ``macos:tahoe``).
+ #: ``--image`` wins, then this, then ``CUA_BENCH_IMAGE``, then the canonical
+ #: image of ``os_type``.
image: str
#: Preferred kind: ``container`` (Linux only) or ``vm``.
kind: str
@@ -92,7 +92,7 @@ class DesktopSetupConfig(TypedDict, total=False):
installed_apps: List[str]
#: Deprecated and ignored.
storage: str
- #: Deprecated: ``"cloud"`` runs on Fleet; use ``--on cloud`` instead.
+ #: Deprecated: ``"cloud"`` named Cua Cloud, which has ended (it raises).
provider_type: str
diff --git a/libs/cua-bench/cua_bench/computers/remote.py b/libs/cua-bench/cua_bench/computers/remote.py
index 500bd627fa..997666569a 100644
--- a/libs/cua-bench/cua_bench/computers/remote.py
+++ b/libs/cua-bench/cua_bench/computers/remote.py
@@ -270,7 +270,7 @@ class RemoteDesktopSession:
Full lifecycle mode opens the sandbox exactly like ``cb run``: the
canonical ``ghcr.io/trycua/<os>`` image unless ``image=`` names a registry
- ref, locally unless ``provider_type="cloud"`` (Fleet).
+ ref, locally (``provider_type="cloud"``: Cua Cloud has ended, it raises).
Supports full bench_ui integration when bench_ui is installed in the
remote environment, enabling:
@@ -329,7 +329,7 @@ class RemoteDesktopSession:
height: Screen height
os_type: Operating system type ("linux", "windows", "android")
image: Registry image (default: the canonical image for os_type)
- provider_type: "cloud" runs on Fleet; anything else runs locally
+ provider_type: "cloud" raises (Cua Cloud has ended); anything else runs locally
memory: VM memory allocation (e.g., "8GB")
cpu: VM CPU allocation (e.g., "4")
name: Container/VM name (auto-generated if empty)
@@ -416,7 +416,7 @@ class RemoteDesktopSession:
"""Wrap an already-connected ``cua_sandbox.Sandbox``.
The caller owns the sandbox: :meth:`close` only drops the reference
- (the runner releases the sandbox or its Fleet claim itself).
+ (the runner releases the sandbox itself).
"""
session = cls(
os_type=os_type,
@@ -568,7 +568,7 @@ class RemoteDesktopSession:
if self._provider_type not in ("docker", "cloud", "local", "native", ""):
_warn_deprecated(
f"RemoteDesktopSession(provider_type={self._provider_type!r}) is deprecated: "
- "the sandbox runtime follows the image (use provider_type='cloud' for Fleet)"
+ "the sandbox runtime follows the image"
)
if self._storage:
_warn_deprecated(
@@ -1111,8 +1111,8 @@ class RemoteDesktopSession:
return
lifecycle, self._lifecycle = self._lifecycle, None
if lifecycle is not None:
- # A sandbox this session opened: release it (local teardown or
- # the Fleet claim) through the same context that created it.
+ # A sandbox this session opened: release it through the same
+ # context that created it.
self._sandbox = None
self._initialized = False
try:
diff --git a/libs/cua-bench/cua_bench/runner/batch_runner.py b/libs/cua-bench/cua_bench/runner/batch_runner.py
index 7af7a7b853..62c0ea9bc1 100644
--- a/libs/cua-bench/cua_bench/runner/batch_runner.py
+++ b/libs/cua-bench/cua_bench/runner/batch_runner.py
@@ -2,13 +2,10 @@
Every variant gets its own sandbox, its own log file and its own
``result.json``; ``Target.concurrency`` bounds how many run
-at once. In the cloud, variants with the same image share one managed pool
-sized for the batch (``max_pool_size = min(concurrency, variants)``), so the
-pool scales up from zero for the batch and back down afterwards.
+at once.
Cancellation (Ctrl-C, ``cb run stop``) cancels the running variants; each
-one's ``async with`` releases its sandbox or claim on the way out. If the
-process dies instead, cloud claims expire after their TTL.
+one's ``async with`` releases its sandbox on the way out.
"""
from __future__ import annotations
@@ -77,7 +74,7 @@ class JobResult:
backend: str = ""
#: The image as the task or ``--image`` named it.
image: Optional[str] = None
- #: The Fleet pool that served the claim (cloud runs).
+ #: The pool that served the sandbox (unused: always ``None`` since Cua Cloud ended).
pool: Optional[str] = None
#: The variant's output directory.
output_dir: str = ""
@@ -197,16 +194,12 @@ class BatchRunner:
self._opener = opener
self._env_factory = env_factory
self._attach = attach
- # Cloud: the first claim per pool key goes alone until its pool exists,
- # so concurrent first-use claims never race to create the same pool.
- self._pool_gates: dict[tuple, asyncio.Event] = {}
def plans(self, jobs: list[Job]) -> list[PoolPlan]:
return plan_claims(((job.session_id, job.spec) for job in jobs), self.target.concurrency)
async def run(self, jobs: list[Job]) -> list[JobResult]:
plans = self.plans(jobs)
- pool_size = {plan.spec.pool_key: plan.max_pool_size for plan in plans}
self.reporter.plan(self.target, jobs, plans)
semaphore = asyncio.Semaphore(self.target.concurrency)
total = len(jobs)
@@ -216,7 +209,7 @@ class BatchRunner:
nonlocal finished
async with semaphore:
self.reporter.started(job, index, total)
- result = await self.run_job(job, max_pool_size=pool_size.get(job.spec.pool_key, 1))
+ result = await self.run_job(job)
finished += 1
self.reporter.finished(result, finished, total)
return result
@@ -228,7 +221,7 @@ class BatchRunner:
except asyncio.CancelledError:
for task in tasks:
task.cancel()
- # Let every variant run its cleanup (claim release) before leaving.
+ # Let every variant run its cleanup (sandbox release) before leaving.
await asyncio.gather(*tasks, return_exceptions=True)
raise
@@ -239,7 +232,7 @@ class BatchRunner:
except Exception: # noqa: BLE001 - bookkeeping never fails a task
pass
- async def run_job(self, job: Job, *, max_pool_size: int = 1) -> JobResult:
+ async def run_job(self, job: Job) -> JobResult:
"""Run one variant; retry infrastructure failures up to ``retries`` times.
A retry starts over in a fresh sandbox. Only failures before the task
@@ -248,7 +241,7 @@ class BatchRunner:
"""
retries = 0
while True:
- result = await self._run_once(job, max_pool_size=max_pool_size, retries=retries)
+ result = await self._run_once(job, retries=retries)
if not (getattr(result, "_retryable", False) and retries < self.retries):
return result
retries += 1
@@ -257,7 +250,7 @@ class BatchRunner:
print(f"\n↻ Retrying {job.name} ({retries}/{self.retries}) in {delay:.0f}s")
await asyncio.sleep(delay)
- async def _run_once(self, job: Job, *, max_pool_size: int, retries: int) -> JobResult:
+ async def _run_once(self, job: Job, *, retries: int) -> JobResult:
target, spec = self.target, job.spec
result = JobResult(
session_id=job.session_id,
@@ -284,29 +277,12 @@ class BatchRunner:
started = time.monotonic()
job.output_dir.mkdir(parents=True, exist_ok=True)
self._status(job, "starting")
- pool_seen: dict[str, Optional[str]] = {"pool": None}
- gate: Optional[asyncio.Event] = None
opener, attach = self._opener, self._attach
if not spec.needs_sandbox:
opener, attach = _no_sandbox, _dataset_session
- if target.cloud and spec.needs_sandbox:
- existing = self._pool_gates.get(spec.pool_key)
- if existing is None:
- gate = self._pool_gates[spec.pool_key] = asyncio.Event()
- else:
- await existing.wait()
- loop = asyncio.get_running_loop()
-
- def open_gate() -> None:
- if gate is not None and not gate.is_set():
- loop.call_soon_threadsafe(gate.set)
def on_progress(event: Progress) -> None:
- if event.pool:
- pool_seen["pool"] = event.pool
- if event.stage != "pool": # past pool lookup/creation
- open_gate()
print(f"[sandbox] {event.stage}: {event.message}")
self.reporter.progress(job, event)
@@ -316,11 +292,8 @@ class BatchRunner:
try:
env = self._env_factory(str(job.task_path))
result._setup_started = _now_utc() # type: ignore[attr-defined]
- async with opener(
- spec, target, max_pool_size=max_pool_size, on_progress=on_progress
- ) as sandbox:
- open_gate()
- result.pool = pool_seen["pool"] or getattr(sandbox, "pool_name", None)
+ async with opener(spec, target, on_progress=on_progress) as sandbox:
+ result.pool = getattr(sandbox, "pool_name", None)
result.sandbox = _sandbox_ref(sandbox)
facts = image_facts(sandbox, spec)
for key, value in facts.items():
@@ -351,14 +324,12 @@ class BatchRunner:
result.error = f"agent failure: {episode.failure_mode}"
print(f"\n✗ Task failed: {result.error}")
except asyncio.CancelledError:
- open_gate()
result.status = "cancelled"
result.error = "cancelled"
print("\n✗ Task cancelled (sandbox released)")
self._finish(job, result, started)
raise
except Exception as error: # noqa: BLE001 - one variant never stops the batch
- open_gate()
result.error = explain_error(error, spec, target)
result._error_obj = error # type: ignore[attr-defined]
result._retryable = not isinstance(error, TargetError) # type: ignore[attr-defined]
diff --git a/libs/cua-bench/cua_bench/sandboxes.py b/libs/cua-bench/cua_bench/sandboxes.py
index 630512769e..59fb158e0a 100644
--- a/libs/cua-bench/cua_bench/sandboxes.py
+++ b/libs/cua-bench/cua_bench/sandboxes.py
@@ -6,11 +6,8 @@ and releases it on exit (including cancellation, e.g. Ctrl-C):
* ``--on local``: ``Sandbox.ephemeral(image, on="local")``. The SDK runs a
container under gVisor (``runsc``) or a VM under QEMU / Lume.
-* ``--on cloud``: ``Sandbox.ephemeral(image, on="cloud")`` with no pool.
- cua-sandbox claims it from this account's managed pool for the image
- (``cua-auto-*``), created on first use and reused afterwards; the claim
- carries a TTL renewed by a heartbeat, so a crashed run leaks it for at most
- the TTL. cua-bench never applies pools itself.
+* ``--on cloud`` (Cua Cloud) and ``--image pool:<name>`` end with
+ :class:`~cua_bench.targets.CloudEnded`: Cua Cloud has ended.
* ``--on e2b`` (``daytona``, ``modal``, ...): ``Sandbox.ephemeral(image,
on="e2b")``; the SDK's contrib provider runs the same registry image on
that platform. cua-bench has no provider-specific code: the location word
@@ -34,35 +31,7 @@ from .targets import EnvSpec, Target
logger = logging.getLogger(__name__)
-LOGIN_HINT = (
- "Not signed in to cua cloud. Run `cua auth login` (or set CUA_CLIENT_ID and "
- "CUA_CLIENT_SECRET from `cua auth keys create`, or FLEETS_TOKEN), then retry."
-)
-
-
-class CloudAuthError(RuntimeError):
- """No usable Fleet credentials (the message says how to sign in)."""
-
-
-def cloud_auth_source(source_fn: Optional[Callable[[], Optional[str]]] = None) -> str:
- """Where ``--on cloud`` credentials come from, or :class:`CloudAuthError`.
-
- Resolution is the SDK's (``cua_sandbox.fleet_auth_source``): FLEETS_TOKEN,
- then client credentials, then the ``cua auth login`` session, which the
- SDK refreshes itself for as long as the run lasts.
- """
- if source_fn is None:
- try:
- from cua_sandbox import fleet_auth_source as source_fn
- except Exception as error: # noqa: BLE001 - SDK missing or unloadable
- raise CloudAuthError(f"{LOGIN_HINT}\n (cua-sandbox unavailable: {error})") from error
- source = source_fn()
- if not source:
- raise CloudAuthError(LOGIN_HINT)
- return str(source)
-
-
-#: Sandbox boot / claim bind deadline (Fleet cold starts scale from zero).
+#: Sandbox boot deadline in seconds (a first start can pull an image).
TIME_TO_START_S = 900
@@ -70,7 +39,7 @@ TIME_TO_START_S = 900
class Progress:
"""A lifecycle event for the progress display."""
- stage: str # pool | cold_start | claim | waiting | ready | release
+ stage: str # waiting | ready | release
message: str
pool: Optional[str] = None
elapsed: float = 0.0
@@ -166,18 +135,11 @@ def image_facts(sandbox: Any, spec: EnvSpec) -> dict:
return facts
-def ephemeral_kwargs(
- spec: EnvSpec,
- target: Target,
- *,
- max_pool_size: int,
- progress: Optional[Callable[[Any], Any]] = None,
-) -> dict:
+def ephemeral_kwargs(spec: EnvSpec, target: Target) -> dict:
"""Keyword arguments for ``Sandbox.ephemeral`` on ``target``.
- ``cpu``/``memory_mb`` apply on both targets (the SDK sizes local
- containers and VMs with them); pool options only apply in the cloud.
- Nothing is published for the display: images with cua-spacesd serve
+ ``cpu``/``memory_mb`` size the sandbox (the SDK sizes local containers and
+ VMs with them). Nothing is published for the display: images with cua-spacesd serve
the viewer on the ``env`` service every sandbox declares, so
``Sandbox.get_display_url()`` returns a viewer link.
"""
@@ -194,13 +156,6 @@ def ephemeral_kwargs(
kwargs["memory_mb"] = target.memory_mb
if spec.server_port is not None:
kwargs["server_port"] = spec.server_port
- if target.cloud:
- kwargs["max_pool_size"] = max_pool_size
- kwargs["warm"] = target.warm
- if target.claim_ttl_s is not None:
- kwargs["claim_ttl"] = target.claim_ttl_s
- if progress is not None:
- kwargs["progress"] = progress
return kwargs
@@ -209,40 +164,18 @@ async def open_sandbox(
spec: EnvSpec,
target: Target,
*,
- max_pool_size: int = 1,
on_progress: Optional[ProgressFn] = None,
) -> AsyncIterator[Any]:
"""Yield a connected sandbox for ``spec``; release it on exit."""
image_cls, sandbox_cls = _sdk()
- def relay(event: Any) -> None:
- if on_progress is None:
- return
- on_progress(
- Progress(
- stage=str(getattr(event, "stage", "waiting")),
- message=str(getattr(event, "message", "")),
- pool=getattr(event, "pool", None),
- elapsed=float(getattr(event, "elapsed", 0.0) or 0.0),
- )
- )
-
if spec.pool or target.cloud:
# Cua Cloud has ended: neither `--on cloud` nor `--image pool:<name>` starts one.
from cua_bench.targets import CloudEnded
raise CloudEnded()
- if spec.pool:
- # `--image pool:<name>`: a claim from an existing Fleet pool.
- kwargs = {"pool": spec.pool, "on": "cloud", "time_to_start": TIME_TO_START_S}
- kwargs["telemetry_enabled"] = False
- async with sandbox_cls.ephemeral(None, **kwargs) as sb:
- yield sb
- if on_progress is not None:
- on_progress(Progress(stage="release", message="claim released", pool=spec.pool))
- return
image = build_image(spec, image_cls)
- kwargs = ephemeral_kwargs(spec, target, max_pool_size=max_pool_size, progress=relay)
+ kwargs = ephemeral_kwargs(spec, target)
async with sandbox_cls.ephemeral(image, **kwargs) as sb:
yield sb
if on_progress is not None:
@@ -258,29 +191,15 @@ _PULL_PATTERNS = re.compile(
r"image .* not found|No such image",
re.IGNORECASE,
)
-_AUTH_PATTERNS = re.compile(
- r"\b401\b|Unauthenticated|missing credentials|MissingCredentials|invalid_client|"
- r"FLEETS_TOKEN|CUA_CLIENT_ID|not authenticated",
- re.IGNORECASE,
-)
def explain_error(error: BaseException, spec: Optional[EnvSpec], target: Target) -> str:
"""A one-paragraph, actionable message for common sandbox failures."""
text = f"{type(error).__name__}: {error}"
image = spec.image if spec is not None and spec.image else None
- if _AUTH_PATTERNS.search(text) and target.cloud:
- return f"{LOGIN_HINT}\n ({text})"
if _PULL_PATTERNS.search(text):
ref = image or "the task image"
registry = ref.split("/", 1)[0] if "/" in ref else "docker.io"
- if target.cloud:
- return (
- f"Fleet could not pull {ref} from {registry}. Push it to a registry Fleet can "
- "read (a public repository, or ECR desktop-workspace), pin it by digest if the "
- "tag moves, or run it with --on local from a local build.\n "
- f"({text})"
- )
return (
f"{ref} is not available locally and could not be pulled from {registry}. "
f"Build it (docker build -t {ref} ...) or log in to the registry "
@@ -288,13 +207,3 @@ def explain_error(error: BaseException, spec: Optional[EnvSpec], target: Target)
f"({text})"
)
return text
-
-
-# ── Managed pool maintenance (cb env ls / gc) ──────────────────────────────
-
-
-def pools_module() -> Any:
- """cua-sandbox's public managed-pool API (``cua_sandbox.pools``)."""
- from cua_sandbox import pools
-
- return pools
diff --git a/libs/cua-bench/cua_bench/targets.py b/libs/cua-bench/cua_bench/targets.py
index 0c6607acf9..d5f2e92ee4 100644
--- a/libs/cua-bench/cua_bench/targets.py
+++ b/libs/cua-bench/cua_bench/targets.py
@@ -3,7 +3,7 @@
One flag set drives every command:
* ``--on local|cloud``: where. ``local`` runs sandboxes on this machine
- through the cua SDK; ``cloud`` claims them from managed Fleet pools.
+ through the cua SDK; ``cloud`` (Cua Cloud) has ended and fails.
* ``--kind auto|container|vm``: what kind. ``auto`` (the default) runs Linux
as a container unless the task or the image's variant index says VM;
Windows, macOS and Android are VM-only.
@@ -151,7 +151,7 @@ class TargetError(ValueError):
class CloudEnded(TargetError):
- """``--on cloud`` (Cua Cloud, Fleet-backed) no longer exists."""
+ """``--on cloud`` (Cua Cloud) no longer exists."""
def __init__(self) -> None:
super().__init__(CLOUD_ENDED)
@@ -216,7 +216,7 @@ class Target:
@property
def cloud(self) -> bool:
- """Cua cloud (Fleet): managed pools, warm capacity, claim TTLs."""
+ """Cua Cloud, which has ended (``resolve_target`` refuses it)."""
return self.on == "cloud"
@property
@@ -456,7 +456,7 @@ class EnvSpec:
#: What the task needs from the target (``setup_config.requires``): kvm,
#: egress, openai, hf-gated, env:NAME. Checked by ``cb run`` up front.
requires: tuple = ()
- #: ``--image pool:<name>``: claim from this existing Fleet pool (its
+ #: ``--image pool:<name>``: claim from this existing Cua Cloud pool (its
#: template decides image, kind and runtime) instead of a managed pool.
pool: Optional[str] = None
#: More guest ports the task reaches (``setup_config.ports``): exposed
@@ -546,7 +546,7 @@ def parse_image_alias(value: Any) -> Optional[tuple[str, Optional[str]]]:
def parse_pool_image(value: Any) -> Optional[str]:
"""The pool name of a ``pool:<name>`` image (``fleet:<name>``: deprecated).
- ``pool:`` names an existing Fleet pool (the unified refs scheme);
+ ``pool:`` named an existing Cua Cloud pool (which has ended);
``fleet:`` never names an image any more but still parses, with a warning.
"""
if not isinstance(value, str):
@@ -690,28 +690,9 @@ def resolve_env_spec(
raise TargetError(f"unsupported os_type {setup.get('os_type')!r}")
image = target.image or setup.get("image") or default_image or None
- pool = parse_pool_image(image)
- if pool is not None:
- # `pool:<name>`: an existing Fleet pool; its template decides the rest.
- raise CloudEnded() # pool:<name> names a Fleet pool; Cua Cloud has ended
- if not target.cloud:
- raise TargetError(f"pool:{pool} names a Fleet pool: run it with --on cloud")
- kind = (
- target.kind
- or str(setup.get("kind") or "").strip().lower()
- or ("container" if os_type == "linux" else "vm")
- )
- return EnvSpec(
- provider="native",
- os_type=os_type,
- kind=kind if kind in KIND_CHOICES else "container",
- image=None,
- width=width,
- height=height,
- kind_source="task" if setup.get("kind") else "default",
- requires=_task_requires(setup),
- pool=pool,
- )
+ if parse_pool_image(image) is not None:
+ # `pool:<name>` named a Cua Cloud pool; Cua Cloud has ended.
+ raise CloudEnded()
os_version = None
alias = parse_image_alias(image)
if alias is not None:
diff --git a/libs/cua-bench/cua_bench/templates/starter_env/CLAUDE.md b/libs/cua-bench/cua_bench/templates/starter_env/CLAUDE.md
index 7e58ac5650..1d13162d4e 100644
--- a/libs/cua-bench/cua_bench/templates/starter_env/CLAUDE.md
+++ b/libs/cua-bench/cua_bench/templates/starter_env/CLAUDE.md
@@ -353,7 +353,7 @@ async def start(task_cfg: cb.Task, session: cb.DesktopSession):
**Important limitations:**
-- Runs in a sandbox (a local container by default, `--on cloud` for Fleet)
+- Runs in a sandbox (a local container by default)
- Slower than Universal GUI
- Less deterministic than custom GUIs
diff --git a/libs/cua-bench/cua_bench/templates/starter_env/main.py b/libs/cua-bench/cua_bench/templates/starter_env/main.py
index 97f0cc3ea0..d28ad0a6df 100644
--- a/libs/cua-bench/cua_bench/templates/starter_env/main.py
+++ b/libs/cua-bench/cua_bench/templates/starter_env/main.py
@@ -2,7 +2,6 @@
cb run . # local gVisor container, oracle solution
cb run . --kind vm # the same task in a local QEMU VM
- cb run . --on cloud # a Fleet sandbox
cb interact . # open the sandbox and try it yourself
Each variant asks for one word in a file. Replace the setup, the oracle and
diff --git a/libs/cua-bench/cua_bench/tests/conftest.py b/libs/cua-bench/cua_bench/tests/conftest.py
index de81f2f79f..8e096c7fc2 100644
--- a/libs/cua-bench/cua_bench/tests/conftest.py
+++ b/libs/cua-bench/cua_bench/tests/conftest.py
@@ -21,7 +21,6 @@ _DEFAULT_VARS = (
"CUA_DEFAULT_ON",
"CUA_DEFAULT_KIND",
"CUA_DEFAULT_RUNTIME",
- "CUA_FLEET_WARM",
"CUA_BENCH_IMAGE",
)
diff --git a/libs/cua-bench/cua_bench/tests/golden/cli_tree.json b/libs/cua-bench/cua_bench/tests/golden/cli_tree.json
index 87b51ac17c..7549567bce 100644
--- a/libs/cua-bench/cua_bench/tests/golden/cli_tree.json
+++ b/libs/cua-bench/cua_bench/tests/golden/cli_tree.json
@@ -1103,7 +1103,7 @@
"const": true,
"default": false,
"dest": "warm",
- "hidden": false,
+ "hidden": true,
"metavar": null,
"nargs": 0,
"options": [
@@ -1118,7 +1118,7 @@
"const": null,
"default": null,
"dest": "claim_ttl",
- "hidden": false,
+ "hidden": true,
"metavar": null,
"nargs": null,
"options": [
@@ -1651,7 +1651,7 @@
"const": true,
"default": false,
"dest": "warm",
- "hidden": false,
+ "hidden": true,
"metavar": null,
"nargs": 0,
"options": [
@@ -1666,7 +1666,7 @@
"const": null,
"default": null,
"dest": "claim_ttl",
- "hidden": false,
+ "hidden": true,
"metavar": null,
"nargs": null,
"options": [
@@ -2228,7 +2228,7 @@
"const": true,
"default": false,
"dest": "warm",
- "hidden": false,
+ "hidden": true,
"metavar": null,
"nargs": 0,
"options": [
@@ -2243,7 +2243,7 @@
"const": null,
"default": null,
"dest": "claim_ttl",
- "hidden": false,
+ "hidden": true,
"metavar": null,
"nargs": null,
"options": [
diff --git a/libs/cua-bench/cua_bench/tests/live/test_cloud_live.py b/libs/cua-bench/cua_bench/tests/live/test_cloud_live.py
deleted file mode 100644
index 4b81f76764..0000000000
--- a/libs/cua-bench/cua_bench/tests/live/test_cloud_live.py
+++ /dev/null
@@ -1,232 +0,0 @@
-"""LIVE: ``cb run --on cloud`` on managed Fleet pools (opt-in, billed).
-
-Run only on purpose::
-
- set -a; source ~/.env; set +a
- CUA_E2E_FLEET=1 .venv/bin/python -m pytest -q -s cua_bench/tests/live/test_cloud_live.py
-
-What it proves, through the real CLI in a subprocess:
-
-1. A 2-variant mini-batch with ``-j 2`` claims both sandboxes from ONE
- managed pool (sized ``max_pool_size = 2``) and completes.
-2. A second batch reuses that same pool.
-3. Every claim is released when the runs end; the pool stays (idle GC owns
- it). The test then GCs exactly the managed pools it used, through the
- SDK's scoped GC (by name, only once they have no claims), and verifies
- nothing is left.
-
-The task needs no computer control, so it runs on the public daemon-agnostic
-image (its own daemon on port 8000 is the readiness probe). Managed pools are
-named ``cua-auto-<tenant/spec hash>``; the test tracks the ones its batches
-used plus any new managed pool of its image, and automatic GC is off in the
-CLI subprocesses, so no other pool is touched.
-
-Image and runtime: ``CUA_BENCH_E2E_IMAGE`` / ``CUA_BENCH_E2E_RUNTIME``. The
-default is the gVisor ``docker-*`` tag when the installed cua-sandbox selects
-the Fleet runtime from the image kind, else the KubeVirt containerDisk.
-"""
-
-from __future__ import annotations
-
-import asyncio
-import json
-import os
-import subprocess
-import sys
-import textwrap
-import time
-from pathlib import Path
-
-import pytest
-
-AUTO_PREFIX = "cua-auto-"
-GVISOR_IMAGE = "public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04:docker-main-809e3f81"
-KUBEVIRT_IMAGE = (
- "public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04"
- "@sha256:82702ebdd32d1f8fc05f2ea409a7c67d0ba9f8f8e4e9f1a89ce40989d5f4475d"
-)
-SERVER_PORT = 8000
-RUN_TIMEOUT_S = 1500
-
-pytestmark = [
- pytest.mark.skipif(
- os.environ.get("CUA_E2E_FLEET") != "1",
- reason="opt-in: set CUA_E2E_FLEET=1 (creates billed Fleet sandboxes)",
- ),
- pytest.mark.skipif(
- not (
- os.environ.get("FLEETS_TOKEN")
- or (os.environ.get("CUA_CLIENT_ID") and os.environ.get("CUA_CLIENT_SECRET"))
- ),
- reason="Fleet credentials not set (set -a; source ~/.env; set +a)",
- ),
-]
-
-TASK = textwrap.dedent("""
- import cua_bench as cb
-
- @cb.tasks_config(split="train")
- def load():
- return [
- cb.Task(
- description=f"lifecycle {{i}}",
- computer={{"provider": "native", "setup_config": {{
- "os_type": "linux", "image": {image!r}, "runtime": {runtime!r},
- "server_port": {port}}}}},
- )
- for i in range(2)
- ]
-
- @cb.setup_task(split="train")
- async def setup(task_cfg, session):
- assert session.interface is not None # a claimed, connected sandbox
-
- @cb.evaluate_task(split="train")
- async def evaluate(task_cfg, session):
- return [1.0]
- """)
-
-
-def _defaults() -> tuple[str, str]:
- runtime = os.environ.get("CUA_BENCH_E2E_RUNTIME")
- image = os.environ.get("CUA_BENCH_E2E_IMAGE")
- if runtime is None:
- try:
- from cua_sandbox.transport.fleet_cloud import ( # noqa: F401
- resolve_fleet_runtime,
- )
-
- runtime = "container"
- except ImportError:
- runtime = "vm"
- if image is None:
- image = GVISOR_IMAGE if runtime == "container" else KUBEVIRT_IMAGE
- return image, runtime
-
-
-def log(message: str) -> None:
- print(f"[bench-cloud-live {time.strftime('%H:%M:%S')}] {message}", flush=True)
-
-
-async def _managed_pools() -> dict[str, "object"]:
- """This account's managed pools by name (the SDK's pool listing)."""
- from cua_sandbox import pools
-
- return {p.name: p for p in await pools.list_pools()}
-
-
-async def _claims(pool: str) -> set[str]:
- """Claims still in ``pool`` (the SDK's public claim listing)."""
- from cua_sandbox import pools
-
- return {claim.name for claim in await pools.list_claims() if claim.pool == pool}
-
-
-async def _gc_test_pools(names: set[str]) -> list[str]:
- """GC exactly ``names`` through the SDK (no claims left, idle now)."""
- from cua_sandbox import pools
-
- if not names:
- return []
- report = await pools.gc_pools(sorted(names), 0)
- for error in report.errors:
- log(f"cleanup: {error}")
- return report.pools_deleted + report.namespaces_deleted
-
-
-def _cb(args: list[str], env: dict, cwd: Path) -> subprocess.CompletedProcess:
- cmd = [sys.executable, "-m", "cua_bench.cli.main", *args]
- log("$ cb " + " ".join(args))
- proc = subprocess.run(
- cmd, cwd=cwd, env=env, capture_output=True, text=True, timeout=RUN_TIMEOUT_S
- )
- for line in (proc.stdout + proc.stderr).splitlines():
- log(f" | {line}")
- return proc
-
-
-def _summary(output_dir: Path) -> dict:
- return json.loads((output_dir / "summary.json").read_text())
-
-
-def test_cloud_mini_batch_reuses_one_managed_pool_and_cleans_up(tmp_path):
- from cua_bench.sandboxes import managed_pools_supported
-
- if not managed_pools_supported():
- pytest.skip("installed cua-sandbox has no managed Fleet pools yet")
-
- image, runtime = _defaults()
- log(f"image={image} runtime={runtime}")
- dataset = tmp_path / "dataset" / "lifecycle_env"
- dataset.mkdir(parents=True)
- (dataset / "main.py").write_text(TASK.format(image=image, runtime=runtime, port=SERVER_PORT))
-
- home = tmp_path / "home"
- home.mkdir()
- env = {
- **os.environ,
- "HOME": str(home), # managed-pool cache, GC stamp and claim state stay off ~/.cua
- "XDG_DATA_HOME": str(tmp_path / "data"),
- "XDG_STATE_HOME": str(tmp_path / "state"),
- "CUA_FLEET_POOL_IDLE_GC": "off",
- "CUA_BENCH_NO_BANNER": "1",
- "PYTHONUNBUFFERED": "1",
- }
- runs: list[dict] = []
- # Scope cleanup to this test: pools its batches report, plus any managed
- # pool of its image that did not exist before (a crashed batch).
- before = set(asyncio.run(_managed_pools()))
- used: set[str] = set()
- try:
- for attempt in (1, 2):
- out = tmp_path / f"run{attempt}"
- proc = _cb(
- [
- "run",
- str(dataset.parent),
- "--on",
- "cloud",
- "-j",
- "2",
- "--claim-ttl",
- "5m",
- "--output-dir",
- str(out),
- ],
- env,
- tmp_path,
- )
- assert proc.returncode == 0, f"batch {attempt} failed (exit {proc.returncode})"
- summary = _summary(out)
- runs.append(summary)
- assert summary["completed"] == 2, summary
- pools = {r["pool"] for r in summary["results"]}
- used |= {p for p in pools if p}
- log(f"batch {attempt} pools: {pools}")
- assert len(pools) == 1, f"one managed pool per image, got {pools}"
- (pool,) = pools
- assert pool and pool.startswith(AUTO_PREFIX), pool
- if attempt == 1:
- assert "scaling up from zero" in proc.stdout or "sandbox ready" in proc.stdout
-
- first_pool = runs[0]["results"][0]["pool"]
- assert runs[1]["results"][0]["pool"] == first_pool, "second batch must reuse the pool"
-
- remaining = asyncio.run(_claims(first_pool))
- assert not remaining, f"claims left after the runs: {remaining}"
- assert first_pool in asyncio.run(_managed_pools()), "the managed pool stays for reuse"
- finally:
- now = asyncio.run(_managed_pools())
- used |= {
- n for n, p in now.items() if n not in before and getattr(p, "image", None) == image
- }
- leftover: list[str] = sorted(used)
- for _ in range(60): # up to ~5 min; claim release and deletion are asynchronous
- deleted = asyncio.run(_gc_test_pools(set(leftover)))
- if deleted:
- log(f"deleted test pools {deleted}")
- leftover = sorted(set(leftover) & set(asyncio.run(_managed_pools())))
- if not leftover:
- break
- time.sleep(5)
- assert not leftover, f"test pools left behind: {leftover}"
diff --git a/libs/cua-bench/cua_bench/tests/live/test_fleet_named_pool_live.py b/libs/cua-bench/cua_bench/tests/live/test_fleet_named_pool_live.py
deleted file mode 100644
index 0cc8f63556..0000000000
--- a/libs/cua-bench/cua_bench/tests/live/test_fleet_named_pool_live.py
+++ /dev/null
@@ -1,114 +0,0 @@
-"""LIVE: cua-bench's runner on a Fleet gVisor sandbox (opt-in, billed).
-
-Run only on purpose::
-
- set -a; source ~/.env; set +a
- CUA_E2E_FLEET=1 .venv/bin/python -m pytest -q -s cua_bench/tests/live/test_fleet_named_pool_live.py
-
-It applies one gVisor pool named ``cua-e2e-bench-<random>`` for the
-canonical Linux image (spacesd, env token delivered through the claim's
-Secret), runs ``hello_file_env`` (both variants) through cua-bench's
-BatchRunner on claims from it, checks the rewards and the recorded
-runtime/image facts, and deletes the pool in ``finally``.
-
-``cb run --on cloud`` (managed ``cua-auto-*`` pools) is covered by
-``test_cloud_live.py``.
-"""
-
-from __future__ import annotations
-
-import asyncio
-import json
-import os
-import uuid
-from contextlib import asynccontextmanager
-from pathlib import Path
-
-import pytest
-
-pytestmark = [
- pytest.mark.skipif(
- os.environ.get("CUA_E2E_FLEET") != "1",
- reason="opt-in: set CUA_E2E_FLEET=1 (creates billed Fleet sandboxes)",
- ),
- pytest.mark.skipif(
- not (
- os.environ.get("FLEETS_TOKEN")
- or (os.environ.get("CUA_CLIENT_ID") and os.environ.get("CUA_CLIENT_SECRET"))
- ),
- reason="Fleet credentials not set (set -a; source ~/.env; set +a)",
- ),
-]
-
-HELLO = Path(__file__).resolve().parents[3] / "example_tasks" / "hello_file_env"
-IMAGE = os.environ.get("CUA_BENCH_E2E_FLEET_IMAGE", "ghcr.io/trycua/linux:24.04")
-TIMEOUT_S = 1800
-
-
-def log(message: str) -> None:
- print(f"[bench-fleet-live] {message}", flush=True)
-
-
-async def _run(tmp_path: Path) -> list:
- from cua_bench.runner import AgentOptions, BatchRunner, Job
- from cua_bench.targets import Target, resolve_env_spec
- from cua_sandbox import Image, Pool, PoolOptions, SandboxSpec, generate_claim_token
-
- name = f"cua-e2e-bench-{uuid.uuid4().hex[:8]}"
- log(f"applying pool {name} ({IMAGE}, gvisor)")
- pool = await Pool.apply(
- name,
- SandboxSpec(
- image=Image.from_registry(IMAGE, kind="container"),
- cpu=2,
- memory_mb=4096,
- services={"env": 3211}, # cua-spacesd
- claim_secrets=True,
- ),
- PoolOptions(runtime="gvisor", replicas=0, max_pool_size=2),
- )
- claims = 0
- try:
-
- @asynccontextmanager
- async def opener(spec, target, *, max_pool_size=1, on_progress=None):
- nonlocal claims
- claims += 1
- claim = f"{name}-c{claims}"
- log(f"claiming {claim}")
- async with pool.claim(
- name=claim,
- claim_token=generate_claim_token(),
- time_to_start=900,
- ttl_seconds_after_created=3600,
- ) as sandbox:
- yield sandbox
- log(f"released {claim}")
-
- target = Target(on="cloud", concurrency=2)
- spec = resolve_env_spec(
- {"provider": "native", "setup_config": {"os_type": "linux"}}, target
- )
- jobs = [
- Job(HELLO, v, spec, f"{name}-v{v}", tmp_path / f"hello_file_env_v{v}") for v in (0, 1)
- ]
- runner = BatchRunner(target, AgentOptions(), opener=opener)
- return await asyncio.wait_for(runner.run(jobs), TIMEOUT_S)
- finally:
- log(f"deleting pool {name}")
- await pool.delete()
-
-
-def test_fleet_gvisor_hello_file_env(tmp_path):
- results = asyncio.run(_run(tmp_path))
- for result in results:
- log(f"{result.task} v{result.variant}: {result.status} reward={result.reward}")
- print((Path(result.output_dir) / "run.log").read_text()[-3000:])
- assert [r.status for r in results] == ["completed", "completed"]
- assert all(r.reward == 1.0 for r in results)
- saved = json.loads((tmp_path / "hello_file_env_v0" / "result.json").read_text())
- assert saved["on"] == "cloud" and saved["backend"] == "cloud-gvisor"
- assert saved["runtime"] == "container"
- log(f"image_digest={saved['image_digest']} arch={saved['arch']}")
- # The pool's template image, pinned by the SDK (Fleet.pool_image_info).
- assert "@sha256:" in (saved["image_digest"] or ""), saved
diff --git a/libs/cua-bench/cua_bench/tests/test_cli_golden.py b/libs/cua-bench/cua_bench/tests/test_cli_golden.py
index 9e17827486..ee426c69cf 100644
--- a/libs/cua-bench/cua_bench/tests/test_cli_golden.py
+++ b/libs/cua-bench/cua_bench/tests/test_cli_golden.py
@@ -170,13 +170,10 @@ def cli_env(tmp_path, monkeypatch):
monkeypatch.delenv(var, raising=False)
monkeypatch.setattr(manager, "RUNS_FILE", tmp_path / "state" / "cua-bench" / "runs.json")
# Never read the real credential store (the OS vault on macOS) in tests.
- monkeypatch.setenv("CUA_FLEET_SESSION", "0")
monkeypatch.setenv("CUA_CREDENTIAL_STORE", "file")
monkeypatch.setenv("CUA_HOME", str(tmp_path / "cua-home"))
# No user config (~/.cua/config.yaml, agents.yaml) leaks into the tests.
monkeypatch.setenv("HOME", str(tmp_path / "home"))
- for var in ("FLEETS_TOKEN", "CUA_CLIENT_ID", "CUA_CLIENT_SECRET"):
- monkeypatch.delenv(var, raising=False)
monkeypatch.chdir(tmp_path)
return sdk
@@ -248,7 +245,6 @@ def test_run_list_info_logs_and_trace_lookup(cli_env, tmp_path, capsys):
assert [name for name, _ in traces] == ["hello_file_env_v1"]
[email protected](reason="Cua Cloud has ended (CUA-1854)")
def test_dry_run_plans_without_a_sandbox(cli_env, tmp_path, capsys):
out = tmp_path / "out"
code = run_cb(["run", str(HELLO), "--dry-run", "--kind", "auto", "--output-dir", str(out)])
@@ -259,9 +255,8 @@ def test_dry_run_plans_without_a_sandbox(cli_env, tmp_path, capsys):
assert "no sandbox was started" in text
assert cli_env.calls == [] and not out.exists()
code = run_cb(["run", str(HELLO), "--dry-run", "--kind", "vm", "--on", "cloud"])
- text = capsys.readouterr().out
- assert code == 0
- assert "-> vm (containerdisk) on Fleet via cloud-kubevirt [--kind/--runtime]" in text
+ assert code == 1
+ assert "Cua Cloud has ended" in capsys.readouterr().out
code = run_cb(["run", str(HELLO), "--dry-run", "--runtime", "qemu"])
assert "-> vm (containerdisk) on local via local-qemu [--kind/--runtime]" in (
capsys.readouterr().out
@@ -274,11 +269,10 @@ def test_dry_run_plans_without_a_sandbox(cli_env, tmp_path, capsys):
assert "valid runtime: auto, gvisor, runc, qemu, lume" in capsys.readouterr().out
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-def test_the_user_default_location_drives_cb_run(cli_env, monkeypatch, capsys):
+def test_a_cloud_default_location_fails_unless_overridden(cli_env, monkeypatch, capsys):
monkeypatch.setenv("CUA_DEFAULT_ON", "cloud")
- assert run_cb(["run", str(HELLO), "--dry-run"]) == 0
- assert "on Fleet via cloud-gvisor" in capsys.readouterr().out
+ assert run_cb(["run", str(HELLO), "--dry-run"]) == 1
+ assert "Cua Cloud has ended" in capsys.readouterr().out
assert run_cb(["run", str(HELLO), "--dry-run", "--on", "local"]) == 0
assert "via local-gvisor" in capsys.readouterr().out
@@ -330,46 +324,6 @@ def test_results_record_what_ran(cli_env, tmp_path):
]
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-def test_env_ls_and_gc_use_the_sdk_pools_api(cli_env, monkeypatch, capsys):
- from types import SimpleNamespace
-
- from cua_bench import sandboxes as sb
-
- calls = []
-
- class Pools:
- @staticmethod
- async def list_pools():
- calls.append("list_pools")
- return [
- SimpleNamespace(
- name="cua-auto-abc", ready_replicas=1, replicas=2, claims=1, last_used=None
- )
- ]
-
- @staticmethod
- async def list_claims():
- calls.append("list_claims")
- return [SimpleNamespace(name="c1", pool="cua-auto-abc", phase="Bound", managed=True)]
-
- @staticmethod
- async def gc(idle_after):
- calls.append(("gc", idle_after))
- return SimpleNamespace(pools_deleted=["cua-auto-old"], claims_deleted=[], errors=[])
-
- monkeypatch.setattr(sb, "pools_module", lambda: Pools)
- monkeypatch.setattr(sb, "cloud_auth_source", lambda *a: "client credentials")
- assert run_cb(["env", "ls"]) == 0
- out = capsys.readouterr().out
- assert "cua-auto-abc" in out and "1/2" in out and "Bound" in out
- assert run_cb(["env", "gc", "--idle", "30m"]) == 0
- assert "deleted pool cua-auto-old" in capsys.readouterr().out.replace("\x1b[92m", "").replace(
- "\x1b[0m", ""
- )
- assert calls == ["list_pools", "list_claims", ("gc", 1800)]
-
-
def test_legacy_commands_are_deprecation_shims(cli_env, tmp_path, capsys):
"""image/platform/prune/agent keep parsing and exit 0 with a pointer."""
for argv in (
diff --git a/libs/cua-bench/cua_bench/tests/test_image_facts.py b/libs/cua-bench/cua_bench/tests/test_image_facts.py
index 938daf2a6b..1553e0564a 100644
--- a/libs/cua-bench/cua_bench/tests/test_image_facts.py
+++ b/libs/cua-bench/cua_bench/tests/test_image_facts.py
@@ -1,6 +1,5 @@
"""``image_facts``: what ran, recorded per result (kind, runtime, image ref,
-variant, digest, arch). Hermetic: fake sandboxes and a cua-sandbox Sandbox
-with a faked SDK answer; no network, container, VM or Fleet.
+variant, digest, arch). Hermetic: fake sandboxes; no network, container or VM.
"""
from __future__ import annotations
@@ -63,21 +62,3 @@ def test_no_image_info_keeps_the_spec():
facts = image_facts(sandbox, spec)
assert facts["image_ref"] == "ghcr.io/trycua/linux:24.04"
assert facts["image_digest"] is None and facts["arch"] is None
-
-
-async def test_a_cua_sandbox_named_pool_claim_feeds_image_facts(monkeypatch):
- """End to end through cua-sandbox's claim hook with a faked SDK answer."""
- from cua_sandbox import Sandbox, _sdk
- from cua_sandbox import pool as pool_module
- from cua_sandbox.transport.env import EnvTransport
-
- async def pool_image_info(pool):
- assert pool == "cua-e2e-named"
- return _info()
-
- monkeypatch.setattr(_sdk, "pool_image_info", pool_image_info)
- sandbox = Sandbox(EnvTransport(url="http://127.0.0.1:1"), name="sb")
- await pool_module._record_pool_image(sandbox, "cua-e2e-named")
- facts = image_facts(sandbox, _pool_spec())
- assert facts["image_digest"] == PINNED
- assert facts["arch"] == "amd64"
diff --git a/libs/cua-bench/cua_bench/tests/test_interact_display.py b/libs/cua-bench/cua_bench/tests/test_interact_display.py
index de587d34a0..31395be89b 100644
--- a/libs/cua-bench/cua_bench/tests/test_interact_display.py
+++ b/libs/cua-bench/cua_bench/tests/test_interact_display.py
@@ -115,6 +115,6 @@ def test_no_display_service_is_published():
spec = EnvSpec(provider="native")
windows = EnvSpec(provider="native", os_type="windows", kind="vm")
for env_spec, on in ((spec, "local"), (spec, "cloud"), (windows, "local")):
- kwargs = sandboxes.ephemeral_kwargs(env_spec, Target(on=on), max_pool_size=1)
+ kwargs = sandboxes.ephemeral_kwargs(env_spec, Target(on=on))
assert "services" not in kwargs
diff --git a/libs/cua-bench/cua_bench/tests/test_lifecycle.py b/libs/cua-bench/cua_bench/tests/test_lifecycle.py
index 4125fc68f2..85cb44f16c 100644
--- a/libs/cua-bench/cua_bench/tests/test_lifecycle.py
+++ b/libs/cua-bench/cua_bench/tests/test_lifecycle.py
@@ -38,13 +38,15 @@ async def test_gym_reset_opens_and_close_releases(sdk):
assert sdk.live == 0 and sdk.released == 1
[email protected](reason="Cua Cloud has ended (CUA-1854)")
@pytest.mark.asyncio
-async def test_gym_target_cloud(sdk):
+async def test_gym_target_cloud_ends_with_cua_cloud(sdk):
+ from cua_bench.targets import CloudEnded
+
env = make(str(HELLO))
env.target = Target(on="cloud")
- await env.reset(task_id=0)
- assert sdk.calls[0]["on"] == "cloud" and sdk.calls[0]["max_pool_size"] == 1
+ with pytest.raises(CloudEnded, match="Cua Cloud has ended"):
+ await env.reset(task_id=0)
+ assert sdk.calls == []
await env.close()
assert sdk.live == 0
diff --git a/libs/cua-bench/cua_bench/tests/test_remote_session.py b/libs/cua-bench/cua_bench/tests/test_remote_session.py
index b9ce25d14a..f4eef5d38f 100644
--- a/libs/cua-bench/cua_bench/tests/test_remote_session.py
+++ b/libs/cua-bench/cua_bench/tests/test_remote_session.py
@@ -71,9 +71,8 @@ async def test_full_lifecycle_uses_the_runner_lifecycle(monkeypatch):
assert sdk.live == 0 and sdk.released == 1
[email protected](reason="Cua Cloud has ended (CUA-1854)")
@pytest.mark.asyncio
-async def test_full_lifecycle_windows_and_cloud(monkeypatch):
+async def test_full_lifecycle_windows(monkeypatch):
from cua_bench import sandboxes
from .fakes import FakeSDK
@@ -81,14 +80,30 @@ async def test_full_lifecycle_windows_and_cloud(monkeypatch):
sdk = FakeSDK()
monkeypatch.setattr(sandboxes, "_sdk", sdk.pair)
monkeypatch.delenv("CUA_BENCH_IMAGE", raising=False)
- async with remote.RemoteDesktopSession(os_type="win11", provider_type="cloud"):
+ async with remote.RemoteDesktopSession(os_type="win11"):
pass
(call,) = sdk.calls
- assert call["on"] == "cloud" and call["image"].builtin == "windows"
+ assert call["on"] == "local" and call["image"].builtin == "windows"
assert call["image"].kind == "vm"
assert sdk.released == 1
+async def test_the_cloud_provider_type_ends_with_cua_cloud(monkeypatch):
+ from cua_bench import sandboxes
+ from cua_bench.targets import CloudEnded
+
+ from .fakes import FakeSDK
+
+ sdk = FakeSDK()
+ monkeypatch.setattr(sandboxes, "_sdk", sdk.pair)
+ monkeypatch.delenv("CUA_BENCH_IMAGE", raising=False)
+ with pytest.raises(CloudEnded, match="Cua Cloud has ended"):
+ async with remote.RemoteDesktopSession(os_type="win11", provider_type="cloud"):
+ pass
+ assert sdk.calls == []
+
+
@pytest.mark.asyncio
async def test_actions_map_to_sandbox_interfaces(fake_sdk):
_, sb = fake_sdk
diff --git a/libs/cua-bench/cua_bench/tests/test_targets.py b/libs/cua-bench/cua_bench/tests/test_targets.py
index 42e9ad126d..d7b2480056 100644
--- a/libs/cua-bench/cua_bench/tests/test_targets.py
+++ b/libs/cua-bench/cua_bench/tests/test_targets.py
@@ -9,6 +9,7 @@ kind and the engine, the same as every cua surface. ``--on`` is
import pytest
from cua_bench.targets import (
+ CloudEnded,
EnvSpec,
Target,
TargetError,
@@ -58,12 +59,11 @@ class TestResolveTarget:
with pytest.raises(SystemExit):
parser.parse_args(["--on", "fleet"])
- @pytest.mark.skip(reason="Cua Cloud has ended (CUA-1854)")
def test_env_fallbacks(self):
t = resolve_target(
- environ={"CUA_DEFAULT_ON": "cloud", "CUA_DEFAULT_KIND": "vm", "CUA_BENCH_IMAGE": IMG}
+ environ={"CUA_DEFAULT_ON": "local", "CUA_DEFAULT_KIND": "vm", "CUA_BENCH_IMAGE": IMG}
)
- assert (t.on, t.kind, t.image) == ("cloud", "vm", IMG)
+ assert (t.on, t.kind, t.image) == ("local", "vm", IMG)
assert (t.on_source, t.kind_source) == ("CUA_DEFAULT_ON", "CUA_DEFAULT_KIND")
def test_flags_beat_env(self):
@@ -74,10 +74,9 @@ class TestResolveTarget:
t = resolve_target("local", runtime="qemu", environ={})
assert (t.on, t.kind, t.runtime) == ("local", "vm", "qemu")
- @pytest.mark.skip(reason="Cua Cloud has ended (CUA-1854)")
def test_resources(self):
t = resolve_target(
- "cloud", cpu="2", memory="4G", concurrency=8, warm=True, claim_ttl="20m", environ={}
+ "local", cpu="2", memory="4G", concurrency=8, warm=True, claim_ttl="20m", environ={}
)
assert (t.cpu, t.memory_mb, t.concurrency, t.warm, t.claim_ttl_s) == (
2,
@@ -340,16 +339,11 @@ class TestVariantSelection:
class TestPoolImages:
- @pytest.mark.skip(reason="Cua Cloud has ended (CUA-1854)")
- def test_pool_prefix_claims_from_an_existing_fleet_pool(self):
- spec = resolve_env_spec({"provider": "native"}, Target(on="cloud", image="pool:bench-p"))
- assert (spec.pool, spec.image, spec.image_label) == ("bench-p", None, "pool:bench-p")
- assert spec.backend("cloud") == "cloud-pool:bench-p"
- with pytest.raises(TargetError, match="--on cloud"):
+ def test_pool_images_end_with_cua_cloud(self):
+ with pytest.raises(CloudEnded, match="Cua Cloud has ended"):
resolve_env_spec({"provider": "native"}, Target(image="pool:bench-p"))
- @pytest.mark.skip(reason="Cua Cloud has ended (CUA-1854)")
- def test_fleet_prefix_is_a_deprecated_alias(self):
+ def test_the_fleet_prefix_ends_with_cua_cloud_too(self):
with pytest.warns(DeprecationWarning, match="use pool:old"):
- spec = resolve_env_spec({"provider": "native"}, Target(on="cloud", image="fleet:old"))
- assert spec.pool == "old"
+ with pytest.raises(CloudEnded):
+ resolve_env_spec({"provider": "native"}, Target(image="fleet:old"))
diff --git a/libs/cua-bench/cua_bench/tests/test_unified_runner.py b/libs/cua-bench/cua_bench/tests/test_unified_runner.py
index 33d28bc0fb..148e49e062 100644
--- a/libs/cua-bench/cua_bench/tests/test_unified_runner.py
+++ b/libs/cua-bench/cua_bench/tests/test_unified_runner.py
@@ -1,8 +1,7 @@
-"""Hermetic tests for the unified runner: SDK adapter, cloud auth, batch execution.
+"""Hermetic tests for the unified runner: SDK adapter and batch execution.
No sandbox, VM, container, network or keychain: cua_sandbox is replaced by a
-fake whose ``Sandbox.ephemeral`` has the managed-pool signature (``warm``,
-``max_pool_size``, ``claim_ttl``, ``progress``) and records every claim.
+fake whose ``Sandbox.ephemeral`` records every sandbox it opens.
"""
import asyncio
@@ -79,8 +78,8 @@ class FakeImage:
macos = android = linux
-class FakeFleetSDK:
- """Records claims; ``max_pool_size`` is the managed-pool contract."""
+class FakeSDK:
+ """Records every sandbox it opens and how many are live at once."""
def __init__(self, delay=0.02):
self.calls = []
@@ -103,39 +102,15 @@ class FakeFleetSDK:
memory_mb=None,
time_to_start=None,
telemetry_enabled=True,
- warm=None,
- max_pool_size=None,
- claim_ttl=None,
- progress=None,
):
sdk.calls.append(
- dict(
- image=image,
- on=on,
- local=local,
- cpu=cpu,
- memory_mb=memory_mb,
- warm=warm,
- max_pool_size=max_pool_size,
- claim_ttl=claim_ttl,
- )
+ dict(image=image, on=on, local=local, cpu=cpu, memory_mb=memory_mb)
)
- pool = f"cua-auto-{abs(hash(image.ref)) % 10000}"
- if progress is not None:
- progress(
- SimpleNamespace(
- stage="cold_start", pool=pool, message="scaling from zero", elapsed=0.0
- )
- )
sdk.live += 1
sdk.peak = max(sdk.peak, sdk.live)
try:
await asyncio.sleep(sdk.delay)
- if progress is not None:
- progress(
- SimpleNamespace(stage="ready", pool=pool, message="ready", elapsed=1.0)
- )
- yield FakeSandbox(f"claim-{len(sdk.calls)}", pool)
+ yield FakeSandbox(f"sandbox-{len(sdk.calls)}", None)
finally:
sdk.live -= 1
sdk.released += 1
@@ -145,7 +120,7 @@ class FakeFleetSDK:
@pytest.fixture
def fake_sdk(monkeypatch):
- sdk = FakeFleetSDK()
+ sdk = FakeSDK()
monkeypatch.setattr(sandboxes, "_sdk", lambda: (FakeImage, sdk.Sandbox))
return sdk
@@ -163,81 +138,39 @@ class TestAdapter:
)
assert (vm.builtin, vm.kind) == ("windows", "vm")
- def test_kwargs_local_carry_caps_but_never_pool_options(self):
+ def test_kwargs_carry_the_sizing_and_the_location(self):
spec = EnvSpec(provider="native", image=IMG)
- kw = sandboxes.ephemeral_kwargs(
- spec,
- Target(on="local", cpu=2, memory_mb=2048, warm=True),
- max_pool_size=4,
- )
+ kw = sandboxes.ephemeral_kwargs(spec, Target(on="local", cpu=2, memory_mb=2048, warm=True))
# The SDK sizes local containers and VMs from cpu/memory_mb itself.
assert kw["on"] == "local" and kw["memory_mb"] == 2048 and kw["cpu"] == 2
- assert "max_pool_size" not in kw and "warm" not in kw and "progress" not in kw
-
- def test_kwargs_cloud_managed(self):
- kw = sandboxes.ephemeral_kwargs(
- EnvSpec(provider="native", image=IMG),
- Target(on="cloud", warm=True, claim_ttl_s=600),
- max_pool_size=3,
- progress=print,
- )
- assert (kw["on"], kw["max_pool_size"], kw["warm"], kw["claim_ttl"]) == (
- "cloud",
- 3,
- True,
- 600,
- )
- assert kw["progress"] is print
+ for pool_option in ("max_pool_size", "warm", "claim_ttl", "progress"):
+ assert pool_option not in kw
- def test_explain_pull_error_cloud_and_local(self):
+ def test_explain_pull_error_names_the_registry(self):
spec = EnvSpec(provider="native", image=IMG)
- err = RuntimeError("claim failed: ErrImagePull manifest unknown")
- cloud = sandboxes.explain_error(err, spec, Target(on="cloud"))
- assert "Fleet could not pull" in cloud and "registry.example" in cloud
+ err = RuntimeError("start failed: ErrImagePull manifest unknown")
local = sandboxes.explain_error(err, spec, Target(on="local"))
assert "not available locally" in local and "docker build" in local
+ assert "registry.example" in local
- def test_explain_auth_error(self):
+ def test_other_errors_pass_through(self):
err = RuntimeError("401 Unauthorized")
- msg = sandboxes.explain_error(err, None, Target(on="cloud"))
- assert "cua auth login" in msg
-
-
-# ── Cloud auth (resolved by the SDK) ────────────────────────────────────────
-
-
-class TestCloudAuth:
- def test_source_comes_from_the_sdk(self):
- assert sandboxes.cloud_auth_source(lambda: "client credentials") == "client credentials"
- assert sandboxes.cloud_auth_source(lambda: "FLEETS_TOKEN") == "FLEETS_TOKEN"
-
- def test_not_authed_says_cua_auth_login(self):
- with pytest.raises(sandboxes.CloudAuthError, match="cua auth login"):
- sandboxes.cloud_auth_source(lambda: None)
-
- @pytest.mark.skip(reason="Cua Cloud has ended (CUA-1854)")
- def test_cloud_run_stops_before_any_claim_without_credentials(
- self, fake_sdk, monkeypatch, tmp_path, capsys
- ):
- from cua_bench.cli import main as cli_main
- from cua_bench.sessions import manager
+ assert sandboxes.explain_error(err, None, Target(on="local")) == (
+ "RuntimeError: 401 Unauthorized"
+ )
- monkeypatch.setattr(sandboxes, "cloud_auth_source", _raise_auth)
- monkeypatch.setattr(manager, "RUNS_FILE", tmp_path / "runs.json")
- monkeypatch.setenv("CUA_BENCH_NO_BANNER", "1")
- monkeypatch.setenv("CUA_TELEMETRY_ENABLED", "false")
- task = tmp_path / "t"
- task.mkdir()
- (task / "main.py").write_text(TASK)
- with pytest.raises(SystemExit) as exit_info:
- cli_main.main(["run", str(task), "--on", "cloud", "--output-dir", str(tmp_path / "o")])
- assert exit_info.value.code == 1
- assert "cua auth login" in capsys.readouterr().out
- assert fake_sdk.calls == []
+ def test_cloud_targets_and_pool_images_end_with_cua_cloud(self):
+ from cua_bench.targets import CloudEnded
+ async def go(spec, target):
+ async with sandboxes.open_sandbox(spec, target):
+ pass
-def _raise_auth(*_args):
- raise sandboxes.CloudAuthError(sandboxes.LOGIN_HINT)
+ spec = EnvSpec(provider="native", image=IMG)
+ with pytest.raises(CloudEnded, match="Cua Cloud has ended"):
+ asyncio.run(go(spec, Target(on="cloud")))
+ with pytest.raises(CloudEnded):
+ asyncio.run(go(EnvSpec(provider="native", pool="bench-p"), Target(on="local")))
# ── Batch runner ────────────────────────────────────────────────────────────
@@ -282,7 +215,7 @@ def task_dir(tmp_path):
return path
-def _jobs(task_dir, out, n=3, on="cloud"):
+def _jobs(task_dir, out, n=3):
spec = EnvSpec(provider="native", os_type="linux", kind="container", image=IMG)
return [
Job(
@@ -314,11 +247,12 @@ class Recorder:
class TestBatchRunner:
- @pytest.mark.skip(reason="Cua Cloud has ended (CUA-1854)")
- def test_cloud_batch_claims_one_pool_sized_to_concurrency(self, fake_sdk, task_dir, tmp_path):
+ def test_local_batch_opens_one_sandbox_per_variant_up_to_the_concurrency(
+ self, fake_sdk, task_dir, tmp_path
+ ):
statuses = []
recorder = Recorder()
- target = Target(on="cloud", concurrency=2, warm=True, claim_ttl_s=300)
+ target = Target(on="local", concurrency=2)
runner = BatchRunner(
target,
AgentOptions(oracle=True),
@@ -327,20 +261,16 @@ class TestBatchRunner:
)
results = asyncio.run(runner.run(_jobs(task_dir, tmp_path / "out")))
- assert len(fake_sdk.calls) == 3 # one claim per variant
- assert {c["max_pool_size"] for c in fake_sdk.calls} == {2} # pool sized to the batch
- assert all(
- c["on"] == "cloud" and c["warm"] is True and c["claim_ttl"] == 300
- for c in fake_sdk.calls
- )
- assert {c["image"].ref for c in fake_sdk.calls} == {IMG} # same pool key
- assert fake_sdk.peak <= 2 # never more claims than concurrency
- assert fake_sdk.released == 3 # every claim released
+ assert len(fake_sdk.calls) == 3 # one sandbox per variant
+ assert all(c["on"] == "local" for c in fake_sdk.calls)
+ assert {c["image"].ref for c in fake_sdk.calls} == {IMG}
+ assert fake_sdk.peak <= 2 # never more sandboxes than concurrency
+ assert fake_sdk.released == 3 # every sandbox released
assert ("plan", [(3, 2)]) in recorder.events
by_variant = {r.variant: r for r in results}
assert by_variant[0].status == by_variant[1].status == "completed"
- assert by_variant[0].reward == 1.0 and by_variant[0].pool.startswith("cua-auto-")
+ assert by_variant[0].reward == 1.0 and by_variant[0].pool is None
assert by_variant[2].status == "failed" and "boom in evaluate" in by_variant[2].error
v0 = tmp_path / "out" / "write_env_v0"
@@ -350,57 +280,27 @@ class TestBatchRunner:
assert (saved["status"], saved["reward"], saved["on"], saved["backend"]) == (
"completed",
1.0,
- "cloud",
- "cloud-gvisor",
+ "local",
+ "local-gvisor",
)
assert ("s0", "running") in statuses and ("s2", "failed") in statuses
- @pytest.mark.skip(reason="Cua Cloud has ended (CUA-1854)")
- def test_first_cloud_claim_per_pool_is_single_flight(self, fake_sdk, task_dir, tmp_path):
- order = []
- real = fake_sdk.Sandbox.ephemeral
-
- @asynccontextmanager
- async def ephemeral(image=None, **kw):
- progress = kw.get("progress")
- order.append(("enter", len(order)))
- if progress is not None:
- progress(
- SimpleNamespace(stage="pool", pool=None, message="creating pool", elapsed=0.0)
- )
- await asyncio.sleep(0.05) # pool creation in flight
- order.append(("pool-created", len(order)))
- async with real(image, **kw) as sb:
- yield sb
-
- fake_sdk.Sandbox.ephemeral = ephemeral
- runner = BatchRunner(Target(on="cloud", concurrency=3), AgentOptions(oracle=True))
- results = asyncio.run(runner.run(_jobs(task_dir, tmp_path / "out", n=3)))
- assert [r.status for r in results].count("completed") == 2 # v2 raises in evaluate
- # Nobody else entered before the first claim's pool existed.
- assert [kind for kind, _ in order[:2]] == ["enter", "pool-created"]
- assert fake_sdk.peak == 3 # the rest still claim in parallel
-
def test_local_batch_uses_local_sandboxes(self, fake_sdk, task_dir, tmp_path):
runner = BatchRunner(
Target(on="local", concurrency=3, memory_mb=2048), AgentOptions(oracle=True)
)
results = asyncio.run(runner.run(_jobs(task_dir, tmp_path / "out", n=2)))
assert [r.status for r in results] == ["completed", "completed"]
- assert all(
- c["on"] == "local" and c["max_pool_size"] is None and c["memory_mb"] == 2048
- for c in fake_sdk.calls
- )
+ assert all(c["on"] == "local" and c["memory_mb"] == 2048 for c in fake_sdk.calls)
assert results[0].backend == "local-gvisor"
- @pytest.mark.skip(reason="Cua Cloud has ended (CUA-1854)")
- def test_cancel_releases_every_claim(self, fake_sdk, task_dir, tmp_path):
- fake_sdk.delay = 30 # hold the claims until cancelled
- runner = BatchRunner(Target(on="cloud", concurrency=3), AgentOptions(oracle=True))
+ def test_cancel_releases_every_sandbox(self, fake_sdk, task_dir, tmp_path):
+ fake_sdk.delay = 30 # hold the sandboxes until cancelled
+ runner = BatchRunner(Target(on="local", concurrency=3), AgentOptions(oracle=True))
async def go():
task = asyncio.create_task(runner.run(_jobs(task_dir, tmp_path / "out")))
- for _ in range(200): # bounded wait for all three claims
+ for _ in range(200): # bounded wait for all three sandboxes
if fake_sdk.live == 3:
break
await asyncio.sleep(0.01)
@@ -484,22 +384,3 @@ def test_session_status_without_docker(tmp_path):
if sys.platform == "win32": # pragma: no cover
pytestmark = pytest.mark.skip("fcntl-based run bookkeeping")
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-def test_pool_image_opens_a_claim_from_that_pool(monkeypatch):
- from cua_bench.targets import resolve_env_spec as resolve
-
- from .fakes import FakeSDK
-
- sdk = FakeSDK()
- monkeypatch.setattr(sandboxes, "_sdk", sdk.pair)
- spec = resolve({"provider": "native"}, Target(on="cloud", image="pool:bench-p"))
-
- async def go():
- async with sandboxes.open_sandbox(spec, Target(on="cloud")) as sb:
- return sb.id
-
- assert asyncio.run(go()) == "cloud:sb-1"
- (call,) = sdk.calls
- assert call["image"] is None and call["pool"] == "bench-p" and call["on"] == "cloud"
diff --git a/libs/cua-bench/pyproject.toml b/libs/cua-bench/pyproject.toml
index dfaf1eda0e..e628ad9b98 100644
--- a/libs/cua-bench/pyproject.toml
+++ b/libs/cua-bench/pyproject.toml
@@ -80,8 +80,8 @@ otel = [
"opentelemetry-exporter-otlp-proto-http>=1.20.0",
]
-# Cloud runs use Fleet through cua-sandbox (a core dependency); this extra
-# only adds OpenTelemetry export for long batches.
+# Deprecated: Cua Cloud has ended. Kept so `cua-bench[cloud]` still installs;
+# it only adds OpenTelemetry export for long batches.
cloud = [
"cua-bench[otel]",
]
@@ -206,10 +206,6 @@ testpaths = ["cua_bench/tests"]
cua-agent = { path = "../python/agent", editable = true }
cua-sandbox = { path = "../python/cua-sandbox", editable = true }
-[[tool.uv.index]]
-name = "cua-wheels"
-url = "https://wheels.cua.ai/simple"
-
[tool.uv]
constraint-dependencies = [
"cryptography>=48.0.1",
diff --git a/libs/cua-bench/uv.lock b/libs/cua-bench/uv.lock
index dd87ff68a7..0d5048be66 100644
--- a/libs/cua-bench/uv.lock
+++ b/libs/cua-bench/uv.lock
@@ -780,18 +780,6 @@ provides-extras = ["otel", "telemetry"]
[package.metadata.requires-dev]
dev = [{ name = "pytest", specifier = ">=8.3.5" }]
-[[package]]
-name = "cua-fleet"
-version = "0.1.17"
-source = { registry = "https://wheels.cua.ai/simple" }
-wheels = [
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.17-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:a8908b5c7f0f3c75d09b908b58867d43270f69d3726bb0d90316443f2265d0e3" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.17-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6aea577f21343326aeb06df03c07df65df8dd2f3b0097e02f25a7bc6b9d2c458" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.17-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:bda49298c77c65eb349e8420f9237f6b7fb2fd25203747df98a9513b98fd5d73" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.17-py3-none-manylinux_2_34_x86_64.whl", hash = "sha256:4cdbc89e850d841481713abf1e8bf9719b2e33b3c31f26bbea5f63e1ead3c6c0" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.17-py3-none-win_amd64.whl", hash = "sha256:ee4c139b1c0cebe1702114a34fd0fd60d216c5862d9fdc3472bb8b9879ac9eae" },
-]
-
[[package]]
name = "cua-sandbox"
version = "0.9.0"
@@ -799,7 +787,6 @@ source = { editable = "../python/cua-sandbox" }
dependencies = [
{ name = "cua" },
{ name = "cua-core" },
- { name = "cua-fleet" },
{ name = "grpcio" },
{ name = "httpx" },
{ name = "jsonschema" },
@@ -816,7 +803,6 @@ requires-dist = [
{ name = "cua", editable = "../cua/python" },
{ name = "cua-core", specifier = ">=0.1.18,<0.4.0" },
{ name = "cua-driver", marker = "extra == 'driver'", specifier = "==0.28.2" },
- { name = "cua-fleet", specifier = "==0.1.17" },
{ name = "grpcio", specifier = "==1.78.0" },
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "jsonschema", specifier = ">=4.23,<5.0" },
diff --git a/libs/python/cua-sandbox-apps/uv.lock b/libs/python/cua-sandbox-apps/uv.lock
index feb662098b..aeb6c60564 100644
--- a/libs/python/cua-sandbox-apps/uv.lock
+++ b/libs/python/cua-sandbox-apps/uv.lock
@@ -395,18 +395,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/ed/90/5148998a26671855539e2c3a620f72ef51f83118beffdfb7e77893d4730b/cua_core-0.3.1-py3-none-any.whl", hash = "sha256:9191b8abf5e02ea6bf8ba21237e747d4e3b319f6f24d4e66e04b7606fcc449f6", size = 10239, upload-time = "2026-04-15T21:39:48.265Z" },
]
-[[package]]
-name = "cua-fleet"
-version = "0.1.17"
-source = { registry = "https://pypi.org/simple" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/55/2a/406cc8d9a6f79368cd9a78361ba45c98909498068c345d5a92d3b8b5788e/cua_fleet-0.1.17-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:a8908b5c7f0f3c75d09b908b58867d43270f69d3726bb0d90316443f2265d0e3", size = 2281312, upload-time = "2026-09-11T02:55:56.726Z" },
- { url = "https://files.pythonhosted.org/packages/6c/f5/7fc0160aa7b7f5c2ca110ba40d9c47acbdc76f4919e07621943403b39b4e/cua_fleet-0.1.17-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6aea577f21343326aeb06df03c07df65df8dd2f3b0097e02f25a7bc6b9d2c458", size = 2227112, upload-time = "2026-09-11T02:55:57.916Z" },
- { url = "https://files.pythonhosted.org/packages/cb/51/da3b0b7c6bfb22c0f1e5bdf016b120c9ba11d045a3e97ccb65234eda80a2/cua_fleet-0.1.17-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:bda49298c77c65eb349e8420f9237f6b7fb2fd25203747df98a9513b98fd5d73", size = 2596935, upload-time = "2026-09-11T02:55:59.122Z" },
- { url = "https://files.pythonhosted.org/packages/31/a4/5137ff02e053181ce23f10fe53f1cc6e97165e925e6a00f97919d904fc6f/cua_fleet-0.1.17-py3-none-manylinux_2_34_x86_64.whl", hash = "sha256:4cdbc89e850d841481713abf1e8bf9719b2e33b3c31f26bbea5f63e1ead3c6c0", size = 2531926, upload-time = "2026-09-11T02:56:00.117Z" },
- { url = "https://files.pythonhosted.org/packages/69/ab/cb222383d430cb6cef133e8b3f487e3482cb68823ef90047d1df2c9f3221/cua_fleet-0.1.17-py3-none-win_amd64.whl", hash = "sha256:ee4c139b1c0cebe1702114a34fd0fd60d216c5862d9fdc3472bb8b9879ac9eae", size = 2119057, upload-time = "2026-09-11T02:56:01.225Z" },
-]
-
[[package]]
name = "cua-sandbox"
version = "0.9.0"
@@ -414,7 +402,6 @@ source = { editable = "../cua-sandbox" }
dependencies = [
{ name = "cua" },
{ name = "cua-core" },
- { name = "cua-fleet" },
{ name = "grpcio" },
{ name = "httpx" },
{ name = "jsonschema" },
@@ -431,7 +418,6 @@ requires-dist = [
{ name = "cua", editable = "../../cua/python" },
{ name = "cua-core", specifier = ">=0.1.18,<0.4.0" },
{ name = "cua-driver", marker = "extra == 'driver'", specifier = "==0.28.2" },
- { name = "cua-fleet", specifier = "==0.1.17" },
{ name = "grpcio", specifier = "==1.78.0" },
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "jsonschema", specifier = ">=4.23,<5.0" },
diff --git a/libs/python/cua-sandbox/README.md b/libs/python/cua-sandbox/README.md
index a979f070c6..07472d90db 100644
--- a/libs/python/cua-sandbox/README.md
+++ b/libs/python/cua-sandbox/README.md
@@ -24,7 +24,7 @@ Driver SDK:
pip install 'cua-sandbox[driver]'
```
-The `driver` extra pins `cua-driver==0.27.0`, which provides the typed-window API
+The `driver` extra pins `cua-driver==0.28.2`, which provides the typed-window API
and the remote channel bridge. It requires that version to be published for your
platform.
@@ -40,17 +40,14 @@ async def observe_guest(sb):
### Carriers
-`sb.driver.connect()` picks one carrier and never falls back to another:
+`sb.driver.connect()` rides **cua-spacesd**: the typed-envelope MCP extension
+on the spacesd's `/mcp`, sent through the cua SDK's env client with the
+sandbox's own endpoint and credentials. It works for direct
+(`Sandbox.connect(url=...)`) and local sandboxes. Explicit form:
+`connect(service="env", transport="mcp")`. Named Driver services were a Cua
+Cloud feature and are gone.
-- **cua-spacesd** (default): the typed-envelope MCP extension on the
- spacesd's `/mcp`, sent through the cua SDK's env client with the sandbox's
- own endpoint and credentials. Works for direct (`Sandbox.connect(url=...)`)
- and local sandboxes. Explicit form: `connect(service="env", transport="mcp")`.
-- **`driver` service**: images that publish their own private envelope
- HTTP receiver; explicit form: `connect(service="driver")`.
-- **Named MCP service**: `connect(service="mcp", transport="mcp")`.
-
-MCP selection initializes the session and verifies
+The connection initializes the session and verifies
`capabilities.experimental["ai.cua.driver.envelopes"].version == 1` before
opening a receiver, so a tools-only endpoint fails before any desktop action.
The connection keeps the receiver's generation, host-selected permissions and
@@ -127,8 +124,7 @@ img = Image.from_registry("ghcr.io/acme/app:1", secret=RegistrySecret.from_env()
```
Layers (`apt_install`, `pip_install`, `uv_install`, `run`, `copy`, `env`) apply
-at boot locally; with `local=False` they build remotely on the registry image as
-base, cached by content. See
+at boot, built on the registry image as base and cached by content. See
[Build an image](https://cua.ai/docs/cua-sdk/guides/images) and
[private registries](https://cua.ai/docs/cua-sdk/guides/private-registries).
diff --git a/libs/python/cua-sandbox/cua_sandbox/__init__.py b/libs/python/cua-sandbox/cua_sandbox/__init__.py
index 9d4a0a95da..57812045c8 100644
--- a/libs/python/cua-sandbox/cua_sandbox/__init__.py
+++ b/libs/python/cua-sandbox/cua_sandbox/__init__.py
@@ -1,7 +1,7 @@
"""cua-sandbox — ephemeral and persistent sandboxed computer environments.
-A thin wrapper over the ``cua`` SDK: Fleet, the local runtimes and
-cua-spacesd (the computer interfaces) all go through it.
+A thin wrapper over the ``cua`` SDK: the local runtimes and cua-spacesd (the
+computer interfaces) go through it.
Usage::
@@ -12,7 +12,7 @@ Usage::
command=["python", "-m", "http.server", "8000"],
services={"web": 8000},
wait_for=http("web", "/"),
- on="local", # or "cloud"; unset: `cua config set default.on`
+ on="local",
) as sb:
print((await sb.service("web").request("GET", "/")).status_code)
@@ -21,10 +21,11 @@ To control the local machine, use cua-driver (its SDK or MCP server).
__version__ = "0.9.0" # x-release-please-version
-# Managed Fleet pools (list / gc); imported last, it needs the package loaded.
+# Retired Cua Cloud pools (every call raises CloudEnded).
from cua_sandbox import pools # noqa: E402
from cua_sandbox._auth import login, whoami
-from cua_sandbox._config import configure, fleet_auth_source
+from cua_sandbox._config import configure
+from cua_sandbox._ended import CLOUD_ENDED
from cua_sandbox._refs import AmbiguousSandbox
from cua_sandbox._sdk import (
InvalidArgument,
@@ -47,6 +48,7 @@ from cua_sandbox.runtime.compat import (
from cua_sandbox.sandbox import Sandbox, SandboxInfo, sandbox
from cua_sandbox.spec import (
ClaimSecretsNotDelivered,
+ PoolAccessDeniedError,
PoolExport,
PoolOptions,
PoolSpecMismatch,
@@ -55,36 +57,45 @@ from cua_sandbox.spec import (
)
from cua_sandbox.transport.cloud import CloudTransport
from cua_sandbox.transport.env import EnvTransport
-from cua_sandbox.transport.fleet_cloud import PoolAccessDeniedError
-from fleet_sdk import (
- ClaimSpec,
- CreatePoolRequest,
- CreatePoolRequestBuilder,
- CreateTemplateRequest,
- CreateTemplateRequestBuilder,
- Firmware,
- OsGymSandboxTemplateSpec,
- OsGymSandboxTemplateSpecBuilder,
- OsGymSandboxWarmPoolSpec,
- OsGymSandboxWarmPoolSpecBuilder,
- RuntimeKind,
- SandboxService,
- SandboxServiceBuilder,
- SandboxTemplateRef,
- SandboxTemplateRefBuilder,
- ServiceProtocol,
-)
-from fleet_sdk import Template as TemplateResource
-from fleet_sdk import (
- VmTemplate,
- VmTemplateBuilder,
- WarmPoolAutoscaling,
- WarmPoolAutoscalingBuilder,
+
+# Names that came from Cua Cloud's Fleet SDK package and went with it.
+# Importing one explains why instead of a bare "cannot import name".
+_RETIRED_FLEET_NAMES = frozenset(
+ {
+ "ClaimSpec",
+ "CreatePoolRequest",
+ "CreatePoolRequestBuilder",
+ "CreateTemplateRequest",
+ "CreateTemplateRequestBuilder",
+ "Firmware",
+ "OsGymSandboxTemplateSpec",
+ "OsGymSandboxTemplateSpecBuilder",
+ "OsGymSandboxWarmPoolSpec",
+ "OsGymSandboxWarmPoolSpecBuilder",
+ "RuntimeKind",
+ "SandboxService",
+ "SandboxServiceBuilder",
+ "SandboxTemplateRef",
+ "SandboxTemplateRefBuilder",
+ "ServiceProtocol",
+ "TemplateResource",
+ "VmTemplate",
+ "VmTemplateBuilder",
+ "WarmPoolAutoscaling",
+ "WarmPoolAutoscalingBuilder",
+ "fleet_auth_source",
+ }
)
+
+def __getattr__(name: str):
+ if name in _RETIRED_FLEET_NAMES:
+ raise ImportError(f"cannot import name {name!r} from 'cua_sandbox': {CLOUD_ENDED}")
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+
__all__ = [
"configure",
- "fleet_auth_source",
"pools",
"login",
"whoami",
@@ -100,26 +111,6 @@ __all__ = [
"SandboxSpec",
"generate_claim_token",
"Template",
- "TemplateResource",
- "CreatePoolRequest",
- "CreatePoolRequestBuilder",
- "CreateTemplateRequest",
- "CreateTemplateRequestBuilder",
- "ClaimSpec",
- "SandboxTemplateRef",
- "SandboxTemplateRefBuilder",
- "OsGymSandboxWarmPoolSpec",
- "OsGymSandboxWarmPoolSpecBuilder",
- "WarmPoolAutoscaling",
- "WarmPoolAutoscalingBuilder",
- "OsGymSandboxTemplateSpec",
- "OsGymSandboxTemplateSpecBuilder",
- "RuntimeKind",
- "VmTemplate",
- "VmTemplateBuilder",
- "SandboxService",
- "SandboxServiceBuilder",
- "ServiceProtocol",
"SignedServiceURL",
"ServiceHandle",
"CloudOptions",
@@ -129,7 +120,6 @@ __all__ = [
"PublicUrl",
"http",
"tcp",
- "Firmware",
"Sandbox",
"SandboxInfo",
"sandbox",
diff --git a/libs/python/cua-sandbox/cua_sandbox/_auth.py b/libs/python/cua-sandbox/cua_sandbox/_auth.py
index b2f4dd89b5..31ddefada0 100644
--- a/libs/python/cua-sandbox/cua_sandbox/_auth.py
+++ b/libs/python/cua-sandbox/cua_sandbox/_auth.py
@@ -11,7 +11,7 @@ from pathlib import Path
from typing import Any, Dict, Optional
import httpx
-from cua_sandbox._config import FLEET_CREDENTIALS_MISSING, get_api_key, get_base_url
+from cua_sandbox._config import get_api_key, get_base_url
from cua_sandbox._paths import cua_home, patched_or
_CUA_DIR = cua_home()
@@ -51,7 +51,7 @@ def whoami(*, api_key: Optional[str] = None) -> Dict[str, Any]:
"""
key = get_api_key(api_key)
if not key:
- raise RuntimeError(FLEET_CREDENTIALS_MISSING)
+ raise RuntimeError("No API key: run login(), pass api_key=, or set CUA_API_KEY")
resp = httpx.get(
f"{get_base_url()}/v1/whoami",
headers={"Authorization": f"Bearer {key}"},
diff --git a/libs/python/cua-sandbox/cua_sandbox/_autopool.py b/libs/python/cua-sandbox/cua_sandbox/_autopool.py
deleted file mode 100644
index e8c1e7d513..0000000000
--- a/libs/python/cua-sandbox/cua_sandbox/_autopool.py
+++ /dev/null
@@ -1,785 +0,0 @@
-"""Managed Fleet pools for ``Sandbox.create`` / ``Sandbox.ephemeral`` without ``pool=``.
-
-This module is the single adapter between cua-sandbox and the cua SDK's
-native auto pool manager (``cua_fleet::autopool::PoolManager``, reached
-through the ``cua`` binding). Everything else in the package calls only the
-module-level API:
-
-* :func:`config` builds an :class:`AutoPoolConfig` (defaults + env overrides).
-* :func:`acquire` returns a connected :class:`~cua_sandbox.Sandbox` on the
- managed pool for an image spec, creating or reusing the pool.
-* :func:`list_claims`, :func:`list_pools` and :func:`gc` back
- ``Sandbox.list()`` and pool maintenance.
-
-The native manager implements the whole contract: one pool per tenant +
-spec (``cua-auto-<base32(sha256(sub || spec_hash))[:16]>``, image tags
-resolved to digests), KEDA autoscaling from zero, an existing pool's spec is
-never rewritten, claims carry ``ttlSecondsAfterCreated = claim_ttl`` and a
-heartbeat in the SDK runtime renews them while this process holds them, and
-idle pools are garbage-collected (automatically at most once an hour per
-machine, or on demand with :func:`gc`). The spec encoding helpers below
-mirror it for inspection and tests.
-"""
-
-from __future__ import annotations
-
-import asyncio
-import base64
-import hashlib
-import json
-import logging
-import os
-import re
-from dataclasses import dataclass, field, replace
-from datetime import datetime, timedelta, timezone
-from pathlib import Path
-from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional, Union
-
-from cua_sandbox import _sdk
-from cua_sandbox._paths import cua_home, patched_or
-from cua_sandbox._sdk import ENV_SERVICE, SPACESD_PORT
-from cua_sandbox.image import Image, cloud_registry_image
-from cua_sandbox.pool import _ClaimHandle
-from cua_sandbox.transport.fleet_cloud import (
- _NATIVE_POOL_ACCESS_DENIED,
- FleetCloudTransport,
- default_server_port,
- resolve_fleet_runtime,
-)
-from fleet_sdk import SdkError
-
-if TYPE_CHECKING:
- from cua_sandbox.sandbox import Sandbox
-
-logger = logging.getLogger(__name__)
-
-MANAGED_PREFIX = "cua-auto-"
-LEGACY_EPHEMERAL_PREFIX = "cua-eph-"
-LABEL_MANAGED_BY = "cua.ai/managed-by"
-MANAGED_BY = "cua-sdk"
-LABEL_SPEC_HASH = "cua.ai/spec-hash"
-LABEL_LAST_USED = "cua.ai/last-used"
-
-#: Floor of a claim's bind deadline (``cua_fleet::autopool::MIN_BIND_DEADLINE_SECS``):
-#: live cold binds took 80 to 530 s.
-MIN_BIND_DEADLINE = 900
-_NAME_HASH_CHARS = 16
-_MAX_NAME_ATTEMPTS = 8
-_SPEC_HASH_LABEL_CHARS = 32
-_LIST_CONCURRENCY = 8
-_PROGRESS_TICK = 15.0
-_MAX_PROGRESS_TICKS = 240 # 1 hour of 15 s ticks
-_MIN_CLAIM_TTL = 30
-_MAX_CLAIM_TTL = 7 * 86400
-_COLD_START_NOTE = "the first start of an image can take a few minutes"
-_STARTING_MESSAGE = "Starting a cloud sandbox (first start of an image can take a few minutes)"
-
-#: Where the native manager keeps its pool-name cache and GC lock (patched
-#: by tests).
-CUA_DIR = cua_home()
-_CUA_DIR_DEFAULT = CUA_DIR
-
-
-def cua_dir() -> Path:
- """``$CUA_HOME`` now (or the patched ``CUA_DIR``)."""
- return patched_or(CUA_DIR, _CUA_DIR_DEFAULT)
-
-
-Duration = Union[int, float, timedelta]
-
-
-class AutoPoolError(RuntimeError):
- """A managed Fleet pool could not provide a sandbox."""
-
-
-# ── Configuration ────────────────────────────────────────────────────────
-
-
-def _parse_duration(value: str, variable: str) -> int:
- match = re.fullmatch(r"\s*(\d+)\s*([smhd]?)\s*", value.lower())
- if match is None:
- raise ValueError(f"{variable} must be a duration like 900, 90s, 15m, 1h or 7d")
- amount, unit = int(match.group(1)), match.group(2) or "s"
- return amount * {"s": 1, "m": 60, "h": 3600, "d": 86400}[unit]
-
-
-def _seconds(value: Duration, field_name: str) -> int:
- if isinstance(value, timedelta):
- seconds = value.total_seconds()
- elif isinstance(value, bool) or not isinstance(value, (int, float)):
- raise TypeError(f"{field_name} must be seconds (int/float) or a timedelta")
- else:
- seconds = float(value)
- return int(round(seconds))
-
-
-@dataclass(frozen=True)
-class AutoPoolConfig:
- """Tuning for managed pools. Build it with :func:`config`."""
-
- max_pool_size: int = 10
- claim_ttl: int = 15 * 60
- warm: bool = False
- #: Whether ``warm`` was chosen (argument or ``CUA_FLEET_WARM``); unset,
- #: the SDK makes the canonical images warm and others cold.
- warm_set: bool = False
- bind_deadline: int = MIN_BIND_DEADLINE
- pool_ttl: int = 7 * 86400
- idle_gc: int = 30 * 60
- auto_gc: bool = True
-
- @property
- def initial_pool_size(self) -> int:
- return 1 if self.warm else 0
-
- def validate(self) -> "AutoPoolConfig":
- if (
- isinstance(self.max_pool_size, bool)
- or not isinstance(self.max_pool_size, int)
- or self.max_pool_size < 1
- ):
- raise ValueError("max_pool_size must be a positive integer")
- if not _MIN_CLAIM_TTL <= self.claim_ttl <= _MAX_CLAIM_TTL:
- raise ValueError(
- f"claim_ttl must be between {_MIN_CLAIM_TTL} seconds and 7 days "
- f"(got {self.claim_ttl}s); use sb.keep_alive(minutes=...) to hold a "
- "sandbox longer"
- )
- if self.bind_deadline < 1 or self.pool_ttl < 3600 or self.idle_gc < 0:
- raise ValueError("bind_deadline, pool_ttl and idle_gc must be positive")
- return self
-
-
-def config(
- *,
- warm: Optional[bool] = None,
- max_pool_size: Optional[int] = None,
- claim_ttl: Optional[Duration] = None,
- environ: Optional[Mapping[str, str]] = None,
-) -> AutoPoolConfig:
- """Defaults, then ``CUA_FLEET_*`` env overrides, then explicit kwargs."""
- env = os.environ if environ is None else environ
- cfg = AutoPoolConfig()
- if env.get("CUA_FLEET_MAX_POOL_SIZE", "").strip():
- try:
- cfg = replace(cfg, max_pool_size=int(env["CUA_FLEET_MAX_POOL_SIZE"]))
- except ValueError as error:
- raise ValueError("CUA_FLEET_MAX_POOL_SIZE must be an integer") from error
- if env.get("CUA_FLEET_CLAIM_TTL", "").strip():
- cfg = replace(
- cfg, claim_ttl=_parse_duration(env["CUA_FLEET_CLAIM_TTL"], "CUA_FLEET_CLAIM_TTL")
- )
- idle = env.get("CUA_FLEET_POOL_IDLE_GC", "").strip().lower()
- if idle in ("off", "false", "never", "0"):
- cfg = replace(cfg, auto_gc=False)
- elif idle:
- cfg = replace(cfg, idle_gc=_parse_duration(idle, "CUA_FLEET_POOL_IDLE_GC"))
- if env.get("CUA_FLEET_WARM", "").strip():
- cfg = replace(
- cfg,
- warm=env["CUA_FLEET_WARM"].strip().lower() in ("1", "true", "yes"),
- warm_set=True,
- )
- if warm is not None:
- cfg = replace(cfg, warm=bool(warm), warm_set=True)
- if max_pool_size is not None:
- cfg = replace(cfg, max_pool_size=max_pool_size)
- if claim_ttl is not None:
- cfg = replace(cfg, claim_ttl=_seconds(claim_ttl, "claim_ttl"))
- return cfg.validate()
-
-
-# ── Spec key and naming ──────────────────────────────────────────────────
-
-
-@dataclass(frozen=True)
-class PoolSpecKey:
- """Everything that makes two sandboxes interchangeable.
-
- Mirrors ``cua_fleet::autopool::PoolSpecKey`` field for field so both
- implementations hash (and therefore name) a spec identically.
- """
-
- image: str
- runtime: str = "kubevirt"
- efi: bool = False
- cpu: Optional[int] = None
- memory_mb: Optional[int] = None
- services: tuple[tuple[str, int], ...] = (("env", 3211),)
- readiness_tcp_port: Optional[int] = None
- command: Optional[tuple[str, ...]] = None
- env: tuple[tuple[str, str], ...] = ()
-
- def canonical(self) -> bytes:
- """Versioned JSON array with a fixed field order (serde_json compact)."""
- fields: list = [
- "cua-autopool/v1",
- ["image", self.image.strip()],
- ["runtime", self.runtime],
- ["efi", self.efi],
- ["cpu", self.cpu],
- ["memory_mb", self.memory_mb],
- ["services", [[name, port] for name, port in sorted(self.services)]],
- ["readiness_tcp_port", self.readiness_tcp_port],
- ["command", list(self.command) if self.command is not None else None],
- ]
- # Only when set, so specs without env keep their key (and pool).
- if self.env:
- fields.append(["env", [[k, v] for k, v in sorted(self.env)]])
- return json.dumps(fields, separators=(",", ":"), ensure_ascii=False).encode()
-
- def spec_hash(self) -> str:
- return hashlib.sha256(self.canonical()).hexdigest()
-
- @property
- def label(self) -> str:
- return self.spec_hash()[:_SPEC_HASH_LABEL_CHARS]
-
-
-#: sandbox-core's shape defaults, part of the key so both SDKs share pools.
-DEFAULT_CPU = 2
-DEFAULT_MEMORY_MB = 4096
-
-
-def managed_services(image: Image, server_port: Optional[int] = None) -> dict[str, int]:
- """Services a managed pool publishes: always ``env`` (3211), plus
- ``server`` for a declared ``server_port`` and ``port-<n>`` per exposed
- port (sandbox-core's ``all_services`` rule)."""
- services = {"env": SPACESD_PORT}
- if server_port is not None:
- services["server"] = server_port
- for port in image._ports:
- if port not in services.values():
- services[f"port-{port}"] = port
- return services
-
-
-def spec_key(
- image: Image,
- *,
- cpu: Optional[int] = None,
- memory_mb: Optional[int] = None,
- server_port: Optional[int] = None,
- runtime: str = "kubevirt",
-) -> PoolSpecKey:
- FleetCloudTransport._validate_image(image)
- reference = cloud_registry_image(image)
- assert reference is not None
- return PoolSpecKey(
- image=reference,
- runtime=runtime,
- efi=image.os_type == "windows",
- cpu=cpu if cpu is not None else DEFAULT_CPU,
- memory_mb=memory_mb if memory_mb is not None else DEFAULT_MEMORY_MB,
- services=tuple(sorted(managed_services(image, server_port).items())),
- readiness_tcp_port=server_port,
- )
-
-
-def _runtime_name(kind: Any) -> str:
- """``fleet_sdk.RuntimeKind`` -> its serde name (``kubevirt``/``gvisor``)."""
- return str(getattr(kind, "name", kind)).lower()
-
-
-def pool_name_for(tenant: str, spec_hash: str, prefix: str = MANAGED_PREFIX) -> str:
- digest = hashlib.sha256(tenant.encode() + b"\0" + spec_hash.encode()).digest()
- encoded = base64.b32encode(digest).decode().lower().rstrip("=")
- return prefix + encoded[:_NAME_HASH_CHARS]
-
-
-def candidate_names(base: str) -> list[str]:
- return [base] + [f"{base}-{index}" for index in range(2, _MAX_NAME_ATTEMPTS + 1)]
-
-
-def is_managed_pool_name(name: str, prefix: str = MANAGED_PREFIX) -> bool:
- return name.startswith((prefix, MANAGED_PREFIX, LEGACY_EPHEMERAL_PREFIX))
-
-
-# ── Small helpers ────────────────────────────────────────────────────────
-
-
-def _client_factory() -> Any:
- # Resolved at call time so tests (and FakeFleet) patch one seam:
- # cua_sandbox.pool._FleetClient.
- from cua_sandbox import pool
-
- return pool._FleetClient()
-
-
-def _status(error: BaseException) -> Optional[int]:
- status = getattr(error, "status", None)
- return status if isinstance(status, int) else None
-
-
-def _is_access_denied(error: BaseException) -> bool:
- return (bool(_NATIVE_POOL_ACCESS_DENIED) and isinstance(error, _NATIVE_POOL_ACCESS_DENIED)) or (
- isinstance(error, SdkError) and _status(error) == 403
- )
-
-
-def _is_not_found(error: BaseException) -> bool:
- return isinstance(error, LookupError) or _status(error) == 404
-
-
-def _labels(resource: Any) -> dict[str, str]:
- metadata = getattr(resource, "metadata", None)
- return dict(getattr(metadata, "labels", None) or {})
-
-
-def _parse_time(value: Optional[str]) -> Optional[datetime]:
- if not value:
- return None
- try:
- parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
- except ValueError:
- return None
- return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
-
-
-def _now() -> datetime:
- return datetime.now(timezone.utc)
-
-
-def _rfc3339(moment: datetime) -> str:
- return moment.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
-
-
-def _claim_phase(claim: Any) -> Optional[str]:
- status = getattr(claim, "status", None)
- return getattr(status, "phase", None) if status is not None else None
-
-
-def _claim_reason(claim: Any) -> str:
- status = getattr(claim, "status", None)
- for condition in reversed(list(getattr(status, "conditions", None) or [])):
- reason = getattr(condition, "reason", None)
- message = getattr(condition, "message", None)
- if reason or message:
- return ": ".join(part for part in (reason, message) if part)
- return ""
-
-
-# ── Progress ─────────────────────────────────────────────────────────────
-
-
-@dataclass(frozen=True)
-class AcquireProgress:
- """One step of starting a cloud sandbox, passed to ``progress=``
- callbacks.
-
- ``stage`` is ``"provisioning"`` (capacity is being found or created),
- ``"starting"`` (periodic while the sandbox boots) or ``"ready"``.
- ``claim`` is the sandbox id once known; ``pool`` is always ``None``
- (kept for compatibility; see ``provider_details``).
- """
-
- stage: str
- pool: Optional[str]
- message: str
- claim: Optional[str] = None
- elapsed: float = 0.0
-
-
-ProgressCallback = Callable[[AcquireProgress], Any]
-
-
-def _emit(progress: Optional[ProgressCallback], event: AcquireProgress) -> None:
- if progress is None:
- return
- try:
- progress(event)
- except Exception: # noqa: BLE001 - a broken callback must not fail the acquire
- logger.exception("progress callback raised")
-
-
-# ── The managed claim handle ─────────────────────────────────────────────
-
-
-class ManagedClaimHandle(_ClaimHandle):
- """A claim on a managed pool, held by the SDK runtime.
-
- The runtime's heartbeat renews the claim while the handle is held;
- :meth:`detach` stops it (the claim then lives until its shutdown time)
- and :meth:`release` deletes the claim (the pool stays for reuse).
- """
-
- managed = True
-
- def __init__(
- self,
- *,
- namespace: str,
- name: str,
- service: str,
- native: Any,
- claim_ttl: int,
- agent_type: Optional[str] = None,
- ) -> None:
- super().__init__(
- namespace=namespace,
- name=name,
- pool_name=namespace,
- service=service,
- agent_type=agent_type,
- )
- self._native = native
- self.claim_ttl = claim_ttl
-
- @property
- def heartbeat_running(self) -> bool:
- return self._native is not None
-
- def detach(self) -> None:
- """Stop renewing; the claim lives until its current shutdown time."""
- native, self._native = self._native, None
- if native is not None:
- try:
- native.detach()
- except Exception as error: # noqa: BLE001 - the claim still expires by TTL
- logger.debug("detaching Fleet claim %s failed: %s", self.name, error)
-
- async def renew(self, shutdown_time: str) -> None:
- native = self._native
- if native is None:
- await super().renew(shutdown_time)
- return
- until = _parse_time(shutdown_time)
- seconds = max(1, int((until - _now()).total_seconds())) if until else self.claim_ttl
- # The runtime's heartbeat never renews to an earlier time than this.
- await native.keep_alive(seconds)
-
- async def release(self) -> None:
- native, self._native = self._native, None
- if native is None:
- await super().release()
- return
- try:
- await native.delete()
- except Exception as error:
- if not _sdk.is_not_found(error):
- raise
-
- def state_fields(self) -> dict[str, Any]:
- fields: dict[str, Any] = {"managed": True, "claim_ttl": self.claim_ttl}
- if self.agent_type:
- fields["agent_type"] = self.agent_type
- return fields
-
-
-# ── Reports ──────────────────────────────────────────────────────────────
-
-
-@dataclass
-class ManagedPoolInfo:
- name: str
- spec_hash: Optional[str]
- managed: bool
- replicas: Optional[int]
- ready_replicas: Optional[int]
- claims: int
- last_used: Optional[datetime]
- created_at: Optional[str]
-
-
-@dataclass
-class ClaimInfo:
- name: str
- pool: str
- phase: Optional[str]
- managed: bool
- created_at: Optional[str]
-
-
-@dataclass
-class GcReport:
- pools_deleted: list[str] = field(default_factory=list)
- claims_deleted: list[str] = field(default_factory=list)
- namespaces_deleted: list[str] = field(default_factory=list)
- errors: list[str] = field(default_factory=list)
-
-
-# ── Native manager access ────────────────────────────────────────────────
-
-
-def _native_cua() -> Any:
- """The embedded SDK runtime that owns managed claims and heartbeats.
-
- One per process (cached by ``_sdk.runtime``): the SDK's own Tokio runtime
- keeps renewing claims under the sync facade too.
- """
- return _sdk.runtime(state_dir=_sdk._private_state_dir(), fleet=True, pool_home=cua_dir())
-
-
-def _namespace_of(info: Any) -> Optional[str]:
- """The pool namespace from a Fleet sandbox's gateway endpoint."""
- for url in (getattr(info, "endpoints", None) or {}).values():
- _, sep, rest = url.partition("/api/svc/")
- if sep and rest:
- return rest.split("/", 1)[0]
- return None
-
-
-# ── Module API (the adapter surface) ─────────────────────────────────────
-
-
-async def acquire(
- image: Image,
- *,
- name: Optional[str] = None,
- cpu: Optional[int] = None,
- memory_mb: Optional[int] = None,
- server_port: Optional[int] = None,
- service: str = ENV_SERVICE,
- time_to_start: Optional[float] = None,
- cfg: Optional[AutoPoolConfig] = None,
- progress: Optional[ProgressCallback] = None,
- runtime: Optional[str] = None,
- command: Optional[list[str]] = None,
- env: Optional[dict[str, str]] = None,
- services: Optional[dict[str, int]] = None,
- wait_for: Optional[list] = None,
- sidecars: Optional[list] = None,
- hint: Optional[str] = None,
-) -> "Sandbox":
- """Claim a sandbox for ``image`` from this account's managed pool.
-
- ``runtime`` is ``"kubevirt"`` or ``"gvisor"``; unset, it defaults from
- the image kind (``image.kind``, else the image itself: the cua SDK's
- single runtime/image rule). ``hint`` is appended when there are no
- cloud credentials (the cloud came from a user default). ``command``,
- ``env``, ``services`` and ``wait_for`` are part of the pool's template
- (and key); the SDK waits for the probes before returning.
- """
- from cua_sandbox import _placement
- from cua_sandbox.containers import has_build, image_build, sidecars_of
-
- cfg = cfg or config()
- FleetCloudTransport._validate_image(image)
- build = image_build(image)
- if image._secret is not None or build is not None:
- # The native core reads a private image with its secret, and a build's
- # output is a container rootfs: no anonymous pre-resolution here.
- runtime_name = runtime or ("gvisor" if has_build(image) else None)
- else:
- runtime_name = _runtime_name(resolve_fleet_runtime(runtime, image))
- reference = cloud_registry_image(image)
- assert reference is not None
- # Legacy OSWorld adapter: the disk runs the OSWorld Flask server, not
- # cua-spacesd, so the pool publishes it as ``server`` on 5000.
- server_port = default_server_port(image, server_port)
- if server_port is not None and service == ENV_SERVICE:
- # A declared server_port is the image's own daemon: wait for it.
- service = "server"
- native = _sdk.native()
- bind_budget = max(cfg.bind_deadline, int(time_to_start or 0), MIN_BIND_DEADLINE)
- options = native.SandboxCreateOptions(
- on="cloud",
- kind=image.kind,
- runtime=runtime_name,
- image=reference,
- name=name,
- os="windows" if image.os_type == "windows" else "linux",
- cpus=cpu if cpu is not None else DEFAULT_CPU,
- memory_mb=memory_mb if memory_mb is not None else DEFAULT_MEMORY_MB,
- services={
- **{k: v for k, v in managed_services(image, server_port).items() if k != "env"},
- **dict(services or {}),
- },
- ready_timeout_ms=_sdk.millis(bind_budget),
- command=list(command) if command else None,
- env=dict(env or {}),
- wait_for=[p.native() for p in (wait_for or [])],
- cloud=native.CloudOptions(
- # Unset lets the SDK decide: warm for the canonical images.
- warm=cfg.warm if cfg.warm_set else None,
- max_pool_size=cfg.max_pool_size,
- claim_ttl_seconds=cfg.claim_ttl,
- pool=None,
- ),
- sidecars=[c.native() for c in sidecars_of(sidecars)],
- registry_secret=image._secret.native() if image._secret is not None else None,
- build=build,
- )
- loop = asyncio.get_running_loop()
- started = loop.time()
- _emit(progress, AcquireProgress("provisioning", None, _STARTING_MESSAGE))
- if build is not None:
- _emit(
- progress,
- AcquireProgress(
- "provisioning",
- None,
- "building the image's layers in the cloud (an identical image is reused)",
- ),
- )
-
- async def ticker() -> None:
- for _ in range(_MAX_PROGRESS_TICKS):
- await asyncio.sleep(_PROGRESS_TICK)
- elapsed = loop.time() - started
- _emit(
- progress,
- AcquireProgress(
- "starting",
- None,
- f"waiting for the sandbox to start ({elapsed:.0f}s)",
- elapsed=elapsed,
- ),
- )
-
- ticks = asyncio.ensure_future(ticker()) if progress is not None else None
- try:
- handle_native = await _native_cua().sandboxes().create(options)
- except native.CuaError.ProviderNotConfigured as error:
- # No cloud credentials: say so (and how to switch back to local when
- # the cloud came from a default), not the cold-start hint.
- raise ValueError(f"{error}; {hint}" if hint else str(error)) from error
- except (native.CuaError.InvalidPlacement, native.CuaError.InvalidArgument) as error:
- raise _placement.translate(error) from None
- except Exception as error:
- elapsed = loop.time() - started
- advice = (
- f"no cloud sandbox for {reference} after {elapsed:.0f}s ({_COLD_START_NOTE}). "
- f"If this persists, {cfg.max_pool_size} sandboxes of this image may already be "
- "running (cloud=CloudOptions(max_pool_size=...)) or the image may not start. "
- "Pass time_to_start= to wait longer or cloud=CloudOptions(warm=True) to keep one "
- "ready."
- )
- raise AutoPoolError(f"{advice} Details: {error}") from error
- finally:
- if ticks is not None:
- ticks.cancel()
- info = handle_native.info()
- namespace = dict(info.provider_details).get("namespace") or _namespace_of(info)
- if namespace is None:
- handle_native.detach()
- raise AutoPoolError(f"cloud sandbox {info.name} reported no endpoint")
- handle = ManagedClaimHandle(
- namespace=namespace,
- name=info.name,
- service=service,
- native=handle_native,
- claim_ttl=cfg.claim_ttl,
- agent_type=image._agent_type,
- )
- if services or wait_for:
- # The SDK already waited for the probes; the claim is the readiness.
- service = ENV_SERVICE
- try:
- sandbox = await handle.wait(service=service, time_to_start=time_to_start)
- # Services, forwards and public URLs use the handle that holds the
- # claim (and its heartbeat).
- if getattr(sandbox._transport, "_native_fleet_sandbox", "unset") is None:
- sandbox._transport._native_fleet_sandbox = handle_native
- except BaseException:
- try:
- await handle.release()
- except Exception: # noqa: BLE001 - the TTL reaps it
- pass
- raise
- elapsed = loop.time() - started
- _emit(
- progress,
- AcquireProgress(
- "ready",
- None,
- f"sandbox {info.name} ready in {elapsed:.0f}s",
- claim=info.name,
- elapsed=elapsed,
- ),
- )
- return sandbox
-
-
-async def list_claims(cfg: Optional[AutoPoolConfig] = None) -> list[ClaimInfo]:
- """Claims in every pool this account can see (managed and explicit)."""
- client = _client_factory()
- try:
- names = [ns.name for ns in await client.list_namespaces()]
- gate = asyncio.Semaphore(_LIST_CONCURRENCY)
-
- async def claims_in(namespace: str) -> list[ClaimInfo]:
- async with gate:
- try:
- claims = await client.list_claims(namespace)
- except Exception as error: # noqa: BLE001
- if _is_not_found(error) or _is_access_denied(error):
- return []
- raise
- managed_pool = is_managed_pool_name(namespace)
- return [
- ClaimInfo(
- name=claim.metadata.name,
- pool=namespace,
- phase=_claim_phase(claim),
- managed=managed_pool or _labels(claim).get(LABEL_MANAGED_BY) == MANAGED_BY,
- created_at=claim.metadata.creation_timestamp,
- )
- for claim in claims
- ]
-
- results = await asyncio.gather(*(claims_in(name) for name in names))
- return [claim for group in results for claim in group]
- finally:
- await client.close()
-
-
-def _pools_api() -> Any:
- return _native_cua().fleet().pools()
-
-
-async def list_pools(cfg: Optional[AutoPoolConfig] = None) -> list[ManagedPoolInfo]:
- """This account's managed pools (``cua-auto-*`` and legacy ``cua-eph-*``)."""
- return [
- ManagedPoolInfo(
- name=p.name,
- spec_hash=p.spec_hash,
- managed=p.managed,
- replicas=p.replicas,
- ready_replicas=p.ready_replicas,
- claims=p.claims,
- last_used=(
- datetime.fromtimestamp(p.last_used_unix, timezone.utc)
- if p.last_used_unix is not None
- else None
- ),
- created_at=(
- datetime.fromtimestamp(p.created_unix, timezone.utc).isoformat()
- if p.created_unix is not None
- else None
- ),
- )
- for p in await _pools_api().list()
- ]
-
-
-async def gc(
- idle_after: Optional[Duration] = None, cfg: Optional[AutoPoolConfig] = None
-) -> GcReport:
- """Delete idle managed pools and stuck managed claims now."""
- idle = (cfg or config()).idle_gc if idle_after is None else _seconds(idle_after, "idle_after")
- report = await _pools_api().gc(idle)
- return GcReport(
- pools_deleted=list(report.deleted_pools),
- claims_deleted=list(report.deleted_claims),
- namespaces_deleted=list(report.deleted_namespaces),
- errors=list(report.errors),
- )
-
-
-async def gc_pools(names: list[str], idle_after: Duration = 0) -> GcReport:
- """Delete the named managed pools once they have no claims and have been
- idle for ``idle_after`` (default: now). Pools with live claims are kept.
- Tests use this to remove exactly the pools they created."""
- report = await _pools_api().gc_pools(list(names), _seconds(idle_after, "idle_after"))
- return GcReport(
- pools_deleted=list(report.deleted_pools),
- claims_deleted=list(report.deleted_claims),
- namespaces_deleted=list(report.deleted_namespaces),
- errors=list(report.errors),
- )
-
-
-def stop_all_heartbeats() -> None:
- """Kept for compatibility: heartbeats live in the SDK runtime and stop
- with each sandbox's ``close``/``disconnect``."""
diff --git a/libs/python/cua-sandbox/cua_sandbox/_config.py b/libs/python/cua-sandbox/cua_sandbox/_config.py
index 04949d7702..780a0e78f8 100644
--- a/libs/python/cua-sandbox/cua_sandbox/_config.py
+++ b/libs/python/cua-sandbox/cua_sandbox/_config.py
@@ -1,25 +1,19 @@
-"""Global configuration for cloud sandbox provisioning."""
+"""Process-wide configuration for the legacy API-key helpers."""
from __future__ import annotations
import os
+import warnings
from dataclasses import dataclass
from typing import Optional
_DEFAULT_BASE_URL = "https://api.cua.ai"
-_DEFAULT_FLEET_BASE_URL = "https://run.cua.ai"
-_DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"
@dataclass
class _Config:
api_key: Optional[str] = None
base_url: str = _DEFAULT_BASE_URL
- fleet_base_url: str = _DEFAULT_FLEET_BASE_URL
- token_url: str = _DEFAULT_TOKEN_URL
- client_id: Optional[str] = None
- client_secret: Optional[str] = None
- fleet_token: Optional[str] = None
_global_config = _Config()
@@ -35,25 +29,35 @@ def configure(
client_secret: Optional[str] = None,
fleet_token: Optional[str] = None,
) -> None:
- """Set global configuration for cloud sandboxes.
+ """Set global configuration.
- API-key cloud operations use ``base_url``. Fleet uses ``fleet_base_url`` and
- OAuth client credentials.
+ ``api_key`` and ``base_url`` apply to the legacy ``login()`` and
+ ``whoami()`` helpers. ``fleet_base_url``, ``token_url``, ``client_id``,
+ ``client_secret`` and ``fleet_token`` configured Cua Cloud, which has
+ ended: they are accepted so existing calls keep working, and ignored.
"""
+ retired = [
+ name
+ for name, value in (
+ ("fleet_base_url", fleet_base_url),
+ ("token_url", token_url),
+ ("client_id", client_id),
+ ("client_secret", client_secret),
+ ("fleet_token", fleet_token),
+ )
+ if value is not None
+ ]
+ if retired:
+ warnings.warn(
+ f"configure({', '.join(f'{name}=' for name in retired)}) has no effect: "
+ "Cua Cloud has ended",
+ DeprecationWarning,
+ stacklevel=2,
+ )
if api_key is not None:
_global_config.api_key = api_key
if base_url is not None:
_global_config.base_url = base_url
- if fleet_base_url is not None:
- _global_config.fleet_base_url = fleet_base_url
- if token_url is not None:
- _global_config.token_url = token_url
- if client_id is not None:
- _global_config.client_id = client_id
- if client_secret is not None:
- _global_config.client_secret = client_secret
- if fleet_token is not None:
- _global_config.fleet_token = fleet_token
def get_api_key(override: Optional[str] = None) -> Optional[str]:
@@ -72,100 +76,6 @@ def get_base_url() -> str:
return os.environ.get("CUA_BASE_URL") or _global_config.base_url
-def get_fleet_base_url() -> str:
- """Return the Fleet API endpoint without changing legacy VM API routing."""
- return os.environ.get("CUA_FLEET_BASE_URL") or _global_config.fleet_base_url
-
-
-def get_fleet_token() -> Optional[str]:
- """Resolve a configured or environment-supplied Fleet workload token."""
- for token in (_global_config.fleet_token, os.environ.get("FLEETS_TOKEN")):
- if token:
- token = token.strip()
- if token:
- return token
- return None
-
-
-def has_fleet_auth() -> bool:
- """Return whether static Fleet token or client credential auth is available."""
- return bool(get_fleet_token() or (get_client_id() and get_client_secret()))
-
-
-#: The one "no Fleet credentials" message (``cua_fleet::MISSING_CREDENTIALS``).
-FLEET_CREDENTIALS_MISSING = (
- "Fleet credentials missing: run `cua auth login` or set "
- "CUA_CLIENT_ID/CUA_CLIENT_SECRET, or pass local=True"
-)
-
-
-def has_fleet_session() -> bool:
- """Whether a ``cua auth login`` session is stored (no network access).
-
- Fleet uses it when no token or client credentials are configured. Set
- ``CUA_FLEET_SESSION=0`` to ignore it.
- """
- if os.environ.get("CUA_FLEET_SESSION", "").strip().lower() in ("0", "false", "off", "no"):
- return False
- try:
- from cua_sandbox._sdk import sdk
-
- return bool(sdk().embedded(fleet_from_env=False).auth().status().logged_in)
- except Exception: # noqa: BLE001 - no SDK or unreadable store: no session
- return False
-
-
-def may_have_fleet_session() -> bool:
- """Whether a ``cua auth login`` session may be stored, decided WITHOUT
- reading the OS credential vault: the SDK's non-secret session marker
- (``~/.cua/session.json``, written at login and on the first read of an
- older session) or the file store's file. Implicit calls (the default
- ``Sandbox.list()``) check this first; explicit cloud calls read the
- session (:func:`has_fleet_session`), which writes the marker."""
- try:
- from cua_sandbox._sdk import native
-
- return bool(native().may_have_fleet_session())
- except Exception: # noqa: BLE001 - no SDK: no session to find
- return False
-
-
-def fleet_auth_source(*, read_session: bool = True) -> Optional[str]:
- """Where Fleet credentials come from, in the order the SDK uses them.
-
- ``"FLEETS_TOKEN"`` (a workload token), ``"client credentials"``
- (``CUA_CLIENT_ID``/``CUA_CLIENT_SECRET``), ``"cua auth login session"``
- (the stored session, refreshed by the SDK while it is used) or ``None``
- when nothing is configured. A stored session is only looked up when
- neither of the first two is set. ``read_session=False`` decides that from
- the non-secret session marker alone, without reading the OS credential
- vault (for dashboards and other implicit checks).
- """
- if get_fleet_token():
- return "FLEETS_TOKEN"
- if get_client_id() and get_client_secret():
- return "client credentials"
- found = has_fleet_session() if read_session else may_have_fleet_session()
- return "cua auth login session" if found else None
-
-
-def has_fleet_access() -> bool:
- """Fleet credentials, or a ``cua auth login`` session to fall back to."""
- return has_fleet_auth() or has_fleet_session()
-
-
-def get_token_url() -> str:
- return os.environ.get("CUA_TOKEN_URL") or _global_config.token_url
-
-
-def get_client_id(override: Optional[str] = None) -> Optional[str]:
- return override or _global_config.client_id or os.environ.get("CUA_CLIENT_ID")
-
-
-def get_client_secret(override: Optional[str] = None) -> Optional[str]:
- return override or _global_config.client_secret or os.environ.get("CUA_CLIENT_SECRET")
-
-
def _read_credentials_key() -> Optional[str]:
"""Read a legacy API key from ``$CUA_HOME/credentials`` when present."""
from cua_sandbox._paths import cua_home
diff --git a/libs/python/cua-sandbox/cua_sandbox/_placement.py b/libs/python/cua-sandbox/cua_sandbox/_placement.py
index b24e6ade5e..5f46c46c38 100644
--- a/libs/python/cua-sandbox/cua_sandbox/_placement.py
+++ b/libs/python/cua-sandbox/cua_sandbox/_placement.py
@@ -2,18 +2,19 @@
Three independent axes, the same on every cua surface:
-* ``on``: ``"local"`` or ``"cloud"`` (``local=True``/``False`` is the same
- switch). Other locations (``direct:<addr>``, registered providers) are
- existing machines or plugins, not something cua-sandbox creates.
+* ``on``: ``"local"`` (``local=True`` is the same switch). Cua Cloud has
+ ended: ``"cloud"`` and ``local=False`` raise
+ :class:`~cua_sandbox._ended.CloudEnded`. Other locations (``direct:<addr>``,
+ registered providers) are existing machines or plugins, not something
+ cua-sandbox creates.
* ``kind``: ``"auto"``, ``"container"`` or ``"vm"``.
* ``runtime``: ``"auto"`` or an engine the location offers for the kind:
- locally ``gvisor``/``runc`` (containers) and ``qemu``/``lume`` (VMs); in the
- cloud ``gvisor`` (containers) and ``kubevirt`` (VMs). A legacy
+ ``gvisor``/``runc`` (containers) and ``qemu``/``lume`` (VMs). A legacy
:class:`~cua_sandbox.runtime.Runtime` object still picks a local adapter.
Unset values come from the user's defaults, in this order: environment
(``CUA_DEFAULT_ON``, ``CUA_DEFAULT_KIND``, ``CUA_DEFAULT_RUNTIME``), then
-``$CUA_HOME/config.toml`` (``cua config set default.on cloud``), then the
+``$CUA_HOME/config.toml`` (``cua config set default.on local``), then the
built-in ``local``/``auto``/``auto``. The native cua SDK owns both the
settings and the validation; this module only asks it.
"""
@@ -22,7 +23,6 @@ from __future__ import annotations
import logging
import os
-import warnings
from dataclasses import dataclass
from typing import Any, Optional
@@ -123,7 +123,7 @@ def _text(value: Any, what: str) -> Optional[str]:
def _on_word(on: Any) -> str:
if not isinstance(on, str) or not on.strip():
- raise InvalidArgument(f"on= takes 'local' or 'cloud', got {on!r}")
+ raise InvalidArgument(f"on= takes 'local', got {on!r}")
text = on.strip()
head, sep, rest = text.partition(":")
return head.lower() + sep + rest if sep else text.lower()
@@ -150,18 +150,6 @@ class Placement:
def local(self) -> bool:
return self.on == "local"
- def cloud_default_hint(self) -> Optional[str]:
- """What to say when the cloud came from a user default and there are
- no cloud credentials."""
- if self.on != "cloud" or self.on_source not in ("env", "config"):
- return None
- origin = self.on_origin or ("CUA_DEFAULT_ON" if self.on_source == "env" else "config")
- tail = " and unset CUA_DEFAULT_ON" if self.on_source == "env" else ""
- return (
- f"the default location is cloud ({origin}); run `cua auth login`, or switch "
- f"back with `cua config set default.on local`{tail}"
- )
-
def _notice() -> None:
global _default_notice_shown
@@ -185,16 +173,15 @@ def resolve(
cloud: Any = None,
cloud_only: Optional[list[str]] = None,
image_kind: Optional[str] = None,
- stacklevel: int = 4,
) -> Placement:
"""Where, what kind and which engine (see the module docstring).
Location: ``on=`` or ``local=`` (contradicting each other is
- :class:`InvalidArgument`); else ``cloud=`` implies the cloud; else a
- cloud-only argument keeps the cloud with a ``DeprecationWarning``; else a
- legacy ``Runtime`` object means local; else ``default.on``. The one-time
- "defaulting to a local sandbox" notice appears only when that is the
- built-in default.
+ :class:`InvalidArgument`); else ``cloud=`` or a cloud-only argument means
+ the cloud; else a legacy ``Runtime`` object means local; else
+ ``default.on``. The cloud is gone: it raises :class:`CloudEnded`. The
+ one-time "defaulting to a local sandbox" notice appears only when
+ ``default.on`` is the built-in default.
Kind: ``kind=`` > the image's ``kind`` > the engine's kind >
``default.kind`` (skipped when it does not fit) > auto.
@@ -226,13 +213,6 @@ def resolve(
elif cloud is not None:
where, source, origin = "cloud", "implied", ""
elif cloud_only:
- warnings.warn(
- f"{', '.join(cloud_only)} only appl{'ies' if len(cloud_only) == 1 else 'y'} in the "
- "cloud, so this sandbox runs in the cloud; sandboxes are local by default now. "
- "Pass local=False to keep this behaviour without the warning",
- DeprecationWarning,
- stacklevel=stacklevel,
- )
where, source, origin = "cloud", "implied", ""
elif legacy is not None:
# A Runtime object is a local adapter (Docker, QEMU, Lume, Tart, ...).
@@ -264,7 +244,7 @@ def resolve(
check(where, explicit_kind, engine)
if where not in LOCATIONS:
raise Unsupported(
- f"on={where!r}: cua-sandbox creates local and cloud sandboxes. Connect to an "
+ f"on={where!r}: cua-sandbox creates local sandboxes. Connect to an "
"existing machine with Sandbox.connect(url=...), or use the cua SDK for other "
"providers"
)
diff --git a/libs/python/cua-sandbox/cua_sandbox/_sdk.py b/libs/python/cua-sandbox/cua_sandbox/_sdk.py
index e73577f20a..34ce949096 100644
--- a/libs/python/cua-sandbox/cua_sandbox/_sdk.py
+++ b/libs/python/cua-sandbox/cua_sandbox/_sdk.py
@@ -1,7 +1,7 @@
"""Bridge to the ``cua`` SDK (Rust core, UniFFI binding).
-cua-sandbox is a thin wrapper: spacesd access, Fleet sandbox attachment
-and the Docker/QEMU/Lume runtimes all go through ``cua`` (``libs/cua``).
+cua-sandbox is a thin wrapper: spacesd access and the Docker/QEMU/Lume
+runtimes all go through ``cua`` (``libs/cua``).
This module keeps that dependency in one place and imports it lazily, so
``import cua_sandbox`` stays cheap and the hermetic tests that never touch a
real sandbox do not load the native library.
@@ -9,17 +9,15 @@ real sandbox do not load the native library.
from __future__ import annotations
-import json
import os
import tempfile
import threading
-from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
#: The port cua-spacesd listens on inside every sandbox image.
SPACESD_PORT = 3211
-#: The Fleet service name the spacesd is published under.
+#: The service name cua-spacesd is published under.
ENV_SERVICE = "env"
@@ -95,86 +93,31 @@ def is_not_found(error: BaseException) -> bool:
return isinstance(error, cls)
-def fleet_settings() -> Any:
- """``cua.FleetSettings`` built from cua-sandbox's configuration."""
- from cua_sandbox._config import (
- get_client_id,
- get_client_secret,
- get_fleet_base_url,
- get_fleet_token,
- get_token_url,
- )
-
- token = get_fleet_token()
- return native().FleetSettings(
- base_url=get_fleet_base_url().rstrip("/"),
- token_url=get_token_url(),
- client_id=None if token else get_client_id(),
- client_secret=None if token else get_client_secret(),
- token=token,
- )
-
-
-_RUNTIMES: dict[tuple, Any] = {}
+_RUNTIMES: dict[Optional[str], Any] = {}
_RUNTIMES_LOCK = threading.Lock()
_PRIVATE_STATE_DIR: Optional[Path] = None
-def runtime(
- *,
- state_dir: Optional[os.PathLike | str] = None,
- fleet: bool = False,
- pool_home: Optional[os.PathLike | str] = None,
-) -> Any:
+def runtime(*, state_dir: Optional[os.PathLike | str] = None) -> Any:
"""An embedded ``cua.Cua`` runtime.
- One runtime per (state dir, Fleet configuration) is cached for the life of
- the process: the runtime owns port forwards, connection pools and the
- managed Fleet claims' heartbeats, and creating one does no I/O.
- ``pool_home`` is where managed Fleet pools keep their name cache and GC
- lock (default ``~/.cua``).
+ One runtime per state dir is cached for the life of the process: the
+ runtime owns port forwards and connection pools, and creating one does no
+ I/O.
"""
- settings = fleet_settings() if fleet else None
- key = (
- str(state_dir) if state_dir is not None else None,
- str(pool_home) if pool_home is not None else None,
- (
- None
- if settings is None
- else (
- settings.base_url,
- settings.token_url,
- settings.client_id,
- settings.client_secret,
- settings.token,
- )
- ),
- )
+ key = str(state_dir) if state_dir is not None else None
with _RUNTIMES_LOCK:
existing = _RUNTIMES.get(key)
if existing is not None:
return existing
created = sdk().embedded(
state_dir=None if state_dir is None else str(state_dir),
- fleet=settings,
fleet_from_env=False,
- # No token or client credentials: the `cua auth login` session.
- fleet_from_session=fleet and _session_allowed(),
- fleet_pool_home=None if pool_home is None else str(pool_home),
)
_RUNTIMES[key] = created
return created
-def _session_allowed() -> bool:
- return os.environ.get("CUA_FLEET_SESSION", "").strip().lower() not in (
- "0",
- "false",
- "off",
- "no",
- )
-
-
def local_runtime() -> Any:
"""The runtime local sandboxes use; state lives beside cua-sandbox's own."""
from cua_sandbox import sandbox_state
@@ -183,12 +126,11 @@ def local_runtime() -> Any:
def _private_state_dir() -> Path:
- """A private SDK state directory for Fleet attachments and direct URLs.
+ """A private SDK state directory for direct URLs.
The Python layer keeps the user-visible sandbox records in
- ``$CUA_HOME/sandboxes``; the SDK only needs transient records to attach to a
- claim or remember a URL, so it gets its own directory and never rewrites
- the user's files.
+ ``$CUA_HOME/sandboxes``; the SDK only needs transient records to remember
+ a URL, so it gets its own directory and never rewrites the user's files.
"""
global _PRIVATE_STATE_DIR
if _PRIVATE_STATE_DIR is None:
@@ -196,52 +138,6 @@ def _private_state_dir() -> Path:
return _PRIVATE_STATE_DIR
-async def fleet_sandbox(
- namespace: str,
- claim: str,
- env_token: Optional[str] = None,
- *,
- image_info: Any = None,
-) -> Any:
- """A ``cua.Sandbox`` for a bound Fleet claim (pool name == namespace).
- ``env_token`` is the claim's per-claim env token, when it has one;
- ``image_info`` (a ``cua_sandbox.ImageInfo``) what its ``image_info()``
- reports."""
- state_dir = _private_state_dir()
- record = {
- "name": claim,
- "runtime_type": "fleet",
- "pool_name": namespace,
- "status": "running",
- "created_at": datetime.now(timezone.utc).isoformat(),
- }
- if env_token:
- record["env_token"] = env_token
- if image_info is not None:
- import dataclasses
-
- record["image_info"] = dataclasses.asdict(image_info)
- path = state_dir / f"{claim}.json"
- path.write_text(json.dumps(record))
- if env_token:
- path.chmod(0o600)
- return await runtime(state_dir=state_dir, fleet=True).sandboxes().connect(claim)
-
-
-async def pool_image_info(pool: str) -> Any:
- """The SDK's ``ImageInfo`` for named Fleet pool ``pool``'s template image
- (``Fleet.pool_image_info``: pinned, cached per pool; the reference without
- a digest when its registry cannot be read), or ``None``. Never raises."""
- try:
- fleet = runtime(state_dir=_private_state_dir(), fleet=True).fleet()
- return await fleet.pool_image_info(pool)
- except Exception as error: # noqa: BLE001 - informational; never fail a claim
- import logging
-
- logging.getLogger(__name__).debug("image of pool %s not read: %s", pool, error)
- return None
-
-
async def connect_url(url: str, token: Optional[str] = None, name: Optional[str] = None) -> Any:
"""A direct ``cua.Sandbox`` for a spacesd URL (nothing is probed).
diff --git a/libs/python/cua-sandbox/cua_sandbox/builder/build.py b/libs/python/cua-sandbox/cua_sandbox/builder/build.py
index 169b4d4330..cfc42693dc 100644
--- a/libs/python/cua-sandbox/cua_sandbox/builder/build.py
+++ b/libs/python/cua-sandbox/cua_sandbox/builder/build.py
@@ -423,9 +423,9 @@ async def resolve_backing_disk(image: Image) -> Path:
"""Resolve the disk a local session overlays, preferring the registry containerDisk.
Built-in images (and explicit ``Image.from_registry(...)`` refs) map to a
- KubeVirt containerDisk in the registry — the very image Fleet cloud boots. Pulling
- it keeps local QEMU runs on the same disk as the cloud instead of a separately
- built base. Images with no registry counterpart fall back to the local base build.
+ KubeVirt containerDisk in the registry. Pulling it keeps local QEMU runs on
+ the published disk instead of a separately built base. Images with no
+ registry counterpart fall back to the local base build.
"""
from cua_sandbox.image import cloud_registry_image
@@ -456,8 +456,8 @@ async def create_session_disk(
"""Create a session overlay for a sandbox run.
If the image has layers and a cached user image exists, overlay on that.
- Otherwise overlay on the registry containerDisk (the same disk Fleet cloud
- boots) or on a locally built base image. If the image carries a direct disk
+ Otherwise overlay on the registry containerDisk or on a locally built base
+ image. If the image carries a direct disk
path and no layers, that disk is returned as-is (no overlay).
Returns the disk path to boot.
diff --git a/libs/python/cua-sandbox/cua_sandbox/image.py b/libs/python/cua-sandbox/cua_sandbox/image.py
index 4bcc6209b0..3f6e419068 100644
--- a/libs/python/cua-sandbox/cua_sandbox/image.py
+++ b/libs/python/cua-sandbox/cua_sandbox/image.py
@@ -269,9 +269,9 @@ class Image:
def windows(cls, version: str = "2022", kind: str = "vm", tier: Optional[str] = None) -> Image:
"""Windows: the canonical ``ghcr.io/trycua/windows:2022`` containerDisk.
- Other versions, including ``"11"``, have no canonical image: on Fleet
- they are unsupported, and locally they are installed from a downloaded
- evaluation ISO. ``tier="slim"`` names ``2022-slim`` once published.
+ Other versions, including ``"11"``, have no canonical image: they are
+ installed from a downloaded evaluation ISO. ``tier="slim"`` names
+ ``2022-slim`` once published.
"""
ref = _tier_ref("windows", version, tier)
return cls(os_type="windows", distro="windows", version=version, kind=kind, _registry=ref)
@@ -320,8 +320,8 @@ class Image:
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.
+ server on port 5000 instead of the computer-server on 8000, for local
+ QEMU.
"""
return cls(
os_type=os_type,
@@ -729,7 +729,7 @@ class Image:
def cloud_registry_image(image: Image) -> Optional[str]:
- """The registry reference an image runs from, local or on Fleet.
+ """The registry reference an image runs from.
An explicit ``Image.from_registry(...)`` reference always wins; the
built-in descriptors (``Image.linux()``, ``Image.windows()`` for 2022,
diff --git a/libs/python/cua-sandbox/cua_sandbox/interfaces/_driver_mcp.py b/libs/python/cua-sandbox/cua_sandbox/interfaces/_driver_mcp.py
index 09547d07e0..051e1ed3ed 100644
--- a/libs/python/cua-sandbox/cua_sandbox/interfaces/_driver_mcp.py
+++ b/libs/python/cua-sandbox/cua_sandbox/interfaces/_driver_mcp.py
@@ -1,4 +1,4 @@
-"""Fleet byte transport and ownership adapter for the shared Rust MCP client."""
+"""Byte transport and ownership adapter for the shared Rust MCP client."""
from __future__ import annotations
@@ -8,7 +8,7 @@ from typing import Any
logger = logging.getLogger(__name__)
-_FLEET_DRIVER_MAX_RESPONSE_BYTES = 16 * 1024 * 1024
+_DRIVER_MAX_RESPONSE_BYTES = 16 * 1024 * 1024
def shared_channel(sdk: Any, transport: Any, service: str, principal: str) -> Any:
@@ -39,10 +39,10 @@ def shared_channel(sdk: Any, transport: Any, service: str, principal: str) -> An
body=request.body,
headers=[(header.name, header.value) for header in request.headers],
timeout=request.timeout_ms / 1000,
- max_response_bytes=_FLEET_DRIVER_MAX_RESPONSE_BYTES,
+ max_response_bytes=_DRIVER_MAX_RESPONSE_BYTES,
)
- if len(response.content) > _FLEET_DRIVER_MAX_RESPONSE_BYTES:
- raise RuntimeError("Fleet Driver response exceeds the configured size limit")
+ if len(response.content) > _DRIVER_MAX_RESPONSE_BYTES:
+ raise RuntimeError("Driver response exceeds the configured size limit")
return sdk.DriverServiceResponse(
status=response.status_code,
headers=[
@@ -53,7 +53,7 @@ def shared_channel(sdk: Any, transport: Any, service: str, principal: str) -> An
)
except Exception:
raise sdk.DriverServiceTransportError.Failed(
- "Fleet Driver service transport failed; completion is unknown"
+ "Driver service transport failed; completion is unknown"
) from None
class Connection:
diff --git a/libs/python/cua-sandbox/cua_sandbox/interfaces/driver.py b/libs/python/cua-sandbox/cua_sandbox/interfaces/driver.py
index 5cf503a7e2..413e42a4e3 100644
--- a/libs/python/cua-sandbox/cua_sandbox/interfaces/driver.py
+++ b/libs/python/cua-sandbox/cua_sandbox/interfaces/driver.py
@@ -1,39 +1,28 @@
"""Optional canonical Cua Driver connections for a sandbox.
``sb.driver.connect()`` yields the generated, typed ``cua_driver.CuaDriver``
-for the guest's desktop. Two carriers, no fallback between them:
-
-* **cua-spacesd** (the default for every sandbox the cua SDK drives): the
- typed-envelope MCP extension on the spacesd's ``/mcp`` route, reached
- through the cua SDK's env client (``SpacesdClient.http``) with the sandbox's own
- endpoint and credentials, so Fleet, direct and local sandboxes all work.
-* **Fleet named services** (images that publish their own Driver receiver):
- ``service="driver"`` (private envelope HTTP) or ``service="mcp",
- transport="mcp"``, through the Fleet gateway.
+for the guest's desktop. It rides cua-spacesd, the default for every sandbox
+the cua SDK drives: the typed-envelope MCP extension on the spacesd's ``/mcp``
+route, reached through the cua SDK's env client (``SpacesdClient.http``) with
+the sandbox's own endpoint and credentials, so direct and local sandboxes both
+work.
"""
from __future__ import annotations
import asyncio
import importlib
-import json
import logging
-import re
-import time
import uuid
from contextlib import asynccontextmanager
from typing import TYPE_CHECKING, Any, AsyncIterator, Literal
from cua_sandbox._sdk import ENV_SERVICE
from cua_sandbox.transport.env import EnvTransport
-from cua_sandbox.transport.fleet import FleetTransport
if TYPE_CHECKING:
from cua_driver import CuaDriver
-_REQUEST_LIMIT = 1024 * 1024
-_RESPONSE_LIMIT = 16 * 1024 * 1024
-_TOKEN = re.compile(r"[A-Za-z0-9_-]{1,256}\Z")
_CLEANUP_TIMEOUT = 2.0
logger = logging.getLogger(__name__)
@@ -84,12 +73,12 @@ class Driver:
Use typed inputs with ``session=None`` where optional. For required session
fields, obtain the bound name with ``sandbox.driver.session_name(driver)``. Creating or
rebinding trusted sessions is unsupported. Remote cleanup is best effort
- with a bounded timeout; failures warn and do not block claim release.
+ with a bounded timeout; failures warn and do not block the sandbox's release.
"""
def __init__(self, transport: Any):
self._transport = transport
- # Identity belongs to this bound Fleet client lifecycle, never guest input.
+ # Identity belongs to this sandbox connection, never guest input.
self._principal = uuid.uuid4().hex
self._lock = asyncio.Lock()
self._connections: dict[Any, Any] = {}
@@ -125,13 +114,11 @@ class Driver:
) -> AsyncIterator[CuaDriver]:
"""Yield the canonical Driver; the receiver must support typed envelopes.
- With no arguments this uses the image's Fleet ``driver`` service when
- it publishes one (the private envelope HTTP carrier), and otherwise
- cua-spacesd's ``/mcp`` (``service="env"``, ``transport="mcp"``)
- through the cua SDK. ``service="mcp", transport="mcp"`` selects a
- Fleet named MCP service instead. MCP selection verifies the
- ``ai.cua.driver.envelopes`` extension before opening a receiver. No
- fallback occurs.
+ This uses cua-spacesd's ``/mcp`` (``service="env"``,
+ ``transport="mcp"``) through the cua SDK, and verifies the
+ ``ai.cua.driver.envelopes`` extension before opening a receiver.
+ Named Driver services were a Cua Cloud feature: any other ``service``
+ or ``transport="envelope"`` raises :class:`DriverConnectionError`.
"""
self._check_loop()
if transport not in (None, "envelope", "mcp"):
@@ -143,27 +130,11 @@ class Driver:
raise DriverConnectionError("Sandbox Driver accessor is disconnected")
if not self._transport._connected:
raise DriverConnectionError("Sandbox transport is disconnected")
- if service == ENV_SERVICE and transport == "mcp":
- carrier: Any = _EnvMcpCarrier(self._transport)
- if isinstance(self._transport, FleetTransport) and (
- ENV_SERVICE not in self._transport._bound.services
- ):
- raise DriverConnectionError(
- "Fleet sandbox does not expose the requested Driver service"
- )
- else:
- carrier = self._transport
- if service not in self._transport._bound.services:
- raise DriverConnectionError(
- "Fleet sandbox does not expose the requested Driver service"
- )
+ carrier = _EnvMcpCarrier(self._transport)
sdk = _sdk()
- if transport == "mcp":
- from cua_sandbox.interfaces._driver_mcp import shared_channel
+ from cua_sandbox.interfaces._driver_mcp import shared_channel
- channel = shared_channel(sdk, carrier, service, self._principal)
- else:
- channel = _channel(sdk, carrier, service, self._principal)
+ channel = shared_channel(sdk, carrier, service, self._principal)
async def open_channel():
try:
@@ -182,9 +153,7 @@ class Driver:
async with self._lock:
if self._closed or channel.closed:
raise DriverConnectionError("Sandbox Driver accessor is disconnected")
- driver = (
- channel.driver() if transport == "mcp" else sdk.connect_remote_channel(channel)
- )
+ driver = channel.driver()
self._connections[channel] = driver
yield driver
finally:
@@ -193,26 +162,16 @@ class Driver:
def _resolve(
self, service: str | None, transport: str | None
) -> tuple[str, Literal["envelope", "mcp"]]:
- """Pick the carrier. Only Fleet and cua-spacesd sandboxes have one."""
- sandbox_transport = self._transport
- if not isinstance(sandbox_transport, (FleetTransport, EnvTransport)):
+ """Pick the carrier. Only cua-spacesd sandboxes have one."""
+ if not isinstance(self._transport, EnvTransport):
+ raise DriverConnectionError("Typed Driver requires a cua-spacesd sandbox transport")
+ if transport == "envelope":
+ raise DriverConnectionError("cua-spacesd carries the typed Driver over MCP only")
+ if service not in (None, ENV_SERVICE):
raise DriverConnectionError(
- "Typed Driver requires a Fleet or cua-spacesd sandbox transport"
+ "Named Driver services are not available; cua-spacesd carries the typed Driver"
)
- is_fleet = isinstance(sandbox_transport, FleetTransport)
- if service is None:
- if transport == "envelope" or (
- transport is None and is_fleet and "driver" in sandbox_transport._bound.services
- ):
- return "driver", "envelope"
- return ENV_SERVICE, "mcp"
- if service == ENV_SERVICE:
- if transport == "envelope":
- raise DriverConnectionError("cua-spacesd carries the typed Driver over MCP only")
- return service, "mcp"
- if not is_fleet:
- raise DriverConnectionError("Named Driver services require a Fleet transport")
- return service, transport or "envelope"
+ return ENV_SERVICE, "mcp"
async def _close_connection(self, channel: Any) -> None:
self._check_loop()
@@ -259,230 +218,12 @@ class Driver:
)
-def _channel(sdk: Any, transport: FleetTransport, service: str, principal: str) -> Any:
- class Channel(sdk.ForeignDriverEnvelopeChannel):
- def __init__(self):
- self.connection_id = None
- self.generation = None
- self.public_session = None
- self.capabilities = None
- self.closed = False
- self.cleanup_confirmed = False
- self._close_task = None
- self.cancelled: set[str] = set()
- self._exchanges: dict[str, asyncio.Task] = {}
-
- def fail(self, reason: str):
- return sdk.ForeignDriverChannelError.Failed(reason)
-
- async def request(self, method: str, suffix: str = "", body: Any = None, *, timeout=None):
- path = "/v1/connections"
- headers = None
- if self.connection_id is not None:
- path += "/" + self.connection_id + suffix
- headers = {"X-Cua-Driver-Generation": self.generation}
- try:
- response = await transport.request_service(
- service,
- method=method,
- path=path,
- json_body=body,
- headers=headers,
- **({"timeout": timeout} if timeout is not None else {}),
- )
- except Exception as error:
- if getattr(error, "status", None) in (401, 403):
- raise self.fail("Driver service authorization denied") from None
- raise self.fail("Driver service transport failed; completion is unknown") from None
- status = response.status_code
- if status in (401, 403):
- raise self.fail("Driver service authorization denied")
- if status in (404, 409):
- reason = (
- "Driver connection is stale"
- if self.connection_id
- else "Driver service unavailable"
- )
- if self.connection_id:
- self.closed = True
- raise self.fail(reason)
- if status in (400, 405, 415, 422, 426):
- raise self.fail("Driver service protocol is incompatible")
- if not 200 <= status < 300:
- raise self.fail("Driver service request failed; completion is unknown")
- if len(response.content) > _RESPONSE_LIMIT:
- raise self.fail("Driver service response exceeds the size limit")
- return response
-
- async def open(self):
- response = await self.request("POST", body={})
- try:
- data = response.json()
- connection_id, generation = data["connection_id"], data["generation"]
- if not all(
- isinstance(v, str) and _TOKEN.fullmatch(v) for v in (connection_id, generation)
- ):
- raise ValueError
- self.connection_id, self.generation = connection_id, generation
- caps = data["capabilities"]
- minimum, maximum = (
- caps["minimum_envelope_version"],
- caps["maximum_envelope_version"],
- )
- if (
- type(minimum) is not int
- or type(maximum) is not int
- or not 0 <= minimum <= 1 <= maximum <= 4294967295
- or caps["supports_cancellation"] is not True
- ):
- raise ValueError
- if not isinstance(data["public_session"], str) or not data["public_session"]:
- raise ValueError
- self.public_session = data["public_session"]
- self.capabilities = sdk.ForeignDriverChannelCapabilities(
- minimum_envelope_version=minimum,
- maximum_envelope_version=maximum,
- supports_cancellation=True,
- )
- except (ValueError, TypeError, KeyError):
- raise self.fail("Driver service negotiation is malformed or incompatible") from None
-
- def identity(self):
- return sdk.ForeignDriverChannelIdentity(
- authenticated_principal=principal, connection_generation=self.generation
- )
-
- async def negotiate(self):
- if self.closed:
- raise self.fail("Driver connection is closed")
- return self.capabilities
-
- async def bind_session(self, options):
- raise self.fail(
- "Fleet Driver connections use a host-bound session; rebinding is unsupported"
- )
-
- async def exchange(self, request):
- if self.closed or request.request_id in self.cancelled:
- raise self.fail("Driver connection is closed or request was cancelled")
- try:
- deadline = request.deadline_unix_ms
- if type(deadline) is not int or deadline < 0:
- raise ValueError
- body = {
- "envelope_version": request.envelope_version,
- "request_id": request.request_id,
- "operation": request.operation,
- "name": request.name,
- "arguments": (
- json.loads(request.arguments_json)
- if request.arguments_json is not None
- else None
- ),
- "deadline_unix_ms": request.deadline_unix_ms,
- }
- if len(json.dumps(body, allow_nan=False).encode()) > _REQUEST_LIMIT:
- raise ValueError
- except (ValueError, TypeError):
- raise self.fail("Driver request is malformed or exceeds the size limit") from None
- timeout = min(deadline - int(time.time() * 1000), 120000) / 1000
- if timeout <= 0:
- raise self.fail("Driver request deadline has expired")
- exchange = asyncio.create_task(self.request("POST", "/exchange", body, timeout=timeout))
- self._exchanges[request.request_id] = exchange
- exchange.add_done_callback(lambda done: self._exchanges.pop(request.request_id, None))
- exchange.add_done_callback(_consume_result)
- try:
- done, _ = await asyncio.wait({exchange}, timeout=timeout)
- if exchange not in done:
- raise TimeoutError("Driver request deadline has expired; completion is unknown")
- return await self.decode_response(request, exchange.result())
- except BaseException:
- exchange.cancel()
- await self.cancel(request.request_id)
- await self.close()
- raise
-
- async def decode_response(self, request, response):
- if self.closed or request.request_id in self.cancelled:
- raise self.fail(
- "Driver response arrived after close or cancellation; completion is unknown"
- )
- try:
- data = response.json()
- if (
- type(data["envelope_version"]) is not int
- or data["envelope_version"] != request.envelope_version
- or not isinstance(data["request_id"], str)
- or data["request_id"] != request.request_id
- or type(data["ok"]) is not bool
- or type(data["completion_known"]) is not bool
- or any(
- data.get(key) is not None and not isinstance(data[key], str)
- for key in ("error", "error_code")
- )
- or (
- data.get("error_code") is not None
- and not _TOKEN.fullmatch(data["error_code"])
- )
- ):
- raise ValueError
- result = sdk.ForeignDriverResponseEnvelope(
- envelope_version=data["envelope_version"],
- request_id=data["request_id"],
- ok=data["ok"],
- result_json=(
- json.dumps(data["result"], allow_nan=False) if "result" in data else None
- ),
- error="Driver operation failed" if data.get("error") is not None else None,
- error_code=data.get("error_code"),
- completion_known=data["completion_known"],
- )
- if not data["completion_known"]:
- self.closed = True
- await self.close()
- return result
- except (ValueError, TypeError, KeyError):
- raise self.fail("Driver response is malformed; completion is unknown") from None
-
- async def cancel(self, request_id):
- self.cancelled.add(request_id)
- if not self.closed:
- self.closed = True
- try:
- await _bounded_cleanup(
- self.request("POST", "/cancel", {"request_id": request_id})
- )
- finally:
- await self.close()
-
- async def close(self):
- self.closed = True
- # Do not memoize a no-op before an in-flight open reveals its ID.
- if self.connection_id is None:
- return
- if self._close_task is None:
-
- async def cleanup():
- receiver_closed = self.connection_id is None
- if self.connection_id is not None:
- receiver_close = asyncio.create_task(self.request("DELETE"))
- receiver_closed = await _bounded_cleanup(receiver_close)
- self.cleanup_confirmed = receiver_closed
-
- self._close_task = asyncio.create_task(cleanup())
- await asyncio.shield(self._close_task)
-
- return Channel()
-
-
class _EnvMcpCarrier:
"""``request_service`` over the cua SDK's env client (``SpacesdClient.http``).
- Gives the shared MCP channel the same byte transport it uses for Fleet
- named services, but addressed to cua-spacesd's own ``/mcp`` with the
- sandbox's env credentials. The service name is ignored: there is one
- spacesd per sandbox.
+ Gives the shared MCP channel its byte transport, addressed to
+ cua-spacesd's own ``/mcp`` with the sandbox's env credentials. The service
+ name is ignored: there is one spacesd per sandbox.
"""
def __init__(self, transport: EnvTransport):
diff --git a/libs/python/cua-sandbox/cua_sandbox/interfaces/mcp.py b/libs/python/cua-sandbox/cua_sandbox/interfaces/mcp.py
index cfc0385078..65f3d7a401 100644
--- a/libs/python/cua-sandbox/cua_sandbox/interfaces/mcp.py
+++ b/libs/python/cua-sandbox/cua_sandbox/interfaces/mcp.py
@@ -2,8 +2,7 @@
cua does not implement MCP. It only gets bytes to the service: ``sb.mcp_config``
returns the endpoint URL and the headers the route needs (nothing locally; the
-Fleet gateway bearer and claim header in the cloud; the daemon bearer through
-``cua daemon``). ``sb.mcp`` hands that to the official SDK
+daemon bearer through ``cua daemon``). ``sb.mcp`` hands that to the official SDK
(``pip install "cua-sandbox[mcp]"``), so every protocol revision and every
content block the SDK supports works unchanged::
@@ -12,8 +11,8 @@ content block the SDK supports works unchanged::
result = await client.call_tool("add", {"a": 2, "b": 3})
Any other MCP client (Claude Code, Cursor, the TypeScript SDK) can use
-``await sb.mcp_config("mcp")`` directly. Fleet bearers are short-lived: fetch
-a fresh config per connection.
+``await sb.mcp_config("mcp")`` directly. Bearers can be short-lived: fetch a
+fresh config per connection.
"""
from __future__ import annotations
diff --git a/libs/python/cua-sandbox/cua_sandbox/options.py b/libs/python/cua-sandbox/cua_sandbox/options.py
index b393a1d827..9c138ac443 100644
--- a/libs/python/cua-sandbox/cua_sandbox/options.py
+++ b/libs/python/cua-sandbox/cua_sandbox/options.py
@@ -1,8 +1,8 @@
-"""Sandbox options that mean the same thing locally and in the cloud.
+"""Sandbox options: command, env, services, readiness probes and sizing.
::
- from cua_sandbox import CloudOptions, Image, Sandbox, http
+ from cua_sandbox import Image, Sandbox, http
sb = await Sandbox.create(
Image.from_registry("python:3.12-slim"),
@@ -10,10 +10,9 @@
env={"FOO": "bar"},
services={"mcp": 8765},
wait_for=http("mcp", "/health"),
- on="cloud", # or local=False; unset: `cua config` default
+ on="local",
kind="container", # "auto" | "container" | "vm"
runtime="gvisor", # the engine; "auto" picks one
- cloud=CloudOptions(warm=True), # cloud-only options
)
"""
@@ -29,24 +28,16 @@ if TYPE_CHECKING:
@dataclass(frozen=True)
class CloudOptions:
- """Advanced options for cloud sandboxes. Passing them implies the cloud;
- with ``on="local"``/``local=True`` they are an ``InvalidArgument``. The
- engine is ``Sandbox.create(runtime="gvisor"|"kubevirt")``, not a cloud
- option.
-
- * ``warm``: keep one sandbox of this image ready (faster next start).
- * ``max_pool_size``: most sandboxes of this image at once (default 10).
- * ``claim_ttl``: how long the sandbox outlives this process without a
- ``keep_alive`` (seconds or a timedelta; renewed while held; default
- 15 min).
- * ``pool``: dedicated capacity: claim from this existing pool. Sandbox
- fields given with it (``image``, ``command``, ``env``, ``services``,
- ``sidecars``, ``cpu``, ``memory``, a registry secret) must match the
- pool's template, else :class:`~cua_sandbox.PoolSpecMismatch` (with a
- readable diff) is raised; fields left unset are not compared.
- * ``apply``: with ``pool``, update the pool's template to the given
- fields instead (the pool's capacity is kept; managed ``cua-auto-*``
- pools refuse it).
+ """Options for Cua Cloud sandboxes. Cua Cloud has ended: passing
+ ``cloud=`` to ``Sandbox.create`` or ``Sandbox.ephemeral`` raises
+ :class:`~cua_sandbox._ended.CloudEnded`, and the class goes away in the
+ next minor release.
+
+ * ``warm``: keep one sandbox of this image ready.
+ * ``max_pool_size``: most sandboxes of this image at once.
+ * ``claim_ttl``: how long the sandbox outlived the process.
+ * ``pool``: claim from this existing pool.
+ * ``apply``: with ``pool``, update the pool's template.
"""
warm: Optional[bool] = None
@@ -125,8 +116,8 @@ NETWORK_MODES = ("default", "none")
def check_network(network: Optional[str]) -> Optional[str]:
"""Normalizes ``network=`` (``None`` / ``"default"`` / ``"none"``).
- Only local QEMU VMs can run with ``"none"``; containers, Lume and cloud
- sandboxes reject it (``Unsupported``) rather than ignore it.
+ Only local QEMU VMs can run with ``"none"``; containers and Lume reject it
+ (``Unsupported``) rather than ignore it.
"""
if network is None:
return None
@@ -172,8 +163,8 @@ def parse_memory(memory: Union[str, int, None]) -> Optional[int]:
@dataclass(frozen=True)
class PublicUrl:
"""A shareable URL of a sandbox service that stops working at
- ``expires_at``. Cloud: a signed service URL; local: a loopback URL with
- its own token, served by the cua daemon."""
+ ``expires_at``: a loopback URL with its own token, served by the cua
+ daemon."""
url: str
expires_at: str
diff --git a/libs/python/cua-sandbox/cua_sandbox/pool.py b/libs/python/cua-sandbox/cua_sandbox/pool.py
index 47834c581f..369adc40cc 100644
--- a/libs/python/cua-sandbox/cua_sandbox/pool.py
+++ b/libs/python/cua-sandbox/cua_sandbox/pool.py
@@ -1,683 +1,83 @@
-"""Fleet template and pool APIs for reusable cloud sandboxes."""
+"""Pools and templates: Cua Cloud has ended.
+
+Every call raises :class:`~cua_sandbox._ended.CloudEnded`. The classes stay
+importable so existing code keeps importing; the module goes away in the next
+minor release.
+"""
from __future__ import annotations
-import logging
-import warnings
-from dataclasses import replace
-from typing import Any, Callable, Coroutine, Generic, Optional, TypeVar, cast
+from typing import Any
from cua_sandbox._ended import CloudEnded
from cua_sandbox._sdk import ENV_SERVICE
-from cua_sandbox.image import Image
-from cua_sandbox.sandbox import Sandbox
-from cua_sandbox.spec import (
- PoolExport,
- PoolOptions,
- SandboxSpec,
- call_native,
- native_fleet,
-)
-from cua_sandbox.transport.fleet import claim_service_for, fleet_transport_for
-from cua_sandbox.transport.fleet_cloud import (
- _NATIVE_POOL_ACCESS_DENIED,
- FleetCloudTransport,
- FleetRuntime,
- _canonicalize_pool_access_denied,
- _FleetClient,
- _pool_access_denied,
- default_server_port,
- default_services,
- resolve_fleet_runtime,
- validate_ttl_seconds_after_created,
-)
-from fleet_sdk import (
- Claim,
- ClaimSpec,
- CreateClaimRequest,
- CreatePoolRequest,
- CreateTemplateRequest,
- ResourceMetadata,
- SandboxTemplateRefBuilder,
- SdkError,
- WarmPoolAutoscaling,
-)
-
-_T = TypeVar("_T")
-logger = logging.getLogger(__name__)
-
-
-async def _native_apply(name: str, spec: Any, options: Any) -> Any:
- """``Fleet.apply`` (the SDK's one pool writer), with the pool-name 403
- raised as ``PoolAccessDeniedError`` like the other pool calls."""
- from cua_sandbox._sdk import native
-
- n = native()
- try:
- return await call_native(native_fleet().apply(name, spec, options))
- except n.CuaError.Fleet as error:
- if "globally unique" in str(error):
- raise _pool_access_denied(
- name,
- SdkError.Status(operation="apply pool", status=403, body="forbidden"),
- ) from error
- raise
-
-
-def legacy_parts(
- image: Image,
- *,
- replicas: int = 1,
- cpu: int | None = None,
- memory_mb: int | None = None,
- services: dict[str, int] | None = None,
- autoscaling: Any = None,
- ttl_seconds_after_created: int | None = None,
- runtime: str | None = None,
-) -> tuple[SandboxSpec, PoolOptions]:
- """The old ``Pool.apply`` keywords as :class:`SandboxSpec` +
- :class:`PoolOptions`. A declared ``server`` service (an image with its
- own control server) is the readiness probe, as before."""
- from cua_sandbox.options import tcp
-
- services = dict(services or {})
- spec = SandboxSpec(
- image=image,
- services=services,
- wait_for=tcp("server") if "server" in services else None,
- cpu=cpu,
- memory_mb=memory_mb,
- )
- if autoscaling is not None:
- options = PoolOptions(
- runtime=runtime,
- replicas=(
- autoscaling.initial_pool_size
- if autoscaling.initial_pool_size is not None
- else replicas
- ),
- min_pool_size=(
- autoscaling.min_pool_size if autoscaling.min_pool_size is not None else 0
- ),
- max_pool_size=autoscaling.max_pool_size,
- pool_ttl=ttl_seconds_after_created,
- )
- else:
- options = PoolOptions(
- runtime=runtime, replicas=replicas, pool_ttl=ttl_seconds_after_created
- )
- return spec, options
-
-
-class _ClaimResult(Generic[_T]):
- """Awaitable claim acquisition that also supports scoped cleanup."""
-
- def __init__(self, factory: Callable[[], Coroutine[Any, Any, _T]]) -> None:
- self._factory = factory
- self._instance: Any = None
-
- def __await__(self) -> Any:
- return self._factory().__await__()
-
- async def __aenter__(self) -> _T:
- self._instance = await self._factory()
- return self._instance
-
- async def __aexit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
- if self._instance is None:
- return
- try:
- await self._instance.close()
- except BaseException:
- if exc_type is None:
- raise
- logger.exception("Failed to release Fleet claim after an earlier error")
+from cua_sandbox.spec import PoolExport, SandboxSpec
class Template:
- """A reconciled Fleet sandbox template."""
+ """A sandbox template on Cua Cloud, which has ended. Every call raises
+ :class:`~cua_sandbox._ended.CloudEnded`."""
- def __init__(self, resource: Any) -> None:
- self._resource = resource
-
- @property
- def name(self) -> str:
- return cast(str, self._resource.metadata.name)
-
- @property
- def resource(self) -> Any:
- return self._resource
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ raise CloudEnded()
@classmethod
- async def reconcile(cls, request: CreateTemplateRequest) -> "Template":
- raise CloudEnded() # Cua Cloud has ended (CUA-1854)
- if not isinstance(request, CreateTemplateRequest):
- raise TypeError("Template.reconcile requires a CreateTemplateRequest")
- client = _FleetClient()
- try:
- try:
- return cls(await client.reconcile_template(request))
- except _NATIVE_POOL_ACCESS_DENIED as error:
- raise _canonicalize_pool_access_denied(error)
- except SdkError.Status as error:
- if error.status == 403:
- raise _pool_access_denied(request.namespace, error) from error
- raise
- finally:
- await client.close()
-
-
-def _claim_stub(namespace: str, name: str) -> Claim:
- return Claim(
- api_version="osgym.cua.ai/v1alpha1",
- kind="OSGymSandboxClaim",
- metadata=ResourceMetadata(
- namespace=namespace,
- name=name,
- labels=None,
- creation_timestamp=None,
- ),
- spec=ClaimSpec(
- sandbox_template_ref=SandboxTemplateRefBuilder().name("").build(),
- warmpool=None,
- bind_deadline=None,
- lifecycle=None,
- ),
- status=None,
- )
-
-
-async def _record_pool_image(sandbox: Sandbox, pool: str) -> None:
- """Sets ``sandbox.image_info`` to pool ``pool``'s template image. Never raises."""
- from cua_sandbox import _sdk
- from cua_sandbox.image import ImageInfo
-
- try:
- info = ImageInfo._from_native(await _sdk.pool_image_info(pool))
- except Exception: # noqa: BLE001 - informational; never fail a claim
- info = None
- if info is not None:
- sandbox._image_info_fallback = info
- # The SDK handle the transport opens later reports it too.
- transport = getattr(sandbox, "_transport", None)
- if transport is not None and hasattr(transport, "_image_info"):
- transport._image_info = info
-
-
-class _ClaimHandle:
- """Serializable identity for a held Fleet claim."""
-
- def __init__(
- self,
- *,
- namespace: str,
- name: str,
- pool_name: str | None = None,
- service: str = ENV_SERVICE,
- client: Any = None,
- agent_type: str | None = None,
- env_token: str | None = None,
- ) -> None:
- # The claim's per-claim env token (never serialized).
- self._env_token = env_token
- 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]:
- return {
- "version": 1,
- "provider": "fleet",
- "namespace": self.namespace,
- "pool": self.pool_name,
- "claim": self.name,
- "service": self.service,
- **({"agent_type": self.agent_type} if self.agent_type else {}),
- }
-
- @classmethod
- def from_dict(cls, data: dict[str, Any]) -> "_ClaimHandle":
- if data.get("provider") != "fleet" or data.get("version") != 1:
- raise ValueError("unsupported sandbox reference")
- return cls(
- namespace=data["namespace"],
- pool_name=data["pool"],
- name=data["claim"],
- service=data.get("service", ENV_SERVICE),
- agent_type=data.get("agent_type"),
- )
-
- def _operation_client(self) -> tuple[Any, bool]:
- client = self._client
- closed = bool(
- client is not None
- and (getattr(client, "_closed", False) or getattr(client, "closed", False))
- )
- if client is None or closed:
- return _FleetClient(), True
- return client, False
-
- async def wait(
- self, *, service: str | None = None, time_to_start: float | None = None
- ) -> Sandbox:
- service = service or self.service
- self.service = service
- client, owns_client = self._operation_client()
- self._client = client
- try:
- bound = await client.wait_claim(_claim_stub(self.namespace, self.name))
- 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(
- transport_cls(
- sdk=client,
- bound=bound,
- service_name=service,
- owns_sdk=True,
- env_token=self._env_token,
- ),
- name=bound.name,
- )
- sandbox._claim_handle = self
- await sandbox._connect()
- if not getattr(self, "managed", False):
- # A named pool's template image (a managed claim's SDK
- # handle already knows its own).
- await _record_pool_image(sandbox, self.pool_name)
- return sandbox
- except BaseException:
- if owns_client:
- if self._client is client:
- self._client = None
- await client.close()
- raise
-
- async def renew(self, shutdown_time: str) -> None:
- client, owns_client = self._operation_client()
- try:
- await client.renew_claim(_claim_stub(self.namespace, self.name), shutdown_time)
- finally:
- if owns_client:
- await client.close()
-
- async def release(self) -> None:
- client, owns_client = self._operation_client()
- try:
- try:
- await client.delete_claim(_claim_stub(self.namespace, self.name))
- except SdkError.Status as error:
- if error.status != 404:
- raise
- finally:
- if owns_client:
- await client.close()
+ async def reconcile(cls, request: Any) -> "Template":
+ raise CloudEnded()
class Pool:
- """A Fleet warm pool that can provide durable Sandbox claims."""
-
- 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:
- return cast(str, self._resource.metadata.name)
+ """A warm pool on Cua Cloud, which has ended. Every call raises
+ :class:`~cua_sandbox._ended.CloudEnded`."""
- @property
- def resource(self) -> Any:
- return self._resource
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ raise CloudEnded()
@classmethod
- async def reconcile(cls, request: CreatePoolRequest) -> "Pool":
- raise CloudEnded() # Cua Cloud has ended (CUA-1854)
- if not isinstance(request, CreatePoolRequest):
- raise TypeError("Pool.reconcile requires a CreatePoolRequest")
- client = _FleetClient()
- try:
- try:
- return cls(await client.reconcile_pool(request))
- except _NATIVE_POOL_ACCESS_DENIED as error:
- raise _canonicalize_pool_access_denied(error)
- except SdkError.Status as error:
- if error.status == 403:
- raise _pool_access_denied(request.namespace, error) from error
- raise
- finally:
- await client.close()
+ async def reconcile(cls, request: Any) -> "Pool":
+ raise CloudEnded()
@classmethod
async def get(cls, name: str) -> "Pool":
- raise CloudEnded() # Cua Cloud has ended (CUA-1854)
- client = _FleetClient()
- try:
- return cls(await client.get_pool(name))
- finally:
- await client.close()
+ raise CloudEnded()
@classmethod
async def apply(cls, *args: Any, **kwargs: Any) -> "Pool":
- """Reconcile a Fleet pool: ``Pool.apply(name, spec, options)``.
-
- ``spec`` (:class:`~cua_sandbox.SandboxSpec`) is what the pool's
- sandboxes run and ``options`` (:class:`~cua_sandbox.PoolOptions`) how
- the pool keeps capacity for them. The pool, its namespace and its
- template share ``name``, which is globally unique on Fleet. This is
- the SDK's one pool writer (``Fleet.apply``): the image is pinned to
- the variant the runtime runs, a new pool is rolled back if its
- template fails, and a runtime the image cannot run on raises
- ``cua.CuaError.InvalidArgument`` before anything is created.
-
- The old form ``Pool.apply(image, *, name=..., replicas=..., cpu=...,
- memory_mb=..., services=..., autoscaling=..., ttl_seconds_after_created=...,
- runtime=...)`` still works and is converted to the new one, with a
- ``DeprecationWarning``.
- """
- raise CloudEnded() # Cua Cloud has ended (CUA-1854)
- if (args and isinstance(args[0], Image)) or "image" in kwargs:
- warnings.warn(
- "Pool.apply(image, name=..., ...) is deprecated; use "
- "Pool.apply(name, SandboxSpec(image=...), PoolOptions(...))",
- DeprecationWarning,
- stacklevel=2,
- )
- return await cls._apply_legacy(*args, **kwargs)
- return await cls._apply(*args, **kwargs)
-
- @classmethod
- async def _apply(
- cls, name: str, spec: SandboxSpec, options: Optional[PoolOptions] = None
- ) -> "Pool":
- if not isinstance(name, str) or not name:
- raise ValueError(
- "Pool.apply requires an explicit non-empty pool name; pool "
- "names are globally unique across accounts"
- )
- if not isinstance(spec, SandboxSpec):
- raise TypeError("Pool.apply(name, spec, options) takes a SandboxSpec")
- options = options or PoolOptions()
- if not isinstance(options, PoolOptions):
- raise TypeError("Pool.apply(name, spec, options) takes a PoolOptions")
- image = spec.image if isinstance(spec.image, Image) else None
- if image is not None:
- FleetCloudTransport._validate_image(image)
- if options.runtime is None or options.runtime in ("gvisor", "kubevirt"):
- # The one runtime/image rule, before anything is created.
- runtime = resolve_fleet_runtime(options.runtime, image)
- options = replace(options, runtime=runtime.name.lower())
- await _native_apply(name, spec.native(), options.native())
- client = _FleetClient()
- try:
- resource = await client.get_pool(name)
- try:
- template = await client.get_template(name, name)
- except Exception: # noqa: BLE001 - only needed to delete it later
- template = None
- finally:
- await client.close()
- return cls(
- resource,
- owned_template=template,
- agent_type=image._agent_type if image is not None else None,
- )
-
- @classmethod
- async def _apply_legacy(
- cls,
- image: Image,
- *,
- name: str,
- replicas: int = 1,
- cpu: int | None = None,
- memory_mb: int | None = None,
- services: dict[str, int] | None = None,
- autoscaling: WarmPoolAutoscaling | None = None,
- ttl_seconds_after_created: int | None = None,
- runtime: FleetRuntime | None = None,
- ) -> "Pool":
- if not isinstance(name, str) or not name:
- raise ValueError(
- "Pool.apply requires an explicit non-empty pool name; pool "
- "names are globally unique across accounts"
- )
- FleetCloudTransport._validate_image(image)
- # None (spacesd) unless the image runs its own control server
- # (agent_type="osworld" → the OSWorld Flask server on 5000).
- server_port = default_server_port(image)
- effective_services = services or default_services(server_port, image._ports)
- # Validates every argument and resolves the runtime (the one rule)
- # before anything is created.
- transport = FleetCloudTransport(
- image=image,
- name=name,
- replicas=replicas,
- cpu=cpu,
- memory_mb=memory_mb,
- services=effective_services,
- autoscaling=autoscaling,
- ttl_seconds_after_created=ttl_seconds_after_created,
- fleet_runtime=runtime,
- server_port=server_port,
- )
- spec, options = legacy_parts(
- image,
- replicas=replicas,
- cpu=cpu,
- memory_mb=memory_mb,
- services=dict(effective_services),
- autoscaling=autoscaling,
- ttl_seconds_after_created=ttl_seconds_after_created,
- runtime=transport._runtime.name.lower() if transport._runtime is not None else None,
- )
- return await cls._apply(name, spec, options)
+ raise CloudEnded()
@staticmethod
async def export(name: str, *, terraform: bool = False) -> "PoolExport | str":
- """Read pool ``name`` back as the shared model (a :class:`PoolExport`
- whose ``spec`` / ``options`` are the native records), or with
- ``terraform=True`` the equivalent Terraform ``fleets_pool`` block
- (attributes the provider lacks yet are commented)."""
- raise CloudEnded() # Cua Cloud has ended (CUA-1854)
- exported = await call_native(native_fleet().export_pool(name))
- if terraform:
- return cast(str, exported.terraform)
- return PoolExport(
- name=name,
- runtime=exported.runtime,
- spec=exported.spec,
- options=exported.options,
- terraform=exported.terraform,
- )
+ raise CloudEnded()
@staticmethod
async def check(name: str, spec: SandboxSpec) -> None:
- """Raise :class:`~cua_sandbox.PoolSpecMismatch` (with a readable diff)
- when the set fields of ``spec`` differ from pool ``name``'s
- template."""
- raise CloudEnded() # Cua Cloud has ended (CUA-1854)
- await call_native(native_fleet().check_pool_spec(name, spec.native()))
+ raise CloudEnded()
@staticmethod
async def apply_template(name: str, spec: SandboxSpec) -> None:
- """Lay the set fields of ``spec`` over pool ``name``'s template and
- write it (the pool's capacity is kept; a no-op when nothing
- differs)."""
- raise CloudEnded() # Cua Cloud has ended (CUA-1854)
- await call_native(native_fleet().apply_pool_template(name, spec.native()))
-
- async def _claim_with_token(
- self,
- token: str,
- *,
- name: str | None,
- ttl: int | None,
- service: str,
- time_to_start: float | None,
- agent_type: str | None,
- ) -> Sandbox:
- from cua_sandbox._sdk import native
-
- bound = await call_native(
- native_fleet().acquire_with(
- self.name,
- native().FleetClaimOptions(name=name, ttl_seconds=ttl, claim_token=token),
- )
- )
- handle = _ClaimHandle(
- namespace=bound.namespace,
- name=bound.claim,
- pool_name=self.name,
- service=service,
- agent_type=agent_type,
- env_token=token,
- )
- try:
- return await handle.wait(service=service, time_to_start=time_to_start)
- except BaseException:
- try:
- await handle.release()
- except Exception:
- logger.exception("Failed to release Fleet claim after acquisition failure")
- raise
+ raise CloudEnded()
async def delete(self) -> None:
- """Delete this Fleet pool."""
- raise CloudEnded() # Cua Cloud has ended (CUA-1854)
- client = _FleetClient()
- try:
- await client.delete_pool(self._resource)
- if self._owned_template is not None:
- await client.delete_template(self._owned_template)
- self._owned_template = None
- finally:
- await client.close()
-
- def _claim_spec(
- self, spec: ClaimSpec | None, ttl_seconds_after_created: int | None
- ) -> ClaimSpec | None:
- if ttl_seconds_after_created is None:
- return spec
- if spec is not None:
- raise ValueError(
- "pass ttl_seconds_after_created inside spec when supplying an explicit ClaimSpec"
- )
- validate_ttl_seconds_after_created(ttl_seconds_after_created)
- return ClaimSpec(
- sandbox_template_ref=self._resource.spec.sandbox_template_ref,
- warmpool=None,
- bind_deadline=None,
- lifecycle=None,
- ttl_seconds_after_created=ttl_seconds_after_created,
- )
+ raise CloudEnded()
async def create_claim(
self,
*,
- spec: ClaimSpec | None = None,
+ spec: Any = None,
name: str | None = None,
ttl_seconds_after_created: int | None = None,
- ) -> _ClaimHandle:
- raise CloudEnded() # Cua Cloud has ended (CUA-1854)
- spec = self._claim_spec(spec, ttl_seconds_after_created)
- request = CreateClaimRequest(pool=self._resource, spec=spec, name=name)
- client = _FleetClient()
- try:
- claim = await client.create_claim(request)
- return _ClaimHandle(
- namespace=claim.metadata.namespace,
- name=claim.metadata.name,
- pool_name=self.name,
- agent_type=self._agent_type,
- )
- finally:
- await client.close()
+ ) -> Any:
+ raise CloudEnded()
def claim(
self,
*,
- spec: ClaimSpec | None = None,
+ spec: Any = None,
name: str | None = None,
service: str = ENV_SERVICE,
time_to_start: float | None = None,
ttl_seconds_after_created: int | None = None,
agent_type: str | None = None,
claim_token: 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).
-
- ``claim_token`` (see :func:`generate_claim_token`) is delivered into the
- sandbox at ``/run/cua/env-token`` through the claim's Secret; the pool's
- spec must set ``claim_secrets=True``. The claim waits (at most 90 s
- after it binds) until the sandbox has it, else it is released and
- :class:`~cua_sandbox.ClaimSecretsNotDelivered` is raised."""
- raise CloudEnded() # Cua Cloud has ended (CUA-1854)
- claim_agent_type = agent_type or self._agent_type
- service = claim_service_for(claim_agent_type, service)
- if claim_token is not None:
- if spec is not None:
- raise ValueError("claim_token cannot be combined with an explicit ClaimSpec")
- if ttl_seconds_after_created is not None:
- validate_ttl_seconds_after_created(ttl_seconds_after_created)
- return _ClaimResult(
- lambda: self._claim_with_token(
- claim_token,
- name=name,
- ttl=ttl_seconds_after_created,
- service=service,
- time_to_start=time_to_start,
- agent_type=claim_agent_type,
- )
- )
- spec = self._claim_spec(spec, ttl_seconds_after_created)
-
- async def acquire() -> Sandbox:
- client = _FleetClient()
- claim: Any = None
- created_claim = False
- try:
- if name is not None:
- claim = next(
- (
- existing
- for existing in await client.list_claims(
- self._resource.metadata.namespace
- )
- if existing.metadata.name == name
- ),
- None,
- )
- if claim is None:
- claim = await client.create_claim(
- CreateClaimRequest(pool=self._resource, spec=spec, name=name)
- )
- created_claim = True
- handle = _ClaimHandle(
- namespace=claim.metadata.namespace,
- name=claim.metadata.name,
- 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:
- if created_claim and claim is not None:
- try:
- await client.delete_claim(claim)
- except Exception:
- logger.exception("Failed to release Fleet claim after acquisition failure")
- await client.close()
- raise
-
- return _ClaimResult(acquire)
+ ) -> Any:
+ raise CloudEnded()
diff --git a/libs/python/cua-sandbox/cua_sandbox/pools.py b/libs/python/cua-sandbox/cua_sandbox/pools.py
index b541977156..bdbebae198 100644
--- a/libs/python/cua-sandbox/cua_sandbox/pools.py
+++ b/libs/python/cua-sandbox/cua_sandbox/pools.py
@@ -4,16 +4,48 @@ Every call raises :class:`~cua_sandbox._ended.CloudEnded`; the module goes
away in the next minor release.
"""
-from typing import Any
-
-from cua_sandbox._autopool import (
- ClaimInfo,
- GcReport,
- ManagedPoolInfo,
- is_managed_pool_name,
-)
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any, Optional
+
from cua_sandbox._ended import CloudEnded
+MANAGED_PREFIX = "cua-auto-"
+LEGACY_EPHEMERAL_PREFIX = "cua-eph-"
+
+
+def is_managed_pool_name(name: str, prefix: str = MANAGED_PREFIX) -> bool:
+ return name.startswith((prefix, MANAGED_PREFIX, LEGACY_EPHEMERAL_PREFIX))
+
+
+@dataclass
+class ManagedPoolInfo:
+ name: str
+ spec_hash: Optional[str]
+ managed: bool
+ replicas: Optional[int]
+ ready_replicas: Optional[int]
+ claims: int
+ last_used: Optional[datetime]
+ created_at: Optional[str]
+
+
+@dataclass
+class ClaimInfo:
+ name: str
+ pool: str
+ phase: Optional[str]
+ managed: bool
+ created_at: Optional[str]
+
+
+@dataclass
+class GcReport:
+ pools_deleted: list[str] = field(default_factory=list)
+ claims_deleted: list[str] = field(default_factory=list)
+ namespaces_deleted: list[str] = field(default_factory=list)
+ errors: list[str] = field(default_factory=list)
+
async def list_pools(*args: Any, **kwargs: Any) -> list[ManagedPoolInfo]:
raise CloudEnded()
diff --git a/libs/python/cua-sandbox/cua_sandbox/runtime/native.py b/libs/python/cua-sandbox/cua_sandbox/runtime/native.py
index 807c8ee2c6..00db6508e9 100644
--- a/libs/python/cua-sandbox/cua_sandbox/runtime/native.py
+++ b/libs/python/cua-sandbox/cua_sandbox/runtime/native.py
@@ -140,7 +140,7 @@ class NativeRuntime(Runtime):
return image.os_type or "linux"
#: Whether this runtime mints the spacesd token itself (containers).
- #: Otherwise the SDK mints one for Linux VMs (cloud-init, the Fleet
+ #: Otherwise the SDK mints one for Linux VMs (cloud-init, the
#: /run/cua/env-token contract) and macOS VMs (the Lume setup share) and
#: keeps it in the sandbox record, which ``_info`` reads back.
delivers_guest_env = False
diff --git a/libs/python/cua-sandbox/cua_sandbox/runtime/qemu.py b/libs/python/cua-sandbox/cua_sandbox/runtime/qemu.py
index 70d18f0248..674d511568 100644
--- a/libs/python/cua-sandbox/cua_sandbox/runtime/qemu.py
+++ b/libs/python/cua-sandbox/cua_sandbox/runtime/qemu.py
@@ -103,7 +103,7 @@ class NativeQEMURuntime(NativeRuntime):
if disk and not has_build_work(image):
return f"disk:{disk}"
if ref is not None and not disk and not has_build_work(image):
- # The SDK pulls the pinned containerDisk (the disk Fleet boots).
+ # The SDK pulls the pinned containerDisk.
return f"vm:{ref}"
session = await create_session_disk(image, name, base_disk=Path(disk) if disk else None)
if "sessions" in str(session):
diff --git a/libs/python/cua-sandbox/cua_sandbox/sandbox.py b/libs/python/cua-sandbox/cua_sandbox/sandbox.py
index fc5e2f7f3b..8db8f1303a 100644
--- a/libs/python/cua-sandbox/cua_sandbox/sandbox.py
+++ b/libs/python/cua-sandbox/cua_sandbox/sandbox.py
@@ -3,9 +3,9 @@
Exposes .mouse, .keyboard, .screen, .clipboard, .shell, .window, .terminal
as interface objects backed by a Transport.
-cua-sandbox is a thin wrapper over the ``cua`` SDK: Fleet claims, the
-Docker/QEMU/Lume runtimes and cua-spacesd (the interfaces) all go through
-it. Sandboxes are daemon-agnostic: creating, connecting and deleting one never
+cua-sandbox is a thin wrapper over the ``cua`` SDK: the Docker/QEMU/Lume
+runtimes and cua-spacesd (the interfaces) go through it. Sandboxes are
+daemon-agnostic: creating, connecting and deleting one never
assumes a guest agent; the interfaces use cua-spacesd when the image has it
and an agentless path (QMP, VNC, SSH, ADB) otherwise.
@@ -13,16 +13,14 @@ Usage::
from cua_sandbox import Image, Sandbox, http
- # Any image, local or cloud: the same code, flip on= (or local=).
- # Unset, `cua config set default.on cloud` / CUA_DEFAULT_ON decide.
sb = await Sandbox.create(
Image.from_registry("python:3.12-slim"),
command=["python", "-m", "my_mcp", "--port", "8765"],
services={"mcp": 8765},
wait_for=http("mcp", "/health"),
- on="local", # "local" | "cloud"
+ on="local",
kind="container", # "auto" | "container" | "vm"
- runtime="gvisor", # the engine: "auto", gvisor/runc/qemu/lume, kubevirt
+ runtime="gvisor", # the engine: "auto", gvisor, runc, qemu, lume
)
r = await sb.service("mcp").request("POST", "/mcp", json={...}, headers={...})
url = await sb.public_url("mcp", ttl=3600)
@@ -52,7 +50,6 @@ import os
import random
import time
import warnings
-from collections.abc import Mapping
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
@@ -81,7 +78,6 @@ except ImportError:
from cua_sandbox import _placement, _refs
-from cua_sandbox._config import has_fleet_access
from cua_sandbox._ended import CloudEnded
from cua_sandbox._refs import AmbiguousSandbox # noqa: F401 - re-exported
from cua_sandbox._sdk import ( # noqa: F401 - InvalidPlacement is re-exported
@@ -118,22 +114,13 @@ from cua_sandbox.options import (
parse_memory,
probes,
)
-from cua_sandbox.spec import SandboxSpec
from cua_sandbox.transport.base import Transport
-from cua_sandbox.transport.cloud import CloudTransport
from cua_sandbox.transport.env import EnvTransport, env_url
-from cua_sandbox.transport.fleet_cloud import (
- FleetCloudTransport,
- OSWorldFleetCloudTransport,
- validate_server_port,
-)
-from cua_sandbox.transport.osworld import OSWORLD_SERVER_PORT
if TYPE_CHECKING:
from cua_sandbox.interfaces.services import ServiceHandle
from cua_sandbox.pool import Pool
from cua_sandbox.runtime.base import Runtime, RuntimeInfo
- from cua_sandbox.transport.fleet_cloud import FleetRuntime
logger = logging.getLogger(__name__)
@@ -175,76 +162,31 @@ async def _with_overlays(sandbox: "Sandbox", overlay: Any) -> "Sandbox":
return sandbox
-async def _keep_alive_or_close(sandbox: Any, minutes: float | None) -> None:
- if minutes is None:
+def validate_server_port(server_port: Any) -> None:
+ """``None`` (daemon-agnostic default) or a TCP port."""
+ if server_port is None:
return
- try:
- await sandbox.keep_alive(minutes=minutes)
- except BaseException as keep_alive_error:
- try:
- await sandbox.close()
- except BaseException as close_error:
- logger.warning("Failed to close Fleet claim after keep-alive failure: %s", close_error)
- raise keep_alive_error from close_error
- raise
-
-
-async def _save_fleet_claim_or_close(
- sandbox: Any,
- claim_name: str,
- pool_name: str,
- **extra: Any,
-) -> None:
- from cua_sandbox import sandbox_state
-
- try:
- sandbox_state.save_fleet_claim(claim_name, pool_name, **extra)
- except BaseException as state_error:
- try:
- await sandbox.close()
- except BaseException as close_error:
- raise state_error from close_error
- raise
+ if (
+ isinstance(server_port, bool)
+ or not isinstance(server_port, int)
+ or server_port < 1
+ or server_port > 65535
+ ):
+ raise ValueError("server_port must be an integer between 1 and 65535")
-def _reject_managed_options_for_pool(
- warm: Optional[bool], max_pool_size: Optional[int], claim_ttl: Any
+def _reject_cloud_args(
+ *, pool: Any = None, claim_spec: Any = None, replicas: int = 1, service: str = ENV_SERVICE
) -> None:
- if warm is not None or max_pool_size is not None or claim_ttl is not None:
- raise ValueError(
- "warm, max_pool_size and claim_ttl configure managed pools (image "
- "without pool=). An explicit pool keeps its own configuration: size it "
- "with Pool.apply(..., autoscaling=...) and set a claim TTL with "
- "claim_spec= or pool.claim(ttl_seconds_after_created=...)."
- )
-
-
-def _check_managed_options(
- *,
- replicas: int,
- claim_spec: Any,
- disk_gb: Optional[int],
- region: str,
- request_timeout: Optional[float],
-) -> None:
- if replicas != 1:
- raise ValueError(
- "replicas= sizes an explicit pool. Managed pools autoscale from zero: "
- "use warm=True and max_pool_size= instead, or Pool.apply(image, "
- "name=..., replicas=...) and pass it as pool="
- )
- if claim_spec is not None:
- raise ValueError(
- "claim_spec= needs an explicit pool=. Managed pools set the claim "
- "TTL from claim_ttl= and renew it while the sandbox is held"
- )
- if disk_gb is not None or region != "us-east-1" or request_timeout is not None:
- raise NotImplementedError("the requested option is not supported by Fleet")
+ """``pool=``, ``claim_spec=``, ``replicas=`` and ``service=`` only meant
+ something on Cua Cloud, which has ended."""
+ if pool is not None or claim_spec is not None or replicas != 1 or service != ENV_SERVICE:
+ raise CloudEnded()
def _is_local_sandbox(name: str) -> bool:
- """Whether ``name`` is a local sandbox (a state file that is not a Fleet
- claim)."""
+ """Whether ``name`` is a local sandbox (a state file that is not a stale
+ Cua Cloud claim record)."""
from cua_sandbox import sandbox_state
state = sandbox_state.load(name)
@@ -255,140 +197,50 @@ async def _lookup(name: str, local: Optional[bool]) -> tuple[str, bool]:
"""``(plain name, local)`` for a sandbox ref or bare name (see
:func:`cua_sandbox._refs.resolve`). A ``direct:`` machine is not managed
here: connect to it with ``Sandbox.connect(url=...)``."""
- plain, is_local, direct = await _refs.resolve(name, local)
+ plain, _, direct = await _refs.resolve(name, local)
if direct is not None:
raise Unsupported(
f"{name}: a direct machine is not managed by cua-sandbox; connect to it with "
f"Sandbox.connect({name!r})"
)
- if not is_local:
- # A name that is not a local sandbox was a cloud one.
- raise CloudEnded()
+ # A bare name is a local sandbox (an unknown one fails as "not found" in the
+ # local path); a cloud ref or ``local=False`` already raised CloudEnded.
return plain, True
-def _fleet_lifecycle_unsupported(name: str, operation: str) -> Unsupported:
- """Fleet has no per-sandbox suspend: a claim is running or released, and
- scaling its pool would touch every sandbox in it."""
- return Unsupported(
- f"{operation} is not supported for cloud sandboxes ({name!r}): Fleet cannot "
- "suspend a single sandbox. Hold it with keep_alive(), or release it with "
- "Sandbox.delete(name) and create a new one"
- )
-
-
-async def _acquire_managed(
- image: Image,
- *,
- name: Optional[str],
- service: str,
- cpu: Optional[int],
- memory_mb: Optional[int],
- server_port: Optional[int],
- time_to_start: Optional[float],
- warm: Optional[bool],
- max_pool_size: Optional[int],
- claim_ttl: Any,
- progress: Optional[Callable[[Any], Any]],
- telemetry_enabled: bool,
- ephemeral: bool = False,
- fleet_runtime: Optional[str] = None,
- command: Optional[list[str]] = None,
- sidecars: Optional[list] = None,
- env: Optional[dict[str, str]] = None,
- services: Optional[dict[str, int]] = None,
- wait_for: Optional[list[Probe]] = None,
- hint: Optional[str] = None,
-) -> "Sandbox":
- """Claim ``image`` from this account's managed cloud capacity. ``hint``
- (the cloud came from a user default) is added to a missing-credentials
- error."""
- from cua_sandbox import _autopool
-
- validate_server_port(server_port)
- t_start = time.monotonic()
- sandbox = await _autopool.acquire(
- image,
- name=name,
- cpu=cpu,
- memory_mb=memory_mb,
- server_port=server_port,
- service=service,
- time_to_start=time_to_start,
- cfg=_autopool.config(warm=warm, max_pool_size=max_pool_size, claim_ttl=claim_ttl),
- progress=progress,
- runtime=fleet_runtime,
- command=command,
- sidecars=sidecars,
- env=env,
- services=services,
- wait_for=wait_for,
- hint=hint,
- )
- sandbox._ephemeral = ephemeral
- sandbox.telemetry_enabled = telemetry_enabled
- _record_sandbox_create(sandbox, image=image, local=False, ephemeral=ephemeral, t_start=t_start)
- return sandbox
-
-
-async def _cleanup_ephemeral_fleet(
- sandbox: Any | None,
- pool: Any | None,
- *,
- suppress_errors: bool,
-) -> None:
- cleanup_error: BaseException | None = None
- cleanup_operations = (
- ("claim", sandbox.close if sandbox is not None else None),
- ("pool", pool.delete if pool is not None else None),
- )
- for resource, cleanup in cleanup_operations:
- if cleanup is None:
- continue
- try:
- await cleanup()
- except BaseException as error:
- if suppress_errors or cleanup_error is not None:
- logger.warning("Failed to clean up ephemeral Fleet %s: %s", resource, error)
- else:
- cleanup_error = error
- if cleanup_error is not None:
- raise cleanup_error
-
-
@dataclass
class SandboxInfo:
- """Metadata for a local or cloud sandbox.
+ """Metadata for a local sandbox.
``status`` from :meth:`Sandbox.info` is portable: ``provisioning``,
``starting``, ``ready`` or ``stopped``. Listings keep the provider's word
- (``running``, ``suspended``, ...). Provider internals (the cloud pool,
- namespace and claim; the local backend) are in ``provider_details``.
+ (``running``, ``suspended``, ...). Provider internals (the local backend)
+ are in ``provider_details``.
"""
name: str
status: str
- source: str # "cloud" | "fleet" | "lume" | "docker" | "qemu-baremetal" | ...
+ source: str # "lume" | "docker" | "qemu-baremetal" | ...
os_type: Optional[str] = None
host: Optional[str] = None
vnc_url: Optional[str] = None
api_url: Optional[str] = None
created_at: Optional[str] = None
- #: The qualified ref: ``local:<name>``, ``cloud:<name>`` or
- #: ``direct:<host:port>`` (what ``Sandbox.connect`` / ``delete`` take).
+ #: The qualified ref: ``local:<name>`` or ``direct:<host:port>`` (what
+ #: ``Sandbox.connect`` / ``delete`` take).
id: Optional[str] = None
- location: Optional[str] = None # "local" | "cloud" | "direct"
+ location: Optional[str] = None # "local" | "direct"
services: dict = field(default_factory=dict)
expires_at: Optional[str] = None
provider_details: dict = field(default_factory=dict)
#: What kind of machine: ``container`` or ``vm`` (``None`` when unknown).
kind: Optional[str] = None
- #: Which engine runs it: ``gvisor``, ``runc``, ``qemu``, ``lume`` (local),
- #: ``gvisor``, ``kubevirt`` (cloud); ``None`` when unknown.
+ #: Which engine runs it: ``gvisor``, ``runc``, ``qemu``, ``lume``;
+ #: ``None`` when unknown.
runtime: Optional[str] = None
def __post_init__(self) -> None:
- # The qualified ref (`local:<name>`, `cloud:<name>`) when not given.
+ # The qualified ref (`local:<name>`) when not given.
if self.id is None and self.location and self.name:
self.id = f"{self.location}:{self.name}"
@@ -411,47 +263,6 @@ _PHASE_WORDS = {
}
-def _merge_cloud(
- cloud: Optional[CloudOptions],
- *,
- pool: Any,
- warm: Optional[bool],
- max_pool_size: Optional[int],
- claim_ttl: Any,
-) -> tuple[Any, Optional[bool], Optional[int], Any]:
- """``cloud=`` merged with the deprecated flat kwargs (pool, warm,
- max_pool_size, claim_ttl)."""
- old = {
- "pool": pool,
- "warm": warm,
- "max_pool_size": max_pool_size,
- "claim_ttl": claim_ttl,
- }
- given = [k for k, v in old.items() if v is not None]
- if given:
- warnings.warn(
- f"{', '.join(given)}= {'is' if len(given) == 1 else 'are'} deprecated; pass "
- f"cloud=CloudOptions({', '.join(f'{k}=...' for k in given)})",
- DeprecationWarning,
- stacklevel=4,
- )
- if cloud is None:
- return pool, warm, max_pool_size, claim_ttl
- if not isinstance(cloud, CloudOptions):
- raise TypeError("cloud= takes a CloudOptions")
- merged = []
- for key in ("pool", "warm", "max_pool_size", "claim_ttl"):
- new, previous = getattr(cloud, key), old[key]
- if new is not None and previous is not None and new != previous:
- raise ValueError(f"{key} is set both in cloud= and as a keyword argument")
- merged.append(new if new is not None else previous)
- return tuple(merged) # type: ignore[return-value]
-
-
-#: How long the default ``Sandbox.list()`` waits for the cloud.
-_LIST_CLOUD_TIMEOUT = 5.0
-
-
def _cloud_only_args(
*,
pool: Any = None,
@@ -466,7 +277,9 @@ def _cloud_only_args(
keep_alive_minutes: Any = None,
progress: Any = None,
) -> list[str]:
- """The keyword arguments given that only mean something in the cloud."""
+ """The keyword arguments given that only meant something on Cua Cloud, which
+ has ended: given without ``on=``/``local=`` they select the cloud, and
+ placement raises :class:`CloudEnded`."""
given = {
"pool": pool is not None,
"warm": warm is not None,
@@ -483,17 +296,6 @@ def _cloud_only_args(
return [k for k, v in given.items() if v]
-def _requested_placement(kind: Any, runtime: Any) -> str:
- """The explicit ``kind=``/engine ``runtime=`` the caller passed, as text
- (``""`` when neither; ``"auto"`` counts as unset)."""
- parts = []
- if isinstance(kind, str) and kind.strip().lower() not in ("", "auto"):
- parts.append(f"kind={kind.strip().lower()!r}")
- if isinstance(runtime, str) and runtime.strip().lower() not in ("", "auto"):
- parts.append(f"runtime={runtime.strip().lower()!r}")
- return ", ".join(parts)
-
-
def _apply_on(
on: Optional[str],
local: Optional[bool],
@@ -508,11 +310,12 @@ def _apply_on(
"""Route ``on=`` to a provider when it names one: a contrib platform
(``"e2b"``, ``"daytona"``, ``"modal"``; opt-in SDK builds) or your own
cloud (``"aws"``, ``"gcp"``, ``"modal"``; connect it with ``cua cloud
- connect``). ``"local"``, ``"cloud"``,
- ``"direct:<addr>"`` and ``"relay:<id>"`` fall through to the placement
- model (:mod:`cua_sandbox._placement`). Returns ``(on, local, runtime)``; a
- contrib provider becomes ``(None, True, ContribRuntime(...))``, a local
- sandbox served through the provider's SDK handle."""
+ connect``). ``"local"``, ``"direct:<addr>"`` and ``"relay:<id>"`` fall
+ through to the placement model (:mod:`cua_sandbox._placement`); so do
+ ``"cloud"`` and ``"fleet"``, which raise :class:`CloudEnded`. Returns
+ ``(on, local, runtime)``; a contrib provider becomes ``(None, True,
+ ContribRuntime(...))``, a local sandbox served through the provider's SDK
+ handle."""
if on is None or not str(on).strip():
return on, local, runtime
word = str(on).strip().lower()
@@ -557,22 +360,12 @@ def _place_new(
cloud=cloud,
cloud_only=cloud_only,
image_kind=image.kind if image is not None else None,
- stacklevel=5,
)
if image is not None and place.kind and place.kind != image.kind:
image = image._with(kind=place.kind)
return place, image
-def _reject_cloud_network(network: Optional[str], local: bool) -> None:
- """``network="none"`` is a local QEMU feature; the cloud refuses it."""
- if network == "none" and not local:
- raise Unsupported(
- "network='none' needs a local QEMU VM (local=True); cloud sandboxes always "
- "have outbound network"
- )
-
-
def _sdk_backed(runtime: Any) -> bool:
"""Whether a local adapter starts its sandboxes through the cua SDK (and
so takes ``kind``/``runtime`` start options)."""
@@ -740,10 +533,10 @@ def _pick_runtime(
from cua_sandbox.runtime.qemu import QEMURuntime
if image.os_type == "linux":
- # A Linux VM boots the pinned containerDisk under bare-metal QEMU — the
- # same disk Fleet cloud boots. Docker-wrapped QEMU cannot reach that path
- # at all: resolve_image() hands it the XFCE *container* image, so asking
- # for a VM used to quietly get you a container.
+ # A Linux VM boots the pinned containerDisk under bare-metal QEMU.
+ # Docker-wrapped QEMU cannot reach that path at all: resolve_image()
+ # hands it the XFCE *container* image, so asking for a VM used to
+ # quietly get you a container.
from cua_sandbox.runtime.compat import _has_qemu
if not _has_qemu():
@@ -867,13 +660,10 @@ class Sandbox:
):
self._transport = transport
self.name = name
- """The sandbox name (`None` until a cloud sandbox is bound)."""
+ """The sandbox name."""
self._runtime = _runtime
self._runtime_info = _runtime_info
self._ephemeral = _ephemeral
- self._has_snapshots = False
- self._claim_handle: Any = None
- self._claim_released = False
# Image info the Python side resolved (runtimes with no SDK handle).
self._image_info_fallback: Optional[ImageInfo] = None
# Set for a machine reached by URL (``direct:<host:port>``).
@@ -910,20 +700,9 @@ class Sandbox:
async def _connect(self) -> None:
await self._transport.connect()
- # Update name from transport (e.g. CloudTransport resolves name after creating a VM)
- if self.name is None and isinstance(self._transport, (CloudTransport, FleetCloudTransport)):
- self.name = self._transport.name
async def disconnect(self) -> None:
- """Drop the transport connection. The sandbox keeps running.
-
- A claim on a managed Fleet pool stops being renewed and lives until
- its shutdown time (``claim_ttl``, or later if ``keep_alive`` was
- called).
- """
- detach = getattr(self._claim_handle, "detach", None)
- if callable(detach):
- detach()
+ """Drop the transport connection. The sandbox keeps running."""
await self.driver.close()
await self._transport.disconnect()
@@ -935,8 +714,7 @@ class Sandbox:
so the mapping is only knowable at runtime. Reading it from the saved
state as well means a reconnecting caller can still find the port rather
than it living only on the object create() returned. Empty when the
- runtime forwards nothing (Fleet publishes services instead — use
- tunnel.forward()).
+ runtime forwards nothing (use tunnel.forward()).
"""
info = getattr(self, "_runtime_info", None)
ports = getattr(info, "exposed_ports", None) if info else None
@@ -959,9 +737,7 @@ class Sandbox:
def image_info(self) -> Optional[ImageInfo]:
"""The image this sandbox runs, as resolved and pinned at create time
(digest, variant, arch), or ``None`` when unknown: direct (URL)
- connections, images not resolved from a registry. A claim on a named
- Fleet pool reports its template's image (``pinned_ref``/``digest``
- empty when the registry could not be read).
+ connections, images not resolved from a registry.
The SDK handle's ``image_info()`` is the source of truth; runtimes
without one report what was resolved at create or claim time. Never
@@ -979,51 +755,41 @@ class Sandbox:
def _native_candidates(self) -> list:
"""SDK sandbox handles this sandbox holds, without any I/O."""
info = getattr(self, "_runtime_info", None)
- claim = getattr(self, "_claim_handle", None)
transport = getattr(self, "_transport", None)
found = [
getattr(info, "native", None) if info is not None else None,
- getattr(claim, "_native", None) if claim is not None else None,
- getattr(transport, "_native_fleet_sandbox", None),
getattr(transport, "_native_sandbox", None),
]
return [h for h in found if h is not None]
@property
def claim_name(self) -> str | None:
- """Fleet claim name, distinct from the bound sandbox name."""
- return self._claim_handle.name if self._claim_handle is not None else None
+ """Always ``None``: claims belonged to Cua Cloud, which has ended."""
+ return None
@property
def pool_name(self) -> str | None:
- """Fleet pool that owns this claim (advanced; see
- ``(await sb.info()).provider_details``)."""
- return self._claim_handle.pool_name if self._claim_handle is not None else None
+ """Always ``None``: pools belonged to Cua Cloud, which has ended."""
+ return None
@property
def location(self) -> str:
- """Where it runs: ``local``, ``cloud`` or ``direct``."""
+ """Where it runs: ``local`` or ``direct``."""
if self._direct_url is not None:
return "direct"
- if self._claim_handle is not None or isinstance(
- self._transport, (CloudTransport, FleetCloudTransport)
- ):
- return "cloud"
return "local"
@property
def id(self) -> str | None:
- """The qualified ref, the same kind of value local and in the cloud:
- ``local:<name>``, ``cloud:<name>`` or ``direct:<host:port>``. It is
- what ``Sandbox.connect(id)`` and ``Sandbox.delete(id)`` take, and
+ """The qualified ref: ``local:<name>`` or ``direct:<host:port>``. It
+ is what ``Sandbox.connect(id)`` and ``Sandbox.delete(id)`` take, and
what listings print."""
if self._direct_url is not None:
try:
return _refs.parse(self._direct_url).id
except Exception: # noqa: BLE001 - an unparsable URL keeps its name
return self.name
- name = self.claim_name or self.name
- return _refs.qualified(self.location, name) if name else None
+ return _refs.qualified(self.location, self.name) if self.name else None
async def _native_handle(self) -> Any:
"""The ``cua.Sandbox`` handle (services, forwards, public URLs)."""
@@ -1052,8 +818,8 @@ class Sandbox:
async def info(self) -> SandboxInfo:
"""Portable info: ``status`` (provisioning, starting, ready, stopped),
- ``location`` (local, cloud or direct), ``services`` (name -> guest
- port), ``expires_at`` (cloud) and ``provider_details``."""
+ ``location`` (local or direct), ``services`` (name -> guest port),
+ ``expires_at`` and ``provider_details``."""
handle = await self._native_handle()
record = await handle.refresh()
expires = (
@@ -1065,7 +831,7 @@ class Sandbox:
return SandboxInfo(
name=self.name or record.name,
status=phase,
- source="cloud" if record.location == "cloud" else record.runtime_type,
+ source=record.runtime_type,
os_type=getattr(self._runtime_info, "environment", None),
id=record.id or self.id,
location=record.location,
@@ -1078,8 +844,7 @@ class Sandbox:
def service(self, name: str) -> "ServiceHandle":
"""A named service (``services={"mcp": 8765}`` at create):
- ``request``, ``url`` and ``public_url``, the same local and in the
- cloud."""
+ ``request``, ``url`` and ``public_url``."""
from cua_sandbox.interfaces.services import ServiceHandle
return ServiceHandle(self, name)
@@ -1088,9 +853,8 @@ class Sandbox:
self, service: str, *, ttl: float = 3600, label: Optional[str] = None
) -> PublicUrl:
"""A shareable URL for ``service`` that stops working after ``ttl``
- seconds (60 s to 24 h). Cloud: a signed service URL. Local: a
- loopback URL with its own token, served by the cua daemon (started
- if needed)."""
+ seconds (60 s to 24 h): a loopback URL with its own token, served by
+ the cua daemon (started if needed)."""
from cua_sandbox.interfaces.services import public_url_from_native
handle = await self._native_handle()
@@ -1102,122 +866,41 @@ class Sandbox:
await handle.revoke_public_url(url if isinstance(url, str) else url.id)
def to_dict(self) -> dict[str, Any]:
- """Serialize a durable Fleet sandbox reference."""
- if self._claim_handle is None:
- raise NotImplementedError("serialization is only supported for Fleet claims")
- return self._claim_handle.to_dict()
+ """Always raises :class:`CloudEnded`: durable references were Cua Cloud
+ claims."""
+ raise CloudEnded()
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "_ConnectResult":
- """Reconnect to a serialized Fleet claim reference."""
-
- async def factory() -> "Sandbox":
- from cua_sandbox.pool import _ClaimHandle
-
- handle = _ClaimHandle.from_dict(data)
- if handle.namespace != handle.pool_name:
- raise ValueError("serialized claim does not belong to the requested pool")
- return await handle.wait()
-
- return _ConnectResult(factory)
+ """Always raises :class:`CloudEnded`: durable references were Cua Cloud
+ claims."""
+ raise CloudEnded()
async def keep_alive(self, *, minutes: float) -> None:
- """Push a Fleet claim's controller-enforced shutdown time forward."""
- if self._claim_handle is None:
- raise NotImplementedError("keep_alive is only supported for Fleet claims")
- if minutes <= 0:
- raise ValueError("minutes must be positive")
- shutdown_time = (datetime.now(timezone.utc) + timedelta(minutes=minutes)).isoformat()
- await self._claim_handle.renew(shutdown_time.replace("+00:00", "Z"))
+ """Always raises :class:`CloudEnded`: only Cua Cloud claims had a
+ shutdown time to push back."""
+ raise CloudEnded()
async def close(self) -> None:
- """Release this Fleet claim; repeated calls are safe."""
- if self._claim_released:
- return
- if self._claim_handle is None:
- raise NotImplementedError("close is only supported for Fleet claims")
- await self.driver.close()
- claim_name = self.claim_name
- try:
- await self._claim_handle.release()
- self._claim_released = True
- if claim_name is not None:
- from cua_sandbox import sandbox_state
-
- try:
- sandbox_state.delete(claim_name)
- except OSError as error:
- logger.warning("Failed to remove Fleet claim state %r: %s", claim_name, error)
- finally:
- await self.disconnect()
+ """Always raises :class:`CloudEnded`: only Cua Cloud claims were
+ released. ``destroy()`` deletes a local sandbox."""
+ raise CloudEnded()
async def snapshot(self, name: str | None = None, stateful: bool = False) -> "Image":
- """Snapshot this sandbox's current state. Returns an Image.
-
- The returned Image can be passed to Sandbox.create() or Sandbox.ephemeral()
- to boot a new sandbox from the snapshot (COW fork — instant on btrfs).
-
- Args:
- name: Optional human-readable name for the snapshot.
- stateful: Whether to capture memory state (VMs only).
-
- Returns:
- An Image with _snapshot_source set, ready to pass to Sandbox.ephemeral().
- """
- from cua_sandbox.transport.cloud import CloudTransport
-
- if not isinstance(self._transport, (CloudTransport, FleetCloudTransport)):
- raise NotImplementedError("Snapshots are only supported for cloud sandboxes")
-
- image_desc = await self._transport.create_snapshot(name=name, stateful=stateful)
- self._has_snapshots = True
- from cua_sandbox.image import Image as ImageCls
-
- # Get the original image from the transport for os_type/distro/version
- src_image = getattr(self._transport, "_image", None)
-
- # Prefer the original image's os_type/distro/version — image_desc["kind"]
- # is the snapshot kind (e.g. "vm"), not the OS type, and would misclassify
- # the image for OS-gated builder methods and compat checks.
- return ImageCls(
- os_type=src_image.os_type if src_image else image_desc.get("os_type", "linux"),
- distro=src_image.distro if src_image else image_desc.get("distro", "ubuntu"),
- version=src_image.version if src_image else image_desc.get("version", "24.04"),
- kind=src_image.kind if src_image else image_desc.get("kind"),
- _snapshot_source=image_desc,
- )
+ """Always raises :class:`CloudEnded`: snapshots were a Cua Cloud
+ feature."""
+ raise CloudEnded()
async def destroy(self) -> None:
"""Disconnect and permanently delete the sandbox (VM/container)."""
- if self._has_snapshots:
- logger.warning(
- "Destroying sandbox %s which has snapshots — "
- "forks referencing those snapshots will break. "
- "Use Sandbox.ephemeral() which auto-stops instead of deleting "
- "when snapshots exist.",
- self.name,
- )
if self.telemetry_enabled and _TELEMETRY_AVAILABLE and is_telemetry_enabled():
record_event("sandbox_destroy", {"ephemeral": self._ephemeral})
- if self._claim_handle is not None and not self._claim_released:
- # A Fleet claim (managed or explicit pool): release it; managed
- # pools themselves are reused and reclaimed by idle GC.
- try:
- await self.close()
- except Exception:
- logger.warning("Failed to release Fleet claim for sandbox %r", self.name)
- return
# Run each cleanup step independently so a failure in one
# (e.g. disconnect timeout) doesn't prevent the VM from being deleted.
try:
await self.disconnect()
except Exception:
logger.warning("Failed to disconnect transport for sandbox %r", self.name)
- if isinstance(self._transport, (CloudTransport, FleetCloudTransport)):
- try:
- await self._transport.delete_vm()
- except Exception:
- logger.warning("Failed to delete cloud VM %r", self.name)
if self._runtime and self._runtime_info:
vm_name = self._runtime_info.name or self.name or "cua-sandbox"
try:
@@ -1285,16 +968,16 @@ class Sandbox:
tools = await client.list_tools()
result = await client.call_tool("add", {"a": 2, "b": 3})
- Requests go through the sandbox's service route (loopback locally, the
- Fleet gateway in the cloud), streamed both ways, so every protocol
- feature and content block works unchanged. No cua-spacesd needed.
+ Requests go through the sandbox's service route (loopback), streamed
+ both ways, so every protocol feature and content block works
+ unchanged. No cua-spacesd needed.
"""
return _mcp.open_mcp(lambda: self._transport.native_service(service), path)
async def mcp_config(self, service: str, *, path: str = "/mcp") -> dict:
"""``{"url": ..., "headers": {...}}`` of ``service``'s MCP endpoint, for
any MCP client (Claude Code, Cursor, other SDKs). The headers can carry
- a short-lived Fleet bearer: fetch a fresh config per connection."""
+ a short-lived bearer: fetch a fresh config per connection."""
return await _mcp.mcp_config(lambda: self._transport.native_service(service), path)
async def spacesd(self) -> Any:
@@ -1360,38 +1043,35 @@ class Sandbox:
network: Optional[str] = None,
overlay: "dict[str, Any] | list | None" = None,
) -> "Sandbox":
- """Provision or claim a persistent sandbox and return it connected.
+ """Provision a persistent local sandbox and return it connected.
Where, what kind and which engine are three separate choices:
- * ``on``: ``"local"`` or ``"cloud"``. ``local=True``/``False`` is the
- same switch; ``on`` and a contradicting ``local`` is an
- :class:`InvalidArgument`, and so is ``local=True`` with ``cloud=``.
- Unset, ``cloud=`` implies the cloud; a cloud-only argument (a
- Fleet ``pool``, ``warm``, ``max_pool_size``, ``claim_ttl``,
- ``claim_spec``, ``api_key``, ...) still implies it with a
- ``DeprecationWarning``; otherwise the user default applies
- (``CUA_DEFAULT_ON``, else ``cua config set default.on cloud`` in
- ``$CUA_HOME/config.toml``, else local, with a one-time notice that
- ``CUA_QUIET_DEFAULT=1`` hides).
+ * ``on``: ``"local"``. ``local=True`` is the same switch; ``on`` and a
+ contradicting ``local`` is an :class:`InvalidArgument`. Unset, the
+ user default applies (``CUA_DEFAULT_ON``, else ``cua config set
+ default.on`` in ``$CUA_HOME/config.toml``, else local, with a
+ one-time notice that ``CUA_QUIET_DEFAULT=1`` hides). Cua Cloud has
+ ended: ``on="cloud"``, ``local=False``, ``cloud=`` and the other
+ Cua Cloud arguments (``pool``, ``claim_spec``, ``api_key``, ...)
+ raise :class:`CloudEnded`.
* ``kind``: ``"auto"``, ``"container"`` or ``"vm"``. Unset: the
image's ``kind`` when it has one, else ``default.kind``, else auto
(macOS and Windows images are VMs, a container rootfs is a
container, a disk-only image is a VM).
* ``runtime``: the engine, ``"auto"`` or one the location offers for
- the kind: locally ``"gvisor"``/``"runc"`` (containers) and
- ``"qemu"``/``"lume"`` (VMs); in the cloud ``"gvisor"`` and
- ``"kubevirt"``. Unset: ``default.runtime``, else auto. A local
- sandbox with ``sidecars`` needs ``"runc"`` where gVisor would run
+ the kind: ``"gvisor"``/``"runc"`` (containers) and
+ ``"qemu"``/``"lume"`` (VMs). Unset: ``default.runtime``, else auto.
+ A sandbox with ``sidecars`` needs ``"runc"`` where gVisor would run
(separate gVisor containers cannot share a network namespace).
A :class:`Runtime` object (``DockerRuntime()``, ``TartRuntime()``,
...) still picks a local adapter, as before.
A combination that does not exist (``kind="container",
- runtime="qemu"``, or ``runtime="kubevirt"`` locally) raises
- :class:`InvalidPlacement`, listing the valid values.
+ runtime="qemu"``) raises :class:`InvalidPlacement`, listing the valid
+ values.
- The same options mean the same thing local and in the cloud:
+ Options:
* ``command``: argv replacing the image's entrypoint.
* ``env``: environment variables.
@@ -1400,15 +1080,11 @@ class Sandbox:
``sb.tunnel.forward(8765)``.
* ``wait_for``: ``tcp("mcp")`` / ``http("mcp", "/health")`` (or a
list); readiness otherwise is "the sandbox is running".
- * ``cloud``: :class:`CloudOptions` (warm capacity, limits, TTL, a
- dedicated pool). The flat ``pool``, ``warm``, ``max_pool_size`` and
- ``claim_ttl`` keywords are deprecated aliases.
* ``memory``: ``"4GB"`` / ``"512MB"`` (or ``memory_mb``).
* ``network``: ``"default"`` (outbound network, like a Docker
container) or ``"none"`` (no egress; the SDK still reaches the
guest's published ports). ``"none"`` needs a local QEMU VM;
- containers, Lume and cloud sandboxes raise :class:`Unsupported`.
-
+ containers and Lume raise :class:`Unsupported`.
* ``overlay``: binaries to inject once it is up, so tests run the
build under test and not the copy the image bundles:
``{"cua-driver": "./target/release/cua-driver"}`` (``cua-driver`` and
@@ -1418,35 +1094,15 @@ class Sandbox:
it is restarted. If it fails, the sandbox is deleted and the error
raised. See :meth:`overlay`.
- Supplying ``pool`` claims from an existing Fleet pool without changing
- its configuration.
-
- A Fleet registry image without ``pool`` is claimed from this
- account's managed pool for that image spec (``cua-auto-*``), created
- on first use and reused afterwards. The first start of an image can
- take a few minutes; later starts reuse its capacity. Fleet-only
- options:
-
- * ``warm``: seed one ready replica when the pool is first created.
- * ``max_pool_size``: autoscaling ceiling (default 10).
- * ``claim_ttl``: seconds (or a timedelta) the claim outlives this
- process; it is renewed while the process holds it (default 15 min).
- Use ``keep_alive(minutes=...)`` to keep a sandbox longer.
- * ``progress``: callback receiving ``AcquireProgress`` events.
-
- Without ``on``/``local``, passing one of them keeps the sandbox in
- the cloud (deprecated: pass ``local=False``); with ``local=True`` they
- are ignored. An existing ``pool`` keeps its own kind and runtime
- (``Pool.apply(..., runtime=)``).
-
- ``server_port`` names a port your image serves itself: it is exposed
- (Fleet: as the ``server`` service) and becomes the readiness probe.
- Leave it unset for the default, daemon-agnostic readiness (the
- provider reports the sandbox running; cua-spacesd on 3211 is used
- by the interfaces when the image has it).
- """
- from cua_sandbox.pool import Pool
+ ``warm``, ``max_pool_size``, ``claim_ttl``, ``progress`` and
+ ``keep_alive_minutes`` configured Cua Cloud claims; a local sandbox
+ ignores them.
+ ``server_port`` names a port your image serves itself: it becomes the
+ readiness probe. Leave it unset for the default, daemon-agnostic
+ readiness (the provider reports the sandbox running; cua-spacesd on
+ 3211 is used by the interfaces when the image has it).
+ """
validate_server_port(server_port)
on, local, runtime = _apply_on(
on,
@@ -1458,7 +1114,6 @@ class Sandbox:
memory_mb=memory_mb,
time_to_start=time_to_start,
)
- asked = _requested_placement(kind, runtime)
place, image = _place_new(
image,
on=on,
@@ -1480,18 +1135,10 @@ class Sandbox:
progress=progress,
),
)
- local = place.local
# The engine (a string) and a legacy local Runtime object.
engine, runtime = place.runtime, place.legacy_runtime
network = check_network(network)
- _reject_cloud_network(network, local)
- pool, warm, max_pool_size, claim_ttl = _merge_cloud(
- cloud,
- pool=pool,
- warm=warm,
- max_pool_size=max_pool_size,
- claim_ttl=claim_ttl,
- )
+ _reject_cloud_args(pool=pool, claim_spec=claim_spec, replicas=replicas, service=service)
if memory is not None:
if memory_mb is not None:
raise ValueError("pass memory= or memory_mb=, not both")
@@ -1499,140 +1146,14 @@ class Sandbox:
wait = probes(wait_for)
services = check_services(services, wait)
- apply_template = bool(cloud is not None and cloud.apply)
- if apply_template and pool is None:
- raise ValueError("CloudOptions(apply=True) updates a named pool; pass pool= too")
- if pool is not None:
- if wait:
- raise ValueError(
- "wait_for belongs to the image's template; an existing pool keeps its own "
- "readiness (omit the pool to get a sandbox with it)"
- )
- if replicas != 1 or disk_gb is not None:
- raise ValueError("configuration cannot be supplied for an existing pool")
- pool_name = pool if isinstance(pool, str) else pool.name
- # The given sandbox fields must be the pool's template (never
- # silently ignored), or apply=True updates it.
- requested = SandboxSpec(
- image=image,
- command=command,
- env=dict(env or {}),
- services=dict(services or {}),
- cpu=cpu,
- memory_mb=memory_mb,
- sidecars=list(sidecars or ()),
- )
- if image is not None or command or env or services or sidecars or cpu or memory_mb:
- if apply_template:
- if pool_name.startswith("cua-auto-"):
- raise ValueError(
- f"{pool_name} is a managed pool (its template is its key); "
- "apply=True updates only pools you own (omit the pool to get a "
- "sandbox with these fields)"
- )
- await Pool.apply_template(pool_name, requested)
- else:
- await Pool.check(pool_name, requested)
- _reject_managed_options_for_pool(warm, max_pool_size, claim_ttl)
- if asked:
- raise ValueError(
- f"an existing pool already has its kind and runtime ({asked}); pass "
- "runtime= to Pool.apply(image, name=..., runtime=...) instead"
- )
- if (
- local
- or runtime is not None
- or api_key is not None
- or region != "us-east-1"
- or request_timeout is not None
- or server_port is not None
- ):
- raise NotImplementedError("the requested option is not supported with Fleet pools")
- resolved_pool = await Pool.get(pool) if isinstance(pool, str) else pool
- sandbox = await resolved_pool.claim(
- name=name, spec=claim_spec, service=service, time_to_start=time_to_start
- )
- sandbox_claim_name = getattr(sandbox, "claim_name", None)
- sandbox_pool_name = getattr(sandbox, "pool_name", None)
- claim_name = (
- sandbox_claim_name
- if isinstance(sandbox_claim_name, str) and sandbox_claim_name
- else name
- )
- pool_name = (
- sandbox_pool_name
- if isinstance(sandbox_pool_name, str) and sandbox_pool_name
- else resolved_pool.name
- )
- await _keep_alive_or_close(sandbox, keep_alive_minutes)
- if claim_name is not None:
- await _save_fleet_claim_or_close(sandbox, claim_name, pool_name)
- return await _with_overlays(sandbox, overlay)
-
- from cua_sandbox.image import cloud_registry_image
-
- fleet_image = (
- image is not None
- and cloud_registry_image(image) is not None
- and cls._uses_fleet(api_key)
- and not local
- and runtime is None
- )
- if fleet_image:
- assert image is not None
- _check_managed_options(
- replicas=replicas,
- claim_spec=claim_spec,
- disk_gb=disk_gb,
- region=region,
- request_timeout=request_timeout,
- )
- sandbox = await _acquire_managed(
- image,
- name=name,
- service=service,
- cpu=cpu,
- memory_mb=memory_mb,
- server_port=server_port,
- time_to_start=time_to_start,
- warm=warm,
- max_pool_size=max_pool_size,
- claim_ttl=claim_ttl,
- progress=progress,
- telemetry_enabled=telemetry_enabled,
- fleet_runtime=engine,
- command=command,
- sidecars=sidecars,
- env=env,
- services=services,
- wait_for=wait,
- hint=place.cloud_default_hint(),
- )
- await _keep_alive_or_close(sandbox, keep_alive_minutes)
- await _save_fleet_claim_or_close(
- sandbox,
- sandbox.claim_name,
- sandbox.pool_name,
- **sandbox._claim_handle.state_fields(),
- )
- return await _with_overlays(sandbox, overlay)
-
if image is None:
- raise ValueError("image is required when pool is omitted")
- if not local and engine is not None and "runtime" in asked:
- raise ValueError(
- f"runtime={engine!r} in the cloud applies to registry images only "
- "(Image.from_registry, Image.linux(), Image.windows(), Image.macos())"
- )
- if replicas != 1 or service != ENV_SERVICE or claim_spec is not None:
- raise NotImplementedError("claim options are only supported by Fleet")
+ raise ValueError("image is required")
created = await cls._create(
image=image,
name=name,
- pool=pool,
ephemeral=False,
api_key=api_key,
- local=local,
+ local=True,
runtime=runtime,
cpu=cpu,
memory_mb=memory_mb,
@@ -1649,7 +1170,6 @@ class Sandbox:
env=env,
services=services,
wait_for=wait,
- hint=place.cloud_default_hint(),
)
return await _with_overlays(created, overlay)
@@ -1677,21 +1197,20 @@ class Sandbox:
manager, ``disconnect()`` is called on exit — the sandbox keeps running.
Args:
- name: A sandbox ref (``local:<name>``, ``cloud:<name>``,
- ``direct:<host:port>``, a legacy id) or a name. A bare name
- must be unique across locations, else
- :class:`AmbiguousSandbox` lists the refs it matches.
- local: ``None`` (default): search every location. ``True``/
- ``False`` narrow a bare name to local or cloud.
+ name: A sandbox ref (``local:<name>``, ``direct:<host:port>``, a
+ legacy id) or a name. A ``cloud:<name>`` ref raises
+ :class:`CloudEnded`: Cua Cloud has ended.
+ local: ``None`` (default): the local sandbox ``name``.
+ ``False`` raises :class:`CloudEnded`.
url: A cua-spacesd URL to connect to directly
- (``http://host:3211``, a relay URL or a Fleet service URL).
+ (``http://host:3211`` or a relay URL).
token: The spacesd token for ``url``.
- api_key: Legacy CUA API key (API-key cloud VMs were removed; see
- :mod:`cua_sandbox.transport.cloud`).
+ api_key: Used as the spacesd token for ``url`` when ``token`` is
+ not given.
ws_url: Removed (the computer-server WebSocket protocol is gone).
http_url: Base URL of a cua-spacesd (same as ``url``).
container_name: Unused; kept for compatibility.
- region: Cloud region (default ``"us-east-1"``).
+ region: Unused; kept for compatibility.
Examples::
@@ -1709,18 +1228,16 @@ class Sandbox:
raise ValueError("Sandbox.connect needs a sandbox name or url=")
async def _factory() -> "Sandbox":
- # A ref decides the location; a bare name is the local sandbox
- # when one exists (and no cloud sandbox has the name too, else
- # AmbiguousSandbox), else the cloud.
- target, is_local, direct = name, bool(local), None
+ # A ref decides the location; a bare name is the local sandbox.
+ target, direct = name, None
if name and not (url or http_url):
- target, is_local, direct = await _refs.resolve(name, local)
+ target, _, direct = await _refs.resolve(name, local)
return await cls._create(
name=target if direct is None else None,
url=url or direct,
token=token,
ephemeral=False,
- local=bool(is_local),
+ local=True,
api_key=api_key,
ws_url=ws_url,
http_url=http_url,
@@ -1773,21 +1290,13 @@ class Sandbox:
memory: "str | int | None" = None,
network: Optional[str] = None,
) -> AsyncIterator["Sandbox"]:
- """A sandbox that is released when the ``async with`` block exits.
+ """A local sandbox that is deleted when the ``async with`` block exits.
Takes the same ``on``/``local``, ``kind``, ``runtime``, ``command``,
``env``, ``services``, ``wait_for``, ``cloud``, ``memory`` and
- ``network`` options as :meth:`create`.
-
- A Fleet registry image without ``pool`` is claimed from this
- account's reusable managed pool (see :meth:`create` for ``warm``,
- ``max_pool_size``, ``claim_ttl`` and ``progress``). Exiting releases
- the claim; the pool stays for the next run and idle GC deletes it
- once unused. If the process dies, the claim expires after
- ``claim_ttl``. ``keep_pool`` is deprecated and has no effect.
+ ``network`` options as :meth:`create`. ``keep_pool`` is deprecated and
+ has no effect.
"""
- from cua_sandbox.image import cloud_registry_image
-
on, local, runtime = _apply_on(
on,
local,
@@ -1798,7 +1307,6 @@ class Sandbox:
memory_mb=memory_mb,
time_to_start=time_to_start,
)
- asked = _requested_placement(kind, runtime)
place, image = _place_new(
image,
on=on,
@@ -1820,137 +1328,25 @@ class Sandbox:
progress=progress,
),
)
- local = place.local
# The engine (a string) and a legacy local Runtime object.
engine, runtime = place.runtime, place.legacy_runtime
network = check_network(network)
- _reject_cloud_network(network, local)
- pool, warm, max_pool_size, claim_ttl = _merge_cloud(
- cloud,
- pool=pool,
- warm=warm,
- max_pool_size=max_pool_size,
- claim_ttl=claim_ttl,
- )
+ _reject_cloud_args(pool=pool, claim_spec=claim_spec, replicas=replicas, service=service)
if memory is not None:
if memory_mb is not None:
raise ValueError("pass memory= or memory_mb=, not both")
memory_mb = parse_memory(memory)
wait = probes(wait_for)
services = check_services(services, wait)
- custom = bool(command) or bool(env) or bool(services) or bool(wait) or bool(sidecars)
-
- fleet_image = (
- image is not None
- and cloud_registry_image(image) is not None
- and cls._uses_fleet(api_key)
- and not local
- and runtime is None
- )
- if keep_pool:
- warnings.warn(
- "keep_pool is deprecated and has no effect: managed Fleet pools are "
- "reused automatically and deleted by idle GC once unused",
- DeprecationWarning,
- stacklevel=3,
- )
- if asked and pool is not None:
- raise ValueError(
- f"an existing pool already has its kind and runtime ({asked}); pass "
- "runtime= to Pool.apply(image, name=..., runtime=...) instead"
- )
- if not local and "runtime" in asked and not fleet_image:
- raise ValueError(
- f"runtime={engine!r} in the cloud applies to registry images only "
- "(Image.from_registry, Image.linux(), Image.windows(), Image.macos())"
- )
-
- if pool is not None:
- if custom:
- raise ValueError(
- "command, env, services, sidecars and wait_for belong to the image's "
- "template; an existing pool keeps its own (omit the pool to get a sandbox "
- "with them)"
- )
- _reject_managed_options_for_pool(warm, max_pool_size, claim_ttl)
- sandbox = await cls.create(
- image,
- cloud=CloudOptions(pool=pool),
- name=name,
- replicas=replicas,
- service=service,
- claim_spec=claim_spec,
- keep_alive_minutes=keep_alive_minutes,
- api_key=api_key,
- local=local,
- runtime=runtime,
- cpu=cpu,
- memory_mb=memory_mb,
- disk_gb=disk_gb,
- region=region,
- time_to_start=time_to_start,
- request_timeout=request_timeout,
- server_port=server_port,
- telemetry_enabled=telemetry_enabled,
- )
- try:
- yield sandbox
- except BaseException:
- await _cleanup_ephemeral_fleet(sandbox, None, suppress_errors=True)
- raise
- else:
- await _cleanup_ephemeral_fleet(sandbox, None, suppress_errors=False)
- return
-
- if fleet_image:
- assert image is not None
- _check_managed_options(
- replicas=replicas,
- claim_spec=claim_spec,
- disk_gb=disk_gb,
- region=region,
- request_timeout=request_timeout,
- )
- sandbox = await _acquire_managed(
- image,
- name=name,
- service=service,
- cpu=cpu,
- memory_mb=memory_mb,
- server_port=server_port,
- time_to_start=time_to_start,
- warm=warm,
- max_pool_size=max_pool_size,
- claim_ttl=claim_ttl,
- progress=progress,
- telemetry_enabled=telemetry_enabled,
- ephemeral=True,
- fleet_runtime=engine,
- command=command,
- sidecars=sidecars,
- env=env,
- services=services,
- wait_for=wait,
- hint=place.cloud_default_hint(),
- )
- await _keep_alive_or_close(sandbox, keep_alive_minutes)
- try:
- yield sandbox
- except BaseException:
- await _cleanup_ephemeral_fleet(sandbox, None, suppress_errors=True)
- raise
- else:
- await _cleanup_ephemeral_fleet(sandbox, None, suppress_errors=False)
- return
if image is None:
- raise ValueError("image is required when pool is omitted")
+ raise ValueError("image is required")
sandbox = await cls._create(
image=image,
name=name,
ephemeral=True,
api_key=api_key,
- local=local,
+ local=True,
runtime=runtime,
cpu=cpu,
memory_mb=memory_mb,
@@ -1967,15 +1363,11 @@ class Sandbox:
env=env,
services=services,
wait_for=wait,
- hint=place.cloud_default_hint(),
)
try:
yield sandbox
finally:
- if sandbox._has_snapshots and sandbox.name:
- await cls.suspend(sandbox.name, local=local, api_key=api_key)
- else:
- await sandbox.destroy()
+ await sandbox.destroy()
# ── Lifecycle management ─────────────────────────────────────────────
@@ -1988,26 +1380,20 @@ class Sandbox:
all: Optional[bool] = None, # noqa: A002 - deprecated
api_key: Optional[str] = None,
) -> "list[SandboxInfo]":
- """List sandboxes, each with its ``location``, ``kind`` and
- ``runtime``: local and cloud ones by default.
+ """List the local sandboxes (containers, QEMU, Lume, Android), each
+ with its ``location``, ``kind`` and ``runtime``.
Args:
- location: ``None`` (default): local and cloud. ``"local"``: only
- the local ones (containers, QEMU, Lume, Android).
- ``"cloud"``: only the cloud ones.
+ location: ``None`` (default) or ``"local"``: the local sandboxes.
+ ``"cloud"`` raises :class:`CloudEnded`: Cua Cloud has ended.
local: The same switch as a bool (``True`` is ``"local"``,
``False`` is ``"cloud"``).
all: Deprecated; everything is the default.
- api_key: Legacy CUA API key for api.cua.ai VMs.
-
- The cloud part never fails the default listing: without cloud
- credentials it is left out silently, and when the cloud fails or does
- not answer within 5 s the local rows come back with a logged warning
- ("cloud sandboxes not listed: ...").
+ api_key: Unused; kept for compatibility.
"""
if all is not None:
warnings.warn(
- "Sandbox.list(all=...) is deprecated: local and cloud is the default",
+ "Sandbox.list(all=...) is deprecated: everything is the default",
DeprecationWarning,
stacklevel=2,
)
@@ -2016,49 +1402,15 @@ class Sandbox:
if location is not None:
where = str(location).strip().lower()
if where not in _placement.LOCATIONS:
- raise InvalidArgument(
- f"location={location!r}: cua-sandbox lists 'local' and 'cloud' sandboxes"
- )
+ raise InvalidArgument(f"location={location!r}: cua-sandbox lists 'local' sandboxes")
if local is not None and (where == "local") != bool(local):
raise InvalidArgument(
f"location={location!r} and local={local!r} contradict each other"
)
local = where == "local"
- if local is True:
- return await cls._list_local()
if local is False:
- return await cls._list_cloud(api_key=api_key)
- rows = await cls._list_local()
- # Cua Cloud has ended (CUA-1854): the default listing is local only.
- return rows
- from cua_sandbox._config import (
- get_api_key,
- has_fleet_auth,
- may_have_fleet_session,
- )
-
- if not (api_key or has_fleet_auth() or get_api_key() or may_have_fleet_session()):
- # No cloud credentials that can be read without the OS keychain:
- # nothing to list in the cloud (``local=False`` also uses a
- # keychain session).
- return rows
- try:
- cloud = await asyncio.wait_for(
- cls._list_cloud(api_key=api_key), timeout=_LIST_CLOUD_TIMEOUT
- )
- except asyncio.TimeoutError:
- logger.warning(
- "cloud sandboxes not listed: the cloud did not answer within %ss",
- int(_LIST_CLOUD_TIMEOUT),
- )
- cloud = []
- except Exception as error: # noqa: BLE001 - the cloud never fails the listing
- if "credentials missing" not in str(error).lower():
- logger.warning("cloud sandboxes not listed: %s", error)
- cloud = []
- # One row per ref: a local and a cloud sandbox may share a name.
- ids = {r.id for r in rows}
- return rows + [r for r in cloud if r.id not in ids]
+ raise CloudEnded()
+ return await cls._list_local()
@classmethod
async def _list_local(cls) -> "list[SandboxInfo]":
@@ -2137,93 +1489,6 @@ class Sandbox:
)
return results
- @staticmethod
- def _uses_fleet(api_key: Optional[str]) -> bool:
- """Fleet for every call without an explicit (legacy) API key: with
- client credentials or a token, else the ``cua auth login`` session;
- with neither, the Fleet path raises "Fleet credentials missing"."""
- if api_key is not None:
- return False
- if has_fleet_access():
- return True
- from cua_sandbox._config import get_api_key
-
- # A legacy api.cua.ai key only lists/deletes old VMs; without one
- # (and without Fleet credentials) Fleet explains what to configure.
- return get_api_key() is None
-
- @classmethod
- async def _list_cloud(cls, *, api_key: Optional[str] = None) -> "list[SandboxInfo]":
- raise CloudEnded()
- if not cls._uses_fleet(api_key):
- from cua_sandbox.transport.cloud import cloud_list_vms
-
- vms = await cloud_list_vms(api_key=api_key)
- return [
- SandboxInfo(
- location="cloud",
- id=_refs.qualified("cloud", vm.get("name", "")),
- name=vm.get("name", ""),
- status=vm.get("status", "unknown"),
- source="cloud",
- os_type=vm.get("os_type") or vm.get("os"),
- created_at=vm.get("created_at"),
- )
- for vm in vms
- ]
-
- from cua_sandbox import _autopool
-
- # Every claim in every pool this account can see: managed
- # (cua-auto-*) and explicit pools alike.
- claims = await _autopool.list_claims()
- return [cls._fleet_claim_info(claim) for claim in claims]
-
- @staticmethod
- def _fleet_claim_info(claim: Any) -> SandboxInfo:
- phase = (claim.phase or "").lower()
- status = {"bound": "running", "pending": "provisioning", "": "provisioning"}.get(
- phase, phase
- )
- return SandboxInfo(
- name=claim.name,
- status=status,
- source="fleet",
- created_at=claim.created_at,
- id=_refs.qualified("cloud", claim.name),
- location="cloud",
- provider_details={"pool": claim.pool, "namespace": claim.pool},
- )
-
- @staticmethod
- def _fleet_sandbox_info(pool: Any) -> SandboxInfo:
- if isinstance(pool, Mapping):
- metadata = pool.get("metadata") or {}
- spec = pool.get("spec") or {}
- status = pool.get("status") or {}
- name = metadata.get("name", "")
- replicas = spec.get("replicas", 1)
- ready = status.get("readyReplicas", 0)
- created_at = metadata.get("creationTimestamp")
- else:
- metadata = pool.metadata
- spec = pool.spec
- status = pool.status
- name = metadata.name
- replicas = spec.replicas
- ready = status.ready_replicas if status else 0
- created_at = metadata.creation_timestamp
- state = "suspended" if replicas == 0 else "running" if ready else "provisioning"
- return SandboxInfo(
- name=name,
- status=state,
- source="fleet",
- created_at=created_at,
- id=_refs.qualified("cloud", name),
- location="cloud",
- provider_details={"pool": name},
- )
-
@classmethod
async def get_info(
cls,
@@ -2235,64 +1500,37 @@ class Sandbox:
"""Get metadata for a specific sandbox.
Args:
- name: Sandbox ref (``local:<name>``, ``cloud:<name>``) or a name
- unique across locations.
- local: ``True``/``False`` narrow a bare name to local or cloud.
- ``None`` (default): the local sandbox ``name`` when one
- exists (and no cloud sandbox shares it), else the cloud.
- api_key: CUA API key for cloud.
+ name: Sandbox ref (``local:<name>``) or a name. A ``cloud:<name>``
+ ref raises :class:`CloudEnded`: Cua Cloud has ended.
+ local: ``None`` (default) or ``True``: the local sandbox ``name``.
+ ``False`` raises :class:`CloudEnded`.
+ api_key: Unused; kept for compatibility.
"""
- name, local = await _lookup(name, local)
- if local:
- sandboxes = await cls._list_local()
- match = next((s for s in sandboxes if s.name == name), None)
- if match:
- return match
- # Fall back to state file
- from cua_sandbox import sandbox_state
-
- state = sandbox_state.load(name)
- if state:
- location = "cloud" if state.get("runtime_type") == "fleet" else "local"
- return SandboxInfo(
- location=location,
- id=_refs.qualified(location, name),
- name=name,
- status=state.get("status", "unknown"),
- source=state.get("runtime_type", "unknown"),
- os_type=state.get("os_type"),
- host=state.get("host"),
- api_url=(
- f"http://{state['host']}:{state['api_port']}"
- if state.get("host") and state.get("api_port")
- else None
- ),
- )
- raise ValueError(f"Local sandbox '{name}' not found.")
- if not cls._uses_fleet(api_key):
- from cua_sandbox.transport.cloud import cloud_get_vm
+ name, _ = await _lookup(name, local)
+ sandboxes = await cls._list_local()
+ match = next((s for s in sandboxes if s.name == name), None)
+ if match:
+ return match
+ # Fall back to state file
+ from cua_sandbox import sandbox_state
- vm = await cloud_get_vm(name, api_key=api_key)
+ state = sandbox_state.load(name)
+ if state:
return SandboxInfo(
- location="cloud",
- id=_refs.qualified("cloud", vm.get("name", name)),
- name=vm.get("name", name),
- status=vm.get("status", "unknown"),
- source="cloud",
- os_type=vm.get("os_type") or vm.get("os"),
- created_at=vm.get("created_at"),
+ location="local",
+ id=_refs.qualified("local", name),
+ name=name,
+ status=state.get("status", "unknown"),
+ source=state.get("runtime_type", "unknown"),
+ os_type=state.get("os_type"),
+ host=state.get("host"),
+ api_url=(
+ f"http://{state['host']}:{state['api_port']}"
+ if state.get("host") and state.get("api_port")
+ else None
+ ),
)
- from cua_sandbox import sandbox_state
-
- state = sandbox_state.load(name) or {}
- if state.get("runtime_type") == "fleet" and state.get("pool_name"):
- from cua_sandbox import _autopool
-
- for claim in await _autopool.list_claims():
- if claim.name == name and claim.pool == state["pool_name"]:
- return cls._fleet_claim_info(claim)
- raise ValueError(f"Fleet sandbox {name!r} not found in pool {state['pool_name']!r}")
- return cls._fleet_sandbox_info(await FleetCloudTransport.get_sandbox_info(name))
+ raise ValueError(f"Local sandbox '{name}' not found.")
@classmethod
async def suspend(
@@ -2302,31 +1540,21 @@ class Sandbox:
local: Optional[bool] = None,
api_key: Optional[str] = None,
) -> None:
- """Suspend the sandbox ``name``, keeping its state; :meth:`resume`
- continues it. Only that sandbox is affected.
+ """Suspend the local sandbox ``name``, keeping its state;
+ :meth:`resume` continues it. Only that sandbox is affected.
- Local: the SDK suspends it on its backend (a container is paused or
+ The SDK suspends it on its backend (a container is paused or
checkpointed, a QEMU VM snapshotted, a Lume VM stopped with its
- disk). Cloud: a Fleet sandbox cannot be suspended on its own, so this
- raises :class:`Unsupported`; keep it with ``keep_alive()`` or release
- it with :meth:`delete`. A legacy api.cua.ai VM (an API key) stops.
+ disk).
Args:
name: Sandbox name.
- local: ``None`` (default): the local sandbox ``name`` when one
- exists, else the cloud. ``True``/``False`` decide.
- api_key: Legacy CUA API key (api.cua.ai VMs).
+ local: ``None`` (default) or ``True``: the local sandbox ``name``.
+ ``False`` raises :class:`CloudEnded`: Cua Cloud has ended.
+ api_key: Unused; kept for compatibility.
"""
- name, local = await _lookup(name, local)
- if local:
- await cls._suspend_local(name)
- return
- if not cls._uses_fleet(api_key):
- from cua_sandbox.transport.cloud import cloud_vm_action
-
- await cloud_vm_action(name, "stop", api_key=api_key)
- return
- raise _fleet_lifecycle_unsupported(name, "suspend")
+ name, _ = await _lookup(name, local)
+ await cls._suspend_local(name)
@classmethod
async def _suspend_local(cls, name: str) -> None:
@@ -2361,37 +1589,20 @@ class Sandbox:
local: Optional[bool] = None,
api_key: Optional[str] = None,
) -> "Sandbox":
- """Resume the suspended sandbox ``name`` and return it connected.
-
- Local: the backend resumes it. Cloud: a running sandbox just
- reconnects (a Fleet sandbox is never suspended); one that is gone
- raises :class:`Unsupported`. A legacy api.cua.ai VM (an API key)
- starts.
+ """Resume the suspended local sandbox ``name`` and return it
+ connected. The backend resumes it.
Args:
name: Sandbox name.
- local: ``None`` (default): the local sandbox ``name`` when one
- exists, else the cloud.
- api_key: Legacy CUA API key (api.cua.ai VMs).
+ local: ``None`` (default) or ``True``: the local sandbox ``name``.
+ ``False`` raises :class:`CloudEnded`: Cua Cloud has ended.
+ api_key: Unused; kept for compatibility.
Returns:
A connected Sandbox ready to use.
"""
- name, local = await _lookup(name, local)
- if local:
- return await cls._resume_local(name)
- if not cls._uses_fleet(api_key):
- from cua_sandbox.transport.cloud import cloud_vm_action
-
- await cloud_vm_action(name, "run", api_key=api_key)
- else:
- try:
- return await cls._create(name=name, ephemeral=False, api_key=api_key)
- except Exception as error: # noqa: BLE001 - re-raised typed
- raise _fleet_lifecycle_unsupported(name, "resume") from error
- # Connect to the now-running cloud sandbox.
- sb = await cls._create(name=name, ephemeral=False, api_key=api_key)
- return sb
+ name, _ = await _lookup(name, local)
+ return await cls._resume_local(name)
@classmethod
async def _resume_local(cls, name: str) -> "Sandbox":
@@ -2444,31 +1655,21 @@ class Sandbox:
local: Optional[bool] = None,
api_key: Optional[str] = None,
) -> "Sandbox":
- """Restart the sandbox ``name`` (suspend then resume) and return it
- connected. Local only (see :meth:`suspend`): a Fleet sandbox raises
- :class:`Unsupported`.
+ """Restart the local sandbox ``name`` (suspend then resume) and return
+ it connected (see :meth:`suspend`).
Args:
name: Sandbox name.
- local: ``None`` (default): the local sandbox ``name`` when one
- exists, else the cloud.
- api_key: Legacy CUA API key (api.cua.ai VMs).
+ local: ``None`` (default) or ``True``: the local sandbox ``name``.
+ ``False`` raises :class:`CloudEnded`: Cua Cloud has ended.
+ api_key: Unused; kept for compatibility.
Returns:
A connected Sandbox ready to use.
"""
- name, local = await _lookup(name, local)
- if local:
- await cls._suspend_local(name)
- return await cls._resume_local(name)
- if not cls._uses_fleet(api_key):
- from cua_sandbox.transport.cloud import cloud_vm_action
-
- await cloud_vm_action(name, "restart", api_key=api_key)
- else:
- raise _fleet_lifecycle_unsupported(name, "restart")
- sb = await cls._create(name=name, ephemeral=False, api_key=api_key)
- return sb
+ name, _ = await _lookup(name, local)
+ await cls._suspend_local(name)
+ return await cls._resume_local(name)
@classmethod
async def delete(
@@ -2478,33 +1679,17 @@ class Sandbox:
local: Optional[bool] = None,
api_key: Optional[str] = None,
) -> None:
- """Permanently delete a sandbox.
-
- For local sandboxes, stops the VM and removes the state file.
- For cloud sandboxes, calls DELETE /v1/vms/{name}.
+ """Permanently delete a local sandbox: stops the VM or container and
+ removes the state file.
Args:
name: Sandbox name.
- local: If True, delete a local sandbox. ``None`` (default): the
- local sandbox ``name`` when one exists, else the cloud.
- api_key: CUA API key for cloud.
+ local: ``None`` (default) or ``True``: the local sandbox ``name``.
+ ``False`` raises :class:`CloudEnded`: Cua Cloud has ended.
+ api_key: Unused; kept for compatibility.
"""
- name, local = await _lookup(name, local)
- if local:
- await cls._delete_local(name)
- return
- if not cls._uses_fleet(api_key):
- from cua_sandbox.transport.cloud import cloud_vm_action
-
- await cloud_vm_action(name, "delete", api_key=api_key)
- return
- from cua_sandbox import sandbox_state
-
- state = sandbox_state.load(name)
- pool_name = state.get("pool_name") if state else None
- await FleetCloudTransport.delete_sandbox(name, pool_name=pool_name)
- if pool_name:
- sandbox_state.delete(name)
+ name, _ = await _lookup(name, local)
+ await cls._delete_local(name)
@classmethod
async def _delete_local(cls, name: str) -> None:
@@ -2549,9 +1734,8 @@ class Sandbox:
api_key: Optional[str] = None,
container_name: Optional[str] = None,
image: Optional[Image] = None,
- runtime: Optional["Runtime | FleetRuntime"] = None,
+ runtime: Optional["Runtime"] = None,
name: Optional[str] = None,
- pool: Optional[str] = None,
ephemeral: Optional[bool] = None,
cpu: Optional[int] = None,
memory_mb: Optional[int] = None,
@@ -2561,10 +1745,6 @@ class Sandbox:
request_timeout: Optional[float] = None,
server_port: Optional[int] = None,
telemetry_enabled: bool = True,
- warm: Optional[bool] = None,
- max_pool_size: Optional[int] = None,
- claim_ttl: Any = None,
- progress: Optional[Callable[[Any], Any]] = None,
command: Optional[list[str]] = None,
sidecars: Optional[list] = None,
engine: Optional[str] = None,
@@ -2572,25 +1752,16 @@ class Sandbox:
env: Optional[dict[str, str]] = None,
services: Optional[dict[str, int]] = None,
wait_for: Optional[list[Probe]] = None,
- hint: Optional[str] = None,
) -> "Sandbox":
"""Internal factory that validates server_port before selecting a transport.
``runtime`` is a legacy local :class:`Runtime` object; ``engine`` the
engine name the placement resolved (``gvisor``, ``qemu``, ...), with
- ``image.kind`` already set to the resolved kind. ``hint`` is added to
- a missing-credentials error when the cloud came from a user default.
+ ``image.kind`` already set to the resolved kind.
"""
validate_server_port(server_port)
auto_adapter = runtime is None
- if image is not None and pool is not None:
- raise ValueError("Specify exactly one of image or pool")
- if pool and not name:
- raise ValueError("Pool-backed sandboxes require a name")
- if pool and local:
- raise ValueError("Pool-backed sandboxes are cloud-only")
-
_t_start = time.monotonic()
if ephemeral is None:
ephemeral = bool(image)
@@ -2655,103 +1826,20 @@ class Sandbox:
_record_sandbox_create(sb, image=None, local=local, ephemeral=False, t_start=_t_start)
return sb
- if not local and not (image and runtime):
- # Cua Cloud has ended (CUA-1854): a pool claim, a cloud create
- # and a connect by cloud name all stop here.
+ if not local:
+ # Cua Cloud has ended (CUA-1854): a cloud create and a connect by
+ # cloud name stop here.
raise CloudEnded()
- if pool:
- transport = FleetCloudTransport(
- image=None,
- name=name,
- pool_name=pool,
- create_claim=True,
- region=region,
- time_to_start=time_to_start,
- request_timeout=request_timeout,
- server_port=server_port,
- )
- sb = cls(transport, name=name, _ephemeral=False, _telemetry_enabled=telemetry_enabled)
- await sb._connect()
- from cua_sandbox import sandbox_state
-
- sandbox_state.save_fleet_claim(name, pool)
- _record_sandbox_create(sb, image=None, local=False, ephemeral=False, t_start=_t_start)
- return sb
-
- if image and not runtime and local:
+ if image and not runtime:
# local=True with no runtime → auto-select based on image type
runtime = _auto_runtime(
image, cpu=cpu, memory_mb=memory_mb, server_port=server_port, engine=engine
)
- if image and not runtime and not local:
- # image without runtime and not local → cloud creation
- _reject_cloud_network(network, False)
- if not any([ws_url, http_url]) and cls._uses_fleet(api_key):
- # Claimed from the account's managed pool for this image.
- _check_managed_options(
- replicas=1,
- claim_spec=None,
- disk_gb=disk_gb,
- region=region,
- request_timeout=request_timeout,
- )
- sb = await _acquire_managed(
- image,
- name=name,
- service=ENV_SERVICE,
- cpu=cpu,
- memory_mb=memory_mb,
- server_port=server_port,
- time_to_start=time_to_start,
- warm=warm,
- max_pool_size=max_pool_size,
- claim_ttl=claim_ttl,
- progress=progress,
- telemetry_enabled=telemetry_enabled,
- ephemeral=bool(ephemeral),
- fleet_runtime=engine,
- command=command,
- sidecars=sidecars,
- env=env,
- services=services,
- wait_for=wait_for,
- hint=hint,
- )
- if not ephemeral:
- await _save_fleet_claim_or_close(
- sb, sb.claim_name, sb.pool_name, **sb._claim_handle.state_fields()
- )
- return sb
- if not any([ws_url, http_url]):
- if command or env or services or wait_for or sidecars:
- raise NotImplementedError(
- "command, env, services, sidecars and wait_for need a cloud sandbox (Fleet "
- "credentials: `cua auth login` or CUA_CLIENT_ID/CUA_CLIENT_SECRET) "
- "or local=True"
- )
- transport = _make_transport(
- api_key=api_key,
- image=image,
- name=name,
- cpu=cpu,
- memory_mb=memory_mb,
- disk_gb=disk_gb,
- region=region,
- )
- sb = cls(
- transport, name=name, _ephemeral=ephemeral, _telemetry_enabled=telemetry_enabled
- )
- await sb._connect()
- _record_sandbox_create(
- sb, image=image, local=False, ephemeral=bool(ephemeral), t_start=_t_start
- )
- return sb
- runtime = _auto_runtime(image, cpu=cpu, memory_mb=memory_mb, server_port=server_port)
if image and runtime:
sb_name = name or _random_name()
# 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.
+ # local VM honours cpu= and memory_mb=.
start_opts: dict = {}
if cpu is not None:
start_opts["cpu_count"] = cpu
@@ -2775,7 +1863,7 @@ class Sandbox:
wait_for=list(wait_for or []),
sidecars=list(sidecars or []),
)
- if auto_adapter and local and _sdk_backed(runtime):
+ if auto_adapter and _sdk_backed(runtime):
# The adapter was picked from the placement: the SDK gets the
# kind and engine too (and checks them against the image).
if image.kind:
@@ -2855,39 +1943,15 @@ class Sandbox:
)
else:
if ws_url:
- _make_transport(ws_url=ws_url) # raises: the WebSocket protocol is gone
- if name and cls._uses_fleet(api_key):
- from cua_sandbox import sandbox_state
-
- state = sandbox_state.load(name)
- pool_name = state.get("pool_name") if state else None
- osworld = bool(state) and state.get("agent_type") == "osworld"
- transport_cls = OSWorldFleetCloudTransport if osworld else FleetCloudTransport
- transport = transport_cls(
- image=None,
- name=name,
- pool_name=pool_name,
- cpu=cpu,
- memory_mb=memory_mb,
- disk_gb=disk_gb,
- region=region,
- **({"server_port": OSWORLD_SERVER_PORT} if osworld else {}),
- )
- else:
- transport = _make_transport(
- ws_url=ws_url,
- http_url=http_url,
- api_key=api_key,
- container_name=container_name,
- name=name,
- cpu=cpu,
- memory_mb=memory_mb,
- disk_gb=disk_gb,
- region=region,
+ raise ValueError(
+ "ws_url= spoke the computer-server WebSocket protocol, which was removed. "
+ "Connect to the sandbox's cua-spacesd instead: "
+ "Sandbox.connect(url='http://host:3211', token=...)"
)
+ raise ValueError("a sandbox needs an image, a name or a url")
# Write persistent state for local (non-ephemeral) sandboxes. Runtimes
# on the cua SDK persisted it themselves, in the same format.
- if not ephemeral and rt_info and local and rt_info.native is None:
+ if not ephemeral and rt_info and rt_info.native is None:
from cua_sandbox import sandbox_state
runtime_type = type(runtime).__name__.lower().replace("runtime", "")
@@ -3153,44 +2217,6 @@ def _random_name() -> str:
return f"{random.choice(_ADJECTIVES)}-{random.choice(_NOUNS)}"
-def _make_transport(
- *,
- ws_url: Optional[str] = None,
- http_url: Optional[str] = None,
- api_key: Optional[str] = None,
- container_name: Optional[str] = None,
- image: Optional[Image] = None,
- name: Optional[str] = None,
- cpu: Optional[int] = None,
- memory_mb: Optional[int] = None,
- disk_gb: Optional[int] = None,
- region: str = "us-east-1",
-) -> Transport:
- """Transport for a non-Fleet, non-local target.
-
- ``http_url`` names a cua-spacesd; ``ws_url`` (the computer-server
- WebSocket protocol) is gone; with neither, the legacy API-key cloud shim
- is returned (it explains the move to Fleet on connect).
- """
- if ws_url:
- raise ValueError(
- "ws_url= spoke the computer-server WebSocket protocol, which was removed. "
- "Connect to the sandbox's cua-spacesd instead: "
- "Sandbox.connect(url='http://host:3211', token=...)"
- )
- if http_url:
- return EnvTransport(url=http_url, token=api_key)
- return CloudTransport(
- name=name,
- api_key=api_key,
- image=image,
- cpu=cpu,
- memory_mb=memory_mb,
- disk_gb=disk_gb,
- region=region,
- )
-
-
def _fallback_transport(
host: str,
*,
@@ -3333,7 +2359,7 @@ async def sandbox(
Prefer ``Sandbox.create()``, ``Sandbox.connect()``, or
``Sandbox.ephemeral()`` instead.
"""
- engine, hint = None, None
+ engine = None
if image is not None and not (url or http_url or ws_url):
# A new sandbox: the same placement rules as Sandbox.create.
on, local, runtime = _apply_on(on, local, runtime, cpu=cpu, memory_mb=memory_mb)
@@ -3354,7 +2380,6 @@ async def sandbox(
),
)
local, engine, runtime = place.local, place.runtime, place.legacy_runtime
- hint = place.cloud_default_hint()
elif on is not None:
local = _placement.resolve(on=on, local=local).local
sb = await Sandbox._create(
@@ -3373,12 +2398,7 @@ async def sandbox(
memory_mb=memory_mb,
disk_gb=disk_gb,
region=region,
- warm=warm,
- max_pool_size=max_pool_size,
- claim_ttl=claim_ttl,
- progress=progress,
engine=engine,
- hint=hint,
)
try:
yield sb
diff --git a/libs/python/cua-sandbox/cua_sandbox/sandbox_state.py b/libs/python/cua-sandbox/cua_sandbox/sandbox_state.py
index 02a6a5e035..6ac3efdb3a 100644
--- a/libs/python/cua-sandbox/cua_sandbox/sandbox_state.py
+++ b/libs/python/cua-sandbox/cua_sandbox/sandbox_state.py
@@ -1,8 +1,9 @@
-"""Persistent state tracking for local sandboxes and Fleet claims.
+"""Persistent state tracking for local sandboxes.
-Each running local sandbox or named Fleet claim writes a JSON file at
-``$CUA_HOME/sandboxes/{name}.json`` (default ``~/.cua/sandboxes``). This lets later connect and delete commands route
-to the original runtime or pre-created Fleet pool across process restarts.
+Each running local sandbox writes a JSON file at
+``$CUA_HOME/sandboxes/{name}.json`` (default ``~/.cua/sandboxes``). This lets
+later connect and delete commands route to the original runtime across process
+restarts.
Ephemeral sandboxes never write state files.
"""
@@ -118,23 +119,3 @@ def list_all() -> list[dict]:
except (json.JSONDecodeError, OSError):
pass
return result
-
-
-def save_fleet_claim(name: str, pool_name: str, **extra: Any) -> None:
- """Persist the pool association for a named Fleet claim.
-
- Claims on managed pools also record ``managed=True``, the pool's
- ``spec_hash`` and the ``claim_ttl`` they were created with.
- """
- guard_write(_state_path(name))
- state_dir().mkdir(parents=True, exist_ok=True)
- data: dict[str, Any] = {
- "name": name,
- "runtime_type": "fleet",
- "pool_name": pool_name,
- "status": "running",
- "created_at": datetime.now(timezone.utc).isoformat(),
- **extra,
- }
- guard_write(_state_path(name))
- _state_path(name).write_text(json.dumps(data, indent=2))
diff --git a/libs/python/cua-sandbox/cua_sandbox/spec.py b/libs/python/cua-sandbox/cua_sandbox/spec.py
index 7c7d197fa6..d3c6da6bb4 100644
--- a/libs/python/cua-sandbox/cua_sandbox/spec.py
+++ b/libs/python/cua-sandbox/cua_sandbox/spec.py
@@ -1,85 +1,54 @@
-"""One sandbox model for pools and ``Sandbox.create``.
-
-:class:`SandboxSpec` is what a sandbox runs (image, process, services,
-readiness, resources, sidecars, registry secret, process mode, claim
-secrets) and :class:`PoolOptions` how a pool keeps capacity for it (warm
-floor, size, idle TTL, TTL policy, claim TTL, runtime). Both convert to the
-cua SDK's native records, and ``Pool.apply(name, spec, options)`` writes a
-pool through the SDK's one pool writer (``Fleet.apply``), the same code the
-Rust core, the other language bindings and the ``cua`` CLI use.
+"""Pool and sandbox spec types, retired with Cua Cloud.
+
+Cua Cloud has ended, so there are no pools: every ``Pool`` call raises
+:class:`~cua_sandbox._ended.CloudEnded`. The data classes and errors stay
+importable so existing code keeps importing; the module goes away in the next
+minor release.
"""
from __future__ import annotations
+import secrets
from dataclasses import dataclass, field
from datetime import timedelta
from typing import Any, Optional, Sequence, Union
-from cua_sandbox._sdk import InvalidArgument, native
+from cua_sandbox._sdk import InvalidArgument
Seconds = Union[int, float, timedelta, None]
class PoolSpecMismatch(InvalidArgument):
"""A named cloud pool's template differs from the sandbox fields given
- with it. The message holds a readable diff; pass
- ``CloudOptions(pool=..., apply=True)`` to update the pool's template
- instead, or omit the fields to use the pool as it is."""
+ with it. Pools belonged to Cua Cloud, which has ended; nothing raises this
+ any more."""
class ClaimSecretsNotDelivered(TimeoutError):
"""A claim bound, but its per-claim secrets (the env token) never reached
- the sandbox within the bounded wait (90 s); the claim was released."""
-
-
-def translate_native_error(error: BaseException) -> BaseException:
- """The cua-sandbox exception for a native ``CuaError`` (the error itself
- when it has no dedicated type)."""
- try:
- n = native()
- except ImportError: # pragma: no cover - packaging error
- return error
- if isinstance(error, n.CuaError.PoolSpecMismatch):
- return PoolSpecMismatch(str(error))
- if isinstance(error, n.CuaError.ClaimSecretsNotDelivered):
- return ClaimSecretsNotDelivered(str(error))
- ambiguous = getattr(n.CuaError, "AmbiguousSandbox", None)
- if ambiguous is not None and isinstance(error, ambiguous):
- from cua_sandbox._refs import AmbiguousSandbox
-
- candidates = list(n.ambiguous_sandbox_candidates(str(error)))
- name = candidates[0].split(":", 1)[-1] if candidates else ""
- return AmbiguousSandbox(name, candidates)
- return error
-
-
-def _seconds(value: Seconds, name: str) -> Optional[int]:
- if value is None:
- return None
- if isinstance(value, timedelta):
- value = value.total_seconds()
- if isinstance(value, bool) or not isinstance(value, (int, float)) or value < 0:
- raise ValueError(f"{name} must be a non-negative number of seconds or a timedelta")
- return int(value)
+ the sandbox. Claims belonged to Cua Cloud, which has ended; nothing raises
+ this any more."""
+
+
+class PoolAccessDeniedError(PermissionError):
+ """A pool or template operation was refused for this credential. Pools
+ belonged to Cua Cloud, which has ended; nothing raises this any more."""
@dataclass
class SandboxSpec:
- """What a sandbox runs. Unset fields keep Fleet's defaults (and are not
- compared against a named pool's template).
+ """What a sandbox in a pool ran. Pools belonged to Cua Cloud, which has
+ ended; this data class is kept so existing imports keep working.
- * ``image``: an :class:`~cua_sandbox.Image` (``Image.from_registry(ref,
- secret=...)`` carries its registry secret) or a registry reference.
+ * ``image``: an :class:`~cua_sandbox.Image` or a registry reference.
* ``command`` / ``args``: argv replacing the image ENTRYPOINT / CMD.
* ``env``: plain environment variables (not secrets).
* ``services``: named guest ports, ``{"mcp": 8765}``.
- * ``wait_for``: ``tcp("mcp")`` / ``http("mcp", "/health")``: a replica
- binds a claim only once it passes.
+ * ``wait_for``: ``tcp("mcp")`` / ``http("mcp", "/health")``.
* ``cpu`` / ``memory_mb`` (or ``memory="4GB"``).
* ``sidecars``: :class:`~cua_sandbox.Container` (or image strings).
- * ``registry_secret``: a :class:`~cua_sandbox.RegistrySecret`, stored as
- the pool's ``cua-registry-*`` pull Secret; ``registry_secret_name``
- references an existing one.
+ * ``registry_secret``: a :class:`~cua_sandbox.RegistrySecret`;
+ ``registry_secret_name`` references an existing one.
* ``process_mode``: ``"Legacy"`` or ``"Run"``.
* ``claim_secrets``: claims may carry a per-claim env token.
"""
@@ -100,75 +69,19 @@ class SandboxSpec:
process_mode: Optional[str] = None
claim_secrets: bool = False
- def reference(self) -> str:
- """The image's registry reference (``""`` when unset)."""
- if self.image is None:
- return ""
- if isinstance(self.image, str):
- return self.image
- from cua_sandbox.image import cloud_registry_image
-
- reference = cloud_registry_image(self.image)
- if not reference:
- raise NotImplementedError(
- "Fleet cloud sandboxes require a supported built-in image or "
- "Image.from_registry(...)"
- )
- return reference
-
- def native(self) -> Any:
- """The ``cua.SandboxSpec`` record."""
- from cua_sandbox.containers import sidecars_of
- from cua_sandbox.options import probes
-
- n = native()
- memory_mb = self.memory_mb
- if self.memory is not None:
- if memory_mb is not None:
- raise ValueError("pass memory= or memory_mb=, not both")
- from cua_sandbox.options import parse_memory
-
- memory_mb = parse_memory(self.memory)
- readiness = probes(self.wait_for)
- if len(readiness) > 1:
- raise ValueError("a pool template takes one readiness probe (wait_for=)")
- secret = self.registry_secret
- if secret is None and self.image is not None and not isinstance(self.image, str):
- secret = getattr(self.image, "_secret", None)
- return n.SandboxSpec(
- image=self.reference(),
- command=list(self.command) if self.command else None,
- args=list(self.args) if self.args else None,
- env=dict(self.env or {}),
- services={k: int(v) for k, v in (self.services or {}).items()},
- readiness=readiness[0].native() if readiness else None,
- cpu=self.cpu,
- memory_mb=memory_mb,
- efi=self.efi
- or bool(
- self.image is not None
- and not isinstance(self.image, str)
- and self.image.os_type == "windows"
- ),
- sidecars=[c.native() for c in sidecars_of(self.sidecars)],
- registry_secret=secret.native() if secret is not None else None,
- registry_secret_name=self.registry_secret_name,
- process_mode=self.process_mode,
- claim_secrets=self.claim_secrets,
- )
-
@dataclass
class PoolOptions:
- """How a pool keeps capacity for a :class:`SandboxSpec`. Unset fields keep
- Fleet's defaults.
+ """How a pool kept capacity for a :class:`SandboxSpec`. Pools belonged to
+ Cua Cloud, which has ended; this data class is kept so existing imports
+ keep working.
- * ``runtime``: ``"gvisor"`` or ``"kubevirt"`` (unset: from the image).
- * ``replicas``: size of a pool without autoscaling (default 1).
- * ``warm``: keep one sandbox ready (``minPoolSize: 1``).
+ * ``runtime``: ``"gvisor"`` or ``"kubevirt"``.
+ * ``replicas``: size of a pool without autoscaling.
+ * ``warm``: keep one sandbox ready.
* ``min_pool_size`` / ``max_pool_size``: autoscaling floor / ceiling.
* ``idle_ttl``: delete the pool after this long without claims.
- * ``ttl_policy``: ``"Retain"`` or ``"Cascade"`` (what TTL expiry deletes).
+ * ``ttl_policy``: ``"Retain"`` or ``"Cascade"``.
* ``pool_ttl``: pool creation-age TTL.
* ``claim_ttl``: default TTL of claims made on the pool.
@@ -185,27 +98,6 @@ class PoolOptions:
pool_ttl: Seconds = None
claim_ttl: Seconds = None
- def native(self) -> Any:
- """The ``cua.PoolOptions`` record."""
- if self.runtime == "macos":
- raise ValueError(
- "macOS images run locally with Lume; Fleet does not offer macOS sandboxes in "
- "this SDK"
- )
- if self.runtime is not None and self.runtime not in ("gvisor", "kubevirt"):
- raise ValueError("runtime must be 'gvisor' or 'kubevirt'")
- return native().PoolOptions(
- runtime=self.runtime,
- replicas=self.replicas,
- warm=self.warm,
- min_pool_size=self.min_pool_size,
- max_pool_size=self.max_pool_size,
- idle_ttl_seconds=_seconds(self.idle_ttl, "idle_ttl"),
- ttl_policy=self.ttl_policy,
- pool_ttl_seconds=_seconds(self.pool_ttl, "pool_ttl"),
- claim_ttl_seconds=_seconds(self.claim_ttl, "claim_ttl"),
- )
-
@dataclass(frozen=True)
class PoolExport:
@@ -218,25 +110,6 @@ class PoolExport:
terraform: str
-def native_fleet() -> Any:
- """The SDK's ``Fleet`` control plane (the process-wide embedded runtime)."""
- from cua_sandbox import _autopool
-
- return _autopool._native_cua().fleet()
-
-
-async def call_native(coro: Any) -> Any:
- """Awaits a native call, raising the cua-sandbox exception types."""
- try:
- return await coro
- except Exception as error: # noqa: BLE001 - re-raised, typed when known
- typed = translate_native_error(error)
- if typed is error:
- raise
- raise typed from error
-
-
def generate_claim_token() -> str:
- """A fresh per-claim env token (64 hex characters) for
- ``pool.claim(claim_token=...)``."""
- return str(native().fleet_generate_claim_token())
+ """A fresh per-claim env token (64 hex characters)."""
+ return secrets.token_hex(32)
diff --git a/libs/python/cua-sandbox/cua_sandbox/sync/__init__.py b/libs/python/cua-sandbox/cua_sandbox/sync/__init__.py
index 2855b16850..84157b82ff 100644
--- a/libs/python/cua-sandbox/cua_sandbox/sync/__init__.py
+++ b/libs/python/cua-sandbox/cua_sandbox/sync/__init__.py
@@ -21,11 +21,6 @@ from cua_sandbox.image import Image
from cua_sandbox.pool import Pool as _AsyncPool
from cua_sandbox.pool import Template as _AsyncTemplate
from cua_sandbox.sandbox import Sandbox as _AsyncSandbox
-from fleet_sdk import (
- ClaimSpec,
- CreatePoolRequest,
- CreateTemplateRequest,
-)
def _get_or_create_loop() -> asyncio.AbstractEventLoop:
@@ -89,18 +84,15 @@ class Template:
return self._async_template.name
@classmethod
- def reconcile(cls, request: CreateTemplateRequest) -> "Template":
- """Synchronously create or update a Fleet sandbox template."""
+ def reconcile(cls, request: Any) -> "Template":
+ """Always raises :class:`~cua_sandbox._ended.CloudEnded`: Cua Cloud has
+ ended."""
return cls(_run(_AsyncTemplate.reconcile(request)))
class Pool:
- """Blocking facade for :class:`cua_sandbox.Pool`.
-
- ``Pool.reconcile`` and ``pool.claim`` use the same Fleet lifecycle as the
- async API, but yield synchronous sandbox interface methods for scripts and
- notebooks.
- """
+ """Blocking facade for :class:`cua_sandbox.Pool`. Cua Cloud has ended, so
+ every call raises :class:`~cua_sandbox._ended.CloudEnded`."""
def __init__(self, async_pool: _AsyncPool) -> None:
self._async_pool = async_pool
@@ -110,43 +102,36 @@ class Pool:
return self._async_pool.name
@classmethod
- def reconcile(cls, request: CreatePoolRequest) -> "Pool":
- """Synchronously create or update a Fleet pool."""
+ def reconcile(cls, request: Any) -> "Pool":
return cls(_run(_AsyncPool.reconcile(request)))
@classmethod
def get(cls, name: str) -> "Pool":
- """Synchronously fetch an existing Fleet pool without changing it."""
return cls(_run(_AsyncPool.get(name)))
@classmethod
def apply(cls, *args: Any, **kwargs: Any) -> "Pool":
- """Synchronously apply a Fleet pool: ``Pool.apply(name, spec, options)``
- (the deprecated ``Pool.apply(image, name=..., ...)`` form works too;
- see ``cua_sandbox.Pool.apply``)."""
return cls(_run(_AsyncPool.apply(*args, **kwargs)))
@staticmethod
def export(name: str, *, terraform: bool = False) -> Any:
- """Synchronously read a pool back (see ``cua_sandbox.Pool.export``)."""
return _run(_AsyncPool.export(name, terraform=terraform))
def delete(self) -> None:
- """Synchronously delete this Fleet pool."""
_run(self._async_pool.delete())
@contextmanager
def claim(
self,
*,
- spec: ClaimSpec | None = None,
+ spec: Any = None,
name: str | None = None,
service: str = ENV_SERVICE,
time_to_start: float | None = None,
ttl_seconds_after_created: int | None = None,
claim_token: str | None = None,
) -> Iterator[_SyncProxy]:
- """Synchronously claim a sandbox and release it on exit."""
+ """Always raises :class:`~cua_sandbox._ended.CloudEnded`."""
context = self._async_pool.claim(
spec=spec,
name=name,
@@ -169,8 +154,7 @@ class Sandbox:
"""Blocking facade for :class:`cua_sandbox.Sandbox` factories.
Each method takes the same arguments as its async counterpart and returns
- sync-wrapped sandboxes. Managed Fleet claims keep renewing in the
- background between calls, exactly as with the async API.
+ sync-wrapped sandboxes.
"""
@staticmethod
@@ -234,14 +218,13 @@ def sandbox(
Mirrors :func:`cua_sandbox.sandbox`: an ephemeral sandbox (the default when
``image`` is given) is destroyed on exit, anything else is disconnected.
- Fleet registry images come from the account's managed pool (see
- :meth:`cua_sandbox.Sandbox.create` for ``on``/``local``, ``kind``,
- ``runtime``, ``warm``, ``max_pool_size``, ``claim_ttl`` and ``progress``).
+ See :meth:`cua_sandbox.Sandbox.create` for ``on``/``local``, ``kind`` and
+ ``runtime``.
"""
from cua_sandbox import _placement
from cua_sandbox.sandbox import _cloud_only_args, _place_new
- engine, hint = None, None
+ engine = None
if image is not None and not (url or http_url or ws_url):
place, image = _place_new(
image,
@@ -259,7 +242,6 @@ def sandbox(
),
)
local, engine, runtime = place.local, place.runtime, place.legacy_runtime
- hint = place.cloud_default_hint()
elif on is not None:
local = _placement.resolve(on=on, local=local).local
sb = _run(
@@ -274,12 +256,7 @@ def sandbox(
runtime=runtime,
name=name,
ephemeral=ephemeral,
- warm=warm,
- max_pool_size=max_pool_size,
- claim_ttl=claim_ttl,
- progress=progress,
engine=engine,
- hint=hint,
)
)
proxy = _SyncProxy(sb)
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/__init__.py b/libs/python/cua-sandbox/cua_sandbox/transport/__init__.py
index 05b52efc76..86dc268c1d 100644
--- a/libs/python/cua-sandbox/cua_sandbox/transport/__init__.py
+++ b/libs/python/cua-sandbox/cua_sandbox/transport/__init__.py
@@ -2,7 +2,6 @@ from cua_sandbox.transport.adb import ADBTransport
from cua_sandbox.transport.base import Transport
from cua_sandbox.transport.cloud import CloudTransport
from cua_sandbox.transport.env import EnvTransport
-from cua_sandbox.transport.fleet import FleetTransport
from cua_sandbox.transport.osworld import OSWorldTransport
from cua_sandbox.transport.qmp import QMPTransport
from cua_sandbox.transport.ssh import SSHTransport
@@ -13,7 +12,6 @@ __all__ = [
"Transport",
"EnvTransport",
"CloudTransport",
- "FleetTransport",
"QMPTransport",
"OSWorldTransport",
"ADBTransport",
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/base.py b/libs/python/cua-sandbox/cua_sandbox/transport/base.py
index eab1af5746..b4db02d54d 100644
--- a/libs/python/cua-sandbox/cua_sandbox/transport/base.py
+++ b/libs/python/cua-sandbox/cua_sandbox/transport/base.py
@@ -1,9 +1,8 @@
"""Abstract transport protocol.
A Transport moves commands and data between the sandbox client and the
-underlying computer: cua-spacesd through the ``cua`` SDK (EnvTransport,
-FleetTransport) or an agentless legacy path (QMP, VNC, SSH, ADB, OSWorld,
-the local host).
+underlying computer: cua-spacesd through the ``cua`` SDK (EnvTransport) or an
+agentless legacy path (QMP, VNC, SSH, ADB, OSWorld, the local host).
"""
from __future__ import annotations
@@ -111,8 +110,8 @@ class Transport(ABC):
"""
raise NotImplementedError(
f"{type(self).__name__} does not support port forwarding. "
- "Supported transports: ADBTransport, EnvTransport, FleetCloudTransport, FleetTransport, "
- "GRPCEmulatorTransport, SSHTransport."
+ "Supported transports: ADBTransport, EnvTransport, GRPCEmulatorTransport, "
+ "SSHTransport."
)
async def close_tunnel(self, info: "TunnelInfo") -> None:
@@ -148,9 +147,9 @@ class Transport(ABC):
"""Return a URL to view this sandbox's display.
Args:
- share: If True, return a public link with embedded credentials
- (cloud only). If False, return a direct connection URL
- (localhost VNC for local runtimes; auth-gated URL for cloud).
+ share: If True, return a shareable link with embedded credentials
+ (where the transport supports one). If False, return a
+ direct connection URL (localhost VNC for local runtimes).
Raises NotImplementedError for transports that don't expose a display
(e.g. HTTP, ADB).
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/cloud.py b/libs/python/cua-sandbox/cua_sandbox/transport/cloud.py
index ce4487fe26..f82622899f 100644
--- a/libs/python/cua-sandbox/cua_sandbox/transport/cloud.py
+++ b/libs/python/cua-sandbox/cua_sandbox/transport/cloud.py
@@ -1,182 +1,20 @@
-"""Legacy API-key cloud (api.cua.ai) compatibility.
+"""``CloudTransport``: Cua Cloud has ended.
-API-key cloud VMs were driven through computer-server, which cua-spacesd
-replaced; computer-server and its transports were removed. Cloud sandboxes
-now run on Fleet (OAuth client credentials or a Fleet workload token):
-
- import cua_sandbox as cua
- cua.configure(client_id="...", client_secret="...") # or CUA_CLIENT_ID/SECRET
- pool = await cua.Pool.apply(cua.Image.linux(), name="my-pool")
- async with pool.claim() as sb: ...
-
-:class:`CloudTransport` stays importable (it is a public export) and fails
-with that guidance. The REST helpers below still list, inspect and delete
-existing API-key VMs so they can be cleaned up.
+The transport that drove API-key cloud VMs is gone. The name stays importable
+so existing imports keep working; constructing it raises
+:class:`~cua_sandbox._ended.CloudEnded`.
"""
from __future__ import annotations
-import logging
-from typing import Any, Dict, Optional
+from typing import Any
-import httpx
-from cua_sandbox._config import FLEET_CREDENTIALS_MISSING, get_api_key, get_base_url
+from cua_sandbox._ended import CloudEnded
from cua_sandbox.transport.base import Transport
-logger = logging.getLogger(__name__)
-
-# No legacy api.cua.ai key and no Fleet credentials.
-_NO_KEY_MESSAGE = FLEET_CREDENTIALS_MISSING
-
-LEGACY_CLOUD_REMOVED = (
- "API-key cloud VMs (api.cua.ai) were driven through computer-server, which has "
- "been removed in favour of cua-spacesd. Use Fleet cloud sandboxes instead: "
- "configure OAuth client credentials (cua.configure(client_id=..., client_secret=...) "
- "or CUA_CLIENT_ID/CUA_CLIENT_SECRET, or FLEETS_TOKEN), then "
- "`pool = await Pool.apply(image, name=...)` and `Sandbox.create(pool=pool, ...)` "
- "or `Sandbox.ephemeral(image)`. Existing API-key VMs can still be listed and "
- "deleted with Sandbox.list(api_key=...) / Sandbox.delete(name, api_key=...)."
-)
-
-
-class LegacyCloudRemovedError(RuntimeError):
- """The API-key cloud data plane (computer-server) no longer exists."""
-
class CloudTransport(Transport):
- """Compatibility shim for the removed API-key cloud transport.
-
- Constructing it still works (and keeps the requested image), so code that
- builds one fails at ``connect()`` with a message pointing to Fleet.
- """
-
- def __init__(
- self,
- name: Optional[str] = None,
- *,
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
- image: Optional[Any] = None,
- cpu: Optional[int] = None,
- memory_mb: Optional[int] = None,
- disk_gb: Optional[int] = None,
- region: str = "us-east-1",
- time_to_start: Optional[float] = None,
- request_timeout: Optional[float] = None,
- ):
- self._name = name
- self._api_key_override = api_key
- self._base_url = base_url or get_base_url()
- self._image = image
- self._cpu = cpu
- self._memory_mb = memory_mb
- self._disk_gb = disk_gb
- self._region = region
-
- @property
- def name(self) -> Optional[str]:
- return self._name
-
- async def connect(self) -> None:
- if not get_api_key(self._api_key_override):
- raise ValueError(_NO_KEY_MESSAGE)
- if not self._name and self._image is None:
- raise ValueError("Cannot create a cloud VM without an image")
- raise LegacyCloudRemovedError(LEGACY_CLOUD_REMOVED)
-
- async def disconnect(self) -> None:
- return None
-
- async def delete_vm(self) -> None:
- """Delete an existing API-key VM through the platform API."""
- if not self._name or not get_api_key(self._api_key_override):
- return
- await cloud_vm_action(self._name, "delete", api_key=self._api_key_override)
-
- async def create_snapshot(self, name: str | None = None, stateful: bool = False) -> dict:
- raise LegacyCloudRemovedError(LEGACY_CLOUD_REMOVED)
-
- async def send(self, action: str, **params: Any) -> Any:
- raise LegacyCloudRemovedError(LEGACY_CLOUD_REMOVED)
-
- async def screenshot(self, format: str = "png", quality: int = 95) -> bytes:
- raise LegacyCloudRemovedError(LEGACY_CLOUD_REMOVED)
-
- async def get_screen_size(self) -> Dict[str, int]:
- raise LegacyCloudRemovedError(LEGACY_CLOUD_REMOVED)
-
- async def get_environment(self) -> str:
- raise LegacyCloudRemovedError(LEGACY_CLOUD_REMOVED)
-
- @staticmethod
- async def _build_pwa2apk(*args: Any, **kwargs: Any) -> tuple:
- """Moved to :func:`cua_sandbox.builder.pwa2apk.build_pwa2apk`."""
- from cua_sandbox.builder.pwa2apk import build_pwa2apk
-
- return await build_pwa2apk(*args, **kwargs)
-
-
-async def cloud_list_vms(
- *, api_key: Optional[str] = None, base_url: Optional[str] = None
-) -> list[dict]:
- """List all cloud VMs. Returns raw VM dicts from the API."""
- from cua_sandbox._config import FLEET_CREDENTIALS_MISSING, get_api_key, get_base_url
-
- key = get_api_key(api_key)
- if not key:
- raise ValueError(FLEET_CREDENTIALS_MISSING)
- url = base_url or get_base_url()
- async with httpx.AsyncClient(
- base_url=url,
- headers={"Authorization": f"Bearer {key}"},
- timeout=30.0,
- ) as client:
- resp = await client.get("/v1/vms")
- resp.raise_for_status()
- data = resp.json()
- return data if isinstance(data, list) else data.get("vms", [])
-
-
-async def cloud_get_vm(
- name: str, *, api_key: Optional[str] = None, base_url: Optional[str] = None
-) -> dict:
- """Get info for a single cloud VM by name."""
- from cua_sandbox._config import FLEET_CREDENTIALS_MISSING, get_api_key, get_base_url
-
- key = get_api_key(api_key)
- if not key:
- raise ValueError(FLEET_CREDENTIALS_MISSING)
- url = base_url or get_base_url()
- async with httpx.AsyncClient(
- base_url=url,
- headers={"Authorization": f"Bearer {key}"},
- timeout=30.0,
- ) as client:
- resp = await client.get(f"/v1/vms/{name}")
- resp.raise_for_status()
- return resp.json()
-
-
-async def cloud_vm_action(
- name: str,
- action: str,
- *,
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
-) -> None:
- """POST /v1/vms/{name}/{action}. action is 'stop', 'run', 'restart', or 'delete'."""
- from cua_sandbox._config import FLEET_CREDENTIALS_MISSING, get_api_key, get_base_url
+ """Retired: every Cua Cloud entry point raises :class:`CloudEnded`."""
- key = get_api_key(api_key)
- if not key:
- raise ValueError(FLEET_CREDENTIALS_MISSING)
- url = base_url or get_base_url()
- async with httpx.AsyncClient(
- base_url=url,
- headers={"Authorization": f"Bearer {key}"},
- timeout=30.0,
- ) as client:
- if action == "delete":
- await client.delete(f"/v1/vms/{name}")
- else:
- await client.post(f"/v1/vms/{name}/{action}")
+ def __new__(cls, *args: Any, **kwargs: Any) -> "CloudTransport":
+ raise CloudEnded()
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/cyclops_http_client.py b/libs/python/cua-sandbox/cua_sandbox/transport/cyclops_http_client.py
deleted file mode 100644
index db363c7619..0000000000
--- a/libs/python/cua-sandbox/cua_sandbox/transport/cyclops_http_client.py
+++ /dev/null
@@ -1,50 +0,0 @@
-"""httpx bridge for the generated Cyclops SDK callback interface."""
-
-from __future__ import annotations
-
-import httpx
-from fleet_sdk import HttpClient, HttpError, HttpHeader, HttpRequest, HttpResponse
-
-
-class CyclopsHttpClient(HttpClient):
- """Execute SDK requests with one shared async httpx client."""
-
- def __init__(self, client: httpx.AsyncClient | None = None) -> None:
- self._client = client or httpx.AsyncClient(timeout=30.0)
- self._owns_client = client is None
-
- async def execute(self, request: HttpRequest) -> HttpResponse:
- headers = {header.name: header.value for header in request.headers}
- request_kwargs = {
- "headers": headers,
- "content": request.body,
- }
- if request.timeout_secs is not None:
- request_kwargs["timeout"] = request.timeout_secs
-
- try:
- response = await self._client.request(
- request.method,
- request.url,
- **request_kwargs,
- )
- except httpx.TransportError as error:
- raise HttpError.Transport(str(error) or type(error).__name__) from error
- return HttpResponse(
- status=response.status_code,
- headers=[
- HttpHeader(name=name, value=value) for name, value in response.headers.multi_items()
- ],
- body=response.content,
- )
-
- async def aclose(self) -> None:
- if self._owns_client:
- try:
- await self._client.aclose()
- except RuntimeError as error:
- # The sync facade runs each call on a fresh event loop; a
- # client opened on an earlier (now closed) loop cannot close
- # its sockets there, and they die with that loop anyway.
- if "Event loop is closed" not in str(error):
- raise
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/env.py b/libs/python/cua-sandbox/cua_sandbox/transport/env.py
index 388ebd6d31..d2037caef0 100644
--- a/libs/python/cua-sandbox/cua_sandbox/transport/env.py
+++ b/libs/python/cua-sandbox/cua_sandbox/transport/env.py
@@ -206,11 +206,11 @@ class EnvTransport(Transport):
"""Drives a sandbox through cua-spacesd.
Args:
- url: spacesd URL (``http://host:3211``, a relay or Fleet service URL).
+ url: spacesd URL (``http://host:3211`` or a relay URL).
Ignored when ``env_factory`` is given.
token: spacesd token, if the driver requires one.
- env_factory: coroutine returning a ``cua.SpacesdClient`` (used by Fleet and
- local runtimes, which know how to reach the driver).
+ env_factory: coroutine returning a ``cua.SpacesdClient`` (used by local
+ runtimes, which know how to reach the driver).
environment: OS hint (``linux``, ``windows``, ``mac``) used before the
driver has been reached.
fallback: an agentless transport (QMP/VNC/SSH/ADB) to use when the
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/fleet.py b/libs/python/cua-sandbox/cua_sandbox/transport/fleet.py
deleted file mode 100644
index 2eec07c107..0000000000
--- a/libs/python/cua-sandbox/cua_sandbox/transport/fleet.py
+++ /dev/null
@@ -1,284 +0,0 @@
-"""Transport for a bound Fleet claim.
-
-Two planes, both daemon-agnostic:
-
-* **Named services** (``sb.services.request(...)``) go through the Fleet
- gateway with ``CyclopsClient.service_request``: any HTTP service the image
- declares, no guest agent assumed.
-* **Computer interfaces** (``screen``, ``mouse``, ``shell`` ...) go to
- cua-spacesd on the claim's ``env`` service through the ``cua`` SDK
- (gRPC-Web through the gateway, Fleet bearer + claim header). A claim whose
- image has no spacesd still binds and serves named services; only the
- interfaces raise :class:`~cua_sandbox._sdk.SpacesdNotAvailable`.
-"""
-
-from __future__ import annotations
-
-import json
-import math
-from typing import Any, Dict, List, Mapping, Optional
-
-import httpx
-from cua_sandbox._sdk import ENV_SERVICE, fleet_sandbox, millis
-from cua_sandbox.transport.env import EnvTransport
-from cua_sandbox.transport.osworld import OSWorldOverServiceMixin
-from fleet_sdk import HttpHeader, HttpRequest, HttpRequestBuilder
-
-#: How long the first interface call waits for spacesd on a fresh claim.
-DEFAULT_ENV_READY_TIMEOUT = 300.0
-#: The service an OSWorld pool publishes its Flask server under (legacy adapter).
-OSWORLD_SERVICE = "server"
-
-
-def build_http_request(
- *,
- method: str,
- url: str,
- headers: Optional[List[Any]] = None,
- body: Optional[bytes] = None,
- timeout_secs: Optional[int] = None,
- max_response_bytes: Optional[int] = None,
-) -> HttpRequest:
- """Construct ``fleet_sdk.HttpRequest`` through the builder API.
-
- The builder treats optional record fields as skippable, so request
- construction keeps working when the Fleet SDK adds fields. An absent
- ``timeout_secs`` falls back to the native client's 30-second default.
- """
- builder = HttpRequestBuilder().method(method).url(url).headers(headers or [])
- if body is not None:
- builder = builder.body(body)
- if timeout_secs is not None:
- builder = builder.timeout_secs(timeout_secs)
- if max_response_bytes is not None:
- builder = builder.max_response_bytes(max_response_bytes)
- return builder.build()
-
-
-def _whole_seconds(timeout: Optional[float]) -> Optional[int]:
- if timeout is None or timeout <= 0:
- return None
- return math.ceil(timeout)
-
-
-class FleetTransport(EnvTransport):
- """Interfaces over cua-spacesd, named services over the Fleet gateway."""
-
- def __init__(
- self,
- *,
- sdk: Any,
- bound: Any,
- service_name: str = ENV_SERVICE,
- timeout: float = 30.0,
- owns_sdk: bool = False,
- env_ready_timeout: float = DEFAULT_ENV_READY_TIMEOUT,
- env_token: Optional[str] = None,
- **_: Any,
- ) -> None:
- self._env_token = env_token
- self._sdk = sdk
- self._bound = bound
- self._service_name = service_name
- self._timeout = timeout
- self._owns_sdk = owns_sdk
- self._sdk_closed = False
- self._native_fleet_sandbox: Any = None
- # The claim's image (a named pool's template image), handed to the
- # SDK handle so its ``image_info()`` reports it.
- self._image_info: Any = None
- super().__init__(
- env_factory=self._open_env,
- ready_timeout=env_ready_timeout,
- probe_timeout=min(timeout, 15.0),
- )
-
- async def _fleet_handle(self) -> Any:
- if self._native_fleet_sandbox is None:
- # The claim's per-claim env token, when it has one.
- token = (self._env_token,) if self._env_token else ()
- # The claim's image, when known (a named pool's template image).
- image = {"image_info": self._image_info} if self._image_info is not None else {}
- self._native_fleet_sandbox = await fleet_sandbox(
- self._bound.namespace, self._bound.claim, *token, **image
- )
- return self._native_fleet_sandbox
-
- async def _open_env(self) -> Any:
- from cua_sandbox._sdk import SpacesdNotAvailable
-
- if ENV_SERVICE not in self._bound.services:
- raise SpacesdNotAvailable(
- f"Fleet sandbox {self._bound.name!r} exposes no {ENV_SERVICE!r} service "
- f"(services: {list(self._bound.services)}); its image has no "
- "cua-spacesd, so only named services (sb.services.request) are available"
- )
- handle = await self._fleet_handle()
- return await handle.spacesd(millis(self._probe_timeout))
-
- async def connect(self) -> None:
- # Daemon-agnostic: the claim is bound; nothing in the guest is probed.
- await super().connect()
-
- async def disconnect(self) -> None:
- await super().disconnect()
- self._native_fleet_sandbox = None
- # A transport constructed with owns_sdk=True (e.g. by _ClaimHandle.wait)
- # is the sole holder of its Fleet client, so disconnect is where that
- # client's HTTP resources are returned.
- if self._owns_sdk and not self._sdk_closed:
- await self._sdk.close()
- self._sdk_closed = True
-
- async def request_service(
- self,
- name: str,
- *,
- method: str,
- path: str,
- json_body: Any = None,
- body: bytes | None = None,
- headers: dict[str, str] | list[tuple[str, str]] | None = None,
- timeout: float | None = None,
- max_response_bytes: int | None = None,
- ) -> httpx.Response:
- if name not in self._bound.services:
- raise ValueError(f"Fleet sandbox does not expose service {name!r}")
- return await self._request(
- method,
- path,
- json_body=json_body,
- body=body,
- service_name=name,
- extra_headers=headers,
- timeout=timeout,
- max_response_bytes=max_response_bytes,
- )
-
- async def native_handle(self) -> Any:
- """The ``cua.Sandbox`` handle of this claim (services, forwards,
- public URLs)."""
- return await self._fleet_handle()
-
- async def forward_tunnel(self, sandbox_port: int | str) -> "Any":
- """A loopback forward to ``sandbox_port``: over cua-spacesd's
- tunnel when the image has it, else an HTTP/WebSocket proxy through
- the cloud gateway (the port must be a declared service)."""
- if self._delegate is not None:
- return await self._delegate.forward_tunnel(sandbox_port)
- if not isinstance(sandbox_port, int):
- raise ValueError("only numeric TCP ports can be forwarded")
- forward = await (await self._fleet_handle()).forward(sandbox_port)
- return self._track_forward(forward, sandbox_port)
-
- def _declared_services(self) -> Dict[str, Optional[int]]:
- services = self._bound.services
- if isinstance(services, Mapping):
- return {str(k): (int(v) if v is not None else None) for k, v in services.items()}
- return {str(k): None for k in services or ()}
-
- async def native_service(self, name: str) -> Any:
- if name not in self._bound.services:
- raise ValueError(
- f"Fleet sandbox does not expose service {name!r} "
- f"(services: {list(self._bound.services)})"
- )
- return (await self._fleet_handle()).service(name)
-
- async def create_signed_service_url(
- self,
- name: str,
- *,
- label: str | None,
- expires_in_seconds: int,
- ) -> Any:
- return await self._sdk.create_signed_service_url(
- self._bound,
- name,
- label=label,
- expires_in_seconds=expires_in_seconds,
- )
-
- async def list_signed_service_urls(self) -> list[Any]:
- return await self._sdk.list_signed_service_urls(self._bound)
-
- async def revoke_signed_service_url(self, signed_service_url: Any) -> None:
- await self._sdk.revoke_signed_service_url(signed_service_url)
-
- async def _request(
- self,
- method: str,
- path: str,
- *,
- json_body: Any = None,
- body: bytes | None = None,
- service_name: str | None = None,
- extra_headers: dict[str, str] | list[tuple[str, str]] | None = None,
- timeout: float | None = None,
- max_response_bytes: int | None = None,
- ) -> httpx.Response:
- """One HTTP request to a named service through the Fleet gateway."""
- if body is not None and json_body is not None:
- raise ValueError("Specify either body or json_body, not both")
- if json_body is not None:
- body = json.dumps(json_body).encode()
- request_headers = (
- [] if json_body is None else [HttpHeader(name="content-type", value="application/json")]
- )
- header_items = (
- extra_headers.items() if isinstance(extra_headers, dict) else (extra_headers or [])
- )
- for header, value in header_items:
- request_headers.append(HttpHeader(name=header, value=value))
- result = await self._sdk.service_request(
- self._bound,
- service_name or self._service_name,
- path,
- build_http_request(
- method=method,
- url=f"https://service.invalid{path}",
- headers=request_headers,
- body=body,
- timeout_secs=_whole_seconds(self._timeout if timeout is None else timeout),
- max_response_bytes=max_response_bytes,
- ),
- )
- if max_response_bytes is not None and len(result.body) > max_response_bytes:
- raise RuntimeError("Fleet service response exceeds the configured size limit")
- return httpx.Response(
- result.status,
- headers=[(header.name, header.value) for header in result.headers],
- content=result.body,
- request=httpx.Request(method, f"https://service.invalid{path}"),
- )
-
- async def get_environment(self) -> str:
- try:
- return await super().get_environment()
- except Exception: # noqa: BLE001 - no driver: the pool OS is unknown
- return "linux"
-
-
-class OSWorldFleetTransport(OSWorldOverServiceMixin, FleetTransport):
- """Legacy OSWorld adapter: a claim whose ``server`` service is the OSWorld Flask API.
-
- The OSWorld guest has no cua-spacesd; screenshots, screen size and shell
- commands go to the Flask server through the Fleet gateway instead.
- """
-
- def __init__(self, *, service_name: str = OSWORLD_SERVICE, **kwargs: Any) -> None:
- if service_name == ENV_SERVICE:
- service_name = OSWORLD_SERVICE
- super().__init__(service_name=service_name, **kwargs)
-
-
-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
-
-
-def claim_service_for(agent_type: Optional[str], service: str) -> str:
- """The service a claim waits on: OSWorld pools publish ``server``, not ``env``."""
- if agent_type == "osworld" and service == ENV_SERVICE:
- return OSWORLD_SERVICE
- return service
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py b/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
deleted file mode 100644
index 092a132110..0000000000
--- a/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
+++ /dev/null
@@ -1,999 +0,0 @@
-"""Fleet-backed implementation of the public cloud sandbox transport."""
-
-from __future__ import annotations
-
-import asyncio
-import hashlib
-import json
-import logging
-import os
-from collections.abc import Awaitable, Callable
-from typing import TYPE_CHECKING, Any, Literal, Mapping, Optional
-from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
-
-import httpx
-from cua_sandbox._config import (
- get_client_id,
- get_client_secret,
- get_fleet_base_url,
- get_fleet_token,
- get_token_url,
-)
-from cua_sandbox._sdk import ENV_SERVICE, SPACESD_PORT
-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,
- CreateClaimRequest,
- CreatePoolRequest,
- CreatePoolRequestBuilder,
- CreateTemplateRequest,
- CreateTemplateRequestBuilder,
- CyclopsClient,
- CyclopsConfiguration,
- CyclopsCredentials,
- CyclopsTokenProviderConfiguration,
- Firmware,
- HttpRequest,
- OsGymSandboxTemplateSpecBuilder,
- OsGymSandboxWarmPoolSpecBuilder,
- PreservedJson,
- RuntimeKind,
- SandboxServiceBuilder,
- SandboxTemplateRefBuilder,
- SdkError,
- ServiceProtocol,
- VmTemplateBuilder,
- WarmPoolAutoscaling,
-)
-
-if TYPE_CHECKING:
- from cua_sandbox.interfaces.tunnel import TunnelInfo
-
-logger = logging.getLogger(__name__)
-
-_DNS_LABEL_MAX_LENGTH = 63
-_CLAIM_HASH_LENGTH = 16
-# Bounds each readiness probe so one stalled round-trip cannot eat the whole
-# wait_service_ready deadline. Ignored by cua-fleet <= 0.1.8, whose native
-# client applies the same 30-second default.
-_READINESS_PROBE_TIMEOUT_SECS = 30
-# The name a caller-declared ``server_port`` is published under.
-_SERVER_SERVICE = "server"
-
-
-def default_services(server_port: Optional[int], extra_ports: "tuple[int, ...] | list[int]" = ()):
- """Services a Fleet pool publishes when the caller names none.
-
- Sandboxes are daemon-agnostic: by default a pool publishes cua-spacesd
- as ``env`` (3211) plus each ``Image.expose()`` port as ``port-<n>``. A
- caller-supplied ``server_port`` (an image with its own daemon) is published
- as ``server`` instead.
- """
- if server_port is None:
- primary = {ENV_SERVICE: SPACESD_PORT}
- primary_port = SPACESD_PORT
- else:
- primary = {_SERVER_SERVICE: server_port}
- primary_port = server_port
- return {
- **primary,
- **{f"port-{port}": port for port in extra_ports if port != primary_port},
- }
-
-
-def validate_server_port(server_port: Any) -> None:
- """``None`` (daemon-agnostic default) or a TCP port."""
- if server_port is None:
- return
- if (
- isinstance(server_port, bool)
- or not isinstance(server_port, int)
- or server_port < 1
- or server_port > 65535
- ):
- raise ValueError("server_port must be an integer between 1 and 65535")
-
-
-# Newer Fleet SDKs raise SdkError.PoolAccessDenied from the Rust core for 403s
-# on pool-namespace writes, so every language binding shares one message. Use
-# that type when the installed cua-fleet provides it; otherwise map the plain
-# 403 Status errors older SDKs raise into an equivalent local error.
-_UPSTREAM_POOL_ACCESS_DENIED = getattr(SdkError, "PoolAccessDenied", None)
-
-if _UPSTREAM_POOL_ACCESS_DENIED is not None:
- PoolAccessDeniedError = _UPSTREAM_POOL_ACCESS_DENIED
-else:
-
- class PoolAccessDeniedError(PermissionError): # type: ignore[no-redef]
- """Fleet refused a pool or template operation for this credential."""
-
-
-# Catch tuple for pool-access denials raised natively by newer Fleet SDKs;
-# empty when the installed cua-fleet predates the upstream variant.
-_NATIVE_POOL_ACCESS_DENIED = (
- () if _UPSTREAM_POOL_ACCESS_DENIED is None else (_UPSTREAM_POOL_ACCESS_DENIED,)
-)
-
-
-def _pool_access_denied_message(operation: str, namespace: str, status: int, body: str) -> str:
- return (
- f"Fleet denied {operation} on pool namespace '{namespace}' "
- f"(HTTP {status}: {body}). Pool names are globally unique "
- "across accounts, so this name may already be taken — try a new pool "
- "name. If that does not work, contact support on Discord: "
- "https://discord.gg/mVnXXpdE85"
- )
-
-
-def _canonicalize_pool_access_denied(error: Exception) -> Exception:
- # The uniffi-generated exception renders as a field dump
- # (operation=..., namespace=..., ...); restore the Rust Display message so
- # both raise paths read identically.
- error.args = (
- _pool_access_denied_message(error.operation, error.namespace, error.status, error.body),
- )
- return error
-
-
-def _pool_access_denied(namespace: str, error: SdkError.Status) -> Exception:
- if _UPSTREAM_POOL_ACCESS_DENIED is not None:
- return _canonicalize_pool_access_denied(
- _UPSTREAM_POOL_ACCESS_DENIED(
- operation=error.operation,
- namespace=namespace,
- status=error.status,
- body=error.body,
- )
- )
- return PoolAccessDeniedError(
- _pool_access_denied_message(error.operation, namespace, error.status, error.body)
- )
-
-
-def _claim_name(pool_name: str) -> str:
- normalized_name = pool_name.lower()
- legacy_name = f"{normalized_name}-claim"
- if len(legacy_name) <= _DNS_LABEL_MAX_LENGTH:
- return legacy_name
-
- hash_suffix = hashlib.sha256(normalized_name.encode()).hexdigest()[:_CLAIM_HASH_LENGTH]
- prefix_length = _DNS_LABEL_MAX_LENGTH - len(hash_suffix) - 1
- prefix = normalized_name[:prefix_length].rstrip("-")
- return f"{prefix}-{hash_suffix}"
-
-
-_GITHUB_WIF_AUDIENCE = "fleets"
-_GitHubTokenRequest = Callable[[str, dict[str, str]], Awaitable[tuple[int, Mapping[str, Any]]]]
-
-
-async def _httpx_json_get(url: str, headers: dict[str, str]) -> tuple[int, Mapping[str, Any]]:
- async with httpx.AsyncClient(timeout=15) as client:
- response = await client.get(url, headers=headers)
- payload = response.json()
- if not isinstance(payload, Mapping):
- raise ValueError("GitHub OIDC endpoint returned an invalid response")
- return response.status_code, payload
-
-
-def _with_audience(request_url: str, audience: str) -> str:
- parts = urlsplit(request_url)
- query = [
- (key, value)
- for key, value in parse_qsl(parts.query, keep_blank_values=True)
- if key != "audience"
- ]
- query.append(("audience", audience))
- return urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(query), parts.fragment))
-
-
-class _GitHubActionsAccessTokenProvider(AccessTokenProvider):
- """Refresh a Fleet workload token through GitHub Actions OIDC after a 401."""
-
- def __init__(
- self,
- token: str,
- *,
- environ: Mapping[str, str] | None = None,
- request: _GitHubTokenRequest = _httpx_json_get,
- ) -> None:
- self._token = token
- self._environ = os.environ if environ is None else environ
- self._request = request
-
- async def get_access_token(self, force_refresh: bool) -> str:
- if not force_refresh:
- return self._token
-
- request_url = self._environ.get("ACTIONS_ID_TOKEN_REQUEST_URL", "").strip()
- request_token = self._environ.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "").strip()
- if not request_url or not request_token:
- raise AccessTokenProviderError.Failed(
- "GitHub Actions OIDC environment is unavailable for token refresh"
- )
-
- try:
- status, payload = await self._request(
- _with_audience(request_url, _GITHUB_WIF_AUDIENCE),
- {
- "Accept": "application/json",
- "Authorization": f"bearer {request_token}",
- },
- )
- except AccessTokenProviderError:
- raise
- except Exception as error:
- raise AccessTokenProviderError.Failed("GitHub OIDC token refresh failed") from error
-
- if status != 200:
- raise AccessTokenProviderError.Failed(
- f"GitHub OIDC token refresh failed with HTTP {status}"
- )
- token = payload.get("value")
- if not isinstance(token, str) or not token.strip():
- raise AccessTokenProviderError.Failed(
- "GitHub OIDC token refresh returned an empty token"
- )
- self._token = token.strip()
- return self._token
-
-
-class _StaticAccessTokenProvider(AccessTokenProvider):
- """Return a configured Fleet workload token without attempting refresh."""
-
- def __init__(self, token: str) -> None:
- self._token = token
-
- async def get_access_token(self, force_refresh: bool) -> str:
- return self._token
-
-
-class _SessionAccessTokenProvider(AccessTokenProvider):
- """The ``cua auth login`` session's (refreshing) bearer, via the cua SDK."""
-
- def __init__(self) -> None:
- from cua_sandbox._sdk import sdk
-
- self._auth = sdk().embedded(fleet_from_env=False).auth()
-
- async def get_access_token(self, force_refresh: bool) -> str:
- try:
- return await self._auth.access_token(force_refresh)
- except Exception as error: # noqa: BLE001 - surfaced as a provider failure
- raise AccessTokenProviderError.Failed(str(error)) from error
-
-
-class _FleetClient:
- """Thin async facade over the generated Cyclops SDK."""
-
- def __init__(self) -> None:
- self._closed = False
- fleet_token = get_fleet_token()
- session = False
- if not fleet_token:
- client_id = get_client_id()
- client_secret = get_client_secret()
- if not client_id or not client_secret:
- from cua_sandbox._config import (
- FLEET_CREDENTIALS_MISSING,
- has_fleet_session,
- )
-
- if not has_fleet_session():
- raise ValueError(FLEET_CREDENTIALS_MISSING)
- session = True
- self._base_url = get_fleet_base_url().rstrip("/")
- self._http_client = CyclopsHttpClient()
- if session:
- configuration = CyclopsTokenProviderConfiguration(
- base_url=self._base_url,
- pool_poll_interval_ms=2000,
- pool_poll_limit=300,
- claim_poll_interval_ms=2000,
- claim_poll_limit=300,
- )
- self._client = CyclopsClient.connect_with_access_token_provider(
- configuration, _SessionAccessTokenProvider(), self._http_client
- )
- return
- if fleet_token:
- configuration = CyclopsTokenProviderConfiguration(
- base_url=self._base_url,
- pool_poll_interval_ms=2000,
- pool_poll_limit=300,
- claim_poll_interval_ms=2000,
- claim_poll_limit=300,
- )
- self._client = CyclopsClient.connect_with_access_token_provider(
- configuration,
- (
- _GitHubActionsAccessTokenProvider(fleet_token)
- if os.environ.get("ACTIONS_ID_TOKEN_REQUEST_URL", "").strip()
- and os.environ.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "").strip()
- else _StaticAccessTokenProvider(fleet_token)
- ),
- self._http_client,
- )
- return
- configuration = CyclopsConfiguration(
- base_url=self._base_url,
- token_url=get_token_url(),
- credentials=CyclopsCredentials(client_id, client_secret),
- pool_poll_interval_ms=2000,
- pool_poll_limit=300,
- claim_poll_interval_ms=2000,
- claim_poll_limit=300,
- )
- self._client = CyclopsClient.connect(configuration, self._http_client)
-
- async def close(self) -> None:
- if self._closed:
- return
- await self._http_client.aclose()
- self._closed = True
-
- async def create_pool(self, request: CreatePoolRequest) -> Any:
- return await self._client.create_pool(request)
-
- async def reconcile_pool(self, request: CreatePoolRequest) -> Any:
- return await self._client.reconcile_pool(request)
-
- async def create_template(self, request: CreateTemplateRequest) -> Any:
- return await self._client.create_template(request)
-
- async def reconcile_template(self, request: CreateTemplateRequest) -> Any:
- return await self._client.reconcile_template(request)
-
- async def get_template(self, namespace: str, name: str) -> Any:
- return await self._client.get_template(namespace, name)
-
- async def delete_template(self, template: Any) -> None:
- await self._client.delete_template(template)
-
- async def get_namespace(self, name: str) -> Any:
- return await self._client.get_namespace(name)
-
- async def create_namespace(self, name: str) -> Any:
- return await self._client.create_namespace(name)
-
- async def delete_namespace(self, name: str) -> None:
- await self._client.delete_namespace(name)
-
- async def create_claim(self, request: CreateClaimRequest) -> Any:
- return await self._client.create_claim(request)
-
- async def wait_pool(self, pool: Any, timeout: float = 900.0, poll_interval: float = 5.0) -> Any:
- deadline = asyncio.get_running_loop().time() + timeout
- while True:
- pools = await self._client.list_pools(pool.metadata.namespace)
- for current_pool in pools:
- if current_pool.metadata.name != pool.metadata.name:
- continue
- if current_pool.status and (current_pool.status.ready_replicas or 0) >= 1:
- return current_pool
- break
- if asyncio.get_running_loop().time() >= deadline:
- raise TimeoutError(
- f"Timed out waiting for Fleet pool {pool.metadata.name!r} to warm up"
- )
- await asyncio.sleep(poll_interval)
-
- async def wait_claim(self, claim: Any) -> Any:
- return await self._client.wait_claim(claim)
-
- async def renew_claim(self, claim: Any, shutdown_time: str) -> Any:
- renew = getattr(self._client, "renew_claim", None)
- if renew is None:
- raise RuntimeError(
- "the installed cua-fleet release does not support claim renewal; "
- "upgrade to a build whose CyclopsClient exposes renew_claim"
- )
- return await renew(claim, shutdown_time)
-
- async def delete_claim(self, claim: Any) -> None:
- await self._client.delete_claim(claim)
-
- async def delete_pool(self, pool: Any) -> None:
- await self._client.delete_pool(pool)
-
- async def update_pool(self, pool: Any) -> Any:
- return await self._client.update_pool(pool)
-
- async def service_request(
- self, sandbox: Any, service: str, path: str, request: HttpRequest
- ) -> Any:
- return await self._client.service_request(sandbox, service, path, request)
-
- async def create_signed_service_url(
- self,
- sandbox: Any,
- service: str,
- *,
- label: str | None,
- expires_in_seconds: int,
- ) -> Any:
- try:
- from fleet_sdk import CreateSignedServiceUrlRequestBuilder
- except ImportError as error:
- raise RuntimeError(
- "Signed service URLs require a cua-fleet release with signed URL support"
- ) from error
-
- builder = (
- CreateSignedServiceUrlRequestBuilder()
- .sandbox(sandbox)
- .service(service)
- .expires_in_seconds(expires_in_seconds)
- )
- if label is not None:
- builder = builder.label(label)
- method = getattr(self._client, "create_signed_service_url", None)
- if method is None:
- raise RuntimeError(
- "Signed service URLs require a cua-fleet release with signed URL support"
- )
- return await method(builder.build())
-
- async def list_signed_service_urls(self, sandbox: Any) -> list[Any]:
- method = getattr(self._client, "list_signed_service_urls", None)
- if method is None:
- raise RuntimeError(
- "Signed service URLs require a cua-fleet release with signed URL support"
- )
- return await method(sandbox)
-
- async def revoke_signed_service_url(self, signed_service_url: Any) -> None:
- try:
- from fleet_sdk import SignedServiceUrl
- except ImportError as error:
- raise RuntimeError(
- "Signed service URLs require a cua-fleet release with signed URL support"
- ) from error
-
- method = getattr(self._client, "revoke_signed_service_url", None)
- if method is None:
- raise RuntimeError(
- "Signed service URLs require a cua-fleet release with signed URL support"
- )
- await method(
- SignedServiceUrl(
- id=signed_service_url.id,
- namespace=_detail(signed_service_url, "namespace"),
- claim=_detail(signed_service_url, "claim"),
- sandbox=signed_service_url.sandbox,
- service=signed_service_url.service,
- label=signed_service_url.label,
- url=signed_service_url.url,
- created_at=signed_service_url.created_at,
- expires_at=signed_service_url.expires_at,
- revoked_at=signed_service_url.revoked_at,
- )
- )
-
- async def get_pool(self, name: str) -> Any:
- return await self._client.get_pool(name)
-
- async def list_claims(self, namespace: str) -> list[Any]:
- return await self._client.list_claims(namespace)
-
- async def get_claim(self, pool: Any, name: str | None = None) -> Any:
- expected = name or _claim_name(pool.metadata.name)
- for claim in await self._client.list_claims(pool.metadata.namespace):
- if claim.metadata.name == expected:
- return claim
- raise LookupError(f"Fleet claim {expected!r} was not found")
-
- async def list_namespaces(self) -> list[Any]:
- """The caller's namespaces (tenant-scoped by the Fleet gateway)."""
- return await self._client.list_namespaces()
-
- async def list_pools_in(self, namespace: str) -> list[Any]:
- return await self._client.list_pools(namespace)
-
- async def list_pools(self) -> list[Any]:
- raise NotImplementedError(
- "Fleet sandbox listing requires namespace discovery; use an exact sandbox name instead"
- )
-
- async def set_pool_replicas(self, pool: Any, replicas: int) -> Any:
- pool.spec.replicas = replicas
- return await self._client.update_pool(pool)
-
- async def wait_service_ready(
- self, sandbox: Any, service: str, time_to_start: Optional[float] = None
- ) -> None:
- """Wait until the gateway routes to *service* (any HTTP answer < 500).
-
- Daemon-agnostic: nothing guest-specific is assumed (no ``/status``,
- no port 8000). The ``env`` service is not probed here at all; the
- claim being bound is readiness, and the first interface call waits
- for cua-spacesd itself.
- """
- if service == ENV_SERVICE:
- return
- timeout = time_to_start if time_to_start is not None else 600.0
- deadline = asyncio.get_running_loop().time() + timeout
- while True:
- response = await self.service_request(
- sandbox,
- service,
- "/",
- build_http_request(
- method="GET",
- url="https://service.invalid/",
- timeout_secs=_READINESS_PROBE_TIMEOUT_SECS,
- ),
- )
- if 200 <= response.status < 500:
- return
- if asyncio.get_running_loop().time() >= deadline:
- raise TimeoutError(
- f"Fleet service {service!r} did not become ready within {timeout} seconds"
- )
- await asyncio.sleep(2)
-
- def service_url(self, sandbox: Any, service: str) -> str:
- if service not in sandbox.services:
- raise ValueError(f"Fleet sandbox does not expose service {service!r}")
- return f"{self._base_url}/api/svc/{sandbox.namespace}/{sandbox.name}-{service}/"
-
-
-def _detail(resource: Any, key: str) -> Any:
- """``key`` of a signed URL: from ``details`` (``SignedServiceURL``) or
- the raw resource attribute."""
- details = resource.__dict__.get("details") if hasattr(resource, "__dict__") else None
- if isinstance(details, dict) and key in details:
- return details[key]
- return getattr(resource, key)
-
-
-_ECR_HOST_SUFFIX = ".amazonaws.com"
-_ECR_HOST_MARKER = ".dkr.ecr."
-
-
-def _needs_ecr_pull_secret(image: "str | None") -> bool:
- """True only for the account's private ECR, which the secret authenticates.
-
- Public registries (public.ecr.aws, ghcr.io, quay.io, Docker Hub) are pulled
- anonymously; attaching a credential for them makes the gateway enforce its
- private-registry allowlist against an image that never needed one.
- """
- if not image:
- return False
- host = image.split("/", 1)[0]
- return _ECR_HOST_MARKER in host and host.endswith(_ECR_HOST_SUFFIX)
-
-
-_TTL_SECONDS_MAX = 2**32 - 1
-
-
-def validate_ttl_seconds_after_created(value: "int | None") -> None:
- if value is not None and (
- isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= _TTL_SECONDS_MAX
- ):
- raise ValueError(
- f"ttl_seconds_after_created must be an integer between 0 and {_TTL_SECONDS_MAX}"
- )
-
-
-#: The Fleet runtimes an image-backed pool can use: ``kubevirt`` boots a VM
-#: from the containerDisk, ``gvisor`` runs the container variant as a runsc
-#: pod.
-FleetRuntime = Literal["kubevirt", "gvisor"]
-
-_RUNTIME_KINDS = {"kubevirt": RuntimeKind.KUBEVIRT, "gvisor": RuntimeKind.GVISOR}
-
-
-def resolve_fleet_runtime(runtime: Optional[str], image: Image) -> Any:
- """The ``fleet_sdk.RuntimeKind`` for a pool of *image*.
-
- ``runtime`` wins; otherwise it defaults from the image: ``kind="container"``
- runs on gVisor, ``kind="vm"`` boots on KubeVirt, and an unresolved kind
- follows the image's registry manifest (a ``/disk/disk.img`` layer or
- trycua containerDisk media types = KubeVirt, anything else = gVisor). When
- the manifest cannot be read, the reference decides with a warning (a
- ``docker-`` tag = gVisor, else KubeVirt). The pairing is validated by the
- cua SDK's single rule (``cua.fleet_resolve_runtime``, shared with the Rust
- SDK, CLI and Spaces), which raises ``CuaError.InvalidArgument`` for a
- crossed pairing.
- """
- if runtime is not None and runtime not in _RUNTIME_KINDS:
- raise ValueError(f"runtime must be 'kubevirt' or 'gvisor', not {runtime!r}")
- if runtime is None:
- runtime = {"container": "gvisor", "vm": "kubevirt"}.get(image.kind or "")
- reference = cloud_registry_image(image) or ""
- from cua_sandbox._sdk import native
-
- name = native().fleet_resolve_runtime(runtime, reference)
- return _RUNTIME_KINDS[name]
-
-
-def fleet_image_ref(image: Image, runtime: Any = None) -> Optional[str]:
- """The reference a Fleet template runs: the one native resolver's pinned
- variant for the runtime (a canonical image's ``-disk`` sibling on
- KubeVirt, its rootfs on gVisor), amd64. When the registry cannot be read
- (offline, or ``CUA_IMAGE_RESOLVE=0``) the reference is sent as given and
- Fleet reports what it cannot pull."""
- reference = cloud_registry_image(image)
- if not reference:
- return reference
- name = str(getattr(runtime, "name", runtime) or "").lower()
- backend = {"kubevirt": "vm", "gvisor": "container"}.get(name, "fleet")
- from cua_sandbox._sdk import native
-
- n = native()
- try:
- return n.resolve_image(reference, backend, "amd64").pinned_ref
- except n.CuaError.Unsupported:
- raise
- except n.CuaError as error:
- logger.debug("could not resolve %s for Fleet (%s); sending it as given", reference, error)
- return reference
-
-
-class FleetCloudTransport(FleetTransport):
- """Provision image-backed pools or claim pre-created pools through Fleet."""
-
- def __init__(
- self,
- *,
- image: Optional[Image],
- name: str,
- cpu: Optional[int] = None,
- memory_mb: Optional[int] = None,
- disk_gb: Optional[int] = None,
- region: str = "us-east-1",
- time_to_start: Optional[float] = None,
- request_timeout: Optional[float] = None,
- server_port: Optional[int] = None,
- pool_name: str | None = None,
- create_claim: bool = False,
- replicas: int = 1,
- services: Mapping[str, int] | None = None,
- autoscaling: Optional[WarmPoolAutoscaling] = None,
- ttl_seconds_after_created: Optional[int] = None,
- fleet_runtime: Optional[FleetRuntime] = None,
- ) -> None:
- validate_server_port(server_port)
- if disk_gb is not None:
- raise ValueError("disk_gb is not supported by the Fleet cloud transport")
- if region != "us-east-1":
- raise ValueError("Fleet cloud sandboxes currently support only region='us-east-1'")
- if isinstance(replicas, bool) or not isinstance(replicas, int) or replicas < 1:
- raise ValueError("replicas must be a positive integer")
- if services is not None and (
- not isinstance(services, Mapping)
- or not services
- or any(
- not isinstance(name, str)
- or not name
- or not isinstance(port, int)
- or port < 1
- or port > 65535
- for name, port in services.items()
- )
- ):
- raise ValueError("services must map non-empty names to TCP ports")
- if autoscaling is not None:
- if not isinstance(autoscaling, WarmPoolAutoscaling):
- raise TypeError("autoscaling must be a fleet_sdk.WarmPoolAutoscaling")
- for field, minimum in (
- ("min_pool_size", 0),
- ("initial_pool_size", 0),
- ("max_pool_size", 1),
- ):
- value = getattr(autoscaling, field)
- if value is not None and (
- isinstance(value, bool) or not isinstance(value, int) or value < minimum
- ):
- raise ValueError(f"autoscaling.{field} must be an integer >= {minimum}")
- if (
- autoscaling.min_pool_size is not None
- and autoscaling.max_pool_size is not None
- and autoscaling.min_pool_size > autoscaling.max_pool_size
- ):
- raise ValueError(
- "autoscaling.min_pool_size must not exceed autoscaling.max_pool_size"
- )
- validate_ttl_seconds_after_created(ttl_seconds_after_created)
- self._image = image
- # Resolved (and validated) up front, before any Fleet resource exists.
- self._runtime = (
- resolve_fleet_runtime(fleet_runtime, image)
- if image is not None and cloud_registry_image(image)
- else None
- )
- if fleet_runtime is not None and self._runtime is None:
- raise ValueError("a Fleet runtime applies only to Fleet registry images")
- self._name = name
- self._explicit_pool = pool_name is not None
- self._pool_name = pool_name or name
- self._create_claim = create_claim
- self._claim_name = name if pool_name else _claim_name(name)
- self._cpu = cpu
- self._memory_mb = memory_mb
- self._time_to_start = time_to_start if time_to_start is not None else 600.0
- self._request_timeout = request_timeout or 30.0
- self._server_port = server_port
- self._primary_service = ENV_SERVICE if server_port is None else _SERVER_SERVICE
- self._primary_port = SPACESD_PORT if server_port is None else server_port
- self._replicas = replicas
- self._services = dict(services) if services is not None else None
- self._autoscaling = autoscaling
- self._ttl_seconds_after_created = ttl_seconds_after_created
- self._provisioned = False
- self._owns_resources = image is not None or create_claim
- self._template: Any = None
- self._pool: Any = None
- self._claim: Any = None
- self._sdk: Any = None
-
- @property
- def name(self) -> str:
- return self._name
-
- async def connect(self) -> None:
- if not self._provisioned:
- if self._sdk is None:
- self._sdk = _FleetClient()
- try:
- if self._pool is None:
- if self._image is None:
- self._pool = await self._sdk.get_pool(self._pool_name)
- if self._create_claim:
- self._pool = await self._sdk.set_pool_replicas(self._pool, 1)
- self._pool = await self._sdk.wait_pool(self._pool)
- else:
- self._validate_image(self._image)
- try:
- self._pool = await self._sdk.reconcile_pool(self._pool_request())
- self._template = await self._sdk.reconcile_template(
- self._template_request()
- )
- except _NATIVE_POOL_ACCESS_DENIED as error:
- raise _canonicalize_pool_access_denied(error)
- except SdkError.Status as error:
- if error.status == 403:
- raise _pool_access_denied(self._pool_name, error) from error
- raise
- self._pool = await self._sdk.wait_pool(self._pool)
- if self._claim is None:
- if self._image is None and not self._create_claim:
- self._claim = await self._get_claim()
- else:
- try:
- self._claim = await self._sdk.create_claim(
- CreateClaimRequest(
- pool=self._pool, spec=None, name=self._claim_name
- )
- )
- except Exception as create_error:
- try:
- self._claim = await self._get_claim()
- except Exception as lookup_error:
- raise create_error from lookup_error
- bound = await self._sdk.wait_claim(self._claim)
- await self._sdk.wait_service_ready(
- bound, self._primary_service, self._time_to_start
- )
- except BaseException as provisioning_error:
- cleanup_error: BaseException | None = None
- try:
- if self._owns_resources:
- await self._cleanup_resources()
- except BaseException as error:
- cleanup_error = error
- finally:
- if self._owns_resources:
- self._pool = None
- self._template = None
- if cleanup_error is not None:
- logger.warning(
- "Failed to clean up Fleet sandbox %r: %s", self._name, cleanup_error
- )
- raise provisioning_error from cleanup_error
- raise
- FleetTransport.__init__(
- self,
- sdk=self._sdk,
- bound=bound,
- service_name=self._primary_service,
- timeout=self._request_timeout,
- )
- self._provisioned = True
- await FleetTransport.connect(self)
-
- async def disconnect(self) -> None:
- if not self._provisioned:
- return
- await FleetTransport.disconnect(self)
-
- async def create_snapshot(self, **_: Any) -> dict[str, Any]:
- raise NotImplementedError("Snapshots are not supported by the Fleet cloud transport")
-
- async def forward_tunnel(self, sandbox_port: int | str) -> "TunnelInfo":
- if not isinstance(sandbox_port, int):
- raise ValueError("Fleet services can only expose numeric TCP ports")
- if not self._provisioned:
- raise ValueError("Transport not connected")
- # A loopback forward either way: over the spacesd's /tunnel when
- # the image has it, else a proxy through the gateway.
- return await FleetTransport.forward_tunnel(self, sandbox_port)
-
- async def delete_vm(self) -> None:
- await self._cleanup_resources()
-
- async def _cleanup_resources(self) -> None:
- if self._claim is not None:
- await self._sdk.delete_claim(self._claim)
- self._claim = None
- self._provisioned = False
-
- @classmethod
- async def list_sandboxes(cls) -> list[Any]:
- sdk = _FleetClient()
- try:
- return await sdk.list_pools()
- finally:
- await sdk.close()
-
- @classmethod
- async def get_sandbox_info(cls, name: str) -> Any:
- sdk = _FleetClient()
- try:
- return await sdk.get_pool(name)
- finally:
- await sdk.close()
-
- @classmethod
- async def delete_sandbox(cls, name: str, *, pool_name: str | None = None) -> None:
- sdk = _FleetClient()
- try:
- pool = await sdk.get_pool(pool_name or name)
- if pool_name is not None:
- claim = await sdk.get_claim(pool, name)
- else:
- claim = await sdk.get_claim(pool)
- await sdk.delete_claim(claim)
- finally:
- await sdk.close()
-
- async def _get_claim(self) -> Any:
- if self._explicit_pool:
- return await self._sdk.get_claim(self._pool, self._claim_name)
- return await self._sdk.get_claim(self._pool)
-
- def _template_request(self) -> CreateTemplateRequest:
- assert self._image is not None
- if self._services is not None and self._server_port is None:
- # Caller-declared services are published exactly as given.
- service_ports = dict(self._services)
- elif self._services is not None:
- service_ports = {
- _SERVER_SERVICE: self._server_port,
- **{name: port for name, port in self._services.items() if name != _SERVER_SERVICE},
- }
- else:
- service_ports = default_services(self._server_port, self._image._ports)
- services = [
- SandboxServiceBuilder()
- .name(name)
- .target_port(port)
- .protocol(ServiceProtocol.TCP)
- .build()
- for name, port in service_ports.items()
- ]
- container_disk_image = fleet_image_ref(self._image, self._runtime)
- vm_template_builder = (
- VmTemplateBuilder().container_disk_image(container_disk_image).services(services)
- )
- if self._runtime is not None:
- vm_template_builder = vm_template_builder.runtime(self._runtime)
- # Daemon-agnostic readiness: a claim binds once the VM runs. Only a
- # port the caller declared (server_port, or a "server" service)
- # becomes a readiness probe; the default env service is waited for by
- # the first interface call.
- probe_port = (
- self._server_port
- if self._server_port is not None
- else service_ports.get(_SERVER_SERVICE)
- )
- if probe_port is not None:
- vm_template_builder = vm_template_builder.probes(
- PreservedJson.from_json(
- json.dumps({"readinessProbe": {"tcpSocket": {"port": probe_port}}})
- )
- )
- # The pull secret authenticates the account's private ECR and nothing else.
- # Attaching it to a public image is not merely redundant: the gateway's
- # admission policy reads its presence as "enforce the ECR allowlist", so a
- # public image the cluster can pull anonymously was refused outright.
- if _needs_ecr_pull_secret(container_disk_image):
- vm_template_builder = vm_template_builder.image_pull_secret("ecr-credentials")
-
- # Windows guest disks are built UEFI-only (see registry/qemu_builder.py), and the
- # Fleet schema defaults firmware to BIOS, so a Windows image left at the default
- # boots SeaBIOS against a GPT/ESP disk and never reaches the readiness probe.
- # The local QEMU runtime keys off the same os_type check.
- if self._image.os_type == "windows":
- vm_template_builder = vm_template_builder.firmware(Firmware.EFI)
- if self._cpu is not None:
- vm_template_builder = vm_template_builder.cpu_cores(self._cpu)
- if self._memory_mb is not None:
- vm_template_builder = vm_template_builder.memory(f"{self._memory_mb}Mi")
-
- template_spec = (
- OsGymSandboxTemplateSpecBuilder().vm_template(vm_template_builder.build()).build()
- )
- return (
- CreateTemplateRequestBuilder()
- .namespace(self._pool_name)
- .name(self._pool_name)
- .spec(template_spec)
- .build()
- )
-
- def _pool_request(self) -> CreatePoolRequest:
- template_ref = SandboxTemplateRefBuilder().name(self._pool_name).build()
- pool_spec_builder = (
- OsGymSandboxWarmPoolSpecBuilder()
- .replicas(self._replicas)
- .sandbox_template_ref(template_ref)
- )
- if self._autoscaling is not None:
- pool_spec_builder = pool_spec_builder.autoscaling(self._autoscaling)
- if self._ttl_seconds_after_created is not None:
- pool_spec_builder = pool_spec_builder.ttl_seconds_after_created(
- self._ttl_seconds_after_created
- )
- return (
- CreatePoolRequestBuilder()
- .namespace(self._pool_name)
- .spec(pool_spec_builder.build())
- .build()
- )
-
- @staticmethod
- def _service_names(template: Any) -> list[str]:
- return [service.name for service in template.spec.vm_template.services or []] or [
- ENV_SERVICE
- ]
-
- @staticmethod
- def _validate_image(image: Image) -> None:
- if not cloud_registry_image(image):
- raise NotImplementedError(
- "Fleet cloud sandboxes require a supported built-in image or Image.from_registry(...)"
- )
- if image._snapshot_source or image._disk_path:
- raise NotImplementedError(
- "Fleet cloud runs registry images (layers build remotely on them); local disk "
- "files and snapshots stay local"
- )
-
-
-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: Optional[int] = None) -> Optional[int]:
- """Resolve the guest control-server port for an image.
-
- ``None`` is the daemon-agnostic default (cua-spacesd on ``env``). A
- caller-supplied ``server_port`` wins; otherwise an OSWorld image
- (``agent_type="osworld"``, the legacy adapter) selects the OSWorld Flask
- server on 5000, published as ``server``.
- """
- if server_port is None 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 1553d4f065..7f0bdcae3b 100644
--- a/libs/python/cua-sandbox/cua_sandbox/transport/osworld.py
+++ b/libs/python/cua-sandbox/cua_sandbox/transport/osworld.py
@@ -31,56 +31,6 @@ def normalize_execute_result(payload: Dict[str, Any]) -> Dict[str, Any]:
}
-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)."""
diff --git a/libs/python/cua-sandbox/docs/typed-driver-development.md b/libs/python/cua-sandbox/docs/typed-driver-development.md
index f8073b457a..024e6805a4 100644
--- a/libs/python/cua-sandbox/docs/typed-driver-development.md
+++ b/libs/python/cua-sandbox/docs/typed-driver-development.md
@@ -3,54 +3,45 @@
This developer contract describes the candidate implementation, not a released
setup guide. It needs the matching generated `cua-driver` package and native
library with `connect_remote_channel`, plus a guest carrier: cua-spacesd's
-`/mcp` route with the [typed-envelope MCP extension](../../../cua-driver/docs/mcp-envelope-carrier.md)
-(the default), or a Fleet service implementing the
-[private envelope carrier](../../../cua-driver/docs/private-envelope-http.md).
+`/mcp` route with the [typed-envelope MCP extension](../../../cua-driver/docs/mcp-envelope-carrier.md).
Do not infer support from an image containing an older Driver or an MCP server.
No published package version or image is qualified by this document.
## Keep the existing responsibilities
-Sandbox owns provisioning, claims, shell commands, files, and cleanup. Driver
+Sandbox owns provisioning, shell commands, files, and cleanup. Driver
provides its canonical typed desktop interface. The existing Sandbox methods
(served by cua-spacesd through the cua SDK) remain available; connecting
Driver does not replace them. MCP remains a separate agent-harness integration.
-The accessor supports Fleet and cua-spacesd (`EnvTransport`) sandboxes, with
-no fallback between carriers:
+The accessor supports cua-spacesd (`EnvTransport`) sandboxes; named Driver
+services were a Cua Cloud feature and raise `DriverConnectionError`:
| Call | Carrier |
|---|---|
-| `connect()` | Fleet `driver` service if the claim publishes one, else spacesd `/mcp` |
-| `connect(service="env", transport="mcp")` | spacesd `/mcp` via the cua SDK env client (Fleet, direct, local) |
-| `connect(service="driver")` | Fleet private envelope HTTP service |
-| `connect(service="mcp", transport="mcp")` | Fleet named MCP service |
-
-Fleet carriers use the sandbox's authenticated, namespace-authorized
-named-service route. A guest carrier must remain behind that route or the
-spacesd token; its loopback listener does not authenticate callers.
-Connection generations and public session names are lifecycle metadata, not
-credentials or proof of guest-verified claim authorization. There is never a
+| `connect()` | spacesd `/mcp` via the cua SDK env client (direct, local) |
+| `connect(service="env", transport="mcp")` | the same |
+
+A guest carrier must remain behind the spacesd token; its loopback listener
+does not authenticate callers. Connection generations and public session names are lifecycle metadata, not
+credentials or proof of guest-verified authorization. There is never a
fallback to the caller's own desktop.
## Use the canonical typed interface
-Given an already configured pool exposing the candidate `driver` service, the
+Given a sandbox whose image runs cua-spacesd with the envelope extension, the
proposed usage is:
```python
from cua_driver import GetAgentCursorStateInput, GetScreenSizeInput
-async def inspect_guest(pool):
- async with pool.claim() as sandbox:
- async with sandbox.driver.connect(service="driver") as driver:
- size = await driver.get_screen_size(GetScreenSizeInput(session=None))
- session = sandbox.driver.session_name(driver)
- cursor = await driver.get_agent_cursor_state(
- GetAgentCursorStateInput(session=session)
- )
- return size, cursor
+async def inspect_guest(sandbox):
+ async with sandbox.driver.connect() as driver:
+ size = await driver.get_screen_size(GetScreenSizeInput(session=None))
+ session = sandbox.driver.session_name(driver)
+ cursor = await driver.get_agent_cursor_state(GetAgentCursorStateInput(session=session))
+ return size, cursor
```
`driver` is the generated `cua_driver.CuaDriver`, not a parallel desktop API.
@@ -70,30 +61,30 @@ invalidate the connection. The accessor does not automatically reconnect or
replay an action whose completion is unknown. Connections belong to the event
loop that created them.
-Exiting the Driver context closes that remote session, not the shared daemon,
-spacesd, claim, or pool. Sandbox disconnect, release, and destroy close
-Driver connections before their transport. Cleanup is best effort with bounded
-waits; an unconfirmed cleanup logs a warning and does not block claim release.
+Exiting the Driver context closes that remote session, not the shared daemon
+or spacesd. Sandbox disconnect and destroy close Driver connections before
+their transport. Cleanup is best effort with bounded waits; an unconfirmed
+cleanup logs a warning and does not block the sandbox's release.
The carrier's independent session expiry remains the fallback for unreachable
cleanup. A successful local close is not proof that a remote guest was deleted.
Opening handshakes do not hold the accessor's lifecycle lock. Closing the
accessor invalidates pending opens and bounds the wait for them, so a stalled
-handshake cannot indefinitely delay claim release. If a cancelled open later
+handshake cannot indefinitely delay the sandbox's release. If a cancelled open later
returns a connection ID, the accessor attempts to delete it without yielding a
Driver. Deletion can remain unconfirmed if the owning transport has already
disconnected or the handshake never returns its connection ID.
Each Driver exchange uses the envelope's remaining deadline, capped at 120
-seconds, for its per-request Fleet timeout and local wait. This does not change
-the transport's default timeout for other callers. Expired
-requests fail before dispatch. A locally timed-out or cancelled exchange
-invalidates the connection and attempts bounded cancellation and deletion; it
-does not replay the desktop action.
+seconds, for its per-request timeout and local wait. This does not change the
+transport's default timeout for other callers. Expired requests fail before
+dispatch. A locally timed-out or cancelled exchange invalidates the connection
+and attempts bounded cancellation and deletion; it does not replay the desktop
+action.
## Verification and remaining proof
-The focused tests cover named-service routing, canonical method dispatch,
+The focused tests cover spacesd `/mcp` routing, canonical method dispatch,
response validation, cancellation, and lifecycle ordering. CI requires the
native bridge integration test through `CUA_SANDBOX_REQUIRE_NATIVE_DRIVER=1`;
it fails instead of skipping when the matching native package is absent.
@@ -102,8 +93,7 @@ per-request deadlines, and preservation of ordinary transport timeouts.
These synthetic tests do not prove a real guest desktop effect. Before a
released tutorial or supported-image claim, qualify the exact candidate on a
-Fleet guest: private service routing, observed desktop postcondition,
-coexistence with the spacesd interfaces, stale-connection rejection, and
-resource cleanup.
+guest: spacesd routing, observed desktop postcondition, coexistence with the
+spacesd interfaces, stale-connection rejection, and resource cleanup.
Local guest support needs a separately verified runtime binding and must never
resolve a guest request to the caller's desktop.
diff --git a/libs/python/cua-sandbox/pyproject.toml b/libs/python/cua-sandbox/pyproject.toml
index 06b4ab044e..b7d93a7d5e 100644
--- a/libs/python/cua-sandbox/pyproject.toml
+++ b/libs/python/cua-sandbox/pyproject.toml
@@ -28,14 +28,11 @@ classifiers = [
requires-python = ">=3.11,<3.14"
dependencies = [
- # The cua SDK (Rust core, UniFFI): spacesd, Fleet sandboxes, local runtimes.
+ # The cua SDK (Rust core, UniFFI): spacesd and the local runtimes.
"cua>=0.2.0",
# Telemetry only (imported optionally): 0.1.x is allowed so cua-sandbox
# co-installs with cua-computer 0.5 / cua-agent 0.7 based harnesses.
"cua-core>=0.1.18,<0.4.0",
- # Typed Fleet resource model (pool/template/claim builders) re-exported by
- # cua_sandbox; the cua SDK covers the data plane.
- "cua-fleet==0.1.17",
"pydantic>=2.11,<3.0",
"jsonschema>=4.23,<5.0",
"httpx>=0.27.0",
@@ -116,12 +113,3 @@ dev = [
[tool.uv.sources]
cua-agent = { path = "../agent", editable = true }
cua = { path = "../../cua/python", editable = true }
-
-[[tool.uv.index]]
-name = "cua-wheels"
-url = "https://wheels.cua.ai/simple"
-
-[[tool.pdm.source]]
-name = "cua-wheels"
-url = "https://wheels.cua.ai/simple"
-include_packages = ["cua-fleet"]
diff --git a/libs/python/cua-sandbox/scripts/live_local_linux_docker.py b/libs/python/cua-sandbox/scripts/live_local_linux_docker.py
index f614f4b31e..2dbd1910dd 100755
--- a/libs/python/cua-sandbox/scripts/live_local_linux_docker.py
+++ b/libs/python/cua-sandbox/scripts/live_local_linux_docker.py
@@ -5,10 +5,6 @@
#
# [tool.uv.sources]
# cua-sandbox = { path = "..", editable = true }
-#
-# [[tool.uv.index]]
-# name = "cua-wheels"
-# url = "https://wheels.cua.ai/simple"
# ///
"""Exercise the local Linux Docker sandbox on a real host."""
diff --git a/libs/python/cua-sandbox/tests/_driver_env_support.py b/libs/python/cua-sandbox/tests/_driver_env_support.py
new file mode 100644
index 0000000000..39fcf30210
--- /dev/null
+++ b/libs/python/cua-sandbox/tests/_driver_env_support.py
@@ -0,0 +1,259 @@
+"""Shared helpers for the ``sb.driver`` tests.
+
+``sb.driver`` rides cua-spacesd's ``/mcp`` through the cua SDK's env client
+(``SpacesdClient.http``). These tests never reach a guest: ``McpTransport`` is a
+synthetic MCP receiver, and ``EnvHttp`` is a stand-in ``cua.SpacesdClient``
+whose ``http`` is served by it (or by a canned reply). Import the fixtures into
+a test module the way the other driver tests do (``native = _native_fixture``).
+"""
+
+import asyncio
+import json
+import sys
+from types import SimpleNamespace
+
+import httpx
+import pytest
+from cua_sandbox import _sdk
+from cua_sandbox.sandbox import Sandbox
+from cua_sandbox.transport.env import EnvTransport
+
+
+class ChannelError(Exception):
+ pass
+
+
+class CanonicalDriver:
+ def __init__(self, channel):
+ self.channel = channel
+ self.shutdowns = 0
+
+ async def shutdown(self):
+ self.shutdowns += 1
+ await self.channel.close()
+
+
+def native(monkeypatch):
+ """A fake ``cua_driver`` module, for the tests that must not load the real one."""
+ sdk = SimpleNamespace(
+ CuaDriver=CanonicalDriver,
+ ForeignDriverEnvelopeChannel=object,
+ ForeignDriverChannelError=SimpleNamespace(Failed=ChannelError),
+ ForeignDriverChannelCapabilities=SimpleNamespace,
+ ForeignDriverChannelIdentity=SimpleNamespace,
+ ForeignDriverResponseEnvelope=SimpleNamespace,
+ connect_remote_channel=CanonicalDriver,
+ _native=SimpleNamespace(uniffi_set_event_loop=lambda loop: None),
+ )
+ monkeypatch.setitem(sys.modules, "cua_driver", sdk)
+ return sdk
+
+
+def shared(native):
+ """``native`` plus a fake shared MCP channel; yields ``(native, channels)``."""
+ channels = []
+
+ class Channel:
+ def __init__(self, transport, principal):
+ self.transport, self.principal = transport, principal
+ self.opened, self.closes = False, 0
+ self.canonical = native.CuaDriver(self)
+ channels.append(self)
+
+ async def open(self):
+ self.opened = True
+
+ def driver(self):
+ assert self.opened
+ return self.canonical
+
+ def public_session(self):
+ return "host-selected"
+
+ async def close(self):
+ self.closes += 1
+
+ native.DriverServiceTransport = object
+ native.DriverServiceHeader = SimpleNamespace
+ native.DriverServiceResponse = SimpleNamespace
+ native.DriverServiceTransportError = SimpleNamespace(Failed=RuntimeError)
+ native.open_mcp_driver_channel = Channel
+ return native, channels
+
+
+def records(monkeypatch):
+ """The SDK's record types, without the native library."""
+ types = SimpleNamespace(SpacesdHttpRequest=SimpleNamespace, SpacesdHttpHeader=SimpleNamespace)
+ monkeypatch.setattr(_sdk, "native", lambda: types)
+ return types
+
+
+def negotiation():
+ return dict(
+ connection_id="connection-1",
+ generation="generation-1",
+ public_session="session-1",
+ capabilities=dict(
+ minimum_envelope_version=1, maximum_envelope_version=1, supports_cancellation=True
+ ),
+ )
+
+
+class McpTransport:
+ """A synthetic MCP receiver speaking the typed-envelope extension."""
+
+ def __init__(self, *, sse=False, supported=True):
+ self.events = []
+ self.open_data = negotiation()
+ self.response_data = dict(
+ envelope_version=1,
+ request_id="request-1",
+ ok=True,
+ result={"width": 1280},
+ completion_known=True,
+ )
+ self.sse = sse
+ self.supported = supported
+ self.sessions = set()
+ self.sequence = 0
+ self.mutate = None
+ self.fail_exchange = False
+ self.exchange_started = asyncio.Event()
+ self.exchange_wait = None
+ self.cancel_releases_exchange = True
+ self.exchange_aborted = False
+ self.exchange_finished = asyncio.Event()
+ self.cancel_received = asyncio.Event()
+ self.exchange_timeouts = []
+
+ async def request_service(
+ self,
+ name,
+ *,
+ method,
+ path,
+ body=None,
+ json_body=None,
+ headers=None,
+ timeout=None,
+ max_response_bytes=None,
+ ):
+ assert max_response_bytes == 16 * 1024 * 1024
+ if body:
+ json_body = json.loads(body)
+ headers = httpx.Headers(headers)
+ self.events.append((name, method, path, json_body, headers))
+ assert name == "mcp" and path == "/mcp"
+ assert headers["Accept"] == "application/json, text/event-stream"
+ rpc = json_body.get("method") if json_body else None
+ response_headers = {}
+ if rpc == "initialize":
+ assert "Mcp-Session-Id" not in headers
+ self.sequence += 1
+ session = f"http-session-{self.sequence}"
+ self.sessions.add(session)
+ response_headers["Mcp-Session-Id"] = session
+ result = {
+ "protocolVersion": "2025-06-18",
+ "capabilities": {
+ "experimental": (
+ {"ai.cua.driver.envelopes": {"version": 1}} if self.supported else {}
+ )
+ },
+ }
+ else:
+ session = headers["Mcp-Session-Id"]
+ assert headers["MCP-Protocol-Version"] == "2025-06-18"
+ if session not in self.sessions:
+ return httpx.Response(404)
+ if method == "DELETE":
+ self.sessions.remove(session)
+ return httpx.Response(200)
+ if rpc == "notifications/initialized":
+ assert "id" not in json_body
+ return httpx.Response(202)
+ if rpc == "cua/driver/v1/open":
+ result = dict(self.open_data, connection_id=session, generation=f"gen-{session}")
+ else:
+ assert json_body["params"]["connection_id"] == session
+ assert json_body["params"]["generation"] == f"gen-{session}"
+ if rpc == "cua/driver/v1/exchange":
+ self.exchange_timeouts.append(timeout)
+ self.exchange_started.set()
+ if self.exchange_wait is not None:
+ try:
+ await self.exchange_wait.wait()
+ except asyncio.CancelledError:
+ self.exchange_aborted = True
+ raise
+ if self.fail_exchange:
+ raise RuntimeError("sensitive transport diagnostic")
+ request = json_body["params"]["envelope"]
+ result = dict(self.response_data, request_id=request["request_id"])
+ self.exchange_finished.set()
+ else:
+ assert rpc in ("cua/driver/v1/cancel", "cua/driver/v1/close")
+ if rpc == "cua/driver/v1/cancel":
+ self.cancel_received.set()
+ if self.cancel_releases_exchange and self.exchange_wait is not None:
+ self.exchange_wait.set()
+ result = {"ok": True}
+ response = {"jsonrpc": "2.0", "id": json_body["id"], "result": result}
+ if self.mutate:
+ response = self.mutate(rpc, response)
+ if self.sse:
+ response_headers["Content-Type"] = "text/event-stream"
+ return httpx.Response(
+ 200,
+ content=("event: message\r\ndata: " + json.dumps(response) + "\r\n\r\n"),
+ headers=response_headers,
+ )
+ return httpx.Response(200, json=response, headers=response_headers)
+
+
+class EnvHttp:
+ """A stand-in ``cua.SpacesdClient`` whose ``http`` is served by ``McpTransport``'s
+ synthetic MCP receiver (or a canned reply)."""
+
+ def __init__(self, mcp=None, reply=None):
+ self.mcp = mcp
+ self.reply = reply
+ self.requests = []
+
+ async def http(self, request):
+ self.requests.append(request)
+ if self.reply is not None:
+ return self.reply
+ response = await self.mcp.request_service(
+ "mcp",
+ method=request.method,
+ path=request.path,
+ body=bytes(request.body),
+ headers=[(h.name, h.value) for h in request.headers],
+ timeout=None if request.timeout_ms is None else request.timeout_ms / 1000,
+ max_response_bytes=request.max_response_bytes,
+ )
+ return SimpleNamespace(
+ status=response.status_code,
+ headers=[SimpleNamespace(name=k, value=v) for k, v in response.headers.multi_items()],
+ body=response.content,
+ )
+
+
+async def env_sandbox(env):
+ """A connected sandbox whose cua-spacesd client is ``env``."""
+
+ async def factory():
+ return env
+
+ sb = Sandbox(EnvTransport(env_factory=factory), _telemetry_enabled=False)
+ await sb._connect()
+ return sb
+
+
+async def sandbox(mcp):
+ """A connected sandbox whose cua-spacesd ``/mcp`` is the synthetic receiver ``mcp``."""
+ return await env_sandbox(EnvHttp(mcp=mcp))
diff --git a/libs/python/cua-sandbox/tests/_fake_fleet.py b/libs/python/cua-sandbox/tests/_fake_fleet.py
deleted file mode 100644
index f2fae3b665..0000000000
--- a/libs/python/cua-sandbox/tests/_fake_fleet.py
+++ /dev/null
@@ -1,310 +0,0 @@
-"""In-memory Fleet for hermetic managed-pool tests.
-
-Implements the ``_FleetClient`` surface cua-sandbox uses, backed by real
-``fleet_sdk`` records. Install it through the existing seam::
-
- fleet = FakeFleet()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", fleet.client)
-
-Nothing here touches the network, the host or real Fleet resources.
-"""
-
-from __future__ import annotations
-
-import itertools
-import threading
-from datetime import datetime, timezone
-from typing import Any
-
-from fleet_sdk import (
- Claim,
- ClaimSpec,
- Namespace,
- OsGymSandboxClaimCondition,
- OsGymSandboxClaimStatus,
- OsGymSandboxWarmPoolStatus,
- Pool,
- ResourceMetadata,
-)
-from fleet_sdk import Sandbox as BoundSandbox
-from fleet_sdk import (
- SdkError,
-)
-
-
-def _now() -> str:
- return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
-
-
-def _status_error(operation: str, status: int, body: str = "") -> SdkError:
- return SdkError.Status(operation, status, body)
-
-
-class FakeFleet:
- """Shared state for every client a test creates."""
-
- def __init__(self, *, tenant: str = "tenant-a") -> None:
- self.tenant = tenant
- self.lock = threading.Lock()
- self.namespaces: dict[str, dict[str, str]] = {}
- self.pools: dict[str, Pool] = {}
- self.templates: dict[str, Any] = {}
- self.claims: dict[tuple[str, str], Claim] = {}
- self.foreign: set[str] = set() # names held by another account
- self.terminating: set[str] = set() # own namespaces being deleted
- self.adoption_lag: dict[str, int] = {} # 403s before Capsule adopts
- self.hidden: dict[str, int] = {} # list_namespaces calls that miss a name
- self.calls: list[tuple] = []
- self.renewals: list[tuple[str, str]] = []
- self.patches: list[tuple[str, str, str, dict]] = []
- self.ready_replicas: dict[str, int] = {}
- self.fail_bind: dict[str, str] = {} # pool -> failure reason
- self.clients: list["FakeFleetClient"] = []
- self._ids = itertools.count(1)
-
- def client(self) -> "FakeFleetClient":
- client = FakeFleetClient(self)
- self.clients.append(client)
- return client
-
- def seed_pool(
- self,
- name: str,
- *,
- labels: dict[str, str] | None = None,
- created: str | None = None,
- replicas: int = 0,
- ) -> Pool:
- from fleet_sdk import OsGymSandboxWarmPoolSpecBuilder, SandboxTemplateRefBuilder
-
- self.namespaces[name] = {}
- pool = Pool(
- api_version="osgym.cua.ai/v1alpha1",
- kind="OSGymSandboxWarmPool",
- metadata=ResourceMetadata(
- namespace=name,
- name=name,
- labels=labels,
- creation_timestamp=created or _now(),
- ),
- spec=OsGymSandboxWarmPoolSpecBuilder()
- .replicas(replicas)
- .sandbox_template_ref(SandboxTemplateRefBuilder().name(name).build())
- .build(),
- status=None,
- )
- self.pools[name] = pool
- self.templates[name] = object()
- return pool
-
- def seed_claim(
- self,
- pool: str,
- name: str,
- *,
- phase: str = "Bound",
- created: str | None = None,
- managed: bool = False,
- ) -> Claim:
- claim = Claim(
- api_version="osgym.cua.ai/v1alpha1",
- kind="OSGymSandboxClaim",
- metadata=ResourceMetadata(
- namespace=pool,
- name=name,
- labels={"cua.ai/managed-by": "cua-sdk"} if managed else None,
- creation_timestamp=created or _now(),
- ),
- spec=ClaimSpec(
- sandbox_template_ref=self.pools[pool].spec.sandbox_template_ref,
- warmpool=pool,
- bind_deadline=None,
- lifecycle=None,
- ttl_seconds_after_created=None,
- ),
- status=OsGymSandboxClaimStatus(phase=phase, conditions=None, sandbox=None),
- )
- self.claims[(pool, name)] = claim
- return claim
-
-
-class FakeFleetClient:
- def __init__(self, fleet: FakeFleet) -> None:
- self.fleet = fleet
- self._closed = False
- self._authenticated = False
-
- # --- identity ---
-
- async def close(self) -> None:
- self._closed = True
-
- # --- namespaces / pools / templates ---
-
- async def list_namespaces(self) -> list[Namespace]:
- self._authenticated = True
- self.fleet.calls.append(("list_namespaces",))
- hidden = {name for name, left in self.fleet.hidden.items() if left > 0}
- for name in hidden:
- self.fleet.hidden[name] -= 1
- return [
- Namespace(
- name=name,
- status="Terminating" if name in self.fleet.terminating else "Active",
- created_at=labels.get("__created", _now()) if labels else _now(),
- labels=None,
- )
- for name, labels in self.fleet.namespaces.items()
- if name not in hidden
- ]
-
- async def get_pool(self, name: str) -> Pool:
- self.fleet.calls.append(("get_pool", name))
- if name in self.fleet.foreign:
- raise _status_error("get pool", 403, "forbidden")
- pool = self.fleet.pools.get(name)
- if pool is None:
- raise _status_error("get pool", 404, "not found")
- ready = self.fleet.ready_replicas.get(name)
- if ready is not None:
- pool.status = OsGymSandboxWarmPoolStatus(
- replicas=ready, ready_replicas=ready, selector=None
- )
- return pool
-
- async def create_namespace(self, name: str) -> Namespace:
- self.fleet.calls.append(("create_namespace", name))
- if name in self.fleet.foreign or name in self.fleet.namespaces:
- raise _status_error("create namespace", 409, "exists")
- self.fleet.namespaces[name] = {}
- return Namespace(name=name, status="Active", created_at=_now(), labels=None)
-
- async def create_pool(self, request: Any) -> Pool:
- name = request.namespace
- self.fleet.calls.append(("create_pool", name, request.spec))
- if name in self.fleet.foreign:
- raise SdkError.PoolAccessDenied("create pool", name, 403, "capsule denied")
- if self.fleet.adoption_lag.get(name):
- self.fleet.adoption_lag[name] -= 1
- raise SdkError.PoolAccessDenied("create pool", name, 403, "not adopted yet")
- if name in self.fleet.pools:
- raise _status_error("create pool", 409, "exists")
- self.fleet.namespaces[name] = {}
- pool = Pool(
- api_version="osgym.cua.ai/v1alpha1",
- kind="OSGymSandboxWarmPool",
- metadata=ResourceMetadata(
- namespace=name, name=name, labels=None, creation_timestamp=_now()
- ),
- spec=request.spec,
- status=None,
- )
- self.fleet.pools[name] = pool
- return pool
-
- async def reconcile_pool(self, request: Any) -> Pool: # pragma: no cover - must not be used
- raise AssertionError("managed pools must never reconcile (it fights KEDA)")
-
- async def update_pool(self, pool: Any) -> Pool: # pragma: no cover - must not be used
- raise AssertionError("managed pools must never rewrite a pool spec")
-
- async def reconcile_template(self, request: Any) -> Any:
- self.fleet.calls.append(("reconcile_template", request.name))
- self.fleet.templates[request.name] = request
- return request
-
- async def get_template(self, namespace: str, name: str) -> Any:
- if name not in self.fleet.templates:
- raise _status_error("get template", 404)
- return name
-
- async def delete_template(self, template: Any) -> None:
- self.fleet.calls.append(("delete_template", template))
- self.fleet.templates.pop(template, None)
-
- async def delete_pool(self, pool: Any) -> None:
- name = pool.metadata.name
- self.fleet.calls.append(("delete_pool", name))
- self.fleet.pools.pop(name, None)
-
- async def delete_namespace(self, name: str) -> None:
- self.fleet.calls.append(("delete_namespace", name))
- self.fleet.namespaces.pop(name, None)
-
- async def create_claim(self, request: Any) -> Claim:
- pool = request.pool
- namespace = pool.metadata.namespace
- name = request.name or f"{namespace}-claim-{next(self.fleet._ids)}"
- self.fleet.calls.append(("create_claim", namespace, name, request.spec))
- if (namespace, name) in self.fleet.claims:
- raise _status_error("create claim", 409)
- claim = Claim(
- api_version="osgym.cua.ai/v1alpha1",
- kind="OSGymSandboxClaim",
- metadata=ResourceMetadata(
- namespace=namespace, name=name, labels=None, creation_timestamp=_now()
- ),
- spec=request.spec
- or ClaimSpec(
- sandbox_template_ref=pool.spec.sandbox_template_ref,
- warmpool=None,
- bind_deadline=None,
- lifecycle=None,
- ),
- status=OsGymSandboxClaimStatus(phase="Pending", conditions=None, sandbox=None),
- )
- self.fleet.claims[(namespace, name)] = claim
- return claim
-
- async def list_claims(self, namespace: str) -> list[Claim]:
- if namespace not in self.fleet.pools:
- raise _status_error("list claims", 404)
- return [c for (ns, _), c in self.fleet.claims.items() if ns == namespace]
-
- async def wait_claim(self, claim: Any) -> BoundSandbox:
- namespace, name = claim.metadata.namespace, claim.metadata.name
- self.fleet.calls.append(("wait_claim", namespace, name))
- stored = self.fleet.claims.get((namespace, name))
- if stored is None:
- raise _status_error("wait claim", 404)
- reason = self.fleet.fail_bind.get(namespace)
- if reason is not None:
- stored.status = OsGymSandboxClaimStatus(
- phase="Failed",
- conditions=[
- OsGymSandboxClaimCondition(
- type="Bound",
- status="False",
- reason=reason,
- message="no sandbox became available",
- last_transition_time=None,
- )
- ],
- sandbox=None,
- )
- raise SdkError.ClaimFailed("Failed", reason)
- stored.status = OsGymSandboxClaimStatus(phase="Bound", conditions=None, sandbox=None)
- return BoundSandbox(
- namespace=namespace, claim=name, name=f"sbx-{name}", services=["env", "server"]
- )
-
- async def wait_service_ready(self, sandbox: Any, service: str, time_to_start=None) -> None:
- return None
-
- async def renew_claim(self, claim: Any, shutdown_time: str) -> Any:
- key = (claim.metadata.namespace, claim.metadata.name)
- with self.fleet.lock:
- self.fleet.renewals.append((claim.metadata.name, shutdown_time))
- if key not in self.fleet.claims:
- raise _status_error("renew claim", 404)
- return self.fleet.claims[key]
-
- async def delete_claim(self, claim: Any) -> None:
- key = (claim.metadata.namespace, claim.metadata.name)
- self.fleet.calls.append(("delete_claim", *key))
- if key not in self.fleet.claims:
- raise _status_error("delete claim", 404)
- del self.fleet.claims[key]
-
- def service_url(self, sandbox: Any, service: str) -> str:
- return f"https://fleet.invalid/api/svc/{sandbox.namespace}/{sandbox.name}-{service}/"
diff --git a/libs/python/cua-sandbox/tests/_image_fixtures.py b/libs/python/cua-sandbox/tests/_image_fixtures.py
deleted file mode 100644
index 800dd3e7d4..0000000000
--- a/libs/python/cua-sandbox/tests/_image_fixtures.py
+++ /dev/null
@@ -1,36 +0,0 @@
-"""Offline image manifests for the Fleet runtime/image rule.
-
-The cua SDK's ``fleet_resolve_runtime`` reads the image's registry manifest.
-Unit tests never reach a registry: the autouse fixture in ``conftest.py``
-routes the call through the pure ``fleet_check_runtime`` with the variants
-below (what those manifests would say). Unlisted images are unreadable, so
-the runtime falls back to the reference, exactly as for an offline registry.
-Live suites (``tests/live``) keep the real, registry-reading resolver.
-"""
-
-from __future__ import annotations
-
-from typing import Any, Callable, Optional
-
-DESKTOP = "ghcr.io/trycua/cua-desktop-linux"
-
-VARIANTS = {
- "registry.example/workspace:latest": "container-disk",
- "registry.example/workspace@sha256:0123": "container-disk",
- "registry.example/workspace@sha256:abc": "container-disk",
- "example:latest": "container-disk",
- "123456789012.dkr.ecr.us-west-2.amazonaws.com/example-workspace:main-bac7daa3": "container-disk",
- "ghcr.io/trycua/minecraft-workspace:latest": "container-disk",
- f"{DESKTOP}:latest": "container-disk",
- f"{DESKTOP}:docker-latest": "rootfs",
-}
-
-#: The binding's real ``fleet_resolve_runtime`` (set by the fixture).
-REAL: Optional[Callable[..., Any]] = None
-
-
-def offline_resolver(native: Any) -> Callable[[Optional[str], str], str]:
- def resolve(runtime: Optional[str], image: str) -> str:
- return native.fleet_check_runtime(runtime, image, VARIANTS.get(image))
-
- return resolve
diff --git a/libs/python/cua-sandbox/tests/_native_fleet.py b/libs/python/cua-sandbox/tests/_native_fleet.py
deleted file mode 100644
index 0bc750949b..0000000000
--- a/libs/python/cua-sandbox/tests/_native_fleet.py
+++ /dev/null
@@ -1,63 +0,0 @@
-"""A fake Fleet API for the native pool manager (``cua-test-fixtures``)."""
-
-from __future__ import annotations
-
-import importlib
-import json
-import os
-import subprocess
-from pathlib import Path
-
-import pytest
-from cua_sandbox import Sandbox, _autopool, sandbox_state
-from cua_sandbox.pool import _FleetClient
-
-sandbox_module = importlib.import_module("cua_sandbox.sandbox")
-
-
-def _fixtures_binary() -> Path | None:
- if os.environ.get("CUA_TEST_FIXTURES"):
- return Path(os.environ["CUA_TEST_FIXTURES"])
- root = Path(__file__).resolve().parents[3] / "cua" / "target"
- for profile in ("debug", "release"):
- candidate = root / profile / "cua-test-fixtures"
- if candidate.exists():
- return candidate
- return None
-
-
-def fleet(monkeypatch, tmp_path):
- """A fresh fake Fleet API per test; yields cua-sandbox's Fleet client."""
- binary = _fixtures_binary()
- if binary is None:
- pytest.skip("cua-test-fixtures is not built")
- proc = subprocess.Popen([str(binary)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
- try:
- line = proc.stdout.readline()
- if not line:
- raise RuntimeError("cua-test-fixtures exited before printing endpoints")
- endpoints = json.loads(line)
- monkeypatch.setenv("CUA_FLEET_BASE_URL", endpoints["fleet_base_url"])
- monkeypatch.setenv("FLEETS_TOKEN", endpoints["fleet_token"])
- for variable in (
- "CUA_FLEET_MAX_POOL_SIZE",
- "CUA_FLEET_CLAIM_TTL",
- "CUA_FLEET_WARM",
- "CUA_CLIENT_ID",
- "CUA_CLIENT_SECRET",
- ):
- monkeypatch.delenv(variable, raising=False)
- # The native manager's automatic GC stays out of these tests.
- monkeypatch.setenv("CUA_FLEET_POOL_IDLE_GC", "off")
- monkeypatch.setattr(_autopool, "CUA_DIR", tmp_path / "cua")
- monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path / "sandboxes")
- monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: api_key is None))
- monkeypatch.setattr(sandbox_module, "_TELEMETRY_AVAILABLE", False)
- yield _FleetClient
- finally:
- proc.stdin.close()
- try:
- proc.wait(10)
- except subprocess.TimeoutExpired:
- proc.kill()
diff --git a/libs/python/cua-sandbox/tests/conftest.py b/libs/python/cua-sandbox/tests/conftest.py
index 48a5b8ce30..3540a78aa4 100644
--- a/libs/python/cua-sandbox/tests/conftest.py
+++ b/libs/python/cua-sandbox/tests/conftest.py
@@ -23,42 +23,21 @@ import pytest_asyncio
from cua_sandbox.sandbox import Sandbox
from cua_sandbox.transport.env import EnvTransport
-# ``fleet``: a fake Fleet API (cua-test-fixtures) for the native pool manager.
-from tests._native_fleet import fleet # noqa: F401
-
@pytest.fixture(autouse=True)
-def _offline_image_manifests(request, monkeypatch):
- """Never read a registry for the Fleet runtime rule in unit tests (see
- ``tests/_image_fixtures.py``). Live suites keep the real resolver, which
- reads the manifest with the caller's registry credentials."""
- if str(request.node.path).startswith(_LIVE_DIR):
- yield
- return
- monkeypatch.setenv("CUA_FLEET_IMAGE_INSPECT", "0")
- # The one image resolver (native cua_image) never reads a registry in
- # unit tests; tests that need an answer patch ``native().resolve_image``.
- monkeypatch.setenv("CUA_IMAGE_RESOLVE", "0")
- try:
- from cua_sandbox._sdk import native
-
- n = native()
- except ImportError:
- yield
- return
- from tests import _image_fixtures
-
- _image_fixtures.REAL = n.fleet_resolve_runtime
- monkeypatch.setattr(n, "fleet_resolve_runtime", _image_fixtures.offline_resolver(n))
+def _offline_image_resolver(request, monkeypatch):
+ """The one image resolver (native cua_image) never reads a registry in
+ unit tests; tests that need an answer patch ``native().resolve_image``.
+ Live suites keep the real resolver."""
+ if not str(request.node.path).startswith(_LIVE_DIR):
+ monkeypatch.setenv("CUA_IMAGE_RESOLVE", "0")
yield
class _NoRealLocalSandboxes:
"""``local_runtime()`` in unit tests: creating a real local sandbox
(container, QEMU, Lume) fails loudly instead of touching this machine.
- Local is the default now, so a test that forgets ``local=False`` for the
- fake Fleet lands here. Tests that need a local runtime patch
- ``local_runtime`` themselves."""
+ Tests that need a local runtime patch ``local_runtime`` themselves."""
def __init__(self, real: Any) -> None:
self._real = real
@@ -70,8 +49,7 @@ class _NoRealLocalSandboxes:
def __getattr__(self, name: str) -> Any:
if name == "create":
raise AssertionError(
- "a unit test tried to start a real local sandbox; pass local=False "
- "for the fake Fleet, or patch local_runtime"
+ "a unit test tried to start a real local sandbox; patch local_runtime"
)
return getattr(real, name)
@@ -97,23 +75,16 @@ def _no_real_local_sandboxes(request, monkeypatch):
# ---------------------------------------------------------------------------
-# Hermetic env: keep live-gate and cloud-credential env out of unit tests
+# Hermetic env: keep live-gate and credential env out of unit tests
# ---------------------------------------------------------------------------
# Variables a developer shell (or CI's live lanes) may export that change how
-# unit tests behave: live-E2E knobs, live opt-in gates, Fleet/cloud
-# credentials, the managed-pool scoping the live suites set and the built-in
-# image overrides.
-_LIVE_ENV_PREFIXES = ("CUA_LIVE_E2E_", "CUA_TEST_LOCAL_", "CUA_FLEET_POOL_")
+# unit tests behave: live-E2E knobs, live opt-in gates, API-key credentials and
+# the built-in image overrides.
+_LIVE_ENV_PREFIXES = ("CUA_LIVE_E2E_", "CUA_TEST_LOCAL_")
_LIVE_ENV_NAMES = frozenset(
{
- "CUA_TEST_FLEET_AUTOPOOL_LIVE",
"CUA_TEST_ANDROID_MULTITOUCH",
- "CUA_CLIENT_ID",
- "CUA_CLIENT_SECRET",
- "CUA_TOKEN_URL",
- "CUA_FLEET_BASE_URL",
- "FLEETS_TOKEN",
"CUA_API_KEY",
"CUA_BASE_URL",
"CUA_DEFAULT_LINUX_IMAGE",
@@ -126,7 +97,6 @@ _LIVE_ENV_NAMES = frozenset(
"CUA_DEFAULT_ON",
"CUA_DEFAULT_KIND",
"CUA_DEFAULT_RUNTIME",
- "CUA_FLEET_WARM",
}
)
_LIVE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "live") + os.sep
@@ -153,8 +123,7 @@ def _isolate_live_env(request, monkeypatch, tmp_path_factory):
# caches all live under CUA_HOME (cua_sandbox._paths), here a temp dir.
monkeypatch.setenv("CUA_HOME", str(tmp_path_factory.mktemp("cua-home")))
# Never read the user's `cua auth login` session (the OS keychain) in
- # unit tests; tests of the session fallback use a file store in tmp.
- monkeypatch.setenv("CUA_FLEET_SESSION", "0")
+ # unit tests.
monkeypatch.setenv("CUA_CREDENTIAL_STORE", "file")
diff --git a/libs/python/cua-sandbox/tests/live/fleet_e2e_support.py b/libs/python/cua-sandbox/tests/live/fleet_e2e_support.py
deleted file mode 100644
index fd306ab115..0000000000
--- a/libs/python/cua-sandbox/tests/live/fleet_e2e_support.py
+++ /dev/null
@@ -1,261 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import json
-import os
-import re
-import time
-from pathlib import Path
-from typing import Any
-
-import httpx
-from fleet_sdk import (
- CyclopsClient,
- CyclopsConfiguration,
- CyclopsCredentials,
- HttpClient,
- HttpError,
- HttpHeader,
- HttpRequest,
- HttpResponse,
- SdkError,
-)
-
-#: A containerDisk that ships cua-spacesd (for example a pushed
-#: libs/images/linux build). When set, the live runners use it with
-#: the default `env` service and drive the computer interfaces; otherwise they
-#: use the pinned image and prove only lifecycle + service reachability, which
-#: is all a daemon-agnostic sandbox promises.
-ENV_IMAGE_VARIABLE = "CUA_LIVE_E2E_ENV_IMAGE"
-
-DEFAULT_BASE_URL = "https://run.cua.ai"
-DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"
-SENSITIVE_SUMMARY_KEY_NAMES = {"api_key", "apikey"}
-SENSITIVE_SUMMARY_KEY_PARTS = {"authorization", "password", "secret", "token"}
-
-
-class HttpxFleetClient(HttpClient):
- def __init__(self) -> None:
- self._client = httpx.AsyncClient(timeout=60.0)
-
- async def execute(self, request: HttpRequest) -> HttpResponse:
- try:
- response = await self._client.request(
- request.method,
- request.url,
- headers={header.name: header.value for header in request.headers},
- content=request.body,
- )
- except httpx.TransportError as error:
- raise HttpError.Transport(str(error)) from error
- return HttpResponse(
- status=response.status_code,
- headers=[
- HttpHeader(name=name, value=value) for name, value in response.headers.multi_items()
- ],
- body=response.content,
- )
-
- async def aclose(self) -> None:
- await self._client.aclose()
-
-
-def has_oauth_credentials() -> bool:
- return bool(os.environ.get("CUA_CLIENT_ID") and os.environ.get("CUA_CLIENT_SECRET"))
-
-
-def _event_class(event_name: str) -> str:
- return {
- "schedule": "schedule",
- "push": "push",
- "workflow_dispatch": "manual",
- }.get(event_name, "manual")
-
-
-def _normalize_namespace_name(raw: str) -> str:
- normalized = re.sub(r"[^a-z0-9-]+", "-", raw.lower()).strip("-")
- return normalized[:63].rstrip("-")
-
-
-def build_namespace_name(lane: str, event_name: str) -> str:
- return _normalize_namespace_name(f"cua-live-{lane}-{_event_class(event_name)}")
-
-
-def build_pool_namespace_name(mode: str, lane: str, event_name: str) -> str:
- return _normalize_namespace_name(f"cua-live-pool-{mode}-{lane}-{_event_class(event_name)}")
-
-
-def build_fleet_client() -> tuple[CyclopsClient, HttpxFleetClient]:
- client_id = os.environ["CUA_CLIENT_ID"]
- client_secret = os.environ["CUA_CLIENT_SECRET"]
- http_client = HttpxFleetClient()
- configuration = CyclopsConfiguration(
- base_url=os.environ.get("CUA_FLEET_BASE_URL", DEFAULT_BASE_URL),
- token_url=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL),
- credentials=CyclopsCredentials(client_id, client_secret),
- pool_poll_interval_ms=2000,
- pool_poll_limit=300,
- claim_poll_interval_ms=2000,
- claim_poll_limit=300,
- )
- return CyclopsClient.connect(configuration, http_client), http_client
-
-
-def is_not_found_error(error: BaseException) -> bool:
- return isinstance(error, SdkError.Status) and error.status == 404
-
-
-def is_pool_missing_error(error: BaseException) -> bool:
- # Fleet evaluates RBAC before existence, so reading a pool in a namespace
- # that has not been created yet returns 403 rather than 404. Mirror the
- # SDK's reconcile semantics, which create the pool on either status.
- return isinstance(error, SdkError.Status) and error.status in (403, 404)
-
-
-async def wait_claims_absent(
- client: CyclopsClient,
- name: str,
- *,
- timeout: float = 180.0,
- interval: float = 5.0,
-) -> bool:
- deadline = time.monotonic() + timeout
- while time.monotonic() < deadline:
- try:
- if not await client.list_claims(name):
- return True
- except Exception as error:
- if is_not_found_error(error):
- return True
- raise
- await asyncio.sleep(interval)
- try:
- return not await client.list_claims(name)
- except Exception as error:
- if is_not_found_error(error):
- return True
- raise
-
-
-async def collect_resource_inventory(client: CyclopsClient, name: str) -> dict[str, list[str]]:
- try:
- templates = await client.list_templates(name)
- pools = await client.list_pools(name)
- claims = await client.list_claims(name)
- except Exception as error:
- # Deleting a pool deletes its namespace; once that finishes, RBAC
- # answers 403 for the namespace (checked before existence).
- if is_not_found_error(error) or is_pool_missing_error(error):
- return {"templates": [], "pools": [], "claims": []}
- raise
- return {
- "templates": [item.metadata.name for item in templates],
- "pools": [item.metadata.name for item in pools],
- "claims": [item.metadata.name for item in claims],
- }
-
-
-def env_image() -> str | None:
- return os.environ.get(ENV_IMAGE_VARIABLE) or None
-
-
-#: cua-sandbox's Fleet pools are KubeVirt containerDisk VMs, and Fleet has no
-#: per-claim secret field yet, so the spacesd token cannot reach the guest.
-KUBEVIRT_ENV_SKIP = (
- "KubeVirt spacesd lane needs a per-claim secret field (cloud PR): no way to "
- "deliver the env token to a containerDisk guest yet"
-)
-
-
-def namespace_prefix_ok(namespace: str, *prefixes: str) -> bool:
- """Live namespaces are `cua-live-*` (CI lanes) or `cua-e2e-*` (ad-hoc runs)."""
- return any(namespace.startswith(prefix) for prefix in prefixes)
-
-
-async def check_service_reachable(sandbox: Any, service: str, summary: dict[str, Any]) -> None:
- """Daemon-agnostic guest check: the gateway routes to the named service."""
- response = await sandbox.services.request(service, method="GET", path="/")
- summary["service"] = {"name": service, "status": response.status_code}
- assert response.status_code < 500, f"service {service!r} answered HTTP {response.status_code}"
-
-
-async def check_spacesd(
- sandbox: Any, summary: dict[str, Any], artifact_dir: Path, label: str
-) -> None:
- """cua-spacesd guest check: every interface family answers."""
- width, height = await sandbox.screen.size()
- summary["screen"] = {"width": width, "height": height}
- assert width > 0 and height > 0
-
- screenshot = await sandbox.screenshot()
- artifact_dir.mkdir(parents=True, exist_ok=True)
- (artifact_dir / f"screen-{label}.png").write_bytes(screenshot)
- assert screenshot.startswith(b"\x89PNG\r\n\x1a\n")
- assert len(screenshot) > 1000
-
- result = await sandbox.shell.run("uname -s")
- summary["shell"] = {
- "success": result.success,
- "stdout": result.stdout.strip(),
- "stderr": result.stderr.strip(),
- }
- assert result.success
- assert result.stdout.strip() == "Linux"
-
- payload = os.urandom(65536)
- await sandbox.files.write_bytes("/tmp/cua-e2e-live.bin", payload)
- assert await sandbox.files.read_bytes("/tmp/cua-e2e-live.bin") == payload
- summary["files_round_trip"] = True
-
-
-def assert_env_template_contract(template: Any) -> None:
- """Default (daemon-agnostic) template: `env` on 3211 and no guest probe."""
- vm_template = template.spec.vm_template
- services = {service.name: service.target_port for service in vm_template.services}
- assert services.get("env") == 3211, f"env service must target 3211, got {services}"
- assert vm_template.probes is None, "the default template must not probe a guest agent"
-
-
-def assert_template_contract(template: Any, expected_port: int) -> None:
- vm_template = template.spec.vm_template
- server = next((service for service in vm_template.services if service.name == "server"), None)
- assert server is not None, "server service is required"
- assert (
- server.target_port == expected_port
- ), f"server target_port={server.target_port}, expected {expected_port}"
- # Readiness is client-side for managed pools (daemon-agnostic), so the
- # template may carry no probe; when it does, it must target the server port.
- if vm_template.probes is not None:
- probes = json.loads(vm_template.probes.to_json())
- observed = probes["readinessProbe"]["tcpSocket"]["port"]
- assert (
- observed == expected_port
- ), f"readiness probe port={observed}, expected {expected_port}"
-
-
-def _is_sensitive_summary_key(key: object) -> bool:
- separated = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", str(key))
- normalized = re.sub(r"[^a-z0-9]+", "_", separated.lower()).strip("_")
- return (
- normalized in SENSITIVE_SUMMARY_KEY_NAMES
- or normalized.endswith("_api_key")
- or any(part in SENSITIVE_SUMMARY_KEY_PARTS for part in normalized.split("_"))
- )
-
-
-def _redact_summary(value: Any) -> Any:
- if isinstance(value, dict):
- return {
- key: "<redacted>" if _is_sensitive_summary_key(key) else _redact_summary(item)
- for key, item in value.items()
- }
- if isinstance(value, list):
- return [_redact_summary(item) for item in value]
- if isinstance(value, tuple):
- return tuple(_redact_summary(item) for item in value)
- return value
-
-
-def write_summary(path: Path, summary: dict[str, Any]) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps(_redact_summary(summary), indent=2, sort_keys=True) + "\n")
diff --git a/libs/python/cua-sandbox/tests/live/test_fleet_autopool_live.py b/libs/python/cua-sandbox/tests/live/test_fleet_autopool_live.py
deleted file mode 100644
index 19f8ece503..0000000000
--- a/libs/python/cua-sandbox/tests/live/test_fleet_autopool_live.py
+++ /dev/null
@@ -1,317 +0,0 @@
-"""LIVE: managed Fleet pools end to end (opt-in, creates billed Fleet VMs).
-
-Run only on purpose::
-
- set -a; source ~/.env; set +a
- CUA_TEST_FLEET_AUTOPOOL_LIVE=1 .venv/bin/python -m pytest -q \\
- tests/live/test_fleet_autopool_live.py -s
-
-What it proves, against real Fleet:
-
-1. ``Sandbox.create(image, local=False)`` twice reuses one managed pool (labelled, KEDA
- autoscaled from zero) and ``Sandbox.list()`` shows both claims.
-2. ``Sandbox.ephemeral(image, local=False)`` in a subprocess killed with SIGKILL leaves
- a claim that Fleet reaps within the short test ``claim_ttl``.
-3. Cleanup: every claim is released and the test's pool, template and
- namespace are deleted (verified), whatever happens.
-
-The native manager names pools ``cua-auto-*``; the test deletes exactly the
-pools its sandboxes landed on, and automatic GC is off, so nothing else is
-touched.
-"""
-
-from __future__ import annotations
-
-import asyncio
-import os
-import signal
-import subprocess
-import sys
-import textwrap
-import time
-from pathlib import Path
-
-import pytest
-from cua_sandbox import Image, Sandbox, _autopool
-
-#: Pools this run used (deleted, verified, at the end).
-TEST_POOLS: set[str] = set()
-CLAIM_TTL = 60
-# Pinned image with its own daemon on 8000 (the daemon-agnostic lane).
-IMAGE = (
- "public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04"
- "@sha256:82702ebdd32d1f8fc05f2ea409a7c67d0ba9f8f8e4e9f1a89ce40989d5f4475d"
-)
-SERVER_PORT = 8000
-BIND_TIMEOUT = 1200
-REAP_TIMEOUT = CLAIM_TTL + 180 # TTL + reaper period (30 s) + slack
-PACKAGE_ROOT = Path(__file__).resolve().parents[2]
-
-pytestmark = [
- pytest.mark.asyncio,
- pytest.mark.skipif(
- os.environ.get("CUA_TEST_FLEET_AUTOPOOL_LIVE") != "1",
- reason="opt-in: set CUA_TEST_FLEET_AUTOPOOL_LIVE=1 (creates billed Fleet VMs)",
- ),
- pytest.mark.skipif(
- not (os.environ.get("CUA_CLIENT_ID") and os.environ.get("CUA_CLIENT_SECRET")),
- reason="Fleet OAuth credentials not set",
- ),
-]
-
-CHILD = textwrap.dedent("""
- import asyncio, sys
- from cua_sandbox import Image, Sandbox
-
- async def main():
- async with Sandbox.ephemeral(
- Image.from_registry(sys.argv[1]),
- server_port=int(sys.argv[2]),
- claim_ttl=int(sys.argv[3]),
- time_to_start=1200,
- telemetry_enabled=False, local=False,
- ) as sb:
- print(f"CLAIM {sb.pool_name} {sb.claim_name}", flush=True)
- for _ in range(3600): # bounded: killed long before this ends
- await asyncio.sleep(1)
-
- asyncio.run(main())
- """)
-
-
-def log(message: str) -> None:
- print(f"[autopool-live {time.strftime('%H:%M:%S')}] {message}", flush=True)
-
-
-async def claim_names(pool: str) -> set[str]:
- from cua_sandbox.pool import _FleetClient
-
- client = _FleetClient()
- try:
- return {claim.metadata.name for claim in await client.list_claims(pool)}
- except Exception as error: # noqa: BLE001
- if _autopool._is_not_found(error):
- return set()
- raise
- finally:
- await client.close()
-
-
-async def delete_test_pools() -> list[str]:
- """Delete the pools this run used (claims, pool, template, namespace)."""
- from cua_sandbox.pool import _claim_stub, _FleetClient
-
- client = _FleetClient()
- deleted: list[str] = []
- try:
- for namespace in await client.list_namespaces():
- name = namespace.name
- if name not in TEST_POOLS:
- continue
- for step in ("claims", "pool", "template", "namespace"):
- try:
- if step == "claims":
- for claim in await client.list_claims(name):
- await client.delete_claim(_claim_stub(name, claim.metadata.name))
- elif step == "pool":
- await client.delete_pool(await client.get_pool(name))
- elif step == "template":
- await client.delete_template(await client.get_template(name, name))
- else:
- await client.delete_namespace(name)
- except Exception as error: # noqa: BLE001
- if not _autopool._is_not_found(error):
- log(f"cleanup {step} {name}: {type(error).__name__}: {error}")
- deleted.append(name)
- return deleted
- finally:
- await client.close()
-
-
-async def remaining_test_namespaces() -> list[str]:
- from cua_sandbox.pool import _FleetClient
-
- client = _FleetClient()
- try:
- return [ns.name for ns in await client.list_namespaces() if ns.name in TEST_POOLS]
- finally:
- await client.close()
-
-
-def live_env(monkeypatch, tmp_path):
- from cua_sandbox import sandbox_state
-
- # Keep the name cache and claim state files off the real ~/.cua.
- monkeypatch.setattr(_autopool, "CUA_DIR", tmp_path / ".cua")
- monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path / ".cua" / "sandboxes")
- monkeypatch.setenv("CUA_FLEET_POOL_IDLE_GC", "off")
- monkeypatch.setenv("CUA_FLEET_CLAIM_TTL", str(CLAIM_TTL))
- return tmp_path
-
-
-async def test_managed_pool_reuse_list_and_sigkill_reap(live_env):
- image = Image.from_registry(IMAGE)
- held: list[Sandbox] = []
- child: subprocess.Popen | None = None
- events: list[str] = []
- try:
- # 1. create twice -> one pool
- started = time.monotonic()
- first = await Sandbox.create(
- image,
- server_port=SERVER_PORT,
- time_to_start=BIND_TIMEOUT,
- telemetry_enabled=False,
- progress=lambda event: events.append(f"{event.stage}: {event.message}"),
- local=False,
- )
- held.append(first)
- TEST_POOLS.add(first.pool_name)
- log(
- f"first claim {first.claim_name} on {first.pool_name} in "
- f"{time.monotonic() - started:.0f}s"
- )
- started = time.monotonic()
- second = await Sandbox.create(
- image,
- server_port=SERVER_PORT,
- time_to_start=BIND_TIMEOUT,
- telemetry_enabled=False,
- local=False,
- )
- held.append(second)
- log(
- f"second claim {second.claim_name} on {second.pool_name} in "
- f"{time.monotonic() - started:.0f}s"
- )
- assert first.pool_name == second.pool_name
- assert first.pool_name.startswith("cua-auto-")
- assert any(line.startswith("cold_start") for line in events), events
-
- [info] = [p for p in await _autopool.list_pools() if p.name == first.pool_name]
- log(f"pool info: {info}")
- assert info.managed, "pool labels (merge patch) did not land"
- assert info.spec_hash, "spec-hash label missing"
-
- listed = {sb.name: sb for sb in await Sandbox.list()}
- assert first.claim_name in listed and second.claim_name in listed
- assert listed[first.claim_name].pool == first.pool_name
-
- # 2. ephemeral in a subprocess, SIGKILLed -> claim reaped within TTL
- env = {**os.environ, "PYTHONUNBUFFERED": "1", "HOME": str(live_env)}
- child = subprocess.Popen(
- [sys.executable, "-c", CHILD, IMAGE, str(SERVER_PORT), str(CLAIM_TTL)],
- cwd=PACKAGE_ROOT,
- env=env,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT,
- text=True,
- )
- line = ""
- deadline = time.monotonic() + BIND_TIMEOUT + 60
- assert child.stdout is not None
- while time.monotonic() < deadline: # bounded read of child output
- line = await asyncio.to_thread(child.stdout.readline)
- if not line or line.startswith("CLAIM "):
- break
- log(f"child: {line.rstrip()}")
- assert line.startswith("CLAIM "), f"child exited without a claim: {line!r}"
- _, child_pool, child_claim = line.split()
- assert child_pool == first.pool_name, "ephemeral must reuse the managed pool"
- assert child_claim in {sb.name for sb in await Sandbox.list()}
-
- os.kill(child.pid, signal.SIGKILL)
- child.wait(timeout=30)
- killed = time.monotonic()
- log(f"SIGKILLed child holding {child_claim}; waiting for Fleet to reap it")
- gone_after = None
- for _ in range(REAP_TIMEOUT // 5 + 1):
- if child_claim not in await claim_names(child_pool):
- gone_after = time.monotonic() - killed
- break
- await asyncio.sleep(5)
- assert gone_after is not None, f"claim {child_claim} outlived {REAP_TIMEOUT}s"
- log(f"claim {child_claim} reaped {gone_after:.0f}s after SIGKILL (ttl {CLAIM_TTL}s)")
- assert child_claim not in {sb.name for sb in await Sandbox.list()}
-
- # Released claims disappear; the pool stays for reuse.
- for sb in list(held):
- await sb.close()
- held.remove(sb)
- remaining = await claim_names(first.pool_name)
- assert first.claim_name not in remaining and second.claim_name not in remaining
- assert first.pool_name in await remaining_test_namespaces()
- finally:
- if child is not None and child.poll() is None:
- child.kill()
- child.wait(timeout=30)
- for sb in held:
- try:
- await sb.close()
- except Exception as error: # noqa: BLE001
- log(f"close {sb.claim_name}: {error}")
- _autopool.stop_all_heartbeats() # no-op: heartbeats live in the SDK
- # 3. cleanup, verified (namespace deletion is asynchronous).
- deleted = await delete_test_pools()
- log(f"deleted test pools {deleted}")
- leftover: list[str] = []
- for _ in range(60): # up to ~5 min
- leftover = await remaining_test_namespaces()
- if not leftover:
- break
- await asyncio.sleep(5)
- assert not leftover, f"test namespaces left behind: {leftover}"
-
-
-GVISOR_IMAGE = os.environ.get(
- "CUA_E2E_FLEET_ROOTFS", "public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04:docker-main-809e3f81"
-)
-
-
-async def test_gvisor_managed_pool(live_env):
- """A docker- image defaults to the gVisor runtime; its managed pool says so."""
- from cua_sandbox.pool import _FleetClient
-
- image = Image.from_registry(GVISOR_IMAGE)
- try:
- started = time.monotonic()
- async with Sandbox.ephemeral(
- image,
- server_port=SERVER_PORT,
- time_to_start=BIND_TIMEOUT,
- telemetry_enabled=False,
- local=False,
- ) as sb:
- log(
- f"gVisor claim {sb.claim_name} on {sb.pool_name} in "
- f"{time.monotonic() - started:.0f}s"
- )
- pool_name, claim_name = sb.pool_name, sb.claim_name
- TEST_POOLS.add(pool_name)
- assert pool_name.startswith("cua-auto-")
- client = _FleetClient()
- try:
- template = await client.get_template(pool_name, pool_name)
- finally:
- await client.close()
- runtime = template.spec.vm_template.runtime
- log(f"template runtime: {runtime}")
- assert str(getattr(runtime, "name", runtime)).lower() == "gvisor"
- [info] = [p for p in await _autopool.list_pools() if p.name == pool_name]
- assert info.managed and info.spec_hash
- response = await sb.services.request("server", method="GET", path="/")
- log(f"server / -> HTTP {response.status_code}")
- assert response.status_code < 500
- assert claim_name not in await claim_names(pool_name)
- finally:
- _autopool.stop_all_heartbeats() # no-op: heartbeats live in the SDK
- deleted = await delete_test_pools()
- log(f"deleted test pools {deleted}")
- leftover: list[str] = []
- for _ in range(60): # up to ~5 min
- leftover = await remaining_test_namespaces()
- if not leftover:
- break
- await asyncio.sleep(5)
- assert not leftover, f"test namespaces left behind: {leftover}"
diff --git a/libs/python/cua-sandbox/tests/live/test_fleet_ephemeral.py b/libs/python/cua-sandbox/tests/live/test_fleet_ephemeral.py
deleted file mode 100644
index cea1125a5a..0000000000
--- a/libs/python/cua-sandbox/tests/live/test_fleet_ephemeral.py
+++ /dev/null
@@ -1,292 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import os
-import re
-import time
-from importlib.metadata import version
-from pathlib import Path
-
-import cua_sandbox
-import pytest
-from cua_sandbox import Image, Sandbox
-
-from tests.live.fleet_e2e_support import (
- KUBEVIRT_ENV_SKIP,
- assert_env_template_contract,
- assert_template_contract,
- build_fleet_client,
- build_namespace_name,
- check_service_reachable,
- check_spacesd,
- collect_resource_inventory,
- env_image,
- namespace_prefix_ok,
- wait_claims_absent,
- write_summary,
-)
-
-# Pinned image with its own daemon on 8000: the daemon-agnostic lane declares
-# it as server_port and checks only lifecycle + service reachability.
-IMAGE = (
- "public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04"
- "@sha256:80fff8a40f217a460cef7a60161adb3899eabd02c3451f18926b84d1f81b8da2"
-)
-
-
-INVENTORY_SETTLE_SECONDS = float(os.environ.get("CUA_LIVE_E2E_INVENTORY_SETTLE", "240"))
-
-
-def has_oauth_credentials() -> bool:
- return bool(os.environ.get("CUA_CLIENT_ID") and os.environ.get("CUA_CLIENT_SECRET"))
-
-
-def selected_namespace() -> str:
- lane = os.environ.get("CUA_LIVE_E2E_LANE", "local")
- namespace = os.environ.get("CUA_LIVE_E2E_NAMESPACE") or build_namespace_name(
- lane,
- os.environ.get("CUA_LIVE_E2E_EVENT", os.environ.get("GITHUB_EVENT_NAME", "manual")),
- )
- if not namespace_prefix_ok(namespace, "cua-live-", "cua-e2e-"):
- raise ValueError("CUA_LIVE_E2E_NAMESPACE must start with cua-live- or cua-e2e-")
- if len(namespace) > 63 or re.fullmatch(r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", namespace) is None:
- raise ValueError("CUA_LIVE_E2E_NAMESPACE must be a DNS-1123 label of at most 63 characters")
- return namespace
-
-
-async def delete_managed_pool(name: str) -> None:
- """GC this lane's managed pool through the SDK: only this pool, and only
- once it has no claims (another run sharing the spec keeps it)."""
- from cua_sandbox import _autopool
-
- report = await _autopool.gc_pools([name], 0)
- if report.errors:
- raise RuntimeError(f"managed pool GC failed for {name}: {report.errors}")
-
-
-pytestmark = [
- pytest.mark.asyncio,
- pytest.mark.skipif(not has_oauth_credentials(), reason="Fleet OAuth credentials not set"),
-]
-
-
-async def run_fleet_ephemeral_live() -> None:
- lane = os.environ.get("CUA_LIVE_E2E_LANE", "local")
- namespace = selected_namespace()
- artifact_dir = Path(os.environ.get("CUA_LIVE_E2E_ARTIFACT_DIR", "/tmp/cua-live-e2e"))
- spacesd_image = env_image()
- summary = {
- "lane": lane,
- "namespace": namespace,
- "image": spacesd_image or IMAGE,
- "guest_daemon": "cua-spacesd" if spacesd_image else "image-provided server:8000",
- "source_sha": os.environ.get("CUA_LIVE_E2E_SOURCE_SHA") or os.environ.get("GITHUB_SHA"),
- "packages": {
- "cua-sandbox": version("cua-sandbox"),
- "cua-fleet": version("cua-fleet"),
- "cua": version("cua"),
- },
- "module_origins": {
- "cua_sandbox": str(Path(cua_sandbox.__file__).resolve()),
- },
- }
- fleet, http_client = build_fleet_client()
- primary_error: BaseException | None = None
- cleanup_error: BaseException | None = None
- close_error: BaseException | None = None
- summary_error: BaseException | None = None
- provisioning_attempted = False
- sandbox_yielded = False
-
- def record_cleanup_error(error: BaseException) -> None:
- nonlocal cleanup_error
- error_summary = {"type": type(error).__name__}
- if cleanup_error is None:
- cleanup_error = error
- summary["cleanup_error"] = error_summary
- else:
- summary.setdefault("cleanup_secondary_errors", []).append(error_summary)
-
- # Sandbox.ephemeral(image) claims from a managed cua-auto-<spec hash>
- # pool. Cleanup below GCs exactly that pool by name (only once it has no
- # claims), and automatic GC stays away from other pools.
- managed_prefix = "cua-auto-"
- saved_env = {key: os.environ.get(key) for key in ("CUA_FLEET_POOL_IDLE_GC",)}
- os.environ["CUA_FLEET_POOL_IDLE_GC"] = "off"
- try:
- provisioning_attempted = True
- started = time.monotonic()
- options = {
- "name": namespace,
- "cpu": 4,
- "memory_mb": 4096,
- "time_to_start": 900,
- "telemetry_enabled": False,
- }
- if spacesd_image is None:
- options["server_port"] = 8000
- async with Sandbox.ephemeral(
- Image.from_registry(spacesd_image or IMAGE), **options, local=False
- ) as sandbox:
- sandbox_yielded = True
- summary["provision_seconds"] = time.monotonic() - started
- summary["sandbox_name"] = sandbox.name
- sandbox_claim_name = getattr(sandbox, "claim_name", None)
- sandbox_pool_name = getattr(sandbox, "pool_name", None)
- claim_name = sandbox_claim_name or sandbox.name
- pool_name = sandbox_pool_name or namespace
- summary["claim_name"] = claim_name
- summary["pool_name"] = pool_name
- try:
- assert (
- isinstance(sandbox.name, str) and sandbox.name
- ), "sandbox name must be a non-empty string"
- if sandbox_claim_name is not None:
- assert (
- claim_name == namespace
- ), f"claim name {claim_name!r} must equal requested name {namespace!r}"
- if sandbox_pool_name is not None:
- assert pool_name.startswith(
- managed_prefix
- ), f"pool name {pool_name!r} must be a managed pool ({managed_prefix}*)"
-
- template = await fleet.get_template(pool_name, pool_name)
- if spacesd_image is None:
- assert_template_contract(template, expected_port=8000)
- await check_service_reachable(sandbox, "server", summary)
- else:
- assert_env_template_contract(template)
- await check_spacesd(sandbox, summary, artifact_dir, "ephemeral")
-
- if os.environ.get("CUA_LIVE_E2E_SIGNED_URLS") == "true":
- signed_service = "server" if spacesd_image is None else "env"
- signed_url = await sandbox.services.create_signed_url(
- signed_service,
- label="periodic-live-e2e",
- expires_in_seconds=300,
- )
- assert signed_url.namespace == pool_name
- assert signed_url.service == signed_service
- assert signed_url.label == "periodic-live-e2e"
- assert signed_url.revoked_at is None
-
- try:
- listed_signed_urls = await sandbox.services.list_signed_urls()
- listed_signed_url = next(
- item for item in listed_signed_urls if item.id == signed_url.id
- )
- assert listed_signed_url.revoked_at is None
- finally:
- await sandbox.services.revoke_signed_url(signed_url)
-
- revoked_signed_urls = await sandbox.services.list_signed_urls()
- revoked_signed_url = next(
- item for item in revoked_signed_urls if item.id == signed_url.id
- )
- assert revoked_signed_url.revoked_at is not None
- summary["signed_service_url"] = {
- "created": True,
- "listed": True,
- "revoked": True,
- }
- except BaseException as error:
- primary_error = error
- summary["error"] = {"type": type(error).__name__}
- except BaseException as error:
- if primary_error is None:
- if sandbox_yielded:
- record_cleanup_error(error)
- else:
- primary_error = error
- summary["error"] = {"type": type(error).__name__}
- else:
- summary["context_exit_error"] = {"type": type(error).__name__}
- finally:
- if provisioning_attempted:
- cleanup_started = time.monotonic()
- claims_absent: bool | None = None
- inventory: dict[str, list[str]] | None = None
- resource_namespace = summary.get("pool_name")
- if resource_namespace is not None:
- try:
- claims_absent = await wait_claims_absent(fleet, resource_namespace)
- summary["claims_absent"] = claims_absent
- except BaseException as error:
- record_cleanup_error(error)
- if claims_absent and str(resource_namespace).startswith(managed_prefix):
- # The managed pool outlives the ephemeral claim by design
- # (it is reused); this lane owns it, so remove it now.
- try:
- await delete_managed_pool(resource_namespace)
- except BaseException as error:
- record_cleanup_error(error)
- try:
- expected_inventory = {"templates": [], "pools": [], "claims": []}
- inventory = await collect_resource_inventory(fleet, resource_namespace)
- # Pool deletion tears the namespace down asynchronously:
- # give it a bounded time to settle before calling it a leak.
- settle_deadline = time.monotonic() + INVENTORY_SETTLE_SECONDS
- while (
- claims_absent
- and inventory != {"templates": [], "pools": [], "claims": []}
- and time.monotonic() < settle_deadline
- ):
- await asyncio.sleep(5)
- inventory = await collect_resource_inventory(fleet, resource_namespace)
- summary["persistent_resources"] = inventory
- except BaseException as error:
- record_cleanup_error(error)
-
- if claims_absent is False:
- try:
- summary["claim_leak"] = True
- pytest.fail(
- f"claims remain in namespace {namespace} after Sandbox.ephemeral(local=False)"
- )
- except BaseException as error:
- record_cleanup_error(error)
- if sandbox_yielded and inventory is not None:
- if inventory != expected_inventory:
- try:
- summary["unexpected_inventory"] = True
- pytest.fail(
- "unexpected reconciled resource inventory "
- f"for namespace {namespace}: {inventory}"
- )
- except BaseException as error:
- record_cleanup_error(error)
- summary["cleanup_seconds"] = time.monotonic() - cleanup_started
- if not sandbox_yielded:
- summary["provisioning"] = {"attempted": True, "sandbox_yielded": False}
-
- for key, value in saved_env.items():
- if value is None:
- os.environ.pop(key, None)
- else:
- os.environ[key] = value
- try:
- await http_client.aclose()
- except BaseException as error:
- close_error = error
- summary["close_error"] = {"type": type(error).__name__}
-
- try:
- write_summary(artifact_dir / "summary.json", summary)
- except BaseException as error:
- summary_error = error
- summary["summary_error"] = {"type": type(error).__name__}
-
- if primary_error is not None:
- raise primary_error
- if cleanup_error is not None:
- raise cleanup_error
- if close_error is not None:
- raise close_error
- if summary_error is not None:
- raise summary_error
-
-
-async def test_fleet_ephemeral_live() -> None:
- if env_image() is not None:
- pytest.skip(KUBEVIRT_ENV_SKIP)
- await run_fleet_ephemeral_live()
diff --git a/libs/python/cua-sandbox/tests/live/test_fleet_pool_persistent.py b/libs/python/cua-sandbox/tests/live/test_fleet_pool_persistent.py
deleted file mode 100644
index 1ced842520..0000000000
--- a/libs/python/cua-sandbox/tests/live/test_fleet_pool_persistent.py
+++ /dev/null
@@ -1,293 +0,0 @@
-from __future__ import annotations
-
-import os
-import re
-import time
-from importlib.metadata import version
-from pathlib import Path
-
-import cua_sandbox
-import pytest
-from cua_sandbox import Image, Pool, Sandbox, WarmPoolAutoscaling
-
-from tests.live.fleet_e2e_support import (
- KUBEVIRT_ENV_SKIP,
- assert_env_template_contract,
- assert_template_contract,
- build_fleet_client,
- build_pool_namespace_name,
- check_service_reachable,
- check_spacesd,
- collect_resource_inventory,
- env_image,
- has_oauth_credentials,
- is_pool_missing_error,
- namespace_prefix_ok,
- wait_claims_absent,
- write_summary,
-)
-
-IMAGE = (
- "public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04"
- "@sha256:80fff8a40f217a460cef7a60161adb3899eabd02c3451f18926b84d1f81b8da2"
-)
-
-POOL_CPU = 4
-POOL_MEMORY_MB = 4096
-WARM_TIME_TO_START = 180
-COLD_TIME_TO_START = 900
-WARM_BIND_SLA_SECONDS = 300
-
-MODE_ENV = {
- "warm": "CUA_LIVE_E2E_POOL_WARM_NAMESPACE",
- "cold": "CUA_LIVE_E2E_POOL_COLD_NAMESPACE",
-}
-
-
-def cold_autoscaling() -> WarmPoolAutoscaling:
- # replicas < 1 is rejected by Pool.apply, so scale-to-zero is expressed
- # through autoscaling: KEDA owns spec.replicas and decays it to zero.
- return WarmPoolAutoscaling(min_pool_size=0, initial_pool_size=0, max_pool_size=1)
-
-
-def selected_pool_namespace(mode: str) -> str:
- lane = os.environ.get("CUA_LIVE_E2E_LANE", "local")
- namespace = os.environ.get(MODE_ENV[mode]) or build_pool_namespace_name(
- mode,
- lane,
- os.environ.get("CUA_LIVE_E2E_EVENT", os.environ.get("GITHUB_EVENT_NAME", "manual")),
- )
- if not namespace_prefix_ok(namespace, f"cua-live-pool-{mode}-", f"cua-e2e-pool-{mode}-"):
- raise ValueError(
- f"{MODE_ENV[mode]} must start with cua-live-pool-{mode}- or cua-e2e-pool-{mode}-"
- )
- if len(namespace) > 63 or re.fullmatch(r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", namespace) is None:
- raise ValueError(f"{MODE_ENV[mode]} must be a DNS-1123 label of at most 63 characters")
- return namespace
-
-
-pytestmark = [
- pytest.mark.asyncio,
- pytest.mark.skipif(not has_oauth_credentials(), reason="Fleet OAuth credentials not set"),
-]
-
-
-async def run_fleet_pool_live(mode: str) -> None:
- lane = os.environ.get("CUA_LIVE_E2E_LANE", "local")
- namespace = selected_pool_namespace(mode)
- artifact_dir = Path(os.environ.get("CUA_LIVE_E2E_ARTIFACT_DIR", "/tmp/cua-live-e2e"))
- spacesd_image = env_image()
- summary = {
- "lane": lane,
- "mode": mode,
- "namespace": namespace,
- "image": spacesd_image or IMAGE,
- "guest_daemon": "cua-spacesd" if spacesd_image else "image-provided server:8000",
- "source_sha": os.environ.get("CUA_LIVE_E2E_SOURCE_SHA") or os.environ.get("GITHUB_SHA"),
- "packages": {
- "cua-sandbox": version("cua-sandbox"),
- "cua-fleet": version("cua-fleet"),
- "cua": version("cua"),
- },
- "module_origins": {
- "cua_sandbox": str(Path(cua_sandbox.__file__).resolve()),
- },
- }
- fleet, http_client = build_fleet_client()
- primary_error: BaseException | None = None
- cleanup_error: BaseException | None = None
- close_error: BaseException | None = None
- summary_error: BaseException | None = None
- pool_applied = False
- sandbox_yielded = False
-
- def record_cleanup_error(error: BaseException) -> None:
- nonlocal cleanup_error
- error_summary = {"type": type(error).__name__}
- if cleanup_error is None:
- cleanup_error = error
- summary["cleanup_error"] = error_summary
- else:
- summary.setdefault("cleanup_secondary_errors", []).append(error_summary)
-
- try:
- try:
- existing = await Pool.get(namespace)
- except BaseException as error:
- if not is_pool_missing_error(error):
- raise
- summary["pool_pre_existed"] = False
- else:
- summary["pool_pre_existed"] = True
- summary["spec_replicas_before"] = existing.resource.spec.replicas
- status = getattr(existing.resource, "status", None)
- summary["ready_replicas_before"] = (
- (getattr(status, "ready_replicas", None) or 0) if status is not None else 0
- )
-
- apply_started = time.monotonic()
- pool = await Pool.apply(
- Image.from_registry(spacesd_image or IMAGE),
- name=namespace,
- replicas=1,
- cpu=POOL_CPU,
- memory_mb=POOL_MEMORY_MB,
- # The pinned image serves its own daemon on 8000; declaring it as
- # the `server` service makes it the readiness probe. The env image
- # takes the daemon-agnostic default (`env` on 3211, no probe).
- services=None if spacesd_image else {"server": 8000},
- autoscaling=None if mode == "warm" else cold_autoscaling(),
- )
- pool_applied = True
- summary["apply_seconds"] = time.monotonic() - apply_started
- assert pool.name == namespace, f"pool name {pool.name!r} must equal namespace {namespace!r}"
-
- template = await fleet.get_template(namespace, namespace)
- if spacesd_image is None:
- assert_template_contract(template, expected_port=8000)
- else:
- assert_env_template_contract(template)
-
- claim_started = time.monotonic()
- async with Sandbox.ephemeral(
- pool=namespace,
- name=namespace,
- service="env" if spacesd_image else "server",
- time_to_start=WARM_TIME_TO_START if mode == "warm" else COLD_TIME_TO_START,
- telemetry_enabled=False,
- local=False,
- ) as sandbox:
- sandbox_yielded = True
- claim_seconds = time.monotonic() - claim_started
- summary["claim_seconds"] = claim_seconds
- summary["sandbox_name"] = sandbox.name
- sandbox_claim_name = getattr(sandbox, "claim_name", None)
- sandbox_pool_name = getattr(sandbox, "pool_name", None)
- summary["claim_name"] = sandbox_claim_name or sandbox.name
- summary["pool_name"] = sandbox_pool_name or namespace
- try:
- assert (
- isinstance(sandbox.name, str) and sandbox.name
- ), "sandbox name must be a non-empty string"
- if sandbox_claim_name is not None:
- assert (
- sandbox_claim_name == namespace
- ), f"claim name {sandbox_claim_name!r} must equal requested name {namespace!r}"
- if sandbox_pool_name is not None:
- assert (
- sandbox_pool_name == namespace
- ), f"pool name {sandbox_pool_name!r} must equal namespace {namespace!r}"
-
- warm_bind_sla_applied = (
- mode == "warm"
- and summary.get("pool_pre_existed") is True
- and summary.get("ready_replicas_before", 0) >= 1
- )
- summary["warm_bind_sla_applied"] = warm_bind_sla_applied
- if warm_bind_sla_applied:
- assert claim_seconds < WARM_BIND_SLA_SECONDS, (
- f"pre-provisioned warm claim took {claim_seconds:.1f}s, "
- f"expected under {WARM_BIND_SLA_SECONDS}s"
- )
-
- if spacesd_image is None:
- await check_service_reachable(sandbox, "server", summary)
- else:
- await check_spacesd(sandbox, summary, artifact_dir, f"pool-{mode}")
- except BaseException as error:
- primary_error = error
- summary["error"] = {"type": type(error).__name__}
- except BaseException as error:
- if primary_error is None:
- if sandbox_yielded:
- record_cleanup_error(error)
- else:
- primary_error = error
- summary["error"] = {"type": type(error).__name__}
- else:
- summary["context_exit_error"] = {"type": type(error).__name__}
- finally:
- if pool_applied:
- cleanup_started = time.monotonic()
- claims_absent: bool | None = None
- inventory: dict[str, list[str]] | None = None
- try:
- claims_absent = await wait_claims_absent(fleet, namespace)
- summary["claims_absent"] = claims_absent
- except BaseException as error:
- record_cleanup_error(error)
- try:
- inventory = await collect_resource_inventory(fleet, namespace)
- summary["persistent_resources"] = inventory
- except BaseException as error:
- record_cleanup_error(error)
-
- if claims_absent is False:
- try:
- summary["claim_leak"] = True
- pytest.fail(f"claims remain in namespace {namespace} after claim-only release")
- except BaseException as error:
- record_cleanup_error(error)
- if inventory is not None:
- expected_inventory = {
- "templates": [namespace],
- "pools": [namespace],
- "claims": [],
- }
- if inventory != expected_inventory:
- try:
- summary["unexpected_inventory"] = True
- pytest.fail(
- f"persistent pool inventory for namespace {namespace} must be "
- f"{expected_inventory}, got {inventory}"
- )
- except BaseException as error:
- record_cleanup_error(error)
- try:
- refreshed = await Pool.get(namespace)
- summary["spec_replicas_after"] = refreshed.resource.spec.replicas
- status = getattr(refreshed.resource, "status", None)
- summary["ready_replicas_after"] = (
- (getattr(status, "ready_replicas", None) or 0) if status is not None else 0
- )
- except BaseException as error:
- record_cleanup_error(error)
- summary["cleanup_seconds"] = time.monotonic() - cleanup_started
- if not sandbox_yielded:
- summary["provisioning"] = {
- "pool_applied": pool_applied,
- "sandbox_yielded": False,
- }
-
- try:
- await http_client.aclose()
- except BaseException as error:
- close_error = error
- summary["close_error"] = {"type": type(error).__name__}
-
- try:
- write_summary(artifact_dir / f"summary-pool-{mode}.json", summary)
- except BaseException as error:
- summary_error = error
- summary["summary_error"] = {"type": type(error).__name__}
-
- if primary_error is not None:
- raise primary_error
- if cleanup_error is not None:
- raise cleanup_error
- if close_error is not None:
- raise close_error
- if summary_error is not None:
- raise summary_error
-
-
-async def test_fleet_pool_warm_live() -> None:
- if env_image() is not None:
- pytest.skip(KUBEVIRT_ENV_SKIP)
- await run_fleet_pool_live("warm")
-
-
-async def test_fleet_pool_cold_live() -> None:
- if env_image() is not None:
- pytest.skip(KUBEVIRT_ENV_SKIP)
- await run_fleet_pool_live("cold")
diff --git a/libs/python/cua-sandbox/tests/live/test_unified_api_live.py b/libs/python/cua-sandbox/tests/live/test_unified_api_live.py
index 04abd27cc2..769623e884 100644
--- a/libs/python/cua-sandbox/tests/live/test_unified_api_live.py
+++ b/libs/python/cua-sandbox/tests/live/test_unified_api_live.py
@@ -1,4 +1,4 @@
-"""LIVE: the unified Sandbox API on a plain image, local (gVisor) and cloud.
+"""LIVE: the unified Sandbox API on a plain image, local (gVisor).
The audit's probe scenario: ``python:3.12-slim`` running an MCP-style
server as ``command=``, declared as ``services={"mcp": 8765}`` with an
@@ -14,12 +14,10 @@ Also: image layers (``pip_install``, ``run``, ``env``, ``copy``) on the same
plain image with ``local=True`` build into the container engine before boot
and are reused by an identical second sandbox.
-Opt-in (both create real resources, named ``cua-e2e-*`` and removed in
+Opt-in (it creates real resources, named ``cua-e2e-*`` and removed in
``finally``)::
CUA_TEST_UNIFIED_LOCAL=1 .venv/bin/python -m pytest -q tests/live/test_unified_api_live.py
- set -a; source ~/.env; set +a
- CUA_TEST_UNIFIED_FLEET=1 .venv/bin/python -m pytest -q tests/live/test_unified_api_live.py
The local run starts a cua daemon for the public URL under a throwaway
``CUA_HOME`` (``CUA_BIN`` must name the CLI) and stops it afterwards.
@@ -36,7 +34,7 @@ from urllib.parse import urlsplit, urlunsplit
import httpx
import pytest
-from cua_sandbox import Image, Sandbox, _autopool, http
+from cua_sandbox import Image, Sandbox, http
REPO = Path(__file__).resolve().parents[5]
SERVER = (REPO / "tests" / "e2e" / "cua-sdk" / "fixtures" / "mcp_probe_server.py").read_text()
@@ -216,32 +214,3 @@ async def test_plain_image_layers_build_locally(monkeypatch, tmp_path):
finally:
for tag in created:
_docker("rmi", "-f", f"cua-vmm/build:{tag}")
-
-
[email protected](not _on("CUA_TEST_UNIFIED_FLEET"), reason="CUA_TEST_UNIFIED_FLEET is not set")
-async def test_plain_image_mcp_fleet_gvisor():
- if not (os.environ.get("CUA_CLIENT_ID") or os.environ.get("FLEETS_TOKEN")):
- pytest.skip("no Fleet credentials")
- sb = None
- pool = None
- try:
- sb = await Sandbox.create(
- Image.from_registry("docker.io/library/python:3.12-slim"),
- command=["python", "-c", SERVER],
- services={"mcp": 8765},
- wait_for=http("mcp", "/health"),
- name=f"cua-e2e-unified-{secrets.token_hex(3)}",
- time_to_start=900,
- telemetry_enabled=False,
- local=False,
- )
- pool = sb.pool_name
- info = await sb.info()
- assert info.location == "cloud" and info.expires_at, info
- await _exercise(sb, env_expected=False)
- finally:
- if sb is not None:
- await sb.destroy()
- if pool:
- report = await _autopool.gc_pools([pool])
- assert pool in report.pools_deleted or not report.errors, report
diff --git a/libs/python/cua-sandbox/tests/test_android_multitouch.py b/libs/python/cua-sandbox/tests/test_android_multitouch.py
index d86e4b500a..ddefb891a7 100644
--- a/libs/python/cua-sandbox/tests/test_android_multitouch.py
+++ b/libs/python/cua-sandbox/tests/test_android_multitouch.py
@@ -18,17 +18,12 @@ Usage
# Local emulator:
CUA_TEST_ANDROID_MULTITOUCH=1 pytest tests/test_android_multitouch.py -v -k local
- # Cloud (once implemented):
- CUA_TEST_ANDROID_MULTITOUCH=1 CUA_TEST_API_KEY=sk-... \
- pytest tests/test_android_multitouch.py -v -k cloud
-
Environment variables
─────────────────────
CUA_TEST_ANDROID_MULTITOUCH set to 1 to run this module (default: skipped)
CUA_ANDROID_TEST_APK path or URL to a pre-built TouchTest debug APK
default: latest release from
https://github.com/trycua/android-touch-test-app
- CUA_TEST_API_KEY Anthropic API key (cloud tests only)
CUA_ANDROID_API_LEVEL Android API level to boot (default: 34)
CUA_ANDROID_AVD_NAME AVD name (default: cua-multitouch-test)
@@ -78,7 +73,6 @@ _RESET_ACTION = "com.cuatest.touchtest.RESET_LOG"
_API_LEVEL = int(os.environ.get("CUA_ANDROID_API_LEVEL", "34"))
_AVD_NAME = os.environ.get("CUA_ANDROID_AVD_NAME", "cua-multitouch-test")
-_API_KEY = os.environ.get("CUA_TEST_API_KEY")
_SETTLE_S = 0.6
_LAUNCH_WAIT_S = 3.0
@@ -447,41 +441,3 @@ class TestAndroidMultitouchLocal(_MultitouchTests):
async def sb(self, local_android_sb: Sandbox):
await _reset(local_android_sb)
return local_android_sb
-
-
-# ══════════════════════════════════════════════════════════════════════════════
-# Cloud tests
-# ══════════════════════════════════════════════════════════════════════════════
-
-skip_no_api_key = pytest.mark.skipif(not _API_KEY, reason="CUA_TEST_API_KEY not set")
-# Note: cloud Android tests are gated by API key only — hardware compat is the cloud's concern.
-
-
-@pytest_asyncio.fixture(scope="session", loop_scope="session")
-async def cloud_android_sb():
- """
- Spin up an ephemeral cloud Android VM, install the TouchTest APK, escalate
- to root, launch the app, and yield the ready Sandbox.
- Shared across all cloud tests so we only pay the boot cost once.
- """
- if not _API_KEY:
- pytest.skip("CUA_TEST_API_KEY not set — cloud tests skipped")
-
- image = Image.android("14").apk_install(_APK_RELEASE_URL)
- async with Sandbox.ephemeral(image, api_key=_API_KEY, local=False) as sb:
- # Launch app
- await sb.shell.run(f"am start -n {_APK_ACTIVITY}")
- await asyncio.sleep(_LAUNCH_WAIT_S)
-
- yield sb
-
-
[email protected](loop_scope="session")
[email protected](not _API_KEY, reason="CUA_TEST_API_KEY not set")
-class TestAndroidMultitouchCloud(_MultitouchTests):
- """Full touch action suite against a cloud-hosted Android VM."""
-
- @pytest_asyncio.fixture(loop_scope="session")
- async def sb(self, cloud_android_sb: Sandbox):
- await _reset(cloud_android_sb)
- return cloud_android_sb
diff --git a/libs/python/cua-sandbox/tests/test_autopool.py b/libs/python/cua-sandbox/tests/test_autopool.py
deleted file mode 100644
index a0ef9bc1dc..0000000000
--- a/libs/python/cua-sandbox/tests/test_autopool.py
+++ /dev/null
@@ -1,455 +0,0 @@
-"""Managed Fleet pools (cua_sandbox._autopool) on the cua SDK's native pool
-manager, hermetically.
-
-``cua-test-fixtures`` (``cargo build -p cua-daemon --features test-fixtures
---bin cua-test-fixtures``) serves a fake Fleet API on loopback; both the
-native manager and cua-sandbox's own Fleet client talk to it. ``~/.cua`` and
-the sandbox state directory are redirected to a temp dir. No network, host,
-VM or Fleet resources are touched. Without the fixture binary the native
-tests skip.
-"""
-
-from __future__ import annotations
-
-import importlib
-from datetime import datetime, timedelta, timezone
-
-import pytest
-from cua_sandbox import Image, Sandbox, _autopool, _sdk, sandbox_state
-from cua_sandbox import sync as cua_sync
-
-sandbox_module = importlib.import_module("cua_sandbox.sandbox")
-
-#: Digest-pinned: the native manager never asks a registry to resolve it.
-IMAGE = "registry.example/workspace@sha256:0123"
-
-
-def image() -> Image:
- return Image.from_registry(IMAGE)
-
-
-async def managed_pools(client_factory) -> list[str]:
- client = client_factory()
- try:
- return sorted(
- n.name for n in await client.list_namespaces() if n.name.startswith("cua-auto-")
- )
- finally:
- await client.close()
-
-
-async def pool_of(client_factory, name: str):
- client = client_factory()
- try:
- return await client.get_pool(name)
- finally:
- await client.close()
-
-
-async def claims_in(client_factory, pool: str) -> dict:
- client = client_factory()
- try:
- return {c.metadata.name: c for c in await client.list_claims(pool)}
- finally:
- await client.close()
-
-
-# ── config ───────────────────────────────────────────────────────────────
-
-
-def test_config_defaults_env_and_kwargs():
- cfg = _autopool.config(environ={})
- assert (cfg.max_pool_size, cfg.claim_ttl, cfg.warm, cfg.initial_pool_size) == (
- 10,
- 900,
- False,
- 0,
- )
- # The idle GC default matches the Rust SDK and the docs: 30 min.
- assert cfg.idle_gc == 30 * 60
- cfg = _autopool.config(
- environ={
- "CUA_FLEET_MAX_POOL_SIZE": "4",
- "CUA_FLEET_CLAIM_TTL": "2m",
- "CUA_FLEET_WARM": "1",
- "CUA_FLEET_POOL_IDLE_GC": "1h",
- }
- )
- assert (cfg.max_pool_size, cfg.claim_ttl, cfg.initial_pool_size, cfg.idle_gc) == (
- 4,
- 120,
- 1,
- 3600,
- )
- cfg = _autopool.config(
- environ={"CUA_FLEET_WARM": "1"}, warm=False, claim_ttl=timedelta(minutes=1)
- )
- assert (cfg.warm, cfg.claim_ttl) == (False, 60)
- assert not _autopool.config(environ={"CUA_FLEET_POOL_IDLE_GC": "off"}).auto_gc
- assert _autopool.config(environ={}).bind_deadline == 900
-
-
- "kwargs, message",
- [
- ({"max_pool_size": 0}, "max_pool_size"),
- ({"claim_ttl": 5}, "claim_ttl must be between"),
- ({"claim_ttl": "10m"}, "claim_ttl must be seconds"),
- ],
-)
-def test_config_rejects_bad_values(kwargs, message):
- with pytest.raises((ValueError, TypeError), match=message):
- _autopool.config(environ={}, **kwargs)
-
-
-def test_config_rejects_bad_env_duration():
- with pytest.raises(ValueError, match="CUA_FLEET_CLAIM_TTL"):
- _autopool.config(environ={"CUA_FLEET_CLAIM_TTL": "soon"})
-
-
-# ── spec key and naming (contract helpers) ──────────────────────────────
-
-
-def test_spec_key_is_stable_and_covers_the_spec():
- base = _autopool.spec_key(image())
- assert base.spec_hash() == _autopool.spec_key(image()).spec_hash()
- assert base.services == (("env", 3211),)
- variants = {
- _autopool.spec_key(image(), cpu=4).spec_hash(),
- _autopool.spec_key(image(), memory_mb=8192).spec_hash(),
- _autopool.spec_key(image(), server_port=8000).spec_hash(),
- _autopool.spec_key(Image.from_registry("registry.example/other:1")).spec_hash(),
- _autopool.spec_key(image().expose(5900)).spec_hash(),
- }
- assert base.spec_hash() not in variants
- assert len(variants) == 5
- assert len(base.label) == 32
-
-
-def test_pool_names_are_dns_labels_scoped_by_tenant():
- spec_hash = _autopool.spec_key(image()).spec_hash()
- first = _autopool.pool_name_for("tenant-a", spec_hash)
- assert first == _autopool.pool_name_for("tenant-a", spec_hash)
- assert first != _autopool.pool_name_for("tenant-b", spec_hash)
- assert first.startswith("cua-auto-") and len(first) == len("cua-auto-") + 16
- assert first == first.lower() and first.replace("-", "").isalnum()
- assert _autopool.candidate_names(first)[1:3] == [f"{first}-2", f"{first}-3"]
- assert len(_autopool.candidate_names(first)) == 8
-
-
-def test_canonical_encoding_matches_the_rust_pool_manager():
- # Golden vector for cua_fleet::autopool::PoolSpecKey::new("img").canonical()
- # and auto_pool_name("tenant-a", hash): both SDKs must name a spec alike.
- key = _autopool.PoolSpecKey(image="img")
- assert key.canonical() == (
- b'["cua-autopool/v1",["image","img"],["runtime","kubevirt"],["efi",false],'
- b'["cpu",null],["memory_mb",null],["services",[["env",3211]]],'
- b'["readiness_tcp_port",null],["command",null]]'
- )
- import base64
- import hashlib
-
- digest = hashlib.sha256(b"tenant-a\0" + key.spec_hash().encode()).digest()
- expected = "cua-auto-" + base64.b32encode(digest).decode().lower()[:16]
- assert _autopool.pool_name_for("tenant-a", key.spec_hash()) == expected
-
-
-def test_managed_key_matches_sandbox_core_defaults():
- key = _autopool.spec_key(image().expose(5900), server_port=8000)
- assert (key.cpu, key.memory_mb) == (2, 4096)
- assert dict(key.services) == {"env": 3211, "server": 8000, "port-5900": 5900}
- assert key.readiness_tcp_port == 8000
-
-
-# ── native manager: acquire / reuse ──────────────────────────────────────
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_create_without_pool_claims_from_a_managed_pool(fleet):
- sb = await Sandbox.create(image(), local=False)
-
- [pool_name] = await managed_pools(fleet)
- assert sb.pool_name == pool_name
- pool = await pool_of(fleet, pool_name)
- assert pool.spec.replicas == 0
- assert pool.spec.autoscaling.min_pool_size == 0
- assert pool.spec.autoscaling.initial_pool_size == 0
- assert pool.spec.autoscaling.max_pool_size == 10
- assert pool.spec.ttl_seconds_after_created == 7 * 86400
- labels = pool.metadata.labels
- assert labels["cua.ai/managed-by"] == "cua-sdk"
- assert len(labels["cua.ai/spec-hash"]) == 32
-
- claim = (await claims_in(fleet, pool_name))[sb.claim_name]
- assert claim.spec.ttl_seconds_after_created == 900
- assert claim.spec.bind_deadline >= 900
- assert claim.metadata.labels["cua.ai/managed-by"] == "cua-sdk"
- assert sb._claim_handle.heartbeat_running
-
- state = sandbox_state.load(sb.claim_name)
- assert state["runtime_type"] == "fleet"
- assert state["pool_name"] == pool_name
- assert state["managed"] is True
- assert state["claim_ttl"] == 900
- # The native manager's pool-name cache lives in CUA_DIR (0600).
- cache = _autopool.CUA_DIR / "fleet-pools.json"
- assert pool_name in cache.read_text()
- assert cache.stat().st_mode & 0o777 == 0o600
-
- await sb.close()
- assert not sb._claim_handle.heartbeat_running
- assert sb.claim_name not in await claims_in(fleet, pool_name)
- assert await managed_pools(fleet) == [pool_name], "the pool stays for reuse"
- assert sandbox_state.load(sb.claim_name) is None
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_same_spec_reuses_and_different_specs_do_not(fleet):
- first = await Sandbox.create(image(), local=False)
- second = await Sandbox.create(image(), local=False)
- assert first.pool_name == second.pool_name
- assert first.claim_name != second.claim_name
- other = await Sandbox.create(image(), cpu=4, local=False)
- assert other.pool_name != first.pool_name
- assert len(await managed_pools(fleet)) == 2
- for sb in (first, second, other):
- await sb.close()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_warm_max_pool_size_and_claim_ttl(fleet):
- sb = await Sandbox.create(image(), warm=True, max_pool_size=3, claim_ttl=120, local=False)
- pool = await pool_of(fleet, sb.pool_name)
- assert pool.spec.replicas == 1
- assert pool.spec.autoscaling.initial_pool_size == 1
- assert pool.spec.autoscaling.max_pool_size == 3
- claim = (await claims_in(fleet, sb.pool_name))[sb.claim_name]
- assert claim.spec.ttl_seconds_after_created == 120
- await sb.close()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_long_time_to_start_raises_the_bind_deadline(fleet):
- sb = await Sandbox.create(image(), time_to_start=1800, local=False)
- claim = (await claims_in(fleet, sb.pool_name))[sb.claim_name]
- assert claim.spec.bind_deadline == 1800
- await sb.close()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_named_create_reattaches_an_existing_claim(fleet):
- first = await Sandbox.create(image(), name="job-1", local=False)
- await first.disconnect()
- second = await Sandbox.create(image(), name="job-1", local=False)
- assert second.claim_name == "job-1"
- assert list(await claims_in(fleet, second.pool_name)) == ["job-1"]
- await second.close()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_keep_alive_extends_a_managed_claim(fleet):
- sb = await Sandbox.create(image(), keep_alive_minutes=90, local=False)
- claim = (await claims_in(fleet, sb.pool_name))[sb.claim_name]
- deadline = datetime.fromisoformat(claim.spec.lifecycle.shutdown_time.replace("Z", "+00:00"))
- assert deadline - datetime.now(timezone.utc) > timedelta(minutes=89)
- await sb.close()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_server_port_publishes_and_waits_for_the_server_service(fleet):
- sb = await Sandbox.create(image(), server_port=8000, local=False)
- assert sb._claim_handle.service == "server"
- client = fleet()
- try:
- template = await client.get_template(sb.pool_name, sb.pool_name)
- finally:
- await client.close()
- services = {s.name: s.target_port for s in template.spec.vm_template.services}
- assert services == {"env": 3211, "server": 8000}
- await sb.close()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_osworld_image_claims_the_flask_server_through_the_managed_pool(fleet):
- """Legacy OSWorld adapter on Fleet: an ``agent_type="osworld"`` disk has no
- spacesd, so the managed pool publishes its Flask server as ``server``
- on 5000, readiness waits on it, and the claim speaks the OSWorld API."""
- from cua_sandbox.transport.fleet import OSWorldFleetTransport
-
- osworld = Image.from_registry(IMAGE, os_type="linux", kind="vm", agent_type="osworld")
- sb = await Sandbox.create(osworld, local=False)
- assert sb._claim_handle.service == "server"
- assert sb._claim_handle.agent_type == "osworld"
- assert isinstance(sb._transport, OSWorldFleetTransport)
- client = fleet()
- try:
- template = await client.get_template(sb.pool_name, sb.pool_name)
- finally:
- await client.close()
- services = {s.name: s.target_port for s in template.spec.vm_template.services}
- assert services == {"env": 3211, "server": 5000}
- assert sandbox_state.load(sb.claim_name)["agent_type"] == "osworld"
- # A plain image of the same reference is a different managed pool.
- plain = await Sandbox.create(image(), local=False)
- assert plain.pool_name != sb.pool_name
- await plain.close()
- await sb.close()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_disconnect_detaches_and_keeps_the_claim(fleet):
- sb = await Sandbox.create(image(), local=False)
- await sb.disconnect()
- assert not sb._claim_handle.heartbeat_running
- assert sb.claim_name in await claims_in(fleet, sb.pool_name)
-
-
-# ── ephemeral ────────────────────────────────────────────────────────────
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_ephemeral_releases_the_claim_and_keeps_the_pool(fleet):
- async with Sandbox.ephemeral(image(), local=False) as sb:
- pool_name, claim_name = sb.pool_name, sb.claim_name
- assert claim_name in await claims_in(fleet, pool_name)
- assert sandbox_state.load(claim_name) is None
- assert claim_name not in await claims_in(fleet, pool_name)
- assert await managed_pools(fleet) == [pool_name]
- async with Sandbox.ephemeral(image(), local=False) as again:
- assert again.pool_name == pool_name
- assert not await claims_in(fleet, pool_name)
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_ephemeral_releases_on_body_error(fleet):
- with pytest.raises(RuntimeError, match="body"):
- async with Sandbox.ephemeral(image(), local=False) as sb:
- raise RuntimeError("body")
- assert not await claims_in(fleet, sb.pool_name)
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_keep_pool_is_a_deprecated_no_op(fleet):
- with pytest.warns(DeprecationWarning, match="keep_pool"):
- async with Sandbox.ephemeral(image(), keep_pool=True, local=False) as sb:
- pass
- assert await managed_pools(fleet) == [sb.pool_name]
-
-
-# ── list / pools / gc ────────────────────────────────────────────────────
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_list_pools_and_gc_through_the_native_manager(fleet):
- sb = await Sandbox.create(image(), local=False)
- [info] = await _autopool.list_pools()
- assert info.name == sb.pool_name
- assert info.managed and info.claims == 1
- assert info.last_used is not None
- assert {i.name for i in await Sandbox.list(local=False)} >= {sb.claim_name}
- rows = {i.name: i for i in await Sandbox.list()}
- assert rows[sb.claim_name].location == "cloud"
- kept = await _autopool.gc(idle_after=3600)
- assert kept.pools_deleted == []
- await sb.close()
- report = await _autopool.gc(idle_after=0)
- assert report.pools_deleted == [sb.pool_name]
- assert await managed_pools(fleet) == []
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
[email protected]("operation", ["suspend", "restart"])
-async def test_lifecycle_ops_are_unsupported_on_managed_pools(fleet, operation):
- sb = await Sandbox.create(image(), local=False)
- with pytest.raises(NotImplementedError, match="cannot suspend a single sandbox"):
- await getattr(Sandbox, operation)(sb.claim_name)
- await sb.close()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_concurrent_first_use_in_one_process_creates_one_pool(fleet):
- import asyncio
-
- sandboxes = await asyncio.gather(*(Sandbox.create(image(), local=False) for _ in range(6)))
- assert len({sb.pool_name for sb in sandboxes}) == 1
- assert len(await managed_pools(fleet)) == 1
- for sb in sandboxes:
- await sb.close()
-
-
-# ── sync facade ──────────────────────────────────────────────────────────
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-def test_sync_facade_create_ephemeral_and_list(fleet):
- sb = cua_sync.Sandbox.create(image(), claim_ttl=60, local=False)
- assert sb._claim_handle.heartbeat_running
- assert sb.claim_name in [info.name for info in cua_sync.Sandbox.list(local=False)]
- pool = sb.pool_name
- sb.close()
- with cua_sync.Sandbox.ephemeral(image(), local=False) as eph:
- assert eph.pool_name == pool
-
-
-def test_native_runtime_is_shared_per_pool_home(fleet):
- a = _autopool._native_cua()
- assert a is _autopool._native_cua()
- assert _sdk.runtime(fleet=True) is not a
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_resume_of_a_live_cloud_sandbox_reconnects(fleet):
- sb = await Sandbox.create(image(), local=False)
- again = await Sandbox.resume(sb.claim_name)
- assert again.name == sb.claim_name
- await again.disconnect()
- await sb.close()
-
-
-# -- the default listing and the session marker (a stand-in keychain) --------
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_default_list_reads_a_keychain_session_only_with_the_marker(
- fleet, monkeypatch, tmp_path
-):
- import datetime
- import json
- import os
-
- sb = await Sandbox.create(image(), local=False)
- token = os.environ["FLEETS_TOKEN"]
- home, vault = tmp_path / "cua-home", tmp_path / "vault"
- vault.mkdir()
- expires = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1)
- (vault / "vault.json").write_text(
- json.dumps({"access_token": token, "expires_at": expires.isoformat()})
- )
- # Only the signed-in session (in the stand-in vault) can reach Fleet now.
- monkeypatch.delenv("FLEETS_TOKEN")
- monkeypatch.delenv("CUA_FLEET_SESSION", raising=False)
- monkeypatch.setenv("CUA_HOME", str(home))
- monkeypatch.setenv("CUA_CREDENTIAL_STORE", f"test-keychain:{vault}")
-
- def reads() -> int:
- try:
- return int((vault / "reads").read_text())
- except FileNotFoundError:
- return 0
-
- # No marker: the vault is never probed, no cloud rows.
- names = [i.name for i in await Sandbox.list()]
- assert sb.claim_name not in names
- assert reads() == 0
-
- # With the marker the default listing reads the session and lists the
- # cloud sandbox.
- home.mkdir(exist_ok=True)
- (home / "session.json").write_text(
- json.dumps({"store": "keychain", "account": None, "expires_at": expires.isoformat()})
- )
- rows = {i.name: i for i in await Sandbox.list()}
- assert rows[sb.claim_name].location == "cloud"
- assert reads() > 0
- monkeypatch.setenv("FLEETS_TOKEN", token)
- await sb.close()
diff --git a/libs/python/cua-sandbox/tests/test_cloud.py b/libs/python/cua-sandbox/tests/test_cloud.py
deleted file mode 100644
index 4637f78a46..0000000000
--- a/libs/python/cua-sandbox/tests/test_cloud.py
+++ /dev/null
@@ -1,409 +0,0 @@
-"""Integration tests — cloud sandbox via CUA API.
-
- CUA_API_KEY=sk-... pytest tests/test_cloud.py -v -s
-
-Requires a running cloud VM. Set CUA_TEST_CLOUD_VM_NAME to the VM name.
-"""
-
-from __future__ import annotations
-
-import importlib
-import os
-from types import SimpleNamespace
-from unittest.mock import AsyncMock
-
-import pytest
-from cua_sandbox import Image, Pool, Sandbox, _config
-from cua_sandbox.runtime.base import RuntimeInfo
-
-sandbox_module = importlib.import_module("cua_sandbox.sandbox")
-
-pytestmark = pytest.mark.asyncio
-
-API_KEY = os.environ.get("CUA_API_KEY")
-VM_NAME = os.environ.get("CUA_TEST_CLOUD_VM_NAME", "steady-bluebird")
-
-skip_no_key = pytest.mark.skipif(not API_KEY, reason="CUA_API_KEY not set")
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
- "auth_environment",
- [
- {"FLEETS_TOKEN": "fleet-token"},
- {"CUA_CLIENT_ID": "client-id", "CUA_CLIENT_SECRET": "client-secret"},
- ],
- ids=["workload-token", "client-credentials"],
-)
-async def test_cloud_routes_fleet_auth_without_explicit_legacy_key(
- monkeypatch, tmp_path, auth_environment
-):
- routes = []
- monkeypatch.setattr(_config, "_global_config", _config._Config())
- for variable in ("FLEETS_TOKEN", "CUA_CLIENT_ID", "CUA_CLIENT_SECRET"):
- monkeypatch.delenv(variable, raising=False)
- for variable, value in auth_environment.items():
- monkeypatch.setenv(variable, value)
-
- async def reject_fleet_apply(cls, image, **kwargs):
- raise AssertionError("Fleet-routed images claim from the managed pool, never apply one")
-
- async def managed_acquire(image, **kwargs):
- routes.append(("managed", {"name": kwargs["name"]}))
- return SimpleNamespace(
- name=kwargs["name"],
- claim_name=kwargs["name"],
- pool_name="cua-auto-abc",
- _claim_handle=SimpleNamespace(state_fields=lambda: {"managed": True}),
- telemetry_enabled=False,
- _ephemeral=False,
- )
-
- class LegacyTransport:
- def __init__(self, **kwargs):
- routes.append(("legacy", kwargs))
- self.name = kwargs["name"]
-
- async def connect(self):
- return None
-
- async def disconnect(self):
- return None
-
- from cua_sandbox import _autopool, sandbox_state
-
- monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)
- monkeypatch.setattr(Pool, "apply", classmethod(reject_fleet_apply))
- monkeypatch.setattr(_autopool, "acquire", managed_acquire)
- monkeypatch.setattr(
- sandbox_module, "_make_transport", lambda **kwargs: LegacyTransport(**kwargs)
- )
-
- await Sandbox.create(
- Image.from_registry("example:latest"),
- name="fleet-demo",
- telemetry_enabled=False,
- local=False,
- )
- await Sandbox.create(Image.linux(), name="linux-demo", telemetry_enabled=False, local=False)
- legacy_sandbox = await Sandbox.create(
- Image.from_registry("example:latest"),
- name="legacy-demo",
- api_key="sk-explicit",
- local=False,
- )
- await legacy_sandbox.disconnect()
-
- assert Sandbox._uses_fleet(None)
- assert not Sandbox._uses_fleet("sk-explicit")
- assert [(route, values["name"]) for route, values in routes] == [
- ("managed", "fleet-demo"),
- ("managed", "linux-demo"),
- ("legacy", "legacy-demo"),
- ]
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
[email protected]("legacy_source", ["configured", "environment", "credentials"])
-async def test_registry_image_uses_legacy_auth_when_fleet_auth_is_unavailable(
- monkeypatch, legacy_source
-):
- routes = []
- monkeypatch.setattr(_config, "_global_config", _config._Config())
- for variable in (
- "CUA_API_KEY",
- "FLEETS_TOKEN",
- "CUA_CLIENT_ID",
- "CUA_CLIENT_SECRET",
- ):
- monkeypatch.delenv(variable, raising=False)
-
- if legacy_source == "configured":
- _config.configure(api_key="sk-configured")
- elif legacy_source == "environment":
- monkeypatch.setenv("CUA_API_KEY", "sk-environment")
- else:
- monkeypatch.setattr(_config, "_read_credentials_key", lambda: "sk-credentials")
-
- class LegacyTransport:
- def __init__(self, **kwargs):
- routes.append(kwargs)
- self.name = kwargs["name"]
-
- async def connect(self):
- return None
-
- async def disconnect(self):
- return None
-
- async def reject_fleet_apply(cls, image, **kwargs):
- raise AssertionError("legacy authentication must not route registry images to Fleet")
-
- monkeypatch.setattr(Pool, "apply", classmethod(reject_fleet_apply))
- monkeypatch.setattr(
- sandbox_module, "_make_transport", lambda **kwargs: LegacyTransport(**kwargs)
- )
-
- sandbox = await Sandbox.create(
- Image.from_registry("example:latest"), name="legacy-demo", local=False
- )
- await sandbox.disconnect()
-
- assert not Sandbox._uses_fleet(None)
- assert [route["name"] for route in routes] == ["legacy-demo"]
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_ephemeral_registry_image_uses_legacy_auth_selector(monkeypatch):
- monkeypatch.setattr(_config, "_global_config", _config._Config(api_key="sk-configured"))
- for variable in ("FLEETS_TOKEN", "CUA_CLIENT_ID", "CUA_CLIENT_SECRET"):
- monkeypatch.delenv(variable, raising=False)
-
- legacy_sandbox = SimpleNamespace(
- _has_snapshots=False,
- name="legacy-demo",
- destroy=AsyncMock(),
- )
- create = AsyncMock()
- create_legacy = AsyncMock(return_value=legacy_sandbox)
- monkeypatch.setattr(Sandbox, "create", create)
- monkeypatch.setattr(Sandbox, "_create", create_legacy)
-
- async with Sandbox.ephemeral(
- Image.from_registry("example:latest"), name="legacy-demo", local=False
- ):
- pass
-
- create.assert_not_awaited()
- create_legacy.assert_awaited_once()
- legacy_sandbox.destroy.assert_awaited_once()
-
-
-async def test_cloud_local_creation_never_routes_to_fleet(monkeypatch, tmp_path):
- # The named local sandbox writes a state file; keep it in this test's
- # own CUA_HOME (the autouse conftest one too, but never rely on it).
- monkeypatch.setenv("CUA_HOME", str(tmp_path))
- calls = []
-
- class Runtime:
- # Sandbox._create tells the runtime whether the sandbox is ephemeral;
- # a double that omits it fails the call rather than the assertion.
- async def start(self, image, name, *, ephemeral=True):
- calls.append(("start", image, name))
- return RuntimeInfo(host="127.0.0.1", api_port=8000, name=name, environment="linux")
-
- class FleetTransport:
- def __init__(self, **kwargs):
- raise AssertionError("local creation must not use Fleet")
-
- monkeypatch.setattr(sandbox_module, "FleetCloudTransport", FleetTransport)
-
- sandbox = await Sandbox.create(Image.linux(), name="local-demo", local=True, runtime=Runtime())
- await sandbox.disconnect()
-
- assert calls[0][2] == "local-demo"
- assert (tmp_path / "sandboxes" / "local-demo.json").exists()
-
-
-@skip_no_key
-async def test_cloud_connect_by_name():
- """Connect to an existing cloud VM by name and take a screenshot."""
- sb = await Sandbox.connect(VM_NAME, api_key=API_KEY)
- screenshot = await sb.screenshot()
- assert screenshot[:4] == b"\x89PNG"
- assert len(screenshot) > 1000
- await sb.disconnect()
-
-
-@skip_no_key
-async def test_cloud_shell():
- """Run a shell command on a cloud VM."""
- sb = await Sandbox.connect(VM_NAME, api_key=API_KEY)
- result = await sb.shell.run("echo hello-cloud")
- assert result.success
- assert "hello-cloud" in result.stdout
- await sb.disconnect()
-
-
-@skip_no_key
-async def test_cloud_screen_size():
- """Get screen dimensions from a cloud VM."""
- sb = await Sandbox.connect(VM_NAME, api_key=API_KEY)
- w, h = await sb.get_dimensions()
- assert w > 0
- assert h > 0
- await sb.disconnect()
-
-
-@skip_no_key
-async def test_cloud_keyboard_mouse():
- """Basic keyboard and mouse operations on a cloud VM."""
- sb = await Sandbox.connect(VM_NAME, api_key=API_KEY)
- await sb.mouse.move(100, 100)
- await sb.mouse.click(100, 100)
- await sb.keyboard.type("hello")
- await sb.disconnect()
-
-
-@skip_no_key
-async def test_cloud_environment():
- """Get environment info from a cloud VM."""
- sb = await Sandbox.connect(VM_NAME, api_key=API_KEY)
- env = await sb.get_environment()
- assert env in ("windows", "mac", "linux", "browser")
- await sb.disconnect()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_cloud_no_api_key_errors():
- """Connecting with no credentials names every way to get them."""
- old = os.environ.pop("CUA_API_KEY", None)
- try:
- with pytest.raises(ValueError, match="Fleet credentials missing: run `cua auth login`"):
- await Sandbox.connect("anything")
- finally:
- if old:
- os.environ["CUA_API_KEY"] = old
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_cloud_no_image_no_name_errors():
- """Creating without an image raises a clear error."""
- with pytest.raises((ValueError, TypeError)):
- await Sandbox._create(api_key="sk-test-fake-key")
-
-
-@skip_no_key
-async def test_cloud_ephemeral_linux():
- """Create an ephemeral cloud Linux VM, use it, and destroy on exit."""
- async with Sandbox.ephemeral(Image.linux(), api_key=API_KEY, local=False) as sb:
- assert sb.name is not None
- screenshot = await sb.screenshot()
- assert screenshot[:4] == b"\x89PNG"
- assert len(screenshot) > 1000
- result = await sb.shell.run("echo ephemeral-test")
- assert result.success
- assert "ephemeral-test" in result.stdout
-
-
-@skip_no_key
-async def test_cloud_ephemeral_android():
- """Create an ephemeral Android cloud VM, verify screenshot and display URL."""
- async with Sandbox.ephemeral(Image.android("14"), api_key=API_KEY, local=False) as sb:
- assert sb.name is not None
- screenshot = await sb.screenshot()
- assert screenshot[:4] == b"\x89PNG"
- assert len(screenshot) > 1000
- env = await sb.get_environment()
- assert env == "android"
- display_url = await sb.get_display_url(share=True)
- assert ".cua.sh" in display_url
- assert "password=" in display_url
-
-
-@skip_no_key
-async def test_cloud_invalid_api_key_errors():
- """An invalid (reversed) API key should get an HTTP error from the API."""
- reversed_key = API_KEY[::-1]
- with pytest.raises(Exception):
- sb = await Sandbox.connect(VM_NAME, api_key=reversed_key)
- await sb.screenshot()
- await sb.disconnect()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_backed_create_persists_claim_pool_mapping(monkeypatch, tmp_path):
- from cua_sandbox import sandbox_state
-
- monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)
-
- class ClaimedSandbox:
- pass
-
- class FleetPool:
- name = "cua-cli-wif-smoke"
-
- async def claim(self, **kwargs):
- assert kwargs["name"] == "wif-smoke-123"
- return ClaimedSandbox()
-
- async def get_pool(cls, name):
- assert name == "cua-cli-wif-smoke"
- return FleetPool()
-
- monkeypatch.setattr(Pool, "get", classmethod(get_pool))
-
- await Sandbox.create(pool="cua-cli-wif-smoke", name="wif-smoke-123", local=False)
-
- assert sandbox_state.load("wif-smoke-123")["pool_name"] == "cua-cli-wif-smoke"
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_backed_connect_loads_claim_pool_mapping(monkeypatch, tmp_path):
- from cua_sandbox import sandbox_state
-
- created = []
- monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)
- sandbox_state.save_fleet_claim("wif-smoke-123", "cua-cli-wif-smoke")
- monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: True))
-
- class FleetTransport:
- def __init__(self, **kwargs):
- created.append(kwargs)
- self.name = kwargs["name"]
-
- async def connect(self):
- return None
-
- async def disconnect(self):
- return None
-
- monkeypatch.setattr(sandbox_module, "FleetCloudTransport", FleetTransport)
-
- await Sandbox.connect("wif-smoke-123")
-
- assert created[0]["name"] == "wif-smoke-123"
- assert created[0]["pool_name"] == "cua-cli-wif-smoke"
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_backed_delete_removes_mapping_only_after_success(monkeypatch, tmp_path):
- from cua_sandbox import sandbox_state
-
- calls = []
- monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)
- sandbox_state.save_fleet_claim("wif-smoke-123", "cua-cli-wif-smoke")
- monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: True))
-
- class FleetTransport:
- @classmethod
- async def delete_sandbox(cls, name, *, pool_name=None):
- calls.append((name, pool_name))
-
- monkeypatch.setattr(sandbox_module, "FleetCloudTransport", FleetTransport)
-
- await Sandbox.delete("wif-smoke-123")
-
- assert calls == [("wif-smoke-123", "cua-cli-wif-smoke")]
- assert sandbox_state.load("wif-smoke-123") is None
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_backed_delete_keeps_mapping_when_claim_delete_fails(monkeypatch, tmp_path):
- from cua_sandbox import sandbox_state
-
- monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)
- sandbox_state.save_fleet_claim("wif-smoke-123", "cua-cli-wif-smoke")
- monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: True))
-
- class FleetTransport:
- @classmethod
- async def delete_sandbox(cls, name, *, pool_name=None):
- raise RuntimeError("claim delete failed")
-
- monkeypatch.setattr(sandbox_module, "FleetCloudTransport", FleetTransport)
-
- with pytest.raises(RuntimeError, match="claim delete failed"):
- await Sandbox.delete("wif-smoke-123")
-
- assert sandbox_state.load("wif-smoke-123")["pool_name"] == "cua-cli-wif-smoke"
diff --git a/libs/python/cua-sandbox/tests/test_cloud_ended.py b/libs/python/cua-sandbox/tests/test_cloud_ended.py
index b8c5846c36..07e5b9503c 100644
--- a/libs/python/cua-sandbox/tests/test_cloud_ended.py
+++ b/libs/python/cua-sandbox/tests/test_cloud_ended.py
@@ -2,9 +2,14 @@
from __future__ import annotations
+import importlib
+
import pytest
from cua_sandbox import Image, Pool, Sandbox, pools
from cua_sandbox._ended import CLOUD_ENDED, CloudEnded
+from cua_sandbox.runtime.base import RuntimeInfo
+
+sandbox_module = importlib.import_module("cua_sandbox.sandbox")
MESSAGE = (
"Cua Cloud has ended; use a local sandbox or your own machine. "
@@ -64,3 +69,128 @@ async def test_the_default_listing_is_local_only(monkeypatch):
monkeypatch.setattr(Sandbox, "_list_local", classmethod(lambda cls: local()))
assert await Sandbox.list() == []
+
+
+async def test_local_creation_with_a_runtime_object_writes_its_state_file(monkeypatch, tmp_path):
+ # The named local sandbox writes a state file; keep it in this test's
+ # own CUA_HOME (the autouse conftest one too, but never rely on it).
+ monkeypatch.setenv("CUA_HOME", str(tmp_path))
+ calls = []
+
+ class Runtime:
+ # Sandbox._create tells the runtime whether the sandbox is ephemeral;
+ # a double that omits it fails the call rather than the assertion.
+ async def start(self, image, name, *, ephemeral=True):
+ calls.append(("start", image, name))
+ return RuntimeInfo(host="127.0.0.1", api_port=8000, name=name, environment="linux")
+
+ sandbox = await Sandbox.create(Image.linux(), name="local-demo", local=True, runtime=Runtime())
+ await sandbox.disconnect()
+
+ assert calls[0][2] == "local-demo"
+ assert (tmp_path / "sandboxes" / "local-demo.json").exists()
+
+
+ "kwargs",
+ [
+ {"pool": "my-pool"},
+ {"warm": True},
+ {"max_pool_size": 3},
+ {"claim_ttl": 60},
+ {"claim_spec": object()},
+ {"keep_alive_minutes": 5},
+ {"api_key": "sk-legacy"},
+ ],
+)
+async def test_cloud_only_arguments_select_the_cloud_and_fail_without_a_warning(kwargs):
+ import warnings
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ with pytest.raises(CloudEnded):
+ await Sandbox.create(Image.linux(), **kwargs)
+
+
+ "kwargs",
+ [{"pool": "my-pool"}, {"claim_spec": object()}, {"replicas": 2}, {"service": "driver"}],
+)
+async def test_claim_arguments_fail_even_when_local_is_explicit(kwargs):
+ with pytest.raises(CloudEnded):
+ await Sandbox.create(Image.linux(), local=True, **kwargs)
+ with pytest.raises(CloudEnded):
+ async with Sandbox.ephemeral(Image.linux(), local=True, **kwargs):
+ pass
+
+
+async def test_the_retired_pool_surface_raises_the_one_message():
+ from cua_sandbox import PoolOptions, SandboxSpec, Template, generate_claim_token
+ from cua_sandbox.spec import PoolAccessDeniedError
+
+ for call in (
+ lambda: Pool.reconcile(object()),
+ lambda: Pool.apply("p", SandboxSpec(image="x"), PoolOptions()),
+ lambda: Pool.export("p"),
+ lambda: Pool.check("p", SandboxSpec()),
+ lambda: Pool.apply_template("p", SandboxSpec()),
+ lambda: Template.reconcile(object()),
+ lambda: pools.list_claims(),
+ lambda: pools.gc_pools(["p"]),
+ ):
+ with pytest.raises(CloudEnded) as error:
+ await call()
+ assert str(error.value) == MESSAGE
+ for build in (lambda: Pool(object()), lambda: Template(object())):
+ with pytest.raises(CloudEnded):
+ build()
+ with pytest.raises(CloudEnded):
+ Pool.claim(None)
+ assert len(generate_claim_token()) == 64
+ assert issubclass(PoolAccessDeniedError, PermissionError)
+
+
+async def test_sandbox_methods_that_belonged_to_claims_raise_the_one_message():
+ sb = Sandbox(object(), name="box", _telemetry_enabled=False)
+ assert (sb.claim_name, sb.pool_name) == (None, None)
+ assert sb.id == "local:box"
+ for call in (
+ lambda: sb.keep_alive(minutes=5),
+ lambda: sb.close(),
+ lambda: sb.snapshot(),
+ ):
+ with pytest.raises(CloudEnded):
+ await call()
+ with pytest.raises(CloudEnded):
+ sb.to_dict()
+ with pytest.raises(CloudEnded):
+ Sandbox.from_dict({})
+
+
+def test_retired_cloud_names_explain_themselves_on_import():
+ import cua_sandbox
+ from cua_sandbox import CloudTransport
+
+ for name in ("ClaimSpec", "WarmPoolAutoscaling", "RuntimeKind", "fleet_auth_source"):
+ with pytest.raises(ImportError, match="Cua Cloud has ended"):
+ getattr(cua_sandbox, name)
+ with pytest.raises(AttributeError):
+ cua_sandbox.nonsense
+ with pytest.raises(CloudEnded):
+ CloudTransport(name="x")
+
+
+def test_configure_still_takes_the_retired_cloud_options():
+ from cua_sandbox import configure
+
+ with pytest.warns(DeprecationWarning, match="Cua Cloud has ended"):
+ configure(client_id="id", client_secret="secret")
+
+
+async def test_an_unknown_bare_name_is_not_found_locally(monkeypatch):
+ # A bare name used to fall through to the cloud; now it is a local lookup.
+ monkeypatch.setattr(sandbox_module, "_remove_orphan_container", lambda name: False)
+ with pytest.raises(ValueError, match="No local sandbox named 'nope'"):
+ await Sandbox.connect("nope")
+ with pytest.raises(ValueError, match="No local sandbox named 'nope'"):
+ await Sandbox.delete("nope")
diff --git a/libs/python/cua-sandbox/tests/test_config.py b/libs/python/cua-sandbox/tests/test_config.py
index 6aa154b1c4..f2e1306240 100644
--- a/libs/python/cua-sandbox/tests/test_config.py
+++ b/libs/python/cua-sandbox/tests/test_config.py
@@ -1,27 +1,18 @@
"""Unit tests for config and auth modules."""
+import warnings
+
import pytest
from cua_sandbox._config import (
_global_config,
configure,
get_api_key,
get_base_url,
- get_client_id,
- get_client_secret,
- get_fleet_base_url,
- get_fleet_token,
- get_token_url,
- has_fleet_auth,
)
_CONFIG_ENV_VARS = (
"CUA_API_KEY",
"CUA_BASE_URL",
- "CUA_FLEET_BASE_URL",
- "CUA_TOKEN_URL",
- "CUA_CLIENT_ID",
- "CUA_CLIENT_SECRET",
- "FLEETS_TOKEN",
)
@@ -41,16 +32,8 @@ def isolate_config(monkeypatch):
class TestConfig:
- def test_configure_client_credentials_uses_fleet_defaults(self):
- configure(client_id="client-id", client_secret="client-secret")
-
- assert get_client_id() == "client-id"
- assert get_client_secret() == "client-secret"
+ def test_default_base_url(self):
assert get_base_url() == "https://api.cua.ai"
- assert get_fleet_base_url() == "https://run.cua.ai"
- assert (
- get_token_url() == "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"
- )
def test_configure_api_key(self):
configure(api_key="sk-test-123")
@@ -73,39 +56,22 @@ class TestConfig:
configure(api_key="sk-configured")
assert get_api_key() == "sk-configured"
- def test_get_fleet_token_prefers_configured_token(self, monkeypatch):
- monkeypatch.setenv("FLEETS_TOKEN", " env-token ")
- configure(fleet_token=" configured-token ")
-
- assert get_fleet_token() == "configured-token"
-
- def test_get_fleet_token_uses_trimmed_environment_token(self, monkeypatch):
- monkeypatch.setenv("FLEETS_TOKEN", " env-token ")
-
- assert get_fleet_token() == "env-token"
-
- def test_get_fleet_token_treats_blank_configured_token_as_unset(self, monkeypatch):
- monkeypatch.setenv("FLEETS_TOKEN", "env-token")
- configure(fleet_token=" \t ")
-
- assert get_fleet_token() == "env-token"
+ def test_cloud_options_are_accepted_and_ignored_with_a_warning(self):
+ """Cua Cloud has ended: its options keep parsing but change nothing."""
+ with pytest.warns(DeprecationWarning, match="Cua Cloud has ended"):
+ configure(
+ fleet_base_url="https://fleet.example.test",
+ token_url="https://auth.example.test/token",
+ client_id="client-id",
+ client_secret="client-secret",
+ fleet_token="fleet-token",
+ )
- def test_get_fleet_token_treats_blank_environment_token_as_unset(self, monkeypatch):
- monkeypatch.setenv("FLEETS_TOKEN", " \n ")
-
- assert get_fleet_token() is None
-
- def test_has_fleet_auth_with_static_token(self):
- configure(fleet_token="fleet-token")
-
- assert has_fleet_auth() is True
-
- def test_has_fleet_auth_with_complete_client_credentials(self):
- configure(client_id="client-id", client_secret="client-secret")
-
- assert has_fleet_auth() is True
-
- def test_has_fleet_auth_requires_complete_credentials_without_token(self):
- configure(client_id="client-id")
+ assert get_base_url() == "https://api.cua.ai"
+ assert get_api_key() is None
+ assert not hasattr(_global_config, "client_id")
- assert has_fleet_auth() is False
+ def test_api_key_and_base_url_do_not_warn(self):
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ configure(api_key="sk-test-123", base_url="http://localhost:9000")
diff --git a/libs/python/cua-sandbox/tests/test_cua_home.py b/libs/python/cua-sandbox/tests/test_cua_home.py
index bb5002cb91..2ea4b2c33a 100644
--- a/libs/python/cua-sandbox/tests/test_cua_home.py
+++ b/libs/python/cua-sandbox/tests/test_cua_home.py
@@ -78,8 +78,6 @@ def test_state_goes_to_cua_home_never_the_real_home(fake_homes):
config = importlib.import_module("cua_sandbox._config")
assert config._read_credentials_key() == "test-key"
- autopool = importlib.import_module("cua_sandbox._autopool")
- assert autopool.cua_dir() == cua_home
image = importlib.import_module("cua_sandbox.image")
assert image._image_cache() == cua_home / "cua-sandbox" / "image-cache"
diff --git a/libs/python/cua-sandbox/tests/test_cyclops_http_client.py b/libs/python/cua-sandbox/tests/test_cyclops_http_client.py
deleted file mode 100644
index 728356bec3..0000000000
--- a/libs/python/cua-sandbox/tests/test_cyclops_http_client.py
+++ /dev/null
@@ -1,66 +0,0 @@
-from __future__ import annotations
-
-from typing import Any
-
-import httpx
-import pytest
-from cua_sandbox.transport.cyclops_http_client import CyclopsHttpClient
-from fleet_sdk import HttpError, HttpRequest
-
-
-class RecordingClient:
- def __init__(self, response: httpx.Response | Exception) -> None:
- self.response = response
- self.calls: list[tuple[str, str, dict[str, Any]]] = []
-
- async def request(self, method: str, url: str, **kwargs: Any) -> httpx.Response:
- self.calls.append((method, url, kwargs))
- if isinstance(self.response, Exception):
- raise self.response
- return self.response
-
-
-def fleet_request(timeout_secs: int | None) -> HttpRequest:
- return HttpRequest(
- method="POST",
- url="https://fleet.example/api/svc/ns/computer-server/cmd",
- headers=[],
- body=b"{}",
- timeout_secs=timeout_secs,
- )
-
-
-async def test_execute_forwards_per_request_timeout_to_httpx() -> None:
- response = httpx.Response(200, content=b"ok")
- client = RecordingClient(response)
-
- result = await CyclopsHttpClient(client).execute(fleet_request(120))
-
- assert result.status == 200
- assert client.calls == [
- (
- "POST",
- "https://fleet.example/api/svc/ns/computer-server/cmd",
- {"headers": {}, "content": b"{}", "timeout": 120},
- )
- ]
-
-
-async def test_execute_uses_shared_client_default_without_request_timeout() -> None:
- client = RecordingClient(httpx.Response(200, content=b"ok"))
-
- await CyclopsHttpClient(client).execute(fleet_request(None))
-
- assert "timeout" not in client.calls[0][2]
-
-
-async def test_execute_reports_transport_error_type_when_message_is_empty() -> None:
- client = RecordingClient(httpx.ReadTimeout(""))
-
- with pytest.raises(HttpError.Transport) as raised:
- await CyclopsHttpClient(client).execute(fleet_request(120))
-
- assert raised.value.reason == "ReadTimeout"
diff --git a/libs/python/cua-sandbox/tests/test_display_url.py b/libs/python/cua-sandbox/tests/test_display_url.py
index 5755dd7a04..1a73beef35 100644
--- a/libs/python/cua-sandbox/tests/test_display_url.py
+++ b/libs/python/cua-sandbox/tests/test_display_url.py
@@ -1,7 +1,6 @@
"""``Sandbox.get_display_url()`` on SDK-backed sandboxes: the cua-spacesd
viewer link when the sandbox runs cua-spacesd, else the page of a declared
-legacy web display service (local loopback or a Fleet signed URL). Fakes only;
-nothing is started."""
+legacy web display service (local loopback). Fakes only; nothing is started."""
from __future__ import annotations
@@ -152,34 +151,3 @@ async def test_no_display_points_at_cua_spacesd():
assert "cua-spacesd" in message and "3211" in message
assert "novnc" not in message.lower() and "6080" not in message
assert "EnvTransport" not in message
-
-
-async def test_fleet_transport_returns_the_viewer_link(monkeypatch):
- from cua_sandbox.transport import fleet as fleet_module
-
- handle = _Handle({}, {}, viewer="https://gw.example/api/svc/ns/box/env/viewer/#t=1")
-
- async def fake_fleet_sandbox(*_args):
- return handle
-
- monkeypatch.setattr(fleet_module, "fleet_sandbox", fake_fleet_sandbox)
- bound = SimpleNamespace(name="box", namespace="ns", claim="c1", services={"env": 3211})
- transport = fleet_module.FleetTransport(sdk=object(), bound=bound)
- assert await transport.get_display_url() == handle._viewer
-
-
-async def test_fleet_transport_reads_the_claims_legacy_services(monkeypatch):
- from cua_sandbox.transport import fleet as fleet_module
-
- handle = _Handle({}, {"novnc": "https://gw.example/api/svc/ns/box/novnc?sig=1"})
-
- async def fake_fleet_sandbox(*_args):
- return handle
-
- monkeypatch.setattr(fleet_module, "fleet_sandbox", fake_fleet_sandbox)
- bound = SimpleNamespace(name="box", namespace="ns", claim="c1", services={"novnc": 6080})
- transport = fleet_module.FleetTransport(sdk=object(), bound=bound)
- url = await transport.get_display_url()
- assert url.startswith("https://gw.example/api/svc/ns/box/novnc/vnc.html?sig=1&autoconnect=1")
diff --git a/libs/python/cua-sandbox/tests/test_docs_regressions.py b/libs/python/cua-sandbox/tests/test_docs_regressions.py
index 8620caf448..5e96c65f17 100644
--- a/libs/python/cua-sandbox/tests/test_docs_regressions.py
+++ b/libs/python/cua-sandbox/tests/test_docs_regressions.py
@@ -16,35 +16,6 @@ def _build_helpers():
return build_hash, has_build_work
-class TestCloudTransportGetsItsImage:
- """`_make_transport` dropped `image`, so every API-key cloud create raised
- "Cannot create a cloud VM without an image"."""
-
- def test_make_transport_accepts_an_image(self):
- from cua_sandbox.sandbox import _make_transport
-
- assert "image" in inspect.signature(_make_transport).parameters
-
- def test_cloud_transport_receives_the_image(self):
- from cua_sandbox.sandbox import _make_transport
-
- img = Image.linux()
- transport = _make_transport(api_key="sk-test", name="probe", image=img)
- assert transport._image is img
-
- def test_create_passes_the_image_to_every_make_transport_that_creates_a_vm(self):
- """Guards the exact regression: the Fleet branch passed image=image while
- the api-key branch right below it silently did not."""
- from cua_sandbox.sandbox import Sandbox
-
- src = inspect.getsource(Sandbox._create)
- creating_call = "_make_transport(\n api_key=api_key,\n"
- assert creating_call in src, "the VM-creating _make_transport call moved"
- start = src.index(creating_call)
- call = src[start : src.index(")", start)]
- assert "image=image" in call
-
-
class TestEnvAndFilesAreBuildInputs:
"""`.env()` and `.copy()` were dropped on the QEMU VM path: the builder only
looked at `_layers`, so the variables and files never reached the guest."""
diff --git a/libs/python/cua-sandbox/tests/test_driver_env.py b/libs/python/cua-sandbox/tests/test_driver_env.py
index fa88076824..3bbb4e6f2b 100644
--- a/libs/python/cua-sandbox/tests/test_driver_env.py
+++ b/libs/python/cua-sandbox/tests/test_driver_env.py
@@ -4,85 +4,47 @@
Wire/ownership tests; not proof of a guest desktop or native effects.
"""
+import asyncio
+import sys
from types import SimpleNamespace
import pytest
-from cua_sandbox import _sdk
from cua_sandbox.interfaces.driver import DriverConnectionError
from cua_sandbox.sandbox import Sandbox
-from cua_sandbox.transport.env import EnvTransport
-from cua_sandbox.transport.fleet import FleetTransport
+from cua_sandbox.transport.base import Transport as BaseTransport
-from .test_driver_mcp import McpTransport
-from .test_driver_mcp_shared import shared as _shared_fixture
-from .test_typed_driver import native as _native_fixture
+from ._driver_env_support import EnvHttp, McpTransport, env_sandbox
+from ._driver_env_support import native as _native_fixture
+from ._driver_env_support import records as _records_fixture
+from ._driver_env_support import shared as _shared_fixture
from .test_typed_driver_native import sdk as _sdk_fixture
native = _native_fixture
+records = _records_fixture
shared = _shared_fixture
sdk = _sdk_fixture
-class EnvHttp:
- """A stand-in ``cua.SpacesdClient`` whose ``http`` is served by ``McpTransport``'s
- synthetic MCP receiver (or a canned reply)."""
-
- def __init__(self, mcp=None, reply=None):
- self.mcp = mcp
- self.reply = reply
- self.requests = []
-
- async def http(self, request):
- self.requests.append(request)
- if self.reply is not None:
- return self.reply
- response = await self.mcp.request_service(
- "mcp",
- method=request.method,
- path=request.path,
- body=bytes(request.body),
- headers=[(h.name, h.value) for h in request.headers],
- timeout=None if request.timeout_ms is None else request.timeout_ms / 1000,
- max_response_bytes=request.max_response_bytes,
- )
- return SimpleNamespace(
- status=response.status_code,
- headers=[SimpleNamespace(name=k, value=v) for k, v in response.headers.multi_items()],
- body=response.content,
- )
-
-
-def records(monkeypatch):
- """The SDK's record types, without the native library."""
- types = SimpleNamespace(SpacesdHttpRequest=SimpleNamespace, SpacesdHttpHeader=SimpleNamespace)
- monkeypatch.setattr(_sdk, "native", lambda: types)
- return types
-
+class PlainTransport(BaseTransport):
+ """A transport with no cua-spacesd (e.g. QMP/VNC)."""
-async def env_sandbox(env):
- async def factory():
- return env
+ async def connect(self):
+ pass
- sb = Sandbox(EnvTransport(env_factory=factory), _telemetry_enabled=False)
- await sb._connect()
- return sb
+ async def disconnect(self):
+ pass
+ async def send(self, action, **params):
+ raise NotImplementedError
-class FleetEnvTransport(FleetTransport):
- """A bound Fleet claim whose image runs cua-spacesd (service ``env``)."""
+ async def screenshot(self, format="png", quality=95):
+ raise NotImplementedError
- def __init__(self, env, services=("env",)):
- super().__init__(sdk=None, bound=SimpleNamespace(services=list(services), name="sb"))
- self._env = env
- self.named = []
+ async def get_screen_size(self):
+ raise NotImplementedError
- async def spacesd(self):
- return self._env
-
- async def request_service(self, name, **request):
- self.named.append((name, request))
- raise AssertionError("the spacesd carrier must not use Fleet named services")
+ async def get_environment(self):
+ return "linux"
async def test_default_carrier_is_spacesd_mcp_through_the_sdk(shared, records):
@@ -121,30 +83,12 @@ async def test_default_carrier_is_spacesd_mcp_through_the_sdk(shared, records):
await sb.disconnect()
-async def test_fleet_env_claim_uses_the_env_carrier_not_named_services(shared, records):
- _, channels = shared
- env = EnvHttp(reply=SimpleNamespace(status=200, headers=[], body=b"{}"))
- transport = FleetEnvTransport(env)
- sb = Sandbox(transport, _telemetry_enabled=False)
- await sb._connect()
- async with sb.driver.connect():
- request = SimpleNamespace(method="POST", path="/mcp", body=b"", headers=[], timeout_ms=5)
- await channels[0].transport.send(request)
- assert len(env.requests) == 1 and not transport.named
- await sb.disconnect()
-
-
-async def test_fleet_claim_without_env_service_fails_before_loading_native(monkeypatch):
- import sys
-
+async def test_a_transport_without_spacesd_does_not_load_native(monkeypatch):
monkeypatch.setitem(sys.modules, "cua_driver", None)
- transport = FleetEnvTransport(EnvHttp(), services=("server",))
- sb = Sandbox(transport, _telemetry_enabled=False)
- await sb._connect()
- with pytest.raises(DriverConnectionError, match="expose"):
+ sb = Sandbox(PlainTransport(), _telemetry_enabled=False)
+ with pytest.raises(DriverConnectionError, match="cua-spacesd"):
async with sb.driver.connect():
pass
- await sb.disconnect()
async def test_spacesd_carries_mcp_only(native):
@@ -152,9 +96,18 @@ async def test_spacesd_carries_mcp_only(native):
with pytest.raises(DriverConnectionError, match="MCP only"):
async with sb.driver.connect(service="env", transport="envelope"):
pass
- with pytest.raises(DriverConnectionError, match="Fleet transport"):
+ with pytest.raises(DriverConnectionError, match="MCP only"):
+ async with sb.driver.connect(transport="envelope"):
+ pass
+ with pytest.raises(DriverConnectionError, match="Named Driver services"):
async with sb.driver.connect(service="mcp", transport="mcp"):
pass
+ with pytest.raises(DriverConnectionError, match="Named Driver services"):
+ async with sb.driver.connect(service="driver"):
+ pass
+ with pytest.raises(DriverConnectionError, match="transport must"):
+ async with sb.driver.connect(transport="guess"):
+ pass
await sb.disconnect()
@@ -162,7 +115,6 @@ async def test_actual_generated_driver_over_spacesd_mcp(sdk, records):
"""The real generated binding negotiates the envelope extension and
exchanges typed records over the env carrier."""
mcp = McpTransport()
- await mcp.connect()
mcp.response_data["result"] = {
"content": [{"type": "text", "text": "typed-env-fixture"}],
"isError": False,
@@ -181,4 +133,46 @@ async def test_actual_generated_driver_over_spacesd_mcp(sdk, records):
assert env.requests and all(r.path == "/mcp" for r in env.requests)
finally:
await sb.disconnect()
- await mcp.disconnect()
+
+
+async def test_accessor_rejects_cleanup_from_another_event_loop(shared, records):
+ sb = await env_sandbox(EnvHttp())
+ async with sb.driver.connect():
+
+ def wrong_loop():
+ with pytest.raises(DriverConnectionError, match="different event loop"):
+ asyncio.run(sb.driver.close())
+
+ await asyncio.to_thread(wrong_loop)
+ await sb.disconnect()
+
+
+async def test_session_name_only_for_active_owned_driver(shared, records):
+ sb = await env_sandbox(EnvHttp())
+ async with sb.driver.connect() as driver:
+ assert sb.driver.session_name(driver) == "host-selected"
+ with pytest.raises(DriverConnectionError, match="another sandbox"):
+ sb.driver.session_name(object())
+ with pytest.raises(DriverConnectionError, match="inactive"):
+ sb.driver.session_name(driver)
+ await sb.disconnect()
+
+
+async def test_context_cancellation_closes_the_channel(shared, records):
+ _, channels = shared
+ sb = await env_sandbox(EnvHttp())
+ opened = asyncio.Event()
+
+ async def run():
+ async with sb.driver.connect():
+ opened.set()
+ await asyncio.Event().wait()
+
+ task = asyncio.create_task(run())
+ await opened.wait()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert channels[0].closes >= 1
+ assert not sb.driver._connections
+ await sb.disconnect()
diff --git a/libs/python/cua-sandbox/tests/test_driver_mcp.py b/libs/python/cua-sandbox/tests/test_driver_mcp.py
index 2237cff81c..5db2a4590f 100644
--- a/libs/python/cua-sandbox/tests/test_driver_mcp.py
+++ b/libs/python/cua-sandbox/tests/test_driver_mcp.py
@@ -1,4 +1,4 @@
-"""MCP session/wire tests; not proof of a guest desktop or native effects."""
+"""MCP session/wire tests over the spacesd carrier; not proof of a guest desktop or native effects."""
import asyncio
import json
@@ -6,155 +6,52 @@ import json
import httpx
import pytest
from cua_sandbox.interfaces.driver import DriverConnectionError
-from cua_sandbox.sandbox import Sandbox
-from .test_typed_driver import Transport
+from ._driver_env_support import McpTransport
+from ._driver_env_support import records as _records_fixture
+from ._driver_env_support import sandbox
from .test_typed_driver_native import sdk as _sdk_fixture
+records = _records_fixture
sdk = _sdk_fixture
-class McpTransport(Transport):
- def __init__(self, *, sse=False, supported=True):
- super().__init__()
- self._bound.services.append("mcp")
- self.sse = sse
- self.supported = supported
- self.sessions = set()
- self.sequence = 0
- self.mutate = None
- self.fail_exchange = False
- self.exchange_started = asyncio.Event()
- self.exchange_wait = None
- self.cancel_releases_exchange = True
- self.exchange_aborted = False
- self.exchange_finished = asyncio.Event()
- self.cancel_received = asyncio.Event()
-
- async def request_service(
- self,
- name,
- *,
- method,
- path,
- body=None,
- json_body=None,
- headers=None,
- timeout=None,
- max_response_bytes=None,
- ):
- assert max_response_bytes == 16 * 1024 * 1024
- if body:
- json_body = json.loads(body)
- headers = httpx.Headers(headers)
- self.events.append((name, method, path, json_body, headers))
- assert name == "mcp" and path == "/mcp"
- assert headers["Accept"] == "application/json, text/event-stream"
- rpc = json_body.get("method") if json_body else None
- response_headers = {}
- if rpc == "initialize":
- assert "Mcp-Session-Id" not in headers
- self.sequence += 1
- session = f"http-session-{self.sequence}"
- self.sessions.add(session)
- response_headers["Mcp-Session-Id"] = session
- result = {
- "protocolVersion": "2025-06-18",
- "capabilities": {
- "experimental": (
- {"ai.cua.driver.envelopes": {"version": 1}} if self.supported else {}
- )
- },
- }
- else:
- session = headers["Mcp-Session-Id"]
- assert headers["MCP-Protocol-Version"] == "2025-06-18"
- if session not in self.sessions:
- return httpx.Response(404)
- if method == "DELETE":
- self.sessions.remove(session)
- return httpx.Response(200)
- if rpc == "notifications/initialized":
- assert "id" not in json_body
- return httpx.Response(202)
- if rpc == "cua/driver/v1/open":
- result = dict(self.open_data, connection_id=session, generation=f"gen-{session}")
- else:
- assert json_body["params"]["connection_id"] == session
- assert json_body["params"]["generation"] == f"gen-{session}"
- if rpc == "cua/driver/v1/exchange":
- self.exchange_started.set()
- if self.exchange_wait is not None:
- try:
- await self.exchange_wait.wait()
- except asyncio.CancelledError:
- self.exchange_aborted = True
- raise
- if self.fail_exchange:
- raise RuntimeError("sensitive transport diagnostic")
- request = json_body["params"]["envelope"]
- result = dict(self.response_data, request_id=request["request_id"])
- self.exchange_finished.set()
- else:
- assert rpc in ("cua/driver/v1/cancel", "cua/driver/v1/close")
- if rpc == "cua/driver/v1/cancel":
- self.cancel_received.set()
- if self.cancel_releases_exchange and self.exchange_wait is not None:
- self.exchange_wait.set()
- result = {"ok": True}
- response = {"jsonrpc": "2.0", "id": json_body["id"], "result": result}
- if self.mutate:
- response = self.mutate(rpc, response)
- if self.sse:
- response_headers["Content-Type"] = "text/event-stream"
- return httpx.Response(
- 200,
- content=("event: message\r\ndata: " + json.dumps(response) + "\r\n\r\n"),
- headers=response_headers,
- )
- return httpx.Response(200, json=response, headers=response_headers)
-
-
-async def sandbox(transport):
- sb = Sandbox(transport, _telemetry_enabled=False)
- await sb._connect()
- return sb
-
-
@pytest.mark.parametrize("sse", [False, True])
-async def test_explicit_mcp_preserves_canonical_driver_and_computer_server(sdk, sse):
+async def test_default_carrier_preserves_canonical_driver_and_sandbox_interfaces(sdk, records, sse):
transport = McpTransport(sse=sse)
sb = await sandbox(transport)
+ sandbox_transport = sb._transport
try:
- async with sb.driver.connect(service="mcp", transport="mcp") as driver:
+ async with sb.driver.connect() as driver:
assert type(driver) is sdk.CuaDriver
- assert all(interface._t is transport for interface in (sb.shell, sb.files, sb.mouse))
- assert transport._service_name == "server"
+ assert all(
+ interface._t is sandbox_transport for interface in (sb.shell, sb.files, sb.mouse)
+ )
assert sb.driver.session_name(driver) == "session-1"
assert not transport.sessions
assert transport.events[-2][3]["method"] == "cua/driver/v1/close"
assert transport.events[-1][1] == "DELETE"
- assert transport._connected
+ assert sandbox_transport._connected
finally:
await sb.disconnect()
-async def test_old_tools_only_endpoint_fails_before_open_and_cleans_http_session(sdk):
+async def test_old_tools_only_endpoint_fails_before_open_and_cleans_http_session(sdk, records):
transport = McpTransport(supported=False)
sb = await sandbox(transport)
with pytest.raises(sdk.DriverError.Remote):
- async with sb.driver.connect(service="mcp", transport="mcp"):
+ async with sb.driver.connect():
pytest.fail("must not yield a facade")
assert [event[3]["method"] for event in transport.events if event[3]] == ["initialize"]
assert not transport.sessions
await sb.disconnect()
-async def test_two_channels_keep_distinct_mcp_sessions_and_close_independently(sdk):
+async def test_two_channels_keep_distinct_mcp_sessions_and_close_independently(sdk, records):
transport = McpTransport()
sb = await sandbox(transport)
- async with sb.driver.connect(service="mcp", transport="mcp") as first:
- async with sb.driver.connect(service="mcp", transport="mcp") as second:
+ async with sb.driver.connect() as first:
+ async with sb.driver.connect() as second:
assert first is not second
assert len(transport.sessions) == 2
assert len(transport.sessions) == 1
@@ -162,7 +59,7 @@ async def test_two_channels_keep_distinct_mcp_sessions_and_close_independently(s
await sb.disconnect()
-async def test_unknown_transport_rejected_before_any_service_request(sdk):
+async def test_unknown_transport_rejected_before_any_service_request(sdk, records):
transport = McpTransport()
sb = await sandbox(transport)
with pytest.raises(DriverConnectionError, match="transport must"):
@@ -172,10 +69,10 @@ async def test_unknown_transport_rejected_before_any_service_request(sdk):
await sb.disconnect()
-async def test_lost_exchange_never_retries_or_reinitializes(sdk, caplog):
+async def test_lost_exchange_never_retries_or_reinitializes(sdk, records, caplog):
transport = McpTransport()
sb = await sandbox(transport)
- async with sb.driver.connect(service="mcp", transport="mcp") as driver:
+ async with sb.driver.connect() as driver:
transport.fail_exchange = True
with pytest.raises(sdk.DriverError.ActionInterrupted) as interrupted:
await driver.get_screen_size(sdk.GetScreenSizeInput(session=None))
@@ -198,7 +95,7 @@ async def test_lost_exchange_never_retries_or_reinitializes(sdk, caplog):
@pytest.mark.parametrize("mutation", ["wrong-id", "bad-version", "rpc-error", "wrong-inner-id"])
-async def test_malformed_or_failed_response_closes_without_replay(sdk, mutation):
+async def test_malformed_or_failed_response_closes_without_replay(sdk, records, mutation):
transport = McpTransport()
sb = await sandbox(transport)
@@ -216,7 +113,7 @@ async def test_malformed_or_failed_response_closes_without_replay(sdk, mutation)
response["result"]["request_id"] = "wrong-inner-id"
return response
- async with sb.driver.connect(service="mcp", transport="mcp") as driver:
+ async with sb.driver.connect() as driver:
transport.mutate = mutate
with pytest.raises(sdk.DriverError.ActionInterrupted) as error:
await driver.get_screen_size(sdk.GetScreenSizeInput(session=None))
@@ -226,19 +123,19 @@ async def test_malformed_or_failed_response_closes_without_replay(sdk, mutation)
await sb.disconnect()
-async def test_malformed_initialize_still_deletes_allocated_session(sdk):
+async def test_malformed_initialize_still_deletes_allocated_session(sdk, records):
transport = McpTransport()
transport.mutate = lambda method, response: dict(response, id="wrong")
sb = await sandbox(transport)
with pytest.raises(sdk.DriverError.Remote):
- async with sb.driver.connect(service="mcp", transport="mcp"):
+ async with sb.driver.connect():
pass
assert not transport.sessions
assert transport.events[-1][1] == "DELETE"
await sb.disconnect()
-async def test_disconnect_during_initialization_cleans_late_session(sdk, monkeypatch):
+async def test_disconnect_during_initialization_cleans_late_session(sdk, records, monkeypatch):
transport = McpTransport()
entered, released = asyncio.Event(), asyncio.Event()
original = transport.request_service
@@ -253,7 +150,7 @@ async def test_disconnect_during_initialization_cleans_late_session(sdk, monkeyp
sb = await sandbox(transport)
async def connect():
- async with sb.driver.connect(service="mcp", transport="mcp"):
+ async with sb.driver.connect():
pytest.fail("disconnected accessor must not yield")
opening = asyncio.create_task(connect())
@@ -283,7 +180,7 @@ async def test_disconnect_during_initialization_cleans_late_session(sdk, monkeyp
],
)
async def test_shared_decoder_refuses_ambiguous_incomplete_or_non_json_responses(
- sdk, monkeypatch, body, media
+ sdk, records, monkeypatch, body, media
):
transport = McpTransport()
original = transport.request_service
@@ -301,7 +198,7 @@ async def test_shared_decoder_refuses_ambiguous_incomplete_or_non_json_responses
monkeypatch.setattr(transport, "request_service", malformed)
sb = await sandbox(transport)
- async with sb.driver.connect(service="mcp", transport="mcp") as driver:
+ async with sb.driver.connect() as driver:
with pytest.raises(sdk.DriverError.ActionInterrupted) as error:
await driver.get_screen_size(sdk.GetScreenSizeInput(session=None))
assert error.value.completion == sdk.ActionCompletion.UNKNOWN
diff --git a/libs/python/cua-sandbox/tests/test_driver_mcp_native.py b/libs/python/cua-sandbox/tests/test_driver_mcp_native.py
index 2085c8be07..4292724c1f 100644
--- a/libs/python/cua-sandbox/tests/test_driver_mcp_native.py
+++ b/libs/python/cua-sandbox/tests/test_driver_mcp_native.py
@@ -1,17 +1,20 @@
-"""Real generated Driver binding over a synthetic MCP/Fleet carrier."""
+"""Real generated Driver binding over a synthetic MCP carrier (cua-spacesd's ``/mcp``)."""
import asyncio
import pytest
-from .test_driver_mcp import McpTransport, sandbox
+from ._driver_env_support import McpTransport
+from ._driver_env_support import records as _records_fixture
+from ._driver_env_support import sandbox
from .test_typed_driver_native import sdk as _sdk_fixture
+records = _records_fixture
sdk = _sdk_fixture
@pytest.mark.parametrize("sse", [False, True])
-async def test_actual_generated_driver_and_typed_records_over_mcp(sdk, sse):
+async def test_actual_generated_driver_and_typed_records_over_mcp(sdk, records, sse):
transport = McpTransport(sse=sse)
transport.response_data["result"] = {
"content": [{"type": "text", "text": "typed-mcp-fixture"}],
@@ -19,7 +22,7 @@ async def test_actual_generated_driver_and_typed_records_over_mcp(sdk, sse):
}
sb = await sandbox(transport)
try:
- async with sb.driver.connect(service="mcp", transport="mcp") as driver:
+ async with sb.driver.connect() as driver:
assert type(driver) is sdk.CuaDriver
result = await driver.get_screen_size(sdk.GetScreenSizeInput(session=None))
assert result.text == "typed-mcp-fixture"
@@ -45,11 +48,11 @@ async def test_actual_generated_driver_and_typed_records_over_mcp(sdk, sse):
await sb.disconnect()
-async def test_actual_driver_refuses_noncanonical_metadata(sdk):
+async def test_actual_driver_refuses_noncanonical_metadata(sdk, records):
transport = McpTransport()
sb = await sandbox(transport)
try:
- async with sb.driver.connect(service="mcp", transport="mcp") as driver:
+ async with sb.driver.connect() as driver:
# Metadata still uses the canonical envelope instead of disguising
# an ordinary MCP tools/list result as generated Driver metadata.
transport.response_data["result"] = {"not": "driver metadata"}
@@ -59,11 +62,11 @@ async def test_actual_driver_refuses_noncanonical_metadata(sdk):
await sb.disconnect()
-async def test_actual_driver_does_not_gain_trusted_session_binding(sdk):
+async def test_actual_driver_does_not_gain_trusted_session_binding(sdk, records):
transport = McpTransport()
sb = await sandbox(transport)
try:
- async with sb.driver.connect(service="mcp", transport="mcp") as driver:
+ async with sb.driver.connect() as driver:
options = sdk.TrustedSessionOptions(
public_session="another-session",
mode=sdk.SessionPermissionMode.STANDARD,
@@ -80,12 +83,12 @@ async def test_actual_driver_does_not_gain_trusted_session_binding(sdk):
await sb.disconnect()
-async def test_actual_native_future_cancellation_reaches_mcp_receiver(sdk):
+async def test_actual_native_future_cancellation_reaches_mcp_receiver(sdk, records):
transport = McpTransport()
transport.exchange_wait = asyncio.Event()
sb = await sandbox(transport)
try:
- async with sb.driver.connect(service="mcp", transport="mcp") as driver:
+ async with sb.driver.connect() as driver:
task = asyncio.create_task(driver.get_screen_size(sdk.GetScreenSizeInput(session=None)))
await asyncio.wait_for(transport.exchange_started.wait(), 2)
task.cancel()
@@ -119,13 +122,15 @@ async def test_actual_native_future_cancellation_reaches_mcp_receiver(sdk):
@pytest.mark.parametrize("finish", ["cancel", "close"])
-async def test_shared_native_teardown_drains_pending_response_before_session_close(sdk, finish):
+async def test_shared_native_teardown_drains_pending_response_before_session_close(
+ sdk, records, finish
+):
transport = McpTransport()
transport.exchange_wait = asyncio.Event()
transport.cancel_releases_exchange = False
sb = await sandbox(transport)
try:
- async with sb.driver.connect(service="mcp", transport="mcp") as driver:
+ async with sb.driver.connect() as driver:
task = asyncio.create_task(driver.get_screen_size(sdk.GetScreenSizeInput(session=None)))
await asyncio.wait_for(transport.exchange_started.wait(), 2)
if finish == "cancel":
@@ -156,11 +161,11 @@ async def test_shared_native_teardown_drains_pending_response_before_session_clo
await sb.disconnect()
-async def test_shared_native_sandbox_rejects_use_from_another_event_loop(sdk):
+async def test_shared_native_sandbox_rejects_use_from_another_event_loop(sdk, records):
transport = McpTransport()
sb = await sandbox(transport)
try:
- async with sb.driver.connect(service="mcp", transport="mcp") as driver:
+ async with sb.driver.connect() as driver:
def other_loop():
async def get_session():
@@ -176,13 +181,13 @@ async def test_shared_native_sandbox_rejects_use_from_another_event_loop(sdk):
await sb.disconnect()
-async def test_shared_native_drain_timeout_is_bounded_and_does_not_abort(sdk, caplog):
+async def test_shared_native_drain_timeout_is_bounded_and_does_not_abort(sdk, records, caplog):
transport = McpTransport()
transport.exchange_wait = asyncio.Event()
transport.cancel_releases_exchange = False
sb = await sandbox(transport)
try:
- async with sb.driver.connect(service="mcp", transport="mcp") as driver:
+ async with sb.driver.connect() as driver:
task = asyncio.create_task(driver.get_screen_size(sdk.GetScreenSizeInput(session=None)))
await asyncio.wait_for(transport.exchange_started.wait(), 2)
await asyncio.wait_for(sb.driver.close(), 5)
diff --git a/libs/python/cua-sandbox/tests/test_driver_mcp_shared.py b/libs/python/cua-sandbox/tests/test_driver_mcp_shared.py
index ef4d13f12c..4813c8487b 100644
--- a/libs/python/cua-sandbox/tests/test_driver_mcp_shared.py
+++ b/libs/python/cua-sandbox/tests/test_driver_mcp_shared.py
@@ -8,68 +8,40 @@ import pytest
from cua_sandbox.interfaces._driver_mcp import shared_channel
from cua_sandbox.interfaces.driver import DriverConnectionError
-from .test_driver_mcp import McpTransport, sandbox
-from .test_typed_driver import native as _native_fixture
+from ._driver_env_support import EnvHttp, env_sandbox
+from ._driver_env_support import native as _native_fixture
+from ._driver_env_support import records as _records_fixture
+from ._driver_env_support import shared as _shared_fixture
native = _native_fixture
+records = _records_fixture
+shared = _shared_fixture
-def shared(native):
- channels = []
-
- class Channel:
- def __init__(self, transport, principal):
- self.transport, self.principal = transport, principal
- self.opened, self.closes = False, 0
- self.canonical = native.CuaDriver(self)
- channels.append(self)
-
- async def open(self):
- self.opened = True
-
- def driver(self):
- assert self.opened
- return self.canonical
-
- def public_session(self):
- return "host-selected"
-
- async def close(self):
- self.closes += 1
-
- native.DriverServiceTransport = object
- native.DriverServiceHeader = SimpleNamespace
- native.DriverServiceResponse = SimpleNamespace
- native.DriverServiceTransportError = SimpleNamespace(Failed=RuntimeError)
- native.open_mcp_driver_channel = Channel
- return native, channels
-
-
-async def test_shared_channel_is_canonical_and_closes_before_fleet(shared):
+async def test_shared_channel_is_canonical_and_closes_before_the_transport(shared, records):
sdk, channels = shared
- transport = McpTransport()
- sb = await sandbox(transport)
- async with sb.driver.connect(service="mcp", transport="mcp") as driver:
+ env = EnvHttp()
+ sb = await env_sandbox(env)
+ async with sb.driver.connect() as driver:
assert driver is channels[0].canonical
assert sb.driver.session_name(driver) == "host-selected"
assert channels[0].principal == sb.driver._principal
await sb.disconnect()
assert channels[0].closes >= 1
- assert not transport._connected
+ assert not sb._transport._connected
with pytest.raises(DriverConnectionError, match="inactive"):
sb.driver.session_name(driver)
assert driver.shutdowns == 0
- assert not transport.sessions
+ assert not env.requests
-async def test_missing_shared_api_never_falls_back_to_envelope(native):
- transport = McpTransport()
- sb = await sandbox(transport)
+async def test_missing_shared_api_never_falls_back_to_envelope(native, records):
+ env = EnvHttp()
+ sb = await env_sandbox(env)
with pytest.raises(DriverConnectionError, match="open_mcp_driver_channel"):
- async with sb.driver.connect(service="mcp", transport="mcp"):
+ async with sb.driver.connect():
pytest.fail("old SDK must not silently fall back")
- assert not transport.events
+ assert not env.requests
await sb.disconnect()
diff --git a/libs/python/cua-sandbox/tests/test_env_transport.py b/libs/python/cua-sandbox/tests/test_env_transport.py
index a3036d1b64..889fba25cc 100644
--- a/libs/python/cua-sandbox/tests/test_env_transport.py
+++ b/libs/python/cua-sandbox/tests/test_env_transport.py
@@ -333,9 +333,8 @@ def test_env_url_brackets_ipv6():
assert env_url("::1", 4000) == "http://[::1]:4000"
-def test_computer_server_ws_url_is_rejected_with_guidance():
- from cua_sandbox.sandbox import _make_transport
+async def test_computer_server_ws_url_is_rejected_with_guidance():
+ from cua_sandbox.sandbox import Sandbox
with pytest.raises(ValueError, match="cua-spacesd"):
- _make_transport(ws_url="ws://host:8000/ws")
- assert isinstance(_make_transport(http_url="http://host:3211"), EnvTransport)
+ await Sandbox._create(ws_url="ws://host:8000/ws", name="box", local=True)
diff --git a/libs/python/cua-sandbox/tests/test_exposed_ports_state.py b/libs/python/cua-sandbox/tests/test_exposed_ports_state.py
index 497586edc0..9335b2045f 100644
--- a/libs/python/cua-sandbox/tests/test_exposed_ports_state.py
+++ b/libs/python/cua-sandbox/tests/test_exposed_ports_state.py
@@ -66,9 +66,9 @@ class TestExposedPortsSurviveAReconnect:
class TestTunnelErrorNamesEverySupportedTransport:
- """The message hardcoded a list that fell out of date: FleetCloudTransport
- implements forward_tunnel but was not named, so a local caller was told Fleet
- could not tunnel either — contradicting the documented Fleet path."""
+ """The message hardcoded a list that fell out of date: a transport that
+ implements forward_tunnel was not named, so a caller was told it could not
+ tunnel — contradicting the documented path."""
def test_message_lists_exactly_the_transports_that_implement_it(self):
import importlib
diff --git a/libs/python/cua-sandbox/tests/test_fleet_auth_and_pools.py b/libs/python/cua-sandbox/tests/test_fleet_auth_and_pools.py
deleted file mode 100644
index 4910e8bd29..0000000000
--- a/libs/python/cua-sandbox/tests/test_fleet_auth_and_pools.py
+++ /dev/null
@@ -1,57 +0,0 @@
-"""fleet_auth_source() and the public pools module (no network, no vault)."""
-
-from __future__ import annotations
-
-import cua_sandbox
-import pytest
-from cua_sandbox import _config
-
-
-def clean_env(monkeypatch):
- for var in ("FLEETS_TOKEN", "CUA_CLIENT_ID", "CUA_CLIENT_SECRET"):
- monkeypatch.delenv(var, raising=False)
- monkeypatch.setattr(_config._global_config, "fleet_token", None)
- monkeypatch.setattr(_config._global_config, "client_id", None)
- monkeypatch.setattr(_config._global_config, "client_secret", None)
- monkeypatch.setattr(_config, "has_fleet_session", lambda: False)
- return monkeypatch
-
-
-def test_token_wins(clean_env):
- clean_env.setenv("FLEETS_TOKEN", "t")
- clean_env.setenv("CUA_CLIENT_ID", "id")
- clean_env.setenv("CUA_CLIENT_SECRET", "s")
- assert cua_sandbox.fleet_auth_source() == "FLEETS_TOKEN"
-
-
-def test_client_credentials_then_session(clean_env):
- clean_env.setenv("CUA_CLIENT_ID", "id")
- assert cua_sandbox.fleet_auth_source() is None # secret missing, no session
- clean_env.setenv("CUA_CLIENT_SECRET", "s")
- assert cua_sandbox.fleet_auth_source() == "client credentials"
-
-
-def test_session_only_when_nothing_else(clean_env):
- looked = []
- clean_env.setattr(_config, "has_fleet_session", lambda: looked.append(1) or True)
- assert cua_sandbox.fleet_auth_source() == "cua auth login session"
- clean_env.setenv("FLEETS_TOKEN", "t")
- assert cua_sandbox.fleet_auth_source() == "FLEETS_TOKEN"
- assert looked == [1] # the stored session is not read when a token is set
-
-
-def test_pools_module_is_public():
- from cua_sandbox import pools
-
- for name in ("list_pools", "list_claims", "gc", "gc_pools", "GcReport", "ManagedPoolInfo"):
- assert hasattr(pools, name)
- assert pools.is_managed_pool_name("cua-auto-abc")
-
-
-def test_marker_only_mode_never_reads_the_vault(clean_env):
- clean_env.setattr(_config, "has_fleet_session", lambda: pytest.fail("vault read"))
- clean_env.setattr(_config, "may_have_fleet_session", lambda: True)
- assert cua_sandbox.fleet_auth_source(read_session=False) == "cua auth login session"
- clean_env.setattr(_config, "may_have_fleet_session", lambda: False)
- assert cua_sandbox.fleet_auth_source(read_session=False) is None
diff --git a/libs/python/cua-sandbox/tests/test_fleet_builder_usage.py b/libs/python/cua-sandbox/tests/test_fleet_builder_usage.py
deleted file mode 100644
index 3715162d4e..0000000000
--- a/libs/python/cua-sandbox/tests/test_fleet_builder_usage.py
+++ /dev/null
@@ -1,292 +0,0 @@
-from __future__ import annotations
-
-import ast
-from pathlib import Path
-
-PACKAGE_ROOT = Path(__file__).parents[1]
-FLEET_MODULES = {"cua_sandbox", "fleet_sdk"}
-BUILDER_ENABLED_RECORDS = {
- "CreatePoolRequest",
- "CreateTemplateRequest",
- "OsGymSandboxTemplateSpec",
- "OsGymSandboxWarmPoolSpec",
- "SandboxService",
- "SandboxTemplateRef",
- "VmTemplate",
-}
-MODULE_ALIAS = object()
-OTHER_BINDING = object()
-
-
-class _BindingScope:
- def __init__(self, parent: _BindingScope | None, kind: str) -> None:
- self.parent = parent
- self.kind = kind
- self.bindings: dict[str, object] = {}
-
- def bind(self, name: str, binding: object) -> None:
- self.bindings[name] = binding
-
- def resolve(self, name: str) -> object | None:
- scope: _BindingScope | None = self
- while scope is not None:
- if name in scope.bindings:
- return scope.bindings[name]
- scope = scope.parent
- return None
-
-
-class _BuilderRecordCallVisitor(ast.NodeVisitor):
- def __init__(self) -> None:
- self.calls: list[tuple[int, str]] = []
- self.scope = _BindingScope(parent=None, kind="module")
-
- def _bind_other(self, name: str) -> None:
- self.scope.bind(name, OTHER_BINDING)
-
- def _bind_target(self, target: ast.expr) -> None:
- if isinstance(target, ast.Name):
- self._bind_other(target.id)
- elif isinstance(target, (ast.List, ast.Tuple)):
- for element in target.elts:
- self._bind_target(element)
- elif isinstance(target, ast.Starred):
- self._bind_target(target.value)
-
- def _visit_arguments(self, arguments: ast.arguments) -> None:
- positional = (*arguments.posonlyargs, *arguments.args)
- for argument in (*positional, *arguments.kwonlyargs):
- if argument.annotation is not None:
- self.visit(argument.annotation)
- if arguments.vararg is not None and arguments.vararg.annotation is not None:
- self.visit(arguments.vararg.annotation)
- if arguments.kwarg is not None and arguments.kwarg.annotation is not None:
- self.visit(arguments.kwarg.annotation)
- for default in (*arguments.defaults, *arguments.kw_defaults):
- if default is not None:
- self.visit(default)
-
- def _bind_arguments(self, arguments: ast.arguments) -> None:
- for argument in (*arguments.posonlyargs, *arguments.args, *arguments.kwonlyargs):
- self._bind_other(argument.arg)
- if arguments.vararg is not None:
- self._bind_other(arguments.vararg.arg)
- if arguments.kwarg is not None:
- self._bind_other(arguments.kwarg.arg)
-
- def _visit_function(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
- for decorator in node.decorator_list:
- self.visit(decorator)
- self._visit_arguments(node.args)
- if node.returns is not None:
- self.visit(node.returns)
- for type_parameter in getattr(node, "type_params", ()):
- self.visit(type_parameter)
-
- outer_scope = self.scope
- self._bind_other(node.name)
- parent_scope = outer_scope.parent if outer_scope.kind == "class" else outer_scope
- self.scope = _BindingScope(parent=parent_scope, kind="function")
- try:
- self._bind_arguments(node.args)
- for statement in node.body:
- self.visit(statement)
- finally:
- self.scope = outer_scope
-
- def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
- for alias in node.names:
- if alias.name == "*":
- continue
- local_name = alias.asname or alias.name
- if (
- node.level == 0
- and node.module in FLEET_MODULES
- and alias.name in BUILDER_ENABLED_RECORDS
- ):
- self.scope.bind(local_name, alias.name)
- else:
- self._bind_other(local_name)
-
- def visit_Import(self, node: ast.Import) -> None:
- for alias in node.names:
- local_name = alias.asname or alias.name.split(".", maxsplit=1)[0]
- binding = MODULE_ALIAS if alias.name in FLEET_MODULES else OTHER_BINDING
- self.scope.bind(local_name, binding)
-
- def visit_Call(self, node: ast.Call) -> None:
- record_name: str | None = None
- if isinstance(node.func, ast.Name):
- binding = self.scope.resolve(node.func.id)
- if isinstance(binding, str):
- record_name = binding
- elif (
- isinstance(node.func, ast.Attribute)
- and isinstance(node.func.value, ast.Name)
- and self.scope.resolve(node.func.value.id) is MODULE_ALIAS
- and node.func.attr in BUILDER_ENABLED_RECORDS
- ):
- record_name = node.func.attr
-
- if record_name is not None:
- self.calls.append((node.lineno, record_name))
- self.generic_visit(node)
-
- def visit_Assign(self, node: ast.Assign) -> None:
- self.visit(node.value)
- for target in node.targets:
- self._bind_target(target)
-
- def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
- self.visit(node.annotation)
- if node.value is not None:
- self.visit(node.value)
- self._bind_target(node.target)
-
- def visit_AugAssign(self, node: ast.AugAssign) -> None:
- self.visit(node.target)
- self.visit(node.value)
- self._bind_target(node.target)
-
- def visit_NamedExpr(self, node: ast.NamedExpr) -> None:
- self.visit(node.value)
- self._bind_target(node.target)
-
- def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
- self._visit_function(node)
-
- def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
- self._visit_function(node)
-
- def visit_ClassDef(self, node: ast.ClassDef) -> None:
- for decorator in node.decorator_list:
- self.visit(decorator)
- for base in node.bases:
- self.visit(base)
- for keyword in node.keywords:
- self.visit(keyword)
- for type_parameter in getattr(node, "type_params", ()):
- self.visit(type_parameter)
-
- outer_scope = self.scope
- self.scope = _BindingScope(parent=outer_scope, kind="class")
- try:
- for statement in node.body:
- self.visit(statement)
- finally:
- self.scope = outer_scope
- self._bind_other(node.name)
-
- def visit_Lambda(self, node: ast.Lambda) -> None:
- self._visit_arguments(node.args)
- outer_scope = self.scope
- parent_scope = outer_scope.parent if outer_scope.kind == "class" else outer_scope
- self.scope = _BindingScope(parent=parent_scope, kind="function")
- try:
- self._bind_arguments(node.args)
- self.visit(node.body)
- finally:
- self.scope = outer_scope
-
-
-def _find_builder_record_calls(
- source: str, *, filename: str = "<unknown>"
-) -> list[tuple[int, str]]:
- visitor = _BuilderRecordCallVisitor()
- visitor.visit(ast.parse(source, filename=filename))
- return visitor.calls
-
-
-def test_finds_direct_builder_record_imports() -> None:
- source = (
- "from fleet_sdk import VmTemplate\n"
- "from cua_sandbox import SandboxService\n"
- "VmTemplate()\n"
- "SandboxService()\n"
- )
-
- assert _find_builder_record_calls(source) == [(3, "VmTemplate"), (4, "SandboxService")]
-
-
-def test_finds_aliased_builder_record_imports() -> None:
- source = (
- "from fleet_sdk import VmTemplate as FleetVm\n"
- "from cua_sandbox import SandboxService as FleetService\n"
- "FleetVm()\n"
- "FleetService()\n"
- )
-
- assert _find_builder_record_calls(source) == [(3, "VmTemplate"), (4, "SandboxService")]
-
-
-def test_finds_builder_record_module_attributes() -> None:
- source = (
- "import fleet_sdk as fleet\n"
- "import cua_sandbox as cua\n"
- "fleet.VmTemplate()\n"
- "cua.SandboxService()\n"
- )
-
- assert _find_builder_record_calls(source) == [(3, "VmTemplate"), (4, "SandboxService")]
-
-
-def test_ignores_unrelated_local_builder_record_name() -> None:
- source = "class VmTemplate:\n pass\n\nVmTemplate()\n"
-
- assert _find_builder_record_calls(source) == []
-
-
-def test_ignores_direct_import_after_local_shadowing() -> None:
- sources = (
- "from fleet_sdk import VmTemplate\nclass VmTemplate:\n pass\nVmTemplate()\n",
- "from fleet_sdk import VmTemplate\ndef VmTemplate():\n pass\nVmTemplate()\n",
- "from fleet_sdk import VmTemplate\nVmTemplate = object()\nVmTemplate()\n",
- )
-
- for source in sources:
- assert _find_builder_record_calls(source) == []
-
-
-def test_function_imports_do_not_leak_to_sibling_or_outer_scopes() -> None:
- source = (
- "def fleet_user():\n"
- " from fleet_sdk import VmTemplate\n"
- " VmTemplate()\n"
- "\n"
- "def sibling():\n"
- " class VmTemplate:\n"
- " pass\n"
- " VmTemplate()\n"
- "\n"
- "def VmTemplate():\n"
- " pass\n"
- "\n"
- "VmTemplate()\n"
- )
-
- assert _find_builder_record_calls(source) == [(3, "VmTemplate")]
-
-
-def test_ignores_module_attribute_after_alias_rebinding() -> None:
- source = "import fleet_sdk as fleet\nfleet = object()\nfleet.VmTemplate()\n"
-
- assert _find_builder_record_calls(source) == []
-
-
-def test_nested_scope_resolves_unshadowed_outer_fleet_binding() -> None:
- source = "from fleet_sdk import VmTemplate\ndef build():\n VmTemplate()\n"
-
- assert _find_builder_record_calls(source) == [(3, "VmTemplate")]
-
-
-def test_builder_enabled_fleet_records_use_generated_builders() -> None:
- violations: list[str] = []
- source_roots = (PACKAGE_ROOT / "cua_sandbox", PACKAGE_ROOT / "tests")
-
- for source_root in source_roots:
- for path in source_root.rglob("*.py"):
- calls = _find_builder_record_calls(path.read_text(), filename=str(path))
- relative_path = path.relative_to(PACKAGE_ROOT)
- violations.extend(f"{relative_path}:{line}: {name}" for line, name in calls)
-
- assert violations == [], "Direct Fleet record constructors remain:\n" + "\n".join(violations)
diff --git a/libs/python/cua-sandbox/tests/test_fleet_cloud_client.py b/libs/python/cua-sandbox/tests/test_fleet_cloud_client.py
deleted file mode 100644
index 26ab0b36b9..0000000000
--- a/libs/python/cua-sandbox/tests/test_fleet_cloud_client.py
+++ /dev/null
@@ -1,391 +0,0 @@
-import logging
-from types import SimpleNamespace
-
-import pytest
-from cua_sandbox.transport.fleet_cloud import (
- _FleetClient,
- _GitHubActionsAccessTokenProvider,
-)
-from fleet_sdk import (
- AccessTokenProviderError,
- CyclopsClient,
- CyclopsTokenProviderConfiguration,
- HttpClient,
- HttpResponse,
-)
-
-
-async def test_wait_pool_returns_once_a_replica_is_ready():
- client = _FleetClient.__new__(_FleetClient)
- warming = SimpleNamespace(
- metadata=SimpleNamespace(name="demo", namespace="demo"),
- status=SimpleNamespace(replicas=1, ready_replicas=0, selector=None),
- )
- ready = SimpleNamespace(
- metadata=SimpleNamespace(name="demo", namespace="demo"),
- status=SimpleNamespace(replicas=1, ready_replicas=1, selector=None),
- )
- listings = iter([[warming], [ready]])
-
- class SDK:
- async def list_pools(self, namespace):
- assert namespace == "demo"
- return next(listings)
-
- client._client = SDK()
- assert await client.wait_pool(warming, poll_interval=0) is ready
-
-
-async def test_template_calls_delegate_to_generated_client():
- client = _FleetClient.__new__(_FleetClient)
- calls = []
-
- class SDK:
- async def reconcile_template(self, request):
- calls.append(("reconcile", request))
- return "template"
-
- async def create_template(self, request):
- calls.append(("create", request))
- return "template"
-
- async def get_template(self, namespace, name):
- calls.append(("get", namespace, name))
- return "template"
-
- async def delete_template(self, template):
- calls.append(("delete", template))
-
- client._client = SDK()
- assert await client.reconcile_template("request") == "template"
- assert await client.create_template("request") == "template"
- assert await client.get_template("demo", "workspace") == "template"
- assert await client.delete_template("template") is None
- assert calls == [
- ("reconcile", "request"),
- ("create", "request"),
- ("get", "demo", "workspace"),
- ("delete", "template"),
- ]
-
-
-async def test_namespace_calls_delegate_to_generated_client():
- client = _FleetClient.__new__(_FleetClient)
- calls = []
-
- class SDK:
- async def get_namespace(self, name):
- calls.append(("get", name))
- return "namespace"
-
- async def create_namespace(self, name):
- calls.append(("create", name))
- return "namespace"
-
- async def delete_namespace(self, name):
- calls.append(("delete", name))
-
- client._client = SDK()
- assert await client.get_namespace("demo") == "namespace"
- assert await client.create_namespace("demo") == "namespace"
- assert await client.delete_namespace("demo") is None
- assert calls == [("get", "demo"), ("create", "demo"), ("delete", "demo")]
-
-
-async def test_list_pools_does_not_discover_namespaces():
- client = _FleetClient.__new__(_FleetClient)
-
- class Http:
- async def execute(self, request):
- pytest.fail("Fleet listing must not discover namespaces")
-
- class SDK:
- async def list_pools(self, namespace):
- pytest.fail("Fleet listing requires an explicit namespace")
-
- client._base_url = "https://fleet.example"
- client._http_client = Http()
- client._client = SDK()
-
- with pytest.raises(NotImplementedError, match="exact sandbox name"):
- await client.list_pools()
-
-
-async def test_service_request_delegates_to_generated_client():
- client = _FleetClient.__new__(_FleetClient)
- calls = []
-
- class SDK:
- async def service_request(self, *args):
- calls.append(args)
- return "response"
-
- client._client = SDK()
- assert await client.service_request("sandbox", "server", "/status", "request") == "response"
- assert calls == [("sandbox", "server", "/status", "request")]
-
-
-async def test_wait_service_ready_sets_a_native_request_timeout():
- client = _FleetClient.__new__(_FleetClient)
- calls = []
-
- async def service_request(sandbox, service, path, request):
- calls.append((sandbox, service, path, request))
- return HttpResponse(status=200, headers=[], body=b"")
-
- client.service_request = service_request
-
- await client.wait_service_ready("sandbox", "server")
-
- _, _, _, request = calls[0]
- assert request.timeout_secs == 30
-
-
-async def test_github_actions_token_provider_refreshes_and_caches_token():
- calls = []
-
- async def request(url, headers):
- calls.append((url, headers))
- return 200, {"value": "refreshed-token"}
-
- provider = _GitHubActionsAccessTokenProvider(
- "initial-token",
- environ={
- "ACTIONS_ID_TOKEN_REQUEST_URL": "https://github.example/oidc?existing=value",
- "ACTIONS_ID_TOKEN_REQUEST_TOKEN": "request-token",
- },
- request=request,
- )
-
- assert await provider.get_access_token(False) == "initial-token"
- assert calls == []
- assert await provider.get_access_token(True) == "refreshed-token"
- assert await provider.get_access_token(False) == "refreshed-token"
- assert calls == [
- (
- "https://github.example/oidc?existing=value&audience=fleets",
- {
- "Accept": "application/json",
- "Authorization": "bearer request-token",
- },
- )
- ]
-
-
-async def test_github_actions_token_provider_maps_refresh_failures():
- async def request(url, headers):
- return 403, {"message": "forbidden"}
-
- provider = _GitHubActionsAccessTokenProvider(
- "initial-token",
- environ={
- "ACTIONS_ID_TOKEN_REQUEST_URL": "https://github.example/oidc",
- "ACTIONS_ID_TOKEN_REQUEST_TOKEN": "request-token",
- },
- request=request,
- )
-
- with pytest.raises(AccessTokenProviderError.Failed, match="HTTP 403"):
- await provider.get_access_token(True)
-
-
-async def test_generated_sdk_retries_unauthorized_request_with_refreshed_github_token():
- refresh_calls = 0
-
- async def refresh_token(url, headers):
- nonlocal refresh_calls
- refresh_calls += 1
- return 200, {"value": "refreshed-token"}
-
- class ScriptedHttpClient(HttpClient):
- def __init__(self):
- self.authorization = []
-
- async def execute(self, request):
- authorization = next(
- header.value for header in request.headers if header.name.lower() == "authorization"
- )
- self.authorization.append(authorization)
- if len(self.authorization) == 1:
- return HttpResponse(status=401, headers=[], body=b'{"error":"expired"}')
- return HttpResponse(status=200, headers=[], body=b'{"items":[]}')
-
- provider = _GitHubActionsAccessTokenProvider(
- "initial-token",
- environ={
- "ACTIONS_ID_TOKEN_REQUEST_URL": "https://github.example/oidc",
- "ACTIONS_ID_TOKEN_REQUEST_TOKEN": "request-token",
- },
- request=refresh_token,
- )
- http_client = ScriptedHttpClient()
- client = CyclopsClient.connect_with_access_token_provider(
- CyclopsTokenProviderConfiguration(
- base_url="https://fleet.example",
- pool_poll_interval_ms=1,
- pool_poll_limit=1,
- claim_poll_interval_ms=1,
- claim_poll_limit=1,
- ),
- provider,
- http_client,
- )
-
- assert await client.list_pools("cua-cli-wif-smoke") == []
- assert http_client.authorization == ["Bearer initial-token", "Bearer refreshed-token"]
- assert refresh_calls == 1
-
-
-async def test_fleet_client_uses_static_workload_token_and_closes_http_client(monkeypatch, caplog):
- monkeypatch.delenv("ACTIONS_ID_TOKEN_REQUEST_URL", raising=False)
- monkeypatch.delenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", raising=False)
- from cua_sandbox.transport import fleet_cloud
- from fleet_sdk import AccessTokenProvider, CyclopsTokenProviderConfiguration
-
- token = "fleet-workload-token"
- calls = {}
- caplog.set_level(logging.DEBUG)
-
- class HttpClient:
- close_calls = 0
-
- async def aclose(self):
- self.close_calls += 1
-
- class Client:
- @staticmethod
- def connect_with_access_token_provider(configuration, provider, http_client):
- calls.update(
- configuration=configuration,
- provider=provider,
- http_client=http_client,
- )
- return "token-client"
-
- @staticmethod
- def connect(*args):
- pytest.fail("client-credential connection must not be used with a Fleet token")
-
- monkeypatch.setattr(fleet_cloud, "get_fleet_token", lambda: token)
- monkeypatch.setattr(fleet_cloud, "get_fleet_base_url", lambda: "https://fleet.example/")
- monkeypatch.setattr(fleet_cloud, "CyclopsHttpClient", HttpClient)
- monkeypatch.setattr(fleet_cloud, "CyclopsClient", Client)
-
- client = _FleetClient()
-
- assert client._client == "token-client"
- assert isinstance(calls["configuration"], CyclopsTokenProviderConfiguration)
- assert vars(calls["configuration"]) == {
- "base_url": "https://fleet.example",
- "pool_poll_interval_ms": 2000,
- "pool_poll_limit": 300,
- "claim_poll_interval_ms": 2000,
- "claim_poll_limit": 300,
- }
- assert isinstance(calls["provider"], AccessTokenProvider)
- assert await calls["provider"].get_access_token(False) == token
- assert await calls["provider"].get_access_token(True) == token
- assert token not in caplog.text
-
- await client.close()
- assert calls["http_client"].close_calls == 1
-
-
-def test_fleet_client_uses_refreshable_provider_in_github_actions(monkeypatch):
- from cua_sandbox.transport import fleet_cloud
-
- calls = {}
-
- class HttpClient:
- async def aclose(self):
- pass
-
- class Client:
- @staticmethod
- def connect_with_access_token_provider(configuration, provider, http_client):
- calls["provider"] = provider
- return "token-client"
-
- monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "https://github.example/oidc")
- monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "request-token")
- monkeypatch.setattr(fleet_cloud, "get_fleet_token", lambda: "initial-token")
- monkeypatch.setattr(fleet_cloud, "get_fleet_base_url", lambda: "https://fleet.example/")
- monkeypatch.setattr(fleet_cloud, "CyclopsHttpClient", HttpClient)
- monkeypatch.setattr(fleet_cloud, "CyclopsClient", Client)
-
- client = _FleetClient()
-
- assert client._client == "token-client"
- assert isinstance(calls["provider"], _GitHubActionsAccessTokenProvider)
-
-
-def test_fleet_client_falls_back_to_client_credentials_without_workload_token(monkeypatch):
- from cua_sandbox.transport import fleet_cloud
- from fleet_sdk import CyclopsConfiguration
-
- calls = {}
-
- class HttpClient:
- async def aclose(self):
- pass
-
- class Client:
- @staticmethod
- def connect(configuration, http_client):
- calls.update(configuration=configuration, http_client=http_client)
- return "credential-client"
-
- @staticmethod
- def connect_with_access_token_provider(*args):
- pytest.fail("token-provider connection requires a Fleet token")
-
- monkeypatch.setattr(fleet_cloud, "get_fleet_token", lambda: None)
- monkeypatch.setattr(fleet_cloud, "get_client_id", lambda: "client-id")
- monkeypatch.setattr(fleet_cloud, "get_client_secret", lambda: "client-secret")
- monkeypatch.setattr(fleet_cloud, "get_fleet_base_url", lambda: "https://fleet.example/")
- monkeypatch.setattr(fleet_cloud, "get_token_url", lambda: "https://auth.example/token")
- monkeypatch.setattr(fleet_cloud, "CyclopsHttpClient", HttpClient)
- monkeypatch.setattr(fleet_cloud, "CyclopsClient", Client)
-
- client = _FleetClient()
-
- assert client._client == "credential-client"
- assert isinstance(calls["configuration"], CyclopsConfiguration)
- assert vars(calls["configuration"]) == {
- "base_url": "https://fleet.example",
- "token_url": "https://auth.example/token",
- "credentials": calls["configuration"].credentials,
- "pool_poll_interval_ms": 2000,
- "pool_poll_limit": 300,
- "claim_poll_interval_ms": 2000,
- "claim_poll_limit": 300,
- }
-
-
-def test_fleet_client_requires_credentials_when_no_workload_token_exists(monkeypatch):
- from cua_sandbox.transport import fleet_cloud
-
- monkeypatch.setattr(fleet_cloud, "get_fleet_token", lambda: None)
- monkeypatch.setattr(fleet_cloud, "get_client_id", lambda: None)
- monkeypatch.setattr(fleet_cloud, "get_client_secret", lambda: None)
- monkeypatch.setattr(
- fleet_cloud,
- "CyclopsHttpClient",
- lambda: pytest.fail("missing credentials must fail before creating an HTTP client"),
- )
-
- with pytest.raises(
- ValueError,
- match="Fleet credentials missing: run `cua auth login` or set CUA_CLIENT_ID/CUA_CLIENT_SECRET",
- ):
- _FleetClient()
diff --git a/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py b/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py
deleted file mode 100644
index 8b85e81b90..0000000000
--- a/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py
+++ /dev/null
@@ -1,1052 +0,0 @@
-from types import SimpleNamespace
-
-import pytest
-from cua_sandbox import Image
-from cua_sandbox import Sandbox as CuaSandbox
-from cua_sandbox.transport import fleet_cloud
-from cua_sandbox.transport.fleet_cloud import FleetCloudTransport
-from fleet_sdk import (
- Firmware,
- OsGymSandboxWarmPoolSpecBuilder,
- OsGymSandboxWarmPoolStatus,
- Pool,
- ResourceMetadata,
- Sandbox,
- SandboxTemplateRefBuilder,
- WarmPoolAutoscaling,
-)
-
-
-def _pool(name="demo"):
- return SimpleNamespace(
- metadata=SimpleNamespace(name=name, namespace=name),
- spec=SimpleNamespace(sandbox_template_ref=SimpleNamespace(name=name)),
- )
-
-
-def _bound():
- return Sandbox(namespace="demo", claim="demo-claim", name="sandbox", services=["server"])
-
-
-def test_generated_pool_converts_to_sandbox_info():
- pool = Pool(
- api_version="osgym.cua.ai/v1alpha1",
- kind="OSGymSandboxWarmPool",
- metadata=ResourceMetadata(
- namespace="demo",
- name="demo",
- labels=None,
- creation_timestamp="2026-08-09T00:00:00Z",
- ),
- spec=(
- OsGymSandboxWarmPoolSpecBuilder()
- .replicas(1)
- .sandbox_template_ref(SandboxTemplateRefBuilder().name("demo").build())
- .build()
- ),
- status=OsGymSandboxWarmPoolStatus(replicas=1, ready_replicas=1, selector=None),
- )
-
- info = CuaSandbox._fleet_sandbox_info(pool)
-
- assert info.name == "demo"
- assert info.status == "running"
- assert info.source == "fleet"
- assert info.created_at == "2026-08-09T00:00:00Z"
-
-
-def test_registry_image_becomes_typed_template_request():
- request = FleetCloudTransport(
- image=Image.from_registry("registry.example/workspace@sha256:abc").expose(3000),
- name="demo",
- cpu=4,
- memory_mb=8192,
- )._template_request()
-
- assert (request.namespace, request.name) == ("demo", "demo")
- vm_template = request.spec.vm_template
- assert vm_template.container_disk_image == "registry.example/workspace@sha256:abc"
- assert vm_template.cpu_cores == 4
- assert vm_template.memory == "8192Mi"
- # Daemon-agnostic default: cua-spacesd is published as `env` (3211).
- assert [(service.name, service.target_port) for service in vm_template.services] == [
- ("env", 3211),
- ("port-3000", 3000),
- ]
-
-
-def test_default_linux_image_becomes_typed_template_request():
- request = FleetCloudTransport(image=Image.linux(), name="demo")._template_request()
-
- # Unresolved (hermetic tests read no registry): the canonical ref as given.
- assert request.spec.vm_template.container_disk_image == "ghcr.io/trycua/linux:24.04"
-
-
-def test_default_windows_image_becomes_typed_template_request():
- request = FleetCloudTransport(image=Image.windows(), name="demo")._template_request()
-
- assert request.spec.vm_template.container_disk_image == "ghcr.io/trycua/windows:2022"
-
-
-def test_kubevirt_templates_run_the_resolved_disk_variant(monkeypatch):
- """With a readable registry the template runs the pinned `-disk` variant."""
- from types import SimpleNamespace
-
- from cua_sandbox._sdk import native
-
- n = native()
- calls = []
-
- def resolve_image(reference, backend, arch):
- calls.append((reference, backend, arch))
- return SimpleNamespace(pinned_ref="ghcr.io/trycua/windows@sha256:" + "a" * 64)
-
- monkeypatch.setattr(n, "resolve_image", resolve_image)
- request = FleetCloudTransport(image=Image.windows(), name="demo")._template_request()
- assert request.spec.vm_template.container_disk_image == (
- "ghcr.io/trycua/windows@sha256:" + "a" * 64
- )
- assert calls == [("ghcr.io/trycua/windows:2022", "vm", "amd64")]
-
-
-def test_windows_image_boots_uefi():
- request = FleetCloudTransport(image=Image.windows(), name="demo")._template_request()
-
- assert request.spec.vm_template.firmware == Firmware.EFI
-
-
-def test_linux_image_leaves_firmware_at_the_schema_default():
- request = FleetCloudTransport(image=Image.linux(), name="demo")._template_request()
-
- assert request.spec.vm_template.firmware is None
-
-
-def test_pool_request_uses_the_single_sandbox_name_and_requested_replicas():
- request = FleetCloudTransport(
- image=Image.from_registry("registry.example/workspace@sha256:abc"),
- name="demo",
- replicas=3,
- )._pool_request()
-
- assert request.namespace == "demo"
- assert request.spec.replicas == 3
- assert request.spec.sandbox_template_ref.name == "demo"
- assert request.spec.autoscaling is None
-
-
-def test_pool_request_carries_the_requested_autoscaling():
- autoscaling = WarmPoolAutoscaling(min_pool_size=0, initial_pool_size=2, max_pool_size=10)
-
- request = FleetCloudTransport(
- image=Image.from_registry("registry.example/workspace@sha256:abc"),
- name="demo",
- autoscaling=autoscaling,
- )._pool_request()
-
- assert request.spec.autoscaling == autoscaling
-
-
-def test_pool_request_accepts_partial_autoscaling_bounds():
- autoscaling = WarmPoolAutoscaling(min_pool_size=None, initial_pool_size=None, max_pool_size=25)
-
- request = FleetCloudTransport(
- image=Image.from_registry("registry.example/workspace@sha256:abc"),
- name="demo",
- autoscaling=autoscaling,
- )._pool_request()
-
- assert request.spec.autoscaling == autoscaling
-
-
-def test_pool_request_carries_the_requested_creation_ttl():
- request = FleetCloudTransport(
- image=Image.from_registry("registry.example/workspace@sha256:abc"),
- name="demo",
- ttl_seconds_after_created=3600,
- )._pool_request()
-
- assert request.spec.ttl_seconds_after_created == 3600
-
-
-def test_pool_request_leaves_creation_ttl_unset_by_default():
- request = FleetCloudTransport(
- image=Image.from_registry("registry.example/workspace@sha256:abc"),
- name="demo",
- )._pool_request()
-
- assert request.spec.ttl_seconds_after_created is None
-
-
[email protected]("ttl", [-1, True, "3600", 1.5, 2**32])
-def test_transport_rejects_invalid_creation_ttl(ttl):
- with pytest.raises(ValueError, match="ttl_seconds_after_created"):
- FleetCloudTransport(
- image=Image.from_registry("registry.example/workspace@sha256:abc"),
- name="demo",
- ttl_seconds_after_created=ttl,
- )
-
-
-def test_transport_rejects_untyped_autoscaling():
- with pytest.raises(TypeError, match="WarmPoolAutoscaling"):
- FleetCloudTransport(
- image=Image.from_registry("registry.example/workspace@sha256:abc"),
- name="demo",
- autoscaling={"min_pool_size": 0, "max_pool_size": 10},
- )
-
-
- "autoscaling",
- [
- WarmPoolAutoscaling(min_pool_size=-1, initial_pool_size=None, max_pool_size=None),
- WarmPoolAutoscaling(min_pool_size=None, initial_pool_size=-1, max_pool_size=None),
- WarmPoolAutoscaling(min_pool_size=None, initial_pool_size=None, max_pool_size=0),
- WarmPoolAutoscaling(min_pool_size=True, initial_pool_size=None, max_pool_size=None),
- WarmPoolAutoscaling(min_pool_size="2", initial_pool_size=None, max_pool_size=None),
- WarmPoolAutoscaling(min_pool_size=5, initial_pool_size=None, max_pool_size=2),
- ],
-)
-def test_transport_rejects_invalid_autoscaling_bounds(autoscaling):
- with pytest.raises(ValueError, match="autoscaling"):
- FleetCloudTransport(
- image=Image.from_registry("registry.example/workspace@sha256:abc"),
- name="demo",
- autoscaling=autoscaling,
- )
-
-
[email protected]("pool_length", [57, 58, 63])
-def test_deterministic_claim_name_obeys_dns_label_boundary(pool_length):
- pool_name = "a" * pool_length
-
- claim_name = fleet_cloud._claim_name(pool_name)
-
- assert len(claim_name) <= 63
- assert claim_name == claim_name.lower()
- assert claim_name[0].isalnum()
- assert claim_name[-1].isalnum()
- assert all(
- character.islower() or character.isdigit() or character == "-" for character in claim_name
- )
- if pool_length == 57:
- assert claim_name == f"{pool_name}-claim"
- else:
- prefix, hash_suffix = claim_name.rsplit("-", 1)
- assert pool_name.startswith(prefix)
- assert len(hash_suffix) == 16
- assert all(character in "0123456789abcdef" for character in hash_suffix)
-
-
-def test_deterministic_claim_name_distinguishes_long_pool_names():
- first = fleet_cloud._claim_name(f"{'a' * 62}b")
- second = fleet_cloud._claim_name(f"{'a' * 62}c")
-
- assert first != second
- assert first == fleet_cloud._claim_name(f"{'a' * 62}b")
-
-
-async def test_fleet_client_lookup_uses_bounded_deterministic_claim_name():
- pool_name = "a" * 63
- pool = _pool(pool_name)
- claim = SimpleNamespace(metadata=SimpleNamespace(name=fleet_cloud._claim_name(pool_name)))
- client = fleet_cloud._FleetClient.__new__(fleet_cloud._FleetClient)
-
- class SDK:
- async def list_claims(self, namespace):
- assert namespace == pool_name
- return [claim]
-
- client._client = SDK()
-
- assert await client.get_claim(pool) is claim
-
-
- "image",
- [
- Image.linux("debian", "12"),
- # Client Windows has no pinned containerDisk, so the cloud cannot serve it.
- Image.windows("11"),
- Image.windows("10"),
- ],
-)
-def test_rejects_unsupported_images(image):
- with pytest.raises(NotImplementedError):
- FleetCloudTransport._validate_image(image)
-
-
-async def test_image_connect_reconciles_named_resources_without_namespace_calls(monkeypatch):
- calls = []
- pool = _pool()
- bound = _bound()
-
- class Client:
- async def reconcile_pool(self, request):
- calls.append(("reconcile_pool", request))
- return pool
-
- async def reconcile_template(self, request):
- calls.append(("reconcile_template", request))
- return "template"
-
- async def wait_pool(self, reconciled_pool):
- calls.append(("wait_pool", reconciled_pool))
- return reconciled_pool
-
- async def create_claim(self, request):
- calls.append(("create_claim", request))
- return "claim"
-
- async def wait_claim(self, claim):
- calls.append(("wait_claim", claim))
- return bound
-
- async def wait_service_ready(self, sandbox, service, time_to_start):
- calls.append(("wait_service_ready", sandbox, service, time_to_start))
-
- async def get_namespace(self, name):
- raise AssertionError("Fleet sandbox transport must not get namespaces")
-
- async def create_namespace(self, name):
- raise AssertionError("Fleet sandbox transport must not create namespaces")
-
- async def create_pool(self, request):
- raise AssertionError("Fleet sandbox transport must reconcile pools")
-
- async def create_template(self, request):
- raise AssertionError("Fleet sandbox transport must reconcile templates")
-
- client = Client()
- monkeypatch.setattr(fleet_cloud, "_FleetClient", lambda: client)
-
- transport = FleetCloudTransport(image=Image.from_registry("example:latest"), name="demo")
- await transport.connect()
-
- assert [call[0] for call in calls] == [
- "reconcile_pool",
- "reconcile_template",
- "wait_pool",
- "create_claim",
- "wait_claim",
- "wait_service_ready",
- ]
- pool_request = calls[0][1]
- template_request = calls[1][1]
- claim_request = calls[3][1]
- assert pool_request.namespace == "demo"
- assert pool_request.spec.sandbox_template_ref.name == "demo"
- assert pool_request.spec.replicas == 1
- assert (template_request.namespace, template_request.name) == ("demo", "demo")
- assert claim_request.name == "demo-claim"
- assert calls[-1] == ("wait_service_ready", bound, "env", 600.0)
-
-
-async def test_created_claim_is_resolved_by_later_connect_and_delete(monkeypatch):
- calls = []
- pool_name = "a" * 63
- expected_claim_name = fleet_cloud._claim_name(pool_name)
- pool = _pool(pool_name)
- bound = _bound()
- created_claim = None
-
- class Client:
- async def reconcile_pool(self, request):
- return pool
-
- async def reconcile_template(self, request):
- return "template"
-
- async def wait_pool(self, reconciled_pool):
- return reconciled_pool
-
- async def create_claim(self, request):
- nonlocal created_claim
- calls.append(("create_claim", request.name))
- created_claim = SimpleNamespace(metadata=SimpleNamespace(name=request.name))
- return created_claim
-
- async def get_pool(self, name):
- calls.append(("get_pool", name))
- return pool
-
- async def get_claim(self, existing_pool):
- calls.append(("get_claim", fleet_cloud._claim_name(existing_pool.metadata.name)))
- assert created_claim is not None
- assert created_claim.metadata.name == fleet_cloud._claim_name(
- existing_pool.metadata.name
- )
- return created_claim
-
- async def wait_claim(self, claim):
- assert claim is created_claim
- return bound
-
- async def wait_service_ready(self, sandbox, service, time_to_start):
- return None
-
- async def delete_claim(self, claim):
- calls.append(("delete_claim", claim.metadata.name))
-
- async def close(self):
- calls.append(("close",))
-
- client = Client()
- monkeypatch.setattr(fleet_cloud, "_FleetClient", lambda: client)
-
- await FleetCloudTransport(image=Image.from_registry("example:latest"), name=pool_name).connect()
- await FleetCloudTransport(image=None, name=pool_name).connect()
- await FleetCloudTransport.delete_sandbox(pool_name)
-
- assert calls == [
- ("create_claim", expected_claim_name),
- ("get_pool", pool_name),
- ("get_claim", expected_claim_name),
- ("get_pool", pool_name),
- ("get_claim", expected_claim_name),
- ("delete_claim", expected_claim_name),
- ("close",),
- ]
-
-
[email protected]("failure_stage", ["reconcile_template", "wait_pool"])
-async def test_retry_reruns_full_image_reconciliation_order(monkeypatch, failure_stage):
- calls = []
- pool = _pool()
- bound = _bound()
- failed_once = False
-
- class Client:
- async def reconcile_pool(self, request):
- calls.append("reconcile_pool")
- return pool
-
- async def reconcile_template(self, request):
- nonlocal failed_once
- calls.append("reconcile_template")
- if failure_stage == "reconcile_template" and not failed_once:
- failed_once = True
- raise RuntimeError("reconcile_template failed")
- return "template"
-
- async def wait_pool(self, reconciled_pool):
- nonlocal failed_once
- calls.append("wait_pool")
- if failure_stage == "wait_pool" and not failed_once:
- failed_once = True
- raise RuntimeError("wait_pool failed")
- return reconciled_pool
-
- async def create_claim(self, request):
- calls.append("create_claim")
- assert request.name == "demo-claim"
- return "claim"
-
- async def wait_claim(self, claim):
- calls.append("wait_claim")
- return bound
-
- async def wait_service_ready(self, sandbox, service, time_to_start):
- calls.append("service_ready")
-
- client = Client()
- monkeypatch.setattr(fleet_cloud, "_FleetClient", lambda: client)
- transport = FleetCloudTransport(image=Image.from_registry("example:latest"), name="demo")
-
- with pytest.raises(RuntimeError, match=f"{failure_stage} failed"):
- await transport.connect()
-
- assert transport._pool is None
- assert transport._template is None
- await transport.connect()
-
- first_attempt = ["reconcile_pool", "reconcile_template"]
- if failure_stage == "wait_pool":
- first_attempt.append("wait_pool")
- assert calls == first_attempt + [
- "reconcile_pool",
- "reconcile_template",
- "wait_pool",
- "create_claim",
- "wait_claim",
- "service_ready",
- ]
-
-
-async def test_ambiguous_claim_creation_recovers_deterministic_claim(monkeypatch):
- calls = []
- pool = _pool()
- bound = _bound()
- created_claim = SimpleNamespace(metadata=SimpleNamespace(name="demo-claim"))
-
- class Client:
- async def reconcile_pool(self, request):
- return pool
-
- async def reconcile_template(self, request):
- return "template"
-
- async def wait_pool(self, reconciled_pool):
- return reconciled_pool
-
- async def create_claim(self, request):
- calls.append(("create_claim", request.name))
- raise RuntimeError("response lost after claim creation")
-
- async def get_claim(self, existing_pool):
- calls.append(("get_claim", existing_pool.metadata.name))
- return created_claim
-
- async def wait_claim(self, claim):
- calls.append(("wait_claim", claim.metadata.name))
- return bound
-
- async def wait_service_ready(self, sandbox, service, time_to_start):
- calls.append(("wait_service_ready", sandbox, service, time_to_start))
-
- monkeypatch.setattr(fleet_cloud, "_FleetClient", Client)
-
- transport = FleetCloudTransport(image=Image.from_registry("example:latest"), name="demo")
- await transport.connect()
-
- assert transport._claim is created_claim
- assert calls == [
- ("create_claim", "demo-claim"),
- ("get_claim", "demo"),
- ("wait_claim", "demo-claim"),
- ("wait_service_ready", bound, "env", 600.0),
- ]
-
-
- "failure_stage",
- [
- "reconcile_pool",
- "reconcile_template",
- "wait_pool",
- "create_claim",
- "wait_claim",
- "service_ready",
- ],
-)
-async def test_connect_failure_releases_only_created_claim(monkeypatch, failure_stage):
- calls = []
- pool = _pool()
- bound = _bound()
-
- class Client:
- async def reconcile_pool(self, request):
- calls.append("reconcile_pool")
- if failure_stage == "reconcile_pool":
- raise RuntimeError("reconcile_pool failed")
- return pool
-
- async def reconcile_template(self, request):
- calls.append("reconcile_template")
- if failure_stage == "reconcile_template":
- raise RuntimeError("reconcile_template failed")
- return "template"
-
- async def wait_pool(self, reconciled_pool):
- calls.append("wait_pool")
- if failure_stage == "wait_pool":
- raise RuntimeError("wait_pool failed")
- return reconciled_pool
-
- async def create_claim(self, request):
- calls.append("create_claim")
- if failure_stage == "create_claim":
- raise RuntimeError("create_claim failed")
- return "claim"
-
- async def wait_claim(self, claim):
- calls.append("wait_claim")
- if failure_stage == "wait_claim":
- raise RuntimeError("wait_claim failed")
- return bound
-
- async def wait_service_ready(self, sandbox, service, time_to_start):
- calls.append("service_ready")
- if failure_stage == "service_ready":
- raise RuntimeError("service_ready failed")
-
- async def delete_claim(self, claim):
- calls.append("delete_claim")
-
- async def delete_pool(self, reconciled_pool):
- calls.append("delete_pool")
-
- async def delete_template(self, template):
- calls.append("delete_template")
-
- async def delete_namespace(self, name):
- calls.append("delete_namespace")
-
- client = Client()
- monkeypatch.setattr(fleet_cloud, "_FleetClient", lambda: client)
- transport = FleetCloudTransport(image=Image.from_registry("example:latest"), name="demo")
-
- with pytest.raises(RuntimeError, match=f"{failure_stage} failed"):
- await transport.connect()
-
- claim_was_created = failure_stage in {"wait_claim", "service_ready"}
- assert ("delete_claim" in calls) is claim_was_created
- assert "delete_pool" not in calls
- assert "delete_template" not in calls
- assert "delete_namespace" not in calls
- assert transport._sdk is client
- assert transport._pool is None
- assert transport._template is None
- assert transport._claim is None
- assert not transport._provisioned
-
-
-async def test_connect_failure_preserves_claim_when_claim_cleanup_fails(monkeypatch):
- pool = _pool()
- calls = []
-
- class Client:
- async def reconcile_pool(self, request):
- return pool
-
- async def reconcile_template(self, request):
- return "template"
-
- async def wait_pool(self, reconciled_pool):
- return reconciled_pool
-
- async def create_claim(self, request):
- return "claim"
-
- async def wait_claim(self, claim):
- raise RuntimeError("claim wait failed")
-
- async def delete_claim(self, claim):
- calls.append(("delete_claim", claim))
- raise RuntimeError("claim delete failed")
-
- async def delete_pool(self, reconciled_pool):
- raise AssertionError("failed claim cleanup must not delete the pool")
-
- async def delete_template(self, template):
- raise AssertionError("failed claim cleanup must not delete the template")
-
- client = Client()
- monkeypatch.setattr(fleet_cloud, "_FleetClient", lambda: client)
- transport = FleetCloudTransport(image=Image.from_registry("example:latest"), name="demo")
-
- with pytest.raises(RuntimeError, match="claim wait failed") as error:
- await transport.connect()
-
- assert isinstance(error.value.__cause__, RuntimeError)
- assert str(error.value.__cause__) == "claim delete failed"
- assert calls == [("delete_claim", "claim")]
- assert transport._claim == "claim"
- assert transport._pool is None
- assert transport._template is None
-
-
-async def test_connect_without_image_uses_existing_pool_and_claim_by_name(monkeypatch):
- calls = []
- pool = _pool()
- bound = _bound()
-
- class Client:
- async def get_pool(self, name):
- calls.append(("get_pool", name))
- return pool
-
- async def get_claim(self, existing_pool):
- calls.append(("get_claim", existing_pool))
- return "claim"
-
- async def wait_claim(self, claim):
- calls.append(("wait_claim", claim))
- return bound
-
- async def wait_service_ready(self, sandbox, service, time_to_start):
- calls.append(("wait_service_ready", sandbox, service, time_to_start))
-
- async def get_namespace(self, name):
- raise AssertionError("existing Fleet sandboxes must not get namespaces")
-
- async def create_namespace(self, name):
- raise AssertionError("existing Fleet sandboxes must not create namespaces")
-
- async def reconcile_pool(self, request):
- raise AssertionError("existing Fleet sandboxes must not reconcile pools")
-
- client = Client()
- monkeypatch.setattr(fleet_cloud, "_FleetClient", lambda: client)
-
- await FleetCloudTransport(image=None, name="demo").connect()
-
- assert calls == [
- ("get_pool", "demo"),
- ("get_claim", pool),
- ("wait_claim", "claim"),
- ("wait_service_ready", bound, "env", 600.0),
- ]
-
-
-async def test_instance_cleanup_deletes_only_claim_and_preserves_infrastructure_state():
- calls = []
-
- class Client:
- async def delete_claim(self, claim):
- calls.append(("delete_claim", claim))
-
- async def delete_pool(self, pool):
- calls.append(("delete_pool", pool))
-
- async def delete_template(self, template):
- calls.append(("delete_template", template))
-
- async def delete_namespace(self, name):
- calls.append(("delete_namespace", name))
-
- transport = FleetCloudTransport(image=Image.from_registry("example:latest"), name="demo")
- transport._sdk = Client()
- transport._claim = "claim"
- transport._pool = "pool"
- transport._template = "template"
- transport._provisioned = True
-
- await transport._cleanup_resources()
-
- assert calls == [("delete_claim", "claim")]
- assert transport._claim is None
- assert transport._pool == "pool"
- assert transport._template == "template"
- assert not transport._provisioned
-
-
-async def test_instance_cleanup_stops_after_claim_failure_and_preserves_state():
- calls = []
-
- class Client:
- async def delete_claim(self, claim):
- calls.append(("delete_claim", claim))
- raise RuntimeError("claim delete failed")
-
- async def delete_pool(self, pool):
- raise AssertionError("claim cleanup failure must not delete the pool")
-
- async def delete_template(self, template):
- raise AssertionError("claim cleanup failure must not delete the template")
-
- transport = FleetCloudTransport(image=Image.from_registry("example:latest"), name="demo")
- transport._sdk = Client()
- transport._claim = "claim"
- transport._pool = "pool"
- transport._template = "template"
- transport._provisioned = True
-
- with pytest.raises(RuntimeError, match="claim delete failed"):
- await transport._cleanup_resources()
-
- assert calls == [("delete_claim", "claim")]
- assert transport._claim == "claim"
- assert transport._pool == "pool"
- assert transport._template == "template"
- assert transport._provisioned
-
-
-async def test_delete_sandbox_resolves_and_deletes_only_deterministic_claim(monkeypatch):
- calls = []
- pool = _pool("demo")
-
- class Client:
- async def get_pool(self, name):
- calls.append(("get_pool", name))
- return pool
-
- async def get_claim(self, existing_pool):
- calls.append(("get_claim", existing_pool))
- return "demo-claim"
-
- async def delete_claim(self, claim):
- calls.append(("delete_claim", claim))
-
- async def delete_pool(self, existing_pool):
- calls.append(("delete_pool", existing_pool))
-
- async def delete_template(self, template):
- calls.append(("delete_template", template))
-
- async def delete_namespace(self, name):
- calls.append(("delete_namespace", name))
-
- async def close(self):
- calls.append(("close",))
-
- monkeypatch.setattr(fleet_cloud, "_FleetClient", Client)
-
- await FleetCloudTransport.delete_sandbox("demo")
-
- assert calls == [
- ("get_pool", "demo"),
- ("get_claim", pool),
- ("delete_claim", "demo-claim"),
- ("close",),
- ]
-
-
-async def test_delete_sandbox_closes_sdk_when_claim_delete_fails(monkeypatch):
- calls = []
- pool = _pool("demo")
-
- class Client:
- async def get_pool(self, name):
- calls.append(("get_pool", name))
- return pool
-
- async def get_claim(self, existing_pool):
- calls.append(("get_claim", existing_pool))
- return "demo-claim"
-
- async def delete_claim(self, claim):
- calls.append(("delete_claim", claim))
- raise RuntimeError("claim delete failed")
-
- async def delete_pool(self, existing_pool):
- raise AssertionError("class delete must not delete pools")
-
- async def delete_template(self, template):
- raise AssertionError("class delete must not delete templates")
-
- async def delete_namespace(self, name):
- raise AssertionError("class delete must not delete namespaces")
-
- async def close(self):
- calls.append(("close",))
-
- monkeypatch.setattr(fleet_cloud, "_FleetClient", Client)
-
- with pytest.raises(RuntimeError, match="claim delete failed"):
- await FleetCloudTransport.delete_sandbox("demo")
-
- assert calls == [
- ("get_pool", "demo"),
- ("get_claim", pool),
- ("delete_claim", "demo-claim"),
- ("close",),
- ]
-
-
-async def test_forward_tunnel_without_spacesd_is_a_loopback_gateway_proxy():
- # A plain image (no `env` service): the SDK forwards through the gateway
- # with a loopback proxy, so the caller gets a local URL, not a
- # bearer-only gateway URL.
- forward = _NativeForward("127.0.0.1:45200", "http://127.0.0.1:45200")
- transport, calls = _env_transport_with(forward)
- transport._bound = Sandbox(namespace="demo", claim="claim", name="sandbox", services=["mcp"])
- tunnel = await transport.forward_tunnel(8765)
- assert calls == [8765]
- assert tunnel.url == "http://127.0.0.1:45200"
- assert (tunnel.host, tunnel.port) == ("127.0.0.1", 45200)
-
-
-async def test_snapshot_is_unsupported():
- transport = FleetCloudTransport(image=Image.from_registry("example:latest"), name="demo")
- with pytest.raises(NotImplementedError, match="Snapshots are not supported"):
- await transport.create_snapshot()
-
-
-async def test_existing_pool_claim_uses_distinct_pool_and_sandbox_names(monkeypatch):
- calls = []
- pool = _pool("cua-cli-wif-smoke")
- claim = SimpleNamespace(metadata=SimpleNamespace(name="wif-smoke-123"))
- bound = _bound()
-
- class Client:
- async def get_pool(self, name):
- calls.append(("get_pool", name))
- return pool
-
- async def set_pool_replicas(self, existing_pool, replicas):
- calls.append(("set_pool_replicas", existing_pool.metadata.name, replicas))
- return existing_pool
-
- async def wait_pool(self, existing_pool):
- calls.append(("wait_pool", existing_pool.metadata.name))
- return existing_pool
-
- async def create_claim(self, request):
- calls.append(("create_claim", request.name, request.pool.metadata.name))
- return claim
-
- async def wait_claim(self, existing_claim):
- calls.append(("wait_claim", existing_claim.metadata.name))
- return bound
-
- async def wait_service_ready(self, sandbox, service, time_to_start):
- calls.append(("wait_service_ready", service))
-
- monkeypatch.setattr(fleet_cloud, "_FleetClient", Client)
-
- transport = FleetCloudTransport(
- image=None,
- name="wif-smoke-123",
- pool_name="cua-cli-wif-smoke",
- create_claim=True,
- )
- await transport.connect()
-
- assert calls == [
- ("get_pool", "cua-cli-wif-smoke"),
- ("set_pool_replicas", "cua-cli-wif-smoke", 1),
- ("wait_pool", "cua-cli-wif-smoke"),
- ("create_claim", "wif-smoke-123", "cua-cli-wif-smoke"),
- ("wait_claim", "wif-smoke-123"),
- ("wait_service_ready", "env"),
- ]
-
-
-async def test_existing_pool_claim_reconnect_and_delete_use_exact_claim_name(monkeypatch):
- calls = []
- pool = _pool("cua-cli-wif-smoke")
- claim = SimpleNamespace(metadata=SimpleNamespace(name="wif-smoke-123"))
- bound = _bound()
-
- class Client:
- async def get_pool(self, name):
- calls.append(("get_pool", name))
- return pool
-
- async def get_claim(self, existing_pool, name=None):
- calls.append(("get_claim", existing_pool.metadata.name, name))
- return claim
-
- async def wait_claim(self, existing_claim):
- return bound
-
- async def wait_service_ready(self, sandbox, service, time_to_start):
- return None
-
- async def delete_claim(self, existing_claim):
- calls.append(("delete_claim", existing_claim.metadata.name))
-
- async def close(self):
- calls.append(("close",))
-
- monkeypatch.setattr(fleet_cloud, "_FleetClient", Client)
-
- await FleetCloudTransport(
- image=None,
- name="wif-smoke-123",
- pool_name="cua-cli-wif-smoke",
- ).connect()
- await FleetCloudTransport.delete_sandbox("wif-smoke-123", pool_name="cua-cli-wif-smoke")
-
- assert calls == [
- ("get_pool", "cua-cli-wif-smoke"),
- ("get_claim", "cua-cli-wif-smoke", "wif-smoke-123"),
- ("get_pool", "cua-cli-wif-smoke"),
- ("get_claim", "cua-cli-wif-smoke", "wif-smoke-123"),
- ("delete_claim", "wif-smoke-123"),
- ("close",),
- ]
-
-
-class _NativeForward:
- """A native ``cua.PortForward`` stand-in."""
-
- def __init__(self, local_addr=None, url=None):
- self._local_addr = local_addr
- self._url = url
- self.closed = False
-
- def local_addr(self):
- return self._local_addr
-
- def url(self):
- return self._url
-
- async def close(self):
- self.closed = True
-
-
-def _env_transport_with(forward=None, error=None):
- from cua_sandbox.transport.fleet import FleetTransport
-
- transport = FleetCloudTransport(image=Image.from_registry("example:latest"), name="demo")
- bound = Sandbox(namespace="demo", claim="claim", name="sandbox", services=["env", "port-3000"])
- # What connect() does once the claim is bound.
- FleetTransport.__init__(transport, sdk=None, bound=bound)
- transport._provisioned = True
- calls = []
-
- class Handle:
- async def forward(self, port):
- calls.append(port)
- if error is not None:
- raise error
- return forward
-
- async def fleet_handle():
- return Handle()
-
- class Client:
- def service_url(self, sandbox, service):
- assert service == "port-3000"
- return "https://run.cua.ai/api/svc/demo/sandbox-port-3000/"
-
- transport._fleet_handle = fleet_handle
- transport._sdk = Client()
- return transport, calls
-
-
-async def test_forward_tunnel_prefers_the_spacesd_tunnel():
- forward = _NativeForward("127.0.0.1:45123", "http://127.0.0.1:45123")
- transport, calls = _env_transport_with(forward)
- tunnel = await transport.forward_tunnel(3000)
- assert calls == [3000]
- assert (tunnel.host, tunnel.port, tunnel.sandbox_port) == ("127.0.0.1", 45123, 3000)
- assert tunnel.url == "http://127.0.0.1:45123"
- await transport.close_tunnel(tunnel)
- assert forward.closed
-
-
-async def test_forward_tunnel_keeps_a_url_only_forward_from_an_older_daemon():
- forward = _NativeForward(None, "https://gw.example/api/svc/demo/sandbox-port-3000")
- transport, _ = _env_transport_with(forward)
- tunnel = await transport.forward_tunnel(3000)
- assert tunnel.url == "https://gw.example/api/svc/demo/sandbox-port-3000"
-
-
-async def test_forward_tunnel_surfaces_sdk_errors():
- transport, calls = _env_transport_with(error=RuntimeError("unsupported: port 3000"))
- with pytest.raises(RuntimeError, match="unsupported"):
- await transport.forward_tunnel(3000)
- assert calls == [3000]
-
-
-def test_registry_images_with_layers_are_accepted_for_a_remote_build():
- # Layers on a registry image build remotely (the SDK refuses them with a
- # "not deployed yet" error until Fleet's builder runs container recipes); local
- # disks and snapshots stay local.
- FleetCloudTransport._validate_image(Image.from_registry("example:latest").apt_install("curl"))
- with pytest.raises(NotImplementedError, match="stay local"):
- FleetCloudTransport._validate_image(
- Image.from_registry("example:latest")._with(_disk_path="x")
- )
diff --git a/libs/python/cua-sandbox/tests/test_fleet_image_variants.py b/libs/python/cua-sandbox/tests/test_fleet_image_variants.py
deleted file mode 100644
index 4828a0c6e2..0000000000
--- a/libs/python/cua-sandbox/tests/test_fleet_image_variants.py
+++ /dev/null
@@ -1,72 +0,0 @@
-"""The Fleet runtime/image rule, through the cua SDK binding.
-
-cua-sandbox does not re-implement the rule: it calls the SDK
-(``fleet_resolve_runtime``). These tests run the shared vectors
-(``libs/cua/crates/cua-fleet/tests/fixtures/image-variants.json``, also run
-by cua-fleet's Rust tests) through the pure bindings, so both languages
-agree on what a manifest means. No registry is read.
-"""
-
-from __future__ import annotations
-
-import json
-from pathlib import Path
-
-import pytest
-from cua_sandbox._sdk import native
-
-from tests import _image_fixtures
-
-VECTORS = (
- Path(__file__).resolve().parents[3]
- / "cua"
- / "crates"
- / "cua-fleet"
- / "tests"
- / "fixtures"
- / "image-variants.json"
-)
-CASES = json.loads(VECTORS.read_text())["cases"]
-
-
[email protected]("case", CASES, ids=[c["name"] for c in CASES])
-def test_shared_vectors_classify_and_pick_the_runtime(case):
- n = native()
- config = None if case["config"] is None else json.dumps(case["config"])
- if "refused" in case:
- with pytest.raises(n.CuaError.Unsupported, match=case["refused"]):
- n.fleet_image_variant(json.dumps(case["manifest"]), config)
- return
- variant = n.fleet_image_variant(json.dumps(case["manifest"]), config)
- assert variant == case["variant"]
- runtimes = case["runtimes"]
- assert n.fleet_check_runtime(None, case["reference"], variant) == runtimes["default"]
- for runtime in ("kubevirt", "gvisor"):
- if runtimes[runtime]:
- assert n.fleet_check_runtime(runtime, case["reference"], variant) == runtime
- else:
- with pytest.raises(n.CuaError.InvalidArgument):
- n.fleet_check_runtime(runtime, case["reference"], variant)
-
-
-FALLBACKS = json.loads(VECTORS.read_text())["fallbacks"]
-
-
[email protected]("case", FALLBACKS, ids=[c["reference"] for c in FALLBACKS])
-def test_shared_fallback_vectors_pick_the_runtime_from_the_reference(case):
- # The pure rule with no variant: the manifest could not be read.
- n = native()
- assert n.fleet_check_runtime(None, case["reference"], None) == case["runtime"]
-
-
-def test_an_unreadable_manifest_falls_back_to_the_reference():
- # The real binding; conftest turns registry reads off
- # (CUA_FLEET_IMAGE_INSPECT=0), so every manifest is unreadable. No network.
- resolve = _image_fixtures.REAL
- image = "ghcr.io/trycua/cua-desktop-linux:docker-latest"
- # An explicit runtime is sent unchecked.
- assert resolve("kubevirt", image) == "kubevirt"
- assert resolve("gvisor", image) == "gvisor"
- # An unset one is guessed from the reference, never refused.
- assert resolve(None, image) == "gvisor"
- assert resolve(None, "ghcr.io/trycua/cua-desktop-linux:latest") == "kubevirt"
diff --git a/libs/python/cua-sandbox/tests/test_fleet_sdk_distribution.py b/libs/python/cua-sandbox/tests/test_fleet_sdk_distribution.py
deleted file mode 100644
index 24faa24f02..0000000000
--- a/libs/python/cua-sandbox/tests/test_fleet_sdk_distribution.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from importlib.metadata import distribution
-from pathlib import Path
-
-import fleet_sdk
-
-
-def test_fleet_sdk_is_provided_by_published_fleet_distribution():
- cua_fleet_distribution = distribution("cua-fleet")
- installed_files = {str(path) for path in cua_fleet_distribution.files or []}
- distribution_root = Path(cua_fleet_distribution.locate_file(".")).resolve()
- binding_path = Path(fleet_sdk.__file__).resolve()
-
- assert cua_fleet_distribution.version == "0.1.17"
- assert "fleet_sdk/__init__.py" in installed_files
- assert binding_path.is_relative_to(distribution_root)
-
-
-def test_cua_sdk_is_the_native_binding_distribution():
- """cua-sandbox's data plane is the cua SDK (``cua`` >= 0.2, UniFFI over
- cua-sdk), not the old ``cua`` meta-package (0.1.x, pure re-exports)."""
- import cua
-
- cua_distribution = distribution("cua")
- major, minor = (int(part) for part in cua_distribution.version.split(".")[:2])
-
- assert (major, minor) >= (0, 2)
- assert hasattr(cua, "_native") and hasattr(cua._native, "Cua")
- assert hasattr(cua._native, "SpacesdClient")
diff --git a/libs/python/cua-sandbox/tests/test_fleet_transport.py b/libs/python/cua-sandbox/tests/test_fleet_transport.py
deleted file mode 100644
index 0df3af89f6..0000000000
--- a/libs/python/cua-sandbox/tests/test_fleet_transport.py
+++ /dev/null
@@ -1,264 +0,0 @@
-"""FleetTransport: named services through the Fleet gateway, interfaces
-through cua-spacesd on the claim's ``env`` service (the cua SDK).
-
-The computer-server wire tests that lived here (``POST /cmd`` bodies, the
-``/pty`` routes, "connect rejects a missing service") were replaced: the
-interfaces no longer ride ``service_request``, and connecting to a bound
-claim is daemon-agnostic.
-"""
-
-from types import SimpleNamespace
-
-import cua_sandbox.transport.fleet as fleet_transport
-import pytest
-from cua_sandbox import Sandbox as CuaSandbox
-from cua_sandbox import SpacesdNotAvailable
-from cua_sandbox.transport import fleet as fleet_module
-from cua_sandbox.transport.fleet import FleetTransport, build_http_request
-from fleet_sdk import HttpHeader, HttpRequest, HttpResponse, Sandbox
-
-from tests._fake_env import FakeEnv
-
-
-class FakeSDK:
- def __init__(self, responses):
- self.responses = list(responses)
- self.calls = []
-
- async def service_request(self, sandbox, service, path, request):
- self.calls.append((sandbox, service, path, request))
- return self.responses.pop(0)
-
-
-def response(status=200, body=b"{}"):
- return HttpResponse(status=status, headers=[], body=body)
-
-
-def sandbox(services=("api",)):
- return Sandbox(
- namespace="demo", claim="claim-demo", name="sandbox-demo", services=list(services)
- )
-
-
-class FakeFleetHandle:
- def __init__(self, env):
- self.env_calls = 0
- self._env = env
-
- async def spacesd(self, probe_timeout_ms):
- self.env_calls += 1
- return self._env
-
-
-async def test_interfaces_use_the_env_service_through_the_sdk(monkeypatch):
- env = FakeEnv()
- handle = FakeFleetHandle(env)
- attached = []
-
- async def fleet_sandbox(namespace, claim):
- attached.append((namespace, claim))
- return handle
-
- monkeypatch.setattr(fleet_module, "fleet_sandbox", fleet_sandbox)
- sdk = FakeSDK([])
- sb = CuaSandbox(FleetTransport(sdk=sdk, bound=sandbox(["env", "mcp"])), name="sandbox-demo")
- await sb._connect()
-
- result = await sb.shell.run("uname -a")
- png = await sb.screenshot()
- await sb.mouse.click(10, 20)
-
- assert attached == [("demo", "claim-demo")]
- assert handle.env_calls == 1, "one spacesd connection is reused"
- assert result.success and png.startswith(b"\x89PNG")
- assert ("click", 10.0, 20.0) in env.calls
- assert sdk.calls == [], "interfaces no longer ride Fleet service_request"
-
-
-async def test_connect_is_daemon_agnostic_and_interfaces_fail_clearly_without_env():
- sdk = FakeSDK([response(body=b'{"ok":true}')])
- transport = FleetTransport(sdk=sdk, bound=sandbox(["mcp"]), env_ready_timeout=0)
- sb = CuaSandbox(transport, name="sandbox-demo")
- await sb._connect()
-
- # Named services work on an image without cua-spacesd ...
- reply = await sb.services.request("mcp", method="POST", path="/mcp", json={"id": 1})
- assert reply.status_code == 200
- # ... and the interfaces say why they cannot.
- with pytest.raises(SpacesdNotAvailable, match="no 'env' service"):
- await sb.shell.run("true")
-
-
-async def test_unknown_named_service_is_rejected():
- transport = FleetTransport(sdk=FakeSDK([]), bound=sandbox(["env"]))
- await transport.connect()
- with pytest.raises(ValueError, match="does not expose service"):
- await transport.request_service("mcp", method="GET", path="/")
-
-
-def test_build_http_request_constructs_the_record_through_the_builder():
- unbounded = build_http_request(method="GET", url="https://service.invalid/status")
-
- assert isinstance(unbounded, HttpRequest)
- assert (unbounded.method, unbounded.headers, unbounded.body) == ("GET", [], None)
- assert unbounded.timeout_secs is None
-
-
-def test_build_http_request_forwards_response_limit_to_the_builder(monkeypatch):
- class Builder:
- def __init__(self):
- self.request = SimpleNamespace(body=None, timeout_secs=None, max_response_bytes=None)
-
- def method(self, value):
- self.request.method = value
- return self
-
- def url(self, value):
- self.request.url = value
- return self
-
- def headers(self, value):
- self.request.headers = value
- return self
-
- def timeout_secs(self, value):
- self.request.timeout_secs = value
- return self
-
- def max_response_bytes(self, value):
- self.request.max_response_bytes = value
- return self
-
- def build(self):
- return self.request
-
- monkeypatch.setattr(fleet_transport, "HttpRequestBuilder", Builder)
-
- bounded = build_http_request(
- method="GET",
- url="https://service.invalid/status",
- timeout_secs=30,
- max_response_bytes=4096,
- )
-
- assert (bounded.method, bounded.headers, bounded.body) == ("GET", [], None)
- assert bounded.timeout_secs == 30
- assert bounded.max_response_bytes == 4096
-
-
-async def test_requests_are_bounded_by_the_transport_timeout():
- sdk = FakeSDK([response(), response()])
- transport = FleetTransport(sdk=sdk, bound=sandbox())
- await transport.connect()
- fractional = FleetTransport(sdk=sdk, bound=sandbox(), timeout=0.5)
- await fractional.connect()
-
- await transport.request_service("api", method="GET", path="/status")
- await fractional.request_service("api", method="GET", path="/status")
-
- assert sdk.calls[0][3].timeout_secs == 30
- assert sdk.calls[1][3].timeout_secs == 1
-
-
-async def test_service_response_limit_is_forwarded_and_exact_limit_is_accepted(monkeypatch):
- seen = []
-
- def build_request(**request):
- seen.append(request)
- return SimpleNamespace(**request)
-
- monkeypatch.setattr(fleet_transport, "build_http_request", build_request)
- sdk = FakeSDK([response(body=b"four")])
- transport = FleetTransport(sdk=sdk, bound=sandbox())
- await transport.connect()
-
- result = await transport.request_service(
- "api", method="GET", path="/status", max_response_bytes=4
- )
-
- assert seen[0]["max_response_bytes"] == 4
- assert result.content == b"four"
-
-
-async def test_service_response_over_limit_is_rejected_without_exposing_contents(monkeypatch):
- monkeypatch.setattr(
- fleet_transport, "build_http_request", lambda **request: SimpleNamespace(**request)
- )
- secret = b"private-response-fragment"
- sdk = FakeSDK([response(body=secret)])
- transport = FleetTransport(sdk=sdk, bound=sandbox())
- await transport.connect()
-
- with pytest.raises(RuntimeError, match="configured size limit") as error:
- await transport.request_service(
- "api", method="GET", path="/status", max_response_bytes=len(secret) - 1
- )
-
- assert secret.decode() not in str(error.value)
-
-
[email protected]("default_timeout", [30, 90])
-async def test_service_timeout_override_does_not_change_existing_callers(default_timeout):
- sdk = FakeSDK([response(), response(), response()])
- transport = FleetTransport(sdk=sdk, bound=sandbox(), timeout=default_timeout)
- await transport.connect()
-
- await transport.request_service("api", method="POST", path="/exchange", timeout=119.25)
- await transport.request_service("api", method="GET", path="/status")
- # A later call without an override keeps the transport default (the
- # interfaces ride cua-spacesd, so only named services use this path).
- await transport.request_service("api", method="GET", path="/status")
-
- assert [call[3].timeout_secs for call in sdk.calls] == [120, default_timeout, default_timeout]
- assert transport._timeout == default_timeout
-
-
-async def test_raw_service_bytes_and_duplicate_headers_are_preserved():
- sdk = FakeSDK(
- [
- HttpResponse(
- status=200,
- headers=[
- HttpHeader(name="mcp-session-id", value="first"),
- HttpHeader(name="mcp-session-id", value="second"),
- ],
- body=b"raw response",
- )
- ]
- )
- transport = FleetTransport(sdk=sdk, bound=sandbox())
- await transport.connect()
- result = await transport.request_service(
- "api",
- method="POST",
- path="/mcp",
- body=b"\x00raw bytes",
- headers=[("content-type", "application/octet-stream"), ("x-test", "a"), ("x-test", "b")],
- )
- request = sdk.calls[0][3]
- assert request.body == b"\x00raw bytes"
- assert [(h.name, h.value) for h in request.headers] == [
- ("content-type", "application/octet-stream"),
- ("x-test", "a"),
- ("x-test", "b"),
- ]
- assert result.content == b"raw response"
- assert result.headers.get_list("mcp-session-id") == ["first", "second"]
-
-
-async def test_raw_body_and_json_are_mutually_exclusive():
- sdk = FakeSDK([])
- transport = FleetTransport(sdk=sdk, bound=sandbox())
- await transport.connect()
- with pytest.raises(ValueError, match="either body or json_body"):
- await transport.request_service("api", method="POST", path="/mcp", body=b"", json_body={})
- assert not sdk.calls
diff --git a/libs/python/cua-sandbox/tests/test_from_registry_ostype.py b/libs/python/cua-sandbox/tests/test_from_registry_ostype.py
index 0558a87ada..117efa1eb5 100644
--- a/libs/python/cua-sandbox/tests/test_from_registry_ostype.py
+++ b/libs/python/cua-sandbox/tests/test_from_registry_ostype.py
@@ -1,11 +1,10 @@
"""A registry image must be able to say it is Windows.
-os_type selects the firmware: Windows guest disks are built UEFI-only, and both
-the local QEMU runtime and the Fleet transport read os_type to decide. With
-from_registry hardcoding "linux", a Windows containerDisk pulled from any
-registry was handed BIOS and could not boot — the same failure fixed for Fleet
-in #3125, through a different door. The only escape was reaching past the
-constructor with dataclasses.replace().
+os_type selects the firmware: Windows guest disks are built UEFI-only, and the
+local QEMU runtime reads os_type to decide. With from_registry hardcoding
+"linux", a Windows containerDisk pulled from any registry was handed BIOS and
+could not boot. The only escape was reaching past the constructor with
+dataclasses.replace().
"""
import inspect
@@ -49,12 +48,3 @@ def test_it_offers_the_same_knobs_as_from_file():
@pytest.mark.parametrize("os_type", ["windows", "linux", "macos"])
def test_os_type_is_passed_through_verbatim(os_type):
assert Image.from_registry(REF, os_type=os_type).os_type == os_type
-
-
-def test_windows_registry_image_gets_uefi_on_fleet():
- """The end the bug was actually felt at: firmware selection."""
- from cua_sandbox.transport.fleet_cloud import FleetCloudTransport
-
- image = Image.from_registry(REF, os_type="windows", kind="vm")
- template = FleetCloudTransport(image=image, name="demo")._template_request().spec.vm_template
- assert template.firmware is not None, "a Windows containerDisk must not be handed BIOS"
diff --git a/libs/python/cua-sandbox/tests/test_home_guard.py b/libs/python/cua-sandbox/tests/test_home_guard.py
index 883423c544..ddbc6523d5 100644
--- a/libs/python/cua-sandbox/tests/test_home_guard.py
+++ b/libs/python/cua-sandbox/tests/test_home_guard.py
@@ -6,6 +6,16 @@ import pytest
from cua_sandbox import _paths, sandbox_state
+def _write_state(name):
+ sandbox_state.save(
+ name,
+ runtime_type="docker",
+ image={"os_type": "linux"},
+ host="127.0.0.1",
+ api_port=3211,
+ )
+
+
def test_pytest_is_a_test_process():
assert _paths.is_test_process()
@@ -17,11 +27,11 @@ def test_a_state_write_to_the_real_home_is_refused(monkeypatch):
monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", real / "sandboxes")
before = (real / "sandboxes" / "cua-home-guard-probe.json").exists()
with pytest.raises(PermissionError, match="CUA_HOME"):
- sandbox_state.save_fleet_claim("cua-home-guard-probe", "pool")
+ _write_state("cua-home-guard-probe")
assert (real / "sandboxes" / "cua-home-guard-probe.json").exists() == before
def test_a_temp_home_is_allowed(tmp_path, monkeypatch):
monkeypatch.setenv("CUA_HOME", str(tmp_path))
- sandbox_state.save_fleet_claim("ok", "pool")
+ _write_state("ok")
assert (tmp_path / "sandboxes" / "ok.json").exists()
diff --git a/libs/python/cua-sandbox/tests/test_image_info.py b/libs/python/cua-sandbox/tests/test_image_info.py
index 91117b17b4..bba7eea84d 100644
--- a/libs/python/cua-sandbox/tests/test_image_info.py
+++ b/libs/python/cua-sandbox/tests/test_image_info.py
@@ -91,13 +91,9 @@ def test_the_native_handle_is_the_source_of_truth():
assert sb.image_info is None
-def test_fleet_claims_read_the_claim_or_transport_handle():
+def test_a_transport_handle_is_read_when_the_runtime_has_none():
sb = _sandbox()
- sb._claim_handle = SimpleNamespace(_native=_Handle(_native_info(variant="containerdisk")))
- assert sb.image_info.variant == "containerdisk"
- # After disconnect the claim handle lets go; the transport keeps one.
- sb._claim_handle = SimpleNamespace(_native=None)
- sb._transport._native_fleet_sandbox = _Handle(_native_info(arch=None, emulated=True))
+ sb._transport._native_sandbox = _Handle(_native_info(arch=None, emulated=True))
info = sb.image_info
assert info.arch is None and info.emulated is True
diff --git a/libs/python/cua-sandbox/tests/test_image_resolve.py b/libs/python/cua-sandbox/tests/test_image_resolve.py
index e7dddde1a5..88f94dda06 100644
--- a/libs/python/cua-sandbox/tests/test_image_resolve.py
+++ b/libs/python/cua-sandbox/tests/test_image_resolve.py
@@ -1,19 +1,17 @@
"""The unified image path: one native resolver, canonical images, the P0 fixes.
Hermetic: ``native().resolve_image`` is replaced by a fake (conftest switches
-real registry reads off with ``CUA_IMAGE_RESOLVE=0``), runtimes are
-recorders, and the session tests use a file credential store in tmp.
+real registry reads off with ``CUA_IMAGE_RESOLVE=0``) and runtimes are
+recorders.
"""
from __future__ import annotations
import json
-from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
import pytest
from cua_sandbox import Image, Sandbox, _sdk
-from cua_sandbox._config import FLEET_CREDENTIALS_MISSING, has_fleet_session
from cua_sandbox.image import resolve_image_kind
from cua_sandbox.transport.env import EnvTransport
@@ -165,30 +163,3 @@ async def test_request_service_passes_headers():
("accept", "application/json, text/event-stream"),
("content-type", "application/json"),
}
-
-
-# ── Missing Fleet credentials and the `cua auth login` session ─────────────
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_no_credentials_names_every_way_out():
- with pytest.raises(Exception) as info:
- await Sandbox.create(Image.from_registry("python:3.12-slim"), local=False)
- assert FLEET_CREDENTIALS_MISSING in str(info.value)
- assert "cua auth login" in FLEET_CREDENTIALS_MISSING
- assert "local=True" in FLEET_CREDENTIALS_MISSING
-
-
-def test_the_cua_auth_login_session_counts_as_fleet_access(monkeypatch, tmp_path):
- monkeypatch.setenv("CUA_HOME", str(tmp_path))
- monkeypatch.setenv("CUA_CREDENTIAL_STORE", "file")
- monkeypatch.delenv("CUA_FLEET_SESSION", raising=False)
- assert has_fleet_session() is False
- expires = (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat()
- (tmp_path / "credentials.json").write_text(
- json.dumps({"access_token": "tok", "expires_at": expires})
- )
- assert has_fleet_session() is True
- assert Sandbox._uses_fleet(None) is True
- monkeypatch.setenv("CUA_FLEET_SESSION", "0")
- assert has_fleet_session() is False
diff --git a/libs/python/cua-sandbox/tests/test_live_fleet_e2e_support.py b/libs/python/cua-sandbox/tests/test_live_fleet_e2e_support.py
deleted file mode 100644
index fd9276fe0d..0000000000
--- a/libs/python/cua-sandbox/tests/test_live_fleet_e2e_support.py
+++ /dev/null
@@ -1,992 +0,0 @@
-from __future__ import annotations
-
-import json
-import re
-from types import SimpleNamespace
-
-import pytest
-from cua_sandbox import Image
-from fleet_sdk import SdkError
-
-from tests.live.fleet_e2e_support import (
- assert_template_contract,
- build_namespace_name,
- build_pool_namespace_name,
- collect_resource_inventory,
- has_oauth_credentials,
- is_pool_missing_error,
- wait_claims_absent,
- write_summary,
-)
-
-
-def test_live_test_requires_both_oauth_values(monkeypatch) -> None:
- monkeypatch.delenv("CUA_CLIENT_ID", raising=False)
- monkeypatch.delenv("CUA_CLIENT_SECRET", raising=False)
- from tests.live.test_fleet_ephemeral import has_oauth_credentials
-
- assert not has_oauth_credentials()
- monkeypatch.setenv("CUA_CLIENT_ID", "client")
- assert not has_oauth_credentials()
- monkeypatch.setenv("CUA_CLIENT_SECRET", "secret")
- assert has_oauth_credentials()
-
-
- ("event_name", "event_class"),
- [("schedule", "schedule"), ("push", "push"), ("workflow_dispatch", "manual")],
-)
-def test_build_namespace_name_is_stable_for_each_lane_and_event_class(
- event_name: str, event_class: str
-) -> None:
- name = build_namespace_name("published-package", event_name)
- assert name == f"cua-live-published-package-{event_class}"
- assert len(name) <= 63
-
-
-def test_build_namespace_name_normalizes_invalid_overlong_lane_input() -> None:
- name = build_namespace_name("Published_Package!!!" + "X" * 100, "workflow_dispatch")
-
- assert len(name) <= 63
- assert re.fullmatch(r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", name)
- assert name.startswith("cua-live-published-package-")
-
-
[email protected]("mode", ["warm", "cold"])
- ("event_name", "event_class"),
- [("schedule", "schedule"), ("push", "push"), ("workflow_dispatch", "manual")],
-)
-def test_build_pool_namespace_name_is_stable_for_each_mode_lane_and_event_class(
- mode: str, event_name: str, event_class: str
-) -> None:
- name = build_pool_namespace_name(mode, "published-package", event_name)
- assert name == f"cua-live-pool-{mode}-published-package-{event_class}"
- assert len(name) <= 63
-
-
-def test_build_pool_namespace_name_normalizes_invalid_overlong_input() -> None:
- name = build_pool_namespace_name(
- "warm", "Published_Package!!!" + "X" * 100, "workflow_dispatch"
- )
-
- assert len(name) <= 63
- assert re.fullmatch(r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", name)
- assert name.startswith("cua-live-pool-warm-published-package-")
-
-
- ("error", "missing"),
- [
- (SdkError.Status("get pool", 404, b"not found"), True),
- (SdkError.Status("get pool", 403, b"forbidden"), True),
- (SdkError.Status("get pool", 500, b"failure"), False),
- (RuntimeError("transport down"), False),
- ],
-)
-def test_is_pool_missing_error_mirrors_reconcile_semantics(
- error: BaseException, missing: bool
-) -> None:
- assert is_pool_missing_error(error) is missing
-
-
-def test_support_has_oauth_credentials_requires_both_values(monkeypatch) -> None:
- monkeypatch.delenv("CUA_CLIENT_ID", raising=False)
- monkeypatch.delenv("CUA_CLIENT_SECRET", raising=False)
- assert not has_oauth_credentials()
- monkeypatch.setenv("CUA_CLIENT_ID", "client")
- assert not has_oauth_credentials()
- monkeypatch.setenv("CUA_CLIENT_SECRET", "secret")
- assert has_oauth_credentials()
-
-
-def test_assert_template_contract_accepts_server_port_8000() -> None:
- probes = SimpleNamespace(
- to_json=lambda: json.dumps({"readinessProbe": {"tcpSocket": {"port": 8000}}})
- )
- template = SimpleNamespace(
- spec=SimpleNamespace(
- vm_template=SimpleNamespace(
- services=[SimpleNamespace(name="server", target_port=8000)],
- probes=probes,
- )
- )
- )
- assert_template_contract(template, expected_port=8000)
-
-
-def test_assert_template_contract_rejects_wrong_service_port() -> None:
- probes = SimpleNamespace(
- to_json=lambda: json.dumps({"readinessProbe": {"tcpSocket": {"port": 8000}}})
- )
- template = SimpleNamespace(
- spec=SimpleNamespace(
- vm_template=SimpleNamespace(
- services=[SimpleNamespace(name="server", target_port=5000)],
- probes=probes,
- )
- )
- )
- with pytest.raises(AssertionError, match="target_port"):
- assert_template_contract(template, expected_port=8000)
-
-
-def test_assert_template_contract_rejects_missing_server_service() -> None:
- probes = SimpleNamespace(
- to_json=lambda: json.dumps({"readinessProbe": {"tcpSocket": {"port": 8000}}})
- )
- template = SimpleNamespace(
- spec=SimpleNamespace(
- vm_template=SimpleNamespace(
- services=[SimpleNamespace(name="other", target_port=8000)],
- probes=probes,
- )
- )
- )
-
- with pytest.raises(AssertionError, match="server service"):
- assert_template_contract(template, expected_port=8000)
-
-
-async def test_collect_resource_inventory_lists_owned_resources() -> None:
- def resource(name: str):
- return SimpleNamespace(metadata=SimpleNamespace(name=name))
-
- class FakeClient:
- async def list_templates(self, name: str):
- return [resource("template-a")]
-
- async def list_pools(self, name: str):
- return [resource("pool-a")]
-
- async def list_claims(self, name: str):
- return [resource("claim-a")]
-
- assert await collect_resource_inventory(FakeClient(), "demo") == {
- "templates": ["template-a"],
- "pools": ["pool-a"],
- "claims": ["claim-a"],
- }
-
-
-async def test_wait_claims_absent_polls_until_claims_are_gone() -> None:
- calls = 0
-
- class FakeClient:
- async def list_claims(self, name: str):
- nonlocal calls
- calls += 1
- if calls == 1:
- return [SimpleNamespace(metadata=SimpleNamespace(name="claim-a"))]
- return []
-
- assert await wait_claims_absent(FakeClient(), "demo", timeout=1, interval=0)
- assert calls == 2
-
-
-async def test_wait_claims_absent_returns_true_for_public_sdk_404() -> None:
- class FakeClient:
- async def list_claims(self, name: str):
- raise SdkError.Status("list claims", 404, b"not found")
-
- assert await wait_claims_absent(FakeClient(), "demo", timeout=1, interval=0)
-
-
-async def test_wait_claims_absent_times_out_when_claims_remain() -> None:
- class FakeClient:
- async def list_claims(self, name: str):
- return [SimpleNamespace(metadata=SimpleNamespace(name="claim-a"))]
-
- assert not await wait_claims_absent(FakeClient(), "demo", timeout=0, interval=0)
-
-
-async def test_wait_claims_absent_propagates_non_404_sdk_errors() -> None:
- class FakeClient:
- async def list_claims(self, name: str):
- raise SdkError.Status("list claims", 500, b"failure")
-
- with pytest.raises(SdkError.Status):
- await wait_claims_absent(FakeClient(), "demo", timeout=1, interval=0)
-
-
[email protected]("status", [403, 404])
-async def test_collect_resource_inventory_returns_empty_for_missing_namespace(
- status: int,
-) -> None:
- class FakeClient:
- async def list_templates(self, name: str):
- raise SdkError.Status("list templates", status, b"missing")
-
- assert await collect_resource_inventory(FakeClient(), "demo") == {
- "templates": [],
- "pools": [],
- "claims": [],
- }
-
-
-async def test_collect_resource_inventory_propagates_non_404_sdk_errors() -> None:
- class FakeClient:
- async def list_templates(self, name: str):
- raise SdkError.Status("list templates", 500, b"failure")
-
- with pytest.raises(SdkError.Status):
- await collect_resource_inventory(FakeClient(), "demo")
-
-
-def test_write_summary_recursively_redacts_sensitive_values(tmp_path) -> None:
- path = tmp_path / "summary.json"
- write_summary(
- path,
- {
- "authorization": "Bearer top-secret",
- "token": "token-value",
- "client_secret": "client-secret-value",
- "api_key": "api-key-value",
- "clientSecret": "camel-client-secret-value",
- "accessToken": "access-token-value",
- "refreshToken": "refresh-token-value",
- "nested": {
- "Authorization": "Nested Bearer secret",
- "x-api-key": "header-api-key-value",
- "items": [{"TOKEN": "nested-token"}, {"safe": "visible"}],
- },
- },
- )
-
- rendered = path.read_text()
- summary = json.loads(rendered)
-
- for secret in (
- "Bearer top-secret",
- "token-value",
- "client-secret-value",
- "api-key-value",
- "camel-client-secret-value",
- "access-token-value",
- "refresh-token-value",
- "header-api-key-value",
- "Nested Bearer secret",
- "nested-token",
- ):
- assert secret not in rendered
- assert summary["authorization"] == "<redacted>"
- assert summary["token"] == "<redacted>"
- assert summary["client_secret"] == "<redacted>"
- assert summary["api_key"] == "<redacted>"
- assert summary["clientSecret"] == "<redacted>"
- assert summary["accessToken"] == "<redacted>"
- assert summary["refreshToken"] == "<redacted>"
- assert summary["nested"]["Authorization"] == "<redacted>"
- assert summary["nested"]["x-api-key"] == "<redacted>"
- assert summary["nested"]["items"][0]["TOKEN"] == "<redacted>"
- assert summary["nested"]["items"][1]["safe"] == "visible"
-
-
-def test_live_cleanup_exposes_no_explicit_namespace_deletion_api() -> None:
- from cua_sandbox import Sandbox as CuaSandbox
- from cua_sandbox.transport.fleet_cloud import FleetCloudTransport
-
- from tests.live import fleet_e2e_support
- from tests.live import test_fleet_ephemeral as live_test
-
- assert not hasattr(fleet_e2e_support, "cleanup_namespace")
- assert not hasattr(live_test, "cleanup_namespace")
- assert not hasattr(CuaSandbox, "owns_namespace")
- assert not hasattr(FleetCloudTransport, "owns_namespace")
-
-
-def test_selected_namespace_rejects_unsafe_override(monkeypatch) -> None:
- from tests.live import test_fleet_ephemeral as live_test
-
- monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", "shared-production")
-
- with pytest.raises(ValueError, match="must start with cua-live-"):
- live_test.selected_namespace()
-
-
-async def test_owned_ephemeral_namespace_is_empty_after_cleanup(monkeypatch, tmp_path) -> None:
- from tests.live import test_fleet_ephemeral as live_test
-
- calls: list[str] = []
- summaries = []
-
- class FakeHttpClient:
- async def aclose(self) -> None:
- calls.append("close")
-
- class FakeSandbox:
- name = "cua-live-existing"
-
- class screen:
- @staticmethod
- async def size():
- return (1024, 768)
-
- @staticmethod
- async def screenshot():
- return b"\x89PNG\r\n\x1a\n" + b"x" * 1001
-
- class shell:
- @staticmethod
- async def run(command: str):
- return SimpleNamespace(success=True, stdout="Linux\n", stderr="")
-
- class services:
- @staticmethod
- async def request(name: str, *, method: str, path: str, **_):
- return SimpleNamespace(status_code=200)
-
- class FakeEphemeral:
- async def __aenter__(self):
- return FakeSandbox()
-
- async def __aexit__(self, exc_type, exc_value, traceback) -> None:
- return None
-
- class FakeFleet:
- async def get_template(self, namespace: str, name: str):
- return object()
-
- def ephemeral(*args, **kwargs):
- calls.append("provision")
- return FakeEphemeral()
-
- async def wait_claims_absent(fleet, namespace: str) -> bool:
- return True
-
- async def collect_resource_inventory(fleet, namespace: str):
- return {"templates": [], "pools": [], "claims": []}
-
- monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", "cua-live-existing")
- monkeypatch.setenv("CUA_LIVE_E2E_ARTIFACT_DIR", str(tmp_path))
- monkeypatch.setattr(live_test, "build_fleet_client", lambda: (FakeFleet(), FakeHttpClient()))
- monkeypatch.setattr(live_test.Sandbox, "ephemeral", ephemeral)
- monkeypatch.setattr(live_test, "assert_template_contract", lambda template, expected_port: None)
- monkeypatch.setattr(live_test, "wait_claims_absent", wait_claims_absent)
- monkeypatch.setattr(live_test, "collect_resource_inventory", collect_resource_inventory)
- monkeypatch.setattr(live_test, "write_summary", lambda path, summary: summaries.append(summary))
-
- await live_test.run_fleet_ephemeral_live()
-
- assert calls == ["provision", "close"]
- assert summaries[-1]["persistent_resources"] == {
- "templates": [],
- "pools": [],
- "claims": [],
- }
-
-
[email protected]("cleanup_stage", ["poll", "inventory"])
-async def test_cleanup_failure_does_not_mask_primary_failure(
- monkeypatch, cleanup_stage: str
-) -> None:
- from tests.live import test_fleet_ephemeral as live_test
-
- class PrimaryFailure(Exception):
- pass
-
- class CleanupFailure(Exception):
- pass
-
- class FakeSandbox:
- name = "cua-live-primary-failure"
-
- class FailingEphemeral:
- async def __aenter__(self):
- return FakeSandbox()
-
- async def __aexit__(self, exc_type, exc_value, traceback) -> None:
- return None
-
- class FakeFleet:
- async def get_template(self, namespace: str, name: str):
- raise PrimaryFailure("provision failed")
-
- class FakeHttpClient:
- async def aclose(self) -> None:
- return None
-
- summaries = []
-
- async def wait_claims_absent(fleet, namespace: str) -> bool:
- if cleanup_stage == "poll":
- raise CleanupFailure("poll failed")
- return False
-
- async def collect_resource_inventory(fleet, namespace: str):
- raise CleanupFailure("inventory failed")
-
- monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", "cua-live-primary-failure")
- monkeypatch.setattr(live_test, "build_fleet_client", lambda: (FakeFleet(), FakeHttpClient()))
- monkeypatch.setattr(live_test.Sandbox, "ephemeral", lambda *args, **kwargs: FailingEphemeral())
- monkeypatch.setattr(live_test, "wait_claims_absent", wait_claims_absent)
- monkeypatch.setattr(live_test, "collect_resource_inventory", collect_resource_inventory)
- monkeypatch.setattr(live_test, "write_summary", lambda path, summary: summaries.append(summary))
-
- with pytest.raises(PrimaryFailure, match="provision failed"):
- await live_test.run_fleet_ephemeral_live()
-
- assert summaries[-1]["cleanup_error"] == {"type": "CleanupFailure"}
-
-
-async def test_summary_write_failure_still_closes_and_preserves_primary_error(monkeypatch) -> None:
- from tests.live import test_fleet_ephemeral as live_test
-
- class SummaryWriteFailure(Exception):
- pass
-
- class FakeHttpClient:
- closed = False
-
- async def aclose(self) -> None:
- self.closed = True
-
- class FailingEphemeral:
- async def __aenter__(self):
- raise RuntimeError("primary failure")
-
- async def __aexit__(self, exc_type, exc_value, traceback) -> None:
- return None
-
- http_client = FakeHttpClient()
-
- def write_summary(path, summary) -> None:
- raise SummaryWriteFailure("disk unavailable")
-
- monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", "cua-live-summary-failure")
- monkeypatch.setattr(live_test, "build_fleet_client", lambda: (object(), http_client))
- monkeypatch.setattr(live_test.Sandbox, "ephemeral", lambda *args, **kwargs: FailingEphemeral())
- monkeypatch.setattr(live_test, "write_summary", write_summary)
-
- with pytest.raises(RuntimeError, match="primary failure"):
- await live_test.run_fleet_ephemeral_live()
-
- assert http_client.closed
-
-
-async def test_close_failure_does_not_mask_primary_error(monkeypatch) -> None:
- from tests.live import test_fleet_ephemeral as live_test
-
- class CloseFailure(Exception):
- pass
-
- class FakeHttpClient:
- async def aclose(self) -> None:
- raise CloseFailure("close failed")
-
- class FailingEphemeral:
- async def __aenter__(self):
- raise RuntimeError("primary failure")
-
- async def __aexit__(self, exc_type, exc_value, traceback) -> None:
- return None
-
- summaries = []
-
- monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", "cua-live-close-failure")
- monkeypatch.setattr(live_test, "build_fleet_client", lambda: (object(), FakeHttpClient()))
- monkeypatch.setattr(live_test.Sandbox, "ephemeral", lambda *args, **kwargs: FailingEphemeral())
- monkeypatch.setattr(live_test, "write_summary", lambda path, summary: summaries.append(summary))
-
- with pytest.raises(RuntimeError, match="primary failure"):
- await live_test.run_fleet_ephemeral_live()
-
- assert summaries[-1]["close_error"] == {"type": "CloseFailure"}
-
-
- "namespace",
- ["cua-live-UPPER", "cua-live-", "cua-live-" + "a" * 55, "cua-live-name_"],
-)
-def test_selected_namespace_requires_dns_1123_label(monkeypatch, namespace: str) -> None:
- from tests.live import test_fleet_ephemeral as live_test
-
- monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", namespace)
-
- with pytest.raises(ValueError, match="DNS-1123 label"):
- live_test.selected_namespace()
-
-
-async def test_claim_leak_records_persistent_inventory_without_deletion(
- monkeypatch, tmp_path
-) -> None:
- from tests.live import test_fleet_ephemeral as live_test
-
- summaries = []
-
- class FakeSandbox:
- name = "cua-live-raced"
-
- class screen:
- @staticmethod
- async def size():
- return (1024, 768)
-
- @staticmethod
- async def screenshot():
- return b"\x89PNG\r\n\x1a\n" + b"x" * 1001
-
- class shell:
- @staticmethod
- async def run(command: str):
- return SimpleNamespace(success=True, stdout="Linux\n", stderr="")
-
- class services:
- @staticmethod
- async def request(name: str, *, method: str, path: str, **_):
- return SimpleNamespace(status_code=200)
-
- class FakeEphemeral:
- async def __aenter__(self):
- return FakeSandbox()
-
- async def __aexit__(self, exc_type, exc_value, traceback) -> None:
- return None
-
- class FakeHttpClient:
- async def aclose(self) -> None:
- return None
-
- class FakeFleet:
- async def get_template(self, namespace: str, name: str):
- return object()
-
- async def wait_claims_absent(fleet, namespace: str) -> bool:
- return False
-
- async def collect_resource_inventory(fleet, namespace: str):
- return {"templates": [namespace], "pools": [namespace], "claims": ["claim-a"]}
-
- monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", "cua-live-raced")
- monkeypatch.setenv("CUA_LIVE_E2E_ARTIFACT_DIR", str(tmp_path))
- monkeypatch.setattr(live_test, "build_fleet_client", lambda: (FakeFleet(), FakeHttpClient()))
- monkeypatch.setattr(live_test.Sandbox, "ephemeral", lambda *args, **kwargs: FakeEphemeral())
- monkeypatch.setattr(live_test, "assert_template_contract", lambda template, expected_port: None)
- monkeypatch.setattr(live_test, "wait_claims_absent", wait_claims_absent)
- monkeypatch.setattr(live_test, "collect_resource_inventory", collect_resource_inventory)
- monkeypatch.setattr(live_test, "write_summary", lambda path, summary: summaries.append(summary))
-
- with pytest.raises(pytest.fail.Exception, match="claims remain"):
- await live_test.run_fleet_ephemeral_live()
-
- assert summaries[-1]["claim_leak"] is True
- assert summaries[-1]["persistent_resources"] == {
- "templates": ["cua-live-raced"],
- "pools": ["cua-live-raced"],
- "claims": ["claim-a"],
- }
-
-
-async def test_provisioning_failure_before_yield_never_deletes_namespace(monkeypatch) -> None:
- from tests.live import test_fleet_ephemeral as live_test
-
- class ProvisioningFailure(Exception):
- pass
-
- summaries = []
-
- class FailingEphemeral:
- async def __aenter__(self):
- raise ProvisioningFailure("provisioning failed")
-
- async def __aexit__(self, exc_type, exc_value, traceback) -> None:
- return None
-
- class FakeHttpClient:
- async def aclose(self) -> None:
- return None
-
- async def wait_claims_absent(fleet, namespace: str) -> bool:
- return False
-
- async def collect_resource_inventory(fleet, namespace: str):
- return {"templates": [], "pools": [], "claims": []}
-
- monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", "cua-live-provisioning-failure")
- monkeypatch.setattr(live_test, "build_fleet_client", lambda: (object(), FakeHttpClient()))
- monkeypatch.setattr(live_test.Sandbox, "ephemeral", lambda *args, **kwargs: FailingEphemeral())
- monkeypatch.setattr(live_test, "wait_claims_absent", wait_claims_absent)
- monkeypatch.setattr(live_test, "collect_resource_inventory", collect_resource_inventory)
- monkeypatch.setattr(live_test, "write_summary", lambda path, summary: summaries.append(summary))
-
- with pytest.raises(ProvisioningFailure, match="provisioning failed"):
- await live_test.run_fleet_ephemeral_live()
-
- assert summaries[-1]["provisioning"] == {"attempted": True, "sandbox_yielded": False}
-
-
-async def test_pre_yield_failure_records_no_inventory_without_pool_identity(
- monkeypatch, tmp_path
-) -> None:
- from tests.live import test_fleet_ephemeral as live_test
-
- class ProvisioningFailure(Exception):
- pass
-
- summaries = []
-
- class FailingEphemeral:
- async def __aenter__(self):
- raise ProvisioningFailure("provisioning failed")
-
- async def __aexit__(self, exc_type, exc_value, traceback) -> None:
- return None
-
- class FakeHttpClient:
- async def aclose(self) -> None:
- return None
-
- async def wait_claims_absent(fleet, namespace: str) -> bool:
- return False
-
- async def collect_resource_inventory(fleet, namespace: str):
- return {"templates": [namespace], "pools": [namespace], "claims": ["claim-a"]}
-
- monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", "cua-live-pre-yield-claim")
- monkeypatch.setenv("CUA_LIVE_E2E_ARTIFACT_DIR", str(tmp_path))
- monkeypatch.setattr(live_test, "build_fleet_client", lambda: (object(), FakeHttpClient()))
- monkeypatch.setattr(live_test.Sandbox, "ephemeral", lambda *args, **kwargs: FailingEphemeral())
- monkeypatch.setattr(live_test, "wait_claims_absent", wait_claims_absent)
- monkeypatch.setattr(live_test, "collect_resource_inventory", collect_resource_inventory)
- monkeypatch.setattr(live_test, "write_summary", lambda path, summary: summaries.append(summary))
-
- with pytest.raises(ProvisioningFailure, match="provisioning failed"):
- await live_test.run_fleet_ephemeral_live()
-
- assert summaries[-1]["provisioning"] == {"attempted": True, "sandbox_yielded": False}
- assert "persistent_resources" not in summaries[-1]
- assert "cleanup_error" not in summaries[-1]
-
-
-async def test_pre_yield_missing_namespace_skips_inventory_without_pool_identity(
- monkeypatch, tmp_path
-) -> None:
- from tests.live import test_fleet_ephemeral as live_test
-
- class ProvisioningFailure(Exception):
- pass
-
- summaries = []
-
- class FailingEphemeral:
- async def __aenter__(self):
- raise ProvisioningFailure("provisioning failed")
-
- async def __aexit__(self, exc_type, exc_value, traceback) -> None:
- return None
-
- class FakeHttpClient:
- async def aclose(self) -> None:
- return None
-
- async def wait_claims_absent(fleet, namespace: str) -> bool:
- return True
-
- async def collect_resource_inventory(fleet, namespace: str):
- return {"templates": [], "pools": [], "claims": []}
-
- monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", "cua-live-pre-yield-missing")
- monkeypatch.setenv("CUA_LIVE_E2E_ARTIFACT_DIR", str(tmp_path))
- monkeypatch.setattr(live_test, "build_fleet_client", lambda: (object(), FakeHttpClient()))
- monkeypatch.setattr(live_test.Sandbox, "ephemeral", lambda *args, **kwargs: FailingEphemeral())
- monkeypatch.setattr(live_test, "wait_claims_absent", wait_claims_absent)
- monkeypatch.setattr(live_test, "collect_resource_inventory", collect_resource_inventory)
- monkeypatch.setattr(live_test, "write_summary", lambda path, summary: summaries.append(summary))
-
- with pytest.raises(ProvisioningFailure, match="provisioning failed"):
- await live_test.run_fleet_ephemeral_live()
-
- assert summaries[-1]["provisioning"] == {"attempted": True, "sandbox_yielded": False}
- assert "persistent_resources" not in summaries[-1]
- assert "cleanup_error" not in summaries[-1]
-
-
-async def test_live_runner_uses_pinned_ephemeral_configuration(monkeypatch) -> None:
- from tests.live import test_fleet_ephemeral as live_test
-
- class StopProvisioning(Exception):
- pass
-
- captured = {}
-
- class FailingEphemeral:
- async def __aenter__(self):
- raise StopProvisioning("stop after capturing arguments")
-
- async def __aexit__(self, exc_type, exc_value, traceback) -> None:
- return None
-
- class FakeHttpClient:
- async def aclose(self) -> None:
- return None
-
- def ephemeral(image, **kwargs):
- captured["image"] = image
- captured["kwargs"] = kwargs
- return FailingEphemeral()
-
- monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", "cua-live-configuration")
- monkeypatch.setattr(live_test, "build_fleet_client", lambda: (object(), FakeHttpClient()))
- monkeypatch.setattr(live_test.Sandbox, "ephemeral", ephemeral)
- monkeypatch.setattr(live_test, "write_summary", lambda path, summary: None)
-
- with pytest.raises(StopProvisioning, match="capturing arguments"):
- await live_test.run_fleet_ephemeral_live()
-
- assert captured["image"] == Image.from_registry(live_test.IMAGE)
- assert captured["kwargs"] == {
- "name": "cua-live-configuration",
- "cpu": 4,
- "memory_mb": 4096,
- "server_port": 8000,
- "time_to_start": 900,
- "telemetry_enabled": False,
- "local": False,
- }
-
-
- ("sandbox_name", "sandbox_pool_name", "message"),
- [
- ("", "cua-live-identity", "non-empty string"),
- ("cua-live-unexpected", "cua-live-identity", "claim name"),
- ("cua-live-identity", "cua-live-unexpected", "pool name"),
- ],
-)
-async def test_invalid_sandbox_identity_preserves_primary_error_and_runs_cleanup(
- monkeypatch, tmp_path, sandbox_name: str, sandbox_pool_name: str, message: str
-) -> None:
- from tests.live import test_fleet_ephemeral as live_test
-
- summaries = []
-
- class FakeSandbox:
- name = sandbox_name
- claim_name = sandbox_name
- pool_name = sandbox_pool_name
-
- class FakeEphemeral:
- async def __aenter__(self):
- return FakeSandbox()
-
- async def __aexit__(self, exc_type, exc_value, traceback) -> None:
- return None
-
- class FakeFleet:
- async def get_template(self, namespace: str, name: str):
- raise AssertionError("template inspection must not follow an invalid identity")
-
- class FakeHttpClient:
- async def aclose(self) -> None:
- return None
-
- async def wait_claims_absent(fleet, namespace: str) -> bool:
- return False
-
- async def collect_resource_inventory(fleet, namespace: str):
- return {"templates": [namespace], "pools": [namespace], "claims": ["claim-a"]}
-
- monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", "cua-live-identity")
- monkeypatch.setenv("CUA_LIVE_E2E_SOURCE_SHA", "checked-out-sha")
- monkeypatch.setenv("GITHUB_SHA", "event-sha")
- monkeypatch.setenv("CUA_LIVE_E2E_ARTIFACT_DIR", str(tmp_path))
- monkeypatch.setattr(live_test, "build_fleet_client", lambda: (FakeFleet(), FakeHttpClient()))
- monkeypatch.setattr(live_test.Sandbox, "ephemeral", lambda *args, **kwargs: FakeEphemeral())
- monkeypatch.setattr(live_test, "wait_claims_absent", wait_claims_absent)
- monkeypatch.setattr(live_test, "collect_resource_inventory", collect_resource_inventory)
- monkeypatch.setattr(live_test, "write_summary", lambda path, summary: summaries.append(summary))
-
- with pytest.raises(AssertionError, match=message):
- await live_test.run_fleet_ephemeral_live()
-
- assert summaries[-1]["source_sha"] == "checked-out-sha"
- assert summaries[-1]["claim_leak"] is True
- assert summaries[-1]["persistent_resources"]["claims"] == ["claim-a"]
- assert summaries[-1]["cleanup_error"] == {"type": "Failed"}
-
-
- ("close_fails", "summary_fails"),
- [(True, False), (False, True), (True, True)],
-)
-async def test_cleanup_error_precedes_close_and_summary_failures(
- monkeypatch, tmp_path, close_fails: bool, summary_fails: bool
-) -> None:
- from tests.live import test_fleet_ephemeral as live_test
-
- class CloseFailure(Exception):
- pass
-
- class SummaryFailure(Exception):
- pass
-
- summaries = []
-
- class FakeSandbox:
- name = "cua-live-owned"
-
- class screen:
- @staticmethod
- async def size():
- return (1024, 768)
-
- @staticmethod
- async def screenshot():
- return b"\x89PNG\r\n\x1a\n" + b"x" * 1001
-
- class shell:
- @staticmethod
- async def run(command: str):
- return SimpleNamespace(success=True, stdout="Linux\n", stderr="")
-
- class services:
- @staticmethod
- async def request(name: str, *, method: str, path: str, **_):
- return SimpleNamespace(status_code=200)
-
- class FakeEphemeral:
- async def __aenter__(self):
- return FakeSandbox()
-
- async def __aexit__(self, exc_type, exc_value, traceback) -> None:
- return None
-
- class FakeFleet:
- async def get_template(self, namespace: str, name: str):
- return object()
-
- class FakeHttpClient:
- async def aclose(self) -> None:
- if close_fails:
- raise CloseFailure("close failed")
-
- async def wait_claims_absent(fleet, namespace: str) -> bool:
- return False
-
- async def collect_resource_inventory(fleet, namespace: str):
- return {"templates": [namespace], "pools": [namespace], "claims": ["claim-a"]}
-
- def write_summary(path, summary) -> None:
- summaries.append(summary)
- if summary_fails:
- raise SummaryFailure("summary failed")
-
- monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", "cua-live-owned")
- monkeypatch.setenv("CUA_LIVE_E2E_ARTIFACT_DIR", str(tmp_path))
- monkeypatch.setattr(live_test, "build_fleet_client", lambda: (FakeFleet(), FakeHttpClient()))
- monkeypatch.setattr(live_test.Sandbox, "ephemeral", lambda *args, **kwargs: FakeEphemeral())
- monkeypatch.setattr(live_test, "assert_template_contract", lambda template, expected_port: None)
- monkeypatch.setattr(live_test, "wait_claims_absent", wait_claims_absent)
- monkeypatch.setattr(live_test, "collect_resource_inventory", collect_resource_inventory)
- monkeypatch.setattr(live_test, "write_summary", write_summary)
-
- with pytest.raises(pytest.fail.Exception, match="claims remain"):
- await live_test.run_fleet_ephemeral_live()
-
- assert summaries[-1]["cleanup_error"] == {"type": "Failed"}
- if close_fails:
- assert summaries[-1]["close_error"] == {"type": "CloseFailure"}
- if summary_fails:
- assert summaries[-1]["summary_error"] == {"type": "SummaryFailure"}
-
-
-async def test_live_runner_env_lane_uses_the_env_image_and_default_services(monkeypatch) -> None:
- from tests.live import test_fleet_ephemeral as live_test
-
- class StopProvisioning(Exception):
- pass
-
- captured = {}
-
- class FailingEphemeral:
- async def __aenter__(self):
- raise StopProvisioning("stop after capturing arguments")
-
- async def __aexit__(self, exc_type, exc_value, traceback) -> None:
- return None
-
- class FakeHttpClient:
- async def aclose(self) -> None:
- return None
-
- def ephemeral(image, **kwargs):
- captured["image"] = image
- captured["kwargs"] = kwargs
- return FailingEphemeral()
-
- monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", "cua-e2e-env-lane")
- monkeypatch.setenv("CUA_LIVE_E2E_ENV_IMAGE", "registry.example/linux:pr-1")
- monkeypatch.setattr(live_test, "build_fleet_client", lambda: (object(), FakeHttpClient()))
- monkeypatch.setattr(live_test.Sandbox, "ephemeral", ephemeral)
- monkeypatch.setattr(live_test, "write_summary", lambda path, summary: None)
-
- with pytest.raises(StopProvisioning):
- await live_test.run_fleet_ephemeral_live()
-
- assert captured["image"] == Image.from_registry("registry.example/linux:pr-1")
- assert "server_port" not in captured["kwargs"], "the env lane is daemon-agnostic"
- assert captured["kwargs"]["name"] == "cua-e2e-env-lane"
-
-
-def test_assert_env_template_contract() -> None:
- from tests.live.fleet_e2e_support import assert_env_template_contract
-
- def template(services, probes=None):
- return SimpleNamespace(
- spec=SimpleNamespace(
- vm_template=SimpleNamespace(
- services=[SimpleNamespace(name=n, target_port=p) for n, p in services],
- probes=probes,
- )
- )
- )
-
- assert_env_template_contract(template([("env", 3211), ("port-3000", 3000)]))
- with pytest.raises(AssertionError, match="3211"):
- assert_env_template_contract(template([("server", 8000)]))
- with pytest.raises(AssertionError, match="probe"):
- assert_env_template_contract(template([("env", 3211)], probes=object()))
-
-
-async def test_check_service_reachable_is_daemon_agnostic() -> None:
- from tests.live.fleet_e2e_support import check_service_reachable
-
- def sandbox(status):
- async def request(name, *, method, path, **_):
- assert (name, method, path) == ("server", "GET", "/")
- return SimpleNamespace(status_code=status)
-
- return SimpleNamespace(services=SimpleNamespace(request=request))
-
- summary: dict = {}
- await check_service_reachable(sandbox(404), "server", summary)
- assert summary["service"] == {"name": "server", "status": 404}
- with pytest.raises(AssertionError, match="502"):
- await check_service_reachable(sandbox(502), "server", {})
-
-
-def test_selected_namespace_accepts_ad_hoc_cua_e2e_names(monkeypatch) -> None:
- from tests.live import test_fleet_ephemeral as live_test
-
- monkeypatch.setenv("CUA_LIVE_E2E_NAMESPACE", "cua-e2e-live-abc123")
- assert live_test.selected_namespace() == "cua-e2e-live-abc123"
diff --git a/libs/python/cua-sandbox/tests/test_live_fleet_pool_support.py b/libs/python/cua-sandbox/tests/test_live_fleet_pool_support.py
deleted file mode 100644
index 8af67cfec8..0000000000
--- a/libs/python/cua-sandbox/tests/test_live_fleet_pool_support.py
+++ /dev/null
@@ -1,391 +0,0 @@
-from __future__ import annotations
-
-from types import SimpleNamespace
-
-import pytest
-from fleet_sdk import SdkError
-
-from tests.live import test_fleet_pool_persistent as pool_live
-
-PNG = b"\x89PNG\r\n\x1a\n" + b"0" * 2000
-
-
-def make_pool_resource(namespace: str, *, spec_replicas: int = 1, ready_replicas: int = 1):
- return SimpleNamespace(
- metadata=SimpleNamespace(namespace=namespace, name=namespace),
- spec=SimpleNamespace(replicas=spec_replicas),
- status=SimpleNamespace(ready_replicas=ready_replicas),
- )
-
-
-def not_found(operation: str = "get pool") -> SdkError.Status:
- return SdkError.Status(operation, 404, b"not found")
-
-
-def forbidden(operation: str = "get pool") -> SdkError.Status:
- # Fleet returns 403 for pool reads in namespaces that have not been
- # created yet, because RBAC is evaluated before existence.
- return SdkError.Status(operation, 403, b"forbidden")
-
-
-class FakePoolHandle:
- def __init__(self, resource) -> None:
- self._resource = resource
-
- @property
- def name(self) -> str:
- return self._resource.metadata.name
-
- @property
- def resource(self):
- return self._resource
-
-
-class FakeSandbox:
- def __init__(self, name: str, shell_stdout: str) -> None:
- self.name = name
- self.claim_name = name
- self.pool_name = name
- self.screen = SimpleNamespace(size=self._size)
- self.shell = SimpleNamespace(run=self._run)
- self.services = SimpleNamespace(request=self._request)
- self._shell_stdout = shell_stdout
- self.service_status = 200
-
- async def _request(self, name: str, *, method: str, path: str, **_):
- # "Darwin" stands for a guest check that fails on the daemon-agnostic
- # lane too: the service answers 503.
- return SimpleNamespace(status_code=503 if self._shell_stdout != "Linux" else 200)
-
- async def _size(self) -> tuple[int, int]:
- return (1024, 768)
-
- async def _run(self, command: str):
- return SimpleNamespace(success=True, stdout=self._shell_stdout, stderr="")
-
- async def screenshot(self) -> bytes:
- return PNG
-
-
-class _FakeEphemeral:
- def __init__(self, sandbox: FakeSandbox) -> None:
- self._sandbox = sandbox
-
- async def __aenter__(self) -> FakeSandbox:
- return self._sandbox
-
- async def __aexit__(self, exc_type, exc, traceback) -> bool:
- return False
-
-
-class PoolRunnerHarness:
- def __init__(self) -> None:
- self.get_results: list = []
- self.apply_calls: list[dict] = []
- self.apply_error: BaseException | None = None
- self.ephemeral_calls: list[dict] = []
- self.shell_stdout = "Linux"
- self.claims_absent: object = True
- self.claims_absent_calls: list[str] = []
- self.inventory: object = None
- self.inventory_calls: list[str] = []
- self.template_contract_calls: list[tuple] = []
- self.summaries: dict[str, dict] = {}
-
-
-def install_pool_runner(monkeypatch, tmp_path, *, mode: str, namespace: str) -> PoolRunnerHarness:
- harness = PoolRunnerHarness()
- monkeypatch.setenv("CUA_LIVE_E2E_LANE", "test")
- monkeypatch.setenv("CUA_LIVE_E2E_EVENT", "schedule")
- monkeypatch.setenv("CUA_LIVE_E2E_ARTIFACT_DIR", str(tmp_path))
- monkeypatch.setenv(pool_live.MODE_ENV[mode], namespace)
-
- class FakePool:
- @staticmethod
- async def get(name: str) -> FakePoolHandle:
- assert harness.get_results, "unexpected Pool.get call"
- result = harness.get_results.pop(0)
- if isinstance(result, BaseException):
- raise result
- return FakePoolHandle(result)
-
- @staticmethod
- async def apply(image, **kwargs) -> FakePoolHandle:
- harness.apply_calls.append({"image": image, **kwargs})
- if harness.apply_error is not None:
- raise harness.apply_error
- return FakePoolHandle(make_pool_resource(kwargs["name"]))
-
- class FakeSandboxApi:
- @staticmethod
- def ephemeral(**kwargs) -> _FakeEphemeral:
- harness.ephemeral_calls.append(kwargs)
- return _FakeEphemeral(FakeSandbox(kwargs["name"], harness.shell_stdout))
-
- class FakeFleet:
- async def get_template(self, template_namespace: str, name: str):
- return SimpleNamespace(namespace=template_namespace, name=name)
-
- class FakeHttpClient:
- async def aclose(self) -> None:
- return None
-
- async def fake_wait_claims_absent(fleet, name: str) -> bool:
- harness.claims_absent_calls.append(name)
- if isinstance(harness.claims_absent, BaseException):
- raise harness.claims_absent
- return bool(harness.claims_absent)
-
- async def fake_collect_resource_inventory(fleet, name: str):
- harness.inventory_calls.append(name)
- if isinstance(harness.inventory, BaseException):
- raise harness.inventory
- if harness.inventory is None:
- return {"templates": [name], "pools": [name], "claims": []}
- return harness.inventory
-
- def fake_assert_template_contract(template, expected_port: int) -> None:
- harness.template_contract_calls.append((template, expected_port))
-
- def fake_write_summary(path, summary) -> None:
- harness.summaries[path.name] = summary
-
- monkeypatch.setattr(pool_live, "Pool", FakePool)
- monkeypatch.setattr(pool_live, "Sandbox", FakeSandboxApi)
- monkeypatch.setattr(pool_live, "build_fleet_client", lambda: (FakeFleet(), FakeHttpClient()))
- monkeypatch.setattr(pool_live, "wait_claims_absent", fake_wait_claims_absent)
- monkeypatch.setattr(pool_live, "collect_resource_inventory", fake_collect_resource_inventory)
- monkeypatch.setattr(pool_live, "assert_template_contract", fake_assert_template_contract)
- monkeypatch.setattr(pool_live, "write_summary", fake_write_summary)
- return harness
-
-
-async def test_pool_live_runner_uses_pinned_warm_configuration(monkeypatch, tmp_path) -> None:
- namespace = "cua-live-pool-warm-test-schedule"
- harness = install_pool_runner(monkeypatch, tmp_path, mode="warm", namespace=namespace)
- harness.get_results = [
- make_pool_resource(namespace, ready_replicas=1),
- make_pool_resource(namespace, ready_replicas=1),
- ]
-
- await pool_live.run_fleet_pool_live("warm")
-
- (apply_call,) = harness.apply_calls
- assert apply_call["name"] == namespace
- assert apply_call["replicas"] == 1
- assert apply_call["cpu"] == 4
- assert apply_call["memory_mb"] == 4096
- assert apply_call["autoscaling"] is None
-
- (ephemeral_call,) = harness.ephemeral_calls
- assert ephemeral_call["pool"] == namespace
- assert isinstance(ephemeral_call["pool"], str)
- assert ephemeral_call["name"] == namespace
- assert ephemeral_call["time_to_start"] == 180
- assert ephemeral_call["telemetry_enabled"] is False
- for rejected in ("image", "cpu", "memory_mb", "server_port", "replicas"):
- assert rejected not in ephemeral_call
-
- ((_, contract_port),) = harness.template_contract_calls
- assert contract_port == 8000
- summary = harness.summaries["summary-pool-warm.json"]
- assert summary["pool_pre_existed"] is True
- assert summary["ready_replicas_before"] == 1
- assert summary["warm_bind_sla_applied"] is True
- assert summary["claims_absent"] is True
- assert summary["persistent_resources"] == {
- "templates": [namespace],
- "pools": [namespace],
- "claims": [],
- }
- assert summary["spec_replicas_after"] == 1
-
-
-async def test_pool_live_runner_uses_pinned_cold_configuration(monkeypatch, tmp_path) -> None:
- namespace = "cua-live-pool-cold-test-schedule"
- harness = install_pool_runner(monkeypatch, tmp_path, mode="cold", namespace=namespace)
- harness.get_results = [
- make_pool_resource(namespace, ready_replicas=0),
- make_pool_resource(namespace, ready_replicas=0),
- ]
-
- await pool_live.run_fleet_pool_live("cold")
-
- (apply_call,) = harness.apply_calls
- assert apply_call["replicas"] == 1
- autoscaling = apply_call["autoscaling"]
- assert autoscaling is not None
- assert autoscaling.min_pool_size == 0
- assert autoscaling.initial_pool_size == 0
- assert autoscaling.max_pool_size == 1
-
- (ephemeral_call,) = harness.ephemeral_calls
- assert ephemeral_call["time_to_start"] == 900
-
- summary = harness.summaries["summary-pool-cold.json"]
- assert summary["warm_bind_sla_applied"] is False
-
-
-async def test_pool_pre_existed_false_is_recorded_for_public_sdk_404(monkeypatch, tmp_path) -> None:
- namespace = "cua-live-pool-warm-test-schedule"
- harness = install_pool_runner(monkeypatch, tmp_path, mode="warm", namespace=namespace)
- harness.get_results = [not_found(), make_pool_resource(namespace)]
-
- await pool_live.run_fleet_pool_live("warm")
-
- summary = harness.summaries["summary-pool-warm.json"]
- assert summary["pool_pre_existed"] is False
- assert "ready_replicas_before" not in summary
- assert summary["warm_bind_sla_applied"] is False
-
-
-async def test_pool_pre_existed_false_is_recorded_for_uncreated_namespace_403(
- monkeypatch, tmp_path
-) -> None:
- namespace = "cua-live-pool-warm-test-schedule"
- harness = install_pool_runner(monkeypatch, tmp_path, mode="warm", namespace=namespace)
- harness.get_results = [forbidden(), make_pool_resource(namespace)]
-
- await pool_live.run_fleet_pool_live("warm")
-
- summary = harness.summaries["summary-pool-warm.json"]
- assert summary["pool_pre_existed"] is False
- assert "ready_replicas_before" not in summary
- assert summary["warm_bind_sla_applied"] is False
-
-
-async def test_observe_propagates_non_missing_pool_errors(monkeypatch, tmp_path) -> None:
- namespace = "cua-live-pool-warm-test-schedule"
- harness = install_pool_runner(monkeypatch, tmp_path, mode="warm", namespace=namespace)
- harness.get_results = [SdkError.Status("get pool", 500, b"failure")]
-
- with pytest.raises(SdkError.Status):
- await pool_live.run_fleet_pool_live("warm")
-
- assert harness.apply_calls == []
- summary = harness.summaries["summary-pool-warm.json"]
- assert summary["error"] == {"type": "Status"}
-
-
-async def test_empty_inventory_fails_as_unexpected(monkeypatch, tmp_path) -> None:
- namespace = "cua-live-pool-warm-test-schedule"
- harness = install_pool_runner(monkeypatch, tmp_path, mode="warm", namespace=namespace)
- harness.get_results = [make_pool_resource(namespace), make_pool_resource(namespace)]
- harness.inventory = {"templates": [], "pools": [], "claims": []}
-
- with pytest.raises(pytest.fail.Exception, match="persistent pool inventory"):
- await pool_live.run_fleet_pool_live("warm")
-
- summary = harness.summaries["summary-pool-warm.json"]
- assert summary["unexpected_inventory"] is True
-
-
-async def test_claim_leak_fails_and_is_recorded(monkeypatch, tmp_path) -> None:
- namespace = "cua-live-pool-warm-test-schedule"
- harness = install_pool_runner(monkeypatch, tmp_path, mode="warm", namespace=namespace)
- harness.get_results = [make_pool_resource(namespace), make_pool_resource(namespace)]
- harness.claims_absent = False
-
- with pytest.raises(pytest.fail.Exception, match="claims remain"):
- await pool_live.run_fleet_pool_live("warm")
-
- summary = harness.summaries["summary-pool-warm.json"]
- assert summary["claim_leak"] is True
-
-
-async def test_warm_sla_not_applied_without_ready_replicas(monkeypatch, tmp_path) -> None:
- namespace = "cua-live-pool-warm-test-schedule"
- harness = install_pool_runner(monkeypatch, tmp_path, mode="warm", namespace=namespace)
- harness.get_results = [
- make_pool_resource(namespace, ready_replicas=0),
- make_pool_resource(namespace, ready_replicas=1),
- ]
- monkeypatch.setattr(pool_live, "WARM_BIND_SLA_SECONDS", -1.0)
-
- await pool_live.run_fleet_pool_live("warm")
-
- summary = harness.summaries["summary-pool-warm.json"]
- assert summary["warm_bind_sla_applied"] is False
- assert "error" not in summary
-
-
-async def test_warm_sla_enforced_with_ready_replicas(monkeypatch, tmp_path) -> None:
- namespace = "cua-live-pool-warm-test-schedule"
- harness = install_pool_runner(monkeypatch, tmp_path, mode="warm", namespace=namespace)
- harness.get_results = [
- make_pool_resource(namespace, ready_replicas=1),
- make_pool_resource(namespace, ready_replicas=1),
- ]
- monkeypatch.setattr(pool_live, "WARM_BIND_SLA_SECONDS", -1.0)
-
- with pytest.raises(AssertionError, match="pre-provisioned warm claim"):
- await pool_live.run_fleet_pool_live("warm")
-
- summary = harness.summaries["summary-pool-warm.json"]
- assert summary["warm_bind_sla_applied"] is True
- assert summary["error"] == {"type": "AssertionError"}
-
-
-async def test_cleanup_failure_does_not_mask_primary_failure(monkeypatch, tmp_path) -> None:
- namespace = "cua-live-pool-warm-test-schedule"
- harness = install_pool_runner(monkeypatch, tmp_path, mode="warm", namespace=namespace)
- harness.get_results = [make_pool_resource(namespace), make_pool_resource(namespace)]
- harness.shell_stdout = "Darwin"
- harness.inventory = RuntimeError("inventory unavailable")
-
- with pytest.raises(AssertionError):
- await pool_live.run_fleet_pool_live("warm")
-
- summary = harness.summaries["summary-pool-warm.json"]
- assert summary["error"] == {"type": "AssertionError"}
- assert summary["cleanup_error"] == {"type": "RuntimeError"}
-
-
-async def test_apply_failure_skips_persistence_verification(monkeypatch, tmp_path) -> None:
- namespace = "cua-live-pool-warm-test-schedule"
- harness = install_pool_runner(monkeypatch, tmp_path, mode="warm", namespace=namespace)
- harness.get_results = [not_found()]
- harness.apply_error = RuntimeError("apply rejected")
-
- with pytest.raises(RuntimeError, match="apply rejected"):
- await pool_live.run_fleet_pool_live("warm")
-
- assert harness.claims_absent_calls == []
- assert harness.inventory_calls == []
- assert harness.ephemeral_calls == []
- summary = harness.summaries["summary-pool-warm.json"]
- assert summary["provisioning"] == {"pool_applied": False, "sandbox_yielded": False}
- assert summary["error"] == {"type": "RuntimeError"}
-
-
-def test_selected_pool_namespace_rejects_foreign_prefix(monkeypatch) -> None:
- monkeypatch.setenv("CUA_LIVE_E2E_POOL_WARM_NAMESPACE", "cua-live-warm-other")
-
- with pytest.raises(ValueError, match="must start with cua-live-pool-warm-"):
- pool_live.selected_pool_namespace("warm")
-
-
-def test_selected_pool_namespace_requires_dns_1123_label(monkeypatch) -> None:
- monkeypatch.setenv("CUA_LIVE_E2E_POOL_COLD_NAMESPACE", "cua-live-pool-cold-" + "x" * 60)
-
- with pytest.raises(ValueError, match="DNS-1123"):
- pool_live.selected_pool_namespace("cold")
-
-
-def test_selected_pool_namespace_builds_default_from_lane_and_event(monkeypatch) -> None:
- monkeypatch.delenv("CUA_LIVE_E2E_POOL_WARM_NAMESPACE", raising=False)
- monkeypatch.setenv("CUA_LIVE_E2E_LANE", "main-source")
- monkeypatch.setenv("CUA_LIVE_E2E_EVENT", "schedule")
-
- assert pool_live.selected_pool_namespace("warm") == "cua-live-pool-warm-main-source-schedule"
diff --git a/libs/python/cua-sandbox/tests/test_network.py b/libs/python/cua-sandbox/tests/test_network.py
index 1498995e3b..3d11b39e18 100644
--- a/libs/python/cua-sandbox/tests/test_network.py
+++ b/libs/python/cua-sandbox/tests/test_network.py
@@ -51,10 +51,7 @@ def test_android_cmd_has_egress_unless_restricted():
assert net(none).startswith("user,id=net0,restrict=on,hostfwd=")
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-def test_cloud_sandboxes_refuse_network_none():
- with pytest.raises(Unsupported, match="network='none'"):
- asyncio.run(Sandbox.create(Image.linux(), local=False, network="none"))
+def test_unknown_network_modes_are_refused():
with pytest.raises(ValueError):
asyncio.run(Sandbox.create(Image.linux(), local=True, network="host"))
diff --git a/libs/python/cua-sandbox/tests/test_osworld_fleet.py b/libs/python/cua-sandbox/tests/test_osworld_fleet.py
deleted file mode 100644
index 34cc059087..0000000000
--- a/libs/python/cua-sandbox/tests/test_osworld_fleet.py
+++ /dev/null
@@ -1,126 +0,0 @@
-"""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
- # None is the daemon-agnostic default: the pool publishes cua-spacesd
- # as ``env``; only a declared server_port or an OSWorld disk adds ``server``.
- assert default_server_port(plain) is None
- assert default_server_port(plain, 8000) == 8000
- assert default_server_port(osworld, 5555) == 5555
- assert default_server_port(None) is None
-
-
-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/libs/python/cua-sandbox/tests/test_p2_parity.py b/libs/python/cua-sandbox/tests/test_p2_parity.py
index 9433038f4b..73f44f8863 100644
--- a/libs/python/cua-sandbox/tests/test_p2_parity.py
+++ b/libs/python/cua-sandbox/tests/test_p2_parity.py
@@ -1,10 +1,5 @@
-"""P2 sandbox parity: sidecars, private registry secrets, cloud image layers
-and warm capacity for the canonical images (hermetic).
-
-The pure tests need nothing; the ``fleet`` ones run the native SDK against
-the loopback fake Fleet (``cua-test-fixtures``), which admits sidecars like
-Fleet does (every runtime, reserved service names). Cloud image layers still
-fail with the "not deployed yet" error (Fleet's builder does not run them). The native option objects are checked by capturing what
+"""P2 sandbox parity: sidecars, private registry secrets and image layers
+(hermetic). The native option objects are checked by capturing what
``cua_sandbox`` hands the SDK.
"""
@@ -14,11 +9,9 @@ import asyncio
import importlib
import pytest
-from cua_sandbox import Container, Image, RegistrySecret, Sandbox, _autopool
+from cua_sandbox import Container, Image, RegistrySecret, Sandbox
from cua_sandbox.containers import image_build, sidecars_of
-from tests._native_fleet import fleet # noqa: F401 - fixture
-
sandbox_module = importlib.import_module("cua_sandbox.sandbox")
IMAGE = "registry.example/workspace@sha256:0123"
@@ -98,15 +91,6 @@ def test_native_conversions():
image_build(Image.from_registry("python:3.12-slim")._add_layer({"type": "brew_install"}))
-def test_warm_is_left_to_the_sdk_unless_chosen(monkeypatch):
- monkeypatch.delenv("CUA_FLEET_WARM", raising=False)
- assert _autopool.config().warm_set is False
- assert _autopool.config(warm=False).warm_set is True
- monkeypatch.setenv("CUA_FLEET_WARM", "1")
- cfg = _autopool.config()
- assert cfg.warm and cfg.warm_set
-
-
def test_the_native_sdk_decides_warm_for_canonical_images():
n = pytest.importorskip("cua")._native
assert n.image_alias("linux") is not None
@@ -120,130 +104,6 @@ class _Captured(Exception):
pass
-def _capture(monkeypatch) -> list:
- seen: list = []
-
- class _Sandboxes:
- async def create(self, options):
- seen.append(options)
- raise _Captured()
-
- class _Cua:
- def sandboxes(self):
- return _Sandboxes()
-
- monkeypatch.setattr(_autopool, "_native_cua", lambda: _Cua())
- monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: api_key is None))
- monkeypatch.setattr(sandbox_module, "_TELEMETRY_AVAILABLE", False)
- monkeypatch.delenv("CUA_FLEET_WARM", raising=False)
- return seen
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-def test_cloud_create_hands_sidecars_secret_and_layers_to_the_sdk(monkeypatch):
- pytest.importorskip("cua")
- seen = _capture(monkeypatch)
- img = Image.from_registry("ghcr.io/me/app:1", secret=RegistrySecret("me", "tok")).pip_install(
- "mcp"
- )
- with pytest.raises(_autopool.AutoPoolError):
- asyncio.run(
- Sandbox.create(
- img,
- sidecars=[Container("redis:7-alpine", ports=[6379])],
- services={"db": 6379},
- local=False,
- )
- )
- [o] = seen
- assert [s.image for s in o.sidecars] == ["redis:7-alpine"]
- assert o.registry_secret.username == "me"
- assert len(o.build.layers) == 1
- assert o.services["db"] == 6379
- assert o.cloud.warm is None, "unset: the SDK decides (canonical images warm)"
- assert (o.on, o.runtime) == ("cloud", "gvisor"), "a build's output is a container rootfs"
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-def test_cloud_create_passes_an_explicit_warm(monkeypatch):
- pytest.importorskip("cua")
- seen = _capture(monkeypatch)
- with pytest.raises(_autopool.AutoPoolError):
- asyncio.run(Sandbox.create(Image.from_registry(IMAGE), warm=False, local=False))
- assert seen[0].cloud.warm is False
- assert seen[0].sidecars == [] and seen[0].registry_secret is None and seen[0].build is None
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-def test_an_existing_pool_compares_sidecars_with_its_template(monkeypatch):
- from cua_sandbox import Pool, PoolSpecMismatch
-
- seen: list = []
-
- async def check(name, spec):
- seen.append((name, spec))
- raise PoolSpecMismatch("pool cua-e2e-x's template differs: sidecars")
-
- monkeypatch.setattr(Pool, "check", staticmethod(check))
- with pytest.raises(PoolSpecMismatch, match="sidecars"):
- asyncio.run(Sandbox.create(pool="cua-e2e-x", sidecars=["redis:7-alpine"], local=False))
- [(name, spec)] = seen
- assert name == "cua-e2e-x"
- assert [c.image for c in sidecars_of(spec.sidecars)] == ["redis:7-alpine"]
-
-
-# ── end to end on the fake Fleet ─────────────────────────────────────────
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_cloud_vm_images_take_sidecars(fleet): # noqa: F811
- # IMAGE is a KubeVirt containerDisk in the fake registry: Fleet runs its
- # sidecars in a companion pod, addressed by name like on gVisor.
- sb = await Sandbox.create(
- Image.from_registry(IMAGE),
- sidecars=[Container("redis:7-alpine", ports=[6379], name="db")],
- services={"db": 6379},
- local=False,
- )
- try:
- client = fleet()
- try:
- template = await client.get_template(sb.pool_name, sb.pool_name)
- finally:
- await client.close()
- assert str(template.spec.vm_template.runtime).lower().endswith("kubevirt")
- assert "db" in [s.name for s in template.spec.vm_template.services]
- finally:
- await sb.close()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
[email protected]("reserved", ["main", "sidecars", "sc"])
-async def test_sidecars_reserve_service_names_before_creating_anything(
- fleet, # noqa: F811 - fixture
- reserved,
-):
- with pytest.raises(Exception, match="reserved"):
- await Sandbox.create(
- Image.from_registry(IMAGE),
- sidecars=[Container("redis:7-alpine", ports=[6379], name="db")],
- services={reserved: 6379},
- local=False,
- )
- client = fleet()
- try:
- names = [n.name for n in await client.list_namespaces()]
- finally:
- await client.close()
- assert not [n for n in names if n.startswith("cua-auto-")], "nothing was created"
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_cloud_layers_fail_clearly_until_fleet_builds_them(fleet): # noqa: F811
- with pytest.raises(Exception, match="not deployed yet"):
- await Sandbox.create(Image.from_registry(IMAGE).pip_install("mcp"), local=False)
-
-
def test_local_runc_opt_in_reaches_the_sdk(monkeypatch, tmp_path):
"""runtime="runc" is the explicit opt-in a local sidecar group needs."""
pytest.importorskip("cua")
diff --git a/libs/python/cua-sandbox/tests/test_placement.py b/libs/python/cua-sandbox/tests/test_placement.py
index dd5151d87e..4d050d0627 100644
--- a/libs/python/cua-sandbox/tests/test_placement.py
+++ b/libs/python/cua-sandbox/tests/test_placement.py
@@ -2,17 +2,16 @@
on ``Sandbox.create``, hermetically.
Nothing starts: the native SDK's ``sandboxes().create`` is a recorder that
-raises once it has the options, and the managed cloud path is a stub. The
-user defaults come from the real native settings (``cua.config_get``) over
-the temp ``CUA_HOME`` conftest gives every test, so precedence is tested
-end to end: explicit > env > ``$CUA_HOME/config.toml`` > built-in.
+raises once it has the options. The user defaults come from the real native
+settings (``cua.config_get``) over the temp ``CUA_HOME`` conftest gives every
+test, so precedence is tested end to end: explicit > env >
+``$CUA_HOME/config.toml`` > built-in.
"""
from __future__ import annotations
import importlib
import os
-import warnings
from types import SimpleNamespace
from typing import Any
@@ -23,7 +22,6 @@ from cua_sandbox import (
InvalidArgument,
InvalidPlacement,
Sandbox,
- _autopool,
_placement,
)
from cua_sandbox.runtime import native as native_rt
@@ -59,20 +57,6 @@ def local_sdk(monkeypatch):
return seen
-def cloud(monkeypatch):
- """The managed cloud path: records ``_acquire_managed``'s arguments."""
- seen: list = []
-
- async def managed(image, **kwargs):
- seen.append({"image": image, **kwargs})
- raise _Captured()
-
- monkeypatch.setattr(sandbox_module, "_acquire_managed", managed)
- monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: True))
- return seen
-
-
@pytest.fixture
def notice(monkeypatch, caplog):
monkeypatch.setattr(_placement, "_default_notice_shown", False)
@@ -95,55 +79,30 @@ def _temp_config():
# ── precedence: explicit > env > config > built-in ───────────────────────
-async def test_builtin_default_is_local_with_the_notice(local_sdk, cloud, notice):
+async def test_builtin_default_is_local_with_the_notice(local_sdk, notice):
with pytest.raises(_Captured):
await Sandbox.create(ROOTFS, telemetry_enabled=False)
- assert local_sdk[0].on == "local" and not cloud
+ assert local_sdk[0].on == "local"
[message] = notice()
assert "defaulting to a local sandbox" in message and "CUA_QUIET_DEFAULT=1" in message
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_config_default_on_cloud_sends_create_to_the_cloud(local_sdk, cloud, notice):
- cua.config_set("default.on", "cloud")
- with warnings.catch_warnings():
- warnings.simplefilter("error", DeprecationWarning)
- with pytest.raises(_Captured):
- await Sandbox.create(Image.linux(), telemetry_enabled=False)
- assert cloud and not local_sdk
- assert "cua config set default.on local" in cloud[0]["hint"]
- assert not notice(), "no local notice when the default was chosen"
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_env_beats_config(monkeypatch, local_sdk, cloud, notice):
- cua.config_set("default.on", "cloud")
+async def test_env_beats_config(monkeypatch, local_sdk, notice):
+ cua.config_set("default.on", "aws")
monkeypatch.setenv("CUA_DEFAULT_ON", "local")
with pytest.raises(_Captured):
await Sandbox.create(ROOTFS, telemetry_enabled=False)
- assert local_sdk and not cloud
+ assert local_sdk
assert not notice(), "the notice is only for the built-in default"
- monkeypatch.setenv("CUA_DEFAULT_ON", "cloud")
- with pytest.raises(_Captured):
- await Sandbox.create(Image.linux(), telemetry_enabled=False)
- assert "CUA_DEFAULT_ON" in cloud[0]["hint"]
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_explicit_beats_env(monkeypatch, local_sdk, cloud):
+async def test_explicit_beats_env(monkeypatch, local_sdk):
monkeypatch.setenv("CUA_DEFAULT_ON", "cloud")
with pytest.raises(_Captured):
await Sandbox.create(ROOTFS, local=True, telemetry_enabled=False)
with pytest.raises(_Captured):
await Sandbox.create(ROOTFS, on="local", telemetry_enabled=False)
- assert len(local_sdk) == 2 and not cloud
- monkeypatch.setenv("CUA_DEFAULT_ON", "local")
- with pytest.raises(_Captured):
- await Sandbox.create(Image.linux(), on="cloud", telemetry_enabled=False)
- with pytest.raises(_Captured):
- await Sandbox.create(Image.linux(), local=False, telemetry_enabled=False)
- assert len(cloud) == 2
- assert cloud[0]["hint"] is None, "an explicit cloud gets no default hint"
+ assert len(local_sdk) == 2
async def test_default_kind_and_runtime_come_from_config(local_sdk):
@@ -166,7 +125,7 @@ async def test_a_default_runtime_that_does_not_fit_is_skipped(monkeypatch, local
# ── on / local ───────────────────────────────────────────────────────────
-async def test_on_and_a_contradicting_local_is_invalid(local_sdk, cloud):
+async def test_on_and_a_contradicting_local_is_invalid(local_sdk):
with pytest.raises(InvalidArgument, match="contradict"):
await Sandbox.create(ROOTFS, on="cloud", local=True)
with pytest.raises(InvalidArgument, match="contradict"):
@@ -175,28 +134,11 @@ async def test_on_and_a_contradicting_local_is_invalid(local_sdk, cloud):
await Sandbox.create(ROOTFS, on="local", cloud=CloudOptions(warm=True))
with pytest.raises(InvalidArgument, match="contradict"):
await Sandbox.create(ROOTFS, local=True, cloud=CloudOptions(warm=True))
- assert not local_sdk and not cloud
+ assert not local_sdk
with pytest.raises(_Captured):
await Sandbox.create(ROOTFS, on="local", local=True, telemetry_enabled=False)
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_unknown_locations_list_the_valid_ones():
- with pytest.raises(InvalidPlacement, match="valid on: local, cloud"):
- await Sandbox.create(ROOTFS, on="fleet")
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_cloud_only_arguments_imply_the_cloud(local_sdk, cloud):
- with pytest.warns(DeprecationWarning, match="local=False"):
- with pytest.raises(_Captured):
- await Sandbox.create(Image.linux(), max_pool_size=3, telemetry_enabled=False)
- with pytest.raises(_Captured):
- await Sandbox.create(Image.linux(), cloud=CloudOptions(warm=True), telemetry_enabled=False)
- assert len(cloud) == 2 and not local_sdk
- assert cloud[0]["hint"] is None
-
-
# ── kind and runtime reach the SDK ───────────────────────────────────────
@@ -222,55 +164,21 @@ async def test_ephemeral_takes_the_same_placement(local_sdk):
assert (local_sdk[0].kind, local_sdk[0].runtime) == ("container", "gvisor")
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_cloud_kind_and_runtime_reach_the_managed_pool(cloud):
- with pytest.raises(_Captured):
- await Sandbox.create(Image.linux(), on="cloud", kind="vm", telemetry_enabled=False)
- with pytest.raises(_Captured):
- await Sandbox.create(Image.linux(), on="cloud", runtime="gvisor", telemetry_enabled=False)
- vm, gvisor = cloud
- assert vm["image"].kind == "vm" and vm["fleet_runtime"] is None
- assert gvisor["image"].kind == "container" and gvisor["fleet_runtime"] == "gvisor"
-
-
-async def test_autopool_hands_kind_and_runtime_to_the_sdk(monkeypatch):
- seen: list = []
-
- class _Sandboxes:
- async def create(self, options):
- seen.append(options)
- raise _Captured()
-
- monkeypatch.setattr(
- _autopool, "_native_cua", lambda: SimpleNamespace(sandboxes=lambda: _Sandboxes())
- )
- with pytest.raises(_autopool.AutoPoolError):
- await _autopool.acquire(
- Image.from_registry("registry.example/app@sha256:0123", kind="vm"),
- runtime="kubevirt",
- )
- [options] = seen
- assert (options.on, options.kind, options.runtime) == ("cloud", "vm", "kubevirt")
-
-
# ── InvalidPlacement ─────────────────────────────────────────────────────
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_invalid_combinations_list_the_valid_values(local_sdk, cloud):
+async def test_invalid_combinations_list_the_valid_values(local_sdk):
with pytest.raises(InvalidPlacement, match="valid runtime: auto, gvisor, runc"):
await Sandbox.create(ROOTFS, on="local", kind="container", runtime="qemu")
with pytest.raises(InvalidPlacement, match="not available locally") as info:
await Sandbox.create(ROOTFS, on="local", runtime="kubevirt")
assert isinstance(info.value, InvalidArgument)
- with pytest.raises(InvalidPlacement, match="valid runtime: auto, kubevirt"):
- await Sandbox.create(Image.linux(), on="cloud", kind="vm", runtime="gvisor")
with pytest.raises(InvalidPlacement, match="valid kind: auto, container, vm"):
await Sandbox.create(ROOTFS, on="local", kind="pod")
# The image's own kind against the engine.
with pytest.raises(InvalidPlacement):
await Sandbox.create(Image.linux(kind="vm"), on="local", runtime="runc")
- assert not local_sdk and not cloud
+ assert not local_sdk
async def test_an_sdk_placement_error_surfaces_as_invalid_placement(monkeypatch):
@@ -287,28 +195,6 @@ async def test_an_sdk_placement_error_surfaces_as_invalid_placement(monkeypatch)
await Sandbox.create(ROOTFS, on="local", telemetry_enabled=False)
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_missing_cloud_credentials_from_a_default_say_how_to_switch_back(monkeypatch):
- n = cua._native
-
- class _Sandboxes:
- async def create(self, options):
- raise n.CuaError.ProviderNotConfigured(
- "Fleet credentials missing: run `cua auth login`"
- )
-
- monkeypatch.setattr(
- _autopool, "_native_cua", lambda: SimpleNamespace(sandboxes=lambda: _Sandboxes())
- )
- monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: True))
- cua.config_set("default.on", "cloud")
- with pytest.raises(ValueError, match="credentials missing") as info:
- await Sandbox.create(Image.linux(), telemetry_enabled=False)
- message = str(info.value)
- assert "cua auth login" in message
- assert "switch back with `cua config set default.on local`" in message
-
-
# ── the legacy Runtime object ────────────────────────────────────────────
@@ -322,7 +208,7 @@ class _Recorder(DockerRuntime):
raise _Captured()
-async def test_a_runtime_object_still_runs_locally(monkeypatch, cloud, notice):
+async def test_a_runtime_object_still_runs_locally(monkeypatch, notice):
calls: list = []
monkeypatch.setenv("CUA_DEFAULT_ON", "cloud")
with pytest.raises(_Captured):
@@ -330,7 +216,7 @@ async def test_a_runtime_object_still_runs_locally(monkeypatch, cloud, notice):
# Shipped in 0.8.0: local=False with a Runtime object ran it locally.
with pytest.raises(_Captured):
await Sandbox.create(ROOTFS, runtime=_Recorder(calls), local=False, telemetry_enabled=False)
- assert len(calls) == 2 and not cloud and not notice()
+ assert len(calls) == 2 and not notice()
for _, opts in calls:
assert "kind" not in opts and "runtime" not in opts, "the adapter decides"
with pytest.raises(InvalidArgument, match="on this machine"):
@@ -341,19 +227,17 @@ async def test_a_runtime_object_still_runs_locally(monkeypatch, cloud, notice):
async def test_list_takes_location(monkeypatch):
+ from cua_sandbox._ended import CloudEnded
from cua_sandbox.sandbox import SandboxInfo
async def local_rows(cls):
return [SandboxInfo(name="a", status="running", source="container", location="local")]
- async def cloud_rows(cls, *, api_key=None):
- return [SandboxInfo(name="b", status="running", source="fleet", location="cloud")]
-
monkeypatch.setattr(Sandbox, "_list_local", classmethod(local_rows))
- monkeypatch.setattr(Sandbox, "_list_cloud", classmethod(cloud_rows))
assert [r.id for r in await Sandbox.list(location="local")] == ["local:a"]
- assert [r.id for r in await Sandbox.list(location="cloud")] == ["cloud:b"]
assert [r.id for r in await Sandbox.list(local=True)] == ["local:a"]
+ with pytest.raises(CloudEnded):
+ await Sandbox.list(location="cloud")
with pytest.raises(InvalidArgument, match="contradict"):
await Sandbox.list(location="cloud", local=True)
with pytest.raises(InvalidArgument):
diff --git a/libs/python/cua-sandbox/tests/test_pool.py b/libs/python/cua-sandbox/tests/test_pool.py
deleted file mode 100644
index 162617513b..0000000000
--- a/libs/python/cua-sandbox/tests/test_pool.py
+++ /dev/null
@@ -1,1313 +0,0 @@
-from __future__ import annotations
-
-from types import SimpleNamespace
-
-import fleet_sdk
-import pytest
-from cua_sandbox import (
- ClaimSpec,
- CreatePoolRequest,
- CreatePoolRequestBuilder,
- CreateTemplateRequest,
- CreateTemplateRequestBuilder,
- Firmware,
- Image,
- OsGymSandboxTemplateSpecBuilder,
- OsGymSandboxWarmPoolSpecBuilder,
- Pool,
- PoolAccessDeniedError,
- RuntimeKind,
- SandboxServiceBuilder,
- SandboxTemplateRefBuilder,
- ServiceProtocol,
- Template,
- VmTemplate,
- VmTemplateBuilder,
-)
-from cua_sandbox.pool import _ClaimHandle
-from cua_sandbox.sync import Pool as SyncPool
-from cua_sandbox.sync import Template as SyncTemplate
-from cua_sandbox.transport.fleet_cloud import _FleetClient
-from fleet_sdk import Sandbox as FleetSandbox
-from fleet_sdk import SdkError, WarmPoolAutoscaling
-
-
-def test_public_pool_schema_exports_runtime_kind() -> None:
- assert RuntimeKind.KUBEVIRT.value == 0
-
-
-def test_public_pool_schema_exports_generated_builders() -> None:
- service = SandboxServiceBuilder().name("server").target_port(8000).build()
- vm_template = (
- VmTemplateBuilder()
- .container_disk_image("registry.example/workspace:latest")
- .services([service])
- .build()
- )
- template_request = (
- CreateTemplateRequestBuilder()
- .namespace("default")
- .name("workspace")
- .spec(OsGymSandboxTemplateSpecBuilder().vm_template(vm_template).build())
- .build()
- )
- pool_request = (
- CreatePoolRequestBuilder()
- .namespace("default")
- .spec(
- OsGymSandboxWarmPoolSpecBuilder()
- .replicas(1)
- .sandbox_template_ref(SandboxTemplateRefBuilder().name("workspace").build())
- .build()
- )
- .build()
- )
-
- assert template_request.spec.vm_template.services == [service]
- assert pool_request.spec.sandbox_template_ref.name == "workspace"
-
-
-def pool_request(
- *,
- name: str = "foo",
- template_name: str | None = None,
- replicas: int = 1,
-) -> CreatePoolRequest:
- template_ref = SandboxTemplateRefBuilder().name(template_name or name).build()
- spec = (
- OsGymSandboxWarmPoolSpecBuilder()
- .replicas(replicas)
- .sandbox_template_ref(template_ref)
- .build()
- )
- return CreatePoolRequestBuilder().namespace(name).spec(spec).build()
-
-
-def template_request(
- *,
- name: str = "foo",
- image: str = "example:latest",
- services: dict[str, int] | None = None,
- vm_template: VmTemplate | None = None,
-) -> CreateTemplateRequest:
- if vm_template is None:
- built_services = [
- SandboxServiceBuilder()
- .name(service_name)
- .target_port(port)
- .protocol(ServiceProtocol.TCP)
- .build()
- for service_name, port in (services or {"server": 8000}).items()
- ]
- vm_template = (
- VmTemplateBuilder()
- .container_disk_image(image)
- .image_pull_secret("ecr-credentials")
- .services(built_services)
- .build()
- )
-
- spec = OsGymSandboxTemplateSpecBuilder().vm_template(vm_template).build()
- return CreateTemplateRequestBuilder().namespace(name).name(name).spec(spec).build()
-
-
-def fleet_pool(name: str = "foo") -> SimpleNamespace:
- return SimpleNamespace(
- metadata=SimpleNamespace(name=name, namespace=name),
- spec=SimpleNamespace(
- replicas=1,
- sandbox_template_ref=SimpleNamespace(name=name),
- autoscaling=None,
- ),
- status=SimpleNamespace(replicas=1, ready_replicas=1, selector=None),
- )
-
-
-def fleet_template(name: str = "foo") -> SimpleNamespace:
- return SimpleNamespace(
- metadata=SimpleNamespace(name=name, namespace=name),
- spec=SimpleNamespace(vm_template=SimpleNamespace(services=[])),
- )
-
-
-def fake_claim(namespace: str = "foo", name: str = "claim-1") -> SimpleNamespace:
- return SimpleNamespace(metadata=SimpleNamespace(namespace=namespace, name=name))
-
-
-class FakeFleetClient:
- def __init__(
- self,
- *,
- existing: object | None = None,
- reconcile_error: Exception | None = None,
- release_error: Exception | None = None,
- ):
- self.existing = existing
- self.reconcile_error = reconcile_error
- self.release_error = release_error
- self.reconciled: list[object] = []
- self.reconciled_templates: list[object] = []
- self.claims: list[object] = []
- self.released: list[str] = []
- self.deleted_pools: list[str] = []
- self.deleted_templates: list[str] = []
- self.renewed: list[tuple[str, str]] = []
- self.service_requests: list[object] = []
- self.signed_url_creates: list[tuple[object, str, str | None, int]] = []
- self.signed_url_revocations: list[object] = []
- self.wait_calls = 0
- self.closed = False
-
- async def reconcile_pool(self, request: object) -> object:
- self.reconciled.append(request)
- if self.reconcile_error:
- raise self.reconcile_error
- return self.existing or fleet_pool(request.namespace)
-
- async def reconcile_template(self, request: object) -> object:
- self.reconciled_templates.append(request)
- if self.reconcile_error:
- raise self.reconcile_error
- return self.existing or fleet_template(request.name)
-
- async def get_pool(self, name: str) -> object:
- return self.existing or fleet_pool(name)
-
- async def create_claim(self, request: object) -> object:
- self.claims.append(request)
- return fake_claim()
-
- async def wait_claim(self, claim: object) -> FleetSandbox:
- assert claim.metadata.name == "claim-1"
- self.wait_calls += 1
- return FleetSandbox(
- namespace="foo",
- claim="claim-1",
- name="sandbox-1",
- services=["server", "mcp"],
- )
-
- async def wait_service_ready(self, sandbox, service, time_to_start=None) -> None:
- return None
-
- async def renew_claim(self, claim: object, shutdown_time: str) -> object:
- self.renewed.append((claim.metadata.name, shutdown_time))
- return claim
-
- async def service_request(self, sandbox, service, path, request):
- self.service_requests.append((sandbox, service, path, request))
- return SimpleNamespace(status=200, headers=[], body=b'{"result":"ok"}')
-
- async def create_signed_service_url(
- self,
- sandbox,
- service,
- *,
- label=None,
- expires_in_seconds,
- ):
- self.signed_url_creates.append((sandbox, service, label, expires_in_seconds))
- return signed_service_url()
-
- async def list_signed_service_urls(self, sandbox):
- return [signed_service_url()]
-
- async def revoke_signed_service_url(self, signed_url):
- self.signed_url_revocations.append(signed_url)
-
- async def delete_claim(self, claim: object) -> None:
- self.released.append(claim.metadata.name)
- if self.release_error:
- raise self.release_error
-
- async def delete_pool(self, pool: object) -> None:
- self.deleted_pools.append(pool.metadata.name)
-
- async def delete_template(self, template: object) -> None:
- self.deleted_templates.append(template.metadata.name)
-
- async def close(self) -> None:
- self.closed = True
-
-
-def signed_service_url() -> SimpleNamespace:
- return SimpleNamespace(
- id="31e1c9bb-8cc9-4c50-9cf4-51798b6978e4",
- namespace="foo",
- claim="claim-1",
- sandbox="sandbox-1",
- service="mcp",
- label="Customer demo",
- url="https://signed.example/link",
- created_at="2026-09-01T12:00:00Z",
- expires_at="2026-09-01T13:00:00Z",
- revoked_at=None,
- )
-
-
-async def test_fleet_client_get_pool_uses_name_lookup_without_listing() -> None:
- expected = fleet_pool()
-
- class GeneratedClient:
- async def get_pool(self, name: str) -> object:
- assert name == "foo"
- return expected
-
- client = object.__new__(_FleetClient)
- client._client = GeneratedClient()
-
- async def fail_if_listed() -> list[object]:
- raise AssertionError("get_pool must not list pools")
-
- client.list_pools = fail_if_listed
-
- assert await client.get_pool("foo") is expected
-
-
-async def test_fleet_client_reconcile_pool_delegates_to_generated_client() -> None:
- expected = fleet_pool()
-
- class GeneratedClient:
- async def reconcile_pool(self, request: object) -> object:
- assert request == "desired"
- return expected
-
- client = object.__new__(_FleetClient)
- client._client = GeneratedClient()
-
- assert await client.reconcile_pool("desired") is expected
-
-
-async def test_fleet_client_reconcile_template_delegates_to_generated_client() -> None:
- expected = fleet_template()
-
- class GeneratedClient:
- async def reconcile_template(self, request: object) -> object:
- assert request == "desired"
- return expected
-
- client = object.__new__(_FleetClient)
- client._client = GeneratedClient()
-
- assert await client.reconcile_template("desired") is expected
-
-
-async def test_fleet_client_manages_signed_service_urls(monkeypatch) -> None:
- calls: list[tuple[str, object]] = []
-
- class RequestBuilder:
- def __init__(self):
- self.values = {}
-
- def sandbox(self, value):
- self.values["sandbox"] = value
- return self
-
- def service(self, value):
- self.values["service"] = value
- return self
-
- def label(self, value):
- self.values["label"] = value
- return self
-
- def expires_in_seconds(self, value):
- self.values["expires_in_seconds"] = value
- return self
-
- def build(self):
- return SimpleNamespace(**self.values)
-
- class GeneratedSignedServiceURL(SimpleNamespace):
- def __init__(self, **values):
- super().__init__(**values)
-
- class GeneratedClient:
- async def create_signed_service_url(self, request):
- calls.append(("create", request))
- return signed_service_url()
-
- async def list_signed_service_urls(self, sandbox):
- calls.append(("list", sandbox))
- return [signed_service_url()]
-
- async def revoke_signed_service_url(self, signed_url):
- calls.append(("revoke", signed_url))
-
- monkeypatch.setattr(
- fleet_sdk,
- "CreateSignedServiceUrlRequestBuilder",
- RequestBuilder,
- raising=False,
- )
- monkeypatch.setattr(fleet_sdk, "SignedServiceUrl", GeneratedSignedServiceURL, raising=False)
- client = object.__new__(_FleetClient)
- client._client = GeneratedClient()
- sandbox = FleetSandbox(
- namespace="foo",
- claim="claim-1",
- name="sandbox-1",
- services=["mcp"],
- )
-
- created = await client.create_signed_service_url(
- sandbox,
- "mcp",
- label="Customer demo",
- expires_in_seconds=3600,
- )
- listed = await client.list_signed_service_urls(sandbox)
- await client.revoke_signed_service_url(created)
-
- create_request = calls[0][1]
- assert create_request.sandbox is sandbox
- assert (create_request.service, create_request.label, create_request.expires_in_seconds) == (
- "mcp",
- "Customer demo",
- 3600,
- )
- assert calls[1] == ("list", sandbox)
- assert listed == [created]
- assert calls[2][0] == "revoke"
- assert calls[2][1].id == created.id
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_reconcile_creates_pool_referencing_a_template(monkeypatch):
- client = FakeFleetClient()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- pool = await Pool.reconcile(pool_request(template_name="workspace"))
-
- assert pool.name == "foo"
- assert pool.resource.metadata.name == "foo"
- assert client.closed is True
- assert len(client.reconciled) == 1
- request = client.reconciled[0]
- assert request.namespace == "foo"
- assert request.spec.sandbox_template_ref.name == "workspace"
- assert request.spec.replicas == 1
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_delete_deletes_resource_and_closes_client(monkeypatch):
- client = FakeFleetClient()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- await Pool(fleet_pool()).delete()
-
- assert client.deleted_pools == ["foo"]
- assert client.closed is True
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_template_reconcile_creates_template_from_registry_image(monkeypatch):
- client = FakeFleetClient()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- request = template_request(
- image="registry.example/workspace:latest",
- services={"server": 8000, "port-3000": 3000},
- )
- template = await Template.reconcile(request)
-
- assert template.name == "foo"
- assert template.resource.metadata.name == "foo"
- assert client.closed is True
- assert client.reconciled_templates == [request]
- vm_template = client.reconciled_templates[0].spec.vm_template
- assert vm_template.container_disk_image == "registry.example/workspace:latest"
- assert [(service.name, service.target_port) for service in vm_template.services] == [
- ("server", 8000),
- ("port-3000", 3000),
- ]
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_template_reconcile_closes_temporary_client_when_reconciliation_fails(monkeypatch):
- client = FakeFleetClient(reconcile_error=RuntimeError("reconcile failed"))
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- with pytest.raises(RuntimeError, match="reconcile failed"):
- await Template.reconcile(template_request())
-
- assert client.closed is True
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
[email protected]("invalid_value", [None, {}, "not-a-request", pool_request()])
-async def test_template_reconcile_rejects_non_request(invalid_value):
- with pytest.raises(TypeError, match="CreateTemplateRequest"):
- await Template.reconcile(invalid_value)
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-def test_sync_template_reconcile_matches_async_facade(monkeypatch):
- client = FakeFleetClient()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- template = SyncTemplate.reconcile(template_request())
-
- assert template.name == "foo"
- assert client.closed is True
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_reconcile_closes_temporary_client_when_reconciliation_fails(monkeypatch):
- client = FakeFleetClient(reconcile_error=RuntimeError("reconcile failed"))
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- with pytest.raises(RuntimeError, match="reconcile failed"):
- await Pool.reconcile(pool_request())
-
- assert client.closed is True
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_reconcile_updates_existing_pool_idempotently(monkeypatch):
- existing = fleet_pool()
- client = FakeFleetClient(existing=existing)
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- pool = await Pool.reconcile(pool_request())
-
- assert pool.resource is existing
- assert len(client.reconciled) == 1
- assert client.reconciled[0].spec.sandbox_template_ref.name == "foo"
- assert client.closed is True
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_claim_releases_claim_and_client_after_block_exception(monkeypatch):
- reconcile_client = FakeFleetClient()
- claim_client = FakeFleetClient()
- clients = iter([reconcile_client, claim_client])
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))
- pool = await Pool.reconcile(pool_request())
-
- with pytest.raises(RuntimeError, match="body failed"):
- async with pool.claim() as sandbox:
- assert sandbox.name == "sandbox-1"
- raise RuntimeError("body failed")
-
- assert claim_client.claims[0].pool is pool.resource
- assert claim_client.claims[0].spec is None
- assert claim_client.released == ["claim-1"]
- assert claim_client.closed is True
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_claim_preserves_block_exception_when_release_fails(monkeypatch):
- reconcile_client = FakeFleetClient()
- claim_client = FakeFleetClient(release_error=RuntimeError("release failed"))
- clients = iter([reconcile_client, claim_client])
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))
- pool = await Pool.reconcile(pool_request())
-
- with pytest.raises(ValueError, match="body failed"):
- async with pool.claim():
- raise ValueError("body failed")
-
- assert claim_client.released == ["claim-1"]
- assert claim_client.closed is True
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_claim_raises_release_failure_without_block_exception(monkeypatch):
- reconcile_client = FakeFleetClient()
- claim_client = FakeFleetClient(release_error=RuntimeError("release failed"))
- clients = iter([reconcile_client, claim_client])
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))
- pool = await Pool.reconcile(pool_request())
-
- with pytest.raises(RuntimeError, match="release failed"):
- async with pool.claim():
- pass
-
- assert claim_client.closed is True
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
[email protected]("invalid_value", [None, {}, "not-a-request"])
-async def test_reconcile_rejects_non_request(invalid_value):
- with pytest.raises(TypeError, match="CreatePoolRequest"):
- await Pool.reconcile(invalid_value)
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-def test_sync_pool_delete_matches_async_facade(monkeypatch):
- client = FakeFleetClient()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- SyncPool(Pool(fleet_pool())).delete()
-
- assert client.deleted_pools == ["foo"]
- assert client.closed is True
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-def test_sync_pool_matches_blocking_context_manager(monkeypatch):
- reconcile_client = FakeFleetClient()
- claim_client = FakeFleetClient()
- clients = iter([reconcile_client, claim_client])
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))
-
- pool = SyncPool.reconcile(pool_request())
- spec = ClaimSpec(
- sandbox_template_ref=SandboxTemplateRefBuilder().name(pool.name).build(),
- warmpool=None,
- bind_deadline=900,
- lifecycle=None,
- )
- with pool.claim(spec=spec) as sandbox:
- assert sandbox.name == "sandbox-1"
-
- assert claim_client.claims[0].spec is spec
- assert claim_client.released == ["claim-1"]
- assert claim_client.closed is True
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_reconcile_preserves_replicas_and_template_reference(monkeypatch):
- client = FakeFleetClient()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- await Pool.reconcile(pool_request(replicas=2, template_name="workspace"))
-
- request = client.reconciled[0]
- assert request.spec.replicas == 2
- assert request.spec.sandbox_template_ref.name == "workspace"
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_template_reconcile_preserves_named_services(monkeypatch):
- client = FakeFleetClient()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- await Template.reconcile(
- template_request(
- image="registry.example/workspace:latest",
- services={"server": 8000, "mcp": 3000},
- )
- )
-
- vm_template = client.reconciled_templates[0].spec.vm_template
- assert [(service.name, service.target_port) for service in vm_template.services] == [
- ("server", 8000),
- ("mcp", 3000),
- ]
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_reconcile_forwards_native_create_pool_request_unchanged(monkeypatch):
- client = FakeFleetClient()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
- request = pool_request(replicas=2, template_name="workspace")
-
- await Pool.reconcile(request)
-
- assert client.reconciled == [request]
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_template_reconcile_forwards_native_request_unchanged(monkeypatch):
- client = FakeFleetClient()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
- request = template_request(
- vm_template=(
- VmTemplateBuilder()
- .container_disk_image("registry.example/workspace:latest")
- .runtime(RuntimeKind.KUBEVIRT)
- .image_pull_secret("workspace-pull")
- .cpu_cores(10)
- .memory("20Gi")
- .firmware(Firmware.EFI)
- .services(
- [
- SandboxServiceBuilder()
- .name("server")
- .target_port(8000)
- .protocol(ServiceProtocol.TCP)
- .build()
- ]
- )
- .build()
- ),
- )
-
- await Template.reconcile(request)
-
- assert client.reconciled_templates == [request]
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_claim_exposes_named_service_requests(monkeypatch):
- reconcile_client = FakeFleetClient()
- claim_client = FakeFleetClient()
- clients = iter([reconcile_client, claim_client])
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))
- pool = await Pool.reconcile(pool_request())
-
- async with pool.claim() as sandbox:
- response = await sandbox.services.request(
- "mcp",
- method="POST",
- path="/mcp",
- json={"jsonrpc": "2.0", "method": "tools/list", "id": 1},
- )
-
- assert response.status_code == 200
- _, service, path, request = claim_client.service_requests[0]
- assert (service, path, request.method) == ("mcp", "/mcp", "POST")
- assert request.body == b'{"jsonrpc": "2.0", "method": "tools/list", "id": 1}'
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_claim_manages_signed_service_urls(monkeypatch):
- reconcile_client = FakeFleetClient()
- claim_client = FakeFleetClient()
- clients = iter([reconcile_client, claim_client])
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))
- pool = await Pool.reconcile(pool_request())
-
- async with pool.claim() as sandbox:
- created = await sandbox.services.create_signed_url(
- "mcp",
- label="Customer demo",
- expires_in_seconds=3600,
- )
- listed = await sandbox.services.list_signed_urls()
- await sandbox.services.revoke_signed_url(created)
-
- bound, service, label, expires_in_seconds = claim_client.signed_url_creates[0]
- assert (bound.name, service, label, expires_in_seconds) == (
- "sandbox-1",
- "mcp",
- "Customer demo",
- 3600,
- )
- assert created.url == "https://signed.example/link"
- assert listed == [created]
- assert claim_client.signed_url_revocations == [created]
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_claim_forwards_native_claim_spec_unchanged(monkeypatch):
- reconcile_client = FakeFleetClient()
- claim_client = FakeFleetClient()
- clients = iter([reconcile_client, claim_client])
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))
- pool = await Pool.reconcile(pool_request())
-
- spec = ClaimSpec(
- sandbox_template_ref=SandboxTemplateRefBuilder().name(pool.name).build(),
- warmpool=None,
- bind_deadline=900,
- lifecycle=None,
- )
-
- async with pool.claim(spec=spec) as sandbox:
- assert sandbox.name == "sandbox-1"
-
- request = claim_client.claims[0]
- assert request.pool is pool.resource
- assert request.spec is spec
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_claim_without_spec_uses_operator_default(monkeypatch):
- reconcile_client = FakeFleetClient()
- claim_client = FakeFleetClient()
- clients = iter([reconcile_client, claim_client])
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))
- pool = await Pool.reconcile(pool_request())
-
- async with pool.claim() as sandbox:
- assert sandbox.name == "sandbox-1"
-
- request = claim_client.claims[0]
- assert request.pool is pool.resource
- assert request.spec is None
- assert claim_client.released == ["claim-1"]
- assert claim_client.closed is True
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_get_fetches_without_reconciling(monkeypatch):
- client = FakeFleetClient()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- pool = await Pool.get("foo")
-
- assert pool.name == "foo"
- assert client.reconciled == []
- assert client.closed is True
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_create_claim_returns_a_serializable_lease(monkeypatch):
- reconcile_client = FakeFleetClient()
- claim_client = FakeFleetClient()
- clients = iter([reconcile_client, claim_client])
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))
- pool = await Pool.reconcile(pool_request())
-
- lease = await pool.create_claim()
-
- assert (lease.namespace, lease.name) == ("foo", "claim-1")
- assert claim_client.claims[0].pool is pool.resource
- assert claim_client.claims[0].spec is None
- assert claim_client.released == []
- assert claim_client.closed is True
- assert lease.to_dict() == {
- "version": 1,
- "provider": "fleet",
- "namespace": "foo",
- "pool": "foo",
- "claim": "claim-1",
- "service": "env",
- }
- assert _ClaimHandle.from_dict(lease.to_dict()).to_dict() == lease.to_dict()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_create_claim_forwards_creation_ttl_in_a_derived_spec(monkeypatch):
- reconcile_client = FakeFleetClient()
- claim_client = FakeFleetClient()
- clients = iter([reconcile_client, claim_client])
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))
- pool = await Pool.reconcile(pool_request())
-
- await pool.create_claim(ttl_seconds_after_created=1800)
-
- spec = claim_client.claims[0].spec
- assert spec.ttl_seconds_after_created == 1800
- assert spec.sandbox_template_ref is pool.resource.spec.sandbox_template_ref
- assert spec.warmpool is None
- assert spec.bind_deadline is None
- assert spec.lifecycle is None
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_create_claim_rejects_ttl_alongside_an_explicit_spec(monkeypatch):
- reconcile_client = FakeFleetClient()
- clients = iter([reconcile_client, FakeFleetClient()])
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))
- pool = await Pool.reconcile(pool_request())
-
- with pytest.raises(ValueError, match="inside spec"):
- await pool.create_claim(spec=SimpleNamespace(), ttl_seconds_after_created=1800)
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_claim_forwards_creation_ttl_in_a_derived_spec(monkeypatch):
- reconcile_client = FakeFleetClient()
- claim_client = FakeFleetClient()
- clients = iter([reconcile_client, claim_client])
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))
- pool = await Pool.reconcile(pool_request())
-
- async with pool.claim(ttl_seconds_after_created=900):
- pass
-
- spec = claim_client.claims[0].spec
- assert spec.ttl_seconds_after_created == 900
- assert spec.sandbox_template_ref is pool.resource.spec.sandbox_template_ref
-
-
-async def test_lease_wait_connects_to_the_named_service_and_caches_the_bind(monkeypatch):
- client = FakeFleetClient()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
- lease = _ClaimHandle(namespace="foo", name="claim-1", pool_name="foo")
-
- sandbox = await lease.wait(service="mcp")
-
- assert sandbox.name == "sandbox-1"
- assert client.wait_calls == 1
- assert lease.to_dict()["claim"] == "claim-1"
- response = await sandbox.services.request(
- "mcp", method="POST", path="/mcp", json={"jsonrpc": "2.0", "id": 1}
- )
- assert response.status_code == 200
- assert client.closed is False
- await sandbox.disconnect()
- assert client.closed is True
-
-
-async def test_lease_reattaches_from_serialized_state_without_polling(monkeypatch):
- client = FakeFleetClient()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
- lease = _ClaimHandle.from_dict(
- {
- "version": 1,
- "provider": "fleet",
- "namespace": "foo",
- "pool": "foo",
- "claim": "claim-1",
- }
- )
-
- sandbox = await lease.wait(service="mcp")
-
- assert sandbox.name == "sandbox-1"
- assert client.wait_calls == 1
- await sandbox.disconnect()
- assert client.closed is True
-
-
-async def test_lease_wait_closes_its_client_when_the_bind_fails(monkeypatch):
- client = FakeFleetClient()
-
- async def failing_wait(claim):
- raise RuntimeError("bind failed")
-
- client.wait_claim = failing_wait
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- with pytest.raises(RuntimeError, match="bind failed"):
- await _ClaimHandle(namespace="foo", name="claim-1", pool_name="foo").wait()
-
- assert client.closed is True
-
-
-async def test_lease_release_deletes_the_claim_by_reference(monkeypatch):
- client = FakeFleetClient()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- await _ClaimHandle(namespace="foo", name="claim-1", pool_name="foo").release()
-
- assert client.released == ["claim-1"]
- assert client.closed is True
-
-
-async def test_release_tolerates_claim_already_deleted_by_another_process(monkeypatch):
- first_client = FakeFleetClient()
- second_client = FakeFleetClient()
-
- async def already_deleted(claim):
- raise SdkError.Status("delete claim", 404, b"not found")
-
- second_client.delete_claim = already_deleted
- clients = iter([first_client, second_client])
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))
-
- await _ClaimHandle(namespace="foo", name="claim-1", pool_name="foo").release()
- await _ClaimHandle(namespace="foo", name="claim-1", pool_name="foo").release()
-
- assert first_client.released == ["claim-1"]
- assert first_client.closed is True
- assert second_client.closed is True
-
-
-async def test_lease_renew_pushes_the_shutdown_time_forward(monkeypatch):
- client = FakeFleetClient()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- await _ClaimHandle(namespace="foo", name="claim-1", pool_name="foo").renew(
- "2026-01-01T00:10:00Z"
- )
-
- assert client.renewed == [("claim-1", "2026-01-01T00:10:00Z")]
- assert client.closed is True
-
-
-async def test_fleet_client_renew_claim_requires_a_release_with_renew_support():
- client = object.__new__(_FleetClient)
- client._client = object()
-
- with pytest.raises(RuntimeError, match="renew_claim"):
- await client.renew_claim(fake_claim(), "2026-01-01T00:10:00Z")
-
-
-async def test_fleet_client_renew_claim_delegates_when_supported():
- calls = []
-
- class GeneratedClient:
- async def renew_claim(self, claim, shutdown_time):
- calls.append((claim, shutdown_time))
- return "renewed"
-
- client = object.__new__(_FleetClient)
- client._client = GeneratedClient()
-
- assert await client.renew_claim("claim", "2026-01-01T00:10:00Z") == "renewed"
- assert calls == [("claim", "2026-01-01T00:10:00Z")]
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_named_claim_retry_reattaches_without_creating(monkeypatch):
- client = FakeFleetClient()
- client.existing_claims = [fake_claim()]
-
- async def list_claims(namespace: str):
- assert namespace == "foo"
- return client.existing_claims
-
- client.list_claims = list_claims
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- sandbox = await Pool(fleet_pool()).claim(name="claim-1")
-
- assert client.claims == []
- assert sandbox.claim_name == "claim-1"
- assert sandbox.to_dict()["service"] == "env"
- await sandbox.close()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_named_claim_reattach_failure_does_not_release_existing_claim(monkeypatch):
- client = FakeFleetClient()
- client.existing_claims = [fake_claim()]
-
- async def list_claims(namespace: str):
- assert namespace == "foo"
- return client.existing_claims
-
- async def failing_wait(claim):
- raise RuntimeError("bind failed")
-
- client.list_claims = list_claims
- client.wait_claim = failing_wait
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- with pytest.raises(RuntimeError, match="bind failed"):
- await Pool(fleet_pool()).claim(name="claim-1")
-
- assert client.claims == []
- assert client.released == []
- assert client.closed is True
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_new_claim_acquisition_failure_releases_created_claim(monkeypatch):
- client = FakeFleetClient()
-
- async def list_claims(namespace: str):
- assert namespace == "foo"
- return []
-
- async def failing_wait(claim):
- raise RuntimeError("bind failed")
-
- client.list_claims = list_claims
- client.wait_claim = failing_wait
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
-
- with pytest.raises(RuntimeError, match="bind failed"):
- await Pool(fleet_pool()).claim(name="claim-1")
-
- assert len(client.claims) == 1
- assert client.released == ["claim-1"]
- assert client.closed is True
-
-
-class _AppliedResources:
- """What the Python Fleet client reads back after ``Fleet.apply``."""
-
- def __init__(self) -> None:
- self.closed = False
-
- async def get_pool(self, name: str) -> object:
- return fleet_pool(name)
-
- async def get_template(self, namespace: str, name: str) -> object:
- return fleet_template(name)
-
- async def close(self) -> None:
- self.closed = True
-
-
-def _capture_native_apply(monkeypatch) -> list:
- """``Pool.apply`` writes only through the SDK's ``Fleet.apply``: capture
- the native (name, spec, options) it hands over."""
- seen: list = []
-
- async def native_apply(name, spec, options):
- seen.append((name, spec, options))
-
- monkeypatch.setattr("cua_sandbox.pool._native_apply", native_apply)
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", _AppliedResources)
- return seen
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_apply_goes_through_the_one_native_writer(monkeypatch):
- seen = _capture_native_apply(monkeypatch)
-
- with pytest.warns(DeprecationWarning):
- pool = await Pool.apply(
- Image.from_registry("registry.example/workspace:latest"),
- name="workspace",
- cpu=4,
- memory_mb=4096,
- )
-
- [(name, spec, options)] = seen
- assert name == pool.name == "workspace"
- assert (spec.image, spec.cpu, spec.memory_mb) == ("registry.example/workspace:latest", 4, 4096)
- assert options.replicas == 1
- assert pool._owned_template is not None
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_apply_delete_removes_owned_pool_and_template(monkeypatch):
- _capture_native_apply(monkeypatch)
- pool = await Pool.apply(
- Image.from_registry("registry.example/workspace:latest"),
- name="workspace",
- )
- client = FakeFleetClient()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
- await pool.delete()
-
- assert client.deleted_pools == ["workspace"]
- assert client.deleted_templates == ["workspace"]
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_apply_forwards_autoscaling_to_the_pool_options(monkeypatch):
- seen = _capture_native_apply(monkeypatch)
- autoscaling = WarmPoolAutoscaling(min_pool_size=0, initial_pool_size=2, max_pool_size=10)
-
- await Pool.apply(
- Image.from_registry("registry.example/workspace:latest"),
- name="workspace",
- autoscaling=autoscaling,
- )
-
- options = seen[0][2]
- assert (options.min_pool_size, options.replicas, options.max_pool_size) == (0, 2, 10)
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_apply_without_autoscaling_leaves_the_pool_static(monkeypatch):
- seen = _capture_native_apply(monkeypatch)
-
- await Pool.apply(
- Image.from_registry("registry.example/workspace:latest"),
- name="workspace",
- )
-
- options = seen[0][2]
- assert options.min_pool_size is None and options.max_pool_size is None
- assert options.warm is None
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_apply_requires_an_explicit_name():
- image = Image.from_registry("registry.example/workspace:latest")
-
- with pytest.raises(TypeError):
- await Pool.apply(image)
- with pytest.raises(ValueError, match="globally unique"):
- await Pool.apply(image, name="")
- with pytest.raises(ValueError, match="globally unique"):
- await Pool.apply(image, name=None)
-
-
-async def _applied_runtime(monkeypatch, image, **kwargs):
- seen = _capture_native_apply(monkeypatch)
- await Pool.apply(image, name="workspace", **kwargs)
- return {"gvisor": RuntimeKind.GVISOR, "kubevirt": RuntimeKind.KUBEVIRT}[seen[0][2].runtime]
-
-
-DESKTOP = "ghcr.io/trycua/cua-desktop-linux"
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
- ("reference", "kind", "runtime", "expected"),
- [
- # Defaults from the image kind.
- (f"{DESKTOP}:docker-latest", "container", None, RuntimeKind.GVISOR),
- (f"{DESKTOP}:latest", "vm", None, RuntimeKind.KUBEVIRT),
- # An unresolved kind follows the image's manifest (tests/_image_fixtures.py).
- (f"{DESKTOP}:docker-latest", None, None, RuntimeKind.GVISOR),
- ("registry.example/workspace:latest", None, None, RuntimeKind.KUBEVIRT),
- # Explicit runtimes win; an unreadable manifest sends them unchecked.
- ("public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04:main-1", None, "gvisor", RuntimeKind.GVISOR),
- (f"{DESKTOP}:latest", "container", "kubevirt", RuntimeKind.KUBEVIRT),
- ],
-)
-async def test_pool_apply_sets_the_template_runtime(
- monkeypatch, reference, kind, runtime, expected
-):
- image = Image.from_registry(reference, kind=kind)
- assert await _applied_runtime(monkeypatch, image, runtime=runtime) == expected
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
- ("reference", "runtime", "hint"),
- [
- (f"{DESKTOP}:latest", "gvisor", "containerDisk"),
- (f"{DESKTOP}:docker-latest", "kubevirt", "container rootfs"),
- ],
-)
-async def test_pool_apply_refuses_a_crossed_runtime_before_creating_anything(
- monkeypatch, reference, runtime, hint
-):
- import cua
-
- def no_client():
- raise AssertionError("no Fleet call for an invalid runtime/image pairing")
-
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", no_client)
- with pytest.raises(cua.CuaError.InvalidArgument, match=hint):
- await Pool.apply(Image.from_registry(reference), name="workspace", runtime=runtime)
- with pytest.raises(ValueError, match="kubevirt"):
- await Pool.apply(Image.from_registry(reference), name="workspace", runtime="firecracker")
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-def test_sync_pool_apply_forwards_the_runtime(monkeypatch):
- seen = _capture_native_apply(monkeypatch)
- SyncPool.apply(
- Image.from_registry("public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04:main-1"),
- name="workspace",
- runtime="gvisor",
- )
- assert seen[0][2].runtime == "gvisor"
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-def test_sync_pool_apply_forwards_autoscaling(monkeypatch):
- seen = _capture_native_apply(monkeypatch)
- autoscaling = WarmPoolAutoscaling(min_pool_size=1, initial_pool_size=1, max_pool_size=5)
-
- pool = SyncPool.apply(
- Image.from_registry("registry.example/workspace:latest"),
- name="workspace",
- autoscaling=autoscaling,
- )
-
- assert pool.name == "workspace"
- options = seen[0][2]
- assert (options.min_pool_size, options.replicas, options.max_pool_size) == (1, 1, 5)
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_apply_forwards_creation_ttl_to_the_pool_options(monkeypatch):
- seen = _capture_native_apply(monkeypatch)
-
- await Pool.apply(
- Image.from_registry("registry.example/workspace:latest"),
- name="workspace",
- ttl_seconds_after_created=86400,
- )
-
- assert seen[0][2].pool_ttl_seconds == 86400
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_apply_without_creation_ttl_leaves_the_pool_unreaped(monkeypatch):
- seen = _capture_native_apply(monkeypatch)
-
- await Pool.apply(
- Image.from_registry("registry.example/workspace:latest"),
- name="workspace",
- )
-
- assert seen[0][2].pool_ttl_seconds is None
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_apply_rejects_invalid_creation_ttl(monkeypatch):
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", FakeFleetClient)
-
- with pytest.raises(ValueError, match="ttl_seconds_after_created"):
- await Pool.apply(
- Image.from_registry("registry.example/workspace:latest"),
- name="workspace",
- ttl_seconds_after_created=-1,
- )
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_apply_maps_a_taken_name_to_access_denied(monkeypatch):
- import cua
-
- class _Fleet:
- async def apply(self, name, spec, options):
- raise cua.CuaError.Fleet(
- "Fleet denied create pool on pool namespace 'workspace' (HTTP 403). Pool "
- "names are globally unique across accounts"
- )
-
- monkeypatch.setattr("cua_sandbox.pool.native_fleet", lambda: _Fleet())
- with pytest.raises(PoolAccessDeniedError, match="globally unique") as error:
- await Pool.apply(
- Image.from_registry("registry.example/workspace:latest"),
- name="workspace",
- )
-
- assert "'workspace'" in str(error.value)
- assert "https://discord.gg/mVnXXpdE85" in str(error.value)
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_close_after_disconnect_reopens_client_for_release(monkeypatch):
- claim_client = FakeFleetClient()
- release_client = FakeFleetClient()
- clients = iter([claim_client, release_client])
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: next(clients))
-
- sandbox = await Pool(fleet_pool()).claim()
- await sandbox.disconnect()
- await sandbox.close()
-
- assert claim_client.closed is True
- assert claim_client.released == []
- assert release_client.released == ["claim-1"]
- assert release_client.closed is True
diff --git a/libs/python/cua-sandbox/tests/test_pool_image_info.py b/libs/python/cua-sandbox/tests/test_pool_image_info.py
deleted file mode 100644
index 6364d36e6c..0000000000
--- a/libs/python/cua-sandbox/tests/test_pool_image_info.py
+++ /dev/null
@@ -1,99 +0,0 @@
-"""``Sandbox.image_info`` for claims on a named Fleet pool: its template's
-image, from the native ``Fleet.pool_image_info``.
-
-Hermetic: the loopback fake Fleet (``cua-test-fixtures``) and fake SDK
-records; registry reads are off (conftest), so only a digest-pinned template
-carries a digest here (the Rust tests cover tag resolution).
-"""
-
-from __future__ import annotations
-
-from types import SimpleNamespace
-
-import pytest
-from cua_sandbox import (
- CloudOptions,
- Image,
- Pool,
- PoolOptions,
- Sandbox,
- SandboxSpec,
- _sdk,
-)
-from cua_sandbox import pool as pool_module
-from cua_sandbox.transport.env import EnvTransport
-
-from tests._native_fleet import fleet # noqa: F401 - fixture
-
-DIGEST = "sha256:" + "c" * 64
-PINNED = f"ghcr.io/trycua/cua-e2e-plain@{DIGEST}"
-
-
-def _record(**overrides) -> SimpleNamespace:
- fields = dict(
- reference=PINNED,
- pinned_ref=PINNED,
- digest=DIGEST,
- variant="rootfs",
- arch="amd64",
- os="linux",
- emulated=False,
- )
- fields.update(overrides)
- return SimpleNamespace(**fields)
-
-
-async def test_a_named_pool_claim_records_the_template_image(monkeypatch):
- async def pool_image_info(pool):
- assert pool == "cua-e2e-named"
- return _record()
-
- monkeypatch.setattr(_sdk, "pool_image_info", pool_image_info)
- sb = Sandbox(EnvTransport(url="http://127.0.0.1:1"), name="sb")
- await pool_module._record_pool_image(sb, "cua-e2e-named")
- assert sb.image_info.pinned_ref == PINNED
- assert sb.image_info.digest == DIGEST
-
-
-async def test_an_unreadable_pool_leaves_image_info_unset(monkeypatch):
- async def fails(pool):
- raise RuntimeError("boom")
-
- monkeypatch.setattr(_sdk, "pool_image_info", fails)
- sb = Sandbox(EnvTransport(url="http://127.0.0.1:1"), name="sb")
- await pool_module._record_pool_image(sb, "cua-e2e-named")
- assert sb.image_info is None
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_the_native_fleet_reports_a_named_pool_template_image(fleet): # noqa: F811
- await Pool.apply(
- "cua-e2e-py-digest",
- SandboxSpec(image=Image.from_registry(PINNED, kind="container")),
- PoolOptions(runtime="gvisor"),
- )
- record = await _sdk.pool_image_info("cua-e2e-py-digest")
- assert record is not None
- assert record.pinned_ref == PINNED
- assert record.digest == DIGEST
- assert record.variant == "rootfs"
- # A pool that does not exist: None, never an error.
- assert await _sdk.pool_image_info("cua-e2e-py-missing") is None
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_a_claim_on_a_named_pool_reports_its_image(fleet): # noqa: F811
- await Pool.apply(
- "cua-e2e-py-claim",
- SandboxSpec(image=Image.from_registry(PINNED, kind="container")),
- PoolOptions(runtime="gvisor"),
- )
- async with Sandbox.ephemeral(
- None, cloud=CloudOptions(pool="cua-e2e-py-claim"), local=False
- ) as sb:
- assert sb.image_info is not None
- assert sb.image_info.pinned_ref == PINNED
- assert sb.image_info.digest == DIGEST
- # The SDK handle opened for the claim reports the same.
- handle = await sb._transport._fleet_handle()
- assert handle.image_info().pinned_ref == PINNED
diff --git a/libs/python/cua-sandbox/tests/test_pool_spec.py b/libs/python/cua-sandbox/tests/test_pool_spec.py
deleted file mode 100644
index cf01af8e27..0000000000
--- a/libs/python/cua-sandbox/tests/test_pool_spec.py
+++ /dev/null
@@ -1,301 +0,0 @@
-"""The shared sandbox model in cua-sandbox (hermetic).
-
-``Pool.apply(name, SandboxSpec, PoolOptions)`` is the only pool writer: it
-goes through the native SDK's ``Fleet.apply``. The pure tests capture what
-cua-sandbox hands the SDK; the ``fleet`` ones run the native SDK against the
-loopback fake Fleet (``cua-test-fixtures``).
-"""
-
-from __future__ import annotations
-
-import warnings
-from datetime import timedelta
-from types import SimpleNamespace
-
-import pytest
-from cua_sandbox import (
- ClaimSecretsNotDelivered,
- CloudOptions,
- Image,
- InvalidArgument,
- Pool,
- PoolAccessDeniedError,
- PoolOptions,
- PoolSpecMismatch,
- Sandbox,
- SandboxSpec,
- WarmPoolAutoscaling,
- generate_claim_token,
-)
-from cua_sandbox import pool as pool_module
-from cua_sandbox import (
- tcp,
-)
-from cua_sandbox.spec import translate_native_error
-
-from tests._native_fleet import fleet # noqa: F401 - fixture
-
-ROOTFS = "ghcr.io/trycua/cua-e2e-plain:1"
-
-
-def _native():
- from cua_sandbox._sdk import native
-
- return native()
-
-
-# ── pure ─────────────────────────────────────────────────────────────────
-
-
-def test_spec_and_options_convert_to_the_native_records():
- spec = SandboxSpec(
- image=Image.from_registry(ROOTFS, kind="container"),
- command=["python", "-m", "srv"],
- env={"A": "1"},
- services={"mcp": 8765},
- wait_for=tcp("mcp"),
- cpu=2,
- memory="2GB",
- claim_secrets=True,
- ).native()
- assert spec.image == ROOTFS
- assert spec.command == ["python", "-m", "srv"]
- assert spec.services == {"mcp": 8765}
- assert spec.readiness.service == "mcp"
- assert spec.memory_mb == 2048
- assert spec.claim_secrets is True
- options = PoolOptions(
- runtime="gvisor",
- warm=True,
- max_pool_size=3,
- idle_ttl=timedelta(hours=1),
- ttl_policy="Cascade",
- claim_ttl=600,
- ).native()
- assert options.runtime == "gvisor"
- assert options.warm is True
- assert options.idle_ttl_seconds == 3600
- assert options.ttl_policy == "Cascade"
- assert options.claim_ttl_seconds == 600
- with pytest.raises(ValueError, match="runtime"):
- PoolOptions(runtime="firecracker").native()
- with pytest.raises(ValueError, match="idle_ttl"):
- PoolOptions(idle_ttl=-1).native()
- # A Windows image boots UEFI; an Image's secret becomes the pool's.
- assert SandboxSpec(image=Image.windows()).native().efi is True
-
-
-def test_native_errors_map_to_typed_exceptions():
- n = _native()
- mismatch = translate_native_error(n.CuaError.PoolSpecMismatch("pool x: command differs"))
- assert isinstance(mismatch, PoolSpecMismatch)
- assert isinstance(mismatch, InvalidArgument) and isinstance(mismatch, ValueError)
- assert "command differs" in str(mismatch)
- lost = translate_native_error(n.CuaError.ClaimSecretsNotDelivered("claim c released"))
- assert isinstance(lost, ClaimSecretsNotDelivered) and isinstance(lost, TimeoutError)
- other = n.CuaError.Timeout("x")
- assert translate_native_error(other) is other
- assert len(generate_claim_token()) == 64
-
-
-class _Resources:
- """The Python Fleet client reads the written pool back."""
-
- def __init__(self, name: str) -> None:
- self.pool = SimpleNamespace(metadata=SimpleNamespace(name=name, namespace=name))
- self.template = SimpleNamespace(metadata=SimpleNamespace(name=name, namespace=name))
-
- async def get_pool(self, name):
- return self.pool
-
- async def get_template(self, namespace, name):
- return self.template
-
- async def close(self):
- pass
-
-
-def _capture(monkeypatch, name="workspace"):
- seen = []
-
- async def native_apply(n, spec, options):
- seen.append((n, spec, options))
-
- monkeypatch.setattr(pool_module, "_native_apply", native_apply)
- monkeypatch.setattr(pool_module, "_FleetClient", lambda: _Resources(name))
- return seen
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_apply_writes_through_the_native_fleet_apply(monkeypatch):
- seen = _capture(monkeypatch)
- image = Image.from_registry(ROOTFS, kind="container")
- pool = await Pool.apply(
- "workspace",
- SandboxSpec(image=image, command=["srv"], services={"mcp": 8765}),
- PoolOptions(warm=True),
- )
- assert pool.name == "workspace"
- assert pool._owned_template is not None
- [(name, spec, options)] = seen
- assert name == "workspace"
- assert spec.command == ["srv"]
- # The runtime is resolved (the one rule) before anything is written.
- assert options.runtime == "gvisor"
- assert options.warm is True
- with pytest.raises(ValueError, match="globally unique"):
- await Pool.apply("", SandboxSpec(image=image))
- with pytest.raises(TypeError):
- await Pool.apply("workspace", {"image": ROOTFS})
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_the_old_signature_is_a_deprecated_wrapper(monkeypatch):
- seen = _capture(monkeypatch)
- image = Image.from_registry(ROOTFS, kind="container")
- with pytest.warns(DeprecationWarning, match="SandboxSpec"):
- await Pool.apply(
- image,
- name="workspace",
- cpu=4,
- memory_mb=4096,
- autoscaling=WarmPoolAutoscaling(min_pool_size=1, initial_pool_size=2, max_pool_size=5),
- ttl_seconds_after_created=86400,
- )
- [(_, spec, options)] = seen
- assert (spec.image, spec.cpu, spec.memory_mb) == (ROOTFS, 4, 4096)
- assert spec.services == {"env": 3211}, "daemon-agnostic default services"
- assert spec.readiness is None
- assert (options.min_pool_size, options.replicas, options.max_pool_size) == (1, 2, 5)
- assert options.pool_ttl_seconds == 86400
- assert options.runtime == "gvisor"
-
- seen.clear()
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", DeprecationWarning)
- await Pool.apply(image, name="workspace", replicas=3, services={"server": 8000})
- [(_, spec, options)] = seen
- assert spec.readiness.service == "server", "a server service is the readiness probe"
- assert options.replicas == 3 and options.min_pool_size is None
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", DeprecationWarning)
- with pytest.raises(TypeError):
- await Pool.apply(image)
- with pytest.raises(ValueError, match="globally unique"):
- await Pool.apply(image, name="")
- with pytest.raises(ValueError, match="ttl_seconds_after_created"):
- await Pool.apply(image, name="workspace", ttl_seconds_after_created=-1)
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_a_taken_pool_name_is_access_denied(monkeypatch):
- n = _native()
-
- class _Fleet:
- async def apply(self, name, spec, options):
- raise n.CuaError.Fleet(
- "Fleet denied create pool on pool namespace 'workspace' (HTTP 403). Pool "
- "names are globally unique across accounts"
- )
-
- monkeypatch.setattr(pool_module, "native_fleet", lambda: _Fleet())
- with pytest.raises(PoolAccessDeniedError, match="globally unique"):
- await Pool.apply(
- "workspace",
- SandboxSpec(image=Image.from_registry(ROOTFS, kind="container")),
- )
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_apply_true_needs_a_pool():
- with pytest.raises(ValueError, match="pass pool="):
- await Sandbox.create(
- Image.from_registry(ROOTFS, kind="container"),
- cloud=CloudOptions(apply=True),
- )
-
-
-# ── the fake Fleet ───────────────────────────────────────────────────────
-
-
-async def _apply(name: str) -> Pool:
- return await Pool.apply(
- name,
- SandboxSpec(
- image=Image.from_registry(ROOTFS, kind="container"),
- command=["python", "-m", "srv"],
- services={"mcp": 8765},
- cpu=2,
- memory_mb=2048,
- ),
- PoolOptions(warm=True, idle_ttl=3600, ttl_policy="Cascade"),
- )
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_apply_export_and_terraform_against_the_fake_fleet(fleet): # noqa: F811
- pool = await _apply("cua-e2e-py-spec")
- assert pool.name == "cua-e2e-py-spec"
- exported = await Pool.export("cua-e2e-py-spec")
- assert exported.runtime == "gvisor"
- assert exported.spec.command == ["python", "-m", "srv"]
- assert exported.options.warm is True
- assert exported.options.idle_ttl_seconds == 3600
- assert exported.options.ttl_policy == "Cascade"
- hcl = await Pool.export("cua-e2e-py-spec", terraform=True)
- for want in (
- 'resource "fleets_pool" "cua_e2e_py_spec" {',
- " cpu_cores = 2",
- ' memory = "2048Mi"',
- ' runtime = "gvisor"',
- ' command = ["python", "-m", "srv"]',
- " idle_ttl_seconds = 3600",
- " min_pool_size = 1",
- ):
- assert want in hcl, (want, hcl)
- await pool.delete()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_a_named_pool_is_compared_and_applied(fleet): # noqa: F811
- await _apply("cua-e2e-py-mm")
- await Pool.check("cua-e2e-py-mm", SandboxSpec(command=["python", "-m", "srv"]))
- with pytest.raises(PoolSpecMismatch) as error:
- await Pool.check("cua-e2e-py-mm", SandboxSpec(command=["node", "srv.js"], cpu=4))
- message = str(error.value)
- assert "command: pool has" in message and "cpu: pool has 2, requested 4" in message
- assert "apply=True" in message
-
- # Sandbox.create with the named pool: a mismatch fails before any claim.
- with pytest.raises(PoolSpecMismatch, match="command"):
- await Sandbox.create(
- command=["node", "srv.js"],
- cloud=CloudOptions(pool="cua-e2e-py-mm"),
- )
- client = fleet()
- try:
- assert await client.list_claims("cua-e2e-py-mm") == [], "nothing claimed"
- finally:
- await client.close()
-
- # apply=True reconciles the template's given fields; the rest is kept.
- await Pool.apply_template("cua-e2e-py-mm", SandboxSpec(command=["node", "srv.js"]))
- await Pool.check("cua-e2e-py-mm", SandboxSpec(command=["node", "srv.js"]))
- exported = await Pool.export("cua-e2e-py-mm")
- assert exported.spec.command == ["node", "srv.js"]
- assert exported.spec.services == {"mcp": 8765}
- assert exported.spec.cpu == 2
-
- # Managed pools refuse apply=True (their template is their key).
- with pytest.raises(ValueError, match="managed pool"):
- await Sandbox.create(
- command=["x"],
- cloud=CloudOptions(pool="cua-auto-abc", apply=True),
- )
-
-
-def test_macos_runtime_is_refused_before_any_fleet_call():
- with pytest.raises(ValueError, match="Fleet does not offer macOS sandboxes"):
- PoolOptions(runtime="macos").native()
- with pytest.raises(ValueError, match="runtime must be"):
- PoolOptions(runtime="firecracker").native()
diff --git a/libs/python/cua-sandbox/tests/test_pull_secret.py b/libs/python/cua-sandbox/tests/test_pull_secret.py
deleted file mode 100644
index 21b467be06..0000000000
--- a/libs/python/cua-sandbox/tests/test_pull_secret.py
+++ /dev/null
@@ -1,59 +0,0 @@
-"""The ECR pull secret must only ride on images that need it.
-
-Attaching `imagePullSecret: ecr-credentials` to a public image is not merely
-redundant — the gateway's admission policy reads its presence as "enforce the
-private-registry allowlist", so a public image the cluster can pull anonymously
-was refused with `403 k8s request is not allowed`. Proven with identical request
-bodies differing only in the image: ghcr.io -> 403, public.ecr.aws -> 201.
-"""
-
-import pytest
-from cua_sandbox import Image
-from cua_sandbox.transport.fleet_cloud import (
- FleetCloudTransport,
- _needs_ecr_pull_secret,
-)
-
-PRIVATE = "123456789012.dkr.ecr.us-west-2.amazonaws.com/example-workspace:main-bac7daa3"
-PUBLIC_ECR = "public.ecr.aws/k5j5w0x5/cua-windows-2022:main-bac7daa3"
-
-
- "ref,expected",
- [
- (PRIVATE, True),
- ("123456789012.dkr.ecr.eu-central-1.amazonaws.com/x:1", True),
- (PUBLIC_ECR, False),
- ("ghcr.io/trycua/minecraft-workspace:latest", False),
- ("quay.io/org/image:tag", False),
- ("ubuntu:22.04", False),
- (None, False),
- ("", False),
- ],
-)
-def test_only_private_ecr_needs_the_secret(ref, expected):
- assert _needs_ecr_pull_secret(ref) is expected
-
-
-def test_public_image_template_carries_no_pull_secret():
- """A public image must not be forced into the allowlist branch."""
- request = FleetCloudTransport(image=Image.windows(), name="demo")._template_request()
- template = request.spec.vm_template
- assert template.container_disk_image == "ghcr.io/trycua/windows:2022"
- assert not getattr(template, "image_pull_secret", None)
-
-
-def test_private_registry_image_still_carries_the_secret():
- request = FleetCloudTransport(
- image=Image.from_registry(PRIVATE), name="demo"
- )._template_request()
- assert request.spec.vm_template.image_pull_secret == "ecr-credentials"
-
-
-def test_a_public_non_ecr_registry_is_usable():
- """The case the Minecraft guide needs: a containerDisk pushed to ghcr.io."""
- ref = "ghcr.io/trycua/minecraft-workspace:latest"
- request = FleetCloudTransport(image=Image.from_registry(ref), name="demo")._template_request()
- template = request.spec.vm_template
- assert template.container_disk_image == ref
- assert not getattr(template, "image_pull_secret", None)
diff --git a/libs/python/cua-sandbox/tests/test_refs.py b/libs/python/cua-sandbox/tests/test_refs.py
index ddc7b7ee51..93f2bc96ae 100644
--- a/libs/python/cua-sandbox/tests/test_refs.py
+++ b/libs/python/cua-sandbox/tests/test_refs.py
@@ -8,7 +8,8 @@ from __future__ import annotations
import importlib
import pytest
-from cua_sandbox import AmbiguousSandbox, InvalidArgument, Sandbox, Unsupported, _refs
+from cua_sandbox import InvalidArgument, Sandbox, Unsupported, _refs
+from cua_sandbox._ended import CloudEnded
from cua_sandbox.transport.env import EnvTransport
sandbox_module = importlib.import_module("cua_sandbox.sandbox")
@@ -25,30 +26,22 @@ def test_refs_parse_with_the_legacy_spellings():
_refs.parse("moon:x")
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_resolve_qualified_narrowed_and_ambiguous(monkeypatch):
- local_names = {"box", "only-local"}
- is_local = local_names.__contains__
+async def test_resolve_qualified_narrowed_and_bare_names():
+ is_local = {"box", "only-local"}.__contains__
- async def cloud_has(name: str) -> bool:
- return name in {"box", "only-cloud"}
-
- monkeypatch.setattr(_refs, "_cloud_has", cloud_has)
assert await _refs.resolve("local:box", None) == ("box", True, None)
- assert await _refs.resolve("cloud:box", None) == ("box", False, None)
assert await _refs.resolve("direct:h:1", None) == ("h:1", None, "http://h:1")
assert await _refs.resolve("only-local", None, is_local=is_local) == ("only-local", True, None)
- assert await _refs.resolve("only-cloud", None, is_local=is_local) == ("only-cloud", False, None)
- # A bare name in two locations is a typed error listing both refs.
- with pytest.raises(AmbiguousSandbox) as err:
- await _refs.resolve("box", None, is_local=is_local)
- assert err.value.candidates == ["local:box", "cloud:box"]
- assert "use one of: local:box, cloud:box" in str(err.value)
- # local= narrows it.
+ assert await _refs.resolve("elsewhere", None, is_local=is_local) == ("elsewhere", False, None)
+ # local= narrows a bare name.
assert await _refs.resolve("box", True, is_local=is_local) == ("box", True, None)
- assert await _refs.resolve("box", False, is_local=is_local) == ("box", False, None)
+ # Cua Cloud has ended: a cloud ref, or a bare name narrowed to the cloud, raises.
+ with pytest.raises(CloudEnded):
+ await _refs.resolve("cloud:box", None)
+ with pytest.raises(CloudEnded):
+ await _refs.resolve("box", False, is_local=is_local)
with pytest.raises(InvalidArgument):
- await _refs.resolve("cloud:box", True)
+ await _refs.resolve("local:box", False)
with pytest.raises(Unsupported):
await _refs.resolve("relay:0123abcd4567ef89", None)
@@ -72,15 +65,3 @@ def test_sandbox_ids_are_qualified():
assert (sb.id, sb.location) == ("local:dev", "local")
sb._direct_url = "http://10.0.0.5:3211"
assert (sb.id, sb.location) == ("direct:10.0.0.5:3211", "direct")
-
-
-def test_native_ambiguity_becomes_the_typed_error():
- from cua_sandbox._sdk import native
- from cua_sandbox.spec import translate_native_error
-
- n = native()
- e = translate_native_error(
- n.CuaError.AmbiguousSandbox('"box" names 2 sandboxes; use one of: local:box, cloud:box')
- )
- assert isinstance(e, AmbiguousSandbox)
- assert e.candidates == ["local:box", "cloud:box"]
diff --git a/libs/python/cua-sandbox/tests/test_runtime.py b/libs/python/cua-sandbox/tests/test_runtime.py
index 76b38ca133..7386df59e1 100644
--- a/libs/python/cua-sandbox/tests/test_runtime.py
+++ b/libs/python/cua-sandbox/tests/test_runtime.py
@@ -31,10 +31,6 @@ IS_WINDOWS = platform.system() == "Windows"
IS_MACOS = platform.system() == "Darwin"
-def _has_cua_api_key() -> bool:
- return bool(os.environ.get("CUA_API_KEY"))
-
-
# ── Helpers ──────────────────────────────────────────────────────────────────
@@ -550,36 +546,6 @@ async def test_auto_runtime_windows():
assert screenshot[:4] == b"\x89PNG"
-# ── 11. Cloud sandboxes (local=False) ────────────────────────────────────────
-
-
[email protected](not _has_cua_api_key(), reason="CUA_API_KEY not set")
-async def test_cloud_linux_ephemeral():
- """Cloud sandbox: Sandbox.ephemeral with linux image (local=False)."""
- async with Sandbox.ephemeral(
- Image.linux("ubuntu", "24.04"),
- local=False,
- ) as sb:
- result = await sb.shell.run("uname -s")
- assert result.success
- assert "Linux" in result.stdout
-
- screenshot = await sb.screenshot()
- assert screenshot[:4] == b"\x89PNG"
-
-
[email protected](not _has_cua_api_key(), reason="CUA_API_KEY not set")
-async def test_cloud_android_ephemeral():
- """Cloud sandbox: Sandbox.ephemeral with android image (local=False)."""
- async with Sandbox.ephemeral(
- Image.android("14"),
- local=False,
- ) as sb:
- screenshot = await sb.screenshot()
- assert screenshot[:4] == b"\x89PNG"
- assert len(screenshot) > 1000
-
-
# ── 12. Sandbox.create (persistent) ─────────────────────────────────────────
@@ -603,19 +569,3 @@ async def test_create_persistent_linux():
assert screenshot[:4] == b"\x89PNG"
finally:
await sb.disconnect()
-
-
[email protected](not _has_cua_api_key(), reason="CUA_API_KEY not set")
-async def test_create_persistent_cloud_linux():
- """Sandbox.create provisions a persistent cloud sandbox."""
- sb = await Sandbox.create(
- Image.linux("ubuntu", "24.04"),
- name="cua-test-create-cloud-linux",
- local=False,
- )
- try:
- result = await sb.shell.run("echo persistent")
- assert result.success
- assert "persistent" in result.stdout
- finally:
- await sb.disconnect()
diff --git a/libs/python/cua-sandbox/tests/test_sandbox_fleet_lifecycle.py b/libs/python/cua-sandbox/tests/test_sandbox_fleet_lifecycle.py
deleted file mode 100644
index 7b0c35b6cd..0000000000
--- a/libs/python/cua-sandbox/tests/test_sandbox_fleet_lifecycle.py
+++ /dev/null
@@ -1,485 +0,0 @@
-from __future__ import annotations
-
-from types import SimpleNamespace
-from unittest.mock import AsyncMock
-
-import pytest
-from cua_sandbox import Image, Pool, Sandbox, _autopool
-
-
[email protected](autouse=True)
-def select_fleet_for_lifecycle_tests(monkeypatch):
- monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: api_key is None))
-
-
-def managed_sandbox(pool_name: str, claim_name: str) -> SimpleNamespace:
- """What _autopool.acquire returns: a sandbox holding a managed claim."""
- return SimpleNamespace(
- name=f"sbx-{claim_name}",
- claim_name=claim_name,
- pool_name=pool_name,
- _claim_handle=SimpleNamespace(
- state_fields=lambda: {"managed": True, "spec_hash": "0" * 64, "claim_ttl": 900}
- ),
- _ephemeral=False,
- telemetry_enabled=False,
- keep_alive=AsyncMock(),
- close=AsyncMock(),
- )
-
-
-class FakePool:
- def __init__(self, name: str = "workspace") -> None:
- self.name = name
- self.claims: list[dict] = []
- self.deletes = 0
-
- async def claim(self, **kwargs):
- self.claims.append(kwargs)
- return SimpleNamespace(name="sandbox-1", claim_name=kwargs.get("name"), pool_name=self.name)
-
- async def delete(self):
- self.deletes += 1
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_create_with_pool_name_uses_read_only_pool_lookup(monkeypatch):
- pool = FakePool()
- looked_up: list[str] = []
-
- async def get_pool(cls, name: str):
- looked_up.append(name)
- return pool
-
- monkeypatch.setattr(Pool, "get", classmethod(get_pool), raising=False)
-
- sandbox = await Sandbox.create(pool="workspace", name="job-123", service="mcp", local=False)
-
- assert looked_up == ["workspace"]
- assert pool.claims == [
- {"name": "job-123", "spec": None, "service": "mcp", "time_to_start": None}
- ]
- assert sandbox.claim_name == "job-123"
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_create_with_fleet_image_claims_from_managed_pool(monkeypatch, tmp_path):
- # Was test_create_with_fleet_image_requires_explicit_pool: a Fleet image
- # without pool= now claims from the account's managed pool.
- from cua_sandbox import sandbox_state
-
- apply_pool = AsyncMock()
- monkeypatch.setattr(Pool, "apply", apply_pool)
- monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)
- acquired = managed_sandbox("cua-auto-abc", "job-123")
- acquire = AsyncMock(return_value=acquired)
- monkeypatch.setattr(_autopool, "acquire", acquire)
- image = Image.from_registry("registry.example/workspace:latest")
-
- sandbox = await Sandbox.create(image, name="job-123", telemetry_enabled=False, local=False)
-
- assert sandbox is acquired
- apply_pool.assert_not_awaited()
- assert acquire.await_args.args == (image,)
- assert acquire.await_args.kwargs["name"] == "job-123"
- assert sandbox_state.load("job-123")["pool_name"] == "cua-auto-abc"
- assert sandbox_state.load("job-123")["managed"] is True
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_create_persists_generated_claim_pool_mapping(monkeypatch, tmp_path):
- from cua_sandbox import sandbox_state
-
- class ClaimedSandbox:
- name = "bound-sandbox-1"
- claim_name = "generated-claim-1"
- pool_name = "workspace"
-
- pool = FakePool("workspace")
-
- async def claim(**kwargs):
- pool.claims.append(kwargs)
- return ClaimedSandbox()
-
- pool.claim = claim
- monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)
- monkeypatch.setattr(Pool, "get", AsyncMock(return_value=pool))
-
- sandbox = await Sandbox.create(pool="workspace", local=False)
-
- assert sandbox.name == "bound-sandbox-1"
- assert sandbox.claim_name == "generated-claim-1"
- assert sandbox_state.load("generated-claim-1")["pool_name"] == "workspace"
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
[email protected]("source", ["existing-pool", "pool-object"])
-async def test_keep_alive_failure_releases_claim_without_persisting_state(
- monkeypatch, tmp_path, source
-):
- from cua_sandbox import sandbox_state
-
- claimed = SimpleNamespace(
- name="bound-sandbox-1",
- claim_name="job-123",
- pool_name="workspace",
- keep_alive=AsyncMock(side_effect=RuntimeError("renew failed")),
- close=AsyncMock(),
- )
- pool = FakePool("workspace")
- pool.claim = AsyncMock(return_value=claimed)
- monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)
-
- if source == "existing-pool":
- monkeypatch.setattr(Pool, "get", AsyncMock(return_value=pool))
- create = Sandbox.create(
- pool="workspace", name="job-123", keep_alive_minutes=30, local=False
- )
- else:
- create = Sandbox.create(pool=pool, name="job-123", keep_alive_minutes=30, local=False)
-
- with pytest.raises(RuntimeError, match="renew failed"):
- await create
-
- claimed.close.assert_awaited_once()
- assert sandbox_state.load("job-123") is None
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_state_persistence_failure_releases_acquired_claim(monkeypatch, tmp_path):
- from cua_sandbox import sandbox_state
-
- claimed = SimpleNamespace(
- name="bound-sandbox-1",
- claim_name="job-123",
- pool_name="workspace",
- close=AsyncMock(),
- )
- pool = FakePool("workspace")
- pool.claim = AsyncMock(return_value=claimed)
- monkeypatch.setattr(Pool, "get", AsyncMock(return_value=pool))
- monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)
- monkeypatch.setattr(
- sandbox_state,
- "save_fleet_claim",
- lambda *args, **kwargs: (_ for _ in ()).throw(OSError("state write failed")),
- )
-
- with pytest.raises(OSError, match="state write failed"):
- await Sandbox.create(pool="workspace", name="job-123", local=False)
-
- claimed.close.assert_awaited_once()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_keep_alive_failure_preserves_error_when_claim_close_fails(monkeypatch):
- claimed = SimpleNamespace(
- name="bound-sandbox-1",
- claim_name="job-123",
- pool_name="workspace",
- keep_alive=AsyncMock(side_effect=RuntimeError("renew failed")),
- close=AsyncMock(side_effect=RuntimeError("close failed")),
- )
- pool = FakePool("workspace")
- pool.claim = AsyncMock(return_value=claimed)
-
- with pytest.raises(RuntimeError, match="renew failed") as error:
- await Sandbox.create(pool=pool, name="job-123", keep_alive_minutes=30, local=False)
-
- assert isinstance(error.value.__cause__, RuntimeError)
- assert str(error.value.__cause__) == "close failed"
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_create_compares_an_image_given_with_a_pool(monkeypatch):
- from cua_sandbox import Pool, PoolSpecMismatch
-
- seen: list = []
-
- async def check(name, spec):
- seen.append((name, spec.reference()))
- raise PoolSpecMismatch("image: pool has other@sha256:1, requested ...")
-
- monkeypatch.setattr(Pool, "check", staticmethod(check))
- with pytest.raises(PoolSpecMismatch, match="image"):
- await Sandbox.create(
- Image.from_registry("registry.example/workspace:latest"), pool="pool", local=False
- )
- assert seen == [("pool", "registry.example/workspace:latest")]
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_create_rejects_pool_configuration_for_existing_pool():
- with pytest.raises(ValueError, match="existing pool"):
- await Sandbox.create(pool="pool", replicas=2, local=False)
-
-
-class FakeTransport:
- def __init__(self) -> None:
- self.disconnects = 0
-
- async def connect(self) -> None:
- return None
-
- async def disconnect(self) -> None:
- self.disconnects += 1
-
-
-class FakeClaimHandle:
- name = "job-123"
- pool_name = "workspace"
-
- def __init__(self) -> None:
- self.releases = 0
- self.renewals: list[str] = []
-
- def to_dict(self):
- return {
- "version": 1,
- "provider": "fleet",
- "namespace": "workspace",
- "pool": "workspace",
- "claim": "job-123",
- }
-
- async def release(self) -> None:
- self.releases += 1
-
- async def renew(self, shutdown_time: str) -> None:
- self.renewals.append(shutdown_time)
-
-
-async def test_disconnect_keeps_claim_and_close_releases_once():
- transport = FakeTransport()
- handle = FakeClaimHandle()
- sandbox = Sandbox(transport, name="sandbox-1")
- sandbox._claim_handle = handle
-
- await sandbox.disconnect()
- assert handle.releases == 0
-
- await sandbox.close()
- await sandbox.close()
-
- assert handle.releases == 1
- assert transport.disconnects == 2
-
-
-async def test_close_removes_persisted_claim_mapping(monkeypatch, tmp_path):
- from cua_sandbox import sandbox_state
-
- monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)
- sandbox_state.save_fleet_claim("job-123", "workspace")
- handle = FakeClaimHandle()
- sandbox = Sandbox(FakeTransport(), name="sandbox-1")
- sandbox._claim_handle = handle
-
- await sandbox.close()
-
- assert sandbox_state.load("job-123") is None
-
-
-async def test_keep_alive_renews_with_utc_deadline():
- handle = FakeClaimHandle()
- sandbox = Sandbox(FakeTransport(), name="sandbox-1")
- sandbox._claim_handle = handle
-
- await sandbox.keep_alive(minutes=30)
-
- assert len(handle.renewals) == 1
- assert handle.renewals[0].endswith("Z")
-
-
-def test_to_dict_serializes_claim_not_bound_transport():
- handle = FakeClaimHandle()
- sandbox = Sandbox(FakeTransport(), name="sandbox-1")
- sandbox._claim_handle = handle
-
- assert sandbox.claim_name == "job-123"
- assert sandbox.pool_name == "workspace"
- assert sandbox.to_dict()["claim"] == "job-123"
- assert "sandbox-1" not in str(sandbox.to_dict())
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_ephemeral_pool_closes_claim(monkeypatch):
- closed: list[bool] = []
-
- class Claimed:
- async def close(self):
- closed.append(True)
-
- async def create(cls, *args, **kwargs):
- return Claimed()
-
- monkeypatch.setattr(Sandbox, "create", classmethod(create))
-
- async with Sandbox.ephemeral(pool="workspace", local=False):
- pass
-
- assert closed == [True]
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_ephemeral_image_uses_name_for_the_claim_on_a_managed_pool(monkeypatch):
- # Was test_ephemeral_image_uses_name_for_owned_pool_and_claim: name= now
- # names the claim; the managed pool is reused and never deleted.
- claimed = managed_sandbox("cua-auto-abc", "cua-live-main-source-manual")
- acquire = AsyncMock(return_value=claimed)
- monkeypatch.setattr(_autopool, "acquire", acquire)
- apply_pool = AsyncMock()
- monkeypatch.setattr(Pool, "apply", apply_pool)
- image = Image.from_registry("registry.example/workspace:latest")
-
- async with Sandbox.ephemeral(
- image,
- name="cua-live-main-source-manual",
- cpu=4,
- memory_mb=4096,
- telemetry_enabled=False,
- local=False,
- ):
- pass
-
- apply_pool.assert_not_awaited()
- kwargs = acquire.await_args.kwargs
- assert kwargs["name"] == "cua-live-main-source-manual"
- assert (kwargs["cpu"], kwargs["memory_mb"], kwargs["service"]) == (4, 4096, "env")
- claimed.close.assert_awaited_once()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
- "kwargs",
- [
- {"image": "fleet", "name": "shared-pool"},
- {"image": "fleet"},
- {"pool": "workspace"},
- {"image": "fleet", "api_key": "legacy-key"},
- ],
- ids=["named", "unnamed", "existing-pool", "legacy-cloud"],
-)
-async def test_keep_pool_is_a_deprecated_no_op(monkeypatch, kwargs):
- # Replaces the keep_pool tests (reuses named pool / requires name= /
- # rejected for existing pools / rejected outside Fleet image mode):
- # pools are reused automatically, so keep_pool only warns.
- claimed = managed_sandbox("cua-auto-abc", "claim-1")
- monkeypatch.setattr(_autopool, "acquire", AsyncMock(return_value=claimed))
- monkeypatch.setattr(Sandbox, "create", AsyncMock(return_value=claimed))
- legacy = SimpleNamespace(_has_snapshots=False, name="legacy", destroy=AsyncMock())
- monkeypatch.setattr(Sandbox, "_create", AsyncMock(return_value=legacy))
- if kwargs.get("image") == "fleet":
- kwargs = {**kwargs, "image": Image.from_registry("registry.example/workspace:latest")}
-
- with pytest.warns(DeprecationWarning, match="keep_pool"):
- async with Sandbox.ephemeral(
- keep_pool=True, telemetry_enabled=False, **kwargs, local=False
- ):
- pass
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_ephemeral_image_without_name_never_creates_a_disposable_pool(monkeypatch):
- # Was test_ephemeral_image_without_name_applies_random_disposable_pool:
- # no cua-eph-* pool is applied or deleted any more.
- claimed = managed_sandbox("cua-auto-abc", "generated-claim")
- acquire = AsyncMock(return_value=claimed)
- monkeypatch.setattr(_autopool, "acquire", acquire)
- apply_pool = AsyncMock()
- monkeypatch.setattr(Pool, "apply", apply_pool)
-
- async with Sandbox.ephemeral(
- Image.from_registry("registry.example/workspace:latest"),
- telemetry_enabled=False,
- local=False,
- ):
- pass
-
- apply_pool.assert_not_awaited()
- assert acquire.await_args.kwargs["name"] is None
- claimed.close.assert_awaited_once()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_ephemeral_image_propagates_acquire_failure(monkeypatch):
- # Was test_ephemeral_image_deletes_owned_pool_when_claim_fails: the
- # manager releases its own claim; there is no owned pool to delete.
- monkeypatch.setattr(_autopool, "acquire", AsyncMock(side_effect=RuntimeError("claim failed")))
-
- with pytest.raises(RuntimeError, match="claim failed"):
- async with Sandbox.ephemeral(
- Image.from_registry("registry.example/workspace:latest"), local=False
- ):
- pass
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_ephemeral_image_preserves_body_error_when_claim_cleanup_fails(monkeypatch):
- # Was ..._when_owned_pool_cleanup_fails.
- claimed = managed_sandbox("cua-auto-abc", "claim-1")
- claimed.close = AsyncMock(side_effect=RuntimeError("claim cleanup failed"))
- monkeypatch.setattr(_autopool, "acquire", AsyncMock(return_value=claimed))
-
- with pytest.raises(ValueError, match="body failed"):
- async with Sandbox.ephemeral(
- Image.from_registry("registry.example/workspace:latest"),
- telemetry_enabled=False,
- local=False,
- ):
- raise ValueError("body failed")
-
- claimed.close.assert_awaited_once()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_ephemeral_forwards_the_fleet_runtime_to_the_managed_pool(monkeypatch):
- # Was ..._to_the_owned_pool: the runtime is part of the managed pool key.
- claimed = managed_sandbox("cua-auto-abc", "claim-1")
- acquire = AsyncMock(return_value=claimed)
- monkeypatch.setattr(_autopool, "acquire", acquire)
- image = Image.from_registry("public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04:main-1")
-
- async with Sandbox.ephemeral(image, runtime="gvisor", telemetry_enabled=False, local=False):
- pass
-
- assert acquire.await_args.kwargs["runtime"] == "gvisor"
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_a_fleet_runtime_belongs_to_the_pool_not_the_claim(monkeypatch, tmp_path):
- from cua_sandbox import sandbox_state
-
- monkeypatch.setattr(Pool, "get", AsyncMock(side_effect=AssertionError("no lookup")))
- with pytest.raises(ValueError, match="Pool.apply"):
- await Sandbox.create(pool="workspace", runtime="gvisor", local=False)
- # Without pool=, the runtime selects the managed pool.
- monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)
- acquire = AsyncMock(return_value=managed_sandbox("cua-auto-abc", "job"))
- monkeypatch.setattr(_autopool, "acquire", acquire)
- await Sandbox.create(
- Image.from_registry("registry.example/workspace:latest"),
- name="job",
- runtime="gvisor",
- telemetry_enabled=False,
- local=False,
- )
- assert acquire.await_args.kwargs["runtime"] == "gvisor"
diff --git a/libs/python/cua-sandbox/tests/test_sandbox_mcp.py b/libs/python/cua-sandbox/tests/test_sandbox_mcp.py
index 04d7b2bb19..bc190c920d 100644
--- a/libs/python/cua-sandbox/tests/test_sandbox_mcp.py
+++ b/libs/python/cua-sandbox/tests/test_sandbox_mcp.py
@@ -105,13 +105,13 @@ def server():
@pytest.mark.asyncio
async def test_config_and_official_client_keep_content_lossless(server):
pytest.importorskip("mcp")
- svc = _NativeService(server, {"x-cua-fleet-claim": "c-1"})
+ svc = _NativeService(server, {"x-test-claim": "c-1"})
async def resolve():
return svc
cfg = await mcp_mod.mcp_config(resolve, "/mcp")
- assert cfg == {"url": server + "/mcp", "headers": {"x-cua-fleet-claim": "c-1"}}
+ assert cfg == {"url": server + "/mcp", "headers": {"x-test-claim": "c-1"}}
async with mcp_mod.open_mcp(resolve) as client:
tools = await client.list_tools()
tools = getattr(tools, "tools", tools)
@@ -122,7 +122,7 @@ async def test_config_and_official_client_keep_content_lossless(server):
assert raw["content"][1] == {"type": "image", "data": PNG, "mimeType": "image/png"}
assert raw["content"][2]["mimeType"] == "audio/wav"
assert raw["structuredContent"] == {"w": 1}
- assert all(h.get("x-cua-fleet-claim") == "c-1" for h in _Handler.seen_headers)
+ assert all(h.get("x-test-claim") == "c-1" for h in _Handler.seen_headers)
@pytest.mark.asyncio
@@ -144,26 +144,6 @@ async def test_url_sandbox_resolves_the_native_service(server):
await transport.disconnect()
-async def test_fleet_transport_checks_declared_services():
- from cua_sandbox.transport.fleet import FleetTransport
-
- class Handle:
- def service(self, name):
- return name
-
- transport = FleetTransport.__new__(FleetTransport)
- transport._bound = SimpleNamespace(services=["mcp"], name="sb")
-
- async def fleet_handle():
- return Handle()
-
- transport._fleet_handle = fleet_handle
- assert await transport.native_service("mcp") == "mcp"
- with pytest.raises(ValueError, match="does not expose service 'env'"):
- await transport.native_service("env")
-
-
@pytest.mark.asyncio
async def test_live_reference_everything_server():
"""Opt-in: ``CUA_E2E_MCP_EVERYTHING_URL`` is the reference "everything"
diff --git a/libs/python/cua-sandbox/tests/test_sdk_finalizers.py b/libs/python/cua-sandbox/tests/test_sdk_finalizers.py
index e4ddeeb472..f56db2240f 100644
--- a/libs/python/cua-sandbox/tests/test_sdk_finalizers.py
+++ b/libs/python/cua-sandbox/tests/test_sdk_finalizers.py
@@ -46,11 +46,8 @@ def test_sdk_handles_alive_at_exit_print_nothing(tmp_path):
"HOME": str(home),
"CUA_HOME": str(home / ".cua"),
"CUA_CREDENTIAL_STORE": "file",
- "CUA_FLEET_SESSION": "0",
"CUA_TELEMETRY_ENABLED": "false",
}
- for var in ("FLEETS_TOKEN", "CUA_CLIENT_ID", "CUA_CLIENT_SECRET"):
- env.pop(var, None)
result = subprocess.run(
[sys.executable, "-c", SCRIPT, str(tmp_path / "state")],
env=env,
diff --git a/libs/python/cua-sandbox/tests/test_fleet_sdk_packaging.py b/libs/python/cua-sandbox/tests/test_sdk_packaging.py
similarity index 55%
rename from libs/python/cua-sandbox/tests/test_fleet_sdk_packaging.py
rename to libs/python/cua-sandbox/tests/test_sdk_packaging.py
index d1e88a8984..50014e0cc8 100644
--- a/libs/python/cua-sandbox/tests/test_fleet_sdk_packaging.py
+++ b/libs/python/cua-sandbox/tests/test_sdk_packaging.py
@@ -1,41 +1,35 @@
import tomllib
import unittest
+from importlib.metadata import distribution
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[1]
PYPROJECT_PATH = PROJECT_ROOT / "pyproject.toml"
LOCK_PATH = PROJECT_ROOT / "uv.lock"
CUA_SDK_PYPROJECT_PATH = PROJECT_ROOT.parents[1] / "cua" / "python" / "pyproject.toml"
-FLEET_IMPORTS = (
- PROJECT_ROOT / "cua_sandbox" / "transport" / "cyclops_http_client.py",
- PROJECT_ROOT / "cua_sandbox" / "transport" / "fleet.py",
- PROJECT_ROOT / "cua_sandbox" / "transport" / "fleet_cloud.py",
-)
+PACKAGE_DIR = PROJECT_ROOT / "cua_sandbox"
-class FleetSdkPackagingTests(unittest.TestCase):
- """cua-sandbox depends on two bindings: the published ``cua-fleet`` wheel
- (``fleet_sdk``: the typed Fleet resource model re-exported publicly) and
- the ``cua`` SDK (spacesd, Fleet sandboxes and local runtimes)."""
+class SdkPackagingTests(unittest.TestCase):
+ """cua-sandbox's one binding is the ``cua`` SDK (spacesd and the local
+ runtimes). It installs from PyPI alone: no extra index, no Cua Cloud
+ packages."""
- def test_declares_published_fleet_without_a_direct_train_dependency(self):
+ def test_installs_from_pypi_alone(self):
with PYPROJECT_PATH.open("rb") as pyproject_file:
project = tomllib.load(pyproject_file)
dependencies = project["project"]["dependencies"]
- self.assertIn("cua-fleet==0.1.17", dependencies)
+ self.assertFalse(any(dependency.startswith("cua-fleet") for dependency in dependencies))
self.assertFalse(any(dependency.startswith("cua-train") for dependency in dependencies))
- self.assertNotIn("cua-fleet", project["tool"]["uv"]["sources"])
- self.assertNotIn("cua-train", project["tool"]["uv"]["sources"])
- self.assertEqual(
- project["tool"]["uv"]["index"][0],
- {
- "name": "cua-wheels",
- "url": "https://wheels.cua.ai/simple",
- },
- )
+ uv = project["tool"]["uv"]
+ self.assertNotIn("index", uv)
+ self.assertNotIn("cua-fleet", uv["sources"])
+ self.assertNotIn("pdm", project["tool"])
+ self.assertNotIn("wheels.cua.ai", PYPROJECT_PATH.read_text())
- def test_lock_uses_the_published_fleet_bundle(self):
+ def test_lock_has_no_cloud_packages_and_no_extra_index(self):
+ lock_text = LOCK_PATH.read_text()
with LOCK_PATH.open("rb") as lock_file:
lock = tomllib.load(lock_file)
@@ -43,23 +37,10 @@ class FleetSdkPackagingTests(unittest.TestCase):
sandbox_dependencies = {
dependency["name"] for dependency in packages["cua-sandbox"]["dependencies"]
}
- sandbox_requires_dist = {
- requirement["name"]
- for requirement in packages["cua-sandbox"]["metadata"]["requires-dist"]
- }
- fleet_dependencies = {
- dependency["name"] for dependency in packages["cua-fleet"].get("dependencies", [])
- }
- self.assertIn("cua-fleet", sandbox_dependencies)
- self.assertNotIn("cua-train", sandbox_dependencies)
- self.assertIn("cua-fleet", sandbox_requires_dist)
- self.assertNotIn("cua-train", sandbox_requires_dist)
- self.assertEqual(packages["cua-fleet"]["version"], "0.1.17")
- self.assertEqual(
- packages["cua-fleet"]["source"], {"registry": "https://wheels.cua.ai/simple"}
- )
- self.assertNotIn("cua-train", fleet_dependencies)
+ self.assertNotIn("cua-fleet", packages)
+ self.assertNotIn("cua-fleet", sandbox_dependencies)
self.assertNotIn("cua-train", packages)
+ self.assertNotIn("wheels.cua.ai", lock_text)
def test_depends_on_the_cua_sdk_for_the_data_plane(self):
with PYPROJECT_PATH.open("rb") as pyproject_file:
@@ -96,14 +77,23 @@ class FleetSdkPackagingTests(unittest.TestCase):
project = tomllib.load(pyproject_file)
self.assertNotIn("hooks", project.get("tool", {}).get("hatch", {}).get("build", {}))
- def test_fleet_runtime_imports_published_binding_directly(self):
- for source_path in FLEET_IMPORTS:
+ def test_source_never_imports_the_fleet_sdk(self):
+ for source_path in PACKAGE_DIR.rglob("*.py"):
source = source_path.read_text()
- self.assertIn("from fleet_sdk import", source)
- self.assertNotIn("from cua_train", source)
- self.assertNotIn("sys.path", source)
- self.assertNotIn("site.addsitedir", source)
- self.assertNotIn("ctypes.CDLL", source)
+ self.assertNotIn("fleet_sdk", source, source_path)
+ self.assertNotIn("import cua_fleet", source, source_path)
+
+ def test_cua_sdk_is_the_native_binding_distribution(self):
+ """cua-sandbox's data plane is the cua SDK (``cua`` >= 0.2, UniFFI over
+ cua-sdk), not the old ``cua`` meta-package (0.1.x, pure re-exports)."""
+ import cua
+
+ cua_distribution = distribution("cua")
+ major, minor = (int(part) for part in cua_distribution.version.split(".")[:2])
+
+ self.assertGreaterEqual((major, minor), (0, 2))
+ self.assertTrue(hasattr(cua, "_native") and hasattr(cua._native, "Cua"))
+ self.assertTrue(hasattr(cua._native, "SpacesdClient"))
if __name__ == "__main__":
diff --git a/libs/python/cua-sandbox/tests/test_snapshots.py b/libs/python/cua-sandbox/tests/test_snapshots.py
deleted file mode 100644
index 68f969c4b1..0000000000
--- a/libs/python/cua-sandbox/tests/test_snapshots.py
+++ /dev/null
@@ -1,110 +0,0 @@
-"""Snapshot integration tests — images all the way down.
-
-Tests both Linux VM and Android container snapshot workflows:
-1. Create sandbox → install something → snapshot → returns Image
-2. Boot from snapshot Image → verify install persists → measure fork is faster
-3. Verify state isolation (changes after snapshot don't leak to fork)
-
-Run against local dev stack:
- CUA_API_KEY=sk-dev-test-key-local-12345 CUA_BASE_URL=http://localhost:8082 \
- pytest tests/test_snapshots.py -v -s
-"""
-
-from __future__ import annotations
-
-import os
-import time
-
-import pytest
-from cua_sandbox import Image, Sandbox
-
-pytestmark = pytest.mark.asyncio
-
-
-def _has_cua_api_key() -> bool:
- return bool(os.environ.get("CUA_API_KEY"))
-
-
[email protected](not _has_cua_api_key(), reason="CUA_API_KEY not set")
-async def test_snapshot_linux():
- """Linux: create → install cowsay → snapshot → boot from snapshot → verify."""
- t_create_start = time.monotonic()
-
- async with Sandbox.ephemeral(Image.linux("ubuntu", "24.04"), local=False) as sb:
- # Install something unique
- result = await sb.shell.run(
- "apt-get update -qq && apt-get install -y -qq cowsay", timeout=120
- )
- assert result.success, f"Install failed: {result.stderr}"
-
- # Measure create+install time only after install completes
- t_create = time.monotonic() - t_create_start
-
- # Verify it works
- result = await sb.shell.run("/usr/games/cowsay hello")
- assert result.success
- assert "hello" in result.stdout
-
- # Snapshot → returns Image
- cowsay_image = await sb.snapshot(name="with-cowsay")
- assert cowsay_image is not None
- assert cowsay_image._snapshot_source is not None
-
- # Boot from snapshot image — should be faster (COW fork)
- t_fork_start = time.monotonic()
- async with Sandbox.ephemeral(cowsay_image, local=False) as sb2:
- t_fork = time.monotonic() - t_fork_start
-
- # cowsay should still be installed
- result = await sb2.shell.run("/usr/games/cowsay forked!")
- assert result.success, f"cowsay not found in fork: {result.stderr}"
- assert "forked!" in result.stdout
-
- print(f"\nCreate+install: {t_create:.1f}s, Fork from snapshot: {t_fork:.1f}s")
- # Fork should be faster than original create + install
- assert (
- t_fork < t_create
- ), f"Fork ({t_fork:.1f}s) should be faster than create ({t_create:.1f}s)"
-
-
[email protected](not _has_cua_api_key(), reason="CUA_API_KEY not set")
-async def test_snapshot_android():
- """Android: create with F-Droid → snapshot → boot from snapshot → APK persists."""
- FDROID_APK = "https://f-droid.org/F-Droid.apk"
- t_create_start = time.monotonic()
-
- async with Sandbox.ephemeral(Image.android("14").apk_install(FDROID_APK), local=False) as sb:
- t_create = time.monotonic() - t_create_start
-
- # Verify F-Droid installed (sb.shell.run on android → adb shell)
- result = await sb.shell.run("pm list packages org.fdroid.fdroid")
- assert result.success
- assert "org.fdroid.fdroid" in result.stdout
-
- screenshot = await sb.screenshot()
- assert screenshot[:4] == b"\x89PNG"
-
- # Snapshot → Image
- fdroid_image = await sb.snapshot(name="with-fdroid")
-
- # Boot from snapshot — F-Droid should persist
- t_fork_start = time.monotonic()
- async with Sandbox.ephemeral(fdroid_image, local=False) as sb2:
- t_fork = time.monotonic() - t_fork_start
-
- result = await sb2.shell.run("pm list packages org.fdroid.fdroid")
- assert result.success, f"F-Droid not found in fork: {result.stderr}"
- assert "org.fdroid.fdroid" in result.stdout
-
- screenshot = await sb2.screenshot()
- assert screenshot[:4] == b"\x89PNG"
- assert len(screenshot) > 1000
-
- print(f"\nCreate+install: {t_create:.1f}s, Fork from snapshot: {t_fork:.1f}s")
- # On COW storage (btrfs/zfs), fork is instant. On dir storage the copy
- # is a full rsync so it can be slower than the original create. Only
- # assert that the fork completed (timing checked on COW backends in CI).
- if t_fork < t_create:
- print(" → Fork was faster (COW or small image)")
- else:
- print(" → Fork was slower (dir storage — expected)")
diff --git a/libs/python/cua-sandbox/tests/test_typed_driver.py b/libs/python/cua-sandbox/tests/test_typed_driver.py
deleted file mode 100644
index df4d7e1ae4..0000000000
--- a/libs/python/cua-sandbox/tests/test_typed_driver.py
+++ /dev/null
@@ -1,670 +0,0 @@
-"""Fleet carrier contracts without requiring the optional native Driver library."""
-
-import asyncio
-import json
-import sys
-from types import SimpleNamespace
-
-import httpx
-import pytest
-from cua_sandbox.interfaces.driver import DriverConnectionError
-from cua_sandbox.sandbox import Sandbox
-from cua_sandbox.transport.base import Transport as BaseTransport
-from cua_sandbox.transport.fleet import FleetTransport
-from cua_sandbox.transport.fleet_cloud import FleetCloudTransport
-
-
-class ChannelError(Exception):
- pass
-
-
-class CanonicalDriver:
- def __init__(self, channel):
- self.channel = channel
- self.shutdowns = 0
-
- async def shutdown(self):
- self.shutdowns += 1
- await self.channel.close()
-
-
-def native(monkeypatch):
- sdk = SimpleNamespace(
- CuaDriver=CanonicalDriver,
- ForeignDriverEnvelopeChannel=object,
- ForeignDriverChannelError=SimpleNamespace(Failed=ChannelError),
- ForeignDriverChannelCapabilities=SimpleNamespace,
- ForeignDriverChannelIdentity=SimpleNamespace,
- ForeignDriverResponseEnvelope=SimpleNamespace,
- connect_remote_channel=CanonicalDriver,
- _native=SimpleNamespace(uniffi_set_event_loop=lambda loop: None),
- )
- monkeypatch.setitem(sys.modules, "cua_driver", sdk)
- return sdk
-
-
-def negotiation():
- return dict(
- connection_id="connection-1",
- generation="generation-1",
- public_session="session-1",
- capabilities=dict(
- minimum_envelope_version=1, maximum_envelope_version=1, supports_cancellation=True
- ),
- )
-
-
-def envelope(**overrides):
- return SimpleNamespace(
- **dict(
- dict(
- envelope_version=1,
- request_id="request-1",
- operation="call",
- name="get_screen_size",
- arguments_json='{"session":null}',
- deadline_unix_ms=1900000000000,
- ),
- **overrides,
- )
- )
-
-
-class PlainTransport(BaseTransport):
- """A transport with neither Fleet services nor cua-spacesd (e.g. QMP/VNC)."""
-
- async def connect(self):
- pass
-
- async def disconnect(self):
- pass
-
- async def send(self, action, **params):
- raise NotImplementedError
-
- async def screenshot(self, format="png", quality=95):
- raise NotImplementedError
-
- async def get_screen_size(self):
- raise NotImplementedError
-
- async def get_environment(self):
- return "linux"
-
-
-class Transport(FleetTransport):
- def __init__(self):
- super().__init__(
- sdk=None, bound=SimpleNamespace(services=["server", "driver"]), service_name="server"
- )
- self.events = []
- self.open_data = negotiation()
- self.response_data = dict(
- envelope_version=1,
- request_id="request-1",
- ok=True,
- result={"width": 1280},
- completion_known=True,
- )
- self.status = 200
-
- async def request_service(
- self,
- name,
- *,
- method,
- path,
- json_body=None,
- body=None,
- headers=None,
- timeout=None,
- max_response_bytes=None,
- ):
- assert self._connected
- assert body is None
- assert max_response_bytes is None
- self.events.append((name, method, path, json_body, headers))
- data = self.open_data if path == "/v1/connections" else self.response_data
- return httpx.Response(self.status, json=data)
-
- async def disconnect(self):
- self.events.append("disconnect")
- await super().disconnect()
-
-
-async def sandbox(native):
- sb = Sandbox(Transport(), _telemetry_enabled=False)
- await sb._connect()
- yield sb
- await sb.disconnect()
-
-
-async def test_canonical_driver_preserves_default_transport_and_pins_wire(sandbox):
- transport = sandbox._transport
- async with sandbox.driver.connect() as driver:
- assert isinstance(driver, CanonicalDriver)
- assert sandbox._transport is transport
- for interface in (sandbox.shell, sandbox.files, sandbox.mouse, sandbox.keyboard):
- assert interface._t is transport
- assert transport._service_name == "server"
- channel = driver.channel
- assert channel.public_session == "session-1"
- assert channel.identity().connection_generation == "generation-1"
- assert channel.identity().authenticated_principal != "session-1"
- assert (await channel.negotiate()).supports_cancellation
- result = await channel.exchange(envelope())
- assert json.loads(result.result_json) == {"width": 1280}
- _, method, path, body, headers = transport.events[-1]
- assert (method, path) == ("POST", "/v1/connections/connection-1/exchange")
- assert body["arguments"] == {"session": None}
- assert body["deadline_unix_ms"] == 1900000000000
- assert headers == {"X-Cua-Driver-Generation": "generation-1"}
- assert driver.shutdowns == 1
- assert transport.events[-1][1:3] == ("DELETE", "/v1/connections/connection-1")
- assert transport._connected
-
-
-async def test_disconnect_closes_before_transport_and_context_exit_is_idempotent(sandbox):
- async with sandbox.driver.connect() as driver:
- await sandbox.disconnect()
- assert sandbox._transport.events[-2][1] == "DELETE"
- assert sandbox._transport.events[-1] == "disconnect"
- with pytest.raises(ChannelError, match="closed"):
- await driver.channel.exchange(envelope())
- assert driver.shutdowns == 1
- with pytest.raises(DriverConnectionError, match="disconnected"):
- async with sandbox.driver.connect():
- pass
-
-
-async def test_claim_close_orders_driver_release_transport(sandbox):
- async def release():
- sandbox._transport.events.append("release")
-
- sandbox._claim_handle = SimpleNamespace(release=release, name=None)
- async with sandbox.driver.connect() as driver:
- await sandbox.close()
- assert sandbox._transport.events[-3][1] == "DELETE"
- assert sandbox._transport.events[-2:] == ["release", "disconnect"]
- assert driver.shutdowns == 1
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_pool_claim_context_closes_driver_before_claim_and_client(native, monkeypatch):
- from cua_sandbox import Pool
-
- from .test_pool import FakeFleetClient, fleet_pool
-
- events = []
-
- class Client(FakeFleetClient):
- async def wait_claim(self, claim):
- bound = await super().wait_claim(claim)
- bound.services.append("driver")
- return bound
-
- async def service_request(self, sandbox, service, path, request):
- events.append(request.method)
- return SimpleNamespace(status=200, headers=[], body=json.dumps(negotiation()).encode())
-
- async def delete_claim(self, claim):
- events.append("release")
- await super().delete_claim(claim)
-
- async def close(self):
- events.append("client-close")
- await super().close()
-
- client = Client()
- monkeypatch.setattr("cua_sandbox.pool._FleetClient", lambda: client)
- async with Pool(fleet_pool()).claim() as sb:
- context = sb.driver.connect()
- driver = await context.__aenter__()
- assert events == ["POST", "DELETE", "release", "client-close"]
- await context.__aexit__(None, None, None)
- assert driver.shutdowns == 1
- assert client.deleted_pools == []
- assert client.deleted_templates == []
-
-
-async def test_all_connections_close_when_one_shutdown_fails(sandbox):
- first = sandbox.driver.connect()
- second = sandbox.driver.connect()
- driver = await first.__aenter__()
- other = await second.__aenter__()
-
- async def fail():
- raise RuntimeError("shutdown failed")
-
- driver.shutdown = fail
- await sandbox.disconnect()
- assert driver.channel.closed and other.channel.closed
- assert other.shutdowns == 1
- await first.__aexit__(None, None, None)
- await second.__aexit__(None, None, None)
-
-
-async def test_oversized_request_is_not_dispatched(sandbox):
- async with sandbox.driver.connect() as driver:
- with pytest.raises(ChannelError, match="size limit"):
- await driver.channel.exchange(envelope(arguments_json=json.dumps("x" * 1024 * 1024)))
- assert len(sandbox._transport.events) == 1
-
-
- "status,reason",
- [
- (401, "authorization"),
- (403, "authorization"),
- (404, "stale"),
- (409, "stale"),
- (426, "incompatible"),
- (500, "unknown"),
- ],
-)
-async def test_exchange_errors_are_sanitized_and_never_replayed(sandbox, status, reason):
- async with sandbox.driver.connect() as driver:
- sandbox._transport.status = status
- sandbox._transport.response_data = {"error": "secret-desktop-content"}
- with pytest.raises(ChannelError, match=reason) as error:
- await driver.channel.exchange(envelope())
- assert "secret" not in str(error.value)
- assert len(sandbox._transport.events) == (3 if status in (404, 409) else 4)
- assert sandbox._transport.events[-1][1] == "DELETE"
- assert driver.channel.closed
- before = len(sandbox._transport.events)
- with pytest.raises(ChannelError, match="closed"):
- await driver.channel.exchange(envelope(request_id="next-request"))
- assert len(sandbox._transport.events) == before
-
-
- "field,value",
- [
- ("capabilities", {}),
- ("public_session", None),
- (
- "capabilities",
- dict(
- minimum_envelope_version=2, maximum_envelope_version=2, supports_cancellation=True
- ),
- ),
- ],
-)
-async def test_malformed_negotiation_closes_known_session(sandbox, field, value):
- sandbox._transport.open_data[field] = value
- with pytest.raises(ChannelError, match="negotiation"):
- async with sandbox.driver.connect():
- pass
- assert sandbox._transport.events[-1][1] == "DELETE"
- assert not sandbox.driver._connections
-
-
-async def test_factory_failure_closes_opened_session(sandbox, native):
- def fail(channel):
- raise RuntimeError("factory failed")
-
- native.connect_remote_channel = fail
- with pytest.raises(RuntimeError, match="factory failed"):
- async with sandbox.driver.connect():
- pass
- assert sandbox._transport.events[-1][1] == "DELETE"
-
-
-async def test_missing_completion_is_not_assumed_success(sandbox):
- async with sandbox.driver.connect() as driver:
- del sandbox._transport.response_data["completion_known"]
- with pytest.raises(ChannelError, match="malformed"):
- await driver.channel.exchange(envelope())
-
-
-async def test_cancelled_request_never_dispatches_and_cancel_after_close_is_local(sandbox):
- async with sandbox.driver.connect() as driver:
- await driver.channel.cancel("request-1")
- with pytest.raises(ChannelError, match="cancelled"):
- await driver.channel.exchange(envelope())
- assert not any(
- isinstance(e, tuple) and e[2].endswith("exchange") for e in sandbox._transport.events
- )
- before = len(sandbox._transport.events)
- await driver.channel.cancel("request-2")
- assert len(sandbox._transport.events) == before
-
-
-async def test_bind_session_is_unsupported_without_dispatch(sandbox):
- async with sandbox.driver.connect() as driver:
- with pytest.raises(ChannelError, match="rebinding is unsupported"):
- await driver.channel.bind_session(object())
- assert len(sandbox._transport.events) == 1
-
-
-async def test_unsupported_transport_and_missing_service_do_not_load_native(monkeypatch):
- monkeypatch.setitem(sys.modules, "cua_driver", None)
- sb = Sandbox(PlainTransport(), _telemetry_enabled=False)
- with pytest.raises(DriverConnectionError, match="Fleet"):
- async with sb.driver.connect():
- pass
- transport = Transport()
- await transport.connect()
- transport._bound.services = ["server"]
- sb = Sandbox(transport, _telemetry_enabled=False)
- with pytest.raises(DriverConnectionError, match="expose"):
- async with sb.driver.connect():
- pass
- transport._bound.services.append("driver")
- with pytest.raises(DriverConnectionError, match="Install"):
- async with sb.driver.connect():
- pass
- assert not transport.events
-
-
-def test_fleet_cloud_uses_supported_transport():
- assert issubclass(FleetCloudTransport, FleetTransport)
-
-
-async def test_accessor_rejects_cleanup_from_another_event_loop(sandbox):
- async with sandbox.driver.connect():
-
- def wrong_loop():
- with pytest.raises(DriverConnectionError, match="different event loop"):
- asyncio.run(sandbox.driver.close())
-
- await asyncio.to_thread(wrong_loop)
-
-
-async def test_context_cancellation_closes_session(sandbox):
- opened = asyncio.Event()
-
- async def run():
- async with sandbox.driver.connect():
- opened.set()
- await asyncio.Event().wait()
-
- task = asyncio.create_task(run())
- await opened.wait()
- task.cancel()
- with pytest.raises(asyncio.CancelledError):
- await task
- assert sandbox._transport.events[-1][1] == "DELETE"
- assert not sandbox.driver._connections
-
-
-async def test_native_fleet_authorization_exception_is_sanitized(sandbox, monkeypatch):
- class Denied(Exception):
- status = 403
-
- async def denied(*args, **kwargs):
- raise Denied("synthetic-secret")
-
- monkeypatch.setattr(sandbox._transport, "request_service", denied)
- with pytest.raises(ChannelError, match="authorization denied") as error:
- async with sandbox.driver.connect():
- pass
- assert "synthetic-secret" not in str(error.value)
- assert error.value.__suppress_context__
-
-
-async def test_late_response_after_cancel_is_not_returned(sandbox, monkeypatch):
- started, finish = asyncio.Event(), asyncio.Event()
- original = sandbox._transport.request_service
-
- async def delayed(*args, **kwargs):
- if kwargs["path"].endswith("/exchange"):
- started.set()
- await finish.wait()
- return await original(*args, **kwargs)
-
- monkeypatch.setattr(sandbox._transport, "request_service", delayed)
- async with sandbox.driver.connect() as driver:
- task = asyncio.create_task(driver.channel.exchange(envelope()))
- await started.wait()
- await driver.channel.cancel("request-1")
- finish.set()
- with pytest.raises(ChannelError, match="completion is unknown"):
- await task
-
-
- "updates",
- [
- {"request_id": "wrong"},
- {"envelope_version": 2},
- {"completion_known": None},
- ],
-)
-async def test_invalid_response_immediately_invalidates_connection(sandbox, updates):
- async with sandbox.driver.connect() as driver:
- sandbox._transport.response_data.update(updates)
- with pytest.raises(ChannelError, match="malformed"):
- await driver.channel.exchange(envelope())
- assert driver.channel.closed
- assert sandbox._transport.events[-1][1] == "DELETE"
- before = len(sandbox._transport.events)
- with pytest.raises(ChannelError, match="closed"):
- await driver.channel.exchange(envelope(request_id="next"))
- assert len(sandbox._transport.events) == before
-
-
-async def test_unknown_completion_preserves_envelope_and_invalidates(sandbox):
- async with sandbox.driver.connect() as driver:
- sandbox._transport.response_data.update(
- ok=False, completion_known=False, error="synthetic-secret", error_code="interrupted"
- )
- response = await driver.channel.exchange(envelope())
- assert response.completion_known is False
- assert response.error_code == "interrupted"
- assert response.error == "Driver operation failed"
- assert driver.channel.closed
- assert sandbox._transport.events[-1][1] == "DELETE"
-
-
-async def test_session_name_only_for_active_owned_driver(sandbox):
- async with sandbox.driver.connect() as driver:
- assert sandbox.driver.session_name(driver) == "session-1"
- with pytest.raises(DriverConnectionError, match="another sandbox"):
- sandbox.driver.session_name(object())
- with pytest.raises(DriverConnectionError, match="inactive"):
- sandbox.driver.session_name(driver)
-
-
-async def test_hanging_cleanup_does_not_block_claim_release(sandbox, monkeypatch, caplog):
- monkeypatch.setattr("cua_sandbox.interfaces.driver._CLEANUP_TIMEOUT", 0.01)
- original = sandbox._transport.request_service
-
- async def hanging_delete(*args, **kwargs):
- if kwargs["method"] == "DELETE":
- await asyncio.Event().wait()
- return await original(*args, **kwargs)
-
- monkeypatch.setattr(sandbox._transport, "request_service", hanging_delete)
-
- async def release():
- sandbox._transport.events.append("release")
-
- sandbox._claim_handle = SimpleNamespace(release=release, name=None)
- async with sandbox.driver.connect() as driver:
-
- async def hanging_shutdown():
- await asyncio.Event().wait()
-
- driver.shutdown = hanging_shutdown
- await asyncio.wait_for(sandbox.close(), 0.5)
- assert driver.channel.closed
- assert not driver.channel.cleanup_confirmed
- assert sandbox._transport.events[-2:] == ["release", "disconnect"]
- assert "remote session cleanup is unconfirmed" in caplog.text
-
-
-async def test_cancelled_exchange_invalidates_and_deletes(sandbox, monkeypatch):
- started = asyncio.Event()
- original = sandbox._transport.request_service
-
- async def hanging_exchange(*args, **kwargs):
- if kwargs["path"].endswith("/exchange"):
- started.set()
- await asyncio.Event().wait()
- return await original(*args, **kwargs)
-
- monkeypatch.setattr(sandbox._transport, "request_service", hanging_exchange)
- async with sandbox.driver.connect() as driver:
- task = asyncio.create_task(driver.channel.exchange(envelope()))
- await started.wait()
- task.cancel()
- with pytest.raises(asyncio.CancelledError):
- await task
- assert driver.channel.closed
- assert driver.channel.cleanup_confirmed
- assert sandbox._transport.events[-1][1] == "DELETE"
-
-
[email protected]("close_claim", [False, True])
-async def test_pending_open_does_not_block_disconnect(sandbox, monkeypatch, close_claim):
- monkeypatch.setattr("cua_sandbox.interfaces.driver._CLEANUP_TIMEOUT", 0.01)
- started = asyncio.Event()
- original = sandbox._transport.request_service
-
- async def pending(*args, **kwargs):
- if kwargs["path"] == "/v1/connections":
- started.set()
- await asyncio.Event().wait()
- return await original(*args, **kwargs)
-
- monkeypatch.setattr(sandbox._transport, "request_service", pending)
- if close_claim:
-
- async def release():
- sandbox._transport.events.append("release")
-
- sandbox._claim_handle = SimpleNamespace(release=release, name=None)
- opening = asyncio.create_task(sandbox.driver.connect().__aenter__())
- await started.wait()
- await asyncio.wait_for(sandbox.close() if close_claim else sandbox.disconnect(), 0.5)
- with pytest.raises(asyncio.CancelledError):
- await opening
- assert not sandbox.driver._connections
- assert sandbox._transport.events[-1] == "disconnect"
- if close_claim:
- assert sandbox._transport.events[-2] == "release"
-
-
[email protected]("cancel_context", [False, True])
-async def test_late_open_is_cleaned_without_resurrecting(sandbox, monkeypatch, cancel_context):
- monkeypatch.setattr("cua_sandbox.interfaces.driver._CLEANUP_TIMEOUT", 0.01)
- started, cancelled, finish, deleted = (asyncio.Event() for _ in range(4))
- original = sandbox._transport.request_service
-
- async def resistant(*args, **kwargs):
- if kwargs["path"] == "/v1/connections":
- started.set()
- try:
- await finish.wait()
- except asyncio.CancelledError:
- cancelled.set()
- await finish.wait()
- response = await original(*args, **kwargs)
- if kwargs["method"] == "DELETE":
- deleted.set()
- return response
-
- monkeypatch.setattr(sandbox._transport, "request_service", resistant)
- opening = asyncio.create_task(sandbox.driver.connect().__aenter__())
- await started.wait()
- if cancel_context:
- opening.cancel()
- with pytest.raises(asyncio.CancelledError):
- await asyncio.wait_for(opening, 0.5)
- else:
- await asyncio.wait_for(sandbox.driver.close(), 0.5)
- await cancelled.wait()
- assert not sandbox.driver._connections
- finish.set()
- await asyncio.wait_for(deleted.wait(), 0.5)
- if not cancel_context:
- with pytest.raises(DriverConnectionError, match="disconnected"):
- await opening
- assert [e[1] for e in sandbox._transport.events] == ["POST", "DELETE"]
-
-
[email protected]("deadline", [1120000, 10**1000])
-async def test_driver_deadline_overrides_short_transport_timeout(sandbox, monkeypatch, deadline):
- monkeypatch.setattr("cua_sandbox.interfaces.driver.time.time", lambda: 1000)
- original = sandbox._transport.request_service
- timeouts = []
-
- async def record(*args, **kwargs):
- timeouts.append(kwargs.get("timeout"))
- return await original(*args, **kwargs)
-
- monkeypatch.setattr(sandbox._transport, "request_service", record)
- async with sandbox.driver.connect() as driver:
- await driver.channel.exchange(envelope(deadline_unix_ms=deadline))
- assert timeouts == [None, 120, None]
- assert sandbox._transport._timeout == 30
-
-
[email protected]("deadline", [0, 999999, 1000000, -1])
-async def test_expired_or_invalid_deadline_never_dispatches(sandbox, monkeypatch, deadline):
- monkeypatch.setattr("cua_sandbox.interfaces.driver.time.time", lambda: 1000)
- async with sandbox.driver.connect() as driver:
- with pytest.raises(ChannelError, match="expired|malformed"):
- await driver.channel.exchange(envelope(deadline_unix_ms=deadline))
- assert len(sandbox._transport.events) == 1
-
-
-async def test_local_deadline_cancels_then_deletes_without_replay(sandbox, monkeypatch):
- monkeypatch.setattr("cua_sandbox.interfaces.driver.time.time", lambda: 1000)
- original = sandbox._transport.request_service
- dispatched = []
-
- async def pending(*args, **kwargs):
- dispatched.append((kwargs["method"], kwargs["path"]))
- if kwargs["path"].endswith("/exchange"):
- await asyncio.Event().wait()
- return await original(*args, **kwargs)
-
- monkeypatch.setattr(sandbox._transport, "request_service", pending)
- async with sandbox.driver.connect() as driver:
- with pytest.raises(TimeoutError):
- await driver.channel.exchange(envelope(deadline_unix_ms=1000010))
- assert driver.channel.closed
- assert driver.channel.cleanup_confirmed
- assert dispatched == [
- ("POST", "/v1/connections"),
- ("POST", "/v1/connections/connection-1/exchange"),
- ("POST", "/v1/connections/connection-1/cancel"),
- ("DELETE", "/v1/connections/connection-1"),
- ]
- assert not sandbox.driver._closing
-
-
-async def test_deadline_bounds_cancellation_resistant_exchange(sandbox, monkeypatch):
- monkeypatch.setattr("cua_sandbox.interfaces.driver.time.time", lambda: 1000)
- cancelled, finish, returned = (asyncio.Event() for _ in range(3))
- original = sandbox._transport.request_service
-
- async def resistant(*args, **kwargs):
- if kwargs["path"].endswith("/exchange"):
- try:
- await finish.wait()
- except asyncio.CancelledError:
- cancelled.set()
- await finish.wait()
- result = await original(*args, **kwargs)
- returned.set()
- return result
- return await original(*args, **kwargs)
-
- monkeypatch.setattr(sandbox._transport, "request_service", resistant)
- async with sandbox.driver.connect() as driver:
- with pytest.raises(TimeoutError):
- await asyncio.wait_for(driver.channel.exchange(envelope(deadline_unix_ms=1000010)), 0.5)
- await cancelled.wait()
- assert driver.channel.closed
- assert driver.channel.cleanup_confirmed
- finish.set()
- await asyncio.wait_for(returned.wait(), 0.5)
- with pytest.raises(ChannelError, match="closed"):
- await driver.channel.exchange(envelope(request_id="next"))
- assert [event[1] for event in sandbox._transport.events] == ["POST", "POST", "DELETE", "POST"]
diff --git a/libs/python/cua-sandbox/tests/test_typed_driver_native.py b/libs/python/cua-sandbox/tests/test_typed_driver_native.py
index e916cb8199..31f08eaa8e 100644
--- a/libs/python/cua-sandbox/tests/test_typed_driver_native.py
+++ b/libs/python/cua-sandbox/tests/test_typed_driver_native.py
@@ -5,11 +5,13 @@ import json
import os
from pathlib import Path
-import httpx
import pytest
-from cua_sandbox.sandbox import Sandbox
-from .test_typed_driver import Transport
+from ._driver_env_support import McpTransport
+from ._driver_env_support import records as _records_fixture
+from ._driver_env_support import sandbox as mcp_sandbox
+
+records = _records_fixture
@pytest.fixture
@@ -29,82 +31,46 @@ def refusal():
return json.loads(fixture.read_text())["result"]
-class NativeTransport(Transport):
- def __init__(self, result=None):
- super().__init__()
- self.exchange_timeouts = []
- self.result = (
- result
- if result is not None
- else {
- "content": [{"type": "text", "text": "typed-fleet-fixture"}],
- "isError": False,
- }
- )
+def native_transport(result=None):
+ """A synthetic MCP receiver whose ``exchange`` answers with ``result``."""
+ transport = McpTransport()
+ transport.response_data["result"] = (
+ result
+ if result is not None
+ else {"content": [{"type": "text", "text": "typed-env-fixture"}], "isError": False}
+ )
+ return transport
- async def request_service(
- self,
- name,
- *,
- method,
- path,
- json_body=None,
- body=None,
- headers=None,
- timeout=None,
- max_response_bytes=None,
- ):
- response = await super().request_service(
- name,
- method=method,
- path=path,
- json_body=json_body,
- body=body,
- headers=headers,
- timeout=timeout,
- max_response_bytes=max_response_bytes,
- )
- if path.endswith("/exchange"):
- self.exchange_timeouts.append(timeout)
- return httpx.Response(
- 200,
- json=dict(
- envelope_version=1,
- request_id=json_body["request_id"],
- ok=True,
- result=self.result,
- completion_known=True,
- ),
- )
- return response
+def envelope_of(transport):
+ """The typed envelope of the last JSON-RPC request the receiver saw."""
+ return transport.events[-1][3]["params"]["envelope"]
-async def test_real_canonical_driver_uses_fleet_callback_and_disconnects(sdk):
- transport = NativeTransport()
- sandbox = Sandbox(transport, _telemetry_enabled=False)
- await sandbox._connect()
+async def test_real_canonical_driver_uses_the_env_callback_and_disconnects(sdk, records):
+ transport = native_transport()
+ sb = await mcp_sandbox(transport)
try:
- async with sandbox.driver.connect() as driver:
+ async with sb.driver.connect() as driver:
assert isinstance(driver, sdk.CuaDriver)
result = await driver.get_screen_size(sdk.GetScreenSizeInput(session=None))
- assert result.text == "typed-fleet-fixture"
- request = transport.events[-1][3]
+ assert result.text == "typed-env-fixture"
+ request = envelope_of(transport)
assert request["name"] == "get_screen_size"
assert request["arguments"] == {}
assert request["deadline_unix_ms"] > 0
- session = sandbox.driver.session_name(driver)
+ session = sb.driver.session_name(driver)
await driver.get_agent_cursor_state(sdk.GetAgentCursorStateInput(session=session))
- assert transport.events[-1][3]["arguments"] == {"session": "session-1"}
- await sandbox.disconnect()
- assert transport.events[-2][1] == "DELETE"
- assert transport.events[-1] == "disconnect"
+ assert envelope_of(transport)["arguments"] == {"session": "session-1"}
+ await sb.disconnect()
+ assert not transport.sessions
+ assert transport.events[-1][1] == "DELETE"
before = len(transport.events)
with pytest.raises(sdk.DriverError.Remote, match="closed"):
await driver.get_screen_size(sdk.GetScreenSizeInput(session=None))
assert len(transport.events) == before
finally:
- await sandbox.disconnect()
+ await sb.disconnect()
@pytest.mark.parametrize(
@@ -114,12 +80,11 @@ async def test_real_canonical_driver_uses_fleet_callback_and_disconnects(sdk):
("DESKTOP", {"display_id": "primary"}, {"kind": "desktop", "display_id": "primary"}),
],
)
-async def test_real_canonical_action_target_serializes_over_fleet(
- sdk, refusal, variant, fields, expected
+async def test_real_canonical_action_target_serializes_over_the_env_carrier(
+ sdk, records, refusal, variant, fields, expected
):
- transport = NativeTransport(result=refusal)
- sandbox = Sandbox(transport, _telemetry_enabled=False)
- await sandbox._connect()
+ transport = native_transport(result=refusal)
+ sandbox = await mcp_sandbox(transport)
try:
async with sandbox.driver.connect() as driver:
with pytest.raises(sdk.DriverError.Tool) as error:
@@ -135,7 +100,7 @@ async def test_real_canonical_action_target_serializes_over_fleet(
)
assert error.value.tool == "click"
assert error.value.error_code == "foreground_required"
- request = transport.events[-1][3]
+ request = envelope_of(transport)
assert request["name"] == "click"
assert request["arguments"] == {
"x": 12.5,
@@ -148,10 +113,9 @@ async def test_real_canonical_action_target_serializes_over_fleet(
await sandbox.disconnect()
-async def test_real_canonical_tool_result_preserves_structured_refusal(sdk, refusal):
- transport = NativeTransport(result=refusal)
- sandbox = Sandbox(transport, _telemetry_enabled=False)
- await sandbox._connect()
+async def test_real_canonical_tool_result_preserves_structured_refusal(sdk, records, refusal):
+ transport = native_transport(result=refusal)
+ sandbox = await mcp_sandbox(transport)
try:
async with sandbox.driver.connect() as driver:
result = await driver.get_screen_size(sdk.GetScreenSizeInput(session=None))
@@ -177,7 +141,7 @@ def verification_input(sdk):
element=sdk.ElementPredicate(
selector=sdk.ElementSelector(role="textbox", label_contains="Message"),
exists=True,
- value_equals="typed-fleet-fixture",
+ value_equals="typed-env-fixture",
enabled=True,
selected=False,
),
@@ -190,21 +154,19 @@ def verification_input(sdk):
)
-async def test_real_canonical_verify_state_serializes_over_fleet(refusal, verification_input):
- transport = NativeTransport(result=refusal)
- sandbox = Sandbox(transport, _telemetry_enabled=False)
- await sandbox._connect()
+async def test_real_canonical_verify_state_serializes_over_the_env_carrier(
+ records, refusal, verification_input
+):
+ transport = native_transport(result=refusal)
+ sandbox = await mcp_sandbox(transport)
try:
async with sandbox.driver.connect() as driver:
verification_input.session = sandbox.driver.session_name(driver)
await driver.verify_state(verification_input)
- name, method, path, request, headers = transport.events[-1]
- assert (name, method, path) == (
- "driver",
- "POST",
- "/v1/connections/connection-1/exchange",
- )
- assert headers == {"X-Cua-Driver-Generation": "generation-1"}
+ name, method, path, rpc, headers = transport.events[-1]
+ assert (name, method, path) == ("mcp", "POST", "/mcp")
+ assert rpc["method"] == "cua/driver/v1/exchange"
+ request = rpc["params"]["envelope"]
assert request["name"] == "verify_state"
assert request["arguments"] == {
"pid": 42,
@@ -215,7 +177,7 @@ async def test_real_canonical_verify_state_serializes_over_fleet(refusal, verifi
"element": {
"selector": {"role": "textbox", "label_contains": "Message"},
"exists": True,
- "value_equals": "typed-fleet-fixture",
+ "value_equals": "typed-env-fixture",
"enabled": True,
"selected": False,
}
@@ -228,14 +190,16 @@ async def test_real_canonical_verify_state_serializes_over_fleet(refusal, verifi
}
assert request["deadline_unix_ms"] > 0
assert len(transport.exchange_timeouts) == 1
- assert 0 < transport.exchange_timeouts[0] <= 120
+ # The binding bounds the exchange by the request deadline (120 s by
+ # default) plus its own margin.
+ assert 0 < transport.exchange_timeouts[0] <= 125
finally:
await sandbox.disconnect()
@pytest.mark.parametrize("status", ["satisfied", "unsatisfied", "unknown"])
async def test_real_canonical_verify_state_preserves_structured_outcome(
- sdk, verification_input, status
+ sdk, records, verification_input, status
):
# Synthetic service results qualify the bridge, not live AX observations.
stable = status == "satisfied"
@@ -261,9 +225,8 @@ async def test_real_canonical_verify_state_preserves_structured_outcome(
"structuredContent": structured,
"isError": False,
}
- transport = NativeTransport(result=wire_result)
- sandbox = Sandbox(transport, _telemetry_enabled=False)
- await sandbox._connect()
+ transport = native_transport(result=wire_result)
+ sandbox = await mcp_sandbox(transport)
try:
async with sandbox.driver.connect() as driver:
result = await driver.verify_state(verification_input)
@@ -299,11 +262,10 @@ async def test_real_canonical_verify_state_preserves_structured_outcome(
async def test_real_canonical_verify_state_after_disconnect_does_not_exchange(
- sdk, verification_input
+ sdk, records, verification_input
):
- transport = NativeTransport()
- sandbox = Sandbox(transport, _telemetry_enabled=False)
- await sandbox._connect()
+ transport = native_transport()
+ sandbox = await mcp_sandbox(transport)
try:
async with sandbox.driver.connect() as driver:
await sandbox.disconnect()
diff --git a/libs/python/cua-sandbox/tests/test_unified_api.py b/libs/python/cua-sandbox/tests/test_unified_api.py
index 995c1f6867..7ab6491f68 100644
--- a/libs/python/cua-sandbox/tests/test_unified_api.py
+++ b/libs/python/cua-sandbox/tests/test_unified_api.py
@@ -1,8 +1,7 @@
-"""The unified Sandbox API: command/env/services/wait_for, CloudOptions,
-portable info, service handles and public URLs, hermetically.
+"""The unified Sandbox API: command/env/services/wait_for, portable info,
+service handles and public URLs, hermetically.
-Local: runtimes are recorders (nothing is launched). Cloud: the fake Fleet
-API from ``cua-test-fixtures`` (see ``tests/_native_fleet.py``).
+Runtimes are recorders (nothing is launched).
"""
from __future__ import annotations
@@ -15,16 +14,6 @@ from cua_sandbox import CloudOptions, Image, Sandbox, http, tcp
from cua_sandbox.options import check_services, parse_memory, probes
from cua_sandbox.runtime.native import NativeRuntime
-# Digest-pinned (no registry resolution) and a rootfs (runs on gVisor).
-ROOTFS = "registry.example/mcp@sha256:beef"
-
-
-def rootfs_variant(monkeypatch):
- from tests import _image_fixtures
-
- monkeypatch.setitem(_image_fixtures.VARIANTS, ROOTFS, "rootfs")
-
def test_sandbox_info_location_kind_and_runtime():
from cua_sandbox.sandbox import SandboxInfo
@@ -156,36 +145,6 @@ async def test_quiet_default_hides_the_notice(monkeypatch, fresh_notice, caplog)
assert not [r for r in caplog.records if "defaulting to a local" in r.message]
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_cloud_only_arguments_keep_the_cloud_with_a_deprecation(monkeypatch, fresh_notice):
- seen: list = []
-
- async def managed(image, **kwargs):
- seen.append(kwargs)
- raise _Stop()
-
- import sys
-
- monkeypatch.setattr(sys.modules["cua_sandbox.sandbox"], "_acquire_managed", managed)
- monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: True))
- with pytest.warns(DeprecationWarning, match="local=False"):
- with pytest.raises(_Stop):
- await Sandbox.create(
- Image.from_registry(ROOTFS), claim_ttl=600, telemetry_enabled=False
- )
- assert seen and seen[0]["claim_ttl"] == 600
- # cloud= implies the cloud, without a warning.
- with warnings.catch_warnings():
- warnings.simplefilter("error", DeprecationWarning)
- with pytest.raises(_Stop):
- await Sandbox.create(
- Image.from_registry(ROOTFS),
- cloud=CloudOptions(max_pool_size=2),
- telemetry_enabled=False,
- )
- assert len(seen) == 2
-
-
async def test_local_true_with_cloud_options_is_a_typed_error():
from cua_sandbox import InvalidArgument
@@ -203,35 +162,6 @@ async def test_local_true_with_cloud_options_is_a_typed_error():
pass
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_cloud_suspend_is_unsupported_and_never_scales_a_pool(monkeypatch, tmp_path):
- from cua_sandbox import Unsupported, sandbox_state
-
- monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: True))
- monkeypatch.setattr(sandbox_state, "load", lambda name: None)
-
- async def gone(cls, **kwargs):
- raise RuntimeError("no such claim")
-
- monkeypatch.setattr(Sandbox, "_create", classmethod(gone))
- for op in ("suspend", "resume", "restart"):
- with pytest.raises(Unsupported, match="cannot suspend a single sandbox"):
- await getattr(Sandbox, op)("some-claim")
- # Still a NotImplementedError for older handlers.
- with pytest.raises(NotImplementedError):
- await getattr(Sandbox, op)("some-claim", local=False)
-
- # A running cloud sandbox resumes by reconnecting.
- async def live(cls, **kwargs):
- return ("connected", kwargs["name"])
-
- monkeypatch.setattr(Sandbox, "_create", classmethod(live))
- assert await Sandbox.resume("some-claim") == ("connected", "some-claim")
- from cua_sandbox.transport.fleet_cloud import FleetCloudTransport
-
- assert not hasattr(FleetCloudTransport, "suspend_sandbox"), "no pool scaling path"
-
-
async def test_native_runtime_start_builds_the_sdk_options(monkeypatch):
seen: dict = {}
@@ -379,203 +309,3 @@ async def test_non_sdk_runtimes_refuse_the_portable_options():
services={"mcp": 8765},
telemetry_enabled=False,
)
-
-
-# ── deprecated keywords ─────────────────────────────────────────────────
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_flat_cloud_keywords_are_deprecated_and_conflicts_refused(monkeypatch):
- calls: list = []
- monkeypatch.setattr("cua_sandbox.runtime.docker.DockerRuntime", _native_recorder(calls))
- with pytest.warns(DeprecationWarning, match=r"cloud=CloudOptions\(warm=\.\.\."):
- with pytest.raises(_Stop):
- await Sandbox.create(
- Image.linux(kind="container"), local=True, warm=True, telemetry_enabled=False
- )
- with pytest.raises(ValueError, match="both in cloud="):
- with warnings.catch_warnings():
- warnings.simplefilter("ignore", DeprecationWarning)
- await Sandbox.create(
- Image.linux(kind="container"),
- warm=True,
- cloud=CloudOptions(warm=False),
- telemetry_enabled=False,
- local=False,
- )
- # A named pool: the given fields are compared with its template.
- from cua_sandbox import Pool, PoolSpecMismatch
-
- async def check(name, spec):
- raise PoolSpecMismatch(f"pool {name}: command: pool has [], requested {spec.command}")
-
- monkeypatch.setattr(Pool, "check", staticmethod(check))
- with pytest.raises(PoolSpecMismatch, match="command"):
- await Sandbox.create(
- cloud=CloudOptions(pool="p"), command=["x"], telemetry_enabled=False, local=False
- )
-
-
-# ── cloud: the fake Fleet API ────────────────────────────────────────────
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_cloud_command_services_info_urls_and_progress(fleet, rootfs_variant):
- events: list = []
- sb = await Sandbox.create(
- Image.from_registry(ROOTFS),
- command=["python", "/srv.py"],
- services={"mcp": 8765},
- cloud=CloudOptions(max_pool_size=3, claim_ttl=600),
- progress=events.append,
- telemetry_enabled=False,
- local=False,
- )
- try:
- # The command is part of the template (and the pool key).
- client = fleet()
- try:
- template = await client.get_template(sb.pool_name, sb.pool_name)
- finally:
- await client.close()
- vm = template.spec.vm_template
- assert list(vm.command) == ["python", "/srv.py"]
- assert {s.name: s.target_port for s in vm.services}["mcp"] == 8765
- # Portable progress: no pool/claim words.
- stages = [e.stage for e in events]
- assert stages[0] == "provisioning" and stages[-1] == "ready", stages
- words = [e.message.replace(sb.claim_name or "", "<id>") for e in events]
- assert all("pool" not in m and "claim" not in m for m in words), words
- assert "first start of an image can take a few minutes" in events[0].message
- # Portable identity and info.
- # The qualified ref: no pool or namespace in it.
- assert sb.id == f"cloud:{sb.claim_name}"
- assert sb.location == "cloud"
- info = await sb.info()
- assert (info.location, info.status) == ("cloud", "ready")
- assert info.services.get("mcp") == 8765
- assert info.expires_at is not None
- assert info.provider_details["pool"] == sb.pool_name
- with pytest.warns(DeprecationWarning):
- assert info.pool == sb.pool_name
- # URLs: signed in the cloud.
- url = await sb.service("mcp").url()
- assert url.startswith("https://signed.fleet.test/"), url
- public = await sb.public_url("mcp", ttl=600)
- assert public.url.startswith("https://signed.fleet.test/")
- assert public.service == "mcp" and public.expires_at.endswith("Z")
- assert "claim" in public.provider_details
- with pytest.raises(Exception, match="ttl"):
- await sb.public_url("mcp", ttl=5)
- finally:
- await sb.close()
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_cloud_env_is_created_and_keys_its_own_pool(fleet, rootfs_variant):
- # Cloud env= is the template's env (processMode Run on every runtime).
- plain = await Sandbox.create(Image.from_registry(ROOTFS), telemetry_enabled=False, local=False)
- sb = await Sandbox.create(
- Image.from_registry(ROOTFS), env={"K": "v"}, telemetry_enabled=False, local=False
- )
- try:
- assert sb.pool_name != plain.pool_name, "env is part of the pool key"
- assert sb.location == "cloud"
- finally:
- await sb.close()
- await plain.close()
-
-
-# ── listing: local by default, all=True merges cloud ────────────────────
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-async def test_list_is_everything_by_default_and_the_cloud_never_fails_it(monkeypatch):
- import asyncio
- import sys
-
- from cua_sandbox import InvalidArgument
- from cua_sandbox.sandbox import SandboxInfo
-
- mod = sys.modules["cua_sandbox.sandbox"]
- local = [SandboxInfo(name="l1", status="running", source="container", location="local")]
- cloud = [SandboxInfo(name="c1", status="running", source="fleet", location="cloud")]
- calls: list = []
-
- async def list_local(cls):
- calls.append("local")
- return list(local)
-
- async def list_cloud(cls, *, api_key=None):
- calls.append("cloud")
- return list(cloud)
-
- monkeypatch.setattr(Sandbox, "_list_local", classmethod(list_local))
- monkeypatch.setattr(Sandbox, "_list_cloud", classmethod(list_cloud))
- monkeypatch.setenv("CUA_CLIENT_ID", "cua-e2e-id")
- monkeypatch.setenv("CUA_CLIENT_SECRET", "cua-e2e-secret")
- rows = await Sandbox.list()
- assert [(i.name, i.location) for i in rows] == [("l1", "local"), ("c1", "cloud")]
- assert [i.id for i in rows] == ["local:l1", "cloud:c1"]
- # A local and a cloud sandbox may share a name: both are listed.
- cloud.append(SandboxInfo(name="l1", status="running", source="fleet", location="cloud"))
- assert [i.id for i in await Sandbox.list()] == ["local:l1", "cloud:c1", "cloud:l1"]
- cloud.pop()
- calls.clear()
- assert [i.name for i in await Sandbox.list(local=True)] == ["l1"]
- assert calls == ["local"], "local only never reads the cloud"
- assert [i.name for i in await Sandbox.list(local=False)] == ["c1"]
- with pytest.warns(DeprecationWarning):
- assert len(await Sandbox.list(all=True)) == 2
- with pytest.raises(InvalidArgument), pytest.warns(DeprecationWarning):
- await Sandbox.list(all=True, local=True)
-
- # The cloud failing or hanging: local rows plus a warning.
- async def broken(cls, *, api_key=None):
- raise RuntimeError("fleet unreachable")
-
- monkeypatch.setattr(Sandbox, "_list_cloud", classmethod(broken))
- warned: list = []
- monkeypatch.setattr(mod.logger, "warning", lambda *a: warned.append(a[0] % a[1:]))
- assert [i.name for i in await Sandbox.list()] == ["l1"]
- assert warned == ["cloud sandboxes not listed: fleet unreachable"]
- with pytest.raises(RuntimeError):
- await Sandbox.list(local=False)
-
- async def hangs(cls, *, api_key=None):
- await asyncio.sleep(60)
-
- monkeypatch.setattr(Sandbox, "_list_cloud", classmethod(hangs))
- monkeypatch.setattr(mod, "_LIST_CLOUD_TIMEOUT", 0.05)
- warned.clear()
- assert [i.name for i in await Sandbox.list()] == ["l1"]
- assert warned and "did not answer" in warned[0]
-
- # No credentials readable without the keychain: no cloud call at all.
- monkeypatch.delenv("CUA_CLIENT_ID")
- monkeypatch.delenv("CUA_CLIENT_SECRET")
- monkeypatch.setattr("cua_sandbox._config.get_api_key", lambda override=None: None)
- monkeypatch.setattr("cua_sandbox._config.may_have_fleet_session", lambda: False)
- monkeypatch.setattr(Sandbox, "_list_cloud", classmethod(broken))
- warned.clear()
- assert [i.name for i in await Sandbox.list()] == ["l1"]
- assert warned == [], "silent without credentials"
-
-
-def test_may_have_fleet_session_follows_the_marker_without_reading_the_vault(monkeypatch, tmp_path):
- pytest.importorskip("cua")
- from cua_sandbox import _config
-
- vault = tmp_path / "vault"
- monkeypatch.setenv("CUA_HOME", str(tmp_path / "home"))
- monkeypatch.setenv("CUA_CREDENTIAL_STORE", f"test-keychain:{vault}")
- monkeypatch.delenv("CUA_FLEET_SESSION", raising=False)
- assert not _config.may_have_fleet_session()
- (tmp_path / "home").mkdir()
- (tmp_path / "home" / "session.json").write_text(
- '{"store": "keychain", "expires_at": "2099-01-01T00:00:00Z"}'
- )
- assert _config.may_have_fleet_session()
- assert not (vault / "reads").exists(), "the vault was never read"
- monkeypatch.setenv("CUA_FLEET_SESSION", "0")
- assert not _config.may_have_fleet_session()
diff --git a/libs/python/cua-sandbox/tests/test_vm_cleanup.py b/libs/python/cua-sandbox/tests/test_vm_cleanup.py
index a682167f52..08363c90be 100644
--- a/libs/python/cua-sandbox/tests/test_vm_cleanup.py
+++ b/libs/python/cua-sandbox/tests/test_vm_cleanup.py
@@ -1,320 +1,106 @@
-"""Unit tests for VM cleanup on connection failure and destroy() resilience.
+"""Unit tests for ``destroy()`` resilience and ``ephemeral()`` cleanup.
-These tests mock FleetCloudTransport so they run without a real cloud API.
They verify that:
- 1. _create() cleans up a provisioned VM when _connect() fails.
- 2. destroy() runs every cleanup step independently — a failure in one
- does not prevent the others from executing.
+ 1. destroy() runs every cleanup step independently: a failure in one does
+ not prevent the others from executing.
+ 2. server_port is validated before anything is provisioned.
+ 3. ephemeral() destroys the sandbox on every exit path.
"""
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock, patch
-import httpx
import pytest
from cua_sandbox.image import Image
from cua_sandbox.sandbox import Sandbox
-from cua_sandbox.transport.fleet_cloud import FleetCloudTransport
pytestmark = pytest.mark.asyncio
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
+def _make_sandbox(*, name: str = "test-vm", ephemeral: bool = True) -> Sandbox:
+ """A sandbox over a mock transport, without calling _connect()."""
+ return Sandbox(AsyncMock(), name=name, _ephemeral=ephemeral, _telemetry_enabled=False)
-def _make_cloud_transport(*, name: str = "test-vm") -> FleetCloudTransport:
- """Return a FleetCloudTransport with internal state set as if _create_vm() succeeded."""
- t = FleetCloudTransport.__new__(FleetCloudTransport)
- t._name = name
- t._api_key_override = "sk-fake"
- t._base_url = "https://api.example.com"
- t._image = None
- t._cpu = None
- t._memory_mb = None
- t._disk_gb = None
- t._region = "us-east-1"
- t._inner = None
- t._api_client = None
- return t
-
-
-def _managed_sandbox() -> MagicMock:
- """A sandbox as returned by cua_sandbox._autopool.acquire."""
- claimed = MagicMock()
- claimed.close = AsyncMock()
- claimed.keep_alive = AsyncMock()
- return claimed
-
-
-def _make_sandbox(transport: FleetCloudTransport, **kwargs) -> Sandbox:
- """Return a Sandbox wrapping *transport* without calling _connect()."""
- return Sandbox(
- transport,
- name=transport._name,
- _ephemeral=kwargs.get("ephemeral", True),
- _telemetry_enabled=False,
- )
-
-
-# ===================================================================
-# 1. _create() cleans up on _connect() failure
-# ===================================================================
-
-
[email protected](reason="Cua Cloud has ended (CUA-1854)")
-class TestCreateCleansUpOnConnectFailure:
- """Sandbox._create() releases a managed Fleet claim when attaching fails.
-
- Fleet images come from the account's managed pool (the cua SDK's native
- manager); these run against the ``cua-test-fixtures`` fake Fleet API.
- """
-
- @pytest.fixture(autouse=True)
- def _fleet(self, fleet):
- self.client_factory = fleet
-
- async def _claims(self) -> list[str]:
- client = self.client_factory()
- try:
- names = [n.name for n in await client.list_namespaces()]
- out: list[str] = []
- for ns in names:
- out += [c.metadata.name for c in await client.list_claims(ns)]
- return out
- finally:
- await client.close()
-
- def _fail_attach(self, monkeypatch, error: BaseException) -> None:
- async def wait(self, **_):
- raise error
-
- monkeypatch.setattr("cua_sandbox.pool._ClaimHandle.wait", wait)
-
- async def _create(self):
- return await Sandbox._create(
- image=Image.from_registry("registry.example/workspace@sha256:0123"),
- telemetry_enabled=False,
- )
-
- async def test_delete_vm_called_on_timeout(self, monkeypatch):
- """ReadTimeout while attaching releases the claim and keeps its type."""
- self._fail_attach(monkeypatch, httpx.ReadTimeout("poll timed out"))
- with pytest.raises(httpx.ReadTimeout):
- await self._create()
- assert not await self._claims()
-
- async def test_delete_vm_called_on_generic_exception(self, monkeypatch):
- self._fail_attach(monkeypatch, RuntimeError("unexpected"))
- with pytest.raises(RuntimeError, match="unexpected"):
- await self._create()
- assert not await self._claims()
-
- async def test_original_exception_propagates_even_if_delete_fails(self, monkeypatch):
- from cua_sandbox import _autopool
-
- self._fail_attach(monkeypatch, TimeoutError("poll timeout"))
-
- async def release(self):
- raise httpx.ConnectError("api down")
-
- monkeypatch.setattr(_autopool.ManagedClaimHandle, "release", release)
- with pytest.raises(TimeoutError, match="poll timeout"):
- await self._create()
-
- async def test_no_cleanup_when_vm_not_yet_created(self, monkeypatch):
- """A failure before any claim exists deletes nothing."""
- from cua_sandbox import _autopool
-
- def no_runtime():
- raise ValueError("no api key")
-
- monkeypatch.setattr(_autopool, "_native_cua", no_runtime)
- with pytest.raises(_autopool.AutoPoolError, match="no api key"):
- await self._create()
- assert not await self._claims()
-
- async def test_keyboard_interrupt_still_cleans_up(self, monkeypatch):
- self._fail_attach(monkeypatch, KeyboardInterrupt())
- with pytest.raises(KeyboardInterrupt):
- await self._create()
- assert not await self._claims()
+def _with_runtime(sb: Sandbox, *, name: str, delete: AsyncMock | None = None) -> AsyncMock:
+ runtime = AsyncMock()
+ if delete is not None:
+ runtime.delete = delete
+ runtime_info = MagicMock()
+ runtime_info.name = name
+ sb._runtime = runtime
+ sb._runtime_info = runtime_info
+ return runtime
# ===================================================================
-# 2. destroy() is resilient to individual step failures
+# 1. destroy() resilience
# ===================================================================
class TestDestroyResilience:
"""Each cleanup step in destroy() should run independently."""
- async def test_delete_vm_runs_even_if_disconnect_fails(self):
- """A failing disconnect() must not prevent delete_vm()."""
- transport = _make_cloud_transport(name="leaky-vm")
- transport.disconnect = AsyncMock(side_effect=OSError("connection reset"))
- transport.delete_vm = AsyncMock()
-
- sb = _make_sandbox(transport)
- await sb.destroy()
-
- transport.disconnect.assert_awaited_once()
- transport.delete_vm.assert_awaited_once()
-
- async def test_runtime_stop_runs_even_if_delete_vm_fails(self):
- """A failing delete_vm() must not prevent runtime cleanup."""
- transport = _make_cloud_transport(name="leaky-vm")
- transport.disconnect = AsyncMock()
- transport.delete_vm = AsyncMock(side_effect=httpx.ConnectError("api down"))
-
- runtime = AsyncMock()
- runtime_info = MagicMock()
- runtime_info.name = "leaky-vm"
-
- sb = _make_sandbox(transport)
- sb._runtime = runtime
- sb._runtime_info = runtime_info
+ async def test_runtime_delete_runs_even_if_disconnect_fails(self):
+ """A failing disconnect() must not prevent the runtime cleanup."""
+ sb = _make_sandbox(name="leaky-vm")
+ sb._transport.disconnect = AsyncMock(side_effect=OSError("connection reset"))
+ runtime = _with_runtime(sb, name="leaky-vm")
await sb.destroy()
- transport.delete_vm.assert_awaited_once()
+ sb._transport.disconnect.assert_awaited_once()
runtime.delete.assert_awaited_once_with("leaky-vm")
async def test_destroy_succeeds_when_all_steps_fail(self):
"""destroy() must not raise even if every cleanup step fails."""
- transport = _make_cloud_transport(name="total-fail")
- transport.disconnect = AsyncMock(side_effect=OSError("disconnect fail"))
- transport.delete_vm = AsyncMock(side_effect=httpx.ReadTimeout("delete fail"))
-
- runtime = AsyncMock()
- runtime.delete = AsyncMock(side_effect=RuntimeError("runtime fail"))
- runtime_info = MagicMock()
- runtime_info.name = "total-fail"
-
- sb = _make_sandbox(transport)
- sb._runtime = runtime
- sb._runtime_info = runtime_info
+ sb = _make_sandbox(name="total-fail")
+ sb._transport.disconnect = AsyncMock(side_effect=OSError("disconnect fail"))
+ runtime = _with_runtime(
+ sb, name="total-fail", delete=AsyncMock(side_effect=RuntimeError("runtime fail"))
+ )
# Should not raise
await sb.destroy()
- transport.disconnect.assert_awaited_once()
- transport.delete_vm.assert_awaited_once()
+ sb._transport.disconnect.assert_awaited_once()
runtime.delete.assert_awaited_once()
async def test_destroy_happy_path(self):
- """All steps succeed — basic smoke test."""
- transport = _make_cloud_transport(name="good-vm")
- transport.disconnect = AsyncMock()
- transport.delete_vm = AsyncMock()
+ """All steps succeed: basic smoke test."""
+ sb = _make_sandbox(name="good-vm")
+ runtime = _with_runtime(sb, name="good-vm")
- sb = _make_sandbox(transport)
await sb.destroy()
- transport.disconnect.assert_awaited_once()
- transport.delete_vm.assert_awaited_once()
+ sb._transport.disconnect.assert_awaited_once()
+ runtime.delete.assert_awaited_once_with("good-vm")
- async def test_non_cloud_transport_skips_delete_vm(self):
- """Non-FleetCloudTransport sandboxes should not call delete_vm."""
- transport = AsyncMock() # generic mock, not a FleetCloudTransport instance
- sb = Sandbox(transport, name="local-vm", _ephemeral=True, _telemetry_enabled=False)
+ async def test_a_persistent_sandbox_is_stopped_not_deleted(self):
+ sb = _make_sandbox(name="kept-vm", ephemeral=False)
+ runtime = _with_runtime(sb, name="kept-vm")
await sb.destroy()
- transport.disconnect.assert_awaited_once()
- # delete_vm should not be called since transport is not FleetCloudTransport
- assert not hasattr(transport, "delete_vm") or not transport.delete_vm.called
+ runtime.stop.assert_awaited_once_with("kept-vm")
+ runtime.delete.assert_not_awaited()
+ async def test_a_sandbox_without_a_runtime_only_disconnects(self):
+ sb = _make_sandbox(name="direct-vm")
-# ===================================================================
-# 3. Fleet server_port forwarding and validation
-# ===================================================================
-
-
-class TestFleetServerPortForwarding:
- """Sandbox factories should pass server_port to Fleet and validate it early."""
-
- @pytest.fixture(autouse=True)
- def _select_fleet(self, monkeypatch):
- monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: api_key is None))
-
- @pytest.mark.skip(reason="Cua Cloud has ended (CUA-1854)")
- async def test_create_forwards_server_port_to_the_managed_pool(self):
- # Was test_create_with_fleet_image_requires_explicit_pool.
- apply = AsyncMock()
- acquire = AsyncMock(return_value=_managed_sandbox())
-
- with (
- patch("cua_sandbox.pool.Pool.apply", new=apply),
- patch("cua_sandbox._autopool.acquire", new=acquire),
- patch("cua_sandbox.sandbox._save_fleet_claim_or_close", new=AsyncMock()),
- ):
- await Sandbox.create(
- Image.from_registry("registry.example/workspace:latest"),
- server_port=5000,
- telemetry_enabled=False,
- local=False,
- )
-
- apply.assert_not_awaited()
- assert acquire.await_args.kwargs["server_port"] == 5000
-
- @pytest.mark.skip(reason="Cua Cloud has ended (CUA-1854)")
- async def test_ephemeral_forwards_server_port(self):
- claimed = _managed_sandbox()
- acquire = AsyncMock(return_value=claimed)
+ await sb.destroy()
- with patch("cua_sandbox._autopool.acquire", new=acquire):
- async with Sandbox.ephemeral(
- Image.from_registry("registry.example/workspace:latest"),
- server_port=5000,
- telemetry_enabled=False,
- local=False,
- ):
- pass
-
- assert acquire.await_args.kwargs["server_port"] == 5000
- claimed.close.assert_awaited_once()
-
- @pytest.mark.skip(reason="Cua Cloud has ended (CUA-1854)")
- async def test_create_passes_server_port_to_fleet_transport(self):
- # _create (the sandbox() helper path) routes to the managed pool too.
- acquire = AsyncMock(return_value=_managed_sandbox())
-
- with (
- patch.object(Sandbox, "_uses_fleet", return_value=True),
- patch("cua_sandbox._autopool.acquire", new=acquire),
- patch("cua_sandbox.sandbox._save_fleet_claim_or_close", new=AsyncMock()),
- ):
- await Sandbox._create(
- image=Image.from_registry("registry.example/workspace:latest"),
- server_port=5000,
- telemetry_enabled=False,
- )
+ sb._transport.disconnect.assert_awaited_once()
- assert acquire.await_args.kwargs["server_port"] == 5000
- @pytest.mark.skip(reason="Cua Cloud has ended (CUA-1854)")
- async def test_existing_pool_does_not_pass_server_port_to_fleet_transport(self):
- transport = _make_cloud_transport(name="existing-pool")
+# ===================================================================
+# 2. server_port validation
+# ===================================================================
- with (
- patch.object(Sandbox, "_uses_fleet", return_value=True),
- patch(
- "cua_sandbox.sandbox.FleetCloudTransport",
- return_value=transport,
- ) as fleet_transport,
- patch.object(Sandbox, "_connect", AsyncMock()),
- ):
- await Sandbox._create(
- name="existing-pool",
- server_port=5000,
- telemetry_enabled=False,
- )
- assert "server_port" not in fleet_transport.call_args.kwargs
+class TestServerPortValidation:
+ """Sandbox factories validate server_port before provisioning anything."""
@pytest.mark.parametrize("server_port", [True, False, 0, -1, 65536, 5000.0, "5000"])
async def test_create_rejects_invalid_server_port_before_local_provisioning(self, server_port):
@@ -332,82 +118,67 @@ class TestFleetServerPortForwarding:
runtime.start.assert_not_awaited()
@pytest.mark.parametrize("server_port", [True, False, 0, -1, 65536, 5000.0, "5000"])
- async def test_invalid_server_port_rejects_before_legacy_cloud_provisioning(self, server_port):
- with patch("cua_sandbox.sandbox._make_transport") as make_transport:
- with pytest.raises(
- ValueError, match="server_port must be an integer between 1 and 65535"
- ):
- await Sandbox._create(
- image=Image.from_registry("registry.example/workspace:latest"),
- api_key="sk-legacy",
- server_port=server_port,
- telemetry_enabled=False,
- )
-
- make_transport.assert_not_called()
+ async def test_internal_create_rejects_invalid_server_port(self, server_port):
+ runtime = AsyncMock()
- @pytest.mark.parametrize("server_port", [True, False, 0, -1, 65536, 5000.0, "5000"])
- async def test_invalid_server_port_rejects_before_fleet_provisioning(self, server_port):
- with patch("cua_sandbox.sandbox.FleetCloudTransport") as fleet_transport:
- with pytest.raises(
- ValueError, match="server_port must be an integer between 1 and 65535"
- ):
- await Sandbox._create(
- image=Image.from_registry("registry.example/workspace:latest"),
- server_port=server_port,
- telemetry_enabled=False,
- )
+ with pytest.raises(ValueError, match="server_port must be an integer between 1 and 65535"):
+ await Sandbox._create(
+ image=Image.from_registry("registry.example/workspace:latest"),
+ local=True,
+ runtime=runtime,
+ server_port=server_port,
+ telemetry_enabled=False,
+ )
- fleet_transport.assert_not_called()
+ runtime.start.assert_not_awaited()
# ===================================================================
-# 4. ephemeral() integration — cleanup through the context manager
+# 3. ephemeral() integration: cleanup through the context manager
# ===================================================================
class TestEphemeralCleanup:
- """Sandbox.ephemeral() closes Fleet claims on every exit path."""
+ """Sandbox.ephemeral() destroys the sandbox on every exit path."""
- @pytest.fixture(autouse=True)
- def _select_fleet(self, monkeypatch):
- monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: api_key is None))
+ @staticmethod
+ def _created():
+ created = MagicMock()
+ created.destroy = AsyncMock()
+ return created
- @pytest.mark.skip(reason="Cua Cloud has ended (CUA-1854)")
async def test_ephemeral_destroys_on_normal_exit(self):
- claimed = _managed_sandbox()
- with patch("cua_sandbox._autopool.acquire", new=AsyncMock(return_value=claimed)):
+ created = self._created()
+ with patch.object(Sandbox, "_create", new=AsyncMock(return_value=created)):
async with Sandbox.ephemeral(
Image.from_registry("registry.example/workspace:latest"),
+ local=True,
telemetry_enabled=False,
- local=False,
- ):
- pass
+ ) as sb:
+ assert sb is created
- claimed.close.assert_awaited_once()
+ created.destroy.assert_awaited_once()
- @pytest.mark.skip(reason="Cua Cloud has ended (CUA-1854)")
async def test_ephemeral_destroys_on_test_failure(self):
- claimed = _managed_sandbox()
- with patch("cua_sandbox._autopool.acquire", new=AsyncMock(return_value=claimed)):
+ created = self._created()
+ with patch.object(Sandbox, "_create", new=AsyncMock(return_value=created)):
with pytest.raises(AssertionError):
async with Sandbox.ephemeral(
Image.from_registry("registry.example/workspace:latest"),
+ local=True,
telemetry_enabled=False,
- local=False,
):
raise AssertionError("test failed")
- claimed.close.assert_awaited_once()
+ created.destroy.assert_awaited_once()
- @pytest.mark.skip(reason="Cua Cloud has ended (CUA-1854)")
- async def test_ephemeral_propagates_claim_failure(self):
- acquire = AsyncMock(side_effect=httpx.ReadTimeout("poll timed out"))
- with patch("cua_sandbox._autopool.acquire", new=acquire):
- with pytest.raises(httpx.ReadTimeout):
+ async def test_ephemeral_propagates_create_failure(self):
+ create = AsyncMock(side_effect=TimeoutError("start timed out"))
+ with patch.object(Sandbox, "_create", new=create):
+ with pytest.raises(TimeoutError):
async with Sandbox.ephemeral(
Image.from_registry("registry.example/workspace:latest"),
+ local=True,
telemetry_enabled=False,
- local=False,
):
pass
diff --git a/libs/python/cua-sandbox/tests/test_windows_cloud.py b/libs/python/cua-sandbox/tests/test_windows_cloud.py
deleted file mode 100644
index 58d9b6f68b..0000000000
--- a/libs/python/cua-sandbox/tests/test_windows_cloud.py
+++ /dev/null
@@ -1,112 +0,0 @@
-"""Windows Server E2E test using cua-sandbox SDK.
-
-Run:
- CUA_API_KEY=sk-dev-test-key-local-12345 CUA_BASE_URL=http://localhost:8082 \
- uv run pytest tests/test_windows_cloud.py -v -s
-"""
-
-import os
-import time
-
-import pytest
-from cua_sandbox import Image, Sandbox
-
-pytestmark = pytest.mark.asyncio
-
-
-def P(*a, **kw):
- print(*a, **kw, flush=True)
-
-
-def _has_env() -> bool:
- return bool(os.environ.get("CUA_API_KEY"))
-
-
[email protected](not _has_env(), reason="CUA_API_KEY not set")
-async def test_windows_create_and_snapshot():
- """Image.windows('server-2025') -> Sandbox.ephemeral -> snapshot -> fork."""
-
- t0 = time.monotonic()
-
- P("\n Creating Sandbox with Image.windows('server-2025')...")
- async with Sandbox.ephemeral(Image.windows("server-2025"), local=False) as sb:
- t_create = time.monotonic() - t0
- P(f" Sandbox ready: {t_create:.1f}s name={sb.name}")
-
- # Try screenshot
- try:
- screen = await sb.screenshot()
- P(f" Screenshot: {len(screen)} bytes")
- except Exception as e:
- P(f" Screenshot not available: {e}")
- screen = None
-
- # Snapshot
- t1 = time.monotonic()
- P(" Taking snapshot...")
- snapshot_img = await sb.snapshot()
- t_snap = time.monotonic() - t1
- P(f" Snapshot: {t_snap:.2f}s")
-
- # Fork from snapshot
- t2 = time.monotonic()
- P(" Forking from snapshot...")
- async with Sandbox.ephemeral(snapshot_img, local=False) as fork:
- t_fork = time.monotonic() - t2
- P(f" Fork ready: {t_fork:.1f}s name={fork.name}")
-
- try:
- fork_screen = await fork.screenshot()
- P(f" Fork screenshot: {len(fork_screen)} bytes")
- except Exception as e:
- P(f" Fork screenshot not available: {e}")
- fork_screen = None
-
- t_total = time.monotonic() - t0
- P("\n === TIMINGS ===")
- P(f" Create+ready: {t_create:.1f}s")
- P(f" Snapshot: {t_snap:.2f}s")
- P(f" Fork+ready: {t_fork:.1f}s")
- P(f" Total: {t_total:.1f}s")
-
-
[email protected](not _has_env(), reason="CUA_API_KEY not set")
-async def test_windows_stateful_snapshot_fork():
- """Stateful snapshot captures RAM — fork resumes instantly without rebooting."""
-
- t0 = time.monotonic()
-
- P("\n Creating Sandbox with Image.windows('server-2025')...")
- async with Sandbox.ephemeral(Image.windows("server-2025"), local=False) as sb:
- t_create = time.monotonic() - t0
- P(f" Sandbox ready: {t_create:.1f}s name={sb.name}")
-
- # Verify CUA server is running
- screen = await sb.screenshot()
- P(f" Screenshot: {len(screen)} bytes")
-
- # Stateful snapshot — captures memory state
- t1 = time.monotonic()
- P(" Taking stateful snapshot...")
- snapshot_img = await sb.snapshot(stateful=True)
- t_snap = time.monotonic() - t1
- P(f" Stateful snapshot: {t_snap:.2f}s")
-
- # Fork from stateful snapshot — should resume instantly
- t2 = time.monotonic()
- P(" Forking from stateful snapshot...")
- async with Sandbox.ephemeral(snapshot_img, local=False) as fork:
- t_fork = time.monotonic() - t2
- P(f" Fork ready: {t_fork:.1f}s name={fork.name}")
-
- # Fork should have CUA server immediately available (no reboot)
- fork_screen = await fork.screenshot()
- P(f" Fork screenshot: {len(fork_screen)} bytes")
- assert len(fork_screen) > 1000, "Fork screenshot should be non-trivial"
-
- t_total = time.monotonic() - t0
- P("\n === STATEFUL TIMINGS ===")
- P(f" Create+ready: {t_create:.1f}s")
- P(f" Stateful snapshot: {t_snap:.2f}s")
- P(f" Fork+ready: {t_fork:.1f}s (should be <10s with stateful)")
- P(f" Total: {t_total:.1f}s")
diff --git a/libs/python/cua-sandbox/tests/test_windows_timing.py b/libs/python/cua-sandbox/tests/test_windows_timing.py
deleted file mode 100644
index b371aabde8..0000000000
--- a/libs/python/cua-sandbox/tests/test_windows_timing.py
+++ /dev/null
@@ -1,86 +0,0 @@
-"""Compare Windows VM restore timings: fresh create vs snapshot vs stateful snapshot.
-
-Run:
- CUA_API_KEY=sk-dev-test-key-local-12345 CUA_BASE_URL=http://localhost:8082 \
- uv run pytest tests/test_windows_timing.py -v -s
-"""
-
-import os
-import time
-
-import pytest
-from cua_sandbox import Image, Sandbox
-
-pytestmark = pytest.mark.asyncio
-
-
-def P(*a, **kw):
- print(*a, **kw, flush=True)
-
-
-def _has_env() -> bool:
- return bool(os.environ.get("CUA_API_KEY"))
-
-
[email protected](not _has_env(), reason="CUA_API_KEY not set")
-async def test_windows_all_restore_modes():
- """Compare: Image.windows() vs snapshot() vs snapshot(stateful=True) fork times."""
-
- results = {}
-
- # ── 1. Fresh create from Image.windows("server-2025") ──
- P("\n [1/3] Creating fresh VM from Image.windows('server-2025')...")
- t0 = time.monotonic()
- async with Sandbox.ephemeral(Image.windows("server-2025"), local=False) as sb:
- t_create = time.monotonic() - t0
- P(f" Ready in {t_create:.1f}s name={sb.name}")
- results["create"] = t_create
-
- screen = await sb.screenshot()
- P(f" Screenshot: {len(screen)} bytes")
-
- # ── 2. Non-stateful snapshot + fork ──
- P("\n [2/3] Taking non-stateful snapshot...")
- t1 = time.monotonic()
- snap_img = await sb.snapshot(stateful=False)
- t_snap = time.monotonic() - t1
- P(f" Snapshot: {t_snap:.2f}s")
- results["snapshot"] = t_snap
-
- P(" Forking from non-stateful snapshot...")
- t2 = time.monotonic()
- async with Sandbox.ephemeral(snap_img, local=False) as fork1:
- t_fork1 = time.monotonic() - t2
- P(f" Fork ready: {t_fork1:.1f}s name={fork1.name}")
- results["fork_nonstateful"] = t_fork1
-
- fork1_screen = await fork1.screenshot()
- P(f" Screenshot: {len(fork1_screen)} bytes")
-
- # ── 3. Stateful snapshot + fork ──
- P("\n [3/3] Taking stateful snapshot...")
- t3 = time.monotonic()
- snap_stateful = await sb.snapshot(stateful=True)
- t_snap_s = time.monotonic() - t3
- P(f" Stateful snapshot: {t_snap_s:.2f}s")
- results["snapshot_stateful"] = t_snap_s
-
- P(" Forking from stateful snapshot...")
- t4 = time.monotonic()
- async with Sandbox.ephemeral(snap_stateful, local=False) as fork2:
- t_fork2 = time.monotonic() - t4
- P(f" Fork ready: {t_fork2:.1f}s name={fork2.name}")
- results["fork_stateful"] = t_fork2
-
- fork2_screen = await fork2.screenshot()
- P(f" Screenshot: {len(fork2_screen)} bytes")
-
- P(f"\n {'='*50}")
- P(" TIMING COMPARISON")
- P(f" {'='*50}")
- P(f" Image.windows() create: {results['create']:6.1f}s")
- P(f" snapshot(stateful=False): {results['snapshot']:6.2f}s")
- P(f" fork from non-stateful: {results['fork_nonstateful']:6.1f}s")
- P(f" snapshot(stateful=True): {results['snapshot_stateful']:6.2f}s")
- P(f" fork from stateful: {results['fork_stateful']:6.1f}s")
- P(f" {'='*50}")
diff --git a/libs/python/cua-sandbox/uv.lock b/libs/python/cua-sandbox/uv.lock
index 2369d58440..30abe14d26 100644
--- a/libs/python/cua-sandbox/uv.lock
+++ b/libs/python/cua-sandbox/uv.lock
@@ -583,18 +583,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/9f/1e/5a2322065d7e45dc62e16fc0f8cac065ec7403f5a12f5dc67feff73e2c75/cua_driver-0.28.2-py3-none-win_arm64.whl", hash = "sha256:5c03234fbf9ab8c1830caea4c364f6f84614986c8d15cb8e64210e9b65bec278", size = 25033022, upload-time = "2026-09-15T21:57:34.259Z" },
]
-[[package]]
-name = "cua-fleet"
-version = "0.1.17"
-source = { registry = "https://wheels.cua.ai/simple" }
-wheels = [
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.17-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:a8908b5c7f0f3c75d09b908b58867d43270f69d3726bb0d90316443f2265d0e3" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.17-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6aea577f21343326aeb06df03c07df65df8dd2f3b0097e02f25a7bc6b9d2c458" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.17-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:bda49298c77c65eb349e8420f9237f6b7fb2fd25203747df98a9513b98fd5d73" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.17-py3-none-manylinux_2_34_x86_64.whl", hash = "sha256:4cdbc89e850d841481713abf1e8bf9719b2e33b3c31f26bbea5f63e1ead3c6c0" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.17-py3-none-win_amd64.whl", hash = "sha256:ee4c139b1c0cebe1702114a34fd0fd60d216c5862d9fdc3472bb8b9879ac9eae" },
-]
-
[[package]]
name = "cua-sandbox"
version = "0.9.0"
@@ -602,7 +590,6 @@ source = { editable = "." }
dependencies = [
{ name = "cua" },
{ name = "cua-core" },
- { name = "cua-fleet" },
{ name = "grpcio" },
{ name = "httpx" },
{ name = "jsonschema" },
@@ -646,7 +633,6 @@ requires-dist = [
{ name = "cua", editable = "../../cua/python" },
{ name = "cua-core", specifier = ">=0.1.18,<0.4.0" },
{ name = "cua-driver", marker = "extra == 'driver'", specifier = "==0.28.2" },
- { name = "cua-fleet", specifier = "==0.1.17" },
{ name = "grpcio", specifier = "==1.78.0" },
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "jsonschema", specifier = ">=4.23,<5.0" },
diff --git a/libs/python/cua-train/README.md b/libs/python/cua-train/README.md
deleted file mode 100644
index cef69eddc9..0000000000
--- a/libs/python/cua-train/README.md
+++ /dev/null
@@ -1,24 +0,0 @@
-# cua-train
-
-Python client for the [Cua Cloud](https://run.cua.ai) API.
-
-```bash
-pip install cua-train
-```
-
-```python
-from cua_train import TrainClient
-
-client = TrainClient.from_key(
- client_id="ukey-...", # from your Cua Cloud account
- client_secret="...",
-)
-
-# Control plane: claim a VM
-http = client.get_async_httpx_client()
-await http.post("/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/my-pool/osgymsandboxclaims", json={...})
-
-# Data plane: reach a service the sandbox publishes
-# (/api/svc/<namespace>/<sandbox>-<service>/<path>)
-await http.get("/api/svc/my-pool/my-sandbox-web/health")
-```
diff --git a/libs/python/cua-train/pyproject.toml b/libs/python/cua-train/pyproject.toml
deleted file mode 100644
index bef5804d2a..0000000000
--- a/libs/python/cua-train/pyproject.toml
+++ /dev/null
@@ -1,38 +0,0 @@
-[project]
-name = "cua-train"
-version = "0.1.2"
-description = "Cua Cloud Python client — control and data plane for Cua Cloud desktop VM pools"
-readme = "README.md"
-license = "MIT"
-authors = [
- { name = "TryCua", email = "[email protected]" }
-]
-keywords = [
- "cua",
- "computer-use",
- "cloud",
- "vm",
- "automation",
-]
-classifiers = [
- "Development Status :: 3 - Alpha",
- "Intended Audience :: Developers",
- "License :: OSI Approved :: MIT License",
- "Programming Language :: Python :: 3",
- "Programming Language :: Python :: 3.10",
- "Programming Language :: Python :: 3.11",
- "Programming Language :: Python :: 3.12",
-]
-requires-python = ">=3.10"
-dependencies = ["httpx>=0.27.0"]
-
-[project.urls]
-Homepage = "https://run.cua.ai"
-Repository = "https://github.com/trycua/cua"
-
-[build-system]
-requires = ["hatchling"]
-build-backend = "hatchling.build"
-
-[tool.hatch.build.targets.wheel]
-packages = ["src/cua_train"]
diff --git a/libs/python/cua-train/src/cua_train/__init__.py b/libs/python/cua-train/src/cua_train/__init__.py
deleted file mode 100644
index 4808433189..0000000000
--- a/libs/python/cua-train/src/cua_train/__init__.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""cua-train — Python client for the Cua Cloud API."""
-
-from .client import TrainClient
-
-__all__ = ["TrainClient"]
diff --git a/libs/python/cua-train/src/cua_train/client.py b/libs/python/cua-train/src/cua_train/client.py
deleted file mode 100644
index 652c883a4f..0000000000
--- a/libs/python/cua-train/src/cua_train/client.py
+++ /dev/null
@@ -1,117 +0,0 @@
-"""TrainClient — authenticated httpx client for the Cua Cloud API."""
-
-from __future__ import annotations
-
-import threading
-import time
-
-import httpx
-
-
-class TrainClient:
- """Authenticated client for the Cua Cloud API.
-
- Obtain via :meth:`from_key` using a per-user key (``ukey-…``) from
- your Cua Cloud account. The client transparently refreshes its bearer
- token before it expires.
-
- Both the control plane (VM claim lifecycle via ``/api/k8s``) and the
- data plane (exec/upload/screenshot via ``/api/svc``) are reached through
- the same base URL (default: ``https://run.cua.ai``).
- """
-
- _DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"
- _DEFAULT_BASE_URL = "https://run.cua.ai"
-
- def __init__(
- self,
- token: str,
- base_url: str = _DEFAULT_BASE_URL,
- *,
- token_url: str = _DEFAULT_TOKEN_URL,
- client_id: str = "",
- client_secret: str = "",
- token_deadline: float = 0.0,
- ) -> None:
- self._token = token
- self._base_url = base_url.rstrip("/")
- self._token_url = token_url
- self._client_id = client_id
- self._client_secret = client_secret
- self._token_deadline = token_deadline
- self._refresh_lock = threading.Lock()
- self._async_client: httpx.AsyncClient | None = None
-
- @classmethod
- def from_key(
- cls,
- *,
- token_url: str = _DEFAULT_TOKEN_URL,
- client_id: str,
- client_secret: str,
- base_url: str = _DEFAULT_BASE_URL,
- ) -> "TrainClient":
- """Exchange client credentials for a bearer token.
-
- Args:
- token_url: Keycloak token endpoint.
- client_id: Per-user key client ID (``ukey-…``).
- client_secret: Client secret.
- base_url: Cua Cloud API base URL (default: ``https://run.cua.ai``).
- """
- token, ttl = cls._exchange(token_url, client_id, client_secret)
- return cls(
- token=token,
- base_url=base_url,
- token_url=token_url,
- client_id=client_id,
- client_secret=client_secret,
- token_deadline=time.monotonic() + ttl,
- )
-
- @staticmethod
- def _exchange(token_url: str, client_id: str, client_secret: str) -> tuple[str, float]:
- resp = httpx.post(
- token_url,
- data={
- "grant_type": "client_credentials",
- "client_id": client_id,
- "client_secret": client_secret,
- },
- )
- resp.raise_for_status()
- body = resp.json()
- return body["access_token"], float(body.get("expires_in", 300))
-
- def reset_token(self) -> None:
- """Force re-exchange on the next :meth:`get_async_httpx_client` call."""
- self._token_deadline = 0
-
- def _refresh_token(self) -> None:
- if not self._client_id:
- return
- if time.monotonic() < self._token_deadline - 30:
- return
- with self._refresh_lock:
- if time.monotonic() < self._token_deadline - 30:
- return
- token, ttl = self._exchange(self._token_url, self._client_id, self._client_secret)
- self._token = token
- self._token_deadline = time.monotonic() + ttl
- auth_header = f"Bearer {token}"
- if self._async_client is not None:
- self._async_client.headers["Authorization"] = auth_header
-
- def get_async_httpx_client(self) -> httpx.AsyncClient:
- """Return an async httpx client with the current bearer token.
-
- Re-mints the token transparently when it is about to expire.
- """
- self._refresh_token()
- if self._async_client is None:
- self._async_client = httpx.AsyncClient(
- base_url=self._base_url,
- headers={"Authorization": f"Bearer {self._token}"},
- follow_redirects=False,
- )
- return self._async_client
diff --git a/libs/typescript/playground/src/adapters/cloud.ts b/libs/typescript/playground/src/adapters/cloud.ts
deleted file mode 100644
index c48c765b77..0000000000
--- a/libs/typescript/playground/src/adapters/cloud.ts
+++ /dev/null
@@ -1,282 +0,0 @@
-// Cloud adapter implementation
-// Uses CUA API for persistence, VMs, and inference configuration
-
-import type {
- PlaygroundAdapters,
- PersistenceAdapter,
- ComputerAdapter,
- InferenceAdapter,
- CloudAdapterConfig,
- ComputerInfo,
- InferenceConfig,
-} from './types';
-import type { AgentMessage, Chat, ModelProvider } from '../types';
-
-const CUA_VERSION_HEADERS: Record<string, string> = {
- 'X-Cua-Client-Version': `playground:${__CUA_VERSION__}`,
-};
-
-// =============================================================================
-// API Error Helper
-// =============================================================================
-
-class ApiError extends Error {
- constructor(
- public status: number,
- message: string
- ) {
- super(message);
- this.name = 'ApiError';
- }
-}
-
-// =============================================================================
-// Cloud Persistence Adapter
-// =============================================================================
-
-class CloudPersistenceAdapter implements PersistenceAdapter {
- constructor(
- private apiKey: string,
- private baseUrl: string
- ) {}
-
- private async fetch<T>(path: string, options?: RequestInit): Promise<T> {
- const response = await fetch(`${this.baseUrl}${path}`, {
- ...options,
- headers: {
- Authorization: `Bearer ${this.apiKey}`,
- 'Content-Type': 'application/json',
- ...CUA_VERSION_HEADERS,
- ...options?.headers,
- },
- });
-
- if (!response.ok) {
- let errorMessage: string;
- try {
- const errorBody = await response.json();
- errorMessage = errorBody.detail || errorBody.error || `HTTP ${response.status}`;
- } catch {
- errorMessage = `HTTP ${response.status}`;
- }
- throw new ApiError(response.status, errorMessage);
- }
-
- return response.json();
- }
-
- async loadChats(): Promise<Chat[]> {
- return this.fetch<Chat[]>('/v1/playground/chats');
- }
-
- async saveChat(chat: Chat): Promise<Chat> {
- if (chat.id) {
- return this.fetch<Chat>(`/v1/playground/chats/${chat.id}`, {
- method: 'PUT',
- body: JSON.stringify(chat),
- });
- }
- return this.fetch<Chat>('/v1/playground/chats', {
- method: 'POST',
- body: JSON.stringify(chat),
- });
- }
-
- async deleteChat(chatId: string): Promise<void> {
- await this.fetch(`/v1/playground/chats/${chatId}`, { method: 'DELETE' });
- }
-
- async saveMessages(chatId: string, messages: AgentMessage[]): Promise<void> {
- await this.fetch(`/v1/playground/chats/${chatId}/messages`, {
- method: 'PUT',
- body: JSON.stringify({ messages }),
- });
- }
-
- async loadSettings<T>(key: string): Promise<T | null> {
- try {
- return await this.fetch<T>(`/v1/playground/settings/${key}`);
- } catch (error) {
- // Return null if settings not found (404)
- if (error instanceof ApiError && error.status === 404) {
- return null;
- }
- throw error;
- }
- }
-
- async saveSettings<T>(key: string, value: T): Promise<void> {
- await this.fetch(`/v1/playground/settings/${key}`, {
- method: 'PUT',
- body: JSON.stringify({ value }),
- });
- }
-}
-
-// =============================================================================
-// Cloud Computer Adapter
-// =============================================================================
-
-// VM response type from API
-interface VMResponse {
- id: string;
- vmId?: string;
- name: string;
- customName?: string;
- status: string;
- vncUrl?: string | null;
- vnc_url?: string | null;
- agentUrl?: string | null;
- agent_url?: string | null;
-}
-
-class CloudComputerAdapter implements ComputerAdapter {
- constructor(
- private apiKey: string,
- private baseUrl: string
- ) {}
-
- private async fetch<T>(path: string, options?: RequestInit): Promise<T> {
- const response = await fetch(`${this.baseUrl}${path}`, {
- ...options,
- headers: {
- Authorization: `Bearer ${this.apiKey}`,
- 'Content-Type': 'application/json',
- ...CUA_VERSION_HEADERS,
- ...options?.headers,
- },
- });
-
- if (!response.ok) {
- let errorMessage: string;
- try {
- const errorBody = await response.json();
- errorMessage = errorBody.detail || errorBody.error || `HTTP ${response.status}`;
- } catch {
- errorMessage = `HTTP ${response.status}`;
- }
- throw new ApiError(response.status, errorMessage);
- }
-
- return response.json();
- }
-
- async listComputers(): Promise<ComputerInfo[]> {
- const vms = await this.fetch<VMResponse[]>('/v1/vms');
- return vms.map((vm) => ({
- id: vm.vmId || vm.id,
- name: vm.customName || vm.name || `VM ${vm.id}`,
- vncUrl: vm.vncUrl || vm.vnc_url || '',
- agentUrl: vm.agentUrl || vm.agent_url || '',
- status: this.mapVMStatus(vm.status),
- }));
- }
-
- private mapVMStatus(status: string): 'running' | 'stopped' | 'starting' | 'error' {
- switch (status.toLowerCase()) {
- case 'running':
- return 'running';
- case 'stopped':
- case 'suspended':
- return 'stopped';
- case 'starting':
- case 'provisioning':
- return 'starting';
- default:
- return 'error';
- }
- }
-
- async getDefaultComputer(): Promise<ComputerInfo | null> {
- const computers = await this.listComputers();
- // Prefer a running computer, otherwise return the first one
- return computers.find((c) => c.status === 'running') ?? computers[0] ?? null;
- }
-
- async checkHealth(computerId: string): Promise<boolean> {
- try {
- await this.fetch(`/v1/vms/${computerId}/health`);
- return true;
- } catch {
- return false;
- }
- }
-}
-
-// =============================================================================
-// Cloud Inference Adapter
-// =============================================================================
-
-class CloudInferenceAdapter implements InferenceAdapter {
- constructor(
- private apiKey: string,
- private baseUrl: string
- ) {}
-
- async getConfig(computer: ComputerInfo): Promise<InferenceConfig> {
- // Cloud manages API keys server-side, so we don't need to pass env vars
- return {
- baseUrl: computer.agentUrl,
- };
- }
-
- async getAvailableModels(): Promise<ModelProvider[]> {
- try {
- const response = await fetch(`${this.baseUrl}/v1/models`, {
- headers: { Authorization: `Bearer ${this.apiKey}`, ...CUA_VERSION_HEADERS },
- });
-
- if (!response.ok) {
- // Return default models if endpoint not available
- return this.getDefaultModels();
- }
-
- return response.json();
- } catch {
- // Return default models on error
- return this.getDefaultModels();
- }
- }
-
- private getDefaultModels(): ModelProvider[] {
- return [
- {
- name: 'Anthropic',
- models: [
- { id: 'claude-sonnet-4-20250514', name: 'Claude Sonnet 4' },
- { id: 'claude-3-5-sonnet-20241022', name: 'Claude 3.5 Sonnet' },
- ],
- },
- ];
- }
-}
-
-// =============================================================================
-// Factory Function
-// =============================================================================
-
-/**
- * Create a cloud adapter bundle for the playground.
- *
- * @param config - Configuration for the cloud adapter
- * @returns PlaygroundAdapters bundle for cloud usage
- *
- * @example
- * ```typescript
- * const adapters = createCloudAdapter({
- * apiKey: userApiKey,
- * baseUrl: 'https://api.cua.ai', // optional
- * });
- *
- * <Playground adapters={adapters} />
- * ```
- */
-export function createCloudAdapter(config: CloudAdapterConfig): PlaygroundAdapters {
- const baseUrl = config.baseUrl || 'https://api.cua.ai';
-
- return {
- persistence: new CloudPersistenceAdapter(config.apiKey, baseUrl),
- computer: new CloudComputerAdapter(config.apiKey, baseUrl),
- inference: new CloudInferenceAdapter(config.apiKey, baseUrl),
- };
-}
diff --git a/libs/typescript/playground/src/adapters/index.ts b/libs/typescript/playground/src/adapters/index.ts
index 9346252100..fc4c779545 100644
--- a/libs/typescript/playground/src/adapters/index.ts
+++ b/libs/typescript/playground/src/adapters/index.ts
@@ -1,4 +1,3 @@
// Adapter exports
export { createLocalAdapter } from './local';
-export { createCloudAdapter } from './cloud';
export * from './types';
diff --git a/libs/typescript/playground/src/adapters/types.ts b/libs/typescript/playground/src/adapters/types.ts
index 3c5091d4e8..b0fd2efc32 100644
--- a/libs/typescript/playground/src/adapters/types.ts
+++ b/libs/typescript/playground/src/adapters/types.ts
@@ -24,7 +24,6 @@ export interface PlaygroundAdapters {
/**
* Contract: Where chats are stored
* - Local implementation: localStorage
- * - Cloud implementation: CUA API
*/
export interface PersistenceAdapter {
/** Load all chats for the current user/session */
@@ -69,7 +68,6 @@ export interface ComputerInfo {
/**
* Contract: What computers are available
* - Local implementation: user-provided URLs, stored in localStorage
- * - Cloud implementation: CUA API for VMs
*/
export interface ComputerAdapter {
/** List all available computers */
@@ -113,7 +111,6 @@ export interface InferenceConfig {
/**
* Contract: How inference is configured
* - Local implementation: user-provided API keys
- * - Cloud implementation: CUA-managed keys
*/
export interface InferenceAdapter {
/** Get inference configuration for a specific computer */
@@ -141,15 +138,3 @@ export interface LocalAdapterConfig {
openai?: string;
};
}
-
-/**
- * Configuration for creating a cloud adapter.
- * Used when running the playground with CUA cloud infrastructure.
- */
-export interface CloudAdapterConfig {
- /** CUA API key for authentication */
- apiKey: string;
-
- /** Base URL for the CUA API (defaults to https://api.cua.ai) */
- baseUrl?: string;
-}
diff --git a/libs/typescript/playground/src/components/Playground.tsx b/libs/typescript/playground/src/components/Playground.tsx
index 589dab6269..c4d82a2978 100644
--- a/libs/typescript/playground/src/components/Playground.tsx
+++ b/libs/typescript/playground/src/components/Playground.tsx
@@ -44,8 +44,6 @@ interface PlaygroundProps {
};
/** Custom welcome message for empty state */
welcomeMessage?: string;
- /** Render prop for cloud VM creation wizard. Injected by cloud website. */
- renderCloudCreate?: (props: { onCreated: () => void; onCancel: () => void }) => React.ReactNode;
}
// =============================================================================
@@ -61,7 +59,6 @@ function PlaygroundContentInternal({
className,
logo,
welcomeMessage,
- renderCloudCreate,
}: Omit<PlaygroundProps, 'adapters' | 'initialChats'>) {
const { state, dispatch, adapters } = usePlayground();
const [showCustomComputerModal, setShowCustomComputerModal] = useState(false);
@@ -245,7 +242,6 @@ function PlaygroundContentInternal({
<AddSandboxModal
isOpen={showCustomComputerModal}
onClose={() => setShowCustomComputerModal(false)}
- renderCloudCreate={renderCloudCreate}
/>
</div>
);
diff --git a/libs/typescript/playground/src/components/composed/PlaygroundContent.tsx b/libs/typescript/playground/src/components/composed/PlaygroundContent.tsx
index 21b4a3e822..51dbc96e9b 100644
--- a/libs/typescript/playground/src/components/composed/PlaygroundContent.tsx
+++ b/libs/typescript/playground/src/components/composed/PlaygroundContent.tsx
@@ -85,9 +85,6 @@ interface PlaygroundContentProps {
onToast?: (message: string, type?: 'success' | 'error' | 'info') => void;
/** Optional class name for the root layout container (can override default h-screen w-screen) */
className?: string;
-
- /** Render prop for cloud VM creation wizard. Injected by cloud website. */
- renderCloudCreate?: (props: { onCreated: () => void; onCancel: () => void }) => React.ReactNode;
}
/**
@@ -116,7 +113,6 @@ export function PlaygroundContent({
onExamplePromptSelected,
onToast,
className,
- renderCloudCreate,
}: PlaygroundContentProps) {
const { state, dispatch, adapters } = usePlayground();
const activeChat = useActiveChat();
@@ -342,11 +338,7 @@ export function PlaygroundContent({
{settingsModal}
- <AddSandboxModal
- isOpen={showAddSandboxModal}
- onClose={handleCloseAddSandbox}
- renderCloudCreate={renderCloudCreate}
- />
+ <AddSandboxModal isOpen={showAddSandboxModal} onClose={handleCloseAddSandbox} />
</>
);
}
diff --git a/libs/typescript/playground/src/components/modals/AddSandboxModal.tsx b/libs/typescript/playground/src/components/modals/AddSandboxModal.tsx
index 5fee3653d0..eee2a0ff58 100644
--- a/libs/typescript/playground/src/components/modals/AddSandboxModal.tsx
+++ b/libs/typescript/playground/src/components/modals/AddSandboxModal.tsx
@@ -1,5 +1,5 @@
// Add Sandbox wizard modal
-// Supports three paths: Local Docker, Cloud Sandbox, Custom URL
+// Supports two paths: Local Docker, Custom URL
//
// Sub-components live in sibling files:
// SourcePicker.tsx - Step 1: choose source
@@ -26,21 +26,13 @@ export interface AddSandboxModalProps {
isOpen: boolean;
onClose: () => void;
onAdd?: (computer: ComputerInfo) => void;
- /** Render prop for cloud VM creation wizard. Injected by cloud website. */
- renderCloudCreate?: (props: { onCreated: () => void; onCancel: () => void }) => React.ReactNode;
className?: string;
}
// Backward-compatible alias
export type CustomComputerModalProps = AddSandboxModalProps;
-export function AddSandboxModal({
- isOpen,
- onClose,
- onAdd,
- renderCloudCreate,
- className,
-}: AddSandboxModalProps) {
+export function AddSandboxModal({ isOpen, onClose, onAdd, className }: AddSandboxModalProps) {
const { adapters, dispatch } = usePlayground();
const [step, setStep] = useState<WizardStep>('source');
@@ -190,23 +182,12 @@ export function AddSandboxModal({
[adapters, dispatch, onAdd, handleClose]
);
- const handleCloudCreated = useCallback(async () => {
- try {
- const computers = await adapters.computer.listComputers();
- dispatch({ type: 'SET_COMPUTERS', payload: computers });
- } catch (err) {
- console.error('Failed to refresh computers after cloud creation:', err);
- }
- handleClose();
- }, [adapters, dispatch, handleClose]);
-
const showBackButton = step === 'configure';
const title = (() => {
if (step === 'source') return 'Add Sandbox';
if (source === 'local' && !selectedPreset) return 'Choose Sandbox Type';
if (source === 'local' && selectedPreset) return selectedPreset.name;
- if (source === 'cloud') return 'Create Cloud Sandbox';
if (source === 'custom') return 'Custom URL';
return 'Add Sandbox';
})();
@@ -216,11 +197,7 @@ export function AddSandboxModal({
isOpen={isOpen}
onClose={handleClose}
showCloseButton={!showBackButton}
- contentClassName={cn(
- 'max-w-lg p-0',
- step === 'configure' && source === 'cloud' && 'max-w-2xl',
- className
- )}
+ contentClassName={cn('max-w-lg p-0', className)}
>
{/* Header */}
<div className="flex items-center gap-3 border-b border-neutral-200 px-6 py-4 dark:border-neutral-700">
@@ -238,9 +215,7 @@ export function AddSandboxModal({
{/* Content */}
<div className="overflow-y-auto px-6 py-4" style={{ maxHeight: '70vh' }}>
- {step === 'source' && (
- <SourcePicker onSelect={handleSelectSource} hasCloud={!!renderCloudCreate} />
- )}
+ {step === 'source' && <SourcePicker onSelect={handleSelectSource} />}
{step === 'configure' && source === 'local' && !selectedPreset && (
<PresetGrid onSelect={handleSelectPreset} />
@@ -269,10 +244,6 @@ export function AddSandboxModal({
/>
)}
- {step === 'configure' && source === 'cloud' && renderCloudCreate && (
- <div>{renderCloudCreate({ onCreated: handleCloudCreated, onCancel: handleClose })}</div>
- )}
-
{step === 'configure' && source === 'custom' && (
<CustomUrlForm
name={customName}
diff --git a/libs/typescript/playground/src/components/modals/SourcePicker.tsx b/libs/typescript/playground/src/components/modals/SourcePicker.tsx
index 46ae7a8f22..2b2ac175c2 100644
--- a/libs/typescript/playground/src/components/modals/SourcePicker.tsx
+++ b/libs/typescript/playground/src/components/modals/SourcePicker.tsx
@@ -1,21 +1,19 @@
-// Step 1: Source selection cards (Local Docker, Cloud Sandbox, Custom URL)
+// Step 1: Source selection cards (Local Docker, Custom URL)
-import { ChevronRight, Globe, Monitor, Server } from 'lucide-react';
+import { ChevronRight, Globe, Monitor } from 'lucide-react';
-export type SandboxSource = 'local' | 'cloud' | 'custom';
+export type SandboxSource = 'local' | 'custom';
export interface SourcePickerProps {
onSelect: (source: SandboxSource) => void;
- hasCloud: boolean;
}
-export function SourcePicker({ onSelect, hasCloud }: SourcePickerProps) {
+export function SourcePicker({ onSelect }: SourcePickerProps) {
const cards: Array<{
source: SandboxSource;
icon: React.ReactNode;
title: string;
description: string;
- hidden?: boolean;
}> = [
{
source: 'local',
@@ -23,13 +21,6 @@ export function SourcePicker({ onSelect, hasCloud }: SourcePickerProps) {
title: 'Local (Docker)',
description: 'Run a sandbox on your machine using Docker',
},
- {
- source: 'cloud',
- icon: <Server className="h-6 w-6" />,
- title: 'Cloud Sandbox',
- description: 'Provision a cloud VM',
- hidden: !hasCloud,
- },
{
source: 'custom',
icon: <Globe className="h-6 w-6" />,
@@ -40,25 +31,23 @@ export function SourcePicker({ onSelect, hasCloud }: SourcePickerProps) {
return (
<div className="flex flex-col gap-3">
- {cards
- .filter((c) => !c.hidden)
- .map((card) => (
- <button
- key={card.source}
- type="button"
- onClick={() => onSelect(card.source)}
- className="flex items-center gap-4 rounded-lg border border-neutral-200 p-4 text-left transition-colors hover:border-blue-400 hover:bg-blue-50/50 dark:border-neutral-600 dark:hover:border-blue-500 dark:hover:bg-blue-950/20"
- >
- <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-neutral-100 text-neutral-600 dark:bg-neutral-700 dark:text-neutral-300">
- {card.icon}
- </div>
- <div className="flex-1">
- <p className="font-medium text-neutral-900 dark:text-white">{card.title}</p>
- <p className="text-sm text-neutral-500 dark:text-neutral-400">{card.description}</p>
- </div>
- <ChevronRight className="h-5 w-5 text-neutral-400" />
- </button>
- ))}
+ {cards.map((card) => (
+ <button
+ key={card.source}
+ type="button"
+ onClick={() => onSelect(card.source)}
+ className="flex items-center gap-4 rounded-lg border border-neutral-200 p-4 text-left transition-colors hover:border-blue-400 hover:bg-blue-50/50 dark:border-neutral-600 dark:hover:border-blue-500 dark:hover:bg-blue-950/20"
+ >
+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-neutral-100 text-neutral-600 dark:bg-neutral-700 dark:text-neutral-300">
+ {card.icon}
+ </div>
+ <div className="flex-1">
+ <p className="font-medium text-neutral-900 dark:text-white">{card.title}</p>
+ <p className="text-sm text-neutral-500 dark:text-neutral-400">{card.description}</p>
+ </div>
+ <ChevronRight className="h-5 w-5 text-neutral-400" />
+ </button>
+ ))}
</div>
);
}
diff --git a/libs/typescript/playground/src/index.ts b/libs/typescript/playground/src/index.ts
index bfef06ac57..d4f595f073 100644
--- a/libs/typescript/playground/src/index.ts
+++ b/libs/typescript/playground/src/index.ts
@@ -2,7 +2,7 @@
// @trycua/playground
// =============================================================================
// Reusable playground UI for Cua computer-use agents.
-// Supports both local (localStorage + user-provided URLs) and cloud (CUA API) usage.
+// Runs against your own machines: localStorage + user-provided agent and VNC URLs.
// Types
export * from './types';
@@ -10,7 +10,6 @@ export * from './adapters/types';
// Adapters
export { createLocalAdapter } from './adapters/local';
-export { createCloudAdapter } from './adapters/cloud';
// Utilities
export * from './utils';
diff --git a/pyproject.toml b/pyproject.toml
index 9103fc1b5d..321d70cb42 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -74,16 +74,11 @@ cua-agent = { workspace = true }
cua-core = { workspace = true }
cua-som = { workspace = true }
cua-bench-ui = { workspace = true }
-# cua-sandbox is not a workspace member (it pulls the native cua-fleet wheel
-# from the cua-wheels index); consumers resolve it from the in-repo path.
+# cua-sandbox is not a workspace member; consumers resolve it from the in-repo path.
cua-sandbox = { path = "libs/python/cua-sandbox", editable = true }
# cua-sandbox depends on the cua SDK (UniFFI binding), built from the repo.
cua = { path = "libs/cua/python", editable = true }
-[[tool.uv.index]]
-name = "cua-wheels"
-url = "https://wheels.cua.ai/simple"
-
[tool.black]
line-length = 100
target-version = ["py312"]
diff --git a/release-please-config.json b/release-please-config.json
index f425e98f96..0eb18b91b4 100644
--- a/release-please-config.json
+++ b/release-please-config.json
@@ -570,20 +570,6 @@
}
]
},
- "libs/python/cua-train": {
- "release-type": "simple",
- "component": "train",
- "package-name": "cua-train",
- "bump-minor-pre-major": true,
- "changelog-path": "CHANGELOG.md",
- "extra-files": [
- {
- "type": "toml",
- "path": "pyproject.toml",
- "jsonpath": "$.project.version"
- }
- ]
- },
"libs/typescript/core": {
"release-type": "simple",
"component": "npm-core",
diff --git a/scripts/docs-generators/cli-specs/cb.json b/scripts/docs-generators/cli-specs/cb.json
index f3414585fc..fad4844554 100644
--- a/scripts/docs-generators/cli-specs/cb.json
+++ b/scripts/docs-generators/cli-specs/cb.json
@@ -55,8 +55,8 @@
"aliases": [],
"default_value": false,
"env": null,
- "help": "cloud: keep one replica ready when the managed pool is first created",
- "hidden": false,
+ "help": "",
+ "hidden": true,
"name": "warm",
"repeatable": false,
"short_name": null,
@@ -251,7 +251,7 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "Which engine: gvisor or runc (local containers), qemu or lume (local VMs), gvisor or kubevirt (cloud containers, VMs). Implies its kind. Default auto: the SDK picks (CUA_DEFAULT_RUNTIME, else `cua config set default.runtime`)",
+ "help": "Which engine: gvisor or runc (containers), qemu or lume (VMs). Implies its kind. Default auto: the SDK picks (CUA_DEFAULT_RUNTIME, else `cua config set default.runtime`)",
"hidden": false,
"is_optional": true,
"multiple_values": false,
@@ -274,7 +274,7 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "Image for every task (overrides the task's setup_config.image): an OS alias (linux, windows, macos:tahoe), ghcr.io/trycua/<os>, any registry ref or a digest, or pool:<name> for an existing Fleet pool. Env: CUA_BENCH_IMAGE",
+ "help": "Image for every task (overrides the task's setup_config.image): an OS alias (linux, windows, macos:tahoe), ghcr.io/trycua/<os>, any registry ref or a digest. Env: CUA_BENCH_IMAGE",
"hidden": false,
"is_optional": true,
"multiple_values": false,
@@ -322,8 +322,8 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "cloud: how long a claim outlives a crashed run (default 15m; renewed while running)",
- "hidden": false,
+ "help": "",
+ "hidden": true,
"is_optional": true,
"multiple_values": false,
"name": "claim-ttl",
@@ -544,8 +544,8 @@
"aliases": [],
"default_value": false,
"env": null,
- "help": "cloud: keep one replica ready when the managed pool is first created",
- "hidden": false,
+ "help": "",
+ "hidden": true,
"name": "warm",
"repeatable": false,
"short_name": null,
@@ -756,7 +756,7 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "Which engine: gvisor or runc (local containers), qemu or lume (local VMs), gvisor or kubevirt (cloud containers, VMs). Implies its kind. Default auto: the SDK picks (CUA_DEFAULT_RUNTIME, else `cua config set default.runtime`)",
+ "help": "Which engine: gvisor or runc (containers), qemu or lume (VMs). Implies its kind. Default auto: the SDK picks (CUA_DEFAULT_RUNTIME, else `cua config set default.runtime`)",
"hidden": false,
"is_optional": true,
"multiple_values": false,
@@ -779,7 +779,7 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "Image for every task (overrides the task's setup_config.image): an OS alias (linux, windows, macos:tahoe), ghcr.io/trycua/<os>, any registry ref or a digest, or pool:<name> for an existing Fleet pool. Env: CUA_BENCH_IMAGE",
+ "help": "Image for every task (overrides the task's setup_config.image): an OS alias (linux, windows, macos:tahoe), ghcr.io/trycua/<os>, any registry ref or a digest. Env: CUA_BENCH_IMAGE",
"hidden": false,
"is_optional": true,
"multiple_values": false,
@@ -827,8 +827,8 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "cloud: how long a claim outlives a crashed run (default 15m; renewed while running)",
- "hidden": false,
+ "help": "",
+ "hidden": true,
"is_optional": true,
"multiple_values": false,
"name": "claim-ttl",
@@ -1196,8 +1196,8 @@
"aliases": [],
"default_value": false,
"env": null,
- "help": "cloud: keep one replica ready when the managed pool is first created",
- "hidden": false,
+ "help": "",
+ "hidden": true,
"name": "warm",
"repeatable": false,
"short_name": null,
@@ -1359,7 +1359,7 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "Which engine: gvisor or runc (local containers), qemu or lume (local VMs), gvisor or kubevirt (cloud containers, VMs). Implies its kind. Default auto: the SDK picks (CUA_DEFAULT_RUNTIME, else `cua config set default.runtime`)",
+ "help": "Which engine: gvisor or runc (containers), qemu or lume (VMs). Implies its kind. Default auto: the SDK picks (CUA_DEFAULT_RUNTIME, else `cua config set default.runtime`)",
"hidden": false,
"is_optional": true,
"multiple_values": false,
@@ -1382,7 +1382,7 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "Image for every task (overrides the task's setup_config.image): an OS alias (linux, windows, macos:tahoe), ghcr.io/trycua/<os>, any registry ref or a digest, or pool:<name> for an existing Fleet pool. Env: CUA_BENCH_IMAGE",
+ "help": "Image for every task (overrides the task's setup_config.image): an OS alias (linux, windows, macos:tahoe), ghcr.io/trycua/<os>, any registry ref or a digest. Env: CUA_BENCH_IMAGE",
"hidden": false,
"is_optional": true,
"multiple_values": false,
@@ -1430,8 +1430,8 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "cloud: how long a claim outlives a crashed run (default 15m; renewed while running)",
- "hidden": false,
+ "help": "",
+ "hidden": true,
"is_optional": true,
"multiple_values": false,
"name": "claim-ttl",
diff --git a/scripts/docs-generators/python-sdk.ts b/scripts/docs-generators/python-sdk.ts
index 0f4acc0504..bbbb7b5cec 100644
--- a/scripts/docs-generators/python-sdk.ts
+++ b/scripts/docs-generators/python-sdk.ts
@@ -173,14 +173,14 @@ export const SANDBOX_PAGES: PageSpec[] = [
title: 'Managed pools (cua_sandbox.pools)',
objects: [
`${SB}.pools`,
- `${SB}._autopool.list_pools`,
- `${SB}._autopool.list_claims`,
- `${SB}._autopool.gc`,
- `${SB}._autopool.gc_pools`,
- `${SB}._autopool.is_managed_pool_name`,
- `${SB}._autopool.ManagedPoolInfo`,
- `${SB}._autopool.ClaimInfo`,
- `${SB}._autopool.GcReport`,
+ `${SB}.pools.list_pools`,
+ `${SB}.pools.list_claims`,
+ `${SB}.pools.gc`,
+ `${SB}.pools.gc_pools`,
+ `${SB}.pools.is_managed_pool_name`,
+ `${SB}.pools.ManagedPoolInfo`,
+ `${SB}.pools.ClaimInfo`,
+ `${SB}.pools.GcReport`,
],
},
{
@@ -197,7 +197,7 @@ export const SANDBOX_PAGES: PageSpec[] = [
objects: [
`${SB}.spec.PoolSpecMismatch`,
`${SB}.spec.ClaimSecretsNotDelivered`,
- `${SB}.transport.fleet_cloud.PoolAccessDeniedError`,
+ `${SB}.spec.PoolAccessDeniedError`,
],
},
],
@@ -323,7 +323,6 @@ export const SANDBOX_PAGES: PageSpec[] = [
title: 'Configuration and sign-in',
objects: [
`${SB}._config.configure`,
- `${SB}._config.fleet_auth_source`,
`${SB}._auth.login`,
`${SB}._auth.whoami`,
],
diff --git a/scripts/images/image-refs-allowlist.json b/scripts/images/image-refs-allowlist.json
index 49b6ad26a3..188fe9b94d 100644
--- a/scripts/images/image-refs-allowlist.json
+++ b/scripts/images/image-refs-allowlist.json
@@ -50,7 +50,6 @@
"ghcr.io/x/*": "placeholder namespace in tests",
"ghcr.io/x:*": "placeholder ref in tests",
"ghcr.io/nope/*": "placeholder ref in tests",
- "quay.io/org/*": "placeholder namespace in tests",
"quay.io/x/*": "placeholder namespace in tests",
"public.ecr.aws/example/*": "placeholder namespace in tests",
"registry.example.com/*": "placeholder registry in tests",
@@ -223,8 +222,7 @@
"reason": "legacy name of ghcr.io/trycua/linux (frozen, read-only: never pushed or re-tagged); historical tests of legacy refs and tag safety",
"paths": [
"libs/cua/crates/cua-fleet/tests/fixtures/image-variants.json",
- "libs/cua/crates/cua-spaces/tests/generic.rs",
- "libs/python/cua-sandbox/tests/test_fleet_image_variants.py"
+ "libs/cua/crates/cua-spaces/tests/generic.rs"
]
},
"ghcr.io/trycua/cua-desktop-linux:e2e-86b137f": {
@@ -239,7 +237,6 @@
"libs/cua/crates/cua-fleet/tests/fixtures/image-variants.json",
"libs/cua/crates/cua-image/src/canonical.rs",
"libs/cua/crates/cua-spaces/tests/generic.rs",
- "libs/python/cua-sandbox/tests/test_fleet_image_variants.py",
"scripts/images/docs-image-refs-baseline.json",
"scripts/images/test-check-tag-safety.sh"
]
@@ -261,8 +258,7 @@
"reason": "synthetic tag or digest in a test (parser, resolver or tag-safety input), never pulled",
"paths": [
"libs/cua/crates/cua-fleet/tests/size_limits.rs",
- "libs/cua/crates/cua-fleet/tests/spec.rs",
- "libs/python/cua-sandbox/tests/test_pool_spec.py"
+ "libs/cua/crates/cua-fleet/tests/spec.rs"
]
},
"ghcr.io/trycua/cua-plain-ubuntu-server:existing": {
@@ -425,13 +421,6 @@
"libs/python/cua-sandbox/tests/test_from_registry_ostype.py"
]
},
- "ghcr.io/trycua/minecraft-workspace:latest": {
- "reason": "cloud workspace image in cua-sandbox Fleet test fixtures",
- "paths": [
- "libs/python/cua-sandbox/tests/_image_fixtures.py",
- "libs/python/cua-sandbox/tests/test_pull_secret.py"
- ]
- },
"ghcr.io/trycua/omarchy:edge-20260925-abcdef1": {
"reason": "synthetic tag or digest in a test (parser, resolver or tag-safety input), never pulled",
"paths": [
@@ -536,12 +525,10 @@
"public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04:docker-main-809e3f81": {
"reason": "cloud-built Fleet workspace image (owned and gated by the cloud repo's image doctor); pinned by live tests, fixtures and the qualified-image facts",
"paths": [
- "libs/cua-bench/cua_bench/tests/live/test_cloud_live.py",
"libs/cua/crates/cua-fleet/tests/fixtures/image-variants.json",
"libs/cua/crates/cua-fleet/tests/live.rs",
"libs/cua/crates/cua-fleet/tests/live_autopool.rs",
"libs/cua/python/tests/test_live_fleet.py",
- "libs/python/cua-sandbox/tests/live/test_fleet_autopool_live.py",
"tests/e2e/cua-sdk/python/e2e.py",
"tests/e2e/cua-sdk/rust/src/lib.rs",
"tests/e2e/cua-sdk/typescript/lib.mjs"
@@ -562,13 +549,6 @@
"libs/cua/crates/cua-fleet/src/pool.rs"
]
},
- "public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04:main-1": {
- "reason": "cloud-built Fleet workspace image (owned and gated by the cloud repo's image doctor); pinned by live tests, fixtures and the qualified-image facts",
- "paths": [
- "libs/python/cua-sandbox/tests/test_pool.py",
- "libs/python/cua-sandbox/tests/test_sandbox_fleet_lifecycle.py"
- ]
- },
"public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04:main-38352d34": {
"reason": "cloud-built Fleet workspace image (owned and gated by the cloud repo's image doctor); pinned by live tests, fixtures and the qualified-image facts",
"paths": [
@@ -607,7 +587,6 @@
"paths": [
"libs/cua/crates/cua-sandbox-core/src/fleet_local.rs",
"libs/cua/crates/cua-sandbox-core/tests/providers.rs",
- "libs/python/cua-sandbox/tests/test_pull_secret.py",
"tests/e2e/local-runtimes/fleet-catalog.public.json"
]
}
@@ -652,9 +631,6 @@
"libs/images/common/tools/tests/fixtures/manifest.linux.json",
"libs/images/common/tools/tests/test_cua_image_manifest.py",
"libs/images/linux/image.json",
- "libs/python/cua-sandbox/tests/_image_fixtures.py",
- "libs/python/cua-sandbox/tests/test_fleet_image_variants.py",
- "libs/python/cua-sandbox/tests/test_pool.py",
"scripts/images/check-image-refs.py",
"scripts/images/check-tag-safety.sh",
"scripts/images/docs-image-refs-baseline.json",
diff --git a/tests/e2e/cua-sdk/python/test_cua_sandbox_guides.py b/tests/e2e/cua-sdk/python/test_cua_sandbox_guides.py
index a9526f1d86..1680c38c33 100644
--- a/tests/e2e/cua-sdk/python/test_cua_sandbox_guides.py
+++ b/tests/e2e/cua-sdk/python/test_cua_sandbox_guides.py
@@ -1,5 +1,5 @@
"""cua-sandbox lane: the guides' own public API (``cua_sandbox.Pool``,
-``Image``, ``ClaimSpec``, ``Sandbox.ephemeral``) on top of the cua SDK.
+``Image``, ``Sandbox.ephemeral``) on top of the cua SDK.
Cua Cloud has ended (CUA-1854): every ``Pool`` call raises
``cua_sandbox._ended.CloudEnded``, so each check asserts that instead of a
@@ -37,7 +37,7 @@ def _expect_cloud_ended(py: str, call: str) -> None:
py,
f"""
import asyncio
- from cua_sandbox import Image, Pool, WarmPoolAutoscaling
+ from cua_sandbox import Image, Pool
from cua_sandbox._ended import CloudEnded
async def main():
try:
@@ -68,8 +68,7 @@ def test_pool_apply_with_autoscaling_is_cloud_ended(sandbox_python):
_expect_cloud_ended(
sandbox_python,
f"Pool.apply(Image.from_registry({e2e.LEGACY_FLEET_ROOTFS!r}), name={pool!r}, cpu=1, "
- "memory_mb=2048, autoscaling=WarmPoolAutoscaling(min_pool_size=0, "
- "initial_pool_size=0, max_pool_size=2), ttl_seconds_after_created=3600)",
+ "memory_mb=2048, autoscaling=None, ttl_seconds_after_created=3600)",
)
diff --git a/uv.lock b/uv.lock
index f63f7a07b5..1d0e878a3f 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1096,18 +1096,6 @@ provides-extras = ["otel", "telemetry"]
[package.metadata.requires-dev]
dev = [{ name = "pytest", specifier = ">=8.3.5" }]
-[[package]]
-name = "cua-fleet"
-version = "0.1.17"
-source = { registry = "https://wheels.cua.ai/simple" }
-wheels = [
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.17-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:a8908b5c7f0f3c75d09b908b58867d43270f69d3726bb0d90316443f2265d0e3" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.17-py3-none-macosx_11_0_arm64.whl", hash = "sha256:6aea577f21343326aeb06df03c07df65df8dd2f3b0097e02f25a7bc6b9d2c458" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.17-py3-none-manylinux_2_34_aarch64.whl", hash = "sha256:bda49298c77c65eb349e8420f9237f6b7fb2fd25203747df98a9513b98fd5d73" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.17-py3-none-manylinux_2_34_x86_64.whl", hash = "sha256:4cdbc89e850d841481713abf1e8bf9719b2e33b3c31f26bbea5f63e1ead3c6c0" },
- { url = "https://wheels.cua.ai/simple/cua-fleet/cua_fleet-0.1.17-py3-none-win_amd64.whl", hash = "sha256:ee4c139b1c0cebe1702114a34fd0fd60d216c5862d9fdc3472bb8b9879ac9eae" },
-]
-
[[package]]
name = "cua-sandbox"
version = "0.9.0"
@@ -1115,7 +1103,6 @@ source = { editable = "libs/python/cua-sandbox" }
dependencies = [
{ name = "cua" },
{ name = "cua-core" },
- { name = "cua-fleet" },
{ name = "grpcio" },
{ name = "httpx" },
{ name = "jsonschema" },
@@ -1132,7 +1119,6 @@ requires-dist = [
{ name = "cua", editable = "libs/cua/python" },
{ name = "cua-core", specifier = ">=0.1.18,<0.4.0" },
{ name = "cua-driver", marker = "extra == 'driver'", specifier = "==0.28.2" },
- { name = "cua-fleet", specifier = "==0.1.17" },
{ name = "grpcio", specifier = "==1.78.0" },
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "jsonschema", specifier = ">=4.23,<5.0" },