Skip to content

armgit / E2B

Public Imported from GitHub
0

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

Remove Sandbox.betaCreate / beta_create (#1344)

Jakub Novák2680c89c3e90
diff --git a/.changeset/remove-beta-create.md b/.changeset/remove-beta-create.md
new file mode 100644
index 000000000..703a5b7d7
--- /dev/null
+++ b/.changeset/remove-beta-create.md
@@ -0,0 +1,21 @@
+---
+'e2b': minor
+'@e2b/python-sdk': minor
+---
+
+Remove `Sandbox.betaCreate` (JS) and `Sandbox.beta_create` (Python). These methods were a beta of the `lifecycle` configuration that has since shipped on `Sandbox.create`. Migrate by calling `Sandbox.create` with the `lifecycle` option:
+
+```ts
+// before
+await Sandbox.betaCreate({ autoPause: true })
+// after
+await Sandbox.create({ lifecycle: { onTimeout: 'pause' } })
+```
+
+```python
+# before
+Sandbox.beta_create(auto_pause=True)
+# after
+Sandbox.create(lifecycle={"on_timeout": "pause"})
+```
+
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index 428affe92..3a188e4d8 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -52,7 +52,6 @@ export type {
SandboxOpts,
SandboxApiOpts,
SandboxConnectOpts,
- SandboxBetaCreateOpts,
SandboxMetricsOpts,
SandboxState,
SandboxListOpts,
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index 54b2a82d2..d7d535b54 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -20,7 +20,6 @@ import {
SandboxApi,
SandboxListOpts,
SandboxPaginator,
- SandboxBetaCreateOpts,
SnapshotListOpts,
SnapshotInfo,
SnapshotPaginator,
@@ -322,103 +321,6 @@ export class Sandbox extends SandboxApi {
return sandbox
}
- /**
- * @beta This feature is in beta and may change in the future.
- *
- * Create a new sandbox from the default `base` sandbox template.
- *
- * @param opts connection options.
- *
- * @returns sandbox instance for the new sandbox.
- *
- * @example
- * ```ts
- * const sandbox = await Sandbox.betaCreate()
- * ```
- * @constructs {@link Sandbox}
- */
- static async betaCreate<S extends typeof Sandbox>(
- this: S,
- opts?: SandboxBetaCreateOpts
- ): Promise<InstanceType<S>>
-
- /**
- * @beta This feature is in beta and may change in the future.
- *
- * Create a new sandbox from the specified sandbox template.
- *
- * @param template sandbox template name or ID.
- * @param opts connection options.
- *
- * @returns sandbox instance for the new sandbox.
- *
- * @example
- * ```ts
- * const sandbox = await Sandbox.betaCreate('<template-name-or-id>')
- * ```
- * @constructs {@link Sandbox}
- */
- static async betaCreate<S extends typeof Sandbox>(
- this: S,
- template: string,
- opts?: SandboxBetaCreateOpts
- ): Promise<InstanceType<S>>
- static async betaCreate<S extends typeof Sandbox>(
- this: S,
- templateOrOpts?: SandboxBetaCreateOpts | string,
- opts?: SandboxBetaCreateOpts
- ): Promise<InstanceType<S>> {
- const { template, sandboxOpts } =
- typeof templateOrOpts === 'string'
- ? {
- template: templateOrOpts,
- sandboxOpts: opts,
- }
- : {
- template:
- templateOrOpts?.template ??
- (templateOrOpts?.mcp
- ? this.defaultMcpTemplate
- : this.defaultTemplate),
- sandboxOpts: templateOrOpts,
- }
-
- const config = new ConnectionConfig(sandboxOpts)
- if (config.debug) {
- return new this({
- sandboxId: 'debug_sandbox_id',
- envdVersion: ENVD_DEBUG_FALLBACK,
- ...config,
- }) as InstanceType<S>
- }
-
- const sandboxInfo = await SandboxApi.createSandbox(
- template,
- sandboxOpts?.timeoutMs ?? this.defaultSandboxTimeoutMs,
- sandboxOpts
- )
-
- const sandbox = new this({ ...sandboxInfo, ...config }) as InstanceType<S>
-
- if (sandboxOpts?.mcp) {
- sandbox.mcpToken = crypto.randomUUID()
- const res = await sandbox.commands.run(
- `mcp-gateway --config ${shellQuote(JSON.stringify(sandboxOpts.mcp))}`,
- {
- user: 'root',
- envs: {
- GATEWAY_ACCESS_TOKEN: sandbox.mcpToken ?? '',
- },
- }
- )
- if (res.exitCode !== 0) {
- throw new Error(`Failed to start MCP gateway: ${res.stderr}`)
- }
- }
-
- return sandbox
- }
-
/**
* Connect to a sandbox. If the sandbox is paused, it will be automatically resumed.
* Sandbox must be either running or be paused.
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index 32b37ecff..cae217b64 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -189,16 +189,6 @@ export interface SandboxOpts extends ConnectionOpts {
lifecycle?: SandboxLifecycle
}
-export type SandboxBetaCreateOpts = SandboxOpts & {
- /**
- * @deprecated Use `lifecycle.onTimeout = "pause"` instead.
- *
- * Automatically pause the sandbox after the timeout expires.
- * @default false
- */
- autoPause?: boolean
-}
-
/**
* Options for connecting to a Sandbox.
*/
@@ -423,30 +413,6 @@ export interface SandboxMetrics {
diskTotal: number
}
-export function getLifecycle(
- opts?: Pick<SandboxBetaCreateOpts, 'lifecycle' | 'autoPause'>
-): SandboxLifecycle {
- if (opts?.autoPause !== undefined) {
- console.warn(
- "`autoPause` is deprecated; use `lifecycle: { onTimeout: 'pause' }` instead."
- )
- }
-
- const onTimeout =
- opts?.lifecycle?.onTimeout ?? (opts?.autoPause ? 'pause' : 'kill')
-
- if (opts?.lifecycle?.autoResume === true && onTimeout !== 'pause') {
- throw new InvalidArgumentError(
- "autoResume can only be true when the resolved onTimeout is 'pause'."
- )
- }
-
- return {
- onTimeout,
- autoResume: opts?.lifecycle?.autoResume,
- }
-}
-
export class SandboxApi {
protected constructor() {}
@@ -799,12 +765,18 @@ export class SandboxApi {
protected static async createSandbox(
template: string,
timeoutMs: number,
- opts?: SandboxBetaCreateOpts
+ opts?: SandboxOpts
) {
const config = new ConnectionConfig(opts)
const client = new ApiClient(config)
- const { onTimeout, autoResume } = getLifecycle(opts)
- const autoPause = onTimeout === 'pause'
+ const onTimeout = opts?.lifecycle?.onTimeout ?? 'kill'
+ const autoResume = opts?.lifecycle?.autoResume ?? false
+
+ if (autoResume && onTimeout !== 'pause') {
+ throw new InvalidArgumentError(
+ "autoResume can only be true when the resolved onTimeout is 'pause'."
+ )
+ }
const body: components['schemas']['NewSandbox'] = {
templateID: template,
@@ -815,10 +787,8 @@ export class SandboxApi {
secure: opts?.secure ?? true,
allow_internet_access: opts?.allowInternetAccess ?? true,
network: opts?.network,
- autoPause,
- ...(autoResume !== undefined
- ? { autoResume: { enabled: autoResume } }
- : {}),
+ autoPause: onTimeout === 'pause',
+ autoResume: { enabled: autoResume },
}
if (opts?.volumeMounts) {
diff --git a/packages/js-sdk/tests/sandbox/getLifecycle.test.ts b/packages/js-sdk/tests/sandbox/getLifecycle.test.ts
deleted file mode 100644
index 475ee3260..000000000
--- a/packages/js-sdk/tests/sandbox/getLifecycle.test.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-import { assert, describe, test } from 'vitest'
-
-import { InvalidArgumentError } from '../../src'
-import { getLifecycle } from '../../src/sandbox/sandboxApi'
-
-describe('getLifecycle', () => {
- test('returns defaults when no opts are provided', () => {
- assert.deepEqual(getLifecycle(), {
- onTimeout: 'kill',
- autoResume: undefined,
- })
- })
-
- test('returns defaults when opts is empty', () => {
- assert.deepEqual(getLifecycle({}), {
- onTimeout: 'kill',
- autoResume: undefined,
- })
- })
-
- test('lifecycle.onTimeout takes precedence over autoPause=true', () => {
- assert.deepEqual(
- getLifecycle({ lifecycle: { onTimeout: 'kill' }, autoPause: true }),
- {
- onTimeout: 'kill',
- autoResume: undefined,
- }
- )
- })
-
- test('lifecycle.onTimeout=pause takes precedence over autoPause=false', () => {
- assert.deepEqual(
- getLifecycle({ lifecycle: { onTimeout: 'pause' }, autoPause: false }),
- {
- onTimeout: 'pause',
- autoResume: undefined,
- }
- )
- })
-
- test('falls back to autoPause when lifecycle.onTimeout is missing', () => {
- // partial lifecycle without onTimeout (possible at runtime despite TS typing)
- const lifecycle = { autoResume: true } as unknown as {
- onTimeout: 'pause' | 'kill'
- autoResume?: boolean
- }
- assert.deepEqual(getLifecycle({ lifecycle, autoPause: true }), {
- onTimeout: 'pause',
- autoResume: true,
- })
- })
-
- test('autoPause=true with no lifecycle maps to onTimeout=pause', () => {
- assert.deepEqual(getLifecycle({ autoPause: true }), {
- onTimeout: 'pause',
- autoResume: undefined,
- })
- })
-
- test('autoPause=false with no lifecycle maps to onTimeout=kill', () => {
- assert.deepEqual(getLifecycle({ autoPause: false }), {
- onTimeout: 'kill',
- autoResume: undefined,
- })
- })
-
- test('preserves autoResume from lifecycle', () => {
- assert.deepEqual(
- getLifecycle({ lifecycle: { onTimeout: 'pause', autoResume: true } }),
- {
- onTimeout: 'pause',
- autoResume: true,
- }
- )
- assert.deepEqual(
- getLifecycle({ lifecycle: { onTimeout: 'pause', autoResume: false } }),
- {
- onTimeout: 'pause',
- autoResume: false,
- }
- )
- })
-
- test('autoResume is undefined when omitted from lifecycle', () => {
- assert.deepEqual(getLifecycle({ lifecycle: { onTimeout: 'pause' } }), {
- onTimeout: 'pause',
- autoResume: undefined,
- })
- })
-
- test('autoResume is undefined when only autoPause is provided', () => {
- assert.equal(getLifecycle({ autoPause: true }).autoResume, undefined)
- assert.equal(getLifecycle({ autoPause: false }).autoResume, undefined)
- })
-
- test('throws when autoResume=true and onTimeout=kill', () => {
- assert.throws(
- () =>
- getLifecycle({
- lifecycle: { onTimeout: 'kill', autoResume: true },
- }),
- InvalidArgumentError
- )
- })
-
- test('throws when autoResume=true and effective onTimeout resolves to kill', () => {
- // partial lifecycle with autoResume=true; no onTimeout; autoPause falsy.
- const lifecycle = { autoResume: true } as unknown as {
- onTimeout: 'pause' | 'kill'
- autoResume?: boolean
- }
- assert.throws(() => getLifecycle({ lifecycle }), InvalidArgumentError)
- assert.throws(
- () => getLifecycle({ lifecycle, autoPause: false }),
- InvalidArgumentError
- )
- })
-
- test('does not throw when autoResume=true and autoPause=true (no explicit onTimeout)', () => {
- const lifecycle = { autoResume: true } as unknown as {
- onTimeout: 'pause' | 'kill'
- autoResume?: boolean
- }
- assert.doesNotThrow(() => getLifecycle({ lifecycle, autoPause: true }))
- })
-})
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.py
index 519b8fcfb..c3a07afc1 100644
--- a/packages/python-sdk/e2b/sandbox/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py
@@ -17,7 +17,6 @@ from e2b.api.client.models import (
)
from e2b.api.client.types import Unset
from e2b.connection_config import ApiParams
-from e2b.exceptions import InvalidArgumentException
from e2b.sandbox.mcp import McpServer as BaseMcpServer
@@ -121,31 +120,6 @@ class SandboxInfoLifecycle(TypedDict):
"""
-def get_lifecycle(
- lifecycle: Optional[SandboxLifecycle],
- auto_pause: Optional[bool],
-) -> SandboxLifecycle:
- auto_resume = lifecycle.get("auto_resume") if lifecycle is not None else None
-
- explicit_on_timeout = lifecycle.get("on_timeout") if lifecycle is not None else None
- on_timeout: Literal["pause", "kill"] = (
- explicit_on_timeout
- if explicit_on_timeout is not None
- else ("pause" if auto_pause else "kill")
- )
-
- if auto_resume and on_timeout != "pause":
- raise InvalidArgumentException(
- "auto_resume can only be True when the resolved on_timeout is 'pause'."
- )
-
- resolved = SandboxLifecycle(on_timeout=on_timeout)
- if auto_resume is not None:
- resolved["auto_resume"] = auto_resume
-
- return resolved
-
-
def from_client_network_config(
network: Union[Unset, ClientSandboxNetworkConfig],
) -> Optional[SandboxNetworkOpts]:
diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.py
index 5f8a32b0c..4aa7a9f6a 100644
--- a/packages/python-sdk/e2b/sandbox_async/main.py
+++ b/packages/python-sdk/e2b/sandbox_async/main.py
@@ -3,7 +3,6 @@ import json
import logging
import shlex
import uuid
-import warnings
from typing import Dict, List, Optional, Union, overload
import httpx
@@ -220,7 +219,6 @@ class AsyncSandbox(SandboxApi):
sandbox = await cls._create(
template=template,
timeout=timeout,
- auto_pause=False,
metadata=metadata,
envs=envs,
secure=secure,
@@ -547,94 +545,6 @@ class AsyncSandbox(SandboxApi):
**self.connection_config.get_api_params(**opts),
)
- @classmethod
- async def beta_create(
- cls,
- template: Optional[str] = None,
- timeout: Optional[int] = None,
- auto_pause: Optional[bool] = None,
- metadata: Optional[Dict[str, str]] = None,
- envs: Optional[Dict[str, str]] = None,
- secure: bool = True,
- allow_internet_access: bool = True,
- mcp: Optional[McpServer] = None,
- volume_mounts: Optional[SandboxAsyncVolumeMount] = None,
- lifecycle: Optional[SandboxLifecycle] = None,
- **opts: Unpack[ApiParams],
- ) -> Self:
- """
- [BETA] This feature is in beta and may change in the future.
-
- Create a new sandbox.
-
- By default, the sandbox is created from the default `base` sandbox template.
-
- :param template: Sandbox template name or ID
- :param timeout: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
- :param auto_pause: **Deprecated**: use ``lifecycle={"on_timeout": "pause"}`` instead.
- Automatically pause the sandbox after the timeout expires. Defaults to ``False``.
- :param metadata: Custom metadata for the sandbox
- :param envs: Custom environment variables for the sandbox
- :param secure: Envd is secured with access token and cannot be used without it, defaults to `True`.
- :param allow_internet_access: Allow sandbox to access the internet, defaults to `True`.
- :param mcp: MCP server to enable in the sandbox
- :param volume_mounts: Dictionary mapping mount paths to AsyncVolume instances or volume names
- :param lifecycle: Sandbox lifecycle configuration; controls timeout behavior and auto-resume.
-
- :return: A Sandbox instance for the new sandbox
-
- Use this method instead of using the constructor to create a new sandbox.
- """
- if auto_pause is not None:
- warnings.warn(
- "`auto_pause` is deprecated; use `lifecycle={'on_timeout': 'pause'}` instead.",
- DeprecationWarning,
- stacklevel=2,
- )
-
- if not template and mcp is not None:
- template = cls.default_mcp_template
- elif not template:
- template = cls.default_template
-
- transformed_mounts: Optional[List[SandboxVolumeMountAPI]] = None
- if volume_mounts:
- transformed_mounts = [
- SandboxVolumeMountAPI(
- name=vol.name if isinstance(vol, AsyncVolume) else vol,
- path=path,
- )
- for path, vol in volume_mounts.items()
- ]
-
- sandbox = await cls._create(
- template=template,
- timeout=timeout,
- auto_pause=auto_pause,
- metadata=metadata,
- envs=envs,
- secure=secure,
- allow_internet_access=allow_internet_access,
- mcp=mcp,
- lifecycle=lifecycle,
- volume_mounts=transformed_mounts,
- **opts,
- )
-
- if mcp is not None:
- token = str(uuid.uuid4())
- sandbox._mcp_token = token
-
- res = await sandbox.commands.run(
- f"mcp-gateway --config {shlex.quote(json.dumps(mcp))}",
- user="root",
- envs={"GATEWAY_ACCESS_TOKEN": token},
- )
- if res.exit_code != 0:
- raise Exception(f"Failed to start MCP gateway: {res.stderr}")
-
- return sandbox
-
@overload
async def pause(
self,
@@ -903,7 +813,6 @@ class AsyncSandbox(SandboxApi):
cls,
template: Optional[str],
timeout: Optional[int],
- auto_pause: Optional[bool],
allow_internet_access: bool,
metadata: Optional[Dict[str, str]],
envs: Optional[Dict[str, str]],
@@ -927,7 +836,6 @@ class AsyncSandbox(SandboxApi):
response = await SandboxApi._create_sandbox(
template=template or cls.default_template,
timeout=timeout or cls.default_sandbox_timeout,
- auto_pause=auto_pause,
metadata=metadata,
env_vars=envs,
secure=secure,
diff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
index 69688fca7..78c87feec 100644
--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
@@ -31,6 +31,7 @@ from e2b.api.client.types import UNSET
from e2b.api.client_async import get_api_client
from e2b.connection_config import ApiParams, ConnectionConfig
from e2b.exceptions import (
+ InvalidArgumentException,
SandboxException,
SandboxNotFoundException,
TemplateException,
@@ -44,7 +45,6 @@ from e2b.sandbox.sandbox_api import (
SandboxNetworkOpts,
SandboxQuery,
SnapshotInfo,
- get_lifecycle,
)
from e2b.sandbox_async.paginator import AsyncSandboxPaginator
@@ -164,7 +164,6 @@ class SandboxApi(SandboxBase):
cls,
template: str,
timeout: int,
- auto_pause: Optional[bool],
allow_internet_access: bool,
metadata: Optional[Dict[str, str]],
env_vars: Optional[Dict[str, str]],
@@ -177,10 +176,18 @@ class SandboxApi(SandboxBase):
) -> SandboxCreateResponse:
config = ConnectionConfig(**opts)
- lifecycle = get_lifecycle(lifecycle, auto_pause)
+ on_timeout = lifecycle.get("on_timeout", "kill") if lifecycle else "kill"
+ auto_resume = lifecycle.get("auto_resume", False) if lifecycle else False
+
+ if auto_resume and on_timeout != "pause":
+ raise InvalidArgumentException(
+ "auto_resume can only be True when the resolved on_timeout is 'pause'."
+ )
+
body = NewSandbox(
template_id=template,
- auto_pause=lifecycle["on_timeout"] == "pause",
+ auto_pause=on_timeout == "pause",
+ auto_resume=SandboxAutoResumeConfig(enabled=auto_resume),
metadata=metadata or {},
timeout=timeout,
env_vars=env_vars or {},
@@ -190,8 +197,6 @@ class SandboxApi(SandboxBase):
network=SandboxNetworkConfig(**network) if network else UNSET,
volume_mounts=volume_mounts if volume_mounts else UNSET,
)
- if "auto_resume" in lifecycle:
- body.auto_resume = SandboxAutoResumeConfig(enabled=lifecycle["auto_resume"])
api_client = get_api_client(config)
res = await post_sandboxes.asyncio_detailed(
diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.py
index c2f184c28..3557f1d14 100644
--- a/packages/python-sdk/e2b/sandbox_sync/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/main.py
@@ -3,7 +3,6 @@ import json
import logging
import shlex
import uuid
-import warnings
from typing import Dict, List, Optional, Union, overload
import httpx
@@ -217,7 +216,6 @@ class Sandbox(SandboxApi):
sandbox = cls._create(
template=template,
- auto_pause=False,
timeout=timeout,
metadata=metadata,
envs=envs,
@@ -548,94 +546,6 @@ class Sandbox(SandboxApi):
**self.connection_config.get_api_params(**opts),
)
- @classmethod
- def beta_create(
- cls,
- template: Optional[str] = None,
- timeout: Optional[int] = None,
- auto_pause: Optional[bool] = None,
- metadata: Optional[Dict[str, str]] = None,
- envs: Optional[Dict[str, str]] = None,
- secure: bool = True,
- allow_internet_access: bool = True,
- mcp: Optional[McpServer] = None,
- volume_mounts: Optional[SandboxVolumeMount] = None,
- lifecycle: Optional[SandboxLifecycle] = None,
- **opts: Unpack[ApiParams],
- ) -> Self:
- """
- [BETA] This feature is in beta and may change in the future.
-
- Create a new sandbox.
-
- By default, the sandbox is created from the default `base` sandbox template.
-
- :param template: Sandbox template name or ID
- :param timeout: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
- :param auto_pause: **Deprecated**: use ``lifecycle={"on_timeout": "pause"}`` instead.
- Automatically pause the sandbox after the timeout expires. Defaults to ``False``.
- :param metadata: Custom metadata for the sandbox
- :param envs: Custom environment variables for the sandbox
- :param secure: Envd is secured with access token and cannot be used without it, defaults to `True`.
- :param allow_internet_access: Allow sandbox to access the internet, defaults to `True`.
- :param mcp: MCP server to enable in the sandbox
- :param volume_mounts: Dictionary mapping mount paths to Volume instances or volume names
- :param lifecycle: Sandbox lifecycle configuration; controls timeout behavior and auto-resume.
-
- :return: A Sandbox instance for the new sandbox
-
- Use this method instead of using the constructor to create a new sandbox.
- """
- if auto_pause is not None:
- warnings.warn(
- "`auto_pause` is deprecated; use `lifecycle={'on_timeout': 'pause'}` instead.",
- DeprecationWarning,
- stacklevel=2,
- )
-
- if not template and mcp is not None:
- template = cls.default_mcp_template
- elif not template:
- template = cls.default_template
-
- transformed_mounts = None
- if volume_mounts:
- transformed_mounts = [
- SandboxVolumeMountAPI(
- name=vol.name if isinstance(vol, Volume) else vol,
- path=path,
- )
- for path, vol in volume_mounts.items()
- ]
-
- sandbox = cls._create(
- template=template,
- auto_pause=auto_pause,
- timeout=timeout,
- metadata=metadata,
- envs=envs,
- secure=secure,
- allow_internet_access=allow_internet_access,
- mcp=mcp,
- lifecycle=lifecycle,
- volume_mounts=transformed_mounts,
- **opts,
- )
-
- if mcp is not None:
- token = str(uuid.uuid4())
- sandbox._mcp_token = token
-
- res = sandbox.commands.run(
- f"mcp-gateway --config {shlex.quote(json.dumps(mcp))}",
- user="root",
- envs={"GATEWAY_ACCESS_TOKEN": token},
- )
- if res.exit_code != 0:
- raise Exception(f"Failed to start MCP gateway: {res.stderr}")
-
- return sandbox
-
@overload
def pause(
self,
@@ -898,7 +808,6 @@ class Sandbox(SandboxApi):
cls,
template: Optional[str],
timeout: Optional[int],
- auto_pause: Optional[bool],
metadata: Optional[Dict[str, str]],
envs: Optional[Dict[str, str]],
secure: bool,
@@ -922,7 +831,6 @@ class Sandbox(SandboxApi):
response = SandboxApi._create_sandbox(
template=template or cls.default_template,
timeout=timeout or cls.default_sandbox_timeout,
- auto_pause=auto_pause,
metadata=metadata,
env_vars=envs,
secure=secure,
diff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
index 782db6baf..c84bae72a 100644
--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
@@ -30,6 +30,7 @@ from e2b.api.client.models import (
from e2b.api.client.types import UNSET
from e2b.connection_config import ApiParams, ConnectionConfig
from e2b.exceptions import (
+ InvalidArgumentException,
SandboxException,
SandboxNotFoundException,
TemplateException,
@@ -37,7 +38,6 @@ from e2b.exceptions import (
from e2b.sandbox.main import SandboxBase
from e2b.sandbox.sandbox_api import (
SandboxLifecycle,
- get_lifecycle,
McpServer,
SandboxInfo,
SandboxMetrics,
@@ -163,7 +163,6 @@ class SandboxApi(SandboxBase):
cls,
template: str,
timeout: int,
- auto_pause: Optional[bool],
allow_internet_access: bool,
metadata: Optional[Dict[str, str]],
env_vars: Optional[Dict[str, str]],
@@ -176,10 +175,18 @@ class SandboxApi(SandboxBase):
) -> SandboxCreateResponse:
config = ConnectionConfig(**opts)
- lifecycle = get_lifecycle(lifecycle, auto_pause)
+ on_timeout = lifecycle.get("on_timeout", "kill") if lifecycle else "kill"
+ auto_resume = lifecycle.get("auto_resume", False) if lifecycle else False
+
+ if auto_resume and on_timeout != "pause":
+ raise InvalidArgumentException(
+ "auto_resume can only be True when the resolved on_timeout is 'pause'."
+ )
+
body = NewSandbox(
template_id=template,
- auto_pause=lifecycle["on_timeout"] == "pause",
+ auto_pause=on_timeout == "pause",
+ auto_resume=SandboxAutoResumeConfig(enabled=auto_resume),
metadata=metadata or {},
timeout=timeout,
env_vars=env_vars or {},
@@ -189,8 +196,6 @@ class SandboxApi(SandboxBase):
network=SandboxNetworkConfig(**network) if network else UNSET,
volume_mounts=volume_mounts if volume_mounts else UNSET,
)
- if "auto_resume" in lifecycle:
- body.auto_resume = SandboxAutoResumeConfig(enabled=lifecycle["auto_resume"])
api_client = get_api_client(config)
res = post_sandboxes.sync_detailed(
diff --git a/packages/python-sdk/tests/test_sandbox_api.py b/packages/python-sdk/tests/test_sandbox_api.py
deleted file mode 100644
index faf7b20e9..000000000
--- a/packages/python-sdk/tests/test_sandbox_api.py
+++ /dev/null
@@ -1,70 +0,0 @@
-import pytest
-
-from e2b.exceptions import InvalidArgumentException
-from e2b.sandbox.sandbox_api import get_lifecycle
-
-
-def test_get_lifecycle_returns_defaults_when_nothing_provided():
- assert get_lifecycle(None, None) == {"on_timeout": "kill"}
-
-
-def test_get_lifecycle_on_timeout_takes_precedence_over_auto_pause():
- assert get_lifecycle({"on_timeout": "kill"}, True) == {"on_timeout": "kill"}
- assert get_lifecycle({"on_timeout": "pause"}, False) == {"on_timeout": "pause"}
-
-
-def test_get_lifecycle_falls_back_to_auto_pause_when_on_timeout_missing():
- # partial lifecycle without on_timeout (possible at runtime despite typing).
- assert get_lifecycle({"auto_resume": True}, True) == { # type: ignore[typeddict-item]
- "on_timeout": "pause",
- "auto_resume": True,
- }
-
-
-def test_get_lifecycle_auto_pause_only_maps_to_on_timeout():
- assert get_lifecycle(None, True) == {"on_timeout": "pause"}
- assert get_lifecycle(None, False) == {"on_timeout": "kill"}
-
-
-def test_get_lifecycle_preserves_auto_resume_from_lifecycle():
- assert get_lifecycle({"on_timeout": "pause", "auto_resume": True}, None) == {
- "on_timeout": "pause",
- "auto_resume": True,
- }
- assert get_lifecycle({"on_timeout": "pause", "auto_resume": False}, None) == {
- "on_timeout": "pause",
- "auto_resume": False,
- }
-
-
-def test_get_lifecycle_omits_auto_resume_when_not_set_in_lifecycle():
- # Lifecycle present but auto_resume not specified -> key omitted in result.
- assert "auto_resume" not in get_lifecycle({"on_timeout": "pause"}, None)
-
-
-def test_get_lifecycle_omits_auto_resume_when_only_auto_pause_provided():
- # auto_resume is preserved verbatim from lifecycle input; bare auto_pause
- # does not introduce one.
- assert "auto_resume" not in get_lifecycle(None, True)
- assert "auto_resume" not in get_lifecycle(None, False)
-
-
-def test_get_lifecycle_raises_when_auto_resume_true_with_kill():
- with pytest.raises(InvalidArgumentException):
- get_lifecycle({"on_timeout": "kill", "auto_resume": True}, None)
-
-
-def test_get_lifecycle_raises_when_auto_resume_true_and_effective_is_kill():
- # No on_timeout, auto_pause falsy -> effective kill -> error.
- with pytest.raises(InvalidArgumentException):
- get_lifecycle({"auto_resume": True}, None) # type: ignore[typeddict-item]
- with pytest.raises(InvalidArgumentException):
- get_lifecycle({"auto_resume": True}, False) # type: ignore[typeddict-item]
-
-
-def test_get_lifecycle_does_not_raise_when_auto_resume_true_with_auto_pause():
- # Partial lifecycle with auto_resume=True and auto_pause=True is valid.
- assert get_lifecycle(
- {"auto_resume": True}, # type: ignore[typeddict-item]
- True,
- ) == {"on_timeout": "pause", "auto_resume": True}