Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
List running sandboxes (#297)
Jakub Novák34f49ca3503f
diff --git a/.changeset/hot-pianos-play.md b/.changeset/hot-pianos-play.mdnew file mode 100644index 000000000..50b3ec2c1--- /dev/null+++ b/.changeset/hot-pianos-play.md@@ -0,0 +1,7 @@+---+"@e2b/python-sdk": patch+"@e2b/sdk": patch+"@e2b/cli": patch+---++Add metadata for sandboxesdiff --git a/.changeset/seven-islands-repeat.md b/.changeset/seven-islands-repeat.mdnew file mode 100644index 000000000..a669868b8--- /dev/null+++ b/.changeset/seven-islands-repeat.md@@ -0,0 +1,7 @@+---+"@e2b/python-sdk": patch+"@e2b/sdk": patch+"@e2b/cli": patch+---++Add possibility to list all running sandboxesdiff --git a/.gitattributes b/.gitattributesnew file mode 100644index 000000000..3696fca3e--- /dev/null+++ b/.gitattributes@@ -0,0 +1,3 @@+packages/python-sdk/e2b/api/v1/** linguist-generated=true+packages/python-sdk/e2b/api/v2/** linguist-generated=true+packages/js-sdk/src/api/schema.gen.ts linguist-generated=truediff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.tsindex da6b3d851..86c453a6e 100644--- a/packages/cli/src/commands/index.ts+++ b/packages/cli/src/commands/index.ts@@ -8,6 +8,7 @@ import { listCommand } from './list'import { shellCommand } from './shell'import { initCommand } from './init'import { deleteCommand } from './delete'+import { instancesCommand } from './instances'export const program = new commander.Command().description(`Create sandbox templates from Dockerfiles by running ${asPrimary('e2b build')} then use our SDKs to create sandboxes from these templates.@@ -21,3 +22,4 @@ Visit ${asPrimary('E2B docs (https://e2b.dev/docs)')} to learn how to create san.addCommand(shellCommand).addCommand(initCommand).addCommand(deleteCommand)+ .addCommand(instancesCommand)diff --git a/packages/cli/src/commands/instances.ts b/packages/cli/src/commands/instances.tsnew file mode 100644index 000000000..b32e24fa2--- /dev/null+++ b/packages/cli/src/commands/instances.ts@@ -0,0 +1,51 @@+import * as tablePrinter from 'console-table-printer'+import * as commander from 'commander'+import * as e2b from '@e2b/sdk'++import { ensureAPIKey } from 'src/api'++const listRunningSandboxes = e2b.withAPIKey(+ e2b.api.path('/instances').method('get').create(),+)++export const instancesCommand = new commander.Command('instances')+ .description('List all sandboxes')+ .alias('ins')+ .action(async () => {+ try {+ const apiKey = ensureAPIKey()+ const sandboxes = await listSandboxes({ apiKey })++ if (!sandboxes?.length) {+ console.log('No running sandboxes.')+ } else {+ const table = new tablePrinter.Table({+ title: 'Running sandboxes',+ columns: [+ { name: 'instanceID', alignment: 'left', title: 'Sandbox ID' },+ { name: 'envID', alignment: 'left', title: 'Template ID' },+ { name: 'startedAt', alignment: 'left', title: 'Started at' },+ { name: 'metadata', alignment: 'left', title: 'Metadata'},+ ],+ disabledColumns: ['clientID'],+ rows: sandboxes.map((sandbox) => ({ ...sandbox, startedAt: new Date(sandbox.startedAt).toLocaleString(), metadata: JSON.stringify(sandbox.metadata) })),+ colorMap: {+ orange: '\x1b[38;5;216m',+ },+ })+ table.printTable()++ process.stdout.write('\n')+ }+ } catch (err: any) {+ console.error(err)+ process.exit(1)+ }+ })++export async function listSandboxes({+ apiKey,+}: { apiKey: string }): Promise<e2b.components['schemas']['RunningInstance'][]> {+ const response = await listRunningSandboxes(apiKey, {})+ return response.data+}diff --git a/packages/js-sdk/src/api/schema.gen.ts b/packages/js-sdk/src/api/schema.gen.tsindex ea6712caf..c1a7f6fd1 100644--- a/packages/js-sdk/src/api/schema.gen.ts+++ b/packages/js-sdk/src/api/schema.gen.ts@@ -15,6 +15,20 @@ export interface paths {};};"/instances": {+ /** List all running instances */+ get: {+ responses: {+ /** Successfully returned all running instances */+ 200: {+ content: {+ "application/json": components["schemas"]["RunningInstance"][];+ };+ };+ 400: components["responses"]["400"];+ 401: components["responses"]["401"];+ 500: components["responses"]["500"];+ };+ };/** Create an instance from the environment */post: {responses: {@@ -211,9 +225,11 @@ export interface paths {export interface components {schemas: {+ InstanceMetadata: { [key: string]: string };NewInstance: {/** @description Identifier of the required environment */envID: string;+ metadata?: components["schemas"]["InstanceMetadata"];};Environment: {/** @description Identifier of the environment */@@ -260,6 +276,20 @@ export interface components {/** @description Error */message: string;};+ RunningInstance: {+ /** @description Identifier of the environment from which is the instance created */+ envID: string;+ /** @description Identifier of the instance */+ instanceID: string;+ /** @description Identifier of the client */+ clientID: string;+ /**+ * Format: date-time+ * @description Time when the instance was started+ */+ startedAt: string;+ metadata?: components["schemas"]["InstanceMetadata"];+ };};responses: {/** Bad request */diff --git a/packages/js-sdk/src/sandbox/sandboxConnection.ts b/packages/js-sdk/src/sandbox/sandboxConnection.tsindex b5f9d26aa..834419671 100644--- a/packages/js-sdk/src/sandbox/sandboxConnection.ts+++ b/packages/js-sdk/src/sandbox/sandboxConnection.ts@@ -2,7 +2,6 @@ import { IRpcNotification, RpcWebSocketClient } from './rpc'import api, { components, withAPIKey } from '../api'import { ENVD_PORT, SANDBOX_DOMAIN, SANDBOX_REFRESH_PERIOD, SECURE, WS_RECONNECT_INTERVAL, WS_ROUTE } from '../constants'-import { AuthenticationError } from '../error'import { assertFulfilled, formatSettledErrors, withTimeout } from '../utils/promise'import wait from '../utils/wait'import { codeSnippetService } from './codeSnippet'@@ -10,6 +9,7 @@ import { filesystemService } from './filesystem'import { processService } from './process'import { terminalService } from './terminal'import { EnvVars } from './envVars'+import { getApiKey } from '../utils/apiKey'// eslint-disable-next-line @typescript-eslint/no-explicit-anytype SubscriptionHandler = (result: any) => void;@@ -33,6 +33,10 @@ export interface Logger {error?: (message: string, ...args: unknown[]) => void;}+export interface SandboxMetadata {+ [key: string]: string;+}+export interface SandboxConnectionOpts {/*** Sandbox Template ID or name.@@ -49,6 +53,7 @@ export interface SandboxConnectionOpts {apiKey?: string;cwd?: string;envVars?: EnvVars;+ metadata?: SandboxMetadata;logger?: Logger;__sandbox?: components['schemas']['Instance'];__debug_hostname?: string;@@ -61,6 +66,10 @@ export interface CallOpts {timeout?: number;}++const listSandboxes = withAPIKey(+ api.path('/instances').method('get').create(),+)const createSandbox = withAPIKey(api.path('/instances').method('post').create(),)@@ -93,15 +102,7 @@ export class SandboxConnection {// let's keep opts readonly, but public - for convenience, mainly when debuggingprotected constructor(readonly opts: SandboxConnectionOpts) {this.sandbox = opts.__sandbox- const apiKey = opts.apiKey || process?.env?.E2B_API_KEY- if (!apiKey) {- throw new AuthenticationError(- 'API key is required, please visit https://e2b.dev/docs to get your API key. ' +- 'You can either set the environment variable `E2B_API_KEY` ' +- "or you can pass it directly to the sandbox like Sandbox.create({apiKey: 'e2b_...'})",- )- }- this.apiKey = apiKey+ this.apiKey = getApiKey(opts.apiKey)this.cwd = opts.cwd@@ -132,6 +133,33 @@ export class SandboxConnection {return `${this.sandbox?.instanceID}-${this.sandbox?.clientID}`}+ /**+ * List all running sandboxes+ * @param apiKey API key to use for authentication. If not provided, the `E2B_API_KEY` environment variable will be used.+ */+ static async list(apiKey?: string) {+ apiKey = getApiKey(apiKey)+ try {+ const res = await listSandboxes(apiKey, {})+ return res.data+ } catch (e) {+ if (e instanceof listSandboxes.Error) {+ const error = e.getActualType()+ if (error.status === 401) {+ throw new Error(+ `Error listing sandboxes - (${error.status}) unauthenticated: ${error.data.message}`,+ )+ }+ if (error.status === 500) {+ throw new Error(+ `Error listing sandboxes - (${error.status}) server error: ${error.data.message}`,+ )+ }+ }+ throw e+ }+ }+private get templateID(): string {return this.opts.template || this.opts.id || 'base'}@@ -331,6 +359,7 @@ export class SandboxConnection {try {const res = await createSandbox(this.apiKey, {envID: this.templateID,+ metadata: this.opts.metadata,})this.sandbox = res.datadiff --git a/packages/js-sdk/src/utils/apiKey.ts b/packages/js-sdk/src/utils/apiKey.tsnew file mode 100644index 000000000..be61e1a8d--- /dev/null+++ b/packages/js-sdk/src/utils/apiKey.ts@@ -0,0 +1,15 @@+import { AuthenticationError } from '../error'++export function getApiKey(apiKey?: string): string {+ apiKey = apiKey || process?.env?.E2B_API_KEY++ if (!apiKey) {+ throw new AuthenticationError(+ 'API key is required, please visit https://e2b.dev/docs to get your API key. ' ++ 'You can either set the environment variable `E2B_API_KEY` ' ++ "or you can pass it directly to the sandbox like Sandbox.create({apiKey: 'e2b_...'})",+ )+ }++ return apiKey+}\ No newline at end of filediff --git a/packages/js-sdk/test/listRunningSandboxes.test.mjs b/packages/js-sdk/test/listRunningSandboxes.test.mjsnew file mode 100644index 000000000..2e2adb5d8--- /dev/null+++ b/packages/js-sdk/test/listRunningSandboxes.test.mjs@@ -0,0 +1,22 @@+import { expect, test } from 'vitest'+import { Sandbox } from '../src'++test('list running sandboxes', async () => {+ const sandboxPromises = []+ for (let i = 0; i < 3; i++) {+ sandboxPromises.push(Sandbox.create({+ id: 'base',+ apiKey: process.env.E2B_API_KEY,+ metadata: { n: i.toString() }+ }))+ }+ const sandboxes = await Promise.all(sandboxPromises)++ const running = await Sandbox.list()+ expect(running.length).toEqual(3)+ expect(new Set(running.map(s => s.metadata['n']))).toEqual(new Set(['0', '1', '2']))++ for (const sandbox of sandboxes) {+ await sandbox.close()+ }+})diff --git a/packages/python-sdk/e2b/api/v1/client/__init__.py b/packages/python-sdk/e2b/api/v1/client/__init__.pyindex 610e524bb..25f6a02ec 100644--- a/packages/python-sdk/e2b/api/v1/client/__init__.py+++ b/packages/python-sdk/e2b/api/v1/client/__init__.py@@ -42,3 +42,4 @@ from e2b.api.v1.client.models.instances_instance_id_refreshes_post_request imporInstancesInstanceIDRefreshesPostRequest,)from e2b.api.v1.client.models.new_instance import NewInstance+from e2b.api.v1.client.models.running_instance import RunningInstancediff --git a/packages/python-sdk/e2b/api/v1/client/api/instances_api.py b/packages/python-sdk/e2b/api/v1/client/api/instances_api.pyindex 3f44d7764..d31a0bbe6 100644--- a/packages/python-sdk/e2b/api/v1/client/api/instances_api.py+++ b/packages/python-sdk/e2b/api/v1/client/api/instances_api.py@@ -20,13 +20,14 @@ from pydantic import validate_arguments, ValidationErrorfrom pydantic import StrictStr-from typing import Optional+from typing import List, Optionalfrom e2b.api.v1.client.models.instance import Instancefrom e2b.api.v1.client.models.instances_instance_id_refreshes_post_request import (InstancesInstanceIDRefreshesPostRequest,)from e2b.api.v1.client.models.new_instance import NewInstance+from e2b.api.v1.client.models.running_instance import RunningInstancefrom e2b.api.v1.client.api_client import ApiClientfrom e2b.api.v1.client.api_response import ApiResponse@@ -45,6 +46,143 @@ class InstancesApi:api_client = ApiClient.get_default()self.api_client = api_client+ @validate_arguments+ def instances_get(self, **kwargs) -> List[RunningInstance]: # noqa: E501+ """instances_get # noqa: E501++ List all running instances # noqa: E501+ This method makes a synchronous HTTP request by default. To make an+ asynchronous HTTP request, please pass async_req=True++ >>> thread = api.instances_get(async_req=True)+ >>> result = thread.get()++ :param async_req: Whether to execute the request asynchronously.+ :type async_req: bool, optional+ :param _request_timeout: timeout setting for this request.+ If one number provided, it will be total request+ timeout. It can also be a pair (tuple) of+ (connection, read) timeouts.+ :return: Returns the result object.+ If the method is called asynchronously,+ returns the request thread.+ :rtype: List[RunningInstance]+ """+ kwargs["_return_http_data_only"] = True+ if "_preload_content" in kwargs:+ message = "Error! Please call the instances_get_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501+ raise ValueError(message)+ return self.instances_get_with_http_info(**kwargs) # noqa: E501++ @validate_arguments+ def instances_get_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501+ """instances_get # noqa: E501++ List all running instances # noqa: E501+ This method makes a synchronous HTTP request by default. To make an+ asynchronous HTTP request, please pass async_req=True++ >>> thread = api.instances_get_with_http_info(async_req=True)+ >>> result = thread.get()++ :param async_req: Whether to execute the request asynchronously.+ :type async_req: bool, optional+ :param _preload_content: if False, the ApiResponse.data will+ be set to none and raw_data will store the+ HTTP response body without reading/decoding.+ Default is True.+ :type _preload_content: bool, optional+ :param _return_http_data_only: response data instead of ApiResponse+ object with status code, headers, etc+ :type _return_http_data_only: bool, optional+ :param _request_timeout: timeout setting for this request. If one+ number provided, it will be total request+ timeout. It can also be a pair (tuple) of+ (connection, read) timeouts.+ :param _request_auth: set to override the auth_settings for an a single+ request; this effectively ignores the authentication+ in the spec for a single request.+ :type _request_auth: dict, optional+ :type _content_type: string, optional: force content-type for the request+ :return: Returns the result object.+ If the method is called asynchronously,+ returns the request thread.+ :rtype: tuple(List[RunningInstance], status_code(int), headers(HTTPHeaderDict))+ """++ _params = locals()++ _all_params = []+ _all_params.extend(+ [+ "async_req",+ "_return_http_data_only",+ "_preload_content",+ "_request_timeout",+ "_request_auth",+ "_content_type",+ "_headers",+ ]+ )++ # validate the arguments+ for _key, _val in _params["kwargs"].items():+ if _key not in _all_params:+ raise ApiTypeError(+ "Got an unexpected keyword argument '%s'"+ " to method instances_get" % _key+ )+ _params[_key] = _val+ del _params["kwargs"]++ _collection_formats = {}++ # process the path parameters+ _path_params = {}++ # process the query parameters+ _query_params = []+ # process the header parameters+ _header_params = dict(_params.get("_headers", {}))+ # process the form parameters+ _form_params = []+ _files = {}+ # process the body parameter+ _body_params = None+ # set the HTTP header `Accept`+ _header_params["Accept"] = self.api_client.select_header_accept(+ ["application/json"]+ ) # noqa: E501++ # authentication setting+ _auth_settings = ["ApiKeyAuth"] # noqa: E501++ _response_types_map = {+ "200": "List[RunningInstance]",+ "401": "Error",+ "400": "Error",+ "500": "Error",+ }++ return self.api_client.call_api(+ "/instances",+ "GET",+ _path_params,+ _query_params,+ _header_params,+ body=_body_params,+ post_params=_form_params,+ files=_files,+ response_types_map=_response_types_map,+ auth_settings=_auth_settings,+ async_req=_params.get("async_req"),+ _return_http_data_only=_params.get("_return_http_data_only"), # noqa: E501+ _preload_content=_params.get("_preload_content", True),+ _request_timeout=_params.get("_request_timeout"),+ collection_formats=_collection_formats,+ _request_auth=_params.get("_request_auth"),+ )+@validate_argumentsdef instances_instance_id_refreshes_post(self,diff --git a/packages/python-sdk/e2b/api/v1/client/models/__init__.py b/packages/python-sdk/e2b/api/v1/client/models/__init__.pyindex fecd4eaa6..28647c01a 100644--- a/packages/python-sdk/e2b/api/v1/client/models/__init__.py+++ b/packages/python-sdk/e2b/api/v1/client/models/__init__.py@@ -25,3 +25,4 @@ from e2b.api.v1.client.models.instances_instance_id_refreshes_post_request imporInstancesInstanceIDRefreshesPostRequest,)from e2b.api.v1.client.models.new_instance import NewInstance+from e2b.api.v1.client.models.running_instance import RunningInstancediff --git a/packages/python-sdk/e2b/api/v1/client/models/new_instance.py b/packages/python-sdk/e2b/api/v1/client/models/new_instance.pyindex f72bc5bd3..235a11026 100644--- a/packages/python-sdk/e2b/api/v1/client/models/new_instance.py+++ b/packages/python-sdk/e2b/api/v1/client/models/new_instance.py@@ -18,6 +18,7 @@ import re # noqa: F401import json+from typing import Dict, Optionalfrom pydantic import BaseModel, Field, StrictStr@@ -29,7 +30,8 @@ class NewInstance(BaseModel):env_id: StrictStr = Field(..., alias="envID", description="Identifier of the required environment")- __properties = ["envID"]+ metadata: Optional[Dict[str, StrictStr]] = None+ __properties = ["envID", "metadata"]class Config:"""Pydantic configuration"""@@ -72,5 +74,7 @@ class NewInstance(BaseModel):+ obj)- _obj = NewInstance.parse_obj({"env_id": obj.get("envID")})+ _obj = NewInstance.parse_obj(+ {"env_id": obj.get("envID"), "metadata": obj.get("metadata")}+ )return _objdiff --git a/packages/python-sdk/e2b/api/v1/client/models/running_instance.py b/packages/python-sdk/e2b/api/v1/client/models/running_instance.pynew file mode 100644index 000000000..f335a3a94--- /dev/null+++ b/packages/python-sdk/e2b/api/v1/client/models/running_instance.py@@ -0,0 +1,97 @@+# coding: utf-8++"""+ E2B API++ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)++ The version of the OpenAPI document: 0.1.0+ Generated by OpenAPI Generator (https://openapi-generator.tech)++ Do not edit the class manually.+""" # noqa: E501+++from __future__ import annotations+import pprint+import re # noqa: F401+import json++from datetime import datetime+from typing import Dict, Optional+from pydantic import BaseModel, Field, StrictStr+++class RunningInstance(BaseModel):+ """+ RunningInstance+ """++ env_id: StrictStr = Field(+ ...,+ alias="envID",+ description="Identifier of the environment from which is the instance created",+ )+ instance_id: StrictStr = Field(+ ..., alias="instanceID", description="Identifier of the instance"+ )+ client_id: StrictStr = Field(+ ..., alias="clientID", description="Identifier of the client"+ )+ started_at: datetime = Field(+ ..., alias="startedAt", description="Time when the instance was started"+ )+ metadata: Optional[Dict[str, StrictStr]] = None+ __properties = ["envID", "instanceID", "clientID", "startedAt", "metadata"]++ class Config:+ """Pydantic configuration"""++ allow_population_by_field_name = True+ validate_assignment = True++ def to_str(self) -> str:+ """Returns the string representation of the model using alias"""+ return pprint.pformat(self.dict(by_alias=True))++ def to_json(self) -> str:+ """Returns the JSON representation of the model using alias"""+ return json.dumps(self.to_dict())++ @classmethod+ def from_json(cls, json_str: str) -> RunningInstance:+ """Create an instance of RunningInstance from a JSON string"""+ return cls.from_dict(json.loads(json_str))++ def to_dict(self):+ """Returns the dictionary representation of the model using alias"""+ _dict = self.dict(by_alias=True, exclude={}, exclude_none=True)+ return _dict++ @classmethod+ def from_dict(cls, obj: dict) -> RunningInstance:+ """Create an instance of RunningInstance from a dict"""+ if obj is None:+ return None++ if not isinstance(obj, dict):+ return RunningInstance.parse_obj(obj)++ # raise errors for additional fields in the input+ for _key in obj.keys():+ if _key not in cls.__properties:+ raise ValueError(+ "Error due to additional fields (not defined in RunningInstance) in the input: "+ + obj+ )++ _obj = RunningInstance.parse_obj(+ {+ "env_id": obj.get("envID"),+ "instance_id": obj.get("instanceID"),+ "client_id": obj.get("clientID"),+ "started_at": obj.get("startedAt"),+ "metadata": obj.get("metadata"),+ }+ )+ return _objdiff --git a/packages/python-sdk/e2b/api/v1/client_README.md b/packages/python-sdk/e2b/api/v1/client_README.mdindex 752193f18..b0cab558c 100644--- a/packages/python-sdk/e2b/api/v1/client_README.md+++ b/packages/python-sdk/e2b/api/v1/client_README.md@@ -56,13 +56,13 @@ configuration.api_key['ApiKeyAuth'] = os.environ["API_KEY"]with e2b.api.v1.client.ApiClient(configuration) as api_client:# Create an instance of the API classapi_instance = e2b.api.v1.client.InstancesApi(api_client)- instance_id = 'instance_id_example' # str |- instances_instance_id_refreshes_post_request = e2b.api.v1.client.InstancesInstanceIDRefreshesPostRequest() # InstancesInstanceIDRefreshesPostRequest | (optional)try:- api_instance.instances_instance_id_refreshes_post(instance_id, instances_instance_id_refreshes_post_request=instances_instance_id_refreshes_post_request)+ api_response = api_instance.instances_get()+ print("The response of InstancesApi->instances_get:\n")+ pprint(api_response)except ApiException as e:- print("Exception when calling InstancesApi->instances_instance_id_refreshes_post: %s\n" % e)+ print("Exception when calling InstancesApi->instances_get: %s\n" % e)```@@ -72,6 +72,7 @@ All URIs are relative to *https://api.e2b.dev*Class | Method | HTTP request | Description------------ | ------------- | ------------- | -------------+*InstancesApi* | [**instances_get**](e2b/api/v1/client/docs/InstancesApi.md#instances_get) | **GET** /instances |*InstancesApi* | [**instances_instance_id_refreshes_post**](e2b/api/v1/client/docs/InstancesApi.md#instances_instance_id_refreshes_post) | **POST** /instances/{instanceID}/refreshes |*InstancesApi* | [**instances_post**](e2b/api/v1/client/docs/InstancesApi.md#instances_post) | **POST** /instances |@@ -85,6 +86,7 @@ Class | Method | HTTP request | Description- [Instance](e2b/api/v1/client/docs/Instance.md)- [InstancesInstanceIDRefreshesPostRequest](e2b/api/v1/client/docs/InstancesInstanceIDRefreshesPostRequest.md)- [NewInstance](e2b/api/v1/client/docs/NewInstance.md)+ - [RunningInstance](e2b/api/v1/client/docs/RunningInstance.md)<a id="documentation-for-authorization"></a>diff --git a/packages/python-sdk/e2b/api/v2/client/__init__.py b/packages/python-sdk/e2b/api/v2/client/__init__.pyindex 7e1439dba..054d0a29c 100644--- a/packages/python-sdk/e2b/api/v2/client/__init__.py+++ b/packages/python-sdk/e2b/api/v2/client/__init__.py@@ -42,3 +42,4 @@ from e2b.api.v2.client.models.instances_instance_id_refreshes_post_request imporInstancesInstanceIDRefreshesPostRequest,)from e2b.api.v2.client.models.new_instance import NewInstance+from e2b.api.v2.client.models.running_instance import RunningInstancediff --git a/packages/python-sdk/e2b/api/v2/client/api/instances_api.py b/packages/python-sdk/e2b/api/v2/client/api/instances_api.pyindex ed7ddf1a1..1470f5ee8 100644--- a/packages/python-sdk/e2b/api/v2/client/api/instances_api.py+++ b/packages/python-sdk/e2b/api/v2/client/api/instances_api.py@@ -25,13 +25,14 @@ except ImportError:from pydantic import StrictStr-from typing import Optional+from typing import List, Optionalfrom e2b.api.v2.client.models.instance import Instancefrom e2b.api.v2.client.models.instances_instance_id_refreshes_post_request import (InstancesInstanceIDRefreshesPostRequest,)from e2b.api.v2.client.models.new_instance import NewInstance+from e2b.api.v2.client.models.running_instance import RunningInstancefrom e2b.api.v2.client.api_client import ApiClientfrom e2b.api.v2.client.api_response import ApiResponse@@ -50,6 +51,238 @@ class InstancesApi:api_client = ApiClient.get_default()self.api_client = api_client+ @validate_call+ def instances_get(+ self,+ _request_timeout: Union[+ None,+ Annotated[StrictFloat, Field(gt=0)],+ Tuple[+ Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]+ ],+ ] = None,+ _request_auth: Optional[Dict[StrictStr, Any]] = None,+ _content_type: Optional[StrictStr] = None,+ _headers: Optional[Dict[StrictStr, Any]] = None,+ _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,+ ) -> List[RunningInstance]:+ """instances_get++ List all running instances++ :param _request_timeout: timeout setting for this request. If one+ number provided, it will be total request+ timeout. It can also be a pair (tuple) of+ (connection, read) timeouts.+ :type _request_timeout: int, tuple(int, int), optional+ :param _request_auth: set to override the auth_settings for an a single+ request; this effectively ignores the+ authentication in the spec for a single request.+ :type _request_auth: dict, optional+ :param _content_type: force content-type for the request.+ :type _content_type: str, Optional+ :param _headers: set to override the headers for a single+ request; this effectively ignores the headers+ in the spec for a single request.+ :type _headers: dict, optional+ :param _host_index: set to override the host_index for a single+ request; this effectively ignores the host_index+ in the spec for a single request.+ :type _host_index: int, optional+ :return: Returns the result object.+ """ # noqa: E501++ _param = self._instances_get_serialize(+ _request_auth=_request_auth,+ _content_type=_content_type,+ _headers=_headers,+ _host_index=_host_index,+ )++ _response_types_map: Dict[str, Optional[str]] = {+ "200": "List[RunningInstance]",+ "401": "Error",+ "400": "Error",+ "500": "Error",+ }+ response_data = self.api_client.call_api(+ *_param, _request_timeout=_request_timeout+ )+ response_data.read()+ return self.api_client.response_deserialize(+ response_data=response_data,+ response_types_map=_response_types_map,+ ).data++ @validate_call+ def instances_get_with_http_info(+ self,+ _request_timeout: Union[+ None,+ Annotated[StrictFloat, Field(gt=0)],+ Tuple[+ Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]+ ],+ ] = None,+ _request_auth: Optional[Dict[StrictStr, Any]] = None,+ _content_type: Optional[StrictStr] = None,+ _headers: Optional[Dict[StrictStr, Any]] = None,+ _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,+ ) -> ApiResponse[List[RunningInstance]]:+ """instances_get++ List all running instances++ :param _request_timeout: timeout setting for this request. If one+ number provided, it will be total request+ timeout. It can also be a pair (tuple) of+ (connection, read) timeouts.+ :type _request_timeout: int, tuple(int, int), optional+ :param _request_auth: set to override the auth_settings for an a single+ request; this effectively ignores the+ authentication in the spec for a single request.+ :type _request_auth: dict, optional+ :param _content_type: force content-type for the request.+ :type _content_type: str, Optional+ :param _headers: set to override the headers for a single+ request; this effectively ignores the headers+ in the spec for a single request.+ :type _headers: dict, optional+ :param _host_index: set to override the host_index for a single+ request; this effectively ignores the host_index+ in the spec for a single request.+ :type _host_index: int, optional+ :return: Returns the result object.+ """ # noqa: E501++ _param = self._instances_get_serialize(+ _request_auth=_request_auth,+ _content_type=_content_type,+ _headers=_headers,+ _host_index=_host_index,+ )++ _response_types_map: Dict[str, Optional[str]] = {+ "200": "List[RunningInstance]",+ "401": "Error",+ "400": "Error",+ "500": "Error",+ }+ response_data = self.api_client.call_api(+ *_param, _request_timeout=_request_timeout+ )+ response_data.read()+ return self.api_client.response_deserialize(+ response_data=response_data,+ response_types_map=_response_types_map,+ )++ @validate_call+ def instances_get_without_preload_content(+ self,+ _request_timeout: Union[+ None,+ Annotated[StrictFloat, Field(gt=0)],+ Tuple[+ Annotated[StrictFloat, Field(gt=0)], Annotated[StrictFloat, Field(gt=0)]+ ],+ ] = None,+ _request_auth: Optional[Dict[StrictStr, Any]] = None,+ _content_type: Optional[StrictStr] = None,+ _headers: Optional[Dict[StrictStr, Any]] = None,+ _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,+ ) -> RESTResponseType:+ """instances_get++ List all running instances++ :param _request_timeout: timeout setting for this request. If one+ number provided, it will be total request+ timeout. It can also be a pair (tuple) of+ (connection, read) timeouts.+ :type _request_timeout: int, tuple(int, int), optional+ :param _request_auth: set to override the auth_settings for an a single+ request; this effectively ignores the+ authentication in the spec for a single request.+ :type _request_auth: dict, optional+ :param _content_type: force content-type for the request.+ :type _content_type: str, Optional+ :param _headers: set to override the headers for a single+ request; this effectively ignores the headers+ in the spec for a single request.+ :type _headers: dict, optional+ :param _host_index: set to override the host_index for a single+ request; this effectively ignores the host_index+ in the spec for a single request.+ :type _host_index: int, optional+ :return: Returns the result object.+ """ # noqa: E501++ _param = self._instances_get_serialize(+ _request_auth=_request_auth,+ _content_type=_content_type,+ _headers=_headers,+ _host_index=_host_index,+ )++ _response_types_map: Dict[str, Optional[str]] = {+ "200": "List[RunningInstance]",+ "401": "Error",+ "400": "Error",+ "500": "Error",+ }+ response_data = self.api_client.call_api(+ *_param, _request_timeout=_request_timeout+ )+ return response_data.response++ def _instances_get_serialize(+ self,+ _request_auth,+ _content_type,+ _headers,+ _host_index,+ ) -> Tuple:+ _host = None++ _collection_formats: Dict[str, str] = {}++ _path_params: Dict[str, str] = {}+ _query_params: List[Tuple[str, str]] = []+ _header_params: Dict[str, Optional[str]] = _headers or {}+ _form_params: List[Tuple[str, str]] = []+ _files: Dict[str, str] = {}+ _body_params: Optional[bytes] = None++ # process the path parameters+ # process the query parameters+ # process the header parameters+ # process the form parameters+ # process the body parameter++ # set the HTTP header `Accept`+ _header_params["Accept"] = self.api_client.select_header_accept(+ ["application/json"]+ )++ # authentication setting+ _auth_settings: List[str] = ["ApiKeyAuth"]++ return self.api_client.param_serialize(+ method="GET",+ resource_path="/instances",+ path_params=_path_params,+ query_params=_query_params,+ header_params=_header_params,+ body=_body_params,+ post_params=_form_params,+ files=_files,+ auth_settings=_auth_settings,+ collection_formats=_collection_formats,+ _host=_host,+ _request_auth=_request_auth,+ )+@validate_calldef instances_instance_id_refreshes_post(self,diff --git a/packages/python-sdk/e2b/api/v2/client/models/__init__.py b/packages/python-sdk/e2b/api/v2/client/models/__init__.pyindex 9bf7a98c3..7caebbf31 100644--- a/packages/python-sdk/e2b/api/v2/client/models/__init__.py+++ b/packages/python-sdk/e2b/api/v2/client/models/__init__.py@@ -25,3 +25,4 @@ from e2b.api.v2.client.models.instances_instance_id_refreshes_post_request imporInstancesInstanceIDRefreshesPostRequest,)from e2b.api.v2.client.models.new_instance import NewInstance+from e2b.api.v2.client.models.running_instance import RunningInstancediff --git a/packages/python-sdk/e2b/api/v2/client/models/new_instance.py b/packages/python-sdk/e2b/api/v2/client/models/new_instance.pyindex 35ca42054..3c1637226 100644--- a/packages/python-sdk/e2b/api/v2/client/models/new_instance.py+++ b/packages/python-sdk/e2b/api/v2/client/models/new_instance.py@@ -18,7 +18,7 @@ import re # noqa: F401import json-from typing import Any, ClassVar, Dict, List+from typing import Any, ClassVar, Dict, List, Optionalfrom pydantic import BaseModel, StrictStrfrom pydantic import Field@@ -36,7 +36,8 @@ class NewInstance(BaseModel):env_id: StrictStr = Field(description="Identifier of the required environment", alias="envID")- __properties: ClassVar[List[str]] = ["envID"]+ metadata: Optional[Dict[str, StrictStr]] = None+ __properties: ClassVar[List[str]] = ["envID", "metadata"]model_config = {"populate_by_name": True, "validate_assignment": True}@@ -88,5 +89,7 @@ class NewInstance(BaseModel):+ _key)- _obj = cls.model_validate({"envID": obj.get("envID")})+ _obj = cls.model_validate(+ {"envID": obj.get("envID"), "metadata": obj.get("metadata")}+ )return _objdiff --git a/packages/python-sdk/e2b/api/v2/client/models/running_instance.py b/packages/python-sdk/e2b/api/v2/client/models/running_instance.pynew file mode 100644index 000000000..5322f8c27--- /dev/null+++ b/packages/python-sdk/e2b/api/v2/client/models/running_instance.py@@ -0,0 +1,117 @@+# coding: utf-8++"""+ E2B API++ No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)++ The version of the OpenAPI document: 0.1.0+ Generated by OpenAPI Generator (https://openapi-generator.tech)++ Do not edit the class manually.+""" # noqa: E501+++from __future__ import annotations+import pprint+import re # noqa: F401+import json++from datetime import datetime+from typing import Any, ClassVar, Dict, List, Optional+from pydantic import BaseModel, StrictStr+from pydantic import Field++try:+ from typing import Self+except ImportError:+ from typing_extensions import Self+++class RunningInstance(BaseModel):+ """+ RunningInstance+ """ # noqa: E501++ env_id: StrictStr = Field(+ description="Identifier of the environment from which is the instance created",+ alias="envID",+ )+ instance_id: StrictStr = Field(+ description="Identifier of the instance", alias="instanceID"+ )+ client_id: StrictStr = Field(+ description="Identifier of the client", alias="clientID"+ )+ started_at: datetime = Field(+ description="Time when the instance was started", alias="startedAt"+ )+ metadata: Optional[Dict[str, StrictStr]] = None+ __properties: ClassVar[List[str]] = [+ "envID",+ "instanceID",+ "clientID",+ "startedAt",+ "metadata",+ ]++ model_config = {"populate_by_name": True, "validate_assignment": True}++ def to_str(self) -> str:+ """Returns the string representation of the model using alias"""+ return pprint.pformat(self.model_dump(by_alias=True))++ def to_json(self) -> str:+ """Returns the JSON representation of the model using alias"""+ # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead+ return json.dumps(self.to_dict())++ @classmethod+ def from_json(cls, json_str: str) -> Self:+ """Create an instance of RunningInstance from a JSON string"""+ return cls.from_dict(json.loads(json_str))++ def to_dict(self) -> Dict[str, Any]:+ """Return the dictionary representation of the model using alias.++ This has the following differences from calling pydantic's+ `self.model_dump(by_alias=True)`:++ * `None` is only added to the output dict for nullable fields that+ were set at model initialization. Other fields with value `None`+ are ignored.+ """+ _dict = self.model_dump(+ by_alias=True,+ exclude={},+ exclude_none=True,+ )+ return _dict++ @classmethod+ def from_dict(cls, obj: Dict) -> Self:+ """Create an instance of RunningInstance from a dict"""+ if obj is None:+ return None++ if not isinstance(obj, dict):+ return cls.model_validate(obj)++ # raise errors for additional fields in the input+ for _key in obj.keys():+ if _key not in cls.__properties:+ raise ValueError(+ "Error due to additional fields (not defined in RunningInstance) in the input: "+ + _key+ )++ _obj = cls.model_validate(+ {+ "envID": obj.get("envID"),+ "instanceID": obj.get("instanceID"),+ "clientID": obj.get("clientID"),+ "startedAt": obj.get("startedAt"),+ "metadata": obj.get("metadata"),+ }+ )+ return _objdiff --git a/packages/python-sdk/e2b/api/v2/client_README.md b/packages/python-sdk/e2b/api/v2/client_README.mdindex e60f09ce8..a082b2e0f 100644--- a/packages/python-sdk/e2b/api/v2/client_README.md+++ b/packages/python-sdk/e2b/api/v2/client_README.md@@ -55,13 +55,13 @@ configuration.api_key['ApiKeyAuth'] = os.environ["API_KEY"]with e2b.api.v2.client.ApiClient(configuration) as api_client:# Create an instance of the API classapi_instance = e2b.api.v2.client.InstancesApi(api_client)- instance_id = 'instance_id_example' # str |- instances_instance_id_refreshes_post_request = e2b.api.v2.client.InstancesInstanceIDRefreshesPostRequest() # InstancesInstanceIDRefreshesPostRequest | (optional)try:- api_instance.instances_instance_id_refreshes_post(instance_id, instances_instance_id_refreshes_post_request=instances_instance_id_refreshes_post_request)+ api_response = api_instance.instances_get()+ print("The response of InstancesApi->instances_get:\n")+ pprint(api_response)except ApiException as e:- print("Exception when calling InstancesApi->instances_instance_id_refreshes_post: %s\n" % e)+ print("Exception when calling InstancesApi->instances_get: %s\n" % e)```@@ -71,6 +71,7 @@ All URIs are relative to *https://api.e2b.dev*Class | Method | HTTP request | Description------------ | ------------- | ------------- | -------------+*InstancesApi* | [**instances_get**](e2b/api/v2/client/docs/InstancesApi.md#instances_get) | **GET** /instances |*InstancesApi* | [**instances_instance_id_refreshes_post**](e2b/api/v2/client/docs/InstancesApi.md#instances_instance_id_refreshes_post) | **POST** /instances/{instanceID}/refreshes |*InstancesApi* | [**instances_post**](e2b/api/v2/client/docs/InstancesApi.md#instances_post) | **POST** /instances |@@ -84,6 +85,7 @@ Class | Method | HTTP request | Description- [Instance](e2b/api/v2/client/docs/Instance.md)- [InstancesInstanceIDRefreshesPostRequest](e2b/api/v2/client/docs/InstancesInstanceIDRefreshesPostRequest.md)- [NewInstance](e2b/api/v2/client/docs/NewInstance.md)+ - [RunningInstance](e2b/api/v2/client/docs/RunningInstance.md)<a id="documentation-for-authorization"></a>diff --git a/packages/python-sdk/e2b/sandbox/main.py b/packages/python-sdk/e2b/sandbox/main.pyindex b343a5ecf..551782abf 100644--- a/packages/python-sdk/e2b/sandbox/main.py+++ b/packages/python-sdk/e2b/sandbox/main.py@@ -12,7 +12,7 @@ from e2b.constants import TIMEOUT, ENVD_PORT, FILE_ROUTEfrom e2b.sandbox.code_snippet import CodeSnippetManager, OpenPortfrom e2b.sandbox.env_vars import EnvVarsfrom e2b.sandbox.filesystem import FilesystemManager-from e2b.sandbox.process import Process, ProcessManager, ProcessMessage+from e2b.sandbox.process import ProcessManager, ProcessMessagefrom e2b.sandbox.sandbox_connection import SandboxConnectionfrom e2b.sandbox.terminal import TerminalManager@@ -75,6 +75,7 @@ class Sandbox(SandboxConnection):on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,on_exit: Optional[Union[Callable[[int], Any], Callable[[], Any]]] = None,+ metadata: Optional[Dict[str, str]] = None,timeout: Optional[float] = TIMEOUT,_sandbox: Optional[models.Instance] = None,_debug_hostname: Optional[str] = None,@@ -93,10 +94,12 @@ class Sandbox(SandboxConnection)::param api_key: The API key to use, if not provided, the `E2B_API_KEY` environment variable is used:param cwd: The current working directory to use+ :param env_vars: A dictionary of environment variables to be used for all processes:param on_scan_ports: A callback to handle opened ports:param on_stdout: A default callback that is called when stdout with a newline is received from the process:param on_stderr: A default callback that is called when stderr with a newline is received from the process:param on_exit: A default callback that is called when the process exits+ :param metadata: A dictionary of metadata to be used for the sandbox:param timeout: Timeout for sandbox to initialize in seconds, default is 60 seconds"""@@ -137,6 +140,7 @@ class Sandbox(SandboxConnection):**default_env_vars,**(env_vars or {}),},+ metadata=metadata,_sandbox=_sandbox,_debug_hostname=_debug_hostname,_debug_port=_debug_port,@@ -238,14 +242,73 @@ class Sandbox(SandboxConnection):thread = threading.Thread(target=run_in_thread)thread.start()- def _open(self, timeout: Optional[float] = TIMEOUT) -> None:+ @classmethod+ def reconnect(+ cls,+ sandbox_id: str,+ cwd: Optional[str] = None,+ env_vars: Optional[EnvVars] = None,+ on_scan_ports: Optional[Callable[[List[OpenPort]], Any]] = None,+ on_stdout: Optional[Callable[[ProcessMessage], Any]] = None,+ on_stderr: Optional[Callable[[ProcessMessage], Any]] = None,+ on_exit: Optional[Union[Callable[[int], Any], Callable[[], Any]]] = None,+ timeout: Optional[float] = TIMEOUT,+ **kwargs,+ ):+ """+ Reconnects to a previously created sandbox.++ :param sandbox_id: ID of the sandbox to reconnect to+ :param cwd: The current working directory to use+ :param env_vars: A dictionary of environment variables to be used for all processes+ :param on_scan_ports: A callback to handle opened ports+ :param on_stdout: A default callback that is called when stdout with a newline is received from the process+ :param on_stderr: A default callback that is called when stderr with a newline is received from the process+ :param on_exit: A default callback that is called when the process exits+ :param timeout: Timeout for sandbox to initialize in seconds, default is 60 seconds++ ```py+ sandbox = Sandbox()+ id = sandbox.id+ sandbox.keep_alive(300)+ sandbox.close()++ # Reconnect to the sandbox+ reconnected_sandbox = Sandbox.reconnect(id)+ ```++ """++ logger.info(f"Reconnecting to sandbox {sandbox_id}")+ instance_id, client_id = sandbox_id.split("-")+ return cls(+ cwd=cwd,+ env_vars=env_vars,+ on_scan_ports=on_scan_ports,+ on_stdout=on_stdout,+ on_stderr=on_stderr,+ on_exit=on_exit,+ timeout=timeout,+ _sandbox=models.Instance(+ instance_id=instance_id,+ client_id=client_id,+ env_id=getattr(cls, "sandbox_template_id", "unknown"),+ ),+ **kwargs,+ )++ def _open(+ self,+ metadata: Optional[Dict[str, str]] = None,+ timeout: Optional[float] = TIMEOUT,+ ) -> None:"""Open the sandbox.:param timeout: Specify the duration, in seconds to give the method to finish its execution before it times out (default is 60 seconds). If set to None, the method will continue to wait until it completes, regardless of time"""logger.info(f"Opening sandbox {self._template}")- super()._open(timeout=timeout)+ super()._open(metadata=metadata, timeout=timeout)self._code_snippet._subscribe()logger.info(f"Sandbox {self._template} opened")diff --git a/packages/python-sdk/e2b/sandbox/sandbox_connection.py b/packages/python-sdk/e2b/sandbox/sandbox_connection.pyindex 5839dd2ea..9c2c679e8 100644--- a/packages/python-sdk/e2b/sandbox/sandbox_connection.py+++ b/packages/python-sdk/e2b/sandbox/sandbox_connection.py@@ -4,9 +4,8 @@ import threadingimport tracebackimport warningsfrom concurrent.futures import ThreadPoolExecutor, CancelledError-from os import getenvfrom time import sleep-from typing import Any, Callable, List, Literal, Optional, Union+from typing import Any, Callable, List, Literal, Optional, Union, Dictfrom pydantic import BaseModelfrom urllib3.exceptions import ReadTimeoutError, MaxRetryError, ConnectTimeoutError@@ -22,13 +21,13 @@ from e2b.constants import ()from e2b.sandbox.env_vars import EnvVarsfrom e2b.sandbox.exception import (- AuthenticationException,MultipleExceptions,SandboxException,TimeoutException,SandboxNotOpenException,)from e2b.sandbox.sandbox_rpc import Notification, SandboxRpc+from e2b.utils.api_key import get_api_keyfrom e2b.utils.future import DeferredFuturefrom e2b.utils.str import camel_case_to_snake_case@@ -84,20 +83,14 @@ class SandboxConnection:api_key: Optional[str] = None,cwd: Optional[str] = None,env_vars: Optional[EnvVars] = None,+ metadata: Optional[Dict[str, str]] = None,timeout: Optional[float] = TIMEOUT,_sandbox: Optional[models.Instance] = None,_debug_hostname: Optional[str] = None,_debug_port: Optional[int] = None,_debug_dev_env: Optional[Literal["remote", "local"]] = None,):- api_key = api_key or getenv("E2B_API_KEY")-- if api_key is None:- raise AuthenticationException(- "API key is required, please visit https://e2b.dev/docs to get your API key. "- "You can either set the environment variable `E2B_API_KEY` "- 'or you can pass it directly to the sandbox like Sandbox(api_key="e2b_...")',- )+ api_key = get_api_key(api_key)self.cwd = cwd"""@@ -126,55 +119,13 @@ class SandboxConnection:logger.info(f"Sandbox for template {self._template} initialized")- self._open(timeout=timeout)+ self._open(metadata=metadata, timeout=timeout)@classmethoddef create(cls, *args, **kwargs):warnings.warn("Sandbox.create() is deprecated, use Sandbox() instead")return cls(*args, **kwargs)- @classmethod- def reconnect(- cls,- sandbox_id: str,- *args,- **kwargs,- ):- """- Reconnects to a previously created sandbox.-- :param sandbox_id: ID of the sandbox to reconnect to- :param cwd: The current working directory to use- :param on_scan_ports: A callback to handle opened ports- :param on_stdout: A default callback that is called when stdout with a newline is received from the process- :param on_stderr: A default callback that is called when stderr with a newline is received from the process- :param on_exit: A default callback that is called when the process exits- :param timeout: Timeout for sandbox to initialize in seconds, default is 60 seconds-- ```py- sandbox = Sandbox()- id = sandbox.id- sandbox.keep_alive(300)- sandbox.close()-- # Reconnect to the sandbox- reconnected_sandbox = Sandbox.reconnect(id)- ```-- """-- logger.info(f"Reconnecting to sandbox {sandbox_id}")- instance_id, client_id = sandbox_id.split("-")- return cls(- *args,- _sandbox=models.Instance(- instance_id=instance_id,- client_id=client_id,- env_id=getattr(cls, "sandbox_template_id", "unknown"),- ),- **kwargs,- )-def get_hostname(self, port: Optional[int] = None) -> str:"""Get the hostname for the sandbox or for the specified sandbox's port.@@ -264,7 +215,11 @@ class SandboxConnection:cleanup()self._process_cleanup.clear()- def _open(self, timeout: Optional[float] = TIMEOUT) -> None:+ def _open(+ self,+ metadata: Optional[Dict[str, str]] = None,+ timeout: Optional[float] = TIMEOUT,+ ) -> None:"""Open a connection to a new sandbox.@@ -281,7 +236,7 @@ class SandboxConnection:api = client.InstancesApi(api_client)self._sandbox = api.instances_post(- models.NewInstance(envID=self._template),+ models.NewInstance(envID=self._template, metadata=metadata),_request_timeout=timeout,)logger.info(@@ -496,3 +451,14 @@ class SandboxConnection:logger.info("No sandbox to stop refreshing. Sandbox was not created")self._close()++ @staticmethod+ def list(api_key: Optional[str] = None) -> List[models.RunningInstance]:+ """+ List all running sandboxes.++ :param api_key: API key to use for authentication. If not provided, the `E2B_API_KEY` environment variable will be used.+ """+ api_key = get_api_key(api_key)+ with E2BApiClient(api_key=api_key) as api_client:+ return client.InstancesApi(api_client).instances_get()diff --git a/packages/python-sdk/e2b/utils/api_key.py b/packages/python-sdk/e2b/utils/api_key.pynew file mode 100644index 000000000..edddf0be1--- /dev/null+++ b/packages/python-sdk/e2b/utils/api_key.py@@ -0,0 +1,17 @@+from os import getenv+from typing import Optional++from e2b.sandbox.exception import AuthenticationException+++def get_api_key(api_key: Optional[str]) -> str:+ api_key = api_key or getenv("E2B_API_KEY")++ if api_key is None:+ raise AuthenticationException(+ "API key is required, please visit https://e2b.dev/docs to get your API key. "+ "You can either set the environment variable `E2B_API_KEY` "+ 'or you can pass it directly to the sandbox like Sandbox(api_key="e2b_...")',+ )++ return api_keydiff --git a/packages/python-sdk/tests/test_list_sandboxes.py b/packages/python-sdk/tests/test_list_sandboxes.pynew file mode 100644index 000000000..8526f34b7--- /dev/null+++ b/packages/python-sdk/tests/test_list_sandboxes.py@@ -0,0 +1,14 @@+from e2b import Sandbox+++def test_list_running_sandboxes():+ sandboxes = []+ for i in range(3):+ sandboxes.append(Sandbox(metadata={"n": str(i)}))++ running_sandboxes = Sandbox.list()+ assert len(running_sandboxes) == 3+ assert set(map(lambda x: x.metadata['n'], running_sandboxes)) == {'0', '1', '2'}++ for sandbox in sandboxes:+ sandbox.close()diff --git a/spec/openapi.yml b/spec/openapi.ymlindex b28bdcf02..b721c3e5c 100644--- a/spec/openapi.yml+++ b/spec/openapi.yml@@ -65,6 +65,11 @@ components:$ref: "#/components/schemas/Error"schemas:+ InstanceMetadata:+ additionalProperties:+ type: string+ description: Metadata of the instance+NewInstance:required:- envID@@ -72,6 +77,8 @@ components:envID:type: stringdescription: Identifier of the required environment+ metadata:+ $ref: "#/components/schemas/InstanceMetadata"Environment:required:@@ -93,6 +100,7 @@ components:description: Aliases of the environmentitems:type: string+EnvironmentBuild:required:- envID@@ -149,6 +157,29 @@ components:type: stringdescription: Error+ RunningInstance:+ required:+ - envID+ - instanceID+ - clientID+ - startedAt+ properties:+ envID:+ type: string+ description: Identifier of the environment from which is the instance created+ instanceID:+ type: string+ description: Identifier of the instance+ clientID:+ type: string+ description: Identifier of the client+ startedAt:+ type: string+ format: date-time+ description: Time when the instance was started+ metadata:+ $ref: "#/components/schemas/InstanceMetadata"+tags:- name: instances- name: envs@@ -164,6 +195,27 @@ paths:$ref: "#/components/responses/401"/instances:+ get:+ description: List all running instances+ tags: [instances]+ security:+ - ApiKeyAuth: [ ]+ responses:+ 200:+ description: Successfully returned all running instances+ content:+ application/json:+ schema:+ type: array+ items:+ allOf:+ - $ref: "#/components/schemas/RunningInstance"+ 401:+ $ref: "#/components/responses/401"+ 400:+ $ref: "#/components/responses/400"+ 500:+ $ref: "#/components/responses/500"post:description: Create an instance from the environmenttags: [instances]