Skip to content

sprites_provider

Class info

Re-exported classes

Class Module Description
SpritesExecutionEnvironment exxec.sprites_provider.provider Executes code in a Sprites (Fly.io) cloud VM.
SpritesPtyManager exxec.sprites_provider.pty_manager PTY manager for Sprites cloud VM execution.

🛈 DocStrings

Sprites execution environment that runs code in Fly.io cloud VMs.

SpritesExecutionEnvironment

Bases: ExecutionEnvironment

Executes code in a Sprites (Fly.io) cloud VM.

Source code in src/exxec/sprites_provider/provider.py
class SpritesExecutionEnvironment(ExecutionEnvironment):
    """Executes code in a Sprites (Fly.io) cloud VM."""

    def __init__(
        self,
        lifespan_handler: AbstractAsyncContextManager[ServerInfo] | None = None,
        dependencies: list[str] | None = None,
        name: str | None = None,
        timeout: float = 300.0,
        default_command_timeout: float | None = None,
        keep_alive: bool = False,
        language: Language = "python",
        cwd: str | None = None,
        env_vars: dict[str, str] | None = None,
        inherit_env: bool = False,
        token: str | None = None,
        base_url: str = "https://api.sprites.dev",
        ram_mb: int | None = None,
        cpus: int | None = None,
        region: str | None = None,
        storage_gb: int | None = None,
    ) -> None:
        """Initialize Sprites environment.

        Args:
            lifespan_handler: Async context manager for tool server (optional)
            dependencies: List of packages to install via pip / npm
            name: Sprite name (auto-generated if None)
            timeout: Default command timeout in seconds
            default_command_timeout: Default timeout for command execution in seconds.
                If None, commands run without timeout unless explicitly specified.
            keep_alive: Keep sprite running after exiting context manager
            language: Programming language to use
            cwd: Working directory for the sprite
            env_vars: Environment variables to set for all executions
            inherit_env: If True, inherit environment variables from os.environ
            token: Sprites API token (or use SPRITES_TOKEN env var)
            base_url: Sprites API base URL
            ram_mb: RAM in MB for the sprite
            cpus: Number of CPUs for the sprite
            region: Preferred region for sprite creation
            storage_gb: Storage in GB for the sprite
        """
        super().__init__(
            lifespan_handler=lifespan_handler,
            dependencies=dependencies,
            cwd=cwd,
            env_vars=env_vars,
            inherit_env=inherit_env,
            default_command_timeout=default_command_timeout,
        )
        self.name = name
        self.timeout = timeout
        self.keep_alive = keep_alive
        self.language: Language = language
        self.token = token
        self.base_url = base_url
        self.ram_mb = ram_mb
        self.cpus = cpus
        self.region = region
        self.storage_gb = storage_gb
        self.sprites_client: SpritesClient | None = None
        self.sprite: Sprite | None = None
        self._auto_created = False
        # Sprites VMs run Linux
        self._os_type = "Linux"
        self._pty_manager: SpritesPtyManager | None = None

    def _ensure_initialized(self) -> Sprite:
        """Ensure the sprite has been created/connected."""
        if self.sprite is None:
            raise NotInitializedError("Sprite")
        return self.sprite

    async def __aenter__(self) -> Self:
        """Setup Sprites environment."""
        import os

        from sprites import SpritesClient
        from sprites.types import SpriteConfig

        await super().__aenter__()

        token = self.token or os.environ.get("SPRITES_TOKEN", "")
        self.sprites_client = SpritesClient(
            token=token,
            base_url=self.base_url,
            timeout=self.timeout,
        )

        config = SpriteConfig(
            ram_mb=self.ram_mb,
            cpus=self.cpus,
            region=self.region,
            storage_gb=self.storage_gb,
        )

        if self.name:
            # Try to connect to existing sprite, create if not found
            try:
                self.sprite = await _run_in_thread(self.sprites_client.get_sprite, self.name)
            except Exception:  # noqa: BLE001
                self.sprite = await _run_in_thread(
                    self.sprites_client.create_sprite, self.name, config
                )
                self._auto_created = True
        else:
            # Auto-generate name and create
            import uuid

            self.name = f"exxec-{uuid.uuid4().hex[:8]}"
            self.sprite = await _run_in_thread(self.sprites_client.create_sprite, self.name, config)
            self._auto_created = True

        # Install dependencies if specified
        if self.dependencies:
            match self.language:
                case "python":
                    await self._run_command_async("pip", "install", *self.dependencies)
                case "javascript" | "typescript":
                    await self._run_command_async("npm", "install", *self.dependencies)

        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: TracebackType | None,
    ) -> None:
        """Cleanup sprite."""
        if self.sprite and not self.keep_alive and self._auto_created:
            with contextlib.suppress(Exception):
                await _run_in_thread(self.sprite.delete)
        if self.sprites_client:
            with contextlib.suppress(Exception):
                await _run_in_thread(self.sprites_client.close)
        await super().__aexit__(exc_type, exc_val, exc_tb)

    async def _run_command_async(self, *args: str, **kwargs: Any) -> Any:
        """Run a sprite command in a thread."""
        from sprites.exec import run

        sprite = self._ensure_initialized()
        env = kwargs.pop("env", None) or self.get_env()
        cwd_val = kwargs.pop("cwd", None) or self.cwd
        timeout_val = kwargs.pop("timeout", None)

        def _do_run() -> Any:
            return run(
                sprite,
                *args,
                capture_output=True,
                timeout=timeout_val,
                env=env or {},
                cwd=cwd_val,
            )

        return await _run_in_thread(_do_run)

    def get_fs(self) -> SpritesFS:
        """Return a SpritesFS instance for the sprite."""
        from upathtools.filesystems import SpritesFS

        self._ensure_initialized()
        assert self.name is not None
        token = self.token or ""
        return SpritesFS(
            sprite_name=self.name,
            token=token,
            base_url=self.base_url,
        )

    def get_pty_manager(self) -> SpritesPtyManager:
        """Return a SpritesPtyManager for interactive terminal sessions."""
        if self._pty_manager is None:
            from exxec.sprites_provider.pty_manager import SpritesPtyManager

            sprite = self._ensure_initialized()
            self._pty_manager = SpritesPtyManager(sprite)
        return self._pty_manager

    async def execute(self, code: str) -> ExecutionResult:
        """Execute code in the Sprites VM."""
        sprite = self._ensure_initialized()
        start_time = time.time()
        try:
            wrapped_code = wrap_code(code, language=self.language)
            script_path = get_script_path(self.language)

            # Write code to file via filesystem API
            fs = sprite.filesystem("/")
            await _run_in_thread(lambda: fs.path(script_path).write_text(wrapped_code))

            # Execute the script
            cmd_parts = _get_execution_command(self.language, script_path)
            result = await self._run_command_async(*cmd_parts)

            stdout = result.stdout.decode("utf-8", errors="replace") if result.stdout else ""
            stderr = result.stderr.decode("utf-8", errors="replace") if result.stderr else ""

            execution_result, error_info = parse_output(stdout)
            if result.returncode == 0 and error_info is None:
                return ExecutionResult(
                    result=execution_result,
                    duration=time.time() - start_time,
                    success=True,
                    exit_code=result.returncode,
                    stdout=stdout,
                    stderr=stderr,
                )

            return ExecutionResult(
                result=None,
                duration=time.time() - start_time,
                success=False,
                exit_code=result.returncode,
                error=(error_info or {}).get("error", "Command execution failed"),
                error_type=(error_info or {}).get("type", "ExecutionError"),
                stdout=stdout,
                stderr=stderr,
            )

        except Exception as e:  # noqa: BLE001
            return ExecutionResult.failed(e, start_time)

    async def execute_command(
        self,
        command: str,
        *,
        timeout: float | None = None,
    ) -> ExecutionResult:
        """Execute a terminal command in the Sprites VM."""
        self._ensure_initialized()
        start_time = time.time()
        effective_timeout = timeout if timeout is not None else self.default_command_timeout
        try:
            result = await self._run_command_async(
                "bash",
                "-c",
                command,
                timeout=effective_timeout,
            )
            stdout = result.stdout.decode("utf-8", errors="replace") if result.stdout else ""
            stderr = result.stderr.decode("utf-8", errors="replace") if result.stderr else ""
            success = result.returncode == 0
            return ExecutionResult(
                result=stdout if success else None,
                duration=time.time() - start_time,
                success=success,
                error=stderr if not success else None,
                error_type="CommandError" if not success else None,
                stdout=stdout,
                stderr=stderr,
                exit_code=result.returncode,
            )
        except Exception as e:  # noqa: BLE001
            return ExecutionResult.failed(e, start_time)

    async def stream_code(self, code: str) -> AsyncIterator[ExecutionEvent]:
        """Execute code and stream events in the Sprites VM."""
        sprite = self._ensure_initialized()
        process_id = f"sprites_{id(sprite)}"
        wrapped_code = wrap_code(code, language=self.language)
        script_path = get_script_path(self.language)

        # Write code to file
        fs = sprite.filesystem("/")
        await _run_in_thread(lambda: fs.path(script_path).write_text(wrapped_code))

        cmd_parts = _get_execution_command(self.language, script_path)
        yield ProcessStartedEvent(process_id=process_id, command=f"execute({len(code)} chars)")
        try:
            result = await self._run_command_async(*cmd_parts)
            stdout = result.stdout.decode("utf-8", errors="replace") if result.stdout else ""
            stderr = result.stderr.decode("utf-8", errors="replace") if result.stderr else ""

            if stdout:
                for line in stdout.splitlines():
                    if line:
                        yield OutputEvent(process_id=process_id, data=line, stream="stdout")
            if stderr:
                for line in stderr.splitlines():
                    if line:
                        yield OutputEvent(process_id=process_id, data=line, stream="stderr")

            if result.returncode != 0:
                yield ProcessErrorEvent(
                    process_id=process_id,
                    error=stderr or f"Command exited with code {result.returncode}",
                    error_type="ExecutionError",
                    exit_code=result.returncode,
                )
            else:
                yield ProcessCompletedEvent(process_id=process_id, exit_code=0)

        except Exception as e:  # noqa: BLE001
            yield ProcessErrorEvent.failed(e, process_id=process_id)

    async def stream_command(
        self,
        command: str,
        *,
        timeout: float | None = None,
    ) -> AsyncIterator[ExecutionEvent]:
        """Execute a terminal command and stream events in the Sprites VM."""
        sprite = self._ensure_initialized()
        effective_timeout = timeout if timeout is not None else self.default_command_timeout
        process_id = f"sprites_cmd_{id(sprite)}"
        yield ProcessStartedEvent(process_id=process_id, command=command)
        try:
            result = await self._run_command_async(
                "bash",
                "-c",
                command,
                timeout=effective_timeout,
            )
            stdout = result.stdout.decode("utf-8", errors="replace") if result.stdout else ""
            stderr = result.stderr.decode("utf-8", errors="replace") if result.stderr else ""

            if stdout:
                for line in stdout.splitlines():
                    if line:
                        yield OutputEvent(process_id=process_id, data=line, stream="stdout")
            if stderr:
                for line in stderr.splitlines():
                    if line:
                        yield OutputEvent(process_id=process_id, data=line, stream="stderr")

            if result.returncode == 0:
                yield ProcessCompletedEvent(
                    process_id=process_id,
                    exit_code=result.returncode,
                )
            else:
                yield ProcessErrorEvent(
                    process_id=process_id,
                    error=f"Command exited with code {result.returncode}",
                    error_type="CommandError",
                    exit_code=result.returncode,
                )

        except Exception as e:  # noqa: BLE001
            yield ProcessErrorEvent.failed(e, process_id=process_id)

    async def set_file_content(self, path: str, content: str | bytes) -> None:
        """Set file content in the Sprites VM filesystem."""
        sprite = self._ensure_initialized()
        fs = sprite.filesystem("/")
        if isinstance(content, str):
            await _run_in_thread(lambda: fs.path(path).write_text(content))
        else:
            await _run_in_thread(lambda: fs.path(path).write_bytes(content))

    async def get_file_content(self, path: str) -> bytes:
        """Get file content from the Sprites VM filesystem."""
        sprite = self._ensure_initialized()
        fs = sprite.filesystem("/")
        return await _run_in_thread(lambda: fs.path(path).read_bytes())

