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
cua-temporal-agent: durable mini-swe workflow on the cua-sandbox SDK + cyclops-sdk renew_claim (#6446)
r33drichards29e8de257548
diff --git a/libs/fleet/cua-fleet/cua_fleet/__init__.py b/libs/fleet/cua-fleet/cua_fleet/__init__.pydeleted file mode 100644index 0835305cd1..0000000000--- a/libs/fleet/cua-fleet/cua_fleet/__init__.py+++ /dev/null@@ -1,7 +0,0 @@-"""Cua Fleet facade for the Cua Cloud Python SDK."""--from cua_train import TrainClient--__all__ = ["TrainClient"]--__version__ = "0.0.10"diff --git a/libs/fleet/cua-fleet/pyproject.toml b/libs/fleet/cua-fleet/pyproject.tomldeleted file mode 100644index 9cb10d07f7..0000000000--- a/libs/fleet/cua-fleet/pyproject.toml+++ /dev/null@@ -1,13 +0,0 @@-[project]-name = "cua-fleet"-version = "0.0.10"-description = "Cua Fleet facade for the Cua Cloud Python SDK"-requires-python = ">=3.10"-dependencies = ["cua-train==0.1.6"]--[build-system]-requires = ["hatchling"]-build-backend = "hatchling.build"--[tool.hatch.build.targets.wheel]-packages = ["cua_fleet"]diff --git a/libs/fleet/cua-fleet/scripts/repackage_cua_train_wheel.py b/libs/fleet/cua-fleet/scripts/repackage_cua_train_wheel.pydeleted file mode 100644index 18fde9ad04..0000000000--- a/libs/fleet/cua-fleet/scripts/repackage_cua_train_wheel.py+++ /dev/null@@ -1,264 +0,0 @@-#!/usr/bin/env python3-"""Repackage a verified native cua-train wheel as a cua-fleet wheel."""--from __future__ import annotations--import argparse-import base64-import csv-import hashlib-from io import StringIO-from pathlib import Path-import re-import sys-import zipfile--SOURCE_NAME = "cua-train"-SOURCE_VERSION = "0.1.6"-DESTINATION_NAME = "cua-fleet"-WHEEL_FILENAME = re.compile(- r"^(?P<distribution>[A-Za-z0-9_]+)-(?P<version>[^-]+)-py3-none-(?P<platform>[^-]+)\.whl$"-)---class WheelError(ValueError):- """Raised when a wheel does not satisfy the promotion contract."""---def wheel_stem(name: str) -> str:- return name.replace("-", "_")---def sha256_record(data: bytes) -> tuple[str, str]:- digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode()- return f"sha256={digest}", str(len(data))---def parse_filename(path: Path) -> tuple[str, str, str]:- match = WHEEL_FILENAME.fullmatch(path.name)- if match is None:- raise WheelError(f"unsupported wheel filename: {path.name}")- return match.group("distribution"), match.group("version"), match.group("platform")---def parse_metadata(data: bytes) -> dict[str, str]:- fields: dict[str, str] = {}- for line in data.decode().splitlines():- if not line:- break- if ": " in line:- key, value = line.split(": ", 1)- fields.setdefault(key, value)- return fields---def update_metadata(data: bytes, version: str) -> bytes:- text = data.decode()- _, _, description = text.partition("\n\n")- lines = text.splitlines(keepends=True)- required_dependency = f"Requires-Dist: {SOURCE_NAME} == {SOURCE_VERSION}\n"- found_name = found_version = found_dependency = False- updated: list[str] = []- for line in lines:- if line == "\n" and not found_dependency:- updated.append(required_dependency)- found_dependency = True- if not description.strip() and line.startswith("Description-Content-Type: "):- updated.append("Description-Content-Type: text/plain\n")- continue- if line.startswith("Name: "):- updated.append(f"Name: {DESTINATION_NAME}\n")- found_name = True- elif line.startswith("Version: "):- updated.append(f"Version: {version}\n")- found_version = True- elif line == required_dependency:- updated.append(line)- found_dependency = True- else:- updated.append(line)- if not found_name or not found_version:- raise WheelError("METADATA must contain Name and Version fields")- return "".join(updated).encode()---def csv_bytes(rows: list[list[str]]) -> bytes:- output = StringIO()- csv.writer(output, lineterminator="\n").writerows(rows)- return output.getvalue().encode()---def source_payloads(entries: dict[str, bytes]) -> dict[str, str]:- return {- name: hashlib.sha256(data).hexdigest()- for name, data in entries.items()- if ".dist-info/" not in name- }---def repack(- source: Path, destination_version: str, output_directory: Path, expected_sha256: str | None-) -> Path:- if expected_sha256 is not None:- actual_sha256 = hashlib.sha256(source.read_bytes()).hexdigest()- if actual_sha256 != expected_sha256:- raise WheelError(f"source SHA-256 mismatch for {source.name}: {actual_sha256}")-- distribution, version, platform = parse_filename(source)- if distribution != wheel_stem(SOURCE_NAME) or version != SOURCE_VERSION:- raise WheelError(- f"expected {SOURCE_NAME}=={SOURCE_VERSION}, found {distribution}=={version}"- )-- with zipfile.ZipFile(source) as archive:- entries = {- info.filename: archive.read(info.filename)- for info in archive.infolist()- if not info.is_dir() and not info.filename.endswith(".dist-info/RECORD")- }-- source_dist_info = f"{wheel_stem(SOURCE_NAME)}-{SOURCE_VERSION}.dist-info"- destination_dist_info = f"{wheel_stem(DESTINATION_NAME)}-{destination_version}.dist-info"- metadata_name = f"{source_dist_info}/METADATA"- wheel_name = f"{source_dist_info}/WHEEL"- if metadata_name not in entries or wheel_name not in entries:- raise WheelError("wheel is missing METADATA or WHEEL")-- metadata = parse_metadata(entries[metadata_name])- if metadata.get("Name") != SOURCE_NAME or metadata.get("Version") != SOURCE_VERSION:- raise WheelError("source METADATA does not identify cua-train==0.1.6")- wheel_metadata = entries[wheel_name].decode()- if (- "Root-Is-Purelib: false" not in wheel_metadata- or f"Tag: py3-none-{platform}" not in wheel_metadata- ):- raise WheelError("source WHEEL metadata does not match its native platform tag")-- transformed: dict[str, bytes] = {}- for name, data in entries.items():- destination_name = name.replace(source_dist_info, destination_dist_info, 1)- transformed[destination_name] = (- update_metadata(data, destination_version) if name == metadata_name else data- )-- record_name = f"{destination_dist_info}/RECORD"- records = []- for name in sorted(transformed):- digest, size = sha256_record(transformed[name])- records.append([name, digest, size])- records.append([record_name, "", ""])- transformed[record_name] = csv_bytes(records)-- output_directory.mkdir(parents=True, exist_ok=True)- destination = (- output_directory- / f"{wheel_stem(DESTINATION_NAME)}-{destination_version}-py3-none-{platform}.whl"- )- with zipfile.ZipFile(destination, "w", compression=zipfile.ZIP_DEFLATED) as archive:- for name in sorted(transformed):- archive.writestr(name, transformed[name])-- verify(destination, source)- return destination---def verify(path: Path, source: Path | None = None) -> None:- distribution, version, platform = parse_filename(path)- if distribution != wheel_stem(DESTINATION_NAME):- raise WheelError(f"wheel filename does not identify {DESTINATION_NAME}: {path.name}")-- destination_dist_info = f"{wheel_stem(DESTINATION_NAME)}-{version}.dist-info"- with zipfile.ZipFile(path) as archive:- entries = {- info.filename: archive.read(info.filename)- for info in archive.infolist()- if not info.is_dir()- }-- metadata_name = f"{destination_dist_info}/METADATA"- wheel_name = f"{destination_dist_info}/WHEEL"- record_name = f"{destination_dist_info}/RECORD"- if not {metadata_name, wheel_name, record_name}.issubset(entries):- raise WheelError("destination wheel is missing dist-info metadata")-- metadata_text = entries[metadata_name].decode()- metadata = parse_metadata(entries[metadata_name])- if metadata.get("Name") != DESTINATION_NAME or metadata.get("Version") != version:- raise WheelError("destination METADATA does not match the wheel filename")- if f"Requires-Dist: {SOURCE_NAME} == {SOURCE_VERSION}" not in metadata_text.splitlines():- raise WheelError("destination METADATA must pin cua-train==0.1.6")- wheel_metadata = entries[wheel_name].decode()- if (- "Root-Is-Purelib: false" not in wheel_metadata- or f"Tag: py3-none-{platform}" not in wheel_metadata- ):- raise WheelError("destination WHEEL metadata does not match the wheel filename")- if not any(name.startswith("cua_train/") for name in entries):- raise WheelError("destination wheel is missing cua_train")- if not any(name.startswith("fleet_sdk/") for name in entries):- raise WheelError("destination wheel is missing fleet_sdk")- if not any(name.startswith("fleet_sdk/libcyclops_sdk.") for name in entries):- raise WheelError("destination wheel is missing the native cyclops library")-- record_rows = list(csv.reader(entries[record_name].decode().splitlines()))- recorded = {row[0]: row[1:] for row in record_rows}- if len(recorded) != len(record_rows):- raise WheelError("RECORD contains duplicate entries")- if set(recorded) != set(entries):- raise WheelError("RECORD entries do not match wheel members")- for name, data in entries.items():- digest, size = recorded[name]- if name == record_name:- if digest or size:- raise WheelError("RECORD must have empty hash and size")- elif [digest, size] != list(sha256_record(data)):- raise WheelError(f"RECORD does not match {name}")-- if source is not None:- with zipfile.ZipFile(source) as archive:- source_entries = {- info.filename: archive.read(info.filename)- for info in archive.infolist()- if not info.is_dir() and ".dist-info/" not in info.filename- }- destination_entries = {- name: data for name, data in entries.items() if ".dist-info/" not in name- }- if source_payloads(source_entries) != source_payloads(destination_entries):- raise WheelError("non-dist-info payload bytes changed during repackaging")---def parse_args() -> argparse.Namespace:- parser = argparse.ArgumentParser()- parser.add_argument("--source", type=Path)- parser.add_argument("--destination-version")- parser.add_argument("--outdir", type=Path)- parser.add_argument("--expected-sha256")- parser.add_argument("--verify", type=Path, nargs="+")- return parser.parse_args()---def main() -> int:- args = parse_args()- try:- if args.verify is not None:- for path in args.verify:- verify(path)- print(f"Verified {path}")- return 0- if args.source is None or args.destination_version is None or args.outdir is None:- raise WheelError(- "--source, --destination-version, and --outdir are required when repacking"- )- destination = repack(- args.source, args.destination_version, args.outdir, args.expected_sha256- )- except (WheelError, OSError, zipfile.BadZipFile) as error:- print(f"error: {error}", file=sys.stderr)- return 1- print(destination)- return 0---if __name__ == "__main__":- raise SystemExit(main())diff --git a/libs/fleet/cua-fleet/tests/test_metadata.py b/libs/fleet/cua-fleet/tests/test_metadata.pydeleted file mode 100644index d9fb830b29..0000000000--- a/libs/fleet/cua-fleet/tests/test_metadata.py+++ /dev/null@@ -1,36 +0,0 @@-from __future__ import annotations--import tomllib-from pathlib import Path---def test_metadata_pins_published_cua_train() -> None:- project = tomllib.loads((Path(__file__).parents[1] / "pyproject.toml").read_text())["project"]- assert project["version"] == "0.0.10"- assert project["dependencies"] == ["cua-train==0.1.6"]---def test_publish_prepare_checks_out_canonical_metadata() -> None:- workflow = Path(__file__).parents[3] / ".github/workflows/cua-fleet-publish.yml"- prepare, _ = workflow.read_text().split("\n repackage:", 1)- assert prepare.count(" steps:\n") == 1- assert (- " steps:\n"- " - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4\n"- " - name: Determine and validate patch version"- ) in prepare- assert "@v" not in workflow.read_text()---def test_publish_repackages_the_published_cua_train_0_1_5_wheels() -> None:- workflow = (Path(__file__).parents[3] / ".github/workflows/cua-fleet-publish.yml").read_text()-- expected_sources = {- "cua_train-0.1.6-py3-none-manylinux_2_34_x86_64.whl": "418db974949f4020fae2f3ed2f5a8d0db6ddce38e34f5db89283ac479d816a55",- "cua_train-0.1.6-py3-none-manylinux_2_34_aarch64.whl": "80526bf94ed535383b3dddd9a7da800da9fcb32837c21c2e2caa39390e3548c9",- "cua_train-0.1.6-py3-none-macosx_10_12_x86_64.whl": "87cb4220054514ac5f44118d490ae404fbca5c97d2b964cd4fcaf1facd391fc0",- "cua_train-0.1.6-py3-none-macosx_11_0_arm64.whl": "17563c0504c9270e570332924f3092faec3dcdbf48557a70ee830e165ac7751c",- }-- for wheel, digest in expected_sources.items():- assert f"wheel: {wheel}\n sha256: {digest}" in workflowdiff --git a/libs/fleet/cua-fleet/tests/test_repackage_cua_train_wheel.py b/libs/fleet/cua-fleet/tests/test_repackage_cua_train_wheel.pydeleted file mode 100644index 47d3389611..0000000000--- a/libs/fleet/cua-fleet/tests/test_repackage_cua_train_wheel.py+++ /dev/null@@ -1,75 +0,0 @@-from __future__ import annotations--import base64-import csv-import hashlib-from io import StringIO-from pathlib import Path-import sys-import zipfile--import pytest--sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))-from repackage_cua_train_wheel import WheelError, repack, verify # noqa: E402---def _record(data: bytes) -> tuple[str, str]:- digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode()- return f"sha256={digest}", str(len(data))---def _csv(rows: list[list[str]]) -> bytes:- output = StringIO()- csv.writer(output, lineterminator="\n").writerows(rows)- return output.getvalue().encode()---def _write_source_wheel(path: Path) -> dict[str, bytes]:- dist_info = "cua_train-0.1.6.dist-info"- entries = {- "cua_train/__init__.py": b"TrainClient = object\n",- "fleet_sdk/__init__.py": b"CyclopsClient = object\n",- "fleet_sdk/libcyclops_sdk.so": b"native payload",- f"{dist_info}/METADATA": b"Metadata-Version: 2.4\nName: cua-train\nVersion: 0.1.6\nDescription-Content-Type: text/markdown\n\n",- f"{dist_info}/WHEEL": b"Wheel-Version: 1.0\nRoot-Is-Purelib: false\nTag: py3-none-manylinux_2_34_x86_64\n",- }- record_name = f"{dist_info}/RECORD"- rows = [[name, *_record(data)] for name, data in sorted(entries.items())]- rows.append([record_name, "", ""])- entries[record_name] = _csv(rows)- with zipfile.ZipFile(path, "w") as archive:- for name, data in entries.items():- archive.writestr(name, data)- return entries---def test_repack_updates_distribution_metadata_and_pins_train(tmp_path: Path):- source = tmp_path / "cua_train-0.1.6-py3-none-manylinux_2_34_x86_64.whl"- source_entries = _write_source_wheel(source)-- destination = repack(- source, "0.0.8", tmp_path / "dist", hashlib.sha256(source.read_bytes()).hexdigest()- )-- assert destination.name == "cua_fleet-0.0.8-py3-none-manylinux_2_34_x86_64.whl"- verify(destination, source)- with zipfile.ZipFile(destination) as archive:- assert archive.read("cua_train/__init__.py") == source_entries["cua_train/__init__.py"]- assert (- archive.read("fleet_sdk/libcyclops_sdk.so")- == source_entries["fleet_sdk/libcyclops_sdk.so"]- )- metadata = archive.read("cua_fleet-0.0.8.dist-info/METADATA").decode()- assert "Name: cua-fleet" in metadata- assert "Version: 0.0.8" in metadata- assert "Description-Content-Type: text/plain" in metadata- assert "Requires-Dist: cua-train == 0.1.6" in metadata---def test_repack_rejects_unpinned_source(tmp_path: Path):- source = tmp_path / "cua_train-0.1.6-py3-none-manylinux_2_34_x86_64.whl"- _write_source_wheel(source)-- with pytest.raises(WheelError, match="SHA-256 mismatch"):- repack(source, "0.0.8", tmp_path / "dist", "0" * 64)diff --git a/libs/fleet/python-sdk/.gitignore b/libs/fleet/python-sdk/.gitignoredeleted file mode 100644index 79a2c3d73c..0000000000--- a/libs/fleet/python-sdk/.gitignore+++ /dev/null@@ -1,23 +0,0 @@-__pycache__/-build/-dist/-*.egg-info/-.pytest_cache/--# pyenv-.python-version--# Environments-.env-.venv--# mypy-.mypy_cache/-.dmypy.json-dmypy.json--# JetBrains-.idea/--/coverage.xml-/.coveragediff --git a/libs/fleet/python-sdk/README.md b/libs/fleet/python-sdk/README.mddeleted file mode 100644index 8b13789179..0000000000--- a/libs/fleet/python-sdk/README.md+++ /dev/null@@ -1 +0,0 @@-diff --git a/libs/fleet/python-sdk/cua_train/__init__.py b/libs/fleet/python-sdk/cua_train/__init__.pydeleted file mode 100644index c0b9d96bd7..0000000000--- a/libs/fleet/python-sdk/cua_train/__init__.py+++ /dev/null@@ -1,10 +0,0 @@-"""cua-train — Python client library for the CUA training / batch backend API."""--from ._convenience import TrainClient-from .client import AuthenticatedClient, Client--__all__ = (- "AuthenticatedClient",- "Client",- "TrainClient",-)diff --git a/libs/fleet/python-sdk/cua_train/_convenience.py b/libs/fleet/python-sdk/cua_train/_convenience.pydeleted file mode 100644index dc3422bb00..0000000000--- a/libs/fleet/python-sdk/cua_train/_convenience.py+++ /dev/null@@ -1,147 +0,0 @@-"""-TrainClient — an AuthenticatedClient that also exposes every generated-endpoint as a method, so callers write::-- c = TrainClient.from_key(token_url=..., client_id=..., client_secret=...)- c.acquire_lanes(pool="test-pool", body=AcquireLanesRequest(n=8))- c.submit_label_batch(pool="test-pool", label="run-1", body=BatchSubmitRequest(...))- c.get_label_results(pool="test-pool", label="run-1", completed_only=True)--instead of importing each generated module and calling ``.sync`` by hand.--The endpoint surface is built generically: :func:`_load_operations` loops over-every module under ``cua_train.api`` once at import and maps each operation's-``sync`` function by name. ``TrainClient.__getattr__`` then resolves an-unknown attribute to that function with ``client=self`` pre-bound — no-per-endpoint code and no routing logic, so a new endpoint is callable the moment-it is regenerated from the OpenAPI spec. ``c`` remains a drop-in-``AuthenticatedClient`` for the low-level ``cua_train.api.*`` functions.-"""--from __future__ import annotations--import functools-import importlib-import pkgutil-import threading-import time-from collections.abc import Callable--import httpx--from . import api-from .client import AuthenticatedClient---def _load_operations() -> dict[str, Callable]:- """Map ``operation_name -> sync()`` for every generated endpoint module.-- Walks ``cua_train/api/<tag>/<operation>.py`` (operation names are globally- unique, so a flat namespace is safe). Run once at import.- """- ops: dict[str, Callable] = {}- for tag in pkgutil.iter_modules(api.__path__):- if not tag.ispkg:- continue- pkg = importlib.import_module(f"{api.__name__}.{tag.name}")- for op in pkgutil.iter_modules(pkg.__path__):- module = importlib.import_module(f"{pkg.__name__}.{op.name}")- fn = getattr(module, "sync", None)- if callable(fn):- ops[op.name] = fn- return ops---_OPERATIONS = _load_operations()---class TrainClient(AuthenticatedClient):- """AuthenticatedClient with a ``client_credentials`` helper, a bearer token- that is refreshed transparently before it expires, and every generated- endpoint exposed as a method (its ``sync``, client pre-bound)."""-- @classmethod- def from_key(- cls,- *,- token_url: str,- client_id: str,- client_secret: str,- base_url: str = "https://run.cua.ai",- **kwargs,- ) -> TrainClient:- """Exchange client credentials for a bearer token and return a ready client.-- Args:- token_url: Keycloak token endpoint, e.g.- ``https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token``- client_id: Service-account client ID (starts with ``key-``).- client_secret: Client secret returned by ``POST /api/keys``.- base_url: Backend base URL (default: production, run.cua.ai).- **kwargs: Forwarded to :class:`AuthenticatedClient`.- """- token, ttl = cls._exchange(token_url, client_id, client_secret)- self = cls(base_url=base_url, token=token, **kwargs)- # Stash credentials so the token can be refreshed transparently.- self._token_url = token_url- self._client_id = client_id- self._client_secret = client_secret- self._token_deadline = time.monotonic() + ttl- self._refresh_lock = threading.Lock()- return self-- @staticmethod- def _exchange(token_url: str, client_id: str, client_secret: str) -> tuple[str, float]:- """client_credentials exchange → (access_token, lifetime_seconds)."""- resp = httpx.post(- token_url,- data={- "grant_type": "client_credentials",- "client_id": client_id,- "client_secret": client_secret,- },- )- resp.raise_for_status()- body = resp.json()- return body["access_token"], float(body.get("expires_in", 300))-- def _refresh_token(self) -> None:- """Re-mint the bearer token shortly before it expires. Transparent to- callers, thread-safe (double-checked under a lock), and a no-op for- clients not created via :meth:`from_key`."""- if getattr(self, "_token_url", None) is None:- return- if time.monotonic() < self._token_deadline - 30:- return- with self._refresh_lock:- if time.monotonic() < self._token_deadline - 30:- return- token, ttl = self._exchange(self._token_url, self._client_id, self._client_secret)- self.token = token- self._token_deadline = time.monotonic() + ttl- header = f"{self.prefix} {token}" if self.prefix else token- self._headers[self.auth_header_name] = header- if self._client is not None:- self._client.headers[self.auth_header_name] = header- if self._async_client is not None:- self._async_client.headers[self.auth_header_name] = header-- def get_httpx_client(self) -> httpx.Client:- self._refresh_token()- return super().get_httpx_client()-- def get_async_httpx_client(self) -> httpx.AsyncClient:- self._refresh_token()- return super().get_async_httpx_client()-- def __getattr__(self, name: str) -> Callable:- # Only reached for attributes not found normally (slots/methods take- # precedence), so this never shadows real client state. Unknown names —- # including dunders probed by copy/pickle — raise AttributeError.- fn = _OPERATIONS.get(name)- if fn is None:- raise AttributeError(- f"{type(self).__name__!r} object has no attribute {name!r}; "- f"available operations: {', '.join(sorted(_OPERATIONS))}"- )- return functools.partial(fn, client=self)diff --git a/libs/fleet/python-sdk/cua_train/api/__init__.py b/libs/fleet/python-sdk/cua_train/api/__init__.pydeleted file mode 100644index 81f9fa241b..0000000000--- a/libs/fleet/python-sdk/cua_train/api/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""Contains methods for accessing the API"""diff --git a/libs/fleet/python-sdk/cua_train/api/batch/__init__.py b/libs/fleet/python-sdk/cua_train/api/batch/__init__.pydeleted file mode 100644index 2d7c0b23da..0000000000--- a/libs/fleet/python-sdk/cua_train/api/batch/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""Contains endpoint functions for accessing the API"""diff --git a/libs/fleet/python-sdk/cua_train/api/batch/acquire_lanes.py b/libs/fleet/python-sdk/cua_train/api/batch/acquire_lanes.pydeleted file mode 100644index 453c8323b6..0000000000--- a/libs/fleet/python-sdk/cua_train/api/batch/acquire_lanes.py+++ /dev/null@@ -1,212 +0,0 @@-from http import HTTPStatus-from typing import Any-from urllib.parse import quote--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.acquire_lanes_request import AcquireLanesRequest-from ...models.acquire_lanes_response import AcquireLanesResponse-from ...models.error_response import ErrorResponse-from ...types import Response---def _get_kwargs(- pool: str,- *,- body: AcquireLanesRequest,-) -> dict[str, Any]:- headers: dict[str, Any] = {}-- _kwargs: dict[str, Any] = {- "method": "post",- "url": "/api/batch/{pool}/lanes".format(- pool=quote(str(pool), safe=""),- ),- }-- _kwargs["json"] = body.to_dict()-- headers["Content-Type"] = "application/json"-- _kwargs["headers"] = headers- return _kwargs---def _parse_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> AcquireLanesResponse | ErrorResponse | None:- if response.status_code == 200:- response_200 = AcquireLanesResponse.from_dict(response.json())-- return response_200-- if response.status_code == 400:- response_400 = ErrorResponse.from_dict(response.json())-- return response_400-- if response.status_code == 401:- response_401 = ErrorResponse.from_dict(response.json())-- return response_401-- if response.status_code == 503:- response_503 = ErrorResponse.from_dict(response.json())-- return response_503-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> Response[AcquireLanesResponse | ErrorResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- pool: str,- *,- client: AuthenticatedClient | Client,- body: AcquireLanesRequest,-) -> Response[AcquireLanesResponse | ErrorResponse]:- r"""Acquire warm VM lanes-- Explicitly provisions N warm VMs (\"lanes\") and returns their vm_ids. Pass each as- `RunConfig.vm_id` to run actions on it (state persists across batches), and `DELETE` this route to- release them. All-or-nothing: a partial acquisition is rolled back, and 503 is returned if the pool- can't supply every lane in time.-- Args:- pool (str):- body (AcquireLanesRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[AcquireLanesResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- pool=pool,- body=body,- )-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- pool: str,- *,- client: AuthenticatedClient | Client,- body: AcquireLanesRequest,-) -> AcquireLanesResponse | ErrorResponse | None:- r"""Acquire warm VM lanes-- Explicitly provisions N warm VMs (\"lanes\") and returns their vm_ids. Pass each as- `RunConfig.vm_id` to run actions on it (state persists across batches), and `DELETE` this route to- release them. All-or-nothing: a partial acquisition is rolled back, and 503 is returned if the pool- can't supply every lane in time.-- Args:- pool (str):- body (AcquireLanesRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- AcquireLanesResponse | ErrorResponse- """-- return sync_detailed(- pool=pool,- client=client,- body=body,- ).parsed---async def asyncio_detailed(- pool: str,- *,- client: AuthenticatedClient | Client,- body: AcquireLanesRequest,-) -> Response[AcquireLanesResponse | ErrorResponse]:- r"""Acquire warm VM lanes-- Explicitly provisions N warm VMs (\"lanes\") and returns their vm_ids. Pass each as- `RunConfig.vm_id` to run actions on it (state persists across batches), and `DELETE` this route to- release them. All-or-nothing: a partial acquisition is rolled back, and 503 is returned if the pool- can't supply every lane in time.-- Args:- pool (str):- body (AcquireLanesRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[AcquireLanesResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- pool=pool,- body=body,- )-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- pool: str,- *,- client: AuthenticatedClient | Client,- body: AcquireLanesRequest,-) -> AcquireLanesResponse | ErrorResponse | None:- r"""Acquire warm VM lanes-- Explicitly provisions N warm VMs (\"lanes\") and returns their vm_ids. Pass each as- `RunConfig.vm_id` to run actions on it (state persists across batches), and `DELETE` this route to- release them. All-or-nothing: a partial acquisition is rolled back, and 503 is returned if the pool- can't supply every lane in time.-- Args:- pool (str):- body (AcquireLanesRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- AcquireLanesResponse | ErrorResponse- """-- return (- await asyncio_detailed(- pool=pool,- client=client,- body=body,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/batch/cancel_batch.py b/libs/fleet/python-sdk/cua_train/api/batch/cancel_batch.pydeleted file mode 100644index 00110ea700..0000000000--- a/libs/fleet/python-sdk/cua_train/api/batch/cancel_batch.py+++ /dev/null@@ -1,196 +0,0 @@-from http import HTTPStatus-from typing import Any-from urllib.parse import quote--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.cancel_batch_response import CancelBatchResponse-from ...models.error_response import ErrorResponse-from ...types import Response---def _get_kwargs(- pool: str,- id: str,-) -> dict[str, Any]:-- _kwargs: dict[str, Any] = {- "method": "delete",- "url": "/api/batch/{pool}/{id}".format(- pool=quote(str(pool), safe=""),- id=quote(str(id), safe=""),- ),- }-- return _kwargs---def _parse_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> CancelBatchResponse | ErrorResponse | None:- if response.status_code == 200:- response_200 = CancelBatchResponse.from_dict(response.json())-- return response_200-- if response.status_code == 401:- response_401 = ErrorResponse.from_dict(response.json())-- return response_401-- if response.status_code == 404:- response_404 = ErrorResponse.from_dict(response.json())-- return response_404-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> Response[CancelBatchResponse | ErrorResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- pool: str,- id: str,- *,- client: AuthenticatedClient | Client,-) -> Response[CancelBatchResponse | ErrorResponse]:- """Cancel a batch-- Hard-cancels the batch — aborts in-flight /reset and /step calls- and stops dispatch. Idempotent on terminal batches. Returns 200- with the final status.-- Args:- pool (str):- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[CancelBatchResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- pool=pool,- id=id,- )-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- pool: str,- id: str,- *,- client: AuthenticatedClient | Client,-) -> CancelBatchResponse | ErrorResponse | None:- """Cancel a batch-- Hard-cancels the batch — aborts in-flight /reset and /step calls- and stops dispatch. Idempotent on terminal batches. Returns 200- with the final status.-- Args:- pool (str):- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- CancelBatchResponse | ErrorResponse- """-- return sync_detailed(- pool=pool,- id=id,- client=client,- ).parsed---async def asyncio_detailed(- pool: str,- id: str,- *,- client: AuthenticatedClient | Client,-) -> Response[CancelBatchResponse | ErrorResponse]:- """Cancel a batch-- Hard-cancels the batch — aborts in-flight /reset and /step calls- and stops dispatch. Idempotent on terminal batches. Returns 200- with the final status.-- Args:- pool (str):- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[CancelBatchResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- pool=pool,- id=id,- )-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- pool: str,- id: str,- *,- client: AuthenticatedClient | Client,-) -> CancelBatchResponse | ErrorResponse | None:- """Cancel a batch-- Hard-cancels the batch — aborts in-flight /reset and /step calls- and stops dispatch. Idempotent on terminal batches. Returns 200- with the final status.-- Args:- pool (str):- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- CancelBatchResponse | ErrorResponse- """-- return (- await asyncio_detailed(- pool=pool,- id=id,- client=client,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/batch/get_batch_results.py b/libs/fleet/python-sdk/cua_train/api/batch/get_batch_results.pydeleted file mode 100644index bb2e2b48fd..0000000000--- a/libs/fleet/python-sdk/cua_train/api/batch/get_batch_results.py+++ /dev/null@@ -1,202 +0,0 @@-from http import HTTPStatus-from typing import Any-from urllib.parse import quote--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.batch_in_progress_response import BatchInProgressResponse-from ...models.batch_results_response import BatchResultsResponse-from ...models.error_response import ErrorResponse-from ...types import Response---def _get_kwargs(- pool: str,- id: str,-) -> dict[str, Any]:-- _kwargs: dict[str, Any] = {- "method": "get",- "url": "/api/batch/{pool}/{id}/results".format(- pool=quote(str(pool), safe=""),- id=quote(str(id), safe=""),- ),- }-- return _kwargs---def _parse_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> BatchInProgressResponse | BatchResultsResponse | ErrorResponse | None:- if response.status_code == 200:- response_200 = BatchResultsResponse.from_dict(response.json())-- return response_200-- if response.status_code == 202:- response_202 = BatchInProgressResponse.from_dict(response.json())-- return response_202-- if response.status_code == 401:- response_401 = ErrorResponse.from_dict(response.json())-- return response_401-- if response.status_code == 404:- response_404 = ErrorResponse.from_dict(response.json())-- return response_404-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> Response[BatchInProgressResponse | BatchResultsResponse | ErrorResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- pool: str,- id: str,- *,- client: AuthenticatedClient | Client,-) -> Response[BatchInProgressResponse | BatchResultsResponse | ErrorResponse]:- """Final batch results-- Returns 200 with the full results once the batch is in a terminal- status (completed/failed). While still running, returns 202 with a- `message` field.-- Args:- pool (str):- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[BatchInProgressResponse | BatchResultsResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- pool=pool,- id=id,- )-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- pool: str,- id: str,- *,- client: AuthenticatedClient | Client,-) -> BatchInProgressResponse | BatchResultsResponse | ErrorResponse | None:- """Final batch results-- Returns 200 with the full results once the batch is in a terminal- status (completed/failed). While still running, returns 202 with a- `message` field.-- Args:- pool (str):- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- BatchInProgressResponse | BatchResultsResponse | ErrorResponse- """-- return sync_detailed(- pool=pool,- id=id,- client=client,- ).parsed---async def asyncio_detailed(- pool: str,- id: str,- *,- client: AuthenticatedClient | Client,-) -> Response[BatchInProgressResponse | BatchResultsResponse | ErrorResponse]:- """Final batch results-- Returns 200 with the full results once the batch is in a terminal- status (completed/failed). While still running, returns 202 with a- `message` field.-- Args:- pool (str):- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[BatchInProgressResponse | BatchResultsResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- pool=pool,- id=id,- )-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- pool: str,- id: str,- *,- client: AuthenticatedClient | Client,-) -> BatchInProgressResponse | BatchResultsResponse | ErrorResponse | None:- """Final batch results-- Returns 200 with the full results once the batch is in a terminal- status (completed/failed). While still running, returns 202 with a- `message` field.-- Args:- pool (str):- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- BatchInProgressResponse | BatchResultsResponse | ErrorResponse- """-- return (- await asyncio_detailed(- pool=pool,- id=id,- client=client,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/batch/get_batch_status.py b/libs/fleet/python-sdk/cua_train/api/batch/get_batch_status.pydeleted file mode 100644index e4a13d4a81..0000000000--- a/libs/fleet/python-sdk/cua_train/api/batch/get_batch_status.py+++ /dev/null@@ -1,180 +0,0 @@-from http import HTTPStatus-from typing import Any-from urllib.parse import quote--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.batch_status_response import BatchStatusResponse-from ...models.error_response import ErrorResponse-from ...types import Response---def _get_kwargs(- pool: str,- id: str,-) -> dict[str, Any]:-- _kwargs: dict[str, Any] = {- "method": "get",- "url": "/api/batch/{pool}/{id}/status".format(- pool=quote(str(pool), safe=""),- id=quote(str(id), safe=""),- ),- }-- return _kwargs---def _parse_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> BatchStatusResponse | ErrorResponse | None:- if response.status_code == 200:- response_200 = BatchStatusResponse.from_dict(response.json())-- return response_200-- if response.status_code == 401:- response_401 = ErrorResponse.from_dict(response.json())-- return response_401-- if response.status_code == 404:- response_404 = ErrorResponse.from_dict(response.json())-- return response_404-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> Response[BatchStatusResponse | ErrorResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- pool: str,- id: str,- *,- client: AuthenticatedClient | Client,-) -> Response[BatchStatusResponse | ErrorResponse]:- """Poll batch progress-- Args:- pool (str):- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[BatchStatusResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- pool=pool,- id=id,- )-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- pool: str,- id: str,- *,- client: AuthenticatedClient | Client,-) -> BatchStatusResponse | ErrorResponse | None:- """Poll batch progress-- Args:- pool (str):- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- BatchStatusResponse | ErrorResponse- """-- return sync_detailed(- pool=pool,- id=id,- client=client,- ).parsed---async def asyncio_detailed(- pool: str,- id: str,- *,- client: AuthenticatedClient | Client,-) -> Response[BatchStatusResponse | ErrorResponse]:- """Poll batch progress-- Args:- pool (str):- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[BatchStatusResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- pool=pool,- id=id,- )-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- pool: str,- id: str,- *,- client: AuthenticatedClient | Client,-) -> BatchStatusResponse | ErrorResponse | None:- """Poll batch progress-- Args:- pool (str):- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- BatchStatusResponse | ErrorResponse- """-- return (- await asyncio_detailed(- pool=pool,- id=id,- client=client,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/batch/release_lanes.py b/libs/fleet/python-sdk/cua_train/api/batch/release_lanes.pydeleted file mode 100644index 8c8534cf0f..0000000000--- a/libs/fleet/python-sdk/cua_train/api/batch/release_lanes.py+++ /dev/null@@ -1,199 +0,0 @@-from http import HTTPStatus-from typing import Any-from urllib.parse import quote--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.error_response import ErrorResponse-from ...models.release_lanes_request import ReleaseLanesRequest-from ...models.release_lanes_response import ReleaseLanesResponse-from ...types import Response---def _get_kwargs(- pool: str,- *,- body: ReleaseLanesRequest,-) -> dict[str, Any]:- headers: dict[str, Any] = {}-- _kwargs: dict[str, Any] = {- "method": "delete",- "url": "/api/batch/{pool}/lanes".format(- pool=quote(str(pool), safe=""),- ),- }-- _kwargs["json"] = body.to_dict()-- headers["Content-Type"] = "application/json"-- _kwargs["headers"] = headers- return _kwargs---def _parse_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> ErrorResponse | ReleaseLanesResponse | None:- if response.status_code == 200:- response_200 = ReleaseLanesResponse.from_dict(response.json())-- return response_200-- if response.status_code == 400:- response_400 = ErrorResponse.from_dict(response.json())-- return response_400-- if response.status_code == 401:- response_401 = ErrorResponse.from_dict(response.json())-- return response_401-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> Response[ErrorResponse | ReleaseLanesResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- pool: str,- *,- client: AuthenticatedClient | Client,- body: ReleaseLanesRequest,-) -> Response[ErrorResponse | ReleaseLanesResponse]:- """Release warm VM lanes-- Shuts down the given VMs (lanes from `acquireLanes` or `vm_id`s returned by a `keep_warm` batch).- Best-effort and idempotent — unknown or already-gone ids are ignored.-- Args:- pool (str):- body (ReleaseLanesRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[ErrorResponse | ReleaseLanesResponse]- """-- kwargs = _get_kwargs(- pool=pool,- body=body,- )-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- pool: str,- *,- client: AuthenticatedClient | Client,- body: ReleaseLanesRequest,-) -> ErrorResponse | ReleaseLanesResponse | None:- """Release warm VM lanes-- Shuts down the given VMs (lanes from `acquireLanes` or `vm_id`s returned by a `keep_warm` batch).- Best-effort and idempotent — unknown or already-gone ids are ignored.-- Args:- pool (str):- body (ReleaseLanesRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- ErrorResponse | ReleaseLanesResponse- """-- return sync_detailed(- pool=pool,- client=client,- body=body,- ).parsed---async def asyncio_detailed(- pool: str,- *,- client: AuthenticatedClient | Client,- body: ReleaseLanesRequest,-) -> Response[ErrorResponse | ReleaseLanesResponse]:- """Release warm VM lanes-- Shuts down the given VMs (lanes from `acquireLanes` or `vm_id`s returned by a `keep_warm` batch).- Best-effort and idempotent — unknown or already-gone ids are ignored.-- Args:- pool (str):- body (ReleaseLanesRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[ErrorResponse | ReleaseLanesResponse]- """-- kwargs = _get_kwargs(- pool=pool,- body=body,- )-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- pool: str,- *,- client: AuthenticatedClient | Client,- body: ReleaseLanesRequest,-) -> ErrorResponse | ReleaseLanesResponse | None:- """Release warm VM lanes-- Shuts down the given VMs (lanes from `acquireLanes` or `vm_id`s returned by a `keep_warm` batch).- Best-effort and idempotent — unknown or already-gone ids are ignored.-- Args:- pool (str):- body (ReleaseLanesRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- ErrorResponse | ReleaseLanesResponse- """-- return (- await asyncio_detailed(- pool=pool,- client=client,- body=body,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/batch/submit_batch.py b/libs/fleet/python-sdk/cua_train/api/batch/submit_batch.pydeleted file mode 100644index 5fe187f149..0000000000--- a/libs/fleet/python-sdk/cua_train/api/batch/submit_batch.py+++ /dev/null@@ -1,219 +0,0 @@-from http import HTTPStatus-from typing import Any-from urllib.parse import quote--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.batch_submit_request import BatchSubmitRequest-from ...models.batch_submit_response import BatchSubmitResponse-from ...models.error_response import ErrorResponse-from ...types import Response---def _get_kwargs(- pool: str,- *,- body: BatchSubmitRequest,-) -> dict[str, Any]:- headers: dict[str, Any] = {}-- _kwargs: dict[str, Any] = {- "method": "post",- "url": "/api/batch/{pool}/submit".format(- pool=quote(str(pool), safe=""),- ),- }-- _kwargs["json"] = body.to_dict()-- headers["Content-Type"] = "application/json"-- _kwargs["headers"] = headers- return _kwargs---def _parse_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> BatchSubmitResponse | ErrorResponse | None:- if response.status_code == 202:- response_202 = BatchSubmitResponse.from_dict(response.json())-- return response_202-- if response.status_code == 400:- response_400 = ErrorResponse.from_dict(response.json())-- return response_400-- if response.status_code == 401:- response_401 = ErrorResponse.from_dict(response.json())-- return response_401-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> Response[BatchSubmitResponse | ErrorResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- pool: str,- *,- client: AuthenticatedClient | Client,- body: BatchSubmitRequest,-) -> Response[BatchSubmitResponse | ErrorResponse]:- """Submit a batch of rollouts-- Asynchronously queues a batch of OSGym rollouts under `{pool}`.- Returns immediately with a `batch_id`; poll- `/api/batch/{pool}/{id}/status` for progress and- `/api/batch/{pool}/{id}/results` for the final payload.-- The pool is bound by the URL path; any `pool_name` in the body must- match the URL pool or the request is rejected with 400.-- Args:- pool (str):- body (BatchSubmitRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[BatchSubmitResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- pool=pool,- body=body,- )-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- pool: str,- *,- client: AuthenticatedClient | Client,- body: BatchSubmitRequest,-) -> BatchSubmitResponse | ErrorResponse | None:- """Submit a batch of rollouts-- Asynchronously queues a batch of OSGym rollouts under `{pool}`.- Returns immediately with a `batch_id`; poll- `/api/batch/{pool}/{id}/status` for progress and- `/api/batch/{pool}/{id}/results` for the final payload.-- The pool is bound by the URL path; any `pool_name` in the body must- match the URL pool or the request is rejected with 400.-- Args:- pool (str):- body (BatchSubmitRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- BatchSubmitResponse | ErrorResponse- """-- return sync_detailed(- pool=pool,- client=client,- body=body,- ).parsed---async def asyncio_detailed(- pool: str,- *,- client: AuthenticatedClient | Client,- body: BatchSubmitRequest,-) -> Response[BatchSubmitResponse | ErrorResponse]:- """Submit a batch of rollouts-- Asynchronously queues a batch of OSGym rollouts under `{pool}`.- Returns immediately with a `batch_id`; poll- `/api/batch/{pool}/{id}/status` for progress and- `/api/batch/{pool}/{id}/results` for the final payload.-- The pool is bound by the URL path; any `pool_name` in the body must- match the URL pool or the request is rejected with 400.-- Args:- pool (str):- body (BatchSubmitRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[BatchSubmitResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- pool=pool,- body=body,- )-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- pool: str,- *,- client: AuthenticatedClient | Client,- body: BatchSubmitRequest,-) -> BatchSubmitResponse | ErrorResponse | None:- """Submit a batch of rollouts-- Asynchronously queues a batch of OSGym rollouts under `{pool}`.- Returns immediately with a `batch_id`; poll- `/api/batch/{pool}/{id}/status` for progress and- `/api/batch/{pool}/{id}/results` for the final payload.-- The pool is bound by the URL path; any `pool_name` in the body must- match the URL pool or the request is rejected with 400.-- Args:- pool (str):- body (BatchSubmitRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- BatchSubmitResponse | ErrorResponse- """-- return (- await asyncio_detailed(- pool=pool,- client=client,- body=body,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/health/__init__.py b/libs/fleet/python-sdk/cua_train/api/health/__init__.pydeleted file mode 100644index 2d7c0b23da..0000000000--- a/libs/fleet/python-sdk/cua_train/api/health/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""Contains endpoint functions for accessing the API"""diff --git a/libs/fleet/python-sdk/cua_train/api/health/healthz.py b/libs/fleet/python-sdk/cua_train/api/health/healthz.pydeleted file mode 100644index 267c378898..0000000000--- a/libs/fleet/python-sdk/cua_train/api/health/healthz.py+++ /dev/null@@ -1,124 +0,0 @@-from http import HTTPStatus-from typing import Any--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.health_response import HealthResponse-from ...types import Response---def _get_kwargs() -> dict[str, Any]:-- _kwargs: dict[str, Any] = {- "method": "get",- "url": "/healthz",- }-- return _kwargs---def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> HealthResponse | None:- if response.status_code == 200:- response_200 = HealthResponse.from_dict(response.json())-- return response_200-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[HealthResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- *,- client: AuthenticatedClient | Client,-) -> Response[HealthResponse]:- """Liveness/readiness probe-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[HealthResponse]- """-- kwargs = _get_kwargs()-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- *,- client: AuthenticatedClient | Client,-) -> HealthResponse | None:- """Liveness/readiness probe-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- HealthResponse- """-- return sync_detailed(- client=client,- ).parsed---async def asyncio_detailed(- *,- client: AuthenticatedClient | Client,-) -> Response[HealthResponse]:- """Liveness/readiness probe-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[HealthResponse]- """-- kwargs = _get_kwargs()-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- *,- client: AuthenticatedClient | Client,-) -> HealthResponse | None:- """Liveness/readiness probe-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- HealthResponse- """-- return (- await asyncio_detailed(- client=client,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/keys/__init__.py b/libs/fleet/python-sdk/cua_train/api/keys/__init__.pydeleted file mode 100644index 2d7c0b23da..0000000000--- a/libs/fleet/python-sdk/cua_train/api/keys/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""Contains endpoint functions for accessing the API"""diff --git a/libs/fleet/python-sdk/cua_train/api/keys/create_key.py b/libs/fleet/python-sdk/cua_train/api/keys/create_key.pydeleted file mode 100644index b53a7760db..0000000000--- a/libs/fleet/python-sdk/cua_train/api/keys/create_key.py+++ /dev/null@@ -1,188 +0,0 @@-from http import HTTPStatus-from typing import Any--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.create_key_request import CreateKeyRequest-from ...models.create_key_response import CreateKeyResponse-from ...models.error_response import ErrorResponse-from ...types import Response---def _get_kwargs(- *,- body: CreateKeyRequest,-) -> dict[str, Any]:- headers: dict[str, Any] = {}-- _kwargs: dict[str, Any] = {- "method": "post",- "url": "/api/keys",- }-- _kwargs["json"] = body.to_dict()-- headers["Content-Type"] = "application/json"-- _kwargs["headers"] = headers- return _kwargs---def _parse_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> CreateKeyResponse | ErrorResponse | None:- if response.status_code == 201:- response_201 = CreateKeyResponse.from_dict(response.json())-- return response_201-- if response.status_code == 400:- response_400 = ErrorResponse.from_dict(response.json())-- return response_400-- if response.status_code == 401:- response_401 = ErrorResponse.from_dict(response.json())-- return response_401-- if response.status_code == 403:- response_403 = ErrorResponse.from_dict(response.json())-- return response_403-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> Response[CreateKeyResponse | ErrorResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- *,- client: AuthenticatedClient | Client,- body: CreateKeyRequest,-) -> Response[CreateKeyResponse | ErrorResponse]:- """Create a new API key-- Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is- shown exactly once.-- Args:- body (CreateKeyRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[CreateKeyResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- body=body,- )-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- *,- client: AuthenticatedClient | Client,- body: CreateKeyRequest,-) -> CreateKeyResponse | ErrorResponse | None:- """Create a new API key-- Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is- shown exactly once.-- Args:- body (CreateKeyRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- CreateKeyResponse | ErrorResponse- """-- return sync_detailed(- client=client,- body=body,- ).parsed---async def asyncio_detailed(- *,- client: AuthenticatedClient | Client,- body: CreateKeyRequest,-) -> Response[CreateKeyResponse | ErrorResponse]:- """Create a new API key-- Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is- shown exactly once.-- Args:- body (CreateKeyRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[CreateKeyResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- body=body,- )-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- *,- client: AuthenticatedClient | Client,- body: CreateKeyRequest,-) -> CreateKeyResponse | ErrorResponse | None:- """Create a new API key-- Creates a Keycloak service-account client owned by the calling user. The returned `client_secret` is- shown exactly once.-- Args:- body (CreateKeyRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- CreateKeyResponse | ErrorResponse- """-- return (- await asyncio_detailed(- client=client,- body=body,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/keys/delete_key.py b/libs/fleet/python-sdk/cua_train/api/keys/delete_key.pydeleted file mode 100644index 05dd935582..0000000000--- a/libs/fleet/python-sdk/cua_train/api/keys/delete_key.py+++ /dev/null@@ -1,160 +0,0 @@-from http import HTTPStatus-from typing import Any, cast-from urllib.parse import quote--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.error_response import ErrorResponse-from ...types import Response---def _get_kwargs(- id: str,-) -> dict[str, Any]:-- _kwargs: dict[str, Any] = {- "method": "delete",- "url": "/api/keys/{id}".format(- id=quote(str(id), safe=""),- ),- }-- return _kwargs---def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Any | ErrorResponse | None:- if response.status_code == 204:- response_204 = cast(Any, None)- return response_204-- if response.status_code == 401:- response_401 = ErrorResponse.from_dict(response.json())-- return response_401-- if response.status_code == 403:- response_403 = ErrorResponse.from_dict(response.json())-- return response_403-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[Any | ErrorResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- id: str,- *,- client: AuthenticatedClient | Client,-) -> Response[Any | ErrorResponse]:- """Revoke an API key by Keycloak client UUID-- Args:- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[Any | ErrorResponse]- """-- kwargs = _get_kwargs(- id=id,- )-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- id: str,- *,- client: AuthenticatedClient | Client,-) -> Any | ErrorResponse | None:- """Revoke an API key by Keycloak client UUID-- Args:- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Any | ErrorResponse- """-- return sync_detailed(- id=id,- client=client,- ).parsed---async def asyncio_detailed(- id: str,- *,- client: AuthenticatedClient | Client,-) -> Response[Any | ErrorResponse]:- """Revoke an API key by Keycloak client UUID-- Args:- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[Any | ErrorResponse]- """-- kwargs = _get_kwargs(- id=id,- )-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- id: str,- *,- client: AuthenticatedClient | Client,-) -> Any | ErrorResponse | None:- """Revoke an API key by Keycloak client UUID-- Args:- id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Any | ErrorResponse- """-- return (- await asyncio_detailed(- id=id,- client=client,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/keys/list_keys.py b/libs/fleet/python-sdk/cua_train/api/keys/list_keys.pydeleted file mode 100644index 5b3936ff2f..0000000000--- a/libs/fleet/python-sdk/cua_train/api/keys/list_keys.py+++ /dev/null@@ -1,134 +0,0 @@-from http import HTTPStatus-from typing import Any--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.error_response import ErrorResponse-from ...models.list_keys_response import ListKeysResponse-from ...types import Response---def _get_kwargs() -> dict[str, Any]:-- _kwargs: dict[str, Any] = {- "method": "get",- "url": "/api/keys",- }-- return _kwargs---def _parse_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> ErrorResponse | ListKeysResponse | None:- if response.status_code == 200:- response_200 = ListKeysResponse.from_dict(response.json())-- return response_200-- if response.status_code == 401:- response_401 = ErrorResponse.from_dict(response.json())-- return response_401-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> Response[ErrorResponse | ListKeysResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- *,- client: AuthenticatedClient | Client,-) -> Response[ErrorResponse | ListKeysResponse]:- """List the calling user's API keys-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[ErrorResponse | ListKeysResponse]- """-- kwargs = _get_kwargs()-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- *,- client: AuthenticatedClient | Client,-) -> ErrorResponse | ListKeysResponse | None:- """List the calling user's API keys-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- ErrorResponse | ListKeysResponse- """-- return sync_detailed(- client=client,- ).parsed---async def asyncio_detailed(- *,- client: AuthenticatedClient | Client,-) -> Response[ErrorResponse | ListKeysResponse]:- """List the calling user's API keys-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[ErrorResponse | ListKeysResponse]- """-- kwargs = _get_kwargs()-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- *,- client: AuthenticatedClient | Client,-) -> ErrorResponse | ListKeysResponse | None:- """List the calling user's API keys-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- ErrorResponse | ListKeysResponse- """-- return (- await asyncio_detailed(- client=client,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/label/__init__.py b/libs/fleet/python-sdk/cua_train/api/label/__init__.pydeleted file mode 100644index 2d7c0b23da..0000000000--- a/libs/fleet/python-sdk/cua_train/api/label/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""Contains endpoint functions for accessing the API"""diff --git a/libs/fleet/python-sdk/cua_train/api/label/cancel_label.py b/libs/fleet/python-sdk/cua_train/api/label/cancel_label.pydeleted file mode 100644index c22be8df0f..0000000000--- a/libs/fleet/python-sdk/cua_train/api/label/cancel_label.py+++ /dev/null@@ -1,188 +0,0 @@-from http import HTTPStatus-from typing import Any-from urllib.parse import quote--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.cancel_label_response import CancelLabelResponse-from ...models.error_response import ErrorResponse-from ...types import Response---def _get_kwargs(- pool: str,- label: str,-) -> dict[str, Any]:-- _kwargs: dict[str, Any] = {- "method": "delete",- "url": "/api/label/{pool}/{label}".format(- pool=quote(str(pool), safe=""),- label=quote(str(label), safe=""),- ),- }-- return _kwargs---def _parse_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> CancelLabelResponse | ErrorResponse | None:- if response.status_code == 200:- response_200 = CancelLabelResponse.from_dict(response.json())-- return response_200-- if response.status_code == 401:- response_401 = ErrorResponse.from_dict(response.json())-- return response_401-- if response.status_code == 404:- response_404 = ErrorResponse.from_dict(response.json())-- return response_404-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> Response[CancelLabelResponse | ErrorResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,-) -> Response[CancelLabelResponse | ErrorResponse]:- """Cancel every non-terminal batch under a label (scoped to pool)-- Cancels only batches submitted under `{pool}`; same label in other pools is untouched.-- Args:- pool (str):- label (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[CancelLabelResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- pool=pool,- label=label,- )-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,-) -> CancelLabelResponse | ErrorResponse | None:- """Cancel every non-terminal batch under a label (scoped to pool)-- Cancels only batches submitted under `{pool}`; same label in other pools is untouched.-- Args:- pool (str):- label (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- CancelLabelResponse | ErrorResponse- """-- return sync_detailed(- pool=pool,- label=label,- client=client,- ).parsed---async def asyncio_detailed(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,-) -> Response[CancelLabelResponse | ErrorResponse]:- """Cancel every non-terminal batch under a label (scoped to pool)-- Cancels only batches submitted under `{pool}`; same label in other pools is untouched.-- Args:- pool (str):- label (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[CancelLabelResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- pool=pool,- label=label,- )-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,-) -> CancelLabelResponse | ErrorResponse | None:- """Cancel every non-terminal batch under a label (scoped to pool)-- Cancels only batches submitted under `{pool}`; same label in other pools is untouched.-- Args:- pool (str):- label (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- CancelLabelResponse | ErrorResponse- """-- return (- await asyncio_detailed(- pool=pool,- label=label,- client=client,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/label/get_label_results.py b/libs/fleet/python-sdk/cua_train/api/label/get_label_results.pydeleted file mode 100644index 9083fd115a..0000000000--- a/libs/fleet/python-sdk/cua_train/api/label/get_label_results.py+++ /dev/null@@ -1,227 +0,0 @@-from http import HTTPStatus-from typing import Any-from urllib.parse import quote--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.error_response import ErrorResponse-from ...models.label_in_progress_response import LabelInProgressResponse-from ...models.label_results_response import LabelResultsResponse-from ...types import UNSET, Response, Unset---def _get_kwargs(- pool: str,- label: str,- *,- completed_only: bool | Unset = UNSET,-) -> dict[str, Any]:-- params: dict[str, Any] = {}-- params["completed_only"] = completed_only-- params = {k: v for k, v in params.items() if v is not UNSET and v is not None}-- _kwargs: dict[str, Any] = {- "method": "get",- "url": "/api/label/{pool}/{label}/results".format(- pool=quote(str(pool), safe=""),- label=quote(str(label), safe=""),- ),- "params": params,- }-- return _kwargs---def _parse_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> ErrorResponse | LabelInProgressResponse | LabelResultsResponse | None:- if response.status_code == 200:- response_200 = LabelResultsResponse.from_dict(response.json())-- return response_200-- if response.status_code == 202:- response_202 = LabelInProgressResponse.from_dict(response.json())-- return response_202-- if response.status_code == 401:- response_401 = ErrorResponse.from_dict(response.json())-- return response_401-- if response.status_code == 404:- response_404 = ErrorResponse.from_dict(response.json())-- return response_404-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> Response[ErrorResponse | LabelInProgressResponse | LabelResultsResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,- completed_only: bool | Unset = UNSET,-) -> Response[ErrorResponse | LabelInProgressResponse | LabelResultsResponse]:- """Aggregate results for all batches under a pool+label-- Default mode returns 200 only once every matched batch is completed.- Pass `?completed_only=true` to drain partial results (200 with the- filtered subset; non-completed batches are visible via status).- Aggregates only batches submitted under `{pool}`.-- Args:- pool (str):- label (str):- completed_only (bool | Unset):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[ErrorResponse | LabelInProgressResponse | LabelResultsResponse]- """-- kwargs = _get_kwargs(- pool=pool,- label=label,- completed_only=completed_only,- )-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,- completed_only: bool | Unset = UNSET,-) -> ErrorResponse | LabelInProgressResponse | LabelResultsResponse | None:- """Aggregate results for all batches under a pool+label-- Default mode returns 200 only once every matched batch is completed.- Pass `?completed_only=true` to drain partial results (200 with the- filtered subset; non-completed batches are visible via status).- Aggregates only batches submitted under `{pool}`.-- Args:- pool (str):- label (str):- completed_only (bool | Unset):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- ErrorResponse | LabelInProgressResponse | LabelResultsResponse- """-- return sync_detailed(- pool=pool,- label=label,- client=client,- completed_only=completed_only,- ).parsed---async def asyncio_detailed(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,- completed_only: bool | Unset = UNSET,-) -> Response[ErrorResponse | LabelInProgressResponse | LabelResultsResponse]:- """Aggregate results for all batches under a pool+label-- Default mode returns 200 only once every matched batch is completed.- Pass `?completed_only=true` to drain partial results (200 with the- filtered subset; non-completed batches are visible via status).- Aggregates only batches submitted under `{pool}`.-- Args:- pool (str):- label (str):- completed_only (bool | Unset):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[ErrorResponse | LabelInProgressResponse | LabelResultsResponse]- """-- kwargs = _get_kwargs(- pool=pool,- label=label,- completed_only=completed_only,- )-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,- completed_only: bool | Unset = UNSET,-) -> ErrorResponse | LabelInProgressResponse | LabelResultsResponse | None:- """Aggregate results for all batches under a pool+label-- Default mode returns 200 only once every matched batch is completed.- Pass `?completed_only=true` to drain partial results (200 with the- filtered subset; non-completed batches are visible via status).- Aggregates only batches submitted under `{pool}`.-- Args:- pool (str):- label (str):- completed_only (bool | Unset):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- ErrorResponse | LabelInProgressResponse | LabelResultsResponse- """-- return (- await asyncio_detailed(- pool=pool,- label=label,- client=client,- completed_only=completed_only,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/label/get_label_status.py b/libs/fleet/python-sdk/cua_train/api/label/get_label_status.pydeleted file mode 100644index 815a0f9507..0000000000--- a/libs/fleet/python-sdk/cua_train/api/label/get_label_status.py+++ /dev/null@@ -1,192 +0,0 @@-from http import HTTPStatus-from typing import Any-from urllib.parse import quote--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.error_response import ErrorResponse-from ...models.label_status_response import LabelStatusResponse-from ...types import Response---def _get_kwargs(- pool: str,- label: str,-) -> dict[str, Any]:-- _kwargs: dict[str, Any] = {- "method": "get",- "url": "/api/label/{pool}/{label}/status".format(- pool=quote(str(pool), safe=""),- label=quote(str(label), safe=""),- ),- }-- return _kwargs---def _parse_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> ErrorResponse | LabelStatusResponse | None:- if response.status_code == 200:- response_200 = LabelStatusResponse.from_dict(response.json())-- return response_200-- if response.status_code == 401:- response_401 = ErrorResponse.from_dict(response.json())-- return response_401-- if response.status_code == 404:- response_404 = ErrorResponse.from_dict(response.json())-- return response_404-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> Response[ErrorResponse | LabelStatusResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,-) -> Response[ErrorResponse | LabelStatusResponse]:- """Aggregate status for all batches under a pool+label-- Aggregates only batches submitted under `{pool}`; batches with the same label in other pools are- invisible.-- Args:- pool (str):- label (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[ErrorResponse | LabelStatusResponse]- """-- kwargs = _get_kwargs(- pool=pool,- label=label,- )-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,-) -> ErrorResponse | LabelStatusResponse | None:- """Aggregate status for all batches under a pool+label-- Aggregates only batches submitted under `{pool}`; batches with the same label in other pools are- invisible.-- Args:- pool (str):- label (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- ErrorResponse | LabelStatusResponse- """-- return sync_detailed(- pool=pool,- label=label,- client=client,- ).parsed---async def asyncio_detailed(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,-) -> Response[ErrorResponse | LabelStatusResponse]:- """Aggregate status for all batches under a pool+label-- Aggregates only batches submitted under `{pool}`; batches with the same label in other pools are- invisible.-- Args:- pool (str):- label (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[ErrorResponse | LabelStatusResponse]- """-- kwargs = _get_kwargs(- pool=pool,- label=label,- )-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,-) -> ErrorResponse | LabelStatusResponse | None:- """Aggregate status for all batches under a pool+label-- Aggregates only batches submitted under `{pool}`; batches with the same label in other pools are- invisible.-- Args:- pool (str):- label (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- ErrorResponse | LabelStatusResponse- """-- return (- await asyncio_detailed(- pool=pool,- label=label,- client=client,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/label/submit_label_batch.py b/libs/fleet/python-sdk/cua_train/api/label/submit_label_batch.pydeleted file mode 100644index 3131b4242a..0000000000--- a/libs/fleet/python-sdk/cua_train/api/label/submit_label_batch.py+++ /dev/null@@ -1,225 +0,0 @@-from http import HTTPStatus-from typing import Any-from urllib.parse import quote--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.batch_submit_request import BatchSubmitRequest-from ...models.batch_submit_response import BatchSubmitResponse-from ...models.error_response import ErrorResponse-from ...types import Response---def _get_kwargs(- pool: str,- label: str,- *,- body: BatchSubmitRequest,-) -> dict[str, Any]:- headers: dict[str, Any] = {}-- _kwargs: dict[str, Any] = {- "method": "post",- "url": "/api/label/{pool}/{label}/batch".format(- pool=quote(str(pool), safe=""),- label=quote(str(label), safe=""),- ),- }-- _kwargs["json"] = body.to_dict()-- headers["Content-Type"] = "application/json"-- _kwargs["headers"] = headers- return _kwargs---def _parse_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> BatchSubmitResponse | ErrorResponse | None:- if response.status_code == 202:- response_202 = BatchSubmitResponse.from_dict(response.json())-- return response_202-- if response.status_code == 400:- response_400 = ErrorResponse.from_dict(response.json())-- return response_400-- if response.status_code == 401:- response_401 = ErrorResponse.from_dict(response.json())-- return response_401-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(- *, client: AuthenticatedClient | Client, response: httpx.Response-) -> Response[BatchSubmitResponse | ErrorResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,- body: BatchSubmitRequest,-) -> Response[BatchSubmitResponse | ErrorResponse]:- """Submit a batch under a pool and label-- Same as `/api/batch/{pool}/submit` but pins the batch's `name`- field to the URL label, overriding any value in the body. The- label is scoped to `{pool}`; aggregate routes under- `/api/label/{pool}/{label}/*` only see batches submitted to the- same pool.-- Args:- pool (str):- label (str):- body (BatchSubmitRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[BatchSubmitResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- pool=pool,- label=label,- body=body,- )-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,- body: BatchSubmitRequest,-) -> BatchSubmitResponse | ErrorResponse | None:- """Submit a batch under a pool and label-- Same as `/api/batch/{pool}/submit` but pins the batch's `name`- field to the URL label, overriding any value in the body. The- label is scoped to `{pool}`; aggregate routes under- `/api/label/{pool}/{label}/*` only see batches submitted to the- same pool.-- Args:- pool (str):- label (str):- body (BatchSubmitRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- BatchSubmitResponse | ErrorResponse- """-- return sync_detailed(- pool=pool,- label=label,- client=client,- body=body,- ).parsed---async def asyncio_detailed(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,- body: BatchSubmitRequest,-) -> Response[BatchSubmitResponse | ErrorResponse]:- """Submit a batch under a pool and label-- Same as `/api/batch/{pool}/submit` but pins the batch's `name`- field to the URL label, overriding any value in the body. The- label is scoped to `{pool}`; aggregate routes under- `/api/label/{pool}/{label}/*` only see batches submitted to the- same pool.-- Args:- pool (str):- label (str):- body (BatchSubmitRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[BatchSubmitResponse | ErrorResponse]- """-- kwargs = _get_kwargs(- pool=pool,- label=label,- body=body,- )-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- pool: str,- label: str,- *,- client: AuthenticatedClient | Client,- body: BatchSubmitRequest,-) -> BatchSubmitResponse | ErrorResponse | None:- """Submit a batch under a pool and label-- Same as `/api/batch/{pool}/submit` but pins the batch's `name`- field to the URL label, overriding any value in the body. The- label is scoped to `{pool}`; aggregate routes under- `/api/label/{pool}/{label}/*` only see batches submitted to the- same pool.-- Args:- pool (str):- label (str):- body (BatchSubmitRequest):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- BatchSubmitResponse | ErrorResponse- """-- return (- await asyncio_detailed(- pool=pool,- label=label,- client=client,- body=body,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/lanes/__init__.py b/libs/fleet/python-sdk/cua_train/api/lanes/__init__.pydeleted file mode 100644index 2d7c0b23da..0000000000--- a/libs/fleet/python-sdk/cua_train/api/lanes/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""Contains endpoint functions for accessing the API"""diff --git a/libs/fleet/python-sdk/cua_train/api/lanes/create_lane_lanes_post.py b/libs/fleet/python-sdk/cua_train/api/lanes/create_lane_lanes_post.pydeleted file mode 100644index 0b99cd2dc1..0000000000--- a/libs/fleet/python-sdk/cua_train/api/lanes/create_lane_lanes_post.py+++ /dev/null@@ -1,220 +0,0 @@-from http import HTTPStatus-from typing import Any-from urllib.parse import quote--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.lane_create_request import LaneCreateRequest-from ...models.lane_response import LaneResponse-from ...types import Response---def _get_kwargs(- pool: str,- *,- body: LaneCreateRequest,-) -> dict[str, Any]:- headers: dict[str, Any] = {}-- _kwargs: dict[str, Any] = {- "method": "post",- "url": "/api/gateway/{pool}/lanes".format(- pool=quote(str(pool), safe=""),- ),- }-- _kwargs["json"] = body.to_dict()-- headers["Content-Type"] = "application/json"-- _kwargs["headers"] = headers- return _kwargs---def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> LaneResponse | None:- if response.status_code == 200:- response_200 = LaneResponse.from_dict(response.json())-- return response_200-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[LaneResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- pool: str,- *,- client: AuthenticatedClient | Client,- body: LaneCreateRequest,-) -> Response[LaneResponse]:- """Create Lane-- Create a lane: a fresh OSGymSandboxClaim bound to a Sandbox.-- The lane id is the stable handle the customer holds. The- underlying claim CR's name rotates on swap; the lane id does- not. The initial bind is via the normal queue+CAS-PATCH flow,- same as /reset.-- Args:- pool (str):- body (LaneCreateRequest): Body of POST /lanes.-- ``ttl_seconds`` is the absolute time the claim is reserved for;- after that the reaper deletes it. With ``autoRenew=true`` the lane- auto-renew timer in pool-operator pushes this forward, so the- customer's effective TTL is "as long as the lane exists".-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[LaneResponse]- """-- kwargs = _get_kwargs(- pool=pool,- body=body,- )-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- pool: str,- *,- client: AuthenticatedClient | Client,- body: LaneCreateRequest,-) -> LaneResponse | None:- """Create Lane-- Create a lane: a fresh OSGymSandboxClaim bound to a Sandbox.-- The lane id is the stable handle the customer holds. The- underlying claim CR's name rotates on swap; the lane id does- not. The initial bind is via the normal queue+CAS-PATCH flow,- same as /reset.-- Args:- pool (str):- body (LaneCreateRequest): Body of POST /lanes.-- ``ttl_seconds`` is the absolute time the claim is reserved for;- after that the reaper deletes it. With ``autoRenew=true`` the lane- auto-renew timer in pool-operator pushes this forward, so the- customer's effective TTL is "as long as the lane exists".-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- LaneResponse- """-- return sync_detailed(- pool=pool,- client=client,- body=body,- ).parsed---async def asyncio_detailed(- pool: str,- *,- client: AuthenticatedClient | Client,- body: LaneCreateRequest,-) -> Response[LaneResponse]:- """Create Lane-- Create a lane: a fresh OSGymSandboxClaim bound to a Sandbox.-- The lane id is the stable handle the customer holds. The- underlying claim CR's name rotates on swap; the lane id does- not. The initial bind is via the normal queue+CAS-PATCH flow,- same as /reset.-- Args:- pool (str):- body (LaneCreateRequest): Body of POST /lanes.-- ``ttl_seconds`` is the absolute time the claim is reserved for;- after that the reaper deletes it. With ``autoRenew=true`` the lane- auto-renew timer in pool-operator pushes this forward, so the- customer's effective TTL is "as long as the lane exists".-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[LaneResponse]- """-- kwargs = _get_kwargs(- pool=pool,- body=body,- )-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- pool: str,- *,- client: AuthenticatedClient | Client,- body: LaneCreateRequest,-) -> LaneResponse | None:- """Create Lane-- Create a lane: a fresh OSGymSandboxClaim bound to a Sandbox.-- The lane id is the stable handle the customer holds. The- underlying claim CR's name rotates on swap; the lane id does- not. The initial bind is via the normal queue+CAS-PATCH flow,- same as /reset.-- Args:- pool (str):- body (LaneCreateRequest): Body of POST /lanes.-- ``ttl_seconds`` is the absolute time the claim is reserved for;- after that the reaper deletes it. With ``autoRenew=true`` the lane- auto-renew timer in pool-operator pushes this forward, so the- customer's effective TTL is "as long as the lane exists".-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- LaneResponse- """-- return (- await asyncio_detailed(- pool=pool,- client=client,- body=body,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/lanes/delete_lane_lanes_lane_id_delete.py b/libs/fleet/python-sdk/cua_train/api/lanes/delete_lane_lanes_lane_id_delete.pydeleted file mode 100644index 970656aa75..0000000000--- a/libs/fleet/python-sdk/cua_train/api/lanes/delete_lane_lanes_lane_id_delete.py+++ /dev/null@@ -1,173 +0,0 @@-from http import HTTPStatus-from typing import Any-from urllib.parse import quote--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.lane_delete_response import LaneDeleteResponse-from ...types import Response---def _get_kwargs(- pool: str,- lane_id: str,-) -> dict[str, Any]:-- _kwargs: dict[str, Any] = {- "method": "delete",- "url": "/api/gateway/{pool}/lanes/{lane_id}".format(- pool=quote(str(pool), safe=""),- lane_id=quote(str(lane_id), safe=""),- ),- }-- return _kwargs---def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> LaneDeleteResponse | None:- if response.status_code == 200:- response_200 = LaneDeleteResponse.from_dict(response.json())-- return response_200-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[LaneDeleteResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- pool: str,- lane_id: str,- *,- client: AuthenticatedClient | Client,-) -> Response[LaneDeleteResponse]:- """Delete Lane-- Release the lane's bound claim. Idempotent.-- Args:- pool (str):- lane_id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[LaneDeleteResponse]- """-- kwargs = _get_kwargs(- pool=pool,- lane_id=lane_id,- )-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- pool: str,- lane_id: str,- *,- client: AuthenticatedClient | Client,-) -> LaneDeleteResponse | None:- """Delete Lane-- Release the lane's bound claim. Idempotent.-- Args:- pool (str):- lane_id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- LaneDeleteResponse- """-- return sync_detailed(- pool=pool,- lane_id=lane_id,- client=client,- ).parsed---async def asyncio_detailed(- pool: str,- lane_id: str,- *,- client: AuthenticatedClient | Client,-) -> Response[LaneDeleteResponse]:- """Delete Lane-- Release the lane's bound claim. Idempotent.-- Args:- pool (str):- lane_id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[LaneDeleteResponse]- """-- kwargs = _get_kwargs(- pool=pool,- lane_id=lane_id,- )-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- pool: str,- lane_id: str,- *,- client: AuthenticatedClient | Client,-) -> LaneDeleteResponse | None:- """Delete Lane-- Release the lane's bound claim. Idempotent.-- Args:- pool (str):- lane_id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- LaneDeleteResponse- """-- return (- await asyncio_detailed(- pool=pool,- lane_id=lane_id,- client=client,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/api/lanes/swap_lanes_lane_id_swap_post.py b/libs/fleet/python-sdk/cua_train/api/lanes/swap_lanes_lane_id_swap_post.pydeleted file mode 100644index 5373481c33..0000000000--- a/libs/fleet/python-sdk/cua_train/api/lanes/swap_lanes_lane_id_swap_post.py+++ /dev/null@@ -1,193 +0,0 @@-from http import HTTPStatus-from typing import Any-from urllib.parse import quote--import httpx--from ... import errors-from ...client import AuthenticatedClient, Client-from ...models.lane_swap_response import LaneSwapResponse-from ...types import Response---def _get_kwargs(- pool: str,- lane_id: str,-) -> dict[str, Any]:-- _kwargs: dict[str, Any] = {- "method": "post",- "url": "/api/gateway/{pool}/lanes/{lane_id}/swap".format(- pool=quote(str(pool), safe=""),- lane_id=quote(str(lane_id), safe=""),- ),- }-- return _kwargs---def _parse_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> LaneSwapResponse | None:- if response.status_code == 200:- response_200 = LaneSwapResponse.from_dict(response.json())-- return response_200-- if client.raise_on_unexpected_status:- raise errors.UnexpectedStatus(response.status_code, response.content)- else:- return None---def _build_response(*, client: AuthenticatedClient | Client, response: httpx.Response) -> Response[LaneSwapResponse]:- return Response(- status_code=HTTPStatus(response.status_code),- content=response.content,- headers=response.headers,- parsed=_parse_response(client=client, response=response),- )---def sync_detailed(- pool: str,- lane_id: str,- *,- client: AuthenticatedClient | Client,-) -> Response[LaneSwapResponse]:- """Swap-- New-first claim rotation for ``lane_id``.-- Calls into the pure protocol body in osgym/lane_swap.py with a- K8s-backed SwapDeps. The lane keeps its bound VM if the swap- bind times out (SwapAtomicity); the new vm_id is returned on- success.-- Args:- pool (str):- lane_id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[LaneSwapResponse]- """-- kwargs = _get_kwargs(- pool=pool,- lane_id=lane_id,- )-- response = client.get_httpx_client().request(- **kwargs,- )-- return _build_response(client=client, response=response)---def sync(- pool: str,- lane_id: str,- *,- client: AuthenticatedClient | Client,-) -> LaneSwapResponse | None:- """Swap-- New-first claim rotation for ``lane_id``.-- Calls into the pure protocol body in osgym/lane_swap.py with a- K8s-backed SwapDeps. The lane keeps its bound VM if the swap- bind times out (SwapAtomicity); the new vm_id is returned on- success.-- Args:- pool (str):- lane_id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- LaneSwapResponse- """-- return sync_detailed(- pool=pool,- lane_id=lane_id,- client=client,- ).parsed---async def asyncio_detailed(- pool: str,- lane_id: str,- *,- client: AuthenticatedClient | Client,-) -> Response[LaneSwapResponse]:- """Swap-- New-first claim rotation for ``lane_id``.-- Calls into the pure protocol body in osgym/lane_swap.py with a- K8s-backed SwapDeps. The lane keeps its bound VM if the swap- bind times out (SwapAtomicity); the new vm_id is returned on- success.-- Args:- pool (str):- lane_id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- Response[LaneSwapResponse]- """-- kwargs = _get_kwargs(- pool=pool,- lane_id=lane_id,- )-- response = await client.get_async_httpx_client().request(**kwargs)-- return _build_response(client=client, response=response)---async def asyncio(- pool: str,- lane_id: str,- *,- client: AuthenticatedClient | Client,-) -> LaneSwapResponse | None:- """Swap-- New-first claim rotation for ``lane_id``.-- Calls into the pure protocol body in osgym/lane_swap.py with a- K8s-backed SwapDeps. The lane keeps its bound VM if the swap- bind times out (SwapAtomicity); the new vm_id is returned on- success.-- Args:- pool (str):- lane_id (str):-- Raises:- errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.- httpx.TimeoutException: If the request takes longer than Client.timeout.-- Returns:- LaneSwapResponse- """-- return (- await asyncio_detailed(- pool=pool,- lane_id=lane_id,- client=client,- )- ).parseddiff --git a/libs/fleet/python-sdk/cua_train/client.py b/libs/fleet/python-sdk/cua_train/client.pydeleted file mode 100644index 1b7055ab87..0000000000--- a/libs/fleet/python-sdk/cua_train/client.py+++ /dev/null@@ -1,268 +0,0 @@-import ssl-from typing import Any--import httpx-from attrs import define, evolve, field---@define-class Client:- """A class for keeping track of data related to the API-- The following are accepted as keyword arguments and will be used to construct httpx Clients internally:-- ``base_url``: The base URL for the API, all requests are made to a relative path to this URL-- ``cookies``: A dictionary of cookies to be sent with every request-- ``headers``: A dictionary of headers to be sent with every request-- ``timeout``: The maximum amount of a time a request can take. API functions will raise- httpx.TimeoutException if this is exceeded.-- ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,- but can be set to False for testing purposes.-- ``follow_redirects``: Whether or not to follow redirects. Default value is False.-- ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.--- Attributes:- raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a- status code that was not documented in the source OpenAPI document. Can also be provided as a keyword- argument to the constructor.- """-- raise_on_unexpected_status: bool = field(default=False, kw_only=True)- _base_url: str = field(alias="base_url")- _cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")- _headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")- _timeout: httpx.Timeout | None = field(default=None, kw_only=True, alias="timeout")- _verify_ssl: str | bool | ssl.SSLContext = field(default=True, kw_only=True, alias="verify_ssl")- _follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")- _httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")- _client: httpx.Client | None = field(default=None, init=False)- _async_client: httpx.AsyncClient | None = field(default=None, init=False)-- def with_headers(self, headers: dict[str, str]) -> "Client":- """Get a new client matching this one with additional headers"""- if self._client is not None:- self._client.headers.update(headers)- if self._async_client is not None:- self._async_client.headers.update(headers)- return evolve(self, headers={**self._headers, **headers})-- def with_cookies(self, cookies: dict[str, str]) -> "Client":- """Get a new client matching this one with additional cookies"""- if self._client is not None:- self._client.cookies.update(cookies)- if self._async_client is not None:- self._async_client.cookies.update(cookies)- return evolve(self, cookies={**self._cookies, **cookies})-- def with_timeout(self, timeout: httpx.Timeout) -> "Client":- """Get a new client matching this one with a new timeout configuration"""- if self._client is not None:- self._client.timeout = timeout- if self._async_client is not None:- self._async_client.timeout = timeout- return evolve(self, timeout=timeout)-- def set_httpx_client(self, client: httpx.Client) -> "Client":- """Manually set the underlying httpx.Client-- **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.- """- self._client = client- return self-- def get_httpx_client(self) -> httpx.Client:- """Get the underlying httpx.Client, constructing a new one if not previously set"""- if self._client is None:- self._client = httpx.Client(- base_url=self._base_url,- cookies=self._cookies,- headers=self._headers,- timeout=self._timeout,- verify=self._verify_ssl,- follow_redirects=self._follow_redirects,- **self._httpx_args,- )- return self._client-- def __enter__(self) -> "Client":- """Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""- self.get_httpx_client().__enter__()- return self-- def __exit__(self, *args: Any, **kwargs: Any) -> None:- """Exit a context manager for internal httpx.Client (see httpx docs)"""- self.get_httpx_client().__exit__(*args, **kwargs)-- def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "Client":- """Manually set the underlying httpx.AsyncClient-- **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.- """- self._async_client = async_client- return self-- def get_async_httpx_client(self) -> httpx.AsyncClient:- """Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""- if self._async_client is None:- self._async_client = httpx.AsyncClient(- base_url=self._base_url,- cookies=self._cookies,- headers=self._headers,- timeout=self._timeout,- verify=self._verify_ssl,- follow_redirects=self._follow_redirects,- **self._httpx_args,- )- return self._async_client-- async def __aenter__(self) -> "Client":- """Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""- await self.get_async_httpx_client().__aenter__()- return self-- async def __aexit__(self, *args: Any, **kwargs: Any) -> None:- """Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""- await self.get_async_httpx_client().__aexit__(*args, **kwargs)---@define-class AuthenticatedClient:- """A Client which has been authenticated for use on secured endpoints-- The following are accepted as keyword arguments and will be used to construct httpx Clients internally:-- ``base_url``: The base URL for the API, all requests are made to a relative path to this URL-- ``cookies``: A dictionary of cookies to be sent with every request-- ``headers``: A dictionary of headers to be sent with every request-- ``timeout``: The maximum amount of a time a request can take. API functions will raise- httpx.TimeoutException if this is exceeded.-- ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,- but can be set to False for testing purposes.-- ``follow_redirects``: Whether or not to follow redirects. Default value is False.-- ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.--- Attributes:- raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a- status code that was not documented in the source OpenAPI document. Can also be provided as a keyword- argument to the constructor.- token: The token to use for authentication- prefix: The prefix to use for the Authorization header- auth_header_name: The name of the Authorization header- """-- raise_on_unexpected_status: bool = field(default=False, kw_only=True)- _base_url: str = field(alias="base_url")- _cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")- _headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")- _timeout: httpx.Timeout | None = field(default=None, kw_only=True, alias="timeout")- _verify_ssl: str | bool | ssl.SSLContext = field(default=True, kw_only=True, alias="verify_ssl")- _follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")- _httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")- _client: httpx.Client | None = field(default=None, init=False)- _async_client: httpx.AsyncClient | None = field(default=None, init=False)-- token: str- prefix: str = "Bearer"- auth_header_name: str = "Authorization"-- def with_headers(self, headers: dict[str, str]) -> "AuthenticatedClient":- """Get a new client matching this one with additional headers"""- if self._client is not None:- self._client.headers.update(headers)- if self._async_client is not None:- self._async_client.headers.update(headers)- return evolve(self, headers={**self._headers, **headers})-- def with_cookies(self, cookies: dict[str, str]) -> "AuthenticatedClient":- """Get a new client matching this one with additional cookies"""- if self._client is not None:- self._client.cookies.update(cookies)- if self._async_client is not None:- self._async_client.cookies.update(cookies)- return evolve(self, cookies={**self._cookies, **cookies})-- def with_timeout(self, timeout: httpx.Timeout) -> "AuthenticatedClient":- """Get a new client matching this one with a new timeout configuration"""- if self._client is not None:- self._client.timeout = timeout- if self._async_client is not None:- self._async_client.timeout = timeout- return evolve(self, timeout=timeout)-- def set_httpx_client(self, client: httpx.Client) -> "AuthenticatedClient":- """Manually set the underlying httpx.Client-- **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.- """- self._client = client- return self-- def get_httpx_client(self) -> httpx.Client:- """Get the underlying httpx.Client, constructing a new one if not previously set"""- if self._client is None:- self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token- self._client = httpx.Client(- base_url=self._base_url,- cookies=self._cookies,- headers=self._headers,- timeout=self._timeout,- verify=self._verify_ssl,- follow_redirects=self._follow_redirects,- **self._httpx_args,- )- return self._client-- def __enter__(self) -> "AuthenticatedClient":- """Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""- self.get_httpx_client().__enter__()- return self-- def __exit__(self, *args: Any, **kwargs: Any) -> None:- """Exit a context manager for internal httpx.Client (see httpx docs)"""- self.get_httpx_client().__exit__(*args, **kwargs)-- def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "AuthenticatedClient":- """Manually set the underlying httpx.AsyncClient-- **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.- """- self._async_client = async_client- return self-- def get_async_httpx_client(self) -> httpx.AsyncClient:- """Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""- if self._async_client is None:- self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token- self._async_client = httpx.AsyncClient(- base_url=self._base_url,- cookies=self._cookies,- headers=self._headers,- timeout=self._timeout,- verify=self._verify_ssl,- follow_redirects=self._follow_redirects,- **self._httpx_args,- )- return self._async_client-- async def __aenter__(self) -> "AuthenticatedClient":- """Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""- await self.get_async_httpx_client().__aenter__()- return self-- async def __aexit__(self, *args: Any, **kwargs: Any) -> None:- """Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""- await self.get_async_httpx_client().__aexit__(*args, **kwargs)diff --git a/libs/fleet/python-sdk/cua_train/errors.py b/libs/fleet/python-sdk/cua_train/errors.pydeleted file mode 100644index 5f92e76aca..0000000000--- a/libs/fleet/python-sdk/cua_train/errors.py+++ /dev/null@@ -1,16 +0,0 @@-"""Contains shared errors types that can be raised from API functions"""---class UnexpectedStatus(Exception):- """Raised by api functions when the response status an undocumented status and Client.raise_on_unexpected_status is True"""-- def __init__(self, status_code: int, content: bytes):- self.status_code = status_code- self.content = content-- super().__init__(- f"Unexpected status code: {status_code}\n\nResponse content:\n{content.decode(errors='ignore')}"- )---__all__ = ["UnexpectedStatus"]diff --git a/libs/fleet/python-sdk/cua_train/models/__init__.py b/libs/fleet/python-sdk/cua_train/models/__init__.pydeleted file mode 100644index 39cb3e01a1..0000000000--- a/libs/fleet/python-sdk/cua_train/models/__init__.py+++ /dev/null@@ -1,93 +0,0 @@-"""Contains all the data models used in inputs/outputs"""--from .acquire_lanes_request import AcquireLanesRequest-from .acquire_lanes_response import AcquireLanesResponse-from .action import Action-from .action_parameters import ActionParameters-from .batch_in_progress_response import BatchInProgressResponse-from .batch_progress import BatchProgress-from .batch_results_response import BatchResultsResponse-from .batch_status_response import BatchStatusResponse-from .batch_submit_request import BatchSubmitRequest-from .batch_submit_response import BatchSubmitResponse-from .batch_summary import BatchSummary-from .cancel_batch_response import CancelBatchResponse-from .cancel_label_batch_item import CancelLabelBatchItem-from .cancel_label_response import CancelLabelResponse-from .create_key_request import CreateKeyRequest-from .create_key_response import CreateKeyResponse-from .error_response import ErrorResponse-from .health_response import HealthResponse-from .healthz_response import HealthzResponse-from .key_client import KeyClient-from .label_batch_summary import LabelBatchSummary-from .label_in_progress_response import LabelInProgressResponse-from .label_results_response import LabelResultsResponse-from .label_status_response import LabelStatusResponse-from .lane_create_request import LaneCreateRequest-from .lane_delete_response import LaneDeleteResponse-from .lane_response import LaneResponse-from .lane_swap_response import LaneSwapResponse-from .list_keys_response import ListKeysResponse-from .pool_list_response import PoolListResponse-from .pool_list_response_vms_item import PoolListResponseVmsItem-from .release_lanes_request import ReleaseLanesRequest-from .release_lanes_response import ReleaseLanesResponse-from .reset_request import ResetRequest-from .reset_request_task_config import ResetRequestTaskConfig-from .reset_response import ResetResponse-from .run_config import RunConfig-from .run_result import RunResult-from .screenshot_response import ScreenshotResponse-from .shutdown_request import ShutdownRequest-from .shutdown_response import ShutdownResponse-from .step_request import StepRequest-from .step_response import StepResponse-from .timing_stats import TimingStats--__all__ = (- "AcquireLanesRequest",- "AcquireLanesResponse",- "Action",- "ActionParameters",- "BatchInProgressResponse",- "BatchProgress",- "BatchResultsResponse",- "BatchStatusResponse",- "BatchSubmitRequest",- "BatchSubmitResponse",- "BatchSummary",- "CancelBatchResponse",- "CancelLabelBatchItem",- "CancelLabelResponse",- "CreateKeyRequest",- "CreateKeyResponse",- "ErrorResponse",- "HealthResponse",- "HealthzResponse",- "KeyClient",- "LabelBatchSummary",- "LabelInProgressResponse",- "LabelResultsResponse",- "LabelStatusResponse",- "LaneCreateRequest",- "LaneDeleteResponse",- "LaneResponse",- "LaneSwapResponse",- "ListKeysResponse",- "PoolListResponse",- "PoolListResponseVmsItem",- "ReleaseLanesRequest",- "ReleaseLanesResponse",- "ResetRequest",- "ResetRequestTaskConfig",- "ResetResponse",- "RunConfig",- "RunResult",- "ScreenshotResponse",- "ShutdownRequest",- "ShutdownResponse",- "StepRequest",- "StepResponse",- "TimingStats",-)diff --git a/libs/fleet/python-sdk/cua_train/models/acquire_lanes_request.py b/libs/fleet/python-sdk/cua_train/models/acquire_lanes_request.pydeleted file mode 100644index 0c4d559eef..0000000000--- a/libs/fleet/python-sdk/cua_train/models/acquire_lanes_request.py+++ /dev/null@@ -1,61 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--T = TypeVar("T", bound="AcquireLanesRequest")---@_attrs_define-class AcquireLanesRequest:- """- Attributes:- n (int): Number of warm VM lanes to acquire.- """-- n: int- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- n = self.n-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "n": n,- }- )-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- n = d.pop("n")-- acquire_lanes_request = cls(- n=n,- )-- acquire_lanes_request.additional_properties = d- return acquire_lanes_request-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/acquire_lanes_response.py b/libs/fleet/python-sdk/cua_train/models/acquire_lanes_response.pydeleted file mode 100644index 94a07a9934..0000000000--- a/libs/fleet/python-sdk/cua_train/models/acquire_lanes_response.py+++ /dev/null@@ -1,63 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar, cast--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="AcquireLanesResponse")---@_attrs_define-class AcquireLanesResponse:- """- Attributes:- vm_ids (list[str] | Unset): One warm VM id per acquired lane. Use as RunConfig.vm_id.- """-- vm_ids: list[str] | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- vm_ids: list[str] | Unset = UNSET- if not isinstance(self.vm_ids, Unset):- vm_ids = self.vm_ids-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if vm_ids is not UNSET:- field_dict["vm_ids"] = vm_ids-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- vm_ids = cast(list[str], d.pop("vm_ids", UNSET))-- acquire_lanes_response = cls(- vm_ids=vm_ids,- )-- acquire_lanes_response.additional_properties = d- return acquire_lanes_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/action.py b/libs/fleet/python-sdk/cua_train/models/action.pydeleted file mode 100644index 885240e29c..0000000000--- a/libs/fleet/python-sdk/cua_train/models/action.py+++ /dev/null@@ -1,85 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--if TYPE_CHECKING:- from ..models.action_parameters import ActionParameters---T = TypeVar("T", bound="Action")---@_attrs_define-class Action:- """- Attributes:- action_type (str): OSGym action type (e.g. CLICK, TYPE, KEY). Example: CLICK.- parameters (ActionParameters | Unset): Action-type-specific parameters (e.g. `{x, y, button}` for CLICK).- """-- action_type: str- parameters: ActionParameters | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- action_type = self.action_type-- parameters: dict[str, Any] | Unset = UNSET- if not isinstance(self.parameters, Unset):- parameters = self.parameters.to_dict()-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "action_type": action_type,- }- )- if parameters is not UNSET:- field_dict["parameters"] = parameters-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- from ..models.action_parameters import ActionParameters-- d = dict(src_dict)- action_type = d.pop("action_type")-- _parameters = d.pop("parameters", UNSET)- parameters: ActionParameters | Unset- if isinstance(_parameters, Unset):- parameters = UNSET- else:- parameters = ActionParameters.from_dict(_parameters)-- action = cls(- action_type=action_type,- parameters=parameters,- )-- action.additional_properties = d- return action-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/action_parameters.py b/libs/fleet/python-sdk/cua_train/models/action_parameters.pydeleted file mode 100644index be814ccb07..0000000000--- a/libs/fleet/python-sdk/cua_train/models/action_parameters.py+++ /dev/null@@ -1,47 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--T = TypeVar("T", bound="ActionParameters")---@_attrs_define-class ActionParameters:- """Action-type-specific parameters (e.g. `{x, y, button}` for CLICK)."""-- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- action_parameters = cls()-- action_parameters.additional_properties = d- return action_parameters-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/batch_in_progress_response.py b/libs/fleet/python-sdk/cua_train/models/batch_in_progress_response.pydeleted file mode 100644index e5fe35fb10..0000000000--- a/libs/fleet/python-sdk/cua_train/models/batch_in_progress_response.py+++ /dev/null@@ -1,79 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="BatchInProgressResponse")---@_attrs_define-class BatchInProgressResponse:- """- Attributes:- batch_id (str | Unset):- status (str | Unset):- message (str | Unset):- """-- batch_id: str | Unset = UNSET- status: str | Unset = UNSET- message: str | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- batch_id = self.batch_id-- status = self.status-- message = self.message-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if batch_id is not UNSET:- field_dict["batch_id"] = batch_id- if status is not UNSET:- field_dict["status"] = status- if message is not UNSET:- field_dict["message"] = message-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- batch_id = d.pop("batch_id", UNSET)-- status = d.pop("status", UNSET)-- message = d.pop("message", UNSET)-- batch_in_progress_response = cls(- batch_id=batch_id,- status=status,- message=message,- )-- batch_in_progress_response.additional_properties = d- return batch_in_progress_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/batch_progress.py b/libs/fleet/python-sdk/cua_train/models/batch_progress.pydeleted file mode 100644index c5e3f97322..0000000000--- a/libs/fleet/python-sdk/cua_train/models/batch_progress.py+++ /dev/null@@ -1,88 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="BatchProgress")---@_attrs_define-class BatchProgress:- """- Attributes:- completed (int | Unset):- total (int | Unset):- ok (int | Unset):- failed (int | Unset):- """-- completed: int | Unset = UNSET- total: int | Unset = UNSET- ok: int | Unset = UNSET- failed: int | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- completed = self.completed-- total = self.total-- ok = self.ok-- failed = self.failed-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if completed is not UNSET:- field_dict["completed"] = completed- if total is not UNSET:- field_dict["total"] = total- if ok is not UNSET:- field_dict["ok"] = ok- if failed is not UNSET:- field_dict["failed"] = failed-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- completed = d.pop("completed", UNSET)-- total = d.pop("total", UNSET)-- ok = d.pop("ok", UNSET)-- failed = d.pop("failed", UNSET)-- batch_progress = cls(- completed=completed,- total=total,- ok=ok,- failed=failed,- )-- batch_progress.additional_properties = d- return batch_progress-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/batch_results_response.py b/libs/fleet/python-sdk/cua_train/models/batch_results_response.pydeleted file mode 100644index 1d9590fbc6..0000000000--- a/libs/fleet/python-sdk/cua_train/models/batch_results_response.py+++ /dev/null@@ -1,151 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--if TYPE_CHECKING:- from ..models.batch_summary import BatchSummary- from ..models.run_result import RunResult---T = TypeVar("T", bound="BatchResultsResponse")---@_attrs_define-class BatchResultsResponse:- """- Attributes:- batch_id (str | Unset):- name (str | Unset):- status (str | Unset):- runs (list[RunResult] | Unset):- s3_bucket (str | Unset):- s3_key (str | Unset):- s3_presigned_url (str | Unset):- summary (BatchSummary | Unset):- """-- batch_id: str | Unset = UNSET- name: str | Unset = UNSET- status: str | Unset = UNSET- runs: list[RunResult] | Unset = UNSET- s3_bucket: str | Unset = UNSET- s3_key: str | Unset = UNSET- s3_presigned_url: str | Unset = UNSET- summary: BatchSummary | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- batch_id = self.batch_id-- name = self.name-- status = self.status-- runs: list[dict[str, Any]] | Unset = UNSET- if not isinstance(self.runs, Unset):- runs = []- for runs_item_data in self.runs:- runs_item = runs_item_data.to_dict()- runs.append(runs_item)-- s3_bucket = self.s3_bucket-- s3_key = self.s3_key-- s3_presigned_url = self.s3_presigned_url-- summary: dict[str, Any] | Unset = UNSET- if not isinstance(self.summary, Unset):- summary = self.summary.to_dict()-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if batch_id is not UNSET:- field_dict["batch_id"] = batch_id- if name is not UNSET:- field_dict["name"] = name- if status is not UNSET:- field_dict["status"] = status- if runs is not UNSET:- field_dict["runs"] = runs- if s3_bucket is not UNSET:- field_dict["s3_bucket"] = s3_bucket- if s3_key is not UNSET:- field_dict["s3_key"] = s3_key- if s3_presigned_url is not UNSET:- field_dict["s3_presigned_url"] = s3_presigned_url- if summary is not UNSET:- field_dict["summary"] = summary-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- from ..models.batch_summary import BatchSummary- from ..models.run_result import RunResult-- d = dict(src_dict)- batch_id = d.pop("batch_id", UNSET)-- name = d.pop("name", UNSET)-- status = d.pop("status", UNSET)-- _runs = d.pop("runs", UNSET)- runs: list[RunResult] | Unset = UNSET- if _runs is not UNSET:- runs = []- for runs_item_data in _runs:- runs_item = RunResult.from_dict(runs_item_data)-- runs.append(runs_item)-- s3_bucket = d.pop("s3_bucket", UNSET)-- s3_key = d.pop("s3_key", UNSET)-- s3_presigned_url = d.pop("s3_presigned_url", UNSET)-- _summary = d.pop("summary", UNSET)- summary: BatchSummary | Unset- if isinstance(_summary, Unset):- summary = UNSET- else:- summary = BatchSummary.from_dict(_summary)-- batch_results_response = cls(- batch_id=batch_id,- name=name,- status=status,- runs=runs,- s3_bucket=s3_bucket,- s3_key=s3_key,- s3_presigned_url=s3_presigned_url,- summary=summary,- )-- batch_results_response.additional_properties = d- return batch_results_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/batch_status_response.py b/libs/fleet/python-sdk/cua_train/models/batch_status_response.pydeleted file mode 100644index 8287aea218..0000000000--- a/libs/fleet/python-sdk/cua_train/models/batch_status_response.py+++ /dev/null@@ -1,134 +0,0 @@-from __future__ import annotations--import datetime-from collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--if TYPE_CHECKING:- from ..models.batch_progress import BatchProgress---T = TypeVar("T", bound="BatchStatusResponse")---@_attrs_define-class BatchStatusResponse:- """- Attributes:- batch_id (str | Unset):- name (str | Unset):- status (str | Unset):- progress (BatchProgress | Unset):- created_at (datetime.datetime | Unset):- updated_at (datetime.datetime | Unset):- """-- batch_id: str | Unset = UNSET- name: str | Unset = UNSET- status: str | Unset = UNSET- progress: BatchProgress | Unset = UNSET- created_at: datetime.datetime | Unset = UNSET- updated_at: datetime.datetime | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- batch_id = self.batch_id-- name = self.name-- status = self.status-- progress: dict[str, Any] | Unset = UNSET- if not isinstance(self.progress, Unset):- progress = self.progress.to_dict()-- created_at: str | Unset = UNSET- if not isinstance(self.created_at, Unset):- created_at = self.created_at.isoformat()-- updated_at: str | Unset = UNSET- if not isinstance(self.updated_at, Unset):- updated_at = self.updated_at.isoformat()-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if batch_id is not UNSET:- field_dict["batch_id"] = batch_id- if name is not UNSET:- field_dict["name"] = name- if status is not UNSET:- field_dict["status"] = status- if progress is not UNSET:- field_dict["progress"] = progress- if created_at is not UNSET:- field_dict["created_at"] = created_at- if updated_at is not UNSET:- field_dict["updated_at"] = updated_at-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- from ..models.batch_progress import BatchProgress-- d = dict(src_dict)- batch_id = d.pop("batch_id", UNSET)-- name = d.pop("name", UNSET)-- status = d.pop("status", UNSET)-- _progress = d.pop("progress", UNSET)- progress: BatchProgress | Unset- if isinstance(_progress, Unset):- progress = UNSET- else:- progress = BatchProgress.from_dict(_progress)-- _created_at = d.pop("created_at", UNSET)- created_at: datetime.datetime | Unset- if isinstance(_created_at, Unset):- created_at = UNSET- else:- created_at = datetime.datetime.fromisoformat(_created_at)-- _updated_at = d.pop("updated_at", UNSET)- updated_at: datetime.datetime | Unset- if isinstance(_updated_at, Unset):- updated_at = UNSET- else:- updated_at = datetime.datetime.fromisoformat(_updated_at)-- batch_status_response = cls(- batch_id=batch_id,- name=name,- status=status,- progress=progress,- created_at=created_at,- updated_at=updated_at,- )-- batch_status_response.additional_properties = d- return batch_status_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/batch_submit_request.py b/libs/fleet/python-sdk/cua_train/models/batch_submit_request.pydeleted file mode 100644index 37b2956ce1..0000000000--- a/libs/fleet/python-sdk/cua_train/models/batch_submit_request.py+++ /dev/null@@ -1,115 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--if TYPE_CHECKING:- from ..models.run_config import RunConfig---T = TypeVar("T", bound="BatchSubmitRequest")---@_attrs_define-class BatchSubmitRequest:- """- Attributes:- runs (list[RunConfig]):- concurrency (int | Unset): Default: 10.- pool_name (str | Unset): Optional — must match the URL `{pool}` if provided; ignored otherwise.- name (str | Unset): Optional batch name. Overridden by the URL `{label}` on label routes.- keep_warm (bool | Unset): Leave each run's VM running when the run ends (instead of shutting it down), so a- follow-up batch can reattach to it via RunConfig.vm_id (read each lane's surviving id from RunResult.vm_id).- Best-effort: a warm VM is reaped after its claim TTL (~minutes), after which reattach falls back to a fresh VM.- """-- runs: list[RunConfig]- concurrency: int | Unset = 10- pool_name: str | Unset = UNSET- name: str | Unset = UNSET- keep_warm: bool | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- runs = []- for runs_item_data in self.runs:- runs_item = runs_item_data.to_dict()- runs.append(runs_item)-- concurrency = self.concurrency-- pool_name = self.pool_name-- name = self.name-- keep_warm = self.keep_warm-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "runs": runs,- }- )- if concurrency is not UNSET:- field_dict["concurrency"] = concurrency- if pool_name is not UNSET:- field_dict["pool_name"] = pool_name- if name is not UNSET:- field_dict["name"] = name- if keep_warm is not UNSET:- field_dict["keep_warm"] = keep_warm-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- from ..models.run_config import RunConfig-- d = dict(src_dict)- runs = []- _runs = d.pop("runs")- for runs_item_data in _runs:- runs_item = RunConfig.from_dict(runs_item_data)-- runs.append(runs_item)-- concurrency = d.pop("concurrency", UNSET)-- pool_name = d.pop("pool_name", UNSET)-- name = d.pop("name", UNSET)-- keep_warm = d.pop("keep_warm", UNSET)-- batch_submit_request = cls(- runs=runs,- concurrency=concurrency,- pool_name=pool_name,- name=name,- keep_warm=keep_warm,- )-- batch_submit_request.additional_properties = d- return batch_submit_request-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/batch_submit_response.py b/libs/fleet/python-sdk/cua_train/models/batch_submit_response.pydeleted file mode 100644index 679370ff0e..0000000000--- a/libs/fleet/python-sdk/cua_train/models/batch_submit_response.py+++ /dev/null@@ -1,96 +0,0 @@-from __future__ import annotations--import datetime-from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="BatchSubmitResponse")---@_attrs_define-class BatchSubmitResponse:- """- Attributes:- batch_id (str | Unset):- name (str | Unset):- status (str | Unset):- created_at (datetime.datetime | Unset):- """-- batch_id: str | Unset = UNSET- name: str | Unset = UNSET- status: str | Unset = UNSET- created_at: datetime.datetime | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- batch_id = self.batch_id-- name = self.name-- status = self.status-- created_at: str | Unset = UNSET- if not isinstance(self.created_at, Unset):- created_at = self.created_at.isoformat()-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if batch_id is not UNSET:- field_dict["batch_id"] = batch_id- if name is not UNSET:- field_dict["name"] = name- if status is not UNSET:- field_dict["status"] = status- if created_at is not UNSET:- field_dict["created_at"] = created_at-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- batch_id = d.pop("batch_id", UNSET)-- name = d.pop("name", UNSET)-- status = d.pop("status", UNSET)-- _created_at = d.pop("created_at", UNSET)- created_at: datetime.datetime | Unset- if isinstance(_created_at, Unset):- created_at = UNSET- else:- created_at = datetime.datetime.fromisoformat(_created_at)-- batch_submit_response = cls(- batch_id=batch_id,- name=name,- status=status,- created_at=created_at,- )-- batch_submit_response.additional_properties = d- return batch_submit_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/batch_summary.py b/libs/fleet/python-sdk/cua_train/models/batch_summary.pydeleted file mode 100644index a4113f6db9..0000000000--- a/libs/fleet/python-sdk/cua_train/models/batch_summary.py+++ /dev/null@@ -1,133 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--if TYPE_CHECKING:- from ..models.timing_stats import TimingStats---T = TypeVar("T", bound="BatchSummary")---@_attrs_define-class BatchSummary:- """- Attributes:- n_ok (int | Unset):- n_fail (int | Unset):- total_wall_ms (int | Unset):- reset_stats (TimingStats | Unset):- step_stats (TimingStats | Unset):- shutdown_stats (TimingStats | Unset):- """-- n_ok: int | Unset = UNSET- n_fail: int | Unset = UNSET- total_wall_ms: int | Unset = UNSET- reset_stats: TimingStats | Unset = UNSET- step_stats: TimingStats | Unset = UNSET- shutdown_stats: TimingStats | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- n_ok = self.n_ok-- n_fail = self.n_fail-- total_wall_ms = self.total_wall_ms-- reset_stats: dict[str, Any] | Unset = UNSET- if not isinstance(self.reset_stats, Unset):- reset_stats = self.reset_stats.to_dict()-- step_stats: dict[str, Any] | Unset = UNSET- if not isinstance(self.step_stats, Unset):- step_stats = self.step_stats.to_dict()-- shutdown_stats: dict[str, Any] | Unset = UNSET- if not isinstance(self.shutdown_stats, Unset):- shutdown_stats = self.shutdown_stats.to_dict()-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if n_ok is not UNSET:- field_dict["n_ok"] = n_ok- if n_fail is not UNSET:- field_dict["n_fail"] = n_fail- if total_wall_ms is not UNSET:- field_dict["total_wall_ms"] = total_wall_ms- if reset_stats is not UNSET:- field_dict["reset_stats"] = reset_stats- if step_stats is not UNSET:- field_dict["step_stats"] = step_stats- if shutdown_stats is not UNSET:- field_dict["shutdown_stats"] = shutdown_stats-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- from ..models.timing_stats import TimingStats-- d = dict(src_dict)- n_ok = d.pop("n_ok", UNSET)-- n_fail = d.pop("n_fail", UNSET)-- total_wall_ms = d.pop("total_wall_ms", UNSET)-- _reset_stats = d.pop("reset_stats", UNSET)- reset_stats: TimingStats | Unset- if isinstance(_reset_stats, Unset):- reset_stats = UNSET- else:- reset_stats = TimingStats.from_dict(_reset_stats)-- _step_stats = d.pop("step_stats", UNSET)- step_stats: TimingStats | Unset- if isinstance(_step_stats, Unset):- step_stats = UNSET- else:- step_stats = TimingStats.from_dict(_step_stats)-- _shutdown_stats = d.pop("shutdown_stats", UNSET)- shutdown_stats: TimingStats | Unset- if isinstance(_shutdown_stats, Unset):- shutdown_stats = UNSET- else:- shutdown_stats = TimingStats.from_dict(_shutdown_stats)-- batch_summary = cls(- n_ok=n_ok,- n_fail=n_fail,- total_wall_ms=total_wall_ms,- reset_stats=reset_stats,- step_stats=step_stats,- shutdown_stats=shutdown_stats,- )-- batch_summary.additional_properties = d- return batch_summary-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/cancel_batch_response.py b/libs/fleet/python-sdk/cua_train/models/cancel_batch_response.pydeleted file mode 100644index ace0ea24ae..0000000000--- a/libs/fleet/python-sdk/cua_train/models/cancel_batch_response.py+++ /dev/null@@ -1,70 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="CancelBatchResponse")---@_attrs_define-class CancelBatchResponse:- """- Attributes:- batch_id (str | Unset):- status (str | Unset):- """-- batch_id: str | Unset = UNSET- status: str | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- batch_id = self.batch_id-- status = self.status-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if batch_id is not UNSET:- field_dict["batch_id"] = batch_id- if status is not UNSET:- field_dict["status"] = status-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- batch_id = d.pop("batch_id", UNSET)-- status = d.pop("status", UNSET)-- cancel_batch_response = cls(- batch_id=batch_id,- status=status,- )-- cancel_batch_response.additional_properties = d- return cancel_batch_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/cancel_label_batch_item.py b/libs/fleet/python-sdk/cua_train/models/cancel_label_batch_item.pydeleted file mode 100644index 0040b5eeb4..0000000000--- a/libs/fleet/python-sdk/cua_train/models/cancel_label_batch_item.py+++ /dev/null@@ -1,70 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="CancelLabelBatchItem")---@_attrs_define-class CancelLabelBatchItem:- """- Attributes:- batch_id (str | Unset):- status (str | Unset):- """-- batch_id: str | Unset = UNSET- status: str | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- batch_id = self.batch_id-- status = self.status-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if batch_id is not UNSET:- field_dict["batch_id"] = batch_id- if status is not UNSET:- field_dict["status"] = status-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- batch_id = d.pop("batch_id", UNSET)-- status = d.pop("status", UNSET)-- cancel_label_batch_item = cls(- batch_id=batch_id,- status=status,- )-- cancel_label_batch_item.additional_properties = d- return cancel_label_batch_item-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/cancel_label_response.py b/libs/fleet/python-sdk/cua_train/models/cancel_label_response.pydeleted file mode 100644index a135405c7c..0000000000--- a/libs/fleet/python-sdk/cua_train/models/cancel_label_response.py+++ /dev/null@@ -1,115 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--if TYPE_CHECKING:- from ..models.cancel_label_batch_item import CancelLabelBatchItem---T = TypeVar("T", bound="CancelLabelResponse")---@_attrs_define-class CancelLabelResponse:- """- Attributes:- label (str | Unset):- batch_count (int | Unset):- cancelled_count (int | Unset):- already_done (int | Unset):- batches (list[CancelLabelBatchItem] | Unset):- """-- label: str | Unset = UNSET- batch_count: int | Unset = UNSET- cancelled_count: int | Unset = UNSET- already_done: int | Unset = UNSET- batches: list[CancelLabelBatchItem] | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- label = self.label-- batch_count = self.batch_count-- cancelled_count = self.cancelled_count-- already_done = self.already_done-- batches: list[dict[str, Any]] | Unset = UNSET- if not isinstance(self.batches, Unset):- batches = []- for batches_item_data in self.batches:- batches_item = batches_item_data.to_dict()- batches.append(batches_item)-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if label is not UNSET:- field_dict["label"] = label- if batch_count is not UNSET:- field_dict["batch_count"] = batch_count- if cancelled_count is not UNSET:- field_dict["cancelled_count"] = cancelled_count- if already_done is not UNSET:- field_dict["already_done"] = already_done- if batches is not UNSET:- field_dict["batches"] = batches-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- from ..models.cancel_label_batch_item import CancelLabelBatchItem-- d = dict(src_dict)- label = d.pop("label", UNSET)-- batch_count = d.pop("batch_count", UNSET)-- cancelled_count = d.pop("cancelled_count", UNSET)-- already_done = d.pop("already_done", UNSET)-- _batches = d.pop("batches", UNSET)- batches: list[CancelLabelBatchItem] | Unset = UNSET- if _batches is not UNSET:- batches = []- for batches_item_data in _batches:- batches_item = CancelLabelBatchItem.from_dict(batches_item_data)-- batches.append(batches_item)-- cancel_label_response = cls(- label=label,- batch_count=batch_count,- cancelled_count=cancelled_count,- already_done=already_done,- batches=batches,- )-- cancel_label_response.additional_properties = d- return cancel_label_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/create_key_request.py b/libs/fleet/python-sdk/cua_train/models/create_key_request.pydeleted file mode 100644index 5a8a891095..0000000000--- a/libs/fleet/python-sdk/cua_train/models/create_key_request.py+++ /dev/null@@ -1,69 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--T = TypeVar("T", bound="CreateKeyRequest")---@_attrs_define-class CreateKeyRequest:- """- Attributes:- name (str): Example: ci-prod.- namespace (str): Example: test-pool.- """-- name: str- namespace: str- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- name = self.name-- namespace = self.namespace-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "name": name,- "namespace": namespace,- }- )-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- name = d.pop("name")-- namespace = d.pop("namespace")-- create_key_request = cls(- name=name,- namespace=namespace,- )-- create_key_request.additional_properties = d- return create_key_request-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/create_key_response.py b/libs/fleet/python-sdk/cua_train/models/create_key_response.pydeleted file mode 100644index 78b3a35ca9..0000000000--- a/libs/fleet/python-sdk/cua_train/models/create_key_response.py+++ /dev/null@@ -1,97 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="CreateKeyResponse")---@_attrs_define-class CreateKeyResponse:- """- Attributes:- client_id (str | Unset):- client_secret (str | Unset):- name (str | Unset):- namespace (str | Unset):- token_url (str | Unset):- """-- client_id: str | Unset = UNSET- client_secret: str | Unset = UNSET- name: str | Unset = UNSET- namespace: str | Unset = UNSET- token_url: str | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- client_id = self.client_id-- client_secret = self.client_secret-- name = self.name-- namespace = self.namespace-- token_url = self.token_url-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if client_id is not UNSET:- field_dict["client_id"] = client_id- if client_secret is not UNSET:- field_dict["client_secret"] = client_secret- if name is not UNSET:- field_dict["name"] = name- if namespace is not UNSET:- field_dict["namespace"] = namespace- if token_url is not UNSET:- field_dict["token_url"] = token_url-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- client_id = d.pop("client_id", UNSET)-- client_secret = d.pop("client_secret", UNSET)-- name = d.pop("name", UNSET)-- namespace = d.pop("namespace", UNSET)-- token_url = d.pop("token_url", UNSET)-- create_key_response = cls(- client_id=client_id,- client_secret=client_secret,- name=name,- namespace=namespace,- token_url=token_url,- )-- create_key_response.additional_properties = d- return create_key_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/error_response.py b/libs/fleet/python-sdk/cua_train/models/error_response.pydeleted file mode 100644index 3cd602cb1e..0000000000--- a/libs/fleet/python-sdk/cua_train/models/error_response.py+++ /dev/null@@ -1,61 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="ErrorResponse")---@_attrs_define-class ErrorResponse:- """- Attributes:- error (str | Unset):- """-- error: str | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- error = self.error-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if error is not UNSET:- field_dict["error"] = error-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- error = d.pop("error", UNSET)-- error_response = cls(- error=error,- )-- error_response.additional_properties = d- return error_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/health_response.py b/libs/fleet/python-sdk/cua_train/models/health_response.pydeleted file mode 100644index 8172423767..0000000000--- a/libs/fleet/python-sdk/cua_train/models/health_response.py+++ /dev/null@@ -1,61 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="HealthResponse")---@_attrs_define-class HealthResponse:- """- Attributes:- ok (bool | Unset):- """-- ok: bool | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- ok = self.ok-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if ok is not UNSET:- field_dict["ok"] = ok-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- ok = d.pop("ok", UNSET)-- health_response = cls(- ok=ok,- )-- health_response.additional_properties = d- return health_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/healthz_response.py b/libs/fleet/python-sdk/cua_train/models/healthz_response.pydeleted file mode 100644index b0d829863d..0000000000--- a/libs/fleet/python-sdk/cua_train/models/healthz_response.py+++ /dev/null@@ -1,61 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--T = TypeVar("T", bound="HealthzResponse")---@_attrs_define-class HealthzResponse:- """- Attributes:- status (str):- """-- status: str- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- status = self.status-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "status": status,- }- )-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- status = d.pop("status")-- healthz_response = cls(- status=status,- )-- healthz_response.additional_properties = d- return healthz_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/key_client.py b/libs/fleet/python-sdk/cua_train/models/key_client.pydeleted file mode 100644index 54bb017434..0000000000--- a/libs/fleet/python-sdk/cua_train/models/key_client.py+++ /dev/null@@ -1,97 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="KeyClient")---@_attrs_define-class KeyClient:- """- Attributes:- id (str | Unset):- client_id (str | Unset):- name (str | Unset):- namespace (str | Unset):- owner_sub (str | Unset):- """-- id: str | Unset = UNSET- client_id: str | Unset = UNSET- name: str | Unset = UNSET- namespace: str | Unset = UNSET- owner_sub: str | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- id = self.id-- client_id = self.client_id-- name = self.name-- namespace = self.namespace-- owner_sub = self.owner_sub-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if id is not UNSET:- field_dict["id"] = id- if client_id is not UNSET:- field_dict["client_id"] = client_id- if name is not UNSET:- field_dict["name"] = name- if namespace is not UNSET:- field_dict["namespace"] = namespace- if owner_sub is not UNSET:- field_dict["owner_sub"] = owner_sub-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- id = d.pop("id", UNSET)-- client_id = d.pop("client_id", UNSET)-- name = d.pop("name", UNSET)-- namespace = d.pop("namespace", UNSET)-- owner_sub = d.pop("owner_sub", UNSET)-- key_client = cls(- id=id,- client_id=client_id,- name=name,- namespace=namespace,- owner_sub=owner_sub,- )-- key_client.additional_properties = d- return key_client-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/label_batch_summary.py b/libs/fleet/python-sdk/cua_train/models/label_batch_summary.pydeleted file mode 100644index 91f67ac805..0000000000--- a/libs/fleet/python-sdk/cua_train/models/label_batch_summary.py+++ /dev/null@@ -1,143 +0,0 @@-from __future__ import annotations--import datetime-from collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--if TYPE_CHECKING:- from ..models.batch_progress import BatchProgress---T = TypeVar("T", bound="LabelBatchSummary")---@_attrs_define-class LabelBatchSummary:- """- Attributes:- batch_id (str | Unset):- status (str | Unset):- progress (BatchProgress | Unset):- created_at (datetime.datetime | Unset):- updated_at (datetime.datetime | Unset):- s3_key (str | Unset):- s3_presigned_url (str | Unset):- """-- batch_id: str | Unset = UNSET- status: str | Unset = UNSET- progress: BatchProgress | Unset = UNSET- created_at: datetime.datetime | Unset = UNSET- updated_at: datetime.datetime | Unset = UNSET- s3_key: str | Unset = UNSET- s3_presigned_url: str | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- batch_id = self.batch_id-- status = self.status-- progress: dict[str, Any] | Unset = UNSET- if not isinstance(self.progress, Unset):- progress = self.progress.to_dict()-- created_at: str | Unset = UNSET- if not isinstance(self.created_at, Unset):- created_at = self.created_at.isoformat()-- updated_at: str | Unset = UNSET- if not isinstance(self.updated_at, Unset):- updated_at = self.updated_at.isoformat()-- s3_key = self.s3_key-- s3_presigned_url = self.s3_presigned_url-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if batch_id is not UNSET:- field_dict["batch_id"] = batch_id- if status is not UNSET:- field_dict["status"] = status- if progress is not UNSET:- field_dict["progress"] = progress- if created_at is not UNSET:- field_dict["created_at"] = created_at- if updated_at is not UNSET:- field_dict["updated_at"] = updated_at- if s3_key is not UNSET:- field_dict["s3_key"] = s3_key- if s3_presigned_url is not UNSET:- field_dict["s3_presigned_url"] = s3_presigned_url-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- from ..models.batch_progress import BatchProgress-- d = dict(src_dict)- batch_id = d.pop("batch_id", UNSET)-- status = d.pop("status", UNSET)-- _progress = d.pop("progress", UNSET)- progress: BatchProgress | Unset- if isinstance(_progress, Unset):- progress = UNSET- else:- progress = BatchProgress.from_dict(_progress)-- _created_at = d.pop("created_at", UNSET)- created_at: datetime.datetime | Unset- if isinstance(_created_at, Unset):- created_at = UNSET- else:- created_at = datetime.datetime.fromisoformat(_created_at)-- _updated_at = d.pop("updated_at", UNSET)- updated_at: datetime.datetime | Unset- if isinstance(_updated_at, Unset):- updated_at = UNSET- else:- updated_at = datetime.datetime.fromisoformat(_updated_at)-- s3_key = d.pop("s3_key", UNSET)-- s3_presigned_url = d.pop("s3_presigned_url", UNSET)-- label_batch_summary = cls(- batch_id=batch_id,- status=status,- progress=progress,- created_at=created_at,- updated_at=updated_at,- s3_key=s3_key,- s3_presigned_url=s3_presigned_url,- )-- label_batch_summary.additional_properties = d- return label_batch_summary-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/label_in_progress_response.py b/libs/fleet/python-sdk/cua_train/models/label_in_progress_response.pydeleted file mode 100644index aeaf99e06a..0000000000--- a/libs/fleet/python-sdk/cua_train/models/label_in_progress_response.py+++ /dev/null@@ -1,88 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="LabelInProgressResponse")---@_attrs_define-class LabelInProgressResponse:- """- Attributes:- label (str | Unset):- batch_count (int | Unset):- all_completed (bool | Unset):- message (str | Unset):- """-- label: str | Unset = UNSET- batch_count: int | Unset = UNSET- all_completed: bool | Unset = UNSET- message: str | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- label = self.label-- batch_count = self.batch_count-- all_completed = self.all_completed-- message = self.message-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if label is not UNSET:- field_dict["label"] = label- if batch_count is not UNSET:- field_dict["batch_count"] = batch_count- if all_completed is not UNSET:- field_dict["all_completed"] = all_completed- if message is not UNSET:- field_dict["message"] = message-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- label = d.pop("label", UNSET)-- batch_count = d.pop("batch_count", UNSET)-- all_completed = d.pop("all_completed", UNSET)-- message = d.pop("message", UNSET)-- label_in_progress_response = cls(- label=label,- batch_count=batch_count,- all_completed=all_completed,- message=message,- )-- label_in_progress_response.additional_properties = d- return label_in_progress_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/label_results_response.py b/libs/fleet/python-sdk/cua_train/models/label_results_response.pydeleted file mode 100644index 0ddc78efba..0000000000--- a/libs/fleet/python-sdk/cua_train/models/label_results_response.py+++ /dev/null@@ -1,133 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--if TYPE_CHECKING:- from ..models.batch_results_response import BatchResultsResponse- from ..models.batch_summary import BatchSummary---T = TypeVar("T", bound="LabelResultsResponse")---@_attrs_define-class LabelResultsResponse:- """- Attributes:- label (str | Unset):- batch_count (int | Unset):- completed_batch_count (int | Unset):- all_completed (bool | Unset):- batches (list[BatchResultsResponse] | Unset):- summary (BatchSummary | Unset):- """-- label: str | Unset = UNSET- batch_count: int | Unset = UNSET- completed_batch_count: int | Unset = UNSET- all_completed: bool | Unset = UNSET- batches: list[BatchResultsResponse] | Unset = UNSET- summary: BatchSummary | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- label = self.label-- batch_count = self.batch_count-- completed_batch_count = self.completed_batch_count-- all_completed = self.all_completed-- batches: list[dict[str, Any]] | Unset = UNSET- if not isinstance(self.batches, Unset):- batches = []- for batches_item_data in self.batches:- batches_item = batches_item_data.to_dict()- batches.append(batches_item)-- summary: dict[str, Any] | Unset = UNSET- if not isinstance(self.summary, Unset):- summary = self.summary.to_dict()-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if label is not UNSET:- field_dict["label"] = label- if batch_count is not UNSET:- field_dict["batch_count"] = batch_count- if completed_batch_count is not UNSET:- field_dict["completed_batch_count"] = completed_batch_count- if all_completed is not UNSET:- field_dict["all_completed"] = all_completed- if batches is not UNSET:- field_dict["batches"] = batches- if summary is not UNSET:- field_dict["summary"] = summary-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- from ..models.batch_results_response import BatchResultsResponse- from ..models.batch_summary import BatchSummary-- d = dict(src_dict)- label = d.pop("label", UNSET)-- batch_count = d.pop("batch_count", UNSET)-- completed_batch_count = d.pop("completed_batch_count", UNSET)-- all_completed = d.pop("all_completed", UNSET)-- _batches = d.pop("batches", UNSET)- batches: list[BatchResultsResponse] | Unset = UNSET- if _batches is not UNSET:- batches = []- for batches_item_data in _batches:- batches_item = BatchResultsResponse.from_dict(batches_item_data)-- batches.append(batches_item)-- _summary = d.pop("summary", UNSET)- summary: BatchSummary | Unset- if isinstance(_summary, Unset):- summary = UNSET- else:- summary = BatchSummary.from_dict(_summary)-- label_results_response = cls(- label=label,- batch_count=batch_count,- completed_batch_count=completed_batch_count,- all_completed=all_completed,- batches=batches,- summary=summary,- )-- label_results_response.additional_properties = d- return label_results_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/label_status_response.py b/libs/fleet/python-sdk/cua_train/models/label_status_response.pydeleted file mode 100644index 92148a1df7..0000000000--- a/libs/fleet/python-sdk/cua_train/models/label_status_response.py+++ /dev/null@@ -1,124 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--if TYPE_CHECKING:- from ..models.batch_progress import BatchProgress- from ..models.label_batch_summary import LabelBatchSummary---T = TypeVar("T", bound="LabelStatusResponse")---@_attrs_define-class LabelStatusResponse:- """- Attributes:- label (str | Unset):- batch_count (int | Unset):- all_completed (bool | Unset):- progress (BatchProgress | Unset):- batches (list[LabelBatchSummary] | Unset):- """-- label: str | Unset = UNSET- batch_count: int | Unset = UNSET- all_completed: bool | Unset = UNSET- progress: BatchProgress | Unset = UNSET- batches: list[LabelBatchSummary] | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- label = self.label-- batch_count = self.batch_count-- all_completed = self.all_completed-- progress: dict[str, Any] | Unset = UNSET- if not isinstance(self.progress, Unset):- progress = self.progress.to_dict()-- batches: list[dict[str, Any]] | Unset = UNSET- if not isinstance(self.batches, Unset):- batches = []- for batches_item_data in self.batches:- batches_item = batches_item_data.to_dict()- batches.append(batches_item)-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if label is not UNSET:- field_dict["label"] = label- if batch_count is not UNSET:- field_dict["batch_count"] = batch_count- if all_completed is not UNSET:- field_dict["all_completed"] = all_completed- if progress is not UNSET:- field_dict["progress"] = progress- if batches is not UNSET:- field_dict["batches"] = batches-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- from ..models.batch_progress import BatchProgress- from ..models.label_batch_summary import LabelBatchSummary-- d = dict(src_dict)- label = d.pop("label", UNSET)-- batch_count = d.pop("batch_count", UNSET)-- all_completed = d.pop("all_completed", UNSET)-- _progress = d.pop("progress", UNSET)- progress: BatchProgress | Unset- if isinstance(_progress, Unset):- progress = UNSET- else:- progress = BatchProgress.from_dict(_progress)-- _batches = d.pop("batches", UNSET)- batches: list[LabelBatchSummary] | Unset = UNSET- if _batches is not UNSET:- batches = []- for batches_item_data in _batches:- batches_item = LabelBatchSummary.from_dict(batches_item_data)-- batches.append(batches_item)-- label_status_response = cls(- label=label,- batch_count=batch_count,- all_completed=all_completed,- progress=progress,- batches=batches,- )-- label_status_response.additional_properties = d- return label_status_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/lane_create_request.py b/libs/fleet/python-sdk/cua_train/models/lane_create_request.pydeleted file mode 100644index cfc634808e..0000000000--- a/libs/fleet/python-sdk/cua_train/models/lane_create_request.py+++ /dev/null@@ -1,67 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="LaneCreateRequest")---@_attrs_define-class LaneCreateRequest:- """Body of POST /lanes.-- ``ttl_seconds`` is the absolute time the claim is reserved for;- after that the reaper deletes it. With ``autoRenew=true`` the lane- auto-renew timer in pool-operator pushes this forward, so the- customer's effective TTL is "as long as the lane exists".-- Attributes:- ttl_seconds (int | Unset): Default: 300.- """-- ttl_seconds: int | Unset = 300- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- ttl_seconds = self.ttl_seconds-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if ttl_seconds is not UNSET:- field_dict["ttl_seconds"] = ttl_seconds-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- ttl_seconds = d.pop("ttl_seconds", UNSET)-- lane_create_request = cls(- ttl_seconds=ttl_seconds,- )-- lane_create_request.additional_properties = d- return lane_create_request-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/lane_delete_response.py b/libs/fleet/python-sdk/cua_train/models/lane_delete_response.pydeleted file mode 100644index cc9af25268..0000000000--- a/libs/fleet/python-sdk/cua_train/models/lane_delete_response.py+++ /dev/null@@ -1,61 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--T = TypeVar("T", bound="LaneDeleteResponse")---@_attrs_define-class LaneDeleteResponse:- """- Attributes:- lane_id (str):- """-- lane_id: str- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- lane_id = self.lane_id-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "lane_id": lane_id,- }- )-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- lane_id = d.pop("lane_id")-- lane_delete_response = cls(- lane_id=lane_id,- )-- lane_delete_response.additional_properties = d- return lane_delete_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/lane_response.py b/libs/fleet/python-sdk/cua_train/models/lane_response.pydeleted file mode 100644index 3d1b680806..0000000000--- a/libs/fleet/python-sdk/cua_train/models/lane_response.py+++ /dev/null@@ -1,91 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar, cast--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="LaneResponse")---@_attrs_define-class LaneResponse:- """- Attributes:- lane_id (str):- vm_id (str):- screenshot (None | str | Unset):- """-- lane_id: str- vm_id: str- screenshot: None | str | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- lane_id = self.lane_id-- vm_id = self.vm_id-- screenshot: None | str | Unset- if isinstance(self.screenshot, Unset):- screenshot = UNSET- else:- screenshot = self.screenshot-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "lane_id": lane_id,- "vm_id": vm_id,- }- )- if screenshot is not UNSET:- field_dict["screenshot"] = screenshot-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- lane_id = d.pop("lane_id")-- vm_id = d.pop("vm_id")-- def _parse_screenshot(data: object) -> None | str | Unset:- if data is None:- return data- if isinstance(data, Unset):- return data- return cast(None | str | Unset, data)-- screenshot = _parse_screenshot(d.pop("screenshot", UNSET))-- lane_response = cls(- lane_id=lane_id,- vm_id=vm_id,- screenshot=screenshot,- )-- lane_response.additional_properties = d- return lane_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/lane_swap_response.py b/libs/fleet/python-sdk/cua_train/models/lane_swap_response.pydeleted file mode 100644index 46272c5edf..0000000000--- a/libs/fleet/python-sdk/cua_train/models/lane_swap_response.py+++ /dev/null@@ -1,77 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--T = TypeVar("T", bound="LaneSwapResponse")---@_attrs_define-class LaneSwapResponse:- """- Attributes:- lane_id (str):- vm_id (str):- wait_seconds (float):- """-- lane_id: str- vm_id: str- wait_seconds: float- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- lane_id = self.lane_id-- vm_id = self.vm_id-- wait_seconds = self.wait_seconds-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "lane_id": lane_id,- "vm_id": vm_id,- "wait_seconds": wait_seconds,- }- )-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- lane_id = d.pop("lane_id")-- vm_id = d.pop("vm_id")-- wait_seconds = d.pop("wait_seconds")-- lane_swap_response = cls(- lane_id=lane_id,- vm_id=vm_id,- wait_seconds=wait_seconds,- )-- lane_swap_response.additional_properties = d- return lane_swap_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/list_keys_response.py b/libs/fleet/python-sdk/cua_train/models/list_keys_response.pydeleted file mode 100644index 97a45082fa..0000000000--- a/libs/fleet/python-sdk/cua_train/models/list_keys_response.py+++ /dev/null@@ -1,79 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--if TYPE_CHECKING:- from ..models.key_client import KeyClient---T = TypeVar("T", bound="ListKeysResponse")---@_attrs_define-class ListKeysResponse:- """- Attributes:- keys (list[KeyClient] | Unset):- """-- keys: list[KeyClient] | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- keys: list[dict[str, Any]] | Unset = UNSET- if not isinstance(self.keys, Unset):- keys = []- for keys_item_data in self.keys:- keys_item = keys_item_data.to_dict()- keys.append(keys_item)-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if keys is not UNSET:- field_dict["keys"] = keys-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- from ..models.key_client import KeyClient-- d = dict(src_dict)- _keys = d.pop("keys", UNSET)- keys: list[KeyClient] | Unset = UNSET- if _keys is not UNSET:- keys = []- for keys_item_data in _keys:- keys_item = KeyClient.from_dict(keys_item_data)-- keys.append(keys_item)-- list_keys_response = cls(- keys=keys,- )-- list_keys_response.additional_properties = d- return list_keys_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/pool_list_response.py b/libs/fleet/python-sdk/cua_train/models/pool_list_response.pydeleted file mode 100644index cbfb8db4c5..0000000000--- a/libs/fleet/python-sdk/cua_train/models/pool_list_response.py+++ /dev/null@@ -1,83 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--if TYPE_CHECKING:- from ..models.pool_list_response_vms_item import PoolListResponseVmsItem---T = TypeVar("T", bound="PoolListResponse")---@_attrs_define-class PoolListResponse:- """- Attributes:- vms (list[PoolListResponseVmsItem]):- count (int):- """-- vms: list[PoolListResponseVmsItem]- count: int- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- vms = []- for vms_item_data in self.vms:- vms_item = vms_item_data.to_dict()- vms.append(vms_item)-- count = self.count-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "vms": vms,- "count": count,- }- )-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- from ..models.pool_list_response_vms_item import PoolListResponseVmsItem-- d = dict(src_dict)- vms = []- _vms = d.pop("vms")- for vms_item_data in _vms:- vms_item = PoolListResponseVmsItem.from_dict(vms_item_data)-- vms.append(vms_item)-- count = d.pop("count")-- pool_list_response = cls(- vms=vms,- count=count,- )-- pool_list_response.additional_properties = d- return pool_list_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/pool_list_response_vms_item.py b/libs/fleet/python-sdk/cua_train/models/pool_list_response_vms_item.pydeleted file mode 100644index 79d2871fc2..0000000000--- a/libs/fleet/python-sdk/cua_train/models/pool_list_response_vms_item.py+++ /dev/null@@ -1,47 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--T = TypeVar("T", bound="PoolListResponseVmsItem")---@_attrs_define-class PoolListResponseVmsItem:- """ """-- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- pool_list_response_vms_item = cls()-- pool_list_response_vms_item.additional_properties = d- return pool_list_response_vms_item-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/release_lanes_request.py b/libs/fleet/python-sdk/cua_train/models/release_lanes_request.pydeleted file mode 100644index 69ae98df1c..0000000000--- a/libs/fleet/python-sdk/cua_train/models/release_lanes_request.py+++ /dev/null@@ -1,61 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar, cast--from attrs import define as _attrs_define-from attrs import field as _attrs_field--T = TypeVar("T", bound="ReleaseLanesRequest")---@_attrs_define-class ReleaseLanesRequest:- """- Attributes:- vm_ids (list[str]): VM ids to shut down (lanes to release).- """-- vm_ids: list[str]- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- vm_ids = self.vm_ids-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "vm_ids": vm_ids,- }- )-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- vm_ids = cast(list[str], d.pop("vm_ids"))-- release_lanes_request = cls(- vm_ids=vm_ids,- )-- release_lanes_request.additional_properties = d- return release_lanes_request-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/release_lanes_response.py b/libs/fleet/python-sdk/cua_train/models/release_lanes_response.pydeleted file mode 100644index 494ea6cc48..0000000000--- a/libs/fleet/python-sdk/cua_train/models/release_lanes_response.py+++ /dev/null@@ -1,61 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="ReleaseLanesResponse")---@_attrs_define-class ReleaseLanesResponse:- """- Attributes:- released (int | Unset): Number of vm_ids submitted for release.- """-- released: int | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- released = self.released-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if released is not UNSET:- field_dict["released"] = released-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- released = d.pop("released", UNSET)-- release_lanes_response = cls(- released=released,- )-- release_lanes_response.additional_properties = d- return release_lanes_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/reset_request.py b/libs/fleet/python-sdk/cua_train/models/reset_request.pydeleted file mode 100644index 1d69fc2fd1..0000000000--- a/libs/fleet/python-sdk/cua_train/models/reset_request.py+++ /dev/null@@ -1,75 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--if TYPE_CHECKING:- from ..models.reset_request_task_config import ResetRequestTaskConfig---T = TypeVar("T", bound="ResetRequest")---@_attrs_define-class ResetRequest:- """- Attributes:- task_config (ResetRequestTaskConfig):- timeout (int):- """-- task_config: ResetRequestTaskConfig- timeout: int- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- task_config = self.task_config.to_dict()-- timeout = self.timeout-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "task_config": task_config,- "timeout": timeout,- }- )-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- from ..models.reset_request_task_config import ResetRequestTaskConfig-- d = dict(src_dict)- task_config = ResetRequestTaskConfig.from_dict(d.pop("task_config"))-- timeout = d.pop("timeout")-- reset_request = cls(- task_config=task_config,- timeout=timeout,- )-- reset_request.additional_properties = d- return reset_request-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/reset_request_task_config.py b/libs/fleet/python-sdk/cua_train/models/reset_request_task_config.pydeleted file mode 100644index e8cc4a55c7..0000000000--- a/libs/fleet/python-sdk/cua_train/models/reset_request_task_config.py+++ /dev/null@@ -1,47 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--T = TypeVar("T", bound="ResetRequestTaskConfig")---@_attrs_define-class ResetRequestTaskConfig:- """ """-- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- reset_request_task_config = cls()-- reset_request_task_config.additional_properties = d- return reset_request_task_config-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/reset_response.py b/libs/fleet/python-sdk/cua_train/models/reset_response.pydeleted file mode 100644index de7d5d14b3..0000000000--- a/libs/fleet/python-sdk/cua_train/models/reset_response.py+++ /dev/null@@ -1,77 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--T = TypeVar("T", bound="ResetResponse")---@_attrs_define-class ResetResponse:- """- Attributes:- screenshot (str):- problem (str):- vm_id (str):- """-- screenshot: str- problem: str- vm_id: str- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- screenshot = self.screenshot-- problem = self.problem-- vm_id = self.vm_id-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "screenshot": screenshot,- "problem": problem,- "vm_id": vm_id,- }- )-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- screenshot = d.pop("screenshot")-- problem = d.pop("problem")-- vm_id = d.pop("vm_id")-- reset_response = cls(- screenshot=screenshot,- problem=problem,- vm_id=vm_id,- )-- reset_response.additional_properties = d- return reset_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/run_config.py b/libs/fleet/python-sdk/cua_train/models/run_config.pydeleted file mode 100644index 16cd10739c..0000000000--- a/libs/fleet/python-sdk/cua_train/models/run_config.py+++ /dev/null@@ -1,99 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--if TYPE_CHECKING:- from ..models.action import Action---T = TypeVar("T", bound="RunConfig")---@_attrs_define-class RunConfig:- """- Attributes:- steps (list[Action]): Ordered actions to execute on the rollout VM. A step with `action_type: "RESET"` is a- reserved control action: instead of being forwarded to the VM, it hard-resets the VM in place (new vm_id, clean- baseline desktop), so one run can execute several independent episodes on a warm instance.- timeout (int | Unset): Per-rollout timeout in seconds (max 24h).- vm_id (str | Unset): Reattach this run to an existing warm VM (instance reuse / "lane"), typically a vm_id- returned by a previous `keep_warm` batch, instead of acquiring a fresh one. If that claim has already expired,- the run transparently falls back to a fresh VM.- """-- steps: list[Action]- timeout: int | Unset = UNSET- vm_id: str | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- steps = []- for steps_item_data in self.steps:- steps_item = steps_item_data.to_dict()- steps.append(steps_item)-- timeout = self.timeout-- vm_id = self.vm_id-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "steps": steps,- }- )- if timeout is not UNSET:- field_dict["timeout"] = timeout- if vm_id is not UNSET:- field_dict["vm_id"] = vm_id-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- from ..models.action import Action-- d = dict(src_dict)- steps = []- _steps = d.pop("steps")- for steps_item_data in _steps:- steps_item = Action.from_dict(steps_item_data)-- steps.append(steps_item)-- timeout = d.pop("timeout", UNSET)-- vm_id = d.pop("vm_id", UNSET)-- run_config = cls(- steps=steps,- timeout=timeout,- vm_id=vm_id,- )-- run_config.additional_properties = d- return run_config-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/run_result.py b/libs/fleet/python-sdk/cua_train/models/run_result.pydeleted file mode 100644index ee264934a5..0000000000--- a/libs/fleet/python-sdk/cua_train/models/run_result.py+++ /dev/null@@ -1,139 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar, cast--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="RunResult")---@_attrs_define-class RunResult:- """- Attributes:- run_id (int | Unset):- vm_id (str | Unset):- ok (bool | Unset):- error (str | Unset):- reset_ms (int | Unset):- step_ms (list[int] | Unset):- shutdown_ms (int | Unset):- actions (list[str] | Unset):- screenshots (list[str] | Unset):- """-- run_id: int | Unset = UNSET- vm_id: str | Unset = UNSET- ok: bool | Unset = UNSET- error: str | Unset = UNSET- reset_ms: int | Unset = UNSET- step_ms: list[int] | Unset = UNSET- shutdown_ms: int | Unset = UNSET- actions: list[str] | Unset = UNSET- screenshots: list[str] | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- run_id = self.run_id-- vm_id = self.vm_id-- ok = self.ok-- error = self.error-- reset_ms = self.reset_ms-- step_ms: list[int] | Unset = UNSET- if not isinstance(self.step_ms, Unset):- step_ms = self.step_ms-- shutdown_ms = self.shutdown_ms-- actions: list[str] | Unset = UNSET- if not isinstance(self.actions, Unset):- actions = self.actions-- screenshots: list[str] | Unset = UNSET- if not isinstance(self.screenshots, Unset):- screenshots = self.screenshots-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if run_id is not UNSET:- field_dict["run_id"] = run_id- if vm_id is not UNSET:- field_dict["vm_id"] = vm_id- if ok is not UNSET:- field_dict["ok"] = ok- if error is not UNSET:- field_dict["error"] = error- if reset_ms is not UNSET:- field_dict["reset_ms"] = reset_ms- if step_ms is not UNSET:- field_dict["step_ms"] = step_ms- if shutdown_ms is not UNSET:- field_dict["shutdown_ms"] = shutdown_ms- if actions is not UNSET:- field_dict["actions"] = actions- if screenshots is not UNSET:- field_dict["screenshots"] = screenshots-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- run_id = d.pop("run_id", UNSET)-- vm_id = d.pop("vm_id", UNSET)-- ok = d.pop("ok", UNSET)-- error = d.pop("error", UNSET)-- reset_ms = d.pop("reset_ms", UNSET)-- step_ms = cast(list[int], d.pop("step_ms", UNSET))-- shutdown_ms = d.pop("shutdown_ms", UNSET)-- actions = cast(list[str], d.pop("actions", UNSET))-- screenshots = cast(list[str], d.pop("screenshots", UNSET))-- run_result = cls(- run_id=run_id,- vm_id=vm_id,- ok=ok,- error=error,- reset_ms=reset_ms,- step_ms=step_ms,- shutdown_ms=shutdown_ms,- actions=actions,- screenshots=screenshots,- )-- run_result.additional_properties = d- return run_result-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/screenshot_response.py b/libs/fleet/python-sdk/cua_train/models/screenshot_response.pydeleted file mode 100644index ac733c46b3..0000000000--- a/libs/fleet/python-sdk/cua_train/models/screenshot_response.py+++ /dev/null@@ -1,69 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--T = TypeVar("T", bound="ScreenshotResponse")---@_attrs_define-class ScreenshotResponse:- """- Attributes:- screenshot (str):- vm_id (str):- """-- screenshot: str- vm_id: str- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- screenshot = self.screenshot-- vm_id = self.vm_id-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "screenshot": screenshot,- "vm_id": vm_id,- }- )-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- screenshot = d.pop("screenshot")-- vm_id = d.pop("vm_id")-- screenshot_response = cls(- screenshot=screenshot,- vm_id=vm_id,- )-- screenshot_response.additional_properties = d- return screenshot_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/shutdown_request.py b/libs/fleet/python-sdk/cua_train/models/shutdown_request.pydeleted file mode 100644index 41efd71c6b..0000000000--- a/libs/fleet/python-sdk/cua_train/models/shutdown_request.py+++ /dev/null@@ -1,61 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--T = TypeVar("T", bound="ShutdownRequest")---@_attrs_define-class ShutdownRequest:- """- Attributes:- vm_id (str):- """-- vm_id: str- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- vm_id = self.vm_id-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "vm_id": vm_id,- }- )-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- vm_id = d.pop("vm_id")-- shutdown_request = cls(- vm_id=vm_id,- )-- shutdown_request.additional_properties = d- return shutdown_request-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/shutdown_response.py b/libs/fleet/python-sdk/cua_train/models/shutdown_response.pydeleted file mode 100644index ba86618657..0000000000--- a/libs/fleet/python-sdk/cua_train/models/shutdown_response.py+++ /dev/null@@ -1,61 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--T = TypeVar("T", bound="ShutdownResponse")---@_attrs_define-class ShutdownResponse:- """- Attributes:- vm_id (str):- """-- vm_id: str- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- vm_id = self.vm_id-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "vm_id": vm_id,- }- )-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- vm_id = d.pop("vm_id")-- shutdown_response = cls(- vm_id=vm_id,- )-- shutdown_response.additional_properties = d- return shutdown_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/step_request.py b/libs/fleet/python-sdk/cua_train/models/step_request.pydeleted file mode 100644index ac578484c7..0000000000--- a/libs/fleet/python-sdk/cua_train/models/step_request.py+++ /dev/null@@ -1,80 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="StepRequest")---@_attrs_define-class StepRequest:- """- Attributes:- action (str):- vm_id (str):- timeout (int | Unset): Default: 300.- """-- action: str- vm_id: str- timeout: int | Unset = 300- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- action = self.action-- vm_id = self.vm_id-- timeout = self.timeout-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "action": action,- "vm_id": vm_id,- }- )- if timeout is not UNSET:- field_dict["timeout"] = timeout-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- action = d.pop("action")-- vm_id = d.pop("vm_id")-- timeout = d.pop("timeout", UNSET)-- step_request = cls(- action=action,- vm_id=vm_id,- timeout=timeout,- )-- step_request.additional_properties = d- return step_request-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/step_response.py b/libs/fleet/python-sdk/cua_train/models/step_response.pydeleted file mode 100644index e9a2e89dd5..0000000000--- a/libs/fleet/python-sdk/cua_train/models/step_response.py+++ /dev/null@@ -1,84 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar, cast--from attrs import define as _attrs_define-from attrs import field as _attrs_field--T = TypeVar("T", bound="StepResponse")---@_attrs_define-class StepResponse:- """- Attributes:- screenshot (None | str):- is_finish (bool):- reward (float):- """-- screenshot: None | str- is_finish: bool- reward: float- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- screenshot: None | str- screenshot = self.screenshot-- is_finish = self.is_finish-- reward = self.reward-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update(- {- "screenshot": screenshot,- "is_finish": is_finish,- "reward": reward,- }- )-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)-- def _parse_screenshot(data: object) -> None | str:- if data is None:- return data- return cast(None | str, data)-- screenshot = _parse_screenshot(d.pop("screenshot"))-- is_finish = d.pop("is_finish")-- reward = d.pop("reward")-- step_response = cls(- screenshot=screenshot,- is_finish=is_finish,- reward=reward,- )-- step_response.additional_properties = d- return step_response-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/models/timing_stats.py b/libs/fleet/python-sdk/cua_train/models/timing_stats.pydeleted file mode 100644index 6bd6ebedf6..0000000000--- a/libs/fleet/python-sdk/cua_train/models/timing_stats.py+++ /dev/null@@ -1,88 +0,0 @@-from __future__ import annotations--from collections.abc import Mapping-from typing import Any, TypeVar--from attrs import define as _attrs_define-from attrs import field as _attrs_field--from ..types import UNSET, Unset--T = TypeVar("T", bound="TimingStats")---@_attrs_define-class TimingStats:- """- Attributes:- n (int | Unset):- min_ (int | Unset):- mean (float | Unset):- max_ (int | Unset):- """-- n: int | Unset = UNSET- min_: int | Unset = UNSET- mean: float | Unset = UNSET- max_: int | Unset = UNSET- additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)-- def to_dict(self) -> dict[str, Any]:- n = self.n-- min_ = self.min_-- mean = self.mean-- max_ = self.max_-- field_dict: dict[str, Any] = {}- field_dict.update(self.additional_properties)- field_dict.update({})- if n is not UNSET:- field_dict["n"] = n- if min_ is not UNSET:- field_dict["min"] = min_- if mean is not UNSET:- field_dict["mean"] = mean- if max_ is not UNSET:- field_dict["max"] = max_-- return field_dict-- @classmethod- def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- n = d.pop("n", UNSET)-- min_ = d.pop("min", UNSET)-- mean = d.pop("mean", UNSET)-- max_ = d.pop("max", UNSET)-- timing_stats = cls(- n=n,- min_=min_,- mean=mean,- max_=max_,- )-- timing_stats.additional_properties = d- return timing_stats-- @property- def additional_keys(self) -> list[str]:- return list(self.additional_properties.keys())-- def __getitem__(self, key: str) -> Any:- return self.additional_properties[key]-- def __setitem__(self, key: str, value: Any) -> None:- self.additional_properties[key] = value-- def __delitem__(self, key: str) -> None:- del self.additional_properties[key]-- def __contains__(self, key: str) -> bool:- return key in self.additional_propertiesdiff --git a/libs/fleet/python-sdk/cua_train/py.typed b/libs/fleet/python-sdk/cua_train/py.typeddeleted file mode 100644index 1aad32711f..0000000000--- a/libs/fleet/python-sdk/cua_train/py.typed+++ /dev/null@@ -1 +0,0 @@-# Marker file for PEP 561\ No newline at end of filediff --git a/libs/fleet/python-sdk/cua_train/types.py b/libs/fleet/python-sdk/cua_train/types.pydeleted file mode 100644index b64af09529..0000000000--- a/libs/fleet/python-sdk/cua_train/types.py+++ /dev/null@@ -1,54 +0,0 @@-"""Contains some shared types for properties"""--from collections.abc import Mapping, MutableMapping-from http import HTTPStatus-from typing import IO, BinaryIO, Generic, Literal, TypeVar--from attrs import define---class Unset:- def __bool__(self) -> Literal[False]:- return False---UNSET: Unset = Unset()--# The types that `httpx.Client(files=)` can accept, copied from that library.-FileContent = IO[bytes] | bytes | str-FileTypes = (- # (filename, file (or bytes), content_type)- tuple[str | None, FileContent, str | None]- # (filename, file (or bytes), content_type, headers)- | tuple[str | None, FileContent, str | None, Mapping[str, str]]-)-RequestFiles = list[tuple[str, FileTypes]]---@define-class File:- """Contains information for file uploads"""-- payload: BinaryIO- file_name: str | None = None- mime_type: str | None = None-- def to_tuple(self) -> FileTypes:- """Return a tuple representation that httpx will accept for multipart/form-data"""- return self.file_name, self.payload, self.mime_type---T = TypeVar("T")---@define-class Response(Generic[T]):- """A response from an endpoint"""-- status_code: HTTPStatus- content: bytes- headers: MutableMapping[str, str]- parsed: T | None---__all__ = ["UNSET", "File", "FileTypes", "RequestFiles", "Response", "Unset"]diff --git a/libs/fleet/python-sdk/examples/claim_and_connect.py b/libs/fleet/python-sdk/examples/claim_and_connect.pydeleted file mode 100644index fde6771a9c..0000000000--- a/libs/fleet/python-sdk/examples/claim_and_connect.py+++ /dev/null@@ -1,236 +0,0 @@-#!/usr/bin/env python3-"""Claim a sandbox from a pool, wait for it to bind, then call one of its-service endpoints — all through the cyclops-cs backend with a client id/secret.--What it illustrates:- * ``TrainClient.from_key`` for the client_credentials exchange + transparent- token refresh, reused as a plain authenticated httpx client for endpoints- that are NOT in the generated SDK surface- * creating an ``OSGymSandboxClaim`` CR via the ``/api/k8s`` kubectl-proxy- (the same path the SPA uses — the pool-operator binds it to a warm sandbox)- * reaching the claimed sandbox through ``/api/svc/{namespace}/{service}/``--Auth — use a per-USER key (``ukey-...``), not a per-pool key:-``/api/k8s`` impersonates the token's owner so Capsule tenant RBAC applies.-Per-user keys (POST /api/user-keys) act on behalf of their owner and can-create claims; per-pool keys (POST /api/keys, ``key-...``) have no K8s-identity and are rejected on the claim step.--Setup::-- pip install cua-train --extra-index-url https://wheels.cua.ai/simple/- export CUA_CLIENT_ID=ukey-xxxxxxxx # from POST /api/user-keys- export CUA_CLIENT_SECRET=...- python claim_and_connect.py --pool my-pool # first pool service- python claim_and_connect.py --pool my-pool --service vnc --path /healthz- python claim_and_connect.py --pool win --service cua-driver --mcp--``--mcp`` runs the cua-driver MCP handshake (initialize → session id →-tools/list) instead of a plain GET — proof the desktop is drivable, not-just that something answers HTTP.--The claim is released (DELETE) on exit unless ``--keep`` is passed.--A sandbox released by an earlier claim is hard-reset in place and rejoins-the pool, but its guest OS reboots — the in-guest service answers 502-("upstream unavailable") for a few minutes after the claim binds. The-script polls the service until it responds (``--ready-timeout``).--Env knobs: CUA_CLIENT_ID, CUA_CLIENT_SECRET, CUA_TOKEN_URL, CUA_BASE_URL.-"""--from __future__ import annotations--import argparse-import json-import os-import sys-import time-import uuid--import httpx--from cua_train import TrainClient--# Native CRD coordinates (osgym.cua.ai group). The pool-operator watches-# OSGymSandboxClaims and binds each to a warm sandbox from the pool; the pool's-# VM shape (image, size, services) lives on its OSGymSandboxTemplate.-GROUP = "osgym.cua.ai"-VERSION = "v1alpha1"-CLAIM_PLURAL = "osgymsandboxclaims"-TEMPLATE_PLURAL = "osgymsandboxtemplates"--DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"-DEFAULT_BASE_URL = "https://run.cua.ai"---def claims_url(pool: str, name: str | None = None) -> str:- base = f"/api/k8s/apis/{GROUP}/{VERSION}/namespaces/{pool}/{CLAIM_PLURAL}"- return f"{base}/{name}" if name else base---def template_url(pool: str, name: str) -> str:- return f"/api/k8s/apis/{GROUP}/{VERSION}/namespaces/{pool}/{TEMPLATE_PLURAL}/{name}"---def first_template_service(http: httpx.Client, pool: str) -> str:- """Name of the first service the pool's template declares- (spec.vmTemplate.services[0].name on <pool>-template)."""- tmpl = f"{pool}-template"- r = http.get(template_url(pool, tmpl))- r.raise_for_status()- vm_template = r.json().get("spec", {}).get("vmTemplate") or {}- services = vm_template.get("services") or []- if not services:- sys.exit(- f"template {tmpl!r} declares no services — pass --service or add one "- f"to spec.vmTemplate.services"- )- return services[0]["name"]---def create_claim(http: httpx.Client, pool: str, name: str) -> None:- r = http.post(- claims_url(pool),- json={- "apiVersion": f"{GROUP}/{VERSION}",- "kind": "OSGymSandboxClaim",- "metadata": {"name": name},- # Pool name = namespace name (1:1), and each pool ships a template- # named "<pool>-template" — same convention the SPA uses.- "spec": {"sandboxTemplateRef": {"name": f"{pool}-template"}},- },- )- if r.status_code == 403:- sys.exit(- "403 creating claim — is this a per-pool key? Claims need a per-USER "- "key (client id starting with 'ukey-', from POST /api/user-keys)."- )- r.raise_for_status()---def wait_bound(http: httpx.Client, pool: str, name: str, timeout: float) -> str:- """Poll the claim until status.phase == Bound; return the sandbox name."""- deadline = time.monotonic() + timeout- while True:- r = http.get(claims_url(pool, name))- r.raise_for_status()- status = r.json().get("status") or {}- phase = status.get("phase", "Pending")- sandbox = (status.get("sandbox") or {}).get("name")- if phase == "Bound" and sandbox:- return sandbox- if phase == "Failed":- sys.exit(f"claim {name} failed: {status}")- if time.monotonic() > deadline:- sys.exit(f"timed out after {timeout:.0f}s waiting for claim {name} (phase={phase})")- print(f" claim {name}: {phase} …")- time.sleep(2)---def wait_service_ready(http, url: str, timeout: float) -> httpx.Response:- """GET url until the in-guest service answers with something other than- a proxy 502/503/504 (the guest OS is still booting after a reset)."""- deadline = time.monotonic() + timeout- while True:- resp = http().get(url)- if resp.status_code not in (502, 503, 504):- return resp- if time.monotonic() > deadline:- sys.exit(f"timed out after {timeout:.0f}s waiting for the service (last: HTTP {resp.status_code})")- print(f" HTTP {resp.status_code} — guest still booting …")- time.sleep(15)---def mcp_handshake(http, base: str) -> None:- """initialize → notifications/initialized → tools/list against the- cua-driver Streamable HTTP MCP endpoint at {base}/mcp."""- url = f"{base}/mcp"- headers = {- "Content-Type": "application/json",- "Accept": "application/json, text/event-stream",- }- r = http().post(url, headers=headers, json={- "jsonrpc": "2.0", "id": 1, "method": "initialize",- "params": {- "protocolVersion": "2025-03-26",- "capabilities": {},- "clientInfo": {"name": "claim_and_connect", "version": "0.1.0"},- },- })- r.raise_for_status()- session = r.headers.get("mcp-session-id")- print(f"MCP initialize: HTTP {r.status_code}, session {session}")- if session:- headers["Mcp-Session-Id"] = session- http().post(url, headers=headers, json={"jsonrpc": "2.0", "method": "notifications/initialized"})- r = http().post(url, headers=headers, json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"})- r.raise_for_status()- # Streamable HTTP returns SSE ("event: message\ndata: {...}"); the JSON- # payload is on the data: line.- data = next((ln[6:] for ln in r.text.splitlines() if ln.startswith("data: ")), r.text)- tools = [t.get("name") for t in json.loads(data).get("result", {}).get("tools", [])]- print(f"MCP tools ({len(tools)}): {', '.join(sorted(tools)[:12])}{', …' if len(tools) > 12 else ''}")---def main() -> None:- p = argparse.ArgumentParser(description=__doc__.splitlines()[0])- p.add_argument("--pool", required=True, help="pool name (= namespace)")- p.add_argument("--service", help="service name (default: first service in the pool's template)")- p.add_argument("--path", default="/", help="path to request on the service (default: /)")- p.add_argument("--claim-name", help="claim name (default: claim-<random>)")- p.add_argument("--timeout", type=float, default=300, help="seconds to wait for Bound (default: 300)")- p.add_argument("--ready-timeout", type=float, default=420,- help="seconds to wait for the in-guest service after binding (default: 420)")- p.add_argument("--mcp", action="store_true",- help="run the cua-driver MCP handshake (initialize + tools/list) instead of GET --path")- p.add_argument("--keep", action="store_true", help="keep the claim instead of releasing it on exit")- args = p.parse_args()-- client_id = os.environ.get("CUA_CLIENT_ID")- client_secret = os.environ.get("CUA_CLIENT_SECRET")- if not client_id or not client_secret:- sys.exit("set CUA_CLIENT_ID and CUA_CLIENT_SECRET (per-user key, POST /api/user-keys)")-- client = TrainClient.from_key(- token_url=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL),- client_id=client_id,- client_secret=client_secret,- base_url=os.environ.get("CUA_BASE_URL", DEFAULT_BASE_URL),- )-- # get_httpx_client() re-mints the bearer token when it is close to expiry,- # so fetch it per request rather than holding one reference.- http = client.get_httpx_client- claim_name = args.claim_name or f"claim-{uuid.uuid4().hex[:8]}"-- service = args.service or first_template_service(http(), args.pool)-- print(f"creating claim {claim_name} on pool {args.pool} (template {args.pool}-template)")- create_claim(http(), args.pool, claim_name)-- try:- sandbox = wait_bound(http(), args.pool, claim_name, args.timeout)- # Per-sandbox K8s Services are named "<sandbox>-<service>" and exposed- # on port 80 by the operator; /api/svc proxies to them in-cluster.- svc_base = f"/api/svc/{args.pool}/{sandbox}-{service}"- url = f"{svc_base}/{args.path.lstrip('/')}"- print(f"bound to sandbox {sandbox}; GET {url}")-- resp = wait_service_ready(http, url, args.ready_timeout)- print(f"HTTP {resp.status_code} {resp.headers.get('content-type', '')}")- body = resp.text- print(body[:2000] + ("…" if len(body) > 2000 else ""))-- if args.mcp:- mcp_handshake(http, svc_base)- finally:- if args.keep:- print(f"keeping claim {claim_name} (release with: DELETE {claims_url(args.pool, claim_name)})")- else:- r = http().delete(claims_url(args.pool, claim_name))- print(f"released claim {claim_name} (HTTP {r.status_code})")---if __name__ == "__main__":- main()diff --git a/libs/fleet/python-sdk/examples/create_pool_and_list_tools.py b/libs/fleet/python-sdk/examples/create_pool_and_list_tools.pydeleted file mode 100644index 614eed63b7..0000000000--- a/libs/fleet/python-sdk/examples/create_pool_and_list_tools.py+++ /dev/null@@ -1,589 +0,0 @@-#!/usr/bin/env -S uv run --script-# /// script-# requires-python = ">=3.10"-# dependencies = [-# "cua-train",-# "httpx",-# ]-#-# [tool.uv]-# extra-index-url = ["https://wheels.cua.ai/simple/"]-# ///-"""Create a warm sandbox pool on cyclops-cs / run.cua.ai, claim a sandbox from-it, and list the cua-driver MCP tools it exposes — end to end, from nothing but-a client id/secret.--This is the "create it too" companion to ``claim_and_connect.py`` (which only-claims from a pool that already exists). Here we drive the whole lifecycle and-narrate every step so you can follow along in the console:-- 1. exchange the client_credentials for a bearer token (``TrainClient.from_key``)- 2. create the per-user namespace (``POST /api/namespaces`` — same path the SPA- uses, so Capsule sets up tenant ownership + RBAC; pool name == namespace)- 3. create the two native CRs (``osgym.cua.ai/v1alpha1``) via the ``/api/k8s``- kubectl-proxy: an ``OSGymSandboxTemplate`` (``<pool>-template``) holding the- VM shape — image, size, and a service on the chosen port — and an- ``OSGymSandboxWarmPool`` (``<pool>``) that references it and warms- ``replicas`` VMs.- 4. claim a sandbox (``OSGymSandboxClaim``) and wait for it to bind- 5. reach the bound sandbox through ``/api/svc/{ns}/{sandbox}-{service}/`` and- run the cua-driver MCP handshake (initialize -> tools/list)--Auth — use a per-USER key (``ukey-...``), NOT a per-pool key:-``/api/k8s`` impersonates the token's owner so Capsule tenant RBAC applies.-Per-user keys (POST /api/user-keys) act on behalf of their owner and can create-namespaces, pools, and claims; per-pool keys (POST /api/keys, ``key-...``) have-no K8s identity and are rejected on those steps.--The default image is the Linux ``desktop-workspace`` — it serves the cua-driver-computer-use MCP server over Streamable HTTP on :3000/mcp (with /healthz),-and nothing else (no :5000 Flask server). So we set the pool's readiness probe-to the MCP port: a warm sandbox is only advertised as "available" (and a claim-only binds) once MCP is actually answering, which is exactly what we want-before listing tools.--Setup (zero-install with uv)::-- export CUA_CLIENT_ID=ukey-xxxxxxxx # from POST /api/user-keys- export CUA_CLIENT_SECRET=...- uv run create_pool_and_list_tools.py --name my-pool--…or pass credentials as flags, and/or pin everything explicitly::-- uv run create_pool_and_list_tools.py \- --name my-pool \- --client-id ukey-xxxxxxxx --client-secret ... \- --image 296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace:latest \- --port 3000--If your uv is too old to read the inline extra-index-url, run it the explicit-way (same as the other examples)::-- uv run --with cua-train --with httpx \- --extra-index-url https://wheels.cua.ai/simple/ \- create_pool_and_list_tools.py --name my-pool--The claim is released on exit (so the warm VM returns to the pool); the pool is-kept — it is the thing you asked to create. Pass ``--keep-claim`` to hold the-claim, or ``--delete-pool`` to tear the whole thing (warm pool + template +-namespace) down.--Env knobs: CUA_CLIENT_ID, CUA_CLIENT_SECRET, CUA_TOKEN_URL, CUA_BASE_URL.-"""--from __future__ import annotations--import argparse-import json-import os-import sys-import time-import uuid-from collections.abc import Callable--import httpx--from cua_train import TrainClient--DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"-DEFAULT_BASE_URL = "https://run.cua.ai"-# NOTE: ':latest' is NOT reliably published for the Linux workspace repos — the-# build workflow only tags 'latest' on pushes to main, and ECR lifecycle rules-# expire old tags. A pool pointed at a missing tag never warms (the VM sits in-# ImagePullBackOff). Pass --image with a tag you've confirmed exists, e.g.:-# aws ecr describe-images --repository-name desktop-workspace --region us-west-2-# (verified working at the time of writing: a desktop-workspace gym-seed tag-# 'amazon-feature-gym-uv-seed-openshot-<sha>-base' — Linux, cua-driver MCP on :3000.)-DEFAULT_IMAGE = "296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace:latest"--# A pool is two native CRs in the osgym.cua.ai group: an OSGymSandboxTemplate-# (the VM shape, named "<pool>-template") and an OSGymSandboxWarmPool (named-# "<pool>") that references it and keeps spec.replicas VMs warm. Claims-# (OSGymSandboxClaim) reference the template by name.-EXT_GROUP = "osgym.cua.ai"-EXT_VERSION = "v1alpha1"-TEMPLATE_PLURAL = "osgymsandboxtemplates"-WARMPOOL_PLURAL = "osgymsandboxwarmpools"-CLAIM_PLURAL = "osgymsandboxclaims"---# ── URL builders (relative to base_url, e.g. https://run.cua.ai) ──────────---def template_url(pool: str, name: str | None = None) -> str:- base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{TEMPLATE_PLURAL}"- return f"{base}/{name}" if name else base---def warmpool_url(pool: str, name: str | None = None) -> str:- base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{WARMPOOL_PLURAL}"- return f"{base}/{name}" if name else base---def claims_url(pool: str, name: str | None = None) -> str:- base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{CLAIM_PLURAL}"- return f"{base}/{name}" if name else base---# ── Console helpers ───────────────────────────────────────────────────────---def step(msg: str) -> None:- print(f"\n==> {msg}", flush=True)---def info(msg: str) -> None:- print(f" {msg}", flush=True)---def die(msg: str) -> None:- sys.exit(f"\nERROR: {msg}")---# ── Lifecycle steps ───────────────────────────────────────────────────────---def create_namespace(http: httpx.Client, name: str) -> None:- """Create the per-user namespace via the Capsule-backed SPA endpoint.-- Pool name == namespace name (1:1). Going through /api/namespaces (rather- than a raw /api/k8s namespace create) is what makes Capsule stamp tenant- ownership + RBAC, so the impersonated pool create below is allowed. A 409- just means we are reusing a namespace from an earlier run.- """- r = http.post("/api/namespaces", json={"name": name})- if r.status_code == 409:- info(f"namespace {name!r} already exists — reusing it")- return- if r.status_code == 403:- die(- "403 creating namespace — is this a per-pool key? Namespaces/pools/"- "claims need a per-USER key (client id starting with 'ukey-', from "- "POST /api/user-keys)."- )- r.raise_for_status()- info(f"namespace {name!r} created")---def create_template(- http: httpx.Client,- *,- pool: str,- image: str,- cpu: int,- ram: str,- firmware: str,- service_name: str,- port: int,- readiness_port: int,-) -> None:- """Create the OSGymSandboxTemplate — the VM shape every sandbox in the pool- is stamped from, and what claims reference by name (``<pool>-template``)."""- vm_template: dict = {- "containerDiskImage": image,- "imagePullSecret": "ecr-credentials",- "cpuCores": cpu,- "memory": ram,- # Each entry becomes a per-sandbox K8s Service "<sandbox>-<name>"- # mapping port 80 -> targetPort on the VM.- "services": [- {"name": service_name, "targetPort": port, "protocol": "TCP"}- ],- }- # The SPA only sends firmware when it differs from KubeVirt's bios default.- if firmware != "bios":- vm_template["firmware"] = firmware- # Gate "Ready" (and therefore claim binding) on the in-guest service being- # bound — for desktop-workspace that's the MCP port. Without a probe the VM- # is advertised ready ~30s before the guest finishes booting (CUA-535).- # readiness_port == 0 disables the probe (KubeVirt's launcher-up default).- if readiness_port:- vm_template["probes"] = {"readinessProbe": {"tcpSocket": {"port": readiness_port}}}-- tmpl = f"{pool}-template"- body = {- "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",- "kind": "OSGymSandboxTemplate",- "metadata": {"namespace": pool, "name": tmpl, "labels": {"cua.ai/pool": pool}},- "spec": {"vmTemplate": vm_template},- }-- r = http.post(template_url(pool), json=body)- if r.status_code == 409:- info(f"template {tmpl!r} already exists — reusing it (VM shape unchanged)")- return- if r.status_code == 403:- die(- "403 creating template — per-pool keys cannot reach /api/k8s. Use a "- "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."- )- r.raise_for_status()- info(f"template {tmpl!r} created")- info(f"image: {image}")- info(f"size: {cpu} vCPU / {ram} / firmware={firmware}")- info(f"service: {service_name} -> targetPort {port} (reachable on Service port 80)")- info(f"readiness: {'tcpSocket :' + str(readiness_port) if readiness_port else 'launcher-up (no probe)'}")---def create_warm_pool(http: httpx.Client, *, pool: str, replicas: int) -> None:- """Create the OSGymSandboxWarmPool that keeps ``replicas`` sandboxes warm- from ``<pool>-template``."""- body = {- "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",- "kind": "OSGymSandboxWarmPool",- "metadata": {"namespace": pool, "name": pool, "labels": {"cua.ai/pool": pool}},- "spec": {- "replicas": replicas,- "sandboxTemplateRef": {"name": f"{pool}-template"},- },- }-- r = http.post(warmpool_url(pool), json=body)- if r.status_code == 409:- info(f"warm pool {pool!r} already exists — reusing it (replicas unchanged)")- return- if r.status_code == 403:- die(- "403 creating warm pool — per-pool keys cannot reach /api/k8s. Use a "- "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."- )- r.raise_for_status()- info(f"warm pool {pool!r} created (replicas={replicas} from {pool}-template)")---def pool_counts(get_http: Callable[[], httpx.Client], pool: str) -> tuple[int, int]:- """(replicas, readyReplicas) from the warm pool status, best-effort."""- try:- r = get_http().get(warmpool_url(pool, pool))- r.raise_for_status()- st = r.json().get("status") or {}- return int(st.get("replicas", 0)), int(st.get("readyReplicas", 0))- except Exception:- return (0, 0)---def wait_pool_warm(get_http: Callable[[], httpx.Client], pool: str, timeout: float, poll: float) -> None:- """Wait until the warm pool reports a ready VM.-- This is the key to a reliable first claim: a brand-new pool has to pull the- (multi-GB) containerDisk image, boot the guest, and bring the in-guest- service up on the readiness port before a Sandbox becomes adoptable. That- cold start routinely exceeds the operator's 300s *claim* bind deadline- (claim_handlers.BIND_DEADLINE_DEFAULT_S). If we claim first, the deadline- burns down during the image pull and the claim Fails with- ``BindDeadlineExceeded`` — exactly the failure mode this avoids.-- So we let the warm pool reach status.readyReplicas>=1 *before* claiming; the- subsequent claim then binds in seconds. Re-fetches the ``http`` accessor- each poll to keep the bearer token fresh over a long pull.- """- start = time.monotonic()- deadline = start + timeout- while True:- total, ready = pool_counts(get_http, pool)- if ready >= 1:- info(f"pool warm: {ready}/{total} VM(s) ready")- return- if time.monotonic() > deadline:- die(f"timed out after {timeout:.0f}s waiting for a warm VM "- f"({ready}/{total} ready).\n"- f" Most common cause: the --image tag does not exist in the registry, "- f"so the VM sits in ImagePullBackOff and never boots. Note that "- f"'desktop-workspace:latest' / 'osgym-workspace:latest' are typically "- f"NOT published — list real tags with:\n"- f" aws ecr describe-images --repository-name desktop-workspace --region us-west-2\n"- f" Less commonly the cold pull just needs longer — raise --warm-timeout.")- elapsed = int(time.monotonic() - start)- info(f"[{elapsed:4d}s] pool: {ready}/{total} VMs ready — warming "- f"(image pull + guest boot + service on the readiness port) …")- time.sleep(poll)---def create_claim(http: httpx.Client, pool: str, name: str, bind_deadline: int = 0) -> None:- spec: dict = {"sandboxTemplateRef": {"name": f"{pool}-template"}}- # The pool-operator fails an unbound claim after spec.bindDeadline seconds- # (default 300, claim_handlers.BIND_DEADLINE_DEFAULT_S). We claim only after- # the pool is already warm, so binding is near-instant — but a non-zero- # deadline is a safety margin in case the warm VM is mid hard-reset.- if bind_deadline:- spec["bindDeadline"] = bind_deadline- r = http.post(- claims_url(pool),- json={- "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",- "kind": "OSGymSandboxClaim",- "metadata": {"name": name},- # Same convention the SPA uses: the pool's template is <pool>-template.- "spec": spec,- },- )- if r.status_code == 403:- die(- "403 creating claim — per-pool keys have no K8s identity. Use a "- "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."- )- r.raise_for_status()- info(f"claim {name!r} created")---def wait_bound(get_http: Callable[[], httpx.Client], pool: str, name: str, timeout: float, poll: float) -> str:- """Poll the claim until status.phase == Bound; return the sandbox name.-- While we wait we also surface the warm pool's ready counts, so a cold start- (image pull + guest boot + MCP coming up on the readiness port) is visible- rather than a silent hang. Re-fetches the ``http`` accessor each poll so the- bearer token stays fresh across a long (cold-boot) wait.- """- start = time.monotonic()- deadline = start + timeout- while True:- r = get_http().get(claims_url(pool, name))- r.raise_for_status()- status = r.json().get("status") or {}- phase = status.get("phase", "Pending")- sandbox = (status.get("sandbox") or {}).get("name")- if phase == "Bound" and sandbox:- return sandbox- if phase == "Failed":- die(f"claim {name} failed: {status}")- if time.monotonic() > deadline:- die(f"timed out after {timeout:.0f}s waiting for claim {name} to bind (phase={phase})")- total, ready = pool_counts(get_http, pool)- elapsed = int(time.monotonic() - start)- info(f"[{elapsed:4d}s] claim={phase} pool={ready}/{total} VMs ready …")- time.sleep(poll)---def wait_service_ready(get_http: Callable[[], httpx.Client], url: str, timeout: float, poll: float) -> None:- """GET url until the in-guest service answers (not a proxy 502/503/504).-- Backstop for the slim window where the sandbox is Bound but the in-guest- HTTP server hasn't finished accepting connections yet. Re-fetches the- ``http`` accessor each poll to keep the bearer token fresh.- """- start = time.monotonic()- deadline = start + timeout- while True:- try:- resp = get_http().get(url, timeout=15.0)- except httpx.HTTPError as e:- resp = None- reason = type(e).__name__- else:- reason = f"HTTP {resp.status_code}"- if resp is not None and resp.status_code not in (502, 503, 504):- info(f"service responding ({reason})")- return- if time.monotonic() > deadline:- die(f"timed out after {timeout:.0f}s waiting for the in-guest service (last: {reason})")- elapsed = int(time.monotonic() - start)- info(f"[{elapsed:4d}s] {reason} — guest still booting …")- time.sleep(poll)---def list_mcp_tools(http: httpx.Client, base: str, mcp_path: str) -> None:- """cua-driver MCP handshake over Streamable HTTP:- initialize -> notifications/initialized -> tools/list, then print the tools."""- url = f"{base}/{mcp_path.lstrip('/')}"- headers = {- "Content-Type": "application/json",- # Streamable HTTP requires advertising both content types.- "Accept": "application/json, text/event-stream",- }-- r = http.post(- url,- headers=headers,- timeout=30.0,- json={- "jsonrpc": "2.0",- "id": 1,- "method": "initialize",- "params": {- "protocolVersion": "2025-03-26",- "capabilities": {},- "clientInfo": {"name": "create_pool_and_list_tools", "version": "0.1.0"},- },- },- )- r.raise_for_status()- session = r.headers.get("mcp-session-id")- info(f"MCP initialize: HTTP {r.status_code}" + (f", session {session}" if session else ""))- if session:- headers["Mcp-Session-Id"] = session-- # Notify the server we're ready (no response expected).- http.post(- url,- headers=headers,- timeout=30.0,- json={"jsonrpc": "2.0", "method": "notifications/initialized"},- )-- r = http.post(- url,- headers=headers,- timeout=30.0,- json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"},- )- r.raise_for_status()- # Streamable HTTP returns SSE ("event: message\ndata: {...}"); the JSON- # payload is on the data: line. Fall back to the raw body for plain JSON.- data = next((ln[6:] for ln in r.text.splitlines() if ln.startswith("data: ")), r.text)- tools = json.loads(data).get("result", {}).get("tools", [])-- print(f"\nMCP tools ({len(tools)}):", flush=True)- for i, t in enumerate(sorted(tools, key=lambda t: t.get("name", "")), 1):- name = t.get("name", "?")- desc = " ".join((t.get("description") or "").split())- if len(desc) > 70:- desc = desc[:67] + "…"- print(f" {i:3d}. {name:<24} {desc}", flush=True)- if not tools:- print(" (the server returned an empty tool list)", flush=True)---def delete_pool(http: httpx.Client, pool: str) -> None:- """Delete both pool CRs (warm pool first, so it stops respawning sandboxes- from a template that is on its way out), then the namespace."""- r = http.delete(warmpool_url(pool, pool))- info(f"deleted warm pool {pool!r} (HTTP {r.status_code})")- r = http.delete(template_url(pool, f"{pool}-template"))- info(f"deleted template {pool}-template (HTTP {r.status_code})")- r = http.delete(f"/api/namespaces/{pool}")- info(f"deleted namespace {pool!r} (HTTP {r.status_code})")---# ── Main ──────────────────────────────────────────────────────────────────---def main() -> None:- p = argparse.ArgumentParser(- description="Create a pool on run.cua.ai, claim a sandbox, and list its MCP tools.",- formatter_class=argparse.ArgumentDefaultsHelpFormatter,- )- p.add_argument("--name", required=True, help="pool name (also the namespace; lowercase/dashes)")- p.add_argument("--client-id", default=os.environ.get("CUA_CLIENT_ID"),- help="OAuth client id (per-user key 'ukey-…'); env CUA_CLIENT_ID")- p.add_argument("--client-secret", default=os.environ.get("CUA_CLIENT_SECRET"),- help="OAuth client secret; env CUA_CLIENT_SECRET")- p.add_argument("--image", default=DEFAULT_IMAGE, help="workspace containerDisk image")- p.add_argument("--port", type=int, default=3000, help="service target port on the VM (MCP)")- p.add_argument("--service-name", default="mcp", help="name for the per-sandbox Service")- p.add_argument("--mcp-path", default="/mcp", help="path the MCP server is mounted at")- p.add_argument("--replicas", type=int, default=1, help="pre-warmed VMs the pool keeps")- p.add_argument("--cpu", type=int, default=4, help="vCPU cores per VM")- p.add_argument("--ram", default="4Gi", help="memory per VM (K8s quantity)")- p.add_argument("--firmware", choices=["bios", "efi"], default="bios",- help="VM firmware (efi for GPT/UEFI-only images, e.g. Windows)")- p.add_argument("--readiness-port", type=int, default=None,- help="TCP readiness port (default: --port; 0 disables the probe)")- p.add_argument("--token-url", default=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL),- help="OIDC token endpoint")- p.add_argument("--base-url", default=os.environ.get("CUA_BASE_URL", DEFAULT_BASE_URL),- help="cyclops-cs base URL")- p.add_argument("--claim-name", help="claim name (default: claim-<random>)")- p.add_argument("--warm-timeout", type=float, default=900,- help="seconds to wait for the pool's first warm VM before claiming "- "(covers the cold image pull + guest boot)")- p.add_argument("--bind-deadline", type=int, default=600,- help="claim spec.bindDeadline (operator fails an unbound claim after "- "this; 0 uses the operator default of 300s)")- p.add_argument("--bind-timeout", type=float, default=300,- help="seconds the script waits for the claim to bind (fast once warm)")- p.add_argument("--ready-timeout", type=float, default=420,- help="seconds to wait for the in-guest service after binding")- p.add_argument("--poll-interval", type=float, default=5,- help="seconds between status polls")- p.add_argument("--keep-claim", action="store_true",- help="keep the claim (and its VM) instead of releasing it on exit")- p.add_argument("--delete-pool", action="store_true",- help="tear down the warm pool, template AND namespace on exit (full cleanup)")- args = p.parse_args()-- if not args.client_id or not args.client_secret:- die("set --client-id/--client-secret or CUA_CLIENT_ID/CUA_CLIENT_SECRET "- "(per-user key from POST /api/user-keys)")- if args.client_id.startswith("key-"):- die("that looks like a per-POOL key ('key-…'), which has no K8s identity. "- "Creating namespaces/pools/claims needs a per-USER key ('ukey-…', "- "from POST /api/user-keys).")-- readiness_port = args.port if args.readiness_port is None else args.readiness_port- pool = args.name- claim_name = args.claim_name or f"claim-{uuid.uuid4().hex[:8]}"-- step(f"Authenticating to {args.base_url} (client {args.client_id})")- client = TrainClient.from_key(- token_url=args.token_url,- client_id=args.client_id,- client_secret=args.client_secret,- base_url=args.base_url,- )- # get_httpx_client() re-mints the bearer token near expiry, so fetch it- # per request rather than holding one reference.- http = client.get_httpx_client- info("token acquired")-- step(f"Creating namespace {pool!r}")- create_namespace(http(), pool)-- step(f"Creating sandbox template {pool}-template")- create_template(- http(),- pool=pool,- image=args.image,- cpu=args.cpu,- ram=args.ram,- firmware=args.firmware,- service_name=args.service_name,- port=args.port,- readiness_port=readiness_port,- )-- step(f"Creating warm pool {pool!r}")- create_warm_pool(http(), pool=pool, replicas=args.replicas)-- step("Waiting for the pool's first VM to warm up (so the claim binds fast)")- info("(cold start = containerDisk image pull + guest boot + service on the readiness port)")- wait_pool_warm(http, pool, args.warm_timeout, args.poll_interval)-- step(f"Claiming a sandbox from {pool!r} (claim {claim_name!r})")- create_claim(http(), pool, claim_name, args.bind_deadline)-- try:- step("Waiting for the claim to bind to the warm sandbox")- sandbox = wait_bound(http, pool, claim_name, args.bind_timeout, args.poll_interval)- info(f"bound to sandbox {sandbox!r}")-- # Per-sandbox Service is "<sandbox>-<service>" on port 80 -> targetPort.- svc_base = f"/api/svc/{pool}/{sandbox}-{args.service_name}"-- step("Waiting for the in-guest MCP server to answer")- wait_service_ready(http, f"{svc_base}/healthz", args.ready_timeout, args.poll_interval)-- step(f"Listing MCP tools at {svc_base}{args.mcp_path}")- list_mcp_tools(http(), svc_base, args.mcp_path)- finally:- print(flush=True)- if args.keep_claim:- step(f"Keeping claim {claim_name!r} (its VM stays out of the pool)")- info(f"release later with: DELETE {claims_url(pool, claim_name)}")- else:- step(f"Releasing claim {claim_name!r}")- r = http().delete(claims_url(pool, claim_name))- info(f"released (HTTP {r.status_code}) — the VM hard-resets and rejoins the pool")-- if args.delete_pool:- step(f"Tearing down pool {pool!r}")- delete_pool(http(), pool)- else:- step(f"Pool {pool!r} is live")- info(f"claim more sandboxes: POST {claims_url(pool)} (spec.sandboxTemplateRef.name={pool}-template)")- info(f"delete it when done: DELETE {warmpool_url(pool, pool)}")- info(f" DELETE {template_url(pool, f'{pool}-template')}")- info(f" DELETE /api/namespaces/{pool}")---if __name__ == "__main__":- main()diff --git a/libs/fleet/python-sdk/examples/lanes_fan_out.py b/libs/fleet/python-sdk/examples/lanes_fan_out.pydeleted file mode 100644index 15b34b01f5..0000000000--- a/libs/fleet/python-sdk/examples/lanes_fan_out.py+++ /dev/null@@ -1,134 +0,0 @@-#!/usr/bin/env python3-"""Minimal uv run example: send two batches to the same lane VMs.--Run:- uv run --with cua-train --extra-index-url https://wheels.cua.ai/simple/ \- lanes_fan_out.py \- --client-id key-xxxxxxxx \- --client-secret your-secret \- --pool test-pool-please-ignore-"""--from __future__ import annotations--import argparse-import random-import time--from cua_train import TrainClient-from cua_train.models import (- AcquireLanesRequest,- Action,- ActionParameters,- BatchSubmitRequest,- ReleaseLanesRequest,- RunConfig,-)---def parse_args() -> argparse.Namespace:- parser = argparse.ArgumentParser(description="Submit two batches to the same lane VMs.")- parser.add_argument("--client-id", required=True, help="OAuth client id")- parser.add_argument("--client-secret", required=True, help="OAuth client secret")- parser.add_argument(- "--token-url",- default="https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token",- help="OIDC token endpoint",- )- parser.add_argument("--pool", default="test-pool-please-ignore", help="Target pool name")- parser.add_argument("--lanes", type=int, default=4, help="Number of lanes (VMs) to acquire")- parser.add_argument("--steps", type=int, default=5, help="Clicks per run")- parser.add_argument("--run-timeout", type=int, default=300, help="Run timeout seconds")- parser.add_argument("--poll-interval", type=float, default=2.0, help="Poll interval seconds")- return parser.parse_args()---def random_click() -> Action:- return Action(- action_type="CLICK",- parameters=ActionParameters.from_dict(- {"x": random.randint(200, 1720), "y": random.randint(100, 980), "button": "left"}- ),- )---def wait_for_label(client: TrainClient, pool: str, label: str, poll_interval: float) -> list:- res = client.get_label_results(pool=pool, label=label, completed_only=True)- while True:- runs = [r for b in res.batches for r in b.runs] if getattr(res, "batches", None) else []- if getattr(res, "all_completed", False) and runs:- return runs- time.sleep(poll_interval)- res = client.get_label_results(pool=pool, label=label, completed_only=True)---def submit_and_wait(- client: TrainClient,- pool: str,- lanes: list[str],- label: str,- steps: int,- run_timeout: int,- poll_interval: float,-) -> tuple[int, int]:- runs = [RunConfig(vm_id=vm_id, steps=[random_click() for _ in range(steps)], timeout=run_timeout) for vm_id in lanes]-- client.submit_label_batch(- pool=pool,- label=label,- body=BatchSubmitRequest(- runs=runs,- concurrency=len(lanes),- ),- )- print(f"submitted {label} with {len(runs)} runs")-- results = wait_for_label(client, pool, label, poll_interval)- ok = sum(1 for r in results if getattr(r, "ok", False))- return ok, len(results)---def main() -> None:- args = parse_args()-- client = TrainClient.from_key(- token_url=args.token_url,- client_id=args.client_id,- client_secret=args.client_secret,- )-- lanes = client.acquire_lanes(pool=args.pool, body=AcquireLanesRequest(n=args.lanes)).vm_ids- print(f"acquired {len(lanes)} lanes")-- try:- first_label = f"uv-example-{int(time.time())}-1"- first_ok, first_total = submit_and_wait(- client,- args.pool,- lanes,- first_label,- args.steps,- args.run_timeout,- args.poll_interval,- )- print(f"first batch completed: {first_ok}/{first_total} ok")-- # Reuses the exact same vm_ids from the acquired lanes for a second interaction.- second_label = f"uv-example-{int(time.time())}-2"- second_ok, second_total = submit_and_wait(- client,- args.pool,- lanes,- second_label,- args.steps,- args.run_timeout,- args.poll_interval,- )- print(f"second batch completed: {second_ok}/{second_total} ok")- finally:- released = client.release_lanes(pool=args.pool, body=ReleaseLanesRequest(vm_ids=lanes)).released- print(f"released {released} lanes")---if __name__ == "__main__":- main()diff --git a/libs/fleet/python-sdk/examples/linux-mini-swe.yaml b/libs/fleet/python-sdk/examples/linux-mini-swe.yamldeleted file mode 100644index b1dbf9bdec..0000000000--- a/libs/fleet/python-sdk/examples/linux-mini-swe.yaml+++ /dev/null@@ -1,54 +0,0 @@-apiVersion: cua.ai/v1alpha1-kind: AgentWindowsDoubleMCPRun-metadata:- name: linux-mini-swe-demo--spec:- pool:- image: 296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace-duo:ci-publish-desktop-workspace-duo-main- cpu: 4- ram: 4Gi- firmware: bios # Linux workspace image boots on KubeVirt's default BIOS (efi is for the Windows image)- replicas: 2- minAvailable: 1- readinessPort: 8000- services:- - type: mcp- label: computer-server- service: server- port: 8000- mcpPath: /mcp- health: /status- - type: mcp- label: cua-driver- service: mcp- port: 3000- mcpPath: /mcp- health: /healthz- - type: auxiliary- label: novnc- service: novnc- port: 6080- claim:- bindDeadline: 600- agent:- model: us.anthropic.claude-sonnet-4-6- task: >-- install and launch firefox in this linux env, open- https://news.yahoo.com/, inspect the Yahoo News front page, and then- report the visible page contents in a concise final message. Do all work- inside this remote Windows sandbox, not on the local machine.- maxSteps: 60- keepImages: 2- rollout:- templateTimeout: 120- warmTimeout: 0- bindTimeout: 0- readyTimeout: 0- pollInterval: 10- teardown:- # keepPool:false so `--delete-pool` actually tears down (the script's- # if-keep/elif-delete precedence ignores --delete-pool when keepPool is- # true). With no teardown flags the pool is still left live for reuse.- keepPool: false- deletePool: falsediff --git a/libs/fleet/python-sdk/examples/live_demo.py b/libs/fleet/python-sdk/examples/live_demo.pydeleted file mode 100644index 417ca3cb2d..0000000000--- a/libs/fleet/python-sdk/examples/live_demo.py+++ /dev/null@@ -1,460 +0,0 @@-#!/usr/bin/env python3-"""Live demo — N lanes loop ``square -> triangle -> RESET`` forever, streamed to-a local webserver (one live MJPEG per lane) with a metadata overlay.--What it illustrates (cyclops-cs 0.2.0):- * explicit ``acquire_lanes`` / ``release_lanes``- * the SAME warm VM reused across batches — square (batch 1) then triangle- (batch 2) land on one desktop; the on-frame ``vm`` id stays the same- * in-band ``RESET`` (batch 3) hard-resets the VM — watch the ``vm`` id change- * the generic facade — every call is ``client.<op>(...)``, no ``.sync``--Each frame carries a banner (lane, iteration, phase, step, vm id); while a batch-is being provisioned/run you get a loading screen with an elapsed timer.--Setup::-- pip install cua-train --extra-index-url https://wheels.cua.ai/simple/- pip install pillow boto3- export CUA_CLIENT_ID=key-xxxxxxxx # from POST /api/keys- export CUA_CLIENT_SECRET=...- python live_demo.py # then open http://127.0.0.1:8000--Run-batch screenshots come back as S3 keys, so frames are pulled from the-results bucket (needs AWS read access). Ctrl-C releases the lanes.--Env knobs: CUA_POOL, CUA_LANES (default 4), CUA_DEMO_PORT (8000),-CUA_TOKEN_URL, CUA_RESULTS_BUCKET. Set CUA_DEMO_SELFTEST=1 to serve-loading/placeholder frames without touching the backend (preview the UI).-"""--from __future__ import annotations--import io-import os-import threading-import time-import uuid-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer--import boto3-from PIL import Image, ImageDraw, ImageFont--from cua_train import TrainClient-from cua_train.models import (- AcquireLanesRequest,- Action,- ActionParameters,- BatchSubmitRequest,- ErrorResponse,- ReleaseLanesRequest,- RunConfig,-)--POOL = os.environ.get("CUA_POOL", "test-pool-please-ignore")-TOKEN_URL = os.environ.get(- "CUA_TOKEN_URL",- "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token",-)-RESULTS_BUCKET = os.environ.get("CUA_RESULTS_BUCKET", "cua-osgym-batch-results")-N_LANES = int(os.environ.get("CUA_LANES", "4"))-PORT = int(os.environ.get("CUA_DEMO_PORT", "8000"))-SELFTEST = os.environ.get("CUA_DEMO_SELFTEST") == "1"--W, H = 1920, 1080-SCALE = 960 / W-SW, SH = round(W * SCALE), round(H * SCALE)-ANIM_DT = 0.06 # loading-frame redraw + stream push interval (~16 fps)-RED, BLUE, ORANGE, GREY, INK = (255, 90, 90), (90, 150, 255), (255, 165, 50), (120, 120, 120), (190, 205, 230)--SQUARE = [(480, 270), (1440, 270), (1440, 810), (480, 810), (480, 270)]-TRIANGLE = [(960, 170), (1440, 880), (480, 880), (960, 170)]---def _font(size):- try:- return ImageFont.load_default(size=size)- except TypeError: # lint-ignore: swallowed-exception — old Pillow without size=- return ImageFont.load_default()---FONT, FONT_SM, FONT_BIG = _font(22), _font(16), _font(34)---def _clicks(points):- return [- Action(action_type="CLICK", parameters=ActionParameters.from_dict({"x": x, "y": y, "button": "left"}))- for x, y in points- ]---def _short(vm):- return vm.rsplit("-", 1)[-1][:8] if vm else "?"---# ── shared latest-frame buffers (one JPEG per lane) ────────────────────────────-_frames: list[bytes | None] = [None] * N_LANES-# Each lane's current VM id (changes on RESET); tracked so shutdown releases the-# live VMs rather than the now-stale ones returned by acquire_lanes.-_cur_vms: list[str | None] = [None] * N_LANES-_lock = threading.Lock()---def set_frame(i, jpeg):- with _lock:- _frames[i] = jpeg---def get_frame(i):- with _lock:- return _frames[i]---def _jpeg(im):- buf = io.BytesIO()- im.convert("RGB").save(buf, "JPEG", quality=80)- return buf.getvalue()---def banner(im, lines, accent):- """Top metadata strip: line 0 in the accent colour, the rest dimmed."""- d = ImageDraw.Draw(im, "RGBA")- d.rectangle([0, 0, im.width, 12 + 28 * len(lines)], fill=(0, 0, 0, 170))- y = 8- for i, ln in enumerate(lines):- d.text((12, y), ln, fill=tuple(accent) if i == 0 else (235, 235, 235), font=FONT if i == 0 else FONT_SM)- y += 28---CYAN, MINT = (90, 165, 255), (110, 210, 160)---def loading_frame(head, secs, status="waiting for VM…", sub="", accent=CYAN):- """A status screen with a spinner + elapsed timer. `status`/`accent`- distinguish the wait: acquiring a fresh VM vs. a batch running / waiting- for its results."""- im = Image.new("RGB", (SW, SH), (15, 17, 22))- d = ImageDraw.Draw(im)- cx, cy, r = SW // 2, SH // 2, 40- d.ellipse([cx - r, cy - r, cx + r, cy + r], outline=(40, 46, 58), width=6) # track- a = (secs * 220) % 360 # rotating head- d.arc([cx - r, cy - r, cx + r, cy + r], a, a + 110, fill=accent, width=6)- d.text((cx, cy + r + 36), f"{status} {secs:0.1f}s", fill=INK, font=FONT, anchor="mm")- banner(im, [head, sub], accent)- return _jpeg(im)---def path_frame(base, head, sub, accent, path, upto, prior=None):- """A real screenshot with the click path traced + metadata banner."""- im = base.resize((SW, SH)).convert("RGB")- d = ImageDraw.Draw(im)- if prior: # earlier shape on this same VM, faded- d.line([(x * SCALE, y * SCALE) for x, y in prior], fill=GREY, width=3)- pts = [(x * SCALE, y * SCALE) for x, y in path[: upto + 1]]- if len(pts) >= 2:- d.line(pts, fill=accent, width=4)- for sx, sy in pts:- d.ellipse([sx - 7, sy - 7, sx + 7, sy + 7], fill=accent)- banner(im, [head, sub], accent)- return _jpeg(im)---def reset_frame(base, head, sub):- im = base.resize((SW, SH)).convert("RGB")- banner(im, [head, sub], ORANGE)- return _jpeg(im)---# ── backend helpers ────────────────────────────────────────────────────────────-def make_client():- return TrainClient.from_key(- token_url=TOKEN_URL,- client_id=os.environ["CUA_CLIENT_ID"],- client_secret=os.environ["CUA_CLIENT_SECRET"],- )---def wait_run(client, label, stop, idx, head, timeout=300):- """Poll for the run; meanwhile paint a loading screen with a live timer.- Raises on ErrorResponse (e.g. 401) so the caller can refresh the client."""- t0 = time.time()- last_poll = 0.0- while not stop.is_set():- # Redraw the spinner every frame (smooth); the VM already exists, so- # this is "running / waiting for results", not "waiting for a VM".- set_frame(- idx,- loading_frame(- head,- time.time() - t0,- status="running — waiting for results…",- sub="executing steps on the VM",- accent=MINT,- ),- )- if time.time() - last_poll >= 2:- last_poll = time.time()- try:- res = client.get_label_results(pool=POOL, label=label, completed_only=True)- except Exception as e: # transient network blip — keep waiting- print(f"[lane {idx}] poll {label}: {e!r}", flush=True)- else:- if isinstance(res, ErrorResponse):- raise RuntimeError(f"results error: {res}")- runs = [r for b in res.batches for r in b.runs] if getattr(res, "batches", None) else []- if getattr(res, "all_completed", False) and runs:- return runs[0]- if time.time() - t0 > timeout:- return None- stop.wait(ANIM_DT)- return None---def run_batch(client, idx, vm, steps, stop, head):- label = f"demo-{idx}-{uuid.uuid4().hex[:6]}"- resp = client.submit_label_batch(- pool=POOL,- label=label,- body=BatchSubmitRequest(runs=[RunConfig(vm_id=vm, steps=steps, timeout=300)], concurrency=1, keep_warm=True),- )- if isinstance(resp, ErrorResponse):- raise RuntimeError(f"submit error: {resp}")- return wait_run(client, label, stop, idx, head)---def play(idx, run, s3, stop, frame_fn):- """Stream a run's screenshots (S3 keys) into the lane buffer, one per step."""- shots = run.screenshots or []- for j, k in enumerate(shots):- if stop.is_set():- return- if not k:- continue- raw = s3.get_object(Bucket=RESULTS_BUCKET, Key=k)["Body"].read()- set_frame(idx, frame_fn(Image.open(io.BytesIO(raw)), j, len(shots)))- stop.wait(0.45)---# ── per-lane worker: loop square (b1) → triangle (b2) → RESET (b3), forever ─────-def lane_worker(idx, vm0, stop):- s3 = boto3.client("s3")- client = make_client() # TrainClient refreshes its token transparently- cur, it = vm0, 0- _cur_vms[idx] = vm0- while not stop.is_set():- try:- it += 1-- # batch 1 — square on the current warm VM- r = run_batch(client, idx, cur, _clicks(SQUARE), stop, f"LANE {idx} · iter {it} · SQUARE (batch 1)")- if r is None:- continue- cur = r.vm_id- _cur_vms[idx] = cur- play(- idx,- r,- s3,- stop,- lambda im, j, n: path_frame(- im, f"LANE {idx} iter {it} SQUARE {j + 1}/{n}", f"batch 1 · vm …{_short(cur)}", RED, SQUARE, j- ),- )-- # batch 2 — triangle on the SAME VM (reuse across batches)- r = run_batch(client, idx, cur, _clicks(TRIANGLE), stop, f"LANE {idx} · iter {it} · TRIANGLE (batch 2)")- if r is None:- continue- cur = r.vm_id- _cur_vms[idx] = cur- play(- idx,- r,- s3,- stop,- lambda im, j, n: path_frame(- im,- f"LANE {idx} iter {it} TRIANGLE {j + 1}/{n}",- f"batch 2 · vm …{_short(cur)} (same VM, reused)",- BLUE,- TRIANGLE,- j,- prior=SQUARE,- ),- )-- # batch 3 — in-band RESET: hard reset → new VM- old = cur- r = run_batch(- client, idx, cur, [Action(action_type="RESET")], stop, f"LANE {idx} · iter {it} · RESET (batch 3)"- )- if r is None:- continue- cur = r.vm_id- _cur_vms[idx] = cur- play(- idx,- r,- s3,- stop,- lambda im, j, n: reset_frame(- im, "RESET — hard reset", f"vm …{_short(old)} → …{_short(cur)} (new VM, same lane {idx})"- ),- )- except Exception as e: # transient network blip — log and retry the iteration- print(f"[lane {idx}] iter {it} error: {e!r}; retrying", flush=True)- stop.wait(2)---# ── webserver: one MJPEG stream per lane ───────────────────────────────────────-class Handler(BaseHTTPRequestHandler):- def log_message(self, *_):- pass-- def do_GET(self):- if self.path == "/":- self._page()- elif self.path.startswith("/lane/"):- try:- idx = int(self.path.split("/")[2])- except (IndexError, ValueError): # lint-ignore: swallowed-exception — bad /lane path, handled as 404- self.send_error(404)- return- self._stream(idx)- else:- self.send_error(404)-- def _page(self):- cards = "".join(- f'<figure><figcaption>lane {i}</figcaption><img src="/lane/{i}"></figure>' for i in range(N_LANES)- )- body = f"""<!doctype html><html><head><meta charset=utf-8>-<title>cyclops-cs — square / triangle / reset loop</title>-<style>body{{background:#111;color:#eee;font-family:system-ui;margin:0;padding:24px;text-align:center}}-.grid{{display:flex;flex-wrap:wrap;gap:18px;justify-content:center}}-figure{{margin:0}} img{{width:46vw;border:1px solid #333;border-radius:8px}}-figcaption{{margin:6px;color:#9cf}} .legend{{max-width:1000px;margin:8px auto 0;color:#bbb;line-height:1.5}}-b{{color:#eee}}</style></head>-<body><h2>cyclops-cs 0.2.0 — {N_LANES} lanes looping square → triangle → reset</h2>-<p class=legend>Each tile is one <b>lane</b> = a persistent VM. Per loop it runs three batches on-the <b>same warm VM</b>: <span style="color:#ff5a5a">square</span> (batch 1) →-<span style="color:#5a96ff">triangle</span> (batch 2, <b>VM reused</b>) →-<span style="color:#ffa532">RESET</span> (batch 3, <b>new VM</b> — watch the <code>vm</code> id change).-Then it repeats.</p>-<div class=grid>{cards}</div></body></html>""".encode()- self.send_response(200)- self.send_header("Content-Type", "text/html; charset=utf-8")- self.send_header("Content-Length", str(len(body)))- self.end_headers()- self.wfile.write(body)-- def _stream(self, idx):- self.send_response(200)- self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=frame")- self.send_header("Cache-Control", "no-cache")- self.end_headers()- try:- while True:- frame = get_frame(idx) or loading_frame("starting…", 0.0)- self.wfile.write(b"--frame\r\nContent-Type: image/jpeg\r\n")- self.wfile.write(f"Content-Length: {len(frame)}\r\n\r\n".encode())- self.wfile.write(frame)- self.wfile.write(b"\r\n")- time.sleep(ANIM_DT)- except (BrokenPipeError, ConnectionResetError): # lint-ignore: swallowed-exception — viewer closed stream- pass---def _acquire_with_timer(client, stop_anim):- """Acquire N lanes while painting a loading+timer screen on every tile."""- t0 = time.time()- box = {}-- def anim():- while not stop_anim.is_set():- for i in range(N_LANES):- set_frame(- i,- loading_frame(- f"LANE {i} · acquiring",- time.time() - t0,- status="waiting for VM…",- sub="acquire_lanes — provisioning a warm VM from the pool",- ),- )- time.sleep(ANIM_DT)-- t = threading.Thread(target=anim, daemon=True)- t.start()- try:- # The pool may not have N warm VMs yet (503 / ErrorResponse). Keep the- # "waiting for VM…" screen up and retry instead of crashing.- while not stop_anim.is_set():- res = client.acquire_lanes(pool=POOL, body=AcquireLanesRequest(n=N_LANES))- if isinstance(res, ErrorResponse):- print(f"acquire_lanes: {res}; retrying…", flush=True)- time.sleep(3)- continue- box["lanes"] = res.vm_ids- break- finally:- stop_anim.set()- t.join(timeout=2)- return box["lanes"]---def main():- for i in range(N_LANES):- set_frame(i, loading_frame("starting…", 0.0))-- server = ThreadingHTTPServer(("127.0.0.1", PORT), Handler)- threading.Thread(target=server.serve_forever, daemon=True).start()- print(f"streaming on http://127.0.0.1:{PORT} ({N_LANES} lanes)")-- if SELFTEST:- print("SELFTEST: serving loading frames, no backend. Ctrl-C to stop.")- t0 = time.time()- try:- while True:- for i in range(N_LANES):- state = (- ("running — waiting for results…", "executing steps on the VM", MINT)- if (int(t0) + i) % 2- else ("waiting for VM…", "acquire_lanes — provisioning a warm VM", CYAN)- )- set_frame(- i,- loading_frame(- f"LANE {i} · selftest", time.time() - t0, status=state[0], sub=state[1], accent=state[2]- ),- )- time.sleep(ANIM_DT)- except KeyboardInterrupt: # lint-ignore: swallowed-exception — Ctrl-C stops selftest- return-- client = make_client()- print(f"acquire_lanes(n={N_LANES}) …")- lanes = _acquire_with_timer(client, threading.Event())-- stop = threading.Event()- workers = [threading.Thread(target=lane_worker, args=(i, lanes[i], stop), daemon=True) for i in range(N_LANES)]- for w in workers:- w.start()- try:- while any(w.is_alive() for w in workers):- time.sleep(1)- except KeyboardInterrupt: # lint-ignore: swallowed-exception — Ctrl-C, releases in finally- print("\nstopping …")- finally:- stop.set()- for w in workers:- w.join(timeout=10)- # Release the VMs the lanes currently hold (RESET changes the id each- # iteration), plus the originals, so nothing leaks back to the pool.- to_release = sorted({*lanes, *(v for v in _cur_vms if v)})- client.release_lanes(pool=POOL, body=ReleaseLanesRequest(vm_ids=to_release))- print(f"released {len(to_release)} VMs; bye.")---if __name__ == "__main__":- main()diff --git a/libs/fleet/python-sdk/examples/provision_windows_and_drive_with_cua_sdk.py b/libs/fleet/python-sdk/examples/provision_windows_and_drive_with_cua_sdk.pydeleted file mode 100644index 02cdd4d519..0000000000--- a/libs/fleet/python-sdk/examples/provision_windows_and_drive_with_cua_sdk.py+++ /dev/null@@ -1,572 +0,0 @@-#!/usr/bin/env -S uv run --script-# /// script-# requires-python = ">=3.12,<3.14"-# dependencies = [-# "cua-train",-# "httpx",-# # Direct-proxy support (api_base_url / api_headers) shipped in cua-computer-# # 0.5.19 — https://github.com/trycua/cua/pull/1932-# "cua-computer>=0.5.19",-# ]-#-# [tool.uv]-# extra-index-url = ["https://wheels.cua.ai/simple/"]-# ///-"""Provision a **Windows computer-server** pool on cyclops-cs / run.cua.ai, claim-a sandbox, then drive it with the real ``cua-computer`` SDK (screenshot, screen-size, a shell command) — and tear the whole thing back down afterward.--This is the SDK companion to ``provision_windows_and_list_mcp_tools.py`` (which-claims the same kind of sandbox but only lists its MCP tools). Both target the-Windows ``cua-server-windows`` image, which runs ``python -m computer_server`` on-:8000.--Connecting directly through the proxy (no forwarder)------------------------------------------------------cyclops-cs exposes a sandbox only through an authenticated reverse proxy at-``{base_url}/api/svc/{ns}/{sandbox}-{service}/...`` that wants an-``Authorization: Bearer <token>`` header. The ``cua-computer`` SDK now supports-pointing at exactly that kind of endpoint via two params (added in-https://github.com/trycua/cua/pull/1932):-- Computer(- use_host_computer_server=True,- os_type="windows",- api_base_url="https://run.cua.ai/api/svc/<ns>/<sandbox>-api",- api_headers={"Authorization": "Bearer <token>"},- )--The SDK derives its REST/WebSocket URIs from ``api_base_url`` (keeping the path-prefix) and sends ``api_headers`` on every request — so it talks to the proxy-directly. No localhost forwarder, no subprocess.--> The bearer is short-lived, so we mint a fresh one right before connecting. For-> a long-running session you'd refresh it yourself (the proxy re-checks it per-> request); this example's actions finish in seconds.--Two modes-----------* default — connect the SDK, take a screenshot + screen size + run a command,- print the results, then tear down.-* ``--print-connection`` — print the ``api_base_url`` + a fresh bearer + a- ready-to-paste ``Computer(...)`` snippet and hold the sandbox open so you can- drive it from another process / your own agent. Ctrl-C tears it down.--Lifecycle is otherwise identical to the MCP example: create namespace → sandbox-template (Windows image, **efi firmware**, service on :8000) → warm pool → wait-warm → claim → wait bound → wait ``/status`` → [drive | print] → **teardown**-(claim + warm pool + template + namespace; this is a throwaway test scenario).-Pass ``--keep`` to leave it up.--Auth — use a per-USER key (``ukey-...``, from POST /api/user-keys), not a-per-pool key. Windows is slow to first-boot; the defaults wait generously.--Setup (zero-install with uv)::-- export CUA_CLIENT_ID=ukey-xxxxxxxx- export CUA_CLIENT_SECRET=...- uv run provision_windows_and_drive_with_cua_sdk.py --name win-api-demo- uv run provision_windows_and_drive_with_cua_sdk.py --name win-fwd-demo --print-connection--Env knobs: CUA_CLIENT_ID, CUA_CLIENT_SECRET, CUA_TOKEN_URL, CUA_BASE_URL.-"""--from __future__ import annotations--import argparse-import asyncio-import os-import sys-import time-import uuid-from collections.abc import Callable--import httpx--from cua_train import TrainClient--DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"-DEFAULT_BASE_URL = "https://run.cua.ai"-# The Windows computer-server image: Windows Server 2022 + cua-computer-server on-# :8000. It is a dockur-built GPT/UEFI image, so the pool MUST boot it with efi-# firmware (see --firmware below).-DEFAULT_IMAGE = "296062593712.dkr.ecr.us-west-2.amazonaws.com/cua-server-windows:latest"--# A pool is two native CRs in the osgym.cua.ai group: an OSGymSandboxTemplate-# (the VM shape, named "<pool>-template") and an OSGymSandboxWarmPool (named-# "<pool>") that references it and keeps spec.replicas VMs warm. Claims-# (OSGymSandboxClaim) reference the template by name.-EXT_GROUP = "osgym.cua.ai"-EXT_VERSION = "v1alpha1"-TEMPLATE_PLURAL = "osgymsandboxtemplates"-WARMPOOL_PLURAL = "osgymsandboxwarmpools"-CLAIM_PLURAL = "osgymsandboxclaims"---# ── URL builders (relative to base_url, e.g. https://run.cua.ai) ──────────---def template_url(pool: str, name: str | None = None) -> str:- base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{TEMPLATE_PLURAL}"- return f"{base}/{name}" if name else base---def warmpool_url(pool: str, name: str | None = None) -> str:- base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{WARMPOOL_PLURAL}"- return f"{base}/{name}" if name else base---def claims_url(pool: str, name: str | None = None) -> str:- base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{CLAIM_PLURAL}"- return f"{base}/{name}" if name else base---# ── Console helpers ───────────────────────────────────────────────────────---def step(msg: str) -> None:- print(f"\n==> {msg}", flush=True)---def info(msg: str) -> None:- print(f" {msg}", flush=True)---def die(msg: str) -> None:- sys.exit(f"\nERROR: {msg}")---# ── Lifecycle steps (identical to provision_windows_and_list_mcp_tools.py) ──---def create_namespace(http: httpx.Client, name: str) -> None:- """Create the per-user namespace via the Capsule-backed SPA endpoint.-- Pool name == namespace name (1:1). A 409 just means we are reusing a- namespace from an earlier run.- """- r = http.post("/api/namespaces", json={"name": name})- if r.status_code == 409:- info(f"namespace {name!r} already exists — reusing it")- return- if r.status_code == 403:- die(- "403 creating namespace — is this a per-pool key? Namespaces/pools/"- "claims need a per-USER key (client id starting with 'ukey-', from "- "POST /api/user-keys)."- )- r.raise_for_status()- info(f"namespace {name!r} created")---def create_template(- http: httpx.Client,- *,- pool: str,- image: str,- cpu: int,- ram: str,- firmware: str,- service_name: str,- port: int,- readiness_port: int,-) -> None:- """Create the OSGymSandboxTemplate — the VM shape every sandbox in the pool- is stamped from, and what claims reference by name (``<pool>-template``)."""- vm_template: dict = {- "containerDiskImage": image,- "imagePullSecret": "ecr-credentials",- "cpuCores": cpu,- "memory": ram,- "services": [- {"name": service_name, "targetPort": port, "protocol": "TCP"}- ],- }- # Windows needs efi: the VM builder then auto-applies the Hyper-V- # enlightenments + Windows-tuned clocks (vm_builders.vm_body, firmware=="efi").- if firmware != "bios":- vm_template["firmware"] = firmware- # Gate "Ready" (and claim binding) on the computer-server port being bound —- # without a probe the VM is advertised ready before the guest finishes- # booting (CUA-535). readiness_port == 0 disables the probe.- if readiness_port:- vm_template["probes"] = {"readinessProbe": {"tcpSocket": {"port": readiness_port}}}-- tmpl = f"{pool}-template"- body = {- "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",- "kind": "OSGymSandboxTemplate",- "metadata": {"namespace": pool, "name": tmpl, "labels": {"cua.ai/pool": pool}},- "spec": {"vmTemplate": vm_template},- }-- r = http.post(template_url(pool), json=body)- if r.status_code == 409:- info(f"template {tmpl!r} already exists — reusing it (VM shape unchanged)")- return- if r.status_code == 403:- die(- "403 creating template — per-pool keys cannot reach /api/k8s. Use a "- "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."- )- r.raise_for_status()- info(f"template {tmpl!r} created")- info(f"image: {image}")- info(f"size: {cpu} vCPU / {ram} / firmware={firmware}")- info(f"service: {service_name} -> targetPort {port} (reachable on Service port 80)")- info(f"readiness: {'tcpSocket :' + str(readiness_port) if readiness_port else 'launcher-up (no probe)'}")---def create_warm_pool(http: httpx.Client, *, pool: str, replicas: int) -> None:- """Create the OSGymSandboxWarmPool that keeps ``replicas`` sandboxes warm- from ``<pool>-template``."""- body = {- "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",- "kind": "OSGymSandboxWarmPool",- "metadata": {"namespace": pool, "name": pool, "labels": {"cua.ai/pool": pool}},- "spec": {- "replicas": replicas,- "sandboxTemplateRef": {"name": f"{pool}-template"},- },- }-- r = http.post(warmpool_url(pool), json=body)- if r.status_code == 409:- info(f"warm pool {pool!r} already exists — reusing it (replicas unchanged)")- return- if r.status_code == 403:- die(- "403 creating warm pool — per-pool keys cannot reach /api/k8s. Use a "- "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."- )- r.raise_for_status()- info(f"warm pool {pool!r} created (replicas={replicas} from {pool}-template)")---def pool_counts(get_http: Callable[[], httpx.Client], pool: str) -> tuple[int, int]:- """(replicas, readyReplicas) from the warm pool status, best-effort."""- try:- r = get_http().get(warmpool_url(pool, pool))- r.raise_for_status()- st = r.json().get("status") or {}- return int(st.get("replicas", 0)), int(st.get("readyReplicas", 0))- except Exception:- return (0, 0)---def wait_pool_warm(get_http: Callable[[], httpx.Client], pool: str, timeout: float, poll: float) -> None:- """Wait until the warm pool reports a ready VM before claiming.-- A brand-new Windows pool's cold start (UEFI image pull + Windows Server boot- + the computer-server scheduled task) is *minutes* and routinely exceeds the- operator's 300s claim bind deadline. Letting status.readyReplicas>=1 first- means the subsequent claim binds in seconds. Re-fetches the ``http``- accessor each poll to keep the bearer token fresh over a long pull.- """- start = time.monotonic()- deadline = start + timeout- while True:- total, ready = pool_counts(get_http, pool)- if ready >= 1:- info(f"pool warm: {ready}/{total} VM(s) ready")- return- if time.monotonic() > deadline:- die(f"timed out after {timeout:.0f}s waiting for a warm VM "- f"({ready}/{total} ready).\n"- f" Most common cause: the --image tag does not exist in the registry, "- f"so the VM sits in ImagePullBackOff and never boots. List real tags with:\n"- f" aws ecr describe-images --repository-name cua-server-windows --region us-west-2\n"- f" Less commonly the cold Windows boot just needs longer — raise --warm-timeout.")- elapsed = int(time.monotonic() - start)- info(f"[{elapsed:4d}s] pool: {ready}/{total} VMs ready — warming "- f"(image pull + Windows boot + computer-server on the readiness port) …")- time.sleep(poll)---def create_claim(http: httpx.Client, pool: str, name: str, bind_deadline: int = 0) -> None:- spec: dict = {"sandboxTemplateRef": {"name": f"{pool}-template"}}- if bind_deadline:- spec["bindDeadline"] = bind_deadline- r = http.post(- claims_url(pool),- json={- "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",- "kind": "OSGymSandboxClaim",- "metadata": {"name": name},- "spec": spec,- },- )- if r.status_code == 403:- die(- "403 creating claim — per-pool keys have no K8s identity. Use a "- "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."- )- r.raise_for_status()- info(f"claim {name!r} created")---def wait_bound(get_http: Callable[[], httpx.Client], pool: str, name: str, timeout: float, poll: float) -> str:- """Poll the claim until status.phase == Bound; return the sandbox name."""- start = time.monotonic()- deadline = start + timeout- while True:- r = get_http().get(claims_url(pool, name))- r.raise_for_status()- status = r.json().get("status") or {}- phase = status.get("phase", "Pending")- sandbox = (status.get("sandbox") or {}).get("name")- if phase == "Bound" and sandbox:- return sandbox- if phase == "Failed":- die(f"claim {name} failed: {status}")- if time.monotonic() > deadline:- die(f"timed out after {timeout:.0f}s waiting for claim {name} to bind (phase={phase})")- total, ready = pool_counts(get_http, pool)- elapsed = int(time.monotonic() - start)- info(f"[{elapsed:4d}s] claim={phase} pool={ready}/{total} VMs ready …")- time.sleep(poll)---def wait_service_ready(get_http: Callable[[], httpx.Client], url: str, timeout: float, poll: float) -> None:- """GET url until the in-guest service answers (not a proxy 502/503/504).-- For computer-server that endpoint is ``/status``.- """- start = time.monotonic()- deadline = start + timeout- while True:- try:- resp = get_http().get(url, timeout=15.0)- except httpx.HTTPError as e:- resp = None- reason = type(e).__name__- else:- reason = f"HTTP {resp.status_code}"- if resp is not None and resp.status_code not in (502, 503, 504):- info(f"service responding ({reason})")- return- if time.monotonic() > deadline:- die(f"timed out after {timeout:.0f}s waiting for the in-guest service (last: {reason})")- elapsed = int(time.monotonic() - start)- info(f"[{elapsed:4d}s] {reason} — guest still booting …")- time.sleep(poll)---def teardown(get_http: Callable[[], httpx.Client], pool: str, claim_name: str) -> None:- """Best-effort full cleanup: delete the claim, both pool CRs (warm pool- before template), then the namespace.-- Idempotent — a 404 just means something was already gone.- """- for what, url in (- (f"claim {claim_name!r}", claims_url(pool, claim_name)),- (f"warm pool {pool!r}", warmpool_url(pool, pool)),- (f"template {pool}-template", template_url(pool, f"{pool}-template")),- (f"namespace {pool!r}", f"/api/namespaces/{pool}"),- ):- try:- r = get_http().delete(url)- info(f"deleted {what} (HTTP {r.status_code})")- except httpx.HTTPError as e:- info(f"could not delete {what}: {type(e).__name__}: {e}")---def bearer(client: TrainClient) -> str:- """Mint/refresh and return the current bearer token value."""- client.get_httpx_client() # forces TrainClient._refresh_token()- return f"Bearer {client.token}"---# ── Drive the box with the cua-computer SDK (directly through the proxy) ─────---async def drive_with_sdk(api_base_url: str, auth: str, sandbox: str) -> None:- """Connect the cua-computer SDK straight at the cyclops-cs proxy and do a few- things — no forwarder (uses api_base_url + api_headers from cua#1932)."""- # Imported lazily so --help and arg errors don't pay the cua-computer import.- from computer import Computer-- step(f"Connecting the cua-computer SDK directly to {api_base_url}")- computer = Computer(- use_host_computer_server=True, # connect to an existing server, do not spawn a VM- os_type="windows",- api_base_url=api_base_url,- api_headers={"Authorization": auth},- )- async with computer: # __aenter__ -> run() -> wait_for_ready (REST 'version' then get_screen_size)- size = await computer.interface.get_screen_size()- info(f"screen size: {size['width']}x{size['height']}")-- png = await computer.interface.screenshot()- out = f"{sandbox}-screenshot.png"- with open(out, "wb") as f:- f.write(png)- info(f"screenshot: wrote {len(png)} bytes to {out}")-- res = await computer.interface.run_command("echo hello-from-cua")- info(f"run_command rc={res.returncode} stdout={res.stdout.strip()!r}")-- info("SDK actions complete")---async def print_connection(api_base_url: str, auth: str) -> None:- """Print connection details and hold the sandbox open until Ctrl-C."""- step("Sandbox is live — point any cua-computer client straight at the proxy")- info(f"api_base_url: {api_base_url}")- info("paste into your own script / agent (the bearer below is short-lived):")- print(- "\n"- " from computer import Computer\n"- " computer = Computer(\n"- " use_host_computer_server=True,\n"- ' os_type="windows",\n'- f' api_base_url="{api_base_url}",\n'- f' api_headers={{"Authorization": "{auth}"}},\n'- " )\n"- " async with computer:\n"- " await computer.interface.screenshot()\n",- flush=True,- )- info("Ctrl-C to stop and tear everything down.")- await asyncio.Event().wait() # block; KeyboardInterrupt propagates to main's finally---# ── Main ──────────────────────────────────────────────────────────────────---async def amain() -> None:- p = argparse.ArgumentParser(- description="Provision a Windows computer-server pool on run.cua.ai, claim a sandbox, "- "drive it with the cua-computer SDK (directly through the proxy), then tear it down.",- formatter_class=argparse.ArgumentDefaultsHelpFormatter,- )- p.add_argument("--name", required=True, help="pool name (also the namespace; lowercase/dashes)")- p.add_argument("--client-id", default=os.environ.get("CUA_CLIENT_ID"),- help="OAuth client id (per-user key 'ukey-…'); env CUA_CLIENT_ID")- p.add_argument("--client-secret", default=os.environ.get("CUA_CLIENT_SECRET"),- help="OAuth client secret; env CUA_CLIENT_SECRET")- p.add_argument("--image", default=DEFAULT_IMAGE, help="Windows workspace containerDisk image")- p.add_argument("--port", type=int, default=8000, help="computer-server port on the VM")- p.add_argument("--service-name", default="api", help="name for the per-sandbox Service")- p.add_argument("--replicas", type=int, default=1, help="pre-warmed VMs the pool keeps")- p.add_argument("--cpu", type=int, default=4, help="vCPU cores per VM")- p.add_argument("--ram", default="8Gi", help="memory per VM (K8s quantity; Windows wants >=8Gi)")- p.add_argument("--firmware", choices=["bios", "efi"], default="efi",- help="VM firmware (efi for the GPT/UEFI-only Windows image)")- p.add_argument("--readiness-port", type=int, default=None,- help="TCP readiness port (default: --port; 0 disables the probe)")- p.add_argument("--token-url", default=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL),- help="OIDC token endpoint")- p.add_argument("--base-url", default=os.environ.get("CUA_BASE_URL", DEFAULT_BASE_URL),- help="cyclops-cs base URL")- p.add_argument("--claim-name", help="claim name (default: claim-<random>)")- p.add_argument("--warm-timeout", type=float, default=1200,- help="seconds to wait for the pool's first warm VM before claiming "- "(covers the cold image pull + slow Windows boot)")- p.add_argument("--bind-deadline", type=int, default=600,- help="claim spec.bindDeadline (0 uses the operator default of 300s)")- p.add_argument("--bind-timeout", type=float, default=300,- help="seconds the script waits for the claim to bind (fast once warm)")- p.add_argument("--ready-timeout", type=float, default=420,- help="seconds to wait for the in-guest service after binding")- p.add_argument("--poll-interval", type=float, default=5,- help="seconds between status polls")- p.add_argument("--print-connection", action="store_true",- help="instead of driving the SDK, print the api_base_url + a fresh bearer "- "+ a Computer(...) snippet and hold the sandbox open (Ctrl-C to tear down)")- p.add_argument("--keep", action="store_true",- help="skip teardown — leave the pool, namespace, and claim up for debugging")- args = p.parse_args()-- if not args.client_id or not args.client_secret:- die("set --client-id/--client-secret or CUA_CLIENT_ID/CUA_CLIENT_SECRET "- "(per-user key from POST /api/user-keys)")- if args.client_id.startswith("key-"):- die("that looks like a per-POOL key ('key-…'), which has no K8s identity. "- "Creating namespaces/pools/claims needs a per-USER key ('ukey-…', "- "from POST /api/user-keys).")-- readiness_port = args.port if args.readiness_port is None else args.readiness_port- pool = args.name- claim_name = args.claim_name or f"claim-{uuid.uuid4().hex[:8]}"-- step(f"Authenticating to {args.base_url} (client {args.client_id})")- client = TrainClient.from_key(- token_url=args.token_url,- client_id=args.client_id,- client_secret=args.client_secret,- base_url=args.base_url,- )- http = client.get_httpx_client # callable: re-mints the bearer near expiry- info("token acquired")-- step(f"Creating namespace {pool!r}")- create_namespace(http(), pool)-- step(f"Creating sandbox template {pool}-template")- create_template(- http(),- pool=pool,- image=args.image,- cpu=args.cpu,- ram=args.ram,- firmware=args.firmware,- service_name=args.service_name,- port=args.port,- readiness_port=readiness_port,- )-- step(f"Creating warm pool {pool!r}")- create_warm_pool(http(), pool=pool, replicas=args.replicas)-- step("Waiting for the pool's first VM to warm up (so the claim binds fast)")- info("(cold start = containerDisk image pull + Windows boot + computer-server on the readiness port)")- wait_pool_warm(http, pool, args.warm_timeout, args.poll_interval)-- step(f"Claiming a sandbox from {pool!r} (claim {claim_name!r})")- create_claim(http(), pool, claim_name, args.bind_deadline)-- try:- step("Waiting for the claim to bind to the warm sandbox")- sandbox = wait_bound(http, pool, claim_name, args.bind_timeout, args.poll_interval)- info(f"bound to sandbox {sandbox!r}")-- # Per-sandbox Service is "<sandbox>-<service>" on port 80 -> targetPort.- svc_path = f"/api/svc/{pool}/{sandbox}-{args.service_name}"-- step("Waiting for the in-guest computer-server to answer")- wait_service_ready(http, f"{svc_path}/status", args.ready_timeout, args.poll_interval)-- # Full https URL of the proxied computer-server + a fresh short-lived bearer.- api_base_url = f"{args.base_url}{svc_path}"- auth = bearer(client)-- if args.print_connection:- await print_connection(api_base_url, auth)- else:- await drive_with_sdk(api_base_url, auth, sandbox)- except KeyboardInterrupt:- info("interrupted — tearing down")- finally:- print(flush=True)- if args.keep:- step(f"Keeping infra ({pool!r}) — skipping teardown (--keep)")- info(f"claim: {claims_url(pool, claim_name)}")- info(f"warm pool: {warmpool_url(pool, pool)}")- info(f"template: {template_url(pool, f'{pool}-template')}")- info(f"namespace: /api/namespaces/{pool}")- else:- step(f"Tearing down {pool!r} (claim + warm pool + template + namespace)")- teardown(http, pool, claim_name)- info("done — nothing left billing")---def main() -> None:- try:- asyncio.run(amain())- except KeyboardInterrupt:- pass---if __name__ == "__main__":- main()diff --git a/libs/fleet/python-sdk/examples/provision_windows_and_list_mcp_tools.py b/libs/fleet/python-sdk/examples/provision_windows_and_list_mcp_tools.pydeleted file mode 100644index 7372efae36..0000000000--- a/libs/fleet/python-sdk/examples/provision_windows_and_list_mcp_tools.py+++ /dev/null@@ -1,582 +0,0 @@-#!/usr/bin/env -S uv run --script-# /// script-# requires-python = ">=3.10"-# dependencies = [-# "cua-train",-# "httpx",-# ]-#-# [tool.uv]-# extra-index-url = ["https://wheels.cua.ai/simple/"]-# ///-"""Provision a **Windows computer-server** pool on cyclops-cs / run.cua.ai, claim-a sandbox from it, list the MCP tools it exposes — then tear the whole thing back-down. End to end, from nothing but a client id/secret.--This is the MCP companion to ``provision_windows_and_drive_with_cua_sdk.py``-(which claims the same kind of sandbox but drives it with the ``cua-computer``-SDK instead). Both target the Windows ``cua-server-windows`` image, which runs-``python -m computer_server`` on :8000 and exposes, on that one port:-- * the HTTP/WebSocket computer-use API (``/cmd``, ``/ws``, ``/status``)- * an MCP server over Streamable HTTP at ``/mcp``--Here we only do the MCP side: the Streamable-HTTP handshake-(``initialize`` → ``notifications/initialized`` → ``tools/list``) and print the-advertised tools.--Lifecycle (every step is narrated so you can follow along in the console):-- 1. exchange the client_credentials for a bearer token (``TrainClient.from_key``)- 2. create the per-user namespace (``POST /api/namespaces`` — same path the SPA- uses, so Capsule sets up tenant ownership + RBAC; pool name == namespace)- 3. create the two native CRs (``osgym.cua.ai/v1alpha1``) via the ``/api/k8s``- kubectl-proxy: an ``OSGymSandboxTemplate`` (``<pool>-template``) with the- Windows image, **efi firmware**, and a service on :8000, plus an- ``OSGymSandboxWarmPool`` (``<pool>``) referencing it that warms the VM.- 4. claim a sandbox (``OSGymSandboxClaim``) and wait for it to bind- 5. reach the bound sandbox through ``/api/svc/{ns}/{sandbox}-{service}/`` and- run the computer-server MCP handshake (initialize -> tools/list)- 6. **tear it all down** — delete the claim, both pool CRs, and the namespace.- This is a throwaway test scenario, so nothing is left billing. Pass- ``--keep`` to leave the pool up for poking at.--Auth — use a per-USER key (``ukey-...``), NOT a per-pool key:-``/api/k8s`` impersonates the token's owner so Capsule tenant RBAC applies.-Per-user keys (POST /api/user-keys) can create namespaces, pools, and claims;-per-pool keys (POST /api/keys, ``key-...``) have no K8s identity and are rejected.--Heads up: Windows is **slow to first-boot** (UEFI image pull + Windows Server-boot + computer-server scheduled task coming up). The defaults wait generously;-raise ``--warm-timeout`` if your pull is cold.--Setup (zero-install with uv)::-- export CUA_CLIENT_ID=ukey-xxxxxxxx # from POST /api/user-keys- export CUA_CLIENT_SECRET=...- uv run provision_windows_and_list_mcp_tools.py --name win-mcp-demo--If your uv is too old to read the inline extra-index-url, run it the explicit-way::-- uv run --with cua-train --with httpx \- --extra-index-url https://wheels.cua.ai/simple/ \- provision_windows_and_list_mcp_tools.py --name win-mcp-demo--Env knobs: CUA_CLIENT_ID, CUA_CLIENT_SECRET, CUA_TOKEN_URL, CUA_BASE_URL.-"""--from __future__ import annotations--import argparse-import json-import os-import sys-import time-import uuid-from collections.abc import Callable--import httpx--from cua_train import TrainClient--DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"-DEFAULT_BASE_URL = "https://run.cua.ai"-# The Windows computer-server image: Windows Server 2022 + cua-computer-server on-# :8000 (HTTP/WS API at /cmd//ws, MCP at /mcp). It is a dockur-built GPT/UEFI-# image, so the pool MUST boot it with efi firmware (see --firmware below).-DEFAULT_IMAGE = "296062593712.dkr.ecr.us-west-2.amazonaws.com/cua-server-windows:latest"--# A pool is two native CRs in the osgym.cua.ai group: an OSGymSandboxTemplate-# (the VM shape, named "<pool>-template") and an OSGymSandboxWarmPool (named-# "<pool>") that references it and keeps spec.replicas VMs warm. Claims-# (OSGymSandboxClaim) reference the template by name.-EXT_GROUP = "osgym.cua.ai"-EXT_VERSION = "v1alpha1"-TEMPLATE_PLURAL = "osgymsandboxtemplates"-WARMPOOL_PLURAL = "osgymsandboxwarmpools"-CLAIM_PLURAL = "osgymsandboxclaims"---# ── URL builders (relative to base_url, e.g. https://run.cua.ai) ──────────---def template_url(pool: str, name: str | None = None) -> str:- base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{TEMPLATE_PLURAL}"- return f"{base}/{name}" if name else base---def warmpool_url(pool: str, name: str | None = None) -> str:- base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{WARMPOOL_PLURAL}"- return f"{base}/{name}" if name else base---def claims_url(pool: str, name: str | None = None) -> str:- base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{CLAIM_PLURAL}"- return f"{base}/{name}" if name else base---# ── Console helpers ───────────────────────────────────────────────────────---def step(msg: str) -> None:- print(f"\n==> {msg}", flush=True)---def info(msg: str) -> None:- print(f" {msg}", flush=True)---def die(msg: str) -> None:- sys.exit(f"\nERROR: {msg}")---# ── Lifecycle steps ───────────────────────────────────────────────────────---def create_namespace(http: httpx.Client, name: str) -> None:- """Create the per-user namespace via the Capsule-backed SPA endpoint.-- Pool name == namespace name (1:1). Going through /api/namespaces (rather- than a raw /api/k8s namespace create) is what makes Capsule stamp tenant- ownership + RBAC, so the impersonated pool create below is allowed. A 409- just means we are reusing a namespace from an earlier run.- """- r = http.post("/api/namespaces", json={"name": name})- if r.status_code == 409:- info(f"namespace {name!r} already exists — reusing it")- return- if r.status_code == 403:- die(- "403 creating namespace — is this a per-pool key? Namespaces/pools/"- "claims need a per-USER key (client id starting with 'ukey-', from "- "POST /api/user-keys)."- )- r.raise_for_status()- info(f"namespace {name!r} created")---def create_template(- http: httpx.Client,- *,- pool: str,- image: str,- cpu: int,- ram: str,- firmware: str,- service_name: str,- port: int,- readiness_port: int,-) -> None:- """Create the OSGymSandboxTemplate — the VM shape every sandbox in the pool- is stamped from, and what claims reference by name (``<pool>-template``)."""- vm_template: dict = {- "containerDiskImage": image,- "imagePullSecret": "ecr-credentials",- "cpuCores": cpu,- "memory": ram,- # Each entry becomes a per-sandbox K8s Service "<sandbox>-<name>"- # mapping port 80 -> targetPort on the VM.- "services": [- {"name": service_name, "targetPort": port, "protocol": "TCP"}- ],- }- # The SPA only sends firmware when it differs from KubeVirt's bios default.- # Windows needs efi: the VM builder then auto-applies the Hyper-V- # enlightenments + Windows-tuned clocks (vm_builders.vm_body, firmware=="efi").- if firmware != "bios":- vm_template["firmware"] = firmware- # Gate "Ready" (and therefore claim binding) on the computer-server port- # being bound. Without a probe the VM is advertised ready ~30s before the- # guest finishes booting (CUA-535) — doubly important for slow Windows boots.- # readiness_port == 0 disables the probe (KubeVirt's launcher-up default).- if readiness_port:- vm_template["probes"] = {"readinessProbe": {"tcpSocket": {"port": readiness_port}}}-- tmpl = f"{pool}-template"- body = {- "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",- "kind": "OSGymSandboxTemplate",- "metadata": {"namespace": pool, "name": tmpl, "labels": {"cua.ai/pool": pool}},- "spec": {"vmTemplate": vm_template},- }-- r = http.post(template_url(pool), json=body)- if r.status_code == 409:- info(f"template {tmpl!r} already exists — reusing it (VM shape unchanged)")- return- if r.status_code == 403:- die(- "403 creating template — per-pool keys cannot reach /api/k8s. Use a "- "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."- )- r.raise_for_status()- info(f"template {tmpl!r} created")- info(f"image: {image}")- info(f"size: {cpu} vCPU / {ram} / firmware={firmware}")- info(f"service: {service_name} -> targetPort {port} (reachable on Service port 80)")- info(f"readiness: {'tcpSocket :' + str(readiness_port) if readiness_port else 'launcher-up (no probe)'}")---def create_warm_pool(http: httpx.Client, *, pool: str, replicas: int) -> None:- """Create the OSGymSandboxWarmPool that keeps ``replicas`` sandboxes warm- from ``<pool>-template``."""- body = {- "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",- "kind": "OSGymSandboxWarmPool",- "metadata": {"namespace": pool, "name": pool, "labels": {"cua.ai/pool": pool}},- "spec": {- "replicas": replicas,- "sandboxTemplateRef": {"name": f"{pool}-template"},- },- }-- r = http.post(warmpool_url(pool), json=body)- if r.status_code == 409:- info(f"warm pool {pool!r} already exists — reusing it (replicas unchanged)")- return- if r.status_code == 403:- die(- "403 creating warm pool — per-pool keys cannot reach /api/k8s. Use a "- "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."- )- r.raise_for_status()- info(f"warm pool {pool!r} created (replicas={replicas} from {pool}-template)")---def pool_counts(get_http: Callable[[], httpx.Client], pool: str) -> tuple[int, int]:- """(replicas, readyReplicas) from the warm pool status, best-effort."""- try:- r = get_http().get(warmpool_url(pool, pool))- r.raise_for_status()- st = r.json().get("status") or {}- return int(st.get("replicas", 0)), int(st.get("readyReplicas", 0))- except Exception:- return (0, 0)---def wait_pool_warm(get_http: Callable[[], httpx.Client], pool: str, timeout: float, poll: float) -> None:- """Wait until the warm pool reports a ready VM.-- This is the key to a reliable first claim: a brand-new pool has to pull the- (multi-GB) containerDisk image, boot the guest, and bring the in-guest- service up on the readiness port before a Sandbox becomes adoptable. For the- Windows image that cold start is *minutes* (UEFI image pull + Windows Server- boot + the computer-server scheduled task), and routinely exceeds the- operator's 300s *claim* bind deadline (claim_handlers.BIND_DEADLINE_DEFAULT_S).- If we claim first, the deadline burns down during the image pull and the- claim Fails with ``BindDeadlineExceeded`` — exactly the failure mode this- avoids.-- So we let the warm pool reach status.readyReplicas>=1 *before* claiming; the- subsequent claim then binds in seconds. Re-fetches the ``http`` accessor- each poll to keep the bearer token fresh over a long pull.- """- start = time.monotonic()- deadline = start + timeout- while True:- total, ready = pool_counts(get_http, pool)- if ready >= 1:- info(f"pool warm: {ready}/{total} VM(s) ready")- return- if time.monotonic() > deadline:- die(f"timed out after {timeout:.0f}s waiting for a warm VM "- f"({ready}/{total} ready).\n"- f" Most common cause: the --image tag does not exist in the registry, "- f"so the VM sits in ImagePullBackOff and never boots. List real tags with:\n"- f" aws ecr describe-images --repository-name cua-server-windows --region us-west-2\n"- f" Less commonly the cold Windows boot just needs longer — raise --warm-timeout.")- elapsed = int(time.monotonic() - start)- info(f"[{elapsed:4d}s] pool: {ready}/{total} VMs ready — warming "- f"(image pull + Windows boot + computer-server on the readiness port) …")- time.sleep(poll)---def create_claim(http: httpx.Client, pool: str, name: str, bind_deadline: int = 0) -> None:- spec: dict = {"sandboxTemplateRef": {"name": f"{pool}-template"}}- # The pool-operator fails an unbound claim after spec.bindDeadline seconds- # (default 300, claim_handlers.BIND_DEADLINE_DEFAULT_S). We claim only after- # the pool is already warm, so binding is near-instant — but a non-zero- # deadline is a safety margin in case the warm VM is mid hard-reset.- if bind_deadline:- spec["bindDeadline"] = bind_deadline- r = http.post(- claims_url(pool),- json={- "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",- "kind": "OSGymSandboxClaim",- "metadata": {"name": name},- "spec": spec,- },- )- if r.status_code == 403:- die(- "403 creating claim — per-pool keys have no K8s identity. Use a "- "per-USER key (client id starting with 'ukey-', from POST /api/user-keys)."- )- r.raise_for_status()- info(f"claim {name!r} created")---def wait_bound(get_http: Callable[[], httpx.Client], pool: str, name: str, timeout: float, poll: float) -> str:- """Poll the claim until status.phase == Bound; return the sandbox name.-- While we wait we also surface the warm pool's ready counts, so a cold start- is visible rather than a silent hang. Re-fetches the ``http`` accessor each- poll so the bearer token stays fresh across a long (cold-boot) wait.- """- start = time.monotonic()- deadline = start + timeout- while True:- r = get_http().get(claims_url(pool, name))- r.raise_for_status()- status = r.json().get("status") or {}- phase = status.get("phase", "Pending")- sandbox = (status.get("sandbox") or {}).get("name")- if phase == "Bound" and sandbox:- return sandbox- if phase == "Failed":- die(f"claim {name} failed: {status}")- if time.monotonic() > deadline:- die(f"timed out after {timeout:.0f}s waiting for claim {name} to bind (phase={phase})")- total, ready = pool_counts(get_http, pool)- elapsed = int(time.monotonic() - start)- info(f"[{elapsed:4d}s] claim={phase} pool={ready}/{total} VMs ready …")- time.sleep(poll)---def wait_service_ready(get_http: Callable[[], httpx.Client], url: str, timeout: float, poll: float) -> None:- """GET url until the in-guest service answers (not a proxy 502/503/504).-- Backstop for the slim window where the sandbox is Bound but the in-guest- HTTP server hasn't finished accepting connections yet. For computer-server- that endpoint is ``/status``. Re-fetches the ``http`` accessor each poll to- keep the bearer token fresh.- """- start = time.monotonic()- deadline = start + timeout- while True:- try:- resp = get_http().get(url, timeout=15.0)- except httpx.HTTPError as e:- resp = None- reason = type(e).__name__- else:- reason = f"HTTP {resp.status_code}"- if resp is not None and resp.status_code not in (502, 503, 504):- info(f"service responding ({reason})")- return- if time.monotonic() > deadline:- die(f"timed out after {timeout:.0f}s waiting for the in-guest service (last: {reason})")- elapsed = int(time.monotonic() - start)- info(f"[{elapsed:4d}s] {reason} — guest still booting …")- time.sleep(poll)---def list_mcp_tools(http: httpx.Client, base: str, mcp_path: str) -> None:- """computer-server MCP handshake over Streamable HTTP:- initialize -> notifications/initialized -> tools/list, then print the tools."""- url = f"{base}/{mcp_path.lstrip('/')}"- headers = {- "Content-Type": "application/json",- # Streamable HTTP requires advertising both content types.- "Accept": "application/json, text/event-stream",- }-- r = http.post(- url,- headers=headers,- timeout=30.0,- json={- "jsonrpc": "2.0",- "id": 1,- "method": "initialize",- "params": {- "protocolVersion": "2025-03-26",- "capabilities": {},- "clientInfo": {"name": "provision_windows_and_list_mcp_tools", "version": "0.1.0"},- },- },- )- r.raise_for_status()- session = r.headers.get("mcp-session-id")- info(f"MCP initialize: HTTP {r.status_code}" + (f", session {session}" if session else ""))- if session:- headers["Mcp-Session-Id"] = session-- # Notify the server we're ready (no response expected).- http.post(- url,- headers=headers,- timeout=30.0,- json={"jsonrpc": "2.0", "method": "notifications/initialized"},- )-- r = http.post(- url,- headers=headers,- timeout=30.0,- json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"},- )- r.raise_for_status()- # Streamable HTTP returns SSE ("event: message\ndata: {...}"); the JSON- # payload is on the data: line. Fall back to the raw body for plain JSON.- data = next((ln[6:] for ln in r.text.splitlines() if ln.startswith("data: ")), r.text)- tools = json.loads(data).get("result", {}).get("tools", [])-- print(f"\nMCP tools ({len(tools)}):", flush=True)- for i, t in enumerate(sorted(tools, key=lambda t: t.get("name", "")), 1):- name = t.get("name", "?")- desc = " ".join((t.get("description") or "").split())- if len(desc) > 70:- desc = desc[:67] + "…"- print(f" {i:3d}. {name:<24} {desc}", flush=True)- if not tools:- print(" (the server returned an empty tool list)", flush=True)---def teardown(get_http: Callable[[], httpx.Client], pool: str, claim_name: str) -> None:- """Best-effort full cleanup: delete the claim, both pool CRs (warm pool- before template), then the namespace.-- Idempotent — a 404 just means something was already gone. This is a test- scenario, so we remove everything we created and leave nothing billing.- """- for what, url in (- (f"claim {claim_name!r}", claims_url(pool, claim_name)),- (f"warm pool {pool!r}", warmpool_url(pool, pool)),- (f"template {pool}-template", template_url(pool, f"{pool}-template")),- (f"namespace {pool!r}", f"/api/namespaces/{pool}"),- ):- try:- r = get_http().delete(url)- info(f"deleted {what} (HTTP {r.status_code})")- except httpx.HTTPError as e:- info(f"could not delete {what}: {type(e).__name__}: {e}")---# ── Main ──────────────────────────────────────────────────────────────────---def main() -> None:- p = argparse.ArgumentParser(- description="Provision a Windows computer-server pool on run.cua.ai, claim a sandbox, "- "list its MCP tools, then tear it all down.",- formatter_class=argparse.ArgumentDefaultsHelpFormatter,- )- p.add_argument("--name", required=True, help="pool name (also the namespace; lowercase/dashes)")- p.add_argument("--client-id", default=os.environ.get("CUA_CLIENT_ID"),- help="OAuth client id (per-user key 'ukey-…'); env CUA_CLIENT_ID")- p.add_argument("--client-secret", default=os.environ.get("CUA_CLIENT_SECRET"),- help="OAuth client secret; env CUA_CLIENT_SECRET")- p.add_argument("--image", default=DEFAULT_IMAGE, help="Windows workspace containerDisk image")- p.add_argument("--port", type=int, default=8000, help="computer-server port on the VM")- p.add_argument("--service-name", default="api", help="name for the per-sandbox Service")- p.add_argument("--mcp-path", default="/mcp", help="path the MCP server is mounted at")- p.add_argument("--replicas", type=int, default=1, help="pre-warmed VMs the pool keeps")- p.add_argument("--cpu", type=int, default=4, help="vCPU cores per VM")- p.add_argument("--ram", default="8Gi", help="memory per VM (K8s quantity; Windows wants >=8Gi)")- p.add_argument("--firmware", choices=["bios", "efi"], default="efi",- help="VM firmware (efi for the GPT/UEFI-only Windows image)")- p.add_argument("--readiness-port", type=int, default=None,- help="TCP readiness port (default: --port; 0 disables the probe)")- p.add_argument("--token-url", default=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL),- help="OIDC token endpoint")- p.add_argument("--base-url", default=os.environ.get("CUA_BASE_URL", DEFAULT_BASE_URL),- help="cyclops-cs base URL")- p.add_argument("--claim-name", help="claim name (default: claim-<random>)")- p.add_argument("--warm-timeout", type=float, default=1200,- help="seconds to wait for the pool's first warm VM before claiming "- "(covers the cold image pull + slow Windows boot)")- p.add_argument("--bind-deadline", type=int, default=600,- help="claim spec.bindDeadline (operator fails an unbound claim after "- "this; 0 uses the operator default of 300s)")- p.add_argument("--bind-timeout", type=float, default=300,- help="seconds the script waits for the claim to bind (fast once warm)")- p.add_argument("--ready-timeout", type=float, default=420,- help="seconds to wait for the in-guest service after binding")- p.add_argument("--poll-interval", type=float, default=5,- help="seconds between status polls")- p.add_argument("--keep", action="store_true",- help="skip teardown — leave the pool, namespace, and claim up for debugging")- args = p.parse_args()-- if not args.client_id or not args.client_secret:- die("set --client-id/--client-secret or CUA_CLIENT_ID/CUA_CLIENT_SECRET "- "(per-user key from POST /api/user-keys)")- if args.client_id.startswith("key-"):- die("that looks like a per-POOL key ('key-…'), which has no K8s identity. "- "Creating namespaces/pools/claims needs a per-USER key ('ukey-…', "- "from POST /api/user-keys).")-- readiness_port = args.port if args.readiness_port is None else args.readiness_port- pool = args.name- claim_name = args.claim_name or f"claim-{uuid.uuid4().hex[:8]}"-- step(f"Authenticating to {args.base_url} (client {args.client_id})")- client = TrainClient.from_key(- token_url=args.token_url,- client_id=args.client_id,- client_secret=args.client_secret,- base_url=args.base_url,- )- # get_httpx_client() re-mints the bearer token near expiry, so fetch it- # per request rather than holding one reference.- http = client.get_httpx_client- info("token acquired")-- step(f"Creating namespace {pool!r}")- create_namespace(http(), pool)-- step(f"Creating sandbox template {pool}-template")- create_template(- http(),- pool=pool,- image=args.image,- cpu=args.cpu,- ram=args.ram,- firmware=args.firmware,- service_name=args.service_name,- port=args.port,- readiness_port=readiness_port,- )-- step(f"Creating warm pool {pool!r}")- create_warm_pool(http(), pool=pool, replicas=args.replicas)-- step("Waiting for the pool's first VM to warm up (so the claim binds fast)")- info("(cold start = containerDisk image pull + Windows boot + computer-server on the readiness port)")- wait_pool_warm(http, pool, args.warm_timeout, args.poll_interval)-- step(f"Claiming a sandbox from {pool!r} (claim {claim_name!r})")- create_claim(http(), pool, claim_name, args.bind_deadline)-- try:- step("Waiting for the claim to bind to the warm sandbox")- sandbox = wait_bound(http, pool, claim_name, args.bind_timeout, args.poll_interval)- info(f"bound to sandbox {sandbox!r}")-- # Per-sandbox Service is "<sandbox>-<service>" on port 80 -> targetPort.- svc_base = f"/api/svc/{pool}/{sandbox}-{args.service_name}"-- step("Waiting for the in-guest computer-server to answer")- wait_service_ready(http, f"{svc_base}/status", args.ready_timeout, args.poll_interval)-- step(f"Listing MCP tools at {svc_base}{args.mcp_path}")- list_mcp_tools(http(), svc_base, args.mcp_path)- finally:- print(flush=True)- if args.keep:- step(f"Keeping infra ({pool!r}) — skipping teardown (--keep)")- info(f"claim: {claims_url(pool, claim_name)}")- info(f"warm pool: {warmpool_url(pool, pool)}")- info(f"template: {template_url(pool, f'{pool}-template')}")- info(f"namespace: /api/namespaces/{pool}")- else:- step(f"Tearing down {pool!r} (claim + warm pool + template + namespace)")- teardown(http, pool, claim_name)- info("done — nothing left billing")---if __name__ == "__main__":- main()diff --git a/libs/fleet/python-sdk/examples/requirements.txt b/libs/fleet/python-sdk/examples/requirements.txtdeleted file mode 100644index d37fafb796..0000000000--- a/libs/fleet/python-sdk/examples/requirements.txt+++ /dev/null@@ -1,6 +0,0 @@-# Extra deps for the examples (the SDK itself only needs httpx + attrs).-# pip install cua-train --extra-index-url https://wheels.cua.ai/simple/-# pip install -r requirements.txt-pillow-boto3-pyyamldiff --git a/libs/fleet/python-sdk/examples/sample_agent.py b/libs/fleet/python-sdk/examples/sample_agent.pydeleted file mode 100644index b41c1b59d3..0000000000--- a/libs/fleet/python-sdk/examples/sample_agent.py+++ /dev/null@@ -1,1217 +0,0 @@-#!/usr/bin/env -S uv run --script-# /// script-# requires-python = ">=3.10"-# dependencies = [-# "boto3",-# "cua-train",-# "httpx",-# "pyyaml",-# ]-#-# [tool.uv]-# extra-index-url = ["https://wheels.cua.ai/simple/"]-# ///-"""Run **mini-swe-agent over TWO MCP servers** on a **Windows** CUA sandbox.--Self-contained, single-file — run it straight with ``uv`` (no venv, no-``pip install``); the inline script metadata pulls ``cua-train`` from the wheels-index automatically.--the sandbox runs **two** MCP servers at once:-- * CUA **computer-server** — Service ``<sandbox>-server`` (VM :8000), MCP /mcp- * **cua-driver** — Service ``<sandbox>-mcp`` (VM :3000), MCP /mcp--Lifecycle (every step narrated in the console):-- 1. exchange the client_credentials for a bearer token (``TrainClient.from_key``)- 2. create the per-user namespace (``POST /api/namespaces`` — Capsule tenant- RBAC; pool name == namespace)- 3. create the pool's two native CRs (``osgym.cua.ai/v1alpha1``): an- ``OSGymSandboxTemplate`` (``<pool>-template``) with **one Service per MCP- server**, and an ``OSGymSandboxWarmPool`` (``<pool>``) that warms VMs from it- 4. wait for a warm VM, then claim a sandbox (``OSGymSandboxClaim``)- 5. open one MCP session per server, run the agent, release the claim--Auth needs a per-USER key (``ukey-…``, from POST /api/user-keys); the LLM runs-on **AWS Bedrock** via a direct ``boto3`` ``bedrock-runtime`` Converse call. AWS-credentials come straight from the standard environment / default chain (env-vars, a shared profile, SSO, or an instance role) — there is no LiteLLM layer.-Set AWS_REGION (or pass ``--aws-region``); the model id is a Bedrock id such as-``us.anthropic.claude-sonnet-4-6`` (a leading ``bedrock/`` is stripped).-- export CUA_CLIENT_ID=ukey-xxxxxxxx- export CUA_CLIENT_SECRET=...- export AWS_REGION=us-east-1- export AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... # or AWS_PROFILE / role- uv run sample_agent.py --name windows-agent-demo \- --model us.anthropic.claude-sonnet-4-6 \- --task "Open Microsoft Edge and browse to https://news.yahoo.com/."--…or, if your uv is too old to read the inline extra-index-url::-- uv run --with cua-train --with httpx --with boto3 \- --extra-index-url https://wheels.cua.ai/simple/ \- sample_agent.py --name windows-agent-demo --task "…"--The sandbox claim is ALWAYS released on exit — success, error, or Ctrl-C. Pass-``--keep`` to leave the *pool/namespace* up (the claim is still released),-``--delete-pool`` to tear everything down.-Env knobs: CUA_CLIENT_ID, CUA_CLIENT_SECRET, CUA_TOKEN_URL, CUA_BASE_URL, AGENT_MODEL,-plus the standard AWS_* variables (AWS_REGION, AWS_ACCESS_KEY_ID, …) read by boto3.-"""--from __future__ import annotations--import argparse-import base64-import dataclasses-import json-import os-import re-import signal-import sys-import time-import uuid-from collections.abc import Callable--import boto3-import httpx-import yaml--from cua_train import TrainClient--DEFAULT_TOKEN_URL = "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"-DEFAULT_BASE_URL = "https://run.cua.ai"--# A pool is two native CRs in the osgym.cua.ai group: an OSGymSandboxTemplate-# (the VM shape, named "<pool>-template") and an OSGymSandboxWarmPool (named-# "<pool>") that references it and keeps spec.replicas VMs warm. Claims-# (OSGymSandboxClaim) reference the template by name.-EXT_GROUP, EXT_VERSION = "osgym.cua.ai", "v1alpha1"-TEMPLATE_PLURAL, WARMPOOL_PLURAL = "osgymsandboxtemplates", "osgymsandboxwarmpools"-CLAIM_PLURAL = "osgymsandboxclaims"--SYSTEM = (- "You operate a computer through the provided tools. You have access to "- "MULTIPLE tool servers running inside the same machine — a CUA "- "computer-server and a cua-driver — and their tool names are prefixed with "- "the server they belong to (e.g. 'computer-server__screenshot', "- "'cua-driver__click'). Pick whichever tool fits; they act on the same "- "desktop. Inspect state (take a screenshot, read a file, run a command), "- "then take ONE action at a time and observe the result before the next. "- "When the task is fully complete, reply with a final message and no tool call."-)---def default_run_manifest() -> dict:- return {- "apiVersion": "cua.ai/v1alpha1",- "kind": "AgentWindowsDoubleMCPRun",- "metadata": {"name": None},- "spec": {- "pool": {- "image": DEFAULT_IMAGE,- "cpu": DEFAULT_CPU,- "ram": DEFAULT_RAM,- "firmware": DEFAULT_FIRMWARE,- "replicas": 1,- "minAvailable": 1,- "readinessPort": None,- "services": [],- },- "claim": {- "name": None,- "bindDeadline": 600,- },- "agent": {- "model": None,- "task": None,- "maxSteps": 40,- "keepImages": 2,- },- "rollout": {- "warmTimeout": 0,- "bindTimeout": 0,- "readyTimeout": 0,- "pollInterval": 5,- },- "teardown": {- "keepPool": False,- "deletePool": False,- },- },- }---def deep_merge(base: dict, override: dict) -> dict:- merged = dict(base)- for key, value in override.items():- if isinstance(value, dict) and isinstance(base.get(key), dict):- merged[key] = deep_merge(base[key], value)- else:- merged[key] = value- return merged---def load_run_manifest(path: str | None) -> dict:- manifest = default_run_manifest()- if not path:- return manifest- with open(path, "r", encoding="utf-8") as f:- raw = yaml.safe_load(f) or {}- if not isinstance(raw, dict):- die(f"config {path!r} must be a YAML mapping/object")- manifest = deep_merge(manifest, raw)- kind = manifest.get("kind")- if kind != "AgentWindowsDoubleMCPRun":- die(f"config {path!r} must have kind: AgentWindowsDoubleMCPRun (got {kind!r})")- return manifest---def manifest_get(manifest: dict, *path: str, default=None):- cur = manifest- for part in path:- if not isinstance(cur, dict):- return default- cur = cur.get(part)- if cur is None:- return default- return cur---def resolve_name_template(name: str | None) -> str | None:- if not name:- return name- suffix = uuid.uuid4().hex[:6]- if "{randhex6}" in name:- return name.replace("{randhex6}", suffix)- if name.endswith("-"):- return f"{name}{suffix}"- return name---# Default LLM: Claude on AWS Bedrock (cross-region inference profile). Override-# with --model or AGENT_MODEL; whatever your AWS account/region has enabled.-DEFAULT_BEDROCK_MODEL = "us.anthropic.claude-sonnet-4-6"-MAX_OUTPUT_TOKENS = 4096---def default_model() -> str:- """Bedrock model id default (AGENT_MODEL overrides)."""- return os.environ.get("AGENT_MODEL") or DEFAULT_BEDROCK_MODEL---def env_first(name: str, *aliases: str) -> str | None:- for key in (name, *aliases):- value = os.environ.get(key)- if value:- return value- return None---def bedrock_model_id(model: str) -> str:- """Strip an optional ``bedrock/`` prefix; the Converse API wants the bare id."""- return model[len("bedrock/"):] if model.startswith("bedrock/") else model---def make_bedrock_client(args: argparse.Namespace):- """A boto3 bedrock-runtime client. Credentials and region come from the- standard AWS environment / default chain (env vars, shared profile, SSO,- instance role) — nothing LLM-specific to configure. --aws-region overrides- the region; AWS_REGION/AWS_DEFAULT_REGION are honoured otherwise."""- region = args.aws_region or env_first("AWS_REGION", "AWS_DEFAULT_REGION")- client = boto3.client("bedrock-runtime", region_name=region) if region else boto3.client("bedrock-runtime")- info(f"Bedrock client ready (region {client.meta.region_name})")- return client---# OS profile (Windows)--[email protected](frozen=True)-class McpServerSpec:- """One MCP server exposed by the sandbox VM.-- ``label`` — short name; tool names are namespaced ``<label>__<tool>``.- ``service`` — per-sandbox Service suffix: ``/api/svc/{ns}/{sandbox}-{service}``.- ``port`` — targetPort on the VM the Service maps :80 -> .- ``mcp_path`` — path the MCP server is mounted at (Streamable HTTP).- ``health`` — a cheap GET that returns non-5xx once the guest service is up.- """-- label: str- service: str- port: int- mcp_path: str = "/mcp"- health: str = "/healthz"--[email protected](frozen=True)-class ServiceSpec:- """One non-MCP service exposed by the sandbox VM."""-- label: str- service: str- port: int---OS_NAME = "windows"-DEFAULT_IMAGE = "296062593712.dkr.ecr.us-west-2.amazonaws.com/cua-server-windows:latest"-# KubeVirt VM firmware (spec.vmTemplate.firmware; CRD enum [bios, efi]).-# efi — GPT/UEFI-only guest images (the dockur-built Windows desktop-workspace);-# the operator also flips on Hyper-V enlightenments + clock config for it.-# bios — KubeVirt's default; what the Linux workspace images boot with.-# The SPA/operator only send firmware when it differs from bios, so we omit it for-# bios and let the operator default apply. Default here is efi (this script's-# Windows lineage); per-run configs set spec.pool.firmware for non-Windows images.-DEFAULT_FIRMWARE = "efi"-FIRMWARE_CHOICES = ("bios", "efi")-DEFAULT_RAM = "4Gi"-DEFAULT_CPU = 4-DEFAULT_WARM_TIMEOUT = 900 # cold image pull + Windows boot---# URL builders (relative to base_url, e.g. https://run.cua.ai)---def template_url(pool: str, name: str | None = None) -> str:- base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{TEMPLATE_PLURAL}"- return f"{base}/{name}" if name else base---def warmpool_url(pool: str, name: str | None = None) -> str:- base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{WARMPOOL_PLURAL}"- return f"{base}/{name}" if name else base---def claims_url(pool: str, name: str | None = None) -> str:- base = f"/api/k8s/apis/{EXT_GROUP}/{EXT_VERSION}/namespaces/{pool}/{CLAIM_PLURAL}"- return f"{base}/{name}" if name else base---def load_pool_services(manifest: dict) -> tuple[tuple[McpServerSpec, ...], tuple[ServiceSpec, ...]]:- raw_services = manifest_get(manifest, "spec", "pool", "services")- if not isinstance(raw_services, list) or not raw_services:- die("config must define spec.pool.services as a non-empty list")-- mcp_servers: list[McpServerSpec] = []- extra_services: list[ServiceSpec] = []- labels: set[str] = set()- names: set[str] = set()-- for idx, raw in enumerate(raw_services):- if not isinstance(raw, dict):- die(f"spec.pool.services[{idx}] must be a YAML mapping/object")- kind = raw.get("type")- label = raw.get("label")- service = raw.get("service")- port = raw.get("port")- if kind not in {"mcp", "auxiliary"}:- die(f"spec.pool.services[{idx}].type must be 'mcp' or 'auxiliary'")- if not isinstance(label, str) or not label:- die(f"spec.pool.services[{idx}].label must be a non-empty string")- if not isinstance(service, str) or not service:- die(f"spec.pool.services[{idx}].service must be a non-empty string")- if not isinstance(port, int) or port <= 0:- die(f"spec.pool.services[{idx}].port must be a positive integer")- if label in labels:- die(f"duplicate spec.pool.services label: {label!r}")- if service in names:- die(f"duplicate spec.pool.services service: {service!r}")- labels.add(label)- names.add(service)- if kind == "mcp":- mcp_path = raw.get("mcpPath", "/mcp")- health = raw.get("health", "/healthz")- if not isinstance(mcp_path, str) or not mcp_path.startswith("/"):- die(f"spec.pool.services[{idx}].mcpPath must be an absolute path string")- if not isinstance(health, str) or not health.startswith("/"):- die(f"spec.pool.services[{idx}].health must be an absolute path string")- mcp_servers.append(- McpServerSpec(label=label, service=service, port=port, mcp_path=mcp_path, health=health)- )- else:- extra_services.append(ServiceSpec(label=label, service=service, port=port))-- if not mcp_servers:- die("spec.pool.services must include at least one MCP service")- return tuple(mcp_servers), tuple(extra_services)---def pool_services(- mcp_servers: tuple[McpServerSpec, ...],- extra_services: tuple[ServiceSpec, ...],-) -> tuple[ServiceSpec, ...]:- base = tuple(ServiceSpec(label=s.label, service=s.service, port=s.port) for s in mcp_servers)- return base + extra_services---# Status formatting helpers---def _fmt_conditions(conditions: list[dict] | None) -> str:- if not conditions:- return "none"- parts = []- for cond in conditions:- ctype = cond.get("type", "?")- status = cond.get("status", "?")- reason = cond.get("reason", "?")- msg = " ".join(str(cond.get("message", "")).split())- chunk = f"{ctype}={status}/{reason}"- if msg:- chunk += f" ({msg})"- parts.append(chunk)- return "; ".join(parts)---def pool_status(http: httpx.Client, pool: str) -> dict:- r = http.get(warmpool_url(pool, pool))- r.raise_for_status()- return r.json().get("status") or {}---def claim_status(http: httpx.Client, pool: str, name: str) -> dict:- r = http.get(claims_url(pool, name))- r.raise_for_status()- return r.json().get("status") or {}---def claim_obj(http: httpx.Client, pool: str, name: str) -> dict:- r = http.get(claims_url(pool, name))- r.raise_for_status()- return r.json()---def pool_summary(status: dict) -> str:- return f"ready={int(status.get('readyReplicas', 0))}/{int(status.get('replicas', 0))}"---def claim_summary(status: dict) -> str:- sandbox = (status.get("sandbox") or {}).get("name")- summary = f"phase={status.get('phase', 'Pending')}"- if sandbox:- summary += f" sandbox={sandbox}"- conds = _fmt_conditions(status.get("conditions"))- if conds != "none":- summary += f" conditions=[{conds}]"- return summary---def claim_operator_progress(obj: dict) -> str | None:- raw = (obj.get("metadata") or {}).get("annotations", {}).get("kopf.zalando.org/on_claim_create")- if not raw:- return None- try:- data = json.loads(raw)- except Exception:- return raw- retries = data.get("retries")- message = " ".join(str(data.get("message", "")).split())- parts = []- if retries is not None:- parts.append(f"retries={retries}")- if message:- parts.append(message)- return "; ".join(parts) or None---# Console helpers---def step(msg: str) -> None:- print(f"\n==> {msg}", flush=True)---def info(msg: str) -> None:- print(f" {msg}", flush=True)---def die(msg: str) -> None:- sys.exit(f"\nERROR: {msg}")---class TeeWriter:- def __init__(self, *streams) -> None:- self.streams = streams-- def write(self, data: str) -> int:- for stream in self.streams:- stream.write(data)- return len(data)-- def flush(self) -> None:- for stream in self.streams:- stream.flush()-- def isatty(self) -> bool:- return any(getattr(stream, "isatty", lambda: False)() for stream in self.streams)---def configure_logging(log_file: str | None) -> None:- if not log_file:- return- log_path = os.path.abspath(log_file)- os.makedirs(os.path.dirname(log_path), exist_ok=True)- log_stream = open(log_path, "a", encoding="utf-8", buffering=1)- sys.stdout = TeeWriter(sys.stdout, log_stream)- sys.stderr = TeeWriter(sys.stderr, log_stream)- info(f"logging to {log_path}")---# Pool / claim lifecycle (mirrors create_pool_and_list_tools.py)---def create_namespace(http: httpx.Client, name: str) -> None:- """Create the per-user namespace via the Capsule-backed SPA endpoint.-- Pool name == namespace name (1:1). Going through /api/namespaces is what- makes Capsule stamp tenant ownership + RBAC, so the impersonated pool create- below is allowed. 409 just means we are reusing an earlier run's namespace.- """- r = http.post("/api/namespaces", json={"name": name})- if r.status_code == 409:- info(f"namespace {name!r} already exists — reusing it")- return- if r.status_code == 403:- die("403 creating namespace — namespaces/pools/claims need a per-USER key "- "(client id 'ukey-…', from POST /api/user-keys).")- r.raise_for_status()- info(f"namespace {name!r} created")---def delete_namespace(http: httpx.Client, name: str) -> None:- r = http.delete(f"/api/namespaces/{name}")- if r.status_code in (200, 202, 204, 404):- info(f"namespace {name!r} delete requested (HTTP {r.status_code})")- return- if r.status_code == 403:- die("403 deleting namespace — the user key cannot replace this pool namespace.")- r.raise_for_status()---def recreate_namespace(get_http: Callable[[], httpx.Client], name: str, poll: float) -> None:- delete_namespace(get_http(), name)- while True:- r = get_http().post("/api/namespaces", json={"name": name})- if r.status_code == 409:- info(f"namespace {name!r} still terminating — waiting to recreate …")- time.sleep(poll)- continue- if r.status_code == 403:- die("403 creating namespace during replacement — namespaces/pools/claims need a per-USER key.")- r.raise_for_status()- info(f"namespace {name!r} recreated")- return---def desired_template_spec(- *,- image: str,- cpu: int,- ram: str,- firmware: str,- readiness_port: int | None,- services: tuple[ServiceSpec, ...],-) -> dict:- """OSGymSandboxTemplate.spec — the VM shape, including the per-sandbox- Services (each becomes "<sandbox>-<name>", port 80 -> targetPort)."""- vm_template: dict = {- "containerDiskImage": image,- "imagePullSecret": "ecr-credentials",- "cpuCores": cpu,- "memory": ram,- "services": [{"name": s.service, "targetPort": s.port, "protocol": "TCP"} for s in services],- }- # Match the SPA/operator: only send firmware when it differs from the bios default.- if firmware != "bios":- vm_template["firmware"] = firmware- if readiness_port:- vm_template["probes"] = {"readinessProbe": {"tcpSocket": {"port": readiness_port}}}- return {"vmTemplate": vm_template}---def desired_warm_pool_spec(*, pool: str, replicas: int) -> dict:- """OSGymSandboxWarmPool.spec — how many sandboxes to keep warm, and which- template to stamp them from."""- return {"replicas": replicas, "sandboxTemplateRef": {"name": f"{pool}-template"}}---def _json_canonical(value: dict) -> str:- return json.dumps(value, sort_keys=True, separators=(",", ":"))---def _flatten_json(value, prefix: str = "") -> dict[str, str]:- flat: dict[str, str] = {}- if isinstance(value, dict):- for key in sorted(value):- child = f"{prefix}.{key}" if prefix else str(key)- flat.update(_flatten_json(value[key], child))- if not value and prefix:- flat[prefix] = "{}"- elif isinstance(value, list):- for idx, item in enumerate(value):- child = f"{prefix}[{idx}]"- flat.update(_flatten_json(item, child))- if not value and prefix:- flat[prefix] = "[]"- else:- flat[prefix] = json.dumps(value, sort_keys=True)- return flat---def log_pool_spec_diff(current_spec: dict, desired_spec: dict, what: str = "pool") -> None:- current_flat = _flatten_json(current_spec, "spec")- desired_flat = _flatten_json(desired_spec, "spec")- keys = sorted(set(current_flat) | set(desired_flat))- diffs = []- for key in keys:- current_value = current_flat.get(key, "<missing>")- desired_value = desired_flat.get(key, "<missing>")- if current_value == desired_value:- continue- diffs.append((key, current_value, desired_value))- if not diffs:- info(f"{what} spec diff: none")- return- info(f"{what} spec diff: {len(diffs)} field(s) differ")- for key, current_value, desired_value in diffs:- info(f" {key}: current={current_value} desired={desired_value}")---def create_pool(- get_http: Callable[[], httpx.Client],- *,- pool: str,- image: str,- cpu: int,- ram: str,- firmware: str,- replicas: int,- readiness_port: int | None,- mcp_servers: tuple[McpServerSpec, ...],- extra_services: tuple[ServiceSpec, ...],- poll: float,- allow_replace: bool = True,-) -> None:- """Create the pool's two native CRs: the OSGymSandboxTemplate- ``<pool>-template`` (VM shape + MCP/auxiliary services) and the- OSGymSandboxWarmPool ``<pool>`` that warms sandboxes from it.-- Each service becomes a per-sandbox Service ``<sandbox>-<name>`` (port 80 ->- targetPort). The MCP services are used by the agent; auxiliary services such- as noVNC are exposed for debugging but are not opened as MCP sessions.-- If either CR already exists with a different spec we replace the whole pool- namespace — simpler and more robust than patching two objects in place.- """- tmpl = f"{pool}-template"- template_spec = desired_template_spec(- image=image,- cpu=cpu,- ram=ram,- firmware=firmware,- readiness_port=readiness_port,- services=pool_services(mcp_servers, extra_services),- )- warm_pool_spec = desired_warm_pool_spec(pool=pool, replicas=replicas)-- existing_template = post_cr(- get_http, template_url(pool), f"template {tmpl!r}",- {- "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",- "kind": "OSGymSandboxTemplate",- "metadata": {"namespace": pool, "name": tmpl, "labels": {"cua.ai/pool": pool}},- "spec": template_spec,- },- )- existing_warm_pool = post_cr(- get_http, warmpool_url(pool), f"warm pool {pool!r}",- {- "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}",- "kind": "OSGymSandboxWarmPool",- "metadata": {"namespace": pool, "name": pool, "labels": {"cua.ai/pool": pool}},- "spec": warm_pool_spec,- },- )-- drifted = False- for existing, desired, what in (- (existing_template, template_spec, f"template {tmpl!r}"),- (existing_warm_pool, warm_pool_spec, f"warm pool {pool!r}"),- ):- if existing is None:- info(f"{what} created")- continue- log_pool_spec_diff(existing, desired, what)- if existing == desired:- info(f"{what} already exists — reusing it (spec unchanged)")- else:- drifted = True-- if drifted:- if not allow_replace:- die(f"pool {pool!r} still differs from desired state after replacement attempt")- info(f"pool {pool!r} differs from the desired spec — replacing pool namespace")- recreate_namespace(get_http, pool, poll)- return create_pool(- get_http,- pool=pool,- image=image,- cpu=cpu,- ram=ram,- firmware=firmware,- replicas=replicas,- readiness_port=readiness_port,- mcp_servers=mcp_servers,- extra_services=extra_services,- poll=poll,- allow_replace=False,- )-- info(f"image: {image}")- info(f"size: {cpu} vCPU / {ram} / replicas={replicas} / firmware={firmware}")- for s in mcp_servers:- info(f"service: {s.service:<14} -> targetPort {s.port} (MCP at {s.mcp_path}, health {s.health})")- for s in extra_services:- info(f"service: {s.service:<14} -> targetPort {s.port} (auxiliary {s.label})")- info(f"readiness: {'disabled' if not readiness_port else f'tcpSocket :{readiness_port}'}")---def post_cr(- get_http: Callable[[], httpx.Client], collection_url: str, what: str, body: dict-) -> dict | None:- """POST one CR. Returns None when it was created, or the existing object's- spec on 409 so the caller can decide what to do about the drift."""- r = get_http().post(collection_url, json=body)- if r.status_code == 409:- current = get_http().get(f"{collection_url}/{body['metadata']['name']}")- current.raise_for_status()- return current.json().get("spec") or {}- if r.status_code == 403:- die(f"403 creating {what} — /api/k8s needs a per-USER key ('ukey-…', POST /api/user-keys).")- r.raise_for_status()- return None---def pool_counts(get_http: Callable[[], httpx.Client], pool: str) -> tuple[int, int]:- """(replicas, readyReplicas) from the warm pool status, best-effort."""- try:- st = pool_status(get_http(), pool)- return int(st.get("replicas", 0)), int(st.get("readyReplicas", 0))- except Exception:- return 0, 0---def wait_pool_warm(- get_http: Callable[[], httpx.Client],- pool: str,- timeout: float,- poll: float,- *,- replicas: int,- min_available: int,-) -> None:- """Wait until the warm pool reports ready VMs, so the first claim binds fast.-- A cold pool has to pull the multi-GB containerDisk, boot the guest, and bring- the readiness-port service up before a Sandbox is adoptable. Letting the pool- warm first keeps the claim's bindDeadline from burning down during the pull.- """- start = time.monotonic()- deadline = start + timeout- last_summary = ""- while True:- try:- st = pool_status(get_http(), pool)- total = int(st.get("replicas", 0))- ready = int(st.get("readyReplicas", 0))- summary = pool_summary(st)- except Exception:- total, ready = 0, 0- summary = "ready=0/0"- if total >= replicas and ready >= min_available:- info(f"pool warm: {ready}/{total} VM(s) ready")- return- if summary != last_summary:- info(f"pool detail: {summary}")- last_summary = summary- if timeout > 0 and time.monotonic() > deadline:- info(f"timed out after {timeout:.0f}s waiting for a warm VM ({ready}/{total} ready)")- info("continuing anyway — the claim may still bind once the VM finishes pulling/booting")- return- elapsed = int(time.monotonic() - start)- info(f"[{elapsed:4d}s] pool: {ready}/{total} VMs ready (target total={replicas}, "- f"target ready={min_available}) — warming (image pull + guest boot + service on the readiness port) …")- time.sleep(poll)---def create_claim(http: httpx.Client, pool: str, name: str, bind_deadline: int) -> None:- spec: dict = {"sandboxTemplateRef": {"name": f"{pool}-template"}}- if bind_deadline:- spec["bindDeadline"] = bind_deadline- r = http.post(claims_url(pool), json={- "apiVersion": f"{EXT_GROUP}/{EXT_VERSION}", "kind": "OSGymSandboxClaim",- "metadata": {"name": name}, "spec": spec})- if r.status_code == 403:- die("403 creating claim — per-pool keys have no K8s identity. Use a per-USER key ('ukey-…').")- r.raise_for_status()- info(f"claim {name!r} created")---def wait_bound(get_http: Callable[[], httpx.Client], pool: str, name: str, timeout: float, poll: float) -> str:- """Poll the claim until status.phase == Bound; return the sandbox name."""- start = time.monotonic()- deadline = start + timeout- last_claim = ""- last_pool = ""- last_operator = ""- while True:- claim = claim_obj(get_http(), pool, name)- status = claim.get("status") or {}- phase = status.get("phase", "Pending")- sandbox = (status.get("sandbox") or {}).get("name")- if phase == "Bound" and sandbox:- return sandbox- if phase == "Failed":- die(f"claim {name} failed: {status}")- if timeout > 0 and time.monotonic() > deadline:- die(f"timed out after {timeout:.0f}s waiting for claim {name} to bind (phase={phase})")- claim_line = claim_summary(status)- if claim_line != last_claim:- info(f"claim detail: {claim_line}")- last_claim = claim_line- operator_line = claim_operator_progress(claim)- if operator_line and operator_line != last_operator:- info(f"claim operator: {operator_line}")- last_operator = operator_line- try:- pst = pool_status(get_http(), pool)- total = int(pst.get("replicas", 0))- ready = int(pst.get("readyReplicas", 0))- pool_line = pool_summary(pst)- except Exception:- total, ready = 0, 0- pool_line = "ready=0/0"- if pool_line != last_pool:- info(f"pool detail: {pool_line}")- last_pool = pool_line- elapsed = int(time.monotonic() - start)- info(f"[{elapsed:4d}s] claim={phase} pool={ready}/{total} VMs ready …")- time.sleep(poll)---def wait_service_ready(get_http: Callable[[], httpx.Client], url: str, timeout: float, poll: float) -> None:- """GET url until the in-guest service answers (not a proxy 502/503/504)."""- start = time.monotonic()- deadline = start + timeout- while True:- try:- resp = get_http().get(url, timeout=15.0)- except httpx.HTTPError as e:- resp, reason = None, type(e).__name__- else:- reason = f"HTTP {resp.status_code}"- if resp is not None and resp.status_code not in (502, 503, 504):- info(f"service responding ({reason})")- return- if timeout > 0 and time.monotonic() > deadline:- die(f"timed out after {timeout:.0f}s waiting for the in-guest service (last: {reason})")- elapsed = int(time.monotonic() - start)- info(f"[{elapsed:4d}s] {reason} — guest still booting …")- time.sleep(poll)---# MCP (Streamable HTTP) multi-server---def _sse_json(resp: httpx.Response) -> dict:- """Streamable HTTP replies are SSE ('event: message\\ndata: {...}'); the JSON- is on the data: line. Fall back to the raw body for plain JSON."""- line = next((ln[6:] for ln in resp.text.splitlines() if ln.startswith("data: ")), resp.text)- return json.loads(line)---class McpConn:- """A live MCP session against one server of the bound sandbox."""-- spec: McpServerSpec- svc_base: str # /api/svc/{ns}/{sandbox}-{service}- session_id: str | None- tools: list[dict] # this server's raw tools/list-- @property- def url(self) -> str:- return f"{self.svc_base}{self.spec.mcp_path}"-- def _headers(self) -> dict:- h = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}- if self.session_id:- h["Mcp-Session-Id"] = self.session_id- return h---def mcp_open(http: httpx.Client, spec: McpServerSpec, svc_base: str, client_name: str) -> McpConn:- """initialize -> notifications/initialized -> tools/list for one server."""- url = f"{svc_base}{spec.mcp_path}"- headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}- init = http.post(url, headers=headers, timeout=30.0, json={- "jsonrpc": "2.0", "id": 1, "method": "initialize",- "params": {"protocolVersion": "2025-03-26", "capabilities": {},- "clientInfo": {"name": client_name, "version": "0.1.0"}}})- init.raise_for_status()- sid = init.headers.get("mcp-session-id")- if sid:- headers["Mcp-Session-Id"] = sid- http.post(url, headers=headers, timeout=30.0, json={"jsonrpc": "2.0", "method": "notifications/initialized"})- r = http.post(url, headers=headers, timeout=30.0, json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"})- r.raise_for_status()- tools = _sse_json(r).get("result", {}).get("tools", [])- return McpConn(spec=spec, svc_base=svc_base, session_id=sid, tools=tools)---_BEDROCK_IMAGE_FORMATS = {"png", "jpeg", "gif", "webp"}---def mcp_call(http: httpx.Client, conn: McpConn, name: str, arguments: dict) -> dict:- """Dispatch one tools/call on a specific server. Returns text + inline images- (decoded to raw bytes + Bedrock image format) + isError. Raises on a- transport/proxy error so the caller can surface it."""- r = http.post(conn.url, headers=conn._headers(), timeout=600.0, json={- "jsonrpc": "2.0", "id": 1, "method": "tools/call",- "params": {"name": name, "arguments": arguments}})- if r.status_code in (502, 503, 504):- raise httpx.HTTPError(f"proxy {r.status_code}")- r.raise_for_status()- result = _sse_json(r).get("result", {})- text_parts, images = [], []- for block in result.get("content", []):- if block.get("type") == "text":- text_parts.append(block.get("text", ""))- elif block.get("type") == "image":- mime = block.get("mimeType", "image/png")- fmt = mime.split("/")[-1].lower()- fmt = "jpeg" if fmt == "jpg" else fmt- if fmt not in _BEDROCK_IMAGE_FORMATS:- fmt = "png"- images.append({"format": fmt, "bytes": base64.b64decode(block["data"])})- return {"text": "\n".join(text_parts), "images": images, "is_error": bool(result.get("isError"))}---def _sanitize(label: str) -> str:- return re.sub(r"[^a-zA-Z0-9_-]", "-", label)---def build_tool_registry(conns: list[McpConn]) -> tuple[list[dict], dict[str, tuple[McpConn, str]]]:- """Union every server's tools into one Bedrock Converse toolConfig tool list,- namespacing names as ``<server>__<tool>`` so two servers can expose the same- tool without colliding. Returns (llm_tools, registry) where registry maps the- namespaced name back to (connection, original tool name) for dispatch."""- llm_tools: list[dict] = []- registry: dict[str, tuple[McpConn, str]] = {}- for conn in conns:- prefix = _sanitize(conn.spec.label)- for t in conn.tools:- orig = t["name"]- llm_name = f"{prefix}__{orig}"[:64] # Bedrock caps tool names at 64- # Extremely unlikely, but keep names unique if truncation collides.- while llm_name in registry:- llm_name = f"{llm_name[:60]}_{len(registry)}"- registry[llm_name] = (conn, orig)- desc = f"[{conn.spec.label}] " + " ".join((t.get("description") or "").split())- schema = t.get("inputSchema") or {"type": "object", "properties": {}}- llm_tools.append({"toolSpec": {- "name": llm_name,- "description": desc or llm_name,- "inputSchema": {"json": schema}}})- return llm_tools, registry---def _msg_has_image(m: dict) -> bool:- return isinstance(m.get("content"), list) and any(- "toolResult" in b and any("image" in c for c in b["toolResult"].get("content", []))- for b in m["content"])---def _prune_images(messages: list[dict], keep: int) -> None:- """Drop all but the last `keep` screenshots — image tokens dominate a- computer-use trajectory's cost and stale frames mislead the model. Images live- inside toolResult content blocks; replace each with a text placeholder so the- toolResult stays valid (Converse requires non-empty toolResult content)."""- idx = [i for i, m in enumerate(messages) if _msg_has_image(m)]- for i in (idx[:-keep] if keep else idx):- for b in messages[i]["content"]:- tr = b.get("toolResult")- if not tr:- continue- tr["content"] = [- {"text": "[older screenshot dropped from context]"} if "image" in c else c- for c in tr.get("content", [])]---# The agent loop (mini-swe-agent, multi-MCP)---def _converse_text(content: list[dict]) -> str:- return "\n".join(b["text"] for b in content if "text" in b).strip()---def run_agent(http_get: Callable[[], httpx.Client], conns: list[McpConn], bedrock, *,- task: str, model_id: str, max_steps: int, keep_images: int) -> str:- """Canonical mini-swe-agent loop over the UNION of every server's tools, driven- by the Bedrock Converse API (one tool turn per step)."""- llm_tools, registry = build_tool_registry(conns)- info(f"action space: {len(llm_tools)} tools across {len(conns)} MCP server(s)")- for conn in conns:- names = ", ".join(sorted(t["name"] for t in conn.tools)) or "(none)"- info(f" {conn.spec.label}: {names}")-- system = [{"text": SYSTEM}]- tool_config = {"tools": llm_tools}- messages: list[dict] = [{"role": "user", "content": [{"text": task}]}]- for n in range(1, max_steps + 1):- resp = bedrock.converse(- modelId=model_id,- system=system,- messages=messages,- toolConfig=tool_config,- inferenceConfig={"temperature": 0.0, "maxTokens": MAX_OUTPUT_TOKENS},- )- out = resp["output"]["message"]- messages.append(out)- tool_uses = [b["toolUse"] for b in out["content"] if "toolUse" in b]- if not tool_uses:- step(f"agent finished after {n - 1} action(s)")- final = _converse_text(out["content"])- print(final or "(no final message)", flush=True)- return final or "done"-- result_blocks: list[dict] = []- for tu in tool_uses:- llm_name, tuid = tu["name"], tu["toolUseId"]- tool_args = tu.get("input") or {}- entry = registry.get(llm_name)- if entry is None:- result_blocks.append({"toolResult": {"toolUseId": tuid,- "content": [{"text": f"unknown tool {llm_name!r}"}], "status": "error"}})- continue- conn, orig = entry- info(f"[step {n}] {conn.spec.label} -> {orig}({json.dumps(tool_args)[:120]})")- try:- res = mcp_call(http_get(), conn, orig, tool_args)- except httpx.HTTPError as e:- result_blocks.append({"toolResult": {"toolUseId": tuid,- "content": [{"text": f"tool transport error: {e}"}], "status": "error"}})- continue- content: list[dict] = []- if res["text"]:- content.append({"text": res["text"]})- for img in res["images"]:- content.append({"image": {"format": img["format"], "source": {"bytes": img["bytes"]}}})- if not content:- content.append({"text": "(no output)"})- result_blocks.append({"toolResult": {"toolUseId": tuid, "content": content,- "status": "error" if res["is_error"] else "success"}})- messages.append({"role": "user", "content": result_blocks})- _prune_images(messages, keep_images)- return "max_steps_exceeded"---# Main---def main() -> None:- pre = argparse.ArgumentParser(add_help=False)- pre.add_argument("--config")- pre_args, remaining = pre.parse_known_args()- manifest = load_run_manifest(pre_args.config)- mcp_servers, extra_services = load_pool_services(manifest)-- p = argparse.ArgumentParser(- description=f"Provision a {OS_NAME} double-MCP pool on run.cua.ai, claim a sandbox, "- "and run mini-swe-agent against BOTH its MCP servers.",- formatter_class=argparse.ArgumentDefaultsHelpFormatter,- parents=[pre],- )- cfg_name = manifest_get(manifest, "metadata", "name")- cfg_task = manifest_get(manifest, "spec", "agent", "task")- p.add_argument("--name", required=cfg_name is None, default=cfg_name,- help="pool name (also the namespace; lowercase/dashes). Reuse the same name across retries "- "to keep the same provisioning pool warm.")- p.add_argument("--task", required=cfg_task is None, default=cfg_task, help="the task prompt for the agent")- p.add_argument("--client-id", default=os.environ.get("CUA_CLIENT_ID"),- help="OAuth client id (per-user key 'ukey-…'); env CUA_CLIENT_ID")- p.add_argument("--client-secret", default=os.environ.get("CUA_CLIENT_SECRET"),- help="OAuth client secret; env CUA_CLIENT_SECRET")- p.add_argument("--model", default=manifest_get(manifest, "spec", "agent", "model", default=default_model()) or default_model(),- help="Bedrock model id (a leading 'bedrock/' is stripped). Uses AGENT_MODEL if set, "- f"else {DEFAULT_BEDROCK_MODEL}.")- p.add_argument("--aws-region", default=None,- help="AWS region for the Bedrock client. Defaults to AWS_REGION/AWS_DEFAULT_REGION "- "(or your ~/.aws config). Credentials always come from the AWS env / default chain.")- p.add_argument("--image", default=manifest_get(manifest, "spec", "pool", "image"), help="workspace containerDisk image")- p.add_argument("--cpu", type=int, default=manifest_get(manifest, "spec", "pool", "cpu"), help="vCPU cores per VM")- p.add_argument("--ram", default=manifest_get(manifest, "spec", "pool", "ram"), help="memory per VM (K8s quantity)")- p.add_argument("--firmware", choices=FIRMWARE_CHOICES,- default=manifest_get(manifest, "spec", "pool", "firmware", default=DEFAULT_FIRMWARE) or DEFAULT_FIRMWARE,- help="VM firmware. 'efi' for GPT/UEFI-only images (Windows desktop-workspace); "- "'bios' (KubeVirt default) for the Linux workspace images.")- p.add_argument("--replicas", type=int, default=manifest_get(manifest, "spec", "pool", "replicas"), help="pre-warmed VMs the pool keeps")- p.add_argument("--min-available", type=int, default=manifest_get(manifest, "spec", "pool", "minAvailable"),- help="minimum warm/available VMs to wait for before claiming. Set to 2+ to keep a small surplus warm.")- p.add_argument("--readiness-port", type=int, default=manifest_get(manifest, "spec", "pool", "readinessPort"),- help="TCP port used for readiness probing. Set to 0 to disable readiness probes in the pool template.")- p.add_argument("--max-steps", type=int, default=manifest_get(manifest, "spec", "agent", "maxSteps"), help="agent step budget")- p.add_argument("--keep-images", type=int, default=manifest_get(manifest, "spec", "agent", "keepImages"), help="screenshots kept in LLM context")- p.add_argument("--token-url", default=os.environ.get("CUA_TOKEN_URL", DEFAULT_TOKEN_URL))- p.add_argument("--base-url", default=os.environ.get("CUA_BASE_URL", DEFAULT_BASE_URL))- p.add_argument("--claim-name", default=manifest_get(manifest, "spec", "claim", "name"), help="claim name (default: claim-<random>)")- p.add_argument("--warm-timeout", type=float, default=manifest_get(manifest, "spec", "rollout", "warmTimeout"),- help="seconds to wait for warm pool capacity. 0 waits indefinitely.")- p.add_argument("--bind-deadline", type=int, default=manifest_get(manifest, "spec", "claim", "bindDeadline"))- p.add_argument("--bind-timeout", type=float, default=manifest_get(manifest, "spec", "rollout", "bindTimeout"),- help="seconds to wait for claim binding. 0 waits indefinitely.")- p.add_argument("--ready-timeout", type=float, default=manifest_get(manifest, "spec", "rollout", "readyTimeout"),- help="seconds to wait for each MCP server to answer after binding. 0 waits indefinitely.")- p.add_argument("--poll-interval", type=float, default=manifest_get(manifest, "spec", "rollout", "pollInterval"))- p.add_argument("--log-file", default=None,- help="append all console output to this file while the run is active")- p.add_argument("--keep", action="store_true", default=manifest_get(manifest, "spec", "teardown", "keepPool"),- help="skip teardown — leave the pool/namespace/claim up for debugging or for reuse on the next retry")- p.add_argument("--delete-pool", action="store_true", default=manifest_get(manifest, "spec", "teardown", "deletePool"),- help="on exit also delete the pool AND namespace (full cleanup)")- args = p.parse_args(remaining)- args.name = resolve_name_template(args.name)- args.claim_name = resolve_name_template(args.claim_name)- configure_logging(args.log_file)-- if not args.client_id or not args.client_secret:- die("set --client-id/--client-secret or CUA_CLIENT_ID/CUA_CLIENT_SECRET "- "(per-user key from POST /api/user-keys)")- if args.client_id.startswith("key-"):- die("that looks like a per-POOL key ('key-…'), which has no K8s identity. "- "Creating namespaces/pools/claims needs a per-USER key ('ukey-…').")-- model_id = bedrock_model_id(args.model)- bedrock = make_bedrock_client(args)-- pool = args.name- claim_name = args.claim_name or f"claim-{uuid.uuid4().hex[:8]}"-- step(f"Authenticating to {args.base_url} (client {args.client_id})")- client = TrainClient.from_key(token_url=args.token_url, client_id=args.client_id,- client_secret=args.client_secret, base_url=args.base_url)- http = client.get_httpx_client # call per request — re-mints the bearer near expiry- info("token acquired")-- step(f"Creating namespace {pool!r}")- create_namespace(http(), pool)-- step(f"Creating {OS_NAME} double-MCP pool {pool!r}")- readiness_port = args.readiness_port or None- create_pool(- http,- pool=pool,- image=args.image,- cpu=args.cpu,- ram=args.ram,- firmware=args.firmware,- replicas=args.replicas,- readiness_port=readiness_port,- mcp_servers=mcp_servers,- extra_services=extra_services,- poll=args.poll_interval,- )-- step(f"Claiming a sandbox from {pool!r} (claim {claim_name!r})")-- # The claim is ALWAYS released — on success, on error, or on Ctrl-C — so an- # interrupted or failed run never leaks a claimed VM. --keep only preserves the- # pool/namespace, NOT the claim. The `released` flag makes release idempotent- # across the SIGINT handler and the finally block.- released = False-- def release_claim() -> None:- nonlocal released- if released:- return- released = True- step(f"Releasing claim {claim_name!r}")- try:- r = http().delete(claims_url(pool, claim_name))- info(f"released (HTTP {r.status_code}) — the VM hard-resets and rejoins the pool")- except httpx.HTTPError as e:- info(f"could not release claim: {type(e).__name__}: {e}")-- def _sigint_handler(signum, frame):- print(flush=True)- step("Interrupted (Ctrl-C) — releasing claim before exit")- release_claim()- sys.exit(130)-- signal.signal(signal.SIGINT, _sigint_handler)-- try:- # Inside the try so the finally still releases even if create/bind fails midway.- create_claim(http(), pool, claim_name, args.bind_deadline)- step("Waiting for the claim to bind to the warm sandbox")- sandbox = wait_bound(http, pool, claim_name, args.bind_timeout, args.poll_interval)- info(f"bound to sandbox {sandbox!r}")-- # Connect to EVERY MCP server the double image exposes. Best-effort for- # dev: a server that fails to connect is logged and skipped rather than- # aborting the whole run, so a partial action space is still usable.- conns: list[McpConn] = []- for spec in mcp_servers:- svc_base = f"/api/svc/{pool}/{sandbox}-{spec.service}"- step(f"Waiting for the {spec.label} server (svc {sandbox}-{spec.service}, health {spec.health})")- # wait_service_ready(http, f"{svc_base}{spec.health}", args.ready_timeout, args.poll_interval)- step(f"Opening MCP session: {spec.label} at {svc_base}{spec.mcp_path}")- try:- conn = mcp_open(http(), spec, svc_base, client_name=f"mini-swe-multi-mcp-{OS_NAME}")- except Exception as e:- info(f"could not connect to {spec.label} MCP server: {type(e).__name__}: {e} — skipping (best effort)")- continue- info(f"session {conn.session_id or '(stateless)'} — {len(conn.tools)} tool(s)")- conns.append(conn)-- if not conns:- die("no MCP servers connected — cannot run the agent")-- step(f"Running mini-swe-agent (bedrock {model_id}) against {len(conns)} MCP server(s)")- info(f"task: {args.task}")- result = run_agent(http, conns, bedrock, task=args.task, model_id=model_id,- max_steps=args.max_steps, keep_images=args.keep_images)- step(f"Agent result: {result[:200]}")- finally:- print(flush=True)- # Always release the claim — success, error, or interrupt — no matter what.- release_claim()- if args.keep:- step(f"Keeping pool/namespace {pool!r} — skipping pool teardown (--keep)")- info(f"claim again: POST {claims_url(pool)} (spec.sandboxTemplateRef.name={pool}-template)")- info(f"delete it: DELETE {warmpool_url(pool, pool)}, "- f"DELETE {template_url(pool, f'{pool}-template')} "- f"(and DELETE /api/namespaces/{pool})")- elif args.delete_pool:- step(f"Tearing down pool {pool!r} (warm pool + template + namespace)")- for what, url in ((f"warm pool {pool!r}", warmpool_url(pool, pool)),- (f"template {pool}-template", template_url(pool, f"{pool}-template")),- (f"namespace {pool!r}", f"/api/namespaces/{pool}")):- try:- r = http().delete(url)- info(f"deleted {what} (HTTP {r.status_code})")- except httpx.HTTPError as e:- info(f"could not delete {what}: {type(e).__name__}: {e}")- else:- step(f"Pool {pool!r} is live")- info(f"claim again: POST {claims_url(pool)} (spec.sandboxTemplateRef.name={pool}-template)")- info(f"delete it: DELETE {warmpool_url(pool, pool)}, "- f"DELETE {template_url(pool, f'{pool}-template')} "- f"(and DELETE /api/namespaces/{pool})")---if __name__ == "__main__":- main()diff --git a/libs/fleet/python-sdk/examples/windows-mini-swe.yaml b/libs/fleet/python-sdk/examples/windows-mini-swe.yamldeleted file mode 100644index 3f55ee71c7..0000000000--- a/libs/fleet/python-sdk/examples/windows-mini-swe.yaml+++ /dev/null@@ -1,54 +0,0 @@-apiVersion: cua.ai/v1alpha1-kind: AgentWindowsDoubleMCPRun-metadata:- name: windows-mini-swe--spec:- pool:- image: 296062593712.dkr.ecr.us-west-2.amazonaws.com/cua-server-windows:latest- cpu: 4- ram: 4Gi- firmware: efi # GPT/UEFI-only Windows image; operator also enables Hyper-V enlightenments for efi- replicas: 2- minAvailable: 1- readinessPort: 8000- services:- - type: mcp- label: computer-server- service: server- port: 8000- mcpPath: /mcp- health: /status- - type: mcp- label: cua-driver- service: mcp- port: 3000- mcpPath: /mcp- health: /healthz- - type: auxiliary- label: novnc- service: novnc- port: 6080- claim:- bindDeadline: 600- agent:- model: us.anthropic.claude-sonnet-4-6- task: >-- Launch Microsoft Edge in this Windows environment, open- https://news.yahoo.com/, inspect the Yahoo News front page, and then- report the visible page contents in a concise final message. Do all work- inside this remote Windows sandbox, not on the local machine.- maxSteps: 60- keepImages: 2- rollout:- templateTimeout: 120- warmTimeout: 0- bindTimeout: 0- readyTimeout: 0- pollInterval: 10- teardown:- # keepPool:false so `--delete-pool` actually tears down (the script's- # if-keep/elif-delete precedence ignores --delete-pool when keepPool is- # true). With no teardown flags the pool is still left live for reuse.- keepPool: false- deletePool: falsediff --git a/libs/fleet/python-sdk/openapi3.yaml b/libs/fleet/python-sdk/openapi3.yamldeleted file mode 100644index b4056a5e26..0000000000--- a/libs/fleet/python-sdk/openapi3.yaml+++ /dev/null@@ -1,1246 +0,0 @@-openapi: 3.0.3-info:- title: Cyclops CS Backend API- description: "Backend sidecar for the cyclops-cs SPA — Keycloak-authenticated key\n\- management, authenticated reverse proxies (gateway / k8s / orch), and\nthe in-process\- \ OSGym batch driver.\n\nThe batch driver exposes two pool-scoped surfaces:\n\- - `/api/batch/{pool}/...` — submit, poll, cancel a single batch by ID\n- `/api/label/{pool}/{label}/...`\- \ — aggregate operations across batches\n in `{pool}` that share a `name` field\- \ (the \"label\")\n"- version: '0.2'- contact:- name: API Support- url: https://cua.ai/support- email: [email protected]-servers:-- url: https://run.cua.ai- description: Production-security:-- BearerAuth: []-paths:- /healthz:- get:- summary: Liveness/readiness probe- operationId: healthz- tags:- - health- security: []- responses:- '200':- description: OK- content:- application/json:- schema:- $ref: '#/components/schemas/HealthResponse'- /api/keys:- get:- summary: List the calling user's API keys- operationId: listKeys- tags:- - keys- responses:- '200':- description: OK- content:- application/json:- schema:- $ref: '#/components/schemas/ListKeysResponse'- '401':- $ref: '#/components/responses/Unauthorized'- post:- summary: Create a new API key- operationId: createKey- description: Creates a Keycloak service-account client owned by the calling- user. The returned `client_secret` is shown exactly once.- tags:- - keys- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/CreateKeyRequest'- responses:- '201':- description: Created- content:- application/json:- schema:- $ref: '#/components/schemas/CreateKeyResponse'- '400':- $ref: '#/components/responses/BadRequest'- '401':- $ref: '#/components/responses/Unauthorized'- '403':- $ref: '#/components/responses/Forbidden'- /api/keys/{id}:- delete:- summary: Revoke an API key by Keycloak client UUID- operationId: deleteKey- tags:- - keys- parameters:- - name: id- in: path- required: true- description: Keycloak client UUID- schema:- type: string- responses:- '204':- description: No Content- '401':- $ref: '#/components/responses/Unauthorized'- '403':- $ref: '#/components/responses/Forbidden'- /api/batch/{pool}/submit:- post:- summary: Submit a batch of rollouts- operationId: submitBatch- description: 'Asynchronously queues a batch of OSGym rollouts under `{pool}`.-- Returns immediately with a `batch_id`; poll-- `/api/batch/{pool}/{id}/status` for progress and-- `/api/batch/{pool}/{id}/results` for the final payload.--- The pool is bound by the URL path; any `pool_name` in the body must-- match the URL pool or the request is rejected with 400.-- '- tags:- - batch- parameters:- - name: pool- in: path- required: true- description: Pool name (DNS-1123 label)- schema:- type: string- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/BatchSubmitRequest'- responses:- '202':- description: Accepted- content:- application/json:- schema:- $ref: '#/components/schemas/BatchSubmitResponse'- '400':- $ref: '#/components/responses/BadRequest'- '401':- $ref: '#/components/responses/Unauthorized'- /api/batch/{pool}/lanes:- post:- summary: Acquire warm VM lanes- operationId: acquireLanes- description: 'Explicitly provisions N warm VMs ("lanes") and returns their vm_ids.- Pass each as `RunConfig.vm_id` to run actions on it (state persists across- batches), and `DELETE` this route to release them. All-or-nothing: a partial- acquisition is rolled back, and 503 is returned if the pool can''t supply- every lane in time.'- tags:- - batch- parameters:- - name: pool- in: path- required: true- description: Pool name- schema:- type: string- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/AcquireLanesRequest'- responses:- '200':- description: Lanes acquired- content:- application/json:- schema:- $ref: '#/components/schemas/AcquireLanesResponse'- '400':- $ref: '#/components/responses/BadRequest'- '401':- $ref: '#/components/responses/Unauthorized'- '503':- description: Pool could not supply the requested lanes- content:- application/json:- schema:- $ref: '#/components/schemas/ErrorResponse'- delete:- summary: Release warm VM lanes- operationId: releaseLanes- description: Shuts down the given VMs (lanes from `acquireLanes` or `vm_id`s- returned by a `keep_warm` batch). Best-effort and idempotent — unknown or- already-gone ids are ignored.- tags:- - batch- parameters:- - name: pool- in: path- required: true- description: Pool name- schema:- type: string- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/ReleaseLanesRequest'- responses:- '200':- description: Release accepted- content:- application/json:- schema:- $ref: '#/components/schemas/ReleaseLanesResponse'- '400':- $ref: '#/components/responses/BadRequest'- '401':- $ref: '#/components/responses/Unauthorized'- /api/batch/{pool}/{id}/status:- get:- summary: Poll batch progress- operationId: getBatchStatus- tags:- - batch- parameters:- - name: pool- in: path- required: true- description: Pool name- schema:- type: string- - name: id- in: path- required: true- description: Batch ID (UUID returned by submit)- schema:- type: string- responses:- '200':- description: OK- content:- application/json:- schema:- $ref: '#/components/schemas/BatchStatusResponse'- '401':- $ref: '#/components/responses/Unauthorized'- '404':- $ref: '#/components/responses/NotFound'- /api/batch/{pool}/{id}/results:- get:- summary: Final batch results- operationId: getBatchResults- description: 'Returns 200 with the full results once the batch is in a terminal-- status (completed/failed). While still running, returns 202 with a-- `message` field.-- '- tags:- - batch- parameters:- - name: pool- in: path- required: true- description: Pool name- schema:- type: string- - name: id- in: path- required: true- description: Batch ID- schema:- type: string- responses:- '200':- description: Completed — full results- content:- application/json:- schema:- $ref: '#/components/schemas/BatchResultsResponse'- '202':- description: Still running- content:- application/json:- schema:- $ref: '#/components/schemas/BatchInProgressResponse'- '401':- $ref: '#/components/responses/Unauthorized'- '404':- $ref: '#/components/responses/NotFound'- /api/batch/{pool}/{id}:- delete:- summary: Cancel a batch- operationId: cancelBatch- description: 'Hard-cancels the batch — aborts in-flight /reset and /step calls-- and stops dispatch. Idempotent on terminal batches. Returns 200-- with the final status.-- '- tags:- - batch- parameters:- - name: pool- in: path- required: true- description: Pool name- schema:- type: string- - name: id- in: path- required: true- description: Batch ID- schema:- type: string- responses:- '200':- description: OK- content:- application/json:- schema:- $ref: '#/components/schemas/CancelBatchResponse'- '401':- $ref: '#/components/responses/Unauthorized'- '404':- $ref: '#/components/responses/NotFound'- /api/label/{pool}/{label}/batch:- post:- summary: Submit a batch under a pool and label- operationId: submitLabelBatch- description: 'Same as `/api/batch/{pool}/submit` but pins the batch''s `name`-- field to the URL label, overriding any value in the body. The-- label is scoped to `{pool}`; aggregate routes under-- `/api/label/{pool}/{label}/*` only see batches submitted to the-- same pool.-- '- tags:- - label- parameters:- - name: pool- in: path- required: true- description: Pool name (DNS-1123 label)- schema:- type: string- - name: label- in: path- required: true- description: Batch label / name- schema:- type: string- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/BatchSubmitRequest'- responses:- '202':- description: Accepted- content:- application/json:- schema:- $ref: '#/components/schemas/BatchSubmitResponse'- '400':- $ref: '#/components/responses/BadRequest'- '401':- $ref: '#/components/responses/Unauthorized'- /api/label/{pool}/{label}/status:- get:- summary: Aggregate status for all batches under a pool+label- operationId: getLabelStatus- description: Aggregates only batches submitted under `{pool}`; batches with- the same label in other pools are invisible.- tags:- - label- parameters:- - name: pool- in: path- required: true- description: Pool name- schema:- type: string- - name: label- in: path- required: true- description: Batch label- schema:- type: string- responses:- '200':- description: OK- content:- application/json:- schema:- $ref: '#/components/schemas/LabelStatusResponse'- '401':- $ref: '#/components/responses/Unauthorized'- '404':- $ref: '#/components/responses/NotFound'- /api/label/{pool}/{label}/results:- get:- summary: Aggregate results for all batches under a pool+label- operationId: getLabelResults- description: 'Default mode returns 200 only once every matched batch is completed.-- Pass `?completed_only=true` to drain partial results (200 with the-- filtered subset; non-completed batches are visible via status).-- Aggregates only batches submitted under `{pool}`.-- '- tags:- - label- parameters:- - name: pool- in: path- required: true- description: Pool name- schema:- type: string- - name: label- in: path- required: true- description: Batch label- schema:- type: string- - name: completed_only- in: query- required: false- description: Return completed batches only (drain mode)- schema:- type: boolean- responses:- '200':- description: OK — all batches completed (or drain mode)- content:- application/json:- schema:- $ref: '#/components/schemas/LabelResultsResponse'- '202':- description: Still running (non-drain mode)- content:- application/json:- schema:- $ref: '#/components/schemas/LabelInProgressResponse'- '401':- $ref: '#/components/responses/Unauthorized'- '404':- $ref: '#/components/responses/NotFound'- /api/label/{pool}/{label}:- delete:- summary: Cancel every non-terminal batch under a label (scoped to pool)- operationId: cancelLabel- description: Cancels only batches submitted under `{pool}`; same label in other- pools is untouched.- tags:- - label- parameters:- - name: pool- in: path- required: true- description: Pool name- schema:- type: string- - name: label- in: path- required: true- description: Batch label- schema:- type: string- responses:- '200':- description: OK- content:- application/json:- schema:- $ref: '#/components/schemas/CancelLabelResponse'- '401':- $ref: '#/components/responses/Unauthorized'- '404':- $ref: '#/components/responses/NotFound'- /api/gateway/{pool}/lanes:- post:- summary: Create Lane- description: 'Create a lane: a fresh OSGymSandboxClaim bound to a Sandbox.--- The lane id is the stable handle the customer holds. The-- underlying claim CR''s name rotates on swap; the lane id does-- not. The initial bind is via the normal queue+CAS-PATCH flow,-- same as /reset.'- operationId: create_lane_lanes_post- requestBody:- content:- application/json:- schema:- $ref: '#/components/schemas/LaneCreateRequest'- required: true- responses:- '200':- description: Successful Response- content:- application/json:- schema:- $ref: '#/components/schemas/LaneResponse'- '503':- description: Bind timeout — warm pool exhausted- content:- application/json:- schema:- $ref: '#/components/schemas/LaneErrorResponse'- '422':- description: Validation Error- content:- application/json:- schema:- $ref: '#/components/schemas/HTTPValidationError'- parameters:- - name: pool- in: path- required: true- schema:- type: string- description: Pool name (DNS-1123 label)- tags:- - lanes- /api/gateway/{pool}/lanes/{lane_id}/swap:- post:- summary: Swap- description: 'New-first claim rotation for ``lane_id``.--- Calls into the pure protocol body in osgym/lane_swap.py with a-- K8s-backed SwapDeps. The lane keeps its bound VM if the swap-- bind times out (SwapAtomicity); the new vm_id is returned on-- success.'- operationId: swap_lanes__lane_id__swap_post- parameters:- - name: pool- in: path- required: true- schema:- type: string- description: Pool name (DNS-1123 label)- - name: lane_id- in: path- required: true- schema:- type: string- title: Lane Id- responses:- '200':- description: Successful Response- content:- application/json:- schema:- $ref: '#/components/schemas/LaneSwapResponse'- '404':- description: Lane not found- content:- application/json:- schema:- $ref: '#/components/schemas/LaneErrorResponse'- '503':- description: Swap bind timeout — old VM retained- content:- application/json:- schema:- $ref: '#/components/schemas/LaneErrorResponse'- '422':- description: Validation Error- content:- application/json:- schema:- $ref: '#/components/schemas/HTTPValidationError'- tags:- - lanes- /api/gateway/{pool}/lanes/{lane_id}:- delete:- summary: Delete Lane- description: Release the lane's bound claim. Idempotent.- operationId: delete_lane_lanes__lane_id__delete- parameters:- - name: pool- in: path- required: true- schema:- type: string- description: Pool name (DNS-1123 label)- - name: lane_id- in: path- required: true- schema:- type: string- title: Lane Id- responses:- '200':- description: Successful Response- content:- application/json:- schema:- $ref: '#/components/schemas/LaneDeleteResponse'- '404':- description: Lane not found- content:- application/json:- schema:- $ref: '#/components/schemas/LaneErrorResponse'- '422':- description: Validation Error- content:- application/json:- schema:- $ref: '#/components/schemas/HTTPValidationError'- tags:- - lanes-components:- securitySchemes:- BearerAuth:- type: http- scheme: bearer- description: "Keycloak access token.\n- For `/api/keys` and `/api/{k8s,orch}`:\- \ SPA user JWT (azp=cyclops-cs-spa).\n- For `/api/batch/{pool}/*` and `/api/label/{pool}/*`:\- \ service-account JWT\n minted via `client_credentials` against a per-key\- \ client; the token's\n `namespace` claim must equal `pool-{pool}` (OPA-enforced).\- \ SPA tokens\n may target any pool.\n"- responses:- BadRequest:- description: Bad Request- content:- application/json:- schema:- $ref: '#/components/schemas/ErrorResponse'- Unauthorized:- description: Unauthorized- content:- application/json:- schema:- $ref: '#/components/schemas/ErrorResponse'- Forbidden:- description: Forbidden- content:- application/json:- schema:- $ref: '#/components/schemas/ErrorResponse'- NotFound:- description: Not Found- content:- application/json:- schema:- $ref: '#/components/schemas/ErrorResponse'- schemas:- ErrorResponse:- type: object- properties:- error:- type: string- HealthResponse:- type: object- properties:- ok:- type: boolean- KeyClient:- type: object- properties:- id:- type: string- client_id:- type: string- name:- type: string- namespace:- type: string- owner_sub:- type: string- ListKeysResponse:- type: object- properties:- keys:- type: array- items:- $ref: '#/components/schemas/KeyClient'- CreateKeyRequest:- type: object- required:- - name- - namespace- properties:- name:- type: string- example: ci-prod- namespace:- type: string- example: test-pool- CreateKeyResponse:- type: object- properties:- client_id:- type: string- client_secret:- type: string- name:- type: string- namespace:- type: string- token_url:- type: string- Action:- type: object- required:- - action_type- properties:- action_type:- type: string- description: OSGym action type (e.g. CLICK, TYPE, KEY).- example: CLICK- parameters:- type: object- additionalProperties: true- description: Action-type-specific parameters (e.g. `{x, y, button}` for- CLICK).- RunConfig:- type: object- required:- - steps- properties:- steps:- type: array- description: 'Ordered actions to execute on the rollout VM. A step with- `action_type: "RESET"` is a reserved control action: instead of being- forwarded to the VM, it hard-resets the VM in place (new vm_id, clean- baseline desktop), so one run can execute several independent episodes- on a warm instance.'- items:- $ref: '#/components/schemas/Action'- maxItems: 10000- timeout:- type: integer- minimum: 0- maximum: 86400- description: Per-rollout timeout in seconds (max 24h).- vm_id:- type: string- description: Reattach this run to an existing warm VM (instance reuse /- "lane"), typically a vm_id returned by a previous `keep_warm` batch, instead- of acquiring a fresh one. If that claim has already expired, the run transparently- falls back to a fresh VM.- BatchSubmitRequest:- type: object- required:- - runs- properties:- runs:- type: array- items:- $ref: '#/components/schemas/RunConfig'- maxItems: 10000- concurrency:- type: integer- default: 10- minimum: 1- maximum: 1000- pool_name:- type: string- description: Optional — must match the URL `{pool}` if provided; ignored- otherwise.- name:- type: string- description: Optional batch name. Overridden by the URL `{label}` on label- routes.- maxLength: 256- keep_warm:- type: boolean- description: 'Leave each run''s VM running when the run ends (instead of- shutting it down), so a follow-up batch can reattach to it via RunConfig.vm_id- (read each lane''s surviving id from RunResult.vm_id). Best-effort: a- warm VM is reaped after its claim TTL (~minutes), after which reattach- falls back to a fresh VM.'- BatchSubmitResponse:- type: object- properties:- batch_id:- type: string- name:- type: string- status:- type: string- created_at:- type: string- format: date-time- AcquireLanesRequest:- type: object- required:- - n- properties:- n:- type: integer- minimum: 1- maximum: 1000- description: Number of warm VM lanes to acquire.- AcquireLanesResponse:- type: object- properties:- vm_ids:- type: array- description: One warm VM id per acquired lane. Use as RunConfig.vm_id.- items:- type: string- ReleaseLanesRequest:- type: object- required:- - vm_ids- properties:- vm_ids:- type: array- description: VM ids to shut down (lanes to release).- items:- type: string- ReleaseLanesResponse:- type: object- properties:- released:- type: integer- description: Number of vm_ids submitted for release.- BatchProgress:- type: object- properties:- completed:- type: integer- total:- type: integer- ok:- type: integer- failed:- type: integer- BatchStatusResponse:- type: object- properties:- batch_id:- type: string- name:- type: string- status:- type: string- progress:- $ref: '#/components/schemas/BatchProgress'- created_at:- type: string- format: date-time- updated_at:- type: string- format: date-time- BatchInProgressResponse:- type: object- properties:- batch_id:- type: string- status:- type: string- message:- type: string- CancelBatchResponse:- type: object- properties:- batch_id:- type: string- status:- type: string- TimingStats:- type: object- properties:- n:- type: integer- min:- type: integer- format: int64- mean:- type: number- format: double- max:- type: integer- format: int64- BatchSummary:- type: object- properties:- n_ok:- type: integer- n_fail:- type: integer- total_wall_ms:- type: integer- format: int64- reset_stats:- $ref: '#/components/schemas/TimingStats'- step_stats:- $ref: '#/components/schemas/TimingStats'- shutdown_stats:- $ref: '#/components/schemas/TimingStats'- RunResult:- type: object- properties:- run_id:- type: integer- vm_id:- type: string- ok:- type: boolean- error:- type: string- reset_ms:- type: integer- format: int64- step_ms:- type: array- items:- type: integer- format: int64- shutdown_ms:- type: integer- format: int64- actions:- type: array- items:- type: string- screenshots:- type: array- items:- type: string- BatchResultsResponse:- type: object- properties:- batch_id:- type: string- name:- type: string- status:- type: string- runs:- type: array- items:- $ref: '#/components/schemas/RunResult'- s3_bucket:- type: string- s3_key:- type: string- s3_presigned_url:- type: string- summary:- $ref: '#/components/schemas/BatchSummary'- LabelBatchSummary:- type: object- properties:- batch_id:- type: string- status:- type: string- progress:- $ref: '#/components/schemas/BatchProgress'- created_at:- type: string- format: date-time- updated_at:- type: string- format: date-time- s3_key:- type: string- s3_presigned_url:- type: string- LabelStatusResponse:- type: object- properties:- label:- type: string- batch_count:- type: integer- all_completed:- type: boolean- progress:- $ref: '#/components/schemas/BatchProgress'- batches:- type: array- items:- $ref: '#/components/schemas/LabelBatchSummary'- LabelInProgressResponse:- type: object- properties:- label:- type: string- batch_count:- type: integer- all_completed:- type: boolean- message:- type: string- LabelResultsResponse:- type: object- properties:- label:- type: string- batch_count:- type: integer- completed_batch_count:- type: integer- all_completed:- type: boolean- batches:- type: array- items:- $ref: '#/components/schemas/BatchResultsResponse'- summary:- $ref: '#/components/schemas/BatchSummary'- CancelLabelBatchItem:- type: object- properties:- batch_id:- type: string- status:- type: string- CancelLabelResponse:- type: object- properties:- label:- type: string- batch_count:- type: integer- cancelled_count:- type: integer- already_done:- type: integer- batches:- type: array- items:- $ref: '#/components/schemas/CancelLabelBatchItem'- HealthzResponse:- properties:- status:- type: string- title: Status- type: object- required:- - status- title: HealthzResponse- LaneCreateRequest:- properties:- ttl_seconds:- type: integer- title: Ttl Seconds- default: 300- type: object- title: LaneCreateRequest- description: 'Body of POST /lanes.--- ``ttl_seconds`` is the absolute time the claim is reserved for;-- after that the reaper deletes it. With ``autoRenew=true`` the lane-- auto-renew timer in pool-operator pushes this forward, so the-- customer''s effective TTL is "as long as the lane exists".'- LaneDeleteResponse:- properties:- lane_id:- type: string- title: Lane Id- type: object- required:- - lane_id- title: LaneDeleteResponse- LaneResponse:- properties:- lane_id:- type: string- title: Lane Id- vm_id:- type: string- title: Vm Id- screenshot:- anyOf:- - type: string- - type: 'null'- title: Screenshot- type: object- required:- - lane_id- - vm_id- title: LaneResponse- LaneSwapResponse:- properties:- lane_id:- type: string- title: Lane Id- vm_id:- type: string- title: Vm Id- wait_seconds:- type: number- title: Wait Seconds- type: object- required:- - lane_id- - vm_id- - wait_seconds- title: LaneSwapResponse- PoolListResponse:- properties:- vms:- items:- additionalProperties: true- type: object- type: array- title: Vms- count:- type: integer- title: Count- type: object- required:- - vms- - count- title: PoolListResponse- ResetRequest:- properties:- task_config:- additionalProperties: true- type: object- title: Task Config- timeout:- type: integer- title: Timeout- type: object- required:- - task_config- - timeout- title: ResetRequest- ResetResponse:- properties:- screenshot:- type: string- title: Screenshot- problem:- type: string- title: Problem- vm_id:- type: string- title: Vm Id- type: object- required:- - screenshot- - problem- - vm_id- title: ResetResponse- ScreenshotResponse:- properties:- screenshot:- type: string- title: Screenshot- vm_id:- type: string- title: Vm Id- type: object- required:- - screenshot- - vm_id- title: ScreenshotResponse- ShutdownRequest:- properties:- vm_id:- type: string- title: Vm Id- type: object- required:- - vm_id- title: ShutdownRequest- ShutdownResponse:- properties:- vm_id:- type: string- title: Vm Id- type: object- required:- - vm_id- title: ShutdownResponse- StepRequest:- properties:- action:- type: string- title: Action- vm_id:- type: string- title: Vm Id- timeout:- type: integer- title: Timeout- default: 300- type: object- required:- - action- - vm_id- title: StepRequest- StepResponse:- properties:- screenshot:- anyOf:- - type: string- - type: 'null'- title: Screenshot- is_finish:- type: boolean- title: Is Finish- reward:- type: number- title: Reward- type: object- required:- - screenshot- - is_finish- - reward- title: StepResponse- LaneErrorResponse:- properties:- message:- anyOf:- - type: string- - type: 'null'- title: Message- reason:- anyOf:- - type: string- - type: 'null'- title: Reason- lane_id:- anyOf:- - type: string- - type: 'null'- title: Lane Id- type: object- title: ErrorResponsediff --git a/libs/fleet/python-sdk/package.nix b/libs/fleet/python-sdk/package.nixdeleted file mode 100644index ce60b8c7f6..0000000000--- a/libs/fleet/python-sdk/package.nix+++ /dev/null@@ -1,140 +0,0 @@-# Nix package for the cua-train Python SDK.-#-# Single-step build:-# 1. Import the osgym FastAPI app (fake backend) → dump openapi.json-# 2. Merge lane endpoints into parent openapi3.yaml-# 3. Regenerate api/ + models/ with openapi-python-client-# 4. Format with ruff-# 5. Build the wheel-#-# Usage:-# nix build .#cua-train-sdk-# pip install result/*.whl-{- pkgs,- lib ? pkgs.lib,- # Build against a caller-supplied interpreter so consumers (e.g. the- # cua-temporal-agent worker env) can keep the package on the same Python as- # the rest of their closure. Defaults to 3.12 for the standalone `nix build`.- python ? pkgs.python312,-}:--let- pp = python.pkgs;-- osgymSrc = builtins.path {- path = ../../osgym;- name = "osgym-src";- };-- # Python with deps needed to import the osgym FastAPI app (fake backend)- # AND to run the merge script.- genPython = python.withPackages (- ps: with ps; [- fastapi- pydantic- uvicorn- aiohttp- prometheus-client- kubernetes- pyyaml- ruff- ]- );--in-pp.buildPythonPackage {- pname = "cua-train";- version = "0.1.3";- pyproject = true;-- src = builtins.path {- path = ./.;- name = "cua-train-sdk-src";- filter =- path: type:- let- base = builtins.baseNameOf path;- in- !(- base == ".venv"- || base == "__pycache__"- || base == "dist"- || base == ".pytest_cache"- || lib.hasSuffix ".egg-info" base- );- };-- build-system = [ pp.hatchling ];-- nativeBuildInputs = [- genPython- pkgs.openapi-python-client- ];-- dependencies = with pp; [- httpx- attrs- python-dateutil- ];-- preBuild = ''- echo "==> Generating orchestrator OpenAPI spec"- PYTHONPATH="${osgymSrc}" \- OSGYM_POOL_BACKEND=fake \- OSGYM_ALLOWED_IPS=0.0.0.0/0 \- ${genPython}/bin/python -c "- import json, sys, io-- # Suppress all stdout noise from osgym imports (log messages, banners)- real_stdout = sys.stdout- sys.stdout = io.StringIO()- try:- # Lanes were decoupled out of the orchestrator (osgym #4953), so the- # old \`from lane_endpoints import register\` no longer exists. The lane- # paths now live in the committed openapi3.yaml (the merge below only- # ADDS osgym paths, never drops the parent's), so plain app.openapi()- # is the correct spec source.- from main import app- spec = app.openapi()- finally:- sys.stdout = real_stdout-- json.dump(spec, sys.stdout, indent=2)- " > /tmp/orch-spec.json- echo " Spec: $(wc -l < /tmp/orch-spec.json) lines"- test -s /tmp/orch-spec.json || { echo "FATAL: empty spec"; exit 1; }-- echo "==> Merging lane endpoints"- cat /tmp/orch-spec.json | head -3- ${genPython}/bin/python scripts/merge_orchestrator_spec.py \- --parent openapi3.yaml \- --orchestrator /tmp/orch-spec.json \- --output openapi3.yaml-- echo "==> Regenerating SDK"- openapi-python-client update --path openapi3.yaml || true # lint-ignore: error-masking — may fail on first run-- echo "==> Formatting"- ${genPython}/bin/python -m ruff check --fix cua_train/ 2>/dev/null || true # lint-ignore: error-masking — best-effort autofix- ${genPython}/bin/python -m ruff format cua_train/- '';-- nativeCheckInputs = with pp; [- pytestCheckHook- pytest-httpx- ];-- # test_wheel_build stages the wheel from the repo-absolute path- # /cyclops-cs/python-sdk (valid in the cyclops-cs repo CI container, absent in- # the Nix sandbox) -> FileNotFoundError, which failed every worker image- # build on main. Environment-dependent, not a property of the package: skip.- disabledTestPaths = [ "tests/test_wheel_build.py" ];-- pythonImportsCheck = [ "cua_train" ];-- meta = {- description = "Python SDK for the CUA training / batch backend API";- license = lib.licenses.mit;- };-}diff --git a/libs/fleet/python-sdk/pyproject.toml b/libs/fleet/python-sdk/pyproject.tomldeleted file mode 100644index d10daac1b6..0000000000--- a/libs/fleet/python-sdk/pyproject.toml+++ /dev/null@@ -1,38 +0,0 @@-[build-system]-requires = ["hatchling"]-build-backend = "hatchling.build"--[project]-name = "cua-train"-version = "0.1.6"-description = "Python SDK for the CUA training / batch backend API — generated from OpenAPI spec."-readme = "README.md"-license = { text = "MIT" }-authors = [{ name = "TryCua", email = "[email protected]" }]-requires-python = ">=3.10"-dependencies = [- "httpx>=0.23.0",- "attrs>=22.2.0",- "python-dateutil>=2.8.0",-]--[project.urls]-Repository = "https://github.com/trycua/cloud"-"Issue Tracker" = "https://github.com/trycua/cloud/issues"--[tool.hatch.build.targets.wheel]-packages = ["cua_train"]--[project.optional-dependencies]-dev = [- "build>=1.2",- "pytest>=7.0",- "pytest-httpx>=0.30.0",- "ruff>=0.6",-]--[tool.ruff]-line-length = 120--[tool.ruff.lint]-select = ["F", "I", "UP"]diff --git a/libs/fleet/python-sdk/scripts/build_wheel.py b/libs/fleet/python-sdk/scripts/build_wheel.pydeleted file mode 100755index 74a07a6fa5..0000000000--- a/libs/fleet/python-sdk/scripts/build_wheel.py+++ /dev/null@@ -1,210 +0,0 @@-#!/usr/bin/env python3-"""Build a platform wheel containing the generated Fleet Python binding."""--from __future__ import annotations--import argparse-import base64-import csv-import hashlib-import platform-import shutil-import subprocess-import sys-import tempfile-import zipfile-from pathlib import Path--PACKAGE_NAME = "cua_train"-NATIVE_PACKAGE = "fleet_sdk"---def parse_args() -> argparse.Namespace:- parser = argparse.ArgumentParser()- parser.add_argument("--outdir", type=Path, default=Path("dist"))- parser.add_argument("--native-library", type=Path)- parser.add_argument("--platform-tag")- parser.add_argument("--cargo-target")- return parser.parse_args()---def repository_root() -> Path:- return Path(__file__).resolve().parents[3]---def native_library_name() -> str:- if sys.platform == "darwin":- return "libcyclops_sdk.dylib"- if sys.platform.startswith("linux"):- return "libcyclops_sdk.so"- if sys.platform.startswith("win"):- return "cyclops_sdk.dll"- raise RuntimeError(f"unsupported wheel build platform: {sys.platform}")---def default_platform_tag() -> str:- machine = platform.machine().lower()- aliases = {"amd64": "x86_64", "aarch64": "arm64"}- machine = aliases.get(machine, machine)-- if sys.platform.startswith("linux"):- linux_arches = {"x86_64": "x86_64", "arm64": "aarch64"}- try:- return f"linux_{linux_arches[machine]}"- except KeyError as error:- raise RuntimeError(f"unsupported Linux architecture: {machine}") from error-- if sys.platform == "darwin":- macos_versions = {"x86_64": "10_13", "arm64": "11_0"}- try:- return f"macosx_{macos_versions[machine]}_{machine}"- except KeyError as error:- raise RuntimeError(f"unsupported macOS architecture: {machine}") from error-- if sys.platform.startswith("win"):- if machine != "x86_64":- raise RuntimeError(f"unsupported Windows architecture: {machine}")- return "win_amd64"-- raise RuntimeError(f"unsupported wheel build platform: {sys.platform}")---def native_library_name_for_platform_tag(platform_tag: str) -> str:- if platform_tag == "win_amd64":- return "cyclops_sdk.dll"- if platform_tag.startswith("linux_"):- return "libcyclops_sdk.so"- if platform_tag.startswith("macosx_"):- return "libcyclops_sdk.dylib"- raise RuntimeError(f"unsupported wheel platform tag: {platform_tag}")---def build_native_library(repo_root: Path, cargo_target: str | None) -> Path:- command = [- "cargo",- "build",- "--locked",- "--manifest-path",- str(repo_root / "cyclops-cs" / "Cargo.toml"),- "--package",- "cyclops-sdk",- "--release",- ]- if cargo_target:- command.extend(["--target", cargo_target])- subprocess.run(command, check=True)-- target_directory = repo_root / "cyclops-cs" / "target"- if cargo_target:- target_directory /= cargo_target- library = target_directory / "release" / native_library_name()- if not library.is_file():- raise RuntimeError(f"Cargo did not produce expected native library: {library}")- return library---def stage_project(repo_root: Path, stage_root: Path, library: Path, native_library: str) -> None:- source = repo_root / "cyclops-cs" / "python-sdk"- shutil.copytree(- source,- stage_root,- ignore=shutil.ignore_patterns("build", "dist", "*.egg-info", ".pytest_cache", "__pycache__", ".venv"),- )- shutil.copytree(repo_root / "cyclops-cs" / "sdk-bindings" / "python" / NATIVE_PACKAGE, stage_root / NATIVE_PACKAGE)- shutil.copy2(library, stage_root / NATIVE_PACKAGE / native_library)-- pyproject = stage_root / "pyproject.toml"- contents = pyproject.read_text()- expected = 'packages = ["cua_train"]'- replacement = 'packages = ["cua_train", "fleet_sdk"]'- if expected not in contents:- raise RuntimeError(f"could not configure staged package list in {pyproject}")- pyproject.write_text(contents.replace(expected, replacement, 1))---def record_line(filename: str, data: bytes) -> list[str]:- digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode()- return [filename, f"sha256={digest}", str(len(data))]---def retag_wheel(wheel: Path, platform_tag: str) -> Path:- with zipfile.ZipFile(wheel) as source:- entries = {- entry.filename: source.read(entry.filename)- for entry in source.infolist()- if not entry.filename.endswith(".dist-info/RECORD")- }-- wheel_metadata_name = next(name for name in entries if name.endswith(".dist-info/WHEEL"))- wheel_metadata = entries[wheel_metadata_name].decode().splitlines()- updated_metadata = [- "Root-Is-Purelib: false" if line == "Root-Is-Purelib: true" else line- for line in wheel_metadata- if not line.startswith("Tag: ")- ]- updated_metadata.append(f"Tag: py3-none-{platform_tag}")- entries[wheel_metadata_name] = ("\n".join(updated_metadata) + "\n").encode()-- distribution = wheel.name.split("-")[0]- version = wheel.name.split("-")[1]- retagged = wheel.with_name(f"{distribution}-{version}-py3-none-{platform_tag}.whl")- record_name = next(name for name in entries if name.endswith(".dist-info/WHEEL"))- record_name = record_name.rsplit("/", 1)[0] + "/RECORD"-- with zipfile.ZipFile(retagged, "w", compression=zipfile.ZIP_DEFLATED) as target:- records: list[list[str]] = []- for name in sorted(entries):- data = entries[name]- target.writestr(name, data)- records.append(record_line(name, data))- records.append([record_name, "", ""])- target.writestr(record_name, csv_text(records))-- wheel.unlink()- return retagged---def csv_text(rows: list[list[str]]) -> str:- from io import StringIO-- output = StringIO()- csv.writer(output, lineterminator="\n").writerows(rows)- return output.getvalue()---def main() -> None:- args = parse_args()- repo_root = repository_root()- platform_tag = args.platform_tag or default_platform_tag()- expected_library_name = native_library_name_for_platform_tag(platform_tag)- library = (- args.native_library.resolve()- if args.native_library- else build_native_library(repo_root, args.cargo_target)- )- if not library.is_file():- raise RuntimeError(f"native library does not exist: {library}")- if library.name != expected_library_name:- raise RuntimeError(- f"native library must be named {expected_library_name} for {platform_tag}: {library}"- )-- output = args.outdir.resolve()- output.mkdir(parents=True, exist_ok=True)- with tempfile.TemporaryDirectory(prefix="cua-train-wheel-") as temporary_directory:- stage_root = Path(temporary_directory) / "python-sdk"- stage_project(repo_root, stage_root, library, expected_library_name)- subprocess.run(- [sys.executable, "-m", "build", "--wheel", "--outdir", str(output), str(stage_root)],- check=True,- )-- wheels = sorted(output.glob(f"{PACKAGE_NAME}-*.whl"))- if len(wheels) != 1:- raise RuntimeError(f"expected exactly one built wheel in {output}, found: {wheels}")- wheel = retag_wheel(wheels[0], platform_tag)- print(wheel)---if __name__ == "__main__":- main()diff --git a/libs/fleet/python-sdk/scripts/generate.sh b/libs/fleet/python-sdk/scripts/generate.shdeleted file mode 100755index a960d5d9e5..0000000000--- a/libs/fleet/python-sdk/scripts/generate.sh+++ /dev/null@@ -1,54 +0,0 @@-#!/usr/bin/env bash-# Generate the cua_train SDK from the osgym orchestrator's OpenAPI spec.-#-# Usage:-# ./scripts/generate.sh-set -euo pipefail--SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"-SDK_DIR="$(dirname "$SCRIPT_DIR")"-OSGYM_DIR="$(cd "$SDK_DIR/../../osgym" && pwd)"--# Bootstrap: re-exec inside nix-shell with a proper Python environment-if [ -z "${IN_NIX_SHELL:-}" ]; then- exec nix-shell --pure -E '- let pkgs = import <nixpkgs> {};- python = pkgs.python312.withPackages (ps: with ps; [- fastapi pydantic uvicorn aiohttp prometheus-client- kubernetes pyyaml ruff- ]);- in pkgs.mkShell {- buildInputs = [ python pkgs.openapi-python-client ];- shellHook = "export IN_NIX_SHELL=1";- }- ' --run "bash $0"-fi--echo "==> Step 1: Generate orchestrator OpenAPI spec"-ORCH_SPEC=$(mktemp /tmp/osgym-openapi-XXXXXX.json)-PYTHONPATH="$OSGYM_DIR" \- OSGYM_POOL_BACKEND=fake \- OSGYM_ALLOWED_IPS=0.0.0.0/0 \- python3 -c "-import json-from main import app-print(json.dumps(app.openapi(), indent=2))-" > "$ORCH_SPEC"-echo " Wrote $ORCH_SPEC ($(wc -l < "$ORCH_SPEC") lines)"--echo "==> Step 2: Merge lane endpoints into parent openapi3.yaml"-python3 "$SCRIPT_DIR/merge_orchestrator_spec.py" \- --parent "$SDK_DIR/openapi3.yaml" \- --orchestrator "$ORCH_SPEC" \- --output "$SDK_DIR/openapi3.yaml"--echo "==> Step 3: Regenerate Python SDK"-cd "$SDK_DIR"-openapi-python-client update --path openapi3.yaml || true # lint-ignore: error-masking — may fail on first run--echo "==> Step 4: Format"-python3 -m ruff check --fix cua_train/ 2>/dev/null || true # lint-ignore: error-masking — best-effort autofix-python3 -m ruff format cua_train/--rm -f "$ORCH_SPEC"-echo "==> Done. Review changes with: git diff cyclops-cs/python-sdk/"diff --git a/libs/fleet/python-sdk/scripts/merge_orchestrator_spec.py b/libs/fleet/python-sdk/scripts/merge_orchestrator_spec.pydeleted file mode 100644index 6a59862a7d..0000000000--- a/libs/fleet/python-sdk/scripts/merge_orchestrator_spec.py+++ /dev/null@@ -1,123 +0,0 @@-#!/usr/bin/env python3-"""Merge the osgym orchestrator's OpenAPI spec into the parent SDK spec.--Rewrites orchestrator paths like /lanes → /api/gateway/{pool}/lanes-and adds a {pool} path parameter. Merges schemas into components.-Only merges /lanes endpoints (not /reset, /step, etc. which are-already covered by the batch driver).-"""-import argparse-import copy-import json-import sys--import yaml---# Paths from the orchestrator to include (prefix match)-INCLUDE_PREFIXES = ["/lanes"]--# Schemas to always skip (already in parent or not needed)-SKIP_SCHEMAS = {"HTTPValidationError", "ValidationError"}---def rewrite_path(path: str) -> str:- """Rewrite /lanes/... → /api/gateway/{pool}/lanes/..."""- return f"/api/gateway/{{pool}}{path}"---def add_pool_param(operation: dict) -> None:- """Add {pool} path parameter to an operation if not present."""- params = operation.setdefault("parameters", [])- if any(p.get("name") == "pool" for p in params):- return- params.insert(0, {- "name": "pool",- "in": "path",- "required": True,- "schema": {"type": "string"},- "description": "Pool name (DNS-1123 label)",- })---def fix_ref(obj, old_prefix="#/components/schemas/", renames=None):- """Recursively fix $ref pointers after schema renames."""- if isinstance(obj, dict):- if "$ref" in obj:- ref = obj["$ref"]- if ref.startswith(old_prefix) and renames:- schema_name = ref[len(old_prefix):]- if schema_name in renames:- obj["$ref"] = f"{old_prefix}{renames[schema_name]}"- for v in obj.values():- fix_ref(v, old_prefix, renames)- elif isinstance(obj, list):- for item in obj:- fix_ref(item, old_prefix, renames)---def merge(parent_path: str, orch_path: str, output_path: str) -> None:- with open(parent_path) as f:- parent = yaml.safe_load(f)- with open(orch_path) as f:- orch = json.load(f)-- orch_paths = orch.get("paths", {})- orch_schemas = orch.get("components", {}).get("schemas", {})-- # Determine which schemas are referenced by included paths- included_paths = {}- for path, methods in orch_paths.items():- if not any(path.startswith(p) for p in INCLUDE_PREFIXES):- continue- included_paths[path] = methods-- # Rename schemas with module prefixes (e.g. lane_endpoints__ErrorResponse → LaneErrorResponse)- renames = {}- for name in orch_schemas:- if "__" in name:- # lane_endpoints__ErrorResponse → LaneErrorResponse- new_name = name.split("__")[-1]- # Prefix with "Lane" if it would conflict- if new_name in orch_schemas and new_name != name:- new_name = f"Lane{new_name}"- renames[name] = new_name-- # Add rewritten paths to parent- parent_paths = parent.setdefault("paths", {})- for path, methods in included_paths.items():- new_path = rewrite_path(path)- methods = copy.deepcopy(methods)- for method, operation in methods.items():- if isinstance(operation, dict):- add_pool_param(operation)- # Tag as "lanes" for SDK grouping- operation["tags"] = ["lanes"]- fix_ref(operation, renames=renames)- parent_paths[new_path] = methods-- # Add schemas to parent- parent_schemas = parent.setdefault("components", {}).setdefault("schemas", {})- for name, schema in orch_schemas.items():- if name in SKIP_SCHEMAS:- continue- final_name = renames.get(name, name)- if final_name not in parent_schemas:- schema = copy.deepcopy(schema)- fix_ref(schema, renames=renames)- parent_schemas[final_name] = schema-- with open(output_path, "w") as f:- yaml.dump(parent, f, default_flow_style=False, sort_keys=False, allow_unicode=True)-- added = len(included_paths)- print(f" Merged {added} path(s), {len(orch_schemas) - len(SKIP_SCHEMAS)} schema(s)")---if __name__ == "__main__":- p = argparse.ArgumentParser()- p.add_argument("--parent", required=True)- p.add_argument("--orchestrator", required=True)- p.add_argument("--output", required=True)- args = p.parse_args()- merge(args.parent, args.orchestrator, args.output)diff --git a/libs/fleet/python-sdk/tests/__init__.py b/libs/fleet/python-sdk/tests/__init__.pydeleted file mode 100644index e69de29bb2..0000000000diff --git a/libs/fleet/python-sdk/tests/test_endpoints.py b/libs/fleet/python-sdk/tests/test_endpoints.pydeleted file mode 100644index 3efa39dfed..0000000000--- a/libs/fleet/python-sdk/tests/test_endpoints.py+++ /dev/null@@ -1,672 +0,0 @@-"""-Parametrized tests for every endpoint in the cyclops-cs SDK.--Uses pytest-httpx to intercept httpx calls so no real server is needed.-Each endpoint has three test categories:- - base: happy-path / golden response- - error: 4xx responses parsed into ErrorResponse- - generated: edge-case parameter variants-"""--import pytest-from pytest_httpx import HTTPXMock--from cua_train import TrainClient-from cua_train.api.batch import cancel_batch, get_batch_results, get_batch_status, submit_batch-from cua_train.api.health import healthz-from cua_train.api.keys import create_key, delete_key, list_keys-from cua_train.api.label import cancel_label, get_label_results, get_label_status, submit_label_batch-from cua_train.client import AuthenticatedClient, Client-from cua_train.models import (- Action,- ActionParameters,- BatchInProgressResponse,- BatchResultsResponse,- BatchStatusResponse,- BatchSubmitRequest,- BatchSubmitResponse,- CancelBatchResponse,- CancelLabelResponse,- CreateKeyRequest,- CreateKeyResponse,- ErrorResponse,- HealthResponse,- LabelInProgressResponse,- LabelResultsResponse,- LabelStatusResponse,- ListKeysResponse,- RunConfig,-)--BASE_URL = "https://cyclops-cs.trycua.com"-TOKEN = "test-bearer-token"---# ----------------------------------------------------------------------------# Fixtures-# ------------------------------------------------------------------------------def anon_client() -> Client:- return Client(base_url=BASE_URL, raise_on_unexpected_status=True)---def auth_client() -> AuthenticatedClient:- # TrainClient is a drop-in AuthenticatedClient that also exposes every- # generated endpoint as a method; using it here exercises both the low-level- # api.* calls (client=auth_client) and the generic facade (auth_client.<op>).- return TrainClient(base_url=BASE_URL, token=TOKEN, raise_on_unexpected_status=True)---def test_train_client_refreshes_token(httpx_mock: HTTPXMock):- """from_key mints a token, then get_httpx_client() transparently re-mints it- once it's near expiry — no caller involvement."""- token_ep = "https://auth.example/realms/x/token"- # First exchange returns an already-stale token (expires_in=0).- httpx_mock.add_response(method="POST", url=token_ep, json={"access_token": "t1", "expires_in": 0})- c = TrainClient.from_key(token_url=token_ep, client_id="key-x", client_secret="s", base_url=BASE_URL)- assert c.token == "t1"-- # Next use refreshes (deadline already passed) and bakes the new bearer.- httpx_mock.add_response(method="POST", url=token_ep, json={"access_token": "t2", "expires_in": 300})- client = c.get_httpx_client()- assert c.token == "t2"- assert client.headers["Authorization"] == "Bearer t2"---# ----------------------------------------------------------------------------# /healthz-# ------------------------------------------------------------------------------class TestHealthz:- def test_base_ok(self, httpx_mock: HTTPXMock, anon_client):- """Golden: healthz returns 200 {ok: true}."""- httpx_mock.add_response(- method="GET",- url=f"{BASE_URL}/healthz",- status_code=200,- json={"ok": True},- )- resp = healthz.sync_detailed(client=anon_client)- assert resp.status_code.value == 200- assert isinstance(resp.parsed, HealthResponse)- assert resp.parsed.ok is True-- def test_base_degraded(self, httpx_mock: HTTPXMock, anon_client):- """Edge: ok=false still parses cleanly."""- httpx_mock.add_response(- method="GET",- url=f"{BASE_URL}/healthz",- status_code=200,- json={"ok": False},- )- assert healthz.sync_detailed(client=anon_client).parsed.ok is False-- def test_unexpected_status(self, httpx_mock: HTTPXMock, anon_client):- """Error: unexpected 503 raises when raise_on_unexpected_status=True."""- httpx_mock.add_response(- method="GET", url=f"{BASE_URL}/healthz", status_code=503, json={"error": "svc unavailable"}- )- from cua_train import errors-- with pytest.raises(errors.UnexpectedStatus):- healthz.sync_detailed(client=anon_client)---# ----------------------------------------------------------------------------# /api/keys GET-# ------------------------------------------------------------------------------GOLDEN_KEY = {- "id": "kc-uuid-1",- "client_id": "key-abc123",- "name": "ci-prod",- "namespace": "test-pool",- "owner_sub": "user-sub-1",-}---class TestListKeys:- def test_base(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(method="GET", url=f"{BASE_URL}/api/keys", status_code=200, json={"keys": [GOLDEN_KEY]})- resp = list_keys.sync_detailed(client=auth_client)- assert resp.status_code.value == 200- assert isinstance(resp.parsed, ListKeysResponse)- assert len(resp.parsed.keys) == 1- assert resp.parsed.keys[0].name == "ci-prod"-- def test_empty_list(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(method="GET", url=f"{BASE_URL}/api/keys", status_code=200, json={"keys": []})- assert list_keys.sync_detailed(client=auth_client).parsed.keys == []-- def test_unauthorized(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="GET", url=f"{BASE_URL}/api/keys", status_code=401, json={"error": "unauthorized"}- )- resp = list_keys.sync_detailed(client=auth_client)- assert resp.status_code.value == 401- assert isinstance(resp.parsed, ErrorResponse)---# ----------------------------------------------------------------------------# /api/keys POST-# ------------------------------------------------------------------------------class TestCreateKey:- @pytest.mark.parametrize(- "name,namespace",- [- ("ci-prod", "test-pool"),- ("my-key", "default"),- ("key-with-dashes", "namespace-123"),- ],- )- def test_base(self, httpx_mock: HTTPXMock, auth_client, name, namespace):- httpx_mock.add_response(- method="POST",- url=f"{BASE_URL}/api/keys",- status_code=201,- json={- "client_id": f"key-{name}",- "client_secret": "super-secret",- "name": name,- "namespace": namespace,- "token_url": "https://auth.example.com/token",- },- )- resp = create_key.sync_detailed(client=auth_client, body=CreateKeyRequest(name=name, namespace=namespace))- assert resp.status_code.value == 201- assert isinstance(resp.parsed, CreateKeyResponse)- assert resp.parsed.client_secret == "super-secret"-- def test_bad_request(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="POST", url=f"{BASE_URL}/api/keys", status_code=400, json={"error": "name is required"}- )- resp = create_key.sync_detailed(client=auth_client, body=CreateKeyRequest(name="", namespace="pool"))- assert resp.status_code.value == 400- assert isinstance(resp.parsed, ErrorResponse)-- def test_forbidden(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="POST", url=f"{BASE_URL}/api/keys", status_code=403, json={"error": "key limit reached"}- )- resp = create_key.sync_detailed(client=auth_client, body=CreateKeyRequest(name="extra", namespace="pool"))- assert resp.status_code.value == 403---# ----------------------------------------------------------------------------# /api/keys/{id} DELETE-# ------------------------------------------------------------------------------class TestDeleteKey:- @pytest.mark.parametrize("key_id", ["kc-uuid-1", "kc-uuid-2", "00000000-0000-0000-0000-000000000000"])- def test_base(self, httpx_mock: HTTPXMock, auth_client, key_id):- httpx_mock.add_response(method="DELETE", url=f"{BASE_URL}/api/keys/{key_id}", status_code=204)- assert delete_key.sync_detailed(id=key_id, client=auth_client).status_code.value == 204-- def test_forbidden(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="DELETE", url=f"{BASE_URL}/api/keys/other-uuid", status_code=403, json={"error": "not your key"}- )- assert delete_key.sync_detailed(id="other-uuid", client=auth_client).status_code.value == 403---# ----------------------------------------------------------------------------# /api/batch/{pool}/submit POST-# ------------------------------------------------------------------------------GOLDEN_SUBMIT_RESP = {- "batch_id": "batch-abc",- "name": "my-batch",- "status": "queued",- "created_at": "2026-05-01T00:00:00Z",-}-GOLDEN_RUN = RunConfig(- steps=[Action(action_type="CLICK", parameters=ActionParameters.from_dict({"x": 1, "y": 2}))],- timeout=60,-)---class TestSubmitBatch:- @pytest.mark.parametrize(- "pool,concurrency",- [- ("test-pool", 1),- ("prod-pool", 10),- ("staging", 50),- ],- )- def test_base(self, httpx_mock: HTTPXMock, auth_client, pool, concurrency):- httpx_mock.add_response(- method="POST", url=f"{BASE_URL}/api/batch/{pool}/submit", status_code=202, json=GOLDEN_SUBMIT_RESP- )- resp = submit_batch.sync_detailed(- pool=pool, client=auth_client, body=BatchSubmitRequest(runs=[GOLDEN_RUN], concurrency=concurrency)- )- assert resp.status_code.value == 202- assert isinstance(resp.parsed, BatchSubmitResponse)- assert resp.parsed.batch_id == "batch-abc"-- def test_bad_request_empty_runs(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="POST",- url=f"{BASE_URL}/api/batch/pool/submit",- status_code=400,- json={"error": "runs must not be empty"},- )- resp = submit_batch.sync_detailed(pool="pool", client=auth_client, body=BatchSubmitRequest(runs=[]))- assert resp.status_code.value == 400- assert isinstance(resp.parsed, ErrorResponse)-- def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="POST", url=f"{BASE_URL}/api/label/test-pool/my-run/batch", status_code=202, json=GOLDEN_SUBMIT_RESP- )- result = auth_client.submit_label_batch(- pool="test-pool", label="my-run", body=BatchSubmitRequest(runs=[GOLDEN_RUN])- )- assert isinstance(result, BatchSubmitResponse)---# ----------------------------------------------------------------------------# /api/batch/{pool}/{id}/status GET-# ------------------------------------------------------------------------------GOLDEN_BATCH_STATUS = {- "batch_id": "batch-abc",- "name": "my-batch",- "status": "running",- "progress": {"completed": 3, "total": 10, "ok": 2, "failed": 1},- "created_at": "2026-05-01T00:00:00Z",- "updated_at": "2026-05-01T00:05:00Z",-}---class TestGetBatchStatus:- def test_base(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="GET",- url=f"{BASE_URL}/api/batch/test-pool/batch-abc/status",- status_code=200,- json=GOLDEN_BATCH_STATUS,- )- resp = get_batch_status.sync_detailed(pool="test-pool", id="batch-abc", client=auth_client)- assert resp.status_code.value == 200- assert isinstance(resp.parsed, BatchStatusResponse)- assert resp.parsed.status == "running"-- def test_not_found(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="GET",- url=f"{BASE_URL}/api/batch/test-pool/unknown/status",- status_code=404,- json={"error": "batch not found"},- )- resp = get_batch_status.sync_detailed(pool="test-pool", id="unknown", client=auth_client)- assert resp.status_code.value == 404- assert isinstance(resp.parsed, ErrorResponse)-- @pytest.mark.parametrize("status_val", ["queued", "running", "completed", "failed", "cancelled"])- def test_all_statuses(self, httpx_mock: HTTPXMock, auth_client, status_val):- body = {**GOLDEN_BATCH_STATUS, "status": status_val}- httpx_mock.add_response(- method="GET", url=f"{BASE_URL}/api/batch/pool/batch-abc/status", status_code=200, json=body- )- resp = get_batch_status.sync_detailed(pool="pool", id="batch-abc", client=auth_client)- assert resp.parsed.status == status_val-- def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="GET", url=f"{BASE_URL}/api/label/pool/test-label/status", status_code=200, json=GOLDEN_LABEL_STATUS- )- result = auth_client.get_label_status(pool="pool", label="test-label")- assert isinstance(result, LabelStatusResponse)---# ----------------------------------------------------------------------------# /api/batch/{pool}/{id}/results GET-# ------------------------------------------------------------------------------GOLDEN_BATCH_RESULTS = {- "batch_id": "batch-abc",- "name": "my-batch",- "status": "completed",- "runs": [- {- "run_id": 1,- "vm_id": "vm-1",- "ok": True,- "reset_ms": 100,- "step_ms": [200],- "shutdown_ms": 50,- "actions": [],- "screenshots": [],- }- ],- "s3_bucket": "my-bucket",- "s3_key": "results/batch-abc.json",- "s3_presigned_url": "https://s3.example.com/presigned",- "summary": {- "n_ok": 1,- "n_fail": 0,- "total_wall_ms": 350,- "reset_stats": {"n": 1, "min": 100, "mean": 100.0, "max": 100},- "step_stats": {"n": 1, "min": 200, "mean": 200.0, "max": 200},- "shutdown_stats": {"n": 1, "min": 50, "mean": 50.0, "max": 50},- },-}---class TestGetBatchResults:- def test_base_completed(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="GET", url=f"{BASE_URL}/api/batch/pool/batch-abc/results", status_code=200, json=GOLDEN_BATCH_RESULTS- )- resp = get_batch_results.sync_detailed(pool="pool", id="batch-abc", client=auth_client)- assert resp.status_code.value == 200- assert isinstance(resp.parsed, BatchResultsResponse)- assert resp.parsed.status == "completed"-- def test_in_progress_202(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="GET",- url=f"{BASE_URL}/api/batch/pool/batch-abc/results",- status_code=202,- json={"batch_id": "batch-abc", "status": "running", "message": "batch still running"},- )- resp = get_batch_results.sync_detailed(pool="pool", id="batch-abc", client=auth_client)- assert resp.status_code.value == 202- assert isinstance(resp.parsed, BatchInProgressResponse)-- def test_not_found(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="GET", url=f"{BASE_URL}/api/batch/pool/unknown/results", status_code=404, json={"error": "not found"}- )- assert get_batch_results.sync_detailed(pool="pool", id="unknown", client=auth_client).status_code.value == 404-- def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="GET", url=f"{BASE_URL}/api/label/pool/lbl/results", status_code=200, json=GOLDEN_LABEL_RESULTS- )- result = auth_client.get_label_results(pool="pool", label="lbl")- assert isinstance(result, LabelResultsResponse)---# ----------------------------------------------------------------------------# /api/batch/{pool}/{id} DELETE-# ------------------------------------------------------------------------------class TestCancelBatch:- @pytest.mark.parametrize(- "pool,id,expected_status",- [- ("test-pool", "batch-abc", "cancelling"),- ("prod-pool", "batch-xyz", "completed"),- ("staging", "batch-999", "cancelled"),- ],- )- def test_base(self, httpx_mock: HTTPXMock, auth_client, pool, id, expected_status):- httpx_mock.add_response(- method="DELETE",- url=f"{BASE_URL}/api/batch/{pool}/{id}",- status_code=200,- json={"batch_id": id, "status": expected_status},- )- resp = cancel_batch.sync_detailed(pool=pool, id=id, client=auth_client)- assert resp.status_code.value == 200- assert isinstance(resp.parsed, CancelBatchResponse)- assert resp.parsed.status == expected_status-- def test_not_found(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="DELETE", url=f"{BASE_URL}/api/batch/pool/unknown", status_code=404, json={"error": "not found"}- )- assert cancel_batch.sync_detailed(pool="pool", id="unknown", client=auth_client).status_code.value == 404-- def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="DELETE", url=f"{BASE_URL}/api/label/pool/test-label", status_code=200, json=GOLDEN_CANCEL_LABEL- )- result = auth_client.cancel_label(pool="pool", label="test-label")- assert isinstance(result, CancelLabelResponse)---# ----------------------------------------------------------------------------# /api/label/{pool}/{label}/batch POST-# ------------------------------------------------------------------------------class TestSubmitLabelBatch:- @pytest.mark.parametrize(- "pool,label,concurrency",- [- ("test-pool", "test-label", 1),- ("prod-pool", "prod-run-2026-05-20", 10),- ("staging", "label-with-dashes", 50),- ],- )- def test_base(self, httpx_mock: HTTPXMock, auth_client, pool, label, concurrency):- resp_body = {**GOLDEN_SUBMIT_RESP, "name": label}- httpx_mock.add_response(- method="POST", url=f"{BASE_URL}/api/label/{pool}/{label}/batch", status_code=202, json=resp_body- )- resp = submit_label_batch.sync_detailed(- pool=pool,- label=label,- client=auth_client,- body=BatchSubmitRequest(runs=[GOLDEN_RUN], concurrency=concurrency),- )- assert resp.status_code.value == 202- assert isinstance(resp.parsed, BatchSubmitResponse)-- def test_bad_request(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="POST",- url=f"{BASE_URL}/api/label/pool/test/batch",- status_code=400,- json={"error": "runs must not be empty"},- )- resp = submit_label_batch.sync_detailed(- pool="pool", label="test", client=auth_client, body=BatchSubmitRequest(runs=[])- )- assert resp.status_code.value == 400- assert isinstance(resp.parsed, ErrorResponse)-- def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="POST", url=f"{BASE_URL}/api/label/test-pool/my-run/batch", status_code=202, json=GOLDEN_SUBMIT_RESP- )- result = auth_client.submit_label_batch(- pool="test-pool", label="my-run", body=BatchSubmitRequest(runs=[GOLDEN_RUN])- )- assert isinstance(result, BatchSubmitResponse)---# ----------------------------------------------------------------------------# /api/label/{pool}/{label}/status GET-# ------------------------------------------------------------------------------GOLDEN_LABEL_STATUS = {- "label": "test-label",- "batch_count": 2,- "all_completed": False,- "progress": {"completed": 5, "total": 10, "ok": 4, "failed": 1},- "batches": [- {- "batch_id": "batch-abc",- "status": "running",- "progress": {"completed": 5, "total": 10, "ok": 4, "failed": 1},- "created_at": "2026-05-01T00:00:00Z",- "updated_at": "2026-05-01T01:00:00Z",- }- ],-}---class TestGetLabelStatus:- def test_base(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="GET",- url=f"{BASE_URL}/api/label/test-pool/test-label/status",- status_code=200,- json=GOLDEN_LABEL_STATUS,- )- resp = get_label_status.sync_detailed(pool="test-pool", label="test-label", client=auth_client)- assert resp.status_code.value == 200- assert isinstance(resp.parsed, LabelStatusResponse)- assert resp.parsed.all_completed is False-- def test_all_completed(self, httpx_mock: HTTPXMock, auth_client):- body = {**GOLDEN_LABEL_STATUS, "all_completed": True}- httpx_mock.add_response(method="GET", url=f"{BASE_URL}/api/label/pool/done/status", status_code=200, json=body)- assert (- get_label_status.sync_detailed(pool="pool", label="done", client=auth_client).parsed.all_completed is True- )-- def test_not_found(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="GET",- url=f"{BASE_URL}/api/label/pool/unknown/status",- status_code=404,- json={"error": "label not found"},- )- assert get_label_status.sync_detailed(pool="pool", label="unknown", client=auth_client).status_code.value == 404-- def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="GET", url=f"{BASE_URL}/api/label/pool/lbl/status", status_code=200, json=GOLDEN_LABEL_STATUS- )- result = auth_client.get_label_status(pool="pool", label="lbl")- assert isinstance(result, LabelStatusResponse)---# ----------------------------------------------------------------------------# /api/label/{pool}/{label}/results GET-# ------------------------------------------------------------------------------GOLDEN_LABEL_RESULTS = {- "label": "test-label",- "batch_count": 1,- "completed_batch_count": 1,- "all_completed": True,- "batches": [GOLDEN_BATCH_RESULTS],- "summary": GOLDEN_BATCH_RESULTS["summary"],-}---class TestGetLabelResults:- def test_base_completed(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="GET", url=f"{BASE_URL}/api/label/pool/lbl/results", status_code=200, json=GOLDEN_LABEL_RESULTS- )- resp = get_label_results.sync_detailed(pool="pool", label="lbl", client=auth_client)- assert resp.status_code.value == 200- assert isinstance(resp.parsed, LabelResultsResponse)- assert resp.parsed.all_completed is True-- def test_drain_mode(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="GET",- url=f"{BASE_URL}/api/label/pool/lbl/results?completed_only=true",- status_code=200,- json=GOLDEN_LABEL_RESULTS,- )- resp = get_label_results.sync_detailed(pool="pool", label="lbl", client=auth_client, completed_only=True)- assert resp.status_code.value == 200-- def test_in_progress_202(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="GET",- url=f"{BASE_URL}/api/label/pool/lbl/results",- status_code=202,- json={"label": "lbl", "batch_count": 1, "all_completed": False, "message": "still running"},- )- resp = get_label_results.sync_detailed(pool="pool", label="lbl", client=auth_client)- assert resp.status_code.value == 202- assert isinstance(resp.parsed, LabelInProgressResponse)-- @pytest.mark.parametrize(- "pool,label",- [- ("test-pool", "test-label"),- ("prod-pool", "prod-2026"),- ("staging", "my-experiment"),- ],- )- def test_generated_pool_label(self, httpx_mock: HTTPXMock, auth_client, pool, label):- body = {**GOLDEN_LABEL_RESULTS, "label": label}- httpx_mock.add_response(- method="GET", url=f"{BASE_URL}/api/label/{pool}/{label}/results", status_code=200, json=body- )- resp = get_label_results.sync_detailed(pool=pool, label=label, client=auth_client)- assert resp.parsed.label == label-- def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="GET", url=f"{BASE_URL}/api/label/pool/lbl/results", status_code=200, json=GOLDEN_LABEL_RESULTS- )- result = auth_client.get_label_results(pool="pool", label="lbl")- assert isinstance(result, LabelResultsResponse)---# ----------------------------------------------------------------------------# /api/label/{pool}/{label} DELETE-# ------------------------------------------------------------------------------GOLDEN_CANCEL_LABEL = {- "label": "test-label",- "batch_count": 2,- "cancelled_count": 1,- "already_done": 1,- "batches": [- {"batch_id": "batch-abc", "status": "cancelling"},- {"batch_id": "batch-xyz", "status": "completed"},- ],-}---class TestCancelLabel:- @pytest.mark.parametrize(- "pool,label",- [- ("test-pool", "test-label"),- ("prod-pool", "prod-run"),- ("staging", "experiment-42"),- ],- )- def test_base(self, httpx_mock: HTTPXMock, auth_client, pool, label):- body = {**GOLDEN_CANCEL_LABEL, "label": label}- httpx_mock.add_response(method="DELETE", url=f"{BASE_URL}/api/label/{pool}/{label}", status_code=200, json=body)- resp = cancel_label.sync_detailed(pool=pool, label=label, client=auth_client)- assert resp.status_code.value == 200- assert isinstance(resp.parsed, CancelLabelResponse)-- def test_not_found(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="DELETE",- url=f"{BASE_URL}/api/label/pool/unknown",- status_code=404,- json={"error": "label not found"},- )- assert cancel_label.sync_detailed(pool="pool", label="unknown", client=auth_client).status_code.value == 404-- def test_flat_wrapper(self, httpx_mock: HTTPXMock, auth_client):- httpx_mock.add_response(- method="DELETE", url=f"{BASE_URL}/api/label/pool/lbl", status_code=200, json=GOLDEN_CANCEL_LABEL- )- result = auth_client.cancel_label(pool="pool", label="lbl")- assert isinstance(result, CancelLabelResponse)diff --git a/libs/fleet/python-sdk/tests/test_models.py b/libs/fleet/python-sdk/tests/test_models.pydeleted file mode 100644index cb6ce7df94..0000000000--- a/libs/fleet/python-sdk/tests/test_models.py+++ /dev/null@@ -1,61 +0,0 @@-"""Smoke tests — verify models and TrainClient can be imported and instantiated."""--from cua_train import AuthenticatedClient, TrainClient-from cua_train.models import (- Action,- ActionParameters,- BatchProgress,- BatchSubmitRequest,- LabelStatusResponse,- RunConfig,-)---def test_batch_submit_request_instantiation():- click = Action(action_type="CLICK", parameters=ActionParameters.from_dict({"x": 1, "y": 2}))- req = BatchSubmitRequest(- runs=[RunConfig(steps=[click], timeout=60)],- concurrency=2,- )- assert len(req.runs) == 1- assert req.runs[0].steps[0].action_type == "CLICK"---def test_label_status_response_instantiation():- resp = LabelStatusResponse(- label="test-label",- batch_count=1,- all_completed=False,- progress=BatchProgress(completed=0, total=1, ok=0, failed=0),- batches=[],- )- assert resp.label == "test-label"---def test_train_client_is_subclass():- """TrainClient must be a drop-in for AuthenticatedClient."""- assert issubclass(TrainClient, AuthenticatedClient)---def test_client_exposes_generated_operations():- """Every generated endpoint is reachable as a method on the client- (its sync(), client pre-bound), with no hand-written wrapper."""- import pytest-- c = TrainClient(base_url="https://example.invalid", token="t")-- # A representative op from each tag is exposed and callable.- for op in (- "acquire_lanes",- "release_lanes",- "submit_batch",- "submit_label_batch",- "get_label_results",- "list_keys",- "healthz",- ):- assert callable(getattr(c, op)), f"client.{op} should be callable"-- # Unknown attributes still raise AttributeError (so copy/pickle/etc. behave).- with pytest.raises(AttributeError):- c.definitely_not_an_endpointdiff --git a/libs/fleet/python-sdk/tests/test_wheel_build.py b/libs/fleet/python-sdk/tests/test_wheel_build.pydeleted file mode 100644index 25dff8c70a..0000000000--- a/libs/fleet/python-sdk/tests/test_wheel_build.py+++ /dev/null@@ -1,135 +0,0 @@-import csv-import importlib.util-import subprocess-import sys-import tempfile-import unittest-import zipfile-from pathlib import Path-from unittest.mock import patch---class WheelBuildTest(unittest.TestCase):- def test_windows_x86_64_wheel_contains_generated_loader_dll_and_platform_tag(self):- project = Path(__file__).resolve().parents[1]- builder_path = project / "scripts" / "build_wheel.py"- spec = importlib.util.spec_from_file_location("build_wheel", builder_path)- assert spec and spec.loader- build_wheel = importlib.util.module_from_spec(spec)- spec.loader.exec_module(build_wheel)-- with (- patch.object(build_wheel.sys, "platform", "win32"),- patch.object(build_wheel.platform, "machine", return_value="AMD64"),- ):- self.assertEqual("cyclops_sdk.dll", build_wheel.native_library_name())- self.assertEqual("win_amd64", build_wheel.default_platform_tag())- self.assertEqual("cyclops_sdk.dll", build_wheel.native_library_name_for_platform_tag("win_amd64"))-- with tempfile.TemporaryDirectory() as temporary_directory:- temporary = Path(temporary_directory)- native_library = temporary / "cyclops_sdk.dll"- native_library.write_bytes(b"not a native library")- output = temporary / "dist"-- subprocess.run(- [- sys.executable,- "scripts/build_wheel.py",- "--native-library",- str(native_library),- "--platform-tag",- "win_amd64",- "--outdir",- str(output),- ],- cwd=project,- check=True,- )-- wheels = list(output.glob("*.whl"))- self.assertEqual([wheel.name for wheel in wheels], ["cua_train-0.1.6-py3-none-win_amd64.whl"])- with zipfile.ZipFile(wheels[0]) as archive:- names = archive.namelist()- self.assertIn("fleet_sdk/cyclops_sdk.dll", names)- wheel_metadata = next(name for name in names if name.endswith(".dist-info/WHEEL"))- self.assertIn("Root-Is-Purelib: false", archive.read(wheel_metadata).decode())- self.assertIn("Tag: py3-none-win_amd64", archive.read(wheel_metadata).decode())- record = next(name for name in names if name.endswith(".dist-info/RECORD"))- record_rows = list(csv.reader(archive.read(record).decode().splitlines()))- self.assertIn(- ["fleet_sdk/cyclops_sdk.dll", "sha256=U9PN3aRS1FqC5Fx0fZQjZf4JXxMTFG6yOsDsB5DOjD0", "20"],- record_rows,- )-- def test_wheel_build_rejects_a_native_library_name_the_loader_cannot_find(self):- project = Path(__file__).resolve().parents[1]- with tempfile.TemporaryDirectory() as temporary_directory:- temporary = Path(temporary_directory)- native_library = temporary / "libcyclops_sdk.so"- native_library.write_bytes(b"not a native library")-- process = subprocess.run(- [- sys.executable,- "scripts/build_wheel.py",- "--native-library",- str(native_library),- "--platform-tag",- "win_amd64",- "--outdir",- str(temporary / "dist"),- ],- cwd=project,- text=True,- capture_output=True,- )-- self.assertNotEqual(0, process.returncode)- self.assertIn("native library must be named cyclops_sdk.dll", process.stderr)-- def test_staged_wheel_contains_native_binding_and_platform_tag(self):- project = Path(__file__).resolve().parents[1]- with tempfile.TemporaryDirectory() as temporary_directory:- temporary = Path(temporary_directory)- native_library = temporary / "libcyclops_sdk.so"- native_library.write_bytes(b"not a native library")- output = temporary / "dist"-- subprocess.run(- [- sys.executable,- "scripts/build_wheel.py",- "--native-library",- str(native_library),- "--platform-tag",- "linux_x86_64",- "--outdir",- str(output),- ],- cwd=project,- check=True,- )-- wheels = list(output.glob("*.whl"))- self.assertEqual([wheel.name for wheel in wheels], ["cua_train-0.1.6-py3-none-linux_x86_64.whl"])- with zipfile.ZipFile(wheels[0]) as archive:- names = archive.namelist()- self.assertIn("fleet_sdk/__init__.py", names)- self.assertIn("fleet_sdk/_sdk.py", names)- self.assertIn("fleet_sdk/_schema.py", names)- self.assertIn("fleet_sdk/libcyclops_sdk.so", names)- self.assertIn("cua_train/__init__.py", names)- wheel_metadata = next(name for name in names if name.endswith(".dist-info/WHEEL"))- self.assertIn("Root-Is-Purelib: false", archive.read(wheel_metadata).decode())- self.assertIn("Tag: py3-none-linux_x86_64", archive.read(wheel_metadata).decode())- record = next(name for name in names if name.endswith(".dist-info/RECORD"))- record_rows = list(csv.reader(archive.read(record).decode().splitlines()))- self.assertIn(- ["fleet_sdk/libcyclops_sdk.so", "sha256=U9PN3aRS1FqC5Fx0fZQjZf4JXxMTFG6yOsDsB5DOjD0", "20"],- record_rows,- )---if __name__ == "__main__":- unittest.main()diff --git a/libs/fleet/scripts/build-python-sdk-wheel.py b/libs/fleet/scripts/build-python-sdk-wheel.pynew file mode 100755index 0000000000..16c3e304c6--- /dev/null+++ b/libs/fleet/scripts/build-python-sdk-wheel.py@@ -0,0 +1,223 @@+#!/usr/bin/env python3+"""Build a platform wheel containing only the generated Fleet UniFFI binding."""++from __future__ import annotations++import argparse+import base64+import csv+import hashlib+import io+import platform+import re+import shutil+import subprocess+import sys+import tempfile+import zipfile+from pathlib import Path++DISTRIBUTION_NAME = "cua-fleet"+DISTRIBUTION_STEM = "cua_fleet"+PACKAGE_NAME = "fleet_sdk"+VERSION_PATTERN = re.compile(r"[0-9]+\.[0-9]+\.[0-9]+")+++def parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser()+ parser.add_argument("--version", required=True)+ parser.add_argument("--outdir", type=Path, default=Path("dist"))+ parser.add_argument("--native-library", type=Path)+ parser.add_argument("--platform-tag")+ parser.add_argument("--cargo-target")+ return parser.parse_args()+++def repository_root() -> Path:+ return Path(__file__).resolve().parents[2]+++def native_library_name() -> str:+ if sys.platform == "darwin":+ return "libcyclops_sdk.dylib"+ if sys.platform.startswith("linux"):+ return "libcyclops_sdk.so"+ if sys.platform.startswith("win"):+ return "cyclops_sdk.dll"+ raise RuntimeError(f"unsupported wheel build platform: {sys.platform}")+++def default_platform_tag() -> str:+ machine = platform.machine().lower()+ aliases = {"amd64": "x86_64", "aarch64": "arm64"}+ machine = aliases.get(machine, machine)++ if sys.platform.startswith("linux"):+ linux_arches = {"x86_64": "x86_64", "arm64": "aarch64"}+ try:+ return f"linux_{linux_arches[machine]}"+ except KeyError as error:+ raise RuntimeError(f"unsupported Linux architecture: {machine}") from error++ if sys.platform == "darwin":+ macos_versions = {"x86_64": "10_13", "arm64": "11_0"}+ try:+ return f"macosx_{macos_versions[machine]}_{machine}"+ except KeyError as error:+ raise RuntimeError(f"unsupported macOS architecture: {machine}") from error++ if sys.platform.startswith("win"):+ if machine != "x86_64":+ raise RuntimeError(f"unsupported Windows architecture: {machine}")+ return "win_amd64"++ raise RuntimeError(f"unsupported wheel build platform: {sys.platform}")+++def native_library_name_for_platform_tag(platform_tag: str) -> str:+ if platform_tag == "win_amd64":+ return "cyclops_sdk.dll"+ if platform_tag.startswith("linux_") or platform_tag.startswith("manylinux_"):+ return "libcyclops_sdk.so"+ if platform_tag.startswith("macosx_"):+ return "libcyclops_sdk.dylib"+ raise RuntimeError(f"unsupported wheel platform tag: {platform_tag}")+++def build_native_library(repo_root: Path, cargo_target: str | None, expected_name: str) -> Path:+ command = [+ "cargo",+ "build",+ "--locked",+ "--manifest-path",+ str(repo_root / "cyclops-cs" / "Cargo.toml"),+ "--package",+ "cyclops-sdk",+ "--release",+ ]+ if cargo_target:+ command.extend(["--target", cargo_target])+ subprocess.run(command, check=True)++ target_directory = repo_root / "cyclops-cs" / "target"+ if cargo_target:+ target_directory /= cargo_target+ library = target_directory / "release" / expected_name+ if not library.is_file():+ raise RuntimeError(f"Cargo did not produce expected native library: {library}")+ return library+++def sha256_record(data: bytes) -> tuple[str, str]:+ digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode()+ return f"sha256={digest}", str(len(data))+++def csv_bytes(rows: list[list[str]]) -> bytes:+ output = io.StringIO()+ csv.writer(output, lineterminator="\n").writerows(rows)+ return output.getvalue().encode()+++def package_entries(repo_root: Path, native_library: Path, expected_name: str) -> dict[str, bytes]:+ source = repo_root / "cyclops-cs" / "sdk-bindings" / "python" / PACKAGE_NAME+ if not source.is_dir():+ raise RuntimeError(f"generated Python binding is missing: {source}")++ entries: dict[str, bytes] = {}+ for path in sorted(source.rglob("*")):+ if not path.is_file() or "__pycache__" in path.parts or path.suffix in {".so", ".dylib", ".dll"}:+ continue+ archive_name = f"{PACKAGE_NAME}/{path.relative_to(source).as_posix()}"+ entries[archive_name] = path.read_bytes()+ entries[f"{PACKAGE_NAME}/{expected_name}"] = native_library.read_bytes()+ return entries+++def build_wheel(+ repo_root: Path,+ version: str,+ output_directory: Path,+ native_library: Path | None,+ platform_tag: str | None,+ cargo_target: str | None,+) -> Path:+ if not VERSION_PATTERN.fullmatch(version):+ raise RuntimeError(f"cua-fleet version must be X.Y.Z, got: {version}")++ tag = platform_tag or default_platform_tag()+ expected_name = native_library_name_for_platform_tag(tag)+ library = native_library or build_native_library(repo_root, cargo_target, expected_name)+ library = library.resolve()+ if not library.is_file():+ raise RuntimeError(f"native library does not exist: {library}")+ if library.name != expected_name:+ raise RuntimeError(f"native library must be named {expected_name}, got {library.name}")++ entries = package_entries(repo_root, library, expected_name)+ dist_info = f"{DISTRIBUTION_STEM}-{version}.dist-info"+ entries[f"{dist_info}/METADATA"] = (+ "Metadata-Version: 2.4\n"+ f"Name: {DISTRIBUTION_NAME}\n"+ f"Version: {version}\n"+ "Summary: Python bindings for the Cua Fleet SDK\n"+ "Requires-Python: >=3.10\n"+ "License-Expression: MIT\n"+ "\n"+ ).encode()+ entries[f"{dist_info}/WHEEL"] = (+ "Wheel-Version: 1.0\n"+ "Generator: build-python-sdk-wheel.py\n"+ "Root-Is-Purelib: false\n"+ f"Tag: py3-none-{tag}\n"+ "\n"+ ).encode()++ allowed_roots = {PACKAGE_NAME, dist_info}+ roots = {name.split("/", 1)[0] for name in entries}+ if roots != allowed_roots:+ raise RuntimeError(f"unexpected wheel payload roots: {sorted(roots)}")++ record_name = f"{dist_info}/RECORD"+ record_rows = []+ for name in sorted(entries):+ digest, size = sha256_record(entries[name])+ record_rows.append([name, digest, size])+ record_rows.append([record_name, "", ""])+ entries[record_name] = csv_bytes(record_rows)++ output_directory = output_directory.resolve()+ output_directory.mkdir(parents=True, exist_ok=True)+ wheel = output_directory / f"{DISTRIBUTION_STEM}-{version}-py3-none-{tag}.whl"+ with tempfile.NamedTemporaryFile(dir=output_directory, suffix=".whl", delete=False) as temporary:+ temporary_path = Path(temporary.name)+ try:+ with zipfile.ZipFile(temporary_path, "w", compression=zipfile.ZIP_DEFLATED) as archive:+ for name in sorted(entries):+ archive.writestr(name, entries[name])+ shutil.move(temporary_path, wheel)+ finally:+ temporary_path.unlink(missing_ok=True)+ return wheel+++def main() -> int:+ args = parse_args()+ try:+ wheel = build_wheel(+ repository_root(),+ args.version,+ args.outdir,+ args.native_library,+ args.platform_tag,+ args.cargo_target,+ )+ except (OSError, RuntimeError, subprocess.CalledProcessError) as error:+ print(f"error: {error}", file=sys.stderr)+ return 1+ print(wheel)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/libs/fleet/scripts/generate-sdk-bindings.sh b/libs/fleet/scripts/generate-sdk-bindings.shindex 432cc9d5fb..a8d799f258 100755--- a/libs/fleet/scripts/generate-sdk-bindings.sh+++ b/libs/fleet/scripts/generate-sdk-bindings.sh@@ -807,8 +807,8 @@ def replace_buffer(match):f"{indent})")text, buffer_replacements = re.subn(buffer_pattern, replace_buffer, text)-if buffer_replacements != 20:- raise SystemExit(f"expected 20 Ruby Rust-buffer future wrappers, found {buffer_replacements}")+if buffer_replacements != 21:+ raise SystemExit(f"expected 21 Ruby Rust-buffer future wrappers, found {buffer_replacements}")void_pattern = r"(?m)^(\s*)FleetSdk\.rust_call_with_error\(([^,]+),:([a-z0-9_]+),(.*)\)$"def replace_void(match):diff --git a/libs/fleet/scripts/tests/test_build_python_sdk_wheel.py b/libs/fleet/scripts/tests/test_build_python_sdk_wheel.pynew file mode 100644index 0000000000..801855ed33--- /dev/null+++ b/libs/fleet/scripts/tests/test_build_python_sdk_wheel.py@@ -0,0 +1,154 @@+import csv+import importlib.util+import subprocess+import sys+import tempfile+import unittest+import zipfile+from pathlib import Path+from unittest.mock import patch+++SCRIPT = Path(__file__).resolve().parents[1] / "build-python-sdk-wheel.py"+CYCLOPS_ROOT = Path(__file__).resolve().parents[2]+++def load_builder():+ spec = importlib.util.spec_from_file_location("build_python_sdk_wheel", SCRIPT)+ assert spec and spec.loader+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++class PythonSdkWheelBuildTest(unittest.TestCase):+ def test_windows_x86_64_wheel_contains_only_generated_sdk_and_dll(self):+ builder = load_builder()+ with (+ patch.object(builder.sys, "platform", "win32"),+ patch.object(builder.platform, "machine", return_value="AMD64"),+ ):+ self.assertEqual("cyclops_sdk.dll", builder.native_library_name())+ self.assertEqual("win_amd64", builder.default_platform_tag())++ with tempfile.TemporaryDirectory() as temporary_directory:+ temporary = Path(temporary_directory)+ native_library = temporary / "cyclops_sdk.dll"+ native_library.write_bytes(b"not a native library")+ output = temporary / "dist"++ subprocess.run(+ [+ sys.executable,+ str(SCRIPT),+ "--version",+ "0.1.0",+ "--native-library",+ str(native_library),+ "--platform-tag",+ "win_amd64",+ "--outdir",+ str(output),+ ],+ cwd=CYCLOPS_ROOT,+ check=True,+ )++ wheels = list(output.glob("*.whl"))+ self.assertEqual(+ [wheel.name for wheel in wheels],+ ["cua_fleet-0.1.0-py3-none-win_amd64.whl"],+ )+ with zipfile.ZipFile(wheels[0]) as archive:+ names = archive.namelist()+ roots = {name.split("/", 1)[0] for name in names}+ self.assertEqual(roots, {"fleet_sdk", "cua_fleet-0.1.0.dist-info"})+ self.assertIn("fleet_sdk/cyclops_sdk.dll", names)+ self.assertNotIn("cua_train/__init__.py", names)+ self.assertNotIn("cua_fleet/__init__.py", names)+ metadata = archive.read("cua_fleet-0.1.0.dist-info/METADATA").decode()+ self.assertIn("Name: cua-fleet", metadata)+ self.assertIn("Version: 0.1.0", metadata)+ self.assertNotIn("Requires-Dist:", metadata)+ wheel_metadata = archive.read("cua_fleet-0.1.0.dist-info/WHEEL").decode()+ self.assertIn("Root-Is-Purelib: false", wheel_metadata)+ self.assertIn("Tag: py3-none-win_amd64", wheel_metadata)+ record_rows = list(+ csv.reader(+ archive.read("cua_fleet-0.1.0.dist-info/RECORD")+ .decode()+ .splitlines()+ )+ )+ self.assertIn(+ [+ "fleet_sdk/cyclops_sdk.dll",+ "sha256=U9PN3aRS1FqC5Fx0fZQjZf4JXxMTFG6yOsDsB5DOjD0",+ "20",+ ],+ record_rows,+ )++ def test_linux_wheel_contains_checked_in_binding_and_native_library(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ temporary = Path(temporary_directory)+ native_library = temporary / "libcyclops_sdk.so"+ native_library.write_bytes(b"not a native library")+ output = temporary / "dist"++ subprocess.run(+ [+ sys.executable,+ str(SCRIPT),+ "--version",+ "0.1.0",+ "--native-library",+ str(native_library),+ "--platform-tag",+ "linux_x86_64",+ "--outdir",+ str(output),+ ],+ cwd=CYCLOPS_ROOT,+ check=True,+ )++ wheel = next(output.glob("*.whl"))+ self.assertEqual(wheel.name, "cua_fleet-0.1.0-py3-none-linux_x86_64.whl")+ with zipfile.ZipFile(wheel) as archive:+ names = archive.namelist()+ self.assertIn("fleet_sdk/__init__.py", names)+ self.assertIn("fleet_sdk/_sdk.py", names)+ self.assertIn("fleet_sdk/_schema.py", names)+ self.assertIn("fleet_sdk/libcyclops_sdk.so", names)++ def test_rejects_native_library_name_the_generated_loader_cannot_find(self):+ with tempfile.TemporaryDirectory() as temporary_directory:+ temporary = Path(temporary_directory)+ native_library = temporary / "libcyclops_sdk.so"+ native_library.write_bytes(b"not a native library")++ process = subprocess.run(+ [+ sys.executable,+ str(SCRIPT),+ "--version",+ "0.1.0",+ "--native-library",+ str(native_library),+ "--platform-tag",+ "win_amd64",+ "--outdir",+ str(temporary / "dist"),+ ],+ cwd=CYCLOPS_ROOT,+ text=True,+ capture_output=True,+ )++ self.assertNotEqual(0, process.returncode)+ self.assertIn("native library must be named cyclops_sdk.dll", process.stderr)+++if __name__ == "__main__":+ unittest.main()diff --git a/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.go b/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.goindex fffef5a2b4..ee034f8542 100644--- a/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.go+++ b/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.go@@ -412,6 +412,15 @@ func uniffiCheckChecksums() {panic("fleet_sdk: uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims: UniFFI API checksum mismatch")}}+ {+ checksum := rustCall(func(_uniffiStatus *C.RustCallStatus) C.uint16_t {+ return C.uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim()+ })+ if checksum != 17505 {+ // If this happens try cleaning and rebuilding your project+ panic("fleet_sdk: uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim: UniFFI API checksum mismatch")+ }+ }{checksum := rustCall(func(_uniffiStatus *C.RustCallStatus) C.uint16_t {return C.uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim()@@ -1192,6 +1201,13 @@ type CyclopsClientInterface interface {DeleteClaim(claim Claim) errorGetClaim(claim Claim) (Claim, error)ListClaims(namespace string) ([]Claim, error)+ // Push the claim's `spec.lifecycle.shutdownTime` forward. That absolute+ // expiry is the only liveness input the pool operator's claim reaper+ // honors, so a holder that outlives its current lease must renew before+ // the deadline passes or the bound sandbox is deleted underneath it.+ // Deliberately narrower than a claim update: nothing else on the claim+ // can be mutated through the SDK.+ RenewClaim(claim Claim, shutdownTime string) (Claim, error)WaitClaim(claim Claim) (Sandbox, error)ListNamespaces() ([]Namespace, error)CreatePool(request CreatePoolRequest) (Pool, error)@@ -1435,6 +1451,47 @@ func (_self *CyclopsClient) ListClaims(namespace string) ([]Claim, error) {return res, err}+// Push the claim's `spec.lifecycle.shutdownTime` forward. That absolute+// expiry is the only liveness input the pool operator's claim reaper+// honors, so a holder that outlives its current lease must renew before+// the deadline passes or the bound sandbox is deleted underneath it.+// Deliberately narrower than a claim update: nothing else on the claim+// can be mutated through the SDK.+func (_self *CyclopsClient) RenewClaim(claim Claim, shutdownTime string) (Claim, error) {+ _pointer := _self.ffiObject.incrementPointer("*CyclopsClient")+ defer _self.ffiObject.decrementPointer()+ res, err := uniffiRustCallAsync[*SdkError](+ FfiConverterSdkErrorINSTANCE,+ // completeFn+ func(handle C.uint64_t, status *C.RustCallStatus) RustBufferI {+ res := C.ffi_cyclops_sdk_rust_future_complete_rust_buffer(handle, status)+ return GoRustBuffer{+ inner: res,+ }+ },+ // liftFn+ func(ffi RustBufferI) Claim {+ return FfiConverterClaimINSTANCE.Lift(ffi)+ },+ C.uniffi_cyclops_sdk_fn_method_cyclopsclient_renew_claim(+ _pointer, FfiConverterClaimINSTANCE.Lower(claim), FfiConverterStringINSTANCE.Lower(shutdownTime)),+ // pollFn+ func(handle C.uint64_t, continuation C.UniffiRustFutureContinuationCallback, data C.uint64_t) {+ C.ffi_cyclops_sdk_rust_future_poll_rust_buffer(handle, continuation, data)+ },+ // freeFn+ func(handle C.uint64_t) {+ C.ffi_cyclops_sdk_rust_future_free_rust_buffer(handle)+ },+ )++ if err == nil {+ return res, nil+ }++ return res, err+}+func (_self *CyclopsClient) WaitClaim(claim Claim) (Sandbox, error) {_pointer := _self.ffiObject.incrementPointer("*CyclopsClient")defer _self.ffiObject.decrementPointer()@@ -2439,11 +2496,16 @@ func (_ FfiDestroyerClaim) Destroy(value Claim) {type CreateClaimRequest struct {Pool PoolSpec *cyclops_sdk_schema.ClaimSpec+ // Explicit claim name. A client-supplied name is used verbatim (after+ // DNS-label validation); left unset, the client generates a random+ // `claim-<petname>` so concurrent leases and retries cannot collide.+ Name *string}func (r *CreateClaimRequest) Destroy() {FfiDestroyerPool{}.Destroy(r.Pool)FfiDestroyerOptionalClaimSpec{}.Destroy(r.Spec)+ FfiDestroyerOptionalString{}.Destroy(r.Name)}type FfiConverterCreateClaimRequest struct{}@@ -2458,6 +2520,7 @@ func (c FfiConverterCreateClaimRequest) Read(reader io.Reader) CreateClaimRequesreturn CreateClaimRequest{FfiConverterPoolINSTANCE.Read(reader),FfiConverterOptionalClaimSpecINSTANCE.Read(reader),+ FfiConverterOptionalStringINSTANCE.Read(reader),}}@@ -2472,6 +2535,7 @@ func (c FfiConverterCreateClaimRequest) LowerExternal(value CreateClaimRequest)func (c FfiConverterCreateClaimRequest) Write(writer io.Writer, value CreateClaimRequest) {FfiConverterPoolINSTANCE.Write(writer, value.Pool)FfiConverterOptionalClaimSpecINSTANCE.Write(writer, value.Spec)+ FfiConverterOptionalStringINSTANCE.Write(writer, value.Name)}type FfiDestroyerCreateClaimRequest struct{}diff --git a/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.h b/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.hindex 26eb4462fb..a5c7f9ff63 100644--- a/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.h+++ b/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk/fleet_sdk.h@@ -481,6 +481,11 @@ uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_get_claim(uint64_t ptr, Rustuint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims(uint64_t ptr, RustBuffer namespace);#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_RENEW_CLAIM+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_RENEW_CLAIM+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_renew_claim(uint64_t ptr, RustBuffer claim, RustBuffer shutdown_time+);+#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_WAIT_CLAIM#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_WAIT_CLAIMuint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(uint64_t ptr, RustBuffer claim@@ -908,6 +913,12 @@ uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim(void#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_CLAIMSuint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims(void+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_RENEW_CLAIM+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_RENEW_CLAIM+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim(void+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_WAIT_CLAIM@@ -919,7 +930,7 @@ uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim(void#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_NAMESPACES#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_NAMESPACESuint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces(void-+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_CREATE_POOL@@ -1003,19 +1014,19 @@ uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template(void#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_CREATE_USER_API_KEY#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_CREATE_USER_API_KEYuint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_create_user_api_key(void-+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_DELETE_USER_API_KEY#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_DELETE_USER_API_KEYuint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_delete_user_api_key(void-+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_USER_API_KEYS#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_USER_API_KEYSuint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys(void-+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_ACCESSTOKENPROVIDER_GET_ACCESS_TOKENdiff --git a/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.kt b/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.ktindex 1874750e51..2e114d72ab 100644--- a/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.kt+++ b/libs/fleet/sdk-bindings/kotlin/ai/cua/cyclops/sdk/fleet_sdk.kt@@ -710,6 +710,8 @@ internal object IntegrityCheckingUniffiLib {): Shortexternal fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims(): Short+ external fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim(+ ): Shortexternal fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim(): Shortexternal fun uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_namespaces(@@ -813,6 +815,8 @@ external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_get_claim(`ptr`: Long,`c): Longexternal fun uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims(`ptr`: Long,`namespace`: RustBuffer.ByValue,): Long+external fun uniffi_cyclops_sdk_fn_method_cyclopsclient_renew_claim(`ptr`: Long,`claim`: RustBuffer.ByValue,`shutdownTime`: RustBuffer.ByValue,+): Longexternal fun uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(`ptr`: Long,`claim`: RustBuffer.ByValue,): Longexternal fun uniffi_cyclops_sdk_fn_method_cyclopsclient_list_namespaces(`ptr`: Long,@@ -1002,6 +1006,9 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims() != 7802.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}+ if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim() != 17505.toShort()) {+ throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ }if (lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim() != 18984.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}@@ -2013,6 +2020,16 @@ public interface CyclopsClientInterface {suspend fun `listClaims`(`namespace`: kotlin.String): List<Claim>+ /**+ * Push the claim's `spec.lifecycle.shutdownTime` forward. That absolute+ * expiry is the only liveness input the pool operator's claim reaper+ * honors, so a holder that outlives its current lease must renew before+ * the deadline passes or the bound sandbox is deleted underneath it.+ * Deliberately narrower than a claim update: nothing else on the claim+ * can be mutated through the SDK.+ */+ suspend fun `renewClaim`(`claim`: Claim, `shutdownTime`: kotlin.String): Claim+suspend fun `waitClaim`(`claim`: Claim): Sandboxsuspend fun `listNamespaces`(): List<Namespace>@@ -2234,6 +2251,35 @@ open class CyclopsClient: Disposable, AutoCloseable, CyclopsClientInterface}+ /**+ * Push the claim's `spec.lifecycle.shutdownTime` forward. That absolute+ * expiry is the only liveness input the pool operator's claim reaper+ * honors, so a holder that outlives its current lease must renew before+ * the deadline passes or the bound sandbox is deleted underneath it.+ * Deliberately narrower than a claim update: nothing else on the claim+ * can be mutated through the SDK.+ */+ @Throws(SdkException::class)+ @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")+ override suspend fun `renewClaim`(`claim`: Claim, `shutdownTime`: kotlin.String) : Claim {+ return uniffiRustCallAsync(+ callWithHandle { uniffiHandle ->+ UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_renew_claim(+ uniffiHandle,+ FfiConverterTypeClaim.lower(`claim`),FfiConverterString.lower(`shutdownTime`),+ )+ },+ { future, callback, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer(future, callback, continuation) },+ { future, continuation -> UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer(future, continuation) },+ { future -> UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer(future) },+ // lift function+ { FfiConverterTypeClaim.lift(it) },+ // Error FFI converter+ SdkException.ErrorHandler,+ )+ }++@Throws(SdkException::class)@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")override suspend fun `waitClaim`(`claim`: Claim) : Sandbox {@@ -3372,6 +3418,13 @@ data class CreateClaimRequest (var `pool`: Pool,var `spec`: ClaimSpec?+ ,+ /**+ * Explicit claim name. A client-supplied name is used verbatim (after+ * DNS-label validation); left unset, the client generates a random+ * `claim-<petname>` so concurrent leases and retries cannot collide.+ */+ var `name`: kotlin.String? = null){@@ -3390,17 +3443,20 @@ public object FfiConverterTypeCreateClaimRequest: FfiConverterRustBuffer<CreateCreturn CreateClaimRequest(FfiConverterTypePool.read(buf),FfiConverterOptionalTypeClaimSpec.read(buf),+ FfiConverterOptionalString.read(buf),)}override fun allocationSize(value: CreateClaimRequest) = (FfiConverterTypePool.allocationSize(value.`pool`) +- FfiConverterOptionalTypeClaimSpec.allocationSize(value.`spec`)+ FfiConverterOptionalTypeClaimSpec.allocationSize(value.`spec`) ++ FfiConverterOptionalString.allocationSize(value.`name`))override fun write(value: CreateClaimRequest, buf: ByteBuffer) {FfiConverterTypePool.write(value.`pool`, buf)FfiConverterOptionalTypeClaimSpec.write(value.`spec`, buf)+ FfiConverterOptionalString.write(value.`name`, buf)}}diff --git a/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.py b/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.pyindex f0e0b969e7..4fce16d3ef 100644--- a/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.py+++ b/libs/fleet/sdk-bindings/python/fleet_sdk/_sdk.py@@ -532,6 +532,8 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_template() != 36469:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim() != 17505:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request() != 46699:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_pool() != 17695:@@ -1023,6 +1025,12 @@ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_reconcile_template.argtype_UniffiRustBuffer,)_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_reconcile_template.restype = ctypes.c_uint64+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_renew_claim.argtypes = (+ ctypes.c_uint64,+ _UniffiRustBuffer,+ _UniffiRustBuffer,+)+_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_renew_claim.restype = ctypes.c_uint64_UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_service_request.argtypes = (ctypes.c_uint64,_UniffiRustBuffer,@@ -1138,6 +1146,9 @@ _UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_pool.resty_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_template.argtypes = ()_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_template.restype = ctypes.c_uint16+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim.argtypes = (+)+_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim.restype = ctypes.c_uint16_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request.argtypes = ()_UniffiLib.uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request.restype = ctypes.c_uint16@@ -1652,20 +1663,26 @@ class _UniffiFfiConverterOptionalTypeClaimSpec(_UniffiConverterRustBuffer):@dataclassclass CreateClaimRequest:- def __init__(self, *, pool:Pool, spec:typing.Optional[fleet_sdk.ClaimSpec]):+ def __init__(self, *, pool:Pool, spec:typing.Optional[fleet_sdk.ClaimSpec], name:typing.Optional[str] = _DEFAULT):self.pool = poolself.spec = spec+ if name is _DEFAULT:+ self.name = None+ else:+ self.name = namedef __str__(self):- return "CreateClaimRequest(pool={}, spec={})".format(self.pool, self.spec)+ return "CreateClaimRequest(pool={}, spec={}, name={})".format(self.pool, self.spec, self.name)def __eq__(self, other):if self.pool != other.pool:return Falseif self.spec != other.spec:return False+ if self.name != other.name:+ return Falsereturn Trueclass _UniffiFfiConverterTypeCreateClaimRequest(_UniffiConverterRustBuffer):@@ -1674,17 +1691,20 @@ class _UniffiFfiConverterTypeCreateClaimRequest(_UniffiConverterRustBuffer):return CreateClaimRequest(pool=_UniffiFfiConverterTypePool.read(buf),spec=_UniffiFfiConverterOptionalTypeClaimSpec.read(buf),+ name=_UniffiFfiConverterOptionalString.read(buf),)@staticmethoddef check_lower(value):_UniffiFfiConverterTypePool.check_lower(value.pool)_UniffiFfiConverterOptionalTypeClaimSpec.check_lower(value.spec)+ _UniffiFfiConverterOptionalString.check_lower(value.name)@staticmethoddef write(value, buf):_UniffiFfiConverterTypePool.write(value.pool, buf)_UniffiFfiConverterOptionalTypeClaimSpec.write(value.spec, buf)+ _UniffiFfiConverterOptionalString.write(value.name, buf)@dataclassclass CreatePoolRequest:@@ -3198,6 +3218,16 @@ class CyclopsClientProtocol(typing.Protocol):raise NotImplementedErrorasync def reconcile_template(self, request: CreateTemplateRequest) -> Template:raise NotImplementedError+ async def renew_claim(self, claim: Claim,shutdown_time: str) -> Claim:+ """+ Push the claim's `spec.lifecycle.shutdownTime` forward. That absolute+ expiry is the only liveness input the pool operator's claim reaper+ honors, so a holder that outlives its current lease must renew before+ the deadline passes or the bound sandbox is deleted underneath it.+ Deliberately narrower than a claim update: nothing else on the claim+ can be mutated through the SDK.+"""+ raise NotImplementedErrorasync def service_request(self, sandbox: Sandbox,service: str,path: str,request: HttpRequest) -> HttpResponse:raise NotImplementedErrorasync def update_pool(self, pool: Pool) -> Pool:@@ -3663,6 +3693,34 @@ class CyclopsClient(CyclopsClientProtocol):_uniffi_lift_return,_uniffi_error_converter,)+ async def renew_claim(self, claim: Claim,shutdown_time: str) -> Claim:+ """+ Push the claim's `spec.lifecycle.shutdownTime` forward. That absolute+ expiry is the only liveness input the pool operator's claim reaper+ honors, so a holder that outlives its current lease must renew before+ the deadline passes or the bound sandbox is deleted underneath it.+ Deliberately narrower than a claim update: nothing else on the claim+ can be mutated through the SDK.+"""++ _UniffiFfiConverterTypeClaim.check_lower(claim)++ _UniffiFfiConverterString.check_lower(shutdown_time)+ _uniffi_lowered_args = (+ self._uniffi_clone_handle(),+ _UniffiFfiConverterTypeClaim.lower(claim),+ _UniffiFfiConverterString.lower(shutdown_time),+ )+ _uniffi_lift_return = _UniffiFfiConverterTypeClaim.lift+ _uniffi_error_converter = _UniffiFfiConverterTypeSdkError+ return await _uniffi_rust_call_async(+ _UniffiLib.uniffi_cyclops_sdk_fn_method_cyclopsclient_renew_claim(*_uniffi_lowered_args),+ _UniffiLib.ffi_cyclops_sdk_rust_future_poll_rust_buffer,+ _UniffiLib.ffi_cyclops_sdk_rust_future_complete_rust_buffer,+ _UniffiLib.ffi_cyclops_sdk_rust_future_free_rust_buffer,+ _uniffi_lift_return,+ _uniffi_error_converter,+ )async def service_request(self, sandbox: Sandbox,service: str,path: str,request: HttpRequest) -> HttpResponse:_UniffiFfiConverterTypeSandbox.check_lower(sandbox)diff --git a/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb b/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rbindex 3f00ee29da..21672db397 100644--- a/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb+++ b/libs/fleet/sdk-bindings/ruby/cyclops_sdk/sdk.rb@@ -197,6 +197,7 @@ private_constant :UniffiHandleMapdef self.check_lower_TypeCreateClaimRequest(v)RustBuffer.check_lower_TypePool(v.pool)RustBuffer.check_lower_OptionalTypeClaimSpec(v.spec)+ RustBuffer.check_lower_Optionalstring(v.name)enddef self.alloc_from_TypeCreateClaimRequest(v)@@ -967,7 +968,8 @@ class RustBufferStreamdef readTypeCreateClaimRequestCreateClaimRequest.new(pool: readTypePool,- spec: readOptionalTypeClaimSpec+ spec: readOptionalTypeClaimSpec,+ name: readOptionalstring)end@@ -1569,6 +1571,7 @@ class RustBufferBuilderdef write_TypeCreateClaimRequest(v)self.write_TypePool(v.pool)self.write_OptionalTypeClaimSpec(v.spec)+ self.write_Optionalstring(v.name)end# The Record type CreatePoolRequest.@@ -2335,6 +2338,9 @@ module UniFFILibattach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims,[:uint64, RustBuffer.by_value, RustCallStatus.by_ref],:uint64+ attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_renew_claim,+ [:uint64, RustBuffer.by_value, RustBuffer.by_value, RustCallStatus.by_ref],+ :uint64attach_function :uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim,[:uint64, RustBuffer.by_value, RustCallStatus.by_ref],:uint64@@ -2474,6 +2480,9 @@ module UniFFILibattach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims,[RustCallStatus.by_ref],:uint16+ attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim,+ [RustCallStatus.by_ref],+ :uint16attach_function :uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim,[RustCallStatus.by_ref],:uint16@@ -2605,11 +2614,12 @@ end# Record type CreateClaimRequestclass CreateClaimRequest- attr_reader :pool, :spec+ attr_reader :pool, :spec, :name- def initialize(pool:, spec:)+ def initialize(pool:, spec:, name: nil)@pool = pool@spec = spec+ @name = nameenddef ==(other)@@ -2619,6 +2629,9 @@ class CreateClaimRequestif @spec != other.specreturn falseend+ if @name != other.name+ return false+ endtrueend@@ -3211,6 +3224,20 @@ end)return result.consumeIntoSequenceTypeClaimend+ def renew_claim(claim, shutdown_time)+ claim = claim+ RustBuffer.check_lower_TypeClaim(claim)+ shutdown_time = FleetSdk::uniffi_utf8(shutdown_time)++ result = FleetSdk.uniffi_rust_future_rust_buffer(++ SdkError,++ UniFFILib.uniffi_cyclops_sdk_fn_method_cyclopsclient_renew_claim(uniffi_clone_handle(),RustBuffer.alloc_from_TypeClaim(claim),RustBuffer.allocFromString(shutdown_time),RustCallStatus.new),++ )+ return result.consumeIntoTypeClaim+ enddef wait_claim(claim)claim = claimRustBuffer.check_lower_TypeClaim(claim)diff --git a/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift b/libs/fleet/sdk-bindings/swift/CyclopsSdk.swiftindex 1c8d369812..d904a4cfe6 100644--- a/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift+++ b/libs/fleet/sdk-bindings/swift/CyclopsSdk.swift@@ -780,6 +780,16 @@ public protocol CyclopsClientProtocol: AnyObject, Sendable {func listClaims(namespace: String) async throws -> [Claim]+ /**+ * Push the claim's `spec.lifecycle.shutdownTime` forward. That absolute+ * expiry is the only liveness input the pool operator's claim reaper+ * honors, so a holder that outlives its current lease must renew before+ * the deadline passes or the bound sandbox is deleted underneath it.+ * Deliberately narrower than a claim update: nothing else on the claim+ * can be mutated through the SDK.+ */+ func renewClaim(claim: Claim, shutdownTime: String) async throws -> Claim+func waitClaim(claim: Claim) async throws -> Sandboxfunc listNamespaces() async throws -> [Namespace]@@ -1002,6 +1012,31 @@ open func listClaims(namespace: String)async throws -> [Claim] {)}+ /**+ * Push the claim's `spec.lifecycle.shutdownTime` forward. That absolute+ * expiry is the only liveness input the pool operator's claim reaper+ * honors, so a holder that outlives its current lease must renew before+ * the deadline passes or the bound sandbox is deleted underneath it.+ * Deliberately narrower than a claim update: nothing else on the claim+ * can be mutated through the SDK.+ */+open func renewClaim(claim: Claim, shutdownTime: String)async throws -> Claim {+ return+ try await uniffiRustCallAsync(+ rustFutureFunc: {+ uniffi_cyclops_sdk_fn_method_cyclopsclient_renew_claim(+ self.uniffiCloneHandle(),+ FfiConverterTypeClaim_lower(claim),FfiConverterString.lower(shutdownTime)+ )+ },+ pollFunc: ffi_cyclops_sdk_rust_future_poll_rust_buffer,+ completeFunc: ffi_cyclops_sdk_rust_future_complete_rust_buffer,+ freeFunc: ffi_cyclops_sdk_rust_future_free_rust_buffer,+ liftFunc: FfiConverterTypeClaim_lift,+ errorHandler: FfiConverterTypeSdkError_lift+ )+}+open func waitClaim(claim: Claim)async throws -> Sandbox {returntry await uniffiRustCallAsync(@@ -1754,12 +1789,24 @@ public func FfiConverterTypeClaim_lower(_ value: Claim) -> RustBuffer {public struct CreateClaimRequest: Equatable, Hashable {public var pool: Poolpublic var spec: ClaimSpec?+ /**+ * Explicit claim name. A client-supplied name is used verbatim (after+ * DNS-label validation); left unset, the client generates a random+ * `claim-<petname>` so concurrent leases and retries cannot collide.+ */+ public var name: String?// Default memberwise initializers are never public by default, so we// declare one manually.- public init(pool: Pool, spec: ClaimSpec?) {+ public init(pool: Pool, spec: ClaimSpec?,+ /**+ * Explicit claim name. A client-supplied name is used verbatim (after+ * DNS-label validation); left unset, the client generates a random+ * `claim-<petname>` so concurrent leases and retries cannot collide.+ */name: String? = nil) {self.pool = poolself.spec = spec+ self.name = name}@@ -1779,13 +1826,15 @@ public struct FfiConverterTypeCreateClaimRequest: FfiConverterRustBuffer {returntry CreateClaimRequest(pool: FfiConverterTypePool.read(from: &buf),- spec: FfiConverterOptionTypeClaimSpec.read(from: &buf)+ spec: FfiConverterOptionTypeClaimSpec.read(from: &buf),+ name: FfiConverterOptionString.read(from: &buf))}public static func write(_ value: CreateClaimRequest, into buf: inout [UInt8]) {FfiConverterTypePool.write(value.pool, into: &buf)FfiConverterOptionTypeClaimSpec.write(value.spec, into: &buf)+ FfiConverterOptionString.write(value.name, into: &buf)}}@@ -3569,6 +3618,9 @@ private let initializationResult: InitializationResult = {if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims() != 7802) {return InitializationResult.apiChecksumMismatch}+ if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim() != 17505) {+ return InitializationResult.apiChecksumMismatch+ }if (uniffi_cyclops_sdk_checksum_method_cyclopsclient_wait_claim() != 18984) {return InitializationResult.apiChecksumMismatch}diff --git a/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h b/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.hindex ec6fde1d71..b0eefb21bf 100644--- a/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h+++ b/libs/fleet/sdk-bindings/swift/CyclopsSdkFFI.h@@ -338,6 +338,11 @@ uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_get_claim(uint64_t ptr, Rustuint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_list_claims(uint64_t ptr, RustBuffer namespace);#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_RENEW_CLAIM+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_RENEW_CLAIM+uint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_renew_claim(uint64_t ptr, RustBuffer claim, RustBuffer shutdown_time+);+#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_WAIT_CLAIM#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_FN_METHOD_CYCLOPSCLIENT_WAIT_CLAIMuint64_t uniffi_cyclops_sdk_fn_method_cyclopsclient_wait_claim(uint64_t ptr, RustBuffer claim@@ -765,6 +770,12 @@ uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_get_claim(void#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_LIST_CLAIMSuint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_claims(void+);+#endif+#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_RENEW_CLAIM+#define UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_RENEW_CLAIM+uint16_t uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim(void+);#endif#ifndef UNIFFI_FFIDEF_UNIFFI_CYCLOPS_SDK_CHECKSUM_METHOD_CYCLOPSCLIENT_WAIT_CLAIMdiff --git a/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.ts b/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.tsindex 92e8dc1997..8a9f152b57 100644--- a/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.ts+++ b/libs/fleet/sdk-bindings/ts-uniffi-browser/ts/fleet_sdk.ts@@ -289,13 +289,21 @@ const FfiConverterTypePool = (() => {export type CreateClaimRequest = {pool: Pool;spec?: ClaimSpec;+ /**+ * Explicit claim name. A client-supplied name is used verbatim (after+ * DNS-label validation); left unset, the client generates a random+ * `claim-<petname>` so concurrent leases and retries cannot collide.+ */+ name?: string;};/*** Generated factory for {@link CreateClaimRequest} record objects.*/export const CreateClaimRequest = (() => {- const defaults = () => ({});+ const defaults = () => ({+ name: undefined,+ });const create = (() => {return uniffiCreateRecord<CreateClaimRequest, ReturnType<typeof defaults>>(defaults,@@ -315,16 +323,19 @@ const FfiConverterTypeCreateClaimRequest = (() => {return {pool: FfiConverterTypePool.read(from),spec: FfiConverterOptionalTypeClaimSpec.read(from),+ name: FfiConverterOptionalString.read(from),};}write(value: TypeName, into: RustBuffer): void {FfiConverterTypePool.write(value.pool, into);FfiConverterOptionalTypeClaimSpec.write(value.spec, into);+ FfiConverterOptionalString.write(value.name, into);}allocationSize(value: TypeName): number {return (FfiConverterTypePool.allocationSize(value.pool) +- FfiConverterOptionalTypeClaimSpec.allocationSize(value.spec)+ FfiConverterOptionalTypeClaimSpec.allocationSize(value.spec) ++ FfiConverterOptionalString.allocationSize(value.name));}}@@ -2222,6 +2233,19 @@ export interface CyclopsClientLike {request: CreateTemplateRequest,asyncOpts_?: { signal: AbortSignal },) /*throws*/ : Promise<Template>;+ /**+ * Push the claim's `spec.lifecycle.shutdownTime` forward. That absolute+ * expiry is the only liveness input the pool operator's claim reaper+ * honors, so a holder that outlives its current lease must renew before+ * the deadline passes or the bound sandbox is deleted underneath it.+ * Deliberately narrower than a claim update: nothing else on the claim+ * can be mutated through the SDK.+ */+ renewClaim(+ claim: Claim,+ shutdownTime: string,+ asyncOpts_?: { signal: AbortSignal },+ ) /*throws*/ : Promise<Claim>;serviceRequest(sandbox: Sandbox,service: string,@@ -3077,6 +3101,53 @@ export class CyclopsClient);}+ /**+ * Push the claim's `spec.lifecycle.shutdownTime` forward. That absolute+ * expiry is the only liveness input the pool operator's claim reaper+ * honors, so a holder that outlives its current lease must renew before+ * the deadline passes or the bound sandbox is deleted underneath it.+ * Deliberately narrower than a claim update: nothing else on the claim+ * can be mutated through the SDK.+ */+ async renewClaim(+ claim: Claim,+ shutdownTime: string,+ asyncOpts_?: { signal: AbortSignal },+ ): Promise<Claim> /*throws*/ {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().ubrn_uniffi_cyclops_sdk_fn_method_cyclopsclient_renew_claim(+ uniffiTypeCyclopsClientObjectFactory.clonePointer(this),+ FfiConverterTypeClaim.lower(claim, nativeModule().rustbuffer_alloc),+ FfiConverterString.lower(+ shutdownTime,+ nativeModule().rustbuffer_alloc,+ ),+ );+ },+ /*pollFunc:*/ nativeModule()+ .ubrn_ffi_cyclops_sdk_rust_future_poll_rust_buffer,+ /*cancelFunc:*/ nativeModule()+ .ubrn_ffi_cyclops_sdk_rust_future_cancel_rust_buffer,+ /*completeFunc:*/ nativeModule()+ .ubrn_ffi_cyclops_sdk_rust_future_complete_rust_buffer,+ /*freeFunc:*/ nativeModule()+ .ubrn_ffi_cyclops_sdk_rust_future_free_rust_buffer,+ // Async returns always go through the JS-side converter: the+ // FFI symbol returns the future handle (u64), and the user-level+ // RustBuffer comes back via the shared `rust_future_complete_*`+ // export. The bytes the runtime hands back must be deserialized+ // here using the per-callable return-type converter.+ /*liftFunc:*/ FfiConverterTypeClaim.lift.bind(FfiConverterTypeClaim),+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeSdkError.lift.bind(+ FfiConverterTypeSdkError,+ ),+ );+ }+async serviceRequest(sandbox: Sandbox,service: string,@@ -3846,6 +3917,14 @@ function uniffiEnsureInitialized() {"uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_template",);}+ if (+ nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim() !==+ 17505+ ) {+ throw new UniffiInternalError.ApiChecksumMismatch(+ "uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim",+ );+ }if (nativeModule().ubrn_uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request() !==46699diff --git a/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk-ffi.ts b/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk-ffi.tsindex 9f6df1be46..f074e4c33d 100644--- a/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk-ffi.ts+++ b/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk-ffi.ts@@ -443,6 +443,11 @@ const DEFINITIONS = {ret: FfiType.Handle,hasRustCallStatus: false,},+ "uniffi_cyclops_sdk_fn_method_cyclopsclient_renew_claim": {+ args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },"uniffi_cyclops_sdk_fn_method_cyclopsclient_service_request": {args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer, FfiType.RustBuffer, FfiType.RustBuffer],ret: FfiType.Handle,@@ -608,6 +613,11 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request": {args: [],ret: FfiType.UInt16,@@ -795,6 +805,7 @@ interface NativeModuleInterface {uniffi_cyclops_sdk_fn_method_cyclopsclient_list_user_api_keys(uniffiSelf: bigint): bigint;uniffi_cyclops_sdk_fn_method_cyclopsclient_reconcile_pool(uniffiSelf: bigint, request: Uint8Array): bigint;uniffi_cyclops_sdk_fn_method_cyclopsclient_reconcile_template(uniffiSelf: bigint, request: Uint8Array): bigint;+ uniffi_cyclops_sdk_fn_method_cyclopsclient_renew_claim(uniffiSelf: bigint, claim: Uint8Array, shutdownTime: Uint8Array): bigint;uniffi_cyclops_sdk_fn_method_cyclopsclient_service_request(uniffiSelf: bigint, sandbox: Uint8Array, service: Uint8Array, path: Uint8Array, request: Uint8Array): bigint;uniffi_cyclops_sdk_fn_method_cyclopsclient_update_pool(uniffiSelf: bigint, pool: Uint8Array): bigint;uniffi_cyclops_sdk_fn_method_cyclopsclient_update_template(uniffiSelf: bigint, template: Uint8Array): bigint;@@ -828,6 +839,7 @@ interface NativeModuleInterface {uniffi_cyclops_sdk_checksum_method_cyclopsclient_list_user_api_keys(): number;uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_pool(): number;uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_template(): number;+ uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim(): number;uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request(): number;uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_pool(): number;uniffi_cyclops_sdk_checksum_method_cyclopsclient_update_template(): number;diff --git a/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.ts b/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.tsindex 99a9627611..ef1358c8d1 100644--- a/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.ts+++ b/libs/fleet/sdk-bindings/ts-uniffi/fleet_sdk.ts@@ -216,7 +216,13 @@ const FfiConverterTypePool = (() => {export type CreateClaimRequest = {pool: Pool,- spec?: ClaimSpec+ spec?: ClaimSpec,+ /**+ * Explicit claim name. A client-supplied name is used verbatim (after+ * DNS-label validation); left unset, the client generates a random+ * `claim-<petname>` so concurrent leases and retries cannot collide.+ */+ name?: string}/**@@ -224,6 +230,7 @@ export type CreateClaimRequest = {*/export const CreateClaimRequest = (() => {const defaults = () => ({+ name: undefined,});const create = (() => {return uniffiCreateRecord<CreateClaimRequest, ReturnType<typeof defaults>>(defaults);@@ -241,16 +248,19 @@ const FfiConverterTypeCreateClaimRequest = (() => {read(from: RustBuffer): TypeName {return {pool: FfiConverterTypePool.read(from),- spec: FfiConverterOptionalTypeClaimSpec.read(from)+ spec: FfiConverterOptionalTypeClaimSpec.read(from),+ name: FfiConverterOptionalString.read(from)};}write(value: TypeName, into: RustBuffer): void {FfiConverterTypePool.write(value.pool, into);FfiConverterOptionalTypeClaimSpec.write(value.spec, into);+ FfiConverterOptionalString.write(value.name, into);}allocationSize(value: TypeName): number {return FfiConverterTypePool.allocationSize(value.pool) +- FfiConverterOptionalTypeClaimSpec.allocationSize(value.spec);+ FfiConverterOptionalTypeClaimSpec.allocationSize(value.spec) ++ FfiConverterOptionalString.allocationSize(value.name);}};@@ -2022,6 +2032,15 @@ export interface CyclopsClientLike {listUserApiKeys(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Array<UserApiKey>>;reconcilePool(request: CreatePoolRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Pool>;reconcileTemplate(request: CreateTemplateRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Template>;+ /**+ * Push the claim's `spec.lifecycle.shutdownTime` forward. That absolute+ * expiry is the only liveness input the pool operator's claim reaper+ * honors, so a holder that outlives its current lease must renew before+ * the deadline passes or the bound sandbox is deleted underneath it.+ * Deliberately narrower than a claim update: nothing else on the claim+ * can be mutated through the SDK.+ */+ renewClaim(claim: Claim, shutdownTime: string, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Claim>;serviceRequest(sandbox: Sandbox, service: string, path: string, request: HttpRequest, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<HttpResponse>;updatePool(pool: Pool, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Pool>;updateTemplate(template: Template, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<Template>;@@ -2696,6 +2715,46 @@ private constructor(pointer: UniffiHandle) {}}+ /**+ * Push the claim's `spec.lifecycle.shutdownTime` forward. That absolute+ * expiry is the only liveness input the pool operator's claim reaper+ * honors, so a holder that outlives its current lease must renew before+ * the deadline passes or the bound sandbox is deleted underneath it.+ * Deliberately narrower than a claim update: nothing else on the claim+ * can be mutated through the SDK.+ */+ async renewClaim(claim: Claim, shutdownTime: string, asyncOpts_?: { signal: AbortSignal }): Promise<Claim> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cyclops_sdk_fn_method_cyclopsclient_renew_claim(+ uniffiTypeCyclopsClientObjectFactory.clonePointer(this),FfiConverterTypeClaim.lower(claim, nativeModule().rustbuffer_alloc),FfiConverterString.lower(shutdownTime, nativeModule().rustbuffer_alloc)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_poll_rust_buffer,+ /*cancelFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_cancel_rust_buffer,+ /*completeFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_complete_rust_buffer,+ /*freeFunc:*/ nativeModule().ffi_cyclops_sdk_rust_future_free_rust_buffer,+ // Async returns always go through the JS-side converter: the+ // FFI symbol returns the future handle (u64), and the user-level+ // RustBuffer comes back via the shared `rust_future_complete_*`+ // export. The bytes the runtime hands back must be deserialized+ // here using the per-callable return-type converter.+ /*liftFunc:*/ FfiConverterTypeClaim.lift.bind(FfiConverterTypeClaim),+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeSdkError.lift.bind(FfiConverterTypeSdkError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }+async serviceRequest(sandbox: Sandbox, service: string, path: string, request: HttpRequest, asyncOpts_?: { signal: AbortSignal }): Promise<HttpResponse> /*throws*/ {const __stack = uniffiIsDebug ? new Error().stack : undefined;try {@@ -3242,6 +3301,9 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_template() !== 36469) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_reconcile_template");}+ if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim() !== 17505) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_renew_claim");+ }if (nativeModule().uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request() !== 46699) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cyclops_sdk_checksum_method_cyclopsclient_service_request");}diff --git a/libs/fleet/sdk/src/claims.rs b/libs/fleet/sdk/src/claims.rsindex 9b75a359f9..675b796383 100644--- a/libs/fleet/sdk/src/claims.rs+++ b/libs/fleet/sdk/src/claims.rs@@ -51,13 +51,20 @@ impl CyclopsClient {reason: "sandbox template name must not be empty".into(),});}+ let name = match request.name {+ Some(name) => {+ routes::validate_dns_label_for("claim name", &name)?;+ name+ }+ None => claim_name()?,+ };let claim = Claim {api_version: "osgym.cua.ai/v1alpha1".into(),kind: "OSGymSandboxClaim".into(),metadata: ResourceMetadata {namespace: pool.metadata.namespace.clone(),- name: claim_name()?,+ name,labels: None,creation_timestamp: None,},@@ -108,6 +115,35 @@ impl CyclopsClient {.await}+ /// Push the claim's `spec.lifecycle.shutdownTime` forward. That absolute+ /// expiry is the only liveness input the pool operator's claim reaper+ /// honors, so a holder that outlives its current lease must renew before+ /// the deadline passes or the bound sandbox is deleted underneath it.+ /// Deliberately narrower than a claim update: nothing else on the claim+ /// can be mutated through the SDK.+ pub async fn renew_claim(+ self: Arc<Self>,+ claim: Claim,+ shutdown_time: String,+ ) -> Result<Claim, SdkError> {+ if shutdown_time.trim().is_empty() {+ return Err(SdkError::Configuration {+ reason: "shutdown time must not be empty".into(),+ });+ }+ let item_url = self.claim_item_url(&claim)?;+ let body = to_json(&serde_json::json!({+ "spec": { "lifecycle": { "shutdownTime": shutdown_time } }+ }))?;+ send_json(+ self.as_ref(),+ "renew claim",+ merge_patch_request(item_url, Some(body)),+ &[200],+ )+ .await+ }+pub async fn wait_claim(self: Arc<Self>, claim: Claim) -> Result<Sandbox, SdkError> {self.claim_item_url(&claim)?;for attempt in 0..self.claim_poll_limit() {@@ -221,6 +257,12 @@ fn serialized_status<T: Serialize>(status: Option<&T>) -> Result<String, SdkErro})}+fn merge_patch_request(url: Url, body: Option<Vec<u8>>) -> HttpRequest {+ let mut request = json_request("PATCH", url, body);+ request.headers[1].value = "application/merge-patch+json".into();+ request+}+fn json_request(method: &str, url: Url, body: Option<Vec<u8>>) -> HttpRequest {HttpRequest {method: method.into(),diff --git a/libs/fleet/sdk/src/types.rs b/libs/fleet/sdk/src/types.rsindex 149de2f526..3ecd684cd8 100644--- a/libs/fleet/sdk/src/types.rs+++ b/libs/fleet/sdk/src/types.rs@@ -242,11 +242,19 @@ impl PartialEq for CreateTemplateRequest {pub struct CreateClaimRequest {pub pool: Pool,pub spec: Option<ClaimSpec>,+ /// Explicit claim name. A client-supplied name is used verbatim (after+ /// DNS-label validation); left unset, the client generates a random+ /// `claim-<petname>` so concurrent leases and retries cannot collide.+ #[serde(default)]+ #[uniffi(default = None)]+ pub name: Option<String>,}impl PartialEq for CreateClaimRequest {fn eq(&self, other: &Self) -> bool {- self.pool == other.pool && schema_values_equal(&self.spec, &other.spec)+ self.pool == other.pool+ && schema_values_equal(&self.spec, &other.spec)+ && self.name == other.name}}diff --git a/libs/fleet/sdk/tests/claim_flow.rs b/libs/fleet/sdk/tests/claim_flow.rsindex 29da963559..16fc21e56e 100644--- a/libs/fleet/sdk/tests/claim_flow.rs+++ b/libs/fleet/sdk/tests/claim_flow.rs@@ -33,6 +33,7 @@ async fn creates_pending_demand_immediately_for_a_nonzero_unavailable_pool() {.create_claim(CreateClaimRequest {pool: unavailable_pool,spec: Some(spec.clone()),+ name: None,}).await.unwrap(),@@ -57,6 +58,7 @@ async fn zero_and_nonzero_pools_post_a_single_claim_create() {.create_claim(CreateClaimRequest {pool: pool(replicas),spec: None,+ name: None,}).await.unwrap();@@ -97,6 +99,100 @@ async fn claim_crud_uses_prefixed_routes_and_expected_statuses() {assert_request(&requests[2], "DELETE", &item, None);}+#[tokio::test]+async fn renew_claim_merge_patches_only_the_lifecycle_shutdown_time() {+ let current = claim("named-claim", claim_spec("example-pool-template"), None);+ let item = format!("{CLAIM_COLLECTION}/named-claim");+ let http = Arc::new(ScriptedHttpClient::new([+ Ok(token()),+ Ok(json_response(200, ¤t)),+ ]));++ assert_eq!(+ client(Arc::clone(&http), 1, 1)+ .renew_claim(current.clone(), "2026-01-01T00:10:00Z".into())+ .await+ .unwrap(),+ current+ );++ let requests = http.authenticated_requests().await;+ assert_eq!(requests.len(), 1);+ let request = &requests[0];+ assert_eq!(request.method, "PATCH");+ assert_eq!(request.url, item);+ assert_eq!(+ request+ .headers+ .iter()+ .find(|header| header.name == "content-type")+ .map(|header| header.value.as_str()),+ Some("application/merge-patch+json")+ );+ assert_eq!(+ serde_json::from_slice::<serde_json::Value>(request.body.as_deref().unwrap()).unwrap(),+ serde_json::json!({ "spec": { "lifecycle": { "shutdownTime": "2026-01-01T00:10:00Z" } } })+ );+}++#[tokio::test]+async fn renew_claim_rejects_an_empty_shutdown_time_before_any_request() {+ let http = Arc::new(ScriptedHttpClient::new([]));+ let current = claim("named-claim", claim_spec("example-pool-template"), None);++ assert!(matches!(+ client(Arc::clone(&http), 1, 1)+ .renew_claim(current, " ".into())+ .await,+ Err(SdkError::Configuration { .. })+ ));++ assert!(http.authenticated_requests().await.is_empty());+}++#[tokio::test]+async fn create_claim_uses_a_client_supplied_name_verbatim() {+ let spec = claim_spec("example-pool-template");+ let created = claim("claim-1", spec.clone(), None);+ let http = Arc::new(ScriptedHttpClient::new([+ Ok(token()),+ Ok(json_response(201, &created)),+ ]));++ let result = client(Arc::clone(&http), 2, 2)+ .create_claim(CreateClaimRequest {+ pool: pool(1),+ spec: Some(spec.clone()),+ name: Some("claim-1".into()),+ })+ .await+ .unwrap();+ assert_eq!(result, created);++ let requests = http.authenticated_requests().await;+ assert_eq!(requests.len(), 1);+ let body: Claim = serde_json::from_slice(requests[0].body.as_deref().unwrap()).unwrap();+ assert_eq!(body.metadata.name, "claim-1");+}++#[tokio::test]+async fn create_claim_rejects_an_invalid_client_supplied_name_before_any_request() {+ let http = Arc::new(ScriptedHttpClient::new([]));++ assert!(matches!(+ client(Arc::clone(&http), 1, 1)+ .create_claim(CreateClaimRequest {+ pool: pool(1),+ spec: None,+ name: Some("Not A DNS Label".into()),+ })+ .await,+ Err(SdkError::InvalidResourceName { .. })+ ));++ assert!(http.authenticated_requests().await.is_empty());+}+#[tokio::test]async fn wait_claim_returns_bound_sandbox_with_sorted_deduplicated_pool_services() {let current = claim(@@ -185,11 +281,13 @@ async fn generated_claim_names_are_unique_under_concurrency_and_fit_dns_labels()let (first, second) = tokio::join!(client.clone().create_claim(CreateClaimRequest {pool: pool.clone(),- spec: Some(claim_spec("short-template"))+ spec: Some(claim_spec("short-template")),+ name: None,}),client.create_claim(CreateClaimRequest {pool,- spec: Some(claim_spec("short-template"))+ spec: Some(claim_spec("short-template")),+ name: None,}),);assert!(first.is_ok());@@ -227,7 +325,8 @@ async fn validation_and_malformed_responses_fail_without_unexpected_http() {client(Arc::clone(&invalid_http), 1, 1).create_claim(CreateClaimRequest {pool: invalid_pool,- spec: None+ spec: None,+ name: None,}).await,Err(SdkError::InvalidResourceName { .. })@@ -427,7 +526,11 @@ async fn default_template_ref_for_a_63_byte_pool_passes_through_without_dns_vali]));client(Arc::clone(&http), 1, 1)- .create_claim(CreateClaimRequest { pool, spec: None })+ .create_claim(CreateClaimRequest {+ pool,+ spec: None,+ name: None,+ }).await.unwrap();@@ -452,6 +555,7 @@ async fn explicit_non_dns_template_ref_passes_through_but_empty_ref_is_rejected_.create_claim(CreateClaimRequest {pool: pool(0),spec: Some(claim_spec(template_name)),+ name: None,}).await.unwrap();@@ -466,6 +570,7 @@ async fn explicit_non_dns_template_ref_passes_through_but_empty_ref_is_rejected_.create_claim(CreateClaimRequest {pool: pool(0),spec: Some(claim_spec("")),+ name: None,}).await,Err(SdkError::Configuration { .. })diff --git a/libs/fleet/sdk/tests/public_api.rs b/libs/fleet/sdk/tests/public_api.rsindex 867f0c26d4..a84631b746 100644--- a/libs/fleet/sdk/tests/public_api.rs+++ b/libs/fleet/sdk/tests/public_api.rs@@ -251,9 +251,10 @@ fn resources_use_canonical_schema_specs_and_statuses() {}fn assert_create_claim_request(request: CreateClaimRequest) {- let CreateClaimRequest { pool, spec } = request;+ let CreateClaimRequest { pool, spec, name } = request;assert_pool_types(pool);let _: Option<ClaimSpec> = spec;+ let _: Option<String> = name;}let _: fn(Claim) = assert_claim_types;@@ -278,6 +279,7 @@ fn resources_support_equality_and_kubernetes_camel_case_json() {let create_claim = CreateClaimRequest {pool: pool.clone(),spec: Some(claim.spec.clone()),+ name: None,};assert_eq!(pool, pool.clone());