Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
feat(sdk): add an E2B client to the Code Interpreter SDKs (#1783)
devin-ai-integration[bot]390a1bfdd306
diff --git a/.changeset/large-desks-bind.md b/.changeset/large-desks-bind.mdnew file mode 100644index 000000000..42a3737d8--- /dev/null+++ b/.changeset/large-desks-bind.md@@ -0,0 +1,6 @@+---+'@e2b/desktop': minor+'@e2b/desktop-python': minor+---++Add an `E2B` client to the Desktop SDKs that binds the connection configuration explicitly, so the API key and domain no longer have to come from the environment variables: `new E2B({ apiKey, domain }).Sandbox.create()` in JavaScript and `E2B(api_key=..., domain=...).Sandbox.create()` in Python. The client exposes the package's own `Sandbox` together with the core `Volume`, `Template` and `Secret` resources, per-call options still take precedence, and multiple clients are isolated from each other and from the env-configured top-level exports.diff --git a/.changeset/shiny-clients-bind.md b/.changeset/shiny-clients-bind.mdnew file mode 100644index 000000000..b587e7a12--- /dev/null+++ b/.changeset/shiny-clients-bind.md@@ -0,0 +1,6 @@+---+'@e2b/code-interpreter': minor+'@e2b/code-interpreter-python': minor+---++Add an `E2B` client to the Code Interpreter SDKs that binds the connection configuration explicitly, so the API key and domain no longer have to come from the environment variables: `new E2B({ apiKey, domain }).Sandbox.create()` in JavaScript and `E2B(api_key=..., domain=...).Sandbox.create()` in Python. The client exposes the package's own `Sandbox` (and `AsyncSandbox` in Python) together with the core `Volume`, `Template` and `Secret` resources, per-call options still take precedence, and multiple clients are isolated from each other and from the env-configured top-level exports.diff --git a/packages/code-interpreter-js/README.md b/packages/code-interpreter-js/README.mdindex d2ef90eed..297ac7108 100644--- a/packages/code-interpreter-js/README.md+++ b/packages/code-interpreter-js/README.md@@ -45,8 +45,32 @@ const execution = await sbx.runCode('x+=1; x')console.log(execution.text) // outputs 2```-### 4. Check docs+### 4. Bind the configuration to a client++The top-level `Sandbox` export reads its configuration from the environment variables. To use an explicit configuration — e.g. several API keys or domains in one process — create an `E2B` client and use the resources it exposes:++```ts+import { E2B } from '@e2b/code-interpreter'++const client = new E2B({ apiKey: 'e2b_***', domain: 'e2b.dev' })++const sbx = await client.Sandbox.create()+const execution = await sbx.runCode('x = 1; x += 1; x')++// The core resources are bound to the client's configuration as well.+const volume = await client.Volume.create('my-volume')+const exists = await client.Template.exists('my-template')+await client.Secret.create('openai-api-key', 'sk-***')++// The classes can be destructured and used like the top-level ones.+const { Sandbox } = client+const paginator = Sandbox.list()+```++Per-call options still take precedence over the client's options, and clients are isolated from each other and from the env-configured top-level exports.++### 5. Check docsVisit [E2B documentation](https://docs.e2b.dev/?utm_source=npm&utm_medium=referral&utm_campaign=readme&utm_content=code-interpreter).-### 5. E2B cookbook+### 6. E2B cookbookVisit our [Cookbook](https://github.com/e2b-dev/e2b-cookbook/tree/main) to get inspired by examples with different LLMs and AI frameworks.diff --git a/packages/code-interpreter-js/src/client.ts b/packages/code-interpreter-js/src/client.tsnew file mode 100644index 000000000..3d2de57b3--- /dev/null+++ b/packages/code-interpreter-js/src/client.ts@@ -0,0 +1,94 @@+import {+ ConnectionOpts,+ E2BClientOpts,+ E2B as CoreE2B,+ Secret,+ Template,+ Volume,+} from 'e2b'++import { Sandbox } from './sandbox'++export type { E2BClientOpts }++/**+ * E2B client with an explicitly bound connection configuration.+ *+ * The resources exposed by the client ({@link E2B.Sandbox},+ * {@link E2B.Volume}, {@link E2B.Template}, {@link E2B.Secret}) behave exactly+ * like the top-level `Sandbox` / `Volume` / `Template` / `Secret` exports,+ * except the options passed to the client are used as the defaults instead of+ * the environment variables.+ * Per-call options still take precedence over the client's options.+ *+ * Multiple clients are fully isolated from each other and from the top-level+ * env-configured exports.+ *+ * @example+ * ```ts+ * import { E2B } from '@e2b/code-interpreter'+ *+ * const client = new E2B({ apiKey: 'e2b_...', domain: 'e2b.dev' })+ *+ * const sandbox = await client.Sandbox.create()+ * const execution = await sandbox.runCode('x = 1; x += 1; x')+ * ```+ */+export class E2B {+ /**+ * Code Interpreter `Sandbox` class bound to this client's connection+ * configuration.+ */+ readonly Sandbox: typeof Sandbox++ /**+ * `Volume` class bound to this client's connection configuration.+ */+ readonly Volume: typeof Volume++ /**+ * `Template` bound to this client's connection configuration. Both the+ * builder (`client.Template()`) and the statics+ * (`client.Template.build(...)`, `client.Template.exists(...)`, …) work like+ * the top-level `Template`.+ */+ readonly Template: typeof Template++ /**+ * `Secret` class bound to this client's connection configuration.+ */+ readonly Secret: typeof Secret++ /**+ * Create a new client with the connection options bound to it.+ *+ * @param opts connection options used as the defaults for every call made+ * through this client's resource classes.+ */+ constructor(opts?: E2BClientOpts) {+ // Options are copied so later mutations of the caller's object cannot+ // change the bound configuration. `signal` is dropped rather than only+ // typed away, since it cancels a single request and a caller passing a+ // wider-typed object (or plain JS) would otherwise bind it to every call.+ const boundOpts: E2BClientOpts = { ...(opts ?? {}) }+ delete (boundOpts as ConnectionOpts).signal++ if (boundOpts.headers) {+ boundOpts.headers = { ...boundOpts.headers }+ }+ if (boundOpts.apiHeaders) {+ boundOpts.apiHeaders = { ...boundOpts.apiHeaders }+ }++ this.Sandbox = class extends Sandbox {+ protected static override readonly boundOpts = boundOpts+ }++ // The resources that are not specific to the Code Interpreter are bound by+ // the core client.+ const core = new CoreE2B(boundOpts)+ this.Volume = core.Volume+ this.Template = core.Template+ this.Secret = core.Secret+ }+}diff --git a/packages/code-interpreter-js/src/index.ts b/packages/code-interpreter-js/src/index.tsindex d45981211..9a309eb50 100644--- a/packages/code-interpreter-js/src/index.ts+++ b/packages/code-interpreter-js/src/index.ts@@ -1,5 +1,7 @@export * from 'e2b'+export { E2B } from './client'+export type { E2BClientOpts } from './client'export { Sandbox } from './sandbox'export type {Context,diff --git a/packages/code-interpreter-python/README.md b/packages/code-interpreter-python/README.mdindex e9016af6f..9b2fd58c7 100644--- a/packages/code-interpreter-python/README.md+++ b/packages/code-interpreter-python/README.md@@ -44,8 +44,35 @@ with Sandbox.create() as sandbox:print(execution.text) # outputs 2```-### 4. Check docs+### 4. Bind the configuration to a client++The top-level `Sandbox` and `AsyncSandbox` exports read their configuration from the environment variables. To use an explicit configuration — e.g. several API keys or domains in one process — create an `E2B` client and use the resource classes it exposes:++```py+from e2b_code_interpreter import E2B++client = E2B(api_key="e2b_***", domain="e2b.dev")++with client.Sandbox.create() as sandbox:+ execution = sandbox.run_code("x = 1; x += 1; x")++# The async variant is exposed as well.+async_sandbox = await client.AsyncSandbox.create()++# The core resources are bound to the client's configuration as well.+volume = client.Volume.create("my-volume")+exists = client.Template.exists("my-template")+secret = client.Secret.create("openai-api-key", "sk-***")++# The classes can be assigned and used like the top-level ones.+Sandbox = client.Sandbox+paginator = Sandbox.list()+```++Per-call params still take precedence over the client's params, and clients are isolated from each other and from the env-configured top-level exports.++### 5. Check docsVisit [E2B documentation](https://docs.e2b.dev/?utm_source=pypi&utm_medium=referral&utm_campaign=readme&utm_content=code-interpreter).-### 5. E2B cookbook+### 6. E2B cookbookVisit our [Cookbook](https://github.com/e2b-dev/e2b-cookbook/tree/main) to get inspired by examples with different LLMs and AI frameworks.diff --git a/packages/code-interpreter-python/e2b_code_interpreter/__init__.py b/packages/code-interpreter-python/e2b_code_interpreter/__init__.pyindex 5202d5deb..94c804a37 100644--- a/packages/code-interpreter-python/e2b_code_interpreter/__init__.py+++ b/packages/code-interpreter-python/e2b_code_interpreter/__init__.py@@ -1,4 +1,5 @@from e2b import *+from .client import E2B, E2BClientParamsfrom .code_interpreter_sync import Sandboxfrom .code_interpreter_async import AsyncSandboxfrom .models import (diff --git a/packages/code-interpreter-python/e2b_code_interpreter/client.py b/packages/code-interpreter-python/e2b_code_interpreter/client.pynew file mode 100644index 000000000..47d286e34--- /dev/null+++ b/packages/code-interpreter-python/e2b_code_interpreter/client.py@@ -0,0 +1,93 @@+from typing import Dict, Type, TypeVar, cast++from e2b import ApiParams, E2BClientParams+from e2b import E2B as CoreE2B+from typing_extensions import Unpack++from e2b_code_interpreter.code_interpreter_async import AsyncSandbox+from e2b_code_interpreter.code_interpreter_sync import Sandbox++T = TypeVar("T")++__all__ = ["E2B", "E2BClientParams"]+++def _bind(cls: Type[T], api_params: ApiParams) -> Type[T]:+ """Generate a subclass of ``cls`` carrying ``api_params`` as its bound params."""+ return cast(+ Type[T],+ type(cls.__name__, (cls,), {"_bound_api_params": api_params}),+ )+++class E2B:+ """+ E2B client with an explicitly bound connection configuration.++ The resource classes exposed by the client (`Sandbox`, `AsyncSandbox`,+ `Volume`, `AsyncVolume`, `Template`, `AsyncTemplate`, `Secret`,+ `AsyncSecret`) behave exactly like the top-level exports of the same name,+ except the params passed to the client are used as the defaults instead of+ the environment variables.+ Per-call params still take precedence over the client's params.++ Multiple clients are fully isolated from each other and from the top-level+ env-configured exports.++ Example:+ ```python+ from e2b_code_interpreter import E2B++ client = E2B(api_key="e2b_...", domain="e2b.dev")++ sandbox = client.Sandbox.create()+ execution = sandbox.run_code("x = 1; x += 1; x")+ ```+ """++ def __init__(self, **opts: Unpack[E2BClientParams]):+ """+ Create a new client with the API params bound to it.++ :param opts: API params used as the defaults for every call made+ through this client's resource classes.+ """+ # Params are copied so later mutations of the caller's dicts cannot+ # change the bound configuration.+ api_params = cast(ApiParams, dict(cast(Dict[str, object], opts)))++ headers = api_params.get("headers")+ if headers is not None:+ api_params["headers"] = dict(headers)++ api_headers = api_params.get("api_headers")+ if api_headers is not None:+ api_params["api_headers"] = dict(api_headers)++ self.Sandbox = _bind(Sandbox, api_params)+ """Code Interpreter `Sandbox` class bound to this client's connection configuration."""++ self.AsyncSandbox = _bind(AsyncSandbox, api_params)+ """Code Interpreter `AsyncSandbox` class bound to this client's connection configuration."""++ # The resources that are not specific to the Code Interpreter are bound+ # by the core client.+ core = CoreE2B(**api_params)++ self.Volume = core.Volume+ """`Volume` class bound to this client's connection configuration."""++ self.AsyncVolume = core.AsyncVolume+ """`AsyncVolume` class bound to this client's connection configuration."""++ self.Template = core.Template+ """`Template` class bound to this client's connection configuration."""++ self.AsyncTemplate = core.AsyncTemplate+ """`AsyncTemplate` class bound to this client's connection configuration."""++ self.Secret = core.Secret+ """`Secret` class bound to this client's connection configuration."""++ self.AsyncSecret = core.AsyncSecret+ """`AsyncSecret` class bound to this client's connection configuration."""diff --git a/packages/code-interpreter-python/pyproject.toml b/packages/code-interpreter-python/pyproject.tomlindex e6fd8a6d5..59f2b3d74 100644--- a/packages/code-interpreter-python/pyproject.toml+++ b/packages/code-interpreter-python/pyproject.toml@@ -9,7 +9,7 @@ requires-python = ">=3.10"dependencies = ["httpx>=0.20.0,<1.0.0","attrs>=21.3.0",- "e2b>=2.39.1,<3.0.0",+ "e2b>=2.44.0,<3.0.0",][project.urls]diff --git a/packages/desktop-js/README.md b/packages/desktop-js/README.mdindex 022fdbfd2..62006fa82 100644--- a/packages/desktop-js/README.md+++ b/packages/desktop-js/README.md@@ -59,6 +59,30 @@ console.log('Stream URL:', desktop.stream.getUrl({ authKey }))// await desktop.kill()```+### 4. Bind the configuration to a client++The top-level `Sandbox` export reads its configuration from the environment variables. To use an explicit configuration — e.g. several API keys or domains in one process — create an `E2B` client and use the resources it exposes:++```javascript+import { E2B } from '@e2b/desktop'++const client = new E2B({ apiKey: 'e2b_***', domain: 'e2b.dev' })++const desktop = await client.Sandbox.create()+await desktop.stream.start()++// The core resources are bound to the client's configuration as well.+const volume = await client.Volume.create('my-volume')+const exists = await client.Template.exists('my-template')+await client.Secret.create('openai-api-key', 'sk-***')++// The classes can be destructured and used like the top-level ones.+const { Sandbox } = client+const paginator = Sandbox.list()+```++Per-call options still take precedence over the client's options, and clients are isolated from each other and from the env-configured top-level exports.+## Features### Streaming desktop's screendiff --git a/packages/desktop-js/src/client.ts b/packages/desktop-js/src/client.tsnew file mode 100644index 000000000..07f064b76--- /dev/null+++ b/packages/desktop-js/src/client.ts@@ -0,0 +1,93 @@+import {+ ConnectionOpts,+ E2BClientOpts,+ E2B as CoreE2B,+ Secret,+ Template,+ Volume,+} from 'e2b'++import { Sandbox } from './sandbox'++export type { E2BClientOpts }++/**+ * E2B client with an explicitly bound connection configuration.+ *+ * The resources exposed by the client ({@link E2B.Sandbox},+ * {@link E2B.Volume}, {@link E2B.Template}, {@link E2B.Secret}) behave exactly+ * like the top-level `Sandbox` / `Volume` / `Template` / `Secret` exports,+ * except the options passed to the client are used as the defaults instead of+ * the environment variables.+ * Per-call options still take precedence over the client's options.+ *+ * Multiple clients are fully isolated from each other and from the top-level+ * env-configured exports.+ *+ * @example+ * ```ts+ * import { E2B } from '@e2b/desktop'+ *+ * const client = new E2B({ apiKey: 'e2b_...', domain: 'e2b.dev' })+ *+ * const desktop = await client.Sandbox.create()+ * await desktop.stream.start()+ * ```+ */+export class E2B {+ /**+ * Desktop `Sandbox` class bound to this client's connection configuration.+ */+ readonly Sandbox: typeof Sandbox++ /**+ * `Volume` class bound to this client's connection configuration.+ */+ readonly Volume: typeof Volume++ /**+ * `Template` bound to this client's connection configuration. Both the+ * builder (`client.Template()`) and the statics+ * (`client.Template.build(...)`, `client.Template.exists(...)`, …) work like+ * the top-level `Template`.+ */+ readonly Template: typeof Template++ /**+ * `Secret` class bound to this client's connection configuration.+ */+ readonly Secret: typeof Secret++ /**+ * Create a new client with the connection options bound to it.+ *+ * @param opts connection options used as the defaults for every call made+ * through this client's resource classes.+ */+ constructor(opts?: E2BClientOpts) {+ // Options are copied so later mutations of the caller's object cannot+ // change the bound configuration. `signal` is dropped rather than only+ // typed away, since it cancels a single request and a caller passing a+ // wider-typed object (or plain JS) would otherwise bind it to every call.+ const boundOpts: E2BClientOpts = { ...(opts ?? {}) }+ delete (boundOpts as ConnectionOpts).signal++ if (boundOpts.headers) {+ boundOpts.headers = { ...boundOpts.headers }+ }+ if (boundOpts.apiHeaders) {+ boundOpts.apiHeaders = { ...boundOpts.apiHeaders }+ }++ this.Sandbox = class extends Sandbox {+ protected static override readonly boundOpts = boundOpts+ }++ // The resources that are not specific to the Desktop are bound by the core+ // client.+ const core = new CoreE2B(boundOpts)+ this.Volume = core.Volume+ this.Template = core.Template+ this.Secret = core.Secret+ }+}diff --git a/packages/desktop-js/src/index.ts b/packages/desktop-js/src/index.tsindex 3e072a924..c975f412b 100644--- a/packages/desktop-js/src/index.ts+++ b/packages/desktop-js/src/index.ts@@ -1,3 +1,5 @@export * from 'e2b'+export { E2B } from './client'+export type { E2BClientOpts } from './client'export { Sandbox } from './sandbox'diff --git a/packages/desktop-js/tests/client.test.ts b/packages/desktop-js/tests/client.test.tsnew file mode 100644index 000000000..1960af1c5--- /dev/null+++ b/packages/desktop-js/tests/client.test.ts@@ -0,0 +1,254 @@+import {+ createServer,+ IncomingMessage,+ Server,+ ServerResponse,+} from 'node:http'+import { AddressInfo } from 'node:net'+import { afterAll, assert, beforeAll, beforeEach, test, vi } from 'vitest'++import { E2B, Sandbox, Volume } from '../src'++const API_KEY_A = `e2b_${'a'.repeat(40)}`+const API_KEY_B = `e2b_${'b'.repeat(40)}`+const ENV_API_KEY = `e2b_${'e'.repeat(40)}`++const DOMAIN_A = 'client-a.test'+const DOMAIN_B = 'client-b.test'+const DOMAIN_ENV = 'env.test'++interface RecordedRequest {+ path: string+ apiKey?: string+ headers: Record<string, string | string[] | undefined>+ body: unknown+}++let requests: RecordedRequest[] = []+let server: Server+let apiUrl: string++const lastRequest = () => requests[requests.length - 1]+const apiKeys = () => requests.map((request) => request.apiKey)++async function handler(req: IncomingMessage, res: ServerResponse) {+ const chunks: Buffer[] = []+ for await (const chunk of req) {+ chunks.push(chunk as Buffer)+ }+ const raw = Buffer.concat(chunks).toString()++ requests.push({+ path: req.url ?? '',+ apiKey: (req.headers['x-api-key'] as string | undefined) ?? undefined,+ headers: { ...req.headers },+ body: raw ? JSON.parse(raw) : undefined,+ })++ const respond = (status: number, body: unknown) => {+ res.writeHead(status, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify(body))+ }++ const path = req.url ?? ''+ if (path.startsWith('/sandboxes')) {+ respond(201, {+ sandboxID: 'test-sandbox-id',+ templateID: 'desktop',+ envdVersion: '0.2.4',+ })+ } else if (path.startsWith('/volumes')) {+ respond(201, {+ volumeID: 'test-volume-id',+ name: 'test-volume',+ token: 'test-volume-token',+ })+ } else if (path.startsWith('/templates/aliases/')) {+ respond(200, { aliases: [], templateID: 'test-template-id' })+ } else if (path.startsWith('/secrets')) {+ respond(201, {+ secretID: 'test-secret-id',+ name: 'test-secret',+ currentVersion: 1,+ metadata: {},+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ })+ } else {+ respond(404, { code: 404, message: 'not found' })+ }+}++const envBackup: Record<string, string | undefined> = {}+const envOverrides: Record<string, string | undefined> = {+ E2B_API_KEY: ENV_API_KEY,+ E2B_DOMAIN: DOMAIN_ENV,+ E2B_API_URL: undefined,+ E2B_SANDBOX_URL: undefined,+ E2B_DEBUG: undefined,+}++beforeAll(async () => {+ for (const [key, value] of Object.entries(envOverrides)) {+ envBackup[key] = process.env[key]+ if (value === undefined) {+ delete process.env[key]+ } else {+ process.env[key] = value+ }+ }++ // Starting the desktop environment talks to envd inside the sandbox, which+ // does not exist for a mocked API. The API calls that carry the bound+ // configuration all happen before it.+ vi.spyOn(+ Sandbox.prototype as unknown as { _start: () => Promise<void> },+ '_start'+ ).mockResolvedValue(undefined)++ server = createServer(handler)+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ apiUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`+})++afterAll(async () => {+ vi.restoreAllMocks()++ await new Promise<void>((resolve, reject) =>+ server.close((err) => (err ? reject(err) : resolve()))+ )++ for (const [key, value] of Object.entries(envBackup)) {+ if (value === undefined) {+ delete process.env[key]+ } else {+ process.env[key] = value+ }+ }+})++beforeEach(() => {+ requests = []+})++test('client.Sandbox.create uses the client config instead of env vars', async () => {+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A, apiUrl })++ const sandbox = await client.Sandbox.create()++ assert.deepEqual(apiKeys(), [API_KEY_A])+ assert.equal(sandbox.sandboxDomain, DOMAIN_A)+ // The desktop template is still the default.+ assert.equal(+ (lastRequest().body as { templateID: string }).templateID,+ 'desktop'+ )+})++test('client.Sandbox instances keep the desktop API', async () => {+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A, apiUrl })++ assert.notEqual(client.Sandbox, Sandbox)+ assert.isTrue(client.Sandbox.prototype instanceof Sandbox)++ const sandbox = await client.Sandbox.create()++ assert.instanceOf(sandbox, Sandbox)+ assert.instanceOf(sandbox, client.Sandbox)+ assert.isFunction(sandbox.screenshot)+ assert.isFunction(sandbox.stream.start)+ assert.equal(sandbox.display, ':0')+})++test('per-call options take precedence over the client config', async () => {+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A, apiUrl })++ const sandbox = await client.Sandbox.create({+ apiKey: API_KEY_B,+ domain: DOMAIN_B,+ })++ assert.deepEqual(apiKeys(), [API_KEY_B])+ assert.equal(sandbox.sandboxDomain, DOMAIN_B)+})++test('per-call options explicitly set to undefined keep the client config', async () => {+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A, apiUrl })++ const sandbox = await client.Sandbox.create({+ apiKey: undefined,+ domain: undefined,+ })++ assert.deepEqual(apiKeys(), [API_KEY_A])+ assert.equal(sandbox.sandboxDomain, DOMAIN_A)+})++test('two clients with different configs stay isolated', async () => {+ const clientA = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A, apiUrl })+ const clientB = new E2B({ apiKey: API_KEY_B, domain: DOMAIN_B, apiUrl })++ const sandboxA = await clientA.Sandbox.create()+ const sandboxB = await clientB.Sandbox.create()++ assert.deepEqual(apiKeys(), [API_KEY_A, API_KEY_B])+ assert.equal(sandboxA.sandboxDomain, DOMAIN_A)+ assert.equal(sandboxB.sandboxDomain, DOMAIN_B)+})++test('mutating the options object does not change the bound config', async () => {+ const opts = { apiKey: API_KEY_A, domain: DOMAIN_A, apiUrl }+ const client = new E2B(opts)+ opts.apiKey = API_KEY_B++ await client.Sandbox.create()++ assert.deepEqual(apiKeys(), [API_KEY_A])+})++test('mutating the header map does not change the bound config', async () => {+ const headers = { 'X-Test': 'bound' }+ const client = new E2B({+ apiKey: API_KEY_A,+ domain: DOMAIN_A,+ apiUrl,+ headers,+ })+ headers['X-Test'] = 'mutated'++ await client.Sandbox.create()++ assert.equal(lastRequest().headers['x-test'], 'bound')+})++test('client.Sandbox can be rebound to a variable', async () => {+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A, apiUrl })+ const S = client.Sandbox++ const sandbox = await S.create()++ assert.deepEqual(apiKeys(), [API_KEY_A])+ assert.equal(sandbox.sandboxDomain, DOMAIN_A)+})++test('the core resources are bound to the client config as well', async () => {+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A, apiUrl })++ const volume = await client.Volume.create('test-volume')+ assert.instanceOf(volume, Volume)++ assert.isTrue(await client.Template.exists('test-template'))+ await client.Secret.create('test-secret', 'value')++ assert.deepEqual(apiKeys(), [API_KEY_A, API_KEY_A, API_KEY_A])+})++test('the top-level Sandbox keeps using the environment configuration', async () => {+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A, apiUrl })+ await client.Sandbox.create()++ const sandbox = await Sandbox.create({ apiUrl })++ assert.equal(lastRequest().apiKey, ENV_API_KEY)+ assert.equal(sandbox.sandboxDomain, DOMAIN_ENV)+})diff --git a/packages/desktop-js/tests/runtimes/cloudflare/vitest.config.mts b/packages/desktop-js/tests/runtimes/cloudflare/vitest.config.mtsindex f0cb75e40..825966d16 100644--- a/packages/desktop-js/tests/runtimes/cloudflare/vitest.config.mts+++ b/packages/desktop-js/tests/runtimes/cloudflare/vitest.config.mts@@ -7,6 +7,11 @@ import {export default defineConfig(createCloudflareVitestConfig({+ exclude: [+ // Serves the mocked API from a local node:http server, which workerd+ // cannot listen on; the Node unit project keeps running it.+ 'tests/client.test.ts',+ ],testTimeout: 90_000,maxWorkers: 1,isExpectedRejection: isConnectRpcRejection,diff --git a/packages/desktop-python/README.md b/packages/desktop-python/README.mdindex 3f54361a1..df7b11820 100644--- a/packages/desktop-python/README.md+++ b/packages/desktop-python/README.md@@ -59,6 +59,30 @@ print('Stream URL:', desktop.stream.get_url(auth_key=auth_key))# desktop.kill()```+### 4. Bind the configuration to a client++The top-level `Sandbox` export reads its configuration from the environment variables. To use an explicit configuration — e.g. several API keys or domains in one process — create an `E2B` client and use the resource classes it exposes:++```python+from e2b_desktop import E2B++client = E2B(api_key="e2b_***", domain="e2b.dev")++desktop = client.Sandbox.create()+desktop.stream.start()++# The core resources are bound to the client's configuration as well.+volume = client.Volume.create("my-volume")+exists = client.Template.exists("my-template")+secret = client.Secret.create("openai-api-key", "sk-***")++# The classes can be assigned and used like the top-level ones.+Sandbox = client.Sandbox+paginator = Sandbox.list()+```++Per-call params still take precedence over the client's params, and clients are isolated from each other and from the env-configured top-level exports.+## Features### Streaming desktop's screendiff --git a/packages/desktop-python/e2b_desktop/__init__.py b/packages/desktop-python/e2b_desktop/__init__.pyindex 163338b5d..337164028 100644--- a/packages/desktop-python/e2b_desktop/__init__.py+++ b/packages/desktop-python/e2b_desktop/__init__.py@@ -1,3 +1,4 @@from e2b import *+from .client import E2B, E2BClientParamsfrom .main import Sandboxdiff --git a/packages/desktop-python/e2b_desktop/client.py b/packages/desktop-python/e2b_desktop/client.pynew file mode 100644index 000000000..55d859a01--- /dev/null+++ b/packages/desktop-python/e2b_desktop/client.py@@ -0,0 +1,89 @@+from typing import Dict, Type, TypeVar, cast++from e2b import ApiParams, E2BClientParams+from e2b import E2B as CoreE2B+from typing_extensions import Unpack++from e2b_desktop.main import Sandbox++T = TypeVar("T")++__all__ = ["E2B", "E2BClientParams"]+++def _bind(cls: Type[T], api_params: ApiParams) -> Type[T]:+ """Generate a subclass of ``cls`` carrying ``api_params`` as its bound params."""+ return cast(+ Type[T],+ type(cls.__name__, (cls,), {"_bound_api_params": api_params}),+ )+++class E2B:+ """+ E2B client with an explicitly bound connection configuration.++ The resource classes exposed by the client (`Sandbox`, `Volume`,+ `AsyncVolume`, `Template`, `AsyncTemplate`, `Secret`, `AsyncSecret`) behave+ exactly like the top-level exports of the same name, except the params+ passed to the client are used as the defaults instead of the environment+ variables.+ Per-call params still take precedence over the client's params.++ Multiple clients are fully isolated from each other and from the top-level+ env-configured exports.++ Example:+ ```python+ from e2b_desktop import E2B++ client = E2B(api_key="e2b_...", domain="e2b.dev")++ desktop = client.Sandbox.create()+ desktop.stream.start()+ ```+ """++ def __init__(self, **opts: Unpack[E2BClientParams]):+ """+ Create a new client with the API params bound to it.++ :param opts: API params used as the defaults for every call made+ through this client's resource classes.+ """+ # Params are copied so later mutations of the caller's dicts cannot+ # change the bound configuration.+ api_params = cast(ApiParams, dict(cast(Dict[str, object], opts)))++ headers = api_params.get("headers")+ if headers is not None:+ api_params["headers"] = dict(headers)++ api_headers = api_params.get("api_headers")+ if api_headers is not None:+ api_params["api_headers"] = dict(api_headers)++ self.Sandbox = _bind(Sandbox, api_params)+ """Desktop `Sandbox` class bound to this client's connection configuration."""++ # The resources that are not specific to the Desktop are bound by the+ # core client.+ core = CoreE2B(**api_params)++ self.Volume = core.Volume+ """`Volume` class bound to this client's connection configuration."""++ self.AsyncVolume = core.AsyncVolume+ """`AsyncVolume` class bound to this client's connection configuration."""++ self.Template = core.Template+ """`Template` class bound to this client's connection configuration."""++ self.AsyncTemplate = core.AsyncTemplate+ """`AsyncTemplate` class bound to this client's connection configuration."""++ self.Secret = core.Secret+ """`Secret` class bound to this client's connection configuration."""++ self.AsyncSecret = core.AsyncSecret+ """`AsyncSecret` class bound to this client's connection configuration."""diff --git a/packages/desktop-python/pyproject.toml b/packages/desktop-python/pyproject.tomlindex 5d2ea03e3..2ee427cd9 100644--- a/packages/desktop-python/pyproject.toml+++ b/packages/desktop-python/pyproject.toml@@ -7,7 +7,7 @@ license = "MIT"readme = "README.md"requires-python = ">=3.10"dependencies = [- "e2b>=2.38.0,<3.0.0",+ "e2b>=2.44.0,<3.0.0","requests>=2.32.3,<3","pillow>=12.0.0,<13",]diff --git a/packages/desktop-python/tests/test_client.py b/packages/desktop-python/tests/test_client.pynew file mode 100644index 000000000..7f89d3433--- /dev/null+++ b/packages/desktop-python/tests/test_client.py@@ -0,0 +1,230 @@+import asyncio+import json+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from typing import Dict, List, Tuple++import pytest+from e2b import AsyncSecret, AsyncTemplate, AsyncVolume, Secret, Template, Volume+from e2b.sandbox_sync.commands.command import Commands++from e2b_desktop import E2B, Sandbox++API_KEY_A = "e2b_" + "a" * 40+API_KEY_B = "e2b_" + "b" * 40+ENV_API_KEY = "e2b_" + "e" * 40++DOMAIN_A = "client-a.example.com"+DOMAIN_B = "client-b.example.com"+ENV_DOMAIN = "env.example.com"++SANDBOX_RESPONSE = {+ "templateID": "desktop",+ "sandboxID": "sbx-test",+ "clientID": "client-test",+ "envdVersion": "0.2.0",+}++SECRET_RESPONSE = {+ "secretID": "secret-test",+ "name": "secret",+ "currentVersion": 1,+ "metadata": {},+ "createdAt": "2026-01-01T00:00:00Z",+ "updatedAt": "2026-01-01T00:00:00Z",+}+++class _Handler(BaseHTTPRequestHandler):+ requests: List[Tuple[str, str, Dict[str, str]]] = []++ def log_message(self, *args): # noqa: A003 - silence the default stderr log+ pass++ def _record_and_respond(self, status: int, body):+ type(self).requests.append(+ (self.command, self.path, {k.lower(): v for k, v in self.headers.items()})+ )+ payload = json.dumps(body).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++ def do_POST(self):+ length = int(self.headers.get("Content-Length") or 0)+ if length:+ self.rfile.read(length)++ if self.path.startswith("/sandboxes"):+ self._record_and_respond(201, SANDBOX_RESPONSE)+ elif self.path.startswith("/volumes"):+ self._record_and_respond(+ 201,+ {"volumeID": "vol-test", "name": "vol", "token": "vol-token"},+ )+ elif self.path.startswith("/secrets"):+ self._record_and_respond(201, SECRET_RESPONSE)+ else:+ self._record_and_respond(404, {"code": 404, "message": "not found"})++ def do_GET(self):+ if self.path.startswith("/templates/aliases/"):+ self._record_and_respond(+ 200,+ {"aliases": [], "templateID": "tmpl-test", "public": False},+ )+ else:+ self._record_and_respond(404, {"code": 404, "message": "not found"})+++class _StubHandle:+ def disconnect(self):+ pass+++def api_server(monkeypatch):+ """Local API server, with the env config pointed away from any client's."""+ monkeypatch.setenv("E2B_API_KEY", ENV_API_KEY)+ monkeypatch.setenv("E2B_DOMAIN", ENV_DOMAIN)+ monkeypatch.delenv("E2B_DEBUG", raising=False)++ # Starting the desktop environment talks to envd inside the sandbox, which+ # does not exist for a mocked API. All the API calls carrying the bound+ # configuration happen before it.+ monkeypatch.setattr(Commands, "run", lambda *args, **kwargs: _StubHandle())+ monkeypatch.setattr(Sandbox, "_wait_and_verify", lambda *args, **kwargs: True)+ monkeypatch.setattr(Sandbox, "_start_xfce4", lambda self: None)++ _Handler.requests = []+ server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield f"http://127.0.0.1:{server.server_port}"+ finally:+ server.shutdown()+ server.server_close()+ thread.join()+++def api_keys() -> List[str]:+ return [headers.get("x-api-key", "") for _, _, headers in _Handler.requests]+++def test_client_sandbox_uses_client_config(api_server):+ client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)++ sandbox = client.Sandbox.create()++ assert api_keys() == [API_KEY_A]+ assert sandbox.connection_config.api_key == API_KEY_A+ assert sandbox.connection_config.domain == DOMAIN_A+++def test_client_sandbox_keeps_the_desktop_api(api_server):+ client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)++ assert issubclass(client.Sandbox, Sandbox)+ assert client.Sandbox is not Sandbox+ # Class-level defaults are inherited.+ assert client.Sandbox.default_template == "desktop"++ sandbox = client.Sandbox.create()++ assert isinstance(sandbox, client.Sandbox)+ assert isinstance(sandbox, Sandbox)+ assert callable(sandbox.screenshot)+ assert callable(sandbox.stream.start)+++def test_per_call_params_override_the_client(api_server):+ client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)++ sandbox = client.Sandbox.create(api_key=API_KEY_B, domain=DOMAIN_B)++ assert api_keys() == [API_KEY_B]+ assert sandbox.connection_config.domain == DOMAIN_B+++def test_per_call_params_set_to_none_keep_the_client_config(api_server):+ client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)++ sandbox = client.Sandbox.create(api_key=None, domain=None)++ assert api_keys() == [API_KEY_A]+ assert sandbox.connection_config.api_key == API_KEY_A+ assert sandbox.connection_config.domain == DOMAIN_A+++def test_client_class_can_be_rebound(api_server):+ client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)++ S = client.Sandbox+ sandbox = S.create()++ assert api_keys() == [API_KEY_A]+ assert sandbox.connection_config.api_key == API_KEY_A+++def test_two_clients_stay_isolated(api_server):+ client_a = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)+ client_b = E2B(api_key=API_KEY_B, domain=DOMAIN_B, api_url=api_server)++ sandbox_a = client_a.Sandbox.create()+ sandbox_b = client_b.Sandbox.create()++ assert api_keys() == [API_KEY_A, API_KEY_B]+ assert sandbox_a.connection_config.domain == DOMAIN_A+ assert sandbox_b.connection_config.domain == DOMAIN_B+++def test_client_params_are_copied(api_server):+ opts = {"api_key": API_KEY_A, "domain": DOMAIN_A, "api_url": api_server}+ client = E2B(**opts)+ opts["api_key"] = API_KEY_B++ sandbox = client.Sandbox.create()++ assert api_keys() == [API_KEY_A]+ assert sandbox.connection_config.api_key == API_KEY_A+++def test_core_resources_are_bound_to_the_client(api_server):+ client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)++ volume = client.Volume.create("vol")+ assert isinstance(volume, Volume)+ assert client.Template.exists("tmpl") is True+ client.Secret.create("secret", "value")++ assert api_keys() == [API_KEY_A, API_KEY_A, API_KEY_A]++ async def run():+ await client.AsyncVolume.create("vol")+ assert await client.AsyncTemplate.exists("tmpl") is True+ await client.AsyncSecret.create("secret", "value")++ asyncio.run(run())++ assert issubclass(client.AsyncVolume, AsyncVolume)+ assert issubclass(client.AsyncTemplate, AsyncTemplate)+ assert issubclass(client.AsyncSecret, AsyncSecret)+ assert issubclass(client.Template, Template)+ assert issubclass(client.Secret, Secret)+ assert api_keys() == [API_KEY_A] * 6+++def test_top_level_classes_keep_using_the_env_config(api_server):+ client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)+ client.Sandbox.create()++ sandbox = Sandbox.create(api_url=api_server)++ assert api_keys()[-1] == ENV_API_KEY+ assert sandbox.connection_config.api_key == ENV_API_KEY+ assert sandbox.connection_config.domain == ENV_DOMAIN+ # Creating clients does not bind anything onto the top-level class.+ assert Sandbox._bound_api_params == {}