__aenter__ async

__aenter__() -> Self

Setup Sprites environment.

Source code in src/exxec/sprites_provider/provider.py
async def __aenter__(self) -> Self:
    """Setup Sprites environment."""
    import os

    from sprites import SpritesClient
    from sprites.types import SpriteConfig

    await super().__aenter__()

    token = self.token or os.environ.get("SPRITES_TOKEN", "")
    self.sprites_client = SpritesClient(
        token=token,
        base_url=self.base_url,
        timeout=self.timeout,
    )

    config = SpriteConfig(
        ram_mb=self.ram_mb,
        cpus=self.cpus,
        region=self.region,
        storage_gb=self.storage_gb,
    )

    if self.name:
        # Try to connect to existing sprite, create if not found
        try:
            self.sprite = await _run_in_thread(self.sprites_client.get_sprite, self.name)
        except Exception:  # noqa: BLE001
            self.sprite = await _run_in_thread(
                self.sprites_client.create_sprite, self.name, config
            )
            self._auto_created = True
    else:
        # Auto-generate name and create
        import uuid

        self.name = f"exxec-{uuid.uuid4().hex[:8]}"
        self.sprite = await _run_in_thread(self.sprites_client.create_sprite, self.name, config)
        self._auto_created = True

    # Install dependencies if specified
    if self.dependencies:
        match self.language:
            case "python":
                await self._run_command_async("pip", "install", *self.dependencies)
            case "javascript" | "typescript":
                await self._run_command_async("npm", "install", *self.dependencies)

    return self

