Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
docs(fleets): restructure cloud and local paths (#3766)
Francesco Bonacciedf8dda03694
diff --git a/.github/workflows/ci-check-docs.yml b/.github/workflows/ci-check-docs.ymlindex 0c14b7c043..d323d95088 100644--- a/.github/workflows/ci-check-docs.yml+++ b/.github/workflows/ci-check-docs.yml@@ -7,8 +7,15 @@ on:- "libs/cua-driver/rust/Cargo.toml"- "libs/cua-driver/rust/Cargo.lock"- "libs/lume/src/**"+ - "libs/python/cua-sandbox/**"+ - "libs/python/cua/pyproject.toml"+ - "libs/python/computer-server/pyproject.toml"+ - "libs/typescript/fleet/package.json"+ - "libs/cua-driver/hyprland-plugin/packaging/release/profiles/omarchy-stable-20260910.json"- "docs/content/docs/reference/cua-driver/**"- "docs/content/docs/reference/lume/**"+ - "docs/content/docs/reference/sandbox-sdk/runtime-support.mdx"+ - "docs/content/docs/reference/sandbox-sdk/os-image-catalog.mdx"- "docs/package.json"- "docs/pnpm-lock.yaml"- "scripts/docs-generators/**"@@ -37,6 +44,9 @@ jobs:- library: lumeplatform: macosos: macos-latest+ - library: sandbox+ platform: linux+ os: ubuntu-latestruns-on: ${{ matrix.os }}defaults:run:@@ -55,7 +65,7 @@ jobs:- name: Test generator routing and ownershiprun: |node docs/node_modules/tsx/dist/cli.mjs scripts/docs-generators/runner.ts --test-routing- node docs/node_modules/tsx/dist/cli.mjs --test scripts/docs-generators/runner.test.ts scripts/docs-generators/cua-driver.test.ts scripts/docs-generators/cua-driver-platform.test.ts+ node docs/node_modules/tsx/dist/cli.mjs --test scripts/docs-generators/runner.test.ts scripts/docs-generators/cua-driver.test.ts scripts/docs-generators/cua-driver-platform.test.ts scripts/docs-generators/sandbox.test.ts- name: Select affected generatorid: scopeenv:@@ -68,7 +78,7 @@ jobs:echo "selected=true" >> "$GITHUB_OUTPUT"fi- name: Install Linux build dependencies- if: steps.scope.outputs.selected == 'true' && matrix.platform == 'linux'+ if: steps.scope.outputs.selected == 'true' && matrix.platform == 'linux' && matrix.library == 'cua-driver'run: |sudo apt-get updatesudo apt-get install -y --no-install-recommends \diff --git a/.github/workflows/docs-fleet-first-run-smoke.yml b/.github/workflows/docs-fleet-first-run-smoke.ymlindex 07407647fb..140c94b9d4 100644--- a/.github/workflows/docs-fleet-first-run-smoke.yml+++ b/.github/workflows/docs-fleet-first-run-smoke.yml@@ -4,7 +4,10 @@ on:pull_request:paths:- docs/content/docs/tutorials/your-first-cloud-fleet.mdx+ - docs/content/docs/how-to-guides/sandbox/recover-first-cloud-fleet.mdx+ - docs/public/scripts/first-cloud-fleet/**- docs/scripts/tests/test_first_cloud_fleet_tutorial.py+ - docs/scripts/tests/first_cloud_fleet_typescript_smoke.mjs- .github/workflows/docs-fleet-first-run-smoke.ymlmerge_group:workflow_dispatch:@@ -25,7 +28,40 @@ jobs:- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5with:python-version: "3.13"- - name: Install the tutorial's published SDK versions- run: python -m pip install "cua-sandbox==0.4.3" "cua-fleet==0.1.14"- - name: Test tutorial snippets with mocked Fleet calls+ - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4+ with:+ node-version: "22"+ - name: Install the published Python SDK+ run: |+ python -m pip install --upgrade pip+ python -m pip install \+ --extra-index-url https://wheels.cua.ai/simple \+ "cua-sandbox==0.7.0"+ - name: Test the Python example with mocked Fleet callsrun: python -m unittest discover -s docs/scripts/tests -p test_first_cloud_fleet_tutorial.py -v+ - name: Compile and test the TypeScript example with mocked Fleet calls+ shell: bash+ run: |+ repo_dir="$PWD"+ test_dir="$(mktemp -d)"+ cd "$test_dir"+ npm init -y+ npm pkg set type=module+ npm install \+ "@trycua/[email protected]" \+ "@types/node@22" \+ "[email protected]" \+ cp "$repo_dir/docs/public/scripts/first-cloud-fleet/first-cloud-fleet.ts.txt" \+ first-cloud-fleet.ts+ ./node_modules/.bin/tsc \+ --noEmit \+ --strict \+ --target ES2022 \+ --module NodeNext \+ --moduleResolution NodeNext \+ --types node \+ first-cloud-fleet.ts+ FIRST_CLOUD_FLEET_TS="$test_dir/first-cloud-fleet.ts" \+ node --import tsx --test \+ "$repo_dir/docs/scripts/tests/first_cloud_fleet_typescript_smoke.mjs"diff --git a/docs/content/docs/(cloud-fleets)/meta.json b/docs/content/docs/(cloud-fleets)/meta.jsonnew file mode 100644index 0000000000..3a35b28af3--- /dev/null+++ b/docs/content/docs/(cloud-fleets)/meta.json@@ -0,0 +1,42 @@+{+ "title": "Cua Fleets",+ "pages": [+ "---Overview---",+ "[Cua Fleets](/cloud-fleets)",+ "[Pools, claims, and guest services](/concepts/pools-claims-and-guest-services)",+ "---Set up---",+ "[Set up Fleet credentials](/how-to-guides/sandbox/set-up-fleet-credentials)",+ "[Choose a Fleet image](/how-to-guides/sandbox/choose-an-image)",+ "---Create and connect---",+ "[Create Fleet capacity](/how-to-guides/sandbox/create-fleet-capacity)",+ "[Claim a Sandbox](/how-to-guides/sandbox/claim-a-sandbox)",+ "[Configure a pool with Terraform](/how-to-guides/sandbox/configure-pool-with-terraform)",+ "---Use the computer---",+ "[Control the desktop with Cua Driver](/how-to-guides/sandbox/control-the-desktop-with-cua-driver)",+ "[Connect to guest services and tunnels](/how-to-guides/sandbox/tunneling)",+ "[Share a guest service with a signed URL](/how-to-guides/sandbox/share-service-with-signed-url)",+ "[Pass secrets safely](/how-to-guides/sandbox/secrets)",+ "---Operate---",+ "[Expire claims and pools](/how-to-guides/sandbox/expire-pools-and-claims)",+ "[Recover an interrupted run](/how-to-guides/sandbox/recover-first-cloud-fleet)",+ "[Troubleshoot Fleet pools](/how-to-guides/sandbox/troubleshoot-fleet-pools)",+ "---Use Fleets with---",+ "[OpenAI Agents](/how-to-guides/sandbox/run-openai-agents-api-on-cloud-fleet)",+ "[Cursor](/how-to-guides/sandbox/run-cursor-cloud-agent-on-fleet)",+ "[OpenClaw](/how-to-guides/sandbox/run-openclaw-on-cloud-fleet)",+ "[Omarchy](/how-to-guides/sandbox/run-omarchy-on-cloud-fleet)",+ "[Omarchy with noVNC](/how-to-guides/sandbox/connect-to-omarchy-with-novnc)",+ "[Minecraft](/how-to-guides/sandbox/minecraft)",+ "---Images---",+ "[Choose a published image](/how-to-guides/sandbox/choose-an-image)",+ "[How Fleet images work](/concepts/how-fleet-images-work)",+ "[Publish a Fleet image](/how-to-guides/sandbox/prepare-and-reference-a-fleet-image)",+ "[Fleet image catalog](/reference/sandbox-sdk/os-image-catalog)",+ "---Reference---",+ "[Python Sandbox APIs for Fleets](/reference/sandbox-sdk)",+ "[Fleet SDK for TypeScript](/reference/sandbox-sdk/typescript)",+ "[Pools, claims, and services](/reference/sandbox-sdk/pool)",+ "[Fleet image support](/reference/sandbox-sdk/runtime-support)",+ "[Image catalog](/reference/sandbox-sdk/os-image-catalog)"+ ]+}diff --git a/docs/content/docs/(local-sandboxes)/meta.json b/docs/content/docs/(local-sandboxes)/meta.jsonnew file mode 100644index 0000000000..b252e81346--- /dev/null+++ b/docs/content/docs/(local-sandboxes)/meta.json@@ -0,0 +1,19 @@+{+ "title": "Local Sandboxes",+ "pages": [+ "---Overview---",+ "[Local Sandboxes](/local-sandboxes)",+ "[Choose a local runtime](/reference/sandbox-sdk/runtime-support)",+ "---Create and use---",+ "[Create and manage a local Sandbox](/how-to-guides/sandbox/manage-local-lifecycle)",+ "[Open a local interactive shell](/how-to-guides/sandbox/interactive-shell)",+ "[Run local Sandboxes in parallel](/how-to-guides/sandbox/scale-out)",+ "---Images---",+ "[Build a local image](/how-to-guides/sandbox/images)",+ "[Local image and runtime support](/reference/sandbox-sdk/runtime-support)",+ "---Reference---",+ "[Sandbox SDK for Python](/reference/sandbox-sdk)",+ "[Local runtime support](/reference/sandbox-sdk/runtime-support)",+ "[Image API](/reference/sandbox-sdk/image)"+ ]+}diff --git a/docs/content/docs/cloud-fleets.mdx b/docs/content/docs/cloud-fleets.mdxindex a918228ed0..715f746ed3 100644--- a/docs/content/docs/cloud-fleets.mdx+++ b/docs/content/docs/cloud-fleets.mdx@@ -1,39 +1,40 @@----title: Cloud Fleets-description: Find tutorials, guides, explanations, and reference for managed cloud sandboxes.+title: Cua Fleets+description: Create, claim, connect to, and operate managed cloud computers.----Cloud Fleets provisions and manages sandbox capacity for your workloads. The-Sandbox SDK represents a Fleet as a `Pool`; your code claims a sandbox from the-pool and uses that guest computer.+The Cua Sandbox SDK represents one isolated computer. It can run locally or on+Cua Fleet capacity. Cua Fleets adds hosted pools, claims, authentication, and+service routing so workloads can reserve and use managed cloud computers.Start with [Your first Cloud Fleet](/tutorials/your-first-cloud-fleet) to provision-a pool, run a command, save a screenshot, and clean up the cloud resources.+a pool, transform a file, verify the result, and clean up the cloud resources.## Find the right pageChoose a page based on what you want to do:-| Your goal | Start here |-| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Learn through a first working example | [Your first Cloud Fleet](/tutorials/your-first-cloud-fleet) |-| Create reusable capacity | [Create a sandbox pool with Python](/how-to-guides/sandbox/create-pool-with-python) or [Configure a sandbox pool with Terraform](/how-to-guides/sandbox/configure-pool-with-terraform) |-| Control resource lifetime | [Expire pools and claims automatically](/how-to-guides/sandbox/expire-pools-and-claims) |-| Prepare a guest environment | [Prepare and reference a Fleet image](/how-to-guides/sandbox/prepare-and-reference-a-fleet-image) |-| Understand the model | [How sandboxes work](/concepts/how-sandboxes-work) and [How Fleet images work](/concepts/how-fleet-images-work) |-| Look up APIs and limits | [Sandbox SDK reference](/reference/sandbox-sdk), [Pool reference](/reference/sandbox-sdk/pool), and [Sandbox runtime support](/reference/sandbox-sdk/runtime-support) |+| Your goal | Start here |+| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| Learn through a first working example | [Your first Cloud Fleet](/tutorials/your-first-cloud-fleet) |+| Create reusable capacity | [Create Fleet capacity](/how-to-guides/sandbox/create-fleet-capacity) or [Configure a sandbox pool with Terraform](/how-to-guides/sandbox/configure-pool-with-terraform) |+| Control resource lifetime | [Expire pools and claims automatically](/how-to-guides/sandbox/expire-pools-and-claims) |+| Prepare a guest environment | [Prepare and reference a Fleet image](/how-to-guides/sandbox/prepare-and-reference-a-fleet-image) |+| Understand the model | [Pools, claims, and guest services](/concepts/pools-claims-and-guest-services) and [How Fleet images work](/concepts/how-fleet-images-work) |+| Look up APIs and limits | [Sandbox SDK reference](/reference/sandbox-sdk), [Pool reference](/reference/sandbox-sdk/pool), and [Sandbox runtime support](/reference/sandbox-sdk/runtime-support) |-## Which computer runs the work?+## One claim, one cloud computerWith Fleet, the SDK connects to a claimed cloud guest. Shell commands and GUI-actions through that sandbox act inside the guest. With `local=True`, the SDK-uses a sandbox runtime on your own hardware. See [How sandboxes work](/concepts/how-sandboxes-work)-for the distinction between the host, guest, and control connection.+actions through that sandbox act inside the guest. A pool owns reusable hosted+capacity; a claim reserves one computer from that capacity for a workload.+Declared guest services provide the connection routes the client needs. See+[Pools, claims, and guest services](/concepts/pools-claims-and-guest-services)+for the hosted model.-The SDK is shared, but setup instructions are not interchangeable. Follow Fleet-guides for hosted pools and claims. For work on your own hardware, start with-[Manage local sandbox lifecycle](/how-to-guides/sandbox/manage-local-lifecycle).-Local image-builder steps do not run when Fleet claims a guest.+Looking for execution on your own hardware? Start with+[Local Sandboxes](/local-sandboxes). Its setup and lifecycle are separate from+hosted Fleet credentials, claims, and capacity.Fleet manages capacity; the Sandbox SDK acquires and uses a guest. The SDK'sdefault guest endpoint is computer-server. Cua Driver can control the desktop@@ -46,7 +47,7 @@ before selecting your environment.Exiting a `pool.claim()` context releases the claim. The pool can still retainwarm sandboxes, and cloud resources can incur usage charges after your workload-finishes. The hosted tutorial includes pool deletion; reusable pools need an-explicit cleanup or expiry policy. See [Pool lifecycle](/reference/sandbox-sdk/pool)+finishes. The hosted tutorial removes its dedicated Fleet resources; reusable+pools need an explicit cleanup or expiry policy. See [Pool lifecycle](/reference/sandbox-sdk/pool)for connection and release semantics, and [Expire pools and claims automatically](/how-to-guides/sandbox/expire-pools-and-claims)for deadlines and their effect on active work.diff --git a/docs/content/docs/concepts/how-fleet-images-work.mdx b/docs/content/docs/concepts/how-fleet-images-work.mdxindex af7e4e4f0d..3a5a790efe 100644--- a/docs/content/docs/concepts/how-fleet-images-work.mdx+++ b/docs/content/docs/concepts/how-fleet-images-work.mdx@@ -15,7 +15,7 @@ The public SDK model is documented in [How sandboxes work](/concepts/how-sandbox## Fleet uses a constrained subset of the SDK image surface-Fleet uses a prebuilt registry artifact as its starting point. The Sandbox SDK can reference that artifact directly with `Image.from_registry(...)` or resolve a built-in image with a registry mapping. In `cua-sandbox` 0.4.3, the built-in Ubuntu 24.04 and Windows Server 2022 VM images have registry mappings.+Fleet uses a prebuilt registry artifact as its starting point. The Sandbox SDK can reference that artifact directly with `Image.from_registry(...)` or resolve a built-in image with a registry mapping. In `cua-sandbox` 0.7.0, the built-in Ubuntu 24.04 and Windows Server 2022 VM images have registry mappings.Fleet does **not** build an environment from SDK layers such as `apt_install`, `pip_install`, `uv_install`, `run`, `copy`, `env`, `from_file`, or snapshot-derived images. The Fleet registry input must reference a guest artifact published before sandbox creation.@@ -47,7 +47,7 @@ A Fleet image does not only determine what operating system boots. It also deterReadiness depends on the services started by the image. A running replica whose configured readiness checks have not passed remains unready for claims.-Ports you mark with `.expose(...)` become named Fleet services. A service URL identifies an endpoint in Fleet's proxy; it does not create a localhost listener or grant access by itself. Access requires Fleet authentication. In 0.4.3, pool-backed sandboxes use `sb.services.request()` for authenticated HTTP requests; their transport does not implement `sb.tunnel.forward()`. See [ports and transports](/reference/sandbox-sdk/runtime-support#ports-and-transports).+Ports you mark with `.expose(...)` become named Fleet services. A service URL identifies an endpoint in Fleet's proxy; it does not create a localhost listener or grant access by itself. Access requires Fleet authentication. In 0.7.0, pool-backed sandboxes use `sb.services.request()` for authenticated HTTP requests; their transport does not implement `sb.tunnel.forward()`. See [ports and transports](/reference/sandbox-sdk/runtime-support#ports-and-transports).With the Sandbox SDK's default service configuration, the published image must start the computer-server endpoint on port `8000`. The SDK creates the `server` service and a TCP readiness probe on that port, then waits for `/status` before returning a connected sandbox.diff --git a/docs/content/docs/concepts/how-sandboxes-work.mdx b/docs/content/docs/concepts/how-sandboxes-work.mdxindex fca17ddb7f..ed824a9b4a 100644--- a/docs/content/docs/concepts/how-sandboxes-work.mdx+++ b/docs/content/docs/concepts/how-sandboxes-work.mdx@@ -82,7 +82,7 @@ A _snapshot_ records a machine's state for later reuse. A _fork_ starts a separamachine from that captured state. These mechanisms can avoid repeating expensivesetup, but they require support from the provisioning and storage system.-In `cua-sandbox` 0.4.3, `Sandbox.snapshot()` is not implemented for local sandboxes+In `cua-sandbox` 0.7.0, `Sandbox.snapshot()` is not implemented for local sandboxesor the Fleet creation paths. Fleet also rejects snapshot-derived image inputs.For these paths, prepare a reusable boot artifact instead. See[Sandbox runtime support](/reference/sandbox-sdk/runtime-support#image-customization)diff --git a/docs/content/docs/concepts/meta.json b/docs/content/docs/concepts/meta.jsonindex 40dc40a945..705a17cfe5 100644--- a/docs/content/docs/concepts/meta.json+++ b/docs/content/docs/concepts/meta.json@@ -13,9 +13,11 @@"browser-targeting-and-background-delivery","how-permission-policies-work","how-cua-driver-is-validated",+ "---Cua Fleets---",+ "pools-claims-and-guest-services",+ "how-fleet-images-work","---Cua Sandbox---","how-sandboxes-work",- "how-fleet-images-work","sandbox-lifecycle","---Lume---","how-lume-unattended-setup-works",diff --git a/docs/content/docs/concepts/pools-claims-and-guest-services.mdx b/docs/content/docs/concepts/pools-claims-and-guest-services.mdxnew file mode 100644index 0000000000..12d66e6ae5--- /dev/null+++ b/docs/content/docs/concepts/pools-claims-and-guest-services.mdx@@ -0,0 +1,48 @@+---+title: Pools, claims, and guest services+description: How Cua Fleets organizes hosted capacity, reserves computers, and routes clients to guest services.+---++Cua Fleets adds hosted capacity and routing to the Sandbox model. A **pool**+defines reusable capacity. A **claim** reserves one computer from that pool.+Named **guest services** give an authenticated client a route to software that+is already running inside the claimed computer.++## Pools own reusable capacity++A pool combines a guest image, resource settings, replica capacity, and named+service declarations. The platform can keep replicas ready for later claims,+so releasing one claim does not delete the pool or guarantee that hosted+capacity is gone.++Delete capacity you no longer need, or configure an expiry policy. A pool can+continue to incur usage charges after a workload releases its claim.++## Claims reserve one computer++A claim binds one workload to one available computer from a pool. Leaving a+`pool.claim()` context releases that claim. Disconnecting a client only closes+the connection; it does not by itself release the claim or delete the pool.++Keep the pool and claim names when a process is interrupted. They identify the+existing resources to inspect and clean up before creating replacements.++## Services are part of the connection contract++A service declaration gives Fleet a named route to a port in the guest. It+does not install the application, start a listener, or prove that the service+is ready. The selected image and its startup behavior must provide the service+that the client expects.++The default Sandbox APIs use `computer-server` for shell, files, terminals,+and screenshots. Cua Driver is a separate typed desktop-control surface. A+guest must advertise the compatible Driver service before a client can connect+to it; choosing an image alone does not establish that support.++## Readiness belongs to the service++A running VM and a usable service are different states. Wait for the named+service required by the task, then verify a representative request before+handing the computer to a workload. For the creation and connection sequence,+follow [Create Fleet capacity](/how-to-guides/sandbox/create-fleet-capacity)+and [Claim a Sandbox](/how-to-guides/sandbox/claim-a-sandbox).diff --git a/docs/content/docs/concepts/sandbox-lifecycle.mdx b/docs/content/docs/concepts/sandbox-lifecycle.mdxindex bb7f537b54..311c9bab54 100644--- a/docs/content/docs/concepts/sandbox-lifecycle.mdx+++ b/docs/content/docs/concepts/sandbox-lifecycle.mdx@@ -34,7 +34,7 @@ a pool only when you own its lifecycle; a shared pool can serve other callers.Local execution and Fleet share SDK concepts, but that does not make theirlifecycle operations interchangeable. See [Sandbox runtime support](/reference/sandbox-sdk/runtime-support)-for versioned image and transport limits. In `cua-sandbox` 0.4.3,+for versioned image and transport limits. In `cua-sandbox` 0.7.0,`Sandbox.snapshot()` is not implemented for local sandboxes or Fleet creationpaths, and Fleet rejects snapshot-derived images.diff --git a/docs/content/docs/how-to-guides/sandbox/choose-an-image.mdx b/docs/content/docs/how-to-guides/sandbox/choose-an-image.mdxindex 86be018b73..231f2c1251 100644--- a/docs/content/docs/how-to-guides/sandbox/choose-an-image.mdx+++ b/docs/content/docs/how-to-guides/sandbox/choose-an-image.mdx@@ -18,7 +18,7 @@ for architecture, guest services, and verification limits. A registry referencedoes not prove that the guest is accessible, bootable, or ready for your client.Declaring a service port does not install the service.-In `cua-sandbox` 0.4.3, Fleet rejects SDK builder customization and+In `cua-sandbox` 0.7.0, Fleet rejects SDK builder customization andsnapshot-derived image inputs. Local builder methods do not publish an artifactor run during a Fleet claim. See [Sandbox runtime support](/reference/sandbox-sdk/runtime-support#image-customization)for the versioned contract and [How Fleet images work](/concepts/how-fleet-images-work)@@ -38,9 +38,9 @@ for the published-artifact model.3. Use the built-in constructor for a mapped artifact, or copy the exact registryreference into `Image.from_registry()`. Set the guest OS and `kind='vm'`explicitly. Use a digest when you need an identity independent of tag changes.-4. Follow [Create a sandbox pool with Python](/how-to-guides/sandbox/create-pool-with-python) to apply- the image and claim a replica. Confirm registry access, guest readiness, and- the operation your workload needs before reusing that pool.+4. Follow [Create Fleet capacity](/how-to-guides/sandbox/create-fleet-capacity) to apply the+ image, then [claim a Sandbox](/how-to-guides/sandbox/claim-a-sandbox). Confirm registry access,+ guest readiness, and the operation your workload needs before reusing that pool.The Ubuntu SDK mapping and dashboard default select different tags. Check the[Ubuntu image details](/reference/sandbox-sdk/os-image-catalog#ubuntu-2404) and usediff --git a/docs/content/docs/how-to-guides/sandbox/claim-a-sandbox.mdx b/docs/content/docs/how-to-guides/sandbox/claim-a-sandbox.mdxnew file mode 100644index 0000000000..1068a27acc--- /dev/null+++ b/docs/content/docs/how-to-guides/sandbox/claim-a-sandbox.mdx@@ -0,0 +1,235 @@+---+title: Claim a Sandbox+description: Reserve one computer from existing Cloud Fleet capacity with Python or TypeScript.+---++import { Callout } from 'fumadocs-ui/components/callout';+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';++A claim reserves one computer from an existing Fleet pool. Python uses the+**Cua Sandbox SDK** to expose that computer through the Sandbox APIs.+TypeScript uses the **Fleet SDK** for hosted claim lifecycle and service+routing; it is not a TypeScript Sandbox SDK.++The examples use the pool's `server` service to prove the claimed computer is+usable. Create a pool first with [Create Fleet capacity](/how-to-guides/sandbox/create-fleet-capacity),+or use a pool managed by your team.++## Prerequisites++- Permission to claim from the pool.+- The pool name and a distinct claim name for this task.+- A declared `server` service on port `8000`.++```bash+export CUA_POOL_NAME="my-team-sandbox-pool"+export CUA_CLAIM_NAME="my-task"+export CUA_CLIENT_ID="<your-client-id>"+export CUA_CLIENT_SECRET="<your-client-secret>"+```++## Claim and use a computer++<Tabs groupId="language" persist items={['Python', 'TypeScript']}>+ <Tab value="Python">++Save this as `claim_sandbox.py`. The Python Sandbox SDK connects the claim to+the familiar shell and screenshot APIs exposed by `computer-server`.++```python title="claim_sandbox.py"+# /// script+# requires-python = ">=3.11,<3.14"+# dependencies = [+# "cua-sandbox==0.7.0",+# ]+# ///++import asyncio+import os+from pathlib import Path++from cua_sandbox import Pool+++async def main() -> None:+ pool = await Pool.get(os.environ["CUA_POOL_NAME"])+ async with pool.claim(+ name=os.environ["CUA_CLAIM_NAME"],+ service="server",+ time_to_start=900,+ ) as sandbox:+ print(f"Pool: {sandbox.pool_name}")+ print(f"Claim: {sandbox.claim_name}")++ result = await sandbox.shell.run("uname -a")+ if not result.success:+ raise RuntimeError(result.stderr)+ print(result.stdout.strip())++ Path("sandbox.png").write_bytes(await sandbox.screenshot())+++asyncio.run(main())+```++Run it:++```bash+uv run claim_sandbox.py+```++The claim context reconnects to an existing named claim when one is present,+waits up to 900 seconds for `server`, and releases the claim on exit.++ </Tab>+ <Tab value="TypeScript">++The TypeScript Fleet SDK claims and waits for capacity, then routes an HTTP+request to the declared guest service. It does not expose the Python Sandbox+object or its shell convenience API.++<Tabs groupId="fleet-typescript-runtime" persist items={['Node.js', 'Browser']}>+ <Tab value="Node.js">++Install `@trycua/[email protected]`, `tsx`, and `typescript` as shown in the capacity+guide. Save this as `claim-sandbox.ts`:++```ts title="claim-sandbox.ts"+import { writeFile } from 'node:fs/promises';+import {+ CreateClaimRequestBuilder,+ CyclopsClient,+ CyclopsCredentials,+ FetchHttpClient,+ type Claim,+ type CyclopsConfiguration,+ uniffiInitAsync,+} from '@trycua/fleet/node';++function requiredEnv(name: string): string {+ const value = process.env[name];+ if (!value) throw new Error(`Missing environment variable: ${name}`);+ return value;+}++function screenshotBase64(responseBody: ArrayBuffer): string {+ const text = new TextDecoder().decode(responseBody);+ const dataLine = text.split('\n').find((line) => line.startsWith('data: '));+ if (!dataLine) throw new Error(`No screenshot data frame: ${text.slice(0, 200)}`);+ const payload = JSON.parse(dataLine.slice(6));+ if (!payload.success) throw new Error(payload.error ?? 'Screenshot failed');+ const encoded = payload.image_data ?? payload.result?.image_data;+ if (typeof encoded !== 'string') throw new Error('Screenshot response has no image data');+ return encoded;+}++await uniffiInitAsync();+const configuration: CyclopsConfiguration = {+ baseUrl: process.env.CUA_FLEET_BASE_URL ?? 'https://run.cua.ai',+ tokenUrl:+ process.env.CUA_TOKEN_URL ??+ 'https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token',+ credentials: new CyclopsCredentials(+ requiredEnv('CUA_CLIENT_ID'),+ requiredEnv('CUA_CLIENT_SECRET')+ ),+ poolPollIntervalMs: 5_000n,+ poolPollLimit: 120,+ claimPollIntervalMs: 5_000n,+ claimPollLimit: 120,+};+const client = CyclopsClient.connect(configuration, new FetchHttpClient()) as CyclopsClient;++let claim: Claim | undefined;+try {+ const pool = await client.getPool(requiredEnv('CUA_POOL_NAME'));+ claim = await client.createClaim(+ new CreateClaimRequestBuilder().pool(pool).name(requiredEnv('CUA_CLAIM_NAME')).build()+ );+ console.log(`Claim: ${claim.metadata.namespace}/${claim.metadata.name}`);+ const sandbox = await client.waitClaim(claim);++ const body = await new Blob([JSON.stringify({ command: 'screenshot' })]).arrayBuffer();+ const response = await client.serviceRequest(sandbox, 'server', '/cmd', {+ method: 'POST',+ url: 'https://service.invalid/cmd',+ headers: [{ name: 'content-type', value: 'application/json' }],+ body,+ timeoutSecs: 60n,+ });+ if (response.status < 200 || response.status >= 300) {+ throw new Error(`Screenshot request failed with HTTP ${response.status}`);+ }+ await writeFile('sandbox.png', Buffer.from(screenshotBase64(response.body), 'base64'));+} finally {+ try {+ if (claim) await client.deleteClaim(claim);+ } finally {+ client.uniffiDestroy();+ }+}+```++Run it:++```bash+npx tsx claim-sandbox.ts+```++ </Tab>+ <Tab value="Browser">++<Callout type="warn">+ Browser code can read bundled credentials. Use temporary, narrowly scoped credentials only in a+ trusted application. Keep long-lived credentials on a backend.+</Callout>++Use the same `getPool()`, `createClaim()`, `waitClaim()`, `serviceRequest()`, and+`deleteClaim()` sequence as the Node.js example. Import the types and builders+from `@trycua/fleet/browser`, read configuration from `import.meta.env`, provide+a browser `fetch` implementation of `HttpClient`, and display the decoded PNG+with `URL.createObjectURL()` instead of writing it with Node.js `fs`.++ </Tab>+</Tabs>++`client.uniffiDestroy()` disposes only the local client. The remote claim is+released by `deleteClaim()`, so keep that call in a `finally` block.++ </Tab>+</Tabs>++## Result and lifecycle++Both paths reserve one computer, wait for the `server` service, capture a+screenshot through `computer-server`, and release only the claim. The pool and+its warm capacity remain available and can continue consuming capacity. Copy+results out before release; a later claim is not guaranteed to receive the same+VM or files.++Claim names are scoped to the pool. Give concurrent tasks different names. A+Python named claim that still exists is reconnected; the TypeScript example+creates a claim and should use a fresh name after release.++## Keep a Python claim between processes++The Python Sandbox SDK can disconnect while leaving its claim held. Save the+Sandbox reference before disconnecting:++```python+import json+from pathlib import Path++sandbox = await pool.claim(name=CLAIM_NAME, service="server", time_to_start=900)+try:+ Path("claim.json").write_text(json.dumps(sandbox.to_dict()))+finally:+ await sandbox.disconnect()+```++Reconnect with `Sandbox.from_dict(reference)`. That context disconnects on+exit; call `await sandbox.close()` when the task is finished to release the+claim. A saved reference does not extend its expiry deadline.++If acquisition or cleanup is interrupted, retain the pool and claim names and+follow [Recover interrupted cleanup](/how-to-guides/sandbox/troubleshoot-fleet-pools#recover-interrupted-cleanup).diff --git a/docs/content/docs/how-to-guides/sandbox/control-the-desktop-with-cua-driver.mdx b/docs/content/docs/how-to-guides/sandbox/control-the-desktop-with-cua-driver.mdxnew file mode 100644index 0000000000..f09967c438--- /dev/null+++ b/docs/content/docs/how-to-guides/sandbox/control-the-desktop-with-cua-driver.mdx@@ -0,0 +1,112 @@+---+title: Control the desktop with Cua Driver+description: Connect the typed Cua Driver SDK to a claimed Cloud Fleet computer.+---++import { Tabs, Tab } from 'fumadocs-ui/components/tabs';++Cua Driver provides typed desktop inspection and control. Use the Sandbox+interfaces backed by `computer-server` for shell commands, files, and+interactive terminals; the Driver connection does not replace those APIs.++Python uses the Sandbox SDK, while TypeScript uses the Fleet SDK for hosted+lifecycle and routing. The TypeScript Fleet SDK is not a TypeScript Sandbox+SDK. Both examples below connect Driver to the same advertised guest service.++## Prerequisites++- An authenticated Cloud Fleet client and a live claim. The Python example+ starts with the `Pool` object for that capacity; the TypeScript example starts+ with its Fleet `client` and `claim`.+- A guest service named `mcp` that advertises the typed Driver envelope+ extension, `capabilities.experimental["ai.cua.driver.envelopes"].version == 1`.+ An ordinary MCP tools endpoint is not enough.+- Guest permissions for the desktop operation you call. Connecting Driver does+ not elevate permissions or make every operation available on every desktop.++No Fleet image is implied to provide this capability. Qualify the exact guest+artifact and matching Driver bindings before relying on it.++## Connect and inspect the desktop++<Tabs groupId="language" persist items={['Python', 'TypeScript']}>+ <Tab value="Python">++Install the Sandbox SDK with its optional Driver dependency:++```bash+python -m pip install --extra-index-url https://wheels.cua.ai/simple 'cua-sandbox[driver]'+```++Claim from the existing pool, then connect the typed Driver through its+advertised `mcp` service:++```python+from cua_driver import GetScreenSizeInput+++async def inspect_desktop(pool):+ async with pool.claim(service="server") as sb:+ # sb.shell, sb.files, and sb.terminal continue to use computer-server.+ async with sb.driver.connect(service="mcp", transport="mcp") as driver:+ result = await driver.get_screen_size(+ GetScreenSizeInput(session=None)+ )+ if result.is_error:+ raise RuntimeError(result.text)+ print(result.text)+```++Exiting the inner context closes Driver before the outer claim context releases+the claim.++ </Tab>+ <Tab value="TypeScript">++The helper is Node-only. Install the Fleet lifecycle SDK and Cua Driver:++```bash+npm install @trycua/fleet @trycua/cua-driver+```++Given the claim your application created, wait for its sandbox and connect the+typed Driver:++```ts+import { GetScreenSizeInput } from '@trycua/cua-driver';+import { connectFleetDriver } from '@trycua/cua-driver/fleet';++let connection: Awaited<ReturnType<typeof connectFleetDriver>> | undefined;++try {+ const sandbox = await client.waitClaim(claim);+ connection = await connectFleetDriver({ client, sandbox });++ const result = await connection.driver.getScreenSize(+ GetScreenSizeInput.new({ session: undefined })+ );+ if (result.isError) throw new Error(result.text);+ console.log(result.text);+} finally {+ try {+ if (connection) await connection.close();+ } finally {+ await client.deleteClaim(claim);+ }+}+```++`connectFleetDriver({ client, sandbox })` selects the advertised `mcp` service+by default. Pass `service` only when the pool deliberately uses another name;+the guest under that name must advertise the same typed envelope capability.+Closing the connection does not release the claim, so the example awaits+`close()` before `deleteClaim()`.++ </Tab>+</Tabs>++The returned object is the typed Cua Driver interface, not a wrapper around MCP+tools. Keep the claim and authenticated client alive for the whole Driver+connection. Copy any results you need out of the guest, close Driver, and only+then release the claim. Releasing a claim first can interrupt cleanup and leave+the outcome of an in-flight desktop action uncertain.diff --git a/docs/content/docs/how-to-guides/sandbox/create-fleet-capacity.mdx b/docs/content/docs/how-to-guides/sandbox/create-fleet-capacity.mdxnew file mode 100644index 0000000000..6a9b01699e--- /dev/null+++ b/docs/content/docs/how-to-guides/sandbox/create-fleet-capacity.mdx@@ -0,0 +1,280 @@+---+title: Create Fleet capacity+description: Create reusable Cloud Fleet capacity with Python or TypeScript.+---++import { Callout } from 'fumadocs-ui/components/callout';+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';++Create a reusable pool before tasks claim computers from it. Python uses the+**Cua Sandbox SDK**, the programming model for one isolated computer that can+run locally or on Cloud Fleet capacity. TypeScript uses the **Fleet SDK**, which+manages hosted Fleet lifecycle and routing; it is not a TypeScript Sandbox SDK.++Both paths below create the same Fleet resources: a one-replica pool, a VM+template, and a `server` service for `computer-server` on port `8000`. They do+not claim a Sandbox.++## Prerequisites++- Permission to manage pools at `run.cua.ai`.+- OAuth client credentials.+- A globally unique pool name written as a lowercase DNS label.++Set the shared values before continuing:++```bash+export CUA_CLIENT_ID="<your-client-id>"+export CUA_CLIENT_SECRET="<your-client-secret>"+export CUA_POOL_NAME="my-team-sandbox-pool"+```++Set `CUA_FLEET_BASE_URL` or `CUA_TOKEN_URL` only when you need different Fleet+or OAuth endpoints.++## Create the pool++<Tabs groupId="language" persist items={['Python', 'TypeScript']}>+ <Tab value="Python">++Install the Python Sandbox SDK in an isolated environment by saving this as+`create_fleet_capacity.py`:++```python title="create_fleet_capacity.py"+# /// script+# requires-python = ">=3.11,<3.14"+# dependencies = [+# "cua-sandbox==0.7.0",+# ]+# ///++import asyncio+import os++from cua_sandbox import Image, Pool+++IMAGE = (+ "public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04"+ "@sha256:c1e601dbb748fdc467c663136f7592e308a91a3c19c309b75261544432826a57"+)+++async def main() -> None:+ pool = await Pool.apply(+ Image.from_registry(IMAGE),+ name=os.environ["CUA_POOL_NAME"],+ replicas=1,+ cpu=4,+ memory_mb=4096,+ services={"server": 8000},+ )+ print(f"Fleet capacity is ready: {pool.name}")+++asyncio.run(main())+```++Run it with Python 3.11–3.13 and [`uv`](https://docs.astral.sh/uv/):++```bash+uv run create_fleet_capacity.py+```++`Pool.apply()` derives and reconciles both the pool and its template. Use it+only when this script owns their configuration.++ </Tab>+ <Tab value="TypeScript">++The TypeScript Fleet SDK provides separate Node.js and browser entry points.+Choose the runtime that owns your Fleet client.++<Tabs groupId="fleet-typescript-runtime" persist items={['Node.js', 'Browser']}>+ <Tab value="Node.js">++Install the Fleet lifecycle SDK and a TypeScript runner:++```bash+npm install @trycua/[email protected]+npm install --save-dev tsx typescript+npm pkg set type=module+```++Save this as `create-fleet-capacity.ts`:++```ts title="create-fleet-capacity.ts"+import {+ CreatePoolRequestBuilder,+ CreateTemplateRequestBuilder,+ CyclopsClient,+ CyclopsCredentials,+ FetchHttpClient,+ OsGymSandboxTemplateSpecBuilder,+ OsGymSandboxWarmPoolSpecBuilder,+ SandboxServiceBuilder,+ SandboxTemplateRefBuilder,+ VmTemplateBuilder,+ type CyclopsConfiguration,+ uniffiInitAsync,+} from '@trycua/fleet/node';++const IMAGE =+ 'public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04' ++ '@sha256:c1e601dbb748fdc467c663136f7592e308a91a3c19c309b75261544432826a57';+const POOL_NAME = requiredEnv('CUA_POOL_NAME');+const TEMPLATE_NAME = `${POOL_NAME}-template`;++function requiredEnv(name: string): string {+ const value = process.env[name];+ if (!value) throw new Error(`Missing environment variable: ${name}`);+ return value;+}++await uniffiInitAsync();+const configuration: CyclopsConfiguration = {+ baseUrl: process.env.CUA_FLEET_BASE_URL ?? 'https://run.cua.ai',+ tokenUrl:+ process.env.CUA_TOKEN_URL ??+ 'https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token',+ credentials: new CyclopsCredentials(+ requiredEnv('CUA_CLIENT_ID'),+ requiredEnv('CUA_CLIENT_SECRET')+ ),+ poolPollIntervalMs: 5_000n,+ poolPollLimit: 120,+ claimPollIntervalMs: 5_000n,+ claimPollLimit: 120,+};+const client = CyclopsClient.connect(configuration, new FetchHttpClient()) as CyclopsClient;++try {+ const server = new SandboxServiceBuilder().name('server').targetPort(8000).build();+ const vm = new VmTemplateBuilder()+ .containerDiskImage(IMAGE)+ .cpuCores(4)+ .memory('4Gi')+ .services([server])+ .build();+ const templateSpec = new OsGymSandboxTemplateSpecBuilder().vmTemplate(vm).build();+ const templateRef = new SandboxTemplateRefBuilder().name(TEMPLATE_NAME).build();+ const poolSpec = new OsGymSandboxWarmPoolSpecBuilder()+ .replicas(1)+ .sandboxTemplateRef(templateRef)+ .build();++ const pool = await client.reconcilePool(+ new CreatePoolRequestBuilder().namespace(POOL_NAME).spec(poolSpec).build()+ );+ const template = await client.reconcileTemplate(+ new CreateTemplateRequestBuilder()+ .namespace(POOL_NAME)+ .name(TEMPLATE_NAME)+ .spec(templateSpec)+ .build()+ );+ console.log(`Fleet capacity is ready: ${pool.metadata.name}/${template.metadata.name}`);+} finally {+ client.uniffiDestroy();+}+```++Run it:++```bash+npx tsx create-fleet-capacity.ts+```++ </Tab>+ <Tab value="Browser">++<Callout type="warn">+ Browser code can read every `VITE_*` value bundled into the application. Use this path only in a+ trusted local or internal application with temporary, narrowly scoped credentials. Keep long-lived+ credentials in Node.js or on your backend.+</Callout>++Create a Vite TypeScript project and install the browser SDK:++```bash+npm create vite@latest fleet-browser -- --template vanilla-ts+cd fleet-browser+npm install+npm install @trycua/[email protected]+```++Use the same builders and reconciliation sequence as the Node.js example, but+import them from `@trycua/fleet/browser`, read credentials from+`import.meta.env`, and supply an `HttpClient` implementation backed by browser+`fetch`. The browser and Node.js entry points expose the same Fleet pool,+template, claim, and service-routing types.++ </Tab>+</Tabs>++Unlike Python `Pool.apply()`, the TypeScript `reconcilePool()` and+`reconcileTemplate()` methods are lower-level Fleet primitives. The application+must build both requests and owns the resulting configuration and cleanup.++ </Tab>+</Tabs>++## What the operation changes++Reconciliation creates the resources when they do not exist and updates their+specifications when they do. The pool keeps one computer warm and continues to+consume capacity until it is scaled down or deleted. It does not reserve that+computer for a task; continue with [Claim a Sandbox](/how-to-guides/sandbox/claim-a-sandbox).++To consume capacity managed by another process or Terraform, do not reconcile+it. Look up the existing pool instead:++<Tabs groupId="language" persist items={['Python', 'TypeScript']}>+ <Tab value="Python">++```python+pool = await Pool.get(POOL_NAME)+```++ </Tab>+ <Tab value="TypeScript">++```ts+const pool = await client.getPool(POOL_NAME);+```++ </Tab>+</Tabs>++Pool names are globally unique across Cua accounts. A changed claim name does+not resolve a pool namespace collision. HTTP 403 can also indicate payment,+authorization, or template-policy failures, so inspect the operation and+response before choosing a different name.++## Delete capacity you own++Delete a Fleet namespace only after all users have released their claims.+Namespace deletion removes the pool, its template, and remaining resources; it+is not per-task cleanup for shared capacity. `deletePool(pool)` removes only the+pool resource and is insufficient for whole-Fleet cleanup.++<Tabs groupId="language" persist items={['Python', 'TypeScript']}>+ <Tab value="Python">++```python+await pool.delete()+```++ </Tab>+ <Tab value="TypeScript">++```ts+await client.deleteNamespace(POOL_NAME);+```++ </Tab>+</Tabs>++If a process stops before cleanup completes, follow+[Recover interrupted cleanup](/how-to-guides/sandbox/troubleshoot-fleet-pools#recover-interrupted-cleanup)+instead of provisioning again just to obtain a deletion handle.diff --git a/docs/content/docs/how-to-guides/sandbox/create-pool-with-python.mdx b/docs/content/docs/how-to-guides/sandbox/create-pool-with-python.mdxdeleted file mode 100644index 215963076e..0000000000--- a/docs/content/docs/how-to-guides/sandbox/create-pool-with-python.mdx+++ /dev/null@@ -1,289 +0,0 @@-----title: Create a sandbox pool with Python-description: Create a reusable warm sandbox pool, claim a sandbox, and run commands with the Cua Sandbox SDK.------Use the Cua Sandbox SDK when you want to create and claim a reusable sandbox-pool from Python. This guide applies a one-replica pool, connects to a named-claim, takes a screenshot, and runs a shell command.--## Prerequisites--- Python `>=3.11,<3.14`.-- [`uv`](https://docs.astral.sh/uv/) to run the self-contained script.-- A run.cua.ai access token or OAuth user key with permission to manage sandbox- pools.--The SDK connects to `https://run.cua.ai` by default. Authenticate with a Fleet-access token:--```bash-export FLEETS_TOKEN="<your-access-token>"-```--Or authenticate with OAuth client credentials:--```bash-export CUA_CLIENT_ID="<your-client-id>"-export CUA_CLIENT_SECRET="<your-client-secret>"-```--Set `CUA_FLEET_BASE_URL` only when you need to use a different Fleet API-endpoint.--## Create and claim the pool--Set a globally unique pool name that you own before running the example:--```bash-export CUA_POOL_NAME="my-team-sandbox-pool"-export CUA_CLAIM_NAME="my-task"-```--The example uses `cua-sandbox==0.4.3`. Use `Pool.apply()` only when this script-owns the pool configuration. For a pool managed by another process or-Terraform, use [an existing pool](#use-an-existing-pool) instead.--Save the following script as `create_pool.py`:--```python title="create_pool.py"-# /// script-# requires-python = ">=3.11,<3.14"-# dependencies = [-# "cua-sandbox==0.4.3",-# ]-# ///--import asyncio-import os-from pathlib import Path--from cua_sandbox import Image, Pool---IMAGE = (- "public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04"- "@sha256:c1e601dbb748fdc467c663136f7592e308a91a3c19c309b75261544432826a57"-)--POOL_NAME = os.environ["CUA_POOL_NAME"]-CLAIM_NAME = os.environ.get("CUA_CLAIM_NAME", POOL_NAME)---async def main() -> None:- # Create or reconcile the warm pool and its template.- pool = await Pool.apply(- Image.from_registry(IMAGE),- name=POOL_NAME,- replicas=1,- cpu=4,- memory_mb=4096,- services={"server": 8000},- )-- # Create or reconnect to the named claim.- # Exiting this block releases the claim but leaves the pool warm.- async with pool.claim(- name=CLAIM_NAME,- service="server",- time_to_start=900,- ) as sandbox:- print(f"Pool: {sandbox.pool_name}")- print(f"Claim: {sandbox.claim_name}")- print(f"Sandbox: {sandbox.name}")-- screenshot = Path("sandbox.png")- screenshot.write_bytes(await sandbox.screenshot())- print(f"Screenshot: {screenshot.resolve()}")-- result = await sandbox.shell.run("uname -a")- if not result.success:- raise RuntimeError(result.stderr)-- print(result.stdout.strip())---asyncio.run(main())-```--Run it with `uv`. The script metadata installs `cua-sandbox` in an isolated-environment automatically:--```bash-uv run create_pool.py-```--`Pool.apply()` creates the pool and its sandbox template when they do not exist.-If the named pool already exists, it reconciles the pool to the image, replica,-CPU, memory, and service configuration in the script.--`pool.claim()` creates or reconnects to the named claim, waits for binding, then-waits up to 900 seconds for the `server` service on port `8000`. The service-timeout is separate from claim binding. Exiting the `async with` block-releases the claim, but the pool and its one warm replica remain available for-the next claim.--The script writes `sandbox.png` in the current directory and raises an error if-`uname -a` does not complete successfully.--## Use an existing pool--Replace the `Pool.apply(...)` call with a lookup to keep the pool's image,-capacity, and services unchanged:--```python-pool = await Pool.get(POOL_NAME)-```--Keep the claim block from the example. Give concurrent tasks different claim-names, or omit `name=` to generate one. A named claim that still exists is-reused; once released, reusing its name creates a new claim. Reusing a pool or-claim name does not guarantee the same VM or preserve files from a released-claim. Copy results out before releasing it.--The claim context releases even an existing claim that it successfully attaches-to. Use it only when this task owns that claim's release. If acquisition fails,-the SDK attempts to release a claim it just created, but leaves a pre-existing-claim alone.--## Keep a claim between processes--To keep a claim after the connection closes, await the claim directly and save-its reference before disconnecting:--```python-import json--sandbox = await pool.claim(name=CLAIM_NAME, service="server", time_to_start=900)-try:- Path("claim.json").write_text(json.dumps(sandbox.to_dict()))- result = await sandbox.shell.run("uname -a")- print(result.stdout)-finally:- await sandbox.disconnect()-```--`disconnect()` closes the client transport and leaves the claim held. A later-process can reconnect using the saved reference without creating a pool or-claim:--```python-import json-from pathlib import Path-from cua_sandbox import Sandbox--reference = json.loads(Path("claim.json").read_text())-async with Sandbox.from_dict(reference) as sandbox:- result = await sandbox.shell.run("uname -a")- print(result.stdout)-```--This reconnect context only disconnects on exit. When the task is finished,-call `await sandbox.close()` to release its claim. A reference does not extend-an expiry deadline. Protect it as resource metadata and keep authenticating-with credentials authorized for that pool.--For Fleet claims, use these explicit pool and claim APIs. The legacy-`Sandbox.list()`, `Sandbox.suspend()`, and `Sandbox.resume()` methods are not-per-claim Fleet lifecycle controls.--## Scale the pool with claim demand--Instead of a static `replicas` count, pass `autoscaling=` to let the pool grow-and shrink with claim demand. The pool scales toward `max_pool_size` while-claims are pending and back down to `min_pool_size` as claims are released;-`initial_pool_size` seeds a one-time warm head start when the pool is created:--```python-from cua_sandbox import Image, Pool, WarmPoolAutoscaling--pool = await Pool.apply(- Image.from_registry(IMAGE),- name=POOL_NAME,- cpu=4,- memory_mb=4096,- autoscaling=WarmPoolAutoscaling(- min_pool_size=0,- initial_pool_size=2,- max_pool_size=10,- ),-)-```--Each field is optional (pass `None` to accept the server default). With-`min_pool_size=0` the pool scales to zero when no claims are held, so the-first claim after an idle period cold-starts a sandbox.--## Expire pools and claims automatically--Pools and claims accept an optional creation-age TTL that deletes them a-fixed time after creation. See-[Expire pools and claims automatically](/how-to-guides/sandbox/expire-pools-and-claims).--## Choose pool and claim names--`CUA_POOL_NAME` is required. If `CUA_CLAIM_NAME` is omitted, the script uses the-pool name for its claim. Override either name without editing the script:--```bash-export CUA_POOL_NAME="my-sandbox-pool"-export CUA_CLAIM_NAME="my-sandbox-claim"-uv run create_pool.py-```--Use a stable pool name for shared capacity and a distinct claim name for each-independent task. Names must be lowercase DNS labels.--## Pool names are globally unique--A pool's name is also its namespace, and that namespace is shared across all-Cua accounts. `Pool.apply()` therefore requires an explicit `name=`, and-`Sandbox.create(image, ...)` refuses Fleet registry images without a pool —-apply a named pool first and pass it as `pool=`:--```python-pool = await Pool.apply(image, name="my-team-windows-pool")-sandbox = await Sandbox.create(pool=pool, name="my-claim")-```--If the name belongs to another account, the SDK can raise-`PoolAccessDeniedError` with a name-collision hint:--```text-PoolAccessDeniedError: Fleet denied create pool on pool namespace-'my-team-windows-pool' (HTTP 403: k8s request is not allowed). 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-```--For a confirmed name collision, choose another pool name; changing claim names-does not fix a pool namespace conflict. Claim names are scoped to their pool's-namespace. The SDK generates random `claim-<petname>` claim names when omitted.--The exception's name-collision hint is not a diagnosis for every HTTP 403.-Inspect the operation and response body: a payment requirement or template-policy denial needs a different action. See-[Troubleshoot Fleet pools and claims](/how-to-guides/sandbox/troubleshoot-fleet-pools).--`Sandbox.ephemeral(image)` remains a one-liner: it creates a disposable pool-under a random `cua-eph-<hex>` name and deletes it on exit. Passing-`keep_pool=True` requires `name=` so later runs can find the kept pool.--## Delete the pool--The example intentionally leaves the pool warm, consuming capacity after the-script exits. When you own the pool and all of its users have finished, call-`await pool.delete()` after releasing every claim. Pool deletion also deletes-the pool namespace and its remaining resources. Do not put it in a worker's-per-task cleanup for a shared pool.--`Pool.apply()` tracks its reconciled template for cleanup, including when that-template already existed. In `cua-sandbox==0.4.3`, a template reconciliation-failure also triggers an attempt to delete the reconciled pool. It is not a-transaction that preserves an existing pool on failure. Use `Pool.get()` when-you only need to consume existing capacity.--If a process exits before cleanup completes, follow-[Recover interrupted cleanup](/how-to-guides/sandbox/troubleshoot-fleet-pools#recover-interrupted-cleanup).-Do not rerun provisioning merely to obtain a handle to delete.diff --git a/docs/content/docs/how-to-guides/sandbox/create-pool-with-typescript.mdx b/docs/content/docs/how-to-guides/sandbox/create-pool-with-typescript.mdxdeleted file mode 100644index 71d5c73342..0000000000--- a/docs/content/docs/how-to-guides/sandbox/create-pool-with-typescript.mdx+++ /dev/null@@ -1,479 +0,0 @@-----title: Create a sandbox pool with TypeScript-description: Create a reusable Fleet pool and capture a sandbox screenshot from browser or Node.js TypeScript.------import { Callout } from 'fumadocs-ui/components/callout';-import { Tab, Tabs } from 'fumadocs-ui/components/tabs';--Use `@trycua/fleet` to reconcile a reusable sandbox pool from TypeScript. This-guide applies a one-replica Linux pool configuration, claims a sandbox, captures-a screenshot, and releases the claim while leaving the pool warm.--The package provides separate runtime entry points:--- `@trycua/fleet/browser` loads the Fleet WebAssembly module in a browser.-- `@trycua/fleet/node` loads the same WebAssembly module from disk and provides- a fetch-based HTTP transport.--## Prerequisites--- Node.js 20 or newer.-- OAuth client credentials with permission to manage sandbox pools.-- A globally unique, lowercase DNS-label pool name.--This guide uses the public Linux computer-server image:--```text-public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04@sha256:c1e601dbb748fdc467c663136f7592e308a91a3c19c309b75261544432826a57-```--<Callout type="warn">- Browser code can read every `VITE_*` value bundled into the application. Use the browser example- only in a trusted local or internal application with temporary, narrowly scoped client- credentials. Keep long-lived credentials in Node.js or on your backend.-</Callout>--## Choose a runtime--<Tabs groupId="fleet-typescript-runtime" persist items={['Node.js', 'Browser']}>- <Tab value="Node.js">--Install the Fleet lifecycle SDK and a TypeScript runner:--```bash-npm install @trycua/[email protected]-npm install --save-dev tsx typescript-npm pkg set type=module-```--Set your OAuth client credentials and a unique pool name:--```bash-export CUA_CLIENT_ID="<your-client-id>"-export CUA_CLIENT_SECRET="<your-client-secret>"-export CUA_POOL_NAME="my-team-js-pool"-```--Set `CUA_FLEET_BASE_URL` or `CUA_TOKEN_URL` only when you need to use different-Fleet or OAuth endpoints.--Save this script as `create-pool.ts`:--```ts title="create-pool.ts"-import { writeFile } from 'node:fs/promises';-import {- CreateClaimRequestBuilder,- CreatePoolRequestBuilder,- CreateTemplateRequestBuilder,- CyclopsClient,- CyclopsCredentials,- FetchHttpClient,- OsGymSandboxTemplateSpecBuilder,- OsGymSandboxWarmPoolSpecBuilder,- SandboxServiceBuilder,- SandboxTemplateRefBuilder,- VmTemplateBuilder,- type Claim,- type CyclopsConfiguration,- uniffiInitAsync,-} from '@trycua/fleet/node';--const IMAGE =- 'public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04' +- '@sha256:c1e601dbb748fdc467c663136f7592e308a91a3c19c309b75261544432826a57';-const BASE_URL = process.env.CUA_FLEET_BASE_URL ?? 'https://run.cua.ai';-const TOKEN_URL =- process.env.CUA_TOKEN_URL ??- 'https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token';-const CLIENT_ID = requiredEnv('CUA_CLIENT_ID');-const CLIENT_SECRET = requiredEnv('CUA_CLIENT_SECRET');-const POOL_NAME = requiredEnv('CUA_POOL_NAME');-const TEMPLATE_NAME = `${POOL_NAME}-template`;--function requiredEnv(name: string): string {- const value = process.env[name];- if (!value) throw new Error(`Missing environment variable: ${name}`);- return value;-}--function screenshotBase64(responseBody: ArrayBuffer): string {- const text = new TextDecoder().decode(responseBody);- const dataLine = text.split('\n').find((line) => line.startsWith('data: '));- if (!dataLine) throw new Error(`No screenshot data frame: ${text.slice(0, 200)}`);-- const payload = JSON.parse(dataLine.slice(6));- if (!payload.success) throw new Error(payload.error ?? 'Screenshot failed');-- const encoded = payload.image_data ?? payload.result?.image_data;- if (typeof encoded !== 'string') throw new Error('Screenshot response has no image data');- return encoded;-}--await uniffiInitAsync();--const configuration: CyclopsConfiguration = {- baseUrl: BASE_URL,- tokenUrl: TOKEN_URL,- credentials: new CyclopsCredentials(CLIENT_ID, CLIENT_SECRET),- poolPollIntervalMs: 5_000n,- poolPollLimit: 120,- claimPollIntervalMs: 5_000n,- claimPollLimit: 120,-};-const client = CyclopsClient.connect(configuration, new FetchHttpClient()) as CyclopsClient;--let claim: Claim | undefined;-try {- const serverService = new SandboxServiceBuilder().name('server').targetPort(8000).build();- const mcpService = new SandboxServiceBuilder().name('mcp').targetPort(3000).build();- const vm = new VmTemplateBuilder()- .containerDiskImage(IMAGE)- .cpuCores(4)- .memory('4Gi')- .services([serverService, mcpService])- .build();- const templateSpec = new OsGymSandboxTemplateSpecBuilder().vmTemplate(vm).build();- const templateRef = new SandboxTemplateRefBuilder().name(TEMPLATE_NAME).build();- const poolSpec = new OsGymSandboxWarmPoolSpecBuilder()- .replicas(1)- .sandboxTemplateRef(templateRef)- .build();-- const pool = await client.reconcilePool(- new CreatePoolRequestBuilder().namespace(POOL_NAME).spec(poolSpec).build()- );- const template = await client.reconcileTemplate(- new CreateTemplateRequestBuilder()- .namespace(POOL_NAME)- .name(TEMPLATE_NAME)- .spec(templateSpec)- .build()- );-- console.log(`Reconciled pool ${pool.metadata.name}`);- console.log(`Reconciled template ${template.metadata.name}`);-- claim = await client.createClaim(new CreateClaimRequestBuilder().pool(pool).build());- console.log(`Claim: ${claim.metadata.namespace}/${claim.metadata.name}`);- const sandbox = await client.waitClaim(claim);-- const requestBody = await new Blob([JSON.stringify({ command: 'screenshot' })]).arrayBuffer();- const response = await client.serviceRequest(sandbox, 'server', '/cmd', {- method: 'POST',- url: 'https://service.invalid/cmd',- headers: [{ name: 'content-type', value: 'application/json' }],- body: requestBody,- timeoutSecs: 60n,- });- if (response.status < 200 || response.status >= 300) {- throw new Error(`Screenshot request failed with HTTP ${response.status}`);- }-- await writeFile('sandbox.png', Buffer.from(screenshotBase64(response.body), 'base64'));- console.log('Wrote sandbox.png');-} finally {- try {- // Release the claim but leave the reusable pool warm.- if (claim) await client.deleteClaim(claim);- } finally {- client.uniffiDestroy();- }-}-```--Run it:--```bash-npx tsx create-pool.ts-```--The script writes `sandbox.png` in the current directory. The Fleet client-creates and waits for the claim, routes `POST /cmd` through the authenticated-`server` service proxy, and deletes the claim before closing. The template also-declares the Cua Driver MCP endpoint as the `mcp` service on port `3000`, so the-same pool works with the signed-service URL guide.-- </Tab>- <Tab value="Browser">--Create a Vite TypeScript project and install the browser SDK:--```bash-npm create vite@latest fleet-browser -- --template vanilla-ts-cd fleet-browser-npm install-npm install @trycua/[email protected]-```--Create `.env.local` with temporary, narrowly scoped OAuth client credentials-and a unique pool name:--```bash title=".env.local"-VITE_CUA_CLIENT_ID=<your-client-id>-VITE_CUA_CLIENT_SECRET=<your-client-secret>-VITE_CUA_POOL_NAME=my-team-browser-pool-```--Set `VITE_CUA_FLEET_BASE_URL` or `VITE_CUA_TOKEN_URL` only when you need to use-different Fleet or OAuth endpoints.--Replace `src/main.ts` with the following code:--```ts title="src/main.ts"-import {- CreateClaimRequestBuilder,- CreatePoolRequestBuilder,- CreateTemplateRequestBuilder,- CyclopsClient,- CyclopsCredentials,- OsGymSandboxTemplateSpecBuilder,- OsGymSandboxWarmPoolSpecBuilder,- SandboxServiceBuilder,- SandboxTemplateRefBuilder,- VmTemplateBuilder,- type Claim,- type CyclopsConfiguration,- type HttpClient,- type HttpRequest,- type HttpResponse,- uniffiInitAsync,-} from '@trycua/fleet/browser';--const IMAGE =- 'public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04' +- '@sha256:c1e601dbb748fdc467c663136f7592e308a91a3c19c309b75261544432826a57';-const BASE_URL = import.meta.env.VITE_CUA_FLEET_BASE_URL ?? 'https://run.cua.ai';-const TOKEN_URL =- import.meta.env.VITE_CUA_TOKEN_URL ??- 'https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token';-const CLIENT_ID = requiredEnv('VITE_CUA_CLIENT_ID');-const CLIENT_SECRET = requiredEnv('VITE_CUA_CLIENT_SECRET');-const POOL_NAME = requiredEnv('VITE_CUA_POOL_NAME');-const TEMPLATE_NAME = `${POOL_NAME}-template`;--function requiredEnv(name: string): string {- const value = import.meta.env[name];- if (!value) throw new Error(`Missing environment variable: ${name}`);- return value;-}--function screenshotBase64(responseBody: ArrayBuffer): string {- const text = new TextDecoder().decode(responseBody);- const dataLine = text.split('\n').find((line) => line.startsWith('data: '));- if (!dataLine) throw new Error(`No screenshot data frame: ${text.slice(0, 200)}`);-- const payload = JSON.parse(dataLine.slice(6));- if (!payload.success) throw new Error(payload.error ?? 'Screenshot failed');-- const encoded = payload.image_data ?? payload.result?.image_data;- if (typeof encoded !== 'string') throw new Error('Screenshot response has no image data');- return encoded;-}--function pngBlob(encoded: string): Blob {- const bytes = Uint8Array.from(atob(encoded), (character) => character.charCodeAt(0));- return new Blob([bytes], { type: 'image/png' });-}--class FetchHttpClient implements HttpClient {- async execute(request: HttpRequest, asyncOpts_?: { signal: AbortSignal }): Promise<HttpResponse> {- const timeoutSignal = request.timeoutSecs- ? AbortSignal.timeout(Number(request.timeoutSecs) * 1_000)- : undefined;- const response = await fetch(request.url, {- method: request.method,- headers: request.headers.map(({ name, value }) => [name, value] as [string, string]),- body: request.body,- signal: asyncOpts_?.signal ?? timeoutSignal,- redirect: 'manual',- });- return {- status: response.status,- headers: [...response.headers].map(([name, value]) => ({ name, value })),- body: await response.arrayBuffer(),- };- }-}--await uniffiInitAsync();--const configuration: CyclopsConfiguration = {- baseUrl: BASE_URL,- tokenUrl: TOKEN_URL,- credentials: new CyclopsCredentials(CLIENT_ID, CLIENT_SECRET),- poolPollIntervalMs: 5_000n,- poolPollLimit: 120,- claimPollIntervalMs: 5_000n,- claimPollLimit: 120,-};-const client = CyclopsClient.connect(configuration, new FetchHttpClient()) as CyclopsClient;--let claim: Claim | undefined;-try {- const serverService = new SandboxServiceBuilder().name('server').targetPort(8000).build();- const mcpService = new SandboxServiceBuilder().name('mcp').targetPort(3000).build();- const vm = new VmTemplateBuilder()- .containerDiskImage(IMAGE)- .cpuCores(4)- .memory('4Gi')- .services([serverService, mcpService])- .build();- const templateSpec = new OsGymSandboxTemplateSpecBuilder().vmTemplate(vm).build();- const templateRef = new SandboxTemplateRefBuilder().name(TEMPLATE_NAME).build();- const poolSpec = new OsGymSandboxWarmPoolSpecBuilder()- .replicas(1)- .sandboxTemplateRef(templateRef)- .build();-- const pool = await client.reconcilePool(- new CreatePoolRequestBuilder().namespace(POOL_NAME).spec(poolSpec).build()- );- const template = await client.reconcileTemplate(- new CreateTemplateRequestBuilder()- .namespace(POOL_NAME)- .name(TEMPLATE_NAME)- .spec(templateSpec)- .build()- );-- console.log(`Reconciled pool ${pool.metadata.name} with template ${template.metadata.name}`);-- claim = await client.createClaim(new CreateClaimRequestBuilder().pool(pool).build());- console.log(`Claim: ${claim.metadata.namespace}/${claim.metadata.name}`);- const sandbox = await client.waitClaim(claim);-- const requestBody = await new Blob([JSON.stringify({ command: 'screenshot' })]).arrayBuffer();- const response = await client.serviceRequest(sandbox, 'server', '/cmd', {- method: 'POST',- url: 'https://service.invalid/cmd',- headers: [{ name: 'content-type', value: 'application/json' }],- body: requestBody,- timeoutSecs: 60n,- });- if (response.status < 200 || response.status >= 300) {- throw new Error(`Screenshot request failed with HTTP ${response.status}`);- }-- const image = document.querySelector<HTMLImageElement>('#screenshot');- if (!image) throw new Error('Missing #screenshot image element');- image.src = URL.createObjectURL(pngBlob(screenshotBase64(response.body)));-} finally {- try {- // Release the claim but leave the reusable pool warm.- if (claim) await client.deleteClaim(claim);- } finally {- client.uniffiDestroy();- }-}-```--Replace `index.html` with a minimal screenshot page:--```html title="index.html"-<!doctype html>-<html lang="en">- <head>- <meta charset="UTF-8" />- <meta name="viewport" content="width=device-width, initial-scale=1.0" />- <title>Fleet screenshot</title>- </head>- <body>- <h1>Fleet sandbox screenshot</h1>- <img id="screenshot" alt="Fleet sandbox desktop" />- <script type="module" src="/src/main.ts"></script>- </body>-</html>-```--Start the development server and open the printed URL:--```bash-npm run dev-```--The browser SDK authenticates the Fleet API request, routes `POST /cmd` through-the named `server` service, decodes the computer-server event-stream response,-and displays the PNG. The pool also exposes the Cua Driver MCP endpoint as the-`mcp` service on port `3000`, matching the service used by the signed-service-URL guide.-- </Tab>-</Tabs>--## Keep or delete the pool--Both examples release only the claim, so the one-replica pool remains warm for-the next task and continues consuming capacity. Each run creates a new claim;-the logged namespace and claim name identify it if cleanup is interrupted.-Copy results out before claim release. Reusing the pool does not guarantee the-same VM or preserve files from the previous claim.--The `@trycua/[email protected]` SDK does not expose `pool.apply`. Instead,-`reconcilePool()` and `reconcileTemplate()` are the lower-level UniFFI-reconciliation primitives that Python `Pool.apply` delegates to internally.-They do not provide `Pool.apply`'s request derivation, validation, ownership,-rollback, or cleanup. Each method looks up its named resource, updates the-existing resource's specification, or creates the resource when the lookup-returns HTTP 403 or 404. Calling both methods lets you rerun the complete example-without maintaining separate get-or-create branches. Use reconciliation only-when this application owns the pool and template configuration.--To use a pool managed by another process or Terraform, replace both-reconciliation calls and their resource-specific log statements with a lookup:--```ts-const pool = await client.getPool(POOL_NAME);-```--Keep the `createClaim`, `waitClaim`, and `deleteClaim` flow. This lookup does not-create or reconfigure the pool. Avoid `Sandbox.suspend` or `Sandbox.resume`-from other SDKs as a way to pause one Fleet claim: scaling shared capacity is-not a per-claim operation.--`client.uniffiDestroy()` only disposes of the local client. Remote claim release-requires `deleteClaim()`. The `finally` blocks attempt that release even if-claim readiness or the screenshot fails, provided `createClaim()` returned the-claim. An interrupted process or a lost create response still needs inventory-inspection; see [Recover interrupted cleanup](/how-to-guides/sandbox/troubleshoot-fleet-pools#recover-interrupted-cleanup).--To remove a pool you own permanently, retain its `pool` value and call the-following while the client is still open, after every user has released their-claims:--```ts-await client.deletePool(pool);-```--Pool deletion also deletes its namespace, including remaining templates and-claims. Do not use it as per-task cleanup for a shared pool. The examples leave-the pool in place if template reconciliation or later work fails; inspect what-exists before deciding whether to repair or remove a dedicated pool.--Pool names are globally unique across Cua accounts. For a confirmed namespace-collision, choose another pool name; changing the claim name does not resolve-it. HTTP 403 can also indicate a payment requirement, authorization, or a-template policy denial. Read the failing operation and response body before-choosing a fix in [Troubleshoot Fleet pools and claims](/how-to-guides/sandbox/troubleshoot-fleet-pools).--## Use autoscaling instead of one replica--Replace `.replicas(1)` with an autoscaling policy and omit `replicas`:--```ts-import { WarmPoolAutoscalingBuilder } from '@trycua/fleet/node';--const autoscaling = new WarmPoolAutoscalingBuilder()- .minPoolSize(0)- .initialPoolSize(2)- .maxPoolSize(10)- .build();--const poolSpec = new OsGymSandboxWarmPoolSpecBuilder()- .autoscaling(autoscaling)- .sandboxTemplateRef(templateRef)- .build();-```--Use the matching `@trycua/fleet/browser` import in browser code. With a minimum-size of zero, the first claim after an idle period cold-starts a sandbox.diff --git a/docs/content/docs/how-to-guides/sandbox/expire-pools-and-claims.mdx b/docs/content/docs/how-to-guides/sandbox/expire-pools-and-claims.mdxindex cf21bc75ad..c24081fbe0 100644--- a/docs/content/docs/how-to-guides/sandbox/expire-pools-and-claims.mdx+++ b/docs/content/docs/how-to-guides/sandbox/expire-pools-and-claims.mdx@@ -13,7 +13,7 @@ claim lifecycle deadlines, normal claim release, pool deletion, and platformpolicies can still end resources.This guide assumes a pool created as in-[Create a sandbox pool with Python](/how-to-guides/sandbox/create-pool-with-python).+[Create Fleet capacity](/how-to-guides/sandbox/create-fleet-capacity).## Expire a pooldiff --git a/docs/content/docs/how-to-guides/sandbox/images.mdx b/docs/content/docs/how-to-guides/sandbox/images.mdxindex d1d73c71ff..dff2b12af2 100644--- a/docs/content/docs/how-to-guides/sandbox/images.mdx+++ b/docs/content/docs/how-to-guides/sandbox/images.mdx@@ -13,7 +13,7 @@ For hosted execution, follow [Choose a Fleet image](/how-to-guides/sandbox/choosThe local builder steps below do not publish a Fleet artifact or run during a claim.<Callout type="warn">- **SDK builder customization is local-only in `cua-sandbox` 0.4.3.** `apt_install()`,+ **SDK builder customization is local-only in `cua-sandbox` 0.7.0.** `apt_install()`,`pip_install()`, `env()`, `run()`, `copy()` and the other builder methods are applied when youboot the image locally (`local=True`). Fleet runs a prebuilt registry artifact and rejects acustomized one with `NotImplementedError: Fleet cloud supports registry images with optional@@ -150,7 +150,7 @@ Image.linux().expose(8080).expose(5432)```<Callout type="warn">- In 0.4.3, bare-metal QEMU forwards exposed ports at startup and reports their host ports in+ In 0.7.0, bare-metal QEMU forwards exposed ports at startup and reports their host ports in`sb.exposed_ports`. Other local backends can differ. Fleet creates named services instead.`expose()` does not make `tunnel.forward()` available on every transport; see [ports andtransports](/reference/sandbox-sdk/runtime-support#ports-and-transports).diff --git a/docs/content/docs/how-to-guides/sandbox/manage-local-lifecycle.mdx b/docs/content/docs/how-to-guides/sandbox/manage-local-lifecycle.mdxindex 851f33e004..41049370e2 100644--- a/docs/content/docs/how-to-guides/sandbox/manage-local-lifecycle.mdx+++ b/docs/content/docs/how-to-guides/sandbox/manage-local-lifecycle.mdx@@ -10,7 +10,7 @@ These patterns run on your own machine with `local=True`. Choose abefore running them. They are operation patterns, not a complete installation tutorial.For the ownership model, read [Sandbox lifecycle](/concepts/sandbox-lifecycle).-For Fleet, use [Create a sandbox pool with Python](/how-to-guides/sandbox/create-pool-with-python):+For Fleet, use [Create Fleet capacity](/how-to-guides/sandbox/create-fleet-capacity):releasing a claim and deleting pool capacity are separate operations.## Create and auto-destroy a sandboxdiff --git a/docs/content/docs/how-to-guides/sandbox/meta.json b/docs/content/docs/how-to-guides/sandbox/meta.jsonindex 8e80aacb6a..38ca4ec765 100644--- a/docs/content/docs/how-to-guides/sandbox/meta.json+++ b/docs/content/docs/how-to-guides/sandbox/meta.json@@ -1,26 +1,36 @@{"title": "Sandbox","pages": [+ "---Cua Fleets: Set up---","set-up-fleet-credentials","choose-an-image",- "manage-local-lifecycle",+ "---Cua Fleets: Create and connect---","configure-pool-with-terraform",- "create-pool-with-python",- "create-pool-with-typescript",- "run-cursor-cloud-agent-on-fleet",- "run-openai-agents-api-on-cloud-fleet",+ "create-fleet-capacity",+ "claim-a-sandbox",+ "---Cua Fleets: Use the computer---",+ "control-the-desktop-with-cua-driver",+ "tunneling",+ "share-service-with-signed-url",+ "secrets",+ "---Cua Fleets: Operate---","expire-pools-and-claims",+ "recover-first-cloud-fleet","troubleshoot-fleet-pools",+ "---Cua Fleets: Use Fleets with---",+ "run-openai-agents-api-on-cloud-fleet",+ "run-cursor-cloud-agent-on-fleet","run-openclaw-on-cloud-fleet","run-omarchy-on-cloud-fleet","connect-to-omarchy-with-novnc",- "secrets",- "scale-out",- "tunneling",- "share-service-with-signed-url",- "images",+ "minecraft",+ "---Cua Fleets: Images---","prepare-and-reference-a-fleet-image",+ "---Local Sandboxes: Create and use---",+ "manage-local-lifecycle","interactive-shell",- "minecraft"+ "scale-out",+ "---Local Sandboxes: Images---",+ "images"]}diff --git a/docs/content/docs/how-to-guides/sandbox/minecraft.mdx b/docs/content/docs/how-to-guides/sandbox/minecraft.mdxindex 89dd192fb0..9aae9195d8 100644--- a/docs/content/docs/how-to-guides/sandbox/minecraft.mdx+++ b/docs/content/docs/how-to-guides/sandbox/minecraft.mdx@@ -10,11 +10,11 @@ Minecraft exercises almost everything a Windows sandbox can do: it needs interneThe timings, guest hardware, graphics behavior, and deployment errors below areobservations from this recipe's environment. They are not a certification of everyFleet deployment or local host. The [runtime support reference](/reference/sandbox-sdk/runtime-support)-separates those observations from the released 0.4.3 image and transport contracts.+separates those observations from the released 0.7.0 image and transport contracts.## Before you start-- **cua-sandbox 0.4.3** for the examples below, including the explicit Fleet pool and claim workflow. The local recipe was originally developed against 0.3.3; its recorded timings and guest behavior are observations from that environment, not a new end-to-end test of 0.4.3.+- **cua-sandbox 0.7.0** for the examples below, including the explicit Fleet pool and claim workflow. The local recipe was originally developed against 0.3.3; its recorded timings and guest behavior are observations from that environment, not a new end-to-end test of 0.7.0.- **A host with hardware virtualisation** for the local path — a Linux x86_64 machine with `/dev/kvm`, or an Intel Mac. This guide passes `-cpu host`, which QEMU only accepts with KVM or HVF. An x86_64 guest on Apple Silicon runs under TCG emulation, where `-cpu host` is rejected outright. The Fleet path runs there instead, including the game, with the one extra environment variable described in the Fleet section below.- **A Microsoft account that owns Minecraft Java Edition.** Signing in uses Microsoft device authorization, so one step in the middle is manual: a code appears inside the sandbox and you approve it in your own browser.- **A vision-capable LLM endpoint** for the agent loop.@@ -63,7 +63,7 @@ A warm boot takes about 30 seconds. `exposed_ports` maps each exposed guest port<Callout type="warn">**Read the port from `sb.exposed_ports` on this bare-metal QEMU path.**`sb.tunnel.forward(3000)` raises `NotImplementedError: HTTPTransport does not support port forwarding`- on the local HTTP transport in 0.4.3. This runtime picks a host port at boot and+ on the local HTTP transport in 0.7.0. This runtime picks a host port at boot andsaves the mapping with the sandbox state so a later `Sandbox.connect()` can readit back. The property is backend-specific. Fleet publishes services instead;use an authenticated named-service request or the service URL as shown below.@@ -320,7 +320,7 @@ Everything above is a one-time cost, and none of it has to be repeated — leastDespite the name, `/disk/disk.img` is a **qcow2**, not a raw image. The puller looks for exactly `disk/disk.img` or `./disk/disk.img` inside the layer tarball and caches whatever it finds under `~/.cua/cua-sandbox/images/container-disks/`. Nothing reads the extension — it is a KubeVirt convention.`Sandbox.snapshot()` is not a substitute for publishing a containerDisk. In-`cua-sandbox` 0.4.3, it is not implemented for local sandboxes or the current Fleet+`cua-sandbox` 0.7.0, it is not implemented for local sandboxes or the current Fleetcreation paths. The package's legacy cloud snapshot code does not enable thisworkflow. See [image customization support](/reference/sandbox-sdk/runtime-support#image-customization).@@ -430,7 +430,7 @@ IMAGE = Image.from_registry(REF, os_type='windows', kind='vm').expose(3000)`IMAGE` is then a drop-in replacement for `Image.windows().expose(3000)` in both snippets earlier in this guide — the local `Sandbox.create(..., local=True, runtime=QEMURuntime(...))` call and the Fleet one. Nothing else changes: the same `EXTRA_ARGS` locally, the same agent loop, and on Fleet the same `GALLIUM_DRIVER=softpipe`.<Callout type="warn">- A Fleet pool claim carries `FleetTransport`, which does not implement `sb.tunnel.forward(3000)` in 0.4.3. Image-based `Sandbox.ephemeral()` uses a pool claim too, and `Sandbox.create(image)` requires an explicitly named pool. For HTTP requests, use `sb.services.request('port-3000', method='GET', path='/healthz')`. A streaming MCP client instead needs the service URL and authentication shown below.+ A Fleet pool claim carries `FleetTransport`, which does not implement `sb.tunnel.forward(3000)` in 0.7.0. Image-based `Sandbox.ephemeral()` uses a pool claim too, and `Sandbox.create(image)` requires an explicitly named pool. For HTTP requests, use `sb.services.request('port-3000', method='GET', path='/healthz')`. A streaming MCP client instead needs the service URL and authentication shown below.</Callout>Booted locally, that image printed `Image(windows/registry:latest, kind=vm, ...)`, came up on the first try, and had everything in it: `instances\1.20.1`, `java\java-runtime-gamma`, Mesa's `opengl32.dll` beside `javaw.exe`, `minecraft-1.20.1-client.jar`, `MaxMemAlloc=2048` — and `Test-Path C:\mc\prismw\accounts.json` returning `False`. Opening Prism shows the Quick Setup account page and *No accounts added!*, which is what a correctly-built image looks like.@@ -453,7 +453,7 @@ The image and the agent loop are identical on Fleet. Two things change: there is`.expose(3000)` becomes a Fleet **service** named `port-3000`. Configure[Fleet pool credentials](/reference/cua-cli/authentication#fleet-pools-need-their-own-credentials)-before running this `cua-sandbox` 0.4.3 example. It creates a dedicated pool with a+before running this `cua-sandbox` 0.7.0 example. It creates a dedicated pool with aunique name and claims a sandbox. The proxy URL uses the returned namespace andbound sandbox name, not the claim name. The MCP client sends a bearer token;the URL alone does not grant access.diff --git a/docs/content/docs/how-to-guides/sandbox/prepare-and-reference-a-fleet-image.mdx b/docs/content/docs/how-to-guides/sandbox/prepare-and-reference-a-fleet-image.mdxindex 05cb77b03d..3071193848 100644--- a/docs/content/docs/how-to-guides/sandbox/prepare-and-reference-a-fleet-image.mdx+++ b/docs/content/docs/how-to-guides/sandbox/prepare-and-reference-a-fleet-image.mdx@@ -8,12 +8,12 @@ import { Callout } from 'fumadocs-ui/components/callout';Fleet does not build a sandbox environment from the full SDK image-builder surface. Instead, Fleet expects a **prebuilt OCI artifact** that already carries the bootable guest image for the pool.<Callout type="info">- Configure [Fleet pool credentials](/reference/cua-cli/authentication#fleet-pools-need-their-own-credentials) before running the SDK example. The image-based `Sandbox.ephemeral()` path in `cua-sandbox` 0.4.3 accepts only the default region, `us-east-1`.+ Configure [Fleet pool credentials](/reference/cua-cli/authentication#fleet-pools-need-their-own-credentials) before running the SDK example. The image-based `Sandbox.ephemeral()` path in `cua-sandbox` 0.7.0 accepts only the default region, `us-east-1`.</Callout>## Before you start-This guide uses `cua-sandbox` 0.4.3 through `cua` 0.1.6. Choose a bootable guest+This guide uses `cua-sandbox` 0.7.0 through `cua` 0.1.6. Choose a bootable guestartifact compatible with your Fleet deployment and a registry that deploymentcan pull from. SDK acceptance does not establish registry access or successful boot.@@ -99,7 +99,7 @@ print(response.text)The image-based `Sandbox.ephemeral()` example creates a temporary pool and claimand uses the same `FleetTransport` as `Pool.claim()` and `Sandbox.create(pool=...)`.It does not create a localhost listener, and that transport does not implement-`tunnel.forward()` in 0.4.3. See [ports and transports](/reference/sandbox-sdk/runtime-support#ports-and-transports).+`tunnel.forward()` in 0.7.0. See [ports and transports](/reference/sandbox-sdk/runtime-support#ports-and-transports).## Related pagesdiff --git a/docs/content/docs/how-to-guides/sandbox/recover-first-cloud-fleet.mdx b/docs/content/docs/how-to-guides/sandbox/recover-first-cloud-fleet.mdxnew file mode 100644index 0000000000..7a6edee82e--- /dev/null+++ b/docs/content/docs/how-to-guides/sandbox/recover-first-cloud-fleet.mdx@@ -0,0 +1,31 @@+---+title: Recover an interrupted first Fleet tutorial+description: Delete the dedicated pool from Your first Cloud Fleet without repeating its workload.+---++Use this guide only when+[Your first Cloud Fleet](/tutorials/your-first-cloud-fleet) stopped after it+printed a pool name but before you confirmed deletion. Do not rerun the+tutorial to recover a handle. Creating another pool does not clean up the+original capacity.++## Delete the recorded pool++1. Restore valid Fleet credentials for the same account that created the pool.+2. Copy the exact `first-fleet-...` name from the tutorial output.+3. Open [Fleet](https://run.cua.ai), find that exact pool, and confirm that it+ belongs to the interrupted tutorial run.+4. Delete the pool. This requests deletion of its dedicated namespace,+ template, claims, and computer capacity.+5. Refresh the account inventory until the exact pool name is absent.++An accepted deletion request can precede final removal. Until the pool is+absent, its capacity can continue to incur usage charges. A `403` response does+not prove absence; verify that you are using the original account and have+permission to inspect the pool.++If the name was not printed, the create response was interrupted, or the pool's+ownership is uncertain, follow+[Recover interrupted cleanup](/how-to-guides/sandbox/troubleshoot-fleet-pools#recover-interrupted-cleanup).+That procedure covers inventory-based recovery without creating or reconciling+resources.diff --git a/docs/content/docs/how-to-guides/sandbox/run-cursor-cloud-agent-on-fleet.mdx b/docs/content/docs/how-to-guides/sandbox/run-cursor-cloud-agent-on-fleet.mdxindex 93f1ee8d08..0bded04725 100644--- a/docs/content/docs/how-to-guides/sandbox/run-cursor-cloud-agent-on-fleet.mdx+++ b/docs/content/docs/how-to-guides/sandbox/run-cursor-cloud-agent-on-fleet.mdx@@ -314,7 +314,7 @@ capacity or leave workers and claims orphaned.## Related documentation-- [Create a sandbox pool with Python](/how-to-guides/sandbox/create-pool-with-python)+- [Create Fleet capacity](/how-to-guides/sandbox/create-fleet-capacity)- [Pass secrets into a sandbox](/how-to-guides/sandbox/secrets)- [Run sandboxes in parallel](/how-to-guides/sandbox/scale-out)- [Cursor Self-Hosted Machines](https://cursor.com/docs/cloud-agent/self-hosted)diff --git a/docs/content/docs/how-to-guides/sandbox/run-omarchy-on-cloud-fleet.mdx b/docs/content/docs/how-to-guides/sandbox/run-omarchy-on-cloud-fleet.mdxindex 5414f80884..928307775f 100644--- a/docs/content/docs/how-to-guides/sandbox/run-omarchy-on-cloud-fleet.mdx+++ b/docs/content/docs/how-to-guides/sandbox/run-omarchy-on-cloud-fleet.mdx@@ -39,7 +39,7 @@ You need:- Python `>=3.11,<3.14`;- [`uv`](https://docs.astral.sh/uv/);-- `cua-sandbox==0.4.3`; and+- `cua-sandbox==0.7.0`; and- a Fleet access token or OAuth client credentials that can manage pools.The Fleet-verified public image reference is:@@ -86,7 +86,7 @@ Save this script as `run_omarchy_fleet.py`:# /// script# requires-python = ">=3.11,<3.14"# dependencies = [-# "cua-sandbox==0.4.3",+# "cua-sandbox==0.7.0",# ]# ///diff --git a/docs/content/docs/how-to-guides/sandbox/run-openai-agents-api-on-cloud-fleet.mdx b/docs/content/docs/how-to-guides/sandbox/run-openai-agents-api-on-cloud-fleet.mdxindex 05febc0a43..0b8386d558 100644--- a/docs/content/docs/how-to-guides/sandbox/run-openai-agents-api-on-cloud-fleet.mdx+++ b/docs/content/docs/how-to-guides/sandbox/run-openai-agents-api-on-cloud-fleet.mdx@@ -230,7 +230,7 @@ and controller timeouts accordingly.## Related documentation-- [Create a sandbox pool with Python](/how-to-guides/sandbox/create-pool-with-python)+- [Create Fleet capacity](/how-to-guides/sandbox/create-fleet-capacity)- [Pass secrets into a sandbox](/how-to-guides/sandbox/secrets)- [Run sandboxes in parallel](/how-to-guides/sandbox/scale-out)- [OpenAI self-hosted sandboxes](https://developers.openai.com/api/docs/guides/agents-api/environments/self-hosted)diff --git a/docs/content/docs/how-to-guides/sandbox/run-openclaw-on-cloud-fleet.mdx b/docs/content/docs/how-to-guides/sandbox/run-openclaw-on-cloud-fleet.mdxindex 72172ad80d..44e9cd9f8c 100644--- a/docs/content/docs/how-to-guides/sandbox/run-openclaw-on-cloud-fleet.mdx+++ b/docs/content/docs/how-to-guides/sandbox/run-openclaw-on-cloud-fleet.mdx@@ -268,4 +268,4 @@ await pool.delete()```For reusable warm capacity, omit the deletion and set a suitable pool and claim-TTL. See [Create a reusable sandbox pool with Python](/how-to-guides/sandbox/create-pool-with-python).+TTL. See [Create Fleet capacity](/how-to-guides/sandbox/create-fleet-capacity).diff --git a/docs/content/docs/how-to-guides/sandbox/scale-out.mdx b/docs/content/docs/how-to-guides/sandbox/scale-out.mdxindex 5911606bf8..cdb18bf484 100644--- a/docs/content/docs/how-to-guides/sandbox/scale-out.mdx+++ b/docs/content/docs/how-to-guides/sandbox/scale-out.mdx@@ -7,10 +7,12 @@ import { Callout } from 'fumadocs-ui/components/callout';This guide runs local sandboxes with `local=True`. Because `Sandbox.ephemeral` and `Sandbox.create` are async, you can **run many local sandboxes at the same time** using `asyncio`.-For hosted Fleet capacity, follow [Create a sandbox pool with Python](/how-to-guides/sandbox/create-pool-with-python) to create a pool and claim sandboxes for your tasks.+For hosted Fleet capacity, follow [Create Fleet capacity](/how-to-guides/sandbox/create-fleet-capacity)+to create a pool, then [claim Sandboxes](/how-to-guides/sandbox/claim-a-sandbox) for your tasks.<Callout type="info">- Every local sandbox consumes host CPU, memory, and disk. Start with low concurrency and increase it only after observing host resource use.+ Every local sandbox consumes host CPU, memory, and disk. Start with low concurrency and increase+ it only after observing host resource use.</Callout>## Run a fixed set concurrently@@ -36,7 +38,7 @@ asyncio.run(main())## Cap the number of concurrent sandboxes-Use an `asyncio.Semaphore` when you need *rate limiting*.+Use an `asyncio.Semaphore` when you need _rate limiting_.```pythonimport asynciodiff --git a/docs/content/docs/how-to-guides/sandbox/share-service-with-signed-url.mdx b/docs/content/docs/how-to-guides/sandbox/share-service-with-signed-url.mdxindex 6abe9bbec9..8335a28317 100644--- a/docs/content/docs/how-to-guides/sandbox/share-service-with-signed-url.mdx+++ b/docs/content/docs/how-to-guides/sandbox/share-service-with-signed-url.mdx@@ -1,6 +1,6 @@---title: Share a sandbox service with a signed URL-description: Create, list, and revoke time-limited public URLs for sandbox services with the TypeScript Fleet SDK.+description: Create, list, and revoke time-limited public URLs for sandbox services with the Fleet SDKs.---import { Callout } from 'fumadocs-ui/components/callout';@@ -21,17 +21,17 @@ the bound sandbox.- A Fleet pool whose template exposes the service you want to share.- A bound sandbox claim. The signed URL does not create or keep a claim alive.- OAuth client credentials with permission to manage the claim.-- The published `@trycua/fleet` 0.1.1 TypeScript package and a Node.js environment+- The published `@trycua/fleet` 0.1.2 TypeScript package and a Node.js environmentwith `fetch` and `AbortSignal.timeout`.-The published Python `cua-sandbox` 0.4.3 package exposes-`sandbox.services.request()`, but does not expose `create_signed_url()`,-`list_signed_urls()`, or `revoke_signed_url()`. Use the TypeScript API below-for signed URLs. See the [service reference](/reference/sandbox-sdk/interfaces#services).+The published Python `cua-sandbox` 0.7.0 package also exposes+`sandbox.services.create_signed_url()`, `list_signed_urls()`, and+`revoke_signed_url()`. This guide uses the TypeScript API below. See the+[service reference](/reference/sandbox-sdk/interfaces#services) for the Python+signatures.-If you do not have a pool yet, create one with-[Python](/how-to-guides/sandbox/create-pool-with-python) or-[TypeScript](/how-to-guides/sandbox/create-pool-with-typescript). The service+If you do not have a pool yet, follow+[Create Fleet capacity](/how-to-guides/sandbox/create-fleet-capacity). The servicename passed to the signed URL API must match a service declared on that pool'stemplate.@@ -65,7 +65,7 @@ releasing the claim.Install the Fleet SDK and a TypeScript runner:```bash-npm install @trycua/[email protected]+npm install @trycua/[email protected]npm install --save-dev tsx typescriptnpm pkg set type=module```@@ -195,6 +195,6 @@ lifecycle.### The SDK says signed service URLs are unavailableConfirm that the Fleet environment has signed service URLs configured. The-TypeScript `@trycua/fleet` 0.1.1 package includes the create, list, and revoke-operations, but package availability does not enable the feature on the server.-The Python `cua-sandbox` 0.4.3 service interface does not include these methods.+TypeScript `@trycua/fleet` 0.1.2 and Python `cua-sandbox` 0.7.0 include the+create, list, and revoke operations, but package availability does not enable+the feature on the server.diff --git a/docs/content/docs/how-to-guides/sandbox/troubleshoot-fleet-pools.mdx b/docs/content/docs/how-to-guides/sandbox/troubleshoot-fleet-pools.mdxindex a451bacf4b..7dd57c78ee 100644--- a/docs/content/docs/how-to-guides/sandbox/troubleshoot-fleet-pools.mdx+++ b/docs/content/docs/how-to-guides/sandbox/troubleshoot-fleet-pools.mdx@@ -5,8 +5,8 @@ description: Diagnose Fleet pool errors and recover interrupted claim or pool clUse this guide when a Fleet pool or claim fails to start, an existing poolcannot be reused, or a process exits before releasing its resources. It applies-to the [Python pool guide](/how-to-guides/sandbox/create-pool-with-python) and-[TypeScript pool guide](/how-to-guides/sandbox/create-pool-with-typescript).+to [Create Fleet capacity](/how-to-guides/sandbox/create-fleet-capacity) and+[Claim a Sandbox](/how-to-guides/sandbox/claim-a-sandbox).## Identify the failing operation@@ -85,7 +85,7 @@ anything. A timestamp or similar-looking name alone is not proof of ownership.For scripted recovery, initialize the TypeScript client using only the imports,configuration, and `CyclopsClient.connect(...)` setup from the-[Node.js example](/how-to-guides/sandbox/create-pool-with-typescript). Do not run+[Node.js example](/how-to-guides/sandbox/create-fleet-capacity). Do not runits reconciliation or claim-creation block. The following snippets use thatopen `client` and the exact `POOL_NAME` you recorded.@@ -114,28 +114,23 @@ if (remaining.some((item) => item.metadata.name === claimName)) {}```-If you own the entire pool and all users have finished, fetch and delete it:+If you own the entire Fleet and all users have finished, delete its namespace:```ts-const pool = await client.getPool(POOL_NAME);-await client.deletePool(pool);+await client.deleteNamespace(POOL_NAME);```-This deletes the pool namespace and its remaining resources, including other-claims and templates. Use this operation only for a pool you intend to remove-completely. In Python, the equivalent is+This deletes the namespace and its remaining resources, including pools,+claims, and templates. Use this operation only for a Fleet you intend to remove+completely. `deletePool(pool)` removes only the pool resource. In Python, the equivalent is`pool = await Pool.get(POOL_NAME)` followed by `await pool.delete()`.If the pool lookup returns 404 but namespace inventory still shows the exactdedicated namespace, inspect its remaining claims and templates. Once you have-confirmed that all remaining resources belong to the cleanup task, delete the-namespace directly:--```ts-await client.deleteNamespace(POOL_NAME);-```+confirmed that all remaining resources belong to the cleanup task, use the+same namespace deletion.-In `@trycua/[email protected]`, namespace deletion accepts an already-absent namespace+In `@trycua/[email protected]`, namespace deletion accepts an already-absent namespaceas success, so the same exact deletion can be retried after interruption.Close the local client with `client.uniffiDestroy()` in a `finally` block whenthe recovery script ends.diff --git a/docs/content/docs/how-to-guides/sandbox/tunneling.mdx b/docs/content/docs/how-to-guides/sandbox/tunneling.mdxindex 741b934845..7c602f3686 100644--- a/docs/content/docs/how-to-guides/sandbox/tunneling.mdx+++ b/docs/content/docs/how-to-guides/sandbox/tunneling.mdx@@ -4,7 +4,7 @@ description: Reach a sandbox service through a Fleet service request, a local st---Choose the connection method for your sandbox's transport. In `cua-sandbox`-0.4.3, local VM `HTTPTransport` and pool-backed `FleetTransport` do not implement+0.7.0, local VM `HTTPTransport` and pool-backed `FleetTransport` do not implement`sb.tunnel.forward()`. Use the supported paths below; see[Sandbox runtime support](/reference/sandbox-sdk/runtime-support#ports-and-transports)for the versioned transport contract.diff --git a/docs/content/docs/index.mdx b/docs/content/docs/index.mdxindex 00e443fe30..5a3d9fe58b 100644--- a/docs/content/docs/index.mdx+++ b/docs/content/docs/index.mdx@@ -13,8 +13,8 @@ import { Card, Cards } from 'fumadocs-ui/components/card';<Cards><Card title="Your first Cloud Fleet" href="/tutorials/your-first-cloud-fleet">- Provision a Cloud Fleet, claim an isolated Linux desktop, run a command, save a screenshot, and- delete the cloud resources when you finish.+ Provision a Cloud Fleet, claim an isolated Linux computer, transform a file, verify the result,+ and delete the cloud resources when you finish.</Card><Card title="Drive a real app — Cua Driver" href="/tutorials/drive-your-first-app">Run a background driver on macOS, Windows, or Linux so an agent can operate native GUI apps youdiff --git a/docs/content/docs/local-sandboxes.mdx b/docs/content/docs/local-sandboxes.mdxnew file mode 100644index 0000000000..687505918c--- /dev/null+++ b/docs/content/docs/local-sandboxes.mdx@@ -0,0 +1,26 @@+---+title: Local Sandboxes+description: Create and use isolated computers on your own hardware.+---++The Cua Sandbox SDK represents one isolated computer. In the local path, a+runtime on your own hardware creates and runs that computer; you do not need a+hosted Fleet pool or claim.++Start with [Create and manage a local Sandbox](/how-to-guides/sandbox/manage-local-lifecycle)+to choose a supported runtime, create a Sandbox, reconnect when needed, and+clean it up. Check [Sandbox runtime support](/reference/sandbox-sdk/runtime-support)+before choosing an operating system or image kind.++## Find the right page++| Your goal | Start here |+| ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |+| Create, reconnect to, or delete a local Sandbox | [Manage local Sandbox lifecycle](/how-to-guides/sandbox/manage-local-lifecycle) |+| Open an interactive terminal | [Open an interactive shell in a local Sandbox](/how-to-guides/sandbox/interactive-shell) |+| Run local jobs concurrently | [Run local Sandboxes in parallel](/how-to-guides/sandbox/scale-out) |+| Customize a local environment | [Build a local Sandbox image](/how-to-guides/sandbox/images) |+| Look up APIs and runtime limits | [Sandbox SDK reference](/reference/sandbox-sdk) and [Sandbox runtime support](/reference/sandbox-sdk/runtime-support) |++For managed cloud capacity, credentials, pools, claims, and guest service+routing, use [Cua Fleets](/cloud-fleets).diff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.jsonindex febf868a81..31b4afe0b3 100644--- a/docs/content/docs/meta.json+++ b/docs/content/docs/meta.json@@ -3,13 +3,17 @@"root": true,"pages": ["index",- "cloud-fleets",- "---Learn---","tutorials",+ "(cloud-fleets)",+ "(local-sandboxes)",+ "---Products---",+ "[Cua Driver](/how-to-guides/driver/install)",+ "[Cua CLI](/reference/cua-cli)",+ "[Lume](/how-to-guides/lume/install-lume)",+ "[Cua-Bench](/how-to-guides/cua-bench/run-a-task)",+ "---Browse by type---","concepts",- "---Connect---","use-cua-with",- "---Do---","how-to-guides","reference"]diff --git a/docs/content/docs/reference/cua-cli/cli-reference.mdx b/docs/content/docs/reference/cua-cli/cli-reference.mdxindex 7fc51fedc9..622df3da16 100644--- a/docs/content/docs/reference/cua-cli/cli-reference.mdx+++ b/docs/content/docs/reference/cua-cli/cli-reference.mdx@@ -9,7 +9,7 @@ import { Callout } from 'fumadocs-ui/components/callout';Cua cloud, manages sandboxes and images, drives a running machine one command ata time, and serves an MCP endpoint for AI assistants.-Documented against `cua-cli` **0.1.14**. Run `cua --version` for your installed+Documented against `cua-cli` **0.1.15**. Run `cua --version` for your installedversion, and `cua <command> --help` for the options your build accepts.## Installdiff --git a/docs/content/docs/reference/sandbox-sdk/image.mdx b/docs/content/docs/reference/sandbox-sdk/image.mdxindex d9843a574e..119e57e985 100644--- a/docs/content/docs/reference/sandbox-sdk/image.mdx+++ b/docs/content/docs/reference/sandbox-sdk/image.mdx@@ -3,7 +3,7 @@ title: Image referencedescription: "API reference for the Image class: the immutable, chainable image specification used to configure sandbox environments."----`Image` is an immutable, chainable image specification in `cua-sandbox` 0.4.3.+`Image` is an immutable, chainable image specification in `cua-sandbox` 0.7.0.Each builder method returns a new `Image` instance; the original is unchanged.Import it from `cua_sandbox`:@@ -19,7 +19,7 @@ environment variables, copied files, snapshot sources, or local disk paths.Exposed service ports are accepted. An OCI reference for Fleet must identify acompatible container disk; an arbitrary application container is not a VM disk.-In 0.4.3, the built-in registry mappings are `Image.linux()` with Ubuntu 24.04+In 0.7.0, the built-in registry mappings are `Image.linux()` with Ubuntu 24.04and `kind='vm'`, and `Image.windows()` with version `'2022'` and `kind='vm'`.Other descriptors require an explicit compatible registry image for Fleet.These mappings describe client image selection, not deployment certification.diff --git a/docs/content/docs/reference/sandbox-sdk/index.mdx b/docs/content/docs/reference/sandbox-sdk/index.mdxindex 80976cc15c..3960ecba3f 100644--- a/docs/content/docs/reference/sandbox-sdk/index.mdx+++ b/docs/content/docs/reference/sandbox-sdk/index.mdx@@ -11,19 +11,19 @@ for connection, claim, and capacity ownership.## Packages-This reference describes the published `cua-sandbox` 0.4.3 Python package and-`@trycua/fleet` 0.1.1 TypeScript package.+This reference describes the published `cua-sandbox` 0.7.0 Python package and+`@trycua/fleet` 0.1.2 TypeScript package.| Distribution | Import | Requirement | API || --- | --- | --- | --- |-| [`cua-sandbox` 0.4.3](https://pypi.org/project/cua-sandbox/0.4.3/) | `cua_sandbox` | Python `>=3.11,<3.14` | `Sandbox`, `Image`, `Pool`, `Template`, and interfaces |+| [`cua-sandbox` 0.7.0](https://pypi.org/project/cua-sandbox/0.7.0/) | `cua_sandbox` | Python `>=3.11,<3.14` | `Sandbox`, `Image`, `Pool`, `Template`, and interfaces || [`cua` 0.1.6](https://pypi.org/project/cua/0.1.6/) | `cua` | Python `>=3.12,<3.14` | Umbrella package; reexports `Sandbox` and `Image`, but not `Pool` |-| [`@trycua/fleet` 0.1.1](/reference/sandbox-sdk/typescript) | `@trycua/fleet/node` or `@trycua/fleet/browser` | Environment-specific WebAssembly entry point | Fleet client, resource types, and builders |+| [`@trycua/fleet` 0.1.2](/reference/sandbox-sdk/typescript) | `@trycua/fleet/node` or `@trycua/fleet/browser` | Environment-specific WebAssembly entry point | Fleet client, resource types, and builders |The Python Sandbox distribution can be installed independently:```bash-pip install cua-sandbox==0.4.3+pip install cua-sandbox==0.7.0```Its primary imports are:diff --git a/docs/content/docs/reference/sandbox-sdk/interfaces.mdx b/docs/content/docs/reference/sandbox-sdk/interfaces.mdxindex c8f1cd12aa..fef45031d6 100644--- a/docs/content/docs/reference/sandbox-sdk/interfaces.mdx+++ b/docs/content/docs/reference/sandbox-sdk/interfaces.mdx@@ -1,9 +1,9 @@---title: Sandbox interfaces reference-description: Python Sandbox computer-control, file, service, tunnel, and application interfaces in cua-sandbox 0.4.3.+description: Python Sandbox computer-control, file, service, tunnel, and application interfaces in cua-sandbox 0.7.0.----These interfaces are exposed by `Sandbox` in the published `cua-sandbox` 0.4.3+These interfaces are exposed by `Sandbox` in the published `cua-sandbox` 0.7.0package. A method's presence does not guarantee support by every transport.Fleet claims route computer-server operations through the selected namedservice; local and legacy transports have different capabilities.@@ -97,7 +97,7 @@ Requests forwarding for one or more sandbox ports or Android abstract socketsfrom the connected transport. Supports `await` and `async with`; context exitcloses the forwards.-In 0.4.3, the `FleetTransport` used by `Pool.claim()` does not implement+In 0.7.0, the `FleetTransport` used by `Pool.claim()` does not implement`tunnel.forward()`. Use `sb.services.request()` for authenticated HTTP requeststo a Fleet service. Local HTTP transports also do not implement this tunnelAPI; use `sb.exposed_ports` for ports forwarded at local startup.@@ -139,10 +139,19 @@ value is an `httpx.Response`. `method` is the HTTP method, `path` is the servicerequest path, `json` is an optional JSON body, and `headers` adds request headers.Transports without named service support raise `NotImplementedError`.-The released 0.4.3 `Services` interface has `request()` only. Signed service URL-creation is available in the [TypeScript Fleet client](/reference/sandbox-sdk/typescript#service-access);-`create_signed_url()`, `list_signed_urls()`, and `revoke_signed_url()` are not-part of this Python release.+The released 0.7.0 `Services` interface also manages signed Fleet service URLs:++```python+async def create_signed_url(+ name: str, *, expires_in_seconds: int, label: str | None = None+) -> SignedServiceURL: ...+async def list_signed_urls() -> list[SignedServiceURL]: ...+async def revoke_signed_url(signed_url: SignedServiceURL) -> None: ...+```++Transports without signed URL support raise `NotImplementedError`. A signed URL+is a bearer credential; see [Share a service with a signed URL](/how-to-guides/sandbox/share-service-with-signed-url)+for expiration and revocation guidance.## Filesdiff --git a/docs/content/docs/reference/sandbox-sdk/os-image-catalog.mdx b/docs/content/docs/reference/sandbox-sdk/os-image-catalog.mdxindex 14deee1db6..5a365b36c9 100644--- a/docs/content/docs/reference/sandbox-sdk/os-image-catalog.mdx+++ b/docs/content/docs/reference/sandbox-sdk/os-image-catalog.mdx@@ -3,21 +3,28 @@ title: OS and image catalogdescription: Sandbox operating systems, Linux distributions, desktop environments, window managers, and image registries.----Windows images do not include a Windows license. Bring your own valid licenses-covering your intended use, including the applicable hosting and virtualization-rights. An image being available or booting successfully does not establish-licensing eligibility. Bundled applications have their own license terms.+Windows images do not include a production or commercial Windows license. Bring+your own appropriate Microsoft license covering your intended use, including the+applicable hosting and virtualization rights. An image being available or booting+successfully does not establish licensing eligibility. Bundled applications have+their own license terms.<span id="hosted-fleet-images" /><span id="ubuntu-2404" />-| OS | Distribution / version / architecture | Desktop / window manager | Image kind / runtime | Registry image or source | Evidence / limits |-| ------- | ----------------------------------------------------------------------- | ------------------------------------------------ | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Linux | Ubuntu 24.04; artifact architecture not established by SDK mapping | Artifact-dependent; not specified by SDK mapping | Fleet containerDisk; local bare-metal QEMU | `public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04:main-38352d34` | `Image.linux()` mapping in `cua-sandbox` 0.4.3; versioned tag, not a digest pin. [SDK checks](/reference/sandbox-sdk/runtime-support#evidence-and-limits) establish selection, not a live pull, boot, or guest-service check. |-| Linux | Ubuntu 24.04 | XFCE runtime mapping | Local Docker container | `public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04:docker-latest` | Local container selector; mutable tag, not the Fleet VM disk |-| Linux | Omarchy (Arch Linux-based), amd64 | Hyprland / Wayland | Fleet containerDisk | `public.ecr.aws/k5j5w0x5/cua-omarchy-workspace@sha256:dc448dcc986f443980dfb3586f1b91d8699091ad96a74b369016535f0dbb0342` | Digest-pinned explicit registry image. The [Fleet recipe](/how-to-guides/sandbox/run-omarchy-on-cloud-fleet) reports boot verification and defines `server: 8000` (computer-server) and `mcp: 3000` (Cua Driver); it does not certify every operation or Hyprland configuration. |-| Linux | NixOS; release and architecture not recorded in the publication summary | StumpWM | Published candidate image | `public.ecr.aws/k5j5w0x5/cua-nixos-stumpwm:git-ee87f38043c043831a8761016015d6ef5ae783d9` | [Publication summary](https://github.com/trycua/cua/pull/3585) reports computer-server and Cua Driver included, guest tests and CI anonymous-pull checks passed. Component versions, service ports, and Fleet claim checks are not recorded there. Commit-named candidate tag, not a digest pin or `latest`; no built-in SDK mapping. |-| Linux | NixOS; release and architecture not recorded in the publication summary | Xfce / Xfwm4 | Published candidate image | `public.ecr.aws/k5j5w0x5/cua-nixos-xfce:git-ee87f38043c043831a8761016015d6ef5ae783d9` | [Publication summary](https://github.com/trycua/cua/pull/3585) reports computer-server and Cua Driver included, guest tests and CI anonymous-pull checks passed. Component versions, service ports, and Fleet claim checks are not recorded there. Commit-named candidate tag, not a digest pin or `latest`; no built-in SDK mapping. |-| Windows | Server 2022; artifact architecture not established by SDK mapping | Native Windows desktop | Fleet containerDisk; local Hyper-V or QEMU | `public.ecr.aws/k5j5w0x5/cua-windows-2022:main-bac7daa3` | `Image.windows()` mapping in `cua-sandbox` 0.4.3; Fleet selects EFI. Versioned tag, not a digest pin. [SDK checks](/reference/sandbox-sdk/runtime-support#evidence-and-limits) establish selection and firmware, not a live pull, boot, or guest-service check. |-| macOS | Sequoia 15 | Native macOS desktop | Local Lume VM | `ghcr.io/trycua/macos-sequoia-cua:latest` | Compatible Apple silicon host required; mutable tag; no built-in Fleet mapping |-| macOS | Tahoe 26 | Native macOS desktop | Local Lume VM | `ghcr.io/trycua/macos-tahoe-cua:latest` | Default `Image.macos()` version; compatible Apple silicon host required; mutable tag; no built-in Fleet mapping |+The built-in and local rows below are published client mappings generated from+the Sandbox source. A deployment-qualified row records a narrower result for one+immutable artifact; it does not change those client mappings.++{/* GENERATED:sandbox-image-catalog:start */}+| OS | Distribution / version / architecture | Desktop / window manager | Image kind / runtime | Registry image or source | Evidence / limits |+| --- | --- | --- | --- | --- | --- |+| Linux | Ubuntu 24.04; artifact architecture not established by SDK mapping | Artifact-dependent; not specified by SDK mapping | Fleet containerDisk; local bare-metal QEMU | `public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04:main-38352d34` | `Image.linux()` mapping in `cua-sandbox` 0.7.0; versioned tag, not a digest pin. [SDK checks](/reference/sandbox-sdk/runtime-support#evidence-and-limits) establish selection, not a live pull, boot, or guest-service check. |+| Linux | Ubuntu 24.04 | XFCE runtime mapping | Local Docker container | `public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04:docker-latest` | Local container selector; mutable tag, not the Fleet VM disk. |+| Linux | Omarchy 4.0.2-1 (Arch Linux-based), amd64 | Hyprland / Wayland | Fleet containerDisk | `public.ecr.aws/k5j5w0x5/cua-omarchy-workspace@sha256:dd09f70f8cd35eca7871dff000538302baad63688a3008803f2238492802d743` | Deployment qualification recorded boot and readiness for `server:8000` and `mcp:3000`. The guest contains `cua-computer-server` 0.3.46 with embedded Driver 0.22.2; direct Driver qualification used 0.26.1. These image-specific results do not change the published client mapping or certify every operation and desktop configuration. |+| Linux | NixOS; release and architecture not recorded in the publication summary | StumpWM | Published candidate image | `public.ecr.aws/k5j5w0x5/cua-nixos-stumpwm:git-ee87f38043c043831a8761016015d6ef5ae783d9` | [Publication summary](https://github.com/trycua/cua/pull/3585) reports computer-server and Cua Driver included, guest tests and CI anonymous-pull checks passed. Component versions, service ports, and Fleet claim checks are not recorded there. Commit-named candidate tag, not a digest pin or `latest`; no built-in SDK mapping. |+| Linux | NixOS; release and architecture not recorded in the publication summary | Xfce / Xfwm4 | Published candidate image | `public.ecr.aws/k5j5w0x5/cua-nixos-xfce:git-ee87f38043c043831a8761016015d6ef5ae783d9` | [Publication summary](https://github.com/trycua/cua/pull/3585) reports computer-server and Cua Driver included, guest tests and CI anonymous-pull checks passed. Component versions, service ports, and Fleet claim checks are not recorded there. Commit-named candidate tag, not a digest pin or `latest`; no built-in SDK mapping. |+| Windows | Server 2022; artifact architecture not established by SDK mapping | Native Windows desktop | Fleet containerDisk; local Hyper-V or QEMU | `public.ecr.aws/k5j5w0x5/cua-windows-2022:main-bac7daa3` | `Image.windows()` mapping in `cua-sandbox` 0.7.0; Fleet selects EFI. Versioned tag, not a digest pin. [SDK checks](/reference/sandbox-sdk/runtime-support#evidence-and-limits) establish selection and firmware, not a live pull, boot, or guest-service check. |+| macOS | Sequoia 15 | Native macOS desktop | Local Lume VM | `ghcr.io/trycua/macos-sequoia-cua:latest` | Compatible Apple silicon host required; mutable tag; no built-in Fleet mapping. |+| macOS | Tahoe 26 | Native macOS desktop | Local Lume VM | `ghcr.io/trycua/macos-tahoe-cua:latest` | Default `Image.macos()` version; compatible Apple silicon host required; mutable tag; no built-in Fleet mapping. |+{/* GENERATED:sandbox-image-catalog:end */}diff --git a/docs/content/docs/reference/sandbox-sdk/pool.mdx b/docs/content/docs/reference/sandbox-sdk/pool.mdxindex 668cae2cf3..3cc6d642fc 100644--- a/docs/content/docs/reference/sandbox-sdk/pool.mdx+++ b/docs/content/docs/reference/sandbox-sdk/pool.mdx@@ -1,9 +1,9 @@---title: Pool and claim reference-description: Python Fleet pool configuration, claim acquisition, cleanup, and resource types in cua-sandbox 0.4.3.+description: Python Fleet pool configuration, claim acquisition, cleanup, and resource types in cua-sandbox 0.7.0.----`Pool` and `Template` are exported by `cua_sandbox` 0.4.3. These APIs use Fleet+`Pool` and `Template` are exported by `cua_sandbox` 0.7.0. These APIs use Fleetcredentials independently of the legacy `CUA_API_KEY` flow. See[configuration and authentication](/reference/sandbox-sdk#configuration-and-authentication).@@ -152,6 +152,6 @@ reexported. A `ClaimSpec` constructor requires keyword argumentsthe latter three are `None`; `ttl_seconds_after_created` is optional. Buildersprovide named setters and `build()` for the types listed above.-These bindings come from the published `cua-fleet` 0.1.14 dependency, imported+These bindings come from the published `cua-fleet` 0.1.17 dependency, importedas `fleet_sdk`. Type availability describes the client schema; it does notestablish runtime or image support on a deployment.diff --git a/docs/content/docs/reference/sandbox-sdk/runtime-support.mdx b/docs/content/docs/reference/sandbox-sdk/runtime-support.mdxindex f6357c67b2..46053940e5 100644--- a/docs/content/docs/reference/sandbox-sdk/runtime-support.mdx+++ b/docs/content/docs/reference/sandbox-sdk/runtime-support.mdx@@ -3,9 +3,11 @@ title: Sandbox runtime supportdescription: Versioned image, runtime, customization, and transport support for the Sandbox SDK.----This reference describes the Python Sandbox SDK in `cua-sandbox` **0.4.3**, exported+{/* GENERATED:sandbox-package-facts:start */}+This reference describes the Python Sandbox SDK in `cua-sandbox` **0.7.0**, exportedby `cua` **0.1.6**. An accepted image specification or generated Fleet template isevidence of SDK behavior, not proof that a guest boots on every host or deployment.+{/* GENERATED:sandbox-package-facts:end */}## Operating systems and image kinds@@ -13,7 +15,7 @@ Local execution uses `local=True`. Fleet execution uses managed pools and claimsThe same guest OS can have different image formats, runtime requirements, andavailable operations on those two paths.-| Image input | Guest and kind | Local runtime selection | Fleet SDK acceptance in 0.4.3 | Verification boundary |+| Image input | Guest and kind | Local runtime selection | Fleet SDK acceptance in 0.7.0 | Verification boundary || --- | --- | --- | --- | --- || `Image.linux()` | Ubuntu 24.04 VM | Bare-metal QEMU; requires `qemu-system-x86_64` | Maps to a built-in registry artifact | Mapping and runtime selection checked; host and Fleet boot not tested here || `Image.linux(kind='container')` | Ubuntu 24.04 container | Docker | Rejected; no built-in Fleet mapping | Constructor and rejection checked; Docker image readiness not tested here |@@ -25,19 +27,21 @@ available operations on those two paths.| `Image.from_registry(...)` | Explicit guest OS and optional kind | Set `kind='vm'` or pass a compatible runtime when kind is unresolved | Registry reference accepted | Acceptance does not validate artifact contents, registry access, guest support, or readiness || `Image.from_file(...)` | Disk or ISO with explicit guest OS | Compatible local VM runtime | Rejected | Format and guest requirements depend on the runtime |-The built-in registry mappings in 0.4.3 are:+The built-in registry mappings in 0.7.0 are generated from the Sandbox package source:+{/* GENERATED:sandbox-builtin-mappings:start */}| Built-in image | Registry artifact || --- | --- || Ubuntu 24.04 VM | `public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04:main-38352d34` || Windows Server 2022 VM | `public.ecr.aws/k5j5w0x5/cua-windows-2022:main-bac7daa3` |+{/* GENERATED:sandbox-builtin-mappings:end */}These are versioned tags selected by the package. Use an immutable digest whenartifact identity must remain fixed independently of a registry tag.### Windows firmware-In released 0.4.3, `FleetCloudTransport` generates `Firmware.EFI` when+In 0.7.0, `FleetCloudTransport` generates `Firmware.EFI` when`image.os_type == 'windows'`. The earlier claim that Windows always receives thedefault BIOS template does not apply to this release. This mapping does not provethat a particular account, registry artifact, or Fleet deployment can boot it.@@ -48,7 +52,7 @@ inspect the disk to infer its OS. For a Windows VM artifact, specify## Image customization-| Operation | Local execution | Fleet execution in 0.4.3 |+| Operation | Local execution | Fleet execution in 0.7.0 || --- | --- | --- || Package and setup layers, including `apt_install()`, `pip_install()`, and `run()` | Applied through local image setup; commands must match the guest OS | Rejected || `env()` and `copy()` | Applied through local image setup | Rejected |@@ -66,7 +70,7 @@ before pool creation. See [Prepare and reference a Fleet image](/how-to-guides/s### Fleet guest-service contract-Image acceptance and service readiness are separate checks. In 0.4.3, the default+Image acceptance and service readiness are separate checks. In 0.7.0, the defaultpool template and Sandbox connection use these contracts:| Service | Template or client behavior | Required guest behavior |@@ -84,21 +88,21 @@ Windows label. For an example service layout, see the### Transport availability-| Sandbox connection | `sb.tunnel.forward()` in 0.4.3 | Connection behavior |+| Sandbox connection | `sb.tunnel.forward()` in 0.7.0 | Connection behavior || --- | --- | --- || Local VM through `HTTPTransport` | Not implemented | Use the runtime's startup mapping where available, such as bare-metal QEMU's `sb.exposed_ports` || Fleet pool claim through base `FleetTransport` | Not implemented | Use `sb.services.request()` for authenticated requests to a named service |+| Fleet lifecycle through `FleetCloudTransport` | Implemented for numeric ports | Resolves the matching authenticated named-service URL; the template must declare the service || SSH or ADB transport | Implemented by those transports | Forwarding depends on the transport; ADB also accepts Android socket names |-`Pool.claim()`, `Sandbox.create(pool=...)`, and the Fleet image path of-`Sandbox.ephemeral(image)` all return the base `FleetTransport`. For persistent-Fleet sandboxes, `Sandbox.create(image)` rejects a registry image without an-explicitly named pool. Apply the pool first, then claim from it.+`Pool.claim()` returns the base `FleetTransport`. `Sandbox.create(pool=...)` and+the Fleet image paths use `FleetCloudTransport`, whose numeric helper maps the+server port to `server` and another port to `port-N`. Declaring or forwarding a+port does not install or start the guest service.-The older `FleetCloudTransport` class implements a numeric-port helper, but its-presence in the package does not make that helper available on the pool-backed-creation paths above. A method on the common Sandbox interface does not establish-support on all transports.+A method on the common Sandbox interface does not establish support on all+transports. In particular, a Sandbox returned directly by `Pool.claim()` uses the+base Fleet transport and its named-service interface.Fleet service URLs require authentication. `sb.services.request()` uses the Fleetconnection's authenticated lease. The lower-level Python Fleet SDK's@@ -107,26 +111,29 @@ exposes `serviceRequest()`. A URL alone does not grant access. See[Fleet pool credentials](/reference/cua-cli/authentication#fleet-pools-need-their-own-credentials)and [Sandbox SDK interfaces](/reference/sandbox-sdk/interfaces).-The Fleet image path of `Sandbox.ephemeral()` in 0.4.3 accepts only the default+The Fleet image path of `Sandbox.ephemeral()` in 0.7.0 accepts only the default`region='us-east-1'`; `Pool.apply()` has no region argument.Registry access, account permissions, resource limits, capacity, and readiness aredeployment requirements that SDK validation cannot establish.## Evidence and limits-The contracts above were checked against these public release artifacts:--- [`cua-sandbox` 0.4.3 on PyPI](https://pypi.org/project/cua-sandbox/0.4.3/):- `image.py` (constructors and registry mappings), `sandbox.py` (runtime selection),- `pool.py` (claims), `transport/fleet_cloud.py` (validation, EFI, and services),- and the transport and runtime implementations.-- [`cua` 0.1.6 on PyPI](https://pypi.org/project/cua/0.1.6/): public Python exports.-- [`cua-fleet` 0.1.14 on PyPI](https://pypi.org/project/cua-fleet/0.1.14/): Python- bound-claim service requests.-- [`@trycua/fleet` 0.1.1 npm version metadata](https://registry.npmjs.org/@trycua/fleet/0.1.1):- TypeScript service request surface.--Verification covers released source and offline contract checks. It does not+The package mappings below are generated from source manifests and image+constants. They describe the clients built and published from this repository;+they are separate from the versions observed in a deployment-qualified image.++{/* GENERATED:sandbox-evidence:start */}+- `cua-sandbox` 0.7.0 source: image constructors, registry mappings, runtime+ selection, pool claims, Fleet validation, firmware, and services.+- `cua` 0.1.6 source: public Python exports.+- `cua-fleet` 0.1.17 package mapping: Python bound-claim service requests.+- `@trycua/fleet` 0.1.2 package mapping: TypeScript service requests.+- `cua-sandbox[driver]` 0.7.0 maps direct Driver use to `cua-driver`+ 0.27.0. This client mapping is not the Driver version inside a particular+ published or deployment-qualified guest image.+{/* GENERATED:sandbox-evidence:end */}++Verification covers source and offline contract checks. It does notinclude provisioned Fleet boots, authenticated service requests, local VM orcontainer boots, or a deployment-wide operating-system certification. Specificrecipe observations, such as the [Windows Minecraft workflow](/how-to-guides/sandbox/minecraft),diff --git a/docs/content/docs/reference/sandbox-sdk/typescript.mdx b/docs/content/docs/reference/sandbox-sdk/typescript.mdxindex 56c888234c..fd221cf069 100644--- a/docs/content/docs/reference/sandbox-sdk/typescript.mdx+++ b/docs/content/docs/reference/sandbox-sdk/typescript.mdx@@ -1,10 +1,10 @@---title: TypeScript Fleet reference-description: Entry points, client methods, resource types, and lifecycle contracts for @trycua/fleet 0.1.1.+description: Entry points, client methods, resource types, and lifecycle contracts for @trycua/fleet 0.1.2.----This page describes the published `@trycua/fleet` 0.1.1 package-([npm version metadata](https://registry.npmjs.org/@trycua/fleet/0.1.1)).+This page describes the published `@trycua/fleet` 0.1.2 package+([npm version metadata](https://registry.npmjs.org/@trycua/fleet/0.1.2)).It provides Fleet resource operations through WebAssembly bindings.Its `Pool` and `Sandbox` exports are resource records, not the Python`Pool.apply()` and computer-control `Sandbox` classes.@@ -14,7 +14,7 @@ Its `Pool` and `Sandbox` exports are resource records, not the PythonThe package is installed with:```bash-npm install @trycua/[email protected]+npm install @trycua/[email protected]```Choose the entry point for the execution environment:@@ -114,9 +114,9 @@ These operations address a service on a bound `Sandbox`:| `revokeSignedServiceUrl(signedServiceUrl: SignedServiceUrl)` | `Promise<void>` |`HttpRequest` carries `method`, `url`, `headers`, optional `body`, and optional-`timeoutSecs`. `HttpResponse` carries `status`, `headers`, and `body`. Headers-are `{ name: string, value: string }[]`; bodies use `ArrayBuffer`, and-`timeoutSecs` uses `bigint`.+`timeoutSecs` and `maxResponseBytes`. `HttpResponse` carries `status`, `headers`,+and `body`. Headers are `{ name: string, value: string }[]`; bodies use+`ArrayBuffer`, and both limits use `bigint`.Signed URLs grant access to their selected service without a separate bearerheader. See [Share a service with a signed URL](/how-to-guides/sandbox/share-service-with-signed-url)@@ -149,4 +149,4 @@ support. The exported `SdkError` variants include status/transport failures,`SignedServiceUrlsUnavailable`.For a complete provisioning example, see-[Create a pool with TypeScript](/how-to-guides/sandbox/create-pool-with-typescript).+[Create Fleet capacity](/how-to-guides/sandbox/create-fleet-capacity).diff --git a/docs/content/docs/tutorials/meta.json b/docs/content/docs/tutorials/meta.jsonindex 0dd326d10a..8baa338c0a 100644--- a/docs/content/docs/tutorials/meta.json+++ b/docs/content/docs/tutorials/meta.json@@ -2,7 +2,6 @@"title": "Start here","icon": "GraduationCap","pages": [- "index","your-first-cloud-fleet","drive-your-first-app","create-your-first-lume-vm",diff --git a/docs/content/docs/tutorials/your-first-cloud-fleet.mdx b/docs/content/docs/tutorials/your-first-cloud-fleet.mdxindex 6618f1d90e..4393389362 100644--- a/docs/content/docs/tutorials/your-first-cloud-fleet.mdx+++ b/docs/content/docs/tutorials/your-first-cloud-fleet.mdx@@ -1,274 +1,164 @@---title: Your first Cloud Fleet-description: Provision a Cloud Fleet, claim an isolated Linux desktop, run a command, save a screenshot, and clean up the cloud resources.+description: Create a Cloud Fleet, use its computer-server to transform a file, verify the result locally, and clean up.---import { Callout } from 'fumadocs-ui/components/callout';+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';-In this tutorial, you provision a one-sandbox **Cloud Fleet** on-`run.cua.ai`, claim its Linux desktop, run `uname -a`, save a screenshot, and-delete the Fleet. The Cua Sandbox SDK represents a Fleet as a `Pool` and an-active desktop as a claim on that pool.+In this tutorial, you create a one-computer Cloud Fleet, claim its Sandbox,+write and hash a file through `computer-server`, and verify the hash on your+computer. You then release the claim and request deletion of the Fleet.-<Callout type="info">- You need Python `>=3.11,<3.14`, [uv](https://docs.astral.sh/uv/), and Fleet- credentials with permission to manage sandbox pools.-</Callout>+Python uses the Cua Sandbox SDK. TypeScript uses the Fleet SDK. Both paths use+the same pool, claim, and guest-service concepts, but they are not equivalent+Sandbox SDKs.<Callout type="warn">- A pool with `replicas=1` keeps one cloud sandbox warm until you delete the pool. Cloud resources- can incur usage charges. The script requests deletion in a `finally` block and sets a one-hour- pool TTL as a fallback. Keep the local run record until cleanup is confirmed.+ A pool with one replica keeps cloud capacity available and can incur usage charges until it is+ deleted. The examples request deletion even when the task fails, but a stopped process cannot run+ its cleanup block. Keep the printed Fleet name until you confirm that the Fleet is absent.</Callout>-## 1. Authenticate with Fleet+## 1. Prepare your account-First, [create a Fleet user API key and check access](/how-to-guides/sandbox/set-up-fleet-credentials).-That setup explains account access, the **API keys** page, payment-method-requirements, and a read-only check that does not provision cloud resources.-Complete it before continuing.+Complete [Set up Fleet credentials](/how-to-guides/sandbox/set-up-fleet-credentials).+You need a Fleet user API key with permission to create and delete pools.-The SDK connects to `https://run.cua.ai` by default. In the same shell, use the-**Client ID** and **Client Secret** from your Fleet key:+Set its client credentials in the shell where you will run the tutorial:```bashexport CUA_CLIENT_ID="<your-client-id>"export CUA_CLIENT_SECRET="<your-client-secret>"-export CUA_TOKEN_URL="https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"-unset FLEETS_TOKEN```-`cua auth login` does not supply credentials to the Fleet SDK. If you already-have a valid Fleet access token, you can set `FLEETS_TOKEN` instead; it takes-precedence over the client credentials and must remain valid through cleanup.+The examples connect to `https://run.cua.ai` and its default OAuth token+endpoint. `cua auth login` does not supply these Fleet SDK credentials.++## 2. Choose an image++Follow [Choose a Fleet image](/how-to-guides/sandbox/choose-an-image) and select+an immutable image reference that the catalog lists for Fleet use with+`computer-server`. The image must listen on the declared `server` service at+port `8000`.++Set the exact registry reference from the catalog:++```bash+export CUA_FLEET_IMAGE="<immutable-registry-reference>"+```++This tutorial does not require Cua Driver or a desktop-control service.++## 3. Download the example-## 2. Prepare a directory for this run+Choose a language. Your choice persists on other Fleet pages that use the same+language tabs.-Use a separate directory for the script and its output:+<Tabs groupId="language" persist items={['Python', 'TypeScript']}>+ <Tab value="Python">++You need Python `>=3.11,<3.14` and+[`uv`](https://docs.astral.sh/uv/). Create a working directory and download the+tested example:```bashmkdir first-cloud-fleetcd first-cloud-fleet+curl -fsSLO https://cua.ai/docs-assets/scripts/first-cloud-fleet/first_cloud_fleet.py```-The script reserves a new, randomly named namespace before creating its pool.-Reservation refuses an existing name instead of modifying an existing pool.-It saves the namespace name and creation timestamp in `cloud-fleet-run.json`.-Do not edit that record or reuse the namespace for other work: cleanup deletes-the namespace and its resources.--## 3. Create the Fleet script--Save the following script as `first_cloud_fleet.py`:--```python title="first_cloud_fleet.py"-# /// script-# requires-python = ">=3.11,<3.14"-# dependencies = [-# "cua-sandbox==0.4.3",-# "cua-fleet==0.1.14",-# ]-# ///--import asyncio-import json-import os-import sys-from pathlib import Path-from uuid import uuid4--from cua_sandbox import Image, Pool-from fleet_sdk import (- CyclopsClient,- CyclopsConfiguration,- CyclopsCredentials,- CyclopsTokenProviderConfiguration,-)---IMAGE = (- "public.ecr.aws/k5j5w0x5/cua-ubuntu-24.04"- "@sha256:c1e601dbb748fdc467c663136f7592e308a91a3c19c309b75261544432826a57"-)-RECORD = Path("cloud-fleet-run.json")---def fleet_client():- configuration = dict(- base_url=os.environ.get("CUA_FLEET_BASE_URL", "https://run.cua.ai"),- pool_poll_interval_ms=2000,- pool_poll_limit=300,- claim_poll_interval_ms=2000,- claim_poll_limit=300,- )- token = os.environ.get("FLEETS_TOKEN")- if token:- return CyclopsClient.connect_with_access_token_and_native_http_client(- CyclopsTokenProviderConfiguration(**configuration), token- )- return CyclopsClient.connect_with_native_http_client(CyclopsConfiguration(- **configuration,- token_url=os.environ["CUA_TOKEN_URL"],- credentials=CyclopsCredentials(- os.environ["CUA_CLIENT_ID"], os.environ["CUA_CLIENT_SECRET"]- ),- ))---async def find_namespace(client, name):- # A direct lookup outside an owned namespace can return 403, even when- # the resource does not exist. Use a successful account inventory instead.- namespaces = await client.list_namespaces()- return next((item for item in namespaces if item.name == name), None)---async def delete_namespace(client, name, created_at):- current = await find_namespace(client, name)- if current is None:- print(f"Namespace no longer in account inventory: {name}")- return- if not created_at or current.created_at != created_at:- raise RuntimeError("Namespace identity changed; refusing cleanup.")- await client.delete_namespace(name)- for _ in range(60):- if await find_namespace(client, name) is None:- print(f"Namespace no longer in account inventory: {name}")- return- await asyncio.sleep(2)- raise TimeoutError("Namespace is still visible. Retry cleanup after it terminates.")---async def cleanup():- record = json.loads(RECORD.read_text())- if not record.get("created_at"):- raise RuntimeError(- "Creation was not confirmed. Check this run's name in Fleet before deleting anything."- )- await delete_namespace(fleet_client(), record["name"], record["created_at"])---async def run():- pool_name = f"first-fleet-{uuid4().hex}"- # Exclusive creation prevents overwriting an earlier run's cleanup record.- with RECORD.open("x") as output:- json.dump({"name": pool_name, "created_at": None}, output)- client = fleet_client()- # Only HTTP 201 confirms reservation. A collision (409) or denied request- # stops here, without reconciling or deleting another namespace's resources.- namespace = await client.create_namespace(pool_name)- try:- RECORD.write_text(json.dumps({- "name": pool_name,- "created_at": namespace.created_at,- }))- if not namespace.created_at:- raise RuntimeError("Namespace creation timestamp missing; inspect Fleet before cleanup.")- print(f"Provisioning Cloud Fleet: {pool_name}")- pool = await Pool.apply(- Image.from_registry(IMAGE),- name=pool_name,- replicas=1,- cpu=4,- memory_mb=4096,- services={"server": 8000},- ttl_seconds_after_created=3600,- )- async with pool.claim(- name="first-claim",- service="server",- time_to_start=900,- ) as sandbox:- print(f"Connected to sandbox: {sandbox.name}")-- result = await sandbox.shell.run("uname -a")- if not result.success:- raise RuntimeError(result.stderr)- print(result.stdout.strip())-- screenshot = Path("cloud-fleet.png")- screenshot.write_bytes(await sandbox.screenshot())- print(f"Screenshot saved to {screenshot.resolve()}")- finally:- print(f"Deleting Cloud Fleet: {pool_name}")- await delete_namespace(client, pool_name, namespace.created_at)---if __name__ == "__main__":- if sys.argv[1:] == ["run"]:- asyncio.run(run())- elif sys.argv[1:] == ["cleanup"]:- asyncio.run(cleanup())- else:- raise SystemExit("Usage: first_cloud_fleet.py run|cleanup")-```+The script metadata installs `cua-sandbox==0.7.0` and configures the Cua wheel+index for its Fleet dependency in an isolated environment.-## 4. Run it+ </Tab>+ <Tab value="TypeScript">-Run the script from the same directory. `uv` reads the inline metadata and-installs `cua-sandbox==0.4.3` and its required Fleet SDK,-`cua-fleet==0.1.14`, in an isolated environment:+You need Node.js 20 or newer. Create a working directory, install the Fleet SDK+and TypeScript runner, and download the tested example:```bash-uv run first_cloud_fleet.py run+mkdir first-cloud-fleet+cd first-cloud-fleet+npm init -y+npm pkg set type=module+npm install @trycua/[email protected]+npm install --save-dev tsx+curl -fsSLo first-cloud-fleet.ts \+ https://cua.ai/docs-assets/scripts/first-cloud-fleet/first-cloud-fleet.ts.txt```-The first run can take several minutes while Fleet provisions the Linux-sandbox. The script prints the sandbox name and Linux kernel information, then-writes `cloud-fleet.png` in the current directory.+ </Tab>+</Tabs>++## 4. Create the Fleet and complete the task-When the claim block exits, the SDK releases the claimed sandbox. The `finally`-block requests deletion of the reserved namespace, which includes the pool,-template, and sandbox resources. It polls successful account-inventory responses-until that namespace is absent. It does not interpret a `403` as absence.-If cleanup fails or times out, follow the next section and check the Fleet UI-for this run's resources. A deletion request alone does not prove that all-resources have finished terminating.+The example generates a unique pool name, then creates one replica with an+explicit `server: 8000` service. After it claims the Sandbox and that service+is ready, it performs these operations through `computer-server`:-## Clean up an interrupted run+1. Write a small text file in the guest.+2. Run `sha256sum` in the guest and save the digest to a second file.+3. Read the saved digest from the guest.+4. Compute SHA-256 independently on your computer and compare the values.-If the process is killed or loses connectivity after provisioning, the-`finally` block might not reach Fleet. Restore connectivity and valid Fleet-credentials for the same account, then run the deletion-only command from the-same directory:+Run the example:++<Tabs groupId="language" persist items={['Python', 'TypeScript']}>+ <Tab value="Python">```bash-uv run first_cloud_fleet.py cleanup+uv run first_cloud_fleet.py```-This command reads `cloud-fleet-run.json`, checks that the recorded namespace-still has the same creation timestamp, and deletes it. It does not call-`Pool.apply()`, claim a sandbox, or repeat the workload. It also handles a run-that reserved a namespace but failed before creating a pool. Keep using the-same account: absence from another account's inventory is not cleanup proof.-The script confirms account-inventory absence, not an independent inspection-of the underlying guest's termination. Save any-remote files you need before cleanup; deletion destroys the sandboxes and-their state.--If the record has no creation timestamp, namespace reservation was not confirmed.-This can happen after a name collision, denied request, or interrupted response. The-command refuses deletion. Find the exact recorded name in the Fleet UI and-verify whether this run created any resources before removing them. Do not-delete an existing pool to resolve an access or billing error.--Keep `cloud-fleet.png` as the local result. For another run, use a new directory-so the earlier cleanup record remains available.+ </Tab>+ <Tab value="TypeScript">++```bash+npx tsx first-cloud-fleet.ts+```++ </Tab>+</Tabs>++Provisioning can take several minutes. A successful run prints output similar+to this:++```text+Cloud Fleet name: first-fleet-0123456789abcdef+Verified SHA-256: d9359aad71bda9a11a4fd2e8d72044d6f0f77519c6b6fb30d251806febcfb4d0+Requesting deletion of Cloud Fleet: first-fleet-0123456789abcdef+```++The matching digest proves that the guest read the same bytes that your local+process hashed. It does not rely on the guest shell to verify its own result.++## 5. Confirm cleanup++Both examples release the claim before removing the dedicated Fleet resources.+Python deletes the pool and the template it created; Fleet can then remove the+empty namespace. TypeScript requests deletion of the dedicated namespace+directly. An accepted cleanup request can precede final removal.++Open [Fleet](https://run.cua.ai) and confirm that the printed Fleet name is no+longer present. Do not treat closing the terminal, a local exception, or a+cleanup request by itself as proof that chargeable capacity is gone.++If the process stopped before cleanup completed, do not rerun the tutorial.+Follow [Recover this tutorial after an interruption](/how-to-guides/sandbox/recover-first-cloud-fleet)+with the printed pool name.## What you built-The Fleet SDK reserved a namespace exclusively for this run. `Pool.apply()`-created a named Fleet pool and its Linux sandbox template inside it.-`pool.claim()` reserved one sandbox and connected the SDK to its-`server` service on port `8000`. This service is the sandbox computer server;-it is not a Cua Driver MCP endpoint. The shell and screenshot calls target the-claimed cloud desktop. This script checks the connection and saves an image;-it does not run an AI agent or connect a local Cua Driver session. Exiting the-claim releases the sandbox, and namespace deletion requests resource removal.+You created a Fleet pool containing one hosted computer. A claim reserved that+computer for the task, and the declared `server` service routed file and shell+operations to its `computer-server` on port `8000`. Releasing the claim ended+the reservation. The final cleanup removed the dedicated Fleet resources and+requested removal of their capacity.## Next steps-- [Create a reusable sandbox pool with Python](/how-to-guides/sandbox/create-pool-with-python)-- [Configure a sandbox pool with Terraform](/how-to-guides/sandbox/configure-pool-with-terraform)+- [Create reusable Fleet capacity](/how-to-guides/sandbox/create-fleet-capacity)+- [Configure a pool with Terraform](/how-to-guides/sandbox/configure-pool-with-terraform)- [Expire pools and claims automatically](/how-to-guides/sandbox/expire-pools-and-claims)-- [Choose a Fleet image](/how-to-guides/sandbox/choose-an-image)- [Sandbox SDK API reference](/reference/sandbox-sdk)diff --git a/docs/next.config.mjs b/docs/next.config.mjsindex 281017ea07..9112e79ba2 100644--- a/docs/next.config.mjs+++ b/docs/next.config.mjs@@ -85,6 +85,16 @@ const config = {destination: '/how-to-guides/sandbox/configure-pool-with-terraform',permanent: true,},+ {+ source: '/how-to-guides/sandbox/create-pool-with-python',+ destination: '/how-to-guides/sandbox/create-fleet-capacity',+ permanent: true,+ },+ {+ source: '/how-to-guides/sandbox/create-pool-with-typescript',+ destination: '/how-to-guides/sandbox/create-fleet-capacity',+ permanent: true,+ },{source: '/how-to-guides/skills/record-a-demonstration',destination: '/how-to-guides',diff --git a/docs/package.json b/docs/package.jsonindex fa73693cf9..7ab030ccff 100644--- a/docs/package.json+++ b/docs/package.json@@ -11,8 +11,10 @@"docs:check": "tsx ../scripts/docs-generators/runner.ts --check","docs:check:cua-driver": "tsx ../scripts/docs-generators/runner.ts --library cua-driver --check","docs:check:lume": "tsx ../scripts/docs-generators/runner.ts --library lume --check",+ "docs:check:sandbox": "tsx ../scripts/docs-generators/runner.ts --library sandbox --check","docs:list": "tsx ../scripts/docs-generators/runner.ts --list","docs:generate:lume": "tsx ../scripts/docs-generators/lume.ts",+ "docs:generate:sandbox": "tsx ../scripts/docs-generators/sandbox.ts","docs:generate:cua-driver": "tsx ../scripts/docs-generators/cua-driver.ts","docs:generate:python": "tsx ../scripts/docs-generators/python-sdk.ts","docs:generate:changelog": "tsx ../scripts/docs-generators/generate-changelog.ts",diff --git a/docs/public/scripts/first-cloud-fleet/first-cloud-fleet.ts.txt b/docs/public/scripts/first-cloud-fleet/first-cloud-fleet.ts.txtnew file mode 100644index 0000000000..77923bb1d8--- /dev/null+++ b/docs/public/scripts/first-cloud-fleet/first-cloud-fleet.ts.txt@@ -0,0 +1,190 @@+import { createHash, randomUUID } from 'node:crypto';+import { setTimeout as sleep } from 'node:timers/promises';+import {+ CyclopsClient,+ CyclopsCredentials,+ FetchHttpClient,+ uniffiInitAsync,+ type Claim,+ type CreateClaimRequest,+ type CreatePoolRequest,+ type CreateTemplateRequest,+ type CyclopsClientLike,+ type CyclopsConfiguration,+ type HttpRequest,+ type Pool,+} from '@trycua/fleet/node';++const SOURCE_TEXT = 'pear\napple\npear\nbanana\n';+const SOURCE_PATH = '/tmp/first-cloud-fleet.txt';+const RESULT_PATH = '/tmp/first-cloud-fleet.sha256';++function requiredEnv(name: string): string {+ const value = process.env[name];+ if (!value) throw new Error(`Missing environment variable: ${name}`);+ return value;+}++function commandBody(command: string, params: Record<string, unknown>): ArrayBuffer {+ return new TextEncoder().encode(JSON.stringify({ command, params })).buffer as ArrayBuffer;+}++async function waitForServer(+ client: CyclopsClientLike,+ sandbox: Parameters<CyclopsClientLike['serviceRequest']>[0]+): Promise<void> {+ const deadline = Date.now() + 15 * 60 * 1_000;+ let lastError: unknown;+ while (Date.now() < deadline) {+ try {+ const response = await client.serviceRequest(sandbox, 'server', '/status', {+ method: 'GET',+ url: 'https://service.invalid/status',+ headers: [],+ timeoutSecs: 10n,+ });+ if (response.status === 200) return;+ lastError = new Error(`computer-server returned HTTP ${response.status}`);+ } catch (error) {+ lastError = error;+ }+ await sleep(2_000);+ }+ throw new Error('computer-server was not ready within 15 minutes', { cause: lastError });+}++async function serverCommand(+ client: CyclopsClientLike,+ sandbox: Parameters<CyclopsClientLike['serviceRequest']>[0],+ command: string,+ params: Record<string, unknown>+): Promise<Record<string, unknown>> {+ const request: HttpRequest = {+ method: 'POST',+ url: 'https://service.invalid/cmd',+ headers: [{ name: 'content-type', value: 'application/json' }],+ body: commandBody(command, params),+ };+ const response = await client.serviceRequest(sandbox, 'server', '/cmd', request);+ if (response.status !== 200) throw new Error(`computer-server returned HTTP ${response.status}`);++ const event = new TextDecoder()+ .decode(response.body)+ .split('\n')+ .find((line) => line.startsWith('data: '));+ if (!event) throw new Error('computer-server returned no data event');+ const payload = JSON.parse(event.slice(6)) as Record<string, unknown>;+ if (payload.success !== true) throw new Error(String(payload.error ?? `${command} failed`));+ return payload;+}++async function deleteOwnedNamespace(client: CyclopsClientLike, namespace: string): Promise<void> {+ await client.deleteNamespace(namespace);+ for (let attempt = 0; attempt < 60; attempt += 1) {+ const namespaces = await client.listNamespaces();+ if (!namespaces.some((item) => item.name === namespace)) return;+ await sleep(2_000);+ }+ throw new Error(`Cloud Fleet namespace is still visible: ${namespace}`);+}++export async function runTutorial(+ client: CyclopsClientLike,+ imageRef: string,+ poolName: string+): Promise<void> {+ const templateName = `${poolName}-template`;+ let pool: Pool | undefined;+ let claim: Claim | undefined;++ try {+ console.log(`Cloud Fleet name: ${poolName}`);+ const poolRequest: CreatePoolRequest = {+ namespace: poolName,+ spec: { replicas: 1, sandboxTemplateRef: { name: templateName } },+ };+ pool = await client.createPool(poolRequest);++ const templateRequest: CreateTemplateRequest = {+ namespace: poolName,+ name: templateName,+ spec: {+ vmTemplate: {+ containerDiskImage: imageRef,+ cpuCores: 4,+ memory: '4Gi',+ services: [{ name: 'server', targetPort: 8000 }],+ },+ },+ };+ await client.createTemplate(templateRequest);++ const claimRequest: CreateClaimRequest = { pool };+ claim = await client.createClaim(claimRequest);+ const sandbox = await client.waitClaim(claim);+ await waitForServer(client, sandbox);++ await serverCommand(client, sandbox, 'write_text', {+ path: SOURCE_PATH,+ content: SOURCE_TEXT,+ });+ await serverCommand(client, sandbox, 'run_command', {+ command: `sha256sum ${SOURCE_PATH} | cut -d ' ' -f 1 > ${RESULT_PATH}`,+ });+ const result = await serverCommand(client, sandbox, 'read_text', { path: RESULT_PATH });+ const guestDigest = String(result.content ?? '').trim();+ const localDigest = createHash('sha256').update(SOURCE_TEXT).digest('hex');+ if (guestDigest !== localDigest) {+ throw new Error(`Verification failed: guest=${guestDigest} local=${localDigest}`);+ }+ console.log(`Verified SHA-256: ${guestDigest}`);+ } finally {+ const cleanupErrors: unknown[] = [];+ if (claim) {+ try {+ await client.deleteClaim(claim);+ } catch (error) {+ cleanupErrors.push(error);+ }+ }+ if (pool) {+ console.log(`Requesting deletion of Cloud Fleet: ${poolName}`);+ try {+ await deleteOwnedNamespace(client, poolName);+ } catch (error) {+ cleanupErrors.push(error);+ }+ }+ if (cleanupErrors.length > 0) {+ throw new AggregateError(cleanupErrors, `Cleanup failed for Cloud Fleet ${poolName}`);+ }+ }+}++async function main(): Promise<void> {+ await uniffiInitAsync();+ const configuration: CyclopsConfiguration = {+ baseUrl: process.env.CUA_FLEET_BASE_URL ?? 'https://run.cua.ai',+ tokenUrl:+ process.env.CUA_TOKEN_URL ??+ 'https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token',+ credentials: new CyclopsCredentials(+ requiredEnv('CUA_CLIENT_ID'),+ requiredEnv('CUA_CLIENT_SECRET')+ ),+ poolPollIntervalMs: 2_000n,+ poolPollLimit: 450,+ claimPollIntervalMs: 2_000n,+ claimPollLimit: 450,+ };+ const client = CyclopsClient.connect(configuration, new FetchHttpClient());+ const poolName = `first-fleet-${randomUUID().replaceAll('-', '').slice(0, 16)}`;+ await runTutorial(client, requiredEnv('CUA_FLEET_IMAGE'), poolName);+}++if (import.meta.url === `file://${process.argv[1]}`) {+ main().catch((error: unknown) => {+ console.error(error);+ process.exitCode = 1;+ });+}diff --git a/docs/public/scripts/first-cloud-fleet/first_cloud_fleet.py b/docs/public/scripts/first-cloud-fleet/first_cloud_fleet.pynew file mode 100644index 0000000000..21fa4d40d1--- /dev/null+++ b/docs/public/scripts/first-cloud-fleet/first_cloud_fleet.py@@ -0,0 +1,69 @@+# /// script+# requires-python = ">=3.11,<3.14"+# dependencies = [+# "cua-sandbox==0.7.0",+# ]+# [[tool.uv.index]]+# name = "cua-wheels"+# url = "https://wheels.cua.ai/simple"+# ///++import asyncio+import hashlib+import os+from uuid import uuid4++from cua_sandbox import Image, Pool+++SOURCE_TEXT = "pear\napple\npear\nbanana\n"+SOURCE_PATH = "/tmp/first-cloud-fleet.txt"+RESULT_PATH = "/tmp/first-cloud-fleet.sha256"+++async def run_tutorial(image_ref: str, pool_name: str) -> None:+ pool = None+ try:+ print(f"Cloud Fleet name: {pool_name}")+ pool = await Pool.apply(+ Image.from_registry(image_ref),+ name=pool_name,+ replicas=1,+ cpu=4,+ memory_mb=4096,+ services={"server": 8000},+ )++ async with pool.claim(+ name="first-task",+ service="server",+ time_to_start=900,+ ) as sandbox:+ await sandbox.files.write_text(SOURCE_PATH, SOURCE_TEXT)+ result = await sandbox.shell.run(+ f"sha256sum {SOURCE_PATH} | cut -d ' ' -f 1 > {RESULT_PATH}"+ )+ if not result.success:+ raise RuntimeError(result.stderr)++ guest_digest = (await sandbox.files.read_text(RESULT_PATH)).strip()+ local_digest = hashlib.sha256(SOURCE_TEXT.encode()).hexdigest()+ if guest_digest != local_digest:+ raise RuntimeError(+ f"Verification failed: guest={guest_digest} local={local_digest}"+ )+ print(f"Verified SHA-256: {guest_digest}")+ finally:+ if pool is not None:+ print(f"Requesting deletion of Cloud Fleet: {pool_name}")+ await pool.delete()+++async def main() -> None:+ image_ref = os.environ["CUA_FLEET_IMAGE"]+ pool_name = f"first-fleet-{uuid4().hex[:16]}"+ await run_tutorial(image_ref, pool_name)+++if __name__ == "__main__":+ asyncio.run(main())diff --git a/docs/scripts/fleet-navigation.test.ts b/docs/scripts/fleet-navigation.test.tsnew file mode 100644index 0000000000..093e02e62e--- /dev/null+++ b/docs/scripts/fleet-navigation.test.ts@@ -0,0 +1,174 @@+import assert from 'node:assert/strict';+import { access, readFile } from 'node:fs/promises';+import path from 'node:path';+import test from 'node:test';++const docs = path.resolve(__dirname, '..');+const content = path.join(docs, 'content/docs');+const plannedPages = new Set([+ '/how-to-guides/sandbox/control-the-desktop-with-cua-driver',+ '/how-to-guides/sandbox/recover-first-cloud-fleet',+]);++async function metadata(relativePath: string): Promise<{ title?: string; pages: string[] }> {+ return JSON.parse(await readFile(path.join(content, relativePath, 'meta.json'), 'utf8'));+}++function link(entry: string): { label: string; url: string } | undefined {+ const match = /^\[([^\]]+)]\(([^)]+)\)$/.exec(entry);+ if (match) return { label: match[1], url: match[2] };+}++function separators(pages: string[]): string[] {+ return pages.filter((entry) => entry.startsWith('---')).map((entry) => entry.slice(3, -3));+}++function links(pages: string[]): Array<{ label: string; url: string }> {+ return pages.flatMap((entry) => {+ const parsed = link(entry);+ return parsed ? [parsed] : [];+ });+}++async function routeExists(url: string): Promise<boolean> {+ if (plannedPages.has(url)) return true;+ const relative = url.replace(/^\//, '');+ for (const candidate of [`${relative}.mdx`, path.join(relative, 'index.mdx')]) {+ try {+ await access(path.join(content, candidate));+ return true;+ } catch {}+ }+ return false;+}++test('desktop and mobile sidebars share the approved top-level product order', async () => {+ const root = await metadata('.');+ const tutorials = await metadata('tutorials');+ const expected = [+ 'index',+ 'tutorials',+ '(cloud-fleets)',+ '(local-sandboxes)',+ '---Products---',+ '[Cua Driver](/how-to-guides/driver/install)',+ '[Cua CLI](/reference/cua-cli)',+ '[Lume](/how-to-guides/lume/install-lume)',+ '[Cua-Bench](/how-to-guides/cua-bench/run-a-task)',+ '---Browse by type---',+ 'concepts',+ 'use-cua-with',+ 'how-to-guides',+ 'reference',+ ];++ // Fumadocs gives both responsive sidebar variants this one page tree.+ for (const viewport of ['desktop', 'mobile']) {+ assert.deepEqual(root.pages, expected, `${viewport} sidebar order`);+ }+ assert.equal(root.pages.filter((entry) => entry === 'tutorials').length, 1);+ assert.equal(tutorials.title, 'Start here');+ assert.equal(tutorials.pages.includes('index'), false, 'omit the redundant Start here link');+});++test('Cua Fleets uses the approved stages and contains no local setup tasks', async () => {+ const fleet = await metadata('(cloud-fleets)');+ assert.equal(fleet.title, 'Cua Fleets');+ assert.deepEqual(separators(fleet.pages), [+ 'Overview',+ 'Set up',+ 'Create and connect',+ 'Use the computer',+ 'Operate',+ 'Use Fleets with',+ 'Images',+ 'Reference',+ ]);++ const fleetLinks = links(fleet.pages);+ const localOnly = new Set([+ '/local-sandboxes',+ '/how-to-guides/sandbox/manage-local-lifecycle',+ '/how-to-guides/sandbox/interactive-shell',+ '/how-to-guides/sandbox/scale-out',+ '/how-to-guides/sandbox/images',+ ]);+ assert.equal(+ fleetLinks.some(({ url }) => localOnly.has(url)),+ false+ );+ assert.equal(+ fleetLinks.some(({ url }) => url.startsWith('/tutorials/')),+ false+ );+ assert.ok(fleetLinks.some(({ url }) => url.endsWith('/control-the-desktop-with-cua-driver')));+ assert.ok(fleetLinks.some(({ url }) => url.endsWith('/recover-first-cloud-fleet')));+});++test('Local Sandboxes owns local creation and lifecycle without Fleet setup', async () => {+ const local = await metadata('(local-sandboxes)');+ assert.equal(local.title, 'Local Sandboxes');+ assert.deepEqual(separators(local.pages), ['Overview', 'Create and use', 'Images', 'Reference']);++ const localLinks = links(local.pages);+ for (const required of [+ '/local-sandboxes',+ '/how-to-guides/sandbox/manage-local-lifecycle',+ '/how-to-guides/sandbox/interactive-shell',+ '/how-to-guides/sandbox/images',+ ]) {+ assert.ok(+ localLinks.some(({ url }) => url === required),+ `missing ${required}`+ );+ }+ assert.equal(+ localLinks.some(({ url }) =>+ /fleet|claim-a-sandbox|configure-pool|set-up-fleet-credentials/.test(url)+ ),+ false+ );+ assert.equal(+ localLinks.some(({ url }) => url.startsWith('/tutorials/')),+ false+ );+});++test('navigation labels point to existing or explicitly stacked pages', async () => {+ for (const group of ['(cloud-fleets)', '(local-sandboxes)']) {+ const nav = await metadata(group);+ for (const { label, url } of links(nav.pages)) {+ assert.ok(label.length > 0, `${group} has an empty label`);+ assert.equal(url.startsWith('/'), true, `${label} must use a stable root-relative URL`);+ assert.equal(await routeExists(url), true, `${label} points to missing ${url}`);+ }+ }+});++test('Track E entry and concept pages link only to existing routes', async () => {+ for (const page of [+ 'cloud-fleets.mdx',+ 'local-sandboxes.mdx',+ 'concepts/pools-claims-and-guest-services.mdx',+ ]) {+ const body = await readFile(path.join(content, page), 'utf8');+ const urls = [...body.matchAll(/\[[^\]]+\]\((\/[^)]+)\)/g)].map((match) => match[1]);+ assert.ok(urls.length > 0, `${page} should provide next steps`);+ for (const url of urls) {+ assert.equal(await routeExists(url), true, `${page} points to missing ${url}`);+ }+ }+});++test('browse-by-type metadata reserves incoming Track F and G pages in stage order', async () => {+ const sandbox = await metadata('how-to-guides/sandbox');+ const driver = sandbox.pages.indexOf('control-the-desktop-with-cua-driver');+ const recovery = sandbox.pages.indexOf('recover-first-cloud-fleet');+ assert.ok(driver > sandbox.pages.indexOf('---Cua Fleets: Use the computer---'));+ assert.ok(driver < sandbox.pages.indexOf('---Cua Fleets: Operate---'));+ assert.ok(recovery > sandbox.pages.indexOf('---Cua Fleets: Operate---'));+ assert.ok(recovery < sandbox.pages.indexOf('troubleshoot-fleet-pools'));++ const concepts = await metadata('concepts');+ assert.ok(concepts.pages.includes('pools-claims-and-guest-services'));+});diff --git a/docs/scripts/fleet-task-pages.test.ts b/docs/scripts/fleet-task-pages.test.tsnew file mode 100644index 0000000000..5470847e46--- /dev/null+++ b/docs/scripts/fleet-task-pages.test.ts@@ -0,0 +1,89 @@+import assert from 'node:assert/strict';+import { access, readFile, readdir } from 'node:fs/promises';+import * as path from 'node:path';+import test from 'node:test';++const docs = path.resolve(__dirname, '..');+const sandbox = path.join(docs, 'content/docs/how-to-guides/sandbox');++async function page(slug: string) {+ return readFile(path.join(sandbox, `${slug}.mdx`), 'utf8');+}++async function mdxFiles(directory: string): Promise<string[]> {+ const entries = await readdir(directory, { withFileTypes: true });+ const nested = await Promise.all(+ entries.map((entry) => {+ const target = path.join(directory, entry.name);+ if (entry.isDirectory()) return mdxFiles(target);+ return entry.name.endsWith('.mdx') ? [target] : [];+ })+ );+ return nested.flat();+}++test('neutral Fleet task pages use persistent Python and TypeScript tabs', async () => {+ for (const slug of ['create-fleet-capacity', 'claim-a-sandbox']) {+ const source = await page(slug);+ assert.match(source, /<Tabs groupId="language" persist items=\{\['Python', 'TypeScript'\]\}>/);+ assert.match(source, /<Tab value="Python">/);+ assert.match(source, /<Tab value="TypeScript">/);+ assert.match(source, /Cua Sandbox SDK/);+ assert.match(source, /Fleet SDK/);+ assert.match(source, /not a TypeScript Sandbox SDK/);+ assert.doesNotMatch(source, /<Tab value="CLI">/);+ }+});++test('capacity and claim remain separate tasks', async () => {+ const capacity = await page('create-fleet-capacity');+ const claim = await page('claim-a-sandbox');+ assert.match(capacity, /They do\n\+?not claim a Sandbox\./);+ assert.doesNotMatch(capacity, /CreateClaimRequestBuilder/);+ assert.match(claim, /Pool\.get/);+ assert.match(claim, /client\.getPool/);+ assert.match(claim, /createClaim/);+ assert.match(claim, /deleteClaim/);+});++test('the Sandbox navigation swaps only the two legacy slugs', async () => {+ const metadata = JSON.parse(await readFile(path.join(sandbox, 'meta.json'), 'utf8'));+ const first = metadata.pages.indexOf('create-fleet-capacity');+ assert.ok(first >= 0);+ assert.equal(metadata.pages[first + 1], 'claim-a-sandbox');+ assert.ok(!metadata.pages.includes('create-pool-with-python'));+ assert.ok(!metadata.pages.includes('create-pool-with-typescript'));++ for (const slug of ['create-pool-with-python', 'create-pool-with-typescript']) {+ await assert.rejects(access(path.join(sandbox, `${slug}.mdx`)));+ }+});++test('no page retains a legacy language-specific capacity link', async () => {+ const files = await mdxFiles(path.join(docs, 'content/docs'));+ const legacySlug = /create-pool-with-(python|typescript)/;+ const remaining: string[] = [];+ for (const file of files) {+ if (legacySlug.test(await readFile(file, 'utf8'))) {+ remaining.push(path.relative(docs, file));+ }+ }+ assert.deepEqual(remaining, []);+});++test('legacy language-specific URLs permanently redirect to neutral capacity', async () => {+ const config = (await import('../next.config.mjs')).default;+ const redirects = await config.redirects();+ for (const language of ['python', 'typescript']) {+ assert.deepEqual(+ redirects.find(+ (redirect) => redirect.source === `/how-to-guides/sandbox/create-pool-with-${language}`+ ),+ {+ source: `/how-to-guides/sandbox/create-pool-with-${language}`,+ destination: '/how-to-guides/sandbox/create-fleet-capacity',+ permanent: true,+ }+ );+ }+});diff --git a/docs/scripts/tests/first_cloud_fleet_typescript_smoke.mjs b/docs/scripts/tests/first_cloud_fleet_typescript_smoke.mjsnew file mode 100644index 0000000000..bcfe3fc10d--- /dev/null+++ b/docs/scripts/tests/first_cloud_fleet_typescript_smoke.mjs@@ -0,0 +1,108 @@+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { pathToFileURL } from 'node:url';+import test from 'node:test';++const source = process.env.FIRST_CLOUD_FLEET_TS;+if (!source) throw new Error('Set FIRST_CLOUD_FLEET_TS to the copied tutorial source');+const { runTutorial } = await import(pathToFileURL(source));++const SOURCE_TEXT = 'pear\napple\npear\nbanana\n';+const POOL_NAME = 'first-fleet-0123456789abcdef';+const IMAGE_REF = `registry.example/cua-image@sha256:${'1'.repeat(64)}`;++function response(payload) {+ return {+ status: 200,+ headers: [],+ body: new TextEncoder().encode(`data: ${JSON.stringify(payload)}\n\n`).buffer,+ };+}++function fakeClient({ failCommand, failDeleteClaim = false } = {}) {+ const calls = [];+ const files = new Map();+ const namespaceListings = [+ [{ name: POOL_NAME }, { name: `${POOL_NAME}-recovery` }],+ [{ name: `${POOL_NAME}-recovery` }],+ ];+ const pool = { metadata: { namespace: POOL_NAME, name: POOL_NAME } };+ const template = { metadata: { namespace: POOL_NAME, name: `${POOL_NAME}-template` } };+ const claim = { metadata: { namespace: POOL_NAME, name: 'first-task' } };+ const sandbox = { metadata: { namespace: POOL_NAME, name: 'guest' } };+ const client = {+ calls,+ createPool: async (request) => (calls.push(['createPool', request]), pool),+ createTemplate: async (request) => (calls.push(['createTemplate', request]), template),+ createClaim: async (request) => (calls.push(['createClaim', request]), claim),+ waitClaim: async (value) => (calls.push(['waitClaim', value]), sandbox),+ deleteClaim: async (value) => {+ calls.push(['deleteClaim', value]);+ if (failDeleteClaim) throw new Error('synthetic claim cleanup failure');+ },+ deleteNamespace: async (value) => calls.push(['deleteNamespace', value]),+ listNamespaces: async () => {+ calls.push(['listNamespaces']);+ return namespaceListings.shift() ?? namespaceListings.at(-1) ?? [];+ },+ serviceRequest: async (_sandbox, service, path, request) => {+ if (path === '/status') {+ calls.push(['serviceRequest', service, path, 'status']);+ return { status: 200, headers: [], body: new ArrayBuffer(0) };+ }+ const { command, params } = JSON.parse(new TextDecoder().decode(request.body));+ calls.push(['serviceRequest', service, path, command, params]);+ if (command === failCommand) throw new Error(`synthetic ${command} failure`);+ if (command === 'write_text') files.set(params.path, params.content);+ if (command === 'run_command') {+ const digest = createHash('sha256')+ .update(files.get('/tmp/first-cloud-fleet.txt'))+ .digest('hex');+ files.set('/tmp/first-cloud-fleet.sha256', `${digest}\n`);+ }+ if (command === 'read_text')+ return response({ success: true, content: files.get(params.path) });+ return response({ success: true });+ },+ };+ return client;+}++test('TypeScript example writes, transforms, independently verifies, and cleans up', async () => {+ const client = fakeClient();+ await runTutorial(client, IMAGE_REF, POOL_NAME);++ const poolRequest = client.calls.find(([name]) => name === 'createPool')[1];+ const templateRequest = client.calls.find(([name]) => name === 'createTemplate')[1];+ assert.equal(poolRequest.spec.replicas, 1);+ assert.deepEqual(templateRequest.spec.vmTemplate.services, [+ { name: 'server', targetPort: 8000 },+ ]);+ assert.deepEqual(+ client.calls.filter(([name]) => name === 'serviceRequest').map((call) => call[3]),+ ['status', 'write_text', 'run_command', 'read_text']+ );+ assert.deepEqual(+ client.calls.slice(-4).map(([name]) => name),+ ['deleteClaim', 'deleteNamespace', 'listNamespaces', 'listNamespaces']+ );+ assert.equal(client.calls.find(([name]) => name === 'deleteNamespace')[1], POOL_NAME);+});++test('TypeScript example cleans up after a guest command fails', async () => {+ const client = fakeClient({ failCommand: 'run_command' });+ await assert.rejects(runTutorial(client, IMAGE_REF, POOL_NAME), /synthetic run_command failure/);+ assert.deepEqual(+ client.calls.slice(-4).map(([name]) => name),+ ['deleteClaim', 'deleteNamespace', 'listNamespaces', 'listNamespaces']+ );+});++test('TypeScript example continues namespace cleanup after claim cleanup fails', async () => {+ const client = fakeClient({ failDeleteClaim: true });+ await assert.rejects(runTutorial(client, IMAGE_REF, POOL_NAME), /Cleanup failed/);+ assert.deepEqual(+ client.calls.slice(-4).map(([name]) => name),+ ['deleteClaim', 'deleteNamespace', 'listNamespaces', 'listNamespaces']+ );+});diff --git a/docs/scripts/tests/test_first_cloud_fleet_tutorial.py b/docs/scripts/tests/test_first_cloud_fleet_tutorial.pyindex 5e2e648a85..3a59896de8 100644--- a/docs/scripts/tests/test_first_cloud_fleet_tutorial.py+++ b/docs/scripts/tests/test_first_cloud_fleet_tutorial.py@@ -1,301 +1,148 @@-"""Run the tutorial snippets with released SDK imports and mocked Fleet calls.--Install cua-sandbox==0.4.3 (requires cua-fleet==0.1.14), then run this file.-No credentials, cloud provisioning, or local desktop actions are used.-"""+"""Credential-free checks for the first Cloud Fleet tutorial and Python example."""import asyncio+import hashlibimport importlib.metadataimport inspect-import json-import osfrom pathlib import Path-import re-import tempfile-from types import SimpleNamespace+import sys+from types import ModuleType, SimpleNamespaceimport unittest-from unittest.mock import AsyncMock, Mock, patch--from cua_sandbox import Pool-from fleet_sdk import SdkError-+from unittest.mock import AsyncMock, Mock-PAGE = Path(__file__).resolve().parents[2] / "content/docs/tutorials/your-first-cloud-fleet.mdx"-SOURCE = re.search(r'```python title="first_cloud_fleet.py"\n(.*?)\n```', PAGE.read_text(), re.S)[1]-CREATED_AT = "2026-01-01T00:00:00Z"-POOL_NAME = "first-fleet-" + "1" * 32+DOCS = Path(__file__).resolve().parents[2]+PAGE = DOCS / "content/docs/tutorials/your-first-cloud-fleet.mdx"+RECOVERY = DOCS / "content/docs/how-to-guides/sandbox/recover-first-cloud-fleet.mdx"+PYTHON_SOURCE = DOCS / "public/scripts/first-cloud-fleet/first_cloud_fleet.py"+TYPESCRIPT_SOURCE = DOCS / "public/scripts/first-cloud-fleet/first-cloud-fleet.ts.txt"+POOL_NAME = "first-fleet-0123456789abcdef"+IMAGE_REF = "registry.example/cua-image@sha256:" + "1" * 64-def missing():- return SdkError.Status(operation="get pool", status=404, body="not found")--class TutorialTests(unittest.TestCase):+class PythonExampleTests(unittest.TestCase):def setUp(self):- self.directory = tempfile.TemporaryDirectory()- self.addCleanup(self.directory.cleanup)- self.root = Path(self.directory.name)- self.namespace = {"__name__": "tutorial_test"}- exec(compile(SOURCE, str(PAGE), "exec"), self.namespace)- self.namespace["RECORD"] = self.root / "cloud-fleet-run.json"- self.namespace["uuid4"] = lambda: SimpleNamespace(hex="1" * 32)- self.namespace["Path"] = lambda name: self.root / name- self.sandbox = SimpleNamespace(- name="tutorial-guest",- shell=SimpleNamespace(- run=AsyncMock(- return_value=SimpleNamespace(- success=True,- stdout="Linux tutorial-guest\n",- stderr="",- )- )- ),- screenshot=AsyncMock(return_value=b"synthetic screenshot"),+ self.files = {}+ self.file_api = SimpleNamespace(+ write_text=AsyncMock(side_effect=self.write_text),+ read_text=AsyncMock(side_effect=self.read_text),)+ self.shell = SimpleNamespace(run=AsyncMock(side_effect=self.run_command))+ self.sandbox = SimpleNamespace(files=self.file_api, shell=self.shell)self.claim = AsyncMock()self.claim.__aenter__.return_value = self.sandboxself.claim.__aexit__.return_value = Falseself.pool = SimpleNamespace(- name=POOL_NAME,- resource=SimpleNamespace(metadata=SimpleNamespace(creation_timestamp=CREATED_AT)),claim=Mock(return_value=self.claim),delete=AsyncMock(),)- self.api = SimpleNamespace(- get=AsyncMock(side_effect=missing()),- apply=AsyncMock(return_value=self.pool),- )- self.namespace["Pool"] = self.api- self.make_client = self.namespace["fleet_client"]- self.reservation = SimpleNamespace(name=POOL_NAME, created_at=CREATED_AT)- self.client = SimpleNamespace(- create_namespace=AsyncMock(return_value=self.reservation),- list_namespaces=AsyncMock(side_effect=[[self.reservation], []]),- delete_namespace=AsyncMock(),+ self.pool_api = SimpleNamespace(apply=AsyncMock(return_value=self.pool))+ fake_sdk = ModuleType("cua_sandbox")+ fake_sdk.Image = SimpleNamespace(from_registry=Mock(side_effect=lambda value: value))+ fake_sdk.Pool = self.pool_api+ self.addCleanup(sys.modules.pop, "cua_sandbox", None)+ sys.modules["cua_sandbox"] = fake_sdk+ self.namespace = {"__name__": "tutorial_test"}+ source = PYTHON_SOURCE.read_text()+ exec(compile(source, str(PYTHON_SOURCE), "exec"), self.namespace)++ async def write_text(self, path, content):+ self.files[path] = content++ async def read_text(self, path):+ return self.files[path]++ async def run_command(self, command):+ source_path = self.namespace["SOURCE_PATH"]+ result_path = self.namespace["RESULT_PATH"]+ self.assertIn("sha256sum", command)+ self.files[result_path] = hashlib.sha256(self.files[source_path].encode()).hexdigest() + "\n"+ return SimpleNamespace(success=True, stderr="")++ def test_success_uses_server_files_and_shell_then_cleans_up(self):+ asyncio.run(self.namespace["run_tutorial"](IMAGE_REF, POOL_NAME))++ apply = self.pool_api.apply.await_args+ self.assertEqual(apply.args, (IMAGE_REF,))+ self.assertEqual(apply.kwargs["name"], POOL_NAME)+ self.assertEqual(apply.kwargs["replicas"], 1)+ self.assertEqual(apply.kwargs["services"], {"server": 8000})+ self.pool.claim.assert_called_once_with(+ name="first-task", service="server", time_to_start=900)- self.namespace["fleet_client"] = lambda: self.client+ self.file_api.write_text.assert_awaited_once()+ self.shell.run.assert_awaited_once()+ self.file_api.read_text.assert_awaited_once()+ self.claim.__aexit__.assert_awaited_once()+ self.pool.delete.assert_awaited_once()- def record(self, created_at=CREATED_AT):- self.namespace["RECORD"].write_text(- json.dumps(- {- "name": POOL_NAME,- "created_at": created_at,- }- )- )+ def test_verification_failure_still_releases_claim_and_deletes_pool(self):+ self.file_api.read_text.side_effect = None+ self.file_api.read_text.return_value = "wrong-digest\n"+ with self.assertRaisesRegex(RuntimeError, "Verification failed"):+ asyncio.run(self.namespace["run_tutorial"](IMAGE_REF, POOL_NAME))+ self.claim.__aexit__.assert_awaited_once()+ self.pool.delete.assert_awaited_once()- def test_released_versions_and_public_signatures(self):- self.assertEqual(importlib.metadata.version("cua-sandbox"), "0.4.3")- self.assertEqual(importlib.metadata.version("cua-fleet"), "0.1.14")- self.assertIn('"cua-sandbox==0.4.3"', SOURCE)- self.assertIn('"cua-fleet==0.1.14"', SOURCE)+ def test_claim_failure_still_deletes_pool(self):+ self.claim.__aenter__.side_effect = TimeoutError("synthetic readiness timeout")+ with self.assertRaisesRegex(TimeoutError, "readiness timeout"):+ asyncio.run(self.namespace["run_tutorial"](IMAGE_REF, POOL_NAME))+ self.pool.delete.assert_awaited_once()+++class DocumentationContractTests(unittest.TestCase):+ def test_python_example_matches_the_published_sdk(self):+ from cua_sandbox import Image, Pool++ self.assertEqual(importlib.metadata.version("cua-sandbox"), "0.7.0")+ image = Image.from_registry(IMAGE_REF)inspect.signature(Pool.apply).bind(- self.namespace["Image"].from_registry(self.namespace["IMAGE"]),+ image,name=POOL_NAME,replicas=1,cpu=4,memory_mb=4096,services={"server": 8000},- ttl_seconds_after_created=3600,- )- inspect.signature(Pool.get).bind(POOL_NAME)- inspect.signature(Pool.claim).bind(- self.pool,- name="first-claim",- service="server",- time_to_start=900,- )-- def test_success_saves_result_releases_claim_and_deletes(self):- asyncio.run(self.namespace["run"]())- self.assertEqual((self.root / "cloud-fleet.png").read_bytes(), b"synthetic screenshot")- self.sandbox.shell.run.assert_awaited_once_with("uname -a")- self.claim.__aexit__.assert_awaited_once()- self.client.create_namespace.assert_awaited_once_with(POOL_NAME)- self.client.delete_namespace.assert_awaited_once_with(POOL_NAME)- self.api.get.assert_not_awaited()- record = json.loads(self.namespace["RECORD"].read_text())- self.assertEqual(record, {"name": POOL_NAME, "created_at": CREATED_AT})- self.assertEqual(self.api.apply.call_args.kwargs["ttl_seconds_after_created"], 3600)-- def test_existing_record_cannot_be_overwritten(self):- self.record()- before = self.namespace["RECORD"].read_bytes()- with self.assertRaises(FileExistsError):- asyncio.run(self.namespace["run"]())- self.assertEqual(self.namespace["RECORD"].read_bytes(), before)- self.api.get.assert_not_awaited()- self.api.apply.assert_not_awaited()- self.client.create_namespace.assert_not_awaited()-- def test_name_collision_does_not_apply_claim_or_delete(self):- self.client.create_namespace.side_effect = SdkError.Status(- operation="create namespace", status=409, body="synthetic collision")- with self.assertRaises(SdkError.Status):- asyncio.run(self.namespace["run"]())- self.api.apply.assert_not_awaited()- self.pool.claim.assert_not_called()- self.client.delete_namespace.assert_not_awaited()- def test_reservation_access_denial_is_not_absence(self):- self.client.create_namespace.side_effect = SdkError.Status(- operation="create namespace",- status=403,- body="synthetic denial",+ def test_tutorial_has_persistent_language_tabs_and_both_examples(self):+ page = PAGE.read_text()+ self.assertGreaterEqual(+ page.count('<Tabs groupId="language" persist items={[\'Python\', \'TypeScript\']}>'),+ 2,)- with self.assertRaises(SdkError.Status):- asyncio.run(self.namespace["run"]())- self.api.apply.assert_not_awaited()- self.client.delete_namespace.assert_not_awaited()-- def test_admission_failure_deletes_only_confirmed_reservation(self):- self.api.apply.side_effect = RuntimeError("synthetic admission denial")- with self.assertRaisesRegex(RuntimeError, "admission denial"):- asyncio.run(self.namespace["run"]())- self.pool.claim.assert_not_called()- self.pool.delete.assert_not_awaited()- self.client.delete_namespace.assert_awaited_once_with(POOL_NAME)-- def test_unconfirmed_reservation_refuses_cleanup(self):- self.record(created_at=None)- with self.assertRaisesRegex(RuntimeError, "not confirmed"):- asyncio.run(self.namespace["cleanup"]())- self.client.list_namespaces.assert_not_awaited()- self.client.delete_namespace.assert_not_awaited()-- def test_claim_failure_deletes_created_pool(self):- self.claim.__aenter__.side_effect = TimeoutError("synthetic readiness timeout")- with self.assertRaises(TimeoutError):- asyncio.run(self.namespace["run"]())- self.client.delete_namespace.assert_awaited_once_with(POOL_NAME)-- def test_workload_failure_releases_claim_and_deletes(self):- self.sandbox.shell.run.return_value = SimpleNamespace(- success=False,- stdout="",- stderr="synthetic command failure",- )- with self.assertRaisesRegex(RuntimeError, "command failure"):- asyncio.run(self.namespace["run"]())- self.claim.__aexit__.assert_awaited_once()- self.client.delete_namespace.assert_awaited_once_with(POOL_NAME)- self.sandbox.screenshot.assert_not_awaited()-- def test_screenshot_failure_still_deletes(self):- self.sandbox.screenshot.side_effect = RuntimeError("synthetic screenshot failure")- with self.assertRaisesRegex(RuntimeError, "screenshot failure"):- asyncio.run(self.namespace["run"]())- self.claim.__aexit__.assert_awaited_once()- self.client.delete_namespace.assert_awaited_once_with(POOL_NAME)-- def test_cleanup_deletes_only_recorded_namespace_without_running_workload(self):- self.record()- asyncio.run(self.namespace["cleanup"]())- self.client.delete_namespace.assert_awaited_once_with(POOL_NAME)- self.api.apply.assert_not_awaited()- self.pool.claim.assert_not_called()- self.api.get.assert_not_awaited()-- def test_repeated_cleanup_of_absent_namespace_is_safe(self):- self.record()- self.client.list_namespaces.side_effect = None- self.client.list_namespaces.return_value = []- asyncio.run(self.namespace["cleanup"]())- asyncio.run(self.namespace["cleanup"]())- self.client.delete_namespace.assert_not_awaited()- self.api.apply.assert_not_awaited()-- def test_cleanup_refuses_a_replacement_namespace(self):- self.record(created_at="2025-01-01T00:00:00Z")- with self.assertRaisesRegex(RuntimeError, "identity changed"):- asyncio.run(self.namespace["cleanup"]())- self.client.delete_namespace.assert_not_awaited()-- def test_cleanup_error_retains_record_for_retry(self):- self.record()- self.client.delete_namespace.side_effect = RuntimeError("synthetic connection loss")- with self.assertRaisesRegex(RuntimeError, "connection loss"):- asyncio.run(self.namespace["cleanup"]())- self.assertTrue(self.namespace["RECORD"].exists())-- def test_deletion_poll_is_bounded_and_reports_timeout(self):- self.record()- self.client.list_namespaces.side_effect = None- self.client.list_namespaces.return_value = [self.reservation]- with patch.object(asyncio, "sleep", new_callable=AsyncMock) as sleep:- with self.assertRaises(TimeoutError):- asyncio.run(self.namespace["cleanup"]())- self.assertEqual(sleep.await_count, 60)- self.assertTrue(self.namespace["RECORD"].exists())-- def test_inventory_denial_is_not_successful_cleanup(self):- self.record()- self.client.list_namespaces.side_effect = SdkError.Status(- operation="list namespaces", status=403, body="synthetic denial"- )- with self.assertRaises(SdkError.Status):- asyncio.run(self.namespace["cleanup"]())- self.client.delete_namespace.assert_not_awaited()-- def test_inventory_failure_after_delete_is_not_absence(self):- self.record()- self.client.list_namespaces.side_effect = [- [self.reservation],- SdkError.Status(operation="list namespaces", status=403, body="synthetic denial"),- ]- with self.assertRaises(SdkError.Status):- asyncio.run(self.namespace["cleanup"]())- self.client.delete_namespace.assert_awaited_once_with(POOL_NAME)-- def test_unrelated_namespaces_are_not_deleted(self):- self.record()- other = SimpleNamespace(name="another-project", created_at=CREATED_AT)- self.client.list_namespaces.side_effect = [[other, self.reservation], [other]]- asyncio.run(self.namespace["cleanup"]())- self.client.delete_namespace.assert_awaited_once_with(POOL_NAME)-- def test_client_credentials_use_the_documented_endpoint(self):- sdk = self.namespace["CyclopsClient"]- credentials = Mock(wraps=self.namespace["CyclopsCredentials"])- with (- patch.dict(- os.environ,- {- "CUA_CLIENT_ID": "synthetic-client",- "CUA_CLIENT_SECRET": "synthetic-secret",- "CUA_TOKEN_URL": "https://auth.example/token",- },- clear=True,- ),- patch.object(sdk, "connect_with_native_http_client") as connect,- patch.dict(self.namespace, {"CyclopsCredentials": credentials}),- ):- self.assertIs(self.make_client(), connect.return_value)- configuration = connect.call_args.args[0]- self.assertEqual(configuration.base_url, "https://run.cua.ai")- self.assertEqual(configuration.token_url, "https://auth.example/token")- credentials.assert_called_once_with("synthetic-client", "synthetic-secret")-- def test_static_token_takes_precedence_for_namespace_operations(self):- sdk = self.namespace["CyclopsClient"]- with (- patch.dict(- os.environ,- {- "FLEETS_TOKEN": "synthetic-token",- "CUA_FLEET_BASE_URL": "https://fleet.example",- },- clear=True,- ),- patch.object(sdk, "connect_with_access_token_and_native_http_client") as connect,- ):- self.assertIs(self.make_client(), connect.return_value)- configuration, token = connect.call_args.args- self.assertEqual(configuration.base_url, "https://fleet.example")- self.assertEqual(token, "synthetic-token")+ self.assertIn("first_cloud_fleet.py", page)+ self.assertIn("first-cloud-fleet.ts", page)+ self.assertIn("cua-sandbox==0.7.0", page)+ self.assertIn("@trycua/[email protected]", page)++ def test_tutorial_requires_server_and_independent_verification(self):+ page = PAGE.read_text()+ python = PYTHON_SOURCE.read_text()+ typescript = TYPESCRIPT_SOURCE.read_text()+ self.assertIn('services={"server": 8000}', python)+ self.assertIn("services: [{ name: 'server', targetPort: 8000 }]", typescript)+ self.assertIn("hashlib.sha256", python)+ self.assertIn("createHash('sha256')", typescript)+ self.assertIn("does not rely on the guest shell to verify its own result", page)++ def test_tutorial_has_no_driver_prerequisite_or_unsupported_image_claim(self):+ page = PAGE.read_text()+ self.assertIn("does not require Cua Driver", page)+ self.assertNotIn("Omarchy", page)+ self.assertNotIn("Driver-compatible", page)+ self.assertNotIn("supported image", page.lower())++ def test_cleanup_is_honest_and_recovery_is_narrow(self):+ page = PAGE.read_text()+ recovery = RECOVERY.read_text()+ self.assertIn("can incur usage charges until it is", page)+ self.assertIn("accepted cleanup request can precede final removal", page)+ self.assertIn("/how-to-guides/sandbox/recover-first-cloud-fleet", page)+ self.assertIn("Do not rerun the", recovery)+ self.assertIn("exact `first-fleet-...` name", recovery)+ self.assertIn("account inventory until the exact pool name is absent", recovery)if __name__ == "__main__":diff --git a/docs/scripts/tests/test_fleet_docs_version_facts.py b/docs/scripts/tests/test_fleet_docs_version_facts.pynew file mode 100644index 0000000000..7e556f903b--- /dev/null+++ b/docs/scripts/tests/test_fleet_docs_version_facts.py@@ -0,0 +1,114 @@+"""Keep maintained Fleet and Sandbox documentation versions aligned with manifests."""++from __future__ import annotations++import json+from pathlib import Path+import re+import tomllib+++REPOSITORY = Path(__file__).resolve().parents[3]+DOCS = REPOSITORY / "docs" / "content" / "docs"+++def load_project(path: str) -> dict:+ with (REPOSITORY / path).open("rb") as stream:+ return tomllib.load(stream)["project"]+++SANDBOX_PROJECT = load_project("libs/python/cua-sandbox/pyproject.toml")+CLI_PROJECT = load_project("libs/python/cua-cli/pyproject.toml")+CUA_PROJECT = load_project("libs/python/cua/pyproject.toml")+TYPESCRIPT_FLEET = json.loads(+ (REPOSITORY / "libs/typescript/fleet/package.json").read_text()+)++SANDBOX_VERSION = SANDBOX_PROJECT["version"]+CLI_VERSION = CLI_PROJECT["version"]+CUA_VERSION = CUA_PROJECT["version"]+TYPESCRIPT_FLEET_VERSION = TYPESCRIPT_FLEET["version"]+PYTHON_FLEET_VERSION = next(+ dependency.removeprefix("cua-fleet==")+ for dependency in SANDBOX_PROJECT["dependencies"]+ if dependency.startswith("cua-fleet==")+)+++EXPECTED_FACTS = {+ "concepts/how-fleet-images-work.mdx": (f"`cua-sandbox` {SANDBOX_VERSION}",),+ "concepts/how-sandboxes-work.mdx": (f"`cua-sandbox` {SANDBOX_VERSION}",),+ "concepts/sandbox-lifecycle.mdx": (f"`cua-sandbox` {SANDBOX_VERSION}",),+ "how-to-guides/sandbox/choose-an-image.mdx": (+ f"`cua-sandbox` {SANDBOX_VERSION}",+ ),+ "how-to-guides/sandbox/images.mdx": (f"`cua-sandbox` {SANDBOX_VERSION}",),+ "how-to-guides/sandbox/minecraft.mdx": (f"cua-sandbox {SANDBOX_VERSION}",),+ "how-to-guides/sandbox/prepare-and-reference-a-fleet-image.mdx": (+ f"`cua-sandbox` {SANDBOX_VERSION}",+ f"`cua` {CUA_VERSION}",+ ),+ "how-to-guides/sandbox/run-omarchy-on-cloud-fleet.mdx": (+ f'"cua-sandbox=={SANDBOX_VERSION}"',+ ),+ "how-to-guides/sandbox/share-service-with-signed-url.mdx": (+ f"`@trycua/fleet` {TYPESCRIPT_FLEET_VERSION}",+ f"`cua-sandbox` {SANDBOX_VERSION}",+ ),+ "how-to-guides/sandbox/troubleshoot-fleet-pools.mdx": (+ f"`@trycua/fleet@{TYPESCRIPT_FLEET_VERSION}`",+ ),+ "how-to-guides/sandbox/tunneling.mdx": (+ f"`cua-sandbox`\n{SANDBOX_VERSION}",+ f"`cua=={CUA_VERSION}`",+ ),+ "reference/cua-cli/cli-reference.mdx": (f"`cua-cli` **{CLI_VERSION}**",),+ "reference/sandbox-sdk/image.mdx": (f"`cua-sandbox` {SANDBOX_VERSION}",),+ "reference/sandbox-sdk/index.mdx": (+ f"`cua-sandbox` {SANDBOX_VERSION}",+ f"`cua` {CUA_VERSION}",+ f"`@trycua/fleet` {TYPESCRIPT_FLEET_VERSION}",+ ),+ "reference/sandbox-sdk/interfaces.mdx": (+ f"`cua-sandbox` {SANDBOX_VERSION}",+ ),+ "reference/sandbox-sdk/pool.mdx": (+ f"`cua_sandbox` {SANDBOX_VERSION}",+ f"`cua-fleet` {PYTHON_FLEET_VERSION}",+ ),+ "reference/sandbox-sdk/typescript.mdx": (+ f"`@trycua/fleet` {TYPESCRIPT_FLEET_VERSION}",+ f"npm install @trycua/fleet@{TYPESCRIPT_FLEET_VERSION}",+ ),+}+++def test_maintained_version_facts_match_package_manifests() -> None:+ for relative_path, expected_facts in EXPECTED_FACTS.items():+ text = (DOCS / relative_path).read_text()+ for fact in expected_facts:+ assert fact in text, f"{relative_path} must contain manifest fact {fact!r}"+++def test_owned_pages_drop_superseded_maintained_versions_and_commands() -> None:+ stale_facts = (+ re.compile(r"cua-sandbox(?:`|\*\*)?[ =@]+0\.4\.3\b"),+ re.compile(r"cua-fleet(?:`|\*\*)?[ =@]+0\.1\.14\b"),+ re.compile(r"@trycua/fleet(?:`|\*\*)?[ =@]+0\.1\.1\b"),+ re.compile(r"cua-cli(?:`|\*\*)?[ =@]+0\.1\.14\b"),+ )+ obsolete_commands = (+ re.compile(r"\bcua (?:sb|sandbox) create\b"),+ re.compile(r"\bcua (?:sb|sandbox) start\b"),+ )++ for relative_path in EXPECTED_FACTS:+ text = (DOCS / relative_path).read_text()+ for pattern in (*stale_facts, *obsolete_commands):+ assert not pattern.search(text), f"{relative_path} contains {pattern.pattern!r}"+++def test_minecraft_keeps_its_intentional_historical_version() -> None:+ text = (DOCS / "how-to-guides/sandbox/minecraft.mdx").read_text()+ assert "The local recipe was originally developed against 0.3.3" in text+ assert "needs cua-sandbox 0.3.3; before that" in textdiff --git a/docs/scripts/tests/test_fleet_driver_guide.py b/docs/scripts/tests/test_fleet_driver_guide.pynew file mode 100644index 0000000000..f72f6ce1d8--- /dev/null+++ b/docs/scripts/tests/test_fleet_driver_guide.py@@ -0,0 +1,58 @@+"""Assert the Fleet Driver how-to preserves the shared service contract."""++from pathlib import Path+import re+import unittest+++ROOT = Path(__file__).resolve().parents[3]+PAGE = (+ ROOT+ / "docs/content/docs/how-to-guides/sandbox/control-the-desktop-with-cua-driver.mdx"+)+FLEET_HELPER = ROOT / "libs/cua-driver/typescript/src/fleet.ts"+++class FleetDriverGuideTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.page = PAGE.read_text()+ cls.python_tab, cls.typescript_tab = re.findall(+ r'<Tab value="(?:Python|TypeScript)">(.*?)</Tab>', cls.page, re.DOTALL+ )++ def test_uses_persistent_language_tabs(self):+ self.assertIn(+ '<Tabs groupId="language" persist items={[\'Python\', \'TypeScript\']}>',+ self.page,+ )++ def test_both_tabs_resolve_the_advertised_mcp_service(self):+ self.assertIn(+ 'sb.driver.connect(service="mcp", transport="mcp")', self.python_tab+ )+ self.assertIn("connectFleetDriver({ client, sandbox })", self.typescript_tab)+ self.assertNotIn("service:", self.typescript_tab)+ self.assertRegex(+ FLEET_HELPER.read_text(),+ r"connectFleetDriver\(\{[\s\S]*?service = 'mcp'",+ )++ def test_shared_requirements_and_cleanup_are_outside_tabs(self):+ before_tabs, after_tabs = self.page.split(+ '<Tabs groupId="language" persist items=', 1+ )+ after_tabs = after_tabs.split("</Tabs>", 1)[1]+ self.assertIn('ai.cua.driver.envelopes', before_tabs)+ self.assertIn("computer-server", before_tabs)+ self.assertIn("close Driver", after_tabs)+ self.assertIn("release the claim", after_tabs)++ def test_does_not_claim_image_support_or_type_script_sandbox_parity(self):+ self.assertIn("No Fleet image is implied to provide this capability", self.page)+ self.assertRegex(self.page, r"not a TypeScript Sandbox\s+SDK")+ self.assertNotRegex(self.page, r"Image\.from_registry|public\.ecr\.aws")+++if __name__ == "__main__":+ unittest.main()diff --git a/docs/scripts/tests/test_sandbox_secret_example.py b/docs/scripts/tests/test_sandbox_secret_example.pyindex 27c721e361..a140b3f9f9 100644--- a/docs/scripts/tests/test_sandbox_secret_example.py+++ b/docs/scripts/tests/test_sandbox_secret_example.py@@ -1,7 +1,8 @@"""Exercise the documented commands with synthetic secrets and a local shell.-Run with Python and cua-sandbox==0.4.3 installed. No sandbox is provisioned;-the released Shell interface sends commands to a disposable local test transport.+Run with Python and the source-matched cua-sandbox package installed. No sandbox+is provisioned; the Shell interface sends commands to a disposable local test+transport."""import asyncio@@ -14,6 +15,7 @@ import shleximport subprocessimport sysimport tempfile+import tomllibimport typesimport unittestfrom unittest.mock import patch@@ -22,6 +24,11 @@ from cua_sandbox.interfaces.shell import ShellPAGE = Path(__file__).resolve().parents[2] / "content/docs/how-to-guides/sandbox/secrets.mdx"+SANDBOX_PROJECT = (+ Path(__file__).resolve().parents[3] / "libs/python/cua-sandbox/pyproject.toml"+)+with SANDBOX_PROJECT.open("rb") as stream:+ SANDBOX_VERSION = tomllib.load(stream)["project"]["version"]BLOCKS = re.findall(r"```python\n(.*?)\n```", PAGE.read_text(), re.DOTALL)SYNTHETIC = "synthetic space 'quote' \"double\" $HOME $(exit 91) `exit 92`\nEOF\nlast\n"@@ -56,7 +63,7 @@ class SecretExampleTests(unittest.TestCase):return namespace[function_name]def test_released_api_and_python_syntax(self):- self.assertEqual(importlib.metadata.version("cua-sandbox"), "0.4.3")+ self.assertEqual(importlib.metadata.version("cua-sandbox"), SANDBOX_VERSION)for block in BLOCKS:compile(block, str(PAGE), "exec")diff --git a/scripts/docs-generators/README.md b/scripts/docs-generators/README.mdindex 4cdf269350..366fb63a36 100644--- a/scripts/docs-generators/README.md+++ b/scripts/docs-generators/README.md@@ -10,6 +10,7 @@ scripts/docs-generators/├── runner.ts # Main orchestrator that runs generators├── cua-driver.ts # cua-driver (Rust) generator├── lume.ts # Lume (Swift) generator+├── sandbox.ts # Sandbox package/image fact generator├── cua-cli.ts # Cua CLI (TypeScript) generator (planned)├── mcp-server.ts # MCP Server (Python) generator (planned)├── python-sdk.ts # Python SDK generator (planned)@@ -109,6 +110,7 @@ The `.github/workflows/docs-sync-check.yml` workflow:| ----------------------- | -------------- | ------------------------- || cua-driver | ✅ Implemented | CLI + MCP tools || lume | ✅ Implemented | CLI + HTTP API |+| sandbox | ✅ Implemented | Package + image facts || cua-cli | ⏸️ Planned | Needs yargs introspection || mcp-server | ⏸️ Planned | Needs MCP tool extraction || computer-sdk-python | ⏸️ Planned | Needs Sphinx/pydoc |diff --git a/scripts/docs-generators/config.json b/scripts/docs-generators/config.jsonindex a0c0ad70c9..123003ffa7 100644--- a/scripts/docs-generators/config.json+++ b/scripts/docs-generators/config.json@@ -75,6 +75,39 @@"enabled": true,"notes": "Generates cli-reference.mdx + http-api.mdx from the Swift binary's `dump-docs` output. These files live under the Diátaxis Reference tree; task-oriented Lume docs belong under how-to-guides/lume."},+ "sandbox": {+ "name": "Sandbox package and image facts",+ "language": "typescript",+ "sourcePath": "libs/python/cua-sandbox",+ "docsOutputPath": "docs/content/docs/reference/sandbox-sdk",+ "generatorScript": "scripts/docs-generators/sandbox.ts",+ "watchPaths": [+ "libs/python/cua/pyproject.toml",+ "libs/python/computer-server/pyproject.toml",+ "libs/typescript/fleet/package.json",+ "libs/cua-driver/hyprland-plugin/packaging/release/profiles/omarchy-stable-20260910.json",+ "scripts/docs-generators/sandbox-facts.json",+ "scripts/docs-generators/sandbox-facts.schema.json",+ "scripts/docs-generators/sandbox.test.ts"+ ],+ "buildCommand": null,+ "buildDirectory": ".",+ "extractionMethod": "source-manifest",+ "outputs": [+ {+ "type": "reference",+ "outputFile": "runtime-support.mdx",+ "extractCommand": null+ },+ {+ "type": "reference",+ "outputFile": "os-image-catalog.mdx",+ "extractCommand": null+ }+ ],+ "enabled": true,+ "notes": "Generates package versions and client image mappings from public source manifests, then combines them with schema-checked deployment qualification facts."+ },"cua-cli": {"name": "Cua CLI","language": "typescript",diff --git a/scripts/docs-generators/runner.ts b/scripts/docs-generators/runner.tsindex 3f5bd6cb91..274dd9cafd 100644--- a/scripts/docs-generators/runner.ts+++ b/scripts/docs-generators/runner.ts@@ -349,11 +349,20 @@ function testGeneratorRouting(config: Config): void {],['lume']);+ assertSelection(+ config,+ [+ 'libs/python/cua-sandbox/cua_sandbox/image.py',+ 'docs/content/docs/reference/sandbox-sdk/os-image-catalog.mdx',+ 'scripts/docs-generators/sandbox-facts.json',+ ],+ ['sandbox']+ );for (const file of ['mcp-tools.mdx', 'mcp-tools-linux.mdx', 'mcp-tools-windows.mdx']) {assertSelection(config, [`docs/content/docs/reference/cua-driver/${file}`], ['cua-driver']);}- assertSelection(config, ['scripts/docs-generators/runner.ts'], ['cua-driver', 'lume']);- assertSelection(config, ['scripts/docs-generators/config.json'], ['cua-driver', 'lume']);+ assertSelection(config, ['scripts/docs-generators/runner.ts'], ['cua-driver', 'lume', 'sandbox']);+ assertSelection(config, ['scripts/docs-generators/config.json'], ['cua-driver', 'lume', 'sandbox']);console.log(`Generator routing assertions passed with pinned tsx ${tsxVersion}`);}diff --git a/scripts/docs-generators/sandbox-facts.json b/scripts/docs-generators/sandbox-facts.jsonnew file mode 100644index 0000000000..ffddd61249--- /dev/null+++ b/scripts/docs-generators/sandbox-facts.json@@ -0,0 +1,46 @@+{+ "$schema": "./sandbox-facts.schema.json",+ "schemaVersion": 1,+ "qualifiedImages": [+ {+ "id": "omarchy-amd64-4-0-2-1",+ "image": "public.ecr.aws/k5j5w0x5/cua-omarchy-workspace@sha256:dd09f70f8cd35eca7871dff000538302baad63688a3008803f2238492802d743",+ "os": "Linux",+ "distribution": "Omarchy 4.0.2-1 (Arch Linux-based), amd64",+ "architecture": "amd64",+ "desktop": "Hyprland / Wayland",+ "kind": "Fleet containerDisk",+ "services": {+ "server": 8000,+ "mcp": 3000+ },+ "components": {+ "computerServer": "0.3.46",+ "embeddedDriver": "0.22.2",+ "directDriver": "0.26.1"+ },+ "qualification": {+ "boot": true,+ "serviceReadiness": true+ }+ }+ ],+ "publishedCandidates": [+ {+ "os": "Linux",+ "distribution": "NixOS; release and architecture not recorded in the publication summary",+ "desktop": "StumpWM",+ "kind": "Published candidate image",+ "image": "public.ecr.aws/k5j5w0x5/cua-nixos-stumpwm:git-ee87f38043c043831a8761016015d6ef5ae783d9",+ "limits": "[Publication summary](https://github.com/trycua/cua/pull/3585) reports computer-server and Cua Driver included, guest tests and CI anonymous-pull checks passed. Component versions, service ports, and Fleet claim checks are not recorded there. Commit-named candidate tag, not a digest pin or `latest`; no built-in SDK mapping."+ },+ {+ "os": "Linux",+ "distribution": "NixOS; release and architecture not recorded in the publication summary",+ "desktop": "Xfce / Xfwm4",+ "kind": "Published candidate image",+ "image": "public.ecr.aws/k5j5w0x5/cua-nixos-xfce:git-ee87f38043c043831a8761016015d6ef5ae783d9",+ "limits": "[Publication summary](https://github.com/trycua/cua/pull/3585) reports computer-server and Cua Driver included, guest tests and CI anonymous-pull checks passed. Component versions, service ports, and Fleet claim checks are not recorded there. Commit-named candidate tag, not a digest pin or `latest`; no built-in SDK mapping."+ }+ ]+}diff --git a/scripts/docs-generators/sandbox-facts.schema.json b/scripts/docs-generators/sandbox-facts.schema.jsonnew file mode 100644index 0000000000..5c3d00bbfe--- /dev/null+++ b/scripts/docs-generators/sandbox-facts.schema.json@@ -0,0 +1,84 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://cua.ai/schemas/docs/sandbox-facts.schema.json",+ "title": "Sandbox documentation deployment facts",+ "type": "object",+ "additionalProperties": false,+ "required": ["schemaVersion", "qualifiedImages", "publishedCandidates"],+ "properties": {+ "schemaVersion": { "const": 1 },+ "qualifiedImages": {+ "type": "array",+ "minItems": 1,+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "id",+ "image",+ "os",+ "distribution",+ "architecture",+ "desktop",+ "kind",+ "services",+ "components",+ "qualification"+ ],+ "properties": {+ "id": { "type": "string", "pattern": "^[a-z0-9-]+$" },+ "image": { "type": "string", "pattern": "@sha256:[0-9a-f]{64}$" },+ "os": { "type": "string" },+ "distribution": { "type": "string" },+ "architecture": { "type": "string" },+ "desktop": { "type": "string" },+ "kind": { "type": "string" },+ "services": {+ "type": "object",+ "additionalProperties": false,+ "required": ["server", "mcp"],+ "properties": {+ "server": { "type": "integer", "minimum": 1, "maximum": 65535 },+ "mcp": { "type": "integer", "minimum": 1, "maximum": 65535 }+ }+ },+ "components": {+ "type": "object",+ "additionalProperties": false,+ "required": ["computerServer", "embeddedDriver", "directDriver"],+ "properties": {+ "computerServer": { "type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$" },+ "embeddedDriver": { "type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$" },+ "directDriver": { "type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$" }+ }+ },+ "qualification": {+ "type": "object",+ "additionalProperties": false,+ "required": ["boot", "serviceReadiness"],+ "properties": {+ "boot": { "const": true },+ "serviceReadiness": { "const": true }+ }+ }+ }+ }+ },+ "publishedCandidates": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": ["os", "distribution", "desktop", "kind", "image", "limits"],+ "properties": {+ "os": { "type": "string" },+ "distribution": { "type": "string" },+ "desktop": { "type": "string" },+ "kind": { "type": "string" },+ "image": { "type": "string" },+ "limits": { "type": "string" }+ }+ }+ }+ }+}diff --git a/scripts/docs-generators/sandbox.test.ts b/scripts/docs-generators/sandbox.test.tsnew file mode 100644index 0000000000..e8c932fcbc--- /dev/null+++ b/scripts/docs-generators/sandbox.test.ts@@ -0,0 +1,49 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import {+ loadManifest,+ loadSourceFacts,+ renderCatalog,+ replaceGeneratedSection,+ validateManifest,+} from './sandbox';++test('qualified image facts conform to the local schema contract', () => {+ const manifest = loadManifest();+ assert.equal(manifest.schemaVersion, 1);+ assert.equal(manifest.qualifiedImages.length, 1);+ assert.match(manifest.qualifiedImages[0].image, /@sha256:[0-9a-f]{64}$/);+});++test('schema validation rejects mutable qualified images and undeclared fields', () => {+ const manifest = structuredClone(loadManifest()) as unknown as Record<string, unknown>;+ const images = manifest.qualifiedImages as Array<Record<string, unknown>>;+ images[0].image = 'public.ecr.aws/example/workspace:latest';+ assert.throws(() => validateManifest(manifest), /image is invalid/);++ const withUndeclaredEvidence = structuredClone(loadManifest()) as unknown as Record<+ string,+ unknown+ >;+ const qualified = withUndeclaredEvidence.qualifiedImages as Array<Record<string, unknown>>;+ qualified[0].evidenceUrl = 'https://example.invalid/qualification-run';+ assert.throws(() => validateManifest(withUndeclaredEvidence), /keys must be/);+});++test('catalog distinguishes source mappings from deployment qualification', () => {+ const catalog = renderCatalog(loadManifest(), loadSourceFacts());+ assert.match(catalog, /Image\.linux\(\).*mapping/);+ assert.match(catalog, /Deployment qualification recorded boot and readiness/);+ assert.match(catalog, /server:8000/);+ assert.match(catalog, /mcp:3000/);+ assert.match(catalog, /embedded Driver 0\.22\.2/);+ assert.match(catalog, /direct Driver qualification used 0\.26\.1/);+});++test('generated section replacement is deterministic and requires markers', () => {+ const input = 'before\n{/* GENERATED:demo:start */}\nold\n{/* GENERATED:demo:end */}\nafter\n';+ const once = replaceGeneratedSection(input, 'demo', 'new');+ assert.equal(replaceGeneratedSection(once, 'demo', 'new'), once);+ assert.throws(() => replaceGeneratedSection('unmarked', 'demo', 'new'), /Expected one/);+});diff --git a/scripts/docs-generators/sandbox.ts b/scripts/docs-generators/sandbox.tsnew file mode 100644index 0000000000..c04aa81f16--- /dev/null+++ b/scripts/docs-generators/sandbox.ts@@ -0,0 +1,439 @@+#!/usr/bin/env npx tsx++/** Generate the source-backed Sandbox package and image facts in public docs. */++import * as fs from 'node:fs';+import * as path from 'node:path';+import { parseArgs } from 'node:util';++const ROOT = path.resolve(__dirname, '../..');+const FACTS_PATH = path.join(__dirname, 'sandbox-facts.json');+const RUNTIME_DOC = path.join(ROOT, 'docs/content/docs/reference/sandbox-sdk/runtime-support.mdx');+const CATALOG_DOC = path.join(ROOT, 'docs/content/docs/reference/sandbox-sdk/os-image-catalog.mdx');++type Services = { server: number; mcp: number };+type Components = { computerServer: string; embeddedDriver: string; directDriver: string };++export interface QualifiedImage {+ id: string;+ image: string;+ os: string;+ distribution: string;+ architecture: string;+ desktop: string;+ kind: string;+ services: Services;+ components: Components;+ qualification: { boot: true; serviceReadiness: true };+}++export interface PublishedCandidate {+ os: string;+ distribution: string;+ desktop: string;+ kind: string;+ image: string;+ limits: string;+}++export interface SandboxFactsManifest {+ $schema: string;+ schemaVersion: 1;+ qualifiedImages: QualifiedImage[];+ publishedCandidates: PublishedCandidate[];+}++interface SourceFacts {+ sandboxVersion: string;+ cuaVersion: string;+ pythonFleetVersion: string;+ typescriptFleetVersion: string;+ sandboxDriverVersion: string;+ computerServerVersion: string;+ embeddedDriverConstraint: string;+ qualifiedDirectDriverVersion: string;+ linuxFleetImage: string;+ windowsFleetImage: string;+ linuxContainerImage: string;+ macosSequoiaImage: string;+ macosTahoeImage: string;+}++const VERSION = /^\d+\.\d+\.\d+$/;+const DIGEST_REF = /@sha256:[0-9a-f]{64}$/;++function object(value: unknown, label: string): Record<string, unknown> {+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {+ throw new Error(`${label} must be an object`);+ }+ return value as Record<string, unknown>;+}++function exactKeys(value: Record<string, unknown>, keys: readonly string[], label: string): void {+ const expected = [...keys].sort();+ const actual = Object.keys(value).sort();+ if (actual.join('\n') !== expected.join('\n')) {+ throw new Error(`${label} keys must be ${expected.join(', ')}; got ${actual.join(', ')}`);+ }+}++function string(value: unknown, label: string, pattern?: RegExp): string {+ if (typeof value !== 'string' || value.length === 0 || (pattern && !pattern.test(value))) {+ throw new Error(`${label} is invalid`);+ }+ return value;+}++function port(value: unknown, label: string): number {+ if (!Number.isInteger(value) || Number(value) < 1 || Number(value) > 65535) {+ throw new Error(`${label} must be a TCP port`);+ }+ return Number(value);+}++/** Validate without a network fetch or an unpinned schema-validator dependency. */+export function validateManifest(value: unknown): SandboxFactsManifest {+ const root = object(value, 'manifest');+ exactKeys(+ root,+ ['$schema', 'schemaVersion', 'qualifiedImages', 'publishedCandidates'],+ 'manifest'+ );+ if (root.$schema !== './sandbox-facts.schema.json' || root.schemaVersion !== 1) {+ throw new Error('manifest schema identity or version is invalid');+ }+ if (!Array.isArray(root.qualifiedImages) || root.qualifiedImages.length === 0) {+ throw new Error('qualifiedImages must be a non-empty array');+ }+ const ids = new Set<string>();+ const qualifiedImages = root.qualifiedImages.map((entry, index): QualifiedImage => {+ const item = object(entry, `qualifiedImages[${index}]`);+ exactKeys(+ item,+ [+ 'id',+ 'image',+ 'os',+ 'distribution',+ 'architecture',+ 'desktop',+ 'kind',+ 'services',+ 'components',+ 'qualification',+ ],+ `qualifiedImages[${index}]`+ );+ const id = string(item.id, `qualifiedImages[${index}].id`, /^[a-z0-9-]+$/);+ if (ids.has(id)) throw new Error(`duplicate qualified image id ${id}`);+ ids.add(id);+ const services = object(item.services, `${id}.services`);+ exactKeys(services, ['server', 'mcp'], `${id}.services`);+ const components = object(item.components, `${id}.components`);+ exactKeys(components, ['computerServer', 'embeddedDriver', 'directDriver'], `${id}.components`);+ const qualification = object(item.qualification, `${id}.qualification`);+ exactKeys(qualification, ['boot', 'serviceReadiness'], `${id}.qualification`);+ if (qualification.boot !== true || qualification.serviceReadiness !== true) {+ throw new Error(`${id}.qualification must record boot and service readiness`);+ }+ return {+ id,+ image: string(item.image, `${id}.image`, DIGEST_REF),+ os: string(item.os, `${id}.os`),+ distribution: string(item.distribution, `${id}.distribution`),+ architecture: string(item.architecture, `${id}.architecture`),+ desktop: string(item.desktop, `${id}.desktop`),+ kind: string(item.kind, `${id}.kind`),+ services: {+ server: port(services.server, `${id}.services.server`),+ mcp: port(services.mcp, `${id}.services.mcp`),+ },+ components: {+ computerServer: string(components.computerServer, `${id}.computerServer`, VERSION),+ embeddedDriver: string(components.embeddedDriver, `${id}.embeddedDriver`, VERSION),+ directDriver: string(components.directDriver, `${id}.directDriver`, VERSION),+ },+ qualification: { boot: true, serviceReadiness: true },+ };+ });+ if (!Array.isArray(root.publishedCandidates)) {+ throw new Error('publishedCandidates must be an array');+ }+ const publishedCandidates = root.publishedCandidates.map((entry, index): PublishedCandidate => {+ const item = object(entry, `publishedCandidates[${index}]`);+ exactKeys(+ item,+ ['os', 'distribution', 'desktop', 'kind', 'image', 'limits'],+ `publishedCandidates[${index}]`+ );+ return {+ os: string(item.os, `publishedCandidates[${index}].os`),+ distribution: string(item.distribution, `publishedCandidates[${index}].distribution`),+ desktop: string(item.desktop, `publishedCandidates[${index}].desktop`),+ kind: string(item.kind, `publishedCandidates[${index}].kind`),+ image: string(item.image, `publishedCandidates[${index}].image`),+ limits: string(item.limits, `publishedCandidates[${index}].limits`),+ };+ });+ return {+ $schema: './sandbox-facts.schema.json',+ schemaVersion: 1,+ qualifiedImages,+ publishedCandidates,+ };+}++export function loadManifest(file = FACTS_PATH): SandboxFactsManifest {+ return validateManifest(JSON.parse(fs.readFileSync(file, 'utf8')));+}++function read(relativePath: string): string {+ return fs.readFileSync(path.join(ROOT, relativePath), 'utf8');+}++function capture(contents: string, pattern: RegExp, label: string): string {+ const match = contents.match(pattern);+ if (!match?.[1]) throw new Error(`Could not extract ${label}`);+ return match[1];+}++function projectVersion(relativePath: string): string {+ const contents = read(relativePath);+ return capture(contents, /\[project\][\s\S]*?\nversion\s*=\s*"([^"]+)"/, relativePath);+}++function pythonConstant(relativePath: string, name: string): string {+ const contents = read(relativePath);+ return capture(+ contents,+ new RegExp(`^${name}\\s*=\\s*"([^"]+)"`, 'm'),+ `${relativePath}:${name}`+ );+}++export function loadSourceFacts(): SourceFacts {+ const sandboxProject = read('libs/python/cua-sandbox/pyproject.toml');+ const computerServerProject = read('libs/python/computer-server/pyproject.toml');+ const runtimeImages = read('libs/python/cua-sandbox/cua_sandbox/runtime/images.py');+ const profile = JSON.parse(+ read('libs/cua-driver/hyprland-plugin/packaging/release/profiles/omarchy-stable-20260910.json')+ ) as { source?: { driver_version?: string } };+ return {+ sandboxVersion: projectVersion('libs/python/cua-sandbox/pyproject.toml'),+ cuaVersion: projectVersion('libs/python/cua/pyproject.toml'),+ pythonFleetVersion: capture(sandboxProject, /"cua-fleet==([^"]+)"/, 'cua-fleet pin'),+ typescriptFleetVersion: String(+ (JSON.parse(read('libs/typescript/fleet/package.json')) as { version: string }).version+ ),+ sandboxDriverVersion: capture(sandboxProject, /"cua-driver==([^"]+)"/, 'Sandbox Driver pin'),+ computerServerVersion: projectVersion('libs/python/computer-server/pyproject.toml'),+ embeddedDriverConstraint: capture(+ computerServerProject,+ /"cua-driver([^";]+)"/,+ 'computer-server embedded Driver constraint'+ ),+ qualifiedDirectDriverVersion: string(+ profile.source?.driver_version,+ 'Omarchy release profile Driver version',+ VERSION+ ),+ linuxFleetImage: pythonConstant(+ 'libs/python/cua-sandbox/cua_sandbox/image.py',+ 'DEFAULT_LINUX_REGISTRY_IMAGE'+ ),+ windowsFleetImage: pythonConstant(+ 'libs/python/cua-sandbox/cua_sandbox/image.py',+ 'DEFAULT_WINDOWS_REGISTRY_IMAGE'+ ),+ linuxContainerImage: pythonConstant(+ 'libs/python/cua-sandbox/cua_sandbox/runtime/images.py',+ 'UBUNTU_XFCE'+ ),+ macosSequoiaImage: capture(runtimeImages, /"15":\s*"([^"]+)"/, 'macOS Sequoia image mapping'),+ macosTahoeImage: capture(runtimeImages, /"26":\s*"([^"]+)"/, 'macOS Tahoe image mapping'),+ };+}++function assertQualificationSources(manifest: SandboxFactsManifest, source: SourceFacts): void {+ for (const image of manifest.qualifiedImages) {+ if (image.components.computerServer !== source.computerServerVersion) {+ throw new Error(`${image.id} computer-server version disagrees with its package manifest`);+ }+ if (!source.embeddedDriverConstraint.includes(image.components.embeddedDriver)) {+ throw new Error(`${image.id} embedded Driver is outside the computer-server package mapping`);+ }+ if (image.components.directDriver !== source.qualifiedDirectDriverVersion) {+ throw new Error(+ `${image.id} direct Driver disagrees with the public Omarchy release profile`+ );+ }+ }+}++function generatedSection(name: string, body: string): string {+ return `{/* GENERATED:${name}:start */}\n${body.trim()}\n{/* GENERATED:${name}:end */}`;+}++export function replaceGeneratedSection(document: string, name: string, body: string): string {+ const start = `{/* GENERATED:${name}:start */}`;+ const end = `{/* GENERATED:${name}:end */}`;+ const startIndex = document.indexOf(start);+ const endIndex = document.indexOf(end);+ if (startIndex < 0 || endIndex < startIndex || document.indexOf(start, startIndex + 1) >= 0) {+ throw new Error(`Expected one generated section named ${name}`);+ }+ return `${document.slice(0, startIndex)}${generatedSection(name, body)}${document.slice(+ endIndex + end.length+ )}`;+}++export function renderRuntimePackageFacts(source: SourceFacts): string {+ return `This reference describes the Python Sandbox SDK in \`cua-sandbox\` **${source.sandboxVersion}**, exported+by \`cua\` **${source.cuaVersion}**. An accepted image specification or generated Fleet template is+evidence of SDK behavior, not proof that a guest boots on every host or deployment.`;+}++export function renderBuiltinMappings(source: SourceFacts): string {+ return `| Built-in image | Registry artifact |+| --- | --- |+| Ubuntu 24.04 VM | \`${source.linuxFleetImage}\` |+| Windows Server 2022 VM | \`${source.windowsFleetImage}\` |`;+}++export function renderEvidence(source: SourceFacts): string {+ return `- \`cua-sandbox\` ${source.sandboxVersion} source: image constructors, registry mappings, runtime+ selection, pool claims, Fleet validation, firmware, and services.+- \`cua\` ${source.cuaVersion} source: public Python exports.+- \`cua-fleet\` ${source.pythonFleetVersion} package mapping: Python bound-claim service requests.+- \`@trycua/fleet\` ${source.typescriptFleetVersion} package mapping: TypeScript service requests.+- \`cua-sandbox[driver]\` ${source.sandboxVersion} maps direct Driver use to \`cua-driver\`+ ${source.sandboxDriverVersion}. This client mapping is not the Driver version inside a particular+ published or deployment-qualified guest image.`;+}++function row(columns: string[]): string {+ return `| ${columns.join(' | ')} |`;+}++export function renderCatalog(manifest: SandboxFactsManifest, source: SourceFacts): string {+ const rows = [+ row([+ 'Linux',+ 'Ubuntu 24.04; artifact architecture not established by SDK mapping',+ 'Artifact-dependent; not specified by SDK mapping',+ 'Fleet containerDisk; local bare-metal QEMU',+ `\`${source.linuxFleetImage}\``,+ `\`Image.linux()\` mapping in \`cua-sandbox\` ${source.sandboxVersion}; versioned tag, not a digest pin. [SDK checks](/reference/sandbox-sdk/runtime-support#evidence-and-limits) establish selection, not a live pull, boot, or guest-service check.`,+ ]),+ row([+ 'Linux',+ 'Ubuntu 24.04',+ 'XFCE runtime mapping',+ 'Local Docker container',+ `\`${source.linuxContainerImage}\``,+ 'Local container selector; mutable tag, not the Fleet VM disk.',+ ]),+ ];+ for (const image of manifest.qualifiedImages) {+ rows.push(+ row([+ image.os,+ image.distribution,+ image.desktop,+ image.kind,+ `\`${image.image}\``,+ `Deployment qualification recorded boot and readiness for \`server:${image.services.server}\` and \`mcp:${image.services.mcp}\`. The guest contains \`cua-computer-server\` ${image.components.computerServer} with embedded Driver ${image.components.embeddedDriver}; direct Driver qualification used ${image.components.directDriver}. These image-specific results do not change the published client mapping or certify every operation and desktop configuration.`,+ ])+ );+ }+ for (const image of manifest.publishedCandidates) {+ rows.push(+ row([+ image.os,+ image.distribution,+ image.desktop,+ image.kind,+ `\`${image.image}\``,+ image.limits,+ ])+ );+ }+ rows.push(+ row([+ 'Windows',+ 'Server 2022; artifact architecture not established by SDK mapping',+ 'Native Windows desktop',+ 'Fleet containerDisk; local Hyper-V or QEMU',+ `\`${source.windowsFleetImage}\``,+ `\`Image.windows()\` mapping in \`cua-sandbox\` ${source.sandboxVersion}; Fleet selects EFI. Versioned tag, not a digest pin. [SDK checks](/reference/sandbox-sdk/runtime-support#evidence-and-limits) establish selection and firmware, not a live pull, boot, or guest-service check.`,+ ]),+ row([+ 'macOS',+ 'Sequoia 15',+ 'Native macOS desktop',+ 'Local Lume VM',+ `\`${source.macosSequoiaImage}\``,+ 'Compatible Apple silicon host required; mutable tag; no built-in Fleet mapping.',+ ]),+ row([+ 'macOS',+ 'Tahoe 26',+ 'Native macOS desktop',+ 'Local Lume VM',+ `\`${source.macosTahoeImage}\``,+ 'Default `Image.macos()` version; compatible Apple silicon host required; mutable tag; no built-in Fleet mapping.',+ ])+ );+ return `| OS | Distribution / version / architecture | Desktop / window manager | Image kind / runtime | Registry image or source | Evidence / limits |+| --- | --- | --- | --- | --- | --- |+${rows.join('\n')}`;+}++export function generateDocuments(): Map<string, string> {+ const manifest = loadManifest();+ const source = loadSourceFacts();+ assertQualificationSources(manifest, source);+ let runtime = fs.readFileSync(RUNTIME_DOC, 'utf8');+ runtime = replaceGeneratedSection(+ runtime,+ 'sandbox-package-facts',+ renderRuntimePackageFacts(source)+ );+ runtime = replaceGeneratedSection(+ runtime,+ 'sandbox-builtin-mappings',+ renderBuiltinMappings(source)+ );+ runtime = replaceGeneratedSection(runtime, 'sandbox-evidence', renderEvidence(source));+ let catalog = fs.readFileSync(CATALOG_DOC, 'utf8');+ catalog = replaceGeneratedSection(+ catalog,+ 'sandbox-image-catalog',+ renderCatalog(manifest, source)+ );+ return new Map([+ [RUNTIME_DOC, runtime],+ [CATALOG_DOC, catalog],+ ]);+}++function main(): void {+ const { values } = parseArgs({ options: { check: { type: 'boolean' } } });+ const generated = generateDocuments();+ let drift = false;+ for (const [file, contents] of generated) {+ const current = fs.readFileSync(file, 'utf8');+ if (current === contents) continue;+ if (values.check) {+ console.error(`Generated Sandbox documentation is stale: ${path.relative(ROOT, file)}`);+ drift = true;+ } else {+ fs.writeFileSync(file, contents);+ console.log(`Generated ${path.relative(ROOT, file)}`);+ }+ }+ if (drift) process.exitCode = 1;+ else if (values.check) console.log('Sandbox package and image facts are up to date.');+}++if (require.main === module) main();