Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Add http_version / httpVersion connection option ("1.1" | "2", E2B_HTTP_VERSION, default "2") (#1920)
devin-ai-integration[bot]2f92cc333c3e
diff --git a/.changeset/code-interpreter-http-version.md b/.changeset/code-interpreter-http-version.mdnew file mode 100644index 000000000..cb46719b6--- /dev/null+++ b/.changeset/code-interpreter-http-version.md@@ -0,0 +1,5 @@+---+'@e2b/code-interpreter-python': patch+---++Pin the Jupyter transport to HTTP/1.1 with `get_transport(config, http_version="1.1")`, following the renamed argument in `e2b` 2.52.0 (now the minimum supported version).diff --git a/.changeset/http-version-option.md b/.changeset/http-version-option.mdnew file mode 100644index 000000000..e9531c8d0--- /dev/null+++ b/.changeset/http-version-option.md@@ -0,0 +1,6 @@+---+'e2b': minor+'@e2b/python-sdk': minor+---++Add an `http_version` (Python) / `httpVersion` (JS) connection option, `"1.1"` or `"2"` (default), also settable with the `E2B_HTTP_VERSION` environment variable, to pin requests to the E2B API, to sandboxes (commands, filesystem, PTY) and to volume content to HTTP/1.1. It can also be bound once on a client: `E2B(http_version="1.1")` / `new E2B({ httpVersion: '1.1' })`.diff --git a/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_async.py b/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_async.pyindex 072a531f0..5e9bd2521 100644--- a/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_async.py+++ b/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_async.py@@ -85,7 +85,7 @@ class AsyncSandbox(BaseAsyncSandbox):# TODO: Remove later# Use a dedicated HTTP/1.1 transport for Jupyter requests.#- # The base SDK's shared transport now defaults to http2=True. With+ # The base SDK's shared transport now defaults to HTTP/2. With# HTTP/2, multiple requests are multiplexed over a single TCP# connection, so when a client cancels a request (e.g. the caller# disconnects from the streaming `/execute` endpoint) the server@@ -98,7 +98,7 @@ class AsyncSandbox(BaseAsyncSandbox):# cancelled reliably. The helper also caches the transport# per-event-loop for async.return AsyncClient(- transport=get_transport(self.connection_config, http2=False),+ transport=get_transport(self.connection_config, http_version="1.1"),)async def _handle_connection_error(self, err: Exception) -> None:diff --git a/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_sync.py b/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_sync.pyindex ebabcfc7e..ec8e25a14 100644--- a/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_sync.py+++ b/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_sync.py@@ -82,7 +82,7 @@ class Sandbox(BaseSandbox):# TODO: Remove later# Use a dedicated HTTP/1.1 transport for Jupyter requests.#- # The base SDK's shared transport now defaults to http2=True. With+ # The base SDK's shared transport now defaults to HTTP/2. With# HTTP/2, multiple requests are multiplexed over a single TCP# connection, so when a client cancels a request (e.g. the caller# disconnects from the streaming `/execute` endpoint) the server@@ -93,7 +93,9 @@ class Sandbox(BaseSandbox):# connection and request, so client disconnects propagate to the# server as a TCP close and long-running executions can be# cancelled reliably.- return Client(transport=get_transport(self.connection_config, http2=False))+ return Client(+ transport=get_transport(self.connection_config, http_version="1.1")+ )def _handle_connection_error(self, err: Exception) -> None:"""diff --git a/packages/code-interpreter-python/pyproject.toml b/packages/code-interpreter-python/pyproject.tomlindex 1ee24f6ca..df334cdf4 100644--- a/packages/code-interpreter-python/pyproject.toml+++ b/packages/code-interpreter-python/pyproject.toml@@ -9,7 +9,7 @@ requires-python = ">=3.10"dependencies = ["httpx>=0.20.0,<1.0.0","attrs>=21.3.0",- "e2b>=2.44.0,<3.0.0",+ "e2b>=2.52.0,<3.0.0",][project.urls]diff --git a/packages/js-sdk/src/api/http2.ts b/packages/js-sdk/src/api/http2.tsindex 2a46c3fcb..41aaba410 100644--- a/packages/js-sdk/src/api/http2.ts+++ b/packages/js-sdk/src/api/http2.ts@@ -1,4 +1,5 @@import { runtime } from '../utils'+import { DEFAULT_HTTP_VERSION, type HttpVersion } from '../connectionConfig'import { parseInflightLimitEnv, parsePositiveIntEnv } from './metadata'import {buildDispatchedFetch,@@ -11,19 +12,27 @@ const DEFAULT_API_CONNECTION_LIMIT = 100// Override via env if your workload needs different.const DEFAULT_API_INFLIGHT_LIMIT = 1000-// Fetchers are cached per proxy so requests without a proxy keep sharing a-// single dispatcher while each distinct proxy URL gets its own.+// Fetchers are cached per proxy and HTTP version so requests without a proxy+// keep sharing a single dispatcher while each distinct proxy URL gets its own.const apiFetchers = new Map<string, typeof fetch>()-export function createApiFetch(proxy?: string): typeof fetch {- const key = proxy ?? ''+export interface FetchOpts {+ proxy?: string+ httpVersion?: HttpVersion+}++export function createApiFetch({+ proxy,+ httpVersion = DEFAULT_HTTP_VERSION,+}: FetchOpts = {}): typeof fetch {+ const key = `${httpVersion}:${proxy ?? ''}`const cached = apiFetchers.get(key)if (cached) {return cached}- const apiFetch = createApiFetchForRuntime(runtime, { proxy })+ const apiFetch = createApiFetchForRuntime(runtime, { proxy, httpVersion })apiFetchers.set(key, apiFetch)return apiFetch@@ -35,6 +44,7 @@ export function createApiFetchForRuntime(connectionLimit?: numberinflightLimit?: numberproxy?: string+ httpVersion?: HttpVersionloadUndici?: () => Promise<UndiciModule | undefined>} = {}): typeof fetch {@@ -45,6 +55,7 @@ export function createApiFetchForRuntime(connections: options.connectionLimit ?? getApiConnectionLimit(),inflightLimit: options.inflightLimit ?? getApiInflightLimit(),proxy: options.proxy,+ httpVersion: options.httpVersion,loadUndici: options.loadUndici,}))diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.tsindex 274491195..678bb4fea 100644--- a/packages/js-sdk/src/api/index.ts+++ b/packages/js-sdk/src/api/index.ts@@ -107,7 +107,7 @@ class ApiClient {this.api = createClient<paths>({baseUrl: config.apiUrl,fetch: withRetry(- createApiFetch(config.proxy),+ createApiFetch(config),config.retries,config.requestTimeoutMs),diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.tsindex 909bc72e6..0810a973e 100644--- a/packages/js-sdk/src/connectionConfig.ts+++ b/packages/js-sdk/src/connectionConfig.ts@@ -2,6 +2,7 @@ import { Logger } from './logs'import { getEnvVar, version } from './api/metadata'import { runtime } from './utils'import { resolveRetries } from './retry'+import { InvalidArgumentError } from './errors'// Remove once all deployments support sandbox subdomainsconst supportedDomains = ['e2b.app', 'e2b.dev', 'e2b.pro', 'e2b-staging.dev']@@ -12,6 +13,30 @@ export const KEEPALIVE_PING_INTERVAL_SEC = 50 // 50 secondsexport const KEEPALIVE_PING_HEADER = 'Keepalive-Ping-Interval'+/**+ * HTTP version the SDK speaks to the E2B API and to sandboxes.+ */+export type HttpVersion = '1.1' | '2'+export const DEFAULT_HTTP_VERSION: HttpVersion = '2'++/**+ * The HTTP version to use: the explicit value, else `E2B_HTTP_VERSION`, else+ * {@link DEFAULT_HTTP_VERSION}. Rejects anything but `'1.1'` or `'2'`.+ */+export function resolveHttpVersion(httpVersion?: string): HttpVersion {+ let source = 'httpVersion'+ if (httpVersion === undefined) {+ source = 'E2B_HTTP_VERSION'+ httpVersion = getEnvVar('E2B_HTTP_VERSION') || DEFAULT_HTTP_VERSION+ }+ if (httpVersion !== '1.1' && httpVersion !== '2') {+ throw new InvalidArgumentError(+ `${source} must be '1.1' or '2', got '${httpVersion}'`+ )+ }+ return httpVersion+}+/*** Connection options for requests to the API.*/@@ -94,6 +119,16 @@ export interface ConnectionOpts {* @example 'http://user:[email protected]:8080'*/proxy?: string+ /**+ * HTTP version for requests to the E2B API and to sandboxes (commands,+ * filesystem, PTY). `'2'` multiplexes streams over shared connections;+ * `'1.1'` pins them to HTTP/1.1 with one connection per concurrent+ * request — for example when an intermediary on the path retires or+ * mishandles long-lived HTTP/2 connections. Only applies in Node.+ *+ * @default E2B_HTTP_VERSION // environment variable or `'2'`+ */+ httpVersion?: HttpVersion/*** Additional headers to send with E2B API requests.@@ -446,6 +481,7 @@ export class ConnectionConfig {readonly requestSource?: stringreadonly proxy?: string+ readonly httpVersion: HttpVersionconstructor(opts?: ConnectionOpts) {this.apiKey = opts?.apiKey || ConnectionConfig.apiKey@@ -459,6 +495,7 @@ export class ConnectionConfig {this.headers = { ...(opts?.headers ?? {}), ...(opts?.apiHeaders ?? {}) }ConnectionConfig.applyUserAgent(this.headers, this.requestSource)this.proxy = opts?.proxy+ this.httpVersion = resolveHttpVersion(opts?.httpVersion)this.apiUrl =opts?.apiUrl ||diff --git a/packages/js-sdk/src/envd/http2.ts b/packages/js-sdk/src/envd/http2.tsindex db674df3c..ccf31d24a 100644--- a/packages/js-sdk/src/envd/http2.ts+++ b/packages/js-sdk/src/envd/http2.ts@@ -1,4 +1,6 @@import { runtime } from '../utils'+import { DEFAULT_HTTP_VERSION, type HttpVersion } from '../connectionConfig'+import type { FetchOpts } from '../api/http2'import { parseInflightLimitEnv, parsePositiveIntEnv } from '../api/metadata'import {buildDispatchedFetch,@@ -10,11 +12,12 @@ type EnvdFetchOptions = {connectionLimit?: numberinflightLimit?: numberproxy?: string+ httpVersion?: HttpVersionloadUndici?: () => Promise<UndiciModule | undefined>}-// Fetchers are cached per proxy so requests without a proxy keep sharing a-// single dispatcher while each distinct proxy URL gets its own.+// Fetchers are cached per proxy and HTTP version so requests without a proxy+// keep sharing a single dispatcher while each distinct proxy URL gets its own.const envdFetchers = new Map<string, typeof fetch>()const envdRpcFetchers = new Map<string, typeof fetch>()const DEFAULT_ENVD_CONNECTION_LIMIT = 10@@ -31,13 +34,24 @@ export function createEnvdFetchForRuntime(connections: options.connectionLimit ?? DEFAULT_ENVD_CONNECTION_LIMIT,inflightLimit: options.inflightLimit ?? 0,proxy: options.proxy,+ httpVersion: options.httpVersion,loadUndici: options.loadUndici,}))}-export function createEnvdFetch(proxy?: string): typeof fetch {- const key = proxy ?? ''+function fetcherKey(+ proxy: string | undefined,+ httpVersion: HttpVersion+): string {+ return `${httpVersion}:${proxy ?? ''}`+}++export function createEnvdFetch({+ proxy,+ httpVersion = DEFAULT_HTTP_VERSION,+}: FetchOpts = {}): typeof fetch {+ const key = fetcherKey(proxy, httpVersion)const cached = envdFetchers.get(key)if (cached) {@@ -49,14 +63,18 @@ export function createEnvdFetch(proxy?: string): typeof fetch {const envdFetch = createEnvdFetchForRuntime(runtime, {inflightLimit: getEnvdInflightLimit(),proxy,+ httpVersion,})envdFetchers.set(key, envdFetch)return envdFetch}-export function createEnvdRpcFetch(proxy?: string): typeof fetch {- const key = proxy ?? ''+export function createEnvdRpcFetch({+ proxy,+ httpVersion = DEFAULT_HTTP_VERSION,+}: FetchOpts = {}): typeof fetch {+ const key = fetcherKey(proxy, httpVersion)const cached = envdRpcFetchers.get(key)if (cached) {@@ -67,6 +85,7 @@ export function createEnvdRpcFetch(proxy?: string): typeof fetch {connectionLimit: getEnvdRpcConnectionLimit(),inflightLimit: getEnvdRpcInflightLimit(),proxy,+ httpVersion,})envdRpcFetchers.set(key, envdRpcFetch)diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.tsindex 1a49508e6..afe6917fc 100644--- a/packages/js-sdk/src/index.ts+++ b/packages/js-sdk/src/index.ts@@ -5,6 +5,7 @@ export { ConnectionConfig } from './connectionConfig'export type {ConnectionConfigOpts,ConnectionOpts,+ HttpVersion,Username,} from './connectionConfig'export {diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.tsindex f9964e2b1..5f0c6f2f5 100644--- a/packages/js-sdk/src/sandbox/index.ts+++ b/packages/js-sdk/src/sandbox/index.ts@@ -161,8 +161,8 @@ export class Sandbox extends SandboxApi {'E2b-Sandbox-Id': this.sandboxId,'E2b-Sandbox-Port': this.envdPort.toString(),}- const envdFetch = createEnvdFetch(this.connectionConfig.proxy)- const envdRpcFetch = createEnvdRpcFetch(this.connectionConfig.proxy)+ const envdFetch = createEnvdFetch(this.connectionConfig)+ const envdRpcFetch = createEnvdRpcFetch(this.connectionConfig)const rpcTransport = createConnectTransport({baseUrl: this.envdApiUrl,diff --git a/packages/js-sdk/src/undici.ts b/packages/js-sdk/src/undici.tsindex 74a2fd102..86f4b9f34 100644--- a/packages/js-sdk/src/undici.ts+++ b/packages/js-sdk/src/undici.ts@@ -3,6 +3,7 @@ import { compareVersions } from 'compare-versions'import { limitConcurrency } from './api/inflight'import { isReadableStreamLike, isRequestLike } from './is'import { dynamicImport, toDispatchableStream } from './utils'+import { DEFAULT_HTTP_VERSION, type HttpVersion } from './connectionConfig'type UndiciRequestInit = RequestInit & {dispatcher?: unknown@@ -10,10 +11,10 @@ type UndiciRequestInit = RequestInit & {}export type UndiciModule = {- Agent: new (options: { allowH2: true; connections?: number }) => unknown+ Agent: new (options: { allowH2: boolean; connections?: number }) => unknownProxyAgent: new (options: {uri: string- allowH2: true+ allowH2: booleanconnections?: numberproxyTunnel: true}) => unknown@@ -87,15 +88,17 @@ export function createRuntimeFetch(}/**- * Build a fetch bound to a bounded undici dispatcher (HTTP/2 enabled,- * `connections` origin connections, optional proxy tunnel), capped at- * `inflightLimit` in-flight requests (`0` disables the cap). Falls back to- * the global fetch — still capped — when undici cannot be loaded.+ * Build a fetch bound to a bounded undici dispatcher (HTTP/2 enabled unless+ * `httpVersion` is `'1.1'`, `connections` origin connections, optional proxy+ * tunnel), capped at `inflightLimit` in-flight requests (`0` disables the+ * cap). Falls back to the global fetch — still capped — when undici cannot be+ * loaded.*/export async function buildDispatchedFetch(options: {connections: numberinflightLimit: numberproxy?: string+ httpVersion?: HttpVersionloadUndici?: () => Promise<UndiciModule | undefined>}): Promise<typeof fetch> {const undici = await (options.loadUndici ?? loadUndici)()@@ -105,15 +108,16 @@ export async function buildDispatchedFetch(options: {}const { Agent, ProxyAgent, fetch: undiciFetch } = undici+ const allowH2 = (options.httpVersion ?? DEFAULT_HTTP_VERSION) === '2'const dispatcher = options.proxy? new ProxyAgent({uri: options.proxy,- allowH2: true,+ allowH2,connections: options.connections,proxyTunnel: true,}): new Agent({- allowH2: true,+ allowH2,connections: options.connections,})const fetchWithDispatcher = undiciFetch as unknown as (diff --git a/packages/js-sdk/src/volume/client.ts b/packages/js-sdk/src/volume/client.tsindex cda7944e5..0b7b9a730 100644--- a/packages/js-sdk/src/volume/client.ts+++ b/packages/js-sdk/src/volume/client.ts@@ -3,7 +3,12 @@ import createClient from 'openapi-fetch'import type { components, paths } from './schema.gen'import { defaultHeaders, getEnvVar } from '../api/metadata'import { createApiFetch } from '../api/http2'-import { buildRequestSignal, REQUEST_TIMEOUT_MS } from '../connectionConfig'+import {+ buildRequestSignal,+ HttpVersion,+ REQUEST_TIMEOUT_MS,+ resolveHttpVersion,+} from '../connectionConfig'import { createApiLogger, Logger } from '../logs'import type { Volume } from './index'@@ -57,6 +62,13 @@ export interface VolumeApiOpts {*/proxy?: string+ /**+ * HTTP version for requests to the volume content API: `'1.1'` or `'2'`.+ *+ * @default E2B_HTTP_VERSION // environment variable or `'2'`+ */+ httpVersion?: HttpVersion+/*** An optional `AbortSignal` that can be used to cancel the in-flight request.* When the signal is aborted, the underlying `fetch` is aborted and the@@ -75,6 +87,7 @@ export class VolumeConnectionConfig {readonly requestTimeoutMs: numberreadonly signal?: AbortSignalreadonly proxy?: string+ readonly httpVersion: HttpVersionconstructor(volume: Volume, opts?: VolumeApiOpts) {this.domain = opts?.domain || volume.domain || VolumeConnectionConfig.domain@@ -89,6 +102,9 @@ export class VolumeConnectionConfig {this.requestTimeoutMs = opts?.requestTimeoutMs ?? REQUEST_TIMEOUT_MSthis.signal = opts?.signalthis.proxy = opts?.proxy || volume.proxy+ this.httpVersion = resolveHttpVersion(+ opts?.httpVersion ?? volume.httpVersion+ )}private static get domain() {@@ -120,7 +136,7 @@ class VolumeApiClient {constructor(config: VolumeConnectionConfig) {this.api = createClient<paths>({baseUrl: config.apiUrl,- fetch: createApiFetch(config.proxy),+ fetch: createApiFetch(config),headers: {...defaultHeaders,...(config.token && { Authorization: `Bearer ${config.token}` }),diff --git a/packages/js-sdk/src/volume/index.ts b/packages/js-sdk/src/volume/index.tsindex 4563d0f9d..da6d8a65f 100644--- a/packages/js-sdk/src/volume/index.ts+++ b/packages/js-sdk/src/volume/index.ts@@ -10,6 +10,7 @@ import {ClientFactory,ConnectionConfig,ConnectionOpts,+ HttpVersion,setupRequestController,wrapStreamWithConnectionCleanup,} from '../connectionConfig'@@ -82,6 +83,11 @@ export class Volume extends ClientFactory {*/readonly proxy?: string+ /**+ * HTTP version used for requests to the volume content API.+ */+ readonly httpVersion?: HttpVersion+/*** Create a local Volume instance with no API call.*@@ -91,6 +97,7 @@ export class Volume extends ClientFactory {* @param domain domain for the volume API.* @param debug whether to use debug mode.* @param proxy proxy URL for the volume content API.+ * @param opts connection options kept for the volume content API.*/constructor(volumeId: string,@@ -98,7 +105,8 @@ export class Volume extends ClientFactory {token: string,domain?: string,debug?: boolean,- proxy?: string+ proxy?: string,+ opts?: Pick<ConnectionOpts, 'httpVersion'>) {super()this.volumeId = volumeId@@ -107,6 +115,7 @@ export class Volume extends ClientFactory {this.domain = domainthis.debug = debugthis.proxy = proxy+ this.httpVersion = opts?.httpVersion}/**@@ -148,7 +157,8 @@ export class Volume extends ClientFactory {res.data.token,res.data.domain || config.domain,config.debug,- config.proxy+ config.proxy,+ { httpVersion: config.httpVersion }) as InstanceType<V>}@@ -174,7 +184,8 @@ export class Volume extends ClientFactory {token,domain ?? config.domain,config.debug,- config.proxy+ config.proxy,+ { httpVersion: config.httpVersion }) as InstanceType<V>}diff --git a/packages/js-sdk/tests/api/http2.test.ts b/packages/js-sdk/tests/api/http2.test.tsindex 3238e16b7..a1cc6fe18 100644--- a/packages/js-sdk/tests/api/http2.test.ts+++ b/packages/js-sdk/tests/api/http2.test.ts@@ -144,17 +144,44 @@ test('late-binds the global fetch fallback when undici cannot be loaded', async}})-test('caches API fetchers per proxy', async () => {+test('pins the API dispatcher to HTTP/1.1 when httpVersion is http1', async () => {+ const agents: Array<{ allowH2?: boolean; connections?: number }> = []++ class Agent {+ constructor(options: { allowH2?: boolean; connections?: number }) {+ agents.push(options)+ }+ }++ const undiciFetch = vi.fn(() => Promise.resolve(new Response('ok')))++ const { createApiFetchForRuntime } = await import('../../src/api/http2')++ const fetcher = createApiFetchForRuntime('node', {+ connectionLimit: 3,+ httpVersion: '1.1',+ loadUndici: () => Promise.resolve({ Agent, fetch: undiciFetch }),+ })+ await fetcher('https://api.e2b.app/sandboxes')++ expect(agents).toEqual([{ allowH2: false, connections: 3 }])+})++test('caches API fetchers per proxy and HTTP version', async () => {const { createApiFetch } = await import('../../src/api/http2')const noProxy = createApiFetch()- const proxyA = createApiFetch('http://127.0.0.1:8080')- const proxyB = createApiFetch('http://127.0.0.1:9090')+ const proxyA = createApiFetch({ proxy: 'http://127.0.0.1:8080' })+ const proxyB = createApiFetch({ proxy: 'http://127.0.0.1:9090' })+ const noProxyH1 = createApiFetch({ httpVersion: '1.1' })expect(createApiFetch()).toBe(noProxy)- expect(createApiFetch('http://127.0.0.1:8080')).toBe(proxyA)+ expect(createApiFetch({ httpVersion: '2' })).toBe(noProxy)+ expect(createApiFetch({ proxy: 'http://127.0.0.1:8080' })).toBe(proxyA)+ expect(createApiFetch({ httpVersion: '1.1' })).toBe(noProxyH1)expect(proxyA).not.toBe(noProxy)expect(proxyA).not.toBe(proxyB)+ expect(noProxyH1).not.toBe(noProxy)})test('getApiConnectionLimit throws on a malformed env value', async () => {diff --git a/packages/js-sdk/tests/client.test.ts b/packages/js-sdk/tests/client.test.tsindex 3364bd191..4c96db88b 100644--- a/packages/js-sdk/tests/client.test.ts+++ b/packages/js-sdk/tests/client.test.ts@@ -345,6 +345,22 @@ test('client.Volume.create uses the client config', async () => {assert.equal(lastRequest().url, `https://api.${DOMAIN_A}/volumes`)})+test('client httpVersion is bound and carried by volumes', async () => {+ const client = new E2B({+ apiKey: API_KEY_A,+ domain: DOMAIN_A,+ httpVersion: '1.1',+ })++ assert.equal((await client.Volume.create('test-volume')).httpVersion, '1.1')+ // A per-call value overrides the bound one.+ assert.equal(+ (await client.Volume.create('test-volume', { httpVersion: '2' }))+ .httpVersion,+ '2'+ )+})+test('client.Template statics use the client config', async () => {const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })diff --git a/packages/js-sdk/tests/connectionConfig.test.ts b/packages/js-sdk/tests/connectionConfig.test.tsindex 8030249a6..2b7df98f4 100644--- a/packages/js-sdk/tests/connectionConfig.test.ts+++ b/packages/js-sdk/tests/connectionConfig.test.ts@@ -6,6 +6,7 @@ import {wrapStreamWithConnectionCleanup,} from '../src/connectionConfig'import { runtime } from '../src/utils'+import { InvalidArgumentError } from '../src/errors'// Store original env vars to restore after testslet originalEnv: { [key: string]: string | undefined }@@ -15,6 +16,7 @@ beforeEach(() => {E2B_API_URL: process.env.E2B_API_URL,E2B_DOMAIN: process.env.E2B_DOMAIN,E2B_SANDBOX_URL: process.env.E2B_SANDBOX_URL,+ E2B_HTTP_VERSION: process.env.E2B_HTTP_VERSION,E2B_DEBUG: process.env.E2B_DEBUG,E2B_USER_AGENT_SOURCE: process.env.E2B_USER_AGENT_SOURCE,}@@ -164,6 +166,46 @@ test('sandbox_url stays localhost in debug mode', () => {)})+test('httpVersion defaults to http2 and reads E2B_HTTP_VERSION', () => {+ delete process.env.E2B_HTTP_VERSION+ assert.equal(new ConnectionConfig().httpVersion, '2')+ assert.equal(new ConnectionConfig({ httpVersion: '1.1' }).httpVersion, '1.1')++ process.env.E2B_HTTP_VERSION = '1.1'+ assert.equal(new ConnectionConfig().httpVersion, '1.1')+ process.env.E2B_HTTP_VERSION = '2'+ assert.equal(new ConnectionConfig().httpVersion, '2')++ process.env.E2B_HTTP_VERSION = 'http3'+ assert.throws(() => new ConnectionConfig(), InvalidArgumentError)+ assert.throws(() => new ConnectionConfig(), /E2B_HTTP_VERSION/)+ // An explicit option never consults the environment.+ assert.equal(new ConnectionConfig({ httpVersion: '1.1' }).httpVersion, '1.1')+})++test('httpVersion rejects values other than 1.1 and 2', () => {+ delete process.env.E2B_HTTP_VERSION+ for (const value of ['http1', 'http2', '1', '2.0', 'HTTP/1.1', '']) {+ assert.throws(+ () => new ConnectionConfig({ httpVersion: value as HttpVersion }),+ InvalidArgumentError+ )+ assert.throws(+ () => new ConnectionConfig({ httpVersion: value as HttpVersion }),+ /httpVersion must be '1.1' or '2'/+ )+ }+})++test('httpVersion in args has priority over env var', () => {+ process.env.E2B_HTTP_VERSION = '1.1'+ assert.equal(new ConnectionConfig({ httpVersion: '2' }).httpVersion, '2')++ // Per-call options and bound options keep the option when merged.+ const merged = ConnectionConfig.mergeOpts({ httpVersion: '1.1' }, {})+ assert.equal(new ConnectionConfig(merged).httpVersion, '1.1')+})+test('debug false in args overrides E2B_DEBUG env var', () => {process.env.E2B_DEBUG = 'true'diff --git a/packages/js-sdk/tests/envd/http2.test.ts b/packages/js-sdk/tests/envd/http2.test.tsindex ed553f888..907c88cf1 100644--- a/packages/js-sdk/tests/envd/http2.test.ts+++ b/packages/js-sdk/tests/envd/http2.test.ts@@ -89,23 +89,78 @@ test('uses a ProxyAgent dispatcher when a proxy is configured', async () => {expect(requests[0].init?.dispatcher).toBeInstanceOf(ProxyAgent)})-test('caches envd fetchers per proxy', async () => {+test('pins the dispatcher to HTTP/1.1 when httpVersion is http1', async () => {+ const agents: Array<{ allowH2?: boolean; connections?: number }> = []+ const proxyAgents: Array<{ uri?: string; allowH2?: boolean }> = []++ class Agent {+ constructor(options: { allowH2?: boolean; connections?: number }) {+ agents.push(options)+ }+ }++ class ProxyAgent {+ constructor(options: { uri?: string; allowH2?: boolean }) {+ proxyAgents.push(options)+ }+ }++ const undiciFetch = vi.fn(() => Promise.resolve(new Response('ok')))++ const { createEnvdFetchForRuntime } = await import('../../src/envd/http2')++ const direct = createEnvdFetchForRuntime('node', {+ connectionLimit: 1,+ httpVersion: '1.1',+ loadUndici: () =>+ Promise.resolve({ Agent, ProxyAgent, fetch: undiciFetch }),+ })+ await direct('https://example.com/status')++ const proxied = createEnvdFetchForRuntime('node', {+ connectionLimit: 1,+ httpVersion: '1.1',+ proxy: 'http://127.0.0.1:8080',+ loadUndici: () =>+ Promise.resolve({ Agent, ProxyAgent, fetch: undiciFetch }),+ })+ await proxied('https://example.com/status')++ expect(agents).toEqual([{ allowH2: false, connections: 1 }])+ expect(proxyAgents).toEqual([+ {+ uri: 'http://127.0.0.1:8080',+ allowH2: false,+ connections: 1,+ proxyTunnel: true,+ },+ ])+})++test('caches envd fetchers per proxy and HTTP version', async () => {const { createEnvdFetch, createEnvdRpcFetch } =await import('../../src/envd/http2')const noProxy = createEnvdFetch()- const proxyA = createEnvdFetch('http://127.0.0.1:8080')+ const proxyA = createEnvdFetch({ proxy: 'http://127.0.0.1:8080' })+ const noProxyH1 = createEnvdFetch({ httpVersion: '1.1' })expect(createEnvdFetch()).toBe(noProxy)- expect(createEnvdFetch('http://127.0.0.1:8080')).toBe(proxyA)+ expect(createEnvdFetch({ httpVersion: '2' })).toBe(noProxy)+ expect(createEnvdFetch({ proxy: 'http://127.0.0.1:8080' })).toBe(proxyA)+ expect(createEnvdFetch({ httpVersion: '1.1' })).toBe(noProxyH1)expect(proxyA).not.toBe(noProxy)+ expect(noProxyH1).not.toBe(noProxy)const rpcNoProxy = createEnvdRpcFetch()- const rpcProxyA = createEnvdRpcFetch('http://127.0.0.1:8080')+ const rpcProxyA = createEnvdRpcFetch({ proxy: 'http://127.0.0.1:8080' })+ const rpcNoProxyH1 = createEnvdRpcFetch({ httpVersion: '1.1' })expect(createEnvdRpcFetch()).toBe(rpcNoProxy)- expect(createEnvdRpcFetch('http://127.0.0.1:8080')).toBe(rpcProxyA)+ expect(createEnvdRpcFetch({ proxy: 'http://127.0.0.1:8080' })).toBe(rpcProxyA)+ expect(createEnvdRpcFetch({ httpVersion: '1.1' })).toBe(rpcNoProxyH1)expect(rpcProxyA).not.toBe(rpcNoProxy)+ expect(rpcNoProxyH1).not.toBe(rpcNoProxy)})test('passes Request objects to undici as URL plus init', async () => {diff --git a/packages/js-sdk/tests/sandbox/httpVersion.test.ts b/packages/js-sdk/tests/sandbox/httpVersion.test.tsnew file mode 100644index 000000000..d01d48e0b--- /dev/null+++ b/packages/js-sdk/tests/sandbox/httpVersion.test.ts@@ -0,0 +1,75 @@+import { afterEach, expect, test, vi } from 'vitest'++const mocks = vi.hoisted(() => ({+ createEnvdFetch: vi.fn(() => vi.fn()),+ createEnvdRpcFetch: vi.fn(() => vi.fn()),+}))++vi.mock('@connectrpc/connect-web', () => ({+ createConnectTransport: vi.fn(() => ({})),+}))++vi.mock('../../src/envd/http2', () => ({+ createEnvdFetch: mocks.createEnvdFetch,+ createEnvdRpcFetch: mocks.createEnvdRpcFetch,+}))++afterEach(() => {+ vi.clearAllMocks()+ delete process.env.E2B_HTTP_VERSION+})++async function createSandbox(opts: {+ httpVersion?: '1.1' | '2'+ proxy?: string+}) {+ const { ConnectionConfig, Sandbox } = await import('../../src')+ const config = new ConnectionConfig(opts)+ return new Sandbox({+ ...config,+ sandboxId: 'sbx-test',+ sandboxDomain: 'sandbox.e2b.dev',+ envdVersion: '0.2.4',+ envdAccessToken: 'tok',+ })+}++test('envd fetchers default to HTTP/2', async () => {+ await createSandbox({})++ expect(mocks.createEnvdFetch.mock.calls[0][0]).toMatchObject({+ proxy: undefined,+ httpVersion: '2',+ })+ expect(mocks.createEnvdRpcFetch.mock.calls[0][0]).toMatchObject({+ proxy: undefined,+ httpVersion: '2',+ })+})++test('httpVersion: 1.1 pins envd HTTP and RPC fetchers to HTTP/1.1', async () => {+ await createSandbox({ httpVersion: '1.1', proxy: 'http://127.0.0.1:8080' })++ expect(mocks.createEnvdFetch.mock.calls[0][0]).toMatchObject({+ proxy: 'http://127.0.0.1:8080',+ httpVersion: '1.1',+ })+ expect(mocks.createEnvdRpcFetch.mock.calls[0][0]).toMatchObject({+ proxy: 'http://127.0.0.1:8080',+ httpVersion: '1.1',+ })+})++test('E2B_HTTP_VERSION=1.1 pins envd fetchers to HTTP/1.1', async () => {+ process.env.E2B_HTTP_VERSION = '1.1'+ await createSandbox({})++ expect(mocks.createEnvdFetch.mock.calls[0][0]).toMatchObject({+ proxy: undefined,+ httpVersion: '1.1',+ })+ expect(mocks.createEnvdRpcFetch.mock.calls[0][0]).toMatchObject({+ proxy: undefined,+ httpVersion: '1.1',+ })+})diff --git a/packages/js-sdk/tests/volume/httpVersion.test.ts b/packages/js-sdk/tests/volume/httpVersion.test.tsnew file mode 100644index 000000000..f4e40836f--- /dev/null+++ b/packages/js-sdk/tests/volume/httpVersion.test.ts@@ -0,0 +1,70 @@+import { afterEach, expect, test, vi } from 'vitest'++const mocks = vi.hoisted(() => ({+ createApiFetch: vi.fn(() => vi.fn()),+}))++vi.mock('../../src/api/http2', () => ({+ createApiFetch: mocks.createApiFetch,+}))++afterEach(() => {+ vi.clearAllMocks()+ delete process.env.E2B_HTTP_VERSION+})++async function createContentClient(+ httpVersion?: '1.1' | '2',+ opts?: { httpVersion?: '1.1' | '2'; proxy?: string }+) {+ const { Volume } = await import('../../src')+ const { VolumeApiClient, VolumeConnectionConfig } =+ await import('../../src/volume/client')+ const volume = new Volume(+ 'vol-id',+ 'vol',+ 'vol-token',+ undefined,+ undefined,+ opts?.proxy,+ { httpVersion }+ )+ return new VolumeApiClient(new VolumeConnectionConfig(volume, opts))+}++test('volume content fetch defaults to HTTP/2', async () => {+ await createContentClient()++ expect(mocks.createApiFetch.mock.calls[0][0]).toMatchObject({+ proxy: undefined,+ httpVersion: '2',+ })+})++test('volume content fetch follows the httpVersion kept on the instance', async () => {+ await createContentClient('1.1', { proxy: 'http://127.0.0.1:8080' })++ expect(mocks.createApiFetch.mock.calls[0][0]).toMatchObject({+ proxy: 'http://127.0.0.1:8080',+ httpVersion: '1.1',+ })+})++test('a per-call httpVersion overrides the instance value', async () => {+ await createContentClient('1.1', { httpVersion: '2' })++ expect(mocks.createApiFetch.mock.calls[0][0]).toMatchObject({+ proxy: undefined,+ httpVersion: '2',+ })+})++test('E2B_HTTP_VERSION=1.1 pins volume content fetch to HTTP/1.1', async () => {+ process.env.E2B_HTTP_VERSION = '1.1'+ await createContentClient()++ expect(mocks.createApiFetch.mock.calls[0][0]).toMatchObject({+ proxy: undefined,+ httpVersion: '1.1',+ })+})diff --git a/packages/js-sdk/tests/volume/volume.test.ts b/packages/js-sdk/tests/volume/volume.test.tsindex c4460dbb8..a308d0d6f 100644--- a/packages/js-sdk/tests/volume/volume.test.ts+++ b/packages/js-sdk/tests/volume/volume.test.ts@@ -189,6 +189,18 @@ describe('Volume CRUD', () => {expect(config.proxy).toBe('http://127.0.0.1:9090')})+ it('should keep the httpVersion on the instance so content calls reuse it', async () => {+ const vol = await Volume.create('http1-volume', { httpVersion: '1.1' })+ expect(vol.httpVersion).toBe('1.1')+ expect(new VolumeConnectionConfig(vol).httpVersion).toBe('1.1')+ expect(+ new VolumeConnectionConfig(vol, { httpVersion: '2' }).httpVersion+ ).toBe('2')++ const connected = await Volume.connect(vol.volumeId, { httpVersion: '1.1' })+ expect(connected.httpVersion).toBe('1.1')+ })+it('should handle full lifecycle: create, get, list, destroy', async () => {// Createconst vol = await Volume.create('lifecycle-vol')diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.pyindex ff010de53..f8371b895 100644--- a/packages/python-sdk/e2b/__init__.py+++ b/packages/python-sdk/e2b/__init__.py@@ -32,6 +32,7 @@ from .api import (from .connection_config import (ApiParams,ConnectionConfig,+ HttpVersion,ProxyTypes,Username,)@@ -171,6 +172,7 @@ __all__ = [# Connection config"ConnectionConfig","VolumeConnectionConfig",+ "HttpVersion","ProxyTypes","ApiParams","VolumeApiParams",diff --git a/packages/python-sdk/e2b/api/client_async/__init__.py b/packages/python-sdk/e2b/api/client_async/__init__.pyindex 711ef14ee..af37aa5b8 100644--- a/packages/python-sdk/e2b/api/client_async/__init__.py+++ b/packages/python-sdk/e2b/api/client_async/__init__.py@@ -20,7 +20,12 @@ from e2b.api import (proxy_to_config,request_origin,)-from e2b.connection_config import READ_TIMEOUT, ConnectionConfig+from e2b.connection_config import (+ DEFAULT_HTTP_VERSION,+ READ_TIMEOUT,+ ConnectionConfig,+ HttpVersion,+)def get_api_client(config: ConnectionConfig, **kwargs) -> AsyncApiClient:@@ -132,7 +137,7 @@ class BalancingTransport(Transport):)-_TransportKey = Tuple[Optional[ProxyConfig], Optional[float], bool]+_TransportKey = Tuple[Optional[ProxyConfig], Optional[float], HttpVersion]"""Cache key: proxy, idle read bound, HTTP version — fixed when a pyqwesttransport is constructed, so each distinct combination is necessarily its owntransport."""@@ -155,7 +160,8 @@ _httpx_transports: Dict[_TransportKey, AsyncPyqwestTransport] = {}def get_pyqwest_transport(proxy: Optional[ProxyConfig],read_timeout: Optional[float] = None,- http2: bool = True,+ *,+ http_version: HttpVersion = DEFAULT_HTTP_VERSION,) -> ConnectionRetryTransport:"""The shared pyqwest transport with the SDK's tuning — system CA certs(without which TLS through an intercepting proxy fails) and the@@ -170,10 +176,10 @@ def get_pyqwest_transport(RPC stack's plain-HTTP-error normalization wraps it, headers and codecs areper-request — so that the pools stay shareable.- ``read_timeout`` bounds every read on the pools' connections and ``http2``- fixes the HTTP version; both are part of the cache key because they are- transport-construction knobs, so one pool cannot serve two values of- either. reqwest's read timer keeps running while a request body is sent and+ ``read_timeout`` bounds every read on the pools' connections and+ ``http_version`` fixes the HTTP version; both are part of the cache key+ because they are transport-construction knobs, so one pool cannot serve two+ values of either. reqwest's read timer keeps running while a request body is sent andwhile waiting for the response head, so a pool carrying one would cut offlong uploads and slow responses — only streamed downloads ask for it, as anidle bound (see :func:`get_transport`).@@ -182,7 +188,7 @@ def get_pyqwest_transport(``pyqwest`` loggers at ``DEBUG`` (off unless enabled) — the transport-leveldiagnostics httpcore used to provide. The SDK's own ``logger`` option isseparate and sits above this, on the httpx client."""- key = (proxy, read_timeout, http2)+ key = (proxy, read_timeout, http_version)def build() -> HTTPTransport:return HTTPTransport(@@ -194,7 +200,7 @@ def get_pyqwest_transport(# `None` leaves the version to ALPN on TLS connections (HTTP/2# against the E2B API and envd) and uses HTTP/1 for plaintext,# like the http2-enabled httpx transport this replaced.- http_version=None if http2 else HTTPVersion.HTTP1,+ http_version=HTTPVersion.HTTP1 if http_version == "1.1" else None,# Redirects belong to the httpx client above (which the generated# clients leave off), not to reqwest.follow_redirects=False,@@ -213,16 +219,17 @@ def get_pyqwest_transport(def get_httpx_transport(proxy: Optional[ProxyConfig],read_timeout: Optional[float] = None,- http2: bool = True,+ *,+ http_version: HttpVersion = DEFAULT_HTTP_VERSION,) -> AsyncPyqwestTransport:"""The httpx adapter over the shared transport of:func:`get_pyqwest_transport`, for the generated httpx clients (controlplane, envd HTTP API, volume content). The adapter holds no state of itsown and does not close the pools, so closing an httpx client leaves themintact for the other clients on it."""- key = (proxy, read_timeout, http2)+ key = (proxy, read_timeout, http_version)# Resolve the pool before taking the lock: it takes the same one.- pool = get_pyqwest_transport(proxy, read_timeout, http2)+ pool = get_pyqwest_transport(proxy, read_timeout, http_version=http_version)with _transport_lock:transport = _httpx_transports.get(key)if transport is None:@@ -233,8 +240,8 @@ def get_httpx_transport(def get_transport(config: ConnectionConfig,- http2: bool = True,*,+ http_version: Optional[HttpVersion] = None,for_streaming: bool = False,) -> AsyncPyqwestTransport:"""The shared httpx transport factory for the control-plane REST API and@@ -242,10 +249,11 @@ def get_transport(negotiates the HTTP version (HTTP/2 against the E2B API), like thehttp2-enabled httpx transport this replaced.- ``http2=False`` returns a separate transport (its own pool) pinned to- HTTP/1.1. That matters for a server that reacts to a client going away:- HTTP/2 multiplexes requests over one connection, so abandoning a request- only resets its stream and the server may never notice, while HTTP/1.1's+ ``http_version`` defaults to the config's ``http_version`` option;+ ``"1.1"`` returns a separate transport (its own pool) pinned to HTTP/1.1.+ That matters for a server that reacts to a client going away: HTTP/2+ multiplexes requests over one connection, so abandoning a request only+ resets its stream and the server may never notice, while HTTP/1.1'sone-connection-per-request closes the connection and the server observesthe disconnect.@@ -260,7 +268,7 @@ def get_transport(return get_httpx_transport(proxy_to_config(config.proxy),READ_TIMEOUT if for_streaming else None,- http2,+ http_version=(config.http_version if http_version is None else http_version),)diff --git a/packages/python-sdk/e2b/api/client_sync/__init__.py b/packages/python-sdk/e2b/api/client_sync/__init__.pyindex 3bcce8b43..720cfdbbd 100644--- a/packages/python-sdk/e2b/api/client_sync/__init__.py+++ b/packages/python-sdk/e2b/api/client_sync/__init__.py@@ -26,7 +26,12 @@ from e2b.api import (proxy_to_config,request_origin,)-from e2b.connection_config import READ_TIMEOUT, ConnectionConfig+from e2b.connection_config import (+ DEFAULT_HTTP_VERSION,+ READ_TIMEOUT,+ ConnectionConfig,+ HttpVersion,+)def get_api_client(config: ConnectionConfig, **kwargs) -> ApiClient:@@ -138,7 +143,7 @@ class BalancingTransport(SyncTransport):)-_TransportKey = Tuple[Optional[ProxyConfig], Optional[float], bool]+_TransportKey = Tuple[Optional[ProxyConfig], Optional[float], HttpVersion]"""Cache key: proxy, idle read bound, HTTP version — fixed when a pyqwesttransport is constructed, so each distinct combination is necessarily its owntransport."""@@ -160,7 +165,8 @@ _httpx_transports: Dict[_TransportKey, PyqwestTransport] = {}def get_pyqwest_transport(proxy: Optional[ProxyConfig],read_timeout: Optional[float] = None,- http2: bool = True,+ *,+ http_version: HttpVersion = DEFAULT_HTTP_VERSION,) -> ConnectionRetryTransport:"""The shared pyqwest transport with the SDK's tuning — system CA certs(without which TLS through an intercepting proxy fails) and the@@ -175,10 +181,10 @@ def get_pyqwest_transport(RPC stack's plain-HTTP-error normalization wraps it, headers and codecs areper-request — so that the pools stay shareable.- ``read_timeout`` bounds every read on the pools' connections and ``http2``- fixes the HTTP version; both are part of the cache key because they are- transport-construction knobs, so one pool cannot serve two values of- either. reqwest's read timer keeps running while a request body is sent and+ ``read_timeout`` bounds every read on the pools' connections and+ ``http_version`` fixes the HTTP version; both are part of the cache key+ because they are transport-construction knobs, so one pool cannot serve two+ values of either. reqwest's read timer keeps running while a request body is sent andwhile waiting for the response head, so a pool carrying one would cut offlong uploads and slow responses — only streamed downloads ask for it, as anidle bound (see :func:`get_transport`).@@ -187,7 +193,7 @@ def get_pyqwest_transport(``pyqwest`` loggers at ``DEBUG`` (off unless enabled) — the transport-leveldiagnostics httpcore used to provide. The SDK's own ``logger`` option isseparate and sits above this, on the httpx client."""- key = (proxy, read_timeout, http2)+ key = (proxy, read_timeout, http_version)def build() -> SyncHTTPTransport:return SyncHTTPTransport(@@ -199,7 +205,7 @@ def get_pyqwest_transport(# `None` leaves the version to ALPN on TLS connections (HTTP/2# against the E2B API and envd) and uses HTTP/1 for plaintext,# like the http2-enabled httpx transport this replaced.- http_version=None if http2 else HTTPVersion.HTTP1,+ http_version=HTTPVersion.HTTP1 if http_version == "1.1" else None,# Redirects belong to the httpx client above (which the generated# clients leave off), not to reqwest.follow_redirects=False,@@ -218,16 +224,17 @@ def get_pyqwest_transport(def get_httpx_transport(proxy: Optional[ProxyConfig],read_timeout: Optional[float] = None,- http2: bool = True,+ *,+ http_version: HttpVersion = DEFAULT_HTTP_VERSION,) -> PyqwestTransport:"""The httpx adapter over the shared transport of:func:`get_pyqwest_transport`, for the generated httpx clients (controlplane, envd HTTP API, volume content). The adapter holds no state of itsown and does not close the pools, so closing an httpx client leaves themintact for the other clients on it."""- key = (proxy, read_timeout, http2)+ key = (proxy, read_timeout, http_version)# Resolve the pool before taking the lock: it takes the same one.- pool = get_pyqwest_transport(proxy, read_timeout, http2)+ pool = get_pyqwest_transport(proxy, read_timeout, http_version=http_version)with _transport_lock:transport = _httpx_transports.get(key)if transport is None:@@ -238,8 +245,8 @@ def get_httpx_transport(def get_transport(config: ConnectionConfig,- http2: bool = True,*,+ http_version: Optional[HttpVersion] = None,for_streaming: bool = False,) -> PyqwestTransport:"""The shared httpx transport factory for the control-plane REST API and@@ -247,10 +254,11 @@ def get_transport(negotiates the HTTP version (HTTP/2 against the E2B API), like thehttp2-enabled httpx transport this replaced.- ``http2=False`` returns a separate transport (its own pool) pinned to- HTTP/1.1. That matters for a server that reacts to a client going away:- HTTP/2 multiplexes requests over one connection, so abandoning a request- only resets its stream and the server may never notice, while HTTP/1.1's+ ``http_version`` defaults to the config's ``http_version`` option;+ ``"1.1"`` returns a separate transport (its own pool) pinned to HTTP/1.1.+ That matters for a server that reacts to a client going away: HTTP/2+ multiplexes requests over one connection, so abandoning a request only+ resets its stream and the server may never notice, while HTTP/1.1'sone-connection-per-request closes the connection and the server observesthe disconnect.@@ -265,7 +273,7 @@ def get_transport(return get_httpx_transport(proxy_to_config(config.proxy),READ_TIMEOUT if for_streaming else None,- http2,+ http_version=(config.http_version if http_version is None else http_version),)diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.pyindex a48983d05..4a712f140 100644--- a/packages/python-sdk/e2b/connection_config.py+++ b/packages/python-sdk/e2b/connection_config.py@@ -2,11 +2,12 @@ import loggingimport osimport re-from typing import cast, Mapping, Optional, Dict, TypedDict, Union+from typing import cast, Literal, Mapping, Optional, Dict, Tuple, TypedDict, Unionimport httpxfrom typing_extensions import Unpack+from e2b.exceptions import InvalidArgumentExceptionfrom e2b.retry import resolve_max_retriesfrom e2b.api.metadata import package_versionfrom e2b.sandbox_domains import is_supported_sandbox_domain@@ -39,6 +40,24 @@ READ_TIMEOUT: float = 60.0 # 60 secondsKEEPALIVE_PING_INTERVAL_SEC = 50 # 50 secondsKEEPALIVE_PING_HEADER = "Keepalive-Ping-Interval"+HttpVersion = Literal["1.1", "2"]+DEFAULT_HTTP_VERSION: HttpVersion = "2"+HTTP_VERSIONS: Tuple[HttpVersion, ...] = ("1.1", "2")+++def resolve_http_version(http_version: Optional[str] = None) -> HttpVersion:+ """The HTTP version to use: the explicit value, else ``E2B_HTTP_VERSION``,+ else ``DEFAULT_HTTP_VERSION``. Rejects anything but ``"1.1"`` or ``"2"``."""+ source = "http_version"+ if http_version is None:+ source = "E2B_HTTP_VERSION"+ http_version = os.getenv("E2B_HTTP_VERSION") or DEFAULT_HTTP_VERSION+ if http_version not in HTTP_VERSIONS:+ raise InvalidArgumentException(+ f"{source} must be '1.1' or '2', got {http_version!r}"+ )+ return cast(HttpVersion, http_version)+class ApiParams(TypedDict, total=False):"""@@ -96,6 +115,14 @@ class ApiParams(TypedDict, total=False):sandbox_url: Optional[str]"""URL to connect to sandbox, defaults to `E2B_SANDBOX_URL` environment variable."""+ http_version: Optional[HttpVersion]+ """HTTP version for requests to the E2B API and to sandboxes (commands,+ filesystem, PTY), defaults to `E2B_HTTP_VERSION` environment variable or+ `"2"`. `"1.1"` pins them to HTTP/1.1, which+ uses one connection per concurrent request instead of multiplexing streams+ over shared connections — for example when an intermediary on the path+ retires or mishandles long-lived HTTP/2 connections."""+class ApiParamsWithLogger(ApiParams, total=False):""":class:`ApiParams` plus the construction-time ``logger``.@@ -259,6 +286,7 @@ class ConnectionConfig:logger: Optional[logging.Logger] = None,*,retries: Optional[int] = None,+ http_version: Optional[HttpVersion] = None,):self.logger = loggerself.domain = domain or ConnectionConfig._domain()@@ -292,6 +320,7 @@ class ConnectionConfig:self._sandbox_url: Optional[str] = (sandbox_url or ConnectionConfig._sandbox_url())+ self.http_version: HttpVersion = resolve_http_version(http_version)@staticmethoddef _get_request_timeout(@@ -370,6 +399,7 @@ class ConnectionConfig:debug = opts.get("debug")proxy = opts.get("proxy")sandbox_url = opts.get("sandbox_url")+ http_version = opts.get("http_version")retries = opts.get("retries")req_headers = self.headers.copy()@@ -409,6 +439,9 @@ class ConnectionConfig:if sandbox_url is not Noneelse cast(Optional[str], self._sandbox_url)),+ http_version=(+ http_version if http_version is not None else self.http_version+ ),logger=self.logger,retries=retries if retries is not None else self.retries,)diff --git a/packages/python-sdk/e2b/envd/client_async/__init__.py b/packages/python-sdk/e2b/envd/client_async/__init__.pyindex dcc979d73..8edf17f4c 100644--- a/packages/python-sdk/e2b/envd/client_async/__init__.py+++ b/packages/python-sdk/e2b/envd/client_async/__init__.py@@ -80,7 +80,11 @@ def create_rpc_client(outside the retries so it converts the settled response once."""http_client = Client(- PlainHTTPErrorTransport(get_pyqwest_transport(proxy_to_config(config.proxy)))+ PlainHTTPErrorTransport(+ get_pyqwest_transport(+ proxy_to_config(config.proxy), http_version=config.http_version+ )+ ))return client_cls(base_url,diff --git a/packages/python-sdk/e2b/envd/client_sync/__init__.py b/packages/python-sdk/e2b/envd/client_sync/__init__.pyindex fadf66323..7d6925da5 100644--- a/packages/python-sdk/e2b/envd/client_sync/__init__.py+++ b/packages/python-sdk/e2b/envd/client_sync/__init__.py@@ -75,7 +75,11 @@ def create_rpc_client(outside the retries so it converts the settled response once."""http_client = SyncClient(- PlainHTTPErrorTransport(get_pyqwest_transport(proxy_to_config(config.proxy)))+ PlainHTTPErrorTransport(+ get_pyqwest_transport(+ proxy_to_config(config.proxy), http_version=config.http_version+ )+ ))return client_cls(base_url,diff --git a/packages/python-sdk/e2b/volume/client_async/__init__.py b/packages/python-sdk/e2b/volume/client_async/__init__.pyindex 3aed1272a..2be37945c 100644--- a/packages/python-sdk/e2b/volume/client_async/__init__.py+++ b/packages/python-sdk/e2b/volume/client_async/__init__.py@@ -73,7 +73,9 @@ def get_transport(config: VolumeConnectionConfig) -> AsyncPyqwestTransport:their whole-request deadlines instead). Streamed downloads, which do needan idle bound, use :func:`get_streaming_transport`."""- return get_httpx_transport(proxy_to_config(config.proxy))+ return get_httpx_transport(+ proxy_to_config(config.proxy), http_version=config.http_version+ )def get_streaming_transport(@@ -87,4 +89,6 @@ def get_streaming_transport(their own, shared with the sandbox filesystem's streaming transportwhenever the two bounds agree."""- return get_httpx_transport(proxy_to_config(config.proxy), READ_TIMEOUT)+ return get_httpx_transport(+ proxy_to_config(config.proxy), READ_TIMEOUT, http_version=config.http_version+ )diff --git a/packages/python-sdk/e2b/volume/client_sync/__init__.py b/packages/python-sdk/e2b/volume/client_sync/__init__.pyindex 57344abbd..1cb67a892 100644--- a/packages/python-sdk/e2b/volume/client_sync/__init__.py+++ b/packages/python-sdk/e2b/volume/client_sync/__init__.py@@ -73,7 +73,9 @@ def get_transport(config: VolumeConnectionConfig) -> PyqwestTransport:their whole-request deadlines instead). Streamed downloads, which do needan idle bound, use :func:`get_streaming_transport`."""- return get_httpx_transport(proxy_to_config(config.proxy))+ return get_httpx_transport(+ proxy_to_config(config.proxy), http_version=config.http_version+ )def get_streaming_transport(config: VolumeConnectionConfig) -> PyqwestTransport:@@ -85,4 +87,6 @@ def get_streaming_transport(config: VolumeConnectionConfig) -> PyqwestTransport:their own, shared with the sandbox filesystem's streaming transportwhenever the two bounds agree."""- return get_httpx_transport(proxy_to_config(config.proxy), READ_TIMEOUT)+ return get_httpx_transport(+ proxy_to_config(config.proxy), READ_TIMEOUT, http_version=config.http_version+ )diff --git a/packages/python-sdk/e2b/volume/connection_config.py b/packages/python-sdk/e2b/volume/connection_config.pyindex 905badebe..e636a208d 100644--- a/packages/python-sdk/e2b/volume/connection_config.py+++ b/packages/python-sdk/e2b/volume/connection_config.py@@ -6,7 +6,7 @@ from typing import Dict, Optional, TypedDictfrom typing_extensions import Unpackfrom e2b.api.metadata import package_version-from e2b.connection_config import ProxyTypes+from e2b.connection_config import HttpVersion, ProxyTypes, resolve_http_versionREQUEST_TIMEOUT: float = 60.0 # 60 seconds@@ -53,6 +53,11 @@ class VolumeApiParams(TypedDict, total=False):proxy: Optional[ProxyTypes]"""Proxy to use for the request."""+ http_version: Optional[HttpVersion]+ """HTTP version for requests to the volume content API, defaults to+ `E2B_HTTP_VERSION` environment variable or `"2"` (see+ `e2b.connection_config.ApiParams.http_version`)."""+logger: Optional[logging.Logger]"""Logger used for request and response logging. Accepts a standard library `logging.Logger`."""@@ -98,6 +103,8 @@ class VolumeConnectionConfig:headers: Optional[Dict[str, str]] = None,proxy: Optional[ProxyTypes] = None,logger: Optional[logging.Logger] = None,+ *,+ http_version: Optional[HttpVersion] = None,):self.logger = loggerself.domain = domain or self._domain()@@ -111,6 +118,7 @@ class VolumeConnectionConfig:self.access_token = tokenself.token = self.access_tokenself.proxy = proxy+ self.http_version: HttpVersion = resolve_http_version(http_version)self.headers = dict(headers) if headers else {}self.headers["User-Agent"] = f"e2b-python-sdk/{package_version}"@@ -136,6 +144,7 @@ class VolumeConnectionConfig:token = opts.get("token")api_url = opts.get("api_url")proxy = opts.get("proxy")+ http_version = opts.get("http_version")logger = opts.get("logger")req_headers = self.headers.copy()@@ -151,6 +160,9 @@ class VolumeConnectionConfig:request_timeout=self.get_request_timeout(request_timeout),headers=req_headers,proxy=proxy if proxy is not None else self.proxy,+ http_version=(+ http_version if http_version is not None else self.http_version+ ),logger=logger if logger is not None else self.logger,))diff --git a/packages/python-sdk/e2b/volume/volume_async.py b/packages/python-sdk/e2b/volume/volume_async.pyindex 192234f40..ec7034a85 100644--- a/packages/python-sdk/e2b/volume/volume_async.py+++ b/packages/python-sdk/e2b/volume/volume_async.py@@ -24,6 +24,7 @@ from e2b.connection_config import (ApiParams,ClientFactory,ConnectionConfig,+ HttpVersion,ProxyTypes,)from e2b.exceptions import (@@ -78,6 +79,8 @@ class AsyncVolume(ClientFactory):domain: Optional[str] = None,debug: Optional[bool] = None,proxy: Optional[ProxyTypes] = None,+ *,+ http_version: Optional[HttpVersion] = None,):self._volume_id = volume_idself._name = name@@ -85,6 +88,7 @@ class AsyncVolume(ClientFactory):self._domain = domainself._debug = debugself._proxy = proxy+ self._http_version = http_version@propertydef volume_id(self) -> str:@@ -110,6 +114,11 @@ class AsyncVolume(ClientFactory):headers=opts.get("headers"),logger=opts.get("logger"),proxy=opts.get("proxy") if opts.get("proxy") is not None else self._proxy,+ http_version=(+ opts.get("http_version")+ if opts.get("http_version") is not None+ else self._http_version+ ),)@classmethod@@ -150,6 +159,7 @@ class AsyncVolume(ClientFactory):domain=domain or config.domain,debug=config.debug,proxy=config.proxy,+ http_version=config.http_version,)return vol@@ -171,6 +181,7 @@ class AsyncVolume(ClientFactory):domain=info.domain or config.domain,debug=config.debug,proxy=config.proxy,+ http_version=config.http_version,)@classmethoddiff --git a/packages/python-sdk/e2b/volume/volume_sync.py b/packages/python-sdk/e2b/volume/volume_sync.pyindex eee5d1b1d..187fe6aed 100644--- a/packages/python-sdk/e2b/volume/volume_sync.py+++ b/packages/python-sdk/e2b/volume/volume_sync.py@@ -23,6 +23,7 @@ from e2b.connection_config import (ApiParams,ClientFactory,ConnectionConfig,+ HttpVersion,ProxyTypes,)from e2b.exceptions import (@@ -77,6 +78,8 @@ class Volume(ClientFactory):domain: Optional[str] = None,debug: Optional[bool] = None,proxy: Optional[ProxyTypes] = None,+ *,+ http_version: Optional[HttpVersion] = None,):self._volume_id = volume_idself._name = name@@ -84,6 +87,7 @@ class Volume(ClientFactory):self._domain = domainself._debug = debugself._proxy = proxy+ self._http_version = http_version@propertydef volume_id(self) -> str:@@ -109,6 +113,11 @@ class Volume(ClientFactory):headers=opts.get("headers"),logger=opts.get("logger"),proxy=opts.get("proxy") if opts.get("proxy") is not None else self._proxy,+ http_version=(+ opts.get("http_version")+ if opts.get("http_version") is not None+ else self._http_version+ ),)@classmethod@@ -149,6 +158,7 @@ class Volume(ClientFactory):domain=domain or config.domain,debug=config.debug,proxy=config.proxy,+ http_version=config.http_version,)return vol@@ -170,6 +180,7 @@ class Volume(ClientFactory):domain=info.domain or config.domain,debug=config.debug,proxy=config.proxy,+ http_version=config.http_version,)@classmethoddiff --git a/packages/python-sdk/tests/test_api_client_transport.py b/packages/python-sdk/tests/test_api_client_transport.pyindex ab73da39d..9828f2cd0 100644--- a/packages/python-sdk/tests/test_api_client_transport.py+++ b/packages/python-sdk/tests/test_api_client_transport.py@@ -211,23 +211,26 @@ def test_sync_transports_keyed_by_http_version(test_api_key):try:negotiated = get_sync_transport(config)- http1 = get_sync_transport(config, http2=False)+ http1 = get_sync_transport(config, http_version="1.1")assert http1 is not negotiated# Each version still has one transport per proxy, and repeat calls# with the same arguments reuse it.- assert get_sync_transport(proxied_config, http2=False) not in (+ assert get_sync_transport(proxied_config, http_version="1.1") not in (http1,negotiated,)- assert get_sync_transport(config, http2=False) is http1+ assert get_sync_transport(config, http_version="1.1") is http1assert get_sync_transport(config) is negotiated- assert get_sync_transport(config, http2=False, for_streaming=True) is not http1+ assert (+ get_sync_transport(config, http_version="1.1", for_streaming=True)+ is not http1+ )# The envd RPC clients' pyqwest transport is the one under the httpx# adapter the envd HTTP API uses, so a sandbox's RPC and HTTP traffic# share connections.assert get_sync_pyqwest_transport(None) is negotiated._transport- assert get_sync_pyqwest_transport(None, http2=False) is http1._transport+ assert get_sync_pyqwest_transport(None, http_version="1.1") is http1._transportfinally:reset_transport_caches()@@ -250,15 +253,44 @@ def test_sync_transports_pass_http_version_to_pyqwest(test_api_key, monkeypatch)try:get_sync_transport(config)- get_sync_transport(config, http2=False)+ get_sync_transport(config, http_version="1.1")# A third pool: same version as the call above, different idle bound.- get_sync_transport(config, http2=False, for_streaming=True)+ get_sync_transport(config, http_version="1.1", for_streaming=True)assert captured == [None, HTTPVersion.HTTP1, HTTPVersion.HTTP1]finally:reset_transport_caches()+def test_sync_transports_follow_the_http_version_option(test_api_key):+ reset_transport_caches()+ default = ConnectionConfig(api_key=test_api_key)+ http1 = ConnectionConfig(api_key=test_api_key, http_version="1.1")++ try:+ assert default.http_version == "2"+ assert get_sync_transport(default) is get_sync_transport(+ default, http_version="2"+ )+ assert get_sync_transport(http1) is get_sync_transport(+ default, http_version="1.1"+ )+ assert get_sync_transport(http1) is not get_sync_transport(default)+ # The explicit argument wins over the option.+ assert get_sync_transport(http1, http_version="2") is get_sync_transport(+ default+ )+ assert get_sync_envd_api(http1, "https://sandbox.e2b.app")._transport is (+ get_sync_transport(http1)+ )+ api_client = get_sync_api_client(http1).get_httpx_client()+ assert isinstance(api_client._transport, RetryableTransport)+ assert api_client._transport.transport is get_sync_transport(http1)+ api_client.close()+ finally:+ reset_transport_caches()++def test_sync_transport_passes_pool_tuning_to_pyqwest(test_api_key, monkeypatch):# The tuning that keeps a sandbox on one reused connection has to reach the# pyqwest constructor: dropping any of it (`pool_max_idle_per_host=0`, no@@ -424,14 +456,17 @@ async def test_async_transports_keyed_by_http_version(test_api_key):try:negotiated = get_async_transport(config)- http1 = get_async_transport(config, http2=False)+ http1 = get_async_transport(config, http_version="1.1")assert http1 is not negotiated- assert get_async_transport(config, http2=False) is http1+ assert get_async_transport(config, http_version="1.1") is http1assert get_async_transport(config) is negotiated- assert get_async_transport(config, http2=False, for_streaming=True) is not http1+ assert (+ get_async_transport(config, http_version="1.1", for_streaming=True)+ is not http1+ )assert get_async_pyqwest_transport(None) is negotiated._transport- assert get_async_pyqwest_transport(None, http2=False) is http1._transport+ assert get_async_pyqwest_transport(None, http_version="1.1") is http1._transportfinally:reset_transport_caches()@@ -451,15 +486,40 @@ async def test_async_transports_pass_http_version_to_pyqwest(test_api_key, monketry:get_async_transport(config)- get_async_transport(config, http2=False)+ get_async_transport(config, http_version="1.1")# A third pool: same version as the call above, different idle bound.- get_async_transport(config, http2=False, for_streaming=True)+ get_async_transport(config, http_version="1.1", for_streaming=True)assert captured == [None, HTTPVersion.HTTP1, HTTPVersion.HTTP1]finally:reset_transport_caches()+async def test_async_transports_follow_the_http_version_option(test_api_key):+ reset_transport_caches()+ default = ConnectionConfig(api_key=test_api_key)+ http1 = ConnectionConfig(api_key=test_api_key, http_version="1.1")++ try:+ assert get_async_transport(http1) is get_async_transport(+ default, http_version="1.1"+ )+ assert get_async_transport(http1) is not get_async_transport(default)+ assert get_async_transport(http1, http_version="2") is get_async_transport(+ default+ )+ assert get_async_envd_api(http1, "https://sandbox.e2b.app")._transport is (+ get_async_transport(http1)+ )+ api_client = get_async_api_client(http1).get_async_httpx_client()+ assert isinstance(api_client._transport, AsyncRetryableTransport)+ assert api_client._transport.transport is get_async_transport(http1)+ await api_client.aclose()+ finally:+ reset_transport_caches()++@pytest.mark.asyncioasync def test_async_transport_passes_pool_tuning_to_pyqwest(test_api_key, monkeypatch):reset_transport_caches()@@ -967,7 +1027,7 @@ def test_sync_http1_transport_round_trips(test_api_key, echo_server, caplog):reset_transport_caches()config = ConnectionConfig(api_key=test_api_key)client = httpx.Client(- base_url=echo_server, transport=get_sync_transport(config, http2=False)+ base_url=echo_server, transport=get_sync_transport(config, http_version="1.1"))try:@@ -990,7 +1050,7 @@ async def test_async_http1_transport_round_trips(test_api_key, echo_server):reset_transport_caches()config = ConnectionConfig(api_key=test_api_key)client = httpx.AsyncClient(- base_url=echo_server, transport=get_async_transport(config, http2=False)+ base_url=echo_server, transport=get_async_transport(config, http_version="1.1"))try:diff --git a/packages/python-sdk/tests/test_client.py b/packages/python-sdk/tests/test_client.pyindex 461983f46..8f4d16411 100644--- a/packages/python-sdk/tests/test_client.py+++ b/packages/python-sdk/tests/test_client.py@@ -228,6 +228,23 @@ def test_async_client_volume_uses_client_config(api_server):assert api_keys() == [API_KEY_A, API_KEY_A]+def test_client_http_version_is_bound_and_carried_by_volumes(api_server):+ client = E2B(+ api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server, http_version="1.1"+ )++ volume = client.Volume.create("vol")+ assert volume._get_volume_config().http_version == "1.1"+ # A per-call value overrides the bound one, on the class and the instance.+ volume = client.Volume.create("vol", http_version="2")+ assert volume._get_volume_config().http_version == "2"+ assert volume._get_volume_config(http_version="1.1").http_version == "1.1"+ assert (+ asyncio.run(client.AsyncVolume.create("vol"))._get_volume_config().http_version+ == "1.1"+ )++def test_client_template_uses_client_config(api_server):client = E2B(api_key=API_KEY_A, domain=DOMAIN_A, api_url=api_server)diff --git a/packages/python-sdk/tests/test_connection_config.py b/packages/python-sdk/tests/test_connection_config.pyindex 4241143ac..5e653822d 100644--- a/packages/python-sdk/tests/test_connection_config.py+++ b/packages/python-sdk/tests/test_connection_config.py@@ -249,3 +249,48 @@ def test_retries_default_to_three_and_propagate():def test_retries_reject_invalid_values(retries):with pytest.raises(InvalidArgumentException):ConnectionConfig(retries=retries)+++def test_http_version_defaults_to_http2_and_propagates(monkeypatch):+ monkeypatch.delenv("E2B_HTTP_VERSION", raising=False)++ assert ConnectionConfig().http_version == "2"+ assert ConnectionConfig().get_api_params()["http_version"] == "2"++ config = ConnectionConfig(http_version="1.1")+ assert config.http_version == "1.1"+ # Reconstructed configs (a sandbox's sub-clients) keep the setting, and a+ # per-call value overrides it.+ assert config.get_api_params()["http_version"] == "1.1"+ assert ConnectionConfig(**config.get_api_params()).http_version == "1.1"+ assert config.get_api_params(http_version="2")["http_version"] == "2"+++ ("value", "expected"),+ [("1.1", "1.1"), ("2", "2"), ("", "2")],+)+def test_http_version_reads_env_var(monkeypatch, value, expected):+ monkeypatch.setenv("E2B_HTTP_VERSION", value)++ assert ConnectionConfig().http_version == expected+ # The explicit argument wins over the environment.+ other = "2" if expected == "1.1" else "1.1"+ assert ConnectionConfig(http_version=other).http_version == other+++def test_http_version_rejects_unknown_env_value(monkeypatch):+ monkeypatch.setenv("E2B_HTTP_VERSION", "http3")++ with pytest.raises(InvalidArgumentException, match="E2B_HTTP_VERSION"):+ ConnectionConfig()+ # An explicit option never consults the environment.+ assert ConnectionConfig(http_version="1.1").http_version == "1.1"++[email protected]("value", ["http1", "http2", "1", "2.0", "HTTP/1.1", ""])+def test_http_version_rejects_unknown_explicit_value(monkeypatch, value):+ monkeypatch.delenv("E2B_HTTP_VERSION", raising=False)++ with pytest.raises(InvalidArgumentException, match="http_version"):+ ConnectionConfig(http_version=value)diff --git a/packages/python-sdk/tests/test_envd_client_transport.py b/packages/python-sdk/tests/test_envd_client_transport.pyindex f99d1f7fe..5c74c5aa0 100644--- a/packages/python-sdk/tests/test_envd_client_transport.py+++ b/packages/python-sdk/tests/test_envd_client_transport.py@@ -140,17 +140,22 @@ def test_async_pool_is_cached_per_proxy():assert api_client_sync.get_pyqwest_transport(None) is not pool_a-def test_rpc_clients_run_on_the_shared_pool(test_api_key, monkeypatch):[email protected]("http_version", ["2", "1.1"])+def test_rpc_clients_run_on_the_shared_pool(test_api_key, monkeypatch, http_version):# The RPC stack is the plain-HTTP-error normalization wrapping the very# pool the httpx clients use, so an envd RPC and an envd HTTP call to the# same sandbox share one HTTP/2 connection. `pyqwest.SyncClient` doesn't# hand its transport back, so record what the normalization is given.- config = ConnectionConfig(api_key=test_api_key)- pool = api_client_sync.get_pyqwest_transport(None)- async_pool = api_client_async.get_pyqwest_transport(None)+ other_version = "1.1" if http_version == "2" else "2"+ config = ConnectionConfig(api_key=test_api_key, http_version=http_version)+ pool = api_client_sync.get_pyqwest_transport(None, http_version=http_version)+ async_pool = api_client_async.get_pyqwest_transport(None, http_version=http_version)+ assert pool is not api_client_sync.get_pyqwest_transport(+ None, http_version=other_version+ )# The httpx adapters every REST client uses sit on those same pools.- assert api_client_sync.get_httpx_transport(None)._transport is pool- assert api_client_async.get_httpx_transport(None)._transport is async_pool+ assert api_client_sync.get_transport(config)._transport is pool+ assert api_client_async.get_transport(config)._transport is async_poolwrapped = []for module in (client_sync, client_async):diff --git a/packages/python-sdk/tests/test_volume_client.py b/packages/python-sdk/tests/test_volume_client.pyindex 8e7c251ca..d2bdab2b5 100644--- a/packages/python-sdk/tests/test_volume_client.py+++ b/packages/python-sdk/tests/test_volume_client.py@@ -160,6 +160,46 @@ def test_volume_transports_are_the_shared_sdk_pools(test_api_key):reset_volume_transports()+def test_volume_transports_follow_the_http_version_option(monkeypatch, test_api_key):+ reset_volume_transports()+ monkeypatch.delenv("E2B_HTTP_VERSION", raising=False)+ http1 = VolumeConnectionConfig(token="vol-token", http_version="1.1")+ api_http1 = ConnectionConfig(api_key=test_api_key, http_version="1.1")+ default = VolumeConnectionConfig(token="vol-token")++ try:+ assert default.http_version == "2"+ assert http1.get_api_params()["http_version"] == "1.1"+ for get_transport, get_streaming_transport, api in (+ (get_sync_transport, get_sync_streaming_transport, api_client_sync),+ (get_async_transport, get_async_streaming_transport, api_client_async),+ ):+ assert get_transport(http1) is api.get_transport(api_http1)+ assert get_transport(http1) is not get_transport(default)+ assert get_streaming_transport(http1) is api.get_transport(+ api_http1, for_streaming=True+ )+ assert get_streaming_transport(http1) is not get_streaming_transport(+ default+ )++ monkeypatch.setenv("E2B_HTTP_VERSION", "1.1")+ assert VolumeConnectionConfig(token="vol-token").http_version == "1.1"+ assert Volume("vol-id", "vol")._get_volume_config().http_version == "1.1"+ assert (+ Volume("vol-id", "vol", http_version="2")._get_volume_config().http_version+ == "2"+ )+ assert (+ AsyncVolume("vol-id", "vol", http_version="2")+ ._get_volume_config()+ .http_version+ == "2"+ )+ finally:+ reset_volume_transports()++def test_sync_transport_is_shared_across_threads():# pyqwest transports are thread-safe, so one transport (and its pool)# serves all threads — the per-thread caching this replaced is gone.