__aexit__ async

__aexit__(
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None

Cleanup sprite.

Source code in src/exxec/sprites_provider/provider.py
async def __aexit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: TracebackType | None,
) -> None:
    """Cleanup sprite."""
    if self.sprite and not self.keep_alive and self._auto_created:
        with contextlib.suppress(Exception):
            await _run_in_thread(self.sprite.delete)
    if self.sprites_client:
        with contextlib.suppress(Exception):
            await _run_in_thread(self.sprites_client.close)
    await super().__aexit__(exc_type, exc_val, exc_tb)

__init__

__init__(
    lifespan_handler: AbstractAsyncContextManager[ServerInfo] | None = None,
    dependencies: list[str] | None = None,
    name: str | None = None,
    timeout: float = 300.0,
    default_command_timeout: float | None = None,
    keep_alive: bool = False,
    language: Language = "python",
    cwd: str | None = None,
    env_vars: dict[str, str] | None = None,
    inherit_env: bool = False,
    token: str | None = None,
    base_url: str = "https://api.sprites.dev",
    ram_mb: int | None = None,
    cpus: int | None = None,
    region: str | None = None,
    storage_gb: int | None = None,
) -> None

Initialize Sprites environment.

Parameters:

Name Type Description Default
lifespan_handler AbstractAsyncContextManager[ServerInfo] | None

Async context manager for tool server (optional)

None
dependencies list[str] | None

List of packages to install via pip / npm

None
name str | None

Sprite name (auto-generated if None)

None
timeout float

Default command timeout in seconds

300.0
default_command_timeout float | None

Default timeout for command execution in seconds. If None, commands run without timeout unless explicitly specified.

None
keep_alive bool

Keep sprite running after exiting context manager

False
language Language

