Skip to content

armgit / E2B

Public Imported from GitHub
0

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

feat(sdk): add sandbox fork to JS and Python SDKs (#1554)

Mish Ushakov95e4dc2832d6
diff --git a/.changeset/sandbox-fork-python.md b/.changeset/sandbox-fork-python.md
new file mode 100644
index 000000000..bad0b82d9
--- /dev/null
+++ b/.changeset/sandbox-fork-python.md
@@ -0,0 +1,13 @@
+---
+'@e2b/python-sdk': minor
+---
+
+Add `sandbox.fork()` / `Sandbox.fork(sandbox_id)` (and the `AsyncSandbox` equivalents) for forking a running sandbox. The sandbox is checkpointed in place (briefly paused, snapshotted with its full memory state, and resumed — its ID and expiration stay untouched) and `count` new sandboxes are created from that snapshot. Each fork succeeds or fails independently: the returned list contains one entry per requested fork, either a running sandbox instance or an exception. Per-fork error codes map to the same exception classes as other API errors (e.g. 429 to `RateLimitException`).
+
+```python
+sandbox = Sandbox.create()
+
+fork1, fork2 = sandbox.fork(count=2, timeout=60)
+if isinstance(fork1, Sandbox):
+ fork1.commands.run('echo "hello from fork"')
+```
diff --git a/.changeset/sandbox-fork.md b/.changeset/sandbox-fork.md
new file mode 100644
index 000000000..745ce32c0
--- /dev/null
+++ b/.changeset/sandbox-fork.md
@@ -0,0 +1,14 @@
+---
+'e2b': minor
+---
+
+Add `sandbox.fork()` and `Sandbox.fork(sandboxId)` for forking a running sandbox. The sandbox is checkpointed in place (briefly paused, snapshotted with its full memory state, and resumed — its ID and expiration stay untouched) and `count` new sandboxes are created from that snapshot. Each fork succeeds or fails independently: the returned array contains one entry per requested fork, either a running `Sandbox` instance or an `Error` (`Promise.allSettled`-style). Per-fork error codes map to the same error classes as other API errors (e.g. 429 to `RateLimitError`).
+
+```ts
+const sandbox = await Sandbox.create()
+
+const [fork1, fork2] = await sandbox.fork({ count: 2, timeoutMs: 60_000 })
+if (fork1 instanceof Sandbox) {
+ await fork1.commands.run('echo "hello from fork"')
+}
+```
diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.ts
index a52fe09ec..6bcafa54b 100644
--- a/packages/js-sdk/src/api/index.ts
+++ b/packages/js-sdk/src/api/index.ts
@@ -23,6 +23,35 @@ export function validateApiKey(apiKey: string): void {
}
}
+/**
+ * Map an API error code and message to the matching error class — the same
+ * mapping {@link handleApiError} applies to HTTP responses, usable for error
+ * objects embedded in response bodies (e.g. per-fork results).
+ */
+export function apiErrorFromCode(
+ code: number,
+ content: unknown,
+ errorClass: new (
+ message: string,
+ stackTrace?: string
+ ) => Error = SandboxError,
+ stackTrace?: string
+): Error {
+ if (code === 401) {
+ const message = 'Unauthorized, please check your credentials.'
+ return new AuthenticationError(
+ content ? `${message} - ${content}` : message
+ )
+ }
+
+ if (code === 429) {
+ const message = 'Rate limit exceeded, please try again later'
+ return new RateLimitError(content ? `${message} - ${content}` : message)
+ }
+
+ return new errorClass(`${code}: ${content}`, stackTrace)
+}
+
export function handleApiError(
response: FetchResponse<any, any, any>,
errorClass: new (
@@ -37,29 +66,22 @@ export function handleApiError(
return
}
- if (response.response.status === 401) {
- const message = 'Unauthorized, please check your credentials.'
- const content = response.error?.message ?? response.error
-
- if (content) {
- return new AuthenticationError(`${message} - ${content}`)
- }
- return new AuthenticationError(message)
- }
-
- if (response.response.status === 429) {
- const message = 'Rate limit exceeded, please try again later'
- const content = response.error?.message ?? response.error
-
- if (content) {
- return new RateLimitError(`${message} - ${content}`)
- }
- return new RateLimitError(message)
+ const status = response.response.status
+ if (status === 401 || status === 429) {
+ return apiErrorFromCode(
+ status,
+ response.error?.message ?? response.error,
+ errorClass,
+ stackTrace
+ )
}
- const message =
- response.error?.message || response.error || response.response.statusText
- return new errorClass(`${response.response.status}: ${message}`, stackTrace)
+ return apiErrorFromCode(
+ status,
+ response.error?.message || response.error || response.response.statusText,
+ errorClass,
+ stackTrace
+ )
}
/**
diff --git a/packages/js-sdk/src/api/schema.gen.ts b/packages/js-sdk/src/api/schema.gen.ts
index 79764409e..4d863e2b3 100644
--- a/packages/js-sdk/src/api/schema.gen.ts
+++ b/packages/js-sdk/src/api/schema.gen.ts
@@ -192,6 +192,55 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/sandboxes/{sandboxID}/fork": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Fork sandbox
+ * @description Fork the sandbox: checkpoint the running sandbox in place (it is briefly paused, snapshotted with its full memory state, and resumed on its node, keeping its ID and expiration untouched) and create count new sandboxes from that snapshot. Returns one result per requested fork, each carrying either the created sandbox or the error that prevented it from starting. A non-201 status means the request failed before any fork was attempted.
+ */
+ post: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ sandboxID: components["parameters"]["sandboxID"];
+ };
+ cookie?: never;
+ };
+ requestBody?: {
+ content: {
+ "application/json": components["schemas"]["SandboxForkRequest"];
+ };
+ };
+ responses: {
+ /** @description The sandbox was snapshotted and the forks were attempted; each entry reports one fork's outcome */
+ 201: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["SandboxForkResult"][];
+ };
+ };
+ 401: components["responses"]["401"];
+ 404: components["responses"]["404"];
+ 409: components["responses"]["409"];
+ 500: components["responses"]["500"];
+ };
+ };
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/sandboxes/{sandboxID}/logs": {
parameters: {
query?: never;
@@ -2247,6 +2296,25 @@ export interface components {
[key: string]: components["schemas"]["SandboxMetric"];
};
};
+ SandboxForkRequest: {
+ /**
+ * Format: int32
+ * @description Number of forked sandboxes to create. All forks boot from the same snapshot, so the snapshot is captured once regardless of count. Each fork succeeds or fails independently; the outcome of each is reported in its entry of the response list.
+ * @default 1
+ */
+ count?: number;
+ /**
+ * Format: int32
+ * @description Time to live for the new forked sandboxes in seconds.
+ * @default 15
+ */
+ timeout?: number;
+ };
+ /** @description Result of one requested fork. Exactly one of sandbox or error is set: sandbox when the fork started successfully, error when it failed to start. */
+ SandboxForkResult: {
+ error?: components["schemas"]["Error"];
+ sandbox?: components["schemas"]["Sandbox"];
+ };
/** @description Sandbox lifecycle policy returned by sandbox info. */
SandboxLifecycle: {
/** @description Whether the sandbox can auto-resume. */
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index e20436ed2..074aa3fc9 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -56,6 +56,7 @@ export type {
SandboxOpts,
SandboxApiOpts,
SandboxConnectOpts,
+ SandboxForkOpts,
SandboxMetricsOpts,
SandboxPauseOpts,
SandboxState,
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index 56caea630..e3133c9c9 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -16,6 +16,7 @@ import { Git } from './git'
import {
SandboxOpts,
SandboxConnectOpts,
+ SandboxForkOpts,
SandboxMetricsOpts,
SandboxApi,
SandboxListOpts,
@@ -383,6 +384,56 @@ export class Sandbox extends SandboxApi {
}) as InstanceType<S>
}
+ /**
+ * Fork a running sandbox specified by sandbox ID.
+ *
+ * The sandbox is checkpointed in place (briefly paused, snapshotted with its
+ * full memory state, and resumed — its ID and expiration stay untouched) and
+ * `count` new sandboxes are created from that snapshot. All forks boot from
+ * the same snapshot, so the snapshot is captured once regardless of count.
+ *
+ * Each fork succeeds or fails independently — the returned array contains
+ * one entry per requested fork, either a running {@link Sandbox} instance or
+ * an `Error` describing why that fork failed to start
+ * (`Promise.allSettled`-style). Per-fork error codes map to the same error
+ * classes as other API errors (e.g. 429 to `RateLimitError`).
+ *
+ * @param sandboxId sandbox ID.
+ * @param opts fork options — `count`, `timeoutMs` and connection options.
+ *
+ * @returns array with one entry per requested fork — a sandbox instance or an error.
+ *
+ * @example
+ * ```ts
+ * const sandbox = await Sandbox.create()
+ *
+ * const [fork1, fork2] = await Sandbox.fork(sandbox.sandboxId, { count: 2 })
+ * if (fork1 instanceof Sandbox) {
+ * await fork1.commands.run('echo "hello from fork"')
+ * }
+ * ```
+ */
+ static async fork<S extends typeof Sandbox>(
+ this: S,
+ sandboxId: string,
+ opts?: SandboxForkOpts
+ ): Promise<Array<InstanceType<S> | Error>> {
+ const config = new ConnectionConfig(opts)
+
+ const results = await SandboxApi.forkSandbox(
+ sandboxId,
+ opts?.timeoutMs ?? this.defaultSandboxTimeoutMs,
+ opts?.count ?? 1,
+ opts
+ )
+
+ return results.map((result) =>
+ result instanceof Error
+ ? result
+ : (new this({ ...result, ...config }) as InstanceType<S>)
+ )
+ }
+
/**
* Connect to a sandbox. If the sandbox is paused, it will be automatically resumed.
* Sandbox must be either running or be paused.
@@ -413,6 +464,41 @@ export class Sandbox extends SandboxApi {
return this
}
+ /**
+ * Fork the sandbox.
+ *
+ * The sandbox is checkpointed in place (briefly paused, snapshotted with its
+ * full memory state, and resumed — its ID and expiration stay untouched) and
+ * `count` new sandboxes are created from that snapshot. All forks boot from
+ * the same snapshot, so the snapshot is captured once regardless of count.
+ *
+ * Each fork succeeds or fails independently — the returned array contains
+ * one entry per requested fork, either a running {@link Sandbox} instance or
+ * an `Error` describing why that fork failed to start
+ * (`Promise.allSettled`-style). Per-fork error codes map to the same error
+ * classes as other API errors (e.g. 429 to `RateLimitError`).
+ *
+ * @param opts fork options — `count`, `timeoutMs` and connection options.
+ *
+ * @returns array with one entry per requested fork — a sandbox instance or an error.
+ *
+ * @example
+ * ```ts
+ * const sandbox = await Sandbox.create()
+ *
+ * const [fork1, fork2] = await sandbox.fork({ count: 2 })
+ * if (fork1 instanceof Sandbox) {
+ * await fork1.commands.run('echo "hello from fork"')
+ * }
+ * ```
+ */
+ async fork(opts?: SandboxForkOpts): Promise<Array<this | Error>> {
+ const cls = this.constructor as typeof Sandbox
+ return (await cls.fork(this.sandboxId, this.resolveApiOpts(opts))) as Array<
+ this | Error
+ >
+ }
+
/**
* Get the host address for the specified sandbox port.
* You can then use this address to connect to the sandbox port from outside the sandbox via HTTP or WebSocket.
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index 2da2aafc5..8cccdb67d 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -1,4 +1,4 @@
-import { ApiClient, components, handleApiError } from '../api'
+import { ApiClient, apiErrorFromCode, components, handleApiError } from '../api'
import {
ConnectionConfig,
ConnectionOpts,
@@ -8,6 +8,8 @@ import { compareVersions } from 'compare-versions'
import { ALL_TRAFFIC } from './network'
import {
InvalidArgumentError,
+ NotFoundError,
+ SandboxError,
SandboxNotFoundError,
TemplateError,
} from '../errors'
@@ -302,6 +304,46 @@ export interface SandboxPauseOpts extends SandboxApiOpts {
keepMemory?: boolean
}
+/**
+ * Options for forking a sandbox.
+ */
+export interface SandboxForkOpts extends ConnectionOpts {
+ /**
+ * Number of forked sandboxes to create.
+ *
+ * All forks boot from the same snapshot — the snapshot is captured once
+ * regardless of count. Each fork succeeds or fails independently; the
+ * outcome of each is reported in its entry of the returned array.
+ *
+ * @default 1
+ */
+ count?: number
+
+ /**
+ * Timeout for the forked sandboxes in **milliseconds**.
+ * 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
+}
+
+/**
+ * Result of one requested fork as returned by the API — either the raw
+ * connection info of the created sandbox, or the error that prevented it
+ * from starting. Per-fork error codes map to the same error classes as other
+ * API errors (e.g. 429 to `RateLimitError`).
+ */
+type SandboxForkResponse =
+ | {
+ sandboxId: string
+ sandboxDomain?: string
+ envdVersion: string
+ envdAccessToken?: string
+ trafficAccessToken?: string
+ }
+ | Error
+
/**
* Options for creating a new Sandbox.
*/
@@ -1209,6 +1251,74 @@ export class SandboxApi {
}
}
+ protected static async forkSandbox(
+ sandboxId: string,
+ timeoutMs: number,
+ count: number,
+ opts?: SandboxApiOpts
+ ): Promise<SandboxForkResponse[]> {
+ if (count < 1) {
+ throw new InvalidArgumentError('count must be at least 1')
+ }
+
+ const config = new ConnectionConfig(opts)
+ const client = new ApiClient(config)
+
+ const res = await client.api.POST('/sandboxes/{sandboxID}/fork', {
+ params: {
+ path: {
+ sandboxID: sandboxId,
+ },
+ },
+ body: {
+ timeout: timeoutToSeconds(timeoutMs),
+ count,
+ },
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ })
+
+ // check the status, not the parsed error body — openapi-fetch leaves
+ // `error` unset for non-2xx responses with an empty body
+ if (res.response.status === 404) {
+ throw new SandboxNotFoundError(
+ res.error?.message ?? `Sandbox ${sandboxId} not found`
+ )
+ }
+
+ const err = handleApiError(res)
+ if (err) {
+ throw err
+ }
+
+ return (res.data ?? []).map(
+ (result: components['schemas']['SandboxForkResult']) => {
+ if (result.error || !result.sandbox) {
+ if (!result.error) {
+ return new SandboxError('Failed to start forked sandbox')
+ }
+ // 404 is call-site-specific in the SDK, so apiErrorFromCode leaves
+ // it to the caller. A per-fork 404 refers to a resource needed to
+ // start that fork (e.g. the snapshot) — not the source sandbox,
+ // which would have failed the whole request — so stay generic.
+ if (result.error.code === 404) {
+ return new NotFoundError(
+ `${result.error.code}: ${result.error.message}`
+ )
+ }
+ return apiErrorFromCode(result.error.code, result.error.message)
+ }
+
+ return {
+ sandboxId: result.sandbox.sandboxID,
+ sandboxDomain: result.sandbox.domain || undefined,
+ envdVersion: result.sandbox.envdVersion,
+ envdAccessToken: result.sandbox.envdAccessToken,
+ trafficAccessToken: result.sandbox.trafficAccessToken || undefined,
+ }
+ }
+ )
+ }
+
protected static async connectSandbox(
sandboxId: string,
opts?: SandboxConnectOpts
diff --git a/packages/js-sdk/tests/sandbox/fork.test.ts b/packages/js-sdk/tests/sandbox/fork.test.ts
new file mode 100644
index 000000000..da3d30b9a
--- /dev/null
+++ b/packages/js-sdk/tests/sandbox/fork.test.ts
@@ -0,0 +1,94 @@
+import { assert, expect, test } from 'vitest'
+
+import { sandboxTest, isDebug, TEST_API_KEY } from '../setup.js'
+import { Sandbox } from '../../src'
+import { InvalidArgumentError, SandboxNotFoundError } from '../../src/errors'
+
+sandboxTest.skipIf(isDebug)('fork a sandbox', async ({ sandbox }) => {
+ await sandbox.files.write('/home/user/state.txt', 'state before fork')
+
+ const forks = await sandbox.fork()
+ assert.equal(forks.length, 1)
+
+ const fork = forks[0]
+ assert.instanceOf(fork, Sandbox)
+ if (!(fork instanceof Sandbox)) {
+ return
+ }
+
+ try {
+ assert.notEqual(fork.sandboxId, sandbox.sandboxId)
+
+ // The original sandbox keeps running
+ assert.isTrue(await sandbox.isRunning())
+ assert.isTrue(await fork.isRunning())
+
+ // The fork inherits the filesystem state
+ const content = await fork.files.read('/home/user/state.txt')
+ assert.equal(content, 'state before fork')
+
+ // The fork is independent of the original
+ await fork.files.write('/home/user/state.txt', 'modified in fork')
+ const originalContent = await sandbox.files.read('/home/user/state.txt')
+ assert.equal(originalContent, 'state before fork')
+ } finally {
+ await fork.kill()
+ }
+})
+
+sandboxTest.skipIf(isDebug)(
+ 'fork a sandbox multiple times',
+ async ({ sandbox }) => {
+ const forks = await sandbox.fork({ count: 2, timeoutMs: 60_000 })
+ assert.equal(forks.length, 2)
+
+ const forkedSandboxes = forks.filter(
+ (fork): fork is Sandbox => fork instanceof Sandbox
+ )
+
+ try {
+ assert.equal(forkedSandboxes.length, 2)
+
+ const ids = new Set(forkedSandboxes.map((s) => s.sandboxId))
+ assert.equal(ids.size, 2)
+ assert.isFalse(ids.has(sandbox.sandboxId))
+
+ for (const fork of forkedSandboxes) {
+ assert.isTrue(await fork.isRunning())
+ }
+ } finally {
+ await Promise.all(forkedSandboxes.map((s) => s.kill()))
+ }
+ }
+)
+
+sandboxTest.skipIf(isDebug)(
+ 'fork a sandbox by ID with the static method',
+ async ({ sandbox }) => {
+ const forks = await Sandbox.fork(sandbox.sandboxId)
+ assert.equal(forks.length, 1)
+
+ const fork = forks[0]
+ assert.instanceOf(fork, Sandbox)
+ if (fork instanceof Sandbox) {
+ try {
+ assert.isTrue(await fork.isRunning())
+ } finally {
+ await fork.kill()
+ }
+ }
+ }
+)
+
+test.skipIf(isDebug)('fork a killed sandbox fails', async () => {
+ const sandbox = await Sandbox.create()
+ await sandbox.kill()
+
+ await expect(sandbox.fork()).rejects.toThrowError(SandboxNotFoundError)
+})
+
+test('fork with count lower than 1 fails', async () => {
+ await expect(
+ Sandbox.fork('sbx-test', { count: 0, apiKey: TEST_API_KEY })
+ ).rejects.toThrowError(InvalidArgumentError)
+})
diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.py
index 2a1e42d20..c0867c41e 100644
--- a/packages/python-sdk/e2b/api/__init__.py
+++ b/packages/python-sdk/e2b/api/__init__.py
@@ -80,6 +80,32 @@ class SandboxCreateResponse:
traffic_access_token: Optional[str]
+def api_exception_from_code(
+ status_code: int,
+ message: Optional[str] = None,
+ default_exception_class: type[Exception] = SandboxException,
+ stack_trace: Optional[TracebackType] = None,
+) -> Exception:
+ """Map an API error code and message to the matching exception class — the
+ same mapping :func:`handle_api_exception` applies to HTTP responses, usable
+ for error objects embedded in response bodies (e.g. per-fork results)."""
+ if status_code == 401:
+ text = f"{status_code}: Unauthorized, please check your credentials."
+ if message:
+ text += f" - {message}"
+ return AuthenticationException(text)
+
+ if status_code == 429:
+ text = f"{status_code}: Rate limit exceeded, please try again later."
+ if message:
+ text += f" - {message}"
+ return RateLimitException(text)
+
+ return default_exception_class(f"{status_code}: {message}").with_traceback(
+ stack_trace
+ )
+
+
def handle_api_exception(
e: "SupportsApiErrorResponse",
default_exception_class: type[Exception] = SandboxException,
@@ -90,24 +116,14 @@ def handle_api_exception(
except json.JSONDecodeError:
body = {}
- if e.status_code == 401:
- message = f"{e.status_code}: Unauthorized, please check your credentials."
- if body.get("message"):
- message += f" - {body['message']}"
- return AuthenticationException(message)
-
- if e.status_code == 429:
- message = f"{e.status_code}: Rate limit exceeded, please try again later."
- if body.get("message"):
- message += f" - {body['message']}"
- return RateLimitException(message)
-
- if "message" in body:
- return default_exception_class(
- f"{e.status_code}: {body['message']}"
- ).with_traceback(stack_trace)
- return default_exception_class(f"{e.status_code}: {e.content}").with_traceback(
- stack_trace
+ message = body["message"] if "message" in body else None
+ if message is None and e.status_code not in (401, 429):
+ return default_exception_class(f"{e.status_code}: {e.content}").with_traceback(
+ stack_trace
+ )
+
+ return api_exception_from_code(
+ e.status_code, message, default_exception_class, stack_trace
)
diff --git a/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_fork.py b/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_fork.py
new file mode 100644
index 000000000..4387dc28d
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/api/sandboxes/post_sandboxes_sandbox_id_fork.py
@@ -0,0 +1,218 @@
+from http import HTTPStatus
+from typing import Any, Optional, Union
+
+import httpx
+
+from ... import errors
+from ...client import AuthenticatedClient, Client
+from ...models.error import Error
+from ...models.sandbox_fork_request import SandboxForkRequest
+from ...models.sandbox_fork_result import SandboxForkResult
+from ...types import Response
+
+
+def _get_kwargs(
+ sandbox_id: str,
+ *,
+ body: SandboxForkRequest,
+) -> dict[str, Any]:
+ headers: dict[str, Any] = {}
+
+ _kwargs: dict[str, Any] = {
+ "method": "post",
+ "url": f"/sandboxes/{sandbox_id}/fork",
+ }
+
+ _kwargs["json"] = body.to_dict()
+
+ headers["Content-Type"] = "application/json"
+
+ _kwargs["headers"] = headers
+ return _kwargs
+
+
+def _parse_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Optional[Union[Error, list["SandboxForkResult"]]]:
+ if response.status_code == 201:
+ response_201 = []
+ _response_201 = response.json()
+ for response_201_item_data in _response_201:
+ response_201_item = SandboxForkResult.from_dict(response_201_item_data)
+
+ response_201.append(response_201_item)
+
+ return response_201
+ if response.status_code == 401:
+ response_401 = Error.from_dict(response.json())
+
+ return response_401
+ if response.status_code == 404:
+ response_404 = Error.from_dict(response.json())
+
+ return response_404
+ if response.status_code == 409:
+ response_409 = Error.from_dict(response.json())
+
+ return response_409
+ if response.status_code == 500:
+ response_500 = Error.from_dict(response.json())
+
+ return response_500
+ if client.raise_on_unexpected_status:
+ raise errors.UnexpectedStatus(response.status_code, response.content)
+ else:
+ return None
+
+
+def _build_response(
+ *, client: Union[AuthenticatedClient, Client], response: httpx.Response
+) -> Response[Union[Error, list["SandboxForkResult"]]]:
+ return Response(
+ status_code=HTTPStatus(response.status_code),
+ content=response.content,
+ headers=response.headers,
+ parsed=_parse_response(client=client, response=response),
+ )
+
+
+def sync_detailed(
+ sandbox_id: str,
+ *,
+ client: AuthenticatedClient,
+ body: SandboxForkRequest,
+) -> Response[Union[Error, list["SandboxForkResult"]]]:
+ """Fork sandbox
+
+ Fork the sandbox: checkpoint the running sandbox in place (it is briefly paused, snapshotted with
+ its full memory state, and resumed on its node, keeping its ID and expiration untouched) and create
+ count new sandboxes from that snapshot. Returns one result per requested fork, each carrying either
+ the created sandbox or the error that prevented it from starting. A non-201 status means the request
+ failed before any fork was attempted.
+
+ Args:
+ sandbox_id (str):
+ body (SandboxForkRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Error, list['SandboxForkResult']]]
+ """
+
+ kwargs = _get_kwargs(
+ sandbox_id=sandbox_id,
+ body=body,
+ )
+
+ response = client.get_httpx_client().request(
+ **kwargs,
+ )
+
+ return _build_response(client=client, response=response)
+
+
+def sync(
+ sandbox_id: str,
+ *,
+ client: AuthenticatedClient,
+ body: SandboxForkRequest,
+) -> Optional[Union[Error, list["SandboxForkResult"]]]:
+ """Fork sandbox
+
+ Fork the sandbox: checkpoint the running sandbox in place (it is briefly paused, snapshotted with
+ its full memory state, and resumed on its node, keeping its ID and expiration untouched) and create
+ count new sandboxes from that snapshot. Returns one result per requested fork, each carrying either
+ the created sandbox or the error that prevented it from starting. A non-201 status means the request
+ failed before any fork was attempted.
+
+ Args:
+ sandbox_id (str):
+ body (SandboxForkRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Error, list['SandboxForkResult']]
+ """
+
+ return sync_detailed(
+ sandbox_id=sandbox_id,
+ client=client,
+ body=body,
+ ).parsed
+
+
+async def asyncio_detailed(
+ sandbox_id: str,
+ *,
+ client: AuthenticatedClient,
+ body: SandboxForkRequest,
+) -> Response[Union[Error, list["SandboxForkResult"]]]:
+ """Fork sandbox
+
+ Fork the sandbox: checkpoint the running sandbox in place (it is briefly paused, snapshotted with
+ its full memory state, and resumed on its node, keeping its ID and expiration untouched) and create
+ count new sandboxes from that snapshot. Returns one result per requested fork, each carrying either
+ the created sandbox or the error that prevented it from starting. A non-201 status means the request
+ failed before any fork was attempted.
+
+ Args:
+ sandbox_id (str):
+ body (SandboxForkRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Response[Union[Error, list['SandboxForkResult']]]
+ """
+
+ kwargs = _get_kwargs(
+ sandbox_id=sandbox_id,
+ body=body,
+ )
+
+ response = await client.get_async_httpx_client().request(**kwargs)
+
+ return _build_response(client=client, response=response)
+
+
+async def asyncio(
+ sandbox_id: str,
+ *,
+ client: AuthenticatedClient,
+ body: SandboxForkRequest,
+) -> Optional[Union[Error, list["SandboxForkResult"]]]:
+ """Fork sandbox
+
+ Fork the sandbox: checkpoint the running sandbox in place (it is briefly paused, snapshotted with
+ its full memory state, and resumed on its node, keeping its ID and expiration untouched) and create
+ count new sandboxes from that snapshot. Returns one result per requested fork, each carrying either
+ the created sandbox or the error that prevented it from starting. A non-201 status means the request
+ failed before any fork was attempted.
+
+ Args:
+ sandbox_id (str):
+ body (SandboxForkRequest):
+
+ Raises:
+ errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
+ httpx.TimeoutException: If the request takes longer than Client.timeout.
+
+ Returns:
+ Union[Error, list['SandboxForkResult']]
+ """
+
+ return (
+ await asyncio_detailed(
+ sandbox_id=sandbox_id,
+ client=client,
+ body=body,
+ )
+ ).parsed
diff --git a/packages/python-sdk/e2b/api/client/models/__init__.py b/packages/python-sdk/e2b/api/client/models/__init__.py
index 1f18254d1..0a9e23b48 100644
--- a/packages/python-sdk/e2b/api/client/models/__init__.py
+++ b/packages/python-sdk/e2b/api/client/models/__init__.py
@@ -46,6 +46,8 @@ from .resumed_sandbox import ResumedSandbox
from .sandbox import Sandbox
from .sandbox_auto_resume_config import SandboxAutoResumeConfig
from .sandbox_detail import SandboxDetail
+from .sandbox_fork_request import SandboxForkRequest
+from .sandbox_fork_result import SandboxForkResult
from .sandbox_lifecycle import SandboxLifecycle
from .sandbox_log import SandboxLog
from .sandbox_log_entry import SandboxLogEntry
@@ -137,6 +139,8 @@ __all__ = (
"SandboxAutoResumeConfig",
"SandboxDetail",
"SandboxesWithMetrics",
+ "SandboxForkRequest",
+ "SandboxForkResult",
"SandboxLifecycle",
"SandboxLog",
"SandboxLogEntry",
diff --git a/packages/python-sdk/e2b/api/client/models/sandbox_fork_request.py b/packages/python-sdk/e2b/api/client/models/sandbox_fork_request.py
new file mode 100644
index 000000000..3af8d6781
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/models/sandbox_fork_request.py
@@ -0,0 +1,70 @@
+from collections.abc import Mapping
+from typing import Any, TypeVar, Union
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+T = TypeVar("T", bound="SandboxForkRequest")
+
+
+@_attrs_define
+class SandboxForkRequest:
+ """
+ Attributes:
+ count (Union[Unset, int]): Number of forked sandboxes to create. All forks boot from the same snapshot, so the
+ snapshot is captured once regardless of count. Each fork succeeds or fails independently; the outcome of each is
+ reported in its entry of the response list. Default: 1.
+ timeout (Union[Unset, int]): Time to live for the new forked sandboxes in seconds. Default: 15.
+ """
+
+ count: Union[Unset, int] = 1
+ timeout: Union[Unset, int] = 15
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ count = self.count
+
+ timeout = self.timeout
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if count is not UNSET:
+ field_dict["count"] = count
+ if timeout is not UNSET:
+ field_dict["timeout"] = timeout
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ d = dict(src_dict)
+ count = d.pop("count", UNSET)
+
+ timeout = d.pop("timeout", UNSET)
+
+ sandbox_fork_request = cls(
+ count=count,
+ timeout=timeout,
+ )
+
+ sandbox_fork_request.additional_properties = d
+ return sandbox_fork_request
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/packages/python-sdk/e2b/api/client/models/sandbox_fork_result.py b/packages/python-sdk/e2b/api/client/models/sandbox_fork_result.py
new file mode 100644
index 000000000..532f38c38
--- /dev/null
+++ b/packages/python-sdk/e2b/api/client/models/sandbox_fork_result.py
@@ -0,0 +1,92 @@
+from collections.abc import Mapping
+from typing import TYPE_CHECKING, Any, TypeVar, Union
+
+from attrs import define as _attrs_define
+from attrs import field as _attrs_field
+
+from ..types import UNSET, Unset
+
+if TYPE_CHECKING:
+ from ..models.error import Error
+ from ..models.sandbox import Sandbox
+
+
+T = TypeVar("T", bound="SandboxForkResult")
+
+
+@_attrs_define
+class SandboxForkResult:
+ """Result of one requested fork. Exactly one of sandbox or error is set: sandbox when the fork started successfully,
+ error when it failed to start.
+
+ Attributes:
+ error (Union[Unset, Error]):
+ sandbox (Union[Unset, Sandbox]):
+ """
+
+ error: Union[Unset, "Error"] = UNSET
+ sandbox: Union[Unset, "Sandbox"] = UNSET
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ error: Union[Unset, dict[str, Any]] = UNSET
+ if not isinstance(self.error, Unset):
+ error = self.error.to_dict()
+
+ sandbox: Union[Unset, dict[str, Any]] = UNSET
+ if not isinstance(self.sandbox, Unset):
+ sandbox = self.sandbox.to_dict()
+
+ field_dict: dict[str, Any] = {}
+ field_dict.update(self.additional_properties)
+ field_dict.update({})
+ if error is not UNSET:
+ field_dict["error"] = error
+ if sandbox is not UNSET:
+ field_dict["sandbox"] = sandbox
+
+ return field_dict
+
+ @classmethod
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
+ from ..models.error import Error
+ from ..models.sandbox import Sandbox
+
+ d = dict(src_dict)
+ _error = d.pop("error", UNSET)
+ error: Union[Unset, Error]
+ if isinstance(_error, Unset):
+ error = UNSET
+ else:
+ error = Error.from_dict(_error)
+
+ _sandbox = d.pop("sandbox", UNSET)
+ sandbox: Union[Unset, Sandbox]
+ if isinstance(_sandbox, Unset):
+ sandbox = UNSET
+ else:
+ sandbox = Sandbox.from_dict(_sandbox)
+
+ sandbox_fork_result = cls(
+ error=error,
+ sandbox=sandbox,
+ )
+
+ sandbox_fork_result.additional_properties = d
+ return sandbox_fork_result
+
+ @property
+ def additional_keys(self) -> list[str]:
+ return list(self.additional_properties.keys())
+
+ def __getitem__(self, key: str) -> Any:
+ return self.additional_properties[key]
+
+ def __setitem__(self, key: str, value: Any) -> None:
+ self.additional_properties[key] = value
+
+ def __delitem__(self, key: str) -> None:
+ del self.additional_properties[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.additional_properties
diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.py
index 50fbdaa0f..3cbc490f1 100644
--- a/packages/python-sdk/e2b/sandbox_async/main.py
+++ b/packages/python-sdk/e2b/sandbox_async/main.py
@@ -347,6 +347,123 @@ class AsyncSandbox(SandboxApi):
return self
+ @overload
+ async def fork(
+ self,
+ timeout: Optional[int] = None,
+ count: Optional[int] = None,
+ **opts: Unpack[ApiParams],
+ ) -> List[Union[Self, Exception]]:
+ """
+ Fork the sandbox.
+
+ The sandbox is checkpointed in place (briefly paused, snapshotted with
+ its full memory state, and resumed — its ID and expiration stay
+ untouched) and `count` new sandboxes are created from that snapshot.
+ All forks boot from the same snapshot, so the snapshot is captured once
+ regardless of count.
+
+ Each fork succeeds or fails independently — the returned list contains
+ one entry per requested fork, either a running `AsyncSandbox` instance
+ or an exception describing why that fork failed to start. Per-fork
+ error codes map to the same exception classes as other API errors
+ (e.g. 429 to `RateLimitException`).
+
+ :param timeout: Timeout for the forked sandboxes in **seconds**, defaults to 300 seconds
+ :param count: Number of forked sandboxes to create, defaults to 1
+
+ :return: List with one entry per requested fork — a sandbox instance or an exception
+
+ @example
+ ```python
+ sandbox = await AsyncSandbox.create()
+
+ fork1, fork2 = await sandbox.fork(count=2)
+ ```
+ """
+ ...
+
+ @overload
+ @staticmethod
+ async def fork(
+ sandbox_id: str,
+ timeout: Optional[int] = None,
+ count: Optional[int] = None,
+ logger: Optional[logging.Logger] = None,
+ **opts: Unpack[ApiParams],
+ ) -> List[Union["AsyncSandbox", Exception]]:
+ """
+ Fork a running sandbox specified by sandbox ID.
+
+ The sandbox is checkpointed in place (briefly paused, snapshotted with
+ its full memory state, and resumed — its ID and expiration stay
+ untouched) and `count` new sandboxes are created from that snapshot.
+ All forks boot from the same snapshot, so the snapshot is captured once
+ regardless of count.
+
+ Each fork succeeds or fails independently — the returned list contains
+ one entry per requested fork, either a running `AsyncSandbox` instance
+ or an exception describing why that fork failed to start. Per-fork
+ error codes map to the same exception classes as other API errors
+ (e.g. 429 to `RateLimitException`).
+
+ :param sandbox_id: Sandbox ID
+ :param timeout: Timeout for the forked sandboxes in **seconds**, defaults to 300 seconds
+ :param count: Number of forked sandboxes to create, defaults to 1
+ :param logger: Logger used for request and response logging for the forked sandboxes. Accepts any standard library `logging.Logger`. When omitted, no request/response logging is emitted.
+
+ :return: List with one entry per requested fork — a sandbox instance or an exception
+
+ @example
+ ```python
+ sandbox = await AsyncSandbox.create()
+
+ fork1, fork2 = await AsyncSandbox.fork(sandbox.sandbox_id, count=2)
+ ```
+ """
+ ...
+
+ @class_method_variant("_cls_fork_sandbox")
+ async def fork(
+ self,
+ timeout: Optional[int] = None,
+ count: Optional[int] = None,
+ **opts: Unpack[ApiParams],
+ ) -> List[Union[Self, Exception]]:
+ """
+ Fork the sandbox.
+
+ The sandbox is checkpointed in place (briefly paused, snapshotted with
+ its full memory state, and resumed — its ID and expiration stay
+ untouched) and `count` new sandboxes are created from that snapshot.
+ All forks boot from the same snapshot, so the snapshot is captured once
+ regardless of count.
+
+ Each fork succeeds or fails independently — the returned list contains
+ one entry per requested fork, either a running `AsyncSandbox` instance
+ or an exception describing why that fork failed to start. Per-fork
+ error codes map to the same exception classes as other API errors
+ (e.g. 429 to `RateLimitException`).
+
+ :param timeout: Timeout for the forked sandboxes in **seconds**, defaults to 300 seconds
+ :param count: Number of forked sandboxes to create, defaults to 1
+
+ :return: List with one entry per requested fork — a sandbox instance or an exception
+
+ @example
+ ```python
+ sandbox = await AsyncSandbox.create()
+
+ fork1, fork2 = await sandbox.fork(count=2)
+ ```
+ """
+ return await type(self)._cls_fork_sandbox(
+ self.sandbox_id,
+ timeout=timeout,
+ count=count,
+ **self.connection_config.get_api_params(**opts),
+ )
+
async def __aenter__(self):
return self
@@ -925,6 +1042,55 @@ class AsyncSandbox(SandboxApi):
connection_config=connection_config,
)
+ @classmethod
+ async def _cls_fork_sandbox(
+ cls,
+ sandbox_id: str,
+ timeout: Optional[int] = None,
+ count: Optional[int] = None,
+ logger: Optional[logging.Logger] = None,
+ **opts: Unpack[ApiParams],
+ ) -> List[Union[Self, Exception]]:
+ responses = await SandboxApi._cls_fork(
+ sandbox_id=sandbox_id,
+ timeout=timeout,
+ count=count,
+ logger=logger,
+ **opts,
+ )
+
+ sandboxes: List[Union[Self, Exception]] = []
+ for response in responses:
+ if isinstance(response, Exception):
+ sandboxes.append(response)
+ continue
+
+ sandbox_headers = {
+ "E2b-Sandbox-Id": response.sandbox_id,
+ "E2b-Sandbox-Port": str(ConnectionConfig.envd_port),
+ }
+ if response.envd_access_token is not None:
+ sandbox_headers["X-Access-Token"] = response.envd_access_token
+
+ connection_config = ConnectionConfig(
+ extra_sandbox_headers=sandbox_headers,
+ logger=logger,
+ **opts,
+ )
+
+ sandboxes.append(
+ cls(
+ sandbox_id=response.sandbox_id,
+ sandbox_domain=response.sandbox_domain,
+ envd_version=Version(response.envd_version),
+ envd_access_token=response.envd_access_token,
+ traffic_access_token=response.traffic_access_token,
+ connection_config=connection_config,
+ )
+ )
+
+ return sandboxes
+
@classmethod
async def _create(
cls,
diff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
index ae55ca7ed..31ffe2e15 100644
--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
@@ -1,17 +1,22 @@
import datetime
import logging
-from typing import Any, Dict, List, Optional, cast
+from typing import Any, Dict, List, Optional, Union, cast
from packaging.version import Version
from typing_extensions import Unpack
-from e2b.api import SandboxCreateResponse, handle_api_exception
+from e2b.api import (
+ SandboxCreateResponse,
+ api_exception_from_code,
+ handle_api_exception,
+)
from e2b.api.client.api.sandboxes import (
delete_sandboxes_sandbox_id,
get_sandboxes_sandbox_id,
get_sandboxes_sandbox_id_metrics,
post_sandboxes,
post_sandboxes_sandbox_id_connect,
+ post_sandboxes_sandbox_id_fork,
post_sandboxes_sandbox_id_pause,
post_sandboxes_sandbox_id_snapshots,
post_sandboxes_sandbox_id_timeout,
@@ -25,15 +30,17 @@ from e2b.api.client.models import (
PostSandboxesSandboxIDSnapshotsBody,
PostSandboxesSandboxIDTimeoutBody,
SandboxAutoResumeConfig,
+ SandboxForkRequest,
SandboxNetworkConfig,
SandboxPauseRequest,
SandboxVolumeMount as SandboxVolumeMountAPI,
)
-from e2b.api.client.types import UNSET
+from e2b.api.client.types import UNSET, Unset
from e2b.api.client_async import get_api_client
from e2b.connection_config import ApiParams, ConnectionConfig
from e2b.exceptions import (
InvalidArgumentException,
+ NotFoundException,
SandboxException,
SandboxNotFoundException,
TemplateException,
@@ -450,6 +457,93 @@ class SandboxApi(SandboxBase):
return True
+ @classmethod
+ async def _cls_fork(
+ cls,
+ sandbox_id: str,
+ timeout: Optional[int] = None,
+ count: Optional[int] = None,
+ logger: Optional[logging.Logger] = None,
+ **opts: Unpack[ApiParams],
+ ) -> List[Union[SandboxCreateResponse, Exception]]:
+ timeout = (
+ timeout if timeout is not None else SandboxBase.default_sandbox_timeout
+ )
+ count = count if count is not None else 1
+
+ if count < 1:
+ raise InvalidArgumentException("count must be at least 1")
+
+ config = ConnectionConfig(logger=logger, **opts)
+
+ api_client = get_api_client(config)
+ res = await post_sandboxes_sandbox_id_fork.asyncio_detailed(
+ sandbox_id,
+ client=api_client,
+ body=SandboxForkRequest(timeout=timeout, count=count),
+ )
+
+ if res.status_code == 404:
+ message = (
+ res.parsed.message
+ if isinstance(res.parsed, Error)
+ else f"Sandbox {sandbox_id} not found"
+ )
+ raise SandboxNotFoundException(message)
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res)
+
+ if isinstance(res.parsed, Error):
+ raise SandboxException(f"{res.parsed.message}: Request failed")
+
+ if res.parsed is None:
+ raise Exception("Body of the request is None")
+
+ results: List[Union[SandboxCreateResponse, Exception]] = []
+ for result in res.parsed:
+ sandbox = None if isinstance(result.sandbox, Unset) else result.sandbox
+ error = None if isinstance(result.error, Unset) else result.error
+
+ if error is not None or sandbox is None:
+ if error is None:
+ exception = SandboxException("Failed to start forked sandbox")
+ elif error.code == 404:
+ # 404 is call-site-specific in the SDK, so
+ # api_exception_from_code leaves it to the caller. A
+ # per-fork 404 refers to a resource needed to start that
+ # fork (e.g. the snapshot) — not the source sandbox, which
+ # would have failed the whole request — so stay generic.
+ exception = NotFoundException(f"{error.code}: {error.message}")
+ else:
+ exception = api_exception_from_code(error.code, error.message)
+ results.append(exception)
+ continue
+
+ domain = sandbox.domain if isinstance(sandbox.domain, str) else None
+ envd_token = (
+ sandbox.envd_access_token
+ if isinstance(sandbox.envd_access_token, str)
+ else None
+ )
+ traffic_token = (
+ sandbox.traffic_access_token
+ if isinstance(sandbox.traffic_access_token, str)
+ else None
+ )
+
+ results.append(
+ SandboxCreateResponse(
+ sandbox_id=sandbox.sandbox_id,
+ sandbox_domain=domain,
+ envd_version=sandbox.envd_version,
+ envd_access_token=envd_token,
+ traffic_access_token=traffic_token,
+ )
+ )
+
+ return results
+
@classmethod
async def _cls_connect(
cls,
diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.py
index 005e2d30a..4141eeda8 100644
--- a/packages/python-sdk/e2b/sandbox_sync/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/main.py
@@ -334,6 +334,123 @@ class Sandbox(SandboxApi):
return self
+ @overload
+ def fork(
+ self,
+ timeout: Optional[int] = None,
+ count: Optional[int] = None,
+ **opts: Unpack[ApiParams],
+ ) -> List[Union[Self, Exception]]:
+ """
+ Fork the sandbox.
+
+ The sandbox is checkpointed in place (briefly paused, snapshotted with
+ its full memory state, and resumed — its ID and expiration stay
+ untouched) and `count` new sandboxes are created from that snapshot.
+ All forks boot from the same snapshot, so the snapshot is captured once
+ regardless of count.
+
+ Each fork succeeds or fails independently — the returned list contains
+ one entry per requested fork, either a running `Sandbox` instance
+ or an exception describing why that fork failed to start. Per-fork
+ error codes map to the same exception classes as other API errors
+ (e.g. 429 to `RateLimitException`).
+
+ :param timeout: Timeout for the forked sandboxes in **seconds**, defaults to 300 seconds
+ :param count: Number of forked sandboxes to create, defaults to 1
+
+ :return: List with one entry per requested fork — a sandbox instance or an exception
+
+ @example
+ ```python
+ sandbox = Sandbox.create()
+
+ fork1, fork2 = sandbox.fork(count=2)
+ ```
+ """
+ ...
+
+ @overload
+ @staticmethod
+ def fork(
+ sandbox_id: str,
+ timeout: Optional[int] = None,
+ count: Optional[int] = None,
+ logger: Optional[logging.Logger] = None,
+ **opts: Unpack[ApiParams],
+ ) -> List[Union["Sandbox", Exception]]:
+ """
+ Fork a running sandbox specified by sandbox ID.
+
+ The sandbox is checkpointed in place (briefly paused, snapshotted with
+ its full memory state, and resumed — its ID and expiration stay
+ untouched) and `count` new sandboxes are created from that snapshot.
+ All forks boot from the same snapshot, so the snapshot is captured once
+ regardless of count.
+
+ Each fork succeeds or fails independently — the returned list contains
+ one entry per requested fork, either a running `Sandbox` instance
+ or an exception describing why that fork failed to start. Per-fork
+ error codes map to the same exception classes as other API errors
+ (e.g. 429 to `RateLimitException`).
+
+ :param sandbox_id: Sandbox ID
+ :param timeout: Timeout for the forked sandboxes in **seconds**, defaults to 300 seconds
+ :param count: Number of forked sandboxes to create, defaults to 1
+ :param logger: Logger used for request and response logging for the forked sandboxes. Accepts any standard library `logging.Logger`. When omitted, no request/response logging is emitted.
+
+ :return: List with one entry per requested fork — a sandbox instance or an exception
+
+ @example
+ ```python
+ sandbox = Sandbox.create()
+
+ fork1, fork2 = Sandbox.fork(sandbox.sandbox_id, count=2)
+ ```
+ """
+ ...
+
+ @class_method_variant("_cls_fork_sandbox")
+ def fork(
+ self,
+ timeout: Optional[int] = None,
+ count: Optional[int] = None,
+ **opts: Unpack[ApiParams],
+ ) -> List[Union[Self, Exception]]:
+ """
+ Fork the sandbox.
+
+ The sandbox is checkpointed in place (briefly paused, snapshotted with
+ its full memory state, and resumed — its ID and expiration stay
+ untouched) and `count` new sandboxes are created from that snapshot.
+ All forks boot from the same snapshot, so the snapshot is captured once
+ regardless of count.
+
+ Each fork succeeds or fails independently — the returned list contains
+ one entry per requested fork, either a running `Sandbox` instance
+ or an exception describing why that fork failed to start. Per-fork
+ error codes map to the same exception classes as other API errors
+ (e.g. 429 to `RateLimitException`).
+
+ :param timeout: Timeout for the forked sandboxes in **seconds**, defaults to 300 seconds
+ :param count: Number of forked sandboxes to create, defaults to 1
+
+ :return: List with one entry per requested fork — a sandbox instance or an exception
+
+ @example
+ ```python
+ sandbox = Sandbox.create()
+
+ fork1, fork2 = sandbox.fork(count=2)
+ ```
+ """
+ return type(self)._cls_fork_sandbox(
+ self.sandbox_id,
+ timeout=timeout,
+ count=count,
+ **self.connection_config.get_api_params(**opts),
+ )
+
def __enter__(self):
return self
@@ -913,6 +1030,55 @@ class Sandbox(SandboxApi):
connection_config=connection_config,
)
+ @classmethod
+ def _cls_fork_sandbox(
+ cls,
+ sandbox_id: str,
+ timeout: Optional[int] = None,
+ count: Optional[int] = None,
+ logger: Optional[logging.Logger] = None,
+ **opts: Unpack[ApiParams],
+ ) -> List[Union[Self, Exception]]:
+ responses = SandboxApi._cls_fork(
+ sandbox_id=sandbox_id,
+ timeout=timeout,
+ count=count,
+ logger=logger,
+ **opts,
+ )
+
+ sandboxes: List[Union[Self, Exception]] = []
+ for response in responses:
+ if isinstance(response, Exception):
+ sandboxes.append(response)
+ continue
+
+ sandbox_headers = {
+ "E2b-Sandbox-Id": response.sandbox_id,
+ "E2b-Sandbox-Port": str(ConnectionConfig.envd_port),
+ }
+ if response.envd_access_token is not None:
+ sandbox_headers["X-Access-Token"] = response.envd_access_token
+
+ connection_config = ConnectionConfig(
+ extra_sandbox_headers=sandbox_headers,
+ logger=logger,
+ **opts,
+ )
+
+ sandboxes.append(
+ cls(
+ sandbox_id=response.sandbox_id,
+ sandbox_domain=response.sandbox_domain,
+ envd_version=Version(response.envd_version),
+ envd_access_token=response.envd_access_token,
+ traffic_access_token=response.traffic_access_token,
+ connection_config=connection_config,
+ )
+ )
+
+ return sandboxes
+
@classmethod
def _create(
cls,
diff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
index 6ddcd075f..c66b04183 100644
--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
@@ -1,17 +1,22 @@
import datetime
import logging
-from typing import Any, Dict, List, Optional, cast
+from typing import Any, Dict, List, Optional, Union, cast
from packaging.version import Version
from typing_extensions import Unpack
-from e2b.api import SandboxCreateResponse, handle_api_exception
+from e2b.api import (
+ SandboxCreateResponse,
+ api_exception_from_code,
+ handle_api_exception,
+)
from e2b.api.client.api.sandboxes import (
delete_sandboxes_sandbox_id,
get_sandboxes_sandbox_id,
get_sandboxes_sandbox_id_metrics,
post_sandboxes,
post_sandboxes_sandbox_id_connect,
+ post_sandboxes_sandbox_id_fork,
post_sandboxes_sandbox_id_pause,
post_sandboxes_sandbox_id_snapshots,
post_sandboxes_sandbox_id_timeout,
@@ -25,14 +30,16 @@ from e2b.api.client.models import (
PostSandboxesSandboxIDSnapshotsBody,
PostSandboxesSandboxIDTimeoutBody,
SandboxAutoResumeConfig,
+ SandboxForkRequest,
SandboxNetworkConfig,
SandboxPauseRequest,
SandboxVolumeMount as SandboxVolumeMountAPI,
)
-from e2b.api.client.types import UNSET
+from e2b.api.client.types import UNSET, Unset
from e2b.connection_config import ApiParams, ConnectionConfig
from e2b.exceptions import (
InvalidArgumentException,
+ NotFoundException,
SandboxException,
SandboxNotFoundException,
TemplateException,
@@ -403,6 +410,93 @@ class SandboxApi(SandboxBase):
traffic_access_token=traffic_token,
)
+ @classmethod
+ def _cls_fork(
+ cls,
+ sandbox_id: str,
+ timeout: Optional[int] = None,
+ count: Optional[int] = None,
+ logger: Optional[logging.Logger] = None,
+ **opts: Unpack[ApiParams],
+ ) -> List[Union[SandboxCreateResponse, Exception]]:
+ timeout = (
+ timeout if timeout is not None else SandboxBase.default_sandbox_timeout
+ )
+ count = count if count is not None else 1
+
+ if count < 1:
+ raise InvalidArgumentException("count must be at least 1")
+
+ config = ConnectionConfig(logger=logger, **opts)
+
+ api_client = get_api_client(config)
+ res = post_sandboxes_sandbox_id_fork.sync_detailed(
+ sandbox_id,
+ client=api_client,
+ body=SandboxForkRequest(timeout=timeout, count=count),
+ )
+
+ if res.status_code == 404:
+ message = (
+ res.parsed.message
+ if isinstance(res.parsed, Error)
+ else f"Sandbox {sandbox_id} not found"
+ )
+ raise SandboxNotFoundException(message)
+
+ if res.status_code >= 300:
+ raise handle_api_exception(res)
+
+ if isinstance(res.parsed, Error):
+ raise SandboxException(f"{res.parsed.message}: Request failed")
+
+ if res.parsed is None:
+ raise Exception("Body of the request is None")
+
+ results: List[Union[SandboxCreateResponse, Exception]] = []
+ for result in res.parsed:
+ sandbox = None if isinstance(result.sandbox, Unset) else result.sandbox
+ error = None if isinstance(result.error, Unset) else result.error
+
+ if error is not None or sandbox is None:
+ if error is None:
+ exception = SandboxException("Failed to start forked sandbox")
+ elif error.code == 404:
+ # 404 is call-site-specific in the SDK, so
+ # api_exception_from_code leaves it to the caller. A
+ # per-fork 404 refers to a resource needed to start that
+ # fork (e.g. the snapshot) — not the source sandbox, which
+ # would have failed the whole request — so stay generic.
+ exception = NotFoundException(f"{error.code}: {error.message}")
+ else:
+ exception = api_exception_from_code(error.code, error.message)
+ results.append(exception)
+ continue
+
+ domain = sandbox.domain if isinstance(sandbox.domain, str) else None
+ envd_token = (
+ sandbox.envd_access_token
+ if isinstance(sandbox.envd_access_token, str)
+ else None
+ )
+ traffic_token = (
+ sandbox.traffic_access_token
+ if isinstance(sandbox.traffic_access_token, str)
+ else None
+ )
+
+ results.append(
+ SandboxCreateResponse(
+ sandbox_id=sandbox.sandbox_id,
+ sandbox_domain=domain,
+ envd_version=sandbox.envd_version,
+ envd_access_token=envd_token,
+ traffic_access_token=traffic_token,
+ )
+ )
+
+ return results
+
@classmethod
def _cls_create_snapshot(
cls,
diff --git a/packages/python-sdk/tests/async/sandbox_async/test_fork.py b/packages/python-sdk/tests/async/sandbox_async/test_fork.py
new file mode 100644
index 000000000..19f8c7ef2
--- /dev/null
+++ b/packages/python-sdk/tests/async/sandbox_async/test_fork.py
@@ -0,0 +1,83 @@
+import pytest
+
+from e2b import AsyncSandbox
+from e2b.exceptions import InvalidArgumentException, SandboxNotFoundException
+
+
+async def test_fork(async_sandbox: AsyncSandbox):
+ await async_sandbox.files.write("/home/user/state.txt", "state before fork")
+
+ forks = await async_sandbox.fork()
+ assert len(forks) == 1
+
+ fork = forks[0]
+ assert isinstance(fork, AsyncSandbox)
+
+ try:
+ assert fork.sandbox_id != async_sandbox.sandbox_id
+
+ # The original sandbox keeps running
+ assert await async_sandbox.is_running()
+ assert await fork.is_running()
+
+ # The fork inherits the filesystem state
+ assert await fork.files.read("/home/user/state.txt") == "state before fork"
+
+ # The fork is independent of the original
+ await fork.files.write("/home/user/state.txt", "modified in fork")
+ assert (
+ await async_sandbox.files.read("/home/user/state.txt")
+ == "state before fork"
+ )
+ finally:
+ await fork.kill()
+
+
+async def test_fork_multiple(async_sandbox: AsyncSandbox):
+ forks = await async_sandbox.fork(count=2, timeout=60)
+ assert len(forks) == 2
+
+ forked_sandboxes = [fork for fork in forks if isinstance(fork, AsyncSandbox)]
+
+ try:
+ assert len(forked_sandboxes) == 2
+
+ ids = {s.sandbox_id for s in forked_sandboxes}
+ assert len(ids) == 2
+ assert async_sandbox.sandbox_id not in ids
+
+ for fork in forked_sandboxes:
+ assert await fork.is_running()
+ finally:
+ for fork in forked_sandboxes:
+ await fork.kill()
+
+
+async def test_fork_by_id(async_sandbox: AsyncSandbox):
+ forks = await AsyncSandbox.fork(async_sandbox.sandbox_id)
+ assert len(forks) == 1
+
+ fork = forks[0]
+ assert isinstance(fork, AsyncSandbox)
+
+ try:
+ assert await fork.is_running()
+ finally:
+ await fork.kill()
+
+
+async def test_fork_killed_sandbox(async_sandbox_factory):
+ sandbox = await async_sandbox_factory()
+ await sandbox.kill()
+
+ with pytest.raises(SandboxNotFoundException):
+ await sandbox.fork()
+
+
+async def test_fork_invalid_count():
+ with pytest.raises(InvalidArgumentException):
+ await AsyncSandbox.fork("sbx-test", count=0)
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_fork.py b/packages/python-sdk/tests/sync/sandbox_sync/test_fork.py
new file mode 100644
index 000000000..7159a5310
--- /dev/null
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_fork.py
@@ -0,0 +1,80 @@
+import pytest
+
+from e2b import Sandbox
+from e2b.exceptions import InvalidArgumentException, SandboxNotFoundException
+
+
+def test_fork(sandbox: Sandbox):
+ sandbox.files.write("/home/user/state.txt", "state before fork")
+
+ forks = sandbox.fork()
+ assert len(forks) == 1
+
+ fork = forks[0]
+ assert isinstance(fork, Sandbox)
+
+ try:
+ assert fork.sandbox_id != sandbox.sandbox_id
+
+ # The original sandbox keeps running
+ assert sandbox.is_running()
+ assert fork.is_running()
+
+ # The fork inherits the filesystem state
+ assert fork.files.read("/home/user/state.txt") == "state before fork"
+
+ # The fork is independent of the original
+ fork.files.write("/home/user/state.txt", "modified in fork")
+ assert sandbox.files.read("/home/user/state.txt") == "state before fork"
+ finally:
+ fork.kill()
+
+
+def test_fork_multiple(sandbox: Sandbox):
+ forks = sandbox.fork(count=2, timeout=60)
+ assert len(forks) == 2
+
+ forked_sandboxes = [fork for fork in forks if isinstance(fork, Sandbox)]
+
+ try:
+ assert len(forked_sandboxes) == 2
+
+ ids = {s.sandbox_id for s in forked_sandboxes}
+ assert len(ids) == 2
+ assert sandbox.sandbox_id not in ids
+
+ for fork in forked_sandboxes:
+ assert fork.is_running()
+ finally:
+ for fork in forked_sandboxes:
+ fork.kill()
+
+
+def test_fork_by_id(sandbox: Sandbox):
+ forks = Sandbox.fork(sandbox.sandbox_id)
+ assert len(forks) == 1
+
+ fork = forks[0]
+ assert isinstance(fork, Sandbox)
+
+ try:
+ assert fork.is_running()
+ finally:
+ fork.kill()
+
+
+def test_fork_killed_sandbox(sandbox_factory):
+ sandbox = sandbox_factory()
+ sandbox.kill()
+
+ with pytest.raises(SandboxNotFoundException):
+ sandbox.fork()
+
+
+def test_fork_invalid_count():
+ with pytest.raises(InvalidArgumentException):
+ Sandbox.fork("sbx-test", count=0)
diff --git a/spec/openapi.yml b/spec/openapi.yml
index f772100d1..da541a1f4 100644
--- a/spec/openapi.yml
+++ b/spec/openapi.yml
@@ -761,6 +761,39 @@ components:
format: int32
minimum: 0
+ SandboxForkRequest:
+ type: object
+ properties:
+ timeout:
+ type: integer
+ format: int32
+ minimum: 0
+ default: 15
+ description: Time to live for the new forked sandboxes in seconds.
+ count:
+ type: integer
+ format: int32
+ minimum: 1
+ maximum: 100
+ default: 1
+ description: >-
+ Number of forked sandboxes to create. All forks boot from the same
+ snapshot, so the snapshot is captured once regardless of count.
+ Each fork succeeds or fails independently; the outcome of each is
+ reported in its entry of the response list.
+
+ SandboxForkResult:
+ type: object
+ description: >-
+ Result of one requested fork. Exactly one of sandbox or error is set:
+ sandbox when the fork started successfully, error when it failed to
+ start.
+ properties:
+ sandbox:
+ $ref: '#/components/schemas/Sandbox'
+ error:
+ $ref: '#/components/schemas/Error'
+
TeamMetric:
description: Team metric with timestamp
required:
@@ -2427,6 +2460,52 @@ paths:
'500':
$ref: '#/components/responses/500'
+ /sandboxes/{sandboxID}/fork:
+ post:
+ summary: Fork sandbox
+ description: >-
+ Fork the sandbox: checkpoint the running sandbox in place (it is
+ briefly paused, snapshotted with its full memory state, and resumed on
+ its node, keeping its ID and expiration untouched) and create count
+ new sandboxes from that snapshot. Returns one result per requested
+ fork, each carrying either the created sandbox or the error that
+ prevented it from starting. A non-201 status means the request failed
+ before any fork was attempted.
+ tags: [sandboxes]
+ security:
+ - ApiKeyAuth: []
+ - Supabase1TokenAuth: []
+ Supabase2TeamAuth: []
+ - AuthProviderBearerAuth: []
+ AuthProviderTeamAuth: []
+ parameters:
+ - $ref: '#/components/parameters/sandboxID'
+ requestBody:
+ required: false
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SandboxForkRequest'
+ responses:
+ '201':
+ description: >-
+ The sandbox was snapshotted and the forks were attempted; each
+ entry reports one fork's outcome
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '#/components/schemas/SandboxForkResult'
+ '409':
+ $ref: '#/components/responses/409'
+ '404':
+ $ref: '#/components/responses/404'
+ '401':
+ $ref: '#/components/responses/401'
+ '500':
+ $ref: '#/components/responses/500'
+
/sandboxes/{sandboxID}/connect:
post:
description: Returns sandbox details. If the sandbox is paused, it will be resumed. TTL is only extended.