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 E2B client for multiple bound connection configs (#1720)

devin-ai-integration[bot]5759f17e56ca
diff --git a/.changeset/e2b-multi-client.md b/.changeset/e2b-multi-client.md
new file mode 100644
index 000000000..88304d8fb
--- /dev/null
+++ b/.changeset/e2b-multi-client.md
@@ -0,0 +1,40 @@
+---
+'e2b': minor
+'@e2b/python-sdk': minor
+---
+
+Add an `E2B` client that binds a connection config once and exposes the resource surfaces off it, so a single process can talk to several API keys, domains or deployments. The classes it exposes are per-client subclasses of the real `Sandbox`/`Volume`/`Template`/`Secret` classes, so they behave exactly like the top-level ones — per-call options still win over the client's options, which win over the environment variables. The named top-level exports are unchanged and keep reading the environment.
+
+Nothing existing changes: `Template` is now the `TemplateBase` class made callable as a factory, so `Template(...)`, the statics and `instanceof` keep working, and the default export is still `Sandbox`.
+
+```ts
+import { E2B } from 'e2b'
+
+const { Sandbox, Volume, Template, Secret } = new E2B({
+ apiKey: 'e2b_***',
+ domain: 'e2b.dev',
+})
+
+const sandbox = await Sandbox.create()
+const volume = await Volume.create('my-volume')
+const exists = await Template.exists('my-template')
+await Template.build(Template().fromPythonImage('3'), 'my-env')
+await Secret.create('openai-api-key', 'sk-***')
+```
+
+```python
+from e2b import E2B
+
+client = E2B(api_key="e2b_***", domain="e2b.dev")
+Sandbox, Volume, Template = client.Sandbox, client.Volume, client.Template
+Secret = client.Secret
+
+sandbox = Sandbox.create()
+volume = Volume.create("my-volume")
+exists = Template.exists("my-template")
+secret = Secret.create("openai-api-key", "sk-***")
+
+# Async variants are exposed too.
+AsyncSandbox = client.AsyncSandbox
+async_sandbox = await AsyncSandbox.create()
+```
diff --git a/packages/js-sdk/README.md b/packages/js-sdk/README.md
index 6ba613a72..d9019e89a 100644
--- a/packages/js-sdk/README.md
+++ b/packages/js-sdk/README.md
@@ -38,14 +38,35 @@ E2B_API_KEY=e2b_***
### 3. Start a sandbox and run commands
```ts
-import Sandbox from 'e2b'
+import { Sandbox } from 'e2b'
const sandbox = await Sandbox.create()
const result = await sandbox.commands.run('echo "Hello from E2B!"')
console.log(result.stdout) // Hello from E2B!
```
-### 4. Code execution with Code Interpreter
+### 4. Bind the configuration to a client
+
+The top-level `Sandbox`, `Volume`, `Template` and `Secret` 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 resources it exposes:
+
+```ts
+import { E2B } from 'e2b'
+
+const client = new E2B({ apiKey: 'e2b_***', domain: 'e2b.dev' })
+
+const sandbox = await client.Sandbox.create()
+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. Code execution with Code Interpreter
If you need [`runCode()`](https://e2b.dev/docs/code-interpreting?utm_source=npm&utm_medium=referral&utm_campaign=readme&utm_content=e2b), install the [Code Interpreter SDK](https://github.com/e2b-dev/code-interpreter):
@@ -61,8 +82,8 @@ const execution = await sandbox.runCode('x = 1; x += 1; x')
console.log(execution.text) // outputs 2
```
-### 5. Check docs
+### 6. Check docs
Visit [E2B documentation](https://e2b.dev/docs?utm_source=npm&utm_medium=referral&utm_campaign=readme&utm_content=e2b).
-### 6. E2B cookbook
+### 7. E2B cookbook
Visit 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/js-sdk/src/client.ts b/packages/js-sdk/src/client.ts
new file mode 100644
index 000000000..3ae82dcec
--- /dev/null
+++ b/packages/js-sdk/src/client.ts
@@ -0,0 +1,96 @@
+import { ConnectionOpts } from './connectionConfig'
+import { Sandbox } from './sandbox'
+import { Secret } from './secret'
+import { Template, TemplateBase } from './template'
+import { callableTemplate } from './template/callable'
+import { Volume } from './volume'
+
+/**
+ * Connection options bound to an {@link E2B} client.
+ *
+ * Same as {@link ConnectionOpts} without `signal`, which cancels a single
+ * request and therefore can only be passed per call.
+ */
+export type E2BClientOpts = Omit<ConnectionOpts, 'signal'>
+
+/**
+ * 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'
+ *
+ * const client = new E2B({ apiKey: 'e2b_...', domain: 'e2b.dev' })
+ *
+ * const sandbox = await client.Sandbox.create()
+ * const volumes = await client.Volume.list()
+ * await client.Template.build(client.Template().fromPythonImage('3'), 'my-env')
+ * ```
+ */
+export class E2B {
+ /**
+ * `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
+
+ this.Sandbox = class extends Sandbox {
+ protected static override readonly boundOpts = boundOpts
+ }
+
+ this.Volume = class extends Volume {
+ protected static override readonly boundOpts = boundOpts
+ }
+
+ this.Secret = class extends Secret {
+ protected static override readonly boundOpts = boundOpts
+ }
+
+ this.Template = callableTemplate(
+ class extends TemplateBase {
+ protected static override readonly boundOpts = boundOpts
+ }
+ )
+ }
+}
diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.ts
index c69a0654d..680723f1b 100644
--- a/packages/js-sdk/src/connectionConfig.ts
+++ b/packages/js-sdk/src/connectionConfig.ts
@@ -423,6 +423,43 @@ export class ConnectionConfig {
this.sandboxUrl = opts?.sandboxUrl || ConnectionConfig.sandboxUrl
}
+ /**
+ * Merge connection options bound to a class (e.g. by an `E2B` client) with
+ * the per-call options. Per-call options win, then the bound options, then
+ * the environment variables resolved by the `ConnectionConfig` constructor.
+ *
+ * Explicitly `undefined` per-call values are dropped so they fall back to the
+ * bound options instead of clearing them.
+ *
+ * @internal
+ * @hidden
+ * @hide
+ */
+ static mergeOpts<T extends ConnectionOpts>(
+ boundOpts: ConnectionOpts | undefined,
+ opts?: T
+ ): T | undefined {
+ if (!boundOpts) {
+ return opts
+ }
+
+ const merged: Record<string, unknown> = { ...boundOpts }
+ for (const [key, value] of Object.entries(opts ?? {})) {
+ if (value !== undefined) {
+ // `defineProperty` so a `__proto__` key (e.g. from parsed JSON) becomes
+ // a plain own property instead of changing the prototype.
+ Object.defineProperty(merged, key, {
+ value,
+ enumerable: true,
+ writable: true,
+ configurable: true,
+ })
+ }
+ }
+
+ return merged as T
+ }
+
private static get domain() {
return getEnvVar('E2B_DOMAIN') || 'e2b.app'
}
@@ -499,6 +536,44 @@ export class ConnectionConfig {
}
}
+/**
+ * Base class for the resource classes (`Sandbox`, `Volume`, `Template`,
+ * `Secret`) whose static methods build a `ConnectionConfig` from per-call
+ * options. An {@link E2B} client exposes subclasses of these with its own
+ * options bound, and every static method resolves them through
+ * {@link ClientFactory.resolveOpts}.
+ *
+ * @internal
+ * @hidden
+ * @hide
+ */
+export class ClientFactory {
+ /**
+ * Connection options bound to this class by an {@link E2B} client.
+ *
+ * Empty on the base classes, so the env-configured default path is unchanged.
+ *
+ * @internal
+ * @hidden
+ * @hide
+ */
+ protected static readonly boundOpts?: Omit<ConnectionOpts, 'signal'>
+
+ /**
+ * Merge the connection options bound to this class with the per-call options,
+ * with the per-call options taking precedence.
+ *
+ * @internal
+ * @hidden
+ * @hide
+ */
+ protected static resolveOpts<T extends ConnectionOpts>(
+ opts?: T
+ ): T | undefined {
+ return ConnectionConfig.mergeOpts(this.boundOpts, opts)
+ }
+}
+
/**
* User used for the operation in the sandbox.
*/
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index 921087d2b..b2c321834 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -156,6 +156,8 @@ export type {
export { Sandbox }
import { Sandbox } from './sandbox'
+export { E2B, type E2BClientOpts } from './client'
+
export default Sandbox
export * from './template'
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index 37f97c695..4ae2e8e56 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -243,7 +243,7 @@ export class Sandbox extends SandboxApi {
* `await paginator.nextItems()` while `paginator.hasNext` is `true`.
*/
static list(opts?: SandboxListOpts): SandboxPaginator {
- return new SandboxPaginator(opts)
+ return new SandboxPaginator(this.resolveOpts(opts))
}
/**
@@ -303,7 +303,8 @@ export class Sandbox extends SandboxApi {
sandboxOpts: templateOrOpts,
}
- const config = new ConnectionConfig(sandboxOpts)
+ const apiOpts = this.resolveOpts(sandboxOpts)
+ const config = new ConnectionConfig(apiOpts)
if (config.debug) {
return new this({
sandboxId: 'debug_sandbox_id',
@@ -312,10 +313,10 @@ export class Sandbox extends SandboxApi {
}) as InstanceType<S>
}
- const sandboxInfo = await SandboxApi.createSandbox(
+ const sandboxInfo = await this.createSandbox(
template,
- sandboxOpts?.timeoutMs ?? this.defaultSandboxTimeoutMs,
- sandboxOpts
+ apiOpts?.timeoutMs ?? this.defaultSandboxTimeoutMs,
+ apiOpts
)
const sandbox = new this({ ...sandboxInfo, ...config }) as InstanceType<S>
@@ -369,7 +370,8 @@ export class Sandbox extends SandboxApi {
sandboxId: string,
opts?: SandboxConnectOpts
): Promise<InstanceType<S>> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
if (config.debug) {
return new this({
sandboxId,
@@ -378,7 +380,7 @@ export class Sandbox extends SandboxApi {
}) as InstanceType<S>
}
- const sandbox = await SandboxApi.connectSandbox(sandboxId, opts)
+ const sandbox = await this.connectSandbox(sandboxId, apiOpts)
return new this({
sandboxId,
@@ -424,13 +426,14 @@ export class Sandbox extends SandboxApi {
sandboxId: string,
opts?: SandboxForkOpts
): Promise<Array<InstanceType<S> | Error>> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
- const results = await SandboxApi.forkSandbox(
+ const results = await this.forkSandbox(
sandboxId,
- opts?.timeoutMs ?? this.defaultSandboxTimeoutMs,
- opts?.count ?? 1,
- opts
+ apiOpts?.timeoutMs ?? this.defaultSandboxTimeoutMs,
+ apiOpts?.count ?? 1,
+ apiOpts
)
return results.map((result) =>
@@ -885,10 +888,10 @@ export class Sandbox extends SandboxApi {
private resolveApiOpts<T extends ConnectionOpts>(
opts?: T
): ConnectionOpts & T {
- return {
- ...this.connectionConfig,
- ...(opts ?? {}),
- } as ConnectionOpts & T
+ return ConnectionConfig.mergeOpts(
+ this.connectionConfig,
+ opts
+ ) as ConnectionOpts & T
}
private fileUrl(path: string | undefined, username: string | undefined) {
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index 565655535..e3dcafce8 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -1,5 +1,6 @@
import { ApiClient, apiErrorFromCode, components, handleApiError } from '../api'
import {
+ ClientFactory,
ConnectionConfig,
ConnectionOpts,
DEFAULT_SANDBOX_TIMEOUT_MS,
@@ -1149,8 +1150,10 @@ function buildNetworkUpdateBody(
: {}),
}
}
-export class SandboxApi {
- protected constructor() {}
+export class SandboxApi extends ClientFactory {
+ protected constructor() {
+ super()
+ }
/**
* Kill the sandbox specified by sandbox ID.
@@ -1164,7 +1167,8 @@ export class SandboxApi {
sandboxId: string,
opts?: SandboxApiOpts
): Promise<boolean> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
if (config.debug) {
// Skip killing the sandbox in debug mode
@@ -1179,7 +1183,7 @@ export class SandboxApi {
sandboxID: sandboxId,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.error?.code === 404) {
@@ -1206,7 +1210,8 @@ export class SandboxApi {
sandboxId: string,
opts?: SandboxApiOpts
): Promise<SandboxInfo> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.GET('/sandboxes/{sandboxID}', {
@@ -1215,7 +1220,7 @@ export class SandboxApi {
sandboxID: sandboxId,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.error?.code === 404) {
@@ -1291,7 +1296,8 @@ export class SandboxApi {
sandboxId: string,
opts?: SandboxMetricsOpts
): Promise<SandboxMetrics[]> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
if (config.debug) {
// Skip getting the metrics in debug mode
@@ -1301,10 +1307,12 @@ export class SandboxApi {
const client = new ApiClient(config)
// JS timestamp is in milliseconds, convert to unix (seconds)
- const start = opts?.start
- ? Math.round(opts.start.getTime() / 1000)
+ const start = apiOpts?.start
+ ? Math.round(apiOpts.start.getTime() / 1000)
+ : undefined
+ const end = apiOpts?.end
+ ? Math.round(apiOpts.end.getTime() / 1000)
: undefined
- const end = opts?.end ? Math.round(opts.end.getTime() / 1000) : undefined
const res = await client.api.GET('/sandboxes/{sandboxID}/metrics', {
params: {
path: {
@@ -1315,7 +1323,7 @@ export class SandboxApi {
end,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.error?.code === 404) {
@@ -1358,7 +1366,8 @@ export class SandboxApi {
timeoutMs: number,
opts?: SandboxApiOpts
): Promise<void> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.POST('/sandboxes/{sandboxID}/timeout', {
@@ -1370,7 +1379,7 @@ export class SandboxApi {
body: {
timeout: timeoutToSeconds(timeoutMs),
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.error?.code === 404) {
@@ -1398,7 +1407,8 @@ export class SandboxApi {
network: SandboxNetworkUpdate,
opts?: SandboxApiOpts
): Promise<void> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.PUT('/sandboxes/{sandboxID}/network', {
@@ -1408,7 +1418,7 @@ export class SandboxApi {
},
},
body: buildNetworkUpdateBody(network),
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.error?.code === 404) {
@@ -1433,7 +1443,8 @@ export class SandboxApi {
sandboxId: string,
opts?: SandboxPauseOpts
): Promise<boolean> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.POST('/sandboxes/{sandboxID}/pause', {
@@ -1443,9 +1454,9 @@ export class SandboxApi {
},
},
body: {
- memory: opts?.keepMemory ?? true,
+ memory: apiOpts?.keepMemory ?? true,
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.error?.code === 404) {
@@ -1491,7 +1502,8 @@ export class SandboxApi {
sandboxId: string,
opts?: CreateSnapshotOpts
): Promise<SnapshotInfo> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.POST('/sandboxes/{sandboxID}/snapshots', {
@@ -1500,8 +1512,8 @@ export class SandboxApi {
sandboxID: sandboxId,
},
},
- body: opts?.name ? { name: opts.name } : {},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ body: apiOpts?.name ? { name: apiOpts.name } : {},
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.error?.code === 404) {
@@ -1527,7 +1539,7 @@ export class SandboxApi {
* @returns paginator for listing snapshots.
*/
static listSnapshots(opts?: SnapshotListOpts): SnapshotPaginator {
- return new SnapshotPaginator(opts)
+ return new SnapshotPaginator(this.resolveOpts(opts))
}
/**
@@ -1542,7 +1554,8 @@ export class SandboxApi {
snapshotId: string,
opts?: SandboxApiOpts
): Promise<boolean> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.DELETE('/templates/{templateID}', {
@@ -1551,7 +1564,7 @@ export class SandboxApi {
templateID: snapshotId,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.error?.code === 404) {
@@ -1571,7 +1584,8 @@ export class SandboxApi {
timeoutMs: number,
opts?: SandboxOpts
) {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
// onTimeout accepts a bare action (`'pause'` / `'kill'`) or the object form
// `{ action, keepMemory }`. The discriminated union type forbids `keepMemory`
@@ -1644,7 +1658,7 @@ export class SandboxApi {
const res = await client.api.POST('/sandboxes', {
body,
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
const err = handleApiError(res)
@@ -1653,7 +1667,7 @@ export class SandboxApi {
}
if (compareVersions(res.data!.envdVersion, '0.1.0') < 0) {
- await this.kill(res.data!.sandboxID, opts)
+ await this.kill(res.data!.sandboxID, apiOpts)
throw new TemplateError(
'You need to update the template to use the new SDK.'
)
@@ -1678,7 +1692,8 @@ export class SandboxApi {
throw new InvalidArgumentError('count must be at least 1')
}
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.POST('/sandboxes/{sandboxID}/fork', {
@@ -1691,7 +1706,7 @@ export class SandboxApi {
timeout: timeoutToSeconds(timeoutMs),
count,
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
// check the status, not the parsed error body — openapi-fetch leaves
@@ -1740,9 +1755,10 @@ export class SandboxApi {
sandboxId: string,
opts?: SandboxConnectOpts
) {
- const timeoutMs = opts?.timeoutMs ?? DEFAULT_SANDBOX_TIMEOUT_MS
+ const apiOpts = this.resolveOpts(opts)
+ const timeoutMs = apiOpts?.timeoutMs ?? DEFAULT_SANDBOX_TIMEOUT_MS
- const config = new ConnectionConfig(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.POST('/sandboxes/{sandboxID}/connect', {
@@ -1754,7 +1770,7 @@ export class SandboxApi {
body: {
timeout: timeoutToSeconds(timeoutMs),
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.error?.code === 404) {
@@ -1814,7 +1830,8 @@ export class SandboxPaginator extends Paginator<SandboxInfo, SandboxApiOpts> {
metadata = new URLSearchParams(encodedPairs).toString()
}
- const config = new ConnectionConfig({ ...this.opts, ...opts })
+ const apiOpts = ConnectionConfig.mergeOpts(this.opts, opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.GET('/v2/sandboxes', {
@@ -1826,7 +1843,7 @@ export class SandboxPaginator extends Paginator<SandboxInfo, SandboxApiOpts> {
nextToken: this.nextToken,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
const err = handleApiError(res)
@@ -1882,7 +1899,8 @@ export class SnapshotPaginator extends Paginator<SnapshotInfo, SandboxApiOpts> {
throw new Error('No more items to fetch')
}
- const config = new ConnectionConfig({ ...this.opts, ...opts })
+ const apiOpts = ConnectionConfig.mergeOpts(this.opts, opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.GET('/snapshots', {
@@ -1894,7 +1912,7 @@ export class SnapshotPaginator extends Paginator<SnapshotInfo, SandboxApiOpts> {
nextToken: this.nextToken,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
const err = handleApiError(res)
diff --git a/packages/js-sdk/src/secret.ts b/packages/js-sdk/src/secret.ts
index fbe648f0f..37ae24bea 100644
--- a/packages/js-sdk/src/secret.ts
+++ b/packages/js-sdk/src/secret.ts
@@ -1,5 +1,9 @@
import { ApiClient, components, handleApiError } from './api'
-import { ConnectionConfig, ConnectionOpts } from './connectionConfig'
+import {
+ ClientFactory,
+ ConnectionConfig,
+ ConnectionOpts,
+} from './connectionConfig'
import {
InvalidArgumentError,
SecretError,
@@ -118,7 +122,8 @@ export class SecretPaginator extends Paginator<SecretInfo> {
throw new Error('No more items to fetch')
}
- const config = new ConnectionConfig({ ...this.opts, ...opts })
+ const apiOpts = ConnectionConfig.mergeOpts(this.opts, opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.GET('/secrets', {
@@ -128,7 +133,7 @@ export class SecretPaginator extends Paginator<SecretInfo> {
nextToken: this.nextToken,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
const err = handleApiError(res, SecretError)
@@ -148,7 +153,7 @@ export class SecretPaginator extends Paginator<SecretInfo> {
* Secret values are write-only: they are accepted by {@link Secret.create}
* and {@link Secret.update} but never returned by any read surface.
*/
-export class Secret {
+export class Secret extends ClientFactory {
/**
* Create a new secret and its first value.
*
@@ -164,16 +169,17 @@ export class Secret {
value: string,
opts?: SecretCreateOpts
): Promise<SecretInfo> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.POST('/secrets', {
body: {
name,
value,
- metadata: opts?.metadata,
+ metadata: apiOpts?.metadata,
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
const err = handleApiError(res, SecretError)
@@ -203,7 +209,8 @@ export class Secret {
value: string,
opts?: SecretUpdateOpts
): Promise<SecretInfo> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.POST('/secrets/{secretID}', {
@@ -214,9 +221,9 @@ export class Secret {
},
body: {
value,
- metadata: opts?.metadata,
+ metadata: apiOpts?.metadata,
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.response.status === 404) {
@@ -248,7 +255,8 @@ export class Secret {
secret: string,
opts?: SecretGetInfoOpts
): Promise<SecretInfo> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.GET('/secrets/{secretID}', {
@@ -257,7 +265,7 @@ export class Secret {
secretID: secret,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.response.status === 404) {
@@ -293,7 +301,7 @@ export class Secret {
* ```
*/
static list(opts?: SecretListOpts): SecretPaginator {
- return new SecretPaginator(opts)
+ return new SecretPaginator(this.resolveOpts(opts))
}
/**
@@ -309,7 +317,7 @@ export class Secret {
opts?: SecretExistsOpts
): Promise<boolean> {
try {
- await Secret.getInfo(secret, opts)
+ await this.getInfo(secret, opts)
return true
} catch (err) {
if (err instanceof SecretNotFoundError) {
@@ -331,7 +339,8 @@ export class Secret {
secret: string,
opts?: SecretDestroyOpts
): Promise<boolean> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.DELETE('/secrets/{secretID}', {
@@ -340,7 +349,7 @@ export class Secret {
secretID: secret,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.response.status === 404) {
diff --git a/packages/js-sdk/src/template/callable.ts b/packages/js-sdk/src/template/callable.ts
new file mode 100644
index 000000000..82f177b5f
--- /dev/null
+++ b/packages/js-sdk/src/template/callable.ts
@@ -0,0 +1,62 @@
+import type { TemplateBase } from './index'
+import type { TemplateFromImage, TemplateOptions } from './types'
+
+/**
+ * A template class that can also be called without `new`.
+ *
+ * @internal
+ * @hidden
+ * @hide
+ */
+export type CallableTemplate<T extends typeof TemplateBase> = T &
+ ((options?: TemplateOptions) => TemplateFromImage)
+
+/**
+ * Make a template class callable as a factory, so `Template(opts)` keeps
+ * returning a builder, and keep the statics usable when they are pulled off the
+ * class on their own (`const { build } = Template`). Everything else —
+ * construction, `instanceof`, subclassing — goes straight to the class.
+ *
+ * @internal
+ * @hidden
+ * @hide
+ */
+export function callableTemplate<T extends typeof TemplateBase>(
+ cls: T
+): CallableTemplate<T> {
+ const bound = new WeakMap<object, Map<PropertyKey, unknown>>()
+
+ return new Proxy(cls, {
+ apply(target, _thisArg, args: [TemplateOptions?]) {
+ return new target(...args)
+ },
+ get(target, prop, receiver) {
+ const value = Reflect.get(target, prop, receiver)
+
+ if (prop === 'prototype' || typeof value !== 'function') {
+ return value
+ }
+
+ // Statics resolve their options off the class they are called on, so they
+ // are bound to it to keep working detached from it. The class accessed
+ // through a subclass is the subclass, so its own options are kept.
+ const self = (
+ typeof receiver === 'function' ? receiver : target
+ ) as object
+
+ let methods = bound.get(self)
+ if (!methods) {
+ methods = new Map()
+ bound.set(self, methods)
+ }
+
+ let method = methods.get(prop)
+ if (!method) {
+ method = value.bind(self)
+ methods.set(prop, method)
+ }
+
+ return method
+ },
+ }) as CallableTemplate<T>
+}
diff --git a/packages/js-sdk/src/template/index.ts b/packages/js-sdk/src/template/index.ts
index 36a16f886..1b712c18a 100644
--- a/packages/js-sdk/src/template/index.ts
+++ b/packages/js-sdk/src/template/index.ts
@@ -1,8 +1,13 @@
import type { PathLike } from 'node:fs'
import { ApiClient } from '../api'
-import { ConnectionConfig, ConnectionOpts } from '../connectionConfig'
+import {
+ ClientFactory,
+ ConnectionConfig,
+ ConnectionOpts,
+} from '../connectionConfig'
import { BuildError, InvalidArgumentError } from '../errors'
import { runtime, shellQuote } from '../utils'
+import { callableTemplate } from './callable'
import {
assignTags,
checkAliasExists,
@@ -50,39 +55,14 @@ import {
} from './utils'
/**
- * Base class for building E2B sandbox templates.
+ * Builder for E2B sandbox templates, and the entrypoint for the template API.
+ *
+ * Exposed as {@link Template}, which can be called as a factory.
*/
export class TemplateBase
+ extends ClientFactory
implements TemplateFromImage, TemplateBuilder, TemplateFinal
{
- /**
- * Connection options bound to this class, used as defaults for every
- * operation that talks to the API. Undefined here, so the config comes from
- * per-call options and environment variables; per-client subclasses bind
- * their own options.
- *
- * @internal
- * @hidden
- * @hide
- */
- protected static readonly boundOpts?: Omit<ConnectionOpts, 'signal'>
-
- /**
- * Layer per-call options over the options bound to the class. Per-call
- * options explicitly set to `undefined` don't clear the bound ones.
- *
- * @internal
- * @hidden
- * @hide
- */
- protected static resolveOpts<T extends ConnectionOpts>(opts?: T): T {
- const perCallOpts = Object.fromEntries(
- Object.entries(opts ?? {}).filter(([, value]) => value !== undefined)
- )
-
- return { ...this.boundOpts, ...perCallOpts } as T
- }
-
private defaultBaseImage: string = 'e2bdev/base'
private baseImage: string | undefined = this.defaultBaseImage
private baseTemplate: string | undefined = undefined
@@ -100,6 +80,7 @@ export class TemplateBase
private stackTraces: (string | undefined)[] = []
constructor(options?: TemplateOptions) {
+ super()
this.fileContextPath =
options?.fileContextPath ??
(runtime === 'browser' ? '.' : (getCallerDirectory() ?? '.'))
@@ -186,7 +167,7 @@ export class TemplateBase
options
)
- const buildOpts = this.resolveOpts(buildOptions)
+ const buildOpts = this.resolveOpts(buildOptions) ?? {}
try {
buildOpts.onBuildLogs?.(new LogEntryStart(new Date(), 'Build started'))
@@ -270,7 +251,7 @@ export class TemplateBase
options
)
- const buildOpts = this.resolveOpts(buildOptions)
+ const buildOpts = this.resolveOpts(buildOptions) ?? {}
const config = new ConnectionConfig(buildOpts)
const client = new ApiClient(config)
@@ -1285,10 +1266,16 @@ export class TemplateBase
}
/**
- * Create a new E2B template builder instance.
+ * Builder and API entrypoint for E2B sandbox templates.
*
- * @param options Optional configuration for the template builder
- * @returns A new template builder instance
+ * `Template` is the {@link TemplateBase} class, wrapped so it can also be
+ * called as a factory returning a builder. The statics (`Template.build`,
+ * `Template.exists`, …) resolve their connection options off the class they are
+ * called on — so a subclass can bind its own defaults.
+ *
+ * @param options Optional builder options, e.g. the file context path used to
+ * resolve relative paths passed to `copy`
+ * @returns A template builder
*
* @example
* ```ts
@@ -1302,29 +1289,7 @@ export class TemplateBase
* await Template.build(template, 'my-python-app:v1.0')
* ```
*/
-export function Template(options?: TemplateOptions): TemplateFromImage {
- return new TemplateBase(options)
-}
-
-/**
- * The statics resolve their connection options off `this`, so they are bound to
- * `TemplateBase` (which carries no bound options) when re-exposed as plain
- * properties of the `Template` factory function.
- */
-function boundToBase<T extends (...args: never[]) => unknown>(fn: T): T {
- return fn.bind(TemplateBase) as T
-}
-
-Template.build = boundToBase(TemplateBase.build)
-Template.buildInBackground = boundToBase(TemplateBase.buildInBackground)
-Template.getBuildStatus = boundToBase(TemplateBase.getBuildStatus)
-Template.exists = boundToBase(TemplateBase.exists)
-Template.aliasExists = boundToBase(TemplateBase.aliasExists)
-Template.assignTags = boundToBase(TemplateBase.assignTags)
-Template.removeTags = boundToBase(TemplateBase.removeTags)
-Template.getTags = boundToBase(TemplateBase.getTags)
-Template.toJSON = TemplateBase.toJSON
-Template.toDockerfile = TemplateBase.toDockerfile
+export const Template = callableTemplate(TemplateBase)
export type {
BuildInfo,
diff --git a/packages/js-sdk/src/volume/index.ts b/packages/js-sdk/src/volume/index.ts
index c3c54b508..93c307168 100644
--- a/packages/js-sdk/src/volume/index.ts
+++ b/packages/js-sdk/src/volume/index.ts
@@ -7,6 +7,7 @@ import {
FILE_TIMEOUT_MS,
} from './client'
import {
+ ClientFactory,
ConnectionConfig,
ConnectionOpts,
setupRequestController,
@@ -51,7 +52,7 @@ function convertVolumeEntryStat(
* Create a `Volume` instance to interact with a volume by its ID,
* or use the static methods to manage volumes.
*/
-export class Volume {
+export class Volume extends ClientFactory {
/**
* Volume ID.
*/
@@ -100,6 +101,7 @@ export class Volume {
debug?: boolean,
proxy?: string
) {
+ super()
this.volumeId = volumeId
this.name = name
this.token = token
@@ -116,15 +118,20 @@ export class Volume {
*
* @returns new Volume instance.
*/
- static async create(name: string, opts?: ConnectionOpts): Promise<Volume> {
- const config = new ConnectionConfig(opts)
+ static async create<V extends typeof Volume>(
+ this: V,
+ name: string,
+ opts?: ConnectionOpts
+ ): Promise<InstanceType<V>> {
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.POST('/volumes', {
body: {
name,
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
const err = handleApiError(res, VolumeError)
@@ -136,14 +143,14 @@ export class Volume {
throw new Error('Response data is missing')
}
- return new Volume(
+ return new this(
res.data.volumeID,
res.data.name,
res.data.token,
res.data.domain || config.domain,
config.debug,
config.proxy
- )
+ ) as InstanceType<V>
}
/**
@@ -154,20 +161,22 @@ export class Volume {
*
* @returns Volume instance.
*/
- static async connect(
+ static async connect<V extends typeof Volume>(
+ this: V,
volumeId: string,
opts?: ConnectionOpts
- ): Promise<Volume> {
- const config = new ConnectionConfig(opts)
- const { name, token, domain } = await Volume.getInfo(volumeId, opts)
- return new Volume(
+ ): Promise<InstanceType<V>> {
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
+ const { name, token, domain } = await this.getInfo(volumeId, apiOpts)
+ return new this(
volumeId,
name,
token,
domain ?? config.domain,
config.debug,
config.proxy
- )
+ ) as InstanceType<V>
}
/**
@@ -182,7 +191,8 @@ export class Volume {
volumeId: string,
opts?: ConnectionOpts
): Promise<VolumeAndToken> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.GET('/volumes/{volumeID}', {
@@ -191,7 +201,7 @@ export class Volume {
volumeID: volumeId,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.response.status === 404) {
@@ -219,11 +229,12 @@ export class Volume {
* @returns list of volume information.
*/
static async list(opts?: ConnectionOpts): Promise<VolumeInfo[]> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.GET('/volumes', {
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
const err = handleApiError(res, VolumeError)
@@ -247,7 +258,8 @@ export class Volume {
volumeId: string,
opts?: ConnectionOpts
): Promise<boolean> {
- const config = new ConnectionConfig(opts)
+ const apiOpts = this.resolveOpts(opts)
+ const config = new ConnectionConfig(apiOpts)
const client = new ApiClient(config)
const res = await client.api.DELETE('/volumes/{volumeID}', {
@@ -256,7 +268,7 @@ export class Volume {
volumeID: volumeId,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(apiOpts?.requestTimeoutMs, apiOpts?.signal),
})
if (res.response.status === 404) {
diff --git a/packages/js-sdk/tests/client.test.ts b/packages/js-sdk/tests/client.test.ts
new file mode 100644
index 000000000..bb7f47280
--- /dev/null
+++ b/packages/js-sdk/tests/client.test.ts
@@ -0,0 +1,394 @@
+import { afterAll, afterEach, assert, beforeAll, expect, test } from 'vitest'
+import { http, HttpResponse } from 'msw'
+import { setupServer } from 'msw/node'
+
+import DefaultExport, {
+ type ConnectionOpts,
+ E2B,
+ Sandbox,
+ Secret,
+ Template,
+ TemplateBase,
+ Volume,
+} from '../src'
+import { TEST_API_KEY } from './setup'
+
+const API_KEY_A = `e2b_${'a'.repeat(40)}`
+const API_KEY_B = `e2b_${'b'.repeat(40)}`
+
+const DOMAIN_A = 'client-a.test'
+const DOMAIN_B = 'client-b.test'
+const DOMAIN_ENV = 'env.test'
+
+interface RecordedRequest {
+ url: string
+ apiKey?: string
+}
+
+const requests: RecordedRequest[] = []
+
+function record(request: Request) {
+ requests.push({
+ url: request.url,
+ apiKey: request.headers.get('X-API-KEY') ?? undefined,
+ })
+}
+
+const lastRequest = () => requests[requests.length - 1]
+
+const sandboxResponse = {
+ sandboxID: 'test-sandbox-id',
+ templateID: 'base',
+ envdVersion: '0.2.4',
+}
+
+const secretResponse = {
+ secretID: 'test-secret-id',
+ name: 'test-secret',
+ currentVersion: 1,
+ metadata: {},
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+}
+
+const server = setupServer(
+ http.post(/\/sandboxes$/, async ({ request }) => {
+ record(request)
+ return HttpResponse.json(sandboxResponse)
+ }),
+ http.delete(/\/sandboxes\/[^/]+$/, ({ request }) => {
+ record(request)
+ return new HttpResponse(null, { status: 204 })
+ }),
+ http.get(/\/v2\/sandboxes/, ({ request }) => {
+ record(request)
+ return HttpResponse.json([])
+ }),
+ http.post(/\/volumes$/, ({ request }) => {
+ record(request)
+ return HttpResponse.json({
+ volumeID: 'test-volume-id',
+ name: 'test-volume',
+ token: 'test-volume-token',
+ })
+ }),
+ http.get(/\/volumes$/, ({ request }) => {
+ record(request)
+ return HttpResponse.json([])
+ }),
+ http.get(/\/templates\/aliases\/[^/]+$/, ({ request }) => {
+ record(request)
+ return HttpResponse.json({ aliases: [], templateID: 'test-template-id' })
+ }),
+ http.get(/\/templates\/[^/]+\/tags$/, ({ request }) => {
+ record(request)
+ return HttpResponse.json([])
+ }),
+ http.post(/\/secrets$/, ({ request }) => {
+ record(request)
+ return HttpResponse.json(secretResponse)
+ }),
+ http.get(/\/secrets$/, ({ request }) => {
+ record(request)
+ return HttpResponse.json([secretResponse])
+ }),
+ http.get(/\/secrets\/[^/]+$/, ({ request }) => {
+ record(request)
+ return HttpResponse.json(secretResponse)
+ })
+)
+
+const envBackup: Record<string, string | undefined> = {}
+const envOverrides = {
+ E2B_DOMAIN: DOMAIN_ENV,
+ E2B_API_KEY: TEST_API_KEY,
+ E2B_API_URL: undefined,
+ E2B_SANDBOX_URL: undefined,
+ E2B_DEBUG: undefined,
+}
+
+beforeAll(() => {
+ 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
+ }
+ }
+
+ server.listen({ onUnhandledRequest: 'error' })
+})
+
+afterAll(() => {
+ server.close()
+
+ for (const [key, value] of Object.entries(envBackup)) {
+ if (value === undefined) {
+ delete process.env[key]
+ } else {
+ process.env[key] = value
+ }
+ }
+})
+
+afterEach(() => {
+ requests.length = 0
+ server.resetHandlers()
+})
+
+test('client.Sandbox.create uses the client config instead of env vars', async () => {
+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })
+
+ const sandbox = await client.Sandbox.create()
+
+ assert.equal(lastRequest().url, `https://api.${DOMAIN_A}/sandboxes`)
+ assert.equal(lastRequest().apiKey, API_KEY_A)
+ // The bound config is also carried by the created sandbox instance.
+ assert.equal(sandbox.sandboxDomain, DOMAIN_A)
+})
+
+test('client.Sandbox instances are subclass instances of Sandbox', async () => {
+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })
+
+ assert.notEqual(client.Sandbox, Sandbox)
+ assert.isTrue(client.Sandbox.prototype instanceof Sandbox)
+ assert.instanceOf(await client.Sandbox.create(), Sandbox)
+ // Class-level defaults are inherited from Sandbox.
+ assert.equal(lastRequest().url, `https://api.${DOMAIN_A}/sandboxes`)
+})
+
+test('per-call options take precedence over the client config', async () => {
+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })
+
+ await client.Sandbox.create({ apiKey: API_KEY_B, domain: DOMAIN_B })
+
+ assert.equal(lastRequest().url, `https://api.${DOMAIN_B}/sandboxes`)
+ assert.equal(lastRequest().apiKey, API_KEY_B)
+})
+
+test('client.Sandbox can be rebound to a variable', async () => {
+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })
+ const S = client.Sandbox
+
+ await S.create()
+ await S.kill('test-sandbox-id')
+ await S.list().nextItems()
+
+ for (const request of requests) {
+ expect(request.url).toContain(`api.${DOMAIN_A}`)
+ assert.equal(request.apiKey, API_KEY_A)
+ }
+})
+
+test('two clients with different configs stay isolated', async () => {
+ const clientA = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })
+ const clientB = new E2B({ apiKey: API_KEY_B, domain: DOMAIN_B })
+
+ await clientA.Sandbox.create()
+ await clientB.Sandbox.create()
+
+ assert.deepEqual(
+ requests.map((r) => [r.url, r.apiKey]),
+ [
+ [`https://api.${DOMAIN_A}/sandboxes`, API_KEY_A],
+ [`https://api.${DOMAIN_B}/sandboxes`, API_KEY_B],
+ ]
+ )
+})
+
+test('mutating the options object does not change the bound config', async () => {
+ const opts = { apiKey: API_KEY_A, domain: DOMAIN_A }
+ const client = new E2B(opts)
+ opts.domain = DOMAIN_B
+
+ await client.Sandbox.create()
+
+ assert.equal(lastRequest().url, `https://api.${DOMAIN_A}/sandboxes`)
+})
+
+test('per-call options explicitly set to undefined keep the client config', async () => {
+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })
+
+ await client.Sandbox.create({ apiKey: undefined, domain: undefined })
+ assert.equal(lastRequest().url, `https://api.${DOMAIN_A}/sandboxes`)
+ assert.equal(lastRequest().apiKey, API_KEY_A)
+
+ await client.Sandbox.list().nextItems({ domain: undefined })
+ expect(lastRequest().url).toContain(`api.${DOMAIN_A}`)
+ assert.equal(lastRequest().apiKey, API_KEY_A)
+
+ const sandbox = await client.Sandbox.create()
+ await sandbox.kill({ apiKey: undefined })
+ assert.equal(lastRequest().apiKey, API_KEY_A)
+})
+
+test('a signal is not bound to the client', async () => {
+ const controller = new AbortController()
+ const opts: ConnectionOpts = {
+ apiKey: API_KEY_A,
+ domain: DOMAIN_A,
+ signal: controller.signal,
+ }
+ const client = new E2B(opts)
+ controller.abort()
+
+ await client.Sandbox.create()
+
+ assert.equal(lastRequest().url, `https://api.${DOMAIN_A}/sandboxes`)
+})
+
+test('a __proto__ option does not pollute the prototype', async () => {
+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })
+
+ await client.Sandbox.create(
+ JSON.parse('{"__proto__": {"polluted": "yes"}}') as Record<string, never>
+ )
+
+ assert.isUndefined(({} as Record<string, unknown>).polluted)
+ assert.equal(lastRequest().url, `https://api.${DOMAIN_A}/sandboxes`)
+})
+
+test('Template statics work detached from the class', async () => {
+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })
+ const { exists: clientExists } = client.Template
+ const { exists } = Template
+
+ await clientExists('test-template')
+ assert.equal(lastRequest().apiKey, API_KEY_A)
+
+ await exists('test-template')
+ assert.equal(lastRequest().apiKey, TEST_API_KEY)
+})
+
+test('client.Volume.create uses the client config', async () => {
+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })
+
+ const volume = await client.Volume.create('test-volume')
+
+ assert.equal(lastRequest().url, `https://api.${DOMAIN_A}/volumes`)
+ assert.equal(lastRequest().apiKey, API_KEY_A)
+ assert.instanceOf(volume, Volume)
+ assert.instanceOf(volume, client.Volume)
+ assert.equal(volume.domain, DOMAIN_A)
+
+ await client.Volume.list()
+ assert.equal(lastRequest().url, `https://api.${DOMAIN_A}/volumes`)
+})
+
+test('client.Template statics use the client config', async () => {
+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })
+
+ await client.Template.exists('test-template')
+ await client.Template.getTags('test-template-id')
+
+ for (const request of requests) {
+ expect(request.url).toContain(`api.${DOMAIN_A}`)
+ assert.equal(request.apiKey, API_KEY_A)
+ }
+
+ // Per-call options still win.
+ await client.Template.getTags('test-template-id', {
+ apiKey: API_KEY_B,
+ domain: DOMAIN_B,
+ })
+ assert.equal(
+ lastRequest().url,
+ `https://api.${DOMAIN_B}/templates/test-template-id/tags`
+ )
+ assert.equal(lastRequest().apiKey, API_KEY_B)
+})
+
+test('client.Template builds template instances', async () => {
+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })
+ const template = client.Template().fromPythonImage('3')
+
+ assert.instanceOf(template, TemplateBase)
+ assert.instanceOf(template, client.Template)
+ assert.instanceOf(new client.Template(), client.Template)
+ assert.equal(
+ await client.Template.toDockerfile(template),
+ await Template.toDockerfile(Template().fromPythonImage('3'))
+ )
+})
+
+test('client.Template can be rebound to a variable', async () => {
+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })
+ const T = client.Template
+
+ await T.exists('test-template')
+
+ assert.equal(
+ lastRequest().url,
+ `https://api.${DOMAIN_A}/templates/aliases/test-template`
+ )
+ assert.equal(lastRequest().apiKey, API_KEY_A)
+})
+
+test('client.Secret uses the client config instead of env vars', async () => {
+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })
+
+ await client.Secret.create('test-secret', 'value')
+ assert.equal(lastRequest().url, `https://api.${DOMAIN_A}/secrets`)
+ assert.equal(lastRequest().apiKey, API_KEY_A)
+
+ await client.Secret.getInfo('test-secret')
+ assert.equal(lastRequest().apiKey, API_KEY_A)
+
+ await client.Secret.list().nextItems()
+ expect(lastRequest().url).toContain(`api.${DOMAIN_A}/secrets`)
+ assert.equal(lastRequest().apiKey, API_KEY_A)
+
+ // Per-call options win over the client's.
+ await client.Secret.exists('test-secret', {
+ apiKey: API_KEY_B,
+ domain: DOMAIN_B,
+ })
+ assert.equal(lastRequest().apiKey, API_KEY_B)
+ expect(lastRequest().url).toContain(`api.${DOMAIN_B}`)
+
+ // Explicit undefined does not erase the client's config.
+ await client.Secret.getInfo('test-secret', { apiKey: undefined })
+ assert.equal(lastRequest().apiKey, API_KEY_A)
+
+ // Rebinding the class keeps the client's config.
+ const S = client.Secret
+ await S.getInfo('test-secret')
+ assert.equal(lastRequest().apiKey, API_KEY_A)
+
+ // The top-level Secret keeps using the environment configuration.
+ await Secret.getInfo('test-secret')
+ assert.equal(lastRequest().apiKey, TEST_API_KEY)
+ expect(lastRequest().url).toContain(`api.${DOMAIN_ENV}`)
+})
+
+test('top-level exports keep using the environment configuration', async () => {
+ // Constructed (and used) first to prove clients do not leak into the
+ // env-configured default path.
+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })
+ await client.Sandbox.create()
+
+ await Sandbox.create()
+ assert.equal(lastRequest().url, `https://api.${DOMAIN_ENV}/sandboxes`)
+ assert.equal(lastRequest().apiKey, TEST_API_KEY)
+
+ await Volume.list()
+ assert.equal(lastRequest().url, `https://api.${DOMAIN_ENV}/volumes`)
+ assert.equal(lastRequest().apiKey, TEST_API_KEY)
+
+ await Template.exists('test-template')
+ assert.equal(
+ lastRequest().url,
+ `https://api.${DOMAIN_ENV}/templates/aliases/test-template`
+ )
+ assert.equal(lastRequest().apiKey, TEST_API_KEY)
+})
+
+test('the default export is still Sandbox', async () => {
+ assert.equal(DefaultExport, Sandbox)
+
+ await DefaultExport.create()
+
+ assert.equal(lastRequest().url, `https://api.${DOMAIN_ENV}/sandboxes`)
+ assert.equal(lastRequest().apiKey, TEST_API_KEY)
+})
diff --git a/packages/python-sdk/README.md b/packages/python-sdk/README.md
index 3bc0808bd..468454a0d 100644
--- a/packages/python-sdk/README.md
+++ b/packages/python-sdk/README.md
@@ -42,7 +42,31 @@ with Sandbox.create() as sandbox:
print(result.stdout) # Hello from E2B!
```
-### 4. Code execution with Code Interpreter
+### 4. Bind the configuration to a client
+
+The top-level `Sandbox`, `AsyncSandbox`, `Volume`, `AsyncVolume`, `Template`, `AsyncTemplate` and `Secret` 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 import E2B
+
+client = E2B(api_key="e2b_***", domain="e2b.dev")
+
+sandbox = client.Sandbox.create()
+volume = client.Volume.create("my-volume")
+exists = client.Template.exists("my-template")
+secret = client.Secret.create("openai-api-key", "sk-***")
+
+# The async variants are exposed as well.
+async_sandbox = await client.AsyncSandbox.create()
+
+# 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. Code execution with Code Interpreter
If you need [`run_code()`](https://e2b.dev/docs/code-interpreting?utm_source=pypi&utm_medium=referral&utm_campaign=readme&utm_content=e2b), install the [Code Interpreter SDK](https://github.com/e2b-dev/code-interpreter):
@@ -58,8 +82,8 @@ with Sandbox.create() as sandbox:
print(execution.text) # outputs 2
```
-### 5. Check docs
+### 6. Check docs
Visit [E2B documentation](https://e2b.dev/docs?utm_source=pypi&utm_medium=referral&utm_campaign=readme&utm_content=e2b).
-### 6. E2B cookbook
+### 7. E2B cookbook
Visit 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/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.py
index 66306a767..3b13505d1 100644
--- a/packages/python-sdk/e2b/__init__.py
+++ b/packages/python-sdk/e2b/__init__.py
@@ -150,6 +150,7 @@ from .template_sync.main import Template
from .volume.volume_sync import Volume
from .volume.volume_async import AsyncVolume
+from .client import E2B, E2BClientParams
from .volume.types import (
VolumeInfo,
VolumeAndToken,
@@ -158,6 +159,9 @@ from .volume.types import (
)
__all__ = [
+ # Client
+ "E2B",
+ "E2BClientParams",
# API
"ApiClient",
"client",
diff --git a/packages/python-sdk/e2b/client.py b/packages/python-sdk/e2b/client.py
new file mode 100644
index 000000000..ada3965f0
--- /dev/null
+++ b/packages/python-sdk/e2b/client.py
@@ -0,0 +1,89 @@
+from typing import Dict, Type, TypeVar, cast
+
+from typing_extensions import Unpack
+
+from e2b.connection_config import ApiParams
+from e2b.sandbox_async.main import AsyncSandbox
+from e2b.sandbox_sync.main import Sandbox
+from e2b.secret import AsyncSecret, Secret
+from e2b.template_async.main import AsyncTemplate
+from e2b.template_sync.main import Template
+from e2b.volume.volume_async import AsyncVolume
+from e2b.volume.volume_sync import Volume
+
+T = TypeVar("T")
+
+
+class E2BClientParams(ApiParams, total=False):
+ """Params bound to an :class:`E2B` client, used as the defaults for every
+ call made through its resource classes. Same shape as :class:`ApiParams`."""
+
+
+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 import E2B
+
+ client = E2B(api_key="e2b_...", domain="e2b.dev")
+
+ sandbox = client.Sandbox.create()
+ volumes = client.Volume.list()
+ exists = client.Template.exists("my-template")
+ ```
+ """
+
+ 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)))
+
+ self.Sandbox = _bind(Sandbox, api_params)
+ """`Sandbox` class bound to this client's connection configuration."""
+
+ self.AsyncSandbox = _bind(AsyncSandbox, api_params)
+ """`AsyncSandbox` class bound to this client's connection configuration."""
+
+ self.Volume = _bind(Volume, api_params)
+ """`Volume` class bound to this client's connection configuration."""
+
+ self.AsyncVolume = _bind(AsyncVolume, api_params)
+ """`AsyncVolume` class bound to this client's connection configuration."""
+
+ self.Template = _bind(Template, api_params)
+ """`Template` class bound to this client's connection configuration."""
+
+ self.AsyncTemplate = _bind(AsyncTemplate, api_params)
+ """`AsyncTemplate` class bound to this client's connection configuration."""
+
+ self.Secret = _bind(Secret, api_params)
+ """`Secret` class bound to this client's connection configuration."""
+
+ self.AsyncSecret = _bind(AsyncSecret, api_params)
+ """`AsyncSecret` class bound to this client's connection configuration."""
diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.py
index bad04d6ee..8729419a6 100644
--- a/packages/python-sdk/e2b/connection_config.py
+++ b/packages/python-sdk/e2b/connection_config.py
@@ -1,7 +1,7 @@
import logging
import os
-from typing import cast, Optional, Dict, TypedDict, Union
+from typing import cast, Mapping, Optional, Dict, TypedDict, Union
import httpx
from typing_extensions import Unpack
@@ -90,6 +90,56 @@ class ApiParamsWithLogger(ApiParams, total=False):
logger: Optional[logging.Logger]
+def merge_api_params(
+ bound_params: Optional[ApiParams], params: Mapping[str, object]
+) -> ApiParams:
+ """
+ Merge the API params bound to a class (e.g. by an :class:`e2b.E2B` client)
+ with the per-call params. Per-call params win, then the bound params, then
+ the environment variables resolved by :class:`ConnectionConfig`.
+
+ Per-call params explicitly set to ``None`` are dropped so they fall back to
+ the bound params instead of clearing them.
+
+ :meta private:
+ """
+ if not bound_params:
+ return cast(ApiParams, params)
+
+ merged = cast(Dict[str, object], dict(bound_params))
+ merged.update({k: v for k, v in params.items() if v is not None})
+ return cast(ApiParams, merged)
+
+
+class ClientFactory:
+ """
+ Base class for the resource classes (`Sandbox`, `Volume`, `Template`,
+ `Secret`) whose classmethods build a :class:`ConnectionConfig` from per-call
+ params. An :class:`e2b.E2B` client exposes subclasses of these with its own
+ params bound, and every classmethod resolves them through
+ :meth:`_resolve_api_params`.
+
+ :meta private:
+ """
+
+ _bound_api_params: ApiParams = {}
+ """API params bound to this class by an :class:`e2b.E2B` client.
+
+ Empty on the base classes, so the env-configured default path is unchanged.
+
+ :meta private:
+ """
+
+ @classmethod
+ def _resolve_api_params(cls, **opts: Unpack[ApiParams]) -> ApiParams:
+ """
+ Merge the API params bound to this class with the per-call params.
+
+ :meta private:
+ """
+ return merge_api_params(cls._bound_api_params, opts)
+
+
class ConnectionConfig:
"""
Configuration for the connection to the API.
diff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.py
index b0687711c..3f0d8c9aa 100644
--- a/packages/python-sdk/e2b/sandbox/main.py
+++ b/packages/python-sdk/e2b/sandbox/main.py
@@ -3,7 +3,12 @@ from typing import Optional, TypedDict
from packaging.version import Version
-from e2b.connection_config import ConnectionConfig, default_username
+
+from e2b.connection_config import (
+ ClientFactory,
+ ConnectionConfig,
+ default_username,
+)
from e2b.envd.api import ENVD_API_FILES_ROUTE
from e2b.envd.versions import ENVD_DEFAULT_USER
from e2b.exceptions import InvalidArgumentException
@@ -19,7 +24,7 @@ class SandboxOpts(TypedDict):
connection_config: ConnectionConfig
-class SandboxBase:
+class SandboxBase(ClientFactory):
mcp_port = 50005
default_sandbox_timeout = 300
diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.py
index 7e8cb3aa0..319600875 100644
--- a/packages/python-sdk/e2b/sandbox_async/main.py
+++ b/packages/python-sdk/e2b/sandbox_async/main.py
@@ -956,8 +956,9 @@ class AsyncSandbox(SandboxApi):
**self.connection_config.get_api_params(**opts),
)
- @staticmethod
+ @classmethod
def _cls_list_snapshots(
+ cls,
sandbox_id: Optional[str] = None,
limit: Optional[int] = None,
next_token: Optional[str] = None,
@@ -969,11 +970,12 @@ class AsyncSandbox(SandboxApi):
name=name,
limit=limit,
next_token=next_token,
- **opts,
+ **cls._resolve_api_params(**opts),
)
- @staticmethod
+ @classmethod
async def delete_snapshot(
+ cls,
snapshot_id: str,
**opts: Unpack[ApiParams],
) -> bool:
@@ -983,7 +985,7 @@ class AsyncSandbox(SandboxApi):
:param snapshot_id: Snapshot ID
:return: `True` if the snapshot was deleted, `False` if it was not found
"""
- return await SandboxApi._cls_delete_snapshot(
+ return await cls._cls_delete_snapshot(
snapshot_id=snapshot_id,
**opts,
)
@@ -1008,7 +1010,8 @@ class AsyncSandbox(SandboxApi):
logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> Self:
- debug = ConnectionConfig(**opts).debug
+ params = cls._resolve_api_params(**opts)
+ debug = ConnectionConfig(**params).debug
if debug:
sandbox_domain = None
envd_version = ENVD_DEBUG_FALLBACK
@@ -1019,7 +1022,7 @@ class AsyncSandbox(SandboxApi):
sandbox_id=sandbox_id,
timeout=timeout,
logger=logger,
- **opts,
+ **params,
)
sandbox_id = sandbox.sandbox_id
@@ -1038,7 +1041,7 @@ class AsyncSandbox(SandboxApi):
connection_config = ConnectionConfig(
extra_sandbox_headers=sandbox_headers,
logger=logger,
- **opts,
+ **params,
)
return cls(
@@ -1059,12 +1062,13 @@ class AsyncSandbox(SandboxApi):
logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> List[Union[Self, Exception]]:
+ params = cls._resolve_api_params(**opts)
responses = await SandboxApi._cls_fork(
sandbox_id=sandbox_id,
timeout=timeout,
count=count,
logger=logger,
- **opts,
+ **params,
)
sandboxes: List[Union[Self, Exception]] = []
@@ -1083,7 +1087,7 @@ class AsyncSandbox(SandboxApi):
connection_config = ConnectionConfig(
extra_sandbox_headers=sandbox_headers,
logger=logger,
- **opts,
+ **params,
)
sandboxes.append(
@@ -1116,9 +1120,10 @@ class AsyncSandbox(SandboxApi):
logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> Self:
+ params = cls._resolve_api_params(**opts)
extra_sandbox_headers = {}
- debug = ConnectionConfig(**opts).debug
+ debug = ConnectionConfig(**params).debug
if debug:
sandbox_id = "debug_sandbox_id"
sandbox_domain = None
@@ -1139,7 +1144,7 @@ class AsyncSandbox(SandboxApi):
lifecycle=lifecycle,
volume_mounts=volume_mounts,
logger=logger,
- **opts,
+ **params,
)
sandbox_id = response.sandbox_id
@@ -1159,7 +1164,7 @@ class AsyncSandbox(SandboxApi):
connection_config = ConnectionConfig(
extra_sandbox_headers=extra_sandbox_headers,
logger=logger,
- **opts,
+ **params,
)
return cls(
diff --git a/packages/python-sdk/e2b/sandbox_async/paginator.py b/packages/python-sdk/e2b/sandbox_async/paginator.py
index bc8f5380a..9d19d09b4 100644
--- a/packages/python-sdk/e2b/sandbox_async/paginator.py
+++ b/packages/python-sdk/e2b/sandbox_async/paginator.py
@@ -6,7 +6,7 @@ from typing_extensions import Unpack
from e2b.api.client.api.sandboxes import get_v2_sandboxes
from e2b.api.client.api.snapshots import get_snapshots
from e2b.api.client.types import UNSET
-from e2b.connection_config import ApiParams, ConnectionConfig
+from e2b.connection_config import ApiParams, ConnectionConfig, merge_api_params
from e2b.exceptions import SandboxException
from e2b.sandbox.sandbox_api import (
SandboxPaginatorBase,
@@ -41,7 +41,7 @@ class AsyncSandboxPaginator(SandboxPaginatorBase):
:param opts: Per-call connection options (e.g. `api_key`, `domain`,
`headers`, `request_timeout`). When provided, this call uses these
- options instead of the ones the paginator was constructed with.
+ options on top of the ones the paginator was constructed with.
:returns: List of sandboxes
"""
@@ -57,7 +57,7 @@ class AsyncSandboxPaginator(SandboxPaginatorBase):
}
metadata = urllib.parse.urlencode(quoted_metadata)
- config = ConnectionConfig(**{**self._opts, **opts})
+ config = ConnectionConfig(**merge_api_params(self._opts, opts))
api_client = get_api_client(config)
res = await get_v2_sandboxes.asyncio_detailed(
client=api_client,
@@ -104,14 +104,14 @@ class AsyncSnapshotPaginator(SnapshotPaginatorBase):
:param opts: Per-call connection options (e.g. `api_key`, `domain`,
`headers`, `request_timeout`). When provided, this call uses these
- options instead of the ones the paginator was constructed with.
+ options on top of the ones the paginator was constructed with.
:returns: List of snapshots
"""
if not self.has_next:
raise Exception("No more items to fetch")
- config = ConnectionConfig(**{**self._opts, **opts})
+ config = ConnectionConfig(**merge_api_params(self._opts, opts))
api_client = get_api_client(config)
res = await get_snapshots.asyncio_detailed(
client=api_client,
diff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
index 934f71e39..ced697c14 100644
--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
@@ -65,8 +65,9 @@ from e2b.sandbox_async.paginator import AsyncSandboxPaginator
class SandboxApi(SandboxBase):
- @staticmethod
+ @classmethod
def list(
+ cls,
query: Optional[SandboxQuery] = None,
limit: Optional[int] = None,
next_token: Optional[str] = None,
@@ -88,7 +89,7 @@ class SandboxApi(SandboxBase):
query=query,
limit=limit,
next_token=next_token,
- **opts,
+ **cls._resolve_api_params(**opts),
)
@classmethod
@@ -103,7 +104,7 @@ class SandboxApi(SandboxBase):
:return: Sandbox info
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = await get_sandboxes_sandbox_id.asyncio_detailed(
@@ -131,7 +132,7 @@ class SandboxApi(SandboxBase):
sandbox_id: str,
**opts: Unpack[ApiParams],
) -> bool:
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
if config.debug:
# Skip killing the sandbox in debug mode
@@ -158,7 +159,7 @@ class SandboxApi(SandboxBase):
timeout: int,
**opts: Unpack[ApiParams],
) -> None:
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
if config.debug:
# Skip setting the timeout in debug mode
@@ -184,7 +185,7 @@ class SandboxApi(SandboxBase):
network: SandboxNetworkUpdate,
**opts: Unpack[ApiParams],
) -> None:
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = await put_sandboxes_sandbox_id_network.asyncio_detailed(
@@ -216,7 +217,8 @@ class SandboxApi(SandboxBase):
logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> SandboxCreateResponse:
- config = ConnectionConfig(logger=logger, **opts)
+ params = cls._resolve_api_params(**opts)
+ config = ConnectionConfig(logger=logger, **params)
lifecycle_body = build_lifecycle_config(lifecycle)
@@ -256,7 +258,7 @@ class SandboxApi(SandboxBase):
raise SandboxException(f"{res.parsed.message}: Request failed")
if Version(res.parsed.envd_version) < Version("0.1.0"):
- await SandboxApi._cls_kill(res.parsed.sandbox_id)
+ await SandboxApi._cls_kill(res.parsed.sandbox_id, **params)
raise TemplateException(
"You need to update the template to use the new SDK."
)
@@ -298,7 +300,7 @@ class SandboxApi(SandboxBase):
:return: List of sandbox metrics containing CPU, memory and disk usage information
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
if config.debug:
# Skip getting the metrics in debug mode
@@ -347,7 +349,7 @@ class SandboxApi(SandboxBase):
name: Optional[str] = None,
**opts: Unpack[ApiParams],
) -> SnapshotInfo:
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = await post_sandboxes_sandbox_id_snapshots.asyncio_detailed(
@@ -379,7 +381,7 @@ class SandboxApi(SandboxBase):
snapshot_id: str,
**opts: Unpack[ApiParams],
) -> bool:
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = await delete_templates_template_id.asyncio_detailed(
@@ -402,7 +404,7 @@ class SandboxApi(SandboxBase):
keep_memory: bool = True,
**opts: Unpack[ApiParams],
) -> bool:
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = await post_sandboxes_sandbox_id_pause.asyncio_detailed(
@@ -444,7 +446,7 @@ class SandboxApi(SandboxBase):
if count < 1:
raise InvalidArgumentException("count must be at least 1")
- config = ConnectionConfig(logger=logger, **opts)
+ config = ConnectionConfig(logger=logger, **cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = await post_sandboxes_sandbox_id_fork.asyncio_detailed(
@@ -525,7 +527,7 @@ class SandboxApi(SandboxBase):
timeout = timeout or SandboxBase.default_sandbox_timeout
# Sandbox is not running, resume it
- config = ConnectionConfig(logger=logger, **opts)
+ config = ConnectionConfig(logger=logger, **cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = await post_sandboxes_sandbox_id_connect.asyncio_detailed(
diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.py
index d831b44cf..2ebda95aa 100644
--- a/packages/python-sdk/e2b/sandbox_sync/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/main.py
@@ -954,8 +954,9 @@ class Sandbox(SandboxApi):
**self.connection_config.get_api_params(**opts),
)
- @staticmethod
+ @classmethod
def _cls_list_snapshots(
+ cls,
sandbox_id: Optional[str] = None,
limit: Optional[int] = None,
next_token: Optional[str] = None,
@@ -967,11 +968,12 @@ class Sandbox(SandboxApi):
name=name,
limit=limit,
next_token=next_token,
- **opts,
+ **cls._resolve_api_params(**opts),
)
- @staticmethod
+ @classmethod
def delete_snapshot(
+ cls,
snapshot_id: str,
**opts: Unpack[ApiParams],
) -> bool:
@@ -981,7 +983,7 @@ class Sandbox(SandboxApi):
:param snapshot_id: Snapshot ID
:return: `True` if the snapshot was deleted, `False` if it was not found
"""
- return SandboxApi._cls_delete_snapshot(
+ return cls._cls_delete_snapshot(
snapshot_id=snapshot_id,
**opts,
)
@@ -1004,7 +1006,8 @@ class Sandbox(SandboxApi):
logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> Self:
- debug = ConnectionConfig(**opts).debug
+ params = cls._resolve_api_params(**opts)
+ debug = ConnectionConfig(**params).debug
if debug:
sandbox_domain = None
envd_version = ENVD_DEBUG_FALLBACK
@@ -1015,7 +1018,7 @@ class Sandbox(SandboxApi):
sandbox_id=sandbox_id,
timeout=timeout,
logger=logger,
- **opts,
+ **params,
)
sandbox_id = sandbox.sandbox_id
@@ -1034,7 +1037,7 @@ class Sandbox(SandboxApi):
connection_config = ConnectionConfig(
extra_sandbox_headers=sandbox_headers,
logger=logger,
- **opts,
+ **params,
)
return cls(
@@ -1055,12 +1058,13 @@ class Sandbox(SandboxApi):
logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> List[Union[Self, Exception]]:
+ params = cls._resolve_api_params(**opts)
responses = SandboxApi._cls_fork(
sandbox_id=sandbox_id,
timeout=timeout,
count=count,
logger=logger,
- **opts,
+ **params,
)
sandboxes: List[Union[Self, Exception]] = []
@@ -1079,7 +1083,7 @@ class Sandbox(SandboxApi):
connection_config = ConnectionConfig(
extra_sandbox_headers=sandbox_headers,
logger=logger,
- **opts,
+ **params,
)
sandboxes.append(
@@ -1112,9 +1116,10 @@ class Sandbox(SandboxApi):
logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> Self:
+ params = cls._resolve_api_params(**opts)
extra_sandbox_headers = {}
- debug = ConnectionConfig(**opts).debug
+ debug = ConnectionConfig(**params).debug
if debug:
sandbox_id = "debug_sandbox_id"
sandbox_domain = None
@@ -1135,7 +1140,7 @@ class Sandbox(SandboxApi):
lifecycle=lifecycle,
volume_mounts=volume_mounts,
logger=logger,
- **opts,
+ **params,
)
sandbox_id = response.sandbox_id
@@ -1155,7 +1160,7 @@ class Sandbox(SandboxApi):
connection_config = ConnectionConfig(
extra_sandbox_headers=extra_sandbox_headers,
logger=logger,
- **opts,
+ **params,
)
return cls(
diff --git a/packages/python-sdk/e2b/sandbox_sync/paginator.py b/packages/python-sdk/e2b/sandbox_sync/paginator.py
index aa896dd4b..a88ad5d27 100644
--- a/packages/python-sdk/e2b/sandbox_sync/paginator.py
+++ b/packages/python-sdk/e2b/sandbox_sync/paginator.py
@@ -8,7 +8,7 @@ from e2b.api.client.api.sandboxes import get_v2_sandboxes
from e2b.api.client.api.snapshots import get_snapshots
from e2b.api.client.models.error import Error
from e2b.api.client.types import UNSET
-from e2b.connection_config import ApiParams, ConnectionConfig
+from e2b.connection_config import ApiParams, ConnectionConfig, merge_api_params
from e2b.exceptions import SandboxException
from e2b.sandbox.sandbox_api import (
SandboxPaginatorBase,
@@ -41,7 +41,7 @@ class SandboxPaginator(SandboxPaginatorBase):
:param opts: Per-call connection options (e.g. `api_key`, `domain`,
`headers`, `request_timeout`). When provided, this call uses these
- options instead of the ones the paginator was constructed with.
+ options on top of the ones the paginator was constructed with.
:returns: List of sandboxes
"""
@@ -57,7 +57,7 @@ class SandboxPaginator(SandboxPaginatorBase):
}
metadata = urllib.parse.urlencode(quoted_metadata)
- config = ConnectionConfig(**{**self._opts, **opts})
+ config = ConnectionConfig(**merge_api_params(self._opts, opts))
api_client = get_api_client(config)
res = get_v2_sandboxes.sync_detailed(
client=api_client,
@@ -104,14 +104,14 @@ class SnapshotPaginator(SnapshotPaginatorBase):
:param opts: Per-call connection options (e.g. `api_key`, `domain`,
`headers`, `request_timeout`). When provided, this call uses these
- options instead of the ones the paginator was constructed with.
+ options on top of the ones the paginator was constructed with.
:returns: List of snapshots
"""
if not self.has_next:
raise Exception("No more items to fetch")
- config = ConnectionConfig(**{**self._opts, **opts})
+ config = ConnectionConfig(**merge_api_params(self._opts, opts))
api_client = get_api_client(config)
res = get_snapshots.sync_detailed(
client=api_client,
diff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
index a19864c13..0fc615e21 100644
--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
@@ -64,8 +64,9 @@ from e2b.sandbox_sync.paginator import SandboxPaginator, get_api_client
class SandboxApi(SandboxBase):
- @staticmethod
+ @classmethod
def list(
+ cls,
query: Optional[SandboxQuery] = None,
limit: Optional[int] = None,
next_token: Optional[str] = None,
@@ -87,7 +88,7 @@ class SandboxApi(SandboxBase):
query=query,
limit=limit,
next_token=next_token,
- **opts,
+ **cls._resolve_api_params(**opts),
)
@classmethod
@@ -102,7 +103,7 @@ class SandboxApi(SandboxBase):
:return: Sandbox info
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = get_sandboxes_sandbox_id.sync_detailed(
@@ -130,7 +131,7 @@ class SandboxApi(SandboxBase):
sandbox_id: str,
**opts: Unpack[ApiParams],
) -> bool:
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
if config.debug:
# Skip killing the sandbox in debug mode
@@ -157,7 +158,7 @@ class SandboxApi(SandboxBase):
timeout: int,
**opts: Unpack[ApiParams],
) -> None:
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
if config.debug:
# Skip setting timeout in debug mode
@@ -183,7 +184,7 @@ class SandboxApi(SandboxBase):
network: SandboxNetworkUpdate,
**opts: Unpack[ApiParams],
) -> None:
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = put_sandboxes_sandbox_id_network.sync_detailed(
@@ -215,7 +216,8 @@ class SandboxApi(SandboxBase):
logger: Optional[logging.Logger] = None,
**opts: Unpack[ApiParams],
) -> SandboxCreateResponse:
- config = ConnectionConfig(logger=logger, **opts)
+ params = cls._resolve_api_params(**opts)
+ config = ConnectionConfig(logger=logger, **params)
lifecycle_body = build_lifecycle_config(lifecycle)
@@ -255,7 +257,7 @@ class SandboxApi(SandboxBase):
raise SandboxException(f"{res.parsed.message}: Request failed")
if Version(res.parsed.envd_version) < Version("0.1.0"):
- SandboxApi._cls_kill(res.parsed.sandbox_id)
+ SandboxApi._cls_kill(res.parsed.sandbox_id, **params)
raise TemplateException(
"You need to update the template to use the new SDK."
)
@@ -288,7 +290,7 @@ class SandboxApi(SandboxBase):
end: Optional[datetime.datetime] = None,
**opts: Unpack[ApiParams],
) -> List[SandboxMetrics]:
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
if config.debug:
# Skip getting the metrics in debug mode
@@ -339,7 +341,7 @@ class SandboxApi(SandboxBase):
) -> SandboxCreateResponse:
timeout = timeout or SandboxBase.default_sandbox_timeout
- config = ConnectionConfig(logger=logger, **opts)
+ config = ConnectionConfig(logger=logger, **cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = post_sandboxes_sandbox_id_connect.sync_detailed(
@@ -397,7 +399,7 @@ class SandboxApi(SandboxBase):
if count < 1:
raise InvalidArgumentException("count must be at least 1")
- config = ConnectionConfig(logger=logger, **opts)
+ config = ConnectionConfig(logger=logger, **cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = post_sandboxes_sandbox_id_fork.sync_detailed(
@@ -474,7 +476,7 @@ class SandboxApi(SandboxBase):
name: Optional[str] = None,
**opts: Unpack[ApiParams],
) -> SnapshotInfo:
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = post_sandboxes_sandbox_id_snapshots.sync_detailed(
@@ -506,7 +508,7 @@ class SandboxApi(SandboxBase):
snapshot_id: str,
**opts: Unpack[ApiParams],
) -> bool:
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = delete_templates_template_id.sync_detailed(
@@ -529,7 +531,7 @@ class SandboxApi(SandboxBase):
keep_memory: bool = True,
**opts: Unpack[ApiParams],
) -> bool:
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = post_sandboxes_sandbox_id_pause.sync_detailed(
diff --git a/packages/python-sdk/e2b/secret/base.py b/packages/python-sdk/e2b/secret/base.py
index e9fe72f0f..a40929911 100644
--- a/packages/python-sdk/e2b/secret/base.py
+++ b/packages/python-sdk/e2b/secret/base.py
@@ -1,6 +1,7 @@
import re
-from e2b.connection_config import ApiParams
+
+from e2b.connection_config import ApiParams, ClientFactory
from e2b.exceptions import InvalidArgumentException
from e2b.paginator import PaginatorBase
from e2b.sandbox.sandbox_api import SandboxIamToken, SandboxIamTokenType
@@ -24,7 +25,7 @@ def _validate_secret_name(name: str) -> None:
)
-class SecretBase:
+class SecretBase(ClientFactory):
"""
Module for managing E2B secrets and workload identity helpers.
diff --git a/packages/python-sdk/e2b/secret/secret_async.py b/packages/python-sdk/e2b/secret/secret_async.py
index 3094af5e1..f0e3cdd32 100644
--- a/packages/python-sdk/e2b/secret/secret_async.py
+++ b/packages/python-sdk/e2b/secret/secret_async.py
@@ -18,7 +18,7 @@ from e2b.api.client.models import (
)
from e2b.api.client.types import UNSET
from e2b.api.client_async import get_api_client
-from e2b.connection_config import ApiParams, ConnectionConfig
+from e2b.connection_config import ApiParams, ConnectionConfig, merge_api_params
from e2b.exceptions import SecretException, SecretNotFoundException
from e2b.secret.base import SecretBase, SecretPaginatorBase
from e2b.secret.types import SecretInfo
@@ -60,7 +60,7 @@ class AsyncSecretPaginator(SecretPaginatorBase):
if not self.has_next:
raise Exception("No more items to fetch")
- config = ConnectionConfig(**{**self._opts, **opts})
+ config = ConnectionConfig(**merge_api_params(self._opts, opts))
api_client = get_api_client(config)
res = await get_secrets.asyncio_detailed(
client=api_client,
@@ -90,8 +90,9 @@ class AsyncSecret(SecretBase):
``update`` but never returned by any read surface.
"""
- @staticmethod
+ @classmethod
async def create(
+ cls,
name: str,
value: str,
metadata: Optional[Dict[str, str]] = None,
@@ -107,7 +108,7 @@ class AsyncSecret(SecretBase):
:return: The secret's ID, name, current version (`1` for a new
secret), metadata, and creation and update times.
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = await post_secrets.asyncio_detailed(
client=api_client,
@@ -129,8 +130,9 @@ class AsyncSecret(SecretBase):
return SecretInfo._from_model(res.parsed)
- @staticmethod
+ @classmethod
async def update(
+ cls,
secret: str,
value: str,
metadata: Optional[Dict[str, str]] = None,
@@ -147,7 +149,7 @@ class AsyncSecret(SecretBase):
:return: The secret's ID, name, new current version, metadata, and
creation and update times.
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = await post_secrets_secret_id.asyncio_detailed(
secret,
@@ -172,8 +174,8 @@ class AsyncSecret(SecretBase):
return SecretInfo._from_model(res.parsed)
- @staticmethod
- async def get_info(secret: str, **opts: Unpack[ApiParams]) -> SecretInfo:
+ @classmethod
+ async def get_info(cls, secret: str, **opts: Unpack[ApiParams]) -> SecretInfo:
"""
Get a secret's metadata.
@@ -182,7 +184,7 @@ class AsyncSecret(SecretBase):
:return: The secret's ID, name, current version, metadata, and
creation and update times.
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = await get_secrets_secret_id.asyncio_detailed(
secret,
@@ -203,8 +205,9 @@ class AsyncSecret(SecretBase):
return SecretInfo._from_model(res.parsed)
- @staticmethod
+ @classmethod
def list(
+ cls,
limit: Optional[int] = None,
next_token: Optional[str] = None,
**opts: Unpack[ApiParams],
@@ -223,10 +226,14 @@ class AsyncSecret(SecretBase):
secrets = await paginator.next_items()
```
"""
- return AsyncSecretPaginator(limit=limit, next_token=next_token, **opts)
+ return AsyncSecretPaginator(
+ limit=limit,
+ next_token=next_token,
+ **cls._resolve_api_params(**opts),
+ )
- @staticmethod
- async def exists(secret: str, **opts: Unpack[ApiParams]) -> bool:
+ @classmethod
+ async def exists(cls, secret: str, **opts: Unpack[ApiParams]) -> bool:
"""
Check whether a secret exists.
@@ -235,13 +242,13 @@ class AsyncSecret(SecretBase):
:return: `True` if the secret exists, `False` otherwise.
"""
try:
- await AsyncSecret.get_info(secret, **opts)
+ await cls.get_info(secret, **opts)
return True
except SecretNotFoundException:
return False
- @staticmethod
- async def destroy(secret: str, **opts: Unpack[ApiParams]) -> bool:
+ @classmethod
+ async def destroy(cls, secret: str, **opts: Unpack[ApiParams]) -> bool:
"""
Destroy a secret, making all its versions inaccessible.
@@ -249,7 +256,7 @@ class AsyncSecret(SecretBase):
:return: `True` if the secret was destroyed, `False` if it was not found.
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = await delete_secrets_secret_id.asyncio_detailed(
secret,
diff --git a/packages/python-sdk/e2b/secret/secret_sync.py b/packages/python-sdk/e2b/secret/secret_sync.py
index eab2368cf..908936112 100644
--- a/packages/python-sdk/e2b/secret/secret_sync.py
+++ b/packages/python-sdk/e2b/secret/secret_sync.py
@@ -18,7 +18,7 @@ from e2b.api.client.models import (
)
from e2b.api.client.types import UNSET
from e2b.api.client_sync import get_api_client
-from e2b.connection_config import ApiParams, ConnectionConfig
+from e2b.connection_config import ApiParams, ConnectionConfig, merge_api_params
from e2b.exceptions import SecretException, SecretNotFoundException
from e2b.secret.base import SecretBase, SecretPaginatorBase
from e2b.secret.types import SecretInfo
@@ -60,7 +60,7 @@ class SecretPaginator(SecretPaginatorBase):
if not self.has_next:
raise Exception("No more items to fetch")
- config = ConnectionConfig(**{**self._opts, **opts})
+ config = ConnectionConfig(**merge_api_params(self._opts, opts))
api_client = get_api_client(config)
res = get_secrets.sync_detailed(
client=api_client,
@@ -90,8 +90,9 @@ class Secret(SecretBase):
``update`` but never returned by any read surface.
"""
- @staticmethod
+ @classmethod
def create(
+ cls,
name: str,
value: str,
metadata: Optional[Dict[str, str]] = None,
@@ -107,7 +108,7 @@ class Secret(SecretBase):
:return: The secret's ID, name, current version (`1` for a new
secret), metadata, and creation and update times.
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = post_secrets.sync_detailed(
client=api_client,
@@ -129,8 +130,9 @@ class Secret(SecretBase):
return SecretInfo._from_model(res.parsed)
- @staticmethod
+ @classmethod
def update(
+ cls,
secret: str,
value: str,
metadata: Optional[Dict[str, str]] = None,
@@ -147,7 +149,7 @@ class Secret(SecretBase):
:return: The secret's ID, name, new current version, metadata, and
creation and update times.
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = post_secrets_secret_id.sync_detailed(
secret,
@@ -172,8 +174,8 @@ class Secret(SecretBase):
return SecretInfo._from_model(res.parsed)
- @staticmethod
- def get_info(secret: str, **opts: Unpack[ApiParams]) -> SecretInfo:
+ @classmethod
+ def get_info(cls, secret: str, **opts: Unpack[ApiParams]) -> SecretInfo:
"""
Get a secret's metadata.
@@ -182,7 +184,7 @@ class Secret(SecretBase):
:return: The secret's ID, name, current version, metadata, and
creation and update times.
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = get_secrets_secret_id.sync_detailed(
secret,
@@ -203,8 +205,9 @@ class Secret(SecretBase):
return SecretInfo._from_model(res.parsed)
- @staticmethod
+ @classmethod
def list(
+ cls,
limit: Optional[int] = None,
next_token: Optional[str] = None,
**opts: Unpack[ApiParams],
@@ -223,10 +226,14 @@ class Secret(SecretBase):
secrets = paginator.next_items()
```
"""
- return SecretPaginator(limit=limit, next_token=next_token, **opts)
+ return SecretPaginator(
+ limit=limit,
+ next_token=next_token,
+ **cls._resolve_api_params(**opts),
+ )
- @staticmethod
- def exists(secret: str, **opts: Unpack[ApiParams]) -> bool:
+ @classmethod
+ def exists(cls, secret: str, **opts: Unpack[ApiParams]) -> bool:
"""
Check whether a secret exists.
@@ -235,13 +242,13 @@ class Secret(SecretBase):
:return: `True` if the secret exists, `False` otherwise.
"""
try:
- Secret.get_info(secret, **opts)
+ cls.get_info(secret, **opts)
return True
except SecretNotFoundException:
return False
- @staticmethod
- def destroy(secret: str, **opts: Unpack[ApiParams]) -> bool:
+ @classmethod
+ def destroy(cls, secret: str, **opts: Unpack[ApiParams]) -> bool:
"""
Destroy a secret, making all its versions inaccessible.
@@ -249,7 +256,7 @@ class Secret(SecretBase):
:return: `True` if the secret was destroyed, `False` if it was not found.
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_api_client(config)
res = delete_secrets_secret_id.sync_detailed(
secret,
diff --git a/packages/python-sdk/e2b/template/main.py b/packages/python-sdk/e2b/template/main.py
index ab970c598..a81eb0e24 100644
--- a/packages/python-sdk/e2b/template/main.py
+++ b/packages/python-sdk/e2b/template/main.py
@@ -3,9 +3,8 @@ import shlex
from typing import Dict, List, Optional, Union, Literal
from pathlib import Path
-from typing_extensions import Unpack
-from e2b.connection_config import ApiParams
+from e2b.connection_config import ClientFactory
from e2b.exceptions import BuildException, InvalidArgumentException
from e2b.template.consts import RESOLVE_SYMLINKS
from e2b.template.dockerfile_parser import parse_dockerfile
@@ -751,33 +750,13 @@ class TemplateFinal:
self._template = template
-class TemplateBase:
+class TemplateBase(ClientFactory):
"""
Base class for building E2B sandbox templates.
"""
_logs_refresh_frequency = 0.2
- _bound_api_params: ApiParams = {}
- """API parameters bound to this class, used as defaults for every operation
- that talks to the API. Empty here, so the config comes from per-call
- parameters and environment variables; per-client subclasses bind their own.
-
- :meta private:
- """
-
- @classmethod
- def _resolve_api_params(cls, **opts: Unpack[ApiParams]) -> ApiParams:
- """
- Layer per-call API parameters over the parameters bound to the class.
- Per-call parameters explicitly set to `None` don't clear the bound ones.
-
- :meta private:
- """
- per_call_opts = {key: value for key, value in opts.items() if value is not None}
-
- return {**cls._bound_api_params, **per_call_opts}
-
def __init__(
self,
file_context_path: Optional[Union[str, Path]] = None,
diff --git a/packages/python-sdk/e2b/volume/utils.py b/packages/python-sdk/e2b/volume/utils.py
index cd9e3e51d..26d1323f6 100644
--- a/packages/python-sdk/e2b/volume/utils.py
+++ b/packages/python-sdk/e2b/volume/utils.py
@@ -40,6 +40,10 @@ class DualMethod:
When accessed on the class (e.g. ``Volume.get_info``), the static function
is returned. When accessed on an instance (e.g. ``vol.get_info``), the
instance method is returned as a bound method.
+
+ ``static_fn`` may be a ``classmethod``, in which case it is bound to the
+ accessed class so it can read class-level state (e.g. the API params an
+ :class:`e2b.E2B` client bound to a generated subclass).
"""
def __init__(self, static_fn, instance_fn):
@@ -48,5 +52,5 @@ class DualMethod:
def __get__(self, obj, objtype=None):
if obj is None:
- return self._static_fn
+ return self._static_fn.__get__(None, objtype)
return self._instance_fn.__get__(obj, objtype)
diff --git a/packages/python-sdk/e2b/volume/volume_async.py b/packages/python-sdk/e2b/volume/volume_async.py
index 03bee8b0e..192234f40 100644
--- a/packages/python-sdk/e2b/volume/volume_async.py
+++ b/packages/python-sdk/e2b/volume/volume_async.py
@@ -5,7 +5,7 @@ from http import HTTPStatus
import httpx
-from typing_extensions import Unpack
+from typing_extensions import Self, Unpack
from e2b.api import handle_api_exception
from e2b.api.client.api.volumes import (
@@ -20,7 +20,12 @@ from e2b.api.client.models import (
)
from e2b.api.client.types import Response
from e2b.api.client_async import get_api_client as get_core_api_client
-from e2b.connection_config import ApiParams, ConnectionConfig, ProxyTypes
+from e2b.connection_config import (
+ ApiParams,
+ ClientFactory,
+ ConnectionConfig,
+ ProxyTypes,
+)
from e2b.exceptions import (
NotFoundException,
VolumeException,
@@ -62,7 +67,7 @@ from e2b.volume.utils import (
)
-class AsyncVolume:
+class AsyncVolume(ClientFactory):
"""E2B Volume for persistent storage that can be mounted to sandboxes (async)."""
def __init__(
@@ -108,7 +113,7 @@ class AsyncVolume:
)
@classmethod
- async def create(cls, name: str, **opts: Unpack[ApiParams]) -> "AsyncVolume":
+ async def create(cls, name: str, **opts: Unpack[ApiParams]) -> Self:
"""
Create a new volume.
@@ -116,7 +121,7 @@ class AsyncVolume:
:return: An AsyncVolume instance for the new volume
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_core_api_client(config)
res = await post_volumes.asyncio_detailed(
@@ -149,7 +154,7 @@ class AsyncVolume:
return vol
@classmethod
- async def connect(cls, volume_id: str, **opts: Unpack[ApiParams]) -> "AsyncVolume":
+ async def connect(cls, volume_id: str, **opts: Unpack[ApiParams]) -> Self:
"""
Connect to an existing volume by ID.
@@ -158,7 +163,7 @@ class AsyncVolume:
:return: An AsyncVolume instance for the existing volume
"""
info = await cls.get_info(volume_id, **opts)
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
return cls(
volume_id=volume_id,
name=info.name,
@@ -168,9 +173,9 @@ class AsyncVolume:
proxy=config.proxy,
)
- @staticmethod
+ @classmethod
async def _class_get_info(
- volume_id: str, **opts: Unpack[ApiParams]
+ cls, volume_id: str, **opts: Unpack[ApiParams]
) -> VolumeAndToken:
"""
Get information about a volume.
@@ -179,7 +184,7 @@ class AsyncVolume:
:return: Volume info
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_core_api_client(config)
res = await get_volumes_volume_id.asyncio_detailed(
@@ -211,14 +216,14 @@ class AsyncVolume:
domain=domain,
)
- @staticmethod
- async def _class_list(**opts: Unpack[ApiParams]) -> List[VolumeInfo]:
+ @classmethod
+ async def _class_list(cls, **opts: Unpack[ApiParams]) -> List[VolumeInfo]:
"""
List all volumes.
:return: List of volumes
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_core_api_client(config)
res = await get_volumes.asyncio_detailed(
@@ -236,14 +241,14 @@ class AsyncVolume:
return [VolumeInfo(volume_id=v.volume_id, name=v.name) for v in res.parsed]
- @staticmethod
- async def destroy(volume_id: str, **opts: Unpack[ApiParams]) -> bool:
+ @classmethod
+ async def destroy(cls, volume_id: str, **opts: Unpack[ApiParams]) -> bool:
"""
Destroy a volume.
:param volume_id: Volume ID
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_core_api_client(config)
res = await delete_volumes_volume_id.asyncio_detailed(
@@ -399,8 +404,8 @@ class AsyncVolume:
return convert_volume_entry_stat(cast(VolumeEntryStatApi, res.parsed))
- get_info = DualMethod(_class_get_info.__func__, _instance_get_info)
- list = DualMethod(_class_list.__func__, _instance_list)
+ get_info = DualMethod(_class_get_info, _instance_get_info)
+ list = DualMethod(_class_list, _instance_list)
async def update_metadata(
self,
diff --git a/packages/python-sdk/e2b/volume/volume_sync.py b/packages/python-sdk/e2b/volume/volume_sync.py
index b9dad9d51..eee5d1b1d 100644
--- a/packages/python-sdk/e2b/volume/volume_sync.py
+++ b/packages/python-sdk/e2b/volume/volume_sync.py
@@ -4,7 +4,7 @@ from http import HTTPStatus
import httpx
-from typing_extensions import Unpack
+from typing_extensions import Self, Unpack
from e2b.api import handle_api_exception
from e2b.api.client.api.volumes import (
@@ -19,7 +19,12 @@ from e2b.api.client.models import (
)
from e2b.api.client.types import Response
from e2b.api.client_sync import get_api_client as get_core_api_client
-from e2b.connection_config import ApiParams, ConnectionConfig, ProxyTypes
+from e2b.connection_config import (
+ ApiParams,
+ ClientFactory,
+ ConnectionConfig,
+ ProxyTypes,
+)
from e2b.exceptions import (
NotFoundException,
VolumeException,
@@ -61,7 +66,7 @@ from e2b.volume.utils import (
)
-class Volume:
+class Volume(ClientFactory):
"""E2B Volume for persistent storage that can be mounted to sandboxes."""
def __init__(
@@ -107,7 +112,7 @@ class Volume:
)
@classmethod
- def create(cls, name: str, **opts: Unpack[ApiParams]) -> "Volume":
+ def create(cls, name: str, **opts: Unpack[ApiParams]) -> Self:
"""
Create a new volume.
@@ -115,7 +120,7 @@ class Volume:
:return: A Volume instance for the new volume
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_core_api_client(config)
res = post_volumes.sync_detailed(
@@ -148,7 +153,7 @@ class Volume:
return vol
@classmethod
- def connect(cls, volume_id: str, **opts: Unpack[ApiParams]) -> "Volume":
+ def connect(cls, volume_id: str, **opts: Unpack[ApiParams]) -> Self:
"""
Connect to an existing volume by ID.
@@ -157,7 +162,7 @@ class Volume:
:return: A Volume instance for the existing volume
"""
info = cls.get_info(volume_id, **opts)
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
return cls(
volume_id=volume_id,
name=info.name,
@@ -167,8 +172,10 @@ class Volume:
proxy=config.proxy,
)
- @staticmethod
- def _class_get_info(volume_id: str, **opts: Unpack[ApiParams]) -> VolumeAndToken:
+ @classmethod
+ def _class_get_info(
+ cls, volume_id: str, **opts: Unpack[ApiParams]
+ ) -> VolumeAndToken:
"""
Get information about a volume.
@@ -176,7 +183,7 @@ class Volume:
:return: Volume info
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_core_api_client(config)
res = get_volumes_volume_id.sync_detailed(
@@ -208,14 +215,14 @@ class Volume:
domain=domain,
)
- @staticmethod
- def _class_list(**opts: Unpack[ApiParams]) -> List[VolumeInfo]:
+ @classmethod
+ def _class_list(cls, **opts: Unpack[ApiParams]) -> List[VolumeInfo]:
"""
List all volumes.
:return: List of volumes
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_core_api_client(config)
res = get_volumes.sync_detailed(
@@ -233,14 +240,14 @@ class Volume:
return [VolumeInfo(volume_id=v.volume_id, name=v.name) for v in res.parsed]
- @staticmethod
- def destroy(volume_id: str, **opts: Unpack[ApiParams]) -> bool:
+ @classmethod
+ def destroy(cls, volume_id: str, **opts: Unpack[ApiParams]) -> bool:
"""
Destroy a volume.
:param volume_id: Volume ID
"""
- config = ConnectionConfig(**opts)
+ config = ConnectionConfig(**cls._resolve_api_params(**opts))
api_client = get_core_api_client(config)
res = delete_volumes_volume_id.sync_detailed(
@@ -396,8 +403,8 @@ class Volume:
return convert_volume_entry_stat(cast(VolumeEntryStatApi, res.parsed))
- get_info = DualMethod(_class_get_info.__func__, _instance_get_info)
- list = DualMethod(_class_list.__func__, _instance_list)
+ get_info = DualMethod(_class_get_info, _instance_get_info)
+ list = DualMethod(_class_list, _instance_list)
def update_metadata(
self,
diff --git a/packages/python-sdk/tests/test_client.py b/packages/python-sdk/tests/test_client.py
new file mode 100644
index 000000000..21ad9dbc1
--- /dev/null
+++ b/packages/python-sdk/tests/test_client.py
@@ -0,0 +1,321 @@
+import asyncio
+import json
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from typing import Dict, List, Tuple
+
+import pytest
+
+from e2b import (
+ E2B,
+ AsyncSandbox,
+ AsyncSecret,
+ AsyncTemplate,
+ AsyncVolume,
+ Sandbox,
+ Secret,
+ Template,
+ Volume,
+)
+
+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": "base",
+ "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("/v2/sandboxes"):
+ self._record_and_respond(200, [])
+ elif self.path.startswith("/volumes"):
+ self._record_and_respond(200, [])
+ elif self.path.startswith("/templates/aliases/"):
+ self._record_and_respond(
+ 200,
+ {"aliases": [], "templateID": "tmpl-test", "public": False},
+ )
+ elif self.path.startswith("/templates/"):
+ self._record_and_respond(200, [])
+ elif self.path == "/secrets":
+ self._record_and_respond(200, [SECRET_RESPONSE])
+ elif self.path.startswith("/secrets/"):
+ self._record_and_respond(200, SECRET_RESPONSE)
+ else:
+ self._record_and_respond(404, {"code": 404, "message": "not found"})
+
+
+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)
+
+ _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 requests() -> List[Tuple[str, str, Dict[str, str]]]:
+ return _Handler.requests
+
+
+def api_keys() -> List[str]:
+ return [headers.get("x-api-key", "") for _, _, headers in 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.domain == DOMAIN_A
+ assert sandbox.connection_config.api_key == API_KEY_A
+
+
+def test_client_sandbox_is_a_subclass(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
+ assert isinstance(client.Sandbox.create(), client.Sandbox)
+ # Class-level defaults are inherited.
+ assert client.Sandbox.default_template == Sandbox.default_template
+ assert client.Sandbox.default_mcp_template == Sandbox.default_mcp_template
+ assert client.Sandbox.default_sandbox_timeout == Sandbox.default_sandbox_timeout
+
+
+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_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_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 sandbox.connection_config.api_key == API_KEY_A
+ assert sandbox.connection_config.domain == DOMAIN_A
+
+ client.Sandbox.list().next_items(api_key=None)
+ assert api_keys() == [API_KEY_A, 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_async_client_sandbox_uses_client_config(api_server):
+ client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)
+
+ async def run():
+ return await client.AsyncSandbox.create()
+
+ sandbox = asyncio.run(run())
+
+ assert issubclass(client.AsyncSandbox, AsyncSandbox)
+ assert isinstance(sandbox, client.AsyncSandbox)
+ 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_volume_uses_client_config(api_server):
+ client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)
+
+ volume = client.Volume.create("vol")
+ client.Volume.list()
+
+ assert issubclass(client.Volume, Volume)
+ assert isinstance(volume, client.Volume)
+ assert api_keys() == [API_KEY_A, API_KEY_A]
+
+
+def test_async_client_volume_uses_client_config(api_server):
+ client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)
+
+ async def run():
+ volume = await client.AsyncVolume.create("vol")
+ await client.AsyncVolume.list()
+ return volume
+
+ volume = asyncio.run(run())
+
+ assert issubclass(client.AsyncVolume, AsyncVolume)
+ assert isinstance(volume, client.AsyncVolume)
+ assert api_keys() == [API_KEY_A, API_KEY_A]
+
+
+def test_client_template_uses_client_config(api_server):
+ client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)
+
+ assert issubclass(client.Template, Template)
+ assert client.Template.exists("tmpl") is True
+ client.Template.get_tags("tmpl-test")
+
+ assert api_keys() == [API_KEY_A, API_KEY_A]
+ # Per-call params still win.
+ client.Template.get_tags("tmpl-test", api_key=API_KEY_B)
+ assert api_keys()[-1] == API_KEY_B
+
+
+def test_client_template_builder_is_usable(api_server):
+ client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)
+
+ template = client.Template().from_python_image("3")
+
+ assert client.Template.to_dockerfile(template) == Template.to_dockerfile(
+ Template().from_python_image("3")
+ )
+
+
+def test_async_client_template_uses_client_config(api_server):
+ client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)
+
+ async def run():
+ return await client.AsyncTemplate.exists("tmpl")
+
+ assert issubclass(client.AsyncTemplate, AsyncTemplate)
+ assert asyncio.run(run()) is True
+ assert api_keys() == [API_KEY_A]
+
+
+def test_client_secret_uses_client_config(api_server):
+ client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)
+
+ assert issubclass(client.Secret, Secret)
+
+ client.Secret.create("secret", "value")
+ client.Secret.get_info("secret")
+ client.Secret.list().next_items()
+
+ assert api_keys() == [API_KEY_A, API_KEY_A, API_KEY_A]
+ # Per-call params still win, and `None` does not erase the client's.
+ client.Secret.get_info("secret", api_key=API_KEY_B)
+ assert api_keys()[-1] == API_KEY_B
+ client.Secret.get_info("secret", api_key=None)
+ assert api_keys()[-1] == API_KEY_A
+
+
+def test_client_async_secret_uses_client_config(api_server):
+ client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)
+
+ async def run():
+ return await client.AsyncSecret.exists("secret")
+
+ assert issubclass(client.AsyncSecret, AsyncSecret)
+ assert asyncio.run(run()) is True
+ assert api_keys() == [API_KEY_A]
+
+
+def test_top_level_classes_keep_using_the_env_config(api_server):
+ sandbox = Sandbox.create(api_url=api_server)
+
+ assert api_keys() == [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 classes.
+ assert Sandbox._bound_api_params == {}
+ assert AsyncSandbox._bound_api_params == {}
+ assert Volume._bound_api_params == {}
+ assert AsyncVolume._bound_api_params == {}
+ assert Template._bound_api_params == {}
+ assert AsyncTemplate._bound_api_params == {}
+ assert Secret._bound_api_params == {}
+ assert AsyncSecret._bound_api_params == {}
+
+ assert Template.exists("tmpl", api_url=api_server) is True
+ assert api_keys()[-1] == ENV_API_KEY
+
+
+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