Programming language to use

'python'
cwd str | None

Working directory for the sprite

None
env_vars dict[str, str] | None

Environment variables to set for all executions

None
inherit_env bool

If True, inherit environment variables from os.environ

False
token str | None

Sprites API token (or use SPRITES_TOKEN env var)

None
base_url str

Sprites API base URL

'https://api.sprites.dev'
ram_mb int | None

RAM in MB for the sprite

None
cpus int | None

Number of CPUs for the sprite

None
region str | None

Preferred region for sprite creation

None
storage_gb int | None

Storage in GB for the sprite

None
Source code in src/exxec/sprites_provider/provider.py
def __init__(
    self,
    lifespan_handler: AbstractAsyncContextManager[ServerInfo] | None = None,
    dependencies: list[str] | None = None,
    name: str | None = None,
    timeout: float = 300.0,
    default_command_timeout: float | None = None,
    keep_alive: bool = False,
    language: Language = "python",
    cwd: str | None = None,
    env_vars: dict[str, str] | None = None,
    inherit_env: bool = False,
    token: str | None = None,
    base_url: str = "https://api.sprites.dev",
    ram_mb: int | None = None,
    cpus: int | None = None,
    region: str | None = None,
    storage_gb: int | None = None,
) -> None:
    """Initialize Sprites environment.

    Args:
        lifespan_handler: Async context manager for tool server (optional)
        dependencies: List of packages to install via pip / npm
        name: Sprite name (auto-generated if None)
        timeout: Default command timeout in seconds
        default_command_timeout: Default timeout for command execution in seconds.
            If None, commands run without timeout unless explicitly specified.
        keep_alive: Keep sprite running after exiting context manager
        language: Programming language to use
        cwd: Working directory for the sprite
        env_vars: Environment variables to set for all executions
        inherit_env: If True, inherit environment variables from os.environ
        token: Sprites API token (or use SPRITES_TOKEN env var)
        base_url: Sprites API base URL
        ram_mb: RAM in MB for the sprite
        cpus: Number of CPUs for the sprite
        region: Preferred region for sprite creation
        storage_gb: Storage in GB for the sprite
    """
    super().__init__(
        lifespan_handler=lifespan_handler,
        dependencies=dependencies,
        cwd=cwd,
        env_vars=env_vars,
        inherit_env=inherit_env,
        default_command_timeout=default_command_timeout,
    )
    self.name = name
    self.timeout = timeout
    self.keep_alive = keep_alive
    self.language: Language = language
    self.token = token
    self.base_url = base_url
    self.ram_mb = ram_mb
    self.cpus = cpus
    self.region = region
    self.storage_gb = storage_gb
    self.sprites_client: SpritesClient | None = None
    self.sprite: Sprite | None = None
    self._auto_created = False
    # Sprites VMs run Linux
    self._os_type = "Linux"
    self._pty_manager: SpritesPtyManager | None = None

execute async

execute(code: str) -> ExecutionResult

Execute code in the Sprites VM.

Source code in src/exxec/sprites_provider/provider.py
async def execute(self, code: str) -> ExecutionResult:
    """Execute code in the Sprites VM."""
    sprite = self._ensure_initialized()
    start_time = time.time()
    try:
        wrapped_code = wrap_code(code, language=self.language)
        script_path = get_script_path(self.language)

        # Write code to file via filesystem API
        fs = sprite.filesystem("/")
        await _run_in_thread(lambda: fs.path(script_path).write_text(wrapped_code))

        # Execute the script
        cmd_parts = _get_execution_command(self.language, script_path)
        result = await self._run_command_async(*cmd_parts)

        stdout = result.stdout.decode("utf-8", errors="replace") if result.stdout else ""
        stderr = result.stderr.decode("utf-8", errors="replace") if result.stderr else ""

        execution_result, error_info = parse_output(stdout)
        if result.returncode == 0 and error_info is None:
            return ExecutionResult(
                result=execution_result,
                duration=time.time() - start_time,
                success=True,
                exit_code=result.returncode,
                stdout=stdout,
                stderr=stderr,
            )

        return ExecutionResult(
            result=None,
            duration=time.time() - start_time,
            success=False,
            exit_code=result.returncode,
            error=(error_info or {}).get("error", "Command execution failed"),
            error_type=(error_info or {}).get("type", "ExecutionError"),
            stdout=stdout,
            stderr=stderr,
        )

    except Exception as e:  # noqa: BLE001
        return ExecutionResult.failed(e, start_time)

execute_command async

execute_command(command: str, *, timeout: float | None = None) -> ExecutionResult

Execute a terminal command in the Sprites VM.

Source code in src/exxec/sprites_provider/provider.py
async def execute_command(
    self,
    command: str,
    *,
    timeout: float | None = None,
) -> ExecutionResult:
    """Execute a terminal command in the Sprites VM."""
    self._ensure_initialized()
    start_time = time.time()
    effective_timeout = timeout if timeout is not None else self.default_command_timeout
    try:
        result = await self._run_command_async(
            "bash",
            "-c",
            command,
            timeout=effective_timeout,
        )
        stdout = result.stdout.decode("utf-8", errors="replace") if result.stdout else ""
        stderr = result.stderr.decode("utf-8", errors="replace") if result.stderr else ""
        success = result.returncode == 0
        return ExecutionResult(
            result=stdout if success else None,
            duration=time.time() - start_time,
            success=success,
            error=stderr if not success else None,
            error_type="CommandError" if not success else None,
            stdout=stdout,
            stderr=stderr,
            exit_code=result.returncode,
        )
    except Exception as e:  # noqa: BLE001
        return ExecutionResult.failed(e, start_time)

