Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Update connect method (#1001)
Jakub Novák742a9ba9530e
diff --git a/.changeset/serious-badgers-jump.md b/.changeset/serious-badgers-jump.mdnew file mode 100644index 000000000..80f81f8c1--- /dev/null+++ b/.changeset/serious-badgers-jump.md@@ -0,0 +1,7 @@+---+'@e2b/python-sdk': minor+'e2b': minor+'@e2b/cli': minor+---++Update connect to only extend timeoutdiff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.tsindex 3ba18bc2f..9d08bed89 100644--- a/packages/js-sdk/src/sandbox/index.ts+++ b/packages/js-sdk/src/sandbox/index.ts@@ -404,29 +404,14 @@ export class Sandbox extends SandboxApi {sandboxId: string,opts?: SandboxConnectOpts): Promise<InstanceType<S>> {- try {- await SandboxApi.setTimeout(- sandboxId,- opts?.timeoutMs || DEFAULT_SANDBOX_TIMEOUT_MS,- opts- )- } catch (e) {- if (e instanceof SandboxError) {- await SandboxApi.resumeSandbox(sandboxId, opts)- } else {- throw e- }- }-- const info = await SandboxApi.getFullInfo(sandboxId, opts)-+ const sandbox = await SandboxApi.connectSandbox(sandboxId, opts)const config = new ConnectionConfig(opts)return new this({sandboxId,- sandboxDomain: info.sandboxDomain,- envdAccessToken: info.envdAccessToken,- envdVersion: info.envdVersion,+ sandboxDomain: sandbox.sandboxDomain,+ envdAccessToken: sandbox.envdAccessToken,+ envdVersion: sandbox.envdVersion,...config,}) as InstanceType<S>}@@ -451,15 +436,7 @@ export class Sandbox extends SandboxApi {* ```*/async connect(opts?: SandboxBetaCreateOpts): Promise<this> {- try {- await SandboxApi.setTimeout(- this.sandboxId,- opts?.timeoutMs || DEFAULT_SANDBOX_TIMEOUT_MS,- opts- )- } catch (e) {- await SandboxApi.resumeSandbox(this.sandboxId, opts)- }+ await SandboxApi.connectSandbox(this.sandboxId, opts)return this}diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.tsindex a7ebed21b..dec43ed4f 100644--- a/packages/js-sdk/src/sandbox/sandboxApi.ts+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts@@ -103,7 +103,16 @@ export type SandboxBetaCreateOpts = SandboxOpts & {/*** Options for connecting to a Sandbox.*/-export type SandboxConnectOpts = Omit<SandboxOpts, 'metadata' | 'envs'>+export type SandboxConnectOpts = ConnectionOpts & {+ /**+ * Timeout for the sandbox in **milliseconds**.+ * For running sandboxes, the timeout will update only if the new timeout is longer than the existing one.+ * Maximum time a sandbox can be kept alive is 24 hours (86_400_000 milliseconds) for Pro users and 1 hour (3_600_000 milliseconds) for Hobby users.+ *+ * @default 300_000 // 5 minutes+ */+ timeoutMs?: number+}/*** State of the sandbox.@@ -468,12 +477,7 @@ export class SandboxApi {template: string,timeoutMs: number,opts?: SandboxBetaCreateOpts- ): Promise<{- sandboxId: string- sandboxDomain?: string- envdVersion: string- envdAccessToken?: string- }> {+ ) {const config = new ConnectionConfig(opts)const client = new ApiClient(config)@@ -512,16 +516,16 @@ export class SandboxApi {}}- protected static async resumeSandbox(+ protected static async connectSandbox(sandboxId: string,opts?: SandboxConnectOpts- ): Promise<boolean> {+ ) {const timeoutMs = opts?.timeoutMs ?? DEFAULT_SANDBOX_TIMEOUT_MSconst config = new ConnectionConfig(opts)const client = new ApiClient(config)- const res = await client.api.POST('/sandboxes/{sandboxID}/resume', {+ const res = await client.api.POST('/sandboxes/{sandboxID}/connect', {params: {path: {sandboxID: sandboxId,@@ -537,17 +541,17 @@ export class SandboxApi {throw new NotFoundError(`Paused sandbox ${sandboxId} not found`)}- if (res.error?.code === 409) {- // Sandbox is already running- return false- }-const err = handleApiError(res)if (err) {throw err}- return true+ return {+ sandboxId: res.data!.sandboxID,+ sandboxDomain: res.data!.domain || undefined,+ envdVersion: res.data!.envdVersion,+ envdAccessToken: res.data!.envdAccessToken,+ }}}diff --git a/packages/js-sdk/tests/sandbox/connect.test.ts b/packages/js-sdk/tests/sandbox/connect.test.tsindex 98975b921..3f548c5db 100644--- a/packages/js-sdk/tests/sandbox/connect.test.ts+++ b/packages/js-sdk/tests/sandbox/connect.test.ts@@ -35,3 +35,54 @@ sandboxTest.skipIf(isDebug)()})++test.skipIf(isDebug)(+ 'connect does not shorten timeout on running sandbox',+ async () => {+ // Create sandbox with a 300 second timeout+ const sbx = await Sandbox.create(template, { timeoutMs: 300_000 })++ try {+ const isRunning = await sbx.isRunning()+ assert.isTrue(isRunning)++ // Get initial info to check endAt+ const infoBefore = await Sandbox.getInfo(sbx.sandboxId)++ // Connect with a shorter timeout (10 seconds)+ await Sandbox.connect(sbx.sandboxId, { timeoutMs: 10_000 })++ // Get info after connection+ const infoAfter = await sbx.getInfo()++ // The endAt time should not have been shortened. It should be the same+ assert.equal(+ infoAfter.endAt.getTime(),+ infoBefore.endAt.getTime(),+ `Timeout was shortened: before=${infoBefore.endAt.toISOString()}, after=${infoAfter.endAt.toISOString()}`+ )+ } finally {+ await sbx.kill()+ }+ }+)++sandboxTest.skipIf(isDebug)(+ 'connect extends timeout on running sandbox',+ async ({ sandbox }) => {+ // Get initial info to check endAt+ const infoBefore = await sandbox.getInfo()++ // Connect with a longer timeout+ await sandbox.connect({ timeoutMs: 600_000 })++ // Get info after connection+ const infoAfter = await sandbox.getInfo()++ // The endAt time should have been extended+ assert.isTrue(+ infoAfter.endAt.getTime() > infoBefore.endAt.getTime(),+ `Timeout was not extended: before=${infoBefore.endAt.toISOString()}, after=${infoAfter.endAt.toISOString()}`+ )+ }+)diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.pyindex c46a725cb..66ad93306 100644--- a/packages/python-sdk/e2b/sandbox_async/main.py+++ b/packages/python-sdk/e2b/sandbox_async/main.py@@ -228,6 +228,7 @@ class AsyncSandbox(SandboxApi):With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc).:param timeout: Timeout for the sandbox in **seconds**+ For running sandboxes, the timeout will update only if the new timeout is longer than the existing one.:return: A running sandbox instance@example@@ -257,6 +258,7 @@ class AsyncSandbox(SandboxApi)::param sandbox_id: Sandbox ID:param timeout: Timeout for the sandbox in **seconds**+ For running sandboxes, the timeout will update only if the new timeout is longer than the existing one.:return: A running sandbox instance@example@@ -283,6 +285,7 @@ class AsyncSandbox(SandboxApi):With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc).:param timeout: Timeout for the sandbox in **seconds**+ For running sandboxes, the timeout will update only if the new timeout is longer than the existing one.:return: A running sandbox instance@example@@ -294,7 +297,7 @@ class AsyncSandbox(SandboxApi):same_sandbox = await sandbox.connect()```"""- await SandboxApi._cls_resume(+ await SandboxApi._cls_connect(sandbox_id=self.sandbox_id,timeout=timeout,**opts,@@ -650,16 +653,14 @@ class AsyncSandbox(SandboxApi):timeout: Optional[int] = None,**opts: Unpack[ApiParams],) -> Self:- await SandboxApi._cls_resume(+ sandbox = await SandboxApi._cls_connect(sandbox_id=sandbox_id,timeout=timeout,**opts,)- response = await SandboxApi._cls_get_info(sandbox_id, **opts)-sandbox_headers = {}- envd_access_token = response._envd_access_token+ envd_access_token = sandbox.envd_access_tokenif envd_access_token is not None and not isinstance(envd_access_token, Unset):sandbox_headers["X-Access-Token"] = envd_access_token@@ -669,9 +670,9 @@ class AsyncSandbox(SandboxApi):)return cls(- sandbox_id=response.sandbox_id,- sandbox_domain=response.sandbox_domain,- envd_version=Version(response.envd_version),+ sandbox_id=sandbox.sandbox_id,+ sandbox_domain=sandbox.domain,+ envd_version=Version(sandbox.envd_version),envd_access_token=envd_access_token,connection_config=connection_config,)diff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.pyindex 08a59ee36..27015feb6 100644--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py@@ -13,7 +13,8 @@ from e2b.api.client.models import (NewSandbox,PostSandboxesSandboxIDTimeoutBody,Error,- ResumedSandbox,+ ConnectSandbox,+ Sandbox,)from e2b.api.client.api.sandboxes import (get_sandboxes_sandbox_id,@@ -22,7 +23,7 @@ from e2b.api.client.api.sandboxes import (post_sandboxes,get_sandboxes_sandbox_id_metrics,post_sandboxes_sandbox_id_pause,- post_sandboxes_sandbox_id_resume,+ post_sandboxes_sandbox_id_connect,)from e2b.connection_config import ConnectionConfig, ApiParamsfrom e2b.api import handle_api_exception@@ -282,52 +283,42 @@ class SandboxApi(SandboxBase):if res.status_code >= 300:raise handle_api_exception(res)+ # Check if res.parse is Error+ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")+return sandbox_id@classmethod- async def _cls_resume(+ async def _cls_connect(cls,sandbox_id: str,timeout: Optional[int] = None,**opts: Unpack[ApiParams],- ) -> bool:+ ) -> Sandbox:timeout = timeout or SandboxBase.default_sandbox_timeout- # Temporary solution (02/12/2025),- # Options discussed:- # 1. No set - never sure how long the sandbox will be running- # 2. Always set the timeout in code - the user can't just connect to the sandbox- # without changing the timeout, round trip to the server time- # 3. Set the timeout in resume on backend - side effect on error- # 4. Create new endpoint for connect- try:- await SandboxApi._cls_set_timeout(- sandbox_id=sandbox_id,- timeout=timeout,- **opts,+ # Sandbox is not running, resume it+ config = ConnectionConfig(**opts)++ async with AsyncApiClient(+ config,+ limits=SandboxBase._limits,+ ) as api_client:+ res = await post_sandboxes_sandbox_id_connect.asyncio_detailed(+ sandbox_id,+ client=api_client,+ body=ConnectSandbox(timeout=timeout),)- return False- except SandboxException:- # Sandbox is not running, resume it- config = ConnectionConfig(**opts)-- async with AsyncApiClient(- config,- limits=SandboxBase._limits,- ) as api_client:- res = await post_sandboxes_sandbox_id_resume.asyncio_detailed(- sandbox_id,- client=api_client,- body=ResumedSandbox(timeout=timeout),- )- if res.status_code == 404:- raise NotFoundException(f"Paused sandbox {sandbox_id} not found")+ if res.status_code == 404:+ raise NotFoundException(f"Paused sandbox {sandbox_id} not found")- if res.status_code == 409:- return False+ if res.status_code >= 300:+ raise handle_api_exception(res)- if res.status_code >= 300:- raise handle_api_exception(res)+ # Check if res.parse is Error+ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")- return True+ return res.parseddiff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.pyindex 7ee2b786f..9c39f7432 100644--- a/packages/python-sdk/e2b/sandbox_sync/main.py+++ b/packages/python-sdk/e2b/sandbox_sync/main.py@@ -231,6 +231,7 @@ class Sandbox(SandboxApi):With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc).:param timeout: Timeout for the sandbox in **seconds**+ For running sandboxes, the timeout will update only if the new timeout is longer than the existing one.:return: A running sandbox instance@example@@ -260,7 +261,8 @@ class Sandbox(SandboxApi):With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc).:param sandbox_id: Sandbox ID- :param timeout: Timeout for the sandbox in **seconds**+ :param timeout: Timeout for the sandbox in **seconds**.+ For running sandboxes, the timeout will update only if the new timeout is longer than the existing one.:return: A running sandbox instance@example@@ -286,7 +288,8 @@ class Sandbox(SandboxApi):With sandbox ID you can connect to the same sandbox from different places or environments (serverless functions, etc).- :param timeout: Timeout for the sandbox in **seconds**+ :param timeout: Timeout for the sandbox in **seconds**.+ For running sandboxes, the timeout will update only if the new timeout is longer than the existing one.:return: A running sandbox instance@example@@ -298,7 +301,7 @@ class Sandbox(SandboxApi):same_sandbox = sandbox.connect()```"""- SandboxApi._cls_resume(+ SandboxApi._cls_connect(sandbox_id=self.sandbox_id,timeout=timeout,**opts,@@ -651,12 +654,10 @@ class Sandbox(SandboxApi):timeout: Optional[int] = None,**opts: Unpack[ApiParams],) -> Self:- SandboxApi._cls_resume(sandbox_id, timeout, **opts)-- response = cls._cls_get_info(sandbox_id, **opts)+ sandbox = SandboxApi._cls_connect(sandbox_id, timeout, **opts)sandbox_headers = {}- envd_access_token = response._envd_access_token+ envd_access_token = sandbox.envd_access_tokenif envd_access_token is not None and not isinstance(envd_access_token, Unset):sandbox_headers["X-Access-Token"] = envd_access_token@@ -667,9 +668,9 @@ class Sandbox(SandboxApi):return cls(sandbox_id=sandbox_id,- sandbox_domain=response.sandbox_domain,+ sandbox_domain=sandbox.domain,connection_config=connection_config,- envd_version=Version(response.envd_version),+ envd_version=Version(sandbox.envd_version),envd_access_token=envd_access_token,)diff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.pyindex 0563d8aa3..82104efd2 100644--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py@@ -13,7 +13,8 @@ from e2b.api.client.models import (NewSandbox,PostSandboxesSandboxIDTimeoutBody,Error,- ResumedSandbox,+ ConnectSandbox,+ Sandbox,)from e2b.api.client.api.sandboxes import (get_sandboxes_sandbox_id,@@ -21,7 +22,7 @@ from e2b.api.client.api.sandboxes import (delete_sandboxes_sandbox_id,post_sandboxes,get_sandboxes_sandbox_id_metrics,- post_sandboxes_sandbox_id_resume,+ post_sandboxes_sandbox_id_connect,post_sandboxes_sandbox_id_pause,)from e2b.connection_config import ConnectionConfig, ApiParams@@ -244,52 +245,36 @@ class SandboxApi(SandboxBase):]@classmethod- def _cls_resume(+ def _cls_connect(cls,sandbox_id: str,timeout: Optional[int] = None,**opts: Unpack[ApiParams],- ) -> bool:+ ) -> Sandbox:timeout = timeout or SandboxBase.default_sandbox_timeout- # Temporary solution (02/12/2025),- # Options discussed:- # 1. No set - never sure how long the sandbox will be running- # 2. Always set the timeout in code - the user can't just connect to the sandbox- # without changing the timeout, round trip to the server time- # 3. Set the timeout in resume on backend - side effect on error- # 4. Create new endpoint for connect- try:- cls._cls_set_timeout(- sandbox_id=sandbox_id,- timeout=timeout,- **opts,+ config = ConnectionConfig(**opts)++ with ApiClient(+ config,+ limits=SandboxBase._limits,+ ) as api_client:+ res = post_sandboxes_sandbox_id_connect.sync_detailed(+ sandbox_id,+ client=api_client,+ body=ConnectSandbox(timeout=timeout),)- return False- except SandboxException:- # Sandbox is not running, resume it- config = ConnectionConfig(**opts)-- with ApiClient(- config,- limits=SandboxBase._limits,- ) as api_client:- res = post_sandboxes_sandbox_id_resume.sync_detailed(- sandbox_id,- client=api_client,- body=ResumedSandbox(timeout=timeout),- )- if res.status_code == 404:- raise NotFoundException(f"Paused sandbox {sandbox_id} not found")+ if res.status_code == 404:+ raise NotFoundException(f"Paused sandbox {sandbox_id} not found")- if res.status_code == 409:- return False+ if res.status_code >= 300:+ raise handle_api_exception(res)- if res.status_code >= 300:- raise handle_api_exception(res)+ if isinstance(res.parsed, Error):+ raise SandboxException(f"{res.parsed.message}: Request failed")- return True+ return res.parsed@classmethoddef _cls_pause(diff --git a/packages/python-sdk/tests/async/sandbox_async/test_connect.py b/packages/python-sdk/tests/async/sandbox_async/test_connect.pyindex 6a6fc65a2..33bdcdb3d 100644--- a/packages/python-sdk/tests/async/sandbox_async/test_connect.py+++ b/packages/python-sdk/tests/async/sandbox_async/test_connect.py@@ -32,3 +32,47 @@ async def test_connect_with_secure(template):assert await sbx_connection.is_running()finally:await sbx.kill()++[email protected]_debug()+async def test_connect_does_not_shorten_timeout_on_running_sandbox(template):+ # Create sandbox with a 300 second timeout+ sbx = await AsyncSandbox.create(template, timeout=300)+ try:+ assert await sbx.is_running()++ # Get initial info to check end_at+ info_before = await AsyncSandbox.get_info(sbx.sandbox_id)++ # Connect with a shorter timeout (10 seconds)+ await AsyncSandbox.connect(sbx.sandbox_id, timeout=10)++ # Get info after connection+ info_after = await AsyncSandbox.get_info(sbx.sandbox_id)++ # The end_at time should not have been shortened. It should be the same+ assert info_after.end_at == info_before.end_at, (+ f"Timeout was changed: before={info_before.end_at}, after={info_after.end_at}"+ )+ finally:+ await sbx.kill()++[email protected]_debug()+async def test_connect_extends_timeout_on_running_sandbox(async_sandbox):+ # Create sandbox with a short timeout+ assert await async_sandbox.is_running()++ # Get initial info to check end_at+ info_before = await async_sandbox.get_info()++ # Connect with a longer timeout+ await AsyncSandbox.connect(async_sandbox.sandbox_id, timeout=600)++ # Get info after connection+ info_after = await AsyncSandbox.get_info(async_sandbox.sandbox_id)++ # The end_at time should have been extended+ assert info_after.end_at > info_before.end_at, (+ f"Timeout was not extended: before={info_before.end_at}, after={info_after.end_at}"+ )diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_connect.py b/packages/python-sdk/tests/sync/sandbox_sync/test_connect.pyindex 5c71a2ab5..ebe496e45 100644--- a/packages/python-sdk/tests/sync/sandbox_sync/test_connect.py+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_connect.py@@ -32,3 +32,44 @@ def test_connect_with_secure(template):finally:sbx.kill()++[email protected]_debug()+def test_connect_does_not_shorten_timeout_on_running_sandbox(template):+ # Create sandbox with a 300 second timeout+ sbx = Sandbox.create(template, timeout=300)+ try:+ assert sbx.is_running()++ # Get initial info to check end_at+ info_before = Sandbox.get_info(sbx.sandbox_id)++ # Connect with a shorter timeout (10 seconds)+ Sandbox.connect(sbx.sandbox_id, timeout=10)++ # Get info after connection+ info_after = Sandbox.get_info(sbx.sandbox_id)++ # The end_at time should not have been shortened. It should be the same+ assert info_after.end_at == info_before.end_at, (+ f"Timeout was shortened: before={info_before.end_at}, after={info_after.end_at}"+ )+ finally:+ sbx.kill()++[email protected]_debug()+def test_connect_extends_timeout_on_running_sandbox(sandbox):+ # Get initial info to check end_at+ info_before = sandbox.get_info()++ # Connect with a longer timeout+ Sandbox.connect(sandbox.sandbox_id, timeout=600)++ # Get info after connection+ info_after = sandbox.get_info()++ # The end_at time should have been extended+ assert info_after.end_at > info_before.end_at, (+ f"Timeout was not extended: before={info_before.end_at}, after={info_after.end_at}"+ )