Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Add integration user agent composibility (#1454)
Matt Brockman432c0913c842
diff --git a/.changeset/integration-attribution-headers.md b/.changeset/integration-attribution-headers.mdnew file mode 100644index 000000000..1e9422e0b--- /dev/null+++ b/.changeset/integration-attribution-headers.md@@ -0,0 +1,6 @@+---+'e2b': patch+'@e2b/python-sdk': patch+---++Add integration attribution options that append integration metadata to the SDK `User-Agent`.diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.tsindex 29b9378c0..c73b627af 100644--- a/packages/js-sdk/src/connectionConfig.ts+++ b/packages/js-sdk/src/connectionConfig.ts@@ -90,6 +90,13 @@ export interface ConnectionOpts {*/apiHeaders?: Record<string, string>+ /**+ * Integration wrapping the E2B SDK, appended to the `User-Agent`.+ *+ * @example 'e2b-code-interpreter/0.1.0'+ */+ integration?: string+/*** 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@@ -191,6 +198,16 @@ export function setupRequestController(return { controller, clearStartTimeout, cleanup }}+function buildUserAgent(integration?: string) {+ const userAgentParts = [`e2b-js-sdk/${version}`]++ if (integration) {+ userAgentParts.push(integration)+ }++ return userAgentParts.join(' ')+}+/*** Configuration for connecting to the API.*/@@ -209,6 +226,8 @@ export class ConnectionConfig {readonly validateApiKey: booleanreadonly accessToken?: string+ readonly integration?: string+readonly headers?: Record<string, string>readonly proxy?: string@@ -222,8 +241,9 @@ export class ConnectionConfig {this.accessToken = opts?.accessToken || ConnectionConfig.accessTokenthis.requestTimeoutMs = opts?.requestTimeoutMs ?? REQUEST_TIMEOUT_MSthis.logger = opts?.logger+ this.integration = opts?.integrationthis.headers = { ...(opts?.headers ?? {}), ...(opts?.apiHeaders ?? {}) }- this.headers['User-Agent'] = `e2b-js-sdk/${version}`+ this.headers['User-Agent'] = buildUserAgent(this.integration)this.proxy = opts?.proxythis.apiUrl =diff --git a/packages/js-sdk/tests/connectionConfig.test.ts b/packages/js-sdk/tests/connectionConfig.test.tsindex c3d01f077..04bf24510 100644--- a/packages/js-sdk/tests/connectionConfig.test.ts+++ b/packages/js-sdk/tests/connectionConfig.test.ts@@ -182,6 +182,30 @@ test('debug defaults to E2B_DEBUG env var', () => {assert.equal(config.debug, true)})+test('integration options are appended to the user agent', () => {+ const config = new ConnectionConfig({+ integration: 'testing/version',+ })++ assert.equal(config.headers?.['User-Agent']?.startsWith('e2b-js-sdk/'), true)+ assert.equal(+ config.headers?.['User-Agent']?.endsWith(' testing/version'),+ true+ )+})++test('integration option survives config rebuilds', () => {+ const config = new ConnectionConfig({+ integration: 'testing/version',+ })+ const rebuiltConfig = new ConnectionConfig({ ...config })++ assert.equal(+ rebuiltConfig.headers?.['User-Agent']?.endsWith(' testing/version'),+ true+ )+})+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/sandbox/rpcHeaders.test.ts b/packages/js-sdk/tests/sandbox/rpcHeaders.test.tsindex 3c7e205d7..1c4f3ee5c 100644--- a/packages/js-sdk/tests/sandbox/rpcHeaders.test.ts+++ b/packages/js-sdk/tests/sandbox/rpcHeaders.test.ts@@ -24,6 +24,7 @@ test('does not pass custom connection headers to envd RPC requests', async () =>sandboxDomain: 'sandbox.e2b.dev',envdVersion: '0.2.4',envdAccessToken: 'tok',+ integration: 'testing/version',headers: {Authorization: 'Bearer user-token','X-Custom': 'secret',@@ -41,6 +42,7 @@ 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.pyindex 01eda5ce7..335751faa 100644--- a/packages/python-sdk/e2b/connection_config.py+++ b/packages/python-sdk/e2b/connection_config.py@@ -30,6 +30,9 @@ class ApiParams(TypedDict, total=False):api_headers: Optional[Dict[str, str]]"""Additional headers to send with E2B API requests."""+ integration: Optional[str]+ """Integration wrapping the E2B SDK, appended to the User-Agent."""+api_key: Optional[str]"""E2B API Key to use for authentication, defaults to `E2B_API_KEY` environment variable."""@@ -90,6 +93,17 @@ class ConnectionConfig:def _access_token():return os.getenv("E2B_ACCESS_TOKEN")+ @staticmethod+ def _build_user_agent(+ integration: Optional[str] = None,+ ) -> str:+ user_agent_parts = [f"e2b-python-sdk/{package_version}"]++ if integration:+ user_agent_parts.append(integration)++ return " ".join(user_agent_parts)+def __init__(self,domain: Optional[str] = None,@@ -102,6 +116,7 @@ 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,):@@ -114,8 +129,11 @@ class ConnectionConfig:else ConnectionConfig._validate_api_key())self.access_token = access_token or ConnectionConfig._access_token()+ self.integration = integrationself.headers = {**(headers or {}), **(api_headers or {})}- self.headers["User-Agent"] = f"e2b-python-sdk/{package_version}"+ self.headers["User-Agent"] = self._build_user_agent(+ self.integration,+ )self.__extra_sandbox_headers = extra_sandbox_headers or {}self.proxy = proxy@@ -205,6 +223,7 @@ class ConnectionConfig:"""headers = opts.get("headers")api_headers = opts.get("api_headers")+ integration = opts.get("integration", self.integration)request_timeout = opts.get("request_timeout")api_key = opts.get("api_key")validate_api_key = opts.get("validate_api_key")@@ -219,22 +238,31 @@ class ConnectionConfig:req_headers.update(headers)if api_headers is not None:req_headers.update(api_headers)+ if integration is not None:+ req_headers["User-Agent"] = self._build_user_agent(+ integration,+ )return dict(ApiParams(api_key=api_key if api_key is not None else self.api_key,- validate_api_key=validate_api_key- if validate_api_key is not None- else self.validate_api_key,+ validate_api_key=(+ validate_api_key+ if validate_api_key is not None+ else self.validate_api_key+ ),api_url=api_url if api_url is not None else self.api_url,domain=domain if domain is not None else self.domain,debug=debug if debug is not None else self.debug,request_timeout=self.get_request_timeout(request_timeout),headers=req_headers,+ integration=integration,proxy=proxy if proxy is not None else self.proxy,- sandbox_url=sandbox_url- if sandbox_url is not None- else cast(Optional[str], self._sandbox_url),+ sandbox_url=(+ sandbox_url+ if sandbox_url is not None+ else cast(Optional[str], self._sandbox_url)+ ),))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.pyindex b352ca80f..2a51e7184 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@@ -9,7 +9,6 @@ from e2b.api import SandboxCreateResponsefrom e2b.connection_config import ConnectionConfigimport e2b.sandbox_async.main as sandbox_async_main-BASE_DOMAIN = "base.e2b.dev"BASE_REQUEST_TIMEOUT = 11BASE_DEBUG = False@@ -105,11 +104,20 @@ async def test_connect_sets_stable_host_routing_headers(monkeypatch, test_api_kemonkeypatch.setattr(sandbox_async_main.SandboxApi, "_cls_connect", mock_connect)sandbox = await AsyncSandbox.connect(- "sbx-test", api_key=test_api_key, headers=BASE_HEADERS+ "sbx-test",+ api_key=test_api_key,+ headers=BASE_HEADERS,+ integration="testing/version",)assert sandbox.envd_api_url == "https://sandbox.e2b.app"assert "X-Test" not in sandbox.connection_config.sandbox_headers+ assert sandbox.connection_config.sandbox_headers["User-Agent"].startswith(+ "e2b-python-sdk/"+ )+ assert sandbox.connection_config.sandbox_headers["User-Agent"].endswith(+ " testing/version"+ )assert sandbox.connection_config.sandbox_headers["E2b-Sandbox-Id"] == "sbx-test"assert sandbox.connection_config.sandbox_headers["E2b-Sandbox-Port"] == str(ConnectionConfig.envd_portdiff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py b/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.pyindex 7f77d4cf7..fef4e3000 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@@ -8,7 +8,6 @@ from e2b.api import SandboxCreateResponsefrom e2b.connection_config import ConnectionConfigimport e2b.sandbox_sync.main as sandbox_sync_main-BASE_DOMAIN = "base.e2b.dev"BASE_REQUEST_TIMEOUT = 11BASE_DEBUG = False@@ -91,10 +90,21 @@ def test_connect_sets_stable_host_routing_headers(monkeypatch, test_api_key):)monkeypatch.setattr(sandbox_sync_main.SandboxApi, "_cls_connect", mock_connect)- sandbox = Sandbox.connect("sbx-test", api_key=test_api_key, headers=BASE_HEADERS)+ sandbox = Sandbox.connect(+ "sbx-test",+ api_key=test_api_key,+ headers=BASE_HEADERS,+ integration="testing/version",+ )assert sandbox.envd_api_url == "https://sandbox.e2b.app"assert "X-Test" not in sandbox.connection_config.sandbox_headers+ assert sandbox.connection_config.sandbox_headers["User-Agent"].startswith(+ "e2b-python-sdk/"+ )+ assert sandbox.connection_config.sandbox_headers["User-Agent"].endswith(+ " testing/version"+ )assert sandbox.connection_config.sandbox_headers["E2b-Sandbox-Id"] == "sbx-test"assert sandbox.connection_config.sandbox_headers["E2b-Sandbox-Port"] == str(ConnectionConfig.envd_portdiff --git a/packages/python-sdk/tests/test_connection_config.py b/packages/python-sdk/tests/test_connection_config.pyindex 5853e97dd..099459d19 100644--- a/packages/python-sdk/tests/test_connection_config.py+++ b/packages/python-sdk/tests/test_connection_config.py@@ -131,6 +131,20 @@ def test_debug_defaults_to_env_var(monkeypatch):assert config.debug is True+def test_integration_options_are_appended_to_user_agent():+ config = ConnectionConfig(integration="testing/version")++ assert config.headers["User-Agent"].startswith("e2b-python-sdk/")+ assert config.headers["User-Agent"].endswith(" testing/version")+++def test_integration_option_survives_api_param_rebuilds():+ config = ConnectionConfig(integration="testing/version")+ rebuilt_config = ConnectionConfig(**config.get_api_params())++ assert rebuilt_config.headers["User-Agent"].endswith(" testing/version")++def test_request_timeout_zero_means_no_timeout():config = ConnectionConfig(request_timeout=0)assert config.request_timeout is None