get_file_content async

get_file_content(path: str) -> bytes

Get file content from the Sprites VM filesystem.

Source code in src/exxec/sprites_provider/provider.py
async def get_file_content(self, path: str) -> bytes:
    """Get file content from the Sprites VM filesystem."""
    sprite = self._ensure_initialized()
    fs = sprite.filesystem("/")
    return await _run_in_thread(lambda: fs.path(path).read_bytes())

get_fs

get_fs() -> SpritesFS

Return a SpritesFS instance for the sprite.

Source code in src/exxec/sprites_provider/provider.py
def get_fs(self) -> SpritesFS:
    """Return a SpritesFS instance for the sprite."""
    from upathtools.filesystems import SpritesFS

    self._ensure_initialized()
    assert self.name is not None
    token = self.token or ""
    return SpritesFS(
        sprite_name=self.name,
        token=token,
        base_url=self.base_url,
    )

get_pty_manager

get_pty_manager() -> SpritesPtyManager

Return a SpritesPtyManager for interactive terminal sessions.

Source code in src/exxec/sprites_provider/provider.py
def get_pty_manager(self) -> SpritesPtyManager:
    """Return a SpritesPtyManager for interactive terminal sessions."""
    if self._pty_manager is None:
        from exxec.sprites_provider.pty_manager import SpritesPtyManager

        sprite = self._ensure_initialized()
        self._pty_manager = SpritesPtyManager(sprite)
    return self._pty_manager

set_file_content async

set_file_content(path: str, content: str | bytes) -> None

Set file content in the Sprites VM filesystem.

Source code in src/exxec/sprites_provider/provider.py
async def set_file_content(self, path: str, content: str | bytes) -> None:
    """Set file content in the Sprites VM filesystem."""
    sprite = self._ensure_initialized()
    fs = sprite.filesystem("/")
    if isinstance(content, str):
        await _run_in_thread(lambda: fs.path(path).write_text(content))
    else:
        await _run_in_thread(lambda: fs.path(path).write_bytes(content))

stream_code async

stream_code(code: str) -> AsyncIterator[ExecutionEvent]

Execute code and stream events in the Sprites VM.

Source code in src/exxec/sprites_provider/provider.py
async def stream_code(self, code: str) -> AsyncIterator[ExecutionEvent]:
    """Execute code and stream events in the Sprites VM."""
    sprite = self._ensure_initialized()
    process_id = f"sprites_{id(sprite)}"
    wrapped_code = wrap_code(code, language=self.language)
    script_path = get_script_path(self.language)

    # Write code to file
    fs = sprite.filesystem("/")
    await _run_in_thread(lambda: fs.path(script_path).write_text(wrapped_code))

    cmd_parts = _get_execution_command(self.language, script_path)
    yield ProcessStartedEvent(process_id=process_id, command=f"execute({len(code)} chars)")
    try:
        result = await self._run_command_async(*cmd_parts)
        stdout = result.stdout.decode("utf-8", errors="replace") if result.stdout else ""
        stderr = result.stderr.decode("utf-8", errors="replace") if result.stderr else ""

        if stdout:
            for line in stdout.splitlines():
                if line:
                    yield OutputEvent(process_id=process_id, data=line, stream="stdout")
        if stderr:
            for line in stderr.splitlines():
                if line:
                    yield OutputEvent(process_id=process_id, data=line, stream="stderr")

        if result.returncode != 0:
            yield ProcessErrorEvent(
                process_id=process_id,
                error=stderr or f"Command exited with code {result.returncode}",
                error_type="ExecutionError",
                exit_code=result.returncode,
            )
        else:
            yield ProcessCompletedEvent(process_id=process_id, exit_code=0)

    except Exception as e:  # noqa: BLE001
        yield ProcessErrorEvent.failed(e, process_id=process_id)

stream_command async

stream_command(command: str, *, timeout: float | None = None) -> AsyncIterator[ExecutionEvent]

Execute a terminal command and stream events in the Sprites VM.

Source code in src/exxec/sprites_provider/provider.py
async def stream_command(
    self,
    command: str,
    *,
    timeout: float | None = None,
) -> AsyncIterator[ExecutionEvent]:
    """Execute a terminal command and stream events in the Sprites VM."""
    sprite = self._ensure_initialized()
    effective_timeout = timeout if timeout is not None else self.default_command_timeout
    process_id = f"sprites_cmd_{id(sprite)}"
    yield ProcessStartedEvent(process_id=process_id, command=command)
    try:
        result = await self._run_command_async(
            "bash",
            "-c",
            command,
            timeout=effective_timeout,
        )
        stdout = result.stdout.decode("utf-8", errors="replace") if result.stdout else ""
        stderr = result.stderr.decode("utf-8", errors="replace") if result.stderr else ""

        if stdout:
            for line in stdout.splitlines():
                if line:
                    yield OutputEvent(process_id=process_id, data=line, stream="stdout")
        if stderr:
            for line in stderr.splitlines():
                if line:
                    yield OutputEvent(process_id=process_id, data=line, stream="stderr")

        if result.returncode == 0:
            yield ProcessCompletedEvent(
                process_id=process_id,
                exit_code=result.returncode,
            )
        else:
            yield ProcessErrorEvent(
                process_id=process_id,
                error=f"Command exited with code {result.returncode}",
                error_type="CommandError",
                exit_code=result.returncode,
            )

    except Exception as e:  # noqa: BLE001
        yield ProcessErrorEvent.failed(e, process_id=process_id)

