Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Ensure that httpx transport is reused across calls by default (#997)
Joseph Lombrozo98d2c8c0a80e
diff --git a/.changeset/popular-spoons-attack.md b/.changeset/popular-spoons-attack.mdnew file mode 100644index 000000000..15ddb4b7e--- /dev/null+++ b/.changeset/popular-spoons-attack.md@@ -0,0 +1,6 @@+---+"@e2b/cli": patch+"@e2b/python-sdk": patch+---++Ensure that httpx transport is reused across calls by defaultdiff --git a/.editorconfig b/.editorconfignew file mode 100644index 000000000..c29d2f85a--- /dev/null+++ b/.editorconfig@@ -0,0 +1,4 @@+root = true++[*.py]+indent_size = 4diff --git a/packages/cli/.envrc b/packages/cli/.envrcnew file mode 100644index 000000000..5241869fc--- /dev/null+++ b/packages/cli/.envrc@@ -0,0 +1,3 @@+source_up++dotenv ../../../.env.localdiff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.pyindex 713704a37..44a1cc64e 100644--- a/packages/python-sdk/e2b/api/__init__.py+++ b/packages/python-sdk/e2b/api/__init__.py@@ -1,11 +1,11 @@+import osfrom types import TracebackTypeimport jsonimport logging-from typing import Optional-from httpx import Limits+from typing import Optional, Union+from httpx import Limits, BaseTransport, AsyncBaseTransportfrom dataclasses import dataclass-from e2b.api.client.client import AuthenticatedClientfrom e2b.connection_config import ConnectionConfigfrom e2b.api.metadata import default_headers@@ -18,6 +18,12 @@ from e2b.api.client.types import Responselogger = logging.getLogger(__name__)+limits = Limits(+ max_keepalive_connections=int(os.getenv("E2B_MAX_KEEPALIVE_CONNECTIONS", "20")),+ max_connections=int(os.getenv("E2B_MAX_CONNECTIONS", "2000")),+ keepalive_expiry=int(os.getenv("E2B_KEEPALIVE_EXPIRY", "300")),+)+@dataclassclass SandboxCreateResponse:@@ -68,7 +74,7 @@ class ApiClient(AuthenticatedClient):config: ConnectionConfig,require_api_key: bool = True,require_access_token: bool = False,- limits: Optional[Limits] = None,+ transport: Optional[Union[BaseTransport, AsyncBaseTransport]] = None,*args,**kwargs,):@@ -109,7 +115,9 @@ class ApiClient(AuthenticatedClient):}# Prevent passing these parameters twice- kwargs.pop("headers", None)+ more_headers: Optional[dict] = kwargs.pop("headers", None)+ if more_headers:+ headers.update(more_headers)kwargs.pop("token", None)kwargs.pop("auth_header_name", None)kwargs.pop("prefix", None)@@ -122,7 +130,7 @@ class ApiClient(AuthenticatedClient):"response": [self._log_response],},"proxy": config.proxy,- "limits": limits,+ "transport": transport,},headers=headers,token=token,diff --git a/packages/python-sdk/e2b/api/client_async/__init__.py b/packages/python-sdk/e2b/api/client_async/__init__.pynew file mode 100644index 000000000..5d5c51c28--- /dev/null+++ b/packages/python-sdk/e2b/api/client_async/__init__.py@@ -0,0 +1,50 @@+import httpx+import logging++from typing import Optional++from typing_extensions import Self++from e2b.connection_config import ConnectionConfig+from e2b.api import limits, AsyncApiClient+++logger = logging.getLogger(__name__)+++def get_api_client(config: ConnectionConfig, **kwargs) -> AsyncApiClient:+ return AsyncApiClient(+ config,+ transport=get_transport(config),+ **kwargs,+ )+++class AsyncTransportWithLogger(httpx.AsyncHTTPTransport):+ singleton: Optional[Self] = None++ async def handle_async_request(self, request):+ url = f"{request.url.scheme}://{request.url.host}{request.url.path}"+ logger.info(f"Request: {request.method} {url}")+ response = await super().handle_async_request(request)++ # data = connect.GzipCompressor.decompress(response.read()).decode()+ logger.info(f"Response: {response.status_code} {url}")++ return response++ @property+ def pool(self):+ return self._pool+++def get_transport(config: ConnectionConfig) -> AsyncTransportWithLogger:+ if AsyncTransportWithLogger.singleton is not None:+ return AsyncTransportWithLogger.singleton++ transport = AsyncTransportWithLogger(+ limits=limits,+ proxy=config.proxy,+ )+ AsyncTransportWithLogger.singleton = transport+ return transportdiff --git a/packages/python-sdk/e2b/api/client_sync/__init__.py b/packages/python-sdk/e2b/api/client_sync/__init__.pynew file mode 100644index 000000000..029b3e4e9--- /dev/null+++ b/packages/python-sdk/e2b/api/client_sync/__init__.py@@ -0,0 +1,52 @@+from typing import Optional++import httpx+import logging++from typing_extensions import Self++from e2b.api import ApiClient, limits+from e2b.connection_config import ConnectionConfig++logger = logging.getLogger(__name__)+++def get_api_client(config: ConnectionConfig, **kwargs) -> ApiClient:+ return ApiClient(+ config,+ transport=get_transport(config),+ **kwargs,+ )+++class TransportWithLogger(httpx.HTTPTransport):+ singleton: Optional[Self] = None++ def handle_request(self, request):+ url = f"{request.url.scheme}://{request.url.host}{request.url.path}"+ logger.info(f"Request: {request.method} {url}")+ response = super().handle_request(request)++ # data = connect.GzipCompressor.decompress(response.read()).decode()+ logger.info(f"Response: {response.status_code} {url}")++ return response++ @property+ def pool(self):+ return self._pool+++_transport: Optional[TransportWithLogger] = None+++def get_transport(config: ConnectionConfig) -> TransportWithLogger:+ if TransportWithLogger.singleton is not None:+ return TransportWithLogger.singleton++ transport = TransportWithLogger(+ limits=limits,+ proxy=config.proxy,+ )+ TransportWithLogger.singleton = transport+ return transportdiff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.pyindex efc89091a..adc490859 100644--- a/packages/python-sdk/e2b/connection_config.py+++ b/packages/python-sdk/e2b/connection_config.py@@ -1,6 +1,7 @@import osfrom typing import Optional, Dict, TypedDict+from httpx._types import ProxyTypesfrom typing_extensions import Unpackdiff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.pyindex c1b028a70..6fa396042 100644--- a/packages/python-sdk/e2b/sandbox/main.py+++ b/packages/python-sdk/e2b/sandbox/main.py@@ -7,7 +7,6 @@ from e2b.sandbox.signature import get_signaturefrom e2b.connection_config import ConnectionConfig, default_usernamefrom e2b.envd.api import ENVD_API_FILES_ROUTEfrom e2b.envd.versions import ENVD_DEFAULT_USER-from httpx import Limitsclass SandboxOpts(TypedDict):@@ -20,12 +19,6 @@ class SandboxOpts(TypedDict):class SandboxBase:- _limits = Limits(- max_keepalive_connections=40,- max_connections=40,- keepalive_expiry=300,- )-mcp_port = 50005default_sandbox_timeout = 300diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.pyindex 6e514c922..1a4600817 100644--- a/packages/python-sdk/e2b/sandbox_async/main.py+++ b/packages/python-sdk/e2b/sandbox_async/main.py@@ -21,26 +21,11 @@ from e2b.sandbox_async.filesystem.filesystem import Filesystemfrom e2b.sandbox_async.commands.command import Commandsfrom e2b.sandbox_async.commands.pty import Ptyfrom e2b.sandbox_async.sandbox_api import SandboxApi, SandboxInfo+from e2b.api.client_async import get_transportlogger = logging.getLogger(__name__)-class AsyncTransportWithLogger(httpx.AsyncHTTPTransport):- async def handle_async_request(self, request):- url = f"{request.url.scheme}://{request.url.host}{request.url.path}"- logger.info(f"Request: {request.method} {url}")- response = await super().handle_async_request(request)-- # data = connect.GzipCompressor.decompress(response.read()).decode()- logger.info(f"Response: {response.status_code} {url}")-- return response-- @property- def pool(self):- return self._pool--class AsyncSandbox(SandboxApi):"""E2B cloud sandbox is a secure and isolated cloud environment.@@ -85,15 +70,16 @@ class AsyncSandbox(SandboxApi):"""return self._pty- def __init__(self, **opts: Unpack[SandboxOpts]):+ def __init__(+ self,+ **opts: Unpack[SandboxOpts],+ ):"""Use `AsyncSandbox.create()` to create a new sandbox instead."""super().__init__(**opts)- self._transport = AsyncTransportWithLogger(- limits=self._limits, proxy=self.connection_config.proxy- )+ self._transport = get_transport(self.connection_config)self._envd_api = httpx.AsyncClient(base_url=self.connection_config.get_sandbox_url(self.sandbox_id, self.sandbox_domaindiff --git a/packages/python-sdk/e2b/sandbox_async/paginator.py b/packages/python-sdk/e2b/sandbox_async/paginator.pyindex cbcf2d18a..8bfe15b2e 100644--- a/packages/python-sdk/e2b/sandbox_async/paginator.py+++ b/packages/python-sdk/e2b/sandbox_async/paginator.py@@ -4,10 +4,10 @@ from typing import Optional, Listfrom e2b.api.client.api.sandboxes import get_v2_sandboxesfrom e2b.api.client.types import UNSETfrom e2b.exceptions import SandboxException-from e2b.sandbox.main import SandboxBasefrom e2b.sandbox.sandbox_api import SandboxPaginatorBase, SandboxInfo-from e2b.api import AsyncApiClient, handle_api_exception+from e2b.api import handle_api_exceptionfrom e2b.api.client.models.error import Error+from e2b.api.client_async import get_api_clientclass AsyncSandboxPaginator(SandboxPaginatorBase):@@ -44,29 +44,26 @@ class AsyncSandboxPaginator(SandboxPaginatorBase):}metadata = urllib.parse.urlencode(quoted_metadata)- async with AsyncApiClient(- self._config,- limits=SandboxBase._limits,- ) as api_client:- res = await get_v2_sandboxes.asyncio_detailed(- client=api_client,- metadata=metadata if metadata else UNSET,- state=self.query.state if self.query and self.query.state else UNSET,- limit=self.limit if self.limit else UNSET,- next_token=self._next_token if self._next_token else UNSET,- )+ api_client = get_api_client(self._config)+ res = await get_v2_sandboxes.asyncio_detailed(+ client=api_client,+ metadata=metadata if metadata else UNSET,+ state=self.query.state if self.query and self.query.state else UNSET,+ limit=self.limit if self.limit else UNSET,+ next_token=self._next_token if self._next_token else UNSET,+ )- if res.status_code >= 300:- raise handle_api_exception(res)+ if res.status_code >= 300:+ raise handle_api_exception(res)- self._next_token = res.headers.get("x-next-token")- self._has_next = bool(self._next_token)+ self._next_token = res.headers.get("x-next-token")+ self._has_next = bool(self._next_token)- if res.parsed is None:- return []+ if res.parsed is None:+ return []- # Check if res.parse is Error- if isinstance(res.parsed, Error):- raise SandboxException(f"{res.parsed.message}: Request failed")+ # Check if res.parse is Error+ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")- return [SandboxInfo._from_listed_sandbox(sandbox) for sandbox in res.parsed]+ return [SandboxInfo._from_listed_sandbox(sandbox) for sandbox in res.parsed]diff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.pyindex 84bf11fa2..8aa92c2f5 100644--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py@@ -1,6 +1,7 @@import datetimefrom typing import Optional, Dict, List+from packaging.version import Versionfrom typing_extensions import Unpack@@ -8,13 +9,13 @@ from e2b.api.client.types import UNSETfrom e2b.sandbox.main import SandboxBasefrom e2b.sandbox.sandbox_api import SandboxInfo, SandboxMetrics, SandboxQuery, McpServerfrom e2b.exceptions import TemplateException, SandboxException, NotFoundException-from e2b.api import AsyncApiClient, SandboxCreateResponse+from e2b.api import SandboxCreateResponsefrom e2b.api.client.models import (NewSandbox,PostSandboxesSandboxIDTimeoutBody,Error,- ConnectSandbox,Sandbox,+ ConnectSandbox,)from e2b.api.client.api.sandboxes import (get_sandboxes_sandbox_id,@@ -28,6 +29,7 @@ from e2b.api.client.api.sandboxes import (from e2b.connection_config import ConnectionConfig, ApiParamsfrom e2b.api import handle_api_exceptionfrom e2b.sandbox_async.paginator import AsyncSandboxPaginator+from e2b.api.client_async import get_api_clientclass SandboxApi(SandboxBase):@@ -68,28 +70,25 @@ class SandboxApi(SandboxBase):"""config = ConnectionConfig(**opts)- async with AsyncApiClient(- config,- limits=SandboxBase._limits,- ) as api_client:- res = await get_sandboxes_sandbox_id.asyncio_detailed(- sandbox_id,- client=api_client,- )+ api_client = get_api_client(config)+ res = await get_sandboxes_sandbox_id.asyncio_detailed(+ sandbox_id,+ client=api_client,+ )- if res.status_code == 404:- raise NotFoundException(f"Sandbox {sandbox_id} not found")+ if res.status_code == 404:+ raise NotFoundException(f"Sandbox {sandbox_id} not found")- if res.status_code >= 300:- raise handle_api_exception(res)+ if res.status_code >= 300:+ raise handle_api_exception(res)- if res.parsed is None:- raise Exception("Body of the request is None")+ if res.parsed is None:+ raise Exception("Body of the request is None")- if isinstance(res.parsed, Error):- raise SandboxException(f"{res.parsed.message}: Request failed")+ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")- return SandboxInfo._from_sandbox_detail(res.parsed)+ return SandboxInfo._from_sandbox_detail(res.parsed)@classmethodasync def _cls_kill(@@ -103,22 +102,19 @@ class SandboxApi(SandboxBase):# Skip killing the sandbox in debug modereturn True- async with AsyncApiClient(- config,- limits=SandboxBase._limits,- ) as api_client:- res = await delete_sandboxes_sandbox_id.asyncio_detailed(- sandbox_id,- client=api_client,- )+ api_client = get_api_client(config)+ res = await delete_sandboxes_sandbox_id.asyncio_detailed(+ sandbox_id,+ client=api_client,+ )- if res.status_code == 404:- return False+ if res.status_code == 404:+ return False- if res.status_code >= 300:- raise handle_api_exception(res)+ if res.status_code >= 300:+ raise handle_api_exception(res)- return True+ return True@classmethodasync def _cls_set_timeout(@@ -133,21 +129,18 @@ class SandboxApi(SandboxBase):# Skip setting the timeout in debug modereturn- async with AsyncApiClient(- config,- limits=SandboxBase._limits,- ) as api_client:- res = await post_sandboxes_sandbox_id_timeout.asyncio_detailed(- sandbox_id,- client=api_client,- body=PostSandboxesSandboxIDTimeoutBody(timeout=timeout),- )+ api_client = get_api_client(config)+ res = await post_sandboxes_sandbox_id_timeout.asyncio_detailed(+ sandbox_id,+ client=api_client,+ body=PostSandboxesSandboxIDTimeoutBody(timeout=timeout),+ )- if res.status_code == 404:- raise NotFoundException(f"Paused sandbox {sandbox_id} not found")+ if res.status_code == 404:+ raise NotFoundException(f"Paused sandbox {sandbox_id} not found")- if res.status_code >= 300:- raise handle_api_exception(res)+ if res.status_code >= 300:+ raise handle_api_exception(res)@classmethodasync def _create_sandbox(@@ -164,47 +157,44 @@ class SandboxApi(SandboxBase):) -> SandboxCreateResponse:config = ConnectionConfig(**opts)- async with AsyncApiClient(- config,- limits=SandboxBase._limits,- ) as api_client:- res = await post_sandboxes.asyncio_detailed(- body=NewSandbox(- template_id=template,- auto_pause=auto_pause,- metadata=metadata or {},- timeout=timeout,- env_vars=env_vars or {},- mcp=mcp or UNSET,- secure=secure,- allow_internet_access=allow_internet_access,- ),- client=api_client,- )-- if res.status_code >= 300:- raise handle_api_exception(res)+ api_client = get_api_client(config)+ res = await post_sandboxes.asyncio_detailed(+ body=NewSandbox(+ template_id=template,+ auto_pause=auto_pause,+ metadata=metadata or {},+ timeout=timeout,+ env_vars=env_vars or {},+ mcp=mcp or UNSET,+ secure=secure,+ allow_internet_access=allow_internet_access,+ ),+ client=api_client,+ )- if res.parsed is None:- raise Exception("Body of the request is None")+ if res.status_code >= 300:+ raise handle_api_exception(res)- if isinstance(res.parsed, Error):- raise SandboxException(f"{res.parsed.message}: Request failed")+ if res.parsed is None:+ raise Exception("Body of the request is None")- if Version(res.parsed.envd_version) < Version("0.1.0"):- await SandboxApi._cls_kill(res.parsed.sandbox_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."- )+ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")- return SandboxCreateResponse(- sandbox_id=res.parsed.sandbox_id,- sandbox_domain=res.parsed.domain,- envd_version=res.parsed.envd_version,- envd_access_token=res.parsed.envd_access_token,+ if Version(res.parsed.envd_version) < Version("0.1.0"):+ await SandboxApi._cls_kill(res.parsed.sandbox_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 SandboxCreateResponse(+ sandbox_id=res.parsed.sandbox_id,+ sandbox_domain=res.parsed.domain,+ envd_version=res.parsed.envd_version,+ envd_access_token=res.parsed.envd_access_token,+ )+@classmethodasync def _cls_get_metrics(cls,@@ -228,40 +218,37 @@ class SandboxApi(SandboxBase):# Skip getting the metrics in debug modereturn []- async with AsyncApiClient(- config,- limits=SandboxBase._limits,- ) as api_client:- res = await get_sandboxes_sandbox_id_metrics.asyncio_detailed(- sandbox_id,- start=int(start.timestamp() * 1000) if start else UNSET,- end=int(end.timestamp() * 1000) if end else UNSET,- client=api_client,- )+ api_client = get_api_client(config)+ res = await get_sandboxes_sandbox_id_metrics.asyncio_detailed(+ sandbox_id,+ start=int(start.timestamp() * 1000) if start else UNSET,+ end=int(end.timestamp() * 1000) if end else UNSET,+ client=api_client,+ )- if res.status_code >= 300:- raise handle_api_exception(res)-- if res.parsed is None:- return []-- # Check if res.parse is Error- if isinstance(res.parsed, Error):- raise SandboxException(f"{res.parsed.message}: Request failed")-- # Convert to typed SandboxMetrics objects- return [- SandboxMetrics(- cpu_count=metric.cpu_count,- cpu_used_pct=metric.cpu_used_pct,- disk_total=metric.disk_total,- disk_used=metric.disk_used,- mem_total=metric.mem_total,- mem_used=metric.mem_used,- timestamp=metric.timestamp,- )- for metric in res.parsed- ]+ if res.status_code >= 300:+ raise handle_api_exception(res)++ if res.parsed is None:+ return []++ # Check if res.parse is Error+ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")++ # Convert to typed SandboxMetrics objects+ return [+ SandboxMetrics(+ cpu_count=metric.cpu_count,+ cpu_used_pct=metric.cpu_used_pct,+ disk_total=metric.disk_total,+ disk_used=metric.disk_used,+ mem_total=metric.mem_total,+ mem_used=metric.mem_used,+ timestamp=metric.timestamp,+ )+ for metric in res.parsed+ ]@classmethodasync def _cls_pause(@@ -271,29 +258,26 @@ class SandboxApi(SandboxBase):) -> str:config = ConnectionConfig(**opts)- async with AsyncApiClient(- config,- limits=SandboxBase._limits,- ) as api_client:- res = await post_sandboxes_sandbox_id_pause.asyncio_detailed(- sandbox_id,- client=api_client,- )+ api_client = get_api_client(config)+ res = await post_sandboxes_sandbox_id_pause.asyncio_detailed(+ sandbox_id,+ client=api_client,+ )- if res.status_code == 404:- raise NotFoundException(f"Sandbox {sandbox_id} not found")+ if res.status_code == 404:+ raise NotFoundException(f"Sandbox {sandbox_id} not found")- if res.status_code == 409:- return sandbox_id+ if res.status_code == 409:+ return sandbox_id- if res.status_code >= 300:- raise handle_api_exception(res)+ if res.status_code >= 300:+ raise handle_api_exception(res)- # Check if res.parse is Error- if isinstance(res.parsed, Error):- raise SandboxException(f"{res.parsed.message}: Request failed")+ # Check if res.parse is Error+ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")- return sandbox_id+ return sandbox_id@classmethodasync def _cls_connect(@@ -307,28 +291,27 @@ class SandboxApi(SandboxBase):# Sandbox is not running, resume itconfig = ConnectionConfig(**opts)- async with AsyncApiClient(+ api_client = get_api_client(config,- limits=SandboxBase._limits,headers={"E2b-Sandbox-Id": sandbox_id,- "E2b-Sandbox-Port": config.envd_port,+ "E2b-Sandbox-Port": str(config.envd_port),},- ) as api_client:- res = await post_sandboxes_sandbox_id_connect.asyncio_detailed(- sandbox_id,- client=api_client,- body=ConnectSandbox(timeout=timeout),- )+ )+ res = await post_sandboxes_sandbox_id_connect.asyncio_detailed(+ sandbox_id,+ client=api_client,+ body=ConnectSandbox(timeout=timeout),+ )- if res.status_code == 404:- raise NotFoundException(f"Paused sandbox {sandbox_id} not found")+ if res.status_code == 404:+ raise NotFoundException(f"Paused sandbox {sandbox_id} not found")- if res.status_code >= 300:- raise handle_api_exception(res)+ if res.status_code >= 300:+ raise handle_api_exception(res)- # Check if res.parse is Error- if isinstance(res.parsed, Error):- raise SandboxException(f"{res.parsed.message}: Request failed")+ # Check if res.parse is Error+ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")- return res.parsed+ return res.parseddiff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.pyindex 1e82a4bca..78be6052f 100644--- a/packages/python-sdk/e2b/sandbox_sync/main.py+++ b/packages/python-sdk/e2b/sandbox_sync/main.py@@ -22,26 +22,11 @@ from e2b.sandbox_sync.filesystem.filesystem import Filesystemfrom e2b.sandbox_sync.commands.command import Commandsfrom e2b.sandbox_sync.commands.pty import Ptyfrom e2b.sandbox_sync.sandbox_api import SandboxApi, SandboxInfo+from e2b.api.client_sync import get_transportlogger = logging.getLogger(__name__)-class TransportWithLogger(httpx.HTTPTransport):- def handle_request(self, request):- url = f"{request.url.scheme}://{request.url.host}{request.url.path}"- logger.info(f"Request: {request.method} {url}")- response = super().handle_request(request)-- # data = connect.GzipCompressor.decompress(response.read()).decode()- logger.info(f"Response: {response.status_code} {url}")-- return response-- @property- def pool(self):- return self._pool--class Sandbox(SandboxApi):"""E2B cloud sandbox is a secure and isolated cloud environment.@@ -94,9 +79,8 @@ class Sandbox(SandboxApi):"""super().__init__(**opts)- self._transport = TransportWithLogger(- limits=self._limits, proxy=self.connection_config.proxy- )+ self._transport = get_transport(self.connection_config)+self._envd_api = httpx.Client(base_url=self.envd_api_url,transport=self._transport,diff --git a/packages/python-sdk/e2b/sandbox_sync/paginator.py b/packages/python-sdk/e2b/sandbox_sync/paginator.pyindex 9b4c60b25..89e3eb5c5 100644--- a/packages/python-sdk/e2b/sandbox_sync/paginator.py+++ b/packages/python-sdk/e2b/sandbox_sync/paginator.py@@ -1,13 +1,13 @@import urllib.parsefrom typing import Optional, List+from e2b.api import handle_api_exceptionfrom e2b.api.client.api.sandboxes import get_v2_sandboxes+from e2b.api.client.models.error import Errorfrom e2b.api.client.types import UNSETfrom e2b.exceptions import SandboxException-from e2b.sandbox.main import SandboxBasefrom e2b.sandbox.sandbox_api import SandboxPaginatorBase, SandboxInfo-from e2b.api import handle_api_exception, ApiClient-from e2b.api.client.models.error import Error+from e2b.api.client_sync import get_api_clientclass SandboxPaginator(SandboxPaginatorBase):@@ -44,29 +44,26 @@ class SandboxPaginator(SandboxPaginatorBase):}metadata = urllib.parse.urlencode(quoted_metadata)- with ApiClient(- self._config,- limits=SandboxBase._limits,- ) as api_client:- res = get_v2_sandboxes.sync_detailed(- client=api_client,- metadata=metadata if metadata else UNSET,- state=self.query.state if self.query and self.query.state else UNSET,- limit=self.limit if self.limit else UNSET,- next_token=self._next_token if self._next_token else UNSET,- )+ api_client = get_api_client(self._config)+ res = get_v2_sandboxes.sync_detailed(+ client=api_client,+ metadata=metadata if metadata else UNSET,+ state=self.query.state if self.query and self.query.state else UNSET,+ limit=self.limit if self.limit else UNSET,+ next_token=self._next_token if self._next_token else UNSET,+ )- if res.status_code >= 300:- raise handle_api_exception(res)+ if res.status_code >= 300:+ raise handle_api_exception(res)- self._next_token = res.headers.get("x-next-token")- self._has_next = bool(self._next_token)+ self._next_token = res.headers.get("x-next-token")+ self._has_next = bool(self._next_token)- if res.parsed is None:- return []+ if res.parsed is None:+ return []- # Check if res.parse is Error- if isinstance(res.parsed, Error):- raise SandboxException(f"{res.parsed.message}: Request failed")+ # Check if res.parse is Error+ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")- return [SandboxInfo._from_listed_sandbox(sandbox) for sandbox in res.parsed]+ return [SandboxInfo._from_listed_sandbox(sandbox) for sandbox in res.parsed]diff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.pyindex 1600e19dc..269d72581 100644--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py@@ -1,20 +1,13 @@import datetime-from typing import Optional, Dict, List-from e2b.api.client.types import UNSET+from packaging.version import Versionfrom typing_extensions import Unpack-from e2b.sandbox.sandbox_api import SandboxInfo, SandboxMetrics, SandboxQuery, McpServer-from e2b.sandbox.main import SandboxBase-from e2b.exceptions import TemplateException, SandboxException, NotFoundException-from e2b.api import ApiClient, SandboxCreateResponse+from e2b.api import SandboxCreateResponse, handle_api_exceptionfrom e2b.api.client.models import (- NewSandbox,- PostSandboxesSandboxIDTimeoutBody,- Error,- ConnectSandbox,Sandbox,+ ConnectSandbox,)from e2b.api.client.api.sandboxes import (get_sandboxes_sandbox_id,@@ -22,12 +15,20 @@ from e2b.api.client.api.sandboxes import (delete_sandboxes_sandbox_id,post_sandboxes,get_sandboxes_sandbox_id_metrics,- post_sandboxes_sandbox_id_connect,post_sandboxes_sandbox_id_pause,+ post_sandboxes_sandbox_id_connect,)+from e2b.api.client.models import (+ NewSandbox,+ PostSandboxesSandboxIDTimeoutBody,+ Error,+)+from e2b.api.client.types import UNSETfrom e2b.connection_config import ConnectionConfig, ApiParams-from e2b.api import handle_api_exception-from e2b.sandbox_sync.paginator import SandboxPaginator+from e2b.exceptions import TemplateException, SandboxException, NotFoundException+from e2b.sandbox.main import SandboxBase+from e2b.sandbox.sandbox_api import SandboxInfo, SandboxMetrics, SandboxQuery, McpServer+from e2b.sandbox_sync.paginator import SandboxPaginator, get_api_clientclass SandboxApi(SandboxBase):@@ -68,28 +69,25 @@ class SandboxApi(SandboxBase):"""config = ConnectionConfig(**opts)- with ApiClient(- config,- limits=SandboxBase._limits,- ) as api_client:- res = get_sandboxes_sandbox_id.sync_detailed(- sandbox_id,- client=api_client,- )+ api_client = get_api_client(config)+ res = get_sandboxes_sandbox_id.sync_detailed(+ sandbox_id,+ client=api_client,+ )- if res.status_code == 404:- raise NotFoundException(f"Sandbox {sandbox_id} not found")+ if res.status_code == 404:+ raise NotFoundException(f"Sandbox {sandbox_id} not found")- if res.status_code >= 300:- raise handle_api_exception(res)+ if res.status_code >= 300:+ raise handle_api_exception(res)- if res.parsed is None:- raise SandboxException("Body of the request is None")+ if res.parsed is None:+ raise SandboxException("Body of the request is None")- if isinstance(res.parsed, Error):- raise SandboxException(f"{res.parsed.message}: Request failed")+ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")- return SandboxInfo._from_sandbox_detail(res.parsed)+ return SandboxInfo._from_sandbox_detail(res.parsed)@classmethoddef _cls_kill(@@ -103,22 +101,19 @@ class SandboxApi(SandboxBase):# Skip killing the sandbox in debug modereturn True- with ApiClient(- config,- limits=SandboxBase._limits,- ) as api_client:- res = delete_sandboxes_sandbox_id.sync_detailed(- sandbox_id,- client=api_client,- )+ api_client = get_api_client(config)+ res = delete_sandboxes_sandbox_id.sync_detailed(+ sandbox_id,+ client=api_client,+ )- if res.status_code == 404:- return False+ if res.status_code == 404:+ return False- if res.status_code >= 300:- raise handle_api_exception(res)+ if res.status_code >= 300:+ raise handle_api_exception(res)- return True+ return True@classmethoddef _cls_set_timeout(@@ -133,21 +128,18 @@ class SandboxApi(SandboxBase):# Skip setting timeout in debug modereturn- with ApiClient(- config,- limits=SandboxBase._limits,- ) as api_client:- res = post_sandboxes_sandbox_id_timeout.sync_detailed(- sandbox_id,- client=api_client,- body=PostSandboxesSandboxIDTimeoutBody(timeout=timeout),- )+ api_client = get_api_client(config)+ res = post_sandboxes_sandbox_id_timeout.sync_detailed(+ sandbox_id,+ client=api_client,+ body=PostSandboxesSandboxIDTimeoutBody(timeout=timeout),+ )- if res.status_code == 404:- raise NotFoundException(f"Sandbox {sandbox_id} not found")+ if res.status_code == 404:+ raise NotFoundException(f"Sandbox {sandbox_id} not found")- if res.status_code >= 300:- raise handle_api_exception(res)+ if res.status_code >= 300:+ raise handle_api_exception(res)@classmethoddef _create_sandbox(@@ -164,44 +156,44 @@ class SandboxApi(SandboxBase):) -> SandboxCreateResponse:config = ConnectionConfig(**opts)- with ApiClient(config, limits=SandboxBase._limits) as api_client:- res = post_sandboxes.sync_detailed(- body=NewSandbox(- template_id=template,- auto_pause=auto_pause,- metadata=metadata or {},- timeout=timeout,- env_vars=env_vars or {},- mcp=mcp or UNSET,- secure=secure,- allow_internet_access=allow_internet_access,- ),- client=api_client,- )-- if res.status_code >= 300:- raise handle_api_exception(res)+ api_client = get_api_client(config)+ res = post_sandboxes.sync_detailed(+ body=NewSandbox(+ template_id=template,+ auto_pause=auto_pause,+ metadata=metadata or {},+ timeout=timeout,+ env_vars=env_vars or {},+ mcp=mcp or UNSET,+ secure=secure,+ allow_internet_access=allow_internet_access,+ ),+ client=api_client,+ )- if res.parsed is None:- raise Exception("Body of the request is None")+ if res.status_code >= 300:+ raise handle_api_exception(res)- if isinstance(res.parsed, Error):- raise SandboxException(f"{res.parsed.message}: Request failed")+ 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(res.parsed.sandbox_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."- )+ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")- return SandboxCreateResponse(- sandbox_id=res.parsed.sandbox_id,- sandbox_domain=res.parsed.domain,- envd_version=res.parsed.envd_version,- envd_access_token=res.parsed.envd_access_token,+ if Version(res.parsed.envd_version) < Version("0.1.0"):+ SandboxApi._cls_kill(res.parsed.sandbox_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 SandboxCreateResponse(+ sandbox_id=res.parsed.sandbox_id,+ sandbox_domain=res.parsed.domain,+ envd_version=res.parsed.envd_version,+ envd_access_token=res.parsed.envd_access_token,+ )+@classmethoddef _cls_get_metrics(cls,@@ -216,39 +208,36 @@ class SandboxApi(SandboxBase):# Skip getting the metrics in debug modereturn []- with ApiClient(- config,- limits=SandboxBase._limits,- ) as api_client:- res = get_sandboxes_sandbox_id_metrics.sync_detailed(- sandbox_id,- start=int(start.timestamp() * 1000) if start else None,- end=int(end.timestamp() * 1000) if end else None,- client=api_client,- )+ api_client = get_api_client(config)+ res = get_sandboxes_sandbox_id_metrics.sync_detailed(+ sandbox_id,+ start=int(start.timestamp() * 1000) if start else None,+ end=int(end.timestamp() * 1000) if end else None,+ client=api_client,+ )++ if res.status_code >= 300:+ raise handle_api_exception(res)- if res.status_code >= 300:- raise handle_api_exception(res)-- if res.parsed is None:- return []-- if isinstance(res.parsed, Error):- raise SandboxException(f"{res.parsed.message}: Request failed")-- # Convert to typed SandboxMetrics objects- return [- SandboxMetrics(- cpu_count=metric.cpu_count,- cpu_used_pct=metric.cpu_used_pct,- disk_total=metric.disk_total,- disk_used=metric.disk_used,- mem_total=metric.mem_total,- mem_used=metric.mem_used,- timestamp=metric.timestamp,- )- for metric in res.parsed- ]+ if res.parsed is None:+ return []++ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")++ # Convert to typed SandboxMetrics objects+ return [+ SandboxMetrics(+ cpu_count=metric.cpu_count,+ cpu_used_pct=metric.cpu_used_pct,+ disk_total=metric.disk_total,+ disk_used=metric.disk_used,+ mem_total=metric.mem_total,+ mem_used=metric.mem_used,+ timestamp=metric.timestamp,+ )+ for metric in res.parsed+ ]@classmethoddef _cls_connect(@@ -261,30 +250,29 @@ class SandboxApi(SandboxBase):config = ConnectionConfig(**opts)- with ApiClient(+ api_client = get_api_client(config,- limits=SandboxBase._limits,headers={"E2b-Sandbox-Id": sandbox_id,- "E2b-Sandbox-Port": config.envd_port,+ "E2b-Sandbox-Port": str(config.envd_port),},- ) as api_client:- res = post_sandboxes_sandbox_id_connect.sync_detailed(- sandbox_id,- client=api_client,- body=ConnectSandbox(timeout=timeout),- )+ )+ res = post_sandboxes_sandbox_id_connect.sync_detailed(+ sandbox_id,+ client=api_client,+ body=ConnectSandbox(timeout=timeout),+ )- if res.status_code == 404:- raise NotFoundException(f"Paused sandbox {sandbox_id} not found")+ if res.status_code == 404:+ raise NotFoundException(f"Paused sandbox {sandbox_id} not found")- if res.status_code >= 300:- raise handle_api_exception(res)+ if res.status_code >= 300:+ raise handle_api_exception(res)- if isinstance(res.parsed, Error):- raise SandboxException(f"{res.parsed.message}: Request failed")+ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")- return res.parsed+ return res.parsed@classmethoddef _cls_pause(@@ -294,22 +282,19 @@ class SandboxApi(SandboxBase):) -> str:config = ConnectionConfig(**opts)- with ApiClient(- config,- limits=SandboxBase._limits,- ) as api_client:- res = post_sandboxes_sandbox_id_pause.sync_detailed(- sandbox_id,- client=api_client,- )+ api_client = get_api_client(config)+ res = post_sandboxes_sandbox_id_pause.sync_detailed(+ sandbox_id,+ client=api_client,+ )- if res.status_code == 404:- raise NotFoundException(f"Sandbox {sandbox_id} not found")+ if res.status_code == 404:+ raise NotFoundException(f"Sandbox {sandbox_id} not found")- if res.status_code == 409:- return sandbox_id+ if res.status_code == 409:+ return sandbox_id- if res.status_code >= 300:- raise handle_api_exception(res)+ if res.status_code >= 300:+ raise handle_api_exception(res)return sandbox_iddiff --git a/packages/python-sdk/e2b/template/main.py b/packages/python-sdk/e2b/template/main.pyindex 72bada15b..040525a6c 100644--- a/packages/python-sdk/e2b/template/main.py+++ b/packages/python-sdk/e2b/template/main.py@@ -2,7 +2,6 @@ import jsonfrom typing import Dict, List, Optional, Union, Literalfrom pathlib import Path-from httpx import Limitsfrom e2b.exceptions import BuildExceptionfrom e2b.template.consts import STACK_TRACE_DEPTH, RESOLVE_SYMLINKS@@ -762,11 +761,6 @@ class TemplateBase:Base class for building E2B sandbox templates."""- _limits = Limits(- max_keepalive_connections=40,- max_connections=40,- keepalive_expiry=300,- )_logs_refresh_frequency = 0.2def __init__(diff --git a/packages/python-sdk/e2b/template_async/build_api.py b/packages/python-sdk/e2b/template_async/build_api.pyindex 76a5774ab..13ff984d8 100644--- a/packages/python-sdk/e2b/template_async/build_api.py+++ b/packages/python-sdk/e2b/template_async/build_api.py@@ -78,6 +78,7 @@ async def get_file_upload_link(async def upload_file(+ api_client: AuthenticatedClient,file_name: str,context_path: str,url: str,@@ -89,9 +90,10 @@ async def upload_file(tar_buffer = tar_file_stream(file_name, context_path, ignore_patterns, resolve_symlinks)- async with httpx.AsyncClient() as client:- response = await client.put(url, content=tar_buffer.getvalue())- response.raise_for_status()++ client = api_client.get_async_httpx_client()+ response = await client.put(url, content=tar_buffer.getvalue())+ response.raise_for_status()except httpx.HTTPStatusError as e:raise FileUploadException(f"Failed to upload file: {e}").with_traceback(stack_tracediff --git a/packages/python-sdk/e2b/template_async/main.py b/packages/python-sdk/e2b/template_async/main.pyindex e9b7313d3..809d0d804 100644--- a/packages/python-sdk/e2b/template_async/main.py+++ b/packages/python-sdk/e2b/template_async/main.py@@ -2,7 +2,6 @@ import osfrom datetime import datetimefrom typing import Callable, Optional-from e2b.api import AsyncApiClientfrom e2b.api.client.client import AuthenticatedClientfrom e2b.connection_config import ConnectionConfigfrom e2b.template.consts import RESOLVE_SYMLINKS@@ -18,6 +17,7 @@ from .build_api import (upload_file,wait_for_build_finish,)+from e2b.api.client_async import get_api_clientclass AsyncTemplate(TemplateBase):@@ -106,6 +106,7 @@ class AsyncTemplate(TemplateBase):file_info.present is False and file_info.url):await upload_file(+ api_client,src,template._template._file_context_path,file_info.url,@@ -221,43 +222,41 @@ class AsyncTemplate(TemplateBase):config = ConnectionConfig(domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY"))- client = AsyncApiClient(+ api_client = get_api_client(config,require_api_key=True,require_access_token=False,- limits=TemplateBase._limits,)- with client as api_client:- data = await AsyncTemplate._build(- template,- api_client,- alias,- cpu_count,- memory_mb,- skip_cache,- on_build_logs,- )+ data = await AsyncTemplate._build(+ template,+ api_client,+ alias,+ cpu_count,+ memory_mb,+ skip_cache,+ on_build_logs,+ )- if on_build_logs:- on_build_logs(- LogEntry(- timestamp=datetime.now(),- level="info",- message="Waiting for logs...",- )+ if on_build_logs:+ on_build_logs(+ LogEntry(+ timestamp=datetime.now(),+ level="info",+ message="Waiting for logs...",)-- await wait_for_build_finish(- api_client,- data.template_id,- data.build_id,- on_build_logs,- logs_refresh_frequency=TemplateBase._logs_refresh_frequency,- stack_traces=template._template._stack_traces,)- return data+ await wait_for_build_finish(+ api_client,+ data.template_id,+ data.build_id,+ on_build_logs,+ logs_refresh_frequency=TemplateBase._logs_refresh_frequency,+ stack_traces=template._template._stack_traces,+ )++ return datafinally:if on_build_logs:on_build_logs(@@ -313,23 +312,21 @@ class AsyncTemplate(TemplateBase):config = ConnectionConfig(domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY"))- client = AsyncApiClient(+ api_client = get_api_client(config,require_api_key=True,require_access_token=False,- limits=TemplateBase._limits,)- with client as api_client:- return await AsyncTemplate._build(- template,- api_client,- alias,- cpu_count,- memory_mb,- skip_cache,- on_build_logs,- )+ return await AsyncTemplate._build(+ template,+ api_client,+ alias,+ cpu_count,+ memory_mb,+ skip_cache,+ on_build_logs,+ )@staticmethodasync def get_build_status(@@ -359,17 +356,10 @@ class AsyncTemplate(TemplateBase):config = ConnectionConfig(domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY"))- client = AsyncApiClient(- config,- require_api_key=True,- require_access_token=False,- limits=TemplateBase._limits,+ api_client = get_api_client(config)+ return await get_build_status(+ api_client,+ build_info.template_id,+ build_info.build_id,+ logs_offset,)-- with client as api_client:- return await get_build_status(- api_client,- build_info.template_id,- build_info.build_id,- logs_offset,- )diff --git a/packages/python-sdk/e2b/template_sync/build_api.py b/packages/python-sdk/e2b/template_sync/build_api.pyindex 116a1c922..392737cd4 100644--- a/packages/python-sdk/e2b/template_sync/build_api.py+++ b/packages/python-sdk/e2b/template_sync/build_api.py@@ -78,6 +78,7 @@ def get_file_upload_link(def upload_file(+ api_client: AuthenticatedClient,file_name: str,context_path: str,url: str,@@ -89,9 +90,9 @@ def upload_file(tar_buffer = tar_file_stream(file_name, context_path, ignore_patterns, resolve_symlinks)- with httpx.Client() as client:- response = client.put(url, content=tar_buffer.getvalue())- response.raise_for_status()+ client = api_client.get_httpx_client()+ response = client.put(url, content=tar_buffer.getvalue())+ response.raise_for_status()except httpx.HTTPStatusError as e:raise FileUploadException(f"Failed to upload file: {e}").with_traceback(stack_tracediff --git a/packages/python-sdk/e2b/template_sync/main.py b/packages/python-sdk/e2b/template_sync/main.pyindex 77aa01e28..fe41afdfd 100644--- a/packages/python-sdk/e2b/template_sync/main.py+++ b/packages/python-sdk/e2b/template_sync/main.py@@ -2,9 +2,10 @@ import osfrom datetime import datetimefrom typing import Callable, Optional-from e2b.api import ApiClientfrom e2b.api.client.client import AuthenticatedClientfrom e2b.connection_config import ConnectionConfig++from e2b.api.client_sync import get_api_clientfrom e2b.template.consts import RESOLVE_SYMLINKSfrom e2b.template.logger import LogEntry, LogEntryEnd, LogEntryStartfrom e2b.template.main import TemplateBase, TemplateClass@@ -106,6 +107,7 @@ class Template(TemplateBase):file_info.present is False and file_info.url):upload_file(+ api_client,src,template._template._file_context_path,file_info.url,@@ -221,43 +223,41 @@ class Template(TemplateBase):config = ConnectionConfig(domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY"))- client = ApiClient(+ api_client = get_api_client(config,require_api_key=True,require_access_token=False,- limits=TemplateBase._limits,)- with client as api_client:- data = Template._build(- template,- api_client,- alias,- cpu_count,- memory_mb,- skip_cache,- on_build_logs,- )+ data = Template._build(+ template,+ api_client,+ alias,+ cpu_count,+ memory_mb,+ skip_cache,+ on_build_logs,+ )- if on_build_logs:- on_build_logs(- LogEntry(- timestamp=datetime.now(),- level="info",- message="Waiting for logs...",- )+ if on_build_logs:+ on_build_logs(+ LogEntry(+ timestamp=datetime.now(),+ level="info",+ message="Waiting for logs...",)-- wait_for_build_finish(- api_client,- data.template_id,- data.build_id,- on_build_logs,- logs_refresh_frequency=TemplateBase._logs_refresh_frequency,- stack_traces=template._template._stack_traces,)- return data+ wait_for_build_finish(+ api_client,+ data.template_id,+ data.build_id,+ on_build_logs,+ logs_refresh_frequency=TemplateBase._logs_refresh_frequency,+ stack_traces=template._template._stack_traces,+ )++ return datafinally:if on_build_logs:on_build_logs(@@ -313,23 +313,21 @@ class Template(TemplateBase):config = ConnectionConfig(domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY"))- client = ApiClient(+ api_client = get_api_client(config,require_api_key=True,require_access_token=False,- limits=TemplateBase._limits,)- with client as api_client:- return Template._build(- template,- api_client,- alias,- cpu_count,- memory_mb,- skip_cache,- on_build_logs,- )+ return Template._build(+ template,+ api_client,+ alias,+ cpu_count,+ memory_mb,+ skip_cache,+ on_build_logs,+ )@staticmethoddef get_build_status(@@ -359,17 +357,15 @@ class Template(TemplateBase):config = ConnectionConfig(domain=domain, api_key=api_key or os.environ.get("E2B_API_KEY"))- client = ApiClient(+ api_client = get_api_client(config,require_api_key=True,require_access_token=False,- limits=TemplateBase._limits,)- with client as api_client:- return get_build_status(- api_client,- build_info.template_id,- build_info.build_id,- logs_offset,- )+ return get_build_status(+ api_client,+ build_info.template_id,+ build_info.build_id,+ logs_offset,+ )diff --git a/packages/python-sdk/e2b_connect/client.py b/packages/python-sdk/e2b_connect/client.pyindex 034a8478d..55587fa64 100644--- a/packages/python-sdk/e2b_connect/client.py+++ b/packages/python-sdk/e2b_connect/client.py@@ -1,6 +1,8 @@import gzip+import inspectimport jsonimport struct+import typingfrom httpcore import (ConnectionPool,@@ -11,7 +13,6 @@ from httpcore import (from enum import Flag, Enumfrom typing import Callable, Optional, Dict, Any, Generator, Tuplefrom google.protobuf import json_format-from httpcore import URLclass EnvelopeFlags(Flag):@@ -106,6 +107,42 @@ def make_error(error):return ConnectException(status, error.get("message", ""))+def _sync_retry(func, exc, retries):+ def retry(*args, **kwargs):+ for _ in range(retries):+ try:+ return func(*args, **kwargs)+ except exc:+ continue++ return func(*args, **kwargs)++ return retry+++def _async_retry(func, exc, retries):+ async def retry(*args, **kwargs):+ for _ in range(retries):+ try:+ return await func(*args, **kwargs)+ except exc:+ continue++ return await func(*args, **kwargs)++ return retry+++def _retry(exc: typing.Type[Exception], retries: int):+ def decorator(func):+ if inspect.iscoroutinefunction(func):+ return _async_retry(func, exc, retries)++ return _sync_retry(func, exc, retries)++ return decorator++class GzipCompressor:name = "gzip"decompress = gzip.decompress@@ -168,14 +205,17 @@ class Client:self,req,request_timeout=None,- headers={},+ headers: Optional[dict] = None,**opts,- ):+ ) -> dict:data = self._codec.encode(req)if self._compressor is not None:data = self._compressor.compress(data)+ if headers is None:+ headers = {}+extensions = (Noneif request_timeout is None@@ -223,11 +263,12 @@ class Client:msg_type=self._response_type,)+ @_retry(RemoteProtocolError, 3)async def acall_unary(self,req,request_timeout=None,- headers={},+ headers: Optional[dict] = None,**opts,):if self.async_pool is None:@@ -240,20 +281,17 @@ class Client:**opts,)- conn = self.async_pool-- for _ in range(self._connection_retries):- try:- res = await conn.request(**req_data)- return self._process_unary_response(res)- except RemoteProtocolError:- conn = self.async_pool.create_connection(URL(req_data["url"]).origin)-- continue- except:- raise+ res = await self.async_pool.request(**req_data)+ return self._process_unary_response(res)- def call_unary(self, req, request_timeout=None, headers={}, **opts):+ @_retry(RemoteProtocolError, 3)+ def call_unary(+ self,+ req,+ request_timeout=None,+ headers: Optional[dict] = None,+ **opts,+ ):if self.pool is None:raise ValueError("pool is required")@@ -264,18 +302,8 @@ class Client:**opts,)- conn = self.pool-- for _ in range(self._connection_retries):- try:- res = conn.request(**req_data)- return self._process_unary_response(res)- except RemoteProtocolError:- conn = self.pool.create_connection(URL(req_data["url"]).origin)-- continue- except:- raise+ res = self.pool.request(**req_data)+ return self._process_unary_response(res)def _create_stream_timeout(self, timeout: Optional[int]):if timeout:@@ -287,9 +315,9 @@ class Client:req,request_timeout=None,timeout=None,- headers=None,+ headers: Optional[dict] = None,**opts,- ):+ ) -> dict:headers = headers or {}data = self._codec.encode(req)flags = EnvelopeFlags(0)@@ -327,12 +355,13 @@ class Client:},}+ @_retry(RemoteProtocolError, 3)async def acall_server_stream(self,req,request_timeout=None,timeout=None,- headers={},+ headers: Optional[dict] = None,**opts,):if self.async_pool is None:@@ -346,38 +375,27 @@ class Client:**opts,)- conn = self.async_pool-- for _ in range(self._connection_retries):- try:- async with conn.stream(**req_data) as http_resp:- if http_resp.status != 200:- await http_resp.aread()- raise error_for_response(http_resp)-- parser = ServerStreamParser(- decode=self._codec.decode,- response_type=self._response_type,- )-- async for chunk in http_resp.aiter_stream():- for chunk in parser.parse(chunk):- yield chunk+ parser = ServerStreamParser(+ decode=self._codec.decode,+ response_type=self._response_type,+ )- return- except RemoteProtocolError:- conn = self.async_pool.create_connection(URL(req_data["url"]).origin)+ async with self.async_pool.stream(**req_data) as http_resp:+ if http_resp.status != 200:+ await http_resp.aread()+ raise error_for_response(http_resp)- continue- except:- raise+ async for chunk in http_resp.aiter_stream():+ for parsed in parser.parse(chunk):+ yield parsed+ @_retry(RemoteProtocolError, 3)def call_server_stream(self,req,request_timeout=None,timeout=None,- headers={},+ headers: Optional[dict] = None,**opts,):if self.pool is None:@@ -391,30 +409,19 @@ class Client:**opts,)- conn = self.pool-- for _ in range(self._connection_retries):- try:- with conn.stream(**req_data) as http_resp:- if http_resp.status != 200:- http_resp.read()- raise error_for_response(http_resp)-- parser = ServerStreamParser(- decode=self._codec.decode,- response_type=self._response_type,- )-- for chunk in http_resp.iter_stream():- yield from parser.parse(chunk)+ parser = ServerStreamParser(+ decode=self._codec.decode,+ response_type=self._response_type,+ )- return- except RemoteProtocolError:- conn = self.pool.create_connection(URL(req_data["url"]).origin)+ with self.pool.stream(**req_data) as http_resp:+ if http_resp.status != 200:+ http_resp.read()+ raise error_for_response(http_resp)- continue- except:- raise+ for chunk in http_resp.iter_stream():+ for parsed in parser.parse(chunk):+ yield parseddef call_client_stream(self, req, **opts):raise NotImplementedError("client stream not supported")diff --git a/packages/python-sdk/tests/async/api_async/test_sbx_list.py b/packages/python-sdk/tests/async/api_async/test_sbx_list.pyindex 028f254ac..cc19fd1ef 100644--- a/packages/python-sdk/tests/async/api_async/test_sbx_list.py+++ b/packages/python-sdk/tests/async/api_async/test_sbx_list.py@@ -16,19 +16,14 @@ async def test_list_sandboxes(async_sandbox: AsyncSandbox, sandbox_test_id: str)@pytest.mark.skip_debug()-async def test_list_sandboxes_with_filter(sandbox_test_id: str):+async def test_list_sandboxes_with_filter(sandbox_test_id: str, async_sandbox_factory):unique_id = str(int(time.time()))- extra_sbx = await AsyncSandbox.create(metadata={"unique_id": unique_id})+ extra_sbx = await async_sandbox_factory(metadata={"unique_id": unique_id})- try:- paginator = AsyncSandbox.list(- query=SandboxQuery(metadata={"unique_id": unique_id})- )- sandboxes = await paginator.next_items()- assert len(sandboxes) == 1- assert sandboxes[0].sandbox_id == extra_sbx.sandbox_id- finally:- await extra_sbx.kill()+ paginator = AsyncSandbox.list(query=SandboxQuery(metadata={"unique_id": unique_id}))+ sandboxes = await paginator.next_items()+ assert len(sandboxes) == 1+ assert sandboxes[0].sandbox_id == extra_sbx.sandbox_id@pytest.mark.skip_debug()@@ -71,124 +66,117 @@ async def test_list_paused_sandboxes(async_sandbox: AsyncSandbox, sandbox_test_i@pytest.mark.skip_debug()-async def test_paginate_running_sandboxes(- async_sandbox: AsyncSandbox, sandbox_test_id: str-):- # Create extra sandbox- extra_sbx = await AsyncSandbox.create(metadata={"sandbox_test_id": sandbox_test_id})-- try:- # Test pagination with limit- paginator = AsyncSandbox.list(- query=SandboxQuery(- metadata={"sandbox_test_id": sandbox_test_id},- state=[SandboxState.RUNNING],- ),- limit=1,- )- sandboxes = await paginator.next_items()+async def test_paginate_running_sandboxes(sandbox_test_id: str, async_sandbox_factory):+ sbx1 = await async_sandbox_factory()+ sbx2 = await async_sandbox_factory()- # Check first page- assert len(sandboxes) == 1- assert sandboxes[0].state == SandboxState.RUNNING- assert paginator.has_next is True- assert paginator.next_token is not None- assert sandboxes[0].sandbox_id == extra_sbx.sandbox_id+ # Test pagination with limit+ paginator = AsyncSandbox.list(+ query=SandboxQuery(+ metadata={"sandbox_test_id": sandbox_test_id},+ state=[SandboxState.RUNNING],+ ),+ limit=1,+ )+ sandboxes = await paginator.next_items()- # Get second page- sandboxes2 = await paginator.next_items()+ # Check first page+ assert len(sandboxes) == 1+ assert sandboxes[0].state == SandboxState.RUNNING+ assert paginator.has_next is True+ assert paginator.next_token is not None+ assert sandboxes[0].sandbox_id == sbx2.sandbox_id- # Check second page- assert len(sandboxes2) == 1- assert sandboxes2[0].state == SandboxState.RUNNING- assert paginator.has_next is False- assert paginator.next_token is None- assert sandboxes2[0].sandbox_id == async_sandbox.sandbox_id- finally:- await extra_sbx.kill()+ # Get second page+ sandboxes2 = await paginator.next_items()++ # Check second page+ assert len(sandboxes2) == 1+ assert sandboxes2[0].state == SandboxState.RUNNING+ assert paginator.has_next is False+ assert paginator.next_token is None+ assert sandboxes2[0].sandbox_id == sbx1.sandbox_id@pytest.mark.skip_debug()async def test_paginate_paused_sandboxes(- async_sandbox: AsyncSandbox, sandbox_test_id: str+ async_sandbox: AsyncSandbox, sandbox_test_id: str, async_sandbox_factory):sandbox_id = async_sandbox.sandbox_id.split("-")[0]await async_sandbox.beta_pause()# create another paused sandbox- extra_sbx = await AsyncSandbox.create(metadata={"sandbox_test_id": sandbox_test_id})+ extra_sbx = await async_sandbox_factory(+ metadata={"sandbox_test_id": sandbox_test_id}+ )extra_sbx_id = extra_sbx.sandbox_id.split("-")[0]await extra_sbx.beta_pause()- try:- # Test pagination with limit- paginator = AsyncSandbox.list(- query=SandboxQuery(- state=[SandboxState.PAUSED],- metadata={"sandbox_test_id": sandbox_test_id},- ),- limit=1,- )- sandboxes = await paginator.next_items()+ # Test pagination with limit+ paginator = AsyncSandbox.list(+ query=SandboxQuery(+ state=[SandboxState.PAUSED],+ metadata={"sandbox_test_id": sandbox_test_id},+ ),+ limit=1,+ )+ sandboxes = await paginator.next_items()- # Check first page- assert len(sandboxes) == 1- assert sandboxes[0].state == SandboxState.PAUSED- assert paginator.has_next is True- assert paginator.next_token is not None- assert sandboxes[0].sandbox_id.startswith(extra_sbx_id) is True+ # Check first page+ assert len(sandboxes) == 1+ assert sandboxes[0].state == SandboxState.PAUSED+ assert paginator.has_next is True+ assert paginator.next_token is not None+ assert sandboxes[0].sandbox_id.startswith(extra_sbx_id) is True- # Get second page- sandboxes2 = await paginator.next_items()+ # Get second page+ sandboxes2 = await paginator.next_items()- # Check second page- assert len(sandboxes2) == 1- assert sandboxes2[0].state == SandboxState.PAUSED- assert paginator.has_next is False- assert paginator.next_token is None- assert sandboxes2[0].sandbox_id.startswith(sandbox_id) is True- finally:- await extra_sbx.kill()+ # Check second page+ assert len(sandboxes2) == 1+ assert sandboxes2[0].state == SandboxState.PAUSED+ assert paginator.has_next is False+ assert paginator.next_token is None+ assert sandboxes2[0].sandbox_id.startswith(sandbox_id) is True@pytest.mark.skip_debug()async def test_paginate_running_and_paused_sandboxes(- async_sandbox: AsyncSandbox, sandbox_test_id: str+ async_sandbox: AsyncSandbox, sandbox_test_id: str, async_sandbox_factory):# Create extra paused sandbox- extra_sbx = await AsyncSandbox.create(metadata={"sandbox_test_id": sandbox_test_id})+ extra_sbx = await async_sandbox_factory(+ metadata={"sandbox_test_id": sandbox_test_id}+ )extra_sbx_id = extra_sbx.sandbox_id.split("-")[0]await extra_sbx.beta_pause()- try:- # Test pagination with limit- paginator = AsyncSandbox.list(- query=SandboxQuery(- metadata={"sandbox_test_id": sandbox_test_id},- state=[SandboxState.RUNNING, SandboxState.PAUSED],- ),- limit=1,- )- sandboxes = await paginator.next_items()+ # Test pagination with limit+ paginator = AsyncSandbox.list(+ query=SandboxQuery(+ metadata={"sandbox_test_id": sandbox_test_id},+ state=[SandboxState.RUNNING, SandboxState.PAUSED],+ ),+ limit=1,+ )+ sandboxes = await paginator.next_items()- # Check first page- assert len(sandboxes) == 1- assert sandboxes[0].state == SandboxState.PAUSED- assert paginator.has_next is True- assert paginator.next_token is not None- assert sandboxes[0].sandbox_id.startswith(extra_sbx_id) is True-- # Get second page- sandboxes2 = await paginator.next_items()-- # Check second page- assert len(sandboxes2) == 1- assert sandboxes2[0].state == SandboxState.RUNNING- assert paginator.has_next is False- assert paginator.next_token is None- assert sandboxes2[0].sandbox_id == async_sandbox.sandbox_id- finally:- await extra_sbx.kill()+ # Check first page+ assert len(sandboxes) == 1+ assert sandboxes[0].state == SandboxState.PAUSED+ assert paginator.has_next is True+ assert paginator.next_token is not None+ assert sandboxes[0].sandbox_id.startswith(extra_sbx_id) is True++ # Get second page+ sandboxes2 = await paginator.next_items()++ # Check second page+ assert len(sandboxes2) == 1+ assert sandboxes2[0].state == SandboxState.RUNNING+ assert paginator.has_next is False+ assert paginator.next_token is None+ assert sandboxes2[0].sandbox_id == async_sandbox.sandbox_id@pytest.mark.skip_debug()diff --git a/packages/python-sdk/tests/async/sandbox_async/commands/test_env_vars.py b/packages/python-sdk/tests/async/sandbox_async/commands/test_env_vars.pyindex 20b5a6f3d..9563cac71 100644--- a/packages/python-sdk/tests/async/sandbox_async/commands/test_env_vars.py+++ b/packages/python-sdk/tests/async/sandbox_async/commands/test_env_vars.py@@ -9,13 +9,11 @@ async def test_command_envs(async_sandbox: AsyncSandbox):@pytest.mark.skip_debug()-async def test_sandbox_envs(template):- try:- sbx = await AsyncSandbox.create(template, envs={"FOO": "bar"})- cmd = await sbx.commands.run("echo $FOO")- assert cmd.stdout.strip() == "bar"- finally:- await sbx.kill()+async def test_sandbox_envs(async_sandbox_factory):+ sbx = await async_sandbox_factory(envs={"FOO": "bar"})++ cmd = await sbx.commands.run("echo $FOO")+ assert cmd.stdout.strip() == "bar"async def test_bash_command_scoped_env_vars(async_sandbox: AsyncSandbox):diff --git a/packages/python-sdk/tests/async/sandbox_async/files/test_secured.py b/packages/python-sdk/tests/async/sandbox_async/files/test_secured.pyindex e5945e234..2f904d0e6 100644--- a/packages/python-sdk/tests/async/sandbox_async/files/test_secured.py+++ b/packages/python-sdk/tests/async/sandbox_async/files/test_secured.py@@ -3,71 +3,58 @@ import urllib.errorimport jsonimport pytest-from e2b import (- AsyncSandbox,-)+from e2b.sandbox_async.main import AsyncSandbox@pytest.mark.skip_debug()-async def test_download_url_with_signing(template):- sbx = await AsyncSandbox.create(template, timeout=100, secure=True)+async def test_download_url_with_signing(async_sandbox: AsyncSandbox):file_path = "test_download_url_with_signing.txt"file_content = "This file will be watched."- try:- await sbx.files.write(file_path, file_content)- signed_url = sbx.download_url(file_path, "user")+ await async_sandbox.files.write(file_path, file_content)+ signed_url = async_sandbox.download_url(file_path, "user")- with urllib.request.urlopen(signed_url) as resp:- assert resp.status == 200- body_bytes = resp.read()- body_text = body_bytes.decode()- assert body_text == file_content- finally:- await sbx.kill()+ with urllib.request.urlopen(signed_url) as resp:+ assert resp.status == 200+ body_bytes = resp.read()+ body_text = body_bytes.decode()+ assert body_text == file_content@pytest.mark.skip_debug()-async def test_download_url_with_signing_and_expiration(template):- sbx = await AsyncSandbox.create(template, timeout=100, secure=True)+async def test_download_url_with_signing_and_expiration(async_sandbox: AsyncSandbox):file_path = "test_download_url_with_signing.txt"file_content = "This file will be watched."- try:- await sbx.files.write(file_path, file_content)- signed_url = sbx.download_url(file_path, "user", 120)+ await async_sandbox.files.write(file_path, file_content)+ signed_url = async_sandbox.download_url(file_path, "user", 120)- with urllib.request.urlopen(signed_url) as resp:- assert resp.status == 200- body_bytes = resp.read()- body_text = body_bytes.decode()- assert body_text == file_content- finally:- await sbx.kill()+ with urllib.request.urlopen(signed_url) as resp:+ assert resp.status == 200+ body_bytes = resp.read()+ body_text = body_bytes.decode()+ assert body_text == file_content@pytest.mark.skip_debug()-async def test_download_url_with_expired_signing(template):- sbx = await AsyncSandbox.create(template, timeout=100, secure=True)+async def test_download_url_with_expired_signing(async_sandbox: AsyncSandbox):file_path = "test_download_url_with_signing.txt"file_content = "This file will be watched."- try:- await sbx.files.write(file_path, file_content)+ await async_sandbox.files.write(file_path, file_content)- signed_url = sbx.download_url(file_path, "user", use_signature_expiration=-120)+ signed_url = async_sandbox.download_url(+ file_path, "user", use_signature_expiration=-120+ )- with pytest.raises(urllib.error.HTTPError) as exc_info:- urllib.request.urlopen(signed_url)+ with pytest.raises(urllib.error.HTTPError) as exc_info:+ urllib.request.urlopen(signed_url)- err = exc_info.value- assert err.code == 401, f"Unexpected status {err.code}"+ err = exc_info.value+ assert err.code == 401, f"Unexpected status {err.code}"- error_json_str = err.read().decode() # bytes ➜ str- error_payload = json.loads(error_json_str) # str ➜ dict+ error_json_str = err.read().decode() # bytes ➜ str+ error_payload = json.loads(error_json_str) # str ➜ dict- expected_payload = {"code": 401, "message": "signature is already expired"}- assert error_payload == expected_payload-- finally:- await sbx.kill()+ expected_payload = {"code": 401, "message": "signature is already expired"}+ assert error_payload == expected_payloaddiff --git a/packages/python-sdk/tests/async/sandbox_async/files/test_watch.py b/packages/python-sdk/tests/async/sandbox_async/files/test_watch.pyindex 51402573f..fd0f2f0e4 100644--- a/packages/python-sdk/tests/async/sandbox_async/files/test_watch.py+++ b/packages/python-sdk/tests/async/sandbox_async/files/test_watch.py@@ -114,10 +114,6 @@ async def test_watch_file(async_sandbox: AsyncSandbox):await async_sandbox.files.watch_dir(filename, on_event=lambda e: None)-async def test_watch_file_with_secured_envd(template):- sbx = await AsyncSandbox.create(template, timeout=30, secure=True)- try:- await sbx.files.watch_dir("/home/user/", on_event=lambda e: None)- await sbx.files.write("test_watch.txt", "This file will be watched.")- finally:- await sbx.kill()+async def test_watch_file_with_secured_envd(async_sandbox):+ await async_sandbox.files.watch_dir("/home/user/", on_event=lambda e: None)+ await async_sandbox.files.write("test_watch.txt", "This file will be watched.")diff --git a/packages/python-sdk/tests/async/sandbox_async/files/test_write.py b/packages/python-sdk/tests/async/sandbox_async/files/test_write.pyindex 24fe73c62..35395d44d 100644--- a/packages/python-sdk/tests/async/sandbox_async/files/test_write.py+++ b/packages/python-sdk/tests/async/sandbox_async/files/test_write.py@@ -100,23 +100,20 @@ async def test_write_to_non_existing_directory(async_sandbox: AsyncSandbox):assert read_content == content-async def test_write_with_secured_envd(template):+async def test_write_with_secured_envd(async_sandbox_factory):filename = f"non_existing_dir_{uuid.uuid4()}/test_write.txt"content = "This should succeed too."- sbx = await AsyncSandbox.create(template, timeout=30, secure=True)- try:- assert await sbx.is_running()- assert sbx._envd_version is not None- assert sbx._envd_access_token is not None+ sbx = await async_sandbox_factory(timeout=30, secure=True)- await sbx.files.write(filename, content)+ assert await sbx.is_running()+ assert sbx._envd_version is not None+ assert sbx._envd_access_token is not None- exists = await sbx.files.exists(filename)- assert exists+ await sbx.files.write(filename, content)- read_content = await sbx.files.read(filename)- assert read_content == content+ exists = await sbx.files.exists(filename)+ assert exists- finally:- await sbx.kill()+ read_content = await sbx.files.read(filename)+ assert read_content == contentdiff --git a/packages/python-sdk/tests/async/sandbox_async/test_connect.py b/packages/python-sdk/tests/async/sandbox_async/test_connect.pyindex 33bdcdb3d..d4387ba20 100644--- a/packages/python-sdk/tests/async/sandbox_async/test_connect.py+++ b/packages/python-sdk/tests/async/sandbox_async/test_connect.py@@ -5,33 +5,28 @@ from e2b import AsyncSandbox@pytest.mark.skip_debug()-async def test_connect(template):- sbx = await AsyncSandbox.create(template, timeout=10)- try:- assert await sbx.is_running()+async def test_connect(async_sandbox_factory):+ sbx = await async_sandbox_factory(timeout=10)- sbx_connection = await AsyncSandbox.connect(sbx.sandbox_id)- assert await sbx_connection.is_running()- finally:- await sbx.kill()+ assert await sbx.is_running()++ sbx_connection = await AsyncSandbox.connect(sbx.sandbox_id)+ assert await sbx_connection.is_running()@pytest.mark.skip_debug()-async def test_connect_with_secure(template):+async def test_connect_with_secure(async_sandbox_factory):dir_name = f"test_directory_{uuid.uuid4()}"- sbx = await AsyncSandbox.create(template, timeout=10, secure=True)+ sbx = await async_sandbox_factory(timeout=10, secure=True)assert await sbx.is_running()- try:- sbx_connection = await AsyncSandbox.connect(sbx.sandbox_id)+ sbx_connection = await AsyncSandbox.connect(sbx.sandbox_id)- await sbx_connection.files.make_dir(dir_name)- files = await sbx_connection.files.list(dir_name)- assert len(files) == 0- assert await sbx_connection.is_running()- finally:- await sbx.kill()+ await sbx_connection.files.make_dir(dir_name)+ files = await sbx_connection.files.list(dir_name)+ assert len(files) == 0+ assert await sbx_connection.is_running()@pytest.mark.skip_debug()diff --git a/packages/python-sdk/tests/async/sandbox_async/test_create.py b/packages/python-sdk/tests/async/sandbox_async/test_create.pyindex ac142cb0f..95f000dda 100644--- a/packages/python-sdk/tests/async/sandbox_async/test_create.py+++ b/packages/python-sdk/tests/async/sandbox_async/test_create.py@@ -4,33 +4,24 @@ from e2b import AsyncSandbox, SandboxQuery@pytest.mark.skip_debug()-async def test_start(template):- sbx = await AsyncSandbox.create(template, timeout=5)- try:- assert await sbx.is_running()- assert sbx._envd_version is not None- finally:- await sbx.kill()+async def test_start(async_sandbox):+ assert await async_sandbox.is_running()+ assert async_sandbox._envd_version is not None@pytest.mark.skip_debug()-async def test_metadata(template):- sbx = await AsyncSandbox.create(- template, timeout=5, metadata={"test-key": "test-value"}- )+async def test_metadata(async_sandbox_factory):+ sbx = await async_sandbox_factory(timeout=5, metadata={"test-key": "test-value"})- try:- paginator = AsyncSandbox.list(- query=SandboxQuery(metadata={"test-key": "test-value"})- )- sandboxes = await paginator.next_items()+ paginator = AsyncSandbox.list(+ query=SandboxQuery(metadata={"test-key": "test-value"})+ )+ sandboxes = await paginator.next_items()- for sbx_info in sandboxes:- if sbx.sandbox_id == sbx_info.sandbox_id:- assert sbx_info.metadata is not None- assert sbx_info.metadata["test-key"] == "test-value"- break- else:- assert False, "Sandbox not found"- finally:- await sbx.kill()+ for sbx_info in sandboxes:+ if sbx.sandbox_id == sbx_info.sandbox_id:+ assert sbx_info.metadata is not None+ assert sbx_info.metadata["test-key"] == "test-value"+ break+ else:+ assert False, "Sandbox not found"diff --git a/packages/python-sdk/tests/async/sandbox_async/test_internet_access.py b/packages/python-sdk/tests/async/sandbox_async/test_internet_access.pyindex 8065472f6..3a48249ab 100644--- a/packages/python-sdk/tests/async/sandbox_async/test_internet_access.py+++ b/packages/python-sdk/tests/async/sandbox_async/test_internet_access.py@@ -1,51 +1,42 @@import pytest-from e2b import AsyncSandboxfrom e2b.sandbox.commands.command_handle import CommandExitException@pytest.mark.skip_debug()-async def test_internet_access_enabled(template):+async def test_internet_access_enabled(async_sandbox_factory):"""Test that sandbox with internet access enabled can reach external websites."""- sbx = await AsyncSandbox.create(template, allow_internet_access=True)- try:- # Test internet connectivity by making a curl request to a reliable external site- result = await sbx.commands.run(- "curl -s -o /dev/null -w '%{http_code}' https://e2b.dev"- )- assert result.exit_code == 0- assert result.stdout.strip() == "200"- finally:- await sbx.kill()+ sbx = await async_sandbox_factory(allow_internet_access=True)++ # Test internet connectivity by making a curl request to a reliable external site+ result = await sbx.commands.run(+ "curl -s -o /dev/null -w '%{http_code}' https://e2b.dev"+ )+ assert result.exit_code == 0+ assert result.stdout.strip() == "200"@pytest.mark.skip_debug()-async def test_internet_access_disabled(template):+async def test_internet_access_disabled(async_sandbox_factory):"""Test that sandbox with internet access disabled cannot reach external websites."""- sbx = await AsyncSandbox.create(template, allow_internet_access=False)- try:- # Test that internet connectivity is blocked by making a curl request- with pytest.raises(CommandExitException) as exc_info:- await sbx.commands.run(- "curl --connect-timeout 3 --max-time 5 -Is https://e2b.dev"- )- # The command should fail or timeout when internet access is disabled- assert exc_info.value.exit_code != 0+ sbx = await async_sandbox_factory(allow_internet_access=False)- finally:- await sbx.kill()+ # Test that internet connectivity is blocked by making a curl request+ with pytest.raises(CommandExitException) as exc_info:+ await sbx.commands.run(+ "curl --connect-timeout 3 --max-time 5 -Is https://e2b.dev"+ )+ # The command should fail or timeout when internet access is disabled+ assert exc_info.value.exit_code != 0@pytest.mark.skip_debug()-async def test_internet_access_default(template):+async def test_internet_access_default(async_sandbox):"""Test that sandbox with default settings (no explicit allow_internet_access) has internet access."""- sbx = await AsyncSandbox.create(template)- try:- # Test internet connectivity by making a curl request to a reliable external site- result = await sbx.commands.run(- "curl -s -o /dev/null -w '%{http_code}' https://e2b.dev"- )- assert result.exit_code == 0- assert result.stdout.strip() == "200"- finally:- await sbx.kill()+ # Test internet connectivity by making a curl request to a reliable external site++ result = await async_sandbox.commands.run(+ "curl -s -o /dev/null -w '%{http_code}' https://e2b.dev"+ )+ assert result.exit_code == 0+ assert result.stdout.strip() == "200"diff --git a/packages/python-sdk/tests/async/sandbox_async/test_metrics.py b/packages/python-sdk/tests/async/sandbox_async/test_metrics.pyindex d2ab0191f..0982a5a49 100644--- a/packages/python-sdk/tests/async/sandbox_async/test_metrics.py+++ b/packages/python-sdk/tests/async/sandbox_async/test_metrics.py@@ -2,15 +2,15 @@ import asyncioimport pytest-from e2b import AsyncSandbox-@pytest.mark.skip_debug()-async def test_sbx_metrics(async_sandbox: AsyncSandbox):+async def test_sbx_metrics(async_sandbox_factory):+ sbx = await async_sandbox_factory(timeout=20)+# Wait for the sandbox to have some metricsmetrics = []for _ in range(15):- metrics = await async_sandbox.get_metrics()+ metrics = await sbx.get_metrics()if len(metrics) > 0:breakawait asyncio.sleep(1)diff --git a/packages/python-sdk/tests/async/sandbox_async/test_secure.py b/packages/python-sdk/tests/async/sandbox_async/test_secure.pyindex 8557e4597..3ca68dacd 100644--- a/packages/python-sdk/tests/async/sandbox_async/test_secure.py+++ b/packages/python-sdk/tests/async/sandbox_async/test_secure.py@@ -4,27 +4,23 @@ from e2b import AsyncSandbox@pytest.mark.skip_debug()-async def test_start_secured(template):- sbx = await AsyncSandbox.create(template, timeout=5, secure=True)- try:- assert await sbx.is_running()- assert sbx._envd_version is not None- assert sbx._envd_access_token is not None- finally:- await sbx.kill()+async def test_start_secured(async_sandbox_factory):+ sbx = await async_sandbox_factory(timeout=5, secure=True)++ assert await sbx.is_running()+ assert sbx._envd_version is not None+ assert sbx._envd_access_token is not None@pytest.mark.skip_debug()-async def test_connect_to_secured(template):- sbx = await AsyncSandbox.create(template, timeout=100, secure=True)- try:- assert await sbx.is_running()- assert sbx._envd_version is not None- assert sbx._envd_access_token is not None-- sbx_connection = await AsyncSandbox.connect(sbx.sandbox_id)- assert await sbx_connection.is_running()- assert sbx_connection._envd_version is not None- assert sbx_connection._envd_access_token is not None- finally:- await sbx.kill()+async def test_connect_to_secured(async_sandbox_factory):+ sbx = await async_sandbox_factory(timeout=100, secure=True)++ assert await sbx.is_running()+ assert sbx._envd_version is not None+ assert sbx._envd_access_token is not None++ sbx_connection = await AsyncSandbox.connect(sbx.sandbox_id)+ assert await sbx_connection.is_running()+ assert sbx_connection._envd_version is not None+ assert sbx_connection._envd_access_token is not Nonediff --git a/packages/python-sdk/tests/conftest.py b/packages/python-sdk/tests/conftest.pyindex dd115309f..97e54eed2 100644--- a/packages/python-sdk/tests/conftest.py+++ b/packages/python-sdk/tests/conftest.py@@ -7,8 +7,6 @@ import pytest_asyncioimport osfrom uuid import uuid4-from logging import warning-from e2b import (Sandbox,AsyncSandbox,@@ -33,37 +31,66 @@ def template():@pytest.fixture()-def sandbox(template, debug, sandbox_test_id):- sandbox = Sandbox.create(template, metadata={"sandbox_test_id": sandbox_test_id})+def sandbox_factory(request, template, sandbox_test_id):+ def factory(*, template_name: str = template, **kwargs):+ kwargs.setdefault("secure", False)+ kwargs.setdefault("timeout", 5)- try:- yield sandbox- finally:- try:- sandbox.kill()- except (Exception, RuntimeError):- if not debug:- warning(- "Failed to kill sandbox — this is expected if the test runs with local envd."- )+ metadata = kwargs.setdefault("metadata", dict())+ metadata.setdefault("sandbox_test_id", sandbox_test_id)+ sandbox = Sandbox.create(template_name, **kwargs)++ request.addfinalizer(lambda: sandbox.kill())++ return sandbox++ return factory-@pytest_asyncio.fixture-async def async_sandbox(template, debug, sandbox_test_id):- sandbox = await AsyncSandbox.create(- template, metadata={"sandbox_test_id": sandbox_test_id}- )+def sandbox(sandbox_factory):+ return sandbox_factory()+++# override the event loop so it never closes+# this helps us with the global-scoped async http transport[email protected](scope="session")+def event_loop():try:- yield sandbox- finally:- try:- await sandbox.kill()- except (Exception, RuntimeError):- if not debug:- warning(- "Failed to kill sandbox — this is expected if the test runs with local envd."- )+ loop = asyncio.get_running_loop()+ except RuntimeError:+ loop = asyncio.new_event_loop()+ yield loop+ loop.close()+++def async_sandbox_factory(request, template, sandbox_test_id, event_loop):+ async def factory(*, template_name: str = template, **kwargs):+ kwargs.setdefault("timeout", 5)++ metadata = kwargs.setdefault("metadata", dict())+ metadata.setdefault("sandbox_test_id", sandbox_test_id)++ sandbox = await AsyncSandbox.create(template_name, **kwargs)++ def kill():+ async def _kill():+ await sandbox.kill()++ event_loop.run_until_complete(_kill())++ request.addfinalizer(kill)++ return sandbox++ return factory+++async def async_sandbox(async_sandbox_factory):+ return await async_sandbox_factory()@pytest.fixturediff --git a/packages/python-sdk/tests/e2b_connect/__init__.py b/packages/python-sdk/tests/e2b_connect/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/packages/python-sdk/tests/e2b_connect/test_client.py b/packages/python-sdk/tests/e2b_connect/test_client.pynew file mode 100644index 000000000..ea1f27260--- /dev/null+++ b/packages/python-sdk/tests/e2b_connect/test_client.py@@ -0,0 +1,134 @@+import asyncio++import pytest++from e2b_connect.client import _retry+++class GoodError(Exception):+ pass+++class BadError(Exception):+ pass+++def test_sync_retry_after_expected_exception():+ total = 0++ @_retry(GoodError, 1)+ def f():+ nonlocal total+ total += 1+ raise GoodError()++ with pytest.raises(GoodError):+ f()++ assert total == 2+++def test_sync_do_not_retry_on_unexpected_exception():+ total = 0++ @_retry(GoodError, 1)+ def f():+ nonlocal total+ total += 1+ raise BadError()++ with pytest.raises(BadError):+ f()++ assert total == 1+++def test_sync_do_not_throw_when_retry_works():+ total = 0++ @_retry(GoodError, 1)+ def f():+ nonlocal total+ total += 1++ if total < 2:+ raise GoodError()++ return True++ result = f()+ assert result is True+ assert total == 2+++async def test_async_retry_after_expected_exception():+ total = 0++ @_retry(GoodError, 1)+ async def f():+ nonlocal total+ total += 1+ raise GoodError()++ with pytest.raises(GoodError):+ await f()++ assert total == 2+++async def test_async_do_not_retry_on_unexpected_exception():+ total = 0++ @_retry(GoodError, 1)+ async def f():+ nonlocal total+ total += 1+ raise BadError()++ with pytest.raises(BadError):+ await f()++ assert total == 1+++async def test_async_do_not_throw_when_retry_works():+ total = 0++ @_retry(GoodError, 1)+ async def f():+ nonlocal total+ total += 1++ if total < 2:+ raise GoodError()++ return True++ result = await f()+ assert result is True+ assert total == 2+++async def test_async_with_multiple_await_calls():+ total = 0++ async def a():+ await asyncio.sleep(0.001)++ @_retry(GoodError, 1)+ async def f():+ nonlocal total+ total += 1++ await a()++ if total < 2:+ raise GoodError()++ await a()++ return True++ result = await f()+ assert result is True+ assert total == 2diff --git a/packages/python-sdk/tests/shared/template/utils/test_tar_file_stream.py b/packages/python-sdk/tests/shared/template/utils/test_tar_file_stream.pyindex 8538dbced..63b5cf322 100644--- a/packages/python-sdk/tests/shared/template/utils/test_tar_file_stream.py+++ b/packages/python-sdk/tests/shared/template/utils/test_tar_file_stream.py@@ -85,9 +85,8 @@ class TestTarFileStream:contents = self._extract_tar_contents(tar_buffer)# Should include the directory and files- assert "src" in contents or any("src" in name for name in contents.keys())- assert any("index.ts" in name for name in contents.keys())- assert any("Button.tsx" in name for name in contents.keys())+ assert "src/index.ts" in contents+ assert "src/components/Button.tsx" in contentsdef test_should_resolve_symlinks_when_enabled(self, test_dir):"""Test that function resolves symlinks when resolve_symlinks=True."""diff --git a/packages/python-sdk/tests/sync/sandbox_sync/commands/test_env_vars.py b/packages/python-sdk/tests/sync/sandbox_sync/commands/test_env_vars.pyindex eb58e1110..a9752de24 100644--- a/packages/python-sdk/tests/sync/sandbox_sync/commands/test_env_vars.py+++ b/packages/python-sdk/tests/sync/sandbox_sync/commands/test_env_vars.py@@ -9,13 +9,11 @@ def test_command_envs(sandbox: Sandbox):@pytest.mark.skip_debug()-def test_sandbox_envs(template):- sandbox = Sandbox.create(template, envs={"FOO": "bar"})- try:- cmd = sandbox.commands.run("echo $FOO")- assert cmd.stdout.strip() == "bar"- finally:- sandbox.kill()+def test_sandbox_envs(sandbox_factory):+ sbx = sandbox_factory(envs={"FOO": "bar"})++ cmd = sbx.commands.run("echo $FOO")+ assert cmd.stdout.strip() == "bar"def test_bash_command_scoped_env_vars(sandbox: Sandbox):diff --git a/packages/python-sdk/tests/sync/sandbox_sync/files/test_secured.py b/packages/python-sdk/tests/sync/sandbox_sync/files/test_secured.pyindex f80f521ba..4fa59694c 100644--- a/packages/python-sdk/tests/sync/sandbox_sync/files/test_secured.py+++ b/packages/python-sdk/tests/sync/sandbox_sync/files/test_secured.py@@ -3,69 +3,57 @@ import urllib.errorimport jsonimport pytest-from e2b import Sandbox-@pytest.mark.skip_debug()-def test_download_url_with_signing(template):- sbx = Sandbox.create(template, timeout=100, secure=True)+def test_download_url_with_signing(sandbox_factory):+ sbx = sandbox_factory(timeout=100, secure=True)file_path = "test_download_url_with_signing.txt"file_content = "This file will be watched."- try:- sbx.files.write(file_path, file_content)- signed_url = sbx.download_url(file_path, "user")+ sbx.files.write(file_path, file_content)+ signed_url = sbx.download_url(file_path, "user")- with urllib.request.urlopen(signed_url) as resp:- assert resp.status == 200- body_bytes = resp.read()- body_text = body_bytes.decode()- assert body_text == file_content- finally:- sbx.kill()+ with urllib.request.urlopen(signed_url) as resp:+ assert resp.status == 200+ body_bytes = resp.read()+ body_text = body_bytes.decode()+ assert body_text == file_content@pytest.mark.skip_debug()-def test_download_url_with_signing_and_expiration(template):- sbx = Sandbox.create(template, timeout=100, secure=True)+def test_download_url_with_signing_and_expiration(sandbox_factory):+ sbx = sandbox_factory(timeout=100, secure=True)file_path = "test_download_url_with_signing.txt"file_content = "This file will be watched."- try:- sbx.files.write(file_path, file_content)- signed_url = sbx.download_url(file_path, "user", 120)+ sbx.files.write(file_path, file_content)+ signed_url = sbx.download_url(file_path, "user", 120)- with urllib.request.urlopen(signed_url) as resp:- assert resp.status == 200- body_bytes = resp.read()- body_text = body_bytes.decode()- assert body_text == file_content- finally:- sbx.kill()+ with urllib.request.urlopen(signed_url) as resp:+ assert resp.status == 200+ body_bytes = resp.read()+ body_text = body_bytes.decode()+ assert body_text == file_content@pytest.mark.skip_debug()-def test_download_url_with_expired_signing(template):- sbx = Sandbox.create(template, timeout=100, secure=True)+def test_download_url_with_expired_signing(sandbox_factory):+ sbx = sandbox_factory(timeout=100, secure=True)file_path = "test_download_url_with_signing.txt"file_content = "This file will be watched."- try:- sbx.files.write(file_path, file_content)-- signed_url = sbx.download_url(file_path, "user", use_signature_expiration=-120)+ sbx.files.write(file_path, file_content)- with pytest.raises(urllib.error.HTTPError) as exc_info:- urllib.request.urlopen(signed_url)+ signed_url = sbx.download_url(file_path, "user", use_signature_expiration=-120)- err = exc_info.value- assert err.code == 401, f"Unexpected status {err.code}"+ with pytest.raises(urllib.error.HTTPError) as exc_info:+ urllib.request.urlopen(signed_url)- error_json_str = err.read().decode() # bytes ➜ str- error_payload = json.loads(error_json_str) # str ➜ dict+ err = exc_info.value+ assert err.code == 401, f"Unexpected status {err.code}"- expected_payload = {"code": 401, "message": "signature is already expired"}- assert error_payload == expected_payload+ error_json_str = err.read().decode() # bytes ➜ str+ error_payload = json.loads(error_json_str) # str ➜ dict- finally:- sbx.kill()+ expected_payload = {"code": 401, "message": "signature is already expired"}+ assert error_payload == expected_payloaddiff --git a/packages/python-sdk/tests/sync/sandbox_sync/files/test_watch.py b/packages/python-sdk/tests/sync/sandbox_sync/files/test_watch.pyindex 29fc447fb..a6c433d47 100644--- a/packages/python-sdk/tests/sync/sandbox_sync/files/test_watch.py+++ b/packages/python-sdk/tests/sync/sandbox_sync/files/test_watch.py@@ -111,10 +111,8 @@ def test_watch_file(sandbox: Sandbox):sandbox.files.watch_dir(filename)-def test_watch_file_with_secured_envd(template):- sbx = Sandbox.create(template, timeout=30, secure=True)- try:- sbx.files.watch_dir("/home/user/")- sbx.files.write("test_watch.txt", "This file will be watched.")- finally:- sbx.kill()+def test_watch_file_with_secured_envd(sandbox_factory):+ sbx = sandbox_factory(timeout=30, secure=True)++ sbx.files.watch_dir("/home/user/")+ sbx.files.write("test_watch.txt", "This file will be watched.")diff --git a/packages/python-sdk/tests/sync/sandbox_sync/files/test_write.py b/packages/python-sdk/tests/sync/sandbox_sync/files/test_write.pyindex c6018abaf..97e42e27c 100644--- a/packages/python-sdk/tests/sync/sandbox_sync/files/test_write.py+++ b/packages/python-sdk/tests/sync/sandbox_sync/files/test_write.py@@ -2,7 +2,6 @@ import ioimport uuidfrom e2b.sandbox.filesystem.filesystem import WriteInfo, WriteEntry-from e2b.sandbox_sync.main import Sandboxdef test_write_text_file(sandbox):@@ -102,23 +101,20 @@ def test_write_to_non_existing_directory(sandbox):assert read_content == content-def test_write_with_secured_envd(template):+def test_write_with_secured_envd(sandbox_factory):filename = f"non_existing_dir_{uuid.uuid4()}/test_write.txt"content = "This should succeed too."- sbx = Sandbox.create(template, timeout=30, secure=True)- try:- assert sbx.is_running()- assert sbx._envd_version is not None- assert sbx._envd_access_token is not None+ sbx = sandbox_factory(timeout=30, secure=True)- sbx.files.write(filename, content)+ assert sbx.is_running()+ assert sbx._envd_version is not None+ assert sbx._envd_access_token is not None- exists = sbx.files.exists(filename)- assert exists+ sbx.files.write(filename, content)- read_content = sbx.files.read(filename)- assert read_content == content+ exists = sbx.files.exists(filename)+ assert exists- finally:- sbx.kill()+ read_content = sbx.files.read(filename)+ assert read_content == contentdiff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_connect.py b/packages/python-sdk/tests/sync/sandbox_sync/test_connect.pyindex ebe496e45..cce497d94 100644--- a/packages/python-sdk/tests/sync/sandbox_sync/test_connect.py+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_connect.py@@ -5,33 +5,28 @@ from e2b import Sandbox@pytest.mark.skip_debug()-def test_connect(template):- sbx = Sandbox.create(template, timeout=10)- try:- assert sbx.is_running()+def test_connect(sandbox_factory):+ sbx = sandbox_factory(timeout=10)- sbx_connection = Sandbox.connect(sbx.sandbox_id)- assert sbx_connection.is_running()- finally:- sbx.kill()+ assert sbx.is_running()++ sbx_connection = Sandbox.connect(sbx.sandbox_id)+ assert sbx_connection.is_running()@pytest.mark.skip_debug()-def test_connect_with_secure(template):+def test_connect_with_secure(sandbox_factory):dir_name = f"test_directory_{uuid.uuid4()}"- sbx = Sandbox.create(template, timeout=10, secure=True)- try:- assert sbx.is_running()+ sbx = sandbox_factory(timeout=10, secure=True)- sbx_connection = Sandbox.connect(sbx.sandbox_id)+ assert sbx.is_running()- sbx_connection.files.make_dir(dir_name)- files = sbx_connection.files.list(dir_name)- assert len(files) == 0+ sbx_connection = Sandbox.connect(sbx.sandbox_id)- finally:- sbx.kill()+ sbx_connection.files.make_dir(dir_name)+ files = sbx_connection.files.list(dir_name)+ assert len(files) == 0@pytest.mark.skip_debug()diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_create.py b/packages/python-sdk/tests/sync/sandbox_sync/test_create.pyindex 08ddef35c..4edcdf6e2 100644--- a/packages/python-sdk/tests/sync/sandbox_sync/test_create.py+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_create.py@@ -5,31 +5,24 @@ from e2b.sandbox.sandbox_api import SandboxQuery@pytest.mark.skip_debug()-def test_start(template):- sbx = Sandbox.create(template, timeout=5)- try:- assert sbx.is_running()- assert sbx._envd_version is not None- finally:- sbx.kill()+def test_start(sandbox_factory):+ sbx = sandbox_factory(timeout=5)++ assert sbx.is_running()+ assert sbx._envd_version is not None@pytest.mark.skip_debug()-def test_metadata(template):- sbx = Sandbox.create(template, timeout=5, metadata={"test-key": "test-value"})-- try:- paginator = Sandbox.list(- query=SandboxQuery(metadata={"test-key": "test-value"})- )- sandboxes = paginator.next_items()-- for sbx_info in sandboxes:- if sbx.sandbox_id == sbx_info.sandbox_id:- assert sbx_info.metadata is not None- assert sbx_info.metadata["test-key"] == "test-value"- break- else:- assert False, "Sandbox not found"- finally:- sbx.kill()+def test_metadata(sandbox_factory):+ sbx = sandbox_factory(timeout=5, metadata={"test-key": "test-value"})++ paginator = Sandbox.list(query=SandboxQuery(metadata={"test-key": "test-value"}))+ sandboxes = paginator.next_items()++ for sbx_info in sandboxes:+ if sbx.sandbox_id == sbx_info.sandbox_id:+ assert sbx_info.metadata is not None+ assert sbx_info.metadata["test-key"] == "test-value"+ break+ else:+ assert False, "Sandbox not found"diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_internet_access.py b/packages/python-sdk/tests/sync/sandbox_sync/test_internet_access.pyindex 5e7f4f9e2..fecb2f9ba 100644--- a/packages/python-sdk/tests/sync/sandbox_sync/test_internet_access.py+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_internet_access.py@@ -1,51 +1,38 @@import pytest-from e2b import Sandboxfrom e2b.sandbox.commands.command_handle import CommandExitException@pytest.mark.skip_debug()-def test_internet_access_enabled(template):+def test_internet_access_enabled(sandbox_factory):"""Test that sandbox with internet access enabled can reach external websites."""- sbx = Sandbox.create(template, allow_internet_access=True)- try:- # Test internet connectivity by making a curl request to a reliable external site- result = sbx.commands.run(- "curl -s -o /dev/null -w '%{http_code}' https://e2b.dev"- )- assert result.exit_code == 0- assert result.stdout.strip() == "200"- finally:- sbx.kill()+ sbx = sandbox_factory(allow_internet_access=True)++ # Test internet connectivity by making a curl request to a reliable external site+ result = sbx.commands.run("curl -s -o /dev/null -w '%{http_code}' https://e2b.dev")+ assert result.exit_code == 0+ assert result.stdout.strip() == "200"@pytest.mark.skip_debug()-def test_internet_access_disabled(template):+def test_internet_access_disabled(sandbox_factory):"""Test that sandbox with internet access disabled cannot reach external websites."""- sbx = Sandbox.create(template, allow_internet_access=False)- try:- # Test that internet connectivity is blocked by making a curl request- with pytest.raises(CommandExitException) as exc_info:- sbx.commands.run(- "curl --connect-timeout 3 --max-time 5 -Is https://e2b.dev"- )- # The command should fail or timeout when internet access is disabled- assert exc_info.value.exit_code != 0+ sbx = sandbox_factory(allow_internet_access=False)- finally:- sbx.kill()+ # Test that internet connectivity is blocked by making a curl request+ with pytest.raises(CommandExitException) as exc_info:+ sbx.commands.run("curl --connect-timeout 3 --max-time 5 -Is https://e2b.dev")+ # The command should fail or timeout when internet access is disabled+ assert exc_info.value.exit_code != 0@pytest.mark.skip_debug()-def test_internet_access_default(template):+def test_internet_access_default(sandbox):"""Test that sandbox with default settings (no explicit allow_internet_access) has internet access."""- sbx = Sandbox.create(template)- try:- # Test internet connectivity by making a curl request to a reliable external site- result = sbx.commands.run(- "curl -s -o /dev/null -w '%{http_code}' https://e2b.dev"- )- assert result.exit_code == 0- assert result.stdout.strip() == "200"- finally:- sbx.kill()++ # Test internet connectivity by making a curl request to a reliable external site+ result = sandbox.commands.run(+ "curl -s -o /dev/null -w '%{http_code}' https://e2b.dev"+ )+ assert result.exit_code == 0+ assert result.stdout.strip() == "200"diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_metrics.py b/packages/python-sdk/tests/sync/sandbox_sync/test_metrics.pyindex 9785833bf..675920149 100644--- a/packages/python-sdk/tests/sync/sandbox_sync/test_metrics.py+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_metrics.py@@ -2,15 +2,14 @@ import timeimport pytest-from e2b import Sandbox-@pytest.mark.skip_debug()-def test_sbx_metrics(sandbox: Sandbox) -> None:+def test_sbx_metrics(sandbox_factory) -> None:+ sbx = sandbox_factory(timeout=60)# Wait for the sandbox to have some metricsmetrics = []for _ in range(15):- metrics = sandbox.get_metrics()+ metrics = sbx.get_metrics()if len(metrics) > 0:breaktime.sleep(1)diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_secure.py b/packages/python-sdk/tests/sync/sandbox_sync/test_secure.pyindex 95b3b4752..12bb426b8 100644--- a/packages/python-sdk/tests/sync/sandbox_sync/test_secure.py+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_secure.py@@ -4,27 +4,23 @@ from e2b import Sandbox@pytest.mark.skip_debug()-def test_start_secured(template):- sbx = Sandbox.create(template, timeout=5, secure=True)- try:- assert sbx.is_running()- assert sbx._envd_version is not None- assert sbx._envd_access_token is not None- finally:- sbx.kill()+def test_start_secured(sandbox_factory):+ sbx = sandbox_factory(timeout=5, secure=True)++ assert sbx.is_running()+ assert sbx._envd_version is not None+ assert sbx._envd_access_token is not None@pytest.mark.skip_debug()-def test_connect_to_secured(template):- sbx = Sandbox.create(template, timeout=5, secure=True)- try:- assert sbx.is_running()- assert sbx._envd_version is not None- assert sbx._envd_access_token is not None-- sbx_connection = Sandbox.connect(sbx.sandbox_id)- assert sbx_connection.is_running()- assert sbx_connection._envd_version is not None- assert sbx_connection._envd_access_token is not None- finally:- sbx.kill()+def test_connect_to_secured(sandbox_factory):+ sbx = sandbox_factory(timeout=5, secure=True)++ assert sbx.is_running()+ assert sbx._envd_version is not None+ assert sbx._envd_access_token is not None++ sbx_connection = Sandbox.connect(sbx.sandbox_id)+ assert sbx_connection.is_running()+ assert sbx_connection._envd_version is not None+ assert sbx_connection._envd_access_token is not Nonediff --git a/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py b/packages/python-sdk/tests/sync/template_sync/test_stacktrace.pyindex 1ad094874..1fce7ea3b 100644--- a/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py+++ b/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py@@ -1,3 +1,5 @@+import traceback+import pytestimport linecache@@ -23,8 +25,8 @@ def _expect_to_throw_and_check_trace(func, expected_method: str):saw_expected_method = Truebreaktb = tb.tb_next- assert saw_this_file- assert saw_expected_method+ assert saw_this_file, traceback.format_exc()+ assert saw_expected_method, traceback.format_exc()@pytest.mark.skip_debug()