Skip to content

armgit / E2B

Public Imported from GitHub
0

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

js uses the stable `sandbox` host url with headers (#1342)

Matt Brockman3ea4ef597b9c
diff --git a/.changeset/shiny-zebras-play.md b/.changeset/shiny-zebras-play.md
new file mode 100644
index 000000000..8cb3923b3
--- /dev/null
+++ b/.changeset/shiny-zebras-play.md
@@ -0,0 +1,5 @@
+---
+'e2b': minor
+---
+
+use stable sandbox.e2b.app for h2 efficiency
diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.ts
index dd713cf05..a1004b5c1 100644
--- a/packages/js-sdk/src/connectionConfig.ts
+++ b/packages/js-sdk/src/connectionConfig.ts
@@ -1,5 +1,9 @@
import { Logger } from './logs'
import { getEnvVar, version } from './api/metadata'
+import { runtime } from './utils'
+
+// Remove once all deployments support sandbox subdomains
+const supportedDomains = ['e2b.app', 'e2b.dev', 'e2b.pro', 'e2b-staging.dev']
export const REQUEST_TIMEOUT_MS = 60_000 // 60 seconds
export const DEFAULT_SANDBOX_TIMEOUT_MS = 300_000 // 300 seconds
@@ -38,7 +42,7 @@ export interface ConnectionOpts {
/**
* Sandbox Url to use for the API.
* @internal
- * @default E2B_SANDBOX_URL // environment variable or `https://${port}-${sandboxID}.${domain}`
+ * @default E2B_SANDBOX_URL // environment variable, `https://sandbox.${domain}`
*/
sandboxUrl?: string
/**
@@ -236,7 +240,33 @@ export class ConnectionConfig {
return this.sandboxUrl
}
- return `${this.debug ? 'http' : 'https'}://${this.getHost(sandboxId, opts.envdPort, opts.sandboxDomain)}`
+ if (this.debug) {
+ return `http://${this.getHost(sandboxId, opts.envdPort, opts.sandboxDomain)}`
+ }
+
+ const sandboxDomain = opts.sandboxDomain ?? this.domain
+ // The stable sandbox host is only guaranteed for E2B prod; the various other hosted domains may not serve sandbox.<domain> yet and will follow up once those are updated.
+ // Issue with cors from browser so holding off on using in browser as well.
+ if (runtime !== 'browser' && supportedDomains.includes(sandboxDomain)) {
+ return `https://sandbox.${sandboxDomain}`
+ }
+
+ return `https://${this.getHost(sandboxId, opts.envdPort, sandboxDomain)}`
+ }
+
+ getSandboxDirectUrl(
+ sandboxId: string,
+ opts: { sandboxDomain: string; envdPort: number }
+ ) {
+ if (this.sandboxUrl) {
+ return this.sandboxUrl
+ }
+
+ if (this.debug) {
+ return `http://${this.getHost(sandboxId, opts.envdPort, opts.sandboxDomain)}`
+ }
+
+ return `https://${this.getHost(sandboxId, opts.envdPort, opts.sandboxDomain)}`
}
getHost(sandboxId: string, port: number, sandboxDomain: string) {
diff --git a/packages/js-sdk/src/envd/http2.ts b/packages/js-sdk/src/envd/http2.ts
index b4a276bbe..29950816d 100644
--- a/packages/js-sdk/src/envd/http2.ts
+++ b/packages/js-sdk/src/envd/http2.ts
@@ -1,4 +1,5 @@
import { runtime } from '../utils'
+import { getEnvVar } from '../api/metadata'
import {
loadUndici,
toUndiciRequestInput,
@@ -14,10 +15,12 @@ type EnvdFetchOptions = {
let envdFetch: typeof fetch | undefined
let envdRpcFetch: typeof fetch | undefined
let hasWarnedUndiciFallback = false
+const DEFAULT_ENVD_CONNECTION_LIMIT = 10
+const DEFAULT_ENVD_RPC_CONNECTION_LIMIT = 200
export function createEnvdFetchForRuntime(
currentRuntime = runtime,
- options: EnvdFetchOptions = { connectionLimit: 1 }
+ options: EnvdFetchOptions = {}
): typeof fetch {
if (currentRuntime !== 'node') {
return fetch
@@ -47,9 +50,7 @@ async function buildEnvdFetcher(
const { Agent, fetch: undiciFetch } = undici
const dispatcherOptions: { allowH2: true; connections?: number } = {
allowH2: true,
- }
- if (options.connectionLimit !== undefined) {
- dispatcherOptions.connections = options.connectionLimit
+ connections: options.connectionLimit ?? DEFAULT_ENVD_CONNECTION_LIMIT,
}
const dispatcher = new Agent(dispatcherOptions)
@@ -96,9 +97,23 @@ export function createEnvdRpcFetch(): typeof fetch {
return envdRpcFetch
}
- // RPC streams can stay open while follow-up RPCs run against the same
- // sandbox, so they cannot share the REST client's single-connection cap.
- envdRpcFetch = createEnvdFetchForRuntime(runtime, {})
+ envdRpcFetch = createEnvdFetchForRuntime(runtime, {
+ connectionLimit: getEnvdRpcConnectionLimit(),
+ })
return envdRpcFetch
}
+
+export function getEnvdRpcConnectionLimit() {
+ const raw = getEnvVar('E2B_ENVD_RPC_CONNECTIONS')
+ if (!raw) {
+ return DEFAULT_ENVD_RPC_CONNECTION_LIMIT
+ }
+
+ const parsed = Number.parseInt(raw, 10)
+ if (!Number.isFinite(parsed) || parsed < 1) {
+ return DEFAULT_ENVD_RPC_CONNECTION_LIMIT
+ }
+
+ return parsed
+}
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index d7d535b54..d3e699f33 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -112,6 +112,7 @@ export class Sandbox extends SandboxApi {
protected readonly connectionConfig: ConnectionConfig
protected readonly envdAccessToken?: string
private readonly envdApiUrl: string
+ private readonly envdDirectUrl: string
private readonly envdApi: EnvdApiClient
private mcpToken?: string
@@ -145,6 +146,13 @@ export class Sandbox extends SandboxApi {
sandboxDomain: this.sandboxDomain,
envdPort: this.envdPort,
})
+ this.envdDirectUrl = this.connectionConfig.getSandboxDirectUrl(
+ this.sandboxId,
+ {
+ sandboxDomain: this.sandboxDomain,
+ envdPort: this.envdPort,
+ }
+ )
const sandboxHeaders = {
'E2b-Sandbox-Id': this.sandboxId,
@@ -736,7 +744,7 @@ export class Sandbox extends SandboxApi {
}
private fileUrl(path: string | undefined, username: string | undefined) {
- const url = new URL('/files', this.envdApiUrl)
+ const url = new URL('/files', this.envdDirectUrl)
if (username) {
url.searchParams.set('username', username)
diff --git a/packages/js-sdk/tests/connectionConfig.browser.test.ts b/packages/js-sdk/tests/connectionConfig.browser.test.ts
new file mode 100644
index 000000000..12cc3fa2d
--- /dev/null
+++ b/packages/js-sdk/tests/connectionConfig.browser.test.ts
@@ -0,0 +1,24 @@
+import { afterEach, assert, test, vi } from 'vitest'
+
+afterEach(() => {
+ vi.resetModules()
+ vi.doUnmock('../src/utils')
+})
+
+test('sandbox_url keeps per-sandbox host in browser runtime', async () => {
+ vi.doMock('../src/utils', () => ({
+ runtime: 'browser',
+ runtimeVersion: 'test',
+ }))
+
+ const { ConnectionConfig } = await import('../src/connectionConfig')
+ const config = new ConnectionConfig()
+
+ assert.equal(
+ config.getSandboxUrl('sbx-test', {
+ sandboxDomain: 'e2b.app',
+ envdPort: 49983,
+ }),
+ 'https://49983-sbx-test.e2b.app'
+ )
+})
diff --git a/packages/js-sdk/tests/connectionConfig.test.ts b/packages/js-sdk/tests/connectionConfig.test.ts
index 4a01900e0..f56adf62d 100644
--- a/packages/js-sdk/tests/connectionConfig.test.ts
+++ b/packages/js-sdk/tests/connectionConfig.test.ts
@@ -11,6 +11,7 @@ beforeEach(() => {
originalEnv = {
E2B_API_URL: process.env.E2B_API_URL,
E2B_DOMAIN: process.env.E2B_DOMAIN,
+ E2B_SANDBOX_URL: process.env.E2B_SANDBOX_URL,
E2B_DEBUG: process.env.E2B_DEBUG,
}
})
@@ -55,6 +56,96 @@ test('api_url has correct priority', () => {
assert.equal(config.apiUrl, 'http://localhost:8080')
})
+test('sandbox_url defaults to stable sandbox host in production', () => {
+ delete process.env.E2B_SANDBOX_URL
+ delete process.env.E2B_DOMAIN
+ delete process.env.E2B_DEBUG
+
+ const config = new ConnectionConfig()
+
+ assert.equal(
+ config.getSandboxUrl('sbx-test', {
+ sandboxDomain: 'e2b.app',
+ envdPort: 49983,
+ }),
+ 'https://sandbox.e2b.app'
+ )
+})
+
+test('sandbox_direct_url keeps per-sandbox host in production', () => {
+ delete process.env.E2B_SANDBOX_URL
+ delete process.env.E2B_DOMAIN
+ delete process.env.E2B_DEBUG
+
+ const config = new ConnectionConfig()
+
+ assert.equal(
+ config.getSandboxDirectUrl('sbx-test', {
+ sandboxDomain: 'e2b.app',
+ envdPort: 49983,
+ }),
+ 'https://49983-sbx-test.e2b.app'
+ )
+})
+
+test('sandbox_url keeps per-sandbox host outside production', () => {
+ delete process.env.E2B_SANDBOX_URL
+ delete process.env.E2B_DEBUG
+
+ const config = new ConnectionConfig({ domain: 'e2b.dev' })
+
+ assert.equal(
+ config.getSandboxUrl('sbx-test', {
+ sandboxDomain: 'sandbox.e2b.dev',
+ envdPort: 49983,
+ }),
+ 'https://49983-sbx-test.sandbox.e2b.dev'
+ )
+})
+
+test('sandbox_url in args has priority', () => {
+ process.env.E2B_SANDBOX_URL = 'https://sandbox.from-env'
+
+ const config = new ConnectionConfig({ sandboxUrl: 'https://sandbox.custom' })
+
+ assert.equal(
+ config.getSandboxUrl('sbx-test', {
+ sandboxDomain: 'e2b.app',
+ envdPort: 49983,
+ }),
+ 'https://sandbox.custom'
+ )
+})
+
+test('sandbox_url in env var overrides default', () => {
+ process.env.E2B_SANDBOX_URL = 'https://sandbox.from-env'
+
+ const config = new ConnectionConfig()
+
+ assert.equal(
+ config.getSandboxUrl('sbx-test', {
+ sandboxDomain: 'e2b.app',
+ envdPort: 49983,
+ }),
+ 'https://sandbox.from-env'
+ )
+})
+
+test('sandbox_url stays localhost in debug mode', () => {
+ delete process.env.E2B_SANDBOX_URL
+ process.env.E2B_DEBUG = 'true'
+
+ const config = new ConnectionConfig()
+
+ assert.equal(
+ config.getSandboxUrl('sbx-test', {
+ sandboxDomain: 'e2b.app',
+ envdPort: 49983,
+ }),
+ 'http://localhost:49983'
+ )
+})
+
test('getSignal returns user signal when no timeout is set', () => {
const config = new ConnectionConfig({ requestTimeoutMs: 0 })
const controller = new AbortController()
diff --git a/packages/js-sdk/tests/envd/http2.test.ts b/packages/js-sdk/tests/envd/http2.test.ts
index e673a0008..c73092e96 100644
--- a/packages/js-sdk/tests/envd/http2.test.ts
+++ b/packages/js-sdk/tests/envd/http2.test.ts
@@ -5,6 +5,7 @@ afterEach(() => {
vi.resetModules()
vi.doUnmock('undici')
vi.doUnmock('../../src/utils')
+ delete process.env.E2B_ENVD_RPC_CONNECTIONS
})
test('uses undici with HTTP/2 enabled in Node', async () => {
@@ -66,7 +67,7 @@ test('passes Request objects to undici as URL plus init', async () => {
expect(requests[0].init?.body).toBeInstanceOf(ReadableStream)
})
-test('can create an uncapped dispatcher for RPC streams', async () => {
+test('can create a bounded dispatcher for RPC streams', async () => {
const agents: Array<{ allowH2?: boolean; connections?: number }> = []
class Agent {
@@ -80,11 +81,20 @@ test('can create an uncapped dispatcher for RPC streams', async () => {
const { createEnvdFetchForRuntime } = await import('../../src/envd/http2')
const fetcher = createEnvdFetchForRuntime('node', {
+ connectionLimit: 100,
loadUndici: () => Promise.resolve({ Agent, fetch: undiciFetch }),
})
await fetcher('https://example.com/rpc')
- expect(agents).toEqual([{ allowH2: true }])
+ expect(agents).toEqual([{ allowH2: true, connections: 100 }])
+})
+
+test('reads RPC stream dispatcher connection limit from env', async () => {
+ process.env.E2B_ENVD_RPC_CONNECTIONS = '200'
+
+ const { getEnvdRpcConnectionLimit } = await import('../../src/envd/http2')
+
+ expect(getEnvdRpcConnectionLimit()).toBe(200)
})
test('defers loading undici until the first Node request', async () => {
diff --git a/packages/js-sdk/tests/sandbox/configPropagation.test.ts b/packages/js-sdk/tests/sandbox/configPropagation.test.ts
index ef5ba8e18..f4e031ce1 100644
--- a/packages/js-sdk/tests/sandbox/configPropagation.test.ts
+++ b/packages/js-sdk/tests/sandbox/configPropagation.test.ts
@@ -1,8 +1,10 @@
-import { afterEach, assert, describe, test, vi } from 'vitest'
+import { afterEach, assert, beforeEach, describe, test, vi } from 'vitest'
import { Sandbox } from '../../src'
import { SandboxApi } from '../../src/sandbox/sandboxApi'
+let originalSandboxUrl: string | undefined
+
const baseConfig = {
apiKey: 'base-api-key',
domain: 'base.e2b.dev',
@@ -23,8 +25,17 @@ function createSandbox() {
}
describe('Sandbox API config propagation', () => {
+ beforeEach(() => {
+ originalSandboxUrl = process.env.E2B_SANDBOX_URL
+ })
+
afterEach(() => {
vi.restoreAllMocks()
+ if (originalSandboxUrl === undefined) {
+ delete process.env.E2B_SANDBOX_URL
+ } else {
+ process.env.E2B_SANDBOX_URL = originalSandboxUrl
+ }
})
test('passes connectionConfig to public API methods when called without overrides', async () => {
@@ -56,4 +67,21 @@ describe('Sandbox API config propagation', () => {
assert.equal(opts?.requestTimeoutMs, 9999)
assert.equal(opts?.debug, baseConfig.debug)
})
+
+ test('downloadUrl keeps sandbox identity in production direct URLs', async () => {
+ delete process.env.E2B_SANDBOX_URL
+
+ const sandbox = new Sandbox({
+ sandboxId: 'sbx-test',
+ sandboxDomain: 'e2b.app',
+ envdVersion: '0.2.4',
+ domain: 'e2b.app',
+ debug: false,
+ })
+
+ assert.equal(
+ await sandbox.downloadUrl('/hello.txt'),
+ 'https://49983-sbx-test.e2b.app/files?username=user&path=%2Fhello.txt'
+ )
+ })
})