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(cua-sdk): ship the cua CLI as its own cua-cli wheel, guard wheel size (#5852)

ddupont63b54fd55ddb
diff --git a/.github/scripts/check_static_spacesd_packaged.sh b/.github/scripts/check_static_spacesd_packaged.sh
index 910cc540eb..12fbe91b31 100755
--- a/.github/scripts/check_static_spacesd_packaged.sh
+++ b/.github/scripts/check_static_spacesd_packaged.sh
@@ -9,7 +9,10 @@
# DIR holds downloaded release artifacts, flat or in per-artifact
# subdirectories (gh run download layout):
# *.tgz npm packages; trycua-cua-linux-{x64,arm64}-gnu-* are checked
-# *.whl wheels; manylinux x86_64/aarch64 are checked
+# *.whl wheels; manylinux x86_64/aarch64 `cua` wheels are checked: the
+# SDK library finds cua/bin/cua-spacesd-linux-<arch> (its bin/),
+# and the `cua` command hands it to the `cua-cli` wheel's CLI as
+# $CUA_SPACESD_STATIC)
# *.deb any deb; checked when it contains a `cua` ELF
# cua-cli-*-linux-*.tar.gz, cua-*-linux-*-gnu.tar.gz install.sh archives
# native-linux-*/ extracted native artifacts
@@ -75,6 +78,21 @@ check_dir() {
echo "ok $name: ${bin#"$d"/} (static, $arch, $(wc -c <"$bin" | tr -d ' ') bytes)"
}
+# check_wheel NAME DIR ARCH: DIR holds the unpacked `cua` wheel. The static
+# cua-spacesd must sit at cua/bin/, the library's bin/ directory (the CLI
+# comes from the `cua-cli` wheel and is pointed at it).
+check_wheel() {
+ local name="$1" d="$2" arch="$3" bin why
+ CHECKED=$((CHECKED + 1))
+ bin="$d/cua/bin/cua-spacesd-linux-$arch"
+ if [ ! -f "$bin" ]; then fail "$name" "no cua/bin/cua-spacesd-linux-$arch"; return; fi
+ if ! why="$(elf_check "$bin" "$arch")"; then fail "$name" "cua/bin/cua-spacesd-linux-$arch: $why"; return; fi
+ if [ -n "$VERSION" ] && ! grep -aqF "$VERSION" "$bin"; then
+ fail "$name" "cua/bin/cua-spacesd-linux-$arch does not contain version string $VERSION"; return
+ fi
+ echo "ok $name: cua/bin/cua-spacesd-linux-$arch (static, $arch, $(wc -c <"$bin" | tr -d ' ') bytes)"
+}
+
arch_of() {
case "$1" in
*x64* | *x86_64* | *amd64*) echo x86_64 ;;
@@ -89,10 +107,11 @@ while IFS= read -r f; do
trycua-cua-linux-*-gnu-*.tgz)
mkdir -p "$x"; tar -xzf "$f" -C "$x" || { fail "$base" "cannot unpack"; continue; }
check_dir "npm $base" "$x" "$(arch_of "$base")" ;;
+ cua_cli-*.whl) continue ;;
*.whl)
case "$base" in *manylinux*x86_64*) a=x86_64 ;; *manylinux*aarch64*) a=aarch64 ;; *) continue ;; esac
mkdir -p "$x"; python3 -m zipfile -e "$f" "$x" || { fail "$base" "cannot unpack"; continue; }
- check_dir "wheel $base" "$x" "$a" ;;
+ check_wheel "wheel $base" "$x" "$a" ;;
*.deb)
mkdir -p "$x"
if command -v dpkg-deb >/dev/null 2>&1; then dpkg-deb -x "$f" "$x" 2>/dev/null
diff --git a/.github/scripts/tests/test_cua_sdk_release_repository.py b/.github/scripts/tests/test_cua_sdk_release_repository.py
index 0b476bd84a..854164159a 100644
--- a/.github/scripts/tests/test_cua_sdk_release_repository.py
+++ b/.github/scripts/tests/test_cua_sdk_release_repository.py
@@ -214,7 +214,8 @@ def test_sdk_registries_publish_only_from_trycua_cua() -> None:
wf = workflow("cd-cua-sdk.yml")
assert wf["env"]["CANONICAL"] == "${{ github.repository == 'trycua/cua' }}"
pypi = step("cd-cua-sdk.yml", "publish", "Publish wheels to PyPI")["run"]
- upload = pypi.index("twine upload --skip-existing dist/wheel-*/*.whl")
+ # The first upload is PyPI (cua-cli wheels before cua, see the wheel list).
+ upload = pypi.index("twine upload --skip-existing")
assert pypi.rindex('if [ "$CANONICAL" = true ]; then', 0, upload) >= 0
assert "test.pypi.org" in pypi
npm = step("cd-cua-sdk.yml", "publish", "Publish npm packages")["run"]
diff --git a/.github/workflows/cd-cua-sdk.yml b/.github/workflows/cd-cua-sdk.yml
index 731c479c1c..7d598287c3 100644
--- a/.github/workflows/cd-cua-sdk.yml
+++ b/.github/workflows/cd-cua-sdk.yml
@@ -380,7 +380,10 @@ jobs:
working-directory: libs/cua/python
run: |
VERSION="${{ needs.version.outputs.version }}"
+ # The `cua-cli` wheel (cli/) takes the same version; build_wheel.py
+ # makes the `cua` wheel require it at that version.
sed -i.bak "s/^version = .*/version = \"$VERSION\"/" pyproject.toml && rm pyproject.toml.bak
+ sed -i.bak "s/^version = .*/version = \"$VERSION\"/" cli/pyproject.toml && rm cli/pyproject.toml.bak
sed -i.bak "s/^__version__ = .*/__version__ = \"$VERSION\"/" src/cua/__init__.py && rm src/cua/__init__.py.bak
python -m pip install --upgrade pip build hatchling
DIR="../../../native/native-${{ matrix.native }}"
@@ -391,15 +394,56 @@ jobs:
A=x86_64; [ "${{ matrix.arch }}" = arm64 ] && A=aarch64
SPACESD=(--spacesd "$DIR/cua-spacesd-linux-$A")
fi
+ # Two wheels: `cua` (the SDK library, plus the static cua-spacesd
+ # on Linux) and its dependency `cua-cli` (the `cua` binary).
python build_wheel.py --library "$DIR/${{ matrix.lib }}" --cli "$DIR/$EXE" "${SPACESD[@]}" --platform ${{ matrix.platform }} --arch ${{ matrix.arch }}
- - name: Check the wheel ships the static cua-spacesd next to cua
+ # PyPI rejects a file over 100 MB (HTTP 400) only at upload, after the
+ # whole build: fail here, with margin, instead.
+ - name: Check every wheel is under 95 MB
+ run: |
+ limit=$((95 * 1024 * 1024)); n=0
+ for whl in libs/cua/python/dist/*.whl; do
+ n=$((n + 1))
+ size=$(wc -c < "$whl" | tr -d ' ')
+ echo "$(basename "$whl"): $size bytes"
+ if [ "$size" -gt "$limit" ]; then
+ echo "::error::$(basename "$whl") is $size bytes, over the 95 MB guard (PyPI's per-file limit is 100 MB)"
+ exit 1
+ fi
+ done
+ test "$n" = 2
+ - name: Check the cua wheel requires its cua-cli and the source does not
+ working-directory: libs/cua/python
+ run: |
+ VERSION="${{ needs.version.outputs.version }}"
+ python - "$VERSION" dist/cua-[0-9]*.whl <<'PY'
+ import sys, zipfile
+ version, whl = sys.argv[1], sys.argv[2]
+ z = zipfile.ZipFile(whl)
+ meta = z.read(next(n for n in z.namelist() if n.endswith(".dist-info/METADATA"))).decode()
+ pins = [l for l in meta.splitlines() if l.startswith("Requires-Dist: cua-cli")]
+ assert pins == [f"Requires-Dist: cua-cli=={version}"], pins
+ import tomllib
+ project = tomllib.load(open("pyproject.toml", "rb"))["project"]
+ deps = project["dependencies"] + sum(project.get("optional-dependencies", {}).values(), [])
+ assert not [d for d in deps if d.startswith("cua-cli")], "the source pyproject must not pin cua-cli"
+ print(pins[0])
+ PY
+ - name: Check the wheel ships the static cua-spacesd in cua/bin/
if: matrix.platform == 'linux'
run: .github/scripts/check_static_spacesd_packaged.sh libs/cua/python/dist
- name: Import the wheel
working-directory: libs/cua/python
run: |
- python -m pip install --force-reinstall dist/*.whl
VERSION="${{ needs.version.outputs.version }}"
+ # The SDK alone (--no-deps): the `cua` command says how to get the CLI.
+ python -m venv "$RUNNER_TEMP/sdk-only"
+ py="$RUNNER_TEMP/sdk-only/bin/python"; [ -x "$py" ] || py="$RUNNER_TEMP/sdk-only/Scripts/python.exe"
+ "$py" -m pip install --no-deps dist/cua-[0-9]*.whl
+ set +e; hint="$(cd / && "$py" -c "import cua._cli, sys; sys.exit(cua._cli.main())" 2>&1)"; code=$?; set -e
+ echo "$hint"
+ test "$code" = 127 && grep -qF "pip install \"cua-cli==$VERSION\"" <<<"$hint"
+ python -m pip install --force-reinstall dist/*.whl
cd / && python -c "import cua, sys; v = cua.cua_sdk_version(); print(v); cua.embedded(); sys.exit(v != sys.argv[1])" "$VERSION"
test "$(cua --version | tr -d '\r')" = "cua $VERSION"
- uses: actions/upload-artifact@v4
@@ -563,13 +607,17 @@ jobs:
run: |
python -m pip install --upgrade twine
python -m twine check --strict dist/wheel-*/*.whl
+ # cua-cli first: `cua` depends on it at the same version, so `cua`
+ # never resolves before its CLI is on the index.
+ wheels=(dist/wheel-*/cua_cli-*.whl dist/wheel-*/cua-[0-9]*.whl)
+ all=(dist/wheel-*/*.whl); test "${#wheels[@]}" = "${#all[@]}"
if [ "$CANONICAL" = true ] && [ "$PYPI" = false ]; then
echo "::notice::pypi=false: wheels checked, not uploaded to PyPI"
elif [ "$CANONICAL" = true ]; then
- python -m twine upload --skip-existing dist/wheel-*/*.whl
+ python -m twine upload --skip-existing "${wheels[@]}"
elif [ -n "$TEST_PYPI_TOKEN" ]; then
TWINE_PASSWORD="$TEST_PYPI_TOKEN" python -m twine upload --skip-existing \
- --repository-url https://test.pypi.org/legacy/ dist/wheel-*/*.whl
+ --repository-url https://test.pypi.org/legacy/ "${wheels[@]}"
else
echo "::notice::$GITHUB_REPOSITORY is not trycua/cua: wheels checked, not uploaded to PyPI (DRY RUN)"
fi
diff --git a/.github/workflows/ci-cua-sdk.yml b/.github/workflows/ci-cua-sdk.yml
index a1f4ba1e8e..fd500d9408 100644
--- a/.github/workflows/ci-cua-sdk.yml
+++ b/.github/workflows/ci-cua-sdk.yml
@@ -523,17 +523,18 @@ jobs:
- name: Smoke-test the installed wheel
working-directory: libs/cua/python
run: |
- WHEEL=$(ls dist/*.whl)
- uv run --no-project --isolated --python 3.12 --with pytest --with "$WHEEL" pytest -q -p no:cacheprovider tests
+ # `cua` and the `cua-cli` it requires: the tests drive the CLI too.
+ WHEEL=$(ls dist/cua-[0-9]*.whl); CLI_WHEEL=$(ls dist/cua_cli-*.whl)
+ uv run --no-project --isolated --python 3.12 --with pytest --with "$WHEEL" --with "$CLI_WHEEL" pytest -q -p no:cacheprovider tests
# cua-e2b (the e2b-compatible module) through this wheel against the
# fixture's cua-spacesd, compared with the e2b 2.42 behaviour golden.
- name: cua-e2b conformance against cua-spacesd
if: runner.os == 'Linux'
working-directory: libs/python/cua-e2b
run: |
- WHEEL=$(ls ../../cua/python/dist/*.whl)
+ WHEEL=$(ls ../../cua/python/dist/cua-[0-9]*.whl); CLI_WHEEL=$(ls ../../cua/python/dist/cua_cli-*.whl)
uv run --no-project --isolated --python 3.12 --with pytest --with pytest-asyncio \
- --with "$WHEEL" --with-editable . pytest -q -p no:cacheprovider tests/test_conformance.py
+ --with "$WHEEL" --with "$CLI_WHEEL" --with-editable . pytest -q -p no:cacheprovider tests/test_conformance.py
node:
if: ${{ !cancelled() && !startsWith(github.head_ref, 'release-please--branches--')
diff --git a/.github/workflows/e2b-conformance.yml b/.github/workflows/e2b-conformance.yml
index 27b9decef3..57175ebf1f 100644
--- a/.github/workflows/e2b-conformance.yml
+++ b/.github/workflows/e2b-conformance.yml
@@ -176,8 +176,8 @@ jobs:
working-directory: libs/python/cua-e2b/tests
run: |
export CUA_HOME="$RUNNER_TEMP/cua-home" CUA_E2B_ON=local CONFORMANCE_SCHEME=http
- WHEEL=$(ls ../../../cua/python/dist/*.whl)
- uv run --no-project --isolated --python 3.12 --with "$WHEEL" --with-editable .. \
+ WHEEL=$(ls ../../../cua/python/dist/cua-[0-9]*.whl); CLI_WHEEL=$(ls ../../../cua/python/dist/cua_cli-*.whl)
+ uv run --no-project --isolated --python 3.12 --with "$WHEEL" --with "$CLI_WHEEL" --with-editable .. \
python -m conformance.suite > "$RUNNER_TEMP/cua.json"
uv run --no-project --python 3.12 python - <<'EOF'
import json, os, sys
diff --git a/docs/content/docs/cua-sdk/reference/index.mdx b/docs/content/docs/cua-sdk/reference/index.mdx
index ddda31d24a..f7c71817aa 100644
--- a/docs/content/docs/cua-sdk/reference/index.mdx
+++ b/docs/content/docs/cua-sdk/reference/index.mdx
@@ -14,7 +14,7 @@ The Cua SDK in Python, TypeScript, Swift, Kotlin and Rust, all generated from th
| Language | Package | Import |
| --- | --- | --- |
-| Python | `pip install cua` (0.8.0; `cua[sandbox]` adds the [high-level API](/cua-sdk/reference/python)) | `import cua` |
+| Python | `pip install cua` (0.8.0; `cua[sandbox]` adds the [high-level API](/cua-sdk/reference/python); `--no-deps` skips the `cua` CLI) | `import cua` |
| TypeScript (Node) | `npm install @trycua/cua` (0.8.0) | `import { embedded } from '@trycua/cua'` |
| Browser | `@trycua/cua/browser` (a WebAssembly subset) | `import { Cua } from '@trycua/cua/browser'` |
| Swift | `Cua` (macOS 12+, iOS 15+; not yet released) | `import Cua` |
diff --git a/libs/cua/README.md b/libs/cua/README.md
index e5b4a32c36..2ce0738d7f 100644
--- a/libs/cua/README.md
+++ b/libs/cua/README.md
@@ -102,7 +102,7 @@ Docs: [Sandboxes](https://cua.ai/docs/cua-sdk).
| `cua-daemon` | The SDK runtime and its host: `cua.daemon.v1` on the socket and loopback, env passthrough (`/v1/sandboxes/<name>/env/...`, `/v1/spaces/<key>/env/...`), the ticketed webview media bridge, the Spaces MCP server at `/mcp` and `cua daemon mcp`. Feature `test-fixtures` adds loopback fixtures; the `cua-test-fixtures` binary lives in `libs/cua-spacesd/tests/spaces-e2e` (build it with `scripts/build-test-fixtures.sh`). |
| `cua-sdk` | The **only** `#[uniffi::export]` crate (UniFFI `=0.31.0`): `Cua.embedded` / `Cua.connect`, sandboxes, env (typed plus a proto3-JSON escape hatch over every `cua.env.v1` RPC), media sessions with `FrameSink`/`AudioSink`, local runtimes and images, Spaces, auth and agent setup; a wasm32 browser subset. |
| `cua-bindgen` | The pinned UniFFI CLI used by `scripts/generate-uniffi-bindings.mjs`. |
-| `cua-cli` | The `cua` binary (shipped in the `cua` wheel, `@trycua/cua`, the install scripts and the Spaces app): `auth`, `agents`, `sandbox`, `config`, `do`, `mcp`, `skills`, `trajectory`, `image`, `env`, `daemon`, `runtime`, `host`, `spaces`, `teleport`. Reference: [docs.cua.ai/reference/cua-cli](https://cua.ai/docs/cua-cli/reference/cli). |
+| `cua-cli` | The `cua` binary (shipped in the `cua-cli` wheel, a dependency of the `cua` wheel, `@trycua/cua`, the install scripts and the Spaces app): `auth`, `agents`, `sandbox`, `config`, `do`, `mcp`, `skills`, `trajectory`, `image`, `env`, `daemon`, `runtime`, `host`, `spaces`, `teleport`. Reference: [docs.cua.ai/reference/cua-cli](https://cua.ai/docs/cua-cli/reference/cli). |
Language packages generated from `cua-sdk` (drift-checked by
`scripts/generate-uniffi-bindings.mjs --check`):
diff --git a/libs/cua/crates/cua-vmm/src/inject.rs b/libs/cua/crates/cua-vmm/src/inject.rs
index 2adb8748ae..168065bd89 100644
--- a/libs/cua/crates/cua-vmm/src/inject.rs
+++ b/libs/cua/crates/cua-vmm/src/inject.rs
@@ -99,8 +99,9 @@ pub fn find_binary(arch: Arch) -> Option<PathBuf> {
/// its `bin/`: when Node or Python loads the SDK library in-process the
/// executable is `node` or `python`, and the binary ships with the
/// library instead. The npm native package keeps it beside the library
-/// and `cua`; the wheel keeps the library at `cua/` and the binary next
-/// to `cua/bin/cua`;
+/// and `cua`; the wheel keeps the library at `cua/` and the binary in
+/// `cua/bin/` (the `cua` console command hands it to the CLI from the
+/// `cua-cli` wheel as `$CUA_SPACESD_STATIC`);
/// 3. `$CUA_HOME/bin` (`~/.cua/bin`).
pub fn search_paths(
name: &str,
diff --git a/libs/cua/python/README.md b/libs/cua/python/README.md
index f04fb67331..7bb804bcf6 100644
--- a/libs/cua/python/README.md
+++ b/libs/cua/python/README.md
@@ -40,7 +40,8 @@ info = sb.info() # id, phase, location, services, expires_at_unix, provider_det
```
`public_url` is a signed URL in the cloud and a loopback URL with its own token
-locally, served by the `cua daemon` (started on demand with the bundled CLI).
+locally, served by the `cua daemon` (started on demand with the `cua` CLI, which
+`pip install cua` installs through its `cua-cli` dependency).
`await sb.mcp("mcp", None)` is an MCP client for a server the sandbox serves
and `await sb.mcp_config("mcp", None)` its URL and headers for any MCP client;
neither needs cua-spacesd. `cua.canonical_image("linux", None)` returns
@@ -57,6 +58,7 @@ resolve lazily from optional extras:
pip install "cua[sandbox]" # cua-sandbox: Sandbox, Image, QEMURuntime, ...
pip install "cua[agent]" # cua-agent: ComputerAgent, cua.callbacks, cua.tools
pip install "cua[all]" # both (the `cua` command is the Rust CLI in libs/cua)
+pip install --no-deps cua # the SDK alone, without the `cua` command (`cua-cli`)
```
```python
@@ -72,7 +74,12 @@ returns) is always `cua.SandboxHandle`.
- `cua._native` is generated by `libs/cua/scripts/generate-uniffi-bindings.mjs`
and must not be edited; `--check` fails CI when it drifts.
- Wheels are platform wheels (`build_wheel.py`), one per OS/arch, each with
- the `libcua_sdk` library next to `_native.py`.
+ the `libcua_sdk` library next to `_native.py` (and, on Linux, the static
+ cua-spacesd in `cua/bin/`). The `cua` CLI is a second platform wheel,
+ `cua-cli` (`cli/`), a dependency of `cua` that installs
+ `cua_cli/bin/cua[.exe]`; the `cua` command runs it with
+ `CUA_SPACESD_STATIC` set to that cua-spacesd. PyPI caps each file at
+ 100 MB and the two together are over it.
## Development
diff --git a/libs/cua/python/build_wheel.py b/libs/cua/python/build_wheel.py
index 9b9b5f7a01..c2c95e4d67 100644
--- a/libs/cua/python/build_wheel.py
+++ b/libs/cua/python/build_wheel.py
@@ -1,16 +1,25 @@
#!/usr/bin/env python3
-"""Build a platform wheel of the `cua` package around a built cua-sdk cdylib
-and the `cua` CLI binary.
+"""Build the platform wheels of the `cua` package (around a built cua-sdk
+cdylib) and of `cua-cli` (the `cua` CLI binary).
The native library comes from `--library` (a CI artifact or a local
`cargo build --release -p cua-sdk`) and the CLI from `--cli` (`cargo build
--release -p cua-cli`); by default the host builds under
-libs/cua/target/release are used. The CLI is installed as the `cua` console
-command. Linux wheels also carry the static cua-spacesd (`--spacesd`, the
-`cua-spacesd-linux-<arch>` that .github/scripts/fetch_static_spacesd.sh
-fetches) next to it in `cua/bin/`, where `cua` and the in-process SDK find
-it to inject into images that lack one. The wheel is tagged for the library's platform, the same way
-libs/cua-driver/python/build_wheel.py does it.
+libs/cua/target/release are used.
+
+- `cua`: the library next to `_native.py`. Linux wheels also carry the
+ static cua-spacesd (`--spacesd`, the `cua-spacesd-linux-<arch>` that
+ .github/scripts/fetch_static_spacesd.sh fetches) in `cua/bin/`, where the
+ in-process SDK finds it to inject into images that lack one.
+- `cua-cli` (cli/): `cua_cli/bin/cua[.exe]`, which the `cua` wheel requires
+ at its own version (added at build time; a source install has no pin) and
+ whose `cua` console command runs it, pointing it at that cua-spacesd
+ (`$CUA_SPACESD_STATIC`). `--no-cli` skips it.
+
+The CLI and the library are separate wheels because each repeats most of
+the Rust code and PyPI caps a file at 100 MB. Both are tagged for the
+library's platform, the same way libs/cua-driver/python/build_wheel.py does
+it.
Usage:
python build_wheel.py [--library PATH] [--cli PATH|--no-cli]
@@ -31,6 +40,9 @@ from pathlib import Path
HERE = Path(__file__).resolve().parent
PACKAGE = HERE / "src" / "cua"
+# The cua-cli project; its staged binary lands at cua_cli/bin/ in the wheel.
+CLI_PROJECT = HERE / "cli"
+CLI_BIN = CLI_PROJECT / "src" / "cua_cli" / "bin"
LIB_NAMES = {
"darwin": "libcua_sdk.dylib",
"linux": "libcua_sdk.so",
@@ -68,11 +80,11 @@ def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--library", type=Path)
parser.add_argument("--cli", type=Path, help="the built `cua` CLI binary")
- parser.add_argument("--no-cli", action="store_true", help="build without the CLI binary")
+ parser.add_argument("--no-cli", action="store_true", help="skip the cua-cli wheel")
parser.add_argument(
"--spacesd",
type=Path,
- help="the static cua-spacesd-linux-<arch> (required for Linux wheels with the CLI)",
+ help="the static cua-spacesd-linux-<arch> (required for Linux wheels)",
)
parser.add_argument(
"--no-spacesd",
@@ -98,6 +110,19 @@ def main() -> None:
bin_dir = PACKAGE / "bin"
shutil.rmtree(bin_dir, ignore_errors=True)
+ if system == "linux" and not args.no_spacesd:
+ name = f"cua-spacesd-linux-{'aarch64' if arch == 'arm64' else 'x86_64'}"
+ if args.spacesd is None:
+ raise SystemExit(f"a Linux wheel needs --spacesd PATH (the static {name})")
+ if not args.spacesd.is_file():
+ raise SystemExit(f"missing static cua-spacesd {args.spacesd}")
+ bin_dir.mkdir()
+ shutil.copy2(args.spacesd, bin_dir / name)
+ (bin_dir / name).chmod(0o755)
+ elif args.spacesd is not None:
+ raise SystemExit("--spacesd is for Linux wheels")
+
+ shutil.rmtree(CLI_BIN, ignore_errors=True)
if not args.no_cli:
exe = "cua.exe" if system == "windows" else "cua"
cli = args.cli or (HERE.parent / "target" / "release" / exe)
@@ -109,33 +134,29 @@ def main() -> None:
raise SystemExit(
f"missing CLI binary {cli}; run cargo build --release -p cua-cli or pass --no-cli"
)
- bin_dir.mkdir()
- shutil.copy2(cli, bin_dir / exe)
- (bin_dir / exe).chmod(0o755)
- if system == "linux" and not args.no_cli and not args.no_spacesd:
- name = f"cua-spacesd-linux-{'aarch64' if arch == 'arm64' else 'x86_64'}"
- if args.spacesd is None:
- raise SystemExit(f"a Linux wheel needs --spacesd PATH (the static {name})")
- if not args.spacesd.is_file():
- raise SystemExit(f"missing static cua-spacesd {args.spacesd}")
- shutil.copy2(args.spacesd, bin_dir / name)
- (bin_dir / name).chmod(0o755)
- elif args.spacesd is not None:
- raise SystemExit("--spacesd is for Linux wheels with the CLI")
+ CLI_BIN.mkdir(parents=True)
+ shutil.copy2(cli, CLI_BIN / exe)
+ (CLI_BIN / exe).chmod(0o755)
env = dict(os.environ, CUA_SDK_WHEEL_TAG=wheel_tag(system, arch))
+ # The `cua` wheel requires the `cua-cli` wheel built with it, at the same
+ # version (hatch_build.py adds the pin; the source pyproject has none).
+ env["CUA_SDK_WHEEL_REQUIRES_CLI"] = "0" if args.no_cli else "1"
args.out_dir.mkdir(parents=True, exist_ok=True)
try:
import build # noqa: F401
- cmd = [sys.executable, "-m", "build", "--wheel", "--outdir", str(args.out_dir)]
+ cmd = [sys.executable, "-m", "build", "--wheel", "--outdir", str(args.out_dir.resolve())]
except ImportError:
uv = shutil.which("uv")
if not uv:
raise SystemExit("need `build` (pip install build) or `uv`")
- cmd = [uv, "build", "--wheel", "--out-dir", str(args.out_dir)]
+ cmd = [uv, "build", "--wheel", "--out-dir", str(args.out_dir.resolve())]
subprocess.run(cmd, cwd=HERE, env=env, check=True)
- print(f"built {wheel_tag(system, arch)} wheel into {args.out_dir}")
+ print(f"built the {wheel_tag(system, arch)} cua wheel into {args.out_dir}")
+ if not args.no_cli:
+ subprocess.run(cmd, cwd=CLI_PROJECT, env=env, check=True)
+ print(f"built the {wheel_tag(system, arch)} cua-cli wheel into {args.out_dir}")
if __name__ == "__main__":
diff --git a/libs/cua/python/cli/.gitignore b/libs/cua/python/cli/.gitignore
new file mode 100644
index 0000000000..48406ed476
--- /dev/null
+++ b/libs/cua/python/cli/.gitignore
@@ -0,0 +1,2 @@
+src/cua_cli/bin/
+dist/
diff --git a/libs/cua/python/cli/README.md b/libs/cua/python/cli/README.md
new file mode 100644
index 0000000000..c3bf267457
--- /dev/null
+++ b/libs/cua/python/cli/README.md
@@ -0,0 +1,19 @@
+# cua-cli
+
+The `cua` command line for the [`cua`](https://pypi.org/project/cua/) Python
+package: the Rust `cua` CLI (sandboxes, Spaces, the cua daemon, MCP, images)
+as a platform wheel.
+
+```bash
+pip install cua # depends on cua-cli
+cua --version
+```
+
+`cua` depends on this package at the same version. It installs the `cua`
+binary as `cua_cli/bin/cua`, where the `cua` console command (and so the SDK,
+which starts the cua daemon through it) runs it. The CLI
+also installs standalone, without Python:
+
+```bash
+curl -fsSL https://cua.ai/install.sh | sh
+```
diff --git a/libs/cua/python/cli/pyproject.toml b/libs/cua/python/cli/pyproject.toml
new file mode 100644
index 0000000000..e2fee5f37a
--- /dev/null
+++ b/libs/cua/python/cli/pyproject.toml
@@ -0,0 +1,40 @@
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+# The Rust `cua` CLI as its own platform wheel, a dependency of `cua`. It
+# installs `cua_cli/bin/cua[.exe]`; the `cua` console command (cua._cli)
+# runs it. Its own package, not cua/bin/: upgrading from a `cua` that
+# shipped cua/bin/cua would otherwise delete the new binary when pip
+# removes the old `cua`. No dependency back on `cua`: it is only installed
+# through it. Built by ../build_wheel.py.
+[project]
+name = "cua-cli"
+version = "0.8.0"
+description = "The cua command line (the Rust `cua` CLI) for the cua Python package"
+readme = "README.md"
+license = { text = "MIT" }
+authors = [{ name = "TryCua", email = "[email protected]" }]
+classifiers = [
+ "Development Status :: 3 - Alpha",
+ "Environment :: Console",
+ "License :: OSI Approved :: MIT License",
+ "Operating System :: MacOS",
+ "Operating System :: Microsoft :: Windows",
+ "Operating System :: POSIX :: Linux",
+]
+requires-python = ">=3.10"
+dependencies = []
+
+[project.urls]
+Homepage = "https://github.com/trycua/cua"
+Repository = "https://github.com/trycua/cua"
+Issues = "https://github.com/trycua/cua/issues"
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/cua_cli"]
+artifacts = ["src/cua_cli/bin/*"]
+pure-python = false
+
+[tool.hatch.build.targets.wheel.hooks.custom]
+path = "../hatch_build.py"
diff --git a/libs/cua/python/cli/src/cua_cli/__init__.py b/libs/cua/python/cli/src/cua_cli/__init__.py
new file mode 100644
index 0000000000..b608dabdbf
--- /dev/null
+++ b/libs/cua/python/cli/src/cua_cli/__init__.py
@@ -0,0 +1,12 @@
+"""The Rust `cua` CLI for the `cua` Python package (run through its `cua`
+console command)."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+
+def binary() -> Path:
+ """Path of the bundled `cua` executable."""
+ return Path(__file__).resolve().parent / "bin" / ("cua.exe" if os.name == "nt" else "cua")
diff --git a/libs/cua/python/hatch_build.py b/libs/cua/python/hatch_build.py
index 212138c2fe..c6bc9aeda3 100644
--- a/libs/cua/python/hatch_build.py
+++ b/libs/cua/python/hatch_build.py
@@ -4,9 +4,13 @@ import os
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
+# Set by build_wheel.py when it also builds the `cua-cli` wheel.
+REQUIRE_CLI_ENV = "CUA_SDK_WHEEL_REQUIRES_CLI"
+
class CustomBuildHook(BuildHookInterface):
- """Apply the wheel tag selected by build_wheel.py."""
+ """Apply the wheel tag selected by build_wheel.py, and make the `cua`
+ wheel it builds require the `cua-cli` wheel of the same version."""
def initialize(self, version: str, build_data: dict) -> None:
wheel_tag = os.environ.get("CUA_SDK_WHEEL_TAG")
@@ -14,3 +18,7 @@ class CustomBuildHook(BuildHookInterface):
return
build_data["tag"] = wheel_tag
build_data["pure_python"] = False
+ if self.metadata.name == "cua" and os.environ.get(REQUIRE_CLI_ENV) == "1":
+ build_data.setdefault("dependencies", []).append(
+ f"cua-cli=={self.metadata.version}"
+ )
diff --git a/libs/cua/python/pyproject.toml b/libs/cua/python/pyproject.toml
index 62f4ca9bc5..a9b11f1cd0 100644
--- a/libs/cua/python/pyproject.toml
+++ b/libs/cua/python/pyproject.toml
@@ -25,6 +25,12 @@ classifiers = [
"Topic :: Software Development :: Libraries :: Python Modules",
]
requires-python = ">=3.10"
+# The released wheel also requires `cua-cli==<its version>`: the Rust `cua`
+# CLI as its own platform wheel (cli/), since PyPI caps a file at 100 MB and
+# the CLI and the library together are over it. build_wheel.py adds that
+# pin (hatch_build.py), so a source or editable install of this directory
+# needs nothing that is not on an index. `pip install --no-deps cua` is the
+# SDK alone.
dependencies = []
[project.optional-dependencies]
@@ -45,7 +51,8 @@ Repository = "https://github.com/trycua/cua"
Issues = "https://github.com/trycua/cua/issues"
[project.scripts]
-# The Rust `cua` CLI, bundled as src/cua/bin/cua[.exe] by build_wheel.py.
+# Runs the Rust `cua` CLI at cua_cli/bin/cua[.exe], which the `cua-cli`
+# wheel installs; without it (`--no-deps`), prints how to install it.
cua = "cua._cli:main"
[tool.hatch.build.targets.wheel]
diff --git a/libs/cua/python/src/cua/_cli.py b/libs/cua/python/src/cua/_cli.py
index 330424ec8b..b554023762 100644
--- a/libs/cua/python/src/cua/_cli.py
+++ b/libs/cua/python/src/cua/_cli.py
@@ -1,28 +1,56 @@
-"""The `cua` console command: runs the Rust CLI bundled in this wheel."""
+"""The `cua` console command: runs the Rust CLI that the `cua-cli` wheel (a
+dependency of `cua`) installs at cua_cli/bin/cua[.exe]."""
from __future__ import annotations
import os
import subprocess
import sys
+from importlib import metadata
from pathlib import Path
+# The static cua-spacesd the Linux `cua` wheel ships (cua/bin/, where the
+# in-process SDK finds it); the CLI lives in another package, so it is told.
+SPACESD_ENV = "CUA_SPACESD_STATIC"
-def binary() -> Path:
- """Path of the bundled `cua` executable."""
- name = "cua.exe" if os.name == "nt" else "cua"
- return Path(__file__).resolve().parent / "bin" / name
+
+def binary() -> Path | None:
+ """Path of the `cua` executable the `cua-cli` wheel installs, if any."""
+ try:
+ import cua_cli
+ except ImportError:
+ return None
+ exe = cua_cli.binary()
+ return exe if exe.is_file() else None
+
+
+def spacesd() -> Path | None:
+ """The static cua-spacesd in this wheel (Linux), if any."""
+ for p in sorted((Path(__file__).resolve().parent / "bin").glob("cua-spacesd-linux-*")):
+ if p.is_file():
+ return p
+ return None
+
+
+def install_hint() -> str:
+ try:
+ pin = f"cua-cli=={metadata.version('cua')}"
+ except metadata.PackageNotFoundError:
+ pin = "cua-cli"
+ return (
+ "cua: the cua CLI is not installed (the cua-cli package). "
+ f'Install it with `pip install "{pin}"`.\n'
+ )
def main() -> int:
exe = binary()
- if not exe.exists():
- sys.stderr.write(
- f"cua: the CLI binary is missing from this installation ({exe}).\n"
- "Reinstall a platform wheel of `cua`, or build it with "
- "`cargo install --locked --path libs/cua/crates/cua-cli`.\n"
- )
+ if exe is None:
+ sys.stderr.write(install_hint())
return 127
+ sd = spacesd()
+ if sd is not None and not os.environ.get(SPACESD_ENV):
+ os.environ[SPACESD_ENV] = str(sd)
argv = [str(exe), *sys.argv[1:]]
if os.name == "nt":
return subprocess.call(argv)
diff --git a/libs/cua/python/tests/test_cli_entry.py b/libs/cua/python/tests/test_cli_entry.py
new file mode 100644
index 0000000000..421db0f52f
--- /dev/null
+++ b/libs/cua/python/tests/test_cli_entry.py
@@ -0,0 +1,79 @@
+"""The `cua` console command: runs the CLI from the `cua-cli` wheel, hands
+it the wheel's static cua-spacesd, and without the CLI (`--no-deps`) says
+how to install it."""
+
+from __future__ import annotations
+
+import os
+
+from cua import _cli
+
+
+def test_missing_cli_prints_how_to_install(monkeypatch, capsys) -> None:
+ monkeypatch.setattr(_cli, "binary", lambda: None)
+ assert _cli.main() == 127
+ err = capsys.readouterr().err
+ assert 'pip install "cua-cli' in err
+ assert err.count("\n") == 1
+
+
+def test_the_cli_comes_from_the_cua_cli_package() -> None:
+ exe = _cli.binary()
+ if exe is None: # an SDK-only install
+ return
+ assert exe.is_file() and exe.parent.name == "bin" and exe.parent.parent.name == "cua_cli"
+
+
+def test_the_cli_is_handed_the_wheel_spacesd(monkeypatch, tmp_path) -> None:
+ sd = tmp_path / "cua-spacesd-linux-x86_64"
+ sd.write_bytes(b"")
+ seen = {}
+ monkeypatch.setattr(_cli, "binary", lambda: tmp_path / "cua")
+ monkeypatch.setattr(_cli, "spacesd", lambda: sd)
+ monkeypatch.delenv(_cli.SPACESD_ENV, raising=False)
+
+ def fake_exec(path, argv):
+ seen["env"] = os.environ.get(_cli.SPACESD_ENV)
+ raise SystemExit(0)
+
+ monkeypatch.setattr(_cli.os, "execv", fake_exec)
+ monkeypatch.setattr(_cli.subprocess, "call", lambda argv: fake_exec(argv[0], argv))
+ try:
+ _cli.main()
+ except SystemExit:
+ pass
+ assert seen["env"] == str(sd)
+ # A value the user set wins.
+ monkeypatch.setenv(_cli.SPACESD_ENV, "/mine")
+ try:
+ _cli.main()
+ except SystemExit:
+ pass
+ assert seen["env"] == "/mine"
+
+
+def test_the_source_pyproject_pins_no_cua_cli() -> None:
+ # Source and editable installs of libs/cua/python must resolve without
+ # a cua-cli of the checkout's version on an index; build_wheel.py adds
+ # the pin to the built wheel only.
+ import tomllib
+ from pathlib import Path
+
+ pyproject = Path(__file__).resolve().parent.parent / "pyproject.toml"
+ project = tomllib.loads(pyproject.read_text())["project"]
+ deps = project.get("dependencies", []) + [
+ d for ds in project.get("optional-dependencies", {}).values() for d in ds
+ ]
+ assert not [d for d in deps if d.replace(" ", "").startswith("cua-cli")]
+
+
+def test_a_built_wheel_with_its_cli_requires_it_at_its_version() -> None:
+ from importlib import metadata
+
+ try:
+ metadata.version("cua-cli")
+ except metadata.PackageNotFoundError:
+ return # a source, editable or --no-deps install
+ requires = [r.replace(" ", "") for r in metadata.requires("cua") or []]
+ assert f"cua-cli=={metadata.version('cua')}" in requires
+ assert metadata.version("cua-cli") == metadata.version("cua")
diff --git a/release-please-config.json b/release-please-config.json
index 8f1b234512..2e83cc58f6 100644
--- a/release-please-config.json
+++ b/release-please-config.json
@@ -271,6 +271,11 @@
"path": "python/pyproject.toml",
"jsonpath": "$.project.version"
},
+ {
+ "type": "toml",
+ "path": "python/cli/pyproject.toml",
+ "jsonpath": "$.project.version"
+ },
{
"type": "generic",
"path": "python/src/cua/__init__.py"
diff --git a/scripts/docs-generators/headers/cua-sdk/index.md b/scripts/docs-generators/headers/cua-sdk/index.md
index 364a3acaec..36e6eba4dd 100644
--- a/scripts/docs-generators/headers/cua-sdk/index.md
+++ b/scripts/docs-generators/headers/cua-sdk/index.md
@@ -1,6 +1,6 @@
| Language | Package | Import |
| --- | --- | --- |
-| Python | `pip install cua` ({{version}}; `cua[sandbox]` adds the [high-level API](/cua-sdk/reference/python)) | `import cua` |
+| Python | `pip install cua` ({{version}}; `cua[sandbox]` adds the [high-level API](/cua-sdk/reference/python); `--no-deps` skips the `cua` CLI) | `import cua` |
| TypeScript (Node) | `npm install @trycua/cua` ({{version}}) | `import { embedded } from '@trycua/cua'` |
| Browser | `@trycua/cua/browser` (a WebAssembly subset) | `import { Cua } from '@trycua/cua/browser'` |
| Swift | `Cua` (macOS 12+, iOS 15+; not yet released) | `import Cua` |