Skip to content

armgit / E2B

Public Imported from GitHub
0

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

feat(sdk): set-once integration attribution via ConnectionConfig.setIntegration (#1524)

Mish Ushakov09e12b3f65a1
diff --git a/.changeset/set-integration-once.md b/.changeset/set-integration-once.md
new file mode 100644
index 000000000..32ab943f6
--- /dev/null
+++ b/.changeset/set-integration-once.md
@@ -0,0 +1,6 @@
+---
+"e2b": minor
+"@e2b/python-sdk": minor
+---
+
+Replace the per-call `integration` connection option with a set-once, process-wide `ConnectionConfig.setIntegration()` (JS) / `ConnectionConfig.set_integration()` (Python). Integrations wrapping the SDK call it once at startup and every request is attributed via the `User-Agent` header — no more threading the option through individual SDK calls. The method is internal and hidden from docs. The `integration` option on `ConnectionConfigOpts` (JS) and the `integration` keyword argument on `ConnectionConfig` (Python) are removed; `ConnectionConfigOpts` remains as a deprecated alias of `ConnectionOpts`. In both SDKs, an explicitly provided `User-Agent` header now always takes precedence over the SDK-built one, while SDK-built values are recomputed whenever a config is rebuilt so they always reflect the current integration.
diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.ts
index 63adf1bf5..7b0397104 100644
--- a/packages/js-sdk/src/connectionConfig.ts
+++ b/packages/js-sdk/src/connectionConfig.ts
@@ -103,15 +103,10 @@ export interface ConnectionOpts {
/**
* Options accepted by `ConnectionConfig`.
+ *
+ * @deprecated Use `ConnectionOpts` instead.
*/
-export interface ConnectionConfigOpts extends ConnectionOpts {
- /**
- * Integration wrapping the E2B SDK, appended to the `User-Agent`.
- *
- * @example 'e2b-code-interpreter/0.1.0'
- */
- integration?: string
-}
+export type ConnectionConfigOpts = ConnectionOpts
/**
* Build an `AbortSignal` that combines an optional request-timeout signal
@@ -318,22 +313,63 @@ export function wrapStreamWithConnectionCleanup(
})
}
-function buildUserAgent(integration?: string) {
- const userAgentParts = [`e2b-js-sdk/${version}`]
-
- if (integration) {
- userAgentParts.push(integration)
- }
-
- return userAgentParts.join(' ')
-}
-
/**
* Configuration for connecting to the API.
*/
export class ConnectionConfig {
public static envdPort = 49983
+ private static integration?: string
+
+ private static readonly sdkUserAgentPrefix = 'e2b-js-sdk/'
+
+ private static buildUserAgent() {
+ const userAgentParts = [`${ConnectionConfig.sdkUserAgentPrefix}${version}`]
+
+ if (ConnectionConfig.integration) {
+ userAgentParts.push(ConnectionConfig.integration)
+ }
+
+ return userAgentParts.join(' ')
+ }
+
+ /**
+ * Set the `User-Agent` on `headers`: an explicitly provided value always
+ * wins; otherwise the SDK-built one, tagged with the current integration.
+ *
+ * An SDK-built value carried over from an earlier config (configs are
+ * rebuilt via `new ConnectionConfig({ ...config })`) is recognized by its
+ * prefix and rebuilt, so it stays in sync with the current integration.
+ */
+ private static applyUserAgent(headers: Record<string, string>) {
+ const userAgent = headers['User-Agent']
+
+ if (
+ userAgent !== undefined &&
+ !userAgent.startsWith(ConnectionConfig.sdkUserAgentPrefix)
+ ) {
+ return
+ }
+
+ headers['User-Agent'] = ConnectionConfig.buildUserAgent()
+ }
+
+ /**
+ * Identify traffic from an integration wrapping the E2B SDK by appending
+ * `integration` (e.g. `'e2b-code-interpreter/0.1.0'`) to the `User-Agent`
+ * header of every request.
+ *
+ * Call once at startup, before any `ConnectionConfig` is constructed —
+ * configs read the value at construction time. Pass `undefined` to clear.
+ *
+ * @internal
+ * @hidden
+ * @hide
+ */
+ static setIntegration(integration: string | undefined) {
+ ConnectionConfig.integration = integration
+ }
+
readonly debug: boolean
readonly domain: string
readonly apiUrl: string
@@ -349,13 +385,11 @@ export class ConnectionConfig {
*/
readonly accessToken?: string
- readonly integration?: string
-
readonly headers?: Record<string, string>
readonly proxy?: string
- constructor(opts?: ConnectionConfigOpts) {
+ constructor(opts?: ConnectionOpts) {
this.apiKey = opts?.apiKey || ConnectionConfig.apiKey
this.validateApiKey =
opts?.validateApiKey ?? ConnectionConfig.validateApiKey
@@ -364,9 +398,8 @@ export class ConnectionConfig {
this.accessToken = opts?.accessToken || ConnectionConfig.accessToken
this.requestTimeoutMs = opts?.requestTimeoutMs ?? REQUEST_TIMEOUT_MS
this.logger = opts?.logger
- this.integration = opts?.integration
this.headers = { ...(opts?.headers ?? {}), ...(opts?.apiHeaders ?? {}) }
- this.headers['User-Agent'] = buildUserAgent(this.integration)
+ ConnectionConfig.applyUserAgent(this.headers)
this.proxy = opts?.proxy
this.apiUrl =
diff --git a/packages/js-sdk/tests/connectionConfig.test.ts b/packages/js-sdk/tests/connectionConfig.test.ts
index 97fa044a7..6a839ffb9 100644
--- a/packages/js-sdk/tests/connectionConfig.test.ts
+++ b/packages/js-sdk/tests/connectionConfig.test.ts
@@ -27,6 +27,9 @@ afterEach(() => {
process.env[key] = originalEnv[key]
}
})
+
+ // Clear the process-wide integration attribution
+ ConnectionConfig.setIntegration(undefined)
})
test('api_url defaults correctly', () => {
@@ -183,10 +186,9 @@ test('debug defaults to E2B_DEBUG env var', () => {
assert.equal(config.debug, true)
})
-test('integration option is appended to the user agent', () => {
- const config = new ConnectionConfig({
- integration: 'testing/version',
- })
+test('setIntegration appends the integration to the user agent', () => {
+ ConnectionConfig.setIntegration('testing/version')
+ const config = new ConnectionConfig()
assert.equal(config.headers?.['User-Agent']?.startsWith('e2b-js-sdk/'), true)
assert.equal(
@@ -195,16 +197,80 @@ test('integration option is appended to the user agent', () => {
)
})
-test('integration option survives config rebuilds', () => {
+test('integration survives config rebuilds', () => {
+ ConnectionConfig.setIntegration('testing/version')
+ const config = new ConnectionConfig()
+ const rebuiltConfig = new ConnectionConfig({ ...config })
+
+ assert.equal(
+ rebuiltConfig.headers?.['User-Agent']?.endsWith(' testing/version'),
+ true
+ )
+})
+
+test('setIntegration does not retro-tag configs built earlier', () => {
+ const before = new ConnectionConfig()
+ ConnectionConfig.setIntegration('testing/version')
+ const after = new ConnectionConfig()
+
+ assert.equal(before.headers?.['User-Agent']?.includes('testing'), false)
+ assert.equal(
+ after.headers?.['User-Agent']?.endsWith(' testing/version'),
+ true
+ )
+})
+
+test('clearing the integration restores the plain user agent', () => {
+ ConnectionConfig.setIntegration('testing/version')
+ ConnectionConfig.setIntegration(undefined)
+ const config = new ConnectionConfig()
+
+ assert.equal(config.headers?.['User-Agent']?.startsWith('e2b-js-sdk/'), true)
+ assert.equal(config.headers?.['User-Agent']?.includes('testing'), false)
+})
+
+test('custom user agent is preserved without integration', () => {
const config = new ConnectionConfig({
- integration: 'testing/version',
+ apiHeaders: { 'User-Agent': 'my-app/1.0' },
})
+
+ assert.equal(config.headers?.['User-Agent'], 'my-app/1.0')
+})
+
+test('custom user agent wins over integration', () => {
+ ConnectionConfig.setIntegration('testing/version')
+
+ const config = new ConnectionConfig({
+ headers: { 'User-Agent': 'my-app/1.0' },
+ })
+
+ assert.equal(config.headers?.['User-Agent'], 'my-app/1.0')
+})
+
+test('custom user agent survives config rebuilds', () => {
+ ConnectionConfig.setIntegration('testing/version')
+ const config = new ConnectionConfig({
+ apiHeaders: { 'User-Agent': 'my-app/1.0' },
+ })
+ const rebuiltConfig = new ConnectionConfig({ ...config })
+
+ assert.equal(rebuiltConfig.headers?.['User-Agent'], 'my-app/1.0')
+})
+
+test('clearing the integration propagates to config rebuilds', () => {
+ ConnectionConfig.setIntegration('testing/version')
+ const config = new ConnectionConfig()
+ ConnectionConfig.setIntegration(undefined)
const rebuiltConfig = new ConnectionConfig({ ...config })
assert.equal(
- rebuiltConfig.headers?.['User-Agent']?.endsWith(' testing/version'),
+ rebuiltConfig.headers?.['User-Agent']?.startsWith('e2b-js-sdk/'),
true
)
+ assert.equal(
+ rebuiltConfig.headers?.['User-Agent']?.includes('testing'),
+ false
+ )
})
test('getSignal returns user signal when no timeout is set', () => {
diff --git a/packages/js-sdk/tests/sandbox/rpcHeaders.test.ts b/packages/js-sdk/tests/sandbox/rpcHeaders.test.ts
index 7c6251e70..a559713d3 100644
--- a/packages/js-sdk/tests/sandbox/rpcHeaders.test.ts
+++ b/packages/js-sdk/tests/sandbox/rpcHeaders.test.ts
@@ -19,7 +19,7 @@ vi.mock('../../src/envd/http2', () => ({
test('does not pass custom connection headers to envd RPC requests', async () => {
const { ConnectionConfig, Sandbox } = await import('../../src')
- const config = new ConnectionConfig({ integration: 'testing/version' })
+ const config = new ConnectionConfig()
const sandbox = new Sandbox({
...config,
sandboxId: 'sbx-test',
@@ -43,7 +43,6 @@ test('does not pass custom connection headers to envd RPC requests', async () =>
assert.equal(headers.get('Authorization'), null)
assert.equal(headers.get('X-Custom'), null)
assert.equal(headers.get('User-Agent')?.startsWith('e2b-js-sdk/'), true)
- assert.equal(headers.get('User-Agent')?.endsWith(' testing/version'), true)
assert.equal(headers.get('E2b-Sandbox-Id'), 'sbx-test')
assert.equal(headers.get('X-Access-Token'), 'tok')
assert.equal(headers.get('Connect-Protocol-Version'), '1')
diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.py
index 050a4ca4e..81f4a0946 100644
--- a/packages/python-sdk/e2b/connection_config.py
+++ b/packages/python-sdk/e2b/connection_config.py
@@ -75,6 +75,24 @@ class ConnectionConfig:
envd_port = 49983
+ _integration: Optional[str] = None
+
+ @classmethod
+ def set_integration(cls, integration: Optional[str]) -> None:
+ """
+ Identify traffic from an integration wrapping the E2B SDK by appending
+ ``integration`` (e.g. ``"e2b-code-interpreter/0.1.0"``) to the
+ ``User-Agent`` header of every request.
+
+ Call once at startup, before any ``ConnectionConfig`` is constructed —
+ configs read the value at construction time. Pass ``None`` to clear.
+
+ Internal use only — not part of the public, stable API.
+
+ :meta private:
+ """
+ ConnectionConfig._integration = integration
+
@staticmethod
def _domain():
return os.getenv("E2B_DOMAIN") or "e2b.app"
@@ -104,16 +122,34 @@ class ConnectionConfig:
return os.getenv("E2B_ACCESS_TOKEN")
@staticmethod
- def _build_user_agent(
- integration: Optional[str] = None,
- ) -> str:
+ def _build_user_agent() -> str:
user_agent_parts = [f"e2b-python-sdk/{package_version}"]
- if integration:
- user_agent_parts.append(integration)
+ if ConnectionConfig._integration:
+ user_agent_parts.append(ConnectionConfig._integration)
return " ".join(user_agent_parts)
+ def _apply_user_agent(
+ self,
+ headers: Dict[str, str],
+ user_agent_override: Optional[str],
+ ) -> bool:
+ """
+ Set the ``User-Agent`` on ``headers``: an explicitly provided value
+ always wins; otherwise the SDK-built one, tagged with the current
+ integration.
+
+ Returns whether the SDK-built value was applied, so callers can keep
+ it in sync with the current integration on later rebuilds.
+ """
+ if user_agent_override is not None:
+ headers["User-Agent"] = user_agent_override
+ return False
+
+ headers["User-Agent"] = self._build_user_agent()
+ return True
+
def __init__(
self,
domain: Optional[str] = None,
@@ -126,7 +162,6 @@ class ConnectionConfig:
request_timeout: Optional[float] = None,
headers: Optional[Dict[str, str]] = None,
api_headers: Optional[Dict[str, str]] = None,
- integration: Optional[str] = None,
extra_sandbox_headers: Optional[Dict[str, str]] = None,
proxy: Optional[ProxyTypes] = None,
logger: Optional[logging.Logger] = None,
@@ -143,12 +178,11 @@ class ConnectionConfig:
# Deprecated: pass the token through `api_headers` instead, e.g.
# api_headers={"Authorization": f"Bearer {token}"}.
self.access_token = access_token or ConnectionConfig._access_token()
- self.integration = integration
self.headers = {**(headers or {}), **(api_headers or {})}
- if self.integration is not None or "User-Agent" not in self.headers:
- self.headers["User-Agent"] = self._build_user_agent(
- self.integration,
- )
+ self._user_agent_is_sdk_built = self._apply_user_agent(
+ self.headers,
+ self.headers.get("User-Agent"),
+ )
self.__extra_sandbox_headers = extra_sandbox_headers or {}
self.proxy = proxy
@@ -252,10 +286,12 @@ class ConnectionConfig:
req_headers.update(headers)
if api_headers is not None:
req_headers.update(api_headers)
- if self.integration is not None:
- req_headers["User-Agent"] = self._build_user_agent(
- self.integration,
+ if self._user_agent_is_sdk_built:
+ # Same precedence as the merge above: api_headers wins over headers.
+ per_call_user_agent = {**(headers or {}), **(api_headers or {})}.get(
+ "User-Agent"
)
+ self._apply_user_agent(req_headers, per_call_user_agent)
# `logger` is a construction-time option rather than a per-request
# ApiParams field, but it must propagate to the throwaway
diff --git a/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py b/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py
index 15740cd48..1acfe8780 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py
@@ -103,10 +103,10 @@ async def test_connect_sets_stable_host_routing_headers(monkeypatch, test_api_ke
)
monkeypatch.setattr(sandbox_async_main.SandboxApi, "_cls_connect", mock_connect)
+ monkeypatch.setattr(ConnectionConfig, "_integration", "testing/version")
config = ConnectionConfig(
api_key=test_api_key,
headers=BASE_HEADERS,
- integration="testing/version",
)
sandbox = await AsyncSandbox.connect(
"sbx-test",
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py b/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py
index 05034f05e..4b0c9c533 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py
@@ -90,10 +90,10 @@ def test_connect_sets_stable_host_routing_headers(monkeypatch, test_api_key):
)
monkeypatch.setattr(sandbox_sync_main.SandboxApi, "_cls_connect", mock_connect)
+ monkeypatch.setattr(ConnectionConfig, "_integration", "testing/version")
config = ConnectionConfig(
api_key=test_api_key,
headers=BASE_HEADERS,
- integration="testing/version",
)
sandbox = Sandbox.connect(
"sbx-test",
diff --git a/packages/python-sdk/tests/test_connection_config.py b/packages/python-sdk/tests/test_connection_config.py
index 1e4e7cc63..9c7c6802e 100644
--- a/packages/python-sdk/tests/test_connection_config.py
+++ b/packages/python-sdk/tests/test_connection_config.py
@@ -131,15 +131,38 @@ def test_debug_defaults_to_env_var(monkeypatch):
assert config.debug is True
-def test_integration_option_is_appended_to_user_agent():
- config = ConnectionConfig(integration="testing/version")
+def test_set_integration_appends_to_user_agent():
+ ConnectionConfig.set_integration("testing/version")
+ try:
+ config = ConnectionConfig()
- assert config.headers["User-Agent"].startswith("e2b-python-sdk/")
- assert config.headers["User-Agent"].endswith(" testing/version")
+ assert config.headers["User-Agent"].startswith("e2b-python-sdk/")
+ assert config.headers["User-Agent"].endswith(" testing/version")
+ finally:
+ ConnectionConfig.set_integration(None)
+ config = ConnectionConfig()
+ assert "testing" not in config.headers["User-Agent"]
+
+
+def test_custom_user_agent_is_preserved_without_integration():
+ config = ConnectionConfig(api_headers={"User-Agent": "custom/1.0"})
+
+ assert config.headers["User-Agent"] == "custom/1.0"
+
+
+def test_custom_user_agent_wins_over_integration(monkeypatch):
+ monkeypatch.setattr(ConnectionConfig, "_integration", "testing/version")
+
+ config = ConnectionConfig(api_headers={"User-Agent": "custom/1.0"})
+
+ assert config.headers["User-Agent"] == "custom/1.0"
-def test_integration_option_survives_api_param_rebuilds():
- config = ConnectionConfig(integration="testing/version")
+
+def test_integration_survives_api_param_rebuilds(monkeypatch):
+ monkeypatch.setattr(ConnectionConfig, "_integration", "testing/version")
+
+ config = ConnectionConfig()
rebuilt_config = ConnectionConfig(**config.get_api_params())
assert rebuilt_config.headers["User-Agent"].endswith(" testing/version")
@@ -148,6 +171,52 @@ def test_integration_option_survives_api_param_rebuilds():
].endswith(" testing/version")
+def test_cleared_integration_does_not_leak_into_api_param_rebuilds():
+ ConnectionConfig.set_integration("testing/version")
+ try:
+ config = ConnectionConfig()
+ finally:
+ ConnectionConfig.set_integration(None)
+
+ params = config.get_api_params()
+ assert not params["headers"]["User-Agent"].endswith(" testing/version")
+
+ rebuilt_config = ConnectionConfig(**params)
+ assert not rebuilt_config.headers["User-Agent"].endswith(" testing/version")
+
+
+def test_custom_user_agent_survives_api_param_rebuilds(monkeypatch):
+ monkeypatch.setattr(ConnectionConfig, "_integration", "testing/version")
+
+ config = ConnectionConfig(api_headers={"User-Agent": "custom/1.0"})
+ rebuilt_config = ConnectionConfig(**config.get_api_params())
+
+ assert rebuilt_config.headers["User-Agent"] == "custom/1.0"
+
+ monkeypatch.setattr(ConnectionConfig, "_integration", None)
+
+ config = ConnectionConfig(api_headers={"User-Agent": "custom/1.0"})
+ rebuilt_config = ConnectionConfig(**config.get_api_params())
+ assert rebuilt_config.headers["User-Agent"] == "custom/1.0"
+
+
+def test_per_call_user_agent_override_wins_in_api_params(monkeypatch):
+ monkeypatch.setattr(ConnectionConfig, "_integration", "testing/version")
+
+ config = ConnectionConfig()
+ params = config.get_api_params(api_headers={"User-Agent": "custom/1.0"})
+ assert params["headers"]["User-Agent"] == "custom/1.0"
+
+
+def test_per_call_api_headers_user_agent_wins_over_headers():
+ config = ConnectionConfig()
+ params = config.get_api_params(
+ headers={"User-Agent": "from-headers/1.0"},
+ api_headers={"User-Agent": "from-api-headers/1.0"},
+ )
+ assert params["headers"]["User-Agent"] == "from-api-headers/1.0"
+
+
def test_request_timeout_zero_means_no_timeout():
config = ConnectionConfig(request_timeout=0)
assert config.request_timeout is None