Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Extract shared sync and async shared types
Tomas Valenta3d3b1a91110e
diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.pyindex 96f1b294a..df68b3f8e 100644--- a/packages/python-sdk/e2b/__init__.py+++ b/packages/python-sdk/e2b/__init__.py@@ -15,9 +15,7 @@ from .exceptions import (TemplateException,)from .sandbox.sandbox_api import SandboxInfo-from .sandbox.main import Sandboxfrom .sandbox.process.process_handle import (- ProcessHandle,ProcessResult,Stderr,Stdout,@@ -25,9 +23,11 @@ from .sandbox.process.process_handle import ()from .sandbox.process.main import ProcessInfofrom .sandbox.filesystem.watch_handle import (- WatchHandle,FilesystemEvent,FilesystemEventType,)from .sandbox.filesystem.filesystem import EntryInfo, FileType-from .sandbox.main import Sandbox++from .sandbox.sync.main import Sandbox+from .sandbox.sync.filesystem.watch_handle import WatchHandle+from .sandbox.sync.process.process_handle import ProcessHandlediff --git a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.pyindex 9385a7d2a..61c77483b 100644--- a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py+++ b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py@@ -1,31 +1,7 @@-import connect-import httpx-import httpcore-from enum import Enumfrom dataclasses import dataclass-from typing import (- Iterator,- List,- Optional,- overload,- Literal,- Union,- IO,-)-from e2b.sandbox.filesystem.watch_handle import WatchHandle-from e2b.connection_config import (- Username,- ConnectionConfig,-)-from e2b.exceptions import (- SandboxException,-)-from e2b.envd.api import handle_envd_api_exception-from e2b.envd.rpc import authentication_header, handle_rpc_exception-from e2b.envd.filesystem import filesystem_connect, filesystem_pb2-from e2b.envd.api import ENVD_API_FILES_ROUTE+from e2b.envd.filesystem import filesystem_pb2class FileType(Enum):@@ -44,241 +20,3 @@ def map_file_type(ft: filesystem_pb2.FileType):class EntryInfo:name: strtype: FileType---class Filesystem:- def __init__(- self,- envd_api_url: str,- connection_config: ConnectionConfig,- pool: httpcore.ConnectionPool,- envd_api: httpx.Client,- ) -> None:- self._envd_api_url = envd_api_url- self._connection_config = connection_config- self._pool = pool- self._envd_api = envd_api-- self._rpc = filesystem_connect.FilesystemClient(- envd_api_url,- compressor=connect.GzipCompressor,- pool=pool,- )-- @overload- def read(- self,- path: str,- format: Literal["text"] = "text",- user: Username = "user",- request_timeout: Optional[float] = None,- ) -> str:- ...-- @overload- def read(- self,- path: str,- format: Literal["bytes"],- user: Username = "user",- request_timeout: Optional[float] = None,- ) -> bytearray:- ...-- @overload- def read(- self,- path: str,- format: Literal["stream"],- user: Username = "user",- request_timeout: Optional[float] = None,- ) -> Iterator[bytes]:- ...-- def read(- self,- path: str,- format: Literal["text", "bytes", "stream"] = "text",- user: Username = "user",- request_timeout: Optional[float] = None,- ):- r = self._envd_api.get(- ENVD_API_FILES_ROUTE,- params={"path": path, "username": user},- timeout=self._connection_config.get_request_timeout(request_timeout),- )-- err = handle_envd_api_exception(r)- if err:- raise err-- if format == "text":- return r.text- elif format == "bytes":- return bytearray(r.content)- elif format == "stream":- return r.iter_bytes()-- def write(- self,- path: str,- data: Union[str, bytes, IO],- user: Username = "user",- request_timeout: Optional[float] = None,- ) -> None:- r = self._envd_api.post(- ENVD_API_FILES_ROUTE,- files={"file": data},- params={"path": path, "username": user},- timeout=self._connection_config.get_request_timeout(request_timeout),- )-- err = handle_envd_api_exception(r)- if err:- raise err-- def list(- self,- path: str,- user: Username = "user",- request_timeout: Optional[float] = None,- ) -> List[EntryInfo]:- try:- res = self._rpc.list_dir(- filesystem_pb2.ListDirRequest(- path=path,- ),- request_timeout=self._connection_config.get_request_timeout(- request_timeout- ),- headers=authentication_header(user),- )-- entries: List[EntryInfo] = []- for entry in res.entries:- event_type = map_file_type(entry.type)-- if event_type:- entries.append(EntryInfo(name=entry.name, type=event_type))-- return entries- except Exception as e:- raise handle_rpc_exception(e)-- def exists(- self,- path: str,- user: Username = "user",- request_timeout: Optional[float] = None,- ) -> bool:- try:- self._rpc.stat(- filesystem_pb2.StatRequest(- path=path,- ),- request_timeout=self._connection_config.get_request_timeout(- request_timeout- ),- headers=authentication_header(user),- )- return True-- except Exception as e:- if isinstance(e, connect.ConnectException):- if e.status == connect.Code.not_found:- return False- raise handle_rpc_exception(e)-- def remove(- self,- path: str,- user: Username = "user",- request_timeout: Optional[float] = None,- ) -> None:- try:- self._rpc.remove(- filesystem_pb2.RemoveRequest(- path=path,- ),- request_timeout=self._connection_config.get_request_timeout(- request_timeout- ),- headers=authentication_header(user),- )- except Exception as e:- raise handle_rpc_exception(e)-- def rename(- self,- old_path: str,- new_path: str,- user: Username = "user",- request_timeout: Optional[float] = None,- ) -> None:- try:- self._rpc.move(- filesystem_pb2.MoveRequest(- source=old_path,- destination=new_path,- ),- request_timeout=self._connection_config.get_request_timeout(- request_timeout- ),- headers=authentication_header(user),- )- except Exception as e:- raise handle_rpc_exception(e)-- def make_dir(- self,- path: str,- user: Username = "user",- request_timeout: Optional[float] = None,- ) -> bool:- try:- self._rpc.make_dir(- filesystem_pb2.MakeDirRequest(- path=path,- ),- request_timeout=self._connection_config.get_request_timeout(- request_timeout- ),- headers=authentication_header(user),- )-- return True- except Exception as e:- if isinstance(e, connect.ConnectException):- if e.status == connect.Code.already_exists:- return False- raise handle_rpc_exception(e)-- def watch(- self,- path: str,- user: Username = "user",- request_timeout: Optional[float] = None,- timeout: Optional[float] = 60,- ):- events = self._rpc.watch_dir(- filesystem_pb2.WatchDirRequest(- path=path,- ),- request_timeout=self._connection_config.get_request_timeout(- request_timeout- ),- timeout=timeout,- headers=authentication_header(user),- )-- try:- start_event = next(events)-- if not start_event.HasField("start"):- raise SandboxException(- f"Failed to start watch: expected start event, got {start_event}",- )-- return WatchHandle(events=events)- except Exception as e:- raise handle_rpc_exception(e)diff --git a/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py b/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.pyindex 0616e518a..1266d25e9 100644--- a/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py+++ b/packages/python-sdk/e2b/sandbox/filesystem/watch_handle.py@@ -1,9 +1,7 @@-from typing import Any, Generatorfrom dataclasses import dataclassfrom enum import Enum-from e2b.envd.rpc import handle_rpc_exception-from e2b.envd.filesystem.filesystem_pb2 import EventType, WatchDirResponse+from e2b.envd.filesystem.filesystem_pb2 import EventTypeclass FilesystemEventType(Enum):@@ -31,32 +29,3 @@ def map_event_type(event: EventType):class FilesystemEvent:name: strtype: FilesystemEventType---class WatchHandle:- def __init__(- self,- events: Generator[WatchDirResponse, Any, None],- ):- self._events = events-- def __iter__(self):- return self._handle_events()-- def close(self):- self._events.close()-- def _handle_events(self):- try:- for event in self._events:- if event.HasField("filesystem"):- event_type = map_event_type(event.filesystem.type)- if event_type:- yield FilesystemEvent(- name=event.filesystem.name,- type=event_type,- )- except Exception as e:- raise handle_rpc_exception(e)- finally:- self.close()diff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.pyindex b974a5576..6b8083c05 100644--- a/packages/python-sdk/e2b/sandbox/main.py+++ b/packages/python-sdk/e2b/sandbox/main.py@@ -1,222 +1,5 @@-import logging-import urllib.parse-import httpcore-import httpx--from typing import Optional, Dict, Literal, overload--from e2b.sandbox.utils import class_method_variant-from e2b.sandbox.filesystem.filesystem import Filesystem-from e2b.sandbox.process.main import Process-from e2b.sandbox.sandbox_api import SandboxApi-from e2b.connection_config import ConnectionConfig-from e2b.envd.api import (- ENVD_API_FILES_ROUTE,- handle_envd_api_exception,- ENVD_API_HEALTH_ROUTE,-)-from e2b.exceptions import SandboxException---logger = logging.getLogger(__name__)---class E2BConnectionPool(httpcore.ConnectionPool):- def handle_request(self, request):- url = f"{request.url.scheme.decode()}://{request.url.host.decode()}{request.url.target.decode()}"- logger.info(f"Request: {request.method.decode()} {url}")- response = super().handle_request(request)-- # data = connect.GzipCompressor.decompress(response.read()).decode()- logger.info(f"Response: {response.status} {url}")-- return response---class Sandbox(SandboxApi):+class SandboxSetup:_envd_port = 49983default_sandbox_timeout = 300default_template = "base"-- @property- def files(self) -> Filesystem:- return self._filesystem-- @property- def commands(self) -> Process:- return self._process-- def __init__(- self,- template: Optional[str] = None,- timeout: Optional[int] = None,- metadata: Optional[Dict[str, str]] = None,- api_key: Optional[str] = None,- domain: Optional[str] = None,- debug: Optional[bool] = None,- sandbox_id: Optional[str] = None,- request_timeout: Optional[float] = None,- ):- super().__init__()-- if sandbox_id and (metadata is not None or template is not None):- raise SandboxException(- "Cannot set metadata or timeout when connecting to an existing sandbox. "- "Use Sandbox.connect method instead.",- )-- self._connection_config = ConnectionConfig(- api_key=api_key,- domain=domain,- debug=debug,- request_timeout=request_timeout,- )-- if self._connection_config.debug:- self.sandbox_id = "debug_sandbox_id"- elif sandbox_id is not None:- self.sandbox_id = sandbox_id- else:- template = template or self.default_template- timeout = timeout or self.default_sandbox_timeout- self.sandbox_id = SandboxApi._create_sandbox(- template=template,- api_key=api_key,- timeout=timeout,- metadata=metadata,- domain=domain,- debug=debug,- request_timeout=request_timeout,- )-- self._envd_api_url = f"{'http' if self._connection_config.debug else 'https'}://{self.get_host(self._envd_port)}"-- self._envd_rpc_pool = E2BConnectionPool(max_connections=25)- self._envd_api = httpx.Client(base_url=self._envd_api_url)-- self._filesystem = Filesystem(- self._envd_api_url,- self._connection_config,- self._envd_rpc_pool,- self._envd_api,- )- self._process = Process(- self._envd_api_url, self._connection_config, self._envd_rpc_pool- )-- def get_host(self, port: int) -> str:- if self._connection_config.debug:- return f"localhost:{port}"-- return f"{port}-{self.sandbox_id}.{self._connection_config.domain}"-- def is_running(self, request_timeout: Optional[float] = None) -> Literal[True]:- r = self._envd_api.get(- ENVD_API_HEALTH_ROUTE,- timeout=self._connection_config.get_request_timeout(request_timeout),- )-- err = handle_envd_api_exception(r)- if err:- raise err-- return True-- @classmethod- def connect(- cls,- sandbox_id: str,- api_key: Optional[str] = None,- domain: Optional[str] = None,- debug: Optional[bool] = None,- ):- return cls(- sandbox_id=sandbox_id,- api_key=api_key,- domain=domain,- debug=debug,- )-- def upload_url(self, path: Optional[str] = None) -> str:- url = urllib.parse.urljoin(self._envd_api_url, ENVD_API_FILES_ROUTE)- query = {"path": path} if path else {}- query = {**query, "username": "user"}-- params = urllib.parse.urlencode(- query,- quote_via=urllib.parse.quote,- )- url = urllib.parse.urljoin(url, f"?{params}")-- return url-- def __enter__(self):- return self-- def __exit__(self, exc_type, exc_value, traceback):- self.kill()-- @overload- def kill(self, request_timeout: Optional[float] = None) -> bool: ...-- @overload- @staticmethod- def kill(- sandbox_id: str,- api_key: Optional[str] = None,- domain: Optional[str] = None,- debug: Optional[bool] = None,- request_timeout: Optional[float] = None,- ) -> bool: ...-- @class_method_variant("_cls_kill")- def kill(self, request_timeout: Optional[float] = None) -> bool: # type: ignore- config_dict = self._connection_config.__dict__- config_dict.pop("access_token", None)- config_dict.pop("api_url", None)-- if request_timeout:- config_dict["request_timeout"] = request_timeout-- SandboxApi._cls_kill(- sandbox_id=self.sandbox_id,- **self._connection_config.__dict__,- )-- @overload- def set_timeout(- self,- timeout: int,- request_timeout: Optional[float] = None,- ) -> None: ...-- @overload- @staticmethod- def set_timeout(- sandbox_id: str,- timeout: int,- api_key: Optional[str] = None,- domain: Optional[str] = None,- debug: Optional[bool] = None,- request_timeout: Optional[float] = None,- ) -> None: ...-- @class_method_variant("_cls_set_timeout")- def set_timeout( # type: ignore- self,- timeout: int,- request_timeout: Optional[float] = None,- ) -> None:- config_dict = self._connection_config.__dict__- config_dict.pop("access_token", None)- config_dict.pop("api_url", None)-- if request_timeout:- config_dict["request_timeout"] = request_timeout-- SandboxApi._cls_set_timeout(- sandbox_id=self.sandbox_id,- timeout=timeout,- **self._connection_config.__dict__,- )diff --git a/packages/python-sdk/e2b/sandbox/process/main.py b/packages/python-sdk/e2b/sandbox/process/main.pyindex c2f9bd449..c8f1735db 100644--- a/packages/python-sdk/e2b/sandbox/process/main.py+++ b/packages/python-sdk/e2b/sandbox/process/main.py@@ -1,17 +1,5 @@from dataclasses import dataclass-import connect-import httpcore--from typing import Dict, List, Optional, Literal, overload, Union, Callable--from e2b.envd.process import process_connect, process_pb2-from e2b.sandbox.process.process_handle import ProcessHandle, ProcessResult-from e2b.connection_config import (- Username,- ConnectionConfig,-)-from e2b.exceptions import SandboxException-from e2b.envd.rpc import authentication_header, handle_rpc_exception+from typing import Dict, List, Optional@dataclass@@ -22,218 +10,3 @@ class ProcessInfo:args: List[str]envs: Dict[str, str]cwd: Optional[str]---class Process:- def __init__(- self,- envd_api_url: str,- connection_config: ConnectionConfig,- pool: httpcore.ConnectionPool,- ) -> None:- self._connection_config = connection_config- self._rpc = process_connect.ProcessClient(- envd_api_url,- # TODO: Fix and enable compression again — the headers compression is not solved.- # compressor=connect.GzipCompressor,- pool=pool,- )-- def list(- self,- request_timeout: Optional[float] = None,- ) -> List[ProcessInfo]:- try:- res = self._rpc.list(- process_pb2.ListRequest(),- request_timeout=self._connection_config.get_request_timeout(- request_timeout- ),- )- return [- ProcessInfo(- pid=p.pid,- tag=p.tag,- cmd=p.config.cmd,- args=list(p.config.args),- envs=dict(p.config.envs),- cwd=p.config.cwd,- )- for p in res.processes- ]- except Exception as e:- raise handle_rpc_exception(e)-- def kill(- self,- pid: int,- request_timeout: Optional[float] = None,- ) -> bool:- try:- self._rpc.send_signal(- process_pb2.SendSignalRequest(- process=process_pb2.ProcessSelector(pid=pid),- signal=process_pb2.Signal.SIGNAL_SIGKILL,- ),- request_timeout=self._connection_config.get_request_timeout(- request_timeout- ),- )- return True- except Exception as e:- if isinstance(e, connect.ConnectException):- if e.status == connect.Code.not_found:- return False- raise handle_rpc_exception(e)-- def send_stdin(- self,- pid: int,- data: str,- request_timeout: Optional[float] = None,- ):- try:- self._rpc.send_input(- process_pb2.SendInputRequest(- process=process_pb2.ProcessSelector(pid=pid),- input=process_pb2.ProcessInput(- stdin=data.encode(),- ),- ),- request_timeout=self._connection_config.get_request_timeout(- request_timeout- ),- )- except Exception as e:- raise handle_rpc_exception(e)-- @overload- def run(- self,- cmd: str,- background: Union[Literal[False], None] = None,- envs: Optional[Dict[str, str]] = {},- user: Username = "user",- cwd: Optional[str] = None,- on_stdout: Optional[Callable[[str], None]] = None,- on_stderr: Optional[Callable[[str], None]] = None,- timeout: Optional[float] = 60,- request_timeout: Optional[float] = None,- ) -> ProcessResult: ...-- @overload- def run(- self,- cmd: str,- background: Literal[True],- envs: Optional[Dict[str, str]] = {},- user: Username = "user",- cwd: Optional[str] = None,- on_stdout: Optional[Callable[[str], None]] = None,- on_stderr: Optional[Callable[[str], None]] = None,- timeout: Optional[float] = 60,- request_timeout: Optional[float] = None,- ) -> ProcessHandle: ...-- def run(- self,- cmd: str,- background: Union[bool, None] = None,- envs: Optional[Dict[str, str]] = {},- user: Username = "user",- cwd: Optional[str] = None,- on_stdout: Optional[Callable[[str], None]] = None,- on_stderr: Optional[Callable[[str], None]] = None,- timeout: Optional[float] = 60,- request_timeout: Optional[float] = None,- ):- proc = self._start(- cmd,- envs,- user,- cwd,- timeout,- request_timeout,- )-- return (- proc- if background- else proc.wait(- on_stdout=on_stdout,- on_stderr=on_stderr,- )- )-- def _start(- self,- cmd: str,- envs: Optional[Dict[str, str]] = {},- user: Username = "user",- cwd: Optional[str] = None,- timeout: Optional[float] = 60,- request_timeout: Optional[float] = None,- ):- events = self._rpc.start(- process_pb2.StartRequest(- process=process_pb2.ProcessConfig(- cmd="/bin/bash",- envs=envs,- args=["-l", "-c", cmd],- cwd=cwd,- ),- ),- headers=authentication_header(user),- timeout=timeout,- request_timeout=self._connection_config.get_request_timeout(- request_timeout- ),- )-- try:- start_event = next(events)-- if not start_event.HasField("event"):- raise SandboxException(- f"Failed to start process: expected start event, got {start_event}"- )-- return ProcessHandle(- pid=start_event.event.start.pid,- handle_kill=lambda: self.kill(start_event.event.start.pid),- events=events,- )- except Exception as e:- raise handle_rpc_exception(e)-- def connect(- self,- pid: int,- timeout: Optional[float] = 60,- request_timeout: Optional[float] = None,- ):- events = self._rpc.connect(- process_pb2.ConnectRequest(- process=process_pb2.ProcessSelector(pid=pid),- ),- timeout=timeout,- request_timeout=self._connection_config.get_request_timeout(- request_timeout- ),- )-- try:- start_event = next(events)-- if not start_event.HasField("event"):- raise SandboxException(- f"Failed to connect to process: expected start event, got {start_event}"- )-- return ProcessHandle(- pid=start_event.event.start.pid,- handle_kill=lambda: self.kill(start_event.event.start.pid),- events=events,- )- except Exception as e:- raise handle_rpc_exception(e)diff --git a/packages/python-sdk/e2b/sandbox/process/process_handle.py b/packages/python-sdk/e2b/sandbox/process/process_handle.pyindex 332a205ac..84f2b4bee 100644--- a/packages/python-sdk/e2b/sandbox/process/process_handle.py+++ b/packages/python-sdk/e2b/sandbox/process/process_handle.py@@ -1,9 +1,7 @@from dataclasses import dataclass-from typing import Optional, Callable, Any, Generator, Union, Tuple+from typing import Optionalfrom e2b.exceptions import SandboxException-from e2b.envd.rpc import handle_rpc_exception-from e2b.envd.process import process_pb2Stdout = strStderr = str@@ -21,96 +19,3 @@ class ProcessResult:class ProcessExitException(SandboxException, ProcessResult):def __str__(self):return f"Process exited with code {self.exit_code} and error: {self.error}"---class ProcessHandle:- @property- def pid(self):- return self._pid-- def __init__(- self,- pid: int,- handle_kill: Callable[[], bool],- events: Generator[- Union[process_pb2.StartResponse, process_pb2.ConnectResponse], Any, None- ],- ):- self._pid = pid- self._handle_kill = handle_kill- self._events = events-- self._stdout: str = ""- self._stderr: str = ""-- self._result: Optional[ProcessResult] = None- self._iteration_exception: Optional[Exception] = None-- def __iter__(self):- return self._handle_events()-- def _handle_events(- self,- ) -> Generator[- Union[Tuple[Stdout, None], Tuple[None, Stderr]],- None,- None,- ]:- try:- for event in self._events:- if event.event.HasField("data"):- if event.event.data.stdout:- out = event.event.data.stdout.decode()- self._stdout += out- yield out, None- if event.event.data.stderr:- out = event.event.data.stderr.decode()- self._stderr += out- yield None, out- if event.event.HasField("end"):- self._result = ProcessResult(- stdout=self._stdout,- stderr=self._stderr,- exit_code=event.event.end.exit_code,- error=event.event.end.error,- )- finally:- self.disconnect()-- def disconnect(self) -> None:- self._events.close()-- def wait(- self,- on_stdout: Optional[Callable[[str], None]] = None,- on_stderr: Optional[Callable[[str], None]] = None,- ) -> ProcessResult:- try:- for stdout, stderr in self:- if stdout is not None and on_stdout:- on_stdout(stdout)- elif stderr is not None and on_stderr:- on_stderr(stderr)- except StopIteration:- pass- except Exception as e:- self._iteration_exception = handle_rpc_exception(e)-- if self._iteration_exception:- raise self._iteration_exception-- if self._result is None:- raise Exception("Process ended without an end event")-- if self._result.exit_code != 0:- raise ProcessExitException(- stdout=self._stdout,- stderr=self._stderr,- exit_code=self._result.exit_code,- error=self._result.error,- )-- return self._result-- def kill(self):- self._handle_kill()diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.pyindex caafa00c8..9d74f0c73 100644--- a/packages/python-sdk/e2b/sandbox/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py@@ -1,19 +1,6 @@from dataclasses import dataclass-from typing import Optional, Dict, List+from typing import Optional, Dictfrom datetime import datetime-from packaging.version import Version--from e2b.exceptions import TemplateException-from e2b.api import ApiClient-from e2b.api.client.models import NewSandbox, PostSandboxesSandboxIDTimeoutBody-from e2b.api.client.api.sandboxes import (- post_sandboxes_sandbox_id_timeout,- get_sandboxes,- delete_sandboxes_sandbox_id,- post_sandboxes,-)-from e2b.connection_config import ConnectionConfig-from e2b.api import handle_api_exception@dataclass@@ -30,160 +17,3 @@ class SandboxInfo:"""Saved sandbox metadata."""started_at: datetime"""Sandbox start time."""---class SandboxApi:- @classmethod- def list(- cls,- api_key: Optional[str] = None,- domain: Optional[str] = None,- debug: Optional[bool] = None,- request_timeout: Optional[float] = None,- ) -> List[SandboxInfo]:- config = ConnectionConfig(- api_key=api_key,- domain=domain,- debug=debug,- request_timeout=request_timeout,- )-- with ApiClient(config) as api_client:- res = get_sandboxes.sync_detailed(- client=api_client,- )-- if res.status_code >= 300:- raise handle_api_exception(res)-- if res.parsed is None:- return []-- return [- SandboxInfo(- sandbox_id=SandboxApi._get_sandbox_id(- sandbox.sandbox_id,- sandbox.client_id,- ),- template_id=sandbox.template_id,- name=sandbox.alias if isinstance(sandbox.alias, str) else None,- metadata=(- sandbox.metadata if isinstance(sandbox.metadata, dict) else None- ),- started_at=sandbox.started_at,- )- for sandbox in res.parsed- if sandbox is not None- ]-- @classmethod- def _cls_kill(- cls,- sandbox_id: str,- api_key: Optional[str] = None,- domain: Optional[str] = None,- debug: Optional[bool] = None,- request_timeout: Optional[float] = None,- ) -> bool:- config = ConnectionConfig(- api_key=api_key,- domain=domain,- debug=debug,- request_timeout=request_timeout,- )-- with ApiClient(config) as api_client:- res = delete_sandboxes_sandbox_id.sync_detailed(- sandbox_id,- client=api_client,- )-- if res.status_code == 404:- return False-- if res.status_code >= 300:- raise handle_api_exception(res)-- return True-- @classmethod- def _cls_set_timeout(- cls,- sandbox_id: str,- timeout: int,- api_key: Optional[str] = None,- domain: Optional[str] = None,- debug: Optional[bool] = None,- request_timeout: Optional[float] = None,- ) -> None:- config = ConnectionConfig(- api_key=api_key,- domain=domain,- debug=debug,- request_timeout=request_timeout,- )-- with ApiClient(config) as api_client:- res = post_sandboxes_sandbox_id_timeout.sync_detailed(- sandbox_id,- client=api_client,- body=PostSandboxesSandboxIDTimeoutBody(timeout=timeout),- )-- if res.status_code >= 300:- raise handle_api_exception(res)-- @classmethod- def _create_sandbox(- cls,- template: str,- timeout: int,- metadata: Optional[Dict[str, str]] = None,- api_key: Optional[str] = None,- domain: Optional[str] = None,- debug: Optional[bool] = None,- request_timeout: Optional[float] = None,- ) -> str:- config = ConnectionConfig(- api_key=api_key,- domain=domain,- debug=debug,- request_timeout=request_timeout,- )-- with ApiClient(config) as api_client:- res = post_sandboxes.sync_detailed(- body=NewSandbox(- template_id=template,- metadata=metadata or {},- timeout=timeout,- ),- client=api_client,- )-- if res.status_code >= 300:- raise handle_api_exception(res)-- if res.parsed is None:- raise Exception("Body of the request is None")-- if Version(res.parsed.envd_version) < Version("0.1.0"):- SandboxApi._cls_kill(- SandboxApi._get_sandbox_id(- res.parsed.sandbox_id,- res.parsed.client_id,- )- )- raise TemplateException(- "You need to update the template to use the new SDK. "- "You can do this by running `e2b template build` in the directory with the template."- )-- return SandboxApi._get_sandbox_id(- res.parsed.sandbox_id,- res.parsed.client_id,- )-- @staticmethod- def _get_sandbox_id(sandbox_id: str, client_id: str) -> str:- return f"{sandbox_id}-{client_id}"diff --git a/packages/python-sdk/e2b/sandbox/sync/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox/sync/filesystem/filesystem.pynew file mode 100644index 000000000..43f815f51--- /dev/null+++ b/packages/python-sdk/e2b/sandbox/sync/filesystem/filesystem.py@@ -0,0 +1,262 @@+import connect+import httpx+import httpcore++from typing import (+ Iterator,+ List,+ Optional,+ overload,+ Literal,+ Union,+ IO,+)++from e2b.sandbox.filesystem.filesystem import EntryInfo, map_file_type+from e2b.sandbox.sync.filesystem.watch_handle import WatchHandle+from e2b.connection_config import (+ Username,+ ConnectionConfig,+)+from e2b.exceptions import (+ SandboxException,+)+from e2b.envd.api import handle_envd_api_exception+from e2b.envd.rpc import authentication_header, handle_rpc_exception+from e2b.envd.filesystem import filesystem_connect, filesystem_pb2+from e2b.envd.api import ENVD_API_FILES_ROUTE+++class Filesystem:+ def __init__(+ self,+ envd_api_url: str,+ connection_config: ConnectionConfig,+ pool: httpcore.ConnectionPool,+ envd_api: httpx.Client,+ ) -> None:+ self._envd_api_url = envd_api_url+ self._connection_config = connection_config+ self._pool = pool+ self._envd_api = envd_api++ self._rpc = filesystem_connect.FilesystemClient(+ envd_api_url,+ compressor=connect.GzipCompressor,+ pool=pool,+ )++ @overload+ def read(+ self,+ path: str,+ format: Literal["text"] = "text",+ user: Username = "user",+ request_timeout: Optional[float] = None,+ ) -> str: ...++ @overload+ def read(+ self,+ path: str,+ format: Literal["bytes"],+ user: Username = "user",+ request_timeout: Optional[float] = None,+ ) -> bytearray: ...++ @overload+ def read(+ self,+ path: str,+ format: Literal["stream"],+ user: Username = "user",+ request_timeout: Optional[float] = None,+ ) -> Iterator[bytes]: ...++ def read(+ self,+ path: str,+ format: Literal["text", "bytes", "stream"] = "text",+ user: Username = "user",+ request_timeout: Optional[float] = None,+ ):+ r = self._envd_api.get(+ ENVD_API_FILES_ROUTE,+ params={"path": path, "username": user},+ timeout=self._connection_config.get_request_timeout(request_timeout),+ )++ err = handle_envd_api_exception(r)+ if err:+ raise err++ if format == "text":+ return r.text+ elif format == "bytes":+ return bytearray(r.content)+ elif format == "stream":+ return r.iter_bytes()++ def write(+ self,+ path: str,+ data: Union[str, bytes, IO],+ user: Username = "user",+ request_timeout: Optional[float] = None,+ ) -> None:+ r = self._envd_api.post(+ ENVD_API_FILES_ROUTE,+ files={"file": data},+ params={"path": path, "username": user},+ timeout=self._connection_config.get_request_timeout(request_timeout),+ )++ err = handle_envd_api_exception(r)+ if err:+ raise err++ def list(+ self,+ path: str,+ user: Username = "user",+ request_timeout: Optional[float] = None,+ ) -> List[EntryInfo]:+ try:+ res = self._rpc.list_dir(+ filesystem_pb2.ListDirRequest(+ path=path,+ ),+ request_timeout=self._connection_config.get_request_timeout(+ request_timeout+ ),+ headers=authentication_header(user),+ )++ entries: List[EntryInfo] = []+ for entry in res.entries:+ event_type = map_file_type(entry.type)++ if event_type:+ entries.append(EntryInfo(name=entry.name, type=event_type))++ return entries+ except Exception as e:+ raise handle_rpc_exception(e)++ def exists(+ self,+ path: str,+ user: Username = "user",+ request_timeout: Optional[float] = None,+ ) -> bool:+ try:+ self._rpc.stat(+ filesystem_pb2.StatRequest(+ path=path,+ ),+ request_timeout=self._connection_config.get_request_timeout(+ request_timeout+ ),+ headers=authentication_header(user),+ )+ return True++ except Exception as e:+ if isinstance(e, connect.ConnectException):+ if e.status == connect.Code.not_found:+ return False+ raise handle_rpc_exception(e)++ def remove(+ self,+ path: str,+ user: Username = "user",+ request_timeout: Optional[float] = None,+ ) -> None:+ try:+ self._rpc.remove(+ filesystem_pb2.RemoveRequest(+ path=path,+ ),+ request_timeout=self._connection_config.get_request_timeout(+ request_timeout+ ),+ headers=authentication_header(user),+ )+ except Exception as e:+ raise handle_rpc_exception(e)++ def rename(+ self,+ old_path: str,+ new_path: str,+ user: Username = "user",+ request_timeout: Optional[float] = None,+ ) -> None:+ try:+ self._rpc.move(+ filesystem_pb2.MoveRequest(+ source=old_path,+ destination=new_path,+ ),+ request_timeout=self._connection_config.get_request_timeout(+ request_timeout+ ),+ headers=authentication_header(user),+ )+ except Exception as e:+ raise handle_rpc_exception(e)++ def make_dir(+ self,+ path: str,+ user: Username = "user",+ request_timeout: Optional[float] = None,+ ) -> bool:+ try:+ self._rpc.make_dir(+ filesystem_pb2.MakeDirRequest(+ path=path,+ ),+ request_timeout=self._connection_config.get_request_timeout(+ request_timeout+ ),+ headers=authentication_header(user),+ )++ return True+ except Exception as e:+ if isinstance(e, connect.ConnectException):+ if e.status == connect.Code.already_exists:+ return False+ raise handle_rpc_exception(e)++ def watch(+ self,+ path: str,+ user: Username = "user",+ request_timeout: Optional[float] = None,+ timeout: Optional[float] = 60,+ ):+ events = self._rpc.watch_dir(+ filesystem_pb2.WatchDirRequest(+ path=path,+ ),+ request_timeout=self._connection_config.get_request_timeout(+ request_timeout+ ),+ timeout=timeout,+ headers=authentication_header(user),+ )++ try:+ start_event = next(events)++ if not start_event.HasField("start"):+ raise SandboxException(+ f"Failed to start watch: expected start event, got {start_event}",+ )++ return WatchHandle(events=events)+ except Exception as e:+ raise handle_rpc_exception(e)diff --git a/packages/python-sdk/e2b/sandbox/sync/filesystem/watch_handle.py b/packages/python-sdk/e2b/sandbox/sync/filesystem/watch_handle.pynew file mode 100644index 000000000..125d5de12--- /dev/null+++ b/packages/python-sdk/e2b/sandbox/sync/filesystem/watch_handle.py@@ -0,0 +1,34 @@+from typing import Any, Generator++from e2b.envd.rpc import handle_rpc_exception+from e2b.envd.filesystem.filesystem_pb2 import EventType, WatchDirResponse+from e2b.sandbox.filesystem.watch_handle import FilesystemEvent, map_event_type+++class WatchHandle:+ def __init__(+ self,+ events: Generator[WatchDirResponse, Any, None],+ ):+ self._events = events++ def __iter__(self):+ return self._handle_events()++ def close(self):+ self._events.close()++ def _handle_events(self):+ try:+ for event in self._events:+ if event.HasField("filesystem"):+ event_type = map_event_type(event.filesystem.type)+ if event_type:+ yield FilesystemEvent(+ name=event.filesystem.name,+ type=event_type,+ )+ except Exception as e:+ raise handle_rpc_exception(e)+ finally:+ self.close()diff --git a/packages/python-sdk/e2b/sandbox/sync/main.py b/packages/python-sdk/e2b/sandbox/sync/main.pynew file mode 100644index 000000000..011d9f613--- /dev/null+++ b/packages/python-sdk/e2b/sandbox/sync/main.py@@ -0,0 +1,218 @@+import logging+import urllib.parse+import httpcore+import httpx++from typing import Optional, Dict, Literal, overload++from e2b.sandbox.utils import class_method_variant+from e2b.connection_config import ConnectionConfig+from e2b.envd.api import (+ ENVD_API_FILES_ROUTE,+ handle_envd_api_exception,+ ENVD_API_HEALTH_ROUTE,+)+from e2b.exceptions import SandboxException+from e2b.sandbox.sync.filesystem.filesystem import Filesystem+from e2b.sandbox.sync.process.main import Process+from e2b.sandbox.sync.sandbox_api import SandboxApi+from e2b.sandbox.main import SandboxSetup+++logger = logging.getLogger(__name__)+++class E2BConnectionPool(httpcore.ConnectionPool):+ def handle_request(self, request):+ url = f"{request.url.scheme.decode()}://{request.url.host.decode()}{request.url.target.decode()}"+ logger.info(f"Request: {request.method.decode()} {url}")+ response = super().handle_request(request)++ # data = connect.GzipCompressor.decompress(response.read()).decode()+ logger.info(f"Response: {response.status} {url}")++ return response+++class Sandbox(SandboxSetup, SandboxApi):+ @property+ def files(self) -> Filesystem:+ return self._filesystem++ @property+ def commands(self) -> Process:+ return self._process++ def __init__(+ self,+ template: Optional[str] = None,+ timeout: Optional[int] = None,+ metadata: Optional[Dict[str, str]] = None,+ api_key: Optional[str] = None,+ domain: Optional[str] = None,+ debug: Optional[bool] = None,+ sandbox_id: Optional[str] = None,+ request_timeout: Optional[float] = None,+ ):+ super().__init__()++ if sandbox_id and (metadata is not None or template is not None):+ raise SandboxException(+ "Cannot set metadata or timeout when connecting to an existing sandbox. "+ "Use Sandbox.connect method instead.",+ )++ self._connection_config = ConnectionConfig(+ api_key=api_key,+ domain=domain,+ debug=debug,+ request_timeout=request_timeout,+ )++ if self._connection_config.debug:+ self.sandbox_id = "debug_sandbox_id"+ elif sandbox_id is not None:+ self.sandbox_id = sandbox_id+ else:+ template = template or self.default_template+ timeout = timeout or self.default_sandbox_timeout+ self.sandbox_id = SandboxApi._create_sandbox(+ template=template,+ api_key=api_key,+ timeout=timeout,+ metadata=metadata,+ domain=domain,+ debug=debug,+ request_timeout=request_timeout,+ )++ self._envd_api_url = f"{'http' if self._connection_config.debug else 'https'}://{self.get_host(self._envd_port)}"++ self._envd_rpc_pool = E2BConnectionPool(max_connections=25)+ self._envd_api = httpx.Client(base_url=self._envd_api_url)++ self._filesystem = Filesystem(+ self._envd_api_url,+ self._connection_config,+ self._envd_rpc_pool,+ self._envd_api,+ )+ self._process = Process(+ self._envd_api_url, self._connection_config, self._envd_rpc_pool+ )++ def get_host(self, port: int) -> str:+ if self._connection_config.debug:+ return f"localhost:{port}"++ return f"{port}-{self.sandbox_id}.{self._connection_config.domain}"++ def is_running(self, request_timeout: Optional[float] = None) -> Literal[True]:+ r = self._envd_api.get(+ ENVD_API_HEALTH_ROUTE,+ timeout=self._connection_config.get_request_timeout(request_timeout),+ )++ err = handle_envd_api_exception(r)+ if err:+ raise err++ return True++ @classmethod+ def connect(+ cls,+ sandbox_id: str,+ api_key: Optional[str] = None,+ domain: Optional[str] = None,+ debug: Optional[bool] = None,+ ):+ return cls(+ sandbox_id=sandbox_id,+ api_key=api_key,+ domain=domain,+ debug=debug,+ )++ def upload_url(self, path: Optional[str] = None) -> str:+ url = urllib.parse.urljoin(self._envd_api_url, ENVD_API_FILES_ROUTE)+ query = {"path": path} if path else {}+ query = {**query, "username": "user"}++ params = urllib.parse.urlencode(+ query,+ quote_via=urllib.parse.quote,+ )+ url = urllib.parse.urljoin(url, f"?{params}")++ return url++ def __enter__(self):+ return self++ def __exit__(self, exc_type, exc_value, traceback):+ self.kill()++ @overload+ def kill(self, request_timeout: Optional[float] = None) -> bool: ...++ @overload+ @staticmethod+ def kill(+ sandbox_id: str,+ api_key: Optional[str] = None,+ domain: Optional[str] = None,+ debug: Optional[bool] = None,+ request_timeout: Optional[float] = None,+ ) -> bool: ...++ @class_method_variant("_cls_kill")+ def kill(self, request_timeout: Optional[float] = None) -> bool: # type: ignore+ config_dict = self._connection_config.__dict__+ config_dict.pop("access_token", None)+ config_dict.pop("api_url", None)++ if request_timeout:+ config_dict["request_timeout"] = request_timeout++ SandboxApi._cls_kill(+ sandbox_id=self.sandbox_id,+ **self._connection_config.__dict__,+ )++ @overload+ def set_timeout(+ self,+ timeout: int,+ request_timeout: Optional[float] = None,+ ) -> None: ...++ @overload+ @staticmethod+ def set_timeout(+ sandbox_id: str,+ timeout: int,+ api_key: Optional[str] = None,+ domain: Optional[str] = None,+ debug: Optional[bool] = None,+ request_timeout: Optional[float] = None,+ ) -> None: ...++ @class_method_variant("_cls_set_timeout")+ def set_timeout( # type: ignore+ self,+ timeout: int,+ request_timeout: Optional[float] = None,+ ) -> None:+ config_dict = self._connection_config.__dict__+ config_dict.pop("access_token", None)+ config_dict.pop("api_url", None)++ if request_timeout:+ config_dict["request_timeout"] = request_timeout++ SandboxApi._cls_set_timeout(+ sandbox_id=self.sandbox_id,+ timeout=timeout,+ **self._connection_config.__dict__,+ )diff --git a/packages/python-sdk/e2b/sandbox/sync/process/main.py b/packages/python-sdk/e2b/sandbox/sync/process/main.pynew file mode 100644index 000000000..b5c7449c4--- /dev/null+++ b/packages/python-sdk/e2b/sandbox/sync/process/main.py@@ -0,0 +1,230 @@+import connect+import httpcore++from typing import Dict, List, Optional, Literal, overload, Union, Callable++from e2b.envd.process import process_connect, process_pb2+from e2b.connection_config import (+ Username,+ ConnectionConfig,+)+from e2b.exceptions import SandboxException+from e2b.envd.rpc import authentication_header, handle_rpc_exception+from e2b.sandbox.process.main import ProcessInfo+from e2b.sandbox.process.process_handle import ProcessResult+from e2b.sandbox.sync.process.process_handle import ProcessHandle+++class Process:+ def __init__(+ self,+ envd_api_url: str,+ connection_config: ConnectionConfig,+ pool: httpcore.ConnectionPool,+ ) -> None:+ self._connection_config = connection_config+ self._rpc = process_connect.ProcessClient(+ envd_api_url,+ # TODO: Fix and enable compression again — the headers compression is not solved.+ # compressor=connect.GzipCompressor,+ pool=pool,+ )++ def list(+ self,+ request_timeout: Optional[float] = None,+ ) -> List[ProcessInfo]:+ try:+ res = self._rpc.list(+ process_pb2.ListRequest(),+ request_timeout=self._connection_config.get_request_timeout(+ request_timeout+ ),+ )+ return [+ ProcessInfo(+ pid=p.pid,+ tag=p.tag,+ cmd=p.config.cmd,+ args=list(p.config.args),+ envs=dict(p.config.envs),+ cwd=p.config.cwd,+ )+ for p in res.processes+ ]+ except Exception as e:+ raise handle_rpc_exception(e)++ def kill(+ self,+ pid: int,+ request_timeout: Optional[float] = None,+ ) -> bool:+ try:+ self._rpc.send_signal(+ process_pb2.SendSignalRequest(+ process=process_pb2.ProcessSelector(pid=pid),+ signal=process_pb2.Signal.SIGNAL_SIGKILL,+ ),+ request_timeout=self._connection_config.get_request_timeout(+ request_timeout+ ),+ )+ return True+ except Exception as e:+ if isinstance(e, connect.ConnectException):+ if e.status == connect.Code.not_found:+ return False+ raise handle_rpc_exception(e)++ def send_stdin(+ self,+ pid: int,+ data: str,+ request_timeout: Optional[float] = None,+ ):+ try:+ self._rpc.send_input(+ process_pb2.SendInputRequest(+ process=process_pb2.ProcessSelector(pid=pid),+ input=process_pb2.ProcessInput(+ stdin=data.encode(),+ ),+ ),+ request_timeout=self._connection_config.get_request_timeout(+ request_timeout+ ),+ )+ except Exception as e:+ raise handle_rpc_exception(e)++ @overload+ def run(+ self,+ cmd: str,+ background: Union[Literal[False], None] = None,+ envs: Optional[Dict[str, str]] = {},+ user: Username = "user",+ cwd: Optional[str] = None,+ on_stdout: Optional[Callable[[str], None]] = None,+ on_stderr: Optional[Callable[[str], None]] = None,+ timeout: Optional[float] = 60,+ request_timeout: Optional[float] = None,+ ) -> ProcessResult: ...++ @overload+ def run(+ self,+ cmd: str,+ background: Literal[True],+ envs: Optional[Dict[str, str]] = {},+ user: Username = "user",+ cwd: Optional[str] = None,+ on_stdout: Optional[Callable[[str], None]] = None,+ on_stderr: Optional[Callable[[str], None]] = None,+ timeout: Optional[float] = 60,+ request_timeout: Optional[float] = None,+ ) -> ProcessHandle: ...++ def run(+ self,+ cmd: str,+ background: Union[bool, None] = None,+ envs: Optional[Dict[str, str]] = {},+ user: Username = "user",+ cwd: Optional[str] = None,+ on_stdout: Optional[Callable[[str], None]] = None,+ on_stderr: Optional[Callable[[str], None]] = None,+ timeout: Optional[float] = 60,+ request_timeout: Optional[float] = None,+ ):+ proc = self._start(+ cmd,+ envs,+ user,+ cwd,+ timeout,+ request_timeout,+ )++ return (+ proc+ if background+ else proc.wait(+ on_stdout=on_stdout,+ on_stderr=on_stderr,+ )+ )++ def _start(+ self,+ cmd: str,+ envs: Optional[Dict[str, str]] = {},+ user: Username = "user",+ cwd: Optional[str] = None,+ timeout: Optional[float] = 60,+ request_timeout: Optional[float] = None,+ ):+ events = self._rpc.start(+ process_pb2.StartRequest(+ process=process_pb2.ProcessConfig(+ cmd="/bin/bash",+ envs=envs,+ args=["-l", "-c", cmd],+ cwd=cwd,+ ),+ ),+ headers=authentication_header(user),+ timeout=timeout,+ request_timeout=self._connection_config.get_request_timeout(+ request_timeout+ ),+ )++ try:+ start_event = next(events)++ if not start_event.HasField("event"):+ raise SandboxException(+ f"Failed to start process: expected start event, got {start_event}"+ )++ return ProcessHandle(+ pid=start_event.event.start.pid,+ handle_kill=lambda: self.kill(start_event.event.start.pid),+ events=events,+ )+ except Exception as e:+ raise handle_rpc_exception(e)++ def connect(+ self,+ pid: int,+ timeout: Optional[float] = 60,+ request_timeout: Optional[float] = None,+ ):+ events = self._rpc.connect(+ process_pb2.ConnectRequest(+ process=process_pb2.ProcessSelector(pid=pid),+ ),+ timeout=timeout,+ request_timeout=self._connection_config.get_request_timeout(+ request_timeout+ ),+ )++ try:+ start_event = next(events)++ if not start_event.HasField("event"):+ raise SandboxException(+ f"Failed to connect to process: expected start event, got {start_event}"+ )++ return ProcessHandle(+ pid=start_event.event.start.pid,+ handle_kill=lambda: self.kill(start_event.event.start.pid),+ events=events,+ )+ except Exception as e:+ raise handle_rpc_exception(e)diff --git a/packages/python-sdk/e2b/sandbox/sync/process/process_handle.py b/packages/python-sdk/e2b/sandbox/sync/process/process_handle.pynew file mode 100644index 000000000..cda41fad4--- /dev/null+++ b/packages/python-sdk/e2b/sandbox/sync/process/process_handle.py@@ -0,0 +1,103 @@+from typing import Optional, Callable, Any, Generator, Union, Tuple++from e2b.envd.rpc import handle_rpc_exception+from e2b.envd.process import process_pb2+from e2b.sandbox.process.process_handle import (+ ProcessExitException,+ ProcessResult,+ Stderr,+ Stdout,+)+++class ProcessHandle:+ @property+ def pid(self):+ return self._pid++ def __init__(+ self,+ pid: int,+ handle_kill: Callable[[], bool],+ events: Generator[+ Union[process_pb2.StartResponse, process_pb2.ConnectResponse], Any, None+ ],+ ):+ self._pid = pid+ self._handle_kill = handle_kill+ self._events = events++ self._stdout: str = ""+ self._stderr: str = ""++ self._result: Optional[ProcessResult] = None+ self._iteration_exception: Optional[Exception] = None++ def __iter__(self):+ return self._handle_events()++ def _handle_events(+ self,+ ) -> Generator[+ Union[Tuple[Stdout, None], Tuple[None, Stderr]],+ None,+ None,+ ]:+ try:+ for event in self._events:+ if event.event.HasField("data"):+ if event.event.data.stdout:+ out = event.event.data.stdout.decode()+ self._stdout += out+ yield out, None+ if event.event.data.stderr:+ out = event.event.data.stderr.decode()+ self._stderr += out+ yield None, out+ if event.event.HasField("end"):+ self._result = ProcessResult(+ stdout=self._stdout,+ stderr=self._stderr,+ exit_code=event.event.end.exit_code,+ error=event.event.end.error,+ )+ finally:+ self.disconnect()++ def disconnect(self) -> None:+ self._events.close()++ def wait(+ self,+ on_stdout: Optional[Callable[[str], None]] = None,+ on_stderr: Optional[Callable[[str], None]] = None,+ ) -> ProcessResult:+ try:+ for stdout, stderr in self:+ if stdout is not None and on_stdout:+ on_stdout(stdout)+ elif stderr is not None and on_stderr:+ on_stderr(stderr)+ except StopIteration:+ pass+ except Exception as e:+ self._iteration_exception = handle_rpc_exception(e)++ if self._iteration_exception:+ raise self._iteration_exception++ if self._result is None:+ raise Exception("Process ended without an end event")++ if self._result.exit_code != 0:+ raise ProcessExitException(+ stdout=self._stdout,+ stderr=self._stderr,+ exit_code=self._result.exit_code,+ error=self._result.error,+ )++ return self._result++ def kill(self):+ self._handle_kill()diff --git a/packages/python-sdk/e2b/sandbox/sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sync/sandbox_api.pynew file mode 100644index 000000000..7c9a78059--- /dev/null+++ b/packages/python-sdk/e2b/sandbox/sync/sandbox_api.py@@ -0,0 +1,172 @@+from typing import Optional, Dict, List+from packaging.version import Version++from e2b.sandbox.sandbox_api import SandboxInfo+from e2b.exceptions import TemplateException+from e2b.api import ApiClient+from e2b.api.client.models import NewSandbox, PostSandboxesSandboxIDTimeoutBody+from e2b.api.client.api.sandboxes import (+ post_sandboxes_sandbox_id_timeout,+ get_sandboxes,+ delete_sandboxes_sandbox_id,+ post_sandboxes,+)+from e2b.connection_config import ConnectionConfig+from e2b.api import handle_api_exception+++class SandboxApi:+ @classmethod+ def list(+ cls,+ api_key: Optional[str] = None,+ domain: Optional[str] = None,+ debug: Optional[bool] = None,+ request_timeout: Optional[float] = None,+ ) -> List[SandboxInfo]:+ config = ConnectionConfig(+ api_key=api_key,+ domain=domain,+ debug=debug,+ request_timeout=request_timeout,+ )++ with ApiClient(config) as api_client:+ res = get_sandboxes.sync_detailed(+ client=api_client,+ )++ if res.status_code >= 300:+ raise handle_api_exception(res)++ if res.parsed is None:+ return []++ return [+ SandboxInfo(+ sandbox_id=SandboxApi._get_sandbox_id(+ sandbox.sandbox_id,+ sandbox.client_id,+ ),+ template_id=sandbox.template_id,+ name=sandbox.alias if isinstance(sandbox.alias, str) else None,+ metadata=(+ sandbox.metadata if isinstance(sandbox.metadata, dict) else None+ ),+ started_at=sandbox.started_at,+ )+ for sandbox in res.parsed+ if sandbox is not None+ ]++ @classmethod+ def _cls_kill(+ cls,+ sandbox_id: str,+ api_key: Optional[str] = None,+ domain: Optional[str] = None,+ debug: Optional[bool] = None,+ request_timeout: Optional[float] = None,+ ) -> bool:+ config = ConnectionConfig(+ api_key=api_key,+ domain=domain,+ debug=debug,+ request_timeout=request_timeout,+ )++ with ApiClient(config) as api_client:+ res = delete_sandboxes_sandbox_id.sync_detailed(+ sandbox_id,+ client=api_client,+ )++ if res.status_code == 404:+ return False++ if res.status_code >= 300:+ raise handle_api_exception(res)++ return True++ @classmethod+ def _cls_set_timeout(+ cls,+ sandbox_id: str,+ timeout: int,+ api_key: Optional[str] = None,+ domain: Optional[str] = None,+ debug: Optional[bool] = None,+ request_timeout: Optional[float] = None,+ ) -> None:+ config = ConnectionConfig(+ api_key=api_key,+ domain=domain,+ debug=debug,+ request_timeout=request_timeout,+ )++ with ApiClient(config) as api_client:+ res = post_sandboxes_sandbox_id_timeout.sync_detailed(+ sandbox_id,+ client=api_client,+ body=PostSandboxesSandboxIDTimeoutBody(timeout=timeout),+ )++ if res.status_code >= 300:+ raise handle_api_exception(res)++ @classmethod+ def _create_sandbox(+ cls,+ template: str,+ timeout: int,+ metadata: Optional[Dict[str, str]] = None,+ api_key: Optional[str] = None,+ domain: Optional[str] = None,+ debug: Optional[bool] = None,+ request_timeout: Optional[float] = None,+ ) -> str:+ config = ConnectionConfig(+ api_key=api_key,+ domain=domain,+ debug=debug,+ request_timeout=request_timeout,+ )++ with ApiClient(config) as api_client:+ res = post_sandboxes.sync_detailed(+ body=NewSandbox(+ template_id=template,+ metadata=metadata or {},+ timeout=timeout,+ ),+ client=api_client,+ )++ if res.status_code >= 300:+ raise handle_api_exception(res)++ if res.parsed is None:+ raise Exception("Body of the request is None")++ if Version(res.parsed.envd_version) < Version("0.1.0"):+ SandboxApi._cls_kill(+ SandboxApi._get_sandbox_id(+ res.parsed.sandbox_id,+ res.parsed.client_id,+ )+ )+ raise TemplateException(+ "You need to update the template to use the new SDK. "+ "You can do this by running `e2b template build` in the directory with the template."+ )++ return SandboxApi._get_sandbox_id(+ res.parsed.sandbox_id,+ res.parsed.client_id,+ )++ @staticmethod+ def _get_sandbox_id(sandbox_id: str, client_id: str) -> str:+ return f"{sandbox_id}-{client_id}"diff --git a/packages/python-sdk/poetry.lock b/packages/python-sdk/poetry.lockindex 5ded889f9..57ab875bb 100644--- a/packages/python-sdk/poetry.lock+++ b/packages/python-sdk/poetry.lock@@ -229,6 +229,92 @@ files = [{file = "iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3"},]+[[package]]+name = "jinja2"+version = "3.1.4"+description = "A very fast and expressive template engine."+optional = false+python-versions = ">=3.7"+files = [+ {file = "jinja2-3.1.4-py3-none-any.whl", hash = "sha256:bc5dd2abb727a5319567b7a813e6a2e7318c39f4f487cfe6c89c6f9c7d25197d"},+ {file = "jinja2-3.1.4.tar.gz", hash = "sha256:4a3aee7acbbe7303aede8e9648d13b8bf88a429282aa6122a993f0ac800cb369"},+]++[package.dependencies]+MarkupSafe = ">=2.0"++[package.extras]+i18n = ["Babel (>=2.7)"]++[[package]]+name = "markupsafe"+version = "2.1.5"+description = "Safely add untrusted strings to HTML/XML markup."+optional = false+python-versions = ">=3.7"+files = [+ {file = "MarkupSafe-2.1.5-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:a17a92de5231666cfbe003f0e4b9b3a7ae3afb1ec2845aadc2bacc93ff85febc"},+ {file = "MarkupSafe-2.1.5-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:72b6be590cc35924b02c78ef34b467da4ba07e4e0f0454a2c5907f473fc50ce5"},+ {file = "MarkupSafe-2.1.5-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e61659ba32cf2cf1481e575d0462554625196a1f2fc06a1c777d3f48e8865d46"},+ {file = "MarkupSafe-2.1.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2174c595a0d73a3080ca3257b40096db99799265e1c27cc5a610743acd86d62f"},+ {file = "MarkupSafe-2.1.5-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ae2ad8ae6ebee9d2d94b17fb62763125f3f374c25618198f40cbb8b525411900"},+ {file = "MarkupSafe-2.1.5-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:075202fa5b72c86ad32dc7d0b56024ebdbcf2048c0ba09f1cde31bfdd57bcfff"},+ {file = "MarkupSafe-2.1.5-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:598e3276b64aff0e7b3451b72e94fa3c238d452e7ddcd893c3ab324717456bad"},+ {file = "MarkupSafe-2.1.5-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:fce659a462a1be54d2ffcacea5e3ba2d74daa74f30f5f143fe0c58636e355fdd"},+ {file = "MarkupSafe-2.1.5-cp310-cp310-win32.whl", hash = "sha256:d9fad5155d72433c921b782e58892377c44bd6252b5af2f67f16b194987338a4"},+ {file = "MarkupSafe-2.1.5-cp310-cp310-win_amd64.whl", hash = "sha256:bf50cd79a75d181c9181df03572cdce0fbb75cc353bc350712073108cba98de5"},+ {file = "MarkupSafe-2.1.5-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:629ddd2ca402ae6dbedfceeba9c46d5f7b2a61d9749597d4307f943ef198fc1f"},+ {file = "MarkupSafe-2.1.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:5b7b716f97b52c5a14bffdf688f971b2d5ef4029127f1ad7a513973cfd818df2"},+ {file = "MarkupSafe-2.1.5-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6ec585f69cec0aa07d945b20805be741395e28ac1627333b1c5b0105962ffced"},+ {file = "MarkupSafe-2.1.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b91c037585eba9095565a3556f611e3cbfaa42ca1e865f7b8015fe5c7336d5a5"},+ {file = "MarkupSafe-2.1.5-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7502934a33b54030eaf1194c21c692a534196063db72176b0c4028e140f8f32c"},+ {file = "MarkupSafe-2.1.5-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:0e397ac966fdf721b2c528cf028494e86172b4feba51d65f81ffd65c63798f3f"},+ {file = "MarkupSafe-2.1.5-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:c061bb86a71b42465156a3ee7bd58c8c2ceacdbeb95d05a99893e08b8467359a"},+ {file = "MarkupSafe-2.1.5-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:3a57fdd7ce31c7ff06cdfbf31dafa96cc533c21e443d57f5b1ecc6cdc668ec7f"},+ {file = "MarkupSafe-2.1.5-cp311-cp311-win32.whl", hash = "sha256:397081c1a0bfb5124355710fe79478cdbeb39626492b15d399526ae53422b906"},+ {file = "MarkupSafe-2.1.5-cp311-cp311-win_amd64.whl", hash = "sha256:2b7c57a4dfc4f16f7142221afe5ba4e093e09e728ca65c51f5620c9aaeb9a617"},+ {file = "MarkupSafe-2.1.5-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:8dec4936e9c3100156f8a2dc89c4b88d5c435175ff03413b443469c7c8c5f4d1"},+ {file = "MarkupSafe-2.1.5-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:3c6b973f22eb18a789b1460b4b91bf04ae3f0c4234a0a6aa6b0a92f6f7b951d4"},+ {file = "MarkupSafe-2.1.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ac07bad82163452a6884fe8fa0963fb98c2346ba78d779ec06bd7a6262132aee"},+ {file = "MarkupSafe-2.1.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f5dfb42c4604dddc8e4305050aa6deb084540643ed5804d7455b5df8fe16f5e5"},+ {file = "MarkupSafe-2.1.5-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ea3d8a3d18833cf4304cd2fc9cbb1efe188ca9b5efef2bdac7adc20594a0e46b"},+ {file = "MarkupSafe-2.1.5-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:d050b3361367a06d752db6ead6e7edeb0009be66bc3bae0ee9d97fb326badc2a"},+ {file = "MarkupSafe-2.1.5-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:bec0a414d016ac1a18862a519e54b2fd0fc8bbfd6890376898a6c0891dd82e9f"},+ {file = "MarkupSafe-2.1.5-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:58c98fee265677f63a4385256a6d7683ab1832f3ddd1e66fe948d5880c21a169"},+ {file = "MarkupSafe-2.1.5-cp312-cp312-win32.whl", hash = "sha256:8590b4ae07a35970728874632fed7bd57b26b0102df2d2b233b6d9d82f6c62ad"},+ {file = "MarkupSafe-2.1.5-cp312-cp312-win_amd64.whl", hash = "sha256:823b65d8706e32ad2df51ed89496147a42a2a6e01c13cfb6ffb8b1e92bc910bb"},+ {file = "MarkupSafe-2.1.5-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:c8b29db45f8fe46ad280a7294f5c3ec36dbac9491f2d1c17345be8e69cc5928f"},+ {file = "MarkupSafe-2.1.5-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ec6a563cff360b50eed26f13adc43e61bc0c04d94b8be985e6fb24b81f6dcfdf"},+ {file = "MarkupSafe-2.1.5-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a549b9c31bec33820e885335b451286e2969a2d9e24879f83fe904a5ce59d70a"},+ {file = "MarkupSafe-2.1.5-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4f11aa001c540f62c6166c7726f71f7573b52c68c31f014c25cc7901deea0b52"},+ {file = "MarkupSafe-2.1.5-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:7b2e5a267c855eea6b4283940daa6e88a285f5f2a67f2220203786dfa59b37e9"},+ {file = "MarkupSafe-2.1.5-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:2d2d793e36e230fd32babe143b04cec8a8b3eb8a3122d2aceb4a371e6b09b8df"},+ {file = "MarkupSafe-2.1.5-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:ce409136744f6521e39fd8e2a24c53fa18ad67aa5bc7c2cf83645cce5b5c4e50"},+ {file = "MarkupSafe-2.1.5-cp37-cp37m-win32.whl", hash = "sha256:4096e9de5c6fdf43fb4f04c26fb114f61ef0bf2e5604b6ee3019d51b69e8c371"},+ {file = "MarkupSafe-2.1.5-cp37-cp37m-win_amd64.whl", hash = "sha256:4275d846e41ecefa46e2015117a9f491e57a71ddd59bbead77e904dc02b1bed2"},+ {file = "MarkupSafe-2.1.5-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:656f7526c69fac7f600bd1f400991cc282b417d17539a1b228617081106feb4a"},+ {file = "MarkupSafe-2.1.5-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:97cafb1f3cbcd3fd2b6fbfb99ae11cdb14deea0736fc2b0952ee177f2b813a46"},+ {file = "MarkupSafe-2.1.5-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1f3fbcb7ef1f16e48246f704ab79d79da8a46891e2da03f8783a5b6fa41a9532"},+ {file = "MarkupSafe-2.1.5-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fa9db3f79de01457b03d4f01b34cf91bc0048eb2c3846ff26f66687c2f6d16ab"},+ {file = "MarkupSafe-2.1.5-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ffee1f21e5ef0d712f9033568f8344d5da8cc2869dbd08d87c84656e6a2d2f68"},+ {file = "MarkupSafe-2.1.5-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:5dedb4db619ba5a2787a94d877bc8ffc0566f92a01c0ef214865e54ecc9ee5e0"},+ {file = "MarkupSafe-2.1.5-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:30b600cf0a7ac9234b2638fbc0fb6158ba5bdcdf46aeb631ead21248b9affbc4"},+ {file = "MarkupSafe-2.1.5-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:8dd717634f5a044f860435c1d8c16a270ddf0ef8588d4887037c5028b859b0c3"},+ {file = "MarkupSafe-2.1.5-cp38-cp38-win32.whl", hash = "sha256:daa4ee5a243f0f20d528d939d06670a298dd39b1ad5f8a72a4275124a7819eff"},+ {file = "MarkupSafe-2.1.5-cp38-cp38-win_amd64.whl", hash = "sha256:619bc166c4f2de5caa5a633b8b7326fbe98e0ccbfacabd87268a2b15ff73a029"},+ {file = "MarkupSafe-2.1.5-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:7a68b554d356a91cce1236aa7682dc01df0edba8d043fd1ce607c49dd3c1edcf"},+ {file = "MarkupSafe-2.1.5-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:db0b55e0f3cc0be60c1f19efdde9a637c32740486004f20d1cff53c3c0ece4d2"},+ {file = "MarkupSafe-2.1.5-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3e53af139f8579a6d5f7b76549125f0d94d7e630761a2111bc431fd820e163b8"},+ {file = "MarkupSafe-2.1.5-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:17b950fccb810b3293638215058e432159d2b71005c74371d784862b7e4683f3"},+ {file = "MarkupSafe-2.1.5-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4c31f53cdae6ecfa91a77820e8b151dba54ab528ba65dfd235c80b086d68a465"},+ {file = "MarkupSafe-2.1.5-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:bff1b4290a66b490a2f4719358c0cdcd9bafb6b8f061e45c7a2460866bf50c2e"},+ {file = "MarkupSafe-2.1.5-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:bc1667f8b83f48511b94671e0e441401371dfd0f0a795c7daa4a3cd1dde55bea"},+ {file = "MarkupSafe-2.1.5-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:5049256f536511ee3f7e1b3f87d1d1209d327e818e6ae1365e8653d7e3abb6a6"},+ {file = "MarkupSafe-2.1.5-cp39-cp39-win32.whl", hash = "sha256:00e046b6dd71aa03a41079792f8473dc494d564611a8f89bbbd7cb93295ebdcf"},+ {file = "MarkupSafe-2.1.5-cp39-cp39-win_amd64.whl", hash = "sha256:fa173ec60341d6bb97a89f5ea19c85c5643c1e7dedebc22f5181eb73573142c5"},+ {file = "MarkupSafe-2.1.5.tar.gz", hash = "sha256:d283d37a890ba4c1ae73ffadf8046435c76e7bc2247bbb63c00bd1a709c6544b"},+]+[[package]]name = "mypy-extensions"version = "1.0.0"@@ -445,4 +531,4 @@ files = [[metadata]lock-version = "2.0"python-versions = "^3.8"-content-hash = "e0bad63042465728305d56fa013c5e7c9c207e6d1f31630d1c137c4456ae20a6"+content-hash = "9a1a11cb738cdd20e49d4ebc519e3d57e0f9641cd1e29e4aa6faf1c25094c1bb"diff --git a/packages/python-sdk/pyproject.toml b/packages/python-sdk/pyproject.tomlindex 6e4034244..755dd2691 100644--- a/packages/python-sdk/pyproject.toml+++ b/packages/python-sdk/pyproject.toml@@ -17,6 +17,7 @@ protobuf = "^5.26.1"httpcore = "^1.0.5"httpx = "^0.27.0"attrs = "^23.2.0"+typing-extensions = "^4.12.2"[tool.poetry.group.dev.dependencies]black = "^23.7.0"@@ -24,6 +25,7 @@ pytest = "^7.4.0"pytest-xdist = "^3.3.1"python-dotenv = "^1.0.0"pytest-dotenv = "^0.5.2"+jinja2 = "^3.1.4"[build-system]requires = ["poetry-core"]