SpritesPtyManager

Bases: BasePtyManager

PTY manager for Sprites cloud VM execution.

Uses Sprites' WebSocket command execution with TTY mode for interactive terminal sessions in cloud VMs.

Source code in src/exxec/sprites_provider/pty_manager.py
class SpritesPtyManager(BasePtyManager):
    """PTY manager for Sprites cloud VM execution.

    Uses Sprites' WebSocket command execution with TTY mode for
    interactive terminal sessions in cloud VMs.
    """

    def __init__(self, sprite: Sprite) -> None:
        """Initialize the Sprites PTY manager.

        Args:
            sprite: An active Sprite instance
        """
        super().__init__()
        self._sprite = sprite
        self._sprites_sessions: dict[str, SpritesPtySession] = {}

    async def _read_loop(self, session: SpritesPtySession) -> None:
        """Background task to wait for command completion and collect output."""
        try:
            ws_cmd = session.ws_cmd
            if ws_cmd is None:
                return
            await ws_cmd.wait()
            # Collect any remaining buffered output
            stdout = ws_cmd.get_stdout()
            if stdout:
                session._output_buffer.append(stdout)
                session._output_event.set()
            session.info.status = "exited"
        except Exception:  # noqa: BLE001
            session.info.status = "exited"

    async def create(
        self,
        size: PtySize | None = None,
        command: str | None = None,
        args: list[str] | None = None,
        cwd: str | None = None,
        env: dict[str, str] | None = None,
    ) -> PtyInfo:
        """Create a new PTY session in the Sprites VM.

        Args:
            size: Initial terminal size (defaults to 24x80)
            command: Shell command (defaults to /bin/bash)
            args: Arguments for the command
            cwd: Working directory
            env: Environment variables

        Returns:
            PtyInfo with session details
        """
        from sprites.exec import Cmd
        from sprites.websocket import WSCommand

        size = size or PtySize()
        command = command or "/bin/bash"
        args = args or []
        pty_id = self._generate_id()

        # Build the full command args list
        full_args = [command, *args]

        # Create a Cmd with TTY mode
        cmd = Cmd(
            sprite=self._sprite,
            args=full_args,
            cwd=cwd,
            env=env,
            tty=True,
            tty_rows=size.rows,
            tty_cols=size.cols,
        )

        # Create WSCommand and start it
        ws_cmd = WSCommand(cmd)

        # Set up output capture
        output_buffer: list[bytes] = []
        output_event = asyncio.Event()

        def on_text_message(data: bytes) -> None:
            output_buffer.append(data)
            output_event.set()

        ws_cmd.text_message_handler = on_text_message
        await ws_cmd.start()

        info = PtyInfo(
            id=pty_id,
            pid=0,  # Sprites doesn't expose the actual PID
            command=command,
            args=args,
            cwd=cwd or "/",
            size=size,
            status="running",
        )

        session = SpritesPtySession(
            info=info,
            sprite=self._sprite,
            ws_cmd=ws_cmd,
            _output_buffer=output_buffer,
            _output_event=output_event,
        )
        self._sessions[pty_id] = info
        self._sprites_sessions[pty_id] = session

        # Start background reader to detect completion
        session._reader_task = asyncio.create_task(self._read_loop(session))

        return info

    async def resize(self, pty_id: str, size: PtySize) -> None:
        """Resize a PTY session.

        Args:
            pty_id: The PTY session ID
            size: New terminal size

        Raises:
            KeyError: If PTY session not found
        """
        session = self._sprites_sessions.get(pty_id)
        if not session:
            msg = f"PTY session {pty_id} not found"
            raise KeyError(msg)

        if session.ws_cmd:
            await session.ws_cmd.resize(cols=size.cols, rows=size.rows)
        session.info.size = size

    async def write(self, pty_id: str, data: bytes) -> None:
        """Write data to a PTY's stdin.

        Args:
            pty_id: The PTY session ID
            data: Data to write

        Raises:
            KeyError: If PTY session not found
        """
        session = self._sprites_sessions.get(pty_id)
        if not session:
            msg = f"PTY session {pty_id} not found"
            raise KeyError(msg)

        if session.ws_cmd:
            await session.ws_cmd._write_stdin(data)

    async def read(self, pty_id: str, size: int = 4096) -> bytes:
        """Read data from a PTY's output buffer.

        Args:
            pty_id: The PTY session ID
            size: Maximum bytes to read

        Returns:
            Output data from the PTY

        Raises:
            KeyError: If PTY session not found
        """
        session = self._sprites_sessions.get(pty_id)
        if not session:
            msg = f"PTY session {pty_id} not found"
            raise KeyError(msg)

        # Also check the WSCommand's internal stdout buffer
        if session.ws_cmd:
            ws_stdout = session.ws_cmd.get_stdout()
            if ws_stdout:
                session._output_buffer.append(ws_stdout)
                session.ws_cmd._stdout_buffer.clear()

        if not session._output_buffer:
            try:
                await asyncio.wait_for(session._output_event.wait(), timeout=0.1)
            except TimeoutError:
                return b""

        if session._output_buffer:
            data = b"".join(session._output_buffer)
            session._output_buffer.clear()
            session._output_event.clear()
            return data[:size] if len(data) > size else data

        return b""

    async def stream(self, pty_id: str) -> AsyncIterator[bytes]:
        """Stream output from a PTY session.

        Args:
            pty_id: The PTY session ID

        Yields:
            Chunks of output data as they become available

        Raises:
            KeyError: If PTY session not found
        """
        session = self._sprites_sessions.get(pty_id)
        if not session:
            msg = f"PTY session {pty_id} not found"
            raise KeyError(msg)

        while session.info.status == "running":
            try:
                await asyncio.wait_for(session._output_event.wait(), timeout=0.5)
            except TimeoutError:
                continue

            if session._output_buffer:
                data = b"".join(session._output_buffer)
                session._output_buffer.clear()
                session._output_event.clear()
                yield data

    async def kill(self, pty_id: str) -> bool:
        """Kill a PTY session.

        Args:
            pty_id: The PTY session ID

        Returns:
            True if killed successfully, False if not found
        """
        session = self._sprites_sessions.get(pty_id)
        if not session:
            return False

        try:
            if session._reader_task and not session._reader_task.done():
                session._reader_task.cancel()
            if session.ws_cmd:
                await session.ws_cmd.close()
            session.info.status = "exited"
        except Exception:  # noqa: BLE001
            pass

        del self._sprites_sessions[pty_id]
        del self._sessions[pty_id]

        return True

    async def get_info(self, pty_id: str) -> PtyInfo | None:
        """Get information about a PTY session."""
        return self._sessions.get(pty_id)

