Skip to content

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

15.0 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.
#
"""
Command service adapter implementation.

Implementation of Commands that adapts openapi-python-client generated CommandApi.
This adapter handles command execution within sandboxes, providing both
synchronous and streaming execution modes with proper session management.
"""

import logging
from datetime import timedelta

import httpx

from opensandbox._httpx import build_async_redirect_client_options
from opensandbox.adapters.converter.command_execution import (
    build_run_command_request_body as _build_run_command_request_body,
)
from opensandbox.adapters.converter.command_execution import (
    build_run_in_session_request_body as _build_run_in_session_request_body,
)
from opensandbox.adapters.converter.command_execution import (
    decode_sse_event_data as _decode_sse_event_data,
)
from opensandbox.adapters.converter.command_execution import (
    infer_foreground_exit_code as _infer_foreground_exit_code,
)
from opensandbox.adapters.converter.command_execution import (
    resolve_run_in_session_timeout as _resolve_run_in_session_timeout,
)
from opensandbox.adapters.converter.command_model_converter import to_command_status
from opensandbox.adapters.converter.env_entry import (
    build_set_env_command,
    raise_for_set_env_failure,
)
from opensandbox.adapters.converter.exception_converter import (
    ExceptionConverter,
)
from opensandbox.adapters.converter.execution_event_dispatcher import (
    ExecutionEventDispatcher,
)
from opensandbox.adapters.converter.response_handler import (
    build_api_exception_from_httpx,
    handle_api_error,
)
from opensandbox.adapters.sse import aiter_sse_events
from opensandbox.config import ConnectionConfig
from opensandbox.exceptions import InvalidArgumentException
from opensandbox.models.execd import (
    CommandLogs,
    CommandStatus,
    Execution,
    ExecutionHandlers,
    RunCommandOpts,
)
from opensandbox.models.sandboxes import SandboxEndpoint
from opensandbox.services.command import Commands
from opensandbox.transport import sse_timeout, streaming_transport

logger = logging.getLogger(__name__)


