Skip to content

armgit / E2B

Public Imported from GitHub
0

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

autoresume: lifecycle component in sdk (#1146)

Matt Brockman7027f369a3e3
diff --git a/.changeset/bold-times-decide.md b/.changeset/bold-times-decide.md
new file mode 100644
index 000000000..c32c0b1df
--- /dev/null
+++ b/.changeset/bold-times-decide.md
@@ -0,0 +1,6 @@
+---
+'@e2b/python-sdk': minor
+'e2b': minor
+---
+
+Adds lifecycle prop to control pausing and auto-resume
diff --git a/packages/js-sdk/src/api/schema.gen.ts b/packages/js-sdk/src/api/schema.gen.ts
index 74decb671..df7730a49 100644
--- a/packages/js-sdk/src/api/schema.gen.ts
+++ b/packages/js-sdk/src/api/schema.gen.ts
@@ -2005,16 +2005,15 @@ export interface components {
/** @description Token required for accessing sandbox via proxy. */
trafficAccessToken?: string | null;
};
- /** @description Auto-resume configuration for paused sandboxes. Default is off. */
+ /** @description Auto-resume configuration for paused sandboxes. */
SandboxAutoResumeConfig: {
- policy: components["schemas"]["SandboxAutoResumePolicy"];
+ enabled: components["schemas"]["SandboxAutoResumeEnabled"];
};
/**
- * @description Auto-resume policy for paused sandboxes. Default is off.
- * @default off
- * @enum {string}
+ * @description Auto-resume enabled flag for paused sandboxes. Default false.
+ * @default false
*/
- SandboxAutoResumePolicy: "any" | "off";
+ SandboxAutoResumeEnabled: boolean;
SandboxDetail: {
/** @description Alias of the template */
alias?: string;
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index de04c3c4a..17d4a9752 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -49,6 +49,7 @@ export type {
SandboxListOpts,
SandboxPaginator,
SandboxNetworkOpts,
+ SandboxLifecycle,
SnapshotInfo,
SnapshotListOpts,
SnapshotPaginator,
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index 4d0d54c7f..b6fe426b3 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -466,7 +466,7 @@ export class Sandbox extends SandboxApi {
* const sameSandbox = await sandbox.connect()
* ```
*/
- async connect(opts?: SandboxBetaCreateOpts): Promise<this> {
+ async connect(opts?: SandboxConnectOpts): Promise<this> {
await SandboxApi.connectSandbox(this.sandboxId, opts)
return this
@@ -571,13 +571,24 @@ export class Sandbox extends SandboxApi {
}
/**
- * @beta This feature is in beta and may change in the future.
- *
* Pause a sandbox by its ID.
*
* @param opts connection options.
*
* @returns sandbox ID that can be used to resume the sandbox.
+ *
+ * @example
+ * ```ts
+ * const sandbox = await Sandbox.create()
+ * await sandbox.pause()
+ * ```
+ */
+ async pause(opts?: ConnectionOpts): Promise<boolean> {
+ return await SandboxApi.pause(this.sandboxId, opts)
+ }
+
+ /**
+ * @deprecated Use {@link Sandbox.pause} instead.
*/
async betaPause(opts?: ConnectionOpts): Promise<boolean> {
return await SandboxApi.betaPause(this.sandboxId, opts)
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index 9a3bb7b9f..fec8003c4 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -64,6 +64,21 @@ export type SandboxNetworkOpts = {
maskRequestHost?: string
}
+export type SandboxLifecycle = {
+ /**
+ * Action to take when sandbox timeout is reached.
+ * @default "kill"
+ */
+ onTimeout: 'pause' | 'kill'
+
+ /**
+ * Auto-resume enabled flag.
+ * @default false
+ * Can be `true` only when `onTimeout` is `pause`.
+ */
+ autoResume?: boolean
+}
+
/**
* Options for request to the Sandbox API.
*/
@@ -133,10 +148,17 @@ export interface SandboxOpts extends ConnectionOpts {
* Sandbox URL. Used for local development
*/
sandboxUrl?: string
+
+ /**
+ * Sandbox lifecycle configuration.
+ */
+ lifecycle?: SandboxLifecycle
}
export type SandboxBetaCreateOpts = SandboxOpts & {
/**
+ * @deprecated Use `lifecycle.onTimeout = "pause"` instead.
+ *
* Automatically pause the sandbox after the timeout expires.
* @default false
*/
@@ -330,6 +352,26 @@ export interface SandboxMetrics {
diskTotal: number
}
+function getLifecycle(
+ opts?: Pick<SandboxBetaCreateOpts, 'lifecycle' | 'autoPause'>
+): SandboxLifecycle {
+ if (opts?.lifecycle) {
+ return opts.lifecycle
+ }
+
+ if (opts?.autoPause) {
+ return {
+ onTimeout: 'pause',
+ autoResume: false,
+ }
+ }
+
+ return {
+ onTimeout: 'kill',
+ autoResume: false,
+ }
+}
+
export class SandboxApi {
protected constructor() {}
@@ -529,7 +571,7 @@ export class SandboxApi {
*
* @returns `true` if the sandbox got paused, `false` if the sandbox was already paused.
*/
- static async betaPause(
+ static async pause(
sandboxId: string,
opts?: SandboxApiOpts
): Promise<boolean> {
@@ -562,6 +604,16 @@ export class SandboxApi {
return true
}
+ /**
+ * @deprecated Use {@link SandboxApi.pause} instead.
+ */
+ static async betaPause(
+ sandboxId: string,
+ opts?: SandboxApiOpts
+ ): Promise<boolean> {
+ return this.pause(sandboxId, opts)
+ }
+
/**
* Create a snapshot from a sandbox.
*
@@ -659,19 +711,30 @@ export class SandboxApi {
) {
const config = new ConnectionConfig(opts)
const client = new ApiClient(config)
+ const lifecycle = getLifecycle(opts)
+ const autoPause = lifecycle.onTimeout === 'pause'
+ const autoResumeEnabled =
+ lifecycle.onTimeout === 'pause'
+ ? (lifecycle.autoResume ?? false)
+ : undefined
+
+ const body: components['schemas']['NewSandbox'] = {
+ templateID: template,
+ metadata: opts?.metadata,
+ mcp: opts?.mcp as Record<string, unknown> | undefined,
+ envVars: opts?.envs,
+ timeout: timeoutToSeconds(timeoutMs),
+ secure: opts?.secure ?? true,
+ allow_internet_access: opts?.allowInternetAccess ?? true,
+ network: opts?.network,
+ ...(autoPause !== undefined ? { autoPause } : {}),
+ ...(autoResumeEnabled !== undefined
+ ? { autoResume: { enabled: autoResumeEnabled } }
+ : {}),
+ }
const res = await client.api.POST('/sandboxes', {
- body: {
- autoPause: opts?.autoPause ?? false,
- templateID: template,
- metadata: opts?.metadata,
- mcp: opts?.mcp as Record<string, unknown> | undefined,
- envVars: opts?.envs,
- timeout: timeoutToSeconds(timeoutMs),
- secure: opts?.secure ?? true,
- allow_internet_access: opts?.allowInternetAccess ?? true,
- network: opts?.network,
- },
+ body,
signal: config.getSignal(opts?.requestTimeoutMs),
})
diff --git a/packages/js-sdk/tests/api/snapshot.test.ts b/packages/js-sdk/tests/api/snapshot.test.ts
index ce5022eaf..828389d14 100644
--- a/packages/js-sdk/tests/api/snapshot.test.ts
+++ b/packages/js-sdk/tests/api/snapshot.test.ts
@@ -4,7 +4,7 @@ import { sandboxTest, isDebug } from '../setup.js'
import { Sandbox } from '../../src'
sandboxTest.skipIf(isDebug)('pause sandbox', async ({ sandbox }) => {
- await Sandbox.betaPause(sandbox.sandboxId)
+ await Sandbox.pause(sandbox.sandboxId)
assert.isFalse(
await sandbox.isRunning(),
'Sandbox should not be running after pause'
@@ -12,7 +12,7 @@ sandboxTest.skipIf(isDebug)('pause sandbox', async ({ sandbox }) => {
})
sandboxTest.skipIf(isDebug)('resume sandbox', async ({ sandbox }) => {
- await Sandbox.betaPause(sandbox.sandboxId)
+ await Sandbox.pause(sandbox.sandboxId)
assert.isFalse(
await sandbox.isRunning(),
'Sandbox should not be running after pause'
diff --git a/packages/js-sdk/tests/sandbox/connect.test.ts b/packages/js-sdk/tests/sandbox/connect.test.ts
index 3f548c5db..2a5efc060 100644
--- a/packages/js-sdk/tests/sandbox/connect.test.ts
+++ b/packages/js-sdk/tests/sandbox/connect.test.ts
@@ -20,6 +20,17 @@ test.skipIf(isDebug)('connect', async () => {
}
})
+sandboxTest.skipIf(isDebug)(
+ 'connect resumes paused sandbox',
+ async ({ sandbox }) => {
+ await sandbox.pause()
+ assert.isFalse(await sandbox.isRunning())
+
+ const resumed = await Sandbox.connect(sandbox.sandboxId)
+ assert.isTrue(await resumed.isRunning())
+ }
+)
+
sandboxTest.skipIf(isDebug)(
'connect to non-running sandbox',
async ({ sandbox }) => {
diff --git a/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts b/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts
new file mode 100644
index 000000000..3c930a7fa
--- /dev/null
+++ b/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts
@@ -0,0 +1,63 @@
+import { assert, test } from 'vitest'
+
+import { Sandbox } from '../../src'
+import { isDebug, template, wait } from '../setup.js'
+
+test.skipIf(isDebug)(
+ 'auto-pause without auto-resume requires connect to wake',
+ async () => {
+ const sandbox = await Sandbox.create(template, {
+ timeoutMs: 3_000,
+ lifecycle: {
+ onTimeout: 'pause',
+ autoResume: false,
+ },
+ })
+
+ try {
+ await wait(5_000)
+
+ assert.equal((await sandbox.getInfo()).state, 'paused')
+ assert.isFalse(await sandbox.isRunning())
+
+ await sandbox.connect()
+
+ assert.equal((await sandbox.getInfo()).state, 'running')
+ assert.isTrue(await sandbox.isRunning())
+ } finally {
+ await sandbox.kill().catch(() => {})
+ }
+ },
+ 60_000
+)
+
+test.skipIf(isDebug)(
+ 'auto-resume wakes paused sandbox on http request',
+ async () => {
+ const sandbox = await Sandbox.create(template, {
+ timeoutMs: 3_000,
+ lifecycle: {
+ onTimeout: 'pause',
+ autoResume: true,
+ },
+ })
+
+ try {
+ await sandbox.commands.run('python3 -m http.server 8000', {
+ background: true,
+ })
+
+ await wait(5_000)
+
+ const url = `https://${sandbox.getHost(8000)}`
+ const res = await fetch(url, { signal: AbortSignal.timeout(15_000) })
+
+ assert.equal(res.status, 200)
+ assert.equal((await sandbox.getInfo()).state, 'running')
+ assert.isTrue(await sandbox.isRunning())
+ } finally {
+ await sandbox.kill().catch(() => {})
+ }
+ },
+ 60_000
+)
diff --git a/packages/js-sdk/tests/sandbox/snapshot.test.ts b/packages/js-sdk/tests/sandbox/snapshot.test.ts
index a60ae5f7b..28d2cfc58 100644
--- a/packages/js-sdk/tests/sandbox/snapshot.test.ts
+++ b/packages/js-sdk/tests/sandbox/snapshot.test.ts
@@ -7,7 +7,7 @@ sandboxTest.skipIf(isDebug)(
async ({ sandbox }) => {
assert.isTrue(await sandbox.isRunning())
- await sandbox.betaPause()
+ await sandbox.pause()
assert.isFalse(await sandbox.isRunning())
@@ -35,7 +35,7 @@ describe('pause and resume with env vars', () => {
assert.equal(cmd.exitCode, 0)
assert.equal(cmd.stdout.trim(), 'sfisback')
- await sandbox.betaPause()
+ await sandbox.pause()
assert.isFalse(await sandbox.isRunning())
@@ -68,7 +68,7 @@ sandboxTest.skipIf(isDebug)(
const readContent = await sandbox.files.read(filename)
assert.equal(readContent, content)
- await sandbox.betaPause()
+ await sandbox.pause()
assert.isFalse(await sandbox.isRunning())
await sandbox.connect()
@@ -87,7 +87,7 @@ sandboxTest.skipIf(isDebug)(
const cmd = await sandbox.commands.run('sleep 3600', { background: true })
const expectedPid = cmd.pid
- await sandbox.betaPause()
+ await sandbox.pause()
assert.isFalse(await sandbox.isRunning())
await sandbox.connect()
@@ -121,7 +121,7 @@ sandboxTest.skipIf(isDebug)(
const exists = await sandbox.files.exists(filename)
assert.isFalse(exists)
- await sandbox.betaPause()
+ await sandbox.pause()
assert.isFalse(await sandbox.isRunning())
await sandbox.connect()
@@ -151,7 +151,7 @@ sandboxTest.skipIf(isDebug)(
const response1 = await fetch(`https://${url}`)
assert.equal(response1.status, 200)
- await sandbox.betaPause()
+ await sandbox.pause()
assert.isFalse(await sandbox.isRunning())
await sandbox.connect()
diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.py
index 9fe172afa..264fd5dee 100644
--- a/packages/python-sdk/e2b/__init__.py
+++ b/packages/python-sdk/e2b/__init__.py
@@ -68,6 +68,7 @@ from .sandbox.sandbox_api import (
McpServer,
SandboxInfo,
SandboxMetrics,
+ SandboxLifecycle,
SandboxNetworkOpts,
SandboxQuery,
SandboxState,
@@ -154,6 +155,7 @@ __all__ = [
"FileType",
# Network
"SandboxNetworkOpts",
+ "SandboxLifecycle",
"ALL_TRAFFIC",
# Snapshot
"SnapshotInfo",
diff --git a/packages/python-sdk/e2b/api/client/models/__init__.py b/packages/python-sdk/e2b/api/client/models/__init__.py
index d06a594bd..ee88093d7 100644
--- a/packages/python-sdk/e2b/api/client/models/__init__.py
+++ b/packages/python-sdk/e2b/api/client/models/__init__.py
@@ -44,7 +44,6 @@ from .post_sandboxes_sandbox_id_timeout_body import PostSandboxesSandboxIDTimeou
from .resumed_sandbox import ResumedSandbox
from .sandbox import Sandbox
from .sandbox_auto_resume_config import SandboxAutoResumeConfig
-from .sandbox_auto_resume_policy import SandboxAutoResumePolicy
from .sandbox_detail import SandboxDetail
from .sandbox_log import SandboxLog
from .sandbox_log_entry import SandboxLogEntry
@@ -123,7 +122,6 @@ __all__ = (
"ResumedSandbox",
"Sandbox",
"SandboxAutoResumeConfig",
- "SandboxAutoResumePolicy",
"SandboxDetail",
"SandboxesWithMetrics",
"SandboxLog",
diff --git a/packages/python-sdk/e2b/api/client/models/new_sandbox.py b/packages/python-sdk/e2b/api/client/models/new_sandbox.py
index dcac3592c..8703ef569 100644
--- a/packages/python-sdk/e2b/api/client/models/new_sandbox.py
+++ b/packages/python-sdk/e2b/api/client/models/new_sandbox.py
@@ -24,8 +24,7 @@ class NewSandbox:
allow_internet_access (Union[Unset, bool]): Allow sandbox to access the internet. When set to false, it behaves
the same as specifying denyOut to 0.0.0.0/0 in the network config.
auto_pause (Union[Unset, bool]): Automatically pauses the sandbox after the timeout Default: False.
- auto_resume (Union[Unset, SandboxAutoResumeConfig]): Auto-resume configuration for paused sandboxes. Default is
- off.
+ auto_resume (Union[Unset, SandboxAutoResumeConfig]): Auto-resume configuration for paused sandboxes.
env_vars (Union[Unset, Any]):
mcp (Union['McpType0', None, Unset]): MCP configuration for the sandbox
metadata (Union[Unset, Any]):
diff --git a/packages/python-sdk/e2b/api/client/models/sandbox_auto_resume_config.py b/packages/python-sdk/e2b/api/client/models/sandbox_auto_resume_config.py
index f4c66e0c8..c5db58b37 100644
--- a/packages/python-sdk/e2b/api/client/models/sandbox_auto_resume_config.py
+++ b/packages/python-sdk/e2b/api/client/models/sandbox_auto_resume_config.py
@@ -4,30 +4,28 @@ from typing import Any, TypeVar
from attrs import define as _attrs_define
from attrs import field as _attrs_field
-from ..models.sandbox_auto_resume_policy import SandboxAutoResumePolicy
-
T = TypeVar("T", bound="SandboxAutoResumeConfig")
@_attrs_define
class SandboxAutoResumeConfig:
- """Auto-resume configuration for paused sandboxes. Default is off.
+ """Auto-resume configuration for paused sandboxes.
Attributes:
- policy (SandboxAutoResumePolicy): Auto-resume policy for paused sandboxes. Default is off.
+ enabled (bool): Auto-resume enabled flag for paused sandboxes. Default false.
"""
- policy: SandboxAutoResumePolicy
+ enabled: bool
additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
def to_dict(self) -> dict[str, Any]:
- policy = self.policy.value
+ enabled = self.enabled
field_dict: dict[str, Any] = {}
field_dict.update(self.additional_properties)
field_dict.update(
{
- "policy": policy,
+ "enabled": enabled,
}
)
@@ -36,10 +34,10 @@ class SandboxAutoResumeConfig:
@classmethod
def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
d = dict(src_dict)
- policy = SandboxAutoResumePolicy(d.pop("policy"))
+ enabled = d.pop("enabled")
sandbox_auto_resume_config = cls(
- policy=policy,
+ enabled=enabled,
)
sandbox_auto_resume_config.additional_properties = d
diff --git a/packages/python-sdk/e2b/api/client/models/sandbox_auto_resume_policy.py b/packages/python-sdk/e2b/api/client/models/sandbox_auto_resume_policy.py
deleted file mode 100644
index cec37aa60..000000000
--- a/packages/python-sdk/e2b/api/client/models/sandbox_auto_resume_policy.py
+++ /dev/null
@@ -1,9 +0,0 @@
-from enum import Enum
-
-
-class SandboxAutoResumePolicy(str, Enum):
- ANY = "any"
- OFF = "off"
-
- def __str__(self) -> str:
- return str(self.value)
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.py
index b5a715ee1..7339db3b9 100644
--- a/packages/python-sdk/e2b/sandbox/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass
from datetime import datetime
-from typing import Any, Dict, List, Optional, TypedDict, Union, cast
+from typing import Any, Dict, List, Literal, Optional, TypedDict, Union, cast
from typing_extensions import NotRequired, Unpack
@@ -76,6 +76,31 @@ class SandboxNetworkOpts(TypedDict):
"""
+class SandboxLifecycle(TypedDict):
+ """
+ Sandbox lifecycle configuration; defines post-timeout behavior and auto-resume settings.
+ Defaults to `on_timeout="kill"` and `auto_resume=False`.
+ """
+
+ on_timeout: Literal["pause", "kill"]
+ """
+ What should happen to the sandbox when timeout is reached. `"kill"` means the sandbox will be terminated, while `"pause"` means the sandbox will be paused and can be resumed later. Defaults to `"kill"`.
+ """
+
+ auto_resume: NotRequired[bool]
+ """
+ Whether activity should cause the sandbox to resume when paused. Defaults to `False`.
+ Can be `True` only when `on_timeout` is `pause`.
+ """
+
+
+def get_auto_resume_enabled(lifecycle: Optional[SandboxLifecycle]) -> Optional[bool]:
+ if lifecycle is None or lifecycle.get("on_timeout") != "pause":
+ return None
+
+ return lifecycle.get("auto_resume", False)
+
+
@dataclass
class SandboxInfo:
"""Information about a sandbox."""
diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.py
index f7d0e0a59..d256074a7 100644
--- a/packages/python-sdk/e2b/sandbox_async/main.py
+++ b/packages/python-sdk/e2b/sandbox_async/main.py
@@ -13,10 +13,14 @@ from e2b.api.client_async import get_transport
from e2b.connection_config import ApiParams, ConnectionConfig
from e2b.envd.api import ENVD_API_HEALTH_ROUTE, ahandle_envd_api_exception
from e2b.envd.versions import ENVD_DEBUG_FALLBACK
-from e2b.exceptions import SandboxException, format_request_timeout_error
+from e2b.exceptions import (
+ SandboxException,
+ format_request_timeout_error,
+)
from e2b.sandbox.main import SandboxOpts
from e2b.sandbox.sandbox_api import (
McpServer,
+ SandboxLifecycle,
SandboxMetrics,
SandboxNetworkOpts,
SnapshotInfo,
@@ -168,6 +172,7 @@ class AsyncSandbox(SandboxApi):
allow_internet_access: bool = True,
mcp: Optional[McpServer] = None,
network: Optional[SandboxNetworkOpts] = None,
+ lifecycle: Optional[SandboxLifecycle] = None,
**opts: Unpack[ApiParams],
) -> Self:
"""
@@ -183,6 +188,7 @@ class AsyncSandbox(SandboxApi):
:param allow_internet_access: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`.
:param mcp: MCP server to enable in the sandbox
:param network: Sandbox network configuration
+ :param lifecycle: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` (default) or ``"pause"``; ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout="pause"``). Example: ``{"on_timeout": "pause", "auto_resume": True}``
:return: A Sandbox instance for the new sandbox
@@ -203,6 +209,7 @@ class AsyncSandbox(SandboxApi):
allow_internet_access=allow_internet_access,
mcp=mcp,
network=network,
+ lifecycle=lifecycle,
**opts,
)
@@ -239,7 +246,7 @@ class AsyncSandbox(SandboxApi):
@example
```python
sandbox = await AsyncSandbox.create()
- await sandbox.beta_pause()
+ await sandbox.pause()
# Another code block
same_sandbox = await sandbox.connect()
@@ -268,10 +275,10 @@ class AsyncSandbox(SandboxApi):
@example
```python
sandbox = await AsyncSandbox.create()
- await AsyncSandbox.beta_pause(sandbox.sandbox_id)
+ await AsyncSandbox.pause(sandbox.sandbox_id)
# Another code block
- same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id))
+ same_sandbox = await AsyncSandbox.connect(sandbox.sandbox_id)
```
"""
...
@@ -295,7 +302,7 @@ class AsyncSandbox(SandboxApi):
@example
```python
sandbox = await AsyncSandbox.create()
- await sandbox.beta_pause()
+ await sandbox.pause()
# Another code block
same_sandbox = await sandbox.connect()
@@ -569,6 +576,9 @@ class AsyncSandbox(SandboxApi):
secure=secure,
allow_internet_access=allow_internet_access,
mcp=mcp,
+ lifecycle=(
+ {"on_timeout": "pause", "auto_resume": False} if auto_pause else None
+ ),
**opts,
)
@@ -587,13 +597,11 @@ class AsyncSandbox(SandboxApi):
return sandbox
@overload
- async def beta_pause(
+ async def pause(
self,
**opts: Unpack[ApiParams],
) -> None:
"""
- [BETA] This feature is in beta and may change in the future.
-
Pause the sandbox.
:return: Sandbox ID that can be used to resume the sandbox
@@ -602,13 +610,11 @@ class AsyncSandbox(SandboxApi):
@overload
@staticmethod
- async def beta_pause(
+ async def pause(
sandbox_id: str,
**opts: Unpack[ApiParams],
) -> None:
"""
- [BETA] This feature is in beta and may change in the future.
-
Pause the sandbox specified by sandbox ID.
:param sandbox_id: Sandbox ID
@@ -618,13 +624,11 @@ class AsyncSandbox(SandboxApi):
...
@class_method_variant("_cls_pause")
- async def beta_pause(
+ async def pause(
self,
**opts: Unpack[ApiParams],
) -> None:
"""
- [BETA] This feature is in beta and may change in the future.
-
Pause the sandbox.
:return: Sandbox ID that can be used to resume the sandbox
@@ -635,6 +639,29 @@ class AsyncSandbox(SandboxApi):
**opts,
)
+ @overload
+ async def beta_pause(
+ self,
+ **opts: Unpack[ApiParams],
+ ) -> None: ...
+
+ @overload
+ @staticmethod
+ async def beta_pause(
+ sandbox_id: str,
+ **opts: Unpack[ApiParams],
+ ) -> None: ...
+
+ @class_method_variant("_cls_pause")
+ async def beta_pause(
+ self,
+ **opts: Unpack[ApiParams],
+ ) -> None:
+ """
+ :deprecated: Use `pause()` instead.
+ """
+ await self.pause(**opts)
+
@overload
async def create_snapshot(
self,
@@ -828,13 +855,14 @@ class AsyncSandbox(SandboxApi):
cls,
template: Optional[str],
timeout: Optional[int],
- auto_pause: bool,
+ auto_pause: Optional[bool],
allow_internet_access: bool,
metadata: Optional[Dict[str, str]],
envs: Optional[Dict[str, str]],
secure: bool,
mcp: Optional[McpServer] = None,
network: Optional[SandboxNetworkOpts] = None,
+ lifecycle: Optional[SandboxLifecycle] = None,
**opts: Unpack[ApiParams],
) -> Self:
extra_sandbox_headers = {}
@@ -857,6 +885,7 @@ class AsyncSandbox(SandboxApi):
allow_internet_access=allow_internet_access,
mcp=mcp,
network=network,
+ lifecycle=lifecycle,
**opts,
)
diff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
index b5e8c8835..dc2547ffd 100644
--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
@@ -23,14 +23,21 @@ from e2b.api.client.models import (
PostSandboxesSandboxIDSnapshotsBody,
PostSandboxesSandboxIDTimeoutBody,
Sandbox,
+ SandboxAutoResumeConfig,
SandboxNetworkConfig,
)
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 NotFoundException, SandboxException, TemplateException
+from e2b.exceptions import (
+ NotFoundException,
+ SandboxException,
+ TemplateException,
+)
from e2b.sandbox.main import SandboxBase
from e2b.sandbox.sandbox_api import (
+ SandboxLifecycle,
+ get_auto_resume_enabled,
McpServer,
SandboxInfo,
SandboxMetrics,
@@ -156,30 +163,39 @@ class SandboxApi(SandboxBase):
cls,
template: str,
timeout: int,
- auto_pause: bool,
+ auto_pause: Optional[bool],
allow_internet_access: bool,
metadata: Optional[Dict[str, str]],
env_vars: Optional[Dict[str, str]],
secure: bool,
mcp: Optional[McpServer] = None,
network: Optional[SandboxNetworkOpts] = None,
+ lifecycle: Optional[SandboxLifecycle] = None,
**opts: Unpack[ApiParams],
) -> SandboxCreateResponse:
config = ConnectionConfig(**opts)
+ should_auto_pause = (
+ lifecycle["on_timeout"] == "pause" if lifecycle is not None else auto_pause
+ )
+ auto_resume_enabled = get_auto_resume_enabled(lifecycle)
+ body = NewSandbox(
+ template_id=template,
+ auto_pause=(should_auto_pause if should_auto_pause is not None else UNSET),
+ metadata=metadata or {},
+ timeout=timeout,
+ env_vars=env_vars or {},
+ mcp=cast(Any, mcp) or UNSET,
+ secure=secure,
+ allow_internet_access=allow_internet_access,
+ network=SandboxNetworkConfig(**network) if network else UNSET,
+ )
+ if auto_resume_enabled is not None:
+ body.auto_resume = SandboxAutoResumeConfig(enabled=auto_resume_enabled)
+
api_client = get_api_client(config)
res = await post_sandboxes.asyncio_detailed(
- body=NewSandbox(
- template_id=template,
- auto_pause=auto_pause,
- metadata=metadata or {},
- timeout=timeout,
- env_vars=env_vars or {},
- mcp=cast(Any, mcp) or UNSET,
- secure=secure,
- allow_internet_access=allow_internet_access,
- network=SandboxNetworkConfig(**network) if network else UNSET,
- ),
+ body=body,
client=api_client,
)
diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.py
index 673f919b9..35014e995 100644
--- a/packages/python-sdk/e2b/sandbox_sync/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/main.py
@@ -13,10 +13,14 @@ from e2b.api.client_sync import get_transport
from e2b.connection_config import ApiParams, ConnectionConfig
from e2b.envd.api import ENVD_API_HEALTH_ROUTE, handle_envd_api_exception
from e2b.envd.versions import ENVD_DEBUG_FALLBACK
-from e2b.exceptions import SandboxException, format_request_timeout_error
+from e2b.exceptions import (
+ SandboxException,
+ format_request_timeout_error,
+)
from e2b.sandbox.main import SandboxOpts
from e2b.sandbox.sandbox_api import (
McpServer,
+ SandboxLifecycle,
SandboxMetrics,
SandboxNetworkOpts,
SnapshotInfo,
@@ -166,6 +170,7 @@ class Sandbox(SandboxApi):
allow_internet_access: bool = True,
mcp: Optional[McpServer] = None,
network: Optional[SandboxNetworkOpts] = None,
+ lifecycle: Optional[SandboxLifecycle] = None,
**opts: Unpack[ApiParams],
) -> Self:
"""
@@ -181,6 +186,7 @@ class Sandbox(SandboxApi):
:param allow_internet_access: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`.
:param mcp: MCP server to enable in the sandbox
:param network: Sandbox network configuration
+ :param lifecycle: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` (default) or ``"pause"``; ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout="pause"``). Example: ``{"on_timeout": "pause", "auto_resume": True}``
:return: A Sandbox instance for the new sandbox
@@ -201,6 +207,7 @@ class Sandbox(SandboxApi):
allow_internet_access=allow_internet_access,
mcp=mcp,
network=network,
+ lifecycle=lifecycle,
**opts,
)
@@ -237,7 +244,7 @@ class Sandbox(SandboxApi):
@example
```python
sandbox = Sandbox.create()
- sandbox.beta_pause()
+ sandbox.pause()
# Another code block
same_sandbox = sandbox.connect()
@@ -267,7 +274,7 @@ class Sandbox(SandboxApi):
@example
```python
sandbox = Sandbox.create()
- Sandbox.beta_pause(sandbox.sandbox_id)
+ Sandbox.pause(sandbox.sandbox_id)
# Another code block
same_sandbox = Sandbox.connect(sandbox.sandbox_id)
@@ -294,7 +301,7 @@ class Sandbox(SandboxApi):
@example
```python
sandbox = Sandbox.create()
- sandbox.beta_pause()
+ sandbox.pause()
# Another code block
same_sandbox = sandbox.connect()
@@ -570,6 +577,9 @@ class Sandbox(SandboxApi):
secure=secure,
allow_internet_access=allow_internet_access,
mcp=mcp,
+ lifecycle=(
+ {"on_timeout": "pause", "auto_resume": False} if auto_pause else None
+ ),
**opts,
)
@@ -588,26 +598,22 @@ class Sandbox(SandboxApi):
return sandbox
@overload
- def beta_pause(
+ def pause(
self,
**opts: Unpack[ApiParams],
) -> None:
"""
- [BETA] This feature is in beta and may change in the future.
-
Pause the sandbox.
"""
...
@overload
@staticmethod
- def beta_pause(
+ def pause(
sandbox_id: str,
**opts: Unpack[ApiParams],
) -> None:
"""
- [BETA] This feature is in beta and may change in the future.
-
Pause the sandbox specified by sandbox ID.
:param sandbox_id: Sandbox ID
@@ -615,13 +621,11 @@ class Sandbox(SandboxApi):
...
@class_method_variant("_cls_pause")
- def beta_pause(
+ def pause(
self,
**opts: Unpack[ApiParams],
) -> None:
"""
- [BETA] This feature is in beta and may change in the future.
-
Pause the sandbox.
:return: Sandbox ID that can be used to resume the sandbox
@@ -632,6 +636,29 @@ class Sandbox(SandboxApi):
**opts,
)
+ @overload
+ def beta_pause(
+ self,
+ **opts: Unpack[ApiParams],
+ ) -> None: ...
+
+ @overload
+ @staticmethod
+ def beta_pause(
+ sandbox_id: str,
+ **opts: Unpack[ApiParams],
+ ) -> None: ...
+
+ @class_method_variant("_cls_pause")
+ def beta_pause(
+ self,
+ **opts: Unpack[ApiParams],
+ ) -> None:
+ """
+ :deprecated: Use `pause()` instead.
+ """
+ self.pause(**opts)
+
@overload
def create_snapshot(
self,
@@ -793,7 +820,11 @@ class Sandbox(SandboxApi):
timeout: Optional[int] = None,
**opts: Unpack[ApiParams],
) -> Self:
- sandbox = SandboxApi._cls_connect(sandbox_id, timeout, **opts)
+ sandbox = SandboxApi._cls_connect(
+ sandbox_id=sandbox_id,
+ timeout=timeout,
+ **opts,
+ )
sandbox_headers = {}
envd_access_token = sandbox.envd_access_token
@@ -806,7 +837,7 @@ class Sandbox(SandboxApi):
)
return cls(
- sandbox_id=sandbox_id,
+ sandbox_id=sandbox.sandbox_id,
sandbox_domain=sandbox.domain,
connection_config=connection_config,
envd_version=Version(sandbox.envd_version),
@@ -819,13 +850,14 @@ class Sandbox(SandboxApi):
cls,
template: Optional[str],
timeout: Optional[int],
- auto_pause: bool,
+ auto_pause: Optional[bool],
metadata: Optional[Dict[str, str]],
envs: Optional[Dict[str, str]],
secure: bool,
allow_internet_access: bool,
mcp: Optional[McpServer] = None,
network: Optional[SandboxNetworkOpts] = None,
+ lifecycle: Optional[SandboxLifecycle] = None,
**opts: Unpack[ApiParams],
) -> Self:
extra_sandbox_headers = {}
@@ -848,6 +880,7 @@ class Sandbox(SandboxApi):
allow_internet_access=allow_internet_access,
mcp=mcp,
network=network,
+ lifecycle=lifecycle,
**opts,
)
diff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
index 3fbd7f956..3761730d4 100644
--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
@@ -23,13 +23,20 @@ from e2b.api.client.models import (
PostSandboxesSandboxIDSnapshotsBody,
PostSandboxesSandboxIDTimeoutBody,
Sandbox,
+ SandboxAutoResumeConfig,
SandboxNetworkConfig,
)
from e2b.api.client.types import UNSET
from e2b.connection_config import ApiParams, ConnectionConfig
-from e2b.exceptions import NotFoundException, SandboxException, TemplateException
+from e2b.exceptions import (
+ NotFoundException,
+ SandboxException,
+ TemplateException,
+)
from e2b.sandbox.main import SandboxBase
from e2b.sandbox.sandbox_api import (
+ SandboxLifecycle,
+ get_auto_resume_enabled,
McpServer,
SandboxInfo,
SandboxMetrics,
@@ -155,30 +162,39 @@ class SandboxApi(SandboxBase):
cls,
template: str,
timeout: int,
- auto_pause: bool,
+ auto_pause: Optional[bool],
allow_internet_access: bool,
metadata: Optional[Dict[str, str]],
env_vars: Optional[Dict[str, str]],
secure: bool,
mcp: Optional[McpServer] = None,
network: Optional[SandboxNetworkOpts] = None,
+ lifecycle: Optional[SandboxLifecycle] = None,
**opts: Unpack[ApiParams],
) -> SandboxCreateResponse:
config = ConnectionConfig(**opts)
+ should_auto_pause = (
+ lifecycle["on_timeout"] == "pause" if lifecycle is not None else auto_pause
+ )
+ auto_resume_enabled = get_auto_resume_enabled(lifecycle)
+ body = NewSandbox(
+ template_id=template,
+ auto_pause=(should_auto_pause if should_auto_pause is not None else UNSET),
+ metadata=metadata or {},
+ timeout=timeout,
+ env_vars=env_vars or {},
+ mcp=cast(Any, mcp) or UNSET,
+ secure=secure,
+ allow_internet_access=allow_internet_access,
+ network=SandboxNetworkConfig(**network) if network else UNSET,
+ )
+ if auto_resume_enabled is not None:
+ body.auto_resume = SandboxAutoResumeConfig(enabled=auto_resume_enabled)
+
api_client = get_api_client(config)
res = post_sandboxes.sync_detailed(
- body=NewSandbox(
- template_id=template,
- auto_pause=auto_pause,
- metadata=metadata or {},
- timeout=timeout,
- env_vars=env_vars or {},
- mcp=cast(Any, mcp) or UNSET,
- secure=secure,
- allow_internet_access=allow_internet_access,
- network=SandboxNetworkConfig(**network) if network else UNSET,
- ),
+ body=body,
client=api_client,
)
diff --git a/packages/python-sdk/tests/async/api_async/test_sbx_snapshot.py b/packages/python-sdk/tests/async/api_async/test_sbx_snapshot.py
index 0fa2a34e8..49cc2a5f0 100644
--- a/packages/python-sdk/tests/async/api_async/test_sbx_snapshot.py
+++ b/packages/python-sdk/tests/async/api_async/test_sbx_snapshot.py
@@ -4,14 +4,14 @@ from e2b import AsyncSandbox
@pytest.mark.skip_debug()
async def test_pause_sandbox(async_sandbox: AsyncSandbox):
- await AsyncSandbox.beta_pause(async_sandbox.sandbox_id)
+ await AsyncSandbox.pause(async_sandbox.sandbox_id)
assert not await async_sandbox.is_running()
@pytest.mark.skip_debug()
async def test_resume_sandbox(async_sandbox: AsyncSandbox):
# pause
- await AsyncSandbox.beta_pause(async_sandbox.sandbox_id)
+ await AsyncSandbox.pause(async_sandbox.sandbox_id)
assert not await async_sandbox.is_running()
# resume
diff --git a/packages/python-sdk/tests/async/sandbox_async/test_connect.py b/packages/python-sdk/tests/async/sandbox_async/test_connect.py
index 2d2a6e2c5..8dc89c85c 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_connect.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_connect.py
@@ -30,7 +30,16 @@ async def test_connect_with_secure(async_sandbox_factory):
@pytest.mark.skip_debug()
-async def test_connect_does_not_shorten_timeout_on_running_sandbox(
+async def test_connect_to_paused_sandbox_resumes(async_sandbox):
+ await async_sandbox.pause()
+ assert not await async_sandbox.is_running()
+
+ resumed = await AsyncSandbox.connect(async_sandbox.sandbox_id)
+ assert await resumed.is_running()
+
+
+async def test_resume_does_not_shorten_timeout_on_running_sandbox(
async_sandbox_factory,
):
# Create sandbox with a 300 second timeout
diff --git a/packages/python-sdk/tests/async/sandbox_async/test_create.py b/packages/python-sdk/tests/async/sandbox_async/test_create.py
index 95f000dda..e5d002945 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_create.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_create.py
@@ -1,6 +1,14 @@
+import asyncio
+
+import httpx
import pytest
-from e2b import AsyncSandbox, SandboxQuery
+from e2b import AsyncSandbox, SandboxQuery, SandboxState
+from e2b.api.client.models import (
+ NewSandbox,
+ SandboxAutoResumeConfig,
+)
+from e2b.sandbox.sandbox_api import get_auto_resume_enabled
@pytest.mark.skip_debug()
@@ -25,3 +33,81 @@ async def test_metadata(async_sandbox_factory):
break
else:
assert False, "Sandbox not found"
+
+
+def test_lifecycle_auto_resume_enabled_mapping():
+ assert get_auto_resume_enabled({"on_timeout": "pause", "auto_resume": True}) is True
+ assert (
+ get_auto_resume_enabled({"on_timeout": "pause", "auto_resume": False}) is False
+ )
+ assert get_auto_resume_enabled({"on_timeout": "pause"}) is False
+ assert get_auto_resume_enabled({"on_timeout": "kill", "auto_resume": False}) is None
+ assert get_auto_resume_enabled({"on_timeout": "kill"}) is None
+ assert get_auto_resume_enabled(None) is None
+
+
+def test_create_payload_serializes_auto_resume_enabled():
+ body = NewSandbox(
+ template_id="template-id",
+ auto_pause=True,
+ auto_resume=SandboxAutoResumeConfig(enabled=True),
+ )
+
+ assert body.to_dict()["autoPause"] is True
+ assert body.to_dict()["autoResume"] == {"enabled": True}
+
+
+def test_create_payload_deserializes_auto_resume_enabled():
+ body = NewSandbox.from_dict(
+ {
+ "templateID": "template-id",
+ "autoPause": False,
+ "autoResume": {"enabled": False},
+ }
+ )
+
+ assert isinstance(body.auto_resume, SandboxAutoResumeConfig)
+ assert body.auto_resume.to_dict() == {"enabled": False}
+
+
+async def test_auto_pause_without_auto_resume_requires_connect(async_sandbox_factory):
+ sandbox = await async_sandbox_factory(
+ timeout=3,
+ lifecycle={"on_timeout": "pause", "auto_resume": False},
+ )
+
+ await asyncio.sleep(5)
+
+ assert (await sandbox.get_info()).state == SandboxState.PAUSED
+ assert not await sandbox.is_running()
+
+ await sandbox.connect()
+
+ assert (await sandbox.get_info()).state == SandboxState.RUNNING
+ assert await sandbox.is_running()
+
+
+async def test_auto_resume_wakes_on_http_request(async_sandbox_factory):
+ sandbox = await async_sandbox_factory(
+ timeout=3,
+ lifecycle={"on_timeout": "pause", "auto_resume": True},
+ )
+
+ cmd = await sandbox.commands.run("python3 -m http.server 8000", background=True)
+ try:
+ await asyncio.sleep(5)
+
+ url = f"https://{sandbox.get_host(8000)}"
+ async with httpx.AsyncClient(timeout=15.0) as client:
+ res = await client.get(url)
+
+ assert res.status_code == 200
+ assert (await sandbox.get_info()).state == SandboxState.RUNNING
+ assert await sandbox.is_running()
+ finally:
+ try:
+ await cmd.kill()
+ except Exception:
+ pass
diff --git a/packages/python-sdk/tests/async/sandbox_async/test_snapshot.py b/packages/python-sdk/tests/async/sandbox_async/test_snapshot.py
index d5b7bce4e..a871b8296 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_snapshot.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_snapshot.py
@@ -6,7 +6,7 @@ from e2b import AsyncSandbox
async def test_snapshot(async_sandbox: AsyncSandbox):
assert await async_sandbox.is_running()
- await async_sandbox.beta_pause()
+ await async_sandbox.pause()
assert not await async_sandbox.is_running()
resumed_sandbox = await async_sandbox.connect()
diff --git a/packages/python-sdk/tests/sync/api_sync/test_sbx_snapshot.py b/packages/python-sdk/tests/sync/api_sync/test_sbx_snapshot.py
index b87b8d4c5..627a2f6ef 100644
--- a/packages/python-sdk/tests/sync/api_sync/test_sbx_snapshot.py
+++ b/packages/python-sdk/tests/sync/api_sync/test_sbx_snapshot.py
@@ -4,14 +4,14 @@ from e2b import Sandbox
@pytest.mark.skip_debug()
def test_pause_sandbox(sandbox: Sandbox):
- Sandbox.beta_pause(sandbox.sandbox_id)
+ Sandbox.pause(sandbox.sandbox_id)
assert not sandbox.is_running()
@pytest.mark.skip_debug()
def test_resume_sandbox(sandbox: Sandbox):
# pause
- Sandbox.beta_pause(sandbox.sandbox_id)
+ Sandbox.pause(sandbox.sandbox_id)
assert not sandbox.is_running()
# resume
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_connect.py b/packages/python-sdk/tests/sync/sandbox_sync/test_connect.py
index 7f6eff4bd..b9c6b9fa8 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_connect.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_connect.py
@@ -30,7 +30,16 @@ def test_connect_with_secure(sandbox_factory):
@pytest.mark.skip_debug()
-def test_connect_does_not_shorten_timeout_on_running_sandbox(sandbox_factory):
+def test_connect_to_paused_sandbox_resumes(sandbox):
+ sandbox.pause()
+ assert not sandbox.is_running()
+
+ resumed = Sandbox.connect(sandbox.sandbox_id)
+ assert resumed.is_running()
+
+
+def test_resume_does_not_shorten_timeout_on_running_sandbox(sandbox_factory):
# Create sandbox with a 300 second timeout
sbx = sandbox_factory(timeout=300)
assert sbx.is_running()
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_create.py b/packages/python-sdk/tests/sync/sandbox_sync/test_create.py
index 4edcdf6e2..40622447f 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_create.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_create.py
@@ -1,7 +1,14 @@
+from time import sleep
+
+import httpx
import pytest
-from e2b import Sandbox
-from e2b.sandbox.sandbox_api import SandboxQuery
+from e2b import Sandbox, SandboxState
+from e2b.api.client.models import (
+ NewSandbox,
+ SandboxAutoResumeConfig,
+)
+from e2b.sandbox.sandbox_api import SandboxQuery, get_auto_resume_enabled
@pytest.mark.skip_debug()
@@ -26,3 +33,80 @@ def test_metadata(sandbox_factory):
break
else:
assert False, "Sandbox not found"
+
+
+def test_lifecycle_auto_resume_enabled_mapping():
+ assert get_auto_resume_enabled({"on_timeout": "pause", "auto_resume": True}) is True
+ assert (
+ get_auto_resume_enabled({"on_timeout": "pause", "auto_resume": False}) is False
+ )
+ assert get_auto_resume_enabled({"on_timeout": "pause"}) is False
+ assert get_auto_resume_enabled({"on_timeout": "kill", "auto_resume": False}) is None
+ assert get_auto_resume_enabled({"on_timeout": "kill"}) is None
+ assert get_auto_resume_enabled(None) is None
+
+
+def test_create_payload_serializes_auto_resume_enabled():
+ body = NewSandbox(
+ template_id="template-id",
+ auto_pause=True,
+ auto_resume=SandboxAutoResumeConfig(enabled=True),
+ )
+
+ assert body.to_dict()["autoPause"] is True
+ assert body.to_dict()["autoResume"] == {"enabled": True}
+
+
+def test_create_payload_deserializes_auto_resume_enabled():
+ body = NewSandbox.from_dict(
+ {
+ "templateID": "template-id",
+ "autoPause": False,
+ "autoResume": {"enabled": False},
+ }
+ )
+
+ assert isinstance(body.auto_resume, SandboxAutoResumeConfig)
+ assert body.auto_resume.to_dict() == {"enabled": False}
+
+
+def test_auto_pause_without_auto_resume_requires_connect(sandbox_factory):
+ sandbox = sandbox_factory(
+ timeout=3,
+ lifecycle={"on_timeout": "pause", "auto_resume": False},
+ )
+
+ sleep(5)
+
+ assert sandbox.get_info().state == SandboxState.PAUSED
+ assert not sandbox.is_running()
+
+ sandbox.connect()
+
+ assert sandbox.get_info().state == SandboxState.RUNNING
+ assert sandbox.is_running()
+
+
+def test_auto_resume_wakes_on_http_request(sandbox_factory):
+ sandbox = sandbox_factory(
+ timeout=3,
+ lifecycle={"on_timeout": "pause", "auto_resume": True},
+ )
+
+ cmd = sandbox.commands.run("python3 -m http.server 8000", background=True)
+ try:
+ sleep(5)
+
+ url = f"https://{sandbox.get_host(8000)}"
+ res = httpx.get(url, timeout=15.0)
+
+ assert res.status_code == 200
+ assert sandbox.get_info().state == SandboxState.RUNNING
+ assert sandbox.is_running()
+ finally:
+ try:
+ cmd.kill()
+ except Exception:
+ pass
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_snapshot.py b/packages/python-sdk/tests/sync/sandbox_sync/test_snapshot.py
index 491f6ffa1..c3d5c7ad0 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_snapshot.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_snapshot.py
@@ -6,7 +6,7 @@ from e2b import Sandbox
def test_snapshot(sandbox: Sandbox):
assert sandbox.is_running()
- sandbox.beta_pause()
+ sandbox.pause()
assert not sandbox.is_running()
resumed_sandbox = sandbox.connect()
diff --git a/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py b/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py
index 580124752..c2dd79028 100644
--- a/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py
+++ b/packages/python-sdk/tests/sync/template_sync/test_stacktrace.py
@@ -192,9 +192,11 @@ def test_traces_on_copy_absolute_path():
@pytest.mark.skip_debug()
def test_traces_on_copyItems_absolute_path():
_expect_to_throw_and_check_trace(
- lambda: Template()
- .from_base_image()
- .copy_items([CopyItem(src="/absolute/path", dest="/absolute/path")]),
+ lambda: (
+ Template()
+ .from_base_image()
+ .copy_items([CopyItem(src="/absolute/path", dest="/absolute/path")])
+ ),
"copy_items",
)
diff --git a/spec/openapi.yml b/spec/openapi.yml
index 94b9cf7d8..0d4df3453 100644
--- a/spec/openapi.yml
+++ b/spec/openapi.yml
@@ -283,22 +283,19 @@ components:
type: string
description: Specify host mask which will be used for all sandbox requests
- SandboxAutoResumePolicy:
- type: string
- description: Auto-resume policy for paused sandboxes. Default is off.
- default: "off"
- enum:
- - any
- - "off"
+ SandboxAutoResumeEnabled:
+ type: boolean
+ description: Auto-resume enabled flag for paused sandboxes. Default false.
+ default: false
SandboxAutoResumeConfig:
type: object
- description: Auto-resume configuration for paused sandboxes. Default is off.
+ description: Auto-resume configuration for paused sandboxes.
required:
- - policy
+ - enabled
properties:
- policy:
- $ref: "#/components/schemas/SandboxAutoResumePolicy"
+ enabled:
+ $ref: "#/components/schemas/SandboxAutoResumeEnabled"
SandboxLog:
description: Log entry with timestamp and line