diff --git a/.agents/evidence/verify/2026-11-24-bound-provider-runtime.md b/.agents/evidence/verify/2026-11-24-bound-provider-runtime.md new file mode 100644 index 00000000..9557c149 --- /dev/null +++ b/.agents/evidence/verify/2026-11-24-bound-provider-runtime.md @@ -0,0 +1,45 @@ +# Verification: Explicit Provider binding and runtime preparation + +- Date: 2026-11-24 +- Change: Explicit Python Provider client on the SDK main baseline a9a572d81847fe99216bf1bb454b91810dacc676 +- Result: PARTIAL +- Environment: Python 3.11.15, Linux x86-64 glibc, fixed Node 22.22.2 and OpenSandbox 0.5.1. + Credentials supplied from an existing private environment and excluded from this record. + +## What was verified + +Three reviewers ran independent adversarial checks of contract and target routing, artifact +integrity and cache behavior, and the standalone Node path. Initial review eliminated dependency +on ambient SDK/CLI configuration. Implementation review identified bounded preparation, empty +handshake features, unsupported create inputs, and independent shutdown requirements. The third +round checked the corrections and independently reproduced colliding process IDs across two +Sandbox handles, cancelling a close waiter, and closing during in-flight initialization. + +## Commands run + +- `pytest -q -p no:cacheprovider e2e/test_bound_provider.py`: live Express result 1 pass. + A tagged sandbox returned the expected command output and file content. The exact sandbox + was deleted and follow-up get raised the typed NotFound. +- `pytest -q -p no:cacheprovider client-sdk/tests/test_providers/test_bound_client.py client-sdk/tests/test_providers/test_epp.py`: + development run 38 passed. An initial native fixture misused the Provider object as + its sandbox protocol. The test was corrected to use a separate protocol object. +- Stock Node and OpenSandbox published archives were retrieved over HTTPS, verified against + fixed lengths and SHA-256 values, and prepared through the Python API. Independent harness + runs included a rootless mount namespace masking system Node and a blank caller PATH. + Cold, warm, and offline all succeeded. The EPP calls covered create, get, list, connect, + renew, command streaming, files, ports, PTY, delete and absent state against an + OpenSandbox backend test double. Concurrent streams used the same native process ID. +- The latest complete local test and CI status is recorded in the pull request. + +## Cleanup + +The real Express sandbox was deleted and verified by direct ID. Standalone component runs reaped +all of their subprocesses and removed temporary workspaces. Test sandbox records were empty. +No database, deployment, key, or image was created. + +## Not verified + +Live OpenSandbox backend verification requires a reachable OpenSandbox server or a supported +container runtime. No such target was configured in the workspace. The component tests exercised +real runtime and plugin bytes with a backend test double. Release of a signed catalog and automatic +native package installation remains outside the implemented lock-driven path. diff --git a/.agents/notes/proposed/architecture/2026-11-24-bound-provider-runtime.md b/.agents/notes/proposed/architecture/2026-11-24-bound-provider-runtime.md new file mode 100644 index 00000000..6ceaabd3 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-24-bound-provider-runtime.md @@ -0,0 +1,85 @@ +# Decision: Prepare explicitly bound Provider implementations + +Status: proposed + +## Problem + +Python's existing installed Node Provider path uses the user's shared abx engine. It also +resolves several sandbox behaviors from the global Provider registry after creating a handle. +An application that uses a single standalone Provider should be able to bind its own target +and prepare only the executable artifacts needed by that implementation. + +## Decision + +Use an explicitly supplied, already installed Python Provider when it meets the required feature +set. Otherwise select a standalone EPP entry from an operator-approved release lock. Filter +platform and feature requirements before opening any artifact, prefer the host language, then use +the documented priority. Preflight of the selected implementation terminates on failure. The +approved lock binds opaque compressed bytes to their source, digest, size, and archive member. +The host retrieves public HTTPS archives only during explicit online preparation and reuses +verified private cache blobs offline. + +Reuse the EPP transport and its operation contract. Give each bound Sandbox handle its own +transport because EPP/1 process notifications identify a process without its Sandbox ID. Share +only verified artifacts and the account configuration within a client. Each handle receives its +negotiated Provider object for endpoint resolution, refresh and terminal calls. Close tasks own +local cleanup, including cancellation of a caller waiting for close. Remote deletion is explicit. + +The dependency-free OpenSandbox plugin is the first standalone Node example. The source +fixture pins the existing published Provider and official Node archives. The built-in Express +route uses an explicit Sandbox key and endpoint without account discovery. The current Node CLI +continues to load compatible installed Node modules through its existing ProviderKit. + +## API Design + +- `ProviderClient.prepare(ProviderLock, TransportConfig, native=..., required_features=..., cache_dir=..., download=False)` +- `create(SandboxConfig, request_timeout=..., on_created=...)`, `connect`, `list`, `get`, + `set_timeout`, `delete`, `close`, and async context management +- `ProviderLock` fixes a release and its approved standalone implementations. Each + `EppImplementation` declares language, platform, priority, features, entrypoint and artifact, + with an optional `ProviderRuntime` and required target keys. +- Public usage and prerequisites are in [the English guide](../../../../docs/en/guide/provider-runtime.md) + and [the Chinese guide](../../../../docs/zh/guide/provider-runtime.md). + +## Alternatives considered + +- Bundling the abx executable or interpreters into the SDK would charge direct HTTP callers + for unrelated assets and would retain CLI configuration and subprocess discovery coupling. +- Reusing the ambient catalog index as a trust root would let bytes and the expected hash + change together. Start with an independently approved lock. A signed multi-implementation + publishing workflow is a separate milestone. +- Sharing the EPP process between Sandbox handles can route notifications to the wrong + stream when two backends reuse a bare process ID. Retain per-handle isolation. + +## Dependencies + +Use the installed Python package dependencies, existing EPP/1 protocol and fixed Node and +OpenSandbox distributions. No interpreter or Provider binary is included in the SDK wheel. +The example host is Linux x86-64 with glibc. Native packages are installed by the application +owner. Additional platforms, native package auto-installation and catalog release automation +require their own published artifacts and acceptance. + +## Test Strategy + +Review separate native binding, artifact verification and Node operation boundaries. Run an +explicit Express cloud lifecycle with command and file round-trip and confirmed cleanup. Run the +published Node and OpenSandbox artifacts against the exact protocol with system Node masked, +using cold, warm and offline preparation. Exercise same-ID concurrent streams and cancellation +during process startup and shutdown. A live OpenSandbox deployment is a separate acceptance gate +from the protocol backend test. + +## Acceptance criteria + +1. Required features and explicit target are checked before dispatch. Native use makes no + Provider artifact request. Cross-language launch uses the exact verified interpreter/entry. +2. Normal and cancelled shutdown reaps owned local processes. Closing one handle leaves siblings + usable. After client close, a stale handle cannot reuse HttpClient or the EPP process. +3. Asset mismatch fails closed. Cache readers see a complete verified blob. Offline preparation + never opens the artifact network connection. +4. The supported backend, operation and platform set in the public guides follows real evidence. + Record missing gates distinctly before making release claims. + +## Evidence + +- [Delivery issue #166](https://github.com/Alibaba-Agent-Sandbox/python-sdk/issues/166) +- [Verification and review results](../../../evidence/verify/2026-11-24-bound-provider-runtime.md) diff --git a/CHANGELOG.md b/CHANGELOG.md index a1db3654..f373443a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,8 @@ Release candidate: matching client/server **0.4.0a7**. / 候选版本:客户 ### Added +- Add explicit Python Provider binding and locked standalone EPP runtime preparation with offline cache reuse. / 新增 Python Provider 显式绑定与固定 EPP 运行时准备,支持离线复用缓存。 + - Optional managed Agents API Gateway, Worker and Dispatcher with durable Sessions, explicit queue receipts, files/artifacts, safe cancellation and a restart-aware private guest bridge. / 新增可选托管 Agents API Gateway、Worker、Dispatcher,支持持久 Session、显式队列收据、文件与产物、安全取消和可识别重启的私有沙箱桥接。 - Add explicit application command `invoke` arguments, Express network creation and STS SecurityToken handoff. / 新增应用命令 invoke 显式业务参数、极速版创建时网络配置和 STS SecurityToken 传递。 diff --git a/client-sdk/src/agent_sandbox/api/sandbox.py b/client-sdk/src/agent_sandbox/api/sandbox.py index c7da84f3..7c9b0aae 100644 --- a/client-sdk/src/agent_sandbox/api/sandbox.py +++ b/client-sdk/src/agent_sandbox/api/sandbox.py @@ -21,6 +21,12 @@ from agent_sandbox.api.capability import ( ResolvedCapabilities, ) +from agent_sandbox.models.errors import ( + NetworkError, + ProviderProcessError, + ProviderProtocolError, + ProviderTimeoutError, +) from agent_sandbox.models.sandbox import ( SandboxConfig, SandboxInfo, @@ -54,7 +60,7 @@ SandboxProtocol, ) from agent_sandbox.protocol.contracts import TerminalSession as TerminalSession - from agent_sandbox.providers.base import Provider + from agent_sandbox.providers.base import Provider, ProviderInfra from agent_sandbox.transport.auth_contract import AuthProvider from agent_sandbox.transport.auth_contract import DataPlaneAuth as EnvdTokenManager from agent_sandbox.transport.http import HttpClient @@ -165,7 +171,7 @@ def __init__( info: SandboxInfo, config: TransportConfig, http_client: HttpClient, - auth: AuthProvider, + auth: AuthProvider | None, envd_token: EnvdTokenManager, *, sandbox_protocol: SandboxProtocol | None = None, @@ -177,16 +183,18 @@ def __init__( resolved_capabilities: ResolvedCapabilities | None = None, declared_capabilities: frozenset[str] | None = None, provider_id: str | None = None, + bound_provider: Provider | None = None, + bound_check: Callable[[], None] | None = None, ) -> None: self._info = info self._config = config self._provider_id = provider_id or config.provider - - from agent_sandbox.providers.registry import get_provider + self._bound_provider = bound_provider + self._bound_check = bound_check # The backend owns URL derivation and protocol construction. if not self._info.envd_url and self._info.sandbox_id: - self._info.envd_url = get_provider(self._provider_id).resolve_session_url( + self._info.envd_url = self._provider_impl().resolve_session_url( self._info, self._config ) self._http_client = http_client @@ -197,7 +205,7 @@ def __init__( self._domain = domain if domain is not None else config.sandbox_domain self._secure = secure defaults = ( - get_provider(self._provider_id).session_protocols(http_client) + self._provider_impl().session_protocols(http_client) if any( p is None for p in ( @@ -236,6 +244,11 @@ def __init__( # protocol gate refuses a missing feature with E8004 naming it. self._declared_capabilities = declared_capabilities + def _provider_impl(self) -> Provider: + if self._bound_check is not None: + self._bound_check() + return self._bound_provider or get_provider(self._provider_id) + # ---- Properties ---- @property @@ -275,9 +288,7 @@ def capabilities(self) -> frozenset[str]: @property def operations(self) -> frozenset[str]: """Exact operations implemented by this provider's Python consumer.""" - from agent_sandbox.providers.registry import get_provider - - return frozenset(get_provider(self.provider).operations) + return frozenset(self._provider_impl().operations) # ---- Sub-modules (lazy cached properties) ---- @@ -327,7 +338,6 @@ def network(self) -> NetworkModule: """Network sub-module for port URL calculation.""" from agent_sandbox.api.network import NetworkModule from agent_sandbox.protocol.port_contract import PortContext - from agent_sandbox.providers.registry import get_provider return NetworkModule( sandbox_id=self.id, @@ -336,7 +346,7 @@ def network(self) -> NetworkModule: access_token=self._envd_token.token if self._envd_token else None, capabilities=self._capabilities, port_resolver=self._port_resolver(), - port_access=get_provider(self._provider_id).create_port_access( + port_access=self._provider_impl().create_port_access( PortContext( self.id, self._domain, @@ -424,9 +434,8 @@ async def application_client( from agent_sandbox.api.server_client import ServerClient from agent_sandbox.protocol.port_contract import PortContext - from agent_sandbox.providers.registry import get_provider - descriptor = await get_provider(self.provider).application_endpoint( + descriptor = await self._provider_impl().application_endpoint( PortContext( self.id, self._domain, @@ -1027,32 +1036,56 @@ async def _create_via_provider( options: dict[str, Any] | None, on_created: Callable[[str], None] | None = None, ) -> Sandbox: + sandbox_config = SandboxConfig( # type: ignore[call-arg] + template=template, + timeout=timeout, + metadata=metadata or {}, + env_vars=envs or {}, + cpu=cpu, + memory=memory, + disk=disk, + gpu=gpu, + volume_mounts=volume_mounts, + network=network, + allow_internet_access=allow_internet_access, + secure=secure, + provider_options=dict(options or {}), + ) + infra = await _provider_infra(prov, overrides, options) + return await cls._create_from_infra( + prov, + infra, + sandbox_config, + request_timeout=request_timeout, + domain=domain, + on_created=on_created, + ) + + @classmethod + async def _create_from_infra( + cls, + prov: Provider, + infra: ProviderInfra, + sandbox_config: SandboxConfig, + *, + request_timeout: float | None = None, + domain: str | None = None, + on_created: Callable[[str], None] | None = None, + bound_check: Callable[[], None] | None = None, + ) -> Sandbox: closer = _InfraCloser(infra) created: SandboxInfo | None = None try: - sandbox_config = SandboxConfig( # type: ignore[call-arg] - template=template, - timeout=timeout, - metadata=metadata or {}, - env_vars=envs or {}, - cpu=cpu, - memory=memory, - disk=disk, - gpu=gpu, - volume_mounts=volume_mounts, - network=network, - allow_internet_access=allow_internet_access, - secure=secure, - provider_options=dict(options or {}), - ) info = await infra.sandbox_protocol.create( sandbox_config, request_timeout=request_timeout ) created = info if on_created is not None: on_created(info.sandbox_id) - binding = await prov.prepare_session(infra, info, operation="create", template=template) + binding = await prov.prepare_session( + infra, info, operation="create", template=sandbox_config.template + ) logger.info("Sandbox created: %s (provider %s)", info.sandbox_id, prov.id) resolved = ResolvedCapabilities( capabilities=set(DEFAULT_CAPABILITIES) | set(prov.capabilities()) @@ -1070,15 +1103,31 @@ async def _create_via_provider( "code_interpreter_protocol", infra.code_interpreter_protocol ), domain=domain or infra.config.sandbox_domain, - secure=True if secure is None else secure, + secure=True if sandbox_config.secure is None else sandbox_config.secure, resolved_capabilities=binding.pop("resolved_capabilities", resolved), declared_capabilities=binding.pop( "declared_capabilities", frozenset(prov.capabilities()) ), provider_id=prov.id, + bound_provider=prov if bound_check is not None else None, + bound_check=bound_check, **binding, ) except BaseException as exc: + if ( + bound_check is not None + and created is None + and isinstance( + exc, + ( + NetworkError, + ProviderProcessError, + ProviderProtocolError, + ProviderTimeoutError, + ), + ) + ): + exc.outcome = "unknown_outcome" # type: ignore[union-attr] if created is not None: exc.owned_resource = {"provider_id": prov.id, "sandbox_id": created.sandbox_id} # type: ignore[attr-defined] try: @@ -1105,9 +1154,26 @@ async def _connect_via_provider( traffic_access_token: str | None = None, ) -> Sandbox: infra = await _provider_infra(prov, overrides, options) + return await cls._connect_from_infra( + prov, infra, sandbox_id, domain=domain, traffic_access_token=traffic_access_token + ) + + @classmethod + async def _connect_from_infra( + cls, + prov: Provider, + infra: ProviderInfra, + sandbox_id: str, + *, + domain: str | None = None, + traffic_access_token: str | None = None, + bound_check: Callable[[], None] | None = None, + ) -> Sandbox: closer = _InfraCloser(infra) try: info = await infra.sandbox_protocol.connect(sandbox_id) + if bound_check is not None and info.sandbox_id != sandbox_id: + raise ValueError("Provider connect returned a different sandbox identity.") if traffic_access_token is not None: info.traffic_access_token = traffic_access_token binding = await prov.prepare_session( @@ -1135,9 +1201,11 @@ async def _connect_via_provider( "declared_capabilities", frozenset(prov.capabilities()) ), provider_id=prov.id, + bound_provider=prov if bound_check is not None else None, + bound_check=bound_check, **binding, ) - except Exception: + except BaseException: await closer.close() raise @@ -1209,7 +1277,7 @@ async def refresh_info(self) -> SandboxInfo: """Refresh sandbox info from the platform.""" info = await self._sandbox_protocol.get_info(self.id) if not info.envd_url: - info.envd_url = get_provider(self._provider_id).resolve_session_url(info, self._config) + info.envd_url = self._provider_impl().resolve_session_url(info, self._config) await self._rebind_session(info) return self._info @@ -1221,7 +1289,7 @@ async def _rebind_session(self, info: SandboxInfo) -> None: changes = {name: getattr(info, name) for name in info.model_fields_set} self._info = self._info.model_copy(update=changes) if not self._info.envd_url: - self._info.envd_url = get_provider(self._provider_id).resolve_session_url( + self._info.envd_url = self._provider_impl().resolve_session_url( self._info, self._config ) if "envd_access_token" in changes: @@ -1297,13 +1365,10 @@ async def get_terminal( rows: Terminal rows (default 24). shell: Shell binary (default ``/bin/bash``). """ - from agent_sandbox.providers.registry import get_provider return cast( "TerminalSession", - await get_provider(self._provider_id).open_terminal( - self, cols=cols, rows=rows, shell=shell - ), + await self._provider_impl().open_terminal(self, cols=cols, rows=rows, shell=shell), ) # ---- Named commands (registered on the in-sandbox SandboxServer) ---- diff --git a/client-sdk/src/agent_sandbox/providers/__init__.py b/client-sdk/src/agent_sandbox/providers/__init__.py index e1a79e65..d944edaa 100644 --- a/client-sdk/src/agent_sandbox/providers/__init__.py +++ b/client-sdk/src/agent_sandbox/providers/__init__.py @@ -19,6 +19,10 @@ from agent_sandbox.providers.base import Provider as Provider from agent_sandbox.providers.base import ProviderFeature as ProviderFeature from agent_sandbox.providers.base import ProviderInfra as ProviderInfra + from agent_sandbox.providers.client import EppImplementation as EppImplementation + from agent_sandbox.providers.client import ProviderClient as ProviderClient + from agent_sandbox.providers.client import ProviderLock as ProviderLock + from agent_sandbox.providers.client import ProviderRuntime as ProviderRuntime from agent_sandbox.providers.manifest import ProviderCommand as ProviderCommand from agent_sandbox.providers.registry import ambient_provider_id as ambient_provider_id from agent_sandbox.providers.registry import get_provider as get_provider @@ -28,6 +32,7 @@ from agent_sandbox.providers.registry import register_provider as register_provider from agent_sandbox.providers.registry import resolve_provider_id as resolve_provider_id from agent_sandbox.providers.registry import unregister_provider as unregister_provider + from agent_sandbox.providers.runtime_assets import ProviderArtifact as ProviderArtifact from agent_sandbox.utils.config_keys import BUILTIN_PROVIDER_ID as BUILTIN_PROVIDER_ID __all__ = [ @@ -39,6 +44,11 @@ "ProviderFeature", "ProviderInfra", "ProviderCommand", + "EppImplementation", + "ProviderClient", + "ProviderLock", + "ProviderRuntime", + "ProviderArtifact", "commands", "ambient_provider_id", "get_provider", @@ -61,6 +71,10 @@ def __getattr__(name: str) -> Any: return getattr(import_module("agent_sandbox.utils.config_keys"), name) if name in {"FEATURES", "ConfigField", "Provider", "ProviderFeature", "ProviderInfra"}: module = "base" + elif name in {"EppImplementation", "ProviderClient", "ProviderLock", "ProviderRuntime"}: + module = "client" + elif name == "ProviderArtifact": + module = "runtime_assets" elif name == "ProviderCommand": module = "manifest" elif name in __all__: diff --git a/client-sdk/src/agent_sandbox/providers/client.py b/client-sdk/src/agent_sandbox/providers/client.py new file mode 100644 index 00000000..493a9317 --- /dev/null +++ b/client-sdk/src/agent_sandbox/providers/client.py @@ -0,0 +1,542 @@ +"""Explicit target binding with optional, lock-driven Provider preparation.""" + +from __future__ import annotations + +import asyncio +import math +import platform +import sys +import tempfile +import time +from contextlib import asynccontextmanager +from functools import wraps +from pathlib import Path +from typing import TYPE_CHECKING, Any, cast +from urllib.parse import urlsplit + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +from agent_sandbox._version import __version__ +from agent_sandbox.api.sandbox import Sandbox, _InfraCloser +from agent_sandbox.models.errors import ( + ProviderConfigError, + ProviderFeatureNotSupportedError, + ProviderMismatchError, + ProviderTimeoutError, + ProviderVersionError, +) +from agent_sandbox.models.sandbox import SandboxConfig, SandboxInfo +from agent_sandbox.providers.exec_provider import ExecProvider +from agent_sandbox.providers.manifest import check_requires, load_manifest +from agent_sandbox.providers.runtime_assets import ProviderArtifact, member_path, unpack + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Awaitable, Callable, Collection, Sequence + + from agent_sandbox.models.sandbox import SandboxStatus + from agent_sandbox.providers.base import Provider, ProviderInfra + from agent_sandbox.transport.config import TransportConfig + + +class ProviderRuntime(BaseModel): + """A runtime archive and the two members needed for execution and attribution.""" + + model_config = ConfigDict(extra="forbid", frozen=True, strict=True) + + artifact: ProviderArtifact + executable: str + license_file: str + + @field_validator("executable", "license_file") + @classmethod + def valid_member(cls, value: str) -> str: + return member_path(value).as_posix() + + +class EppImplementation(BaseModel): + """An approved standalone EPP/1 entry and its artifact dependencies.""" + + model_config = ConfigDict(extra="forbid", frozen=True, strict=True) + + id: str = Field(pattern=r"^[a-z0-9][a-z0-9-]*$") + language: str = Field(pattern=r"^[a-z][a-z0-9-]*$") + platform: str = Field(pattern=r"^linux-[a-z0-9_]+-glibc$") + priority: int = Field(ge=0) + features: tuple[str, ...] + entrypoint: str + artifact: ProviderArtifact + runtime: ProviderRuntime | None = None + required_options: tuple[str, ...] = () + + @field_validator("entrypoint") + @classmethod + def valid_entrypoint(cls, entrypoint: str) -> str: + return member_path(entrypoint).as_posix() + + +class ProviderLock(BaseModel): + """A Provider release approved via a trusted channel outside the SDK.""" + + model_config = ConfigDict(extra="forbid", frozen=True, strict=True) + + provider: str = Field(pattern=r"^[a-z0-9][a-z0-9-]*$") + version: str = Field(min_length=1) + implementations: tuple[EppImplementation, ...] = () + + +def _host_platform() -> str: + machine = platform.machine().lower() + libc, _ = platform.libc_ver() + return f"{sys.platform}-{machine}-{libc}" + + +def _select_epp( + implementations: Sequence[EppImplementation], required: frozenset[str] +) -> EppImplementation: + supported = [ + entry + for entry in implementations + if entry.platform == _host_platform() and required.issubset(entry.features) + ] + if not supported: + raise ProviderConfigError( + "No approved Provider implementation matches this host and features." + ) + + def order(entry: EppImplementation) -> tuple[bool, int]: + return entry.language != "python", entry.priority + + winner = min(supported, key=order) + if sum(order(entry) == order(winner) for entry in supported) > 1: + raise ProviderConfigError("Compatible Provider implementations share a priority.") + return winner + + +def _prepare_epp( + lock: ProviderLock, + selected: EppImplementation, + cache: Path, + workspace: Path, + *, + download: bool, + deadline: float, + features: frozenset[str], + option_keys: frozenset[str], +) -> ExecProvider: + plugin_root = workspace / "provider" + unpack( + selected.artifact, + cache, + plugin_root, + download=download, + deadline=deadline, + executable=selected.entrypoint if selected.runtime is None else None, + ) + manifest = load_manifest(plugin_root) + if (manifest.id, manifest.version) != (lock.provider, lock.version): + raise ProviderVersionError("Provider archive identity differs from its lock.") + if ( + manifest.kind not in {"node", "exec"} + or (manifest.kind == "node" and selected.language != "node") + or not set(selected.features) <= set(manifest.features) + ): + raise ProviderVersionError("Provider archive does not declare the locked features.") + check_requires(manifest, component="sdk", host_version=__version__) + declared_options = {field.key for field in manifest.fields} + if ( + not option_keys <= declared_options + or not set(selected.required_options) <= declared_options + ): + raise ProviderConfigError("The bound Provider options differ from its manifest.") + entry = plugin_root / selected.entrypoint + if not entry.is_file(): + raise ProviderVersionError("Provider archive is missing its locked entrypoint.") + runtime = selected.runtime + argv: tuple[str, ...] + if runtime is None: + if manifest.kind == "node": + raise ProviderConfigError("A Node Provider requires an approved runtime archive.") + argv = (str(entry),) + else: + if runtime.executable == runtime.license_file: + raise ProviderConfigError("Runtime executable and license must be different files.") + runtime_root = workspace / "runtime" + unpack( + runtime.artifact, + cache, + runtime_root, + download=download, + deadline=deadline, + executable=runtime.executable, + license_file=runtime.license_file, + ) + argv = (str(runtime_root / runtime.executable), str(entry)) + data_dir = workspace / "data" + data_dir.mkdir(mode=0o700) + provider = ExecProvider( + manifest, + plugin_root, + prepared_argv=argv, + prepared_data_dir=data_dir, + required_features=features, + ) + provider.features = frozenset(selected.features) + return provider + + +class _BoundProtocol: + def __init__(self, protocol: Any, check: Callable[[], None]) -> None: + self._protocol = protocol + self._check = check + + def __getattr__(self, name: str) -> Any: + value = getattr(self._protocol, name) + if not callable(value): + return value + + @wraps(value) + def checked(*args: Any, **kwargs: Any) -> Any: + self._check() + return value(*args, **kwargs) + + return checked + + +class ProviderClient: + """An explicit Provider and account bound to one event loop. + + Call :meth:`prepare` during application startup. Close sandbox handles before + closing the client. Delete owned sandboxes explicitly. + """ + + def __init__( + self, + provider: Provider, + config: TransportConfig, + infra: ProviderInfra | None, + workspace: tempfile.TemporaryDirectory[str] | None, + implementation: str, + ) -> None: + self._provider = provider + self._config = config + self._infra = infra + self._workspace = workspace + self._implementation = implementation + self._loop = asyncio.get_running_loop() + self._closed = False + self._session_lock = asyncio.Lock() + self._sessions: dict[int, Callable[[], Awaitable[None]]] = {} + self._close_task: asyncio.Task[None] | None = None + + @classmethod + async def prepare( + cls, + lock: ProviderLock, + config: TransportConfig, + *, + native: Provider | None = None, + required_features: Collection[str] = (), + cache_dir: Path | None = None, + download: bool = False, + timeout: float = 180.0, + ) -> ProviderClient: + """Bind an installed Python provider or a locked standalone implementation. + + An explicitly supplied compatible native provider wins before downloading. + The cache is offline by default. Neither path discovers global plugins. + """ + if config.provider != lock.provider: + raise ProviderMismatchError("Provider configuration does not match the lock.") + if not 0 < timeout <= 3600: + raise ProviderConfigError("Provider preparation timeout must be in (0, 3600] seconds.") + config = config.model_copy(deep=True) + features = frozenset(required_features) + if native is not None and ( + (native.id, native.version) != (lock.provider, lock.version) + or native.kind not in {"builtin", "python"} + ): + raise ProviderVersionError("Native Provider identity or kind differs from the lock.") + if native is not None and features <= native.features: + if native.kind == "builtin" and ( + not (config.sandbox_api_key or "").strip() + or config.access_key_id + or config.access_key_secret + or config.security_token + or not {"sandbox_base_url", "sandbox_domain"} <= config.model_fields_set + or not config.sandbox_base_url.strip() + or not config.sandbox_domain.strip() + ): + raise ProviderConfigError( + "Bind the built-in Provider with an explicit Sandbox API key, URL and domain." + ) + native.validate_config(config) + return cls(native, config, None, None, "python-native") + if cache_dir is None: + raise ProviderConfigError("A cache_dir is required to prepare a standalone Provider.") + selected = _select_epp(lock.implementations, features) + missing = { + option + for option in selected.required_options + if config.provider_options.get(option) is None + or (isinstance(value := config.provider_options[option], str) and not value.strip()) + } + if missing: + raise ProviderConfigError( + f"Missing explicit Provider options: {', '.join(sorted(missing))}." + ) + workspace = tempfile.TemporaryDirectory(prefix="agent-sandbox-provider-") + deadline = time.monotonic() + timeout + task = asyncio.create_task( + asyncio.to_thread( + _prepare_epp, + lock, + selected, + cache_dir.absolute(), + Path(workspace.name), + download=download, + deadline=deadline, + features=features, + option_keys=frozenset(config.provider_options), + ) + ) + try: + provider = await asyncio.wait_for(asyncio.shield(task), timeout) + except BaseException as exc: + # The thread may still own files when its awaiter is cancelled. + def cleanup(done: asyncio.Task[ExecProvider]) -> None: + if not done.cancelled(): + done.exception() + workspace.cleanup() + + task.add_done_callback(cleanup) + if isinstance(exc, asyncio.TimeoutError): + raise ProviderTimeoutError("Provider artifact preparation timed out.") from None + raise + + try: + for field in provider.config_fields: + if field.type != "url" or field.key not in config.provider_options: + continue + value = config.provider_options[field.key] + try: + url = urlsplit(value) if isinstance(value, str) else None + valid_url = ( + url is not None + and url.scheme in {"http", "https"} + and url.hostname + and url.username is None + and url.password is None + ) + except ValueError: + valid_url = False + if not valid_url: + raise ProviderConfigError(f"Provide an explicit HTTP(S) URL for {field.key}.") + infra = await asyncio.wait_for( + provider.build_infra(config), max(0.0, deadline - time.monotonic()) + ) + except BaseException: + workspace.cleanup() + raise + return cls(provider, config, infra, workspace, selected.id) + + @property + def implementation(self) -> str: + return self._implementation + + @property + def features(self) -> frozenset[str]: + return self._provider.features + + def _check(self) -> None: + if asyncio.get_running_loop() is not self._loop: + raise RuntimeError("Use a ProviderClient on the event loop that prepared it.") + if self._closed: + raise RuntimeError("ProviderClient is closed.") + + def _sandbox_id(self, sandbox_id: str) -> str: + self._check() + prefix, separator, bare = sandbox_id.partition(":") + if separator and prefix != self._provider.id: + raise ProviderMismatchError("Sandbox reference does not match the bound Provider.") + target = bare if separator else prefix + if not target.strip(): + raise ValueError("Sandbox ID must not be empty.") + return target + + async def _sandbox_infra(self) -> tuple[Provider, ProviderInfra, Callable[[], None]]: + async with self._session_lock: + self._check() + provider = self._provider + if isinstance(provider, ExecProvider): + # EPP/1 notifications use bare process IDs, which can collide across sandboxes. + provider = provider._session_provider() + infra = await provider.build_infra(self._config.model_copy(deep=True)) + closer = _InfraCloser(infra) + # Capture the original cleanup before installing the handle's close callback. + close_infra = infra.close + http_client = infra.http_client + if self._closed: + await closer.close() + raise RuntimeError("ProviderClient is closed.") + key = id(infra) + closing: asyncio.Task[None] | None = None + + async def dispose() -> None: + try: + if close_infra is not None: + await close_infra() + elif http_client is not None: + await http_client.close() + finally: + self._sessions.pop(key, None) + + async def close() -> None: + nonlocal closing + if closing is None: + closing = asyncio.create_task(dispose()) + await asyncio.shield(closing) + + def check_handle() -> None: + self._check() + if closing is not None: + raise RuntimeError("Sandbox handle is closed.") + + for field in ( + "sandbox_protocol", + "process_protocol", + "filesystem_protocol", + "code_interpreter_protocol", + ): + protocol = getattr(infra, field) + if protocol is not None: + setattr(infra, field, _BoundProtocol(protocol, check_handle)) + infra.close = close + self._sessions[key] = close + return provider, infra, check_handle + + @asynccontextmanager + async def _control_infra(self) -> AsyncIterator[ProviderInfra]: + self._check() + if self._infra is not None: + yield self._infra + else: + infra = await self._provider.build_infra(self._config.model_copy(deep=True)) + try: + self._check() + yield infra + finally: + await _InfraCloser(infra).close() + + async def create( + self, + config: SandboxConfig | None = None, + *, + request_timeout: float | None = None, + on_created: Callable[[str], None] | None = None, + ) -> Sandbox: + self._check() + if request_timeout is not None and ( + not math.isfinite(request_timeout) or request_timeout <= 0 + ): + raise ValueError("request_timeout must be finite and positive.") + sandbox_config = config if config is not None else SandboxConfig() + # These inputs must never be silently dropped by a transport. + for feature, requested in ( + ("volume_mounts", bool(sandbox_config.volume_mounts)), + ( + "network", + sandbox_config.network is not None + or sandbox_config.allow_internet_access is not None, + ), + ("auto_pause", sandbox_config.auto_pause), + ): + if requested and feature not in self._provider.create_options: + raise ProviderFeatureNotSupportedError(self._provider.id, feature) + if sandbox_config.network is not None: + from agent_sandbox.models.network import network_create_payload + + network_create_payload(sandbox_config.network) + if ( + sandbox_config.network.get("allow_public_traffic") is False + and sandbox_config.secure is False + ): + raise ValueError("Disabling public traffic requires secure=True.") + provider, infra, check_handle = await self._sandbox_infra() + return await Sandbox._create_from_infra( + provider, + infra, + sandbox_config, + request_timeout=request_timeout, + on_created=on_created, + bound_check=check_handle, + ) + + async def connect(self, sandbox_id: str, *, traffic_access_token: str | None = None) -> Sandbox: + target = self._sandbox_id(sandbox_id) + provider, infra, check_handle = await self._sandbox_infra() + return await Sandbox._connect_from_infra( + provider, + infra, + target, + traffic_access_token=traffic_access_token, + bound_check=check_handle, + ) + + async def list( + self, *, status: SandboxStatus | None = None, limit: int = 100, offset: int = 0 + ) -> list[SandboxInfo]: + async with self._control_infra() as infra: + return cast( + "list[SandboxInfo]", + await infra.sandbox_protocol.list(status=status, limit=limit, offset=offset), + ) + + async def get(self, sandbox_id: str) -> SandboxInfo: + target = self._sandbox_id(sandbox_id) + async with self._control_infra() as infra: + info = cast("SandboxInfo", await infra.sandbox_protocol.get_info(target)) + if info.sandbox_id != target: + raise ValueError("Provider get returned a different sandbox identity.") + return info + + async def delete(self, sandbox_id: str) -> None: + target = self._sandbox_id(sandbox_id) + async with self._control_infra() as infra: + await infra.sandbox_protocol.kill(target) + + async def set_timeout(self, sandbox_id: str, timeout: int) -> None: + target = self._sandbox_id(sandbox_id) + async with self._control_infra() as infra: + await infra.sandbox_protocol.set_timeout(target, timeout) + + async def close(self) -> None: + if self._close_task is None: + self._check() + self._closed = True + self._close_task = asyncio.create_task(self._close()) + await asyncio.shield(self._close_task) + + async def _close(self) -> None: + try: + try: + async with self._session_lock: + closing = tuple(self._sessions.values()) + results = await asyncio.gather( + *(close() for close in closing), return_exceptions=True + ) + for result in results: + if isinstance(result, BaseException): + raise result + finally: + if self._infra is not None: + await _InfraCloser(self._infra).close() + finally: + if self._workspace is not None: + self._workspace.cleanup() + + async def __aenter__(self) -> ProviderClient: + self._check() + return self + + async def __aexit__(self, *args: Any) -> None: + await self.close() diff --git a/client-sdk/src/agent_sandbox/providers/epp.py b/client-sdk/src/agent_sandbox/providers/epp.py index a6196469..9be027d2 100644 --- a/client-sdk/src/agent_sandbox/providers/epp.py +++ b/client-sdk/src/agent_sandbox/providers/epp.py @@ -229,7 +229,7 @@ def __init__( self._queues: dict[str, asyncio.Queue[dict[str, Any] | None]] = {} self._early: dict[str, list[dict[str, Any]]] = {} self._failure: E.SandboxError | None = None - self._closed = False + self._close_task: asyncio.Task[None] | None = None self.plugin_info: dict[str, Any] = {} self.features: frozenset[str] = frozenset() @@ -290,7 +290,8 @@ async def start(self, init_params: Mapping[str, Any]) -> dict[str, Any]: f"Provider '{self.provider_id}' answered protocol '{answered}', " f"expected '{PROTOCOL}'." ) - self.plugin_info = dict(result.get("plugin") or {}) + plugin = result.get("plugin") + self.plugin_info = dict(plugin) if isinstance(plugin, dict) else {} feats = result.get("features") self.features = ( frozenset(f for f in feats if isinstance(f, str)) @@ -304,9 +305,11 @@ def _with_tail(self) -> str: return f"Plugin stderr: {tail[-500:]}" if tail else "" async def close(self) -> None: - if self._closed: - return - self._closed = True + if self._close_task is None: + self._close_task = asyncio.create_task(self._close()) + await asyncio.shield(self._close_task) + + async def _close(self) -> None: proc = self._proc if proc is not None and proc.returncode is None: with contextlib.suppress(Exception): @@ -330,7 +333,10 @@ async def close(self) -> None: task.cancel() with contextlib.suppress(asyncio.CancelledError, Exception): await task - self._fail_all(E.ProviderProcessError(f"Provider '{self.provider_id}' was closed.")) + self._fail_all( + E.ProviderProcessError(f"Provider '{self.provider_id}' was closed."), + end_streams=True, + ) def _reap_group(self) -> None: """Kill children the plugin left behind (POSIX: the plugin leads its own session).""" @@ -487,35 +493,51 @@ async def call( self._next_id += 1 rid = self._next_id fut: asyncio.Future[Any] = asyncio.get_running_loop().create_future() - self._pending[rid] = fut - payload = json.dumps( - {"jsonrpc": "2.0", "id": rid, "method": method, "params": dict(params or {})} + payload = ( + json.dumps( + {"jsonrpc": "2.0", "id": rid, "method": method, "params": dict(params or {})} + ).encode("utf-8") + + b"\n" ) + if len(payload) > MAX_LINE_BYTES: + raise E.ProviderProtocolError("Provider request exceeds the EPP frame size limit.") + self._pending[rid] = fut + stdin = proc.stdin + assert stdin is not None + + async def send_and_receive() -> Any: + stdin.write(payload) + await stdin.drain() + return await fut + + limit = timeout if timeout is not None else self._call_timeout try: - proc.stdin.write(payload.encode("utf-8") + b"\n") - await proc.stdin.drain() + return await asyncio.wait_for(send_and_receive(), limit) except (BrokenPipeError, ConnectionResetError) as exc: - self._pending.pop(rid, None) raise E.ProviderProcessError( f"Provider '{self.provider_id}' closed its input.", suggestion=self._with_tail() ) from exc - limit = timeout if timeout is not None else self._call_timeout - try: - return await asyncio.wait_for(fut, limit) - except asyncio.TimeoutError: - self._pending.pop(rid, None) + except (asyncio.TimeoutError, asyncio.CancelledError) as exc: if not _startup: with contextlib.suppress(Exception): - proc.stdin.write( + stdin.write( json.dumps( {"jsonrpc": "2.0", "method": "$/cancel", "params": {"id": rid}} ).encode() + b"\n" ) + if isinstance(exc, asyncio.CancelledError): + raise raise E.ProviderTimeoutError( f"Provider '{self.provider_id}' did not answer '{method}' within {limit:g}s.", suggestion=self._with_tail(), ) from None + finally: + self._pending.pop(rid, None) + if not fut.done(): + fut.cancel() + elif not fut.cancelled(): + fut.exception() def open_stream(self, process_id: str) -> asyncio.Queue[dict[str, Any] | None]: """Register a notification queue for a process id (drains early notifications).""" diff --git a/client-sdk/src/agent_sandbox/providers/exec_provider.py b/client-sdk/src/agent_sandbox/providers/exec_provider.py index c32c8278..f163a438 100644 --- a/client-sdk/src/agent_sandbox/providers/exec_provider.py +++ b/client-sdk/src/agent_sandbox/providers/exec_provider.py @@ -5,6 +5,7 @@ import asyncio import base64 import contextlib +from copy import copy from datetime import datetime, timezone from typing import TYPE_CHECKING, Any @@ -14,6 +15,7 @@ ProviderFeatureNotSupportedError, ProviderProtocolError, ProviderResourceNotFoundError, + ProviderVersionError, SandboxError, SandboxNotFoundError, ) @@ -615,10 +617,17 @@ def __init__( manifest: Manifest, plugin_root: Path, receipt: dict[str, Any] | None = None, + *, + prepared_argv: tuple[str, ...] | None = None, + prepared_data_dir: Path | None = None, + required_features: frozenset[str] = frozenset(), ) -> None: self.manifest = manifest self.plugin_root = plugin_root self.receipt = receipt + self._prepared_argv = prepared_argv + self._prepared_data_dir = prepared_data_dir + self._required_features = required_features self.id = manifest.id self.display_name = manifest.name self.display_name_zh = manifest.name_zh @@ -631,6 +640,10 @@ def __init__( self.auth_any_of = manifest.auth_any_of self.inherit = consented_inherit(manifest.inherit, receipt) + def _session_provider(self) -> ExecProvider: + # The startup contract is shared, while negotiated state belongs to one process. + return copy(self) + async def application_endpoint( self, context: PortContext, port: int, protocol: Any = None ) -> dict[str, Any]: @@ -650,8 +663,15 @@ async def build_infra(self, config: TransportConfig) -> ProviderInfra: self.validate_config(config) if self.receipt is not None: store.verify_integrity(self.id) - argv = resolve_command(self.manifest.command, self.plugin_root) - data_dir = store.data_dir(self.id) + if self._prepared_argv is None or self._prepared_data_dir is None: + argv = resolve_command(self.manifest.command, self.plugin_root) + data_dir = store.data_dir(self.id) + env = scrubbed_env(data_dir, self.manifest.security.get("env_passthrough", [])) + else: + argv = list(self._prepared_argv) + data_dir = self._prepared_data_dir + env = {"HOME": str(data_dir), "TMPDIR": str(data_dir), "PATH": str(data_dir)} + opts = dict(config.provider_options) init_config = { f.key: opts.get(f.key) for f in self.config_fields if opts.get(f.key) is not None @@ -673,7 +693,7 @@ async def build_infra(self, config: TransportConfig) -> ProviderInfra: self.id, argv, cwd=data_dir, - env=scrubbed_env(data_dir, self.manifest.security.get("env_passthrough", [])), + env=env, startup_timeout=self.manifest.startup_timeout_ms / 1000.0, call_timeout=self.manifest.call_timeout_ms / 1000.0, secrets=secret_values, @@ -698,13 +718,48 @@ async def build_infra(self, config: TransportConfig) -> ProviderInfra: or handshake.get("startup_modes") != list(self.manifest.startup_modes) ): await client.close() - from agent_sandbox.models.errors import ProviderVersionError - raise ProviderVersionError( "Provider runtime operation contract differs from its manifest" ) - advertised = client.features or self.features - supported = self.features & advertised + if self._prepared_argv is not None: + if ( + client.plugin_info.get("name") != self.id + or client.plugin_info.get("version") != self.version + or not isinstance(handshake.get("features"), list) + or not all(isinstance(feature, str) for feature in handshake["features"]) + ): + await client.close() + raise ProviderVersionError( + "Provider runtime identity or features differ from the lock." + ) + supported = self.features & client.features + missing = self._required_features - supported + if missing: + await client.close() + raise ProviderFeatureNotSupportedError(self.id, ", ".join(sorted(missing))) + self.features = supported + operation_features = { + "exec.run": "exec.run", + "exec.stream": "exec.stream", + "ports.resolve": "ports.url", + "sandbox.timeout": "sandbox.timeout", + "sandbox.pause": "sandbox.pause", + "sandbox.resume": "sandbox.pause", + } + self.operations = frozenset( + operation + for operation in self.operations + if operation_features.get( + operation, + { + "files": "files.rw", + "sandbox": "sandbox.lifecycle", + }.get(operation.split(".", 1)[0]), + ) + in supported + ) + else: + supported = self.features & (client.features or self.features) native: dict[str, Any] = {} http_client = None auth = None @@ -721,9 +776,11 @@ async def build_infra(self, config: TransportConfig) -> ProviderInfra: } async def _close() -> None: - await client.close() - if http_client is not None: - await http_client.close() + try: + await client.close() + finally: + if http_client is not None: + await http_client.close() from agent_sandbox.providers.feature_gate import gate_operation_protocols diff --git a/client-sdk/src/agent_sandbox/providers/runtime_assets.py b/client-sdk/src/agent_sandbox/providers/runtime_assets.py new file mode 100644 index 00000000..2ae834a9 --- /dev/null +++ b/client-sdk/src/agent_sandbox/providers/runtime_assets.py @@ -0,0 +1,251 @@ +"""Verify and prepare explicitly approved provider and interpreter archives.""" + +from __future__ import annotations + +import contextlib +import gzip +import hashlib +import lzma +import os +import ssl +import stat +import tarfile +import tempfile +import time +from pathlib import Path, PurePosixPath +from typing import TYPE_CHECKING, cast +from urllib.parse import urlsplit + +import httpx +from pydantic import BaseModel, ConfigDict, Field, field_validator + +from agent_sandbox.models.errors import ProviderProcessError, ProviderTimeoutError + +if TYPE_CHECKING: + from typing import BinaryIO + +_MAX_BYTES = 256 * 1024 * 1024 +_MAX_UNPACKED_BYTES = 512 * 1024 * 1024 +_MAX_MEMBERS = 20_000 +_CHUNK = 128 * 1024 + + +class ProviderArtifact(BaseModel): + """An immutable HTTPS tar archive approved by the caller.""" + + model_config = ConfigDict(extra="forbid", frozen=True, strict=True) + + url: str + sha256: str = Field(pattern=r"^[a-f0-9]{64}$") + size: int = Field(gt=0, le=_MAX_BYTES) + root: str + + @field_validator("url") + @classmethod + def https_only(cls, url: str) -> str: + parsed = urlsplit(url) + if parsed.port == 0: + raise ValueError("Artifact port must be greater than zero.") + if ( + parsed.scheme != "https" + or not parsed.hostname + or parsed.username is not None + or parsed.password is not None + or parsed.query + or parsed.fragment + or any(ch.isspace() for ch in url) + ): + raise ValueError("Use an HTTPS artifact URL without credentials, query or fragment.") + return url + + @field_validator("root") + @classmethod + def valid_root(cls, root: str) -> str: + if len(member_path(root).parts) != 1: + raise ValueError("An archive root must be one directory.") + return root + + +def member_path(value: str) -> PurePosixPath: + if ( + any(part in {"", ".", ".."} for part in value.split("/")) + or "\\" in value + or ":" in value + or any(ord(ch) < 32 for ch in value) + ): + raise ValueError("Invalid archive path.") + return PurePosixPath(value) + + +def _budget(deadline: float) -> float: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise ProviderTimeoutError("Provider artifact preparation timed out.") + return remaining + + +def _verify(stream: BinaryIO, asset: ProviderArtifact, deadline: float) -> None: + digest = hashlib.sha256() + size = 0 + while chunk := stream.read(_CHUNK): + _budget(deadline) + size += len(chunk) + if size > asset.size: + break + digest.update(chunk) + if size != asset.size or digest.hexdigest() != asset.sha256: + raise ProviderProcessError("Provider artifact does not match its approved size or digest.") + stream.seek(0) + + +def _download(asset: ProviderArtifact, destination: Path, deadline: float) -> None: + with tempfile.NamedTemporaryFile(dir=destination.parent) as stage: + try: + with ( + httpx.Client( + trust_env=False, + verify=ssl.create_default_context(), + follow_redirects=False, + timeout=min(_budget(deadline), 20.0), + ) as http, + http.stream("GET", asset.url, headers={"Accept-Encoding": "identity"}) as response, + ): + response.raise_for_status() + total = 0 + for chunk in response.iter_raw(): + _budget(deadline) + total += len(chunk) + if total > asset.size: + raise ProviderProcessError("Provider artifact exceeds its approved size.") + stage.write(chunk) + except httpx.HTTPError: + raise ProviderProcessError( + "Could not download the approved provider artifact." + ) from None + stage.flush() + stage.seek(0) + _verify(cast("BinaryIO", stage), asset, deadline) + os.fsync(stage.fileno()) + _budget(deadline) + # A concurrent prepare may have already published a verified copy. + with contextlib.suppress(FileExistsError): + os.link(stage.name, destination) + + +def unpack( + asset: ProviderArtifact, + cache: Path, + destination: Path, + *, + download: bool, + deadline: float, + executable: str | None = None, + license_file: str | None = None, +) -> None: + cache.mkdir(mode=0o700, parents=True, exist_ok=True) + info = cache.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077: + raise ProviderProcessError( + "Use a private provider cache directory owned by the current user." + ) + blob = cache / asset.sha256 + if not blob.exists() and download: + _download(asset, blob, deadline) + try: + fd = os.open(blob, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + except FileNotFoundError: + raise ProviderProcessError( + "The approved provider artifact is missing from the cache." + ) from None + except OSError: + raise ProviderProcessError( + "Could not open the approved cached provider artifact." + ) from None + + with os.fdopen(fd, "rb") as stream: + info = os.fstat(stream.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_size != asset.size: + raise ProviderProcessError( + "The cached provider artifact has an unexpected type or size." + ) + _verify(stream, asset, deadline) + try: + _extract(stream, asset.root, destination, deadline, executable, license_file) + except (OSError, ValueError, tarfile.TarError, EOFError, lzma.LZMAError): + raise ProviderProcessError( + "The approved provider archive has an invalid layout." + ) from None + + +class _ExtractionReader: + def __init__(self, stream: BinaryIO, deadline: float) -> None: + self._stream = stream + self._deadline = deadline + self._remaining = _MAX_UNPACKED_BYTES + + def read(self, count: int) -> bytes: + _budget(self._deadline) + data = self._stream.read(min(count, self._remaining + 1)) + self._remaining -= len(data) + if self._remaining < 0: + raise ValueError("Archive exceeds the decompressed byte limit.") + return data + + +def _extract( + stream: BinaryIO, + root: str, + destination: Path, + deadline: float, + executable: str | None, + license_file: str | None, +) -> None: + selected = {executable, license_file} if license_file else None + extracted: set[str] = set() + members: set[PurePosixPath] = set() + total = 0 + magic = stream.read(6) + stream.seek(0) + if magic.startswith(b"\x1f\x8b"): + decoded = cast("BinaryIO", gzip.GzipFile(fileobj=stream)) + elif magic == b"\xfd7zXZ\x00": + decoded = cast("BinaryIO", lzma.LZMAFile(stream)) # noqa: SIM115 + else: + raise ValueError("Expected a gzip or xz compressed tar archive.") + reader = cast("BinaryIO", _ExtractionReader(decoded, deadline)) + with decoded, tarfile.open(fileobj=reader, mode="r|") as archive: + for member in archive: + _budget(deadline) + path = member_path(member.name) + if path.parts[0] != root or path in members: + raise ValueError("Unexpected or repeated archive path.") + members.add(path) + total += member.size + if len(members) > _MAX_MEMBERS or total > _MAX_UNPACKED_BYTES or member.size < 0: + raise ValueError("Archive exceeds extraction limits.") + relative = "/".join(path.parts[1:]) + if not relative and member.isdir(): + continue + if not relative: + raise ValueError("Archive root must be a directory.") + if selected is not None and relative not in selected: + continue + target = destination.joinpath(*path.parts[1:]) + if member.isdir() and selected is None: + target.mkdir(parents=True, exist_ok=True) + continue + if not member.isfile() or member.issparse(): + raise ValueError("Expected a regular archive member.") + target.parent.mkdir(parents=True, exist_ok=True) + source = archive.extractfile(member) + if source is None: + raise ValueError("Missing archive contents.") + with source, target.open("xb") as output: + while chunk := source.read(_CHUNK): + _budget(deadline) + output.write(chunk) + if relative == executable: + target.chmod(0o700) + extracted.add(relative) + if selected is not None and extracted != selected: + raise ValueError("Missing runtime executable or license.") diff --git a/client-sdk/tests/test_providers/test_bound_client.py b/client-sdk/tests/test_providers/test_bound_client.py new file mode 100644 index 00000000..e11b7499 --- /dev/null +++ b/client-sdk/tests/test_providers/test_bound_client.py @@ -0,0 +1,190 @@ +"""Prepared provider selection, target binding and cache contracts.""" + +from __future__ import annotations + +import hashlib +import io +import tarfile +import time +from types import SimpleNamespace +from typing import TYPE_CHECKING + +import pytest + +from agent_sandbox.api import sandbox as sandbox_module +from agent_sandbox.models.errors import ( + ProviderConfigError, + ProviderFeatureNotSupportedError, + ProviderMismatchError, + ProviderProcessError, +) +from agent_sandbox.models.sandbox import SandboxConfig, SandboxInfo +from agent_sandbox.providers import Provider, ProviderArtifact, ProviderClient, ProviderInfra +from agent_sandbox.providers.client import EppImplementation, ProviderLock, _select_epp +from agent_sandbox.providers.runtime_assets import unpack +from agent_sandbox.transport.config import TransportConfig + +if TYPE_CHECKING: + from pathlib import Path + + +class LocalNative(Provider): + id = "local-native" + version = "1.0.0" + operations = frozenset({"sandbox.create", "sandbox.get", "sandbox.delete"}) + features = frozenset({"sandbox.lifecycle"}) + + def __init__(self, destination: str) -> None: + self.destination = destination + self.calls: list[str] = [] + + async def build_infra(self, config): + self.calls.append(config.provider_options["account"]) + return ProviderInfra( + config, + None, + None, + SimpleNamespace( + create=self.create, + get_info=self.get_info, + kill=self.kill, + ), + ) + + async def create(self, config, request_timeout=None): + return SandboxInfo(sandboxID="shared-id") + + async def get_info(self, sandbox_id): + return SandboxInfo(sandboxID=sandbox_id) + + async def kill(self, sandbox_id): + self.calls.append(sandbox_id) + + def resolve_session_url(self, info, config): + return f"https://{self.destination}.example/{info.sandbox_id}" + + +async def test_same_id_native_targets_are_independent(monkeypatch): + def no_discovery(*args, **kwargs): + pytest.fail("Prepared handles must not consult legacy discovery.") + + monkeypatch.setattr(sandbox_module, "get_provider", no_discovery) + monkeypatch.setattr(sandbox_module, "load_config", no_discovery) + lock = ProviderLock(provider="local-native", version="1.0.0") + first = LocalNative("first") + second = LocalNative("second") + async with ( + await ProviderClient.prepare( + lock, + TransportConfig(provider=first.id, provider_options={"account": "a"}), + native=first, + download=True, + ) as a, + await ProviderClient.prepare( + lock, + TransportConfig(provider=second.id, provider_options={"account": "b"}), + native=second, + ) as b, + ): + left = await a.create() + right = await b.create() + try: + assert left.id == right.id == "shared-id" + assert left.url == "https://first.example/shared-id" + assert right.url == "https://second.example/shared-id" + assert left.operations == first.operations + assert (await right.refresh_info()).envd_url == right.url + with pytest.raises(ProviderMismatchError): + await a.connect("foreign:shared-id") + with pytest.raises(ProviderFeatureNotSupportedError): + await a.create(SandboxConfig(volume_mounts={"/x": "data"})) + assert first.calls == ["a"] + assert second.calls == ["b"] + finally: + await left.kill() + await right.kill() + with pytest.raises(RuntimeError, match="closed"): + await left.refresh_info() + assert first.calls == ["a", "shared-id"] + assert second.calls == ["b", "shared-id"] + + +def _asset(tmp_path: Path) -> tuple[ProviderArtifact, Path]: + cached = io.BytesIO() + with tarfile.open(fileobj=cached, mode="w:gz") as archive: + data = b"test provider" + info = tarfile.TarInfo("provider/entry") + info.size = len(data) + archive.addfile(info, io.BytesIO(data)) + payload = cached.getvalue() + asset = ProviderArtifact( + url="https://packages.example/provider.tar.gz", + size=len(payload), + sha256=hashlib.sha256(payload).hexdigest(), + root="provider", + ) + cache = tmp_path / "cache" + cache.mkdir(mode=0o700) + (cache / asset.sha256).write_bytes(payload) + return asset, cache + + +def test_offline_cache_is_rehashed_before_extraction(tmp_path): + asset, cache = _asset(tmp_path) + destination = tmp_path / "entry" + unpack(asset, cache, destination, download=False, deadline=time.monotonic() + 5) + assert (destination / "entry").read_bytes() == b"test provider" + + blob = cache / asset.sha256 + blob.write_bytes(bytes(asset.size)) + with pytest.raises(ProviderProcessError, match="digest"): + unpack(asset, cache, tmp_path / "corrupt", download=False, deadline=time.monotonic() + 5) + assert not (tmp_path / "corrupt").exists() + + +async def test_required_target_stops_before_opening_cache(monkeypatch, tmp_path): + asset, cache = _asset(tmp_path) + entry = EppImplementation( + id="standalone", + language="node", + platform="linux-x86_64-glibc", + priority=0, + features=("sandbox.lifecycle",), + artifact=asset, + entrypoint="entry", + required_options=("base_url",), + ) + lock = ProviderLock(provider="local-native", version="1.0.0", implementations=(entry,)) + monkeypatch.setattr( + "agent_sandbox.providers.client._host_platform", lambda: "linux-x86_64-glibc" + ) + with pytest.raises(ProviderConfigError, match="base_url"): + await ProviderClient.prepare( + lock, + TransportConfig(provider="local-native", provider_options={"base_url": " "}), + cache_dir=cache, + ) + + +def test_standalone_selection_uses_language_platform_and_features(monkeypatch, tmp_path): + asset, _ = _asset(tmp_path) + monkeypatch.setattr( + "agent_sandbox.providers.client._host_platform", lambda: "linux-x86_64-glibc" + ) + common = { + "platform": "linux-x86_64-glibc", + "features": ("sandbox.lifecycle",), + "entrypoint": "entry", + "artifact": asset, + } + local = EppImplementation(id="python-epp", language="python", priority=20, **common) + alternate = EppImplementation( + id="node-epp", + language="node", + priority=0, + **{**common, "features": ("sandbox.lifecycle", "pty")}, + ) + assert _select_epp((local, alternate), frozenset({"sandbox.lifecycle"})) is local + assert _select_epp((local, alternate), frozenset({"pty"})) is alternate + with pytest.raises(ProviderConfigError, match="No approved"): + _select_epp((local,), frozenset({"pty"})) diff --git a/client-sdk/tests/test_providers/test_epp.py b/client-sdk/tests/test_providers/test_epp.py index 1caf70c2..fc41e3dc 100644 --- a/client-sdk/tests/test_providers/test_epp.py +++ b/client-sdk/tests/test_providers/test_epp.py @@ -135,6 +135,29 @@ async def test_call_timeout(tmp_path): await client.close() +@pytest.mark.asyncio +async def test_close_continues_when_awaiter_is_cancelled(tmp_path): + client = _client( + tmp_path, + """ + import time + msg = json.loads(sys.stdin.readline()) + send({"jsonrpc": "2.0", "id": msg["id"], "result": {"protocol": "epp/1"}}) + time.sleep(30) + """, + ) + await client.start(INIT) + try: + wait = asyncio.create_task(client.close()) + await asyncio.sleep(0) + wait.cancel() + with pytest.raises(asyncio.CancelledError): + await wait + finally: + await asyncio.wait_for(client.close(), 10) + assert client._proc is not None and client._proc.returncode is not None + + @pytest.mark.asyncio async def test_missing_executable(tmp_path): client = EppClient("t", [str(tmp_path / "nope")], cwd=tmp_path, env=scrubbed_env(tmp_path)) diff --git a/docs/en/guide/provider-runtime.md b/docs/en/guide/provider-runtime.md new file mode 100644 index 00000000..3e7cd089 --- /dev/null +++ b/docs/en/guide/provider-runtime.md @@ -0,0 +1,29 @@ +# Prepare a Provider runtime in Python + +Use `agent_sandbox.providers.ProviderClient` from the Python SDK source to bind a Provider and a target at application startup. A compatible Python implementation supplied by the application takes priority. Otherwise the client can fetch an approved standalone EPP implementation and its runtime. The SDK import and direct HTTP clients require no runtime preparation. + +## OpenSandbox on Linux x86-64 with glibc + +The [example lock](../../../examples/providers/locked-opensandbox/provider.lock.json) pins the Provider and Node.js archives, including their URLs, SHA-256 digests and byte lengths. Use a lock obtained through a distribution channel you trust. The OpenSandbox server must be reachable and able to start the selected image. + +- Set `OPENSANDBOX_BASE_URL` to the OpenSandbox server URL. +- Set `OPENSANDBOX_API_KEY` if that server requires authentication. The key is sent to the Provider after local artifact verification. +- Optionally set `OPENSANDBOX_TEST_IMAGE` to an image the server can run. + +The [example program](../../../examples/providers/locked-opensandbox/run.py) downloads the pinned assets, creates a sandbox, runs a command, checks file round-tripping, deletes the sandbox and confirms absence after a second preparation from the cache. + +```bash +python examples/providers/locked-opensandbox/run.py +``` + +In an application, call `await ProviderClient.prepare(lock, config, cache_dir=path, download=True)` during a stage where network access is available. Reuse a private cache whose path and parent directories are controlled by the application operator. For offline preparation use the same cache and the default `download=False`. Cache entries are verified again on every preparation. If a cached digest fails verification, replace that cache entry using an approved copy or prepare into a fresh private cache. + +## Use an installed Python Provider + +Pass a trusted `Provider` instance as `native=`. Its ID and version must match `ProviderLock`. Declare the features you need using `required_features`. The SDK uses the compatible native implementation or selects an approved standalone entry for the host and feature set. Among standalone entries, Python is preferred, then the smallest numeric priority. You can supply a native-only lock without runtime entries. Install the Python implementation using your normal environment management. + +`ProviderClient` provides `create(SandboxConfig(...))`, `connect`, `list`, `get`, `set_timeout` and `delete`. A client belongs to the event loop that prepared it. Close individual sandbox handles and close the client when finished. Call `delete` for owned sandboxes to release remote resources. `ProviderClient.close()` releases local resources. + +Standalone preparation supports Linux glibc artifacts. Packages must provide a standalone EPP/1 entry. The example also requires a glibc version supported by the pinned Node distribution. Catalog installation and existing `ProviderSandbox.create(provider=...)` retain their own setup behavior. [Node.js platform requirements](https://github.com/nodejs/node/blob/v22.22.2/BUILDING.md) + +If an operation loses its response after dispatch, inspect the returned error before retrying. A create error with `outcome == "unknown_outcome"` needs reconciliation. The optional `on_created` callback receives the ID as soon as the Provider returns it. Drain ongoing operations before closing a client. diff --git a/docs/en/guide/providers.md b/docs/en/guide/providers.md index c5824ba0..178484dc 100644 --- a/docs/en/guide/providers.md +++ b/docs/en/guide/providers.md @@ -1,5 +1,7 @@ # Providers +For an explicitly bound Python client or on-demand standalone EPP runtime, see [Prepare a Provider runtime](provider-runtime.md). + Workflow support uses exact consumer operations; see [template workflows](template-workflows.md). This guide describes asynchronous `ProviderSandbox` provider extensions. Root `Sandbox` and `AsyncSandbox` follow the pinned standard migration contract; see [Migrate from E2B](migrate-from-e2b.md). diff --git a/docs/zh/guide/provider-runtime.md b/docs/zh/guide/provider-runtime.md new file mode 100644 index 00000000..1664e0be --- /dev/null +++ b/docs/zh/guide/provider-runtime.md @@ -0,0 +1,29 @@ +# 在 Python 中准备 Provider 运行时 + +使用 Python SDK 源码中的 `agent_sandbox.providers.ProviderClient`,在应用启动阶段绑定 Provider 和服务目标。应用传入兼容的 Python 实现时优先使用它,否则可以获取已确认的独立 EPP 实现及其运行时。导入 SDK 和直接调用业务 HTTP API 均无需准备 Provider 运行时。 + +## 在 Linux x86-64 glibc 上使用 OpenSandbox + +[示例锁文件](../../../examples/providers/locked-opensandbox/provider.lock.json)固定了 Provider 和 Node.js 制品的地址、SHA-256 与字节长度。通过你信任的渠道取得锁文件。OpenSandbox 服务需要可以访问,并能够启动选定的镜像。 + +- 将 `OPENSANDBOX_BASE_URL` 设置为 OpenSandbox 服务地址。 +- 服务启用鉴权时,设置该服务的 `OPENSANDBOX_API_KEY`。本机制品校验通过后,SDK 才把 Key 交给 Provider。 +- 可通过 `OPENSANDBOX_TEST_IMAGE` 指定该服务可运行的镜像。 + +[示例程序](../../../examples/providers/locked-opensandbox/run.py)下载固定制品、创建 Sandbox、运行命令、验证文件读写、删除 Sandbox,再从缓存准备一次并确认实例已删除。 + +```bash +python examples/providers/locked-opensandbox/run.py +``` + +在应用能够联网的准备阶段调用 `await ProviderClient.prepare(lock, config, cache_dir=path, download=True)`。使用由应用操作者管理路径及父目录的私有缓存。离线准备复用该缓存并使用默认的 `download=False`。每次准备都重新验证缓存制品。缓存校验失败时,可以用已确认的副本替换对应条目,或换一个私有缓存重新准备。 + +## 使用已安装的 Python Provider + +通过 `native=` 传入受信的 `Provider` 实例。实现的 ID、版本须与 `ProviderLock` 一致。用 `required_features` 声明所需能力。SDK 优先使用兼容的 Python 实现,否则选择匹配宿主和能力的已确认独立实现。在独立实现中优先选择 Python,然后选择数值最小的优先级。只用本地 Python 时,锁文件可以省略运行时条目。Python 实现沿用应用的依赖安装方式。 + +`ProviderClient` 提供 `create(SandboxConfig(...))`、`connect`、`list`、`get`、`set_timeout` 和 `delete`。在准备客户端的事件循环中使用它。使用结束后关闭各 Sandbox 句柄,再关闭客户端。需要释放自己创建的远端 Sandbox 时调用 `delete`。`ProviderClient.close()` 负责关闭本地资源。 + +独立制品准备支持 Linux glibc。制品需要独立 EPP/1 入口。示例还要求宿主 glibc 版本满足所锁定的 Node 发行版。目录安装与现有 `ProviderSandbox.create(provider=...)` 继续使用各自的设置方式。[Node.js 平台要求](https://github.com/nodejs/node/blob/v22.22.2/BUILDING.md) + +操作提交后若丢失响应,应先查看返回错误。创建错误的 `outcome == "unknown_outcome"` 时须先核对远端状态。可选的 `on_created` 回调会在 Provider 返回实例 ID 后立即收到该 ID。关闭客户端前应等待正在执行的操作结束。 diff --git a/docs/zh/guide/providers.md b/docs/zh/guide/providers.md index 600e5cb5..55405646 100644 --- a/docs/zh/guide/providers.md +++ b/docs/zh/guide/providers.md @@ -1,5 +1,7 @@ # 提供方(Providers) +需要显式绑定 Python 客户端或按需准备独立 EPP 运行时时,参见[准备 Provider 运行时](provider-runtime.md)。 + 工作流按具体消费入口的精确操作判断,见[模板工作流](template-workflows.md)。 本指南描述异步 `ProviderSandbox` 扩展;根级 `Sandbox` 和 `AsyncSandbox` 遵循固定版本的标准迁移契约,详见[从 E2B 迁移](migrate-from-e2b.md)。 diff --git a/e2e/test_bound_provider.py b/e2e/test_bound_provider.py new file mode 100644 index 00000000..f7ebe464 --- /dev/null +++ b/e2e/test_bound_provider.py @@ -0,0 +1,60 @@ +"""Exercise an explicit native Provider binding against Express.""" + +from __future__ import annotations + +import os +from typing import TYPE_CHECKING + +import e2e_helpers as H # noqa: N812 +import pytest + +from agent_sandbox.models.errors import SandboxNotFoundError +from agent_sandbox.models.sandbox import SandboxConfig +from agent_sandbox.providers import ProviderClient, ProviderLock +from agent_sandbox.providers.alicloud_express.provider import AlicloudExpressProvider +from agent_sandbox.transport.config import TransportConfig + +if TYPE_CHECKING: + from collections.abc import Callable, Coroutine + from typing import Any + + +def test_native_provider_target(run: Callable[[Coroutine[Any, Any, None]], None]) -> None: + if H.missing_env(("ABX_SANDBOX_BASE_URL", "ABX_SANDBOX_DOMAIN")): + pytest.skip("The bound test requires an explicit API URL and domain.") + run(_test_native_provider_target()) + + +async def _test_native_provider_target() -> None: + provider = AlicloudExpressProvider() + lock = ProviderLock(provider=provider.id, version=provider.version) + config = TransportConfig( + provider=provider.id, + sandbox_api_key=os.environ["ABX_SANDBOX_API_KEY"], + sandbox_base_url=os.environ["ABX_SANDBOX_BASE_URL"], + sandbox_domain=os.environ["ABX_SANDBOX_DOMAIN"], + ) + async with await ProviderClient.prepare( + lock, + config, + native=provider, + required_features=("sandbox.lifecycle", "exec.run", "files.rw"), + ) as client: + sandbox = await client.create( + SandboxConfig(template=H.OFFICIAL_BASE, timeout=180, metadata=H.tag_metadata("bound")) + ) + sandbox_id = sandbox.id + try: + result = await sandbox.commands.run("printf bound") + assert result.stdout == "bound" and result.exit_code == 0 + await sandbox.files.write("/tmp/provider-binding.txt", "checked") + assert await sandbox.files.read("/tmp/provider-binding.txt") == "checked" + assert (await client.get(sandbox_id)).sandbox_id == sandbox_id + finally: + try: + await client.delete(sandbox_id) + finally: + await sandbox.close() + + with pytest.raises(SandboxNotFoundError): + await client.get(sandbox_id) diff --git a/examples/providers/locked-opensandbox/provider.lock.json b/examples/providers/locked-opensandbox/provider.lock.json new file mode 100644 index 00000000..9d3d18f7 --- /dev/null +++ b/examples/providers/locked-opensandbox/provider.lock.json @@ -0,0 +1,34 @@ +{ + "provider": "opensandbox", + "version": "0.5.1", + "implementations": [ + { + "id": "node-epp", + "language": "node", + "platform": "linux-x86_64-glibc", + "priority": 0, + "features": [ + "sandbox.lifecycle", "sandbox.timeout", "sandbox.pause", "exec.run", + "exec.stream", "files.rw", "ports.url", "process.manage", "pty", "sessions" + ], + "required_options": ["base_url"], + "entrypoint": "provider.mjs", + "artifact": { + "url": "https://registry.agent-sandbox.cn/providers/opensandbox/opensandbox-0.5.1.tar.gz", + "sha256": "529f1a128900c8bcc0b1e2c47a9716e7d7783af5c674cc785c5275df7d61f2c8", + "size": 68665, + "root": "opensandbox" + }, + "runtime": { + "executable": "bin/node", + "license_file": "LICENSE", + "artifact": { + "url": "https://nodejs.org/dist/v22.22.2/node-v22.22.2-linux-x64.tar.xz", + "sha256": "88fd1ce767091fd8d4a99fdb2356e98c819f93f3b1f8663853a2dee9b438068a", + "size": 31065656, + "root": "node-v22.22.2-linux-x64" + } + } + } + ] +} diff --git a/examples/providers/locked-opensandbox/run.py b/examples/providers/locked-opensandbox/run.py new file mode 100644 index 00000000..61402b79 --- /dev/null +++ b/examples/providers/locked-opensandbox/run.py @@ -0,0 +1,65 @@ +"""Create and clean up an OpenSandbox sandbox with a locked Provider runtime.""" + +import asyncio +import os +import tempfile +import uuid +from pathlib import Path + +from agent_sandbox.models.errors import SandboxNotFoundError +from agent_sandbox.models.sandbox import SandboxConfig +from agent_sandbox.providers import ProviderClient, ProviderLock +from agent_sandbox.transport.config import TransportConfig + + +async def main() -> None: + lock = ProviderLock.model_validate_json( + Path(__file__).with_name("provider.lock.json").read_bytes() + ) + config = TransportConfig( + provider="opensandbox", + provider_options={ + "base_url": os.environ["OPENSANDBOX_BASE_URL"], + "api_key": os.environ.get("OPENSANDBOX_API_KEY"), + }, + ) + with tempfile.TemporaryDirectory(prefix="opensandbox-cache-") as cache: + cache_dir = Path(cache) + async with await ProviderClient.prepare( + lock, + config, + cache_dir=cache_dir, + download=True, + required_features=("sandbox.lifecycle", "exec.run", "files.rw"), + ) as client: + run_id = f"locked-provider-{uuid.uuid4().hex}" + sandbox = await client.create( + SandboxConfig( + template=os.environ.get("OPENSANDBOX_TEST_IMAGE", "base"), + metadata={"e2e": run_id}, + ) + ) + sandbox_id = sandbox.id + try: + result = await sandbox.commands.run("printf expected") + assert result.stdout == "expected" and result.exit_code == 0 + await sandbox.files.write("/tmp/locked-provider.txt", "verified") + assert await sandbox.files.read("/tmp/locked-provider.txt") == "verified" + assert (await client.get(sandbox_id)).sandbox_id == sandbox_id + finally: + try: + await client.delete(sandbox_id) + finally: + await sandbox.close() + + async with await ProviderClient.prepare(lock, config, cache_dir=cache_dir) as client: + try: + await client.get(sandbox_id) + except SandboxNotFoundError: + print("Command, files, offline preparation and cleanup confirmed.") + else: + raise RuntimeError("The sandbox still exists after deletion.") + + +if __name__ == "__main__": + asyncio.run(main())