Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Add async python SDK; Reuse connections; [WIP] Add async tests

Tomas Valenta4944c3b13cd7
diff --git a/packages/connect-python/cmd/protoc-gen-connect-python/main.go b/packages/connect-python/cmd/protoc-gen-connect-python/main.go
index 8c43514dd..aa92ce62c 100644
--- a/packages/connect-python/cmd/protoc-gen-connect-python/main.go
+++ b/packages/connect-python/cmd/protoc-gen-connect-python/main.go
@@ -308,7 +308,7 @@ func generate(gen *Plugin, file *descriptor.FileDescriptorProto) {
print(b, "from httpcore import ConnectionPool, AsyncConnectionPool")
print(b, "")
- print(b, "import connect")
+ print(b, "import e2b_connect as connect")
if len(deps) > 0 {
print(b, "")
for _, dep := range deps {
@@ -348,13 +348,13 @@ func generate(gen *Plugin, file *descriptor.FileDescriptorProto) {
print(b, " def %s(self, req: %s , **opts) -> Generator[%s, Any, None]:", toSnakeCase(method.GetName()), getRequestType(gen, method), getResponseType(gen, method))
print(b, " return self.%s.call_%s(req, **opts)", getMethodProperty(method), getMethodType(method))
print(b, "")
- print(b, " async def a%s(self, req: %s , **opts) -> AsyncGenerator[%s, Any]:", toSnakeCase(method.GetName()), getRequestType(gen, method), getResponseType(gen, method))
+ print(b, " def a%s(self, req: %s , **opts) -> AsyncGenerator[%s, Any]:", toSnakeCase(method.GetName()), getRequestType(gen, method), getResponseType(gen, method))
print(b, " return self.%s.acall_%s(req, **opts)", getMethodProperty(method), getMethodType(method))
} else {
print(b, " def %s(self, req: %s, **opts) -> %s:", toSnakeCase(method.GetName()), getRequestType(gen, method), getResponseType(gen, method))
print(b, " return self.%s.call_%s(req, **opts)", getMethodProperty(method), getMethodType(method))
print(b, "")
- print(b, " async def a%s(self, req: %s, **opts) -> Coroutine[Any, Any, %s]:", toSnakeCase(method.GetName()), getRequestType(gen, method), getResponseType(gen, method))
+ print(b, " def a%s(self, req: %s, **opts) -> Coroutine[Any, Any, %s]:", toSnakeCase(method.GetName()), getRequestType(gen, method), getResponseType(gen, method))
print(b, " return self.%s.acall_%s(req, **opts)", getMethodProperty(method), getMethodType(method))
}
}
diff --git a/packages/js-sdk/example.mts b/packages/js-sdk/example.mts
index df44ad953..d75cc1841 100644
--- a/packages/js-sdk/example.mts
+++ b/packages/js-sdk/example.mts
@@ -4,145 +4,8 @@ import dotenv from 'dotenv'
dotenv.config()
-const start = Date.now()
-
-const sbx = await Sandbox.create()
-console.log(sbx.sandboxID)
-
-console.log('time', Date.now() - start)
-
-const list = Date.now()
-
-const res = await sbx.files.list('/')
-
-console.log(res)
-
-console.log('time', Date.now() - list)
-
-// const l = await sbx.commands.list()
-
-// console.log(l)
-
-// // console.log('time', Date.now() - start)
-
-// async function wait(ms: number) {
-// return new Promise((resolve) => setTimeout(resolve, ms))
-// }
-
-// for (let i = 0; i < 10; i++) {
-// const lStart = Date.now()
-// await wait(10000)
-
-// const res = await sbx.files.list('/')
-
-// console.log('time', Date.now() - lStart)
-// }
-
-
-// // const watcher = await sbx.files.watch('./', (e) => {
-// // console.log(e)
-// // }, {
-// // // onExit: (err) => {
-// // // console.log('watcher exited', err)
-// // // },
-// // // timeout: 1000,
-// // // requestTimeoutMs: 1,
-// // })
-
-// // await sbx.files.write('test', 'hello world')
-// // const contents = await sbx.files.read('test')
-// // console.log(contents)
-
-// // await watcher.stop()
-
-
-// // const pStart = Date.now()
-
-// // await sbx.commands.run('python3 -m http.server -b 127.0.0.1 8090', {
-// // await sbx.commands.run('echo "c"', {
-// // background: false,
-// // // user: 'root',
-// // onStdout: (data) => {
-// // console.log('event0', data)
-// // },
-// // })
-
-// // console.log('time', Date.now() - pStart)
-
-// // await wait(3000)
-
-// // const res = await fetch(`https://${sbx.getHost(8090)}`)
-
-// // console.log(await res.text())
-
-
-// // const lStart = Date.now()
-
-// // await sbx.files.makeDir('test')
-
-// // console.log('time', Date.now() - lStart)
-
-// // const rStart = Date.now()
-
-// // await sbx.files.makeDir('test')
-// // // await sbx.files.read('test')
-
-// // console.log('time', Date.now() - rStart)
-// // const xStart = Date.now()
-
-// // await sbx.files.makeDir('test')
-// // // await sbx.files.read('test')
-
-// // console.log('time', Date.now() - xStart)
-// // const yStart = Date.now()
-
-// // await sbx.files.makeDir('test')
-// // // await sbx.files.read('test')
-
-// // console.log('time', Date.now() - yStart)
-
-// // // await sbx.commands.sendStdin(c.pid, 'hello world\n')
-
-// // // console.log(res)
-
-// // // await sbx.files.makeDir('test')
-
-// // // const contents2 = await sbx.files.exists('%%\\test')
-// // // console.log(contents2)
-
-// // // watcher.stop()
-
-
-// // // const start = Date.now()
-
-// // // const res = await sbx.commands.list()
-// // // console.log(res)
-
-// // // const res = await fetch('http://localhost:49982/sync', {
-// // // method: 'POST',
-// // // })
-
-// // // const q = await res.text()
-// // // console.log(q)
-
-
-// // // const res = await sbx.commands.run('sleep 5 && echo hello', {
-// // // background: true,
-// // // onStdout: (data) => {
-// // // console.log('event0', data)
-// // // },
-// // // })
-
-// // // async function wait(ms: number) {
-// // // return new Promise((resolve) => setTimeout(resolve, ms))
-// // // }
-
-// // // // const r2 = await sbx.commands.connect(res.pid, {
-// // // // onStdout: (data) => {
-// // // // console.log('event1', data)
-// // // // },
-// // // // })
-// // // await wait(2000)
-// // // await res.kill()
-
-// // // console.log('time', Date.now() - start)
+for (let i = 0; i < 10; i++) {
+ const start = Date.now()
+ const sbx = await Sandbox.create({ timeout: 10 })
+ console.log('time', Date.now() - start)
+}
diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.ts
index 2f050b988..ec41b3825 100644
--- a/packages/js-sdk/src/api/index.ts
+++ b/packages/js-sdk/src/api/index.ts
@@ -41,6 +41,7 @@ class ApiClient {
this.client = createClient<paths>({
baseUrl: config.apiUrl,
+ keepalive: true,
signal: config.requestTimeoutMs ? AbortSignal.timeout(config.requestTimeoutMs) : undefined,
headers: {
...defaultHeaders,
diff --git a/packages/js-sdk/src/envd/api.ts b/packages/js-sdk/src/envd/api.ts
index 75e1a86e2..62e4ab551 100644
--- a/packages/js-sdk/src/envd/api.ts
+++ b/packages/js-sdk/src/envd/api.ts
@@ -17,7 +17,7 @@ export function handleEnvdApiError(err: {
case 404:
return new NotFoundError(err.message)
case 429:
- return new SandboxError(`${err.code}: ${err.message}: The requests are being rate limited.`)
+ return new SandboxError(`${err.code}: ${err.message}: The requests are being rate limited.`)
case 502:
return formatSandboxTimeoutError(err.message)
case 507:
@@ -35,6 +35,7 @@ class EnvdApiClient {
constructor(config: Pick<ConnectionConfig, 'apiUrl' | 'logger'>) {
this.client = createClient<paths>({
baseUrl: config.apiUrl,
+ keepalive: true,
})
if (config.logger) {
diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.py
index df68b3f8e..f5318e53a 100644
--- a/packages/python-sdk/e2b/__init__.py
+++ b/packages/python-sdk/e2b/__init__.py
@@ -28,6 +28,12 @@ from .sandbox.filesystem.watch_handle import (
)
from .sandbox.filesystem.filesystem import EntryInfo, FileType
-from .sandbox.sync.main import Sandbox
-from .sandbox.sync.filesystem.watch_handle import WatchHandle
-from .sandbox.sync.process.process_handle import ProcessHandle
+from .sandbox_sync.main import Sandbox
+from .sandbox_sync.filesystem.watch_handle import WatchHandle
+from .sandbox_sync.process.process_handle import ProcessHandle
+
+from .sandbox_async.utilts import OutputHandler
+from .sandbox_async.main import AsyncSandbox
+from .sandbox_async.main import AsyncSandbox
+from .sandbox_async.filesystem.watch_handle import AsyncWatchHandle
+from .sandbox_async.process.process_handle import AsyncProcessHandle
diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.py
index 248445a83..91a510d14 100644
--- a/packages/python-sdk/e2b/api/__init__.py
+++ b/packages/python-sdk/e2b/api/__init__.py
@@ -1,6 +1,9 @@
import json
import logging
+from typing import Optional, Union
+from httpx import HTTPTransport, AsyncHTTPTransport
+
from e2b.api.client.client import AuthenticatedClient
from e2b.connection_config import ConnectionConfig
from e2b.api.metadata import default_headers
@@ -23,6 +26,7 @@ class ApiClient(AuthenticatedClient):
config: ConnectionConfig,
require_api_key: bool = True,
require_access_token: bool = False,
+ transport: Optional[Union[HTTPTransport, AsyncHTTPTransport]] = None,
*args,
**kwargs,
):
@@ -46,13 +50,14 @@ class ApiClient(AuthenticatedClient):
auth_header_name = "X-API-KEY" if config.api_key else "Authorization"
prefix = "Bearer" if config.access_token else ""
- super().__init__(
+ c = super().__init__(
base_url=config.api_url,
httpx_args={
"event_hooks": {
"request": [self._log_request],
"response": [self._log_response],
- }
+ },
+ "transport": transport,
},
headers={
**default_headers,
@@ -72,3 +77,15 @@ class ApiClient(AuthenticatedClient):
logger.error(f"Response {response.status_code}")
else:
logger.info(f"Response {response.status_code}")
+
+
+# We need to override the logging hooks for the async usage
+class AsyncApiClient(ApiClient):
+ async def _log_request(self, request):
+ logger.info(f"Request {request.method} {request.url}")
+
+ async def _log_response(self, response: Response):
+ if response.status_code >= 400:
+ logger.error(f"Response {response.status_code}")
+ else:
+ logger.info(f"Response {response.status_code}")
diff --git a/packages/python-sdk/e2b/api/client/client.py b/packages/python-sdk/e2b/api/client/client.py
index 63a2493b9..38b07d057 100644
--- a/packages/python-sdk/e2b/api/client/client.py
+++ b/packages/python-sdk/e2b/api/client/client.py
@@ -38,9 +38,15 @@ class Client:
_base_url: str = field(alias="base_url")
_cookies: Dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
_headers: Dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
- _timeout: Optional[httpx.Timeout] = field(default=None, kw_only=True, alias="timeout")
- _verify_ssl: Union[str, bool, ssl.SSLContext] = field(default=True, kw_only=True, alias="verify_ssl")
- _follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")
+ _timeout: Optional[httpx.Timeout] = field(
+ default=None, kw_only=True, alias="timeout"
+ )
+ _verify_ssl: Union[str, bool, ssl.SSLContext] = field(
+ default=True, kw_only=True, alias="verify_ssl"
+ )
+ _follow_redirects: bool = field(
+ default=False, kw_only=True, alias="follow_redirects"
+ )
_httpx_args: Dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
_client: Optional[httpx.Client] = field(default=None, init=False)
_async_client: Optional[httpx.AsyncClient] = field(default=None, init=False)
@@ -168,9 +174,15 @@ class AuthenticatedClient:
_base_url: str = field(alias="base_url")
_cookies: Dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
_headers: Dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
- _timeout: Optional[httpx.Timeout] = field(default=None, kw_only=True, alias="timeout")
- _verify_ssl: Union[str, bool, ssl.SSLContext] = field(default=True, kw_only=True, alias="verify_ssl")
- _follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")
+ _timeout: Optional[httpx.Timeout] = field(
+ default=None, kw_only=True, alias="timeout"
+ )
+ _verify_ssl: Union[str, bool, ssl.SSLContext] = field(
+ default=True, kw_only=True, alias="verify_ssl"
+ )
+ _follow_redirects: bool = field(
+ default=False, kw_only=True, alias="follow_redirects"
+ )
_httpx_args: Dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
_client: Optional[httpx.Client] = field(default=None, init=False)
_async_client: Optional[httpx.AsyncClient] = field(default=None, init=False)
@@ -214,7 +226,9 @@ class AuthenticatedClient:
def get_httpx_client(self) -> httpx.Client:
"""Get the underlying httpx.Client, constructing a new one if not previously set"""
if self._client is None:
- self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token
+ self._headers[self.auth_header_name] = (
+ f"{self.prefix} {self.token}" if self.prefix else self.token
+ )
self._client = httpx.Client(
base_url=self._base_url,
cookies=self._cookies,
@@ -235,7 +249,9 @@ class AuthenticatedClient:
"""Exit a context manager for internal httpx.Client (see httpx docs)"""
self.get_httpx_client().__exit__(*args, **kwargs)
- def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "AuthenticatedClient":
+ def set_async_httpx_client(
+ self, async_client: httpx.AsyncClient
+ ) -> "AuthenticatedClient":
"""Manually the underlying httpx.AsyncClient
**NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
@@ -246,7 +262,9 @@ class AuthenticatedClient:
def get_async_httpx_client(self) -> httpx.AsyncClient:
"""Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""
if self._async_client is None:
- self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token
+ self._headers[self.auth_header_name] = (
+ f"{self.prefix} {self.token}" if self.prefix else self.token
+ )
self._async_client = httpx.AsyncClient(
base_url=self._base_url,
cookies=self._cookies,
diff --git a/packages/python-sdk/e2b/envd/filesystem/filesystem_connect.py b/packages/python-sdk/e2b/envd/filesystem/filesystem_connect.py
index b0c85f83e..8204899b5 100644
--- a/packages/python-sdk/e2b/envd/filesystem/filesystem_connect.py
+++ b/packages/python-sdk/e2b/envd/filesystem/filesystem_connect.py
@@ -2,7 +2,7 @@
from typing import Any, Generator, Coroutine, AsyncGenerator, Optional
from httpcore import ConnectionPool, AsyncConnectionPool
-import connect
+import e2b_connect as connect
from e2b.envd.filesystem import filesystem_pb2 as filesystem_dot_filesystem__pb2
@@ -69,35 +69,35 @@ class FilesystemClient:
def stat(self, req: filesystem_dot_filesystem__pb2.StatRequest, **opts) -> filesystem_dot_filesystem__pb2.StatResponse:
return self._stat.call_unary(req, **opts)
- async def astat(self, req: filesystem_dot_filesystem__pb2.StatRequest, **opts) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.StatResponse]:
+ def astat(self, req: filesystem_dot_filesystem__pb2.StatRequest, **opts) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.StatResponse]:
return self._stat.acall_unary(req, **opts)
def make_dir(self, req: filesystem_dot_filesystem__pb2.MakeDirRequest, **opts) -> filesystem_dot_filesystem__pb2.MakeDirResponse:
return self._make_dir.call_unary(req, **opts)
- async def amake_dir(self, req: filesystem_dot_filesystem__pb2.MakeDirRequest, **opts) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.MakeDirResponse]:
+ def amake_dir(self, req: filesystem_dot_filesystem__pb2.MakeDirRequest, **opts) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.MakeDirResponse]:
return self._make_dir.acall_unary(req, **opts)
def move(self, req: filesystem_dot_filesystem__pb2.MoveRequest, **opts) -> filesystem_dot_filesystem__pb2.MoveResponse:
return self._move.call_unary(req, **opts)
- async def amove(self, req: filesystem_dot_filesystem__pb2.MoveRequest, **opts) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.MoveResponse]:
+ def amove(self, req: filesystem_dot_filesystem__pb2.MoveRequest, **opts) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.MoveResponse]:
return self._move.acall_unary(req, **opts)
def list_dir(self, req: filesystem_dot_filesystem__pb2.ListDirRequest, **opts) -> filesystem_dot_filesystem__pb2.ListDirResponse:
return self._list_dir.call_unary(req, **opts)
- async def alist_dir(self, req: filesystem_dot_filesystem__pb2.ListDirRequest, **opts) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.ListDirResponse]:
+ def alist_dir(self, req: filesystem_dot_filesystem__pb2.ListDirRequest, **opts) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.ListDirResponse]:
return self._list_dir.acall_unary(req, **opts)
def watch_dir(self, req: filesystem_dot_filesystem__pb2.WatchDirRequest , **opts) -> Generator[filesystem_dot_filesystem__pb2.WatchDirResponse, Any, None]:
return self._watch_dir.call_server_stream(req, **opts)
- async def awatch_dir(self, req: filesystem_dot_filesystem__pb2.WatchDirRequest , **opts) -> AsyncGenerator[filesystem_dot_filesystem__pb2.WatchDirResponse, Any]:
+ def awatch_dir(self, req: filesystem_dot_filesystem__pb2.WatchDirRequest , **opts) -> AsyncGenerator[filesystem_dot_filesystem__pb2.WatchDirResponse, Any]:
return self._watch_dir.acall_server_stream(req, **opts)
def remove(self, req: filesystem_dot_filesystem__pb2.RemoveRequest, **opts) -> filesystem_dot_filesystem__pb2.RemoveResponse:
return self._remove.call_unary(req, **opts)
- async def aremove(self, req: filesystem_dot_filesystem__pb2.RemoveRequest, **opts) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.RemoveResponse]:
+ def aremove(self, req: filesystem_dot_filesystem__pb2.RemoveRequest, **opts) -> Coroutine[Any, Any, filesystem_dot_filesystem__pb2.RemoveResponse]:
return self._remove.acall_unary(req, **opts)
diff --git a/packages/python-sdk/e2b/envd/process/process_connect.py b/packages/python-sdk/e2b/envd/process/process_connect.py
index d3dbcafa0..c7d1c0649 100644
--- a/packages/python-sdk/e2b/envd/process/process_connect.py
+++ b/packages/python-sdk/e2b/envd/process/process_connect.py
@@ -2,7 +2,7 @@
from typing import Any, Generator, Coroutine, AsyncGenerator, Optional
from httpcore import ConnectionPool, AsyncConnectionPool
-import connect
+import e2b_connect as connect
from e2b.envd.process import process_pb2 as process_dot_process__pb2
@@ -78,41 +78,41 @@ class ProcessClient:
def list(self, req: process_dot_process__pb2.ListRequest, **opts) -> process_dot_process__pb2.ListResponse:
return self._list.call_unary(req, **opts)
- async def alist(self, req: process_dot_process__pb2.ListRequest, **opts) -> Coroutine[Any, Any, process_dot_process__pb2.ListResponse]:
+ def alist(self, req: process_dot_process__pb2.ListRequest, **opts) -> Coroutine[Any, Any, process_dot_process__pb2.ListResponse]:
return self._list.acall_unary(req, **opts)
def connect(self, req: process_dot_process__pb2.ConnectRequest , **opts) -> Generator[process_dot_process__pb2.ConnectResponse, Any, None]:
return self._connect.call_server_stream(req, **opts)
- async def aconnect(self, req: process_dot_process__pb2.ConnectRequest , **opts) -> AsyncGenerator[process_dot_process__pb2.ConnectResponse, Any]:
+ def aconnect(self, req: process_dot_process__pb2.ConnectRequest , **opts) -> AsyncGenerator[process_dot_process__pb2.ConnectResponse, Any]:
return self._connect.acall_server_stream(req, **opts)
def start(self, req: process_dot_process__pb2.StartRequest , **opts) -> Generator[process_dot_process__pb2.StartResponse, Any, None]:
return self._start.call_server_stream(req, **opts)
- async def astart(self, req: process_dot_process__pb2.StartRequest , **opts) -> AsyncGenerator[process_dot_process__pb2.StartResponse, Any]:
+ def astart(self, req: process_dot_process__pb2.StartRequest , **opts) -> AsyncGenerator[process_dot_process__pb2.StartResponse, Any]:
return self._start.acall_server_stream(req, **opts)
def update(self, req: process_dot_process__pb2.UpdateRequest, **opts) -> process_dot_process__pb2.UpdateResponse:
return self._update.call_unary(req, **opts)
- async def aupdate(self, req: process_dot_process__pb2.UpdateRequest, **opts) -> Coroutine[Any, Any, process_dot_process__pb2.UpdateResponse]:
+ def aupdate(self, req: process_dot_process__pb2.UpdateRequest, **opts) -> Coroutine[Any, Any, process_dot_process__pb2.UpdateResponse]:
return self._update.acall_unary(req, **opts)
def stream_input(self, req: process_dot_process__pb2.StreamInputRequest, **opts) -> process_dot_process__pb2.StreamInputResponse:
return self._stream_input.call_client_stream(req, **opts)
- async def astream_input(self, req: process_dot_process__pb2.StreamInputRequest, **opts) -> Coroutine[Any, Any, process_dot_process__pb2.StreamInputResponse]:
+ def astream_input(self, req: process_dot_process__pb2.StreamInputRequest, **opts) -> Coroutine[Any, Any, process_dot_process__pb2.StreamInputResponse]:
return self._stream_input.acall_client_stream(req, **opts)
def send_input(self, req: process_dot_process__pb2.SendInputRequest, **opts) -> process_dot_process__pb2.SendInputResponse:
return self._send_input.call_unary(req, **opts)
- async def asend_input(self, req: process_dot_process__pb2.SendInputRequest, **opts) -> Coroutine[Any, Any, process_dot_process__pb2.SendInputResponse]:
+ def asend_input(self, req: process_dot_process__pb2.SendInputRequest, **opts) -> Coroutine[Any, Any, process_dot_process__pb2.SendInputResponse]:
return self._send_input.acall_unary(req, **opts)
def send_signal(self, req: process_dot_process__pb2.SendSignalRequest, **opts) -> process_dot_process__pb2.SendSignalResponse:
return self._send_signal.call_unary(req, **opts)
- async def asend_signal(self, req: process_dot_process__pb2.SendSignalRequest, **opts) -> Coroutine[Any, Any, process_dot_process__pb2.SendSignalResponse]:
+ def asend_signal(self, req: process_dot_process__pb2.SendSignalRequest, **opts) -> Coroutine[Any, Any, process_dot_process__pb2.SendSignalResponse]:
return self._send_signal.acall_unary(req, **opts)
diff --git a/packages/python-sdk/e2b/envd/rpc.py b/packages/python-sdk/e2b/envd/rpc.py
index 4e4f372fa..c0d8cc31f 100644
--- a/packages/python-sdk/e2b/envd/rpc.py
+++ b/packages/python-sdk/e2b/envd/rpc.py
@@ -1,7 +1,7 @@
import base64
from typing import Optional
-from connect.client import Code, ConnectException
+from e2b_connect.client import Code, ConnectException
from e2b.exceptions import (
SandboxException,
diff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.py
index 6b8083c05..2593df9ca 100644
--- a/packages/python-sdk/e2b/sandbox/main.py
+++ b/packages/python-sdk/e2b/sandbox/main.py
@@ -1,5 +1,52 @@
-class SandboxSetup:
- _envd_port = 49983
+import urllib.parse
+
+from abc import ABC, abstractmethod
+from typing import Optional
+
+from e2b.connection_config import ConnectionConfig
+from e2b.envd.api import ENVD_API_FILES_ROUTE
+from httpx import Limits
+
+
+class SandboxSetup(ABC):
+ _limits = Limits(
+ max_keepalive_connections=10,
+ max_connections=20,
+ keepalive_expiry=600,
+ )
+
+ envd_port = 49983
default_sandbox_timeout = 300
default_template = "base"
+
+ @property
+ @abstractmethod
+ def connection_config(self) -> ConnectionConfig: ...
+
+ @property
+ @abstractmethod
+ def envd_api_url(self) -> str: ...
+
+ @property
+ @abstractmethod
+ def sandbox_id(self) -> str: ...
+
+ def upload_url(self, path: Optional[str] = None) -> str:
+ url = urllib.parse.urljoin(self.envd_api_url, ENVD_API_FILES_ROUTE)
+ query = {"path": path} if path else {}
+ query = {**query, "username": "user"}
+
+ params = urllib.parse.urlencode(
+ query,
+ quote_via=urllib.parse.quote,
+ )
+ url = urllib.parse.urljoin(url, f"?{params}")
+
+ return url
+
+ def get_host(self, port: int) -> str:
+ if self.connection_config.debug:
+ return f"localhost:{port}"
+
+ return f"{port}-{self.sandbox_id}.{self.connection_config.domain}"
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.py
index 9d74f0c73..1acfb72f1 100644
--- a/packages/python-sdk/e2b/sandbox/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py
@@ -1,6 +1,8 @@
+from abc import ABC
from dataclasses import dataclass
from typing import Optional, Dict
from datetime import datetime
+from httpx import Limits
@dataclass
@@ -17,3 +19,15 @@ class SandboxInfo:
"""Saved sandbox metadata."""
started_at: datetime
"""Sandbox start time."""
+
+
+class SandboxApiBase(ABC):
+ _limits = Limits(
+ max_keepalive_connections=10,
+ max_connections=20,
+ keepalive_expiry=20,
+ )
+
+ @staticmethod
+ def _get_sandbox_id(sandbox_id: str, client_id: str) -> str:
+ return f"{sandbox_id}-{client_id}"
diff --git a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
new file mode 100644
index 000000000..aea3835d1
--- /dev/null
+++ b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
@@ -0,0 +1,252 @@
+import e2b_connect as connect
+import httpx
+import httpcore
+
+from typing import (
+ AsyncIterator,
+ List,
+ Optional,
+ overload,
+ Literal,
+ Union,
+ IO,
+)
+
+from e2b.sandbox.filesystem.filesystem import EntryInfo, map_file_type
+from e2b.connection_config import Username, ConnectionConfig
+from e2b.exceptions import SandboxException
+from e2b.envd.api import handle_envd_api_exception
+from e2b.envd.rpc import authentication_header, handle_rpc_exception
+from e2b.envd.filesystem import filesystem_connect, filesystem_pb2
+from e2b.envd.api import ENVD_API_FILES_ROUTE
+from e2b.sandbox_async.filesystem.watch_handle import AsyncWatchHandle
+from e2b.sandbox.filesystem.watch_handle import FilesystemEvent
+from e2b.sandbox_async.utilts import OutputHandler
+
+
+class Filesystem:
+ def __init__(
+ self,
+ envd_api_url: str,
+ connection_config: ConnectionConfig,
+ pool: httpcore.AsyncConnectionPool,
+ envd_api: httpx.AsyncClient,
+ ) -> None:
+ self._envd_api_url = envd_api_url
+ self._connection_config = connection_config
+ self._pool = pool
+ self._envd_api = envd_api
+
+ self._rpc = filesystem_connect.FilesystemClient(
+ envd_api_url,
+ compressor=connect.GzipCompressor,
+ async_pool=pool,
+ )
+
+ @overload
+ async def read(
+ self,
+ path: str,
+ format: Literal["text"] = "text",
+ user: Username = "user",
+ request_timeout: Optional[float] = None,
+ ) -> str: ...
+
+ @overload
+ async def read(
+ self,
+ path: str,
+ format: Literal["bytes"],
+ user: Username = "user",
+ request_timeout: Optional[float] = None,
+ ) -> bytearray: ...
+
+ @overload
+ async def read(
+ self,
+ path: str,
+ format: Literal["stream"],
+ user: Username = "user",
+ request_timeout: Optional[float] = None,
+ ) -> AsyncIterator[bytes]: ...
+
+ async def read(
+ self,
+ path: str,
+ format: Literal["text", "bytes", "stream"] = "text",
+ user: Username = "user",
+ request_timeout: Optional[float] = None,
+ ):
+ r = await self._envd_api.get(
+ ENVD_API_FILES_ROUTE,
+ params={"path": path, "username": user},
+ timeout=self._connection_config.get_request_timeout(request_timeout),
+ )
+
+ err = handle_envd_api_exception(r)
+ if err:
+ raise err
+
+ if format == "text":
+ return r.text
+ elif format == "bytes":
+ return bytearray(r.content)
+ elif format == "stream":
+ return r.aiter_bytes()
+
+ async def write(
+ self,
+ path: str,
+ data: Union[str, bytes, IO],
+ user: Username = "user",
+ request_timeout: Optional[float] = None,
+ ) -> None:
+ r = await self._envd_api.post(
+ ENVD_API_FILES_ROUTE,
+ files={"file": data},
+ params={"path": path, "username": user},
+ timeout=self._connection_config.get_request_timeout(request_timeout),
+ )
+
+ err = handle_envd_api_exception(r)
+ if err:
+ raise err
+
+ async def list(
+ self,
+ path: str,
+ user: Username = "user",
+ request_timeout: Optional[float] = None,
+ ) -> List[EntryInfo]:
+ try:
+ res = await self._rpc.alist_dir(
+ filesystem_pb2.ListDirRequest(path=path),
+ request_timeout=self._connection_config.get_request_timeout(
+ request_timeout
+ ),
+ headers=authentication_header(user),
+ )
+
+ entries: List[EntryInfo] = []
+ for entry in res.entries:
+ event_type = map_file_type(entry.type)
+
+ if event_type:
+ entries.append(EntryInfo(name=entry.name, type=event_type))
+
+ return entries
+ except Exception as e:
+ raise handle_rpc_exception(e)
+
+ async def exists(
+ self,
+ path: str,
+ user: Username = "user",
+ request_timeout: Optional[float] = None,
+ ) -> bool:
+ try:
+ res = await self._rpc.astat(
+ filesystem_pb2.StatRequest(path=path),
+ request_timeout=self._connection_config.get_request_timeout(
+ request_timeout
+ ),
+ headers=authentication_header(user),
+ )
+
+ return True
+
+ except Exception as e:
+ if isinstance(e, connect.ConnectException):
+ if e.status == connect.Code.not_found:
+ return False
+ raise handle_rpc_exception(e)
+
+ async def remove(
+ self,
+ path: str,
+ user: Username = "user",
+ request_timeout: Optional[float] = None,
+ ) -> None:
+ try:
+ await self._rpc.aremove(
+ filesystem_pb2.RemoveRequest(path=path),
+ request_timeout=self._connection_config.get_request_timeout(
+ request_timeout
+ ),
+ headers=authentication_header(user),
+ )
+ except Exception as e:
+ raise handle_rpc_exception(e)
+
+ async def rename(
+ self,
+ old_path: str,
+ new_path: str,
+ user: Username = "user",
+ request_timeout: Optional[float] = None,
+ ) -> None:
+ try:
+ await self._rpc.amove(
+ filesystem_pb2.MoveRequest(
+ source=old_path,
+ destination=new_path,
+ ),
+ request_timeout=self._connection_config.get_request_timeout(
+ request_timeout
+ ),
+ headers=authentication_header(user),
+ )
+ except Exception as e:
+ raise handle_rpc_exception(e)
+
+ async def make_dir(
+ self,
+ path: str,
+ user: Username = "user",
+ request_timeout: Optional[float] = None,
+ ) -> bool:
+ try:
+ await self._rpc.amake_dir(
+ filesystem_pb2.MakeDirRequest(path=path),
+ request_timeout=self._connection_config.get_request_timeout(
+ request_timeout
+ ),
+ headers=authentication_header(user),
+ )
+
+ return True
+ except Exception as e:
+ if isinstance(e, connect.ConnectException):
+ if e.status == connect.Code.already_exists:
+ return False
+ raise handle_rpc_exception(e)
+
+ async def watch(
+ self,
+ path: str,
+ on_event: OutputHandler[FilesystemEvent],
+ on_exit: Optional[OutputHandler[Exception]] = None,
+ user: Username = "user",
+ request_timeout: Optional[float] = None,
+ timeout: Optional[float] = 60,
+ ):
+ events = self._rpc.awatch_dir(
+ filesystem_pb2.WatchDirRequest(path=path),
+ request_timeout=self._connection_config.get_request_timeout(
+ request_timeout
+ ),
+ timeout=timeout,
+ headers=authentication_header(user),
+ )
+
+ try:
+ start_event = await events.__anext__()
+
+ if not start_event.HasField("start"):
+ raise SandboxException(
+ f"Failed to start watch: expected start event, got {start_event}",
+ )
+
+ return AsyncWatchHandle(events=events, on_event=on_event, on_exit=on_exit)
+ except Exception as e:
+ raise handle_rpc_exception(e)
diff --git a/packages/python-sdk/e2b/sandbox_async/filesystem/watch_handle.py b/packages/python-sdk/e2b/sandbox_async/filesystem/watch_handle.py
new file mode 100644
index 000000000..cfb2b01a5
--- /dev/null
+++ b/packages/python-sdk/e2b/sandbox_async/filesystem/watch_handle.py
@@ -0,0 +1,53 @@
+import asyncio
+import inspect
+
+from typing import Any, AsyncGenerator, Optional
+
+from e2b.envd.rpc import handle_rpc_exception
+from e2b.envd.filesystem.filesystem_pb2 import WatchDirResponse
+from e2b.sandbox.filesystem.watch_handle import FilesystemEvent, map_event_type
+from e2b.sandbox_async.utilts import OutputHandler
+
+
+class AsyncWatchHandle:
+ def __init__(
+ self,
+ events: AsyncGenerator[WatchDirResponse, Any],
+ on_event: OutputHandler[FilesystemEvent],
+ on_exit: Optional[OutputHandler[Exception]] = None,
+ ):
+ self._events = events
+ self._on_event = on_event
+ self._on_exit = on_exit
+ self._task = asyncio.create_task(self._handle_events())
+
+ async def close(self):
+ self._task.cancel()
+ await self._events.aclose()
+
+ async def _iterate_events(self):
+ try:
+ async for event in self._events:
+ if event.HasField("filesystem"):
+ event_type = map_event_type(event.filesystem.type)
+ if event_type:
+ yield FilesystemEvent(
+ name=event.filesystem.name,
+ type=event_type,
+ )
+ except Exception as e:
+ raise handle_rpc_exception(e)
+ finally:
+ await self.close()
+
+ async def _handle_events(self):
+ try:
+ async for event in self._iterate_events():
+ cb = self._on_event(event)
+ if inspect.isawaitable(cb):
+ await cb
+ except Exception as e:
+ if self._on_exit:
+ cb = self._on_exit(e)
+ if inspect.isawaitable(cb):
+ await cb
diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.py
new file mode 100644
index 000000000..655910701
--- /dev/null
+++ b/packages/python-sdk/e2b/sandbox_async/main.py
@@ -0,0 +1,218 @@
+import logging
+import httpx
+
+from typing import Optional, Dict, Literal, overload
+
+from e2b.sandbox.utils import class_method_variant
+from e2b.connection_config import ConnectionConfig
+from e2b.envd.api import (
+ handle_envd_api_exception,
+ ENVD_API_HEALTH_ROUTE,
+)
+from e2b.sandbox_async.filesystem.filesystem import Filesystem
+from e2b.sandbox_async.process.process import Process
+from e2b.sandbox_async.sandbox_api import SandboxApi
+from e2b.sandbox.main import SandboxSetup
+
+
+logger = 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
+
+
+class AsyncSandbox(SandboxSetup, SandboxApi):
+ @property
+ def files(self) -> Filesystem:
+ return self._filesystem
+
+ @property
+ def commands(self) -> Process:
+ return self._process
+
+ @property
+ def sandbox_id(self) -> str:
+ return self._sandbox_id
+
+ @property
+ def envd_api_url(self) -> str:
+ return self._envd_api_url
+
+ @property
+ def connection_config(self) -> ConnectionConfig:
+ return self._connection_config
+
+ def __init__(self, sandbox_id: str, connection_config: ConnectionConfig):
+ super().__init__()
+
+ self._sandbox_id = sandbox_id
+ self._connection_config = connection_config
+
+ self._envd_api_url = f"{'http' if self.connection_config.debug else 'https'}://{self.get_host(self.envd_port)}"
+
+ self._transport = AsyncTransportWithLogger(limits=self._limits)
+ self._envd_api = httpx.AsyncClient(
+ base_url=self.envd_api_url,
+ transport=self._transport,
+ )
+
+ self._filesystem = Filesystem(
+ self.envd_api_url,
+ self.connection_config,
+ self._transport._pool,
+ self._envd_api,
+ )
+ self._process = Process(
+ self.envd_api_url,
+ self.connection_config,
+ self._transport._pool,
+ )
+
+ async def is_running(
+ self, request_timeout: Optional[float] = None
+ ) -> Literal[True]:
+ r = await self._envd_api.get(
+ ENVD_API_HEALTH_ROUTE,
+ timeout=self.connection_config.get_request_timeout(request_timeout),
+ )
+
+ err = handle_envd_api_exception(r)
+ if err:
+ raise err
+
+ return True
+
+ @classmethod
+ async def create(
+ cls,
+ template: Optional[str] = None,
+ timeout: Optional[int] = None,
+ metadata: Optional[Dict[str, str]] = None,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ debug: Optional[bool] = None,
+ request_timeout: Optional[float] = None,
+ ):
+ connection_config = ConnectionConfig(
+ api_key=api_key,
+ domain=domain,
+ debug=debug,
+ request_timeout=request_timeout,
+ )
+
+ sandbox_id = (
+ "debug_sandbox_id"
+ if connection_config.debug
+ else await SandboxApi._create_sandbox(
+ template=template or cls.default_template,
+ api_key=api_key,
+ timeout=timeout or cls.default_sandbox_timeout,
+ metadata=metadata,
+ domain=domain,
+ debug=debug,
+ request_timeout=request_timeout,
+ )
+ )
+
+ return cls(
+ sandbox_id=sandbox_id,
+ connection_config=connection_config,
+ )
+
+ @classmethod
+ async def connect(
+ cls,
+ sandbox_id: str,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ debug: Optional[bool] = None,
+ ):
+ connection_config = ConnectionConfig(
+ api_key=api_key,
+ domain=domain,
+ debug=debug,
+ )
+
+ return cls(
+ sandbox_id=sandbox_id,
+ connection_config=connection_config,
+ )
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc_value, traceback):
+ await self.kill()
+
+ @overload
+ async def kill(self, request_timeout: Optional[float] = None) -> bool: ...
+
+ @overload
+ @staticmethod
+ async def kill(
+ sandbox_id: str,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ debug: Optional[bool] = None,
+ request_timeout: Optional[float] = None,
+ ) -> bool: ...
+
+ @class_method_variant("_cls_kill")
+ async def kill(self, request_timeout: Optional[float] = None) -> bool: # type: ignore
+ config_dict = self.connection_config.__dict__
+ config_dict.pop("access_token", None)
+ config_dict.pop("api_url", None)
+
+ if request_timeout:
+ config_dict["request_timeout"] = request_timeout
+
+ await SandboxApi._cls_kill(
+ sandbox_id=self.sandbox_id,
+ **self.connection_config.__dict__,
+ )
+
+ @overload
+ async def set_timeout(
+ self,
+ timeout: int,
+ request_timeout: Optional[float] = None,
+ ) -> None: ...
+
+ @overload
+ @staticmethod
+ async def set_timeout(
+ sandbox_id: str,
+ timeout: int,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ debug: Optional[bool] = None,
+ request_timeout: Optional[float] = None,
+ ) -> None: ...
+
+ @class_method_variant("_cls_set_timeout")
+ async def set_timeout( # type: ignore
+ self,
+ timeout: int,
+ request_timeout: Optional[float] = None,
+ ) -> None:
+ config_dict = self.connection_config.__dict__
+ config_dict.pop("access_token", None)
+ config_dict.pop("api_url", None)
+
+ if request_timeout:
+ config_dict["request_timeout"] = request_timeout
+
+ await SandboxApi._cls_set_timeout(
+ sandbox_id=self.sandbox_id,
+ timeout=timeout,
+ **self.connection_config.__dict__,
+ )
diff --git a/packages/python-sdk/e2b/sandbox_async/process/process.py b/packages/python-sdk/e2b/sandbox_async/process/process.py
new file mode 100644
index 000000000..adf9a47ae
--- /dev/null
+++ b/packages/python-sdk/e2b/sandbox_async/process/process.py
@@ -0,0 +1,242 @@
+import e2b_connect
+import httpcore
+
+from typing import (
+ Dict,
+ List,
+ Optional,
+ Literal,
+ overload,
+ Union,
+)
+
+from e2b.envd.process import process_connect, process_pb2
+from e2b.connection_config import Username, ConnectionConfig
+from e2b.exceptions import SandboxException
+from e2b.envd.rpc import authentication_header, handle_rpc_exception
+from e2b.sandbox.process.main import ProcessInfo
+from e2b.sandbox.process.process_handle import ProcessResult
+from e2b.sandbox_async.process.process_handle import (
+ AsyncProcessHandle,
+ Stdout,
+ Stderr,
+)
+from e2b.sandbox_async.utilts import OutputHandler
+
+
+class Process:
+ def __init__(
+ self,
+ envd_api_url: str,
+ connection_config: ConnectionConfig,
+ pool: httpcore.AsyncConnectionPool,
+ ) -> None:
+ self._connection_config = connection_config
+ self._rpc = process_connect.ProcessClient(
+ envd_api_url,
+ # TODO: Fix and enable compression again — the headers compression is not solved.
+ # compressor=connect.GzipCompressor,
+ async_pool=pool,
+ )
+
+ async def list(
+ self,
+ request_timeout: Optional[float] = None,
+ ) -> List[ProcessInfo]:
+ try:
+ res = await self._rpc.alist(
+ process_pb2.ListRequest(),
+ request_timeout=self._connection_config.get_request_timeout(
+ request_timeout
+ ),
+ )
+ return [
+ ProcessInfo(
+ pid=p.pid,
+ tag=p.tag,
+ cmd=p.config.cmd,
+ args=list(p.config.args),
+ envs=dict(p.config.envs),
+ cwd=p.config.cwd,
+ )
+ for p in res.processes
+ ]
+ except Exception as e:
+ raise handle_rpc_exception(e)
+
+ async def kill(
+ self,
+ pid: int,
+ request_timeout: Optional[float] = None,
+ ) -> bool:
+ try:
+ await self._rpc.asend_signal(
+ process_pb2.SendSignalRequest(
+ process=process_pb2.ProcessSelector(pid=pid),
+ signal=process_pb2.Signal.SIGNAL_SIGKILL,
+ ),
+ request_timeout=self._connection_config.get_request_timeout(
+ request_timeout
+ ),
+ )
+ return True
+ except Exception as e:
+ if isinstance(e, e2b_connect.ConnectException):
+ if e.status == e2b_connect.Code.not_found:
+ return False
+ raise handle_rpc_exception(e)
+
+ async def send_stdin(
+ self,
+ pid: int,
+ data: str,
+ request_timeout: Optional[float] = None,
+ ):
+ try:
+ await self._rpc.asend_input(
+ process_pb2.SendInputRequest(
+ process=process_pb2.ProcessSelector(pid=pid),
+ input=process_pb2.ProcessInput(
+ stdin=data.encode(),
+ ),
+ ),
+ request_timeout=self._connection_config.get_request_timeout(
+ request_timeout
+ ),
+ )
+ except Exception as e:
+ raise handle_rpc_exception(e)
+
+ @overload
+ async def run(
+ self,
+ cmd: str,
+ background: Union[Literal[False], None] = None,
+ envs: Optional[Dict[str, str]] = {},
+ user: Username = "user",
+ cwd: Optional[str] = None,
+ on_stdout: Optional[OutputHandler[Stdout]] = None,
+ on_stderr: Optional[OutputHandler[Stderr]] = None,
+ timeout: Optional[float] = 60,
+ request_timeout: Optional[float] = None,
+ ) -> ProcessResult: ...
+
+ @overload
+ async def run(
+ self,
+ cmd: str,
+ background: Literal[True],
+ envs: Optional[Dict[str, str]] = {},
+ user: Username = "user",
+ cwd: Optional[str] = None,
+ on_stdout: Optional[OutputHandler[Stdout]] = None,
+ on_stderr: Optional[OutputHandler[Stderr]] = None,
+ timeout: Optional[float] = 60,
+ request_timeout: Optional[float] = None,
+ ) -> AsyncProcessHandle: ...
+
+ async def run(
+ self,
+ cmd: str,
+ background: Union[bool, None] = None,
+ envs: Optional[Dict[str, str]] = {},
+ user: Username = "user",
+ cwd: Optional[str] = None,
+ on_stdout: Optional[OutputHandler[Stdout]] = None,
+ on_stderr: Optional[OutputHandler[Stderr]] = None,
+ timeout: Optional[float] = 60,
+ request_timeout: Optional[float] = None,
+ ):
+ proc = await self._start(
+ cmd,
+ envs,
+ user,
+ cwd,
+ timeout,
+ request_timeout,
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+ )
+
+ return proc if background else await proc.wait()
+
+ async def _start(
+ self,
+ cmd: str,
+ envs: Optional[Dict[str, str]] = {},
+ user: Username = "user",
+ cwd: Optional[str] = None,
+ timeout: Optional[float] = 60,
+ request_timeout: Optional[float] = None,
+ on_stdout: Optional[OutputHandler[Stdout]] = None,
+ on_stderr: Optional[OutputHandler[Stderr]] = None,
+ ):
+ events = self._rpc.astart(
+ process_pb2.StartRequest(
+ process=process_pb2.ProcessConfig(
+ cmd="/bin/bash",
+ envs=envs,
+ args=["-l", "-c", cmd],
+ cwd=cwd,
+ ),
+ ),
+ headers=authentication_header(user),
+ timeout=timeout,
+ request_timeout=self._connection_config.get_request_timeout(
+ request_timeout
+ ),
+ )
+
+ try:
+ start_event = await events.__anext__()
+
+ if not start_event.HasField("event"):
+ raise SandboxException(
+ f"Failed to start process: expected start event, got {start_event}"
+ )
+
+ return AsyncProcessHandle(
+ pid=start_event.event.start.pid,
+ handle_kill=lambda: self.kill(start_event.event.start.pid),
+ events=events,
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+ )
+ except Exception as e:
+ raise handle_rpc_exception(e)
+
+ async def connect(
+ self,
+ pid: int,
+ timeout: Optional[float] = 60,
+ request_timeout: Optional[float] = None,
+ on_stdout: Optional[OutputHandler[Stdout]] = None,
+ on_stderr: Optional[OutputHandler[Stderr]] = None,
+ ):
+ events = self._rpc.aconnect(
+ process_pb2.ConnectRequest(
+ process=process_pb2.ProcessSelector(pid=pid),
+ ),
+ timeout=timeout,
+ request_timeout=self._connection_config.get_request_timeout(
+ request_timeout
+ ),
+ )
+
+ try:
+ start_event = await events.__anext__()
+
+ if not start_event.HasField("event"):
+ raise SandboxException(
+ f"Failed to connect to process: expected start event, got {start_event}"
+ )
+
+ return AsyncProcessHandle(
+ pid=start_event.event.start.pid,
+ handle_kill=lambda: self.kill(start_event.event.start.pid),
+ events=events,
+ on_stdout=on_stdout,
+ on_stderr=on_stderr,
+ )
+ except Exception as e:
+ raise handle_rpc_exception(e)
diff --git a/packages/python-sdk/e2b/sandbox_async/process/process_handle.py b/packages/python-sdk/e2b/sandbox_async/process/process_handle.py
new file mode 100644
index 000000000..6f592b5a8
--- /dev/null
+++ b/packages/python-sdk/e2b/sandbox_async/process/process_handle.py
@@ -0,0 +1,156 @@
+import asyncio
+import inspect
+from typing import (
+ Optional,
+ Callable,
+ Any,
+ AsyncGenerator,
+ Union,
+ Tuple,
+ Coroutine,
+)
+
+from e2b.envd.rpc import handle_rpc_exception
+from e2b.envd.process import process_pb2
+from e2b.sandbox.process.process_handle import (
+ ProcessExitException,
+ ProcessResult,
+ Stderr,
+ Stdout,
+)
+from e2b.sandbox_async.utilts import OutputHandler
+
+
+class AsyncProcessHandle:
+ @property
+ def pid(self):
+ return self._pid
+
+ @property
+ def stdout(self):
+ return self._stdout
+
+ @property
+ def stderr(self):
+ return self._stderr
+
+ @property
+ def error(self):
+ if self._result is None:
+ return None
+ return self._result.error
+
+ @property
+ def exit_code(self):
+ if self._result is None:
+ return None
+ return self._result.exit_code
+
+ def __init__(
+ self,
+ pid: int,
+ handle_kill: Callable[[], Coroutine[Any, Any, bool]],
+ events: AsyncGenerator[
+ Union[process_pb2.StartResponse, process_pb2.ConnectResponse], Any
+ ],
+ on_stdout: Optional[OutputHandler[Stdout]] = None,
+ on_stderr: Optional[OutputHandler[Stderr]] = None,
+ ):
+ self._pid = pid
+ self._handle_kill = handle_kill
+ self._events = events
+
+ self._stdout: str = ""
+ self._stderr: str = ""
+
+ self._on_stdout = on_stdout
+ self._on_stderr = on_stderr
+
+ self._result: Optional[ProcessResult] = None
+ self._iteration_exception: Optional[Exception] = None
+
+ self._wait = asyncio.create_task(self._handle_events())
+
+ async def _iterate_events(
+ self,
+ ) -> AsyncGenerator[
+ Union[Tuple[Stdout, None], Tuple[None, Stderr]],
+ None,
+ ]:
+ try:
+ async for event in self._events:
+ if event.event.HasField("data"):
+ if event.event.data.stdout:
+ out = event.event.data.stdout.decode()
+ self._stdout += out
+ yield out, None
+ if event.event.data.stderr:
+ out = event.event.data.stderr.decode()
+ self._stderr += out
+ yield None, out
+ if event.event.HasField("end"):
+ self._result = ProcessResult(
+ stdout=self._stdout,
+ stderr=self._stderr,
+ exit_code=event.event.end.exit_code,
+ error=event.event.end.error,
+ )
+ finally:
+ await self.disconnect()
+
+ async def disconnect(self) -> None:
+ await self._events.aclose()
+
+ async def _handle_events(self):
+ try:
+ async for stdout, stderr in self._iterate_events():
+ if stdout is not None and self._on_stdout:
+ cb = self._on_stdout(stdout)
+ if inspect.isawaitable(cb):
+ await cb
+ elif stderr is not None and self._on_stderr:
+ cb = self._on_stderr(stderr)
+ if inspect.isawaitable(cb):
+ await cb
+ except StopIteration:
+ pass
+ except Exception as e:
+ self._iteration_exception = handle_rpc_exception(e)
+
+ if self._iteration_exception:
+ raise self._iteration_exception
+
+ if self._result is None:
+ raise Exception("Process ended without an end event")
+
+ if self._result.exit_code != 0:
+ raise ProcessExitException(
+ stdout=self._stdout,
+ stderr=self._stderr,
+ exit_code=self._result.exit_code,
+ error=self._result.error,
+ )
+
+ return self._result
+
+ async def wait(self) -> ProcessResult:
+ await self._wait
+
+ if self._iteration_exception:
+ raise self._iteration_exception
+
+ if self._result is None:
+ raise Exception("Process ended without an end event")
+
+ if self._result.exit_code != 0:
+ raise ProcessExitException(
+ stdout=self._stdout,
+ stderr=self._stderr,
+ exit_code=self._result.exit_code,
+ error=self._result.error,
+ )
+
+ return self._result
+
+ async def kill(self):
+ await self._handle_kill()
diff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
new file mode 100644
index 000000000..5f1624379
--- /dev/null
+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
@@ -0,0 +1,174 @@
+from typing import Optional, Dict, List
+from httpx import AsyncHTTPTransport
+from packaging.version import Version
+
+from e2b.sandbox.sandbox_api import SandboxInfo, SandboxApiBase
+from e2b.exceptions import TemplateException
+from e2b.api import AsyncApiClient
+from e2b.api.client.models import NewSandbox, PostSandboxesSandboxIDTimeoutBody
+from e2b.api.client.api.sandboxes import (
+ post_sandboxes_sandbox_id_timeout,
+ get_sandboxes,
+ delete_sandboxes_sandbox_id,
+ post_sandboxes,
+)
+from e2b.connection_config import ConnectionConfig
+from e2b.api import handle_api_exception
+
+
+class SandboxApi(SandboxApiBase):
+ _transport = AsyncHTTPTransport(limits=SandboxApiBase._limits)
+
+ @classmethod
+ async def list(
+ cls,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ debug: Optional[bool] = None,
+ request_timeout: Optional[float] = None,
+ ) -> List[SandboxInfo]:
+ config = ConnectionConfig(
+ api_key=api_key,
+ domain=domain,
+ debug=debug,
+ request_timeout=request_timeout,
+ )
+
+ async with AsyncApiClient(config, transport=cls._transport) as api_client:
+ res = await get_sandboxes.asyncio_detailed(
+ client=api_client,
+ )
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res)
+
+ if res.parsed is None:
+ return []
+
+ return [
+ SandboxInfo(
+ sandbox_id=SandboxApi._get_sandbox_id(
+ sandbox.sandbox_id,
+ sandbox.client_id,
+ ),
+ template_id=sandbox.template_id,
+ name=sandbox.alias if isinstance(sandbox.alias, str) else None,
+ metadata=(
+ sandbox.metadata if isinstance(sandbox.metadata, dict) else None
+ ),
+ started_at=sandbox.started_at,
+ )
+ for sandbox in res.parsed
+ ]
+
+ @classmethod
+ async def _cls_kill(
+ cls,
+ sandbox_id: str,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ debug: Optional[bool] = None,
+ request_timeout: Optional[float] = None,
+ ) -> bool:
+ config = ConnectionConfig(
+ api_key=api_key,
+ domain=domain,
+ debug=debug,
+ request_timeout=request_timeout,
+ )
+
+ async with AsyncApiClient(config, transport=cls._transport) as api_client:
+ res = await delete_sandboxes_sandbox_id.asyncio_detailed(
+ sandbox_id,
+ client=api_client,
+ )
+
+ if res.status_code == 404:
+ return False
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res)
+
+ return True
+
+ @classmethod
+ async def _cls_set_timeout(
+ cls,
+ sandbox_id: str,
+ timeout: int,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ debug: Optional[bool] = None,
+ request_timeout: Optional[float] = None,
+ ) -> None:
+ config = ConnectionConfig(
+ api_key=api_key,
+ domain=domain,
+ debug=debug,
+ request_timeout=request_timeout,
+ )
+
+ async with AsyncApiClient(config, transport=cls._transport) as api_client:
+ res = await post_sandboxes_sandbox_id_timeout.asyncio_detailed(
+ sandbox_id,
+ client=api_client,
+ body=PostSandboxesSandboxIDTimeoutBody(timeout=timeout),
+ )
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res)
+
+ @classmethod
+ async def _create_sandbox(
+ cls,
+ template: str,
+ timeout: int,
+ metadata: Optional[Dict[str, str]] = None,
+ api_key: Optional[str] = None,
+ domain: Optional[str] = None,
+ debug: Optional[bool] = None,
+ request_timeout: Optional[float] = None,
+ ) -> str:
+ config = ConnectionConfig(
+ api_key=api_key,
+ domain=domain,
+ debug=debug,
+ request_timeout=request_timeout,
+ )
+
+ async with AsyncApiClient(config, transport=cls._transport) as api_client:
+ res = await post_sandboxes.asyncio_detailed(
+ body=NewSandbox(
+ template_id=template,
+ metadata=metadata or {},
+ timeout=timeout,
+ ),
+ client=api_client,
+ )
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res)
+
+ if res.parsed is None:
+ raise Exception("Body of the request is None")
+
+ if Version(res.parsed.envd_version) < Version("0.1.0"):
+ await SandboxApi._cls_kill(
+ SandboxApi._get_sandbox_id(
+ res.parsed.sandbox_id,
+ res.parsed.client_id,
+ )
+ )
+ raise TemplateException(
+ "You need to update the template to use the new SDK. "
+ "You can do this by running `e2b template build` in the directory with the template."
+ )
+
+ return SandboxApi._get_sandbox_id(
+ res.parsed.sandbox_id,
+ res.parsed.client_id,
+ )
+
+ @staticmethod
+ def _get_sandbox_id(sandbox_id: str, client_id: str) -> str:
+ return f"{sandbox_id}-{client_id}"
diff --git a/packages/python-sdk/e2b/sandbox_async/utilts.py b/packages/python-sdk/e2b/sandbox_async/utilts.py
new file mode 100644
index 000000000..9ed32566b
--- /dev/null
+++ b/packages/python-sdk/e2b/sandbox_async/utilts.py
@@ -0,0 +1,7 @@
+from typing import TypeVar, Union, Callable, Awaitable
+
+T = TypeVar("T")
+OutputHandler = Union[
+ Callable[[T], None],
+ Callable[[T], Awaitable[None]],
+]
diff --git a/packages/python-sdk/e2b/sandbox/sync/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
similarity index 88%
rename from packages/python-sdk/e2b/sandbox/sync/filesystem/filesystem.py
rename to packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
index 43f815f51..bd9f08807 100644
--- a/packages/python-sdk/e2b/sandbox/sync/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
@@ -1,4 +1,4 @@
-import connect
+import e2b_connect
import httpx
import httpcore
@@ -13,7 +13,7 @@ from typing import (
)
from e2b.sandbox.filesystem.filesystem import EntryInfo, map_file_type
-from e2b.sandbox.sync.filesystem.watch_handle import WatchHandle
+from e2b.sandbox_sync.filesystem.watch_handle import WatchHandle
from e2b.connection_config import (
Username,
ConnectionConfig,
@@ -42,7 +42,7 @@ class Filesystem:
self._rpc = filesystem_connect.FilesystemClient(
envd_api_url,
- compressor=connect.GzipCompressor,
+ compressor=e2b_connect.GzipCompressor,
pool=pool,
)
@@ -123,9 +123,7 @@ class Filesystem:
) -> List[EntryInfo]:
try:
res = self._rpc.list_dir(
- filesystem_pb2.ListDirRequest(
- path=path,
- ),
+ filesystem_pb2.ListDirRequest(path=path),
request_timeout=self._connection_config.get_request_timeout(
request_timeout
),
@@ -151,9 +149,7 @@ class Filesystem:
) -> bool:
try:
self._rpc.stat(
- filesystem_pb2.StatRequest(
- path=path,
- ),
+ filesystem_pb2.StatRequest(path=path),
request_timeout=self._connection_config.get_request_timeout(
request_timeout
),
@@ -162,8 +158,8 @@ class Filesystem:
return True
except Exception as e:
- if isinstance(e, connect.ConnectException):
- if e.status == connect.Code.not_found:
+ if isinstance(e, e2b_connect.ConnectException):
+ if e.status == e2b_connect.Code.not_found:
return False
raise handle_rpc_exception(e)
@@ -175,9 +171,7 @@ class Filesystem:
) -> None:
try:
self._rpc.remove(
- filesystem_pb2.RemoveRequest(
- path=path,
- ),
+ filesystem_pb2.RemoveRequest(path=path),
request_timeout=self._connection_config.get_request_timeout(
request_timeout
),
@@ -215,9 +209,7 @@ class Filesystem:
) -> bool:
try:
self._rpc.make_dir(
- filesystem_pb2.MakeDirRequest(
- path=path,
- ),
+ filesystem_pb2.MakeDirRequest(path=path),
request_timeout=self._connection_config.get_request_timeout(
request_timeout
),
@@ -226,8 +218,8 @@ class Filesystem:
return True
except Exception as e:
- if isinstance(e, connect.ConnectException):
- if e.status == connect.Code.already_exists:
+ if isinstance(e, e2b_connect.ConnectException):
+ if e.status == e2b_connect.Code.already_exists:
return False
raise handle_rpc_exception(e)
@@ -239,9 +231,7 @@ class Filesystem:
timeout: Optional[float] = 60,
):
events = self._rpc.watch_dir(
- filesystem_pb2.WatchDirRequest(
- path=path,
- ),
+ filesystem_pb2.WatchDirRequest(path=path),
request_timeout=self._connection_config.get_request_timeout(
request_timeout
),
@@ -250,7 +240,7 @@ class Filesystem:
)
try:
- start_event = next(events)
+ start_event = events.__next__()
if not start_event.HasField("start"):
raise SandboxException(
diff --git a/packages/python-sdk/e2b/sandbox/sync/filesystem/watch_handle.py b/packages/python-sdk/e2b/sandbox_sync/filesystem/watch_handle.py
similarity index 100%
rename from packages/python-sdk/e2b/sandbox/sync/filesystem/watch_handle.py
rename to packages/python-sdk/e2b/sandbox_sync/filesystem/watch_handle.py
diff --git a/packages/python-sdk/e2b/sandbox/sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.py
similarity index 69%
rename from packages/python-sdk/e2b/sandbox/sync/main.py
rename to packages/python-sdk/e2b/sandbox_sync/main.py
index 011d9f613..bc5c353ed 100644
--- a/packages/python-sdk/e2b/sandbox/sync/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/main.py
@@ -1,5 +1,4 @@
import logging
-import urllib.parse
import httpcore
import httpx
@@ -8,28 +7,27 @@ from typing import Optional, Dict, Literal, overload
from e2b.sandbox.utils import class_method_variant
from e2b.connection_config import ConnectionConfig
from e2b.envd.api import (
- ENVD_API_FILES_ROUTE,
handle_envd_api_exception,
ENVD_API_HEALTH_ROUTE,
)
from e2b.exceptions import SandboxException
-from e2b.sandbox.sync.filesystem.filesystem import Filesystem
-from e2b.sandbox.sync.process.main import Process
-from e2b.sandbox.sync.sandbox_api import SandboxApi
from e2b.sandbox.main import SandboxSetup
+from e2b.sandbox_sync.filesystem.filesystem import Filesystem
+from e2b.sandbox_sync.process.main import Process
+from e2b.sandbox_sync.sandbox_api import SandboxApi
logger = logging.getLogger(__name__)
-class E2BConnectionPool(httpcore.ConnectionPool):
+class TransportWithLogger(httpx.HTTPTransport):
def handle_request(self, request):
- url = f"{request.url.scheme.decode()}://{request.url.host.decode()}{request.url.target.decode()}"
- logger.info(f"Request: {request.method.decode()} {url}")
+ 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} {url}")
+ logger.info(f"Response: {response.status_code} {url}")
return response
@@ -43,6 +41,18 @@ class Sandbox(SandboxSetup, SandboxApi):
def commands(self) -> Process:
return self._process
+ @property
+ def sandbox_id(self) -> str:
+ return self._sandbox_id
+
+ @property
+ def connection_config(self) -> ConnectionConfig:
+ return self._connection_config
+
+ @property
+ def envd_api_url(self) -> str:
+ return self._envd_api_url
+
def __init__(
self,
template: Optional[str] = None,
@@ -69,14 +79,14 @@ class Sandbox(SandboxSetup, SandboxApi):
request_timeout=request_timeout,
)
- if self._connection_config.debug:
- self.sandbox_id = "debug_sandbox_id"
+ if self.connection_config.debug:
+ self._sandbox_id = "debug_sandbox_id"
elif sandbox_id is not None:
- self.sandbox_id = sandbox_id
+ self._sandbox_id = sandbox_id
else:
template = template or self.default_template
timeout = timeout or self.default_sandbox_timeout
- self.sandbox_id = SandboxApi._create_sandbox(
+ self._sandbox_id = SandboxApi._create_sandbox(
template=template,
api_key=api_key,
timeout=timeout,
@@ -86,31 +96,30 @@ class Sandbox(SandboxSetup, SandboxApi):
request_timeout=request_timeout,
)
- self._envd_api_url = f"{'http' if self._connection_config.debug else 'https'}://{self.get_host(self._envd_port)}"
+ self._envd_api_url = f"{'http' if self.connection_config.debug else 'https'}://{self.get_host(self.envd_port)}"
- self._envd_rpc_pool = E2BConnectionPool(max_connections=25)
- self._envd_api = httpx.Client(base_url=self._envd_api_url)
+ self._transport = TransportWithLogger(limits=self._limits)
+ self._envd_api = httpx.Client(
+ base_url=self.envd_api_url,
+ transport=self._transport,
+ )
self._filesystem = Filesystem(
- self._envd_api_url,
- self._connection_config,
- self._envd_rpc_pool,
+ self.envd_api_url,
+ self.connection_config,
+ self._transport._pool,
self._envd_api,
)
self._process = Process(
- self._envd_api_url, self._connection_config, self._envd_rpc_pool
+ self.envd_api_url,
+ self.connection_config,
+ self._transport._pool,
)
- def get_host(self, port: int) -> str:
- if self._connection_config.debug:
- return f"localhost:{port}"
-
- return f"{port}-{self.sandbox_id}.{self._connection_config.domain}"
-
def is_running(self, request_timeout: Optional[float] = None) -> Literal[True]:
r = self._envd_api.get(
ENVD_API_HEALTH_ROUTE,
- timeout=self._connection_config.get_request_timeout(request_timeout),
+ timeout=self.connection_config.get_request_timeout(request_timeout),
)
err = handle_envd_api_exception(r)
@@ -134,19 +143,6 @@ class Sandbox(SandboxSetup, SandboxApi):
debug=debug,
)
- def upload_url(self, path: Optional[str] = None) -> str:
- url = urllib.parse.urljoin(self._envd_api_url, ENVD_API_FILES_ROUTE)
- query = {"path": path} if path else {}
- query = {**query, "username": "user"}
-
- params = urllib.parse.urlencode(
- query,
- quote_via=urllib.parse.quote,
- )
- url = urllib.parse.urljoin(url, f"?{params}")
-
- return url
-
def __enter__(self):
return self
@@ -168,7 +164,7 @@ class Sandbox(SandboxSetup, SandboxApi):
@class_method_variant("_cls_kill")
def kill(self, request_timeout: Optional[float] = None) -> bool: # type: ignore
- config_dict = self._connection_config.__dict__
+ config_dict = self.connection_config.__dict__
config_dict.pop("access_token", None)
config_dict.pop("api_url", None)
@@ -177,7 +173,7 @@ class Sandbox(SandboxSetup, SandboxApi):
SandboxApi._cls_kill(
sandbox_id=self.sandbox_id,
- **self._connection_config.__dict__,
+ **self.connection_config.__dict__,
)
@overload
@@ -204,7 +200,7 @@ class Sandbox(SandboxSetup, SandboxApi):
timeout: int,
request_timeout: Optional[float] = None,
) -> None:
- config_dict = self._connection_config.__dict__
+ config_dict = self.connection_config.__dict__
config_dict.pop("access_token", None)
config_dict.pop("api_url", None)
@@ -214,5 +210,5 @@ class Sandbox(SandboxSetup, SandboxApi):
SandboxApi._cls_set_timeout(
sandbox_id=self.sandbox_id,
timeout=timeout,
- **self._connection_config.__dict__,
+ **self.connection_config.__dict__,
)
diff --git a/packages/python-sdk/e2b/sandbox/sync/process/main.py b/packages/python-sdk/e2b/sandbox_sync/process/main.py
similarity index 95%
rename from packages/python-sdk/e2b/sandbox/sync/process/main.py
rename to packages/python-sdk/e2b/sandbox_sync/process/main.py
index b5c7449c4..c39563d4b 100644
--- a/packages/python-sdk/e2b/sandbox/sync/process/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/process/main.py
@@ -1,4 +1,4 @@
-import connect
+import e2b_connect
import httpcore
from typing import Dict, List, Optional, Literal, overload, Union, Callable
@@ -12,7 +12,7 @@ from e2b.exceptions import SandboxException
from e2b.envd.rpc import authentication_header, handle_rpc_exception
from e2b.sandbox.process.main import ProcessInfo
from e2b.sandbox.process.process_handle import ProcessResult
-from e2b.sandbox.sync.process.process_handle import ProcessHandle
+from e2b.sandbox_sync.process.process_handle import ProcessHandle
class Process:
@@ -72,8 +72,8 @@ class Process:
)
return True
except Exception as e:
- if isinstance(e, connect.ConnectException):
- if e.status == connect.Code.not_found:
+ if isinstance(e, e2b_connect.ConnectException):
+ if e.status == e2b_connect.Code.not_found:
return False
raise handle_rpc_exception(e)
@@ -120,8 +120,8 @@ class Process:
envs: Optional[Dict[str, str]] = {},
user: Username = "user",
cwd: Optional[str] = None,
- on_stdout: Optional[Callable[[str], None]] = None,
- on_stderr: Optional[Callable[[str], None]] = None,
+ on_stdout: None = None,
+ on_stderr: None = None,
timeout: Optional[float] = 60,
request_timeout: Optional[float] = None,
) -> ProcessHandle: ...
diff --git a/packages/python-sdk/e2b/sandbox/sync/process/process_handle.py b/packages/python-sdk/e2b/sandbox_sync/process/process_handle.py
similarity index 100%
rename from packages/python-sdk/e2b/sandbox/sync/process/process_handle.py
rename to packages/python-sdk/e2b/sandbox_sync/process/process_handle.py
diff --git a/packages/python-sdk/e2b/sandbox/sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
similarity index 91%
rename from packages/python-sdk/e2b/sandbox/sync/sandbox_api.py
rename to packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
index 7c9a78059..f06b0830c 100644
--- a/packages/python-sdk/e2b/sandbox/sync/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
@@ -1,7 +1,8 @@
+from httpx import HTTPTransport
from typing import Optional, Dict, List
from packaging.version import Version
-from e2b.sandbox.sandbox_api import SandboxInfo
+from e2b.sandbox.sandbox_api import SandboxInfo, SandboxApiBase
from e2b.exceptions import TemplateException
from e2b.api import ApiClient
from e2b.api.client.models import NewSandbox, PostSandboxesSandboxIDTimeoutBody
@@ -15,7 +16,9 @@ from e2b.connection_config import ConnectionConfig
from e2b.api import handle_api_exception
-class SandboxApi:
+class SandboxApi(SandboxApiBase):
+ _transport = HTTPTransport(limits=SandboxApiBase._limits)
+
@classmethod
def list(
cls,
@@ -31,7 +34,7 @@ class SandboxApi:
request_timeout=request_timeout,
)
- with ApiClient(config) as api_client:
+ with ApiClient(config, transport=cls._transport) as api_client:
res = get_sandboxes.sync_detailed(
client=api_client,
)
@@ -56,7 +59,6 @@ class SandboxApi:
started_at=sandbox.started_at,
)
for sandbox in res.parsed
- if sandbox is not None
]
@classmethod
@@ -75,7 +77,7 @@ class SandboxApi:
request_timeout=request_timeout,
)
- with ApiClient(config) as api_client:
+ with ApiClient(config, transport=cls._transport) as api_client:
res = delete_sandboxes_sandbox_id.sync_detailed(
sandbox_id,
client=api_client,
@@ -106,7 +108,7 @@ class SandboxApi:
request_timeout=request_timeout,
)
- with ApiClient(config) as api_client:
+ with ApiClient(config, transport=cls._transport) as api_client:
res = post_sandboxes_sandbox_id_timeout.sync_detailed(
sandbox_id,
client=api_client,
@@ -134,7 +136,7 @@ class SandboxApi:
request_timeout=request_timeout,
)
- with ApiClient(config) as api_client:
+ with ApiClient(config, transport=cls._transport) as api_client:
res = post_sandboxes.sync_detailed(
body=NewSandbox(
template_id=template,
@@ -166,7 +168,3 @@ class SandboxApi:
res.parsed.sandbox_id,
res.parsed.client_id,
)
-
- @staticmethod
- def _get_sandbox_id(sandbox_id: str, client_id: str) -> str:
- return f"{sandbox_id}-{client_id}"
diff --git a/packages/python-sdk/connect/__init__.py b/packages/python-sdk/e2b_connect/__init__.py
similarity index 100%
rename from packages/python-sdk/connect/__init__.py
rename to packages/python-sdk/e2b_connect/__init__.py
diff --git a/packages/python-sdk/connect/client.py b/packages/python-sdk/e2b_connect/client.py
similarity index 100%
rename from packages/python-sdk/connect/client.py
rename to packages/python-sdk/e2b_connect/client.py
diff --git a/packages/python-sdk/example.py b/packages/python-sdk/example.py
index 7297e727e..8b5e07a41 100644
--- a/packages/python-sdk/example.py
+++ b/packages/python-sdk/example.py
@@ -1,27 +1,22 @@
-# from typing import Coroutine, Any
+import asyncio
+import time
+import logging
+from e2b import AsyncSandbox, Sandbox
import dotenv
dotenv.load_dotenv()
-from e2b import Sandbox
+logging.basicConfig(level=logging.ERROR)
-sbx = Sandbox()
-r = sbx.list()
+async def main():
+ for _ in range(10):
+ start = time.time()
+ sbx = await AsyncSandbox.create(timeout=10)
+ end = time.time()
+ print(f"Time taken: {end - start}")
-print(r)
-f = sbx.files.list("/")
-
-print(f)
-
-
-# sbx.files.list("/")
-
-
-# async def a():
-# return "a"
-
-
-# x = a()
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/packages/python-sdk/poetry.lock b/packages/python-sdk/poetry.lock
index 57ab875bb..5ded889f9 100644
--- a/packages/python-sdk/poetry.lock
+++ b/packages/python-sdk/poetry.lock
@@ -229,92 +229,6 @@ files = [
{file = "iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3"},
]
-[[package]]
-name = "jinja2"
-version = "3.1.4"
-description = "A very fast and expressive template engine."
-optional = false
-python-versions = ">=3.7"
-files = [
- {file = "jinja2-3.1.4-py3-none-any.whl", hash = "sha256:bc5dd2abb727a5319567b7a813e6a2e7318c39f4f487cfe6c89c6f9c7d25197d"},
- {file = "jinja2-3.1.4.tar.gz", hash = "sha256:4a3aee7acbbe7303aede8e9648d13b8bf88a429282aa6122a993f0ac800cb369"},
-]
-
-[package.dependencies]
-MarkupSafe = ">=2.0"
-
-[package.extras]
-i18n = ["Babel (>=2.7)"]
-
-[[package]]
-name = "markupsafe"
-version = "2.1.5"
-description = "Safely add untrusted strings to HTML/XML markup."
-optional = false
-python-versions = ">=3.7"
-files = [
- {file = "MarkupSafe-2.1.5-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:a17a92de5231666cfbe003f0e4b9b3a7ae3afb1ec2845aadc2bacc93ff85febc"},
- {file = "MarkupSafe-2.1.5-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:72b6be590cc35924b02c78ef34b467da4ba07e4e0f0454a2c5907f473fc50ce5"},
- {file = "MarkupSafe-2.1.5-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e61659ba32cf2cf1481e575d0462554625196a1f2fc06a1c777d3f48e8865d46"},
- {file = "MarkupSafe-2.1.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2174c595a0d73a3080ca3257b40096db99799265e1c27cc5a610743acd86d62f"},
- {file = "MarkupSafe-2.1.5-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ae2ad8ae6ebee9d2d94b17fb62763125f3f374c25618198f40cbb8b525411900"},
- {file = "MarkupSafe-2.1.5-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:075202fa5b72c86ad32dc7d0b56024ebdbcf2048c0ba09f1cde31bfdd57bcfff"},
- {file = "MarkupSafe-2.1.5-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:598e3276b64aff0e7b3451b72e94fa3c238d452e7ddcd893c3ab324717456bad"},
- {file = "MarkupSafe-2.1.5-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:fce659a462a1be54d2ffcacea5e3ba2d74daa74f30f5f143fe0c58636e355fdd"},
- {file = "MarkupSafe-2.1.5-cp310-cp310-win32.whl", hash = "sha256:d9fad5155d72433c921b782e58892377c44bd6252b5af2f67f16b194987338a4"},
- {file = "MarkupSafe-2.1.5-cp310-cp310-win_amd64.whl", hash = "sha256:bf50cd79a75d181c9181df03572cdce0fbb75cc353bc350712073108cba98de5"},
- {file = "MarkupSafe-2.1.5-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:629ddd2ca402ae6dbedfceeba9c46d5f7b2a61d9749597d4307f943ef198fc1f"},
- {file = "MarkupSafe-2.1.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:5b7b716f97b52c5a14bffdf688f971b2d5ef4029127f1ad7a513973cfd818df2"},
- {file = "MarkupSafe-2.1.5-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6ec585f69cec0aa07d945b20805be741395e28ac1627333b1c5b0105962ffced"},
- {file = "MarkupSafe-2.1.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b91c037585eba9095565a3556f611e3cbfaa42ca1e865f7b8015fe5c7336d5a5"},
- {file = "MarkupSafe-2.1.5-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:7502934a33b54030eaf1194c21c692a534196063db72176b0c4028e140f8f32c"},
- {file = "MarkupSafe-2.1.5-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:0e397ac966fdf721b2c528cf028494e86172b4feba51d65f81ffd65c63798f3f"},
- {file = "MarkupSafe-2.1.5-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:c061bb86a71b42465156a3ee7bd58c8c2ceacdbeb95d05a99893e08b8467359a"},
- {file = "MarkupSafe-2.1.5-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:3a57fdd7ce31c7ff06cdfbf31dafa96cc533c21e443d57f5b1ecc6cdc668ec7f"},
- {file = "MarkupSafe-2.1.5-cp311-cp311-win32.whl", hash = "sha256:397081c1a0bfb5124355710fe79478cdbeb39626492b15d399526ae53422b906"},
- {file = "MarkupSafe-2.1.5-cp311-cp311-win_amd64.whl", hash = "sha256:2b7c57a4dfc4f16f7142221afe5ba4e093e09e728ca65c51f5620c9aaeb9a617"},
- {file = "MarkupSafe-2.1.5-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:8dec4936e9c3100156f8a2dc89c4b88d5c435175ff03413b443469c7c8c5f4d1"},
- {file = "MarkupSafe-2.1.5-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:3c6b973f22eb18a789b1460b4b91bf04ae3f0c4234a0a6aa6b0a92f6f7b951d4"},
- {file = "MarkupSafe-2.1.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ac07bad82163452a6884fe8fa0963fb98c2346ba78d779ec06bd7a6262132aee"},
- {file = "MarkupSafe-2.1.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f5dfb42c4604dddc8e4305050aa6deb084540643ed5804d7455b5df8fe16f5e5"},
- {file = "MarkupSafe-2.1.5-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ea3d8a3d18833cf4304cd2fc9cbb1efe188ca9b5efef2bdac7adc20594a0e46b"},
- {file = "MarkupSafe-2.1.5-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:d050b3361367a06d752db6ead6e7edeb0009be66bc3bae0ee9d97fb326badc2a"},
- {file = "MarkupSafe-2.1.5-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:bec0a414d016ac1a18862a519e54b2fd0fc8bbfd6890376898a6c0891dd82e9f"},
- {file = "MarkupSafe-2.1.5-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:58c98fee265677f63a4385256a6d7683ab1832f3ddd1e66fe948d5880c21a169"},
- {file = "MarkupSafe-2.1.5-cp312-cp312-win32.whl", hash = "sha256:8590b4ae07a35970728874632fed7bd57b26b0102df2d2b233b6d9d82f6c62ad"},
- {file = "MarkupSafe-2.1.5-cp312-cp312-win_amd64.whl", hash = "sha256:823b65d8706e32ad2df51ed89496147a42a2a6e01c13cfb6ffb8b1e92bc910bb"},
- {file = "MarkupSafe-2.1.5-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:c8b29db45f8fe46ad280a7294f5c3ec36dbac9491f2d1c17345be8e69cc5928f"},
- {file = "MarkupSafe-2.1.5-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ec6a563cff360b50eed26f13adc43e61bc0c04d94b8be985e6fb24b81f6dcfdf"},
- {file = "MarkupSafe-2.1.5-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a549b9c31bec33820e885335b451286e2969a2d9e24879f83fe904a5ce59d70a"},
- {file = "MarkupSafe-2.1.5-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4f11aa001c540f62c6166c7726f71f7573b52c68c31f014c25cc7901deea0b52"},
- {file = "MarkupSafe-2.1.5-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:7b2e5a267c855eea6b4283940daa6e88a285f5f2a67f2220203786dfa59b37e9"},
- {file = "MarkupSafe-2.1.5-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:2d2d793e36e230fd32babe143b04cec8a8b3eb8a3122d2aceb4a371e6b09b8df"},
- {file = "MarkupSafe-2.1.5-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:ce409136744f6521e39fd8e2a24c53fa18ad67aa5bc7c2cf83645cce5b5c4e50"},
- {file = "MarkupSafe-2.1.5-cp37-cp37m-win32.whl", hash = "sha256:4096e9de5c6fdf43fb4f04c26fb114f61ef0bf2e5604b6ee3019d51b69e8c371"},
- {file = "MarkupSafe-2.1.5-cp37-cp37m-win_amd64.whl", hash = "sha256:4275d846e41ecefa46e2015117a9f491e57a71ddd59bbead77e904dc02b1bed2"},
- {file = "MarkupSafe-2.1.5-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:656f7526c69fac7f600bd1f400991cc282b417d17539a1b228617081106feb4a"},
- {file = "MarkupSafe-2.1.5-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:97cafb1f3cbcd3fd2b6fbfb99ae11cdb14deea0736fc2b0952ee177f2b813a46"},
- {file = "MarkupSafe-2.1.5-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1f3fbcb7ef1f16e48246f704ab79d79da8a46891e2da03f8783a5b6fa41a9532"},
- {file = "MarkupSafe-2.1.5-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fa9db3f79de01457b03d4f01b34cf91bc0048eb2c3846ff26f66687c2f6d16ab"},
- {file = "MarkupSafe-2.1.5-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ffee1f21e5ef0d712f9033568f8344d5da8cc2869dbd08d87c84656e6a2d2f68"},
- {file = "MarkupSafe-2.1.5-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:5dedb4db619ba5a2787a94d877bc8ffc0566f92a01c0ef214865e54ecc9ee5e0"},
- {file = "MarkupSafe-2.1.5-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:30b600cf0a7ac9234b2638fbc0fb6158ba5bdcdf46aeb631ead21248b9affbc4"},
- {file = "MarkupSafe-2.1.5-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:8dd717634f5a044f860435c1d8c16a270ddf0ef8588d4887037c5028b859b0c3"},
- {file = "MarkupSafe-2.1.5-cp38-cp38-win32.whl", hash = "sha256:daa4ee5a243f0f20d528d939d06670a298dd39b1ad5f8a72a4275124a7819eff"},
- {file = "MarkupSafe-2.1.5-cp38-cp38-win_amd64.whl", hash = "sha256:619bc166c4f2de5caa5a633b8b7326fbe98e0ccbfacabd87268a2b15ff73a029"},
- {file = "MarkupSafe-2.1.5-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:7a68b554d356a91cce1236aa7682dc01df0edba8d043fd1ce607c49dd3c1edcf"},
- {file = "MarkupSafe-2.1.5-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:db0b55e0f3cc0be60c1f19efdde9a637c32740486004f20d1cff53c3c0ece4d2"},
- {file = "MarkupSafe-2.1.5-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3e53af139f8579a6d5f7b76549125f0d94d7e630761a2111bc431fd820e163b8"},
- {file = "MarkupSafe-2.1.5-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:17b950fccb810b3293638215058e432159d2b71005c74371d784862b7e4683f3"},
- {file = "MarkupSafe-2.1.5-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4c31f53cdae6ecfa91a77820e8b151dba54ab528ba65dfd235c80b086d68a465"},
- {file = "MarkupSafe-2.1.5-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:bff1b4290a66b490a2f4719358c0cdcd9bafb6b8f061e45c7a2460866bf50c2e"},
- {file = "MarkupSafe-2.1.5-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:bc1667f8b83f48511b94671e0e441401371dfd0f0a795c7daa4a3cd1dde55bea"},
- {file = "MarkupSafe-2.1.5-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:5049256f536511ee3f7e1b3f87d1d1209d327e818e6ae1365e8653d7e3abb6a6"},
- {file = "MarkupSafe-2.1.5-cp39-cp39-win32.whl", hash = "sha256:00e046b6dd71aa03a41079792f8473dc494d564611a8f89bbbd7cb93295ebdcf"},
- {file = "MarkupSafe-2.1.5-cp39-cp39-win_amd64.whl", hash = "sha256:fa173ec60341d6bb97a89f5ea19c85c5643c1e7dedebc22f5181eb73573142c5"},
- {file = "MarkupSafe-2.1.5.tar.gz", hash = "sha256:d283d37a890ba4c1ae73ffadf8046435c76e7bc2247bbb63c00bd1a709c6544b"},
-]
-
[[package]]
name = "mypy-extensions"
version = "1.0.0"
@@ -531,4 +445,4 @@ files = [
[metadata]
lock-version = "2.0"
python-versions = "^3.8"
-content-hash = "9a1a11cb738cdd20e49d4ebc519e3d57e0f9641cd1e29e4aa6faf1c25094c1bb"
+content-hash = "e0bad63042465728305d56fa013c5e7c9c207e6d1f31630d1c137c4456ae20a6"
diff --git a/packages/python-sdk/pyproject.toml b/packages/python-sdk/pyproject.toml
index 755dd2691..ce0cc537b 100644
--- a/packages/python-sdk/pyproject.toml
+++ b/packages/python-sdk/pyproject.toml
@@ -7,7 +7,7 @@ license = "MIT"
readme = "README.md"
homepage = "https://e2b.dev/"
repository = "https://github.com/e2b-dev/e2b/tree/main/packages/python-sdk"
-packages = [{ include = "e2b" }, { include = "connect" }]
+packages = [{ include = "e2b" }, { include = "e2b_connect" }]
[tool.poetry.dependencies]
python = "^3.8"
@@ -17,7 +17,6 @@ protobuf = "^5.26.1"
httpcore = "^1.0.5"
httpx = "^0.27.0"
attrs = "^23.2.0"
-typing-extensions = "^4.12.2"
[tool.poetry.group.dev.dependencies]
black = "^23.7.0"
@@ -25,7 +24,6 @@ pytest = "^7.4.0"
pytest-xdist = "^3.3.1"
python-dotenv = "^1.0.0"
pytest-dotenv = "^0.5.2"
-jinja2 = "^3.1.4"
[build-system]
requires = ["poetry-core"]
diff --git a/packages/python-sdk/tests/conftest.py b/packages/python-sdk/tests/conftest.py
index 7d3992189..f4f5a0682 100644
--- a/packages/python-sdk/tests/conftest.py
+++ b/packages/python-sdk/tests/conftest.py
@@ -3,7 +3,7 @@ import os
from logging import warning
-from e2b import Sandbox
+from e2b import Sandbox, AsyncSandbox
@pytest.fixture()
@@ -27,6 +27,22 @@ def sandbox(template, debug):
)
+async def async_sandbox(template, debug):
+ sandbox = await AsyncSandbox.create(template)
+
+ try:
+ yield sandbox
+ finally:
+ try:
+ await sandbox.kill()
+ except:
+ if not debug:
+ warning(
+ "Failed to kill sandbox — this is expected if the test runs with local envd."
+ )
+
+
@pytest.fixture
def debug():
return os.getenv("E2B_DEBUG") is not None
diff --git a/packages/python-sdk/tests/sandbox/test_upload_url.py b/packages/python-sdk/tests/sandbox/test_upload_url.py
deleted file mode 100644
index 20b15530d..000000000
--- a/packages/python-sdk/tests/sandbox/test_upload_url.py
+++ /dev/null
@@ -1 +0,0 @@
-import requests
diff --git a/packages/python-sdk/tests/sandbox/commands/test_cmd_connect.py b/packages/python-sdk/tests/sandbox_async/commands/test_cmd_connect.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/commands/test_cmd_connect.py
rename to packages/python-sdk/tests/sandbox_async/commands/test_cmd_connect.py
diff --git a/packages/python-sdk/tests/sandbox/commands/test_cmd_kill.py b/packages/python-sdk/tests/sandbox_async/commands/test_cmd_kill.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/commands/test_cmd_kill.py
rename to packages/python-sdk/tests/sandbox_async/commands/test_cmd_kill.py
diff --git a/packages/python-sdk/tests/sandbox/commands/test_cmd_list.py b/packages/python-sdk/tests/sandbox_async/commands/test_cmd_list.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/commands/test_cmd_list.py
rename to packages/python-sdk/tests/sandbox_async/commands/test_cmd_list.py
diff --git a/packages/python-sdk/tests/sandbox/commands/test_run.py b/packages/python-sdk/tests/sandbox_async/commands/test_run.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/commands/test_run.py
rename to packages/python-sdk/tests/sandbox_async/commands/test_run.py
diff --git a/packages/python-sdk/tests/sandbox/commands/test_send_stdin.py b/packages/python-sdk/tests/sandbox_async/commands/test_send_stdin.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/commands/test_send_stdin.py
rename to packages/python-sdk/tests/sandbox_async/commands/test_send_stdin.py
diff --git a/packages/python-sdk/tests/sandbox_async/files/test_exists.py b/packages/python-sdk/tests/sandbox_async/files/test_exists.py
new file mode 100644
index 000000000..dc7057d6b
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_async/files/test_exists.py
@@ -0,0 +1,11 @@
+import pytest
+
+from e2b import AsyncSandbox
+
+
+async def test_exists(async_sandbox: AsyncSandbox):
+ filename = "test_exists.txt"
+
+ await async_sandbox.files.write(filename, "test")
+ assert await async_sandbox.files.exists(filename)
diff --git a/packages/python-sdk/tests/sandbox/files/test_files_list.py b/packages/python-sdk/tests/sandbox_async/files/test_files_list.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/files/test_files_list.py
rename to packages/python-sdk/tests/sandbox_async/files/test_files_list.py
diff --git a/packages/python-sdk/tests/sandbox/files/test_make_dir.py b/packages/python-sdk/tests/sandbox_async/files/test_make_dir.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/files/test_make_dir.py
rename to packages/python-sdk/tests/sandbox_async/files/test_make_dir.py
diff --git a/packages/python-sdk/tests/sandbox/files/test_read.py b/packages/python-sdk/tests/sandbox_async/files/test_read.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/files/test_read.py
rename to packages/python-sdk/tests/sandbox_async/files/test_read.py
diff --git a/packages/python-sdk/tests/sandbox/files/test_remove.py b/packages/python-sdk/tests/sandbox_async/files/test_remove.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/files/test_remove.py
rename to packages/python-sdk/tests/sandbox_async/files/test_remove.py
diff --git a/packages/python-sdk/tests/sandbox/files/test_rename.py b/packages/python-sdk/tests/sandbox_async/files/test_rename.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/files/test_rename.py
rename to packages/python-sdk/tests/sandbox_async/files/test_rename.py
diff --git a/packages/python-sdk/tests/sandbox/files/test_watch.py b/packages/python-sdk/tests/sandbox_async/files/test_watch.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/files/test_watch.py
rename to packages/python-sdk/tests/sandbox_async/files/test_watch.py
diff --git a/packages/python-sdk/tests/sandbox/files/test_write.py b/packages/python-sdk/tests/sandbox_async/files/test_write.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/files/test_write.py
rename to packages/python-sdk/tests/sandbox_async/files/test_write.py
diff --git a/packages/python-sdk/tests/sandbox/pty/test_pty_create.py b/packages/python-sdk/tests/sandbox_async/pty/test_pty_create.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/pty/test_pty_create.py
rename to packages/python-sdk/tests/sandbox_async/pty/test_pty_create.py
diff --git a/packages/python-sdk/tests/sandbox/pty/test_resize.py b/packages/python-sdk/tests/sandbox_async/pty/test_resize.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/pty/test_resize.py
rename to packages/python-sdk/tests/sandbox_async/pty/test_resize.py
diff --git a/packages/python-sdk/tests/sandbox/pty/test_stream_input.py b/packages/python-sdk/tests/sandbox_async/pty/test_stream_input.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/pty/test_stream_input.py
rename to packages/python-sdk/tests/sandbox_async/pty/test_stream_input.py
diff --git a/packages/python-sdk/tests/sandbox_async/test_connect.py b/packages/python-sdk/tests/sandbox_async/test_connect.py
new file mode 100644
index 000000000..651ca23d5
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_async/test_connect.py
@@ -0,0 +1,12 @@
+import pytest
+
+from e2b import AsyncSandbox
+
+
+async def test_connect(template):
+ sbx = await AsyncSandbox.create(template, timeout=10)
+ assert await sbx.is_running()
+
+ sbx_connection = await AsyncSandbox.connect(sbx.sandbox_id)
+ assert await sbx_connection.is_running()
diff --git a/packages/python-sdk/tests/sandbox_async/test_create.py b/packages/python-sdk/tests/sandbox_async/test_create.py
new file mode 100644
index 000000000..cee667c62
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_async/test_create.py
@@ -0,0 +1,27 @@
+import pytest
+
+from e2b import AsyncSandbox
+
+
+async def test_start(template):
+ sbx = await AsyncSandbox.create(template, timeout=5)
+ assert await sbx.is_running()
+
+
+async def test_metadata(template):
+ sbx = await AsyncSandbox.create(
+ template, timeout=5, metadata={"test-key": "test-value"}
+ )
+ sbxs = await AsyncSandbox.list()
+
+ for sbx_info in sbxs:
+ 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/sandbox_async/test_host.py b/packages/python-sdk/tests/sandbox_async/test_host.py
new file mode 100644
index 000000000..749fbf656
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_async/test_host.py
@@ -0,0 +1,20 @@
+import httpx
+import pytest
+
+from time import sleep
+
+from e2b import AsyncSandbox
+
+
+async def test_ping_server(async_sandbox: AsyncSandbox, debug):
+ cmd = async_sandbox.commands.run("python -m http.server 8000", background=True)
+
+ try:
+ sleep(1)
+ host = async_sandbox.get_host(8000)
+ res = httpx.get(f"{'http' if debug else 'https'}://{host}")
+ assert res.status_code == 200
+
+ finally:
+ cmd.kill()
diff --git a/packages/python-sdk/tests/sandbox_async/test_kill.py b/packages/python-sdk/tests/sandbox_async/test_kill.py
new file mode 100644
index 000000000..19c1cf040
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_async/test_kill.py
@@ -0,0 +1,12 @@
+import pytest
+
+from e2b import AsyncSandbox
+
+
+async def test_kill(async_sandbox: AsyncSandbox):
+ await async_sandbox.kill()
+
+ list = await AsyncSandbox.list()
+ assert async_sandbox.sandbox_id not in [s.sandbox_id for s in list]
diff --git a/packages/python-sdk/tests/sandbox_async/test_timeout.py b/packages/python-sdk/tests/sandbox_async/test_timeout.py
new file mode 100644
index 000000000..452f2a40c
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_async/test_timeout.py
@@ -0,0 +1,25 @@
+import pytest
+
+from time import sleep
+
+from e2b.exceptions import TimeoutException
+from e2b import AsyncSandbox
+
+
+async def test_shorten_timeout(async_sandbox: AsyncSandbox):
+ await async_sandbox.set_timeout(5)
+ sleep(6)
+ with pytest.raises(TimeoutException):
+ await async_sandbox.is_running()
+
+
+async def test_shorten_then_lengthen_timeout(async_sandbox: AsyncSandbox):
+ await async_sandbox.set_timeout(5)
+ sleep(1)
+ await async_sandbox.set_timeout(10)
+ sleep(6)
+ await async_sandbox.is_running()
diff --git a/packages/python-sdk/tests/sandbox_async/test_upload_url.py b/packages/python-sdk/tests/sandbox_async/test_upload_url.py
new file mode 100644
index 000000000..f853a8deb
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_async/test_upload_url.py
@@ -0,0 +1 @@
+import httpx
\ No newline at end of file
diff --git a/packages/python-sdk/tests/sandbox_sync/commands/test_cmd_connect.py b/packages/python-sdk/tests/sandbox_sync/commands/test_cmd_connect.py
new file mode 100644
index 000000000..eb705698d
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_sync/commands/test_cmd_connect.py
@@ -0,0 +1,18 @@
+import pytest
+
+from e2b import NotFoundException
+
+
+def test_connect_to_process(sandbox):
+ cmd = sandbox.commands.run("sleep 10", background=True)
+ pid = cmd.pid
+
+ process_info = sandbox.commands.connect(pid)
+ assert process_info.pid == pid
+
+
+def test_connect_to_non_existing_process(sandbox):
+ non_existing_pid = 999999
+
+ with pytest.raises(NotFoundException):
+ sandbox.commands.connect(non_existing_pid)
diff --git a/packages/python-sdk/tests/sandbox_sync/commands/test_cmd_kill.py b/packages/python-sdk/tests/sandbox_sync/commands/test_cmd_kill.py
new file mode 100644
index 000000000..ed9e21bd3
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_sync/commands/test_cmd_kill.py
@@ -0,0 +1,19 @@
+import pytest
+
+from e2b import Sandbox, ProcessExitException
+
+
+def test_kill_process(sandbox: Sandbox):
+ cmd = sandbox.commands.run("sleep 10", background=True)
+ pid = cmd.pid
+
+ sandbox.commands.kill(pid)
+
+ with pytest.raises(ProcessExitException):
+ sandbox.commands.run(f"kill -0 {pid}")
+
+
+def test_kill_non_existing_process(sandbox):
+ non_existing_pid = 999999
+
+ assert sandbox.commands.kill(non_existing_pid) == False
diff --git a/packages/python-sdk/tests/sandbox_sync/commands/test_cmd_list.py b/packages/python-sdk/tests/sandbox_sync/commands/test_cmd_list.py
new file mode 100644
index 000000000..30bedb510
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_sync/commands/test_cmd_list.py
@@ -0,0 +1,13 @@
+from e2b import Sandbox
+
+
+def test_kill_process(sandbox: Sandbox):
+ c1 = sandbox.commands.run("sleep 10", background=True)
+ c2 = sandbox.commands.run("sleep 10", background=True)
+
+ processes = sandbox.commands.list()
+
+ assert len(processes) >= 2
+ pids = [p.pid for p in processes]
+ assert c1.pid in pids
+ assert c2.pid in pids
diff --git a/packages/python-sdk/tests/sandbox_sync/commands/test_run.py b/packages/python-sdk/tests/sandbox_sync/commands/test_run.py
new file mode 100644
index 000000000..337844e26
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_sync/commands/test_run.py
@@ -0,0 +1,41 @@
+import pytest
+
+from e2b import Sandbox
+
+
+def test_run(sandbox: Sandbox):
+ text = "Hello, World!"
+
+ cmd = sandbox.commands.run(f'echo "{text}"')
+
+ assert cmd.exit_code == 0
+ assert cmd.stdout == f"{text}\n"
+
+
+def test_run_with_special_characters(sandbox: Sandbox):
+ text = "!@#$%^&*()_+"
+
+ cmd = sandbox.commands.run(f'echo "{text}"')
+
+ assert cmd.exit_code == 0
+ assert cmd.stdout == f"{text}\n"
+
+
+def test_run_with_multiline_string(sandbox):
+ text = "Hello,\nWorld!"
+
+ cmd = sandbox.commands.run(f'echo "{text}"')
+
+ assert cmd.exit_code == 0
+ assert cmd.stdout == f"{text}\n"
+
+
+def test_run_with_timeout(sandbox):
+ cmd = sandbox.commands.run('echo "Hello, World!"', timeout=1000)
+
+ assert cmd.exit_code == 0
+
+
+def test_run_with_too_short_timeout(sandbox):
+ with pytest.raises(Exception):
+ sandbox.commands.run("sleep 10", timeout_ms=1000)
diff --git a/packages/python-sdk/tests/sandbox_sync/commands/test_send_stdin.py b/packages/python-sdk/tests/sandbox_sync/commands/test_send_stdin.py
new file mode 100644
index 000000000..640cdf340
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_sync/commands/test_send_stdin.py
@@ -0,0 +1,28 @@
+from e2b import Sandbox
+
+
+def test_send_stdin_to_process(sandbox: Sandbox):
+ cmd = sandbox.commands.run("cat", background=True)
+ sandbox.commands.send_stdin(cmd.pid, "Hello, World!")
+
+ for stdout, _ in cmd:
+ assert stdout == "Hello, World!"
+ break
+
+
+def test_send_special_characters_to_process(sandbox: Sandbox):
+ cmd = sandbox.commands.run("cat", background=True)
+ sandbox.commands.send_stdin(cmd.pid, "!@#$%^&*()_+")
+
+ for stdout, _ in cmd:
+ assert stdout == "!@#$%^&*()_+"
+ break
+
+
+def test_send_multiline_string_to_process(sandbox: Sandbox):
+ cmd = sandbox.commands.run("cat", background=True)
+ sandbox.commands.send_stdin(cmd.pid, "Hello,\nWorld!")
+
+ for stdout, _ in cmd:
+ assert stdout == "Hello,\nWorld!"
+ break
diff --git a/packages/python-sdk/tests/sandbox/files/test_exists.py b/packages/python-sdk/tests/sandbox_sync/files/test_exists.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/files/test_exists.py
rename to packages/python-sdk/tests/sandbox_sync/files/test_exists.py
diff --git a/packages/python-sdk/tests/sandbox_sync/files/test_files_list.py b/packages/python-sdk/tests/sandbox_sync/files/test_files_list.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/packages/python-sdk/tests/sandbox_sync/files/test_make_dir.py b/packages/python-sdk/tests/sandbox_sync/files/test_make_dir.py
new file mode 100644
index 000000000..ce37cbed4
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_sync/files/test_make_dir.py
@@ -0,0 +1,14 @@
+def test_make_directory(sandbox):
+ dir_name = "test_directory"
+
+ sandbox.files.make_dir(dir_name)
+ exists = sandbox.files.exists(dir_name)
+ assert exists
+
+
+def test_make_nested_directory(sandbox):
+ nested_dir_name = "test_directory/nested_directory"
+
+ sandbox.files.make_dir(nested_dir_name)
+ exists = sandbox.files.exists(nested_dir_name)
+ assert exists
diff --git a/packages/python-sdk/tests/sandbox_sync/files/test_read.py b/packages/python-sdk/tests/sandbox_sync/files/test_read.py
new file mode 100644
index 000000000..e010ecbf0
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_sync/files/test_read.py
@@ -0,0 +1,18 @@
+import pytest
+from e2b import NotFoundException
+
+
+def test_read_file(sandbox):
+ filename = "test_read.txt"
+ content = "Hello, world!"
+
+ sandbox.files.write(filename, content)
+ read_content = sandbox.files.read(filename)
+ assert read_content == content
+
+
+def test_read_non_existing_file(sandbox):
+ filename = "non_existing_file.txt"
+
+ with pytest.raises(NotFoundException):
+ sandbox.files.read(filename)
diff --git a/packages/python-sdk/tests/sandbox_sync/files/test_remove.py b/packages/python-sdk/tests/sandbox_sync/files/test_remove.py
new file mode 100644
index 000000000..6e65a6d16
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_sync/files/test_remove.py
@@ -0,0 +1,13 @@
+def test_remove_file(sandbox):
+ filename = "test_remove.txt"
+ content = "This file will be removed."
+
+ sandbox.files.write(filename, content)
+ sandbox.files.remove(filename)
+ exists = sandbox.files.exists(filename)
+ assert not exists
+
+
+def test_remove_non_existing_file(sandbox):
+ filename = "non_existing_file.txt"
+ sandbox.files.remove(filename)
diff --git a/packages/python-sdk/tests/sandbox_sync/files/test_rename.py b/packages/python-sdk/tests/sandbox_sync/files/test_rename.py
new file mode 100644
index 000000000..1267a6842
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_sync/files/test_rename.py
@@ -0,0 +1,25 @@
+import pytest
+from e2b import NotFoundException
+
+
+def test_rename_file(sandbox):
+ old_filename = "test_rename_old.txt"
+ new_filename = "test_rename_new.txt"
+ content = "This file will be renamed."
+
+ sandbox.files.write(old_filename, content)
+ sandbox.files.rename(old_filename, new_filename)
+ exists_old = sandbox.files.exists(old_filename)
+ exists_new = sandbox.files.exists(new_filename)
+ assert not exists_old
+ assert exists_new
+ read_content = sandbox.files.read(new_filename)
+ assert read_content == content
+
+
+def test_rename_non_existing_file(sandbox):
+ old_filename = "non_existing_file.txt"
+ new_filename = "new_non_existing_file.txt"
+
+ with pytest.raises(NotFoundException):
+ sandbox.files.rename(old_filename, new_filename)
diff --git a/packages/python-sdk/tests/sandbox_sync/files/test_watch.py b/packages/python-sdk/tests/sandbox_sync/files/test_watch.py
new file mode 100644
index 000000000..b459fb42d
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_sync/files/test_watch.py
@@ -0,0 +1,40 @@
+from time import sleep
+
+import pytest
+
+from e2b import NotFoundException
+from e2b.sandbox.filesystem.watch_handle import FilesystemEventType
+
+
+def test_watch_directory_changes(sandbox):
+ dirname = "test_watch_dir"
+ filename = "test_watch.txt"
+ content = "This file will be watched."
+ new_content = "This file has been modified."
+
+ sandbox.files.make_dir(dirname)
+ sandbox.files.write(f"{dirname}/{filename}", content)
+
+ event_triggered = False
+ handle = sandbox.files.watch(dirname)
+
+ sandbox.files.write(f"{dirname}/{filename}", new_content)
+
+ sleep(1) # wait for the event to be triggered
+
+ for event in handle:
+ if event.type == FilesystemEventType.WRITE and event.name == filename:
+ event_triggered = True
+
+ assert event_triggered
+
+ handle.close()
+
+
+def test_watch_non_existing_directory(sandbox):
+ dirname = "non_existing_watch_dir"
+
+ with pytest.raises(NotFoundException):
+ sandbox.files.watch(dirname)
+
+# TODO: Add test for nonexistent file
diff --git a/packages/python-sdk/tests/sandbox_sync/files/test_write.py b/packages/python-sdk/tests/sandbox_sync/files/test_write.py
new file mode 100644
index 000000000..0aebddcc1
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_sync/files/test_write.py
@@ -0,0 +1,33 @@
+def test_write_file(sandbox):
+ filename = "test_write.txt"
+ content = "This is a test file."
+
+ sandbox.files.write(filename, content)
+ exists = sandbox.files.exists(filename)
+ assert exists
+
+ read_content = sandbox.files.read(filename)
+ assert read_content == content
+
+
+def test_overwrite_file(sandbox):
+ filename = "test_overwrite.txt"
+ initial_content = "Initial content."
+ new_content = "New content."
+
+ sandbox.files.write(filename, initial_content)
+ sandbox.files.write(filename, new_content)
+ read_content = sandbox.files.read(filename)
+ assert read_content == new_content
+
+
+def test_write_to_non_existing_directory(sandbox):
+ filename = "non_existing_dir/test_write.txt"
+ content = "This should succeed too."
+
+ sandbox.files.write(filename, content)
+ exists = sandbox.files.exists(filename)
+ assert exists
+
+ read_content = sandbox.files.read(filename)
+ assert read_content == content
diff --git a/packages/python-sdk/tests/sandbox_sync/pty/test_pty_create.py b/packages/python-sdk/tests/sandbox_sync/pty/test_pty_create.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/packages/python-sdk/tests/sandbox_sync/pty/test_resize.py b/packages/python-sdk/tests/sandbox_sync/pty/test_resize.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/packages/python-sdk/tests/sandbox_sync/pty/test_stream_input.py b/packages/python-sdk/tests/sandbox_sync/pty/test_stream_input.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/packages/python-sdk/tests/sandbox/test_connect.py b/packages/python-sdk/tests/sandbox_sync/test_connect.py
similarity index 83%
rename from packages/python-sdk/tests/sandbox/test_connect.py
rename to packages/python-sdk/tests/sandbox_sync/test_connect.py
index 10da75ca0..655ff383a 100644
--- a/packages/python-sdk/tests/sandbox/test_connect.py
+++ b/packages/python-sdk/tests/sandbox_sync/test_connect.py
@@ -1,4 +1,4 @@
-from e2b.sandbox.main import Sandbox
+from e2b import Sandbox
def test_connect(template):
diff --git a/packages/python-sdk/tests/sandbox/test_create.py b/packages/python-sdk/tests/sandbox_sync/test_create.py
similarity index 87%
rename from packages/python-sdk/tests/sandbox/test_create.py
rename to packages/python-sdk/tests/sandbox_sync/test_create.py
index cf94b7b9f..0518747de 100644
--- a/packages/python-sdk/tests/sandbox/test_create.py
+++ b/packages/python-sdk/tests/sandbox_sync/test_create.py
@@ -1,6 +1,6 @@
import pytest
-from e2b.sandbox.main import Sandbox
+from e2b import Sandbox
@pytest.mark.skip_debug()
@@ -16,6 +16,7 @@ def test_metadata(template):
for sbx_info in sbxs:
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:
diff --git a/packages/python-sdk/tests/sandbox/test_host.py b/packages/python-sdk/tests/sandbox_sync/test_host.py
similarity index 73%
rename from packages/python-sdk/tests/sandbox/test_host.py
rename to packages/python-sdk/tests/sandbox_sync/test_host.py
index fba71f8af..92a149a80 100644
--- a/packages/python-sdk/tests/sandbox/test_host.py
+++ b/packages/python-sdk/tests/sandbox_sync/test_host.py
@@ -1,7 +1,6 @@
-from time import sleep
+import httpx
-import pytest
-import requests
+from time import sleep
def test_ping_server(sandbox, debug):
@@ -10,7 +9,7 @@ def test_ping_server(sandbox, debug):
try:
sleep(1)
host = sandbox.get_host(8000)
- res = requests.get(f"{'http' if debug else 'https'}://{host}")
+ res = httpx.get(f"{'http' if debug else 'https'}://{host}")
assert res.status_code == 200
finally:
diff --git a/packages/python-sdk/tests/sandbox/test_kill.py b/packages/python-sdk/tests/sandbox_sync/test_kill.py
similarity index 83%
rename from packages/python-sdk/tests/sandbox/test_kill.py
rename to packages/python-sdk/tests/sandbox_sync/test_kill.py
index 855a85c7a..f6ab6e538 100644
--- a/packages/python-sdk/tests/sandbox/test_kill.py
+++ b/packages/python-sdk/tests/sandbox_sync/test_kill.py
@@ -1,6 +1,6 @@
import pytest
-from e2b.sandbox.main import Sandbox
+from e2b import Sandbox
@pytest.mark.skip_debug()
diff --git a/packages/python-sdk/tests/sandbox/test_timeout.py b/packages/python-sdk/tests/sandbox_sync/test_timeout.py
similarity index 100%
rename from packages/python-sdk/tests/sandbox/test_timeout.py
rename to packages/python-sdk/tests/sandbox_sync/test_timeout.py
diff --git a/packages/python-sdk/tests/sandbox_sync/test_upload_url.py b/packages/python-sdk/tests/sandbox_sync/test_upload_url.py
new file mode 100644
index 000000000..ecfbfd5fa
--- /dev/null
+++ b/packages/python-sdk/tests/sandbox_sync/test_upload_url.py
@@ -0,0 +1 @@
+import httpx