class CommandsAdapter(Commands):
    """
    Implementation of Commands that adapts openapi-python-client generated CommandApi.

    This adapter handles command execution within sandboxes, providing both
    synchronous and streaming execution modes with proper session management.

    The adapter uses direct httpx streaming for command execution to handle
    Server-Sent Events (SSE) properly, while using the generated API client
    for simpler operations like interrupt.
    """

    RUN_COMMAND_PATH = "/command"
    SESSION_PATH = "/session"
    RUN_IN_SESSION_PATH = "/session/{session_id}/run"

    def __init__(
        self,
        connection_config: ConnectionConfig,
        execd_endpoint: SandboxEndpoint,
    ) -> None:
        """
        Initialize the command service adapter.

        Args:
            connection_config: Connection configuration (shared transport, headers, timeouts)
            execd_endpoint: Endpoint for execd service
        """
        self.connection_config = connection_config
        self.execd_endpoint = execd_endpoint
        from opensandbox.api.execd import Client

        protocol = self.connection_config.protocol
        base_url = f"{protocol}://{self.execd_endpoint.endpoint}"
        timeout_seconds = self.connection_config.request_timeout.total_seconds()
        timeout = httpx.Timeout(timeout_seconds)

        headers = self.execd_endpoint.build_request_headers(self.connection_config)
        self._client = Client(
            base_url=base_url,
            timeout=timeout,
            follow_redirects=self.connection_config.follow_redirects,
        )

        # Inject httpx client (adapter-owned)
        self._httpx_client = httpx.AsyncClient(
            base_url=base_url,
            headers=headers,
            timeout=timeout,
            transport=self.connection_config.transport,
            **build_async_redirect_client_options(self.connection_config, base_url),
        )
        self._client.set_async_httpx_client(self._httpx_client)

        # SSE client: read timeout bounds the wait for response headers and the gap
        # between stream bytes (see sse_timeout); endpoint headers already in headers
        sse_headers = {
            **headers,
            "Accept": "text/event-stream",
            "Cache-Control": "no-cache",
        }
        # SSE bootstraps keep only the wake-timeout retry: a non-idempotent
        # status opt-in would cause duplicate execution on a resent SSE POST.
        self._sse_client = httpx.AsyncClient(
            headers=sse_headers,
            timeout=sse_timeout(timeout_seconds),
            transport=streaming_transport(self.connection_config.transport),
            **build_async_redirect_client_options(self.connection_config, base_url),
        )

    async def _get_client(self):
        """Return the client for execd API."""
        return self._client

    def _get_execd_url(self, path: str) -> str:
        """Build URL for execd endpoint."""
        protocol = self.connection_config.protocol
        return f"{protocol}://{self.execd_endpoint.endpoint}{path}"

    async def _get_sse_client(self) -> httpx.AsyncClient:
        """Return SSE client (bounded read timeout, see sse_timeout) for execd streaming."""
        return self._sse_client

    async def _execute_streaming_request(
        self,
        *,
        url: str,
        json_body: dict,
        handlers: ExecutionHandlers | None,
        infer_exit_code: bool,
        failure_message: str,
        is_background: bool = False,
    ) -> Execution:
        execution = Execution(
            id=None,
            execution_count=None,
            result=[],
            error=None,
        )
        client = await self._get_sse_client()

        async with client.stream("POST", url, json=json_body) as response:
            if response.status_code != 200:
                await response.aread()
                logger.error(
                    f"{failure_message}. Status: {response.status_code}, Body: {response.text}"
                )
                raise build_api_exception_from_httpx(response, failure_message)

            dispatcher = ExecutionEventDispatcher(execution, handlers)
            async for event in aiter_sse_events(response):
                event_node = _decode_sse_event_data(event.data)
                if event_node is None:
                    continue
                await dispatcher.dispatch(event_node)
                # Foreground responses drain to EOF (no break below): older
                # servers may emit trailing output after the completion event.
                if is_background and event_node.type == "execution_complete":
                    # Background commands are done once execution_complete
                    # arrives; do not wait for the chunked terminator, which
                    # older execd versions delay with a grace-period sleep and can
                    # be lost if the connection is closed early (#1528).
                    break

        if infer_exit_code:
            execution.exit_code = _infer_foreground_exit_code(execution)

        return execution

    async def run(
        self,
        command: str | list[str],
        *,
        opts: RunCommandOpts | None = None,
        handlers: ExecutionHandlers | None = None,
    ) -> Execution:
        """Execute shell text or native executable arguments in the sandbox.

        This method uses direct httpx streaming to handle SSE responses
        from the execd service.
        """
        if isinstance(command, str) and not command.strip():
            raise InvalidArgumentException("Command cannot be empty")

        try:
            opts = opts or RunCommandOpts()
            json_body = _build_run_command_request_body(command, opts).to_dict()
            url = self._get_execd_url(self.RUN_COMMAND_PATH)
            return await self._execute_streaming_request(
                url=url,
                json_body=json_body,
                handlers=handlers,
                infer_exit_code=not opts.background,
                failure_message="Failed to run command",
                is_background=opts.background,
            )

        except Exception as e:
            logger.error("Failed to run command", exc_info=e)
            raise ExceptionConverter.to_sandbox_exception(e) from e

    async def set_env(self, key: str, value: str) -> None:
        """Persist an environment variable for future commands and sessions."""
        command = build_set_env_command(key, value)
        try:
            execution = await self.run(command)
        except Exception as e:
            logger.error("Failed to run command", exc_info=e)
            raise ExceptionConverter.to_sandbox_exception(e) from e
        raise_for_set_env_failure(key, execution)

    async def interrupt(self, execution_id: str) -> None:
        """Interrupt a running command execution."""
        try:
            from opensandbox.api.execd.api.command import interrupt_command

            client = await self._get_client()
            response_obj = await interrupt_command.asyncio_detailed(
                client=client,
                id=execution_id,
            )

            handle_api_error(response_obj, "Interrupt command")

        except Exception as e:
            logger.error("Failed to interrupt command", exc_info=e)
            raise ExceptionConverter.to_sandbox_exception(e) from e

    async def get_command_status(self, execution_id: str) -> CommandStatus:
        """Get the current running status for a command."""
        try:
            from opensandbox.adapters.converter.response_handler import require_parsed
            from opensandbox.api.execd.api.command import get_command_status
            from opensandbox.api.execd.models import CommandStatusResponse

            client = await self._get_client()
            response_obj = await get_command_status.asyncio_detailed(
                client=client,
                id=execution_id,
            )

            handle_api_error(response_obj, "Get command status")
            parsed = require_parsed(
                response_obj, CommandStatusResponse, "Get command status"
            )
            return to_command_status(parsed)
        except Exception as e:
            logger.error("Failed to get command status", exc_info=e)
            raise ExceptionConverter.to_sandbox_exception(e) from e

    async def get_background_command_logs(
        self, execution_id: str, cursor: int | None = None
    ) -> CommandLogs:
        """Get background command logs (non-streamed)."""
        try:
            from opensandbox.adapters.converter.response_handler import require_parsed
            from opensandbox.api.execd.api.command import get_background_command_logs

            client = await self._get_client()
            from opensandbox.api.execd.types import UNSET

            response_obj = await get_background_command_logs.asyncio_detailed(
                client=client,
                id=execution_id,
                cursor=cursor if cursor is not None else UNSET,
            )

            handle_api_error(response_obj, "Get command logs")
            content = require_parsed(response_obj, str, "Get command logs")
            cursor_header = response_obj.headers.get("EXECD-COMMANDS-TAIL-CURSOR")
            next_cursor = None
            if cursor_header:
                try:
                    next_cursor = int(cursor_header)
                except ValueError:
                    next_cursor = None
            return CommandLogs(content=content, cursor=next_cursor)
        except Exception as e:
            logger.error("Failed to get command logs", exc_info=e)
            raise ExceptionConverter.to_sandbox_exception(e) from e

    async def create_session(self, *, working_directory: str | None = None) -> str:
        from opensandbox.adapters.converter.response_handler import require_parsed
        from opensandbox.api.execd.api.command import create_session
        from opensandbox.api.execd.models.create_session_request import (
            CreateSessionRequest,
        )
        from opensandbox.api.execd.models.create_session_response import (
            CreateSessionResponse,
        )
        from opensandbox.api.execd.types import UNSET

        body = (
            CreateSessionRequest(cwd=working_directory) if working_directory else UNSET
        )
        try:
            client = await self._get_client()
            response_obj = await create_session.asyncio_detailed(
                client=client, body=body
            )
            handle_api_error(response_obj, "create_session")
            parsed = require_parsed(
                response_obj, CreateSessionResponse, "create_session"
            )
            return parsed.session_id
        except Exception as e:
            raise ExceptionConverter.to_sandbox_exception(e) from e

    async def run_in_session(
        self,
        session_id: str,
        command: str,
        *,
        working_directory: str | None = None,
        timeout: timedelta | None = None,
        handlers: ExecutionHandlers | None = None,
    ) -> Execution:
        if not (session_id and session_id.strip()):
            raise InvalidArgumentException("session_id cannot be empty")
        if not (command and command.strip()):
            raise InvalidArgumentException("command cannot be empty")

        timeout_ms = _resolve_run_in_session_timeout(timeout)
        body = _build_run_in_session_request_body(
            command, working_directory, timeout_ms
        )
        url = self._get_execd_url(
            self.RUN_IN_SESSION_PATH.format(session_id=session_id)
        )
        try:
            return await self._execute_streaming_request(
                url=url,
                json_body=body.to_dict(),
                handlers=handlers,
                infer_exit_code=True,
                failure_message="run_in_session failed",
            )
        except Exception as e:
            raise ExceptionConverter.to_sandbox_exception(e) from e

    async def delete_session(self, session_id: str) -> None:
        if not (session_id and session_id.strip()):
            raise InvalidArgumentException("session_id cannot be empty")
        from opensandbox.api.execd.api.command import delete_session

        try:
            client = await self._get_client()
            response_obj = await delete_session.asyncio_detailed(
                client=client, session_id=session_id
            )
            handle_api_error(response_obj, "delete_session")
        except Exception as e:
            raise ExceptionConverter.to_sandbox_exception(e) from e