Skip to content

Secure, Fast, and Extensible Sandbox runtime for AI agents.

41.9 KB
Raw Blame
#
# Copyright 2025 The OpenSandbox Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Main Sandbox client implementation.
"""

import asyncio
import logging
import time
from collections.abc import Awaitable, Callable
from datetime import datetime, timedelta, timezone
from typing import Any, TypeVar

from opensandbox.adapters.factory import AdapterFactory
from opensandbox.config import ConnectionConfig
from opensandbox.constants import DEFAULT_EGRESS_PORT, DEFAULT_EXECD_PORT
from opensandbox.exceptions import (
    InvalidArgumentException,
    SandboxException,
    SandboxInternalException,
)
from opensandbox.internal.lifecycle_metrics import report_sandbox_create_metric
from opensandbox.internal.readiness import (
    ReadinessBudget,
    validate_polling_interval,
)
from opensandbox.models.diagnostics import DiagnosticContent, DiagnosticContext
from opensandbox.models.sandboxes import (
    CreateSnapshotRequest,
    CredentialProxyConfig,
    IdlePolicy,
    NetworkPolicy,
    NetworkRule,
    PlatformSpec,
    SandboxCreateResponse,
    SandboxEndpoint,
    SandboxImageSpec,
    SandboxInfo,
    SandboxLifecycle,
    SandboxMetrics,
    SandboxOrigin,
    SandboxRenewResponse,
    SnapshotInfo,
    Volume,
)
from opensandbox.services import (
    Commands,
    CredentialVault,
    Diagnostics,
    Egress,
    Filesystem,
    Health,
    IsolationService,
    Metrics,
    Sandboxes,
)

logger = logging.getLogger(__name__)

_T = TypeVar("_T")


async def _gather_fail_fast(*awaitables: Awaitable[_T]) -> list[_T]:
    """Await concurrent coroutines, cancelling the rest once one fails.

    ``asyncio.gather`` propagates the first exception without cancelling the
    sibling coroutines, so a permanently failing endpoint lookup (401/403 or a
    non-retryable 404) would leave the sibling endpoint's retry loop polling
    until the shared readiness deadline, issuing requests against a sandbox
    that ``create`` is about to clean up. Cancel and await the remaining
    tasks on the first failure (including cancellation of this task), then
    let the original exception propagate. Python 3.10 compatible; no
    ``asyncio.TaskGroup`` (3.11+).
    """
    tasks = [asyncio.ensure_future(awaitable) for awaitable in awaitables]
    try:
        return list(await asyncio.gather(*tasks))
    except BaseException:
        for task in tasks:
            if not task.done():
                task.cancel()
        # return_exceptions suppresses the siblings' CancelledError (and any
        # concurrent failure) so the original exception is the one re-raised.
        await asyncio.gather(*tasks, return_exceptions=True)
        raise


class Sandbox:
    """
    Main entrypoint for the Open Sandbox SDK providing secure, isolated execution environments.

    This class provides a comprehensive interface for interacting with containerized sandbox
    environments, combining lifecycle management with high-level operations for file system
    access, command execution, and real-time monitoring.

    Custom health checks and transports must not block the event loop. Readiness
    timeout requests cancellation, but custom code that suppresses it may continue.

    Key Features:

    - **Secure Isolation**: Complete Linux OS access in isolated containers
    - **File System Operations**: Create, read, update, delete files and directories
    - **Multi-language Execution**: Support for Python, Java, Bash, and other languages
    - **Real-time Command Execution**: Streaming output with timeout handling
    - **Resource Management**: CPU, memory, and storage constraints
    - **Lifecycle Management**: Create, pause, resume, terminate operations
    - **Health Monitoring**: Automatic readiness detection and status tracking

    Usage Example:

    ```python
    from opensandbox.models.sandboxes import SandboxImageSpec, SandboxImageAuth
    from opensandbox.models.execd import RunCommandOpts

    # Create with simple image (positional argument)
    sandbox = await Sandbox.create(
        "python:3.11",
        resource={"cpu": "1", "memory": "500Mi"},
        timeout=timedelta(minutes=30)
    )

    # Or with private registry auth
    sandbox = await Sandbox.create(
        SandboxImageSpec(
            "my-registry.com/my-image:latest",
            auth=SandboxImageAuth(username="user", password="pass")
        ),
    )

    # Use the sandbox
    await sandbox.files.write_file("script.py", "print('Hello World')")
    result = await sandbox.commands.run("python script.py")
    print(result.logs.stdout[0].text)  # Output: Hello World

    # Always terminate the remote sandbox and close local resources
    await sandbox.destroy()
    ```
    """

    def __init__(
        self,
        sandbox_id: str,
        sandbox_service: Sandboxes,
        filesystem_service: Filesystem,
        command_service: Commands,
        health_service: Health,
        metrics_service: Metrics,
        egress_service: Egress,
        connection_config: ConnectionConfig,
        diagnostics_service: Diagnostics | None = None,
        isolated_service: IsolationService | None = None,
        custom_health_check: Callable[["Sandbox"], Awaitable[bool]] | None = None,
        origin: str = SandboxOrigin.UNKNOWN,
    ) -> None:
        """
        Internal constructor for Sandbox. Use Sandbox.create() or Sandbox.connect() instead.
        """
        self.id = sandbox_id
        self._sandbox_service = sandbox_service
        self._filesystem_service = filesystem_service
        self._command_service = command_service
        self._health_service = health_service
        self._metrics_service = metrics_service
        self._egress_service = egress_service
        self._connection_config = connection_config
        self._diagnostics_service = (
            diagnostics_service
            or AdapterFactory(connection_config).create_diagnostics_service()
        )
        self._custom_health_check = custom_health_check
        self._isolated_service = isolated_service
        self._origin = origin

    @property
    def origin(self) -> str:
        """Origin of this sandbox (see :class:`SandboxOrigin`).

        ``template`` when the sandbox runs on a fsb golden-image template:
        set locally by ``create_from_template``, and reported by the
        server's ``OPEN-SANDBOX-ORIGIN`` response header otherwise (also
        honored for snapshot restores, which boot the template's published
        artifact set). ``unknown`` for everything else.

        Template-backed sandboxes route egress policy operations through
        the lifecycle control plane
        (``/sandboxes/{sandboxId}/networkpolicy``) instead of the
        sandbox-side egress sidecar.
        """
        return self._origin

    @property
    def isolation(self) -> IsolationService:
        """Provides access to namespace-isolated session operations (OSEP-0013)."""
        if self._isolated_service is None:
            raise SandboxInternalException("isolated service not initialized")
        return self._isolated_service

    @property
    def files(self) -> Filesystem:
        """
        Provides access to file system operations within the sandbox.

        Allows writing, reading, listing, and deleting files and directories.
        """
        return self._filesystem_service

    def files_with_identity(self, uid: int, gid: int) -> Filesystem:
        """Return a separate filesystem client running as the given Linux UID/GID.

        Requires identity-aware Execd. Unsupported servers fail without falling
        back to the default identity. The existing files client is unchanged.
        """
        from opensandbox.adapters.filesystem_adapter import FilesystemAdapter

        if not isinstance(self._filesystem_service, FilesystemAdapter):
            raise NotImplementedError(
                "The selected filesystem adapter does not support execution identity"
            )
        return self._filesystem_service.with_identity(uid, gid)

    @property
    def commands(self) -> Commands:
        """
        Provides access to command execution operations.

        Allows running shell commands, capturing output, and managing processes.
        """
        return self._command_service

    @property
    def metrics(self) -> Metrics:
        """
        Provides access to sandbox metrics and monitoring.

        Allows retrieving resource usage statistics (CPU, memory) and other performance metrics.
        """
        return self._metrics_service

    @property
    def credential_vault(self) -> CredentialVault:
        """
        Provides access to sandbox-scoped Credential Vault operations.

        Sidecar-backed sandboxes write straight to the egress sidecar.
        Template-backed sandboxes route through the lifecycle server, which
        relays vault revisions to the egress-held vault (OSEP-0022): the ack
        is synchronous and values never appear on any read. A ``412`` patch
        failure means another writer won the revision — re-read and retry
        with the fresh ``expected_revision``.
        """
        return self._egress_service

    @property
    def diagnostics(self) -> Diagnostics:
        """
        Provides access to sandbox diagnostic log and event descriptors.
        """
        return self._diagnostics_service

    @property
    def connection_config(self) -> ConnectionConfig:
        """Provides access to the connection configuration (including shared transport)."""
        return self._connection_config

    async def get_info(self) -> SandboxInfo:
        """
        Get the current status of this sandbox.

        Returns:
            Current sandbox status including state and metadata

        Raises:
            SandboxException: if status cannot be retrieved
        """
        return await self._sandbox_service.get_sandbox_info(self.id)

    async def get_endpoint(self, port: int) -> SandboxEndpoint:
        """
        Get a specific network endpoint for this sandbox.

        Args:
            port: The port number to get the endpoint for

        Returns:
            Endpoint information including connection details

        Raises:
            SandboxException: if endpoint cannot be retrieved
        """
        return await self._sandbox_service.get_sandbox_endpoint(
            self.id, port, self.connection_config.use_server_proxy
        )

    async def get_signed_endpoint(self, port: int, expires: int) -> SandboxEndpoint:
        """
        Get a signed endpoint URL with an OSEP-0011 route token.

        Args:
            port: The port number to get the endpoint for
            expires: Unix epoch seconds for the signed route token expiry

        Returns:
            Endpoint information with a signed URL

        Raises:
            SandboxException: if endpoint cannot be retrieved
        """
        return await self._sandbox_service.get_signed_sandbox_endpoint(
            self.id, port, expires, self.connection_config.use_server_proxy
        )

    async def get_metrics(self) -> SandboxMetrics:
        """
        Get the current resource usage metrics for this sandbox.

        Returns:
            Current sandbox metrics including CPU, memory, and I/O statistics

        Raises:
            SandboxException: if metrics cannot be retrieved
        """
        return await self._metrics_service.get_metrics(self.id)

    async def get_diagnostic_context(self) -> DiagnosticContext:
        """Get the sandbox's runtime backend and diagnostic identifiers."""
        return await self._diagnostics_service.get_context(self.id)

    async def get_diagnostic_logs(self, scope: str) -> DiagnosticContent:
        """
        Get diagnostic log content for this sandbox.

        Args:
            scope: Required diagnostic scope such as "container", "lifecycle", or "all".
        """
        return await self._diagnostics_service.get_logs(self.id, scope)

    async def get_diagnostic_events(self, scope: str) -> DiagnosticContent:
        """
        Get diagnostic event content for this sandbox.

        Args:
            scope: Required diagnostic scope such as "runtime", "lifecycle", or "all".
        """
        return await self._diagnostics_service.get_events(self.id, scope)

    async def renew(self, timeout: timedelta) -> SandboxRenewResponse:
        """
        Set the sandbox expiration time.

        The new expiration time will be set to the current time plus the provided duration.
        This may shorten or extend the remaining lifetime. The creation-time
        server timeout limit does not apply.

        Args:
            timeout: Duration to add to the current time to set the new expiration

        Returns:
            Renew response including the new expiration time.

        Raises:
            SandboxException: if the operation fails
        """
        # Use timezone-aware UTC datetime to avoid cross-timezone ambiguity.
        new_expiration = datetime.now(timezone.utc) + timeout
        logger.info(
            f"Renewing sandbox {self.id} timeout, estimated expiration: {new_expiration}"
        )
        return await self._sandbox_service.renew_sandbox_expiration(
            self.id, new_expiration
        )

    async def patch_metadata(self, patch: dict[str, str | None]) -> SandboxInfo:
        """
        Patch sandbox metadata.

        String values add or replace keys; None deletes keys.
        """
        return await self._sandbox_service.patch_sandbox_metadata(self.id, patch)

    async def create_snapshot(self, name: str | None = None) -> SnapshotInfo:
        """Create a persistent snapshot from this sandbox."""
        return await self._sandbox_service.create_snapshot(
            self.id, CreateSnapshotRequest(name=name)
        )

    async def get_egress_policy(self) -> NetworkPolicy:
        """
        Get current egress policy for this sandbox.
        """
        return await self._egress_service.get_policy()

    async def patch_egress_rules(self, rules: list[NetworkRule]) -> None:
        """
        Patch egress rules for this sandbox using sidecar merge semantics.

        Rules in this patch payload take priority over existing rules with the
        same target. Existing rules for other targets remain unchanged. Within a
        single patch payload, the first rule for a target wins.

        This operation does not replace the entire policy and does not change
        the current defaultAction.
        """
        await self._egress_service.patch_rules(rules)

    async def delete_egress_rules(self, targets: list[str]) -> None:
        """
        Delete egress rules for this sandbox by target.

        Each entry is a FQDN or wildcard domain. Matching rules are removed
        from the currently enforced policy. Targets not present in the policy
        are silently ignored (idempotent). The current defaultAction is
        preserved.
        """
        await self._egress_service.delete_rules(targets)

    async def pause(self) -> None:
        """
        Pause the sandbox while preserving its state.

        The sandbox will transition to PAUSED state and can be resumed later.
        All running processes will be suspended.

        Raises:
            SandboxException: if pause operation fails
        """
        logger.info(f"Pausing sandbox: {self.id}")
        self._sandbox_service.invalidate_endpoint_cache(self.id)
        await self._sandbox_service.pause_sandbox(self.id)

    async def kill(self) -> None:
        """
        Request irreversible termination of the remote sandbox. Returns when
        deletion is accepted; runtime cleanup may continue afterward.

        Note: This method does NOT close the local resources. Use close() or
        async context manager to clean up local resources.

        Raises:
            SandboxException: if termination fails
        """
        logger.info(f"Killing sandbox: {self.id}")
        self._sandbox_service.invalidate_endpoint_cache(self.id)
        await self._sandbox_service.kill_sandbox(self.id)

    async def close(self) -> None:
        """
        Close local resources associated with this sandbox.

        This method closes HTTP client resources and other local resources.
        It does NOT terminate the remote sandbox instance. Call kill() first
        if you want to terminate the remote sandbox.

        Note: This method logs errors but does not raise exceptions to avoid
        issues in context manager cleanup.
        """
        try:
            await self._connection_config.close_transport_if_owned()
            logger.debug(f"Closed resources for sandbox {self.id}")
        except Exception as e:
            logger.warning(
                f"Error closing resources for sandbox {self.id}: {e}", exc_info=True
            )

    async def destroy(self) -> None:
        """
        Terminate the remote sandbox and close local resources.

        Local resources are always closed, even if terminating the remote sandbox
        fails. Any termination error is re-raised after local cleanup completes.

        Raises:
            SandboxException: if termination fails
        """
        try:
            await self.kill()
        finally:
            await self.close()

    async def is_healthy(self) -> bool:
        """
        Check if the sandbox is healthy and responsive.

        Returns:
            True if sandbox is healthy, False otherwise
        """
        if self._custom_health_check:
            return await self._custom_health_check(self)
        return await self._ping()

    async def _ping(self) -> bool:
        """Check if the sandbox is alive."""
        try:
            return await self._health_service.ping(self.id)
        except Exception:
            return False

    async def _probe_health(self) -> bool:
        """Probe readiness without hiding authentication failures."""
        if self._custom_health_check:
            return await self._custom_health_check(self)
        return await self._health_service.ping(self.id)

    async def check_ready(
        self,
        timeout: timedelta,
        polling_interval: timedelta,
    ) -> None:
        """
        Wait for the sandbox to pass health checks with polling.

        Args:
            timeout: Maximum time to wait for health check to pass
            polling_interval: Time between health check attempts

        Raises:
            SandboxReadyTimeoutException: if health check doesn't pass within timeout
            SandboxException: if health check fails
        """
        await self._check_ready(ReadinessBudget(timeout, polling_interval))

    async def _check_ready(self, budget: ReadinessBudget) -> None:
        context = (
            f"ConnectionConfig(domain={self.connection_config.get_domain()}, "
            f"use_server_proxy={self.connection_config.use_server_proxy})"
        )
        # Fast-fail on 401/403 applies only to the built-in /ping probe: a custom
        # health_check may legitimately poll an app whose authorization becomes
        # available asynchronously, so it keeps the retry-until-deadline behavior.
        await budget.health(
            self._probe_health,
            context,
            auth_fail_fast=self._custom_health_check is None,
        )

    @classmethod
    async def create(
        cls,
        image: SandboxImageSpec | str | None = None,
        *,
        snapshot_id: str | None = None,
        timeout: timedelta | None = timedelta(minutes=10),
        ready_timeout: timedelta = timedelta(seconds=30),
        env: dict[str, str] | None = None,
        metadata: dict[str, str] | None = None,
        resource: dict[str, str] | None = None,
        resource_requests: dict[str, str] | None = None,
        platform: PlatformSpec | None = None,
        network_policy: NetworkPolicy | None = None,
        credential_proxy: CredentialProxyConfig | None = None,
        extensions: dict[str, str] | None = None,
        secure_access: bool = False,
        entrypoint: list[str] | None = None,
        volumes: list[Volume] | None = None,
        connection_config: ConnectionConfig | None = None,
        health_check: Callable[["Sandbox"], Awaitable[bool]] | None = None,
        health_check_polling_interval: timedelta = timedelta(milliseconds=200),
        skip_health_check: bool = False,
        lifecycle: SandboxLifecycle | None = None,
    ) -> "Sandbox":
        """
        Create a new sandbox instance with the specified configuration.

        Args:
            image: Container image specification including image reference and optional auth
            timeout: Maximum sandbox lifetime. Pass None to require explicit cleanup.
            ready_timeout: Total budget for endpoint publication and health checks.
            env: Environment variables for the sandbox
            metadata: Custom metadata for the sandbox
            resource: Resource limits (CPU, memory, etc.)
            network_policy: Optional outbound network policy (egress).
            credential_proxy: Optional Credential Vault proxy startup settings.
            extensions: Opaque extension parameters passed through to the server as-is.
                Prefer namespaced keys (e.g. ``storage.id``).
            secure_access: Whether to enable secured access for sandbox endpoints.
            entrypoint: Command to run as entrypoint
            volumes: Optional list of volume mounts for persistent storage.
                Each volume specifies a backend (host path, PVC, or OSSFS) and mount configuration.
            connection_config: Connection configuration
            health_check: Custom async health check function
            health_check_polling_interval: Polling interval used while waiting for endpoint publication and readiness/health.
            skip_health_check: Skip health checks; endpoint publication is still awaited.
            lifecycle: Optional pre-start and periodic lifecycle hooks.

        Returns:
            Fully configured and ready Sandbox instance

        Raises:
            SandboxException: if sandbox creation or initialization fails
        """
        if (image is None) == (snapshot_id is None):
            raise InvalidArgumentException(
                "Exactly one of image or snapshot_id must be specified"
            )
        if not skip_health_check:
            validate_polling_interval(health_check_polling_interval)

        config = (connection_config or ConnectionConfig()).with_transport_if_missing()
        entrypoint = entrypoint or ["tail", "-f", "/dev/null"]
        env = env or {}
        metadata = metadata or {}
        resource = resource or {"cpu": "1", "memory": "2Gi"}
        extensions = extensions or {}

        if isinstance(image, str):
            image = SandboxImageSpec(image=image)

        startup_source = image.image if image is not None else snapshot_id
        timeout_log = (
            "manual-cleanup" if timeout is None else f"{timeout.total_seconds()}s"
        )
        logger.info(
            f"Creating sandbox with startup source: {startup_source} (timeout: {timeout_log})"
        )

        return await cls._launch(
            config=config,
            startup_source=startup_source,
            timeout=timeout,
            ready_timeout=ready_timeout,
            health_check=health_check,
            health_check_polling_interval=health_check_polling_interval,
            skip_health_check=skip_health_check,
            create_call=lambda service: service.create_sandbox(
                spec=image,
                entrypoint=entrypoint,
                env=env,
                metadata=metadata,
                timeout=timeout,
                resource=resource,
                network_policy=network_policy,
                credential_proxy=credential_proxy,
                extensions=extensions,
                volumes=volumes,
                platform=platform,
                secure_access=secure_access,
                snapshot_id=snapshot_id,
                resource_requests=resource_requests,
                lifecycle=lifecycle,
            ),
        )

    @classmethod
    async def create_from_template(
        cls,
        template_id: str,
        *,
        timeout: timedelta,
        ready_timeout: timedelta = timedelta(seconds=30),
        metadata: dict[str, str] | None = None,
        network_policy: NetworkPolicy | None = None,
        extensions: dict[str, str] | None = None,
        idle_policy: IdlePolicy | None = None,
        connection_config: ConnectionConfig | None = None,
        health_check: Callable[["Sandbox"], Awaitable[bool]] | None = None,
        health_check_polling_interval: timedelta = timedelta(milliseconds=200),
        skip_health_check: bool = False,
    ) -> "Sandbox":
        """
        Create a new sandbox from a ``Succeeded`` fsb template.

        Template mode fixes the workload shape on the server: the entrypoint,
        env, resources, volumes, platform and lifecycle hooks of the sandbox come
        from the template's golden image and cannot be overridden here. Only
        metadata, network policy, extensions and the control-plane
        ``idle_policy`` (OSEP-0024 ``lifecycle.idlePolicy``) may accompany the
        template id, and the timeout is required.

        Args:
            template_id: ID of a ``Succeeded`` fsb template (see
                ``SandboxManager.create_template``)
            timeout: Maximum sandbox lifetime (required in template mode)
            ready_timeout: Total budget for endpoint publication and health checks.
            metadata: Custom metadata for the sandbox
            network_policy: Optional outbound network policy (egress).
            extensions: Opaque extension parameters passed through to the server as-is.
                Prefer namespaced keys (e.g. ``storage.id``).
            idle_policy: Optional idle behavior (OSEP-0024, fast-sandbox only).
            connection_config: Connection configuration
            health_check: Custom async health check function
            health_check_polling_interval: Polling interval used while waiting for endpoint publication and readiness/health.
            skip_health_check: Skip health checks; endpoint publication is still awaited.

        Returns:
            Fully configured and ready Sandbox instance

        Raises:
            InvalidArgumentException: if template_id is blank
            SandboxException: if sandbox creation or initialization fails
        """
        if not template_id or not template_id.strip():
            raise InvalidArgumentException("Template ID must be specified")
        if not skip_health_check:
            validate_polling_interval(health_check_polling_interval)

        config = (connection_config or ConnectionConfig()).with_transport_if_missing()
        logger.info(
            f"Creating sandbox from template: {template_id} "
            f"(timeout: {timeout.total_seconds()}s)"
        )

        return await cls._launch(
            config=config,
            startup_source=f"template:{template_id}",
            timeout=timeout,
            ready_timeout=ready_timeout,
            health_check=health_check,
            health_check_polling_interval=health_check_polling_interval,
            skip_health_check=skip_health_check,
            create_call=lambda service: service.create_sandbox_from_template(
                template_id=template_id,
                timeout=timeout,
                metadata=metadata,
                network_policy=network_policy,
                extensions=extensions,
                idle_policy=idle_policy,
            ),
            origin=SandboxOrigin.TEMPLATE,
        )

    @classmethod
    async def _launch(
        cls,
        *,
        config: ConnectionConfig,
        startup_source: str | None,
        timeout: timedelta | None,
        ready_timeout: timedelta,
        health_check: Callable[["Sandbox"], Awaitable[bool]] | None,
        health_check_polling_interval: timedelta,
        skip_health_check: bool,
        create_call: Callable[[Sandboxes], Awaitable[SandboxCreateResponse]],
        origin: str = SandboxOrigin.UNKNOWN,
    ) -> "Sandbox":
        """Shared create flow: create remote sandbox, gather endpoints, attach, verify readiness."""
        factory = AdapterFactory(config)
        sandbox_id: str | None = None
        sandbox_service: Sandboxes | None = None
        create_started = time.monotonic()

        try:
            sandbox_service = factory.create_sandbox_service()
            response = await create_call(sandbox_service)
            sandbox_id = response.id

            budget = ReadinessBudget(ready_timeout, health_check_polling_interval)
            if origin == SandboxOrigin.TEMPLATE:
                # Template-backed (fsb) sandboxes have no sandbox-side egress
                # sidecar: policy operations go through the lifecycle control
                # plane.
                execd_endpoint = await budget.endpoint(
                    lambda: sandbox_service.get_sandbox_endpoint(
                        response.id, DEFAULT_EXECD_PORT, config.use_server_proxy
                    )
                )
                egress_service = factory.create_network_policy_service(response.id)
            else:
                execd_endpoint, egress_endpoint = await _gather_fail_fast(
                    budget.endpoint(lambda: sandbox_service.get_sandbox_endpoint(
                        response.id, DEFAULT_EXECD_PORT, config.use_server_proxy
                    )),
                    budget.endpoint(lambda: sandbox_service.get_sandbox_endpoint(
                        response.id, DEFAULT_EGRESS_PORT, config.use_server_proxy
                    )),
                )
                # The server is authoritative about the runtime backing: for
                # fsb- prefixed sandboxes it reports `template` even when the
                # create used a snapshotId (a restore boots the template's
                # published artifact set). Such sandboxes have no sidecar,
                # so the egress service is swapped for the control-plane
                # adapter and the fetched sidecar endpoint goes unused.
                origin = execd_endpoint.origin or origin
                if origin == SandboxOrigin.TEMPLATE:
                    logger.info(
                        "server reported origin=template for %s; routing "
                        "egress policy through the lifecycle control plane",
                        response.id,
                    )
                    egress_service = factory.create_network_policy_service(
                        response.id
                    )
                else:
                    egress_service = factory.create_egress_service(egress_endpoint)

            sandbox = cls(
                sandbox_id=response.id,
                sandbox_service=sandbox_service,
                filesystem_service=factory.create_filesystem_service(execd_endpoint),
                command_service=factory.create_command_service(execd_endpoint),
                health_service=factory.create_health_service(execd_endpoint),
                metrics_service=factory.create_metrics_service(execd_endpoint),
                egress_service=egress_service,
                diagnostics_service=factory.create_diagnostics_service(),
                isolated_service=factory.create_isolated_session_service(
                    execd_endpoint
                ),
                connection_config=config,
                custom_health_check=health_check,
                origin=origin,
            )

            if not skip_health_check:
                await sandbox._check_ready(budget)
                logger.info(f"Sandbox {sandbox.id} is ready")
            else:
                logger.info(
                    f"Sandbox {sandbox.id} created (skip_health_check=true, sandbox may not be ready yet)"
                )

            report_sandbox_create_metric(
                config,
                sandbox_id=sandbox.id,
                image=startup_source,
                create_duration_ms=int((time.monotonic() - create_started) * 1000),
                success=True,
            )

            return sandbox
        except BaseException as e:
            report_sandbox_create_metric(
                config,
                sandbox_id=sandbox_id,
                image=startup_source,
                create_duration_ms=int((time.monotonic() - create_started) * 1000),
                success=False,
            )
            if sandbox_id and sandbox_service:
                try:
                    logger.warning(
                        f"Sandbox creation failed during initialization. Attempting to terminate zombie sandbox: {sandbox_id}"
                    )
                    await sandbox_service.kill_sandbox(sandbox_id)
                except Exception as cleanup_ex:
                    logger.error(
                        f"Failed to clean up sandbox {sandbox_id} after creation failure",
                        exc_info=cleanup_ex,
                    )

            await config.close_transport_if_owned()
            if isinstance(e, asyncio.CancelledError):
                raise
            if isinstance(e, SandboxException):
                raise
            if not isinstance(e, Exception):
                raise
            logger.error("Unexpected exception during sandbox creation", exc_info=e)
            raise SandboxInternalException(
                f"Internal exception when creating sandbox: {e}"
            ) from e

    @classmethod
    async def connect(
        cls,
        sandbox_id: str,
        connection_config: ConnectionConfig | None = None,
        health_check: Callable[["Sandbox"], Awaitable[bool]] | None = None,
        connect_timeout: timedelta = timedelta(seconds=30),
        health_check_polling_interval: timedelta = timedelta(milliseconds=200),
        skip_health_check: bool = False,
    ) -> "Sandbox":
        """
        Connect to an existing sandbox instance by ID.

        Args:
            sandbox_id: ID of the existing sandbox
            connection_config: Connection configuration
            health_check: Custom async health check function
            connect_timeout: Total budget for endpoint publication and health checks.
            health_check_polling_interval: Polling interval used while waiting for readiness/health.
            skip_health_check: Skip health checks; endpoint publication is still awaited.

        Returns:
            Connected Sandbox instance

        Raises:
            InvalidArgumentException: if required configuration is missing
            SandboxException: if sandbox connection fails
        """
        if not sandbox_id:
            raise InvalidArgumentException("Sandbox ID must be specified")
        sandbox_id = str(sandbox_id)

        config = (connection_config or ConnectionConfig()).with_transport_if_missing()

        logger.info(f"Connecting to sandbox: {sandbox_id}")
        factory = AdapterFactory(config)

        try:
            sandbox_service = factory.create_sandbox_service()
            budget = ReadinessBudget(connect_timeout, health_check_polling_interval)
            execd_endpoint = await budget.endpoint(lambda: sandbox_service.get_sandbox_endpoint(
                sandbox_id, DEFAULT_EXECD_PORT, config.use_server_proxy
            ))
            origin = execd_endpoint.origin or SandboxOrigin.UNKNOWN
            if origin == SandboxOrigin.TEMPLATE:
                # Template-backed (fsb) sandboxes have no sandbox-side egress
                # sidecar: policy operations go through the lifecycle control
                # plane, and the egress sidecar endpoint is never resolved.
                egress_service = factory.create_network_policy_service(sandbox_id)
            else:
                egress_endpoint = await budget.endpoint(lambda: sandbox_service.get_sandbox_endpoint(
                    sandbox_id, DEFAULT_EGRESS_PORT, config.use_server_proxy
                ))
                egress_service = factory.create_egress_service(egress_endpoint)

            sandbox = cls(
                sandbox_id=sandbox_id,
                sandbox_service=sandbox_service,
                filesystem_service=factory.create_filesystem_service(execd_endpoint),
                command_service=factory.create_command_service(execd_endpoint),
                health_service=factory.create_health_service(execd_endpoint),
                metrics_service=factory.create_metrics_service(execd_endpoint),
                egress_service=egress_service,
                diagnostics_service=factory.create_diagnostics_service(),
                isolated_service=factory.create_isolated_session_service(
                    execd_endpoint
                ),
                connection_config=config,
                custom_health_check=health_check,
                origin=origin,
            )

            if not skip_health_check:
                await sandbox._check_ready(budget)
            else:
                logger.info(
                    f"Connected to sandbox {sandbox_id} (skip_health_check=true, sandbox may not be ready yet)"
                )

            logger.info(f"Connected to sandbox {sandbox_id}")
            return sandbox
        except BaseException as e:
            await config.close_transport_if_owned()
            if not isinstance(e, Exception) or isinstance(e, SandboxException):
                raise
            logger.error("Unexpected exception during sandbox connection", exc_info=e)
            raise SandboxInternalException(f"Failed to connect to sandbox: {e}") from e

    @classmethod
    async def resume(
        cls,
        sandbox_id: str,
        connection_config: ConnectionConfig | None = None,
        health_check: Callable[["Sandbox"], Awaitable[bool]] | None = None,
        resume_timeout: timedelta = timedelta(seconds=30),
        health_check_polling_interval: timedelta = timedelta(milliseconds=200),
        skip_health_check: bool = False,
    ) -> "Sandbox":
        """
        Resume a paused sandbox by ID and return a new, usable Sandbox instance.

        This method performs the server-side resume operation, then re-resolves the execd endpoint
        (which may change across pause/resume on some backends), rebuilds service adapters, and
        optionally waits for readiness/health.

        Args:
            sandbox_id: ID of the paused sandbox to resume.
            connection_config: Connection configuration (shared transport, headers, timeouts).
            health_check: Optional custom async health check function (falls back to ping).
            resume_timeout: Total budget for endpoint publication and health checks after resuming.
            health_check_polling_interval: Polling interval used while waiting for readiness/health.
            skip_health_check: Skip health checks; endpoint publication is still awaited.
        """
        if not sandbox_id:
            raise InvalidArgumentException("Sandbox ID must be specified")
        sandbox_id = str(sandbox_id)
        validate_polling_interval(health_check_polling_interval)

        config = (connection_config or ConnectionConfig()).with_transport_if_missing()

        logger.info(f"Resuming sandbox: {sandbox_id}")
        factory = AdapterFactory(config)

        try:
            sandbox_service = factory.create_sandbox_service()
            await sandbox_service.resume_sandbox(sandbox_id)

            budget = ReadinessBudget(resume_timeout, health_check_polling_interval)
            execd_endpoint = await budget.endpoint(lambda: sandbox_service.get_sandbox_endpoint(
                sandbox_id, DEFAULT_EXECD_PORT, config.use_server_proxy
            ))
            origin = execd_endpoint.origin or SandboxOrigin.UNKNOWN
            if origin == SandboxOrigin.TEMPLATE:
                # Template-backed (fsb) sandboxes have no sandbox-side egress
                # sidecar: policy operations go through the lifecycle control
                # plane, and the egress sidecar endpoint is never resolved.
                egress_service = factory.create_network_policy_service(sandbox_id)
            else:
                egress_endpoint = await budget.endpoint(lambda: sandbox_service.get_sandbox_endpoint(
                    sandbox_id, DEFAULT_EGRESS_PORT, config.use_server_proxy
                ))
                egress_service = factory.create_egress_service(egress_endpoint)

            sandbox = cls(
                sandbox_id=sandbox_id,
                sandbox_service=sandbox_service,
                filesystem_service=factory.create_filesystem_service(execd_endpoint),
                command_service=factory.create_command_service(execd_endpoint),
                health_service=factory.create_health_service(execd_endpoint),
                metrics_service=factory.create_metrics_service(execd_endpoint),
                egress_service=egress_service,
                diagnostics_service=factory.create_diagnostics_service(),
                isolated_service=factory.create_isolated_session_service(
                    execd_endpoint
                ),
                connection_config=config,
                custom_health_check=health_check,
                origin=origin,
            )

            if not skip_health_check:
                await sandbox._check_ready(budget)
            else:
                logger.info(
                    f"Resumed sandbox {sandbox_id} (skip_health_check=true, sandbox may not be ready yet)"
                )

            return sandbox
        except BaseException as e:
            await config.close_transport_if_owned()
            if not isinstance(e, Exception) or isinstance(e, SandboxException):
                raise
            logger.error("Unexpected exception during sandbox resume", exc_info=e)
            raise SandboxInternalException(f"Failed to resume sandbox: {e}") from e

    async def __aenter__(self) -> "Sandbox":
        """Async context manager entry."""
        return self

    async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
        """Async context manager exit."""
        await self.close()