__init__

__init__(sprite: Sprite) -> None

Initialize the Sprites PTY manager.

Parameters:

Name Type Description Default
sprite Sprite

An active Sprite instance

required
Source code in src/exxec/sprites_provider/pty_manager.py
def __init__(self, sprite: Sprite) -> None:
    """Initialize the Sprites PTY manager.

    Args:
        sprite: An active Sprite instance
    """
    super().__init__()
    self._sprite = sprite
    self._sprites_sessions: dict[str, SpritesPtySession] = {}

create async

create(
    size: PtySize | None = None,
    command: str | None = None,
    args: list[str] | None = None,
    cwd: str | None = None,
    env: dict[str, str] | None = None,
) -> PtyInfo

Create a new PTY session in the Sprites VM.

Parameters:

Name Type Description Default
size PtySize | None

Initial terminal size (defaults to 24x80)

None
command str | None

Shell command (defaults to /bin/bash)

None
args list[str] | None

Arguments for the command

None
cwd str | None

Working directory

None
env dict[str, str] | None

Environment variables

None

Returns:

Type Description
PtyInfo

PtyInfo with session details

Source code in src/exxec/sprites_provider/pty_manager.py
async def create(
    self,
    size: PtySize | None = None,
    command: str | None = None,
    args: list[str] | None = None,
    cwd: str | None = None,
    env: dict[str, str] | None = None,
) -> PtyInfo:
    """Create a new PTY session in the Sprites VM.

    Args:
        size: Initial terminal size (defaults to 24x80)
        command: Shell command (defaults to /bin/bash)
        args: Arguments for the command
        cwd: Working directory
        env: Environment variables

    Returns:
        PtyInfo with session details
    """
    from sprites.exec import Cmd
    from sprites.websocket import WSCommand

    size = size or PtySize()
    command = command or "/bin/bash"
    args = args or []
    pty_id = self._generate_id()

    # Build the full command args list
    full_args = [command, *args]

    # Create a Cmd with TTY mode
    cmd = Cmd(
        sprite=self._sprite,
        args=full_args,
        cwd=cwd,
        env=env,
        tty=True,
        tty_rows=size.rows,
        tty_cols=size.cols,
    )

    # Create WSCommand and start it
    ws_cmd = WSCommand(cmd)

    # Set up output capture
    output_buffer: list[bytes] = []
    output_event = asyncio.Event()

    def on_text_message(data: bytes) -> None:
        output_buffer.append(data)
        output_event.set()

    ws_cmd.text_message_handler = on_text_message
    await ws_cmd.start()

    info = PtyInfo(
        id=pty_id,
        pid=0,  # Sprites doesn't expose the actual PID
        command=command,
        args=args,
        cwd=cwd or "/",
        size=size,
        status="running",
    )

    session = SpritesPtySession(
        info=info,
        sprite=self._sprite,
        ws_cmd=ws_cmd,
        _output_buffer=output_buffer,
        _output_event=output_event,
    )
    self._sessions[pty_id] = info
    self._sprites_sessions[pty_id] = session

    # Start background reader to detect completion
    session._reader_task = asyncio.create_task(self._read_loop(session))

    return info

get_info async

get_info(pty_id: str) -> PtyInfo | None

Get information about a PTY session.

Source code in src/exxec/sprites_provider/pty_manager.py
async def get_info(self, pty_id: str) -> PtyInfo | None:
    """Get information about a PTY session."""
    return self._sessions.get(pty_id)

kill async

kill(pty_id: str) -> bool

Kill a PTY session.

Parameters:

Name Type Description Default
pty_id str

The PTY session ID

required

Returns:

Type Description
bool

True if killed successfully, False if not found

Source code in src/exxec/sprites_provider/pty_manager.py
async def kill(self, pty_id: str) -> bool:
    """Kill a PTY session.

    Args:
        pty_id: The PTY session ID

    Returns:
        True if killed successfully, False if not found
    """
    session = self._sprites_sessions.get(pty_id)
    if not session:
        return False

    try:
        if session._reader_task and not session._reader_task.done():
            session._reader_task.cancel()
        if session.ws_cmd:
            await session.ws_cmd.close()
        session.info.status = "exited"
    except Exception:  # noqa: BLE001
        pass

    del self._sprites_sessions[pty_id]
    del self._sessions[pty_id]

    return True

read async

read(pty_id: str, size: int = 4096) -> bytes

Read data from a PTY's output buffer.

Parameters:

Name Type Description Default
pty_id str

The PTY session ID

required
size int

Maximum bytes to read

4096

Returns:

Type Description
bytes

Output data from the PTY

Raises:

Type Description
KeyError

If PTY session not found

Source code in src/exxec/sprites_provider/pty_manager.py
async def read(self, pty_id: str, size: int = 4096) -> bytes:
    """Read data from a PTY's output buffer.

    Args:
        pty_id: The PTY session ID
        size: Maximum bytes to read

    Returns:
        Output data from the PTY

    Raises:
        KeyError: If PTY session not found
    """
    session = self._sprites_sessions.get(pty_id)
    if not session:
        msg = f"PTY session {pty_id} not found"
        raise KeyError(msg)

    # Also check the WSCommand's internal stdout buffer
    if session.ws_cmd:
        ws_stdout = session.ws_cmd.get_stdout()
        if ws_stdout:
            session._output_buffer.append(ws_stdout)
            session.ws_cmd._stdout_buffer.clear()

    if not session._output_buffer:
        try:
            await asyncio.wait_for(session._output_event.wait(), timeout=0.1)
        except TimeoutError:
            return b""

    if session._output_buffer:
        data = b"".join(session._output_buffer)
        session._output_buffer.clear()
        session._output_event.clear()
        return data[:size] if len(data) > size else data

    return b""

resize async

resize(pty_id: str, size: PtySize) -> None

Resize a PTY session.

Parameters:

Name Type Description Default
pty_id str

The PTY session ID

required
size PtySize

New terminal size

required

Raises:

Type Description
KeyError

If PTY session not found

Source code in src/exxec/sprites_provider/pty_manager.py
async def resize(self, pty_id: str, size: PtySize) -> None:
    """Resize a PTY session.

    Args:
        pty_id: The PTY session ID
        size: New terminal size

    Raises:
        KeyError: If PTY session not found
    """
    session = self._sprites_sessions.get(pty_id)
    if not session:
        msg = f"PTY session {pty_id} not found"
        raise KeyError(msg)

    if session.ws_cmd:
        await session.ws_cmd.resize(cols=size.cols, rows=size.rows)
    session.info.size = size

stream async

stream(pty_id: str) -> AsyncIterator[bytes]

Stream output from a PTY session.

Parameters:

Name Type Description Default
pty_id str

The PTY session ID

required

Yields:

Type Description
AsyncIterator[bytes]

Chunks of output data as they become available

Raises:

Type Description
KeyError

If PTY session not found

Source code in src/exxec/sprites_provider/pty_manager.py
async def stream(self, pty_id: str) -> AsyncIterator[bytes]:
    """Stream output from a PTY session.

    Args:
        pty_id: The PTY session ID

    Yields:
        Chunks of output data as they become available

    Raises:
        KeyError: If PTY session not found
    """
    session = self._sprites_sessions.get(pty_id)
    if not session:
        msg = f"PTY session {pty_id} not found"
        raise KeyError(msg)

    while session.info.status == "running":
        try:
            await asyncio.wait_for(session._output_event.wait(), timeout=0.5)
        except TimeoutError:
            continue

        if session._output_buffer:
            data = b"".join(session._output_buffer)
            session._output_buffer.clear()
            session._output_event.clear()
            yield data

write async

write(pty_id: str, data: bytes) -> None

Write data to a PTY's stdin.

Parameters:

Name Type Description Default
pty_id str

The PTY session ID

required
data bytes

Data to write

required

Raises:

Type Description
KeyError

If PTY session not found

Source code in src/exxec/sprites_provider/pty_manager.py
async def write(self, pty_id: str, data: bytes) -> None:
    """Write data to a PTY's stdin.

    Args:
        pty_id: The PTY session ID
        data: Data to write

    Raises:
        KeyError: If PTY session not found
    """
    session = self._sprites_sessions.get(pty_id)
    if not session:
        msg = f"PTY session {pty_id} not found"
        raise KeyError(msg)

    if session.ws_cmd:
        await session.ws_cmd._write_stdin(data)