Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
SDK v2 - Changeset and docs (#862)
Jakub Novák74457ff1dde9
diff --git a/.changeset/angry-ties-carry.md b/.changeset/angry-ties-carry.mdnew file mode 100644index 000000000..8f6bcb9dd--- /dev/null+++ b/.changeset/angry-ties-carry.md@@ -0,0 +1,8 @@+---+'@e2b/python-sdk': major+'e2b': major+'@e2b/cli': major+---++- Add beta module (pause and resume)+- Update list method to allow list paused sandboxesdiff --git a/.changeset/strange-hornets-judge.md b/.changeset/strange-hornets-judge.mdnew file mode 100644index 000000000..cb559f6ab--- /dev/null+++ b/.changeset/strange-hornets-judge.md@@ -0,0 +1,5 @@+---+'@e2b/python-sdk': minor+---++Refactor connection config and parameters for all calls to APIdiff --git a/apps/web/src/app/(docs)/docs/api-key/page.mdx b/apps/web/src/app/(docs)/docs/api-key/page.mdxindex 08b427caf..9b65530fa 100644--- a/apps/web/src/app/(docs)/docs/api-key/page.mdx+++ b/apps/web/src/app/(docs)/docs/api-key/page.mdx@@ -16,7 +16,7 @@ const sandbox = await Sandbox.create({ apiKey: 'YOUR_API_KEY' })```python {{ language: 'python' }}from e2b_code_interpreter import Sandbox-sbx = Sandbox(api_key="YOUR_API_KEY")+sbx = Sandbox.create(api_key="YOUR_API_KEY")```</CodeGroup>diff --git a/apps/web/src/app/(docs)/docs/cli/list-sandboxes/page.mdx b/apps/web/src/app/(docs)/docs/cli/list-sandboxes/page.mdxindex 11671efee..6d9b55317 100644--- a/apps/web/src/app/(docs)/docs/cli/list-sandboxes/page.mdx+++ b/apps/web/src/app/(docs)/docs/cli/list-sandboxes/page.mdx@@ -1,6 +1,6 @@# List sandboxes-You can list all running sandboxes using the following command:+You can list all sandboxes using the following command:<CodeGroup isTerminalCommand>```bash@@ -8,21 +8,7 @@ e2b sandbox list```</CodeGroup>-## Changes in the Beta CLI--<Note>-If you're using the [beta version of the CLI](/docs/cli#beta-cli), the `sandbox list` command was updated.-</Note>--### List all sandboxes--To list all sandboxes, use the following command:--```bash-e2b sandbox list-```--This will return all sandboxes, both running and paused.+This will return running sandboxes, you can specify `--state` to get paused or both.### Filter by statediff --git a/apps/web/src/app/(docs)/docs/code-interpreting/analyze-data-with-ai/page.mdx b/apps/web/src/app/(docs)/docs/code-interpreting/analyze-data-with-ai/page.mdxindex 5e75c15eb..1594f183c 100644--- a/apps/web/src/app/(docs)/docs/code-interpreting/analyze-data-with-ai/page.mdx+++ b/apps/web/src/app/(docs)/docs/code-interpreting/analyze-data-with-ai/page.mdx@@ -82,7 +82,7 @@ load_dotenv()from e2b_code_interpreter import Sandbox# Create sandbox-sbx = Sandbox()+sbx = Sandbox.create()# Upload the dataset to the sandboxdataset_path_in_sandbox = ""@@ -453,7 +453,7 @@ from e2b_code_interpreter import Sandboxfrom anthropic import Anthropic# Create sandbox-sbx = Sandbox()+sbx = Sandbox.create()# Upload the dataset to the sandboxwith open("../dataset.csv", "rb") as f:diff --git a/apps/web/src/app/(docs)/docs/code-interpreting/create-charts-visualizations/interactive-charts/page.mdx b/apps/web/src/app/(docs)/docs/code-interpreting/create-charts-visualizations/interactive-charts/page.mdxindex fe356e49b..40578de88 100644--- a/apps/web/src/app/(docs)/docs/code-interpreting/create-charts-visualizations/interactive-charts/page.mdx+++ b/apps/web/src/app/(docs)/docs/code-interpreting/create-charts-visualizations/interactive-charts/page.mdx@@ -68,7 +68,7 @@ plt.tight_layout()plt.show()"""-sandbox = Sandbox()+sandbox = Sandbox.create()execution = sandbox.run_code(code)chart = execution.results[0].chartdiff --git a/apps/web/src/app/(docs)/docs/code-interpreting/create-charts-visualizations/static-charts/page.mdx b/apps/web/src/app/(docs)/docs/code-interpreting/create-charts-visualizations/static-charts/page.mdxindex 28b5b2a39..459acb1f4 100644--- a/apps/web/src/app/(docs)/docs/code-interpreting/create-charts-visualizations/static-charts/page.mdx+++ b/apps/web/src/app/(docs)/docs/code-interpreting/create-charts-visualizations/static-charts/page.mdx@@ -47,7 +47,7 @@ plt.ylabel('some numbers')plt.show()"""-sandbox = Sandbox()+sandbox = Sandbox.create()# Run the code inside the sandboxexecution = sandbox.run_code(code_to_run)diff --git a/apps/web/src/app/(docs)/docs/code-interpreting/streaming/page.mdx b/apps/web/src/app/(docs)/docs/code-interpreting/streaming/page.mdxindex 45a965274..c9cbfe6aa 100644--- a/apps/web/src/app/(docs)/docs/code-interpreting/streaming/page.mdx+++ b/apps/web/src/app/(docs)/docs/code-interpreting/streaming/page.mdx@@ -40,7 +40,7 @@ code_to_run = """print("This goes last")"""-sandbox = Sandbox()+sandbox = Sandbox.create()sandbox.run_code(code_to_run,# Use `on_error` to handle runtime code errors@@ -131,7 +131,7 @@ plt.title('Values by Category')plt.show()"""-sandbox = Sandbox()+sandbox = Sandbox.create()sandbox.run_code(code_to_run,on_result=lambda result: print('result:', result), # $HighlightLinediff --git a/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/bash/page.mdx b/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/bash/page.mdxindex b0ec39d26..0a725a2f4 100644--- a/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/bash/page.mdx+++ b/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/bash/page.mdx@@ -12,7 +12,7 @@ console.log(execution)```pythonfrom e2b_code_interpreter import Sandbox-sbx = Sandbox()+sbx = Sandbox.create()execution = sbx.run_code("echo 'Hello, world!'", language="bash")print(execution)```diff --git a/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/java/page.mdx b/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/java/page.mdxindex 6fdf1894d..ec17d91f5 100644--- a/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/java/page.mdx+++ b/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/java/page.mdx@@ -12,7 +12,7 @@ console.log(execution)```pythonfrom e2b_code_interpreter import Sandbox-sbx = Sandbox()+sbx = Sandbox.create()execution = sbx.run_code('System.out.println("Hello, world!");', language="java")print(execution)```diff --git a/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/javascript/page.mdx b/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/javascript/page.mdxindex 5dd057c00..d818d5d3d 100644--- a/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/javascript/page.mdx+++ b/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/javascript/page.mdx@@ -46,7 +46,7 @@ console.log(execution);from e2b_code_interpreter import Sandbox# Create a new sandbox-sbx = Sandbox()+sbx = Sandbox.create()# Install the axios packagesbx.commands.run("npm install axios")diff --git a/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/python/page.mdx b/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/python/page.mdxindex 276ccfd65..3b08fcc30 100644--- a/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/python/page.mdx+++ b/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/python/page.mdx@@ -11,7 +11,7 @@ console.log(execution)```pythonfrom e2b_code_interpreter import Sandbox-sbx = Sandbox()+sbx = Sandbox.create()execution = sbx.run_code('print("Hello, world!")')print(execution)```diff --git a/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/r/page.mdx b/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/r/page.mdxindex 7f48c3b33..496ffbde6 100644--- a/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/r/page.mdx+++ b/apps/web/src/app/(docs)/docs/code-interpreting/supported-languages/r/page.mdx@@ -12,7 +12,7 @@ console.log(execution)```pythonfrom e2b_code_interpreter import Sandbox-sbx = Sandbox()+sbx = Sandbox.create()execution = sbx.run_code('print("Hello, world!")', language="r")print(execution)```diff --git a/apps/web/src/app/(docs)/docs/commands/background/page.mdx b/apps/web/src/app/(docs)/docs/commands/background/page.mdxindex 84357b254..7331dad6c 100644--- a/apps/web/src/app/(docs)/docs/commands/background/page.mdx+++ b/apps/web/src/app/(docs)/docs/commands/background/page.mdx@@ -23,7 +23,7 @@ await command.kill()```pythonfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()# Start the command in the backgroundcommand = sandbox.commands.run('echo hello; sleep 10; echo world', background=True)diff --git a/apps/web/src/app/(docs)/docs/commands/page.mdx b/apps/web/src/app/(docs)/docs/commands/page.mdxindex c63dc0585..b64587e17 100644--- a/apps/web/src/app/(docs)/docs/commands/page.mdx+++ b/apps/web/src/app/(docs)/docs/commands/page.mdx@@ -13,7 +13,7 @@ console.log(result)```pythonfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()result = sandbox.commands.run('ls -l')print(result)diff --git a/apps/web/src/app/(docs)/docs/commands/streaming/page.mdx b/apps/web/src/app/(docs)/docs/commands/streaming/page.mdxindex b67f282b2..a033d43fa 100644--- a/apps/web/src/app/(docs)/docs/commands/streaming/page.mdx+++ b/apps/web/src/app/(docs)/docs/commands/streaming/page.mdx@@ -21,7 +21,7 @@ console.log(result)```pythonfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()result = sandbox.commands.run('echo hello; sleep 1; echo world', on_stdout=lambda data: print(data), on_stderr=lambda data: print(data))print(result)diff --git a/apps/web/src/app/(docs)/docs/filesystem/download/page.mdx b/apps/web/src/app/(docs)/docs/filesystem/download/page.mdxindex 94e361128..bcbd62c3c 100644--- a/apps/web/src/app/(docs)/docs/filesystem/download/page.mdx+++ b/apps/web/src/app/(docs)/docs/filesystem/download/page.mdx@@ -17,7 +17,7 @@ fs.writeFileSync('/local/path', content)```pythonfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()# Read file from sandboxcontent = sandbox.files.read('/path/in/sandbox')@@ -58,7 +58,7 @@ const content = await res.text()from e2b import Sandbox# Start a secured sandbox (all operations must be authorized by default)-sandbox = Sandbox(timeout=12_000, secure=True)+sandbox = Sandbox.create(timeout=12_000, secure=True)# Create a pre-signed URL for file download with a 10 second expiration# The user only has to visit the URL to download the file, this also works in a browser.diff --git a/apps/web/src/app/(docs)/docs/filesystem/info/page.mdx b/apps/web/src/app/(docs)/docs/filesystem/info/page.mdxindex 70354ba7b..e5282412f 100644--- a/apps/web/src/app/(docs)/docs/filesystem/info/page.mdx+++ b/apps/web/src/app/(docs)/docs/filesystem/info/page.mdx@@ -33,7 +33,7 @@ console.log(info)```pythonfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()# Create a new filesandbox.files.write('test_file', 'Hello, world!')@@ -88,7 +88,7 @@ console.log(info)```pythonfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()# Create a new directorysandbox.files.make_dir('test_dir')diff --git a/apps/web/src/app/(docs)/docs/filesystem/read-write/page.mdx b/apps/web/src/app/(docs)/docs/filesystem/read-write/page.mdxindex b861cbe68..383c7daea 100644--- a/apps/web/src/app/(docs)/docs/filesystem/read-write/page.mdx+++ b/apps/web/src/app/(docs)/docs/filesystem/read-write/page.mdx@@ -13,7 +13,7 @@ const fileContent = await sandbox.files.read('/path/to/file')```pythonfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()file_content = sandbox.files.read('/path/to/file')```</CodeGroup>@@ -32,7 +32,7 @@ await sandbox.files.write('/path/to/file', 'file content')```pythonfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()await sandbox.files.write('/path/to/file', 'file content')```@@ -40,7 +40,7 @@ await sandbox.files.write('/path/to/file', 'file content')## Writing multiple files-You can also write multiple files to the sandbox filesystem using the `files.write()` method.+You can also write multiple files to the sandbox.<CodeGroup>```js@@ -55,9 +55,9 @@ await sandbox.files.write([```pythonfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()-await sandbox.files.write([+await sandbox.files.write_files([{ "path": "/path/to/a", "data": "file content" },{ "path": "another/path/to/b", "data": "file content" }])diff --git a/apps/web/src/app/(docs)/docs/filesystem/upload/page.mdx b/apps/web/src/app/(docs)/docs/filesystem/upload/page.mdxindex 34fe5638c..2197fee6c 100644--- a/apps/web/src/app/(docs)/docs/filesystem/upload/page.mdx+++ b/apps/web/src/app/(docs)/docs/filesystem/upload/page.mdx@@ -19,7 +19,7 @@ await sandbox.files.write('/path/in/sandbox', content)```pythonfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()# Read file from local filesystemwith open("path/to/local/file", "rb") as file:@@ -64,7 +64,7 @@ from e2b import Sandboximport requests# Start a secured sandbox (all operations must be authorized by default)-sandbox = Sandbox(timeout=12_000, secure=True)+sandbox = Sandbox.create(timeout=12_000, secure=True)# Create a pre-signed URL for file upload with a 10 second expirationsigned_url = sbx.upload_url(path="demo.txt", user="user", use_signature_expiration=10_000)@@ -125,7 +125,7 @@ await sandbox.files.write(files)import osfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()def read_directory_files(directory_path):files = []diff --git a/apps/web/src/app/(docs)/docs/filesystem/watch/page.mdx b/apps/web/src/app/(docs)/docs/filesystem/watch/page.mdxindex 15383056e..36d4f6b1a 100644--- a/apps/web/src/app/(docs)/docs/filesystem/watch/page.mdx+++ b/apps/web/src/app/(docs)/docs/filesystem/watch/page.mdx@@ -28,7 +28,7 @@ await sandbox.files.write(`${dirname}/my-file`, 'hello')```pythonfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()dirname = '/home/user'# Watch directory for changes@@ -77,7 +77,7 @@ await sandbox.files.write(`${dirname}/my-folder/my-file`, 'hello') // $Highlight```pythonfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()dirname = '/home/user'# Watch directory for changesdiff --git a/apps/web/src/app/(docs)/docs/legacy/cli/commands/page.mdx b/apps/web/src/app/(docs)/docs/legacy/cli/commands/page.mdxindex 6397c7fcd..9acf27998 100644--- a/apps/web/src/app/(docs)/docs/legacy/cli/commands/page.mdx+++ b/apps/web/src/app/(docs)/docs/legacy/cli/commands/page.mdx@@ -195,7 +195,7 @@ e2b template list## `sandbox list`-List your spawned sandboxes that are running right now.+List your created sandboxes that are running right now.```bashe2b sandbox list@@ -253,7 +253,7 @@ You can use `e2b sandbox list` to get a list of running sandboxes and their IDs## `sandbox connect`-Connects your terminal to a running sandbox that you spawned via the E2B SDK.+Connects your terminal to a running sandbox that you created via the E2B SDK.This command is useful if you need to debug a running sandbox.This command works similar to the `docker exec -it <container> bash` command in Docker.@@ -274,7 +274,7 @@ You can use `e2b sandbox list` to get a list of running sandboxes and their IDs</Option></Options>-## `sandbox spawn`+## `sandbox create`Spawns a sandbox and connects your terminal to the sandbox.This command can be used to debug your sandbox template.@@ -282,18 +282,18 @@ This command can be used to debug your sandbox template.This command works similar to the `docker run -it <image> bash` command in Docker.```bash-e2b sandbox spawn+e2b sandbox create```<Note>-Running `e2b sandbox spawn` without specifying a template with the `[template]` argument will spawn sandbox defined by the `e2b.toml` config.+Running `e2b sandbox create` without specifying a template with the `[template]` argument will create sandbox defined by the `e2b.toml` config.</Note>#### **Arguments**<Options><Option type="[template]">- Specify the template you want to spawn sandbox from. You can use the template name or ID.+ Specify the template you want to create sandbox from. You can use the template name or ID.</Option></Options>diff --git a/apps/web/src/app/(docs)/docs/legacy/guide/beta-migration/page.mdx b/apps/web/src/app/(docs)/docs/legacy/guide/beta-migration/page.mdxindex 1d9a712d2..2bf9851f9 100644--- a/apps/web/src/app/(docs)/docs/legacy/guide/beta-migration/page.mdx+++ b/apps/web/src/app/(docs)/docs/legacy/guide/beta-migration/page.mdx@@ -64,11 +64,11 @@ const sandbox = await Sandbox.create({ timeoutMs: 300_000 })from e2b import Sandbox# Before-# sandbox = Sandbox()+# sandbox = Sandbox.create()# sandbox.close()# Now-sandbox = Sandbox(timeout=300)+sandbox = Sandbox.create(timeout=300)```</CodeGroup>@@ -90,11 +90,11 @@ const sandbox = await Sandbox.create('template-name-or-id', {from e2b import Sandbox# Before-# sandbox = Sandbox(template='template-name-or-id')+# sandbox = Sandbox.create(template='template-name-or-id')# sandbox.close()# Now-sandbox = Sandbox(template='template-name-or-id', timeout=300)+sandbox = Sandbox.create(template='template-name-or-id', timeout=300)```</CodeGroup>@@ -118,11 +118,11 @@ await sandbox.setTimeout(600_000)from e2b import Sandbox# Before-# sandbox = Sandbox()+# sandbox = Sandbox.create()# sandbox.keep_alive(600)# Now-sandbox = Sandbox(timeout=300)+sandbox = Sandbox.create(timeout=300)sandbox.set_timeout(600)```</CodeGroup>@@ -153,14 +153,14 @@ const existingSandbox = await Sandbox.connect(sandbox.sandboxId)from e2b import Sandbox# Before-# sandbox = Sandbox()+# sandbox = Sandbox.create()# sandbox.keep_alive(600)# sandbox.close()# existing_sandbox = Sandbox.reconnect(sandbox.id)# Now-sandbox = Sandbox(timeout=600)+sandbox = Sandbox.create(timeout=600)existing_sandbox = Sandbox.connect(sandbox.sandbox_id)```@@ -305,7 +305,7 @@ const result = await sandbox.commands.run('echo "Hello, World!"', {from e2b import Sandbox# Before-# sandbox = Sandbox()+# sandbox = Sandbox.create()# result = sandbox.process.start_and_wait(# cmd='echo "Hello, world!"',# on_stderr=lambda msg: print(msg.line),@@ -351,7 +351,7 @@ const result = await command.wait()from e2b import Sandbox# Before-# sandbox = Sandbox()+# sandbox = Sandbox.create()# process = sandbox.process.start(# cmd='echo "Hello, world!"',# on_stderr=lambda msg: print(msg.line),@@ -394,14 +394,14 @@ await sandbox.files.watchDir('/path/in/sandbox', (event) => console.log(event))from e2b import Sandbox# Before-# sandbox = Sandbox()+# sandbox = Sandbox.create()# watcher = sandbox.filesystem.watch_dir("/path/in/sandbox")# watcher.add_event_listener(lambda event: print(event))# watcher.start()# Now-sandbox = Sandbox()+sandbox = Sandbox.create()watcher = sandbox.files.watch_dir("/path/in/sandbox")for event in watcher:@@ -632,7 +632,7 @@ If you need to use async import `AsyncSandbox`/`AsyncCodeInterpreter` instead of```python# Sync# from e2b import Sandbox-# sandbox = Sandbox()+# sandbox = Sandbox.create()# from e2b_code_interpreter import CodeInterpreter# sandbox = CodeInterpreter()@@ -655,7 +655,7 @@ The async versions of methods for watching for files' changes and running commanfrom e2b import Sandbox# Sync-# sandbox = Sandbox()+# sandbox = Sandbox.create()# watcher = sandbox.files.watch_dir("/path/in/sandbox")# for event in watcher:@@ -674,7 +674,7 @@ await sandbox.files.watch_dir("/path/in/sandbox", lambda event: print(event))from e2b import Sandbox# Sync-# sandbox = Sandbox()+# sandbox = Sandbox.create()# command = sandbox.commands.run(# cmd='echo "Hello, World!"',# background=True,diff --git a/apps/web/src/app/(docs)/docs/legacy/guide/custom-sandbox/page.mdx b/apps/web/src/app/(docs)/docs/legacy/guide/custom-sandbox/page.mdxindex 92453ed6e..4d57105ae 100644--- a/apps/web/src/app/(docs)/docs/legacy/guide/custom-sandbox/page.mdx+++ b/apps/web/src/app/(docs)/docs/legacy/guide/custom-sandbox/page.mdx@@ -3,7 +3,7 @@ import Image from 'next/image'# Creating Custom SandboxIn this guide, we'll create a custom E2B sandbox with preinstalled dependencies and files.-Once the sandbox is built, we'll show how to spawn and control it with our SDK.+Once the sandbox is built, we'll show how to create and control it with our SDK.## Prerequisites1. [Node.js](https://nodejs.org/) 18.0.0 or later@@ -107,7 +107,7 @@ Postprocessing finished.│ from e2b import Sandbox ││ ││ # Start sandbox │-│ sandbox = Sandbox("my-agent-sandbox") │+│ sandbox = Sandbox.create("my-agent-sandbox") ││ ││ # Interact with sandbox. Learn more here: ││ # https://e2b.dev/docs/sandbox/overview │@@ -184,7 +184,7 @@ await sandbox.close()from e2b import Sandbox# Spawn your custom sandbox-sandbox = Sandbox(template="my-agent-sandbox") # $HighlightLine+sandbox = Sandbox.create(template="my-agent-sandbox") # $HighlightLine# Interact with sandbox. Learn more here:# https://e2b.dev/docs/sandbox/overviewdiff --git a/apps/web/src/app/(docs)/docs/legacy/sandbox/api/metadata/page.mdx b/apps/web/src/app/(docs)/docs/legacy/sandbox/api/metadata/page.mdxindex f23a3c2cb..208b34a90 100644--- a/apps/web/src/app/(docs)/docs/legacy/sandbox/api/metadata/page.mdx+++ b/apps/web/src/app/(docs)/docs/legacy/sandbox/api/metadata/page.mdx@@ -1,6 +1,6 @@## Sandbox metadata-You can assign metadata to your sandbox. This metadata will be available if you call `Sandbox.list()`. This can be useful in situation where each of your users have dedicated sandbox and the time between the steps of the integration is long. You can use the metadata to store the user id and reconnect to it later.+You can assign metadata to your sandbox. This metadata will be available if you call `Sandbox.list()`. This can be useful in a situation where each of your users have dedicated sandbox and the time between the steps of the integration is long. You can use the metadata to store the user id and reconnect to it later.<CodeGroupAutoloadpath="basics/metadata"diff --git a/apps/web/src/app/(docs)/docs/legacy/sandbox/custom/page.mdx b/apps/web/src/app/(docs)/docs/legacy/sandbox/custom/page.mdxindex e8b663ab5..c7a23883a 100644--- a/apps/web/src/app/(docs)/docs/legacy/sandbox/custom/page.mdx+++ b/apps/web/src/app/(docs)/docs/legacy/sandbox/custom/page.mdx@@ -31,7 +31,7 @@ Once you build your custom sandbox template, you can spawn multiple isolated sanfrom e2b import Sandbox# Create new sandbox- sandbox = Sandbox(+ sandbox = Sandbox.create(template="<sandbox-template>", # You get sandbox template from the CLI after you run `$ e2b template build`)diff --git a/apps/web/src/app/(docs)/docs/legacy/sandbox/templates/overview/page.mdx b/apps/web/src/app/(docs)/docs/legacy/sandbox/templates/overview/page.mdxindex 837f1f816..f904f3235 100644--- a/apps/web/src/app/(docs)/docs/legacy/sandbox/templates/overview/page.mdx+++ b/apps/web/src/app/(docs)/docs/legacy/sandbox/templates/overview/page.mdx@@ -44,7 +44,7 @@ Follow our [guide](/docs/guide/custom-sandbox) on how to create a custom sandboxfrom e2b import Sandbox# Create new sandbox- sandbox = Sandbox(+ sandbox = Sandbox.create(# You get sandbox template from the CLI after you run `$ e2b template build`template="<sandbox-template>", # $HighlightLine)diff --git a/apps/web/src/app/(docs)/docs/quickstart/connect-llms/page.mdx b/apps/web/src/app/(docs)/docs/quickstart/connect-llms/page.mdxindex bba3e0f72..220c0084b 100644--- a/apps/web/src/app/(docs)/docs/quickstart/connect-llms/page.mdx+++ b/apps/web/src/app/(docs)/docs/quickstart/connect-llms/page.mdx@@ -46,7 +46,7 @@ code = response.choices[0].message.content# Execute code in E2B Sandboxif code:- with Sandbox() as sandbox:+ with Sandbox.create() as sandbox:execution = sandbox.run_code(code)result = execution.text@@ -110,7 +110,7 @@ if response_message.tool_calls:for tool_call in response_message.tool_calls:if tool_call.function.name == "execute_python":# Create a sandbox and execute the code- with Sandbox() as sandbox:+ with Sandbox.create() as sandbox:code = json.loads(tool_call.function.arguments)['code']execution = sandbox.run_code(code)result = execution.text@@ -164,7 +164,7 @@ response = anthropic.messages.create(code = response.content[0].text# Execute code in E2B Sandbox-with Sandbox() as sandbox:+with Sandbox.create() as sandbox:execution = sandbox.run_code(code)result = execution.logs.stdout@@ -229,7 +229,7 @@ if message.stop_reason == "tool_use":tool_input = tool_use.inputif tool_name == "execute_python":- with Sandbox() as sandbox:+ with Sandbox.create() as sandbox:code = tool_input['code']execution = sandbox.run_code(code)result = execution.text@@ -289,7 +289,7 @@ response = client.chat.complete(code = response.choices[0].message.content# Execute code in E2B Sandbox-with Sandbox() as sandbox:+with Sandbox.create() as sandbox:execution = sandbox.run_code(code)result = execution.text@@ -352,7 +352,7 @@ if response_message.tool_calls:for tool_call in response_message.tool_calls:if tool_call.function.name == "execute_python":# Create a sandbox and execute the code- with Sandbox() as sandbox:+ with Sandbox.create() as sandbox:code = json.loads(tool_call.function.arguments)['code']execution = sandbox.run_code(code)result = execution.text@@ -406,7 +406,7 @@ response = client.chat.completions.create(code = response.choices[0].message.content# Execute code in E2B Sandbox-with Sandbox() as sandbox:+with Sandbox.create() as sandbox:execution = sandbox.run_code(code)result = execution.text@@ -509,7 +509,7 @@ def execute_python(code: str) -> str:"""Execute Python code and return the results."""- with Sandbox() as sandbox:+ with Sandbox.create() as sandbox:execution = sandbox.run_code(code)return execution.text@@ -576,7 +576,7 @@ chain = prompt_template | llm | output_parsercode = chain.invoke({"input": prompt})# Execute code in E2B Sandbox-with Sandbox() as sandbox:+with Sandbox.create() as sandbox:execution = sandbox.run_code(code)result = execution.text@@ -604,7 +604,7 @@ def execute_python(code: str):"""Execute python code in a Jupyter notebook."""- with Sandbox() as sandbox:+ with Sandbox.create() as sandbox:execution = sandbox.run_code(code)return execution.text@@ -637,7 +637,7 @@ from langchain.schema import HumanMessage, AIMessage, FunctionMessagefrom e2b_code_interpreter import Sandboxdef execute_python(code: str):- with Sandbox() as sandbox:+ with Sandbox.create() as sandbox:execution = sandbox.run_code(code)return execution.text@@ -691,7 +691,7 @@ from e2b_code_interpreter import Sandbox# Define the tooldef execute_python(code: str):- with Sandbox() as sandbox:+ with Sandbox.create() as sandbox:execution = sandbox.run_code(code)return execution.text@@ -735,7 +735,7 @@ response = ollama.chat(code = response['message']['content']# Execute code in E2B Sandbox-with Sandbox() as sandbox:+with Sandbox.create() as sandbox:execution = sandbox.run_code(code)result = execution.logs.stdout@@ -797,7 +797,7 @@ completion = client.chat.completions.create(content = completion.choices[0].message.contentcode = match_code_block(content)-with Sandbox() as sandbox:+with Sandbox.create() as sandbox:execution = sandbox.run_code(code)print(execution)```diff --git a/apps/web/src/app/(docs)/docs/quickstart/install-custom-packages/page.mdx b/apps/web/src/app/(docs)/docs/quickstart/install-custom-packages/page.mdxindex 27c24dcc2..c62daa5f7 100644--- a/apps/web/src/app/(docs)/docs/quickstart/install-custom-packages/page.mdx+++ b/apps/web/src/app/(docs)/docs/quickstart/install-custom-packages/page.mdx@@ -100,7 +100,7 @@ const sbx = Sandbox.create({```pythonfrom e2b_code_interpreter import Sandbox-sbx = Sandbox(template='YOUR_TEMPLATE_ID')+sbx = Sandbox.create(template='YOUR_TEMPLATE_ID')```</CodeGroup>@@ -130,7 +130,7 @@ sbx.runCode(````pythonfrom e2b_code_interpreter import Sandbox-sbx = Sandbox()+sbx = Sandbox.create()sbx.commands.run("pip install cowsay") # This will install the cowsay packagesbx.run_code("""import cowsay@@ -155,7 +155,7 @@ sbx.runCode(````pythonfrom e2b_code_interpreter import Sandbox-sbx = Sandbox()+sbx = Sandbox.create()sbx.commands.run("npm install cowsay") # This will install the cowsay packagesbx.run_code("""import { say } from 'cowsay'@@ -181,7 +181,7 @@ await sbx.commands.run('apt-get update && apt-get install -y curl git')```pythonfrom e2b_code_interpreter import Sandbox-sbx = Sandbox()+sbx = Sandbox.create()sbx.commands.run("apt-get update && apt-get install -y curl git")```</CodeGroup>\ No newline at end of filediff --git a/apps/web/src/app/(docs)/docs/quickstart/page.mdx b/apps/web/src/app/(docs)/docs/quickstart/page.mdxindex 8c08ba1f9..4ee7b0004 100644--- a/apps/web/src/app/(docs)/docs/quickstart/page.mdx+++ b/apps/web/src/app/(docs)/docs/quickstart/page.mdx@@ -49,7 +49,7 @@ from dotenv import load_dotenvload_dotenv()from e2b_code_interpreter import Sandbox-sbx = Sandbox() # By default the sandbox is alive for 5 minutes+sbx = Sandbox.create() # By default the sandbox is alive for 5 minutesexecution = sbx.run_code("print('hello world')") # Execute Python inside the sandboxprint(execution.logs)diff --git a/apps/web/src/app/(docs)/docs/quickstart/upload-download-files/page.mdx b/apps/web/src/app/(docs)/docs/quickstart/upload-download-files/page.mdxindex a84371d7d..f6a0ed5e1 100644--- a/apps/web/src/app/(docs)/docs/quickstart/upload-download-files/page.mdx+++ b/apps/web/src/app/(docs)/docs/quickstart/upload-download-files/page.mdx@@ -21,7 +21,7 @@ await sbx.files.write('/home/user/my-file', content)```python {{ language: 'python' }}from e2b_code_interpreter import Sandbox-sbx = Sandbox()+sbx = Sandbox.create()# Read local file relative to the current working directorywith open("local/file", "rb") as file:@@ -53,7 +53,7 @@ await sbx.files.write('/home/user/my-file-b', fileB)```python {{ language: 'python' }}from e2b_code_interpreter import Sandbox-sbx = Sandbox()+sbx = Sandbox.create()# Read local file relative to the current working directorywith open("local/file/a", "rb") as file:@@ -92,7 +92,7 @@ fs.writeFileSync('local/file', content)```python {{ language: 'python' }}from e2b_code_interpreter import Sandbox-sbx = Sandbox()+sbx = Sandbox.create()# Download file from the sandbox to absolute path '/home/user/my-file'content = sbx.files.read('/home/user/my-file')# Write file to local path relative to the current working directory@@ -126,7 +126,7 @@ fs.writeFileSync('local/file/b', contentB)```python {{ language: 'python' }}from e2b_code_interpreter import Sandbox-sbx = Sandbox()+sbx = Sandbox.create()# Download file A from the sandbox by absolute path '/home/user/my-file-a'contentA = sbx.files.read('/home/user/my-file-a')# Write file A to local path relative to the current working directorydiff --git a/apps/web/src/app/(docs)/docs/sandbox-template/page.mdx b/apps/web/src/app/(docs)/docs/sandbox-template/page.mdxindex 08516470b..6f6d2ec9b 100644--- a/apps/web/src/app/(docs)/docs/sandbox-template/page.mdx+++ b/apps/web/src/app/(docs)/docs/sandbox-template/page.mdx@@ -99,7 +99,7 @@ Now you can use the template ID to create a sandbox with the SDK.# Your template ID from the previous steptemplate_id = 'id-of-your-template' # $HighlightLine# Pass the template ID to the `Sandbox.create` method- sandbox = Sandbox(template_id) # $HighlightLine+ sandbox = Sandbox.create(template_id) # $HighlightLine# The template installed cowsay, so we can use itexecution = sandbox.run_code("""diff --git a/apps/web/src/app/(docs)/docs/sandbox-template/start-cmd/page.mdx b/apps/web/src/app/(docs)/docs/sandbox-template/start-cmd/page.mdxindex 46e5429ae..06002667e 100644--- a/apps/web/src/app/(docs)/docs/sandbox-template/start-cmd/page.mdx+++ b/apps/web/src/app/(docs)/docs/sandbox-template/start-cmd/page.mdx@@ -57,7 +57,7 @@ await sandbox.close()from e2b import Sandbox# Spawn your custom sandbox-sandbox = Sandbox(+sandbox = Sandbox.create(id="my-agent-sandbox",# If you specify on_stderr and on_stdout handlers when spawning the sandbox# you will see logs from the start command.diff --git a/apps/web/src/app/(docs)/docs/sandbox/connect-bucket/page.mdx b/apps/web/src/app/(docs)/docs/sandbox/connect-bucket/page.mdxindex 5602d155f..f61cb4c74 100644--- a/apps/web/src/app/(docs)/docs/sandbox/connect-bucket/page.mdx+++ b/apps/web/src/app/(docs)/docs/sandbox/connect-bucket/page.mdx@@ -46,7 +46,7 @@ await sandbox.commands.run('sudo gcsfuse <flags> --key-file /home/user/key.json```python {{ language: 'python' }}from e2b import Sandbox-sandbox = Sandbox("<your template id>")+sandbox = Sandbox.create("<your template id>")sandbox.files.make_dir("/home/user/bucket")sandbox.files.write("key.json", "<your key file content>")@@ -98,7 +98,7 @@ await sandbox.commands.run('sudo s3fs <flags> <bucket-name> /home/user/bucket')```python {{ language: 'python' }}from e2b import Sandbox-sandbox = Sandbox("<your template id>")+sandbox = Sandbox.create("<your template id>")sandbox.files.make_dir("/home/user/bucket")# Create a file with the credentials@@ -144,7 +144,7 @@ await sandbox.commands.run('sudo s3fs -o url=https://<ACCOUNT ID>.r2.cloudflares```python {{ language: 'python' }}from e2b import Sandbox-sandbox = Sandbox("<your template id>")+sandbox = Sandbox.create("<your template id>")sandbox.files.make_dir("/home/user/bucket")# Create a file with the R2 credentialsdiff --git a/apps/web/src/app/(docs)/docs/sandbox/connect/page.mdx b/apps/web/src/app/(docs)/docs/sandbox/connect/page.mdxindex a9b180afc..39902dac1 100644--- a/apps/web/src/app/(docs)/docs/sandbox/connect/page.mdx+++ b/apps/web/src/app/(docs)/docs/sandbox/connect/page.mdx@@ -7,19 +7,19 @@ This is useful if you want to, for example, reuse the same sandbox instance for## 1. Get the sandbox IDTo connect to a running sandbox, you first need to retrieve its ID. You can do this by calling the `Sandbox.list()` method.-<Note>-If you're using the [beta version of the SDKs](/docs/sandbox/installing-beta-sdks), the `Sandbox.list()` method was updated. See [List Sandboxes](/docs/sandbox/list#changes-in-the-beta-sdks) for more information.-</Note>-<CodeGroup>```js-import { Sandbox } from "@e2b/code-interpreter"+import { Sandbox } from '@e2b/code-interpreter'+const sbx = await Sandbox.create()// Get all running sandboxes-const runningSandboxes = await Sandbox.list() // $HighlightLine+const paginator = await Sandbox.list({+ query: { state: ['running'] }, // $HighlightLine+})+const runningSandboxes = await paginator.nextItems()if (runningSandboxes.length === 0) {- throw new Error("No running sandboxes found")+ throw new Error('No running sandboxes found')}// Get the ID of the sandbox you want to connect to@@ -30,14 +30,16 @@ const sandboxId = runningSandboxes[0].sandboxIdfrom e2b_code_interpreter import Sandbox# Get all running sandboxes-running_sandboxes = Sandbox.list() # $HighlightLine+paginator = Sandbox.list() # $HighlightLine# Get the ID of the sandbox you want to connect to+running_sandboxes = paginator.next_items()if len(running_sandboxes) == 0:- raise Exception("No running sandboxes found")+ raise Exception("No running sandboxes found")# Get the ID of the sandbox you want to connect tosandbox_id = running_sandboxes[0].sandbox_id+```</CodeGroup>diff --git a/apps/web/src/app/(docs)/docs/sandbox/environment-variables/page.mdx b/apps/web/src/app/(docs)/docs/sandbox/environment-variables/page.mdxindex 02d2521ab..8a88855bb 100644--- a/apps/web/src/app/(docs)/docs/sandbox/environment-variables/page.mdx+++ b/apps/web/src/app/(docs)/docs/sandbox/environment-variables/page.mdx@@ -18,7 +18,7 @@ const sandbox = await Sandbox.create()const result = await sandbox.commands.run('echo $E2B_SANDBOX_ID')``````python-sandbox = Sandbox()+sandbox = Sandbox.create()result = sandbox.commands.run("echo $E2B_SANDBOX_ID")```</CodeGroup>@@ -55,7 +55,7 @@ const sandbox = await Sandbox.create({```pythonfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox(+sandbox = Sandbox.create(envs={ # $HighlightLine'MY_VAR': 'my_value', # $HighlightLine}, # $HighlightLine@@ -81,7 +81,7 @@ const result = await sandbox.runCode('import os; print(os.environ.get("MY_VAR"))})``````python-sandbox = Sandbox()+sandbox = Sandbox.create()result = sandbox.run_code('import os; print(os.environ.get("MY_VAR"))',envs={ # $HighlightLine@@ -109,7 +109,7 @@ sandbox.commands.run('echo $MY_VAR', {})``````python-sandbox = Sandbox()+sandbox = Sandbox.create()sandbox.commands.run('echo $MY_VAR',envs={ # $HighlightLinediff --git a/apps/web/src/app/(docs)/docs/sandbox/installing-beta-sdks/page.mdx b/apps/web/src/app/(docs)/docs/sandbox/installing-beta-sdks/page.mdxdeleted file mode 100644index 69bdca363..000000000--- a/apps/web/src/app/(docs)/docs/sandbox/installing-beta-sdks/page.mdx+++ /dev/null@@ -1,39 +0,0 @@-# Installing beta SDKs--To use features like [sandbox persistence](/docs/sandbox/persistence) you need to install the beta version of the SDKs.--### Code Interpreter SDK--<CodeGroup>-```bash {{ language: 'js' }}-npm i @e2b/code-interpreter@beta-```--```bash {{ language: 'python' }}-pip install e2b-code-interpreter==1.2.0b5-```-</CodeGroup>--### Core SDK--<CodeGroup>-```bash {{ language: 'js' }}-npm i e2b@beta-```--```bash {{ language: 'python' }}-pip install e2b==1.2.0b6-```-</CodeGroup>--### Desktop SDK--<CodeGroup>-```bash {{ language: 'js' }}-npm i @e2b/desktop@beta-```--```bash {{ language: 'python' }}-pip install e2b-desktop==1.7.1b1-```-</CodeGroup>\ No newline at end of filediff --git a/apps/web/src/app/(docs)/docs/sandbox/internet-access/page.mdx b/apps/web/src/app/(docs)/docs/sandbox/internet-access/page.mdxindex 323201f12..60d3854bc 100644--- a/apps/web/src/app/(docs)/docs/sandbox/internet-access/page.mdx+++ b/apps/web/src/app/(docs)/docs/sandbox/internet-access/page.mdx@@ -20,10 +20,10 @@ const isolatedSandbox = await Sandbox.create({ allowInternetAccess: false })from e2b_code_interpreter import Sandbox# Create sandbox with internet access enabled (default)-sandbox = Sandbox(allow_internet_access=True)+sandbox = Sandbox.create(allow_internet_access=True)# Create sandbox without internet access-isolated_sandbox = Sandbox(allow_internet_access=False)+isolated_sandbox = Sandbox.create(allow_internet_access=False)```</CodeGroup>@@ -45,7 +45,7 @@ console.log(`https://${host}`)```pythonfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()# You need to always pass a port number to get the hosthost = sandbox.get_host(3000) # $HighlightLine@@ -94,7 +94,7 @@ await process.kill()```pythonfrom e2b_code_interpreter import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()# Start a simple HTTP server inside the sandbox.process = sandbox.commands.run("python -m http.server 3000", background=True)diff --git a/apps/web/src/app/(docs)/docs/sandbox/list/page.mdx b/apps/web/src/app/(docs)/docs/sandbox/list/page.mdxindex 64ef162d5..98c89ac9d 100644--- a/apps/web/src/app/(docs)/docs/sandbox/list/page.mdx+++ b/apps/web/src/app/(docs)/docs/sandbox/list/page.mdx@@ -5,158 +5,78 @@ import Link from 'next/link'You can list sandboxes using the `Sandbox.list()` method.<Note>-Once you have information about running sandbox, you can [connect](/docs/sandbox/connect) to it using the `Sandbox.connect()` method.+ Once you have information about running sandbox, you can [connect](/docs/sandbox/connect) to it using the `Sandbox.connect()` method.</Note>-<CodeGroup>-```js-import { Sandbox } from '@e2b/code-interpreter'--// Create a sandbox.-const sandbox = await Sandbox.create({- metadata: {- name: 'My Sandbox',- },-})--// List all running sandboxes.-const runningSandboxes = await Sandbox.list() // $HighlightLine-const runningSandbox = runningSandboxes[0]--console.log('Running sandbox metadata:', runningSandbox.metadata)-console.log('Running sandbox id:', runningSandbox.sandboxId)-console.log('Running sandbox started at:', runningSandbox.startedAt)-console.log('Running sandbox template id:', runningSandbox.templateId)-```-```python-from e2b_code_interpreter import Sandbox--# Create a sandbox.-sandbox = Sandbox({- metadata: {- name: 'My Sandbox',- },-})--# List all running sandboxes.-running_sandboxes = Sandbox.list() # $HighlightLine-running_sandbox = running_sandboxes[0]--print('Running sandbox metadata:', running_sandbox.metadata)-print('Running sandbox id:', running_sandbox.sandbox_id)-print('Running sandbox started at:', running_sandbox.started_at)-print('Running sandbox template id:', running_sandbox.template_id)-```-</CodeGroup>--The code above will output something like this:-<CodeGroup isTerminalCommand>-```bash {{ language: "js" }}-Running sandbox metadata: {- name: "My Sandbox",-}-Running sandbox id: ixjj3iankaishgcge4jwn-b0b684e9-Running sandbox started at: 2024-10-15T21:13:07.311Z-Running sandbox template id: 3e4rngfa34txe0gxc1zf-```-```bash {{ language: "python" }}-Running sandbox metadata: {'name': 'My Sandbox'}-Running sandbox id: ixjj3iankaishgcge4jwn-b0b684e9-Running sandbox started at: 2024-10-15 21:13:07.311861+00:00-Running sandbox template id: 3e4rngfa34txe0gxc1zf-```-</CodeGroup>---## Filtering sandboxes--You can filter sandboxes by specifying <Link href="/docs/sandbox/metadata">Metadata</Link> key value pairs.-Specifying multiple key value pairs will return sandboxes that match all of them.+### Listing sandboxes-This can be useful when you have a large number of sandboxes and want to find only specific ones. The filtering is performed on the server.+The `Sandbox.list()` method supports pagination. In the [advanced pagination](/docs/sandbox/list#advanced-pagination) section, you can find more information about pagination techniques using the updated method.<CodeGroup>-```js-import { Sandbox } from '@e2b/code-interpreter'--// Create sandbox with metadata.-const sandbox = await Sandbox.create({- metadata: {- env: 'dev', // $HighlightLine- app: 'my-app', // $HighlightLine- userId: '123', // $HighlightLine- },-})--// List running sandboxes that has `userId` key with value `123` and `env` key with value `dev`.-const runningSandboxes = await Sandbox.list({- query: {- metadata: { userId: '123', env: 'dev' }, // $HighlightLine- },-})-```-```python-from e2b_code_interpreter import Sandbox-from e2b.sandbox.sandbox_api import SandboxQuery--# Create sandbox with metadata.-sandbox = Sandbox(- metadata={- "env": "dev", # $HighlightLine- "app": "my-app", # $HighlightLine- "user_id": "123", # $HighlightLine- },-)--# List running sandboxes that has `userId` key with value `123` and `env` key with value `dev`.-running_sandboxes = Sandbox.list(- query=SandboxQuery(- metadata={- "userId": "123", # $HighlightLine- "env": "dev", # $HighlightLine- }- ),-)-```-</CodeGroup>--## Changes in the Beta SDKs+ ```js+ import { Sandbox, SandboxInfo } from '@e2b/code-interpreter'-<Note>-If you're using the [beta version of the SDK](/docs/sandbox/installing-beta-sdks), the `Sandbox.list()` method was updated.-</Note>+ const sandbox = await Sandbox.create(+ metadata: {+ name: 'My Sandbox', // $HighlightLine}+ },+ )-### Listing sandboxes+ const sandboxes = []+ const paginator = Sandbox.list() // $HighlightLine-The `Sandbox.list()` method now supports pagination. In the [advanced pagination](/docs/sandbox/list#advanced-pagination) section, you can find more information about pagination techniques using the updated method.+ // Get the first page of sandboxes (running and paused)+ const firstPage = await paginator.nextItems() // $HighlightLine-<CodeGroup>-```js-import { Sandbox, SandboxInfo } from '@e2b/code-interpreter'+ const runningSandbox = firstPage[0]-const sandbox = await Sandbox.create()+ console.log('Running sandbox metadata:', runningSandbox.metadata)+ console.log('Running sandbox id:', runningSandbox.sandboxId)+ console.log('Running sandbox started at:', runningSandbox.startedAt)+ console.log('Running sandbox template id:', runningSandbox.templateId)-const paginator = Sandbox.list() // $HighlightLine+ // Get the next page of sandboxes+ const nextPage = await paginator.nextItems() // $HighlightLine+ ```+ ```python+ from e2b_code_interpreter import Sandbox, SandboxInfo-// Get the first page of sandboxes (running and paused)-const firstPage = await paginator.nextItems() // $HighlightLine+ sandbox = Sandbox.create(+ metadata={+ "name": "My Sandbox", # $HighlightLine+ },+ )-// Get the next page of sandboxes-const nextPage = await paginator.nextItems() // $HighlightLine-```-```python-from e2b_code_interpreter import Sandbox, SandboxInfo+ paginator = Sandbox.list() # $HighlightLine-sandbox = Sandbox()+ # Get the first page of sandboxes (running and paused)+ firstPage = paginator.next_items() # $HighlightLine-paginator = Sandbox.list() # $HighlightLine+ running_sandbox = firstPage[0]-# Get the first page of sandboxes (running and paused)-firstPage = paginator.next_items() # $HighlightLine+ print('Running sandbox metadata:', running_sandbox.metadata)+ print('Running sandbox id:', running_sandbox.sandbox_id)+ print('Running sandbox started at:', running_sandbox.started_at)+ print('Running sandbox template id:', running_sandbox.template_id)-# Get the next page of sandboxes-nextPage = paginator.next_items() # $HighlightLine-```+ # Get the next page of sandboxes+ nextPage = paginator.next_items() # $HighlightLine+ ```+</CodeGroup>+The code above will output something like this:+<CodeGroup isTerminalCommand>+ ```bash {{ language: "js" }}+ Running sandbox metadata: {name: "My Sandbox"}+ Running sandbox id: ixjj3iankaishgcge4jwn-b0b684e9+ Running sandbox started at: 2024-10-15T21:13:07.311Z+ Running sandbox template id: 3e4rngfa34txe0gxc1zf+ ```+ ```bash {{ language: "python" }}+ Running sandbox metadata: {'name': 'My Sandbox'}+ Running sandbox id: ixjj3iankaishgcge4jwn-b0b684e9+ Running sandbox started at: 2024-10-15 21:13:07.311861+00:00+ Running sandbox template id: 3e4rngfa34txe0gxc1zf+ ```</CodeGroup>@@ -165,157 +85,254 @@ nextPage = paginator.next_items() # $HighlightLineFilter sandboxes by their current state. The state parameter can contain either "**running**" for running sandboxes or "**paused**" for paused sandboxes, or both.<CodeGroup>-```js-import { Sandbox } from '@e2b/code-interpreter'--// Create a sandbox.-const sandbox = await Sandbox.create()--// List all sandboxes that are running or paused.-const paginator = Sandbox.list({- query: {- state: ['running', 'paused'], // $HighlightLine- },-})--const sandboxes = await paginator.nextItems() // $HighlightLine-```-```python-from e2b_code_interpreter import Sandbox, SandboxListQuery--# Create a sandbox with metadata.-sandbox = Sandbox()--# List running sandboxes that are running or paused.-paginator = Sandbox.list(- query=SandboxListQuery(- state=['running', 'paused'], # $HighlightLine- ),-)--# Get the first page of sandboxes (running and paused)-sandboxes = paginator.next_items() # $HighlightLine-```+ ```js+ import { Sandbox } from '@e2b/code-interpreter'++ // Create a sandbox.+ const sandbox = await Sandbox.create()++ // List all sandboxes that are running or paused.+ const paginator = Sandbox.list({+ query: {+ state: ['running', 'paused'], // $HighlightLine+ },+ })++ const sandboxes = await paginator.nextItems() // $HighlightLine+ ```+ ```python+ from e2b_code_interpreter import Sandbox, SandboxListQuery++ # Create a sandbox with metadata.+ sandbox = Sandbox.create()++ # List running sandboxes that are running or paused.+ paginator = Sandbox.list(+ query=SandboxListQuery(+ state=['running', 'paused'], # $HighlightLine+ ),+ )++ # Get the first page of sandboxes (running and paused)+ sandboxes = paginator.next_items() # $HighlightLine+ ```</CodeGroup>Filter sandboxes by the metadata key value pairs specified during Sandbox creation.<CodeGroup>-```js-import { Sandbox } from '@e2b/code-interpreter'--// Create sandbox with metadata.-const sandbox = await Sandbox.create({- metadata: {- env: 'dev', // $HighlightLine- app: 'my-app', // $HighlightLine- userId: '123', // $HighlightLine- },-})--// List all sandboxes that has `userId` key with value `123` and `env` key with value `dev`.-const paginator = Sandbox.list({- query: {- metadata: { userId: '123', env: 'dev' }, // $HighlightLine- },-})--const sandboxes = await paginator.nextItems() // $HighlightLine-```-```python-from e2b_code_interpreter import Sandbox, SandboxListQuery--# Create sandbox with metadata.-sandbox = Sandbox(- metadata={- "env": "dev", # $HighlightLine- "app": "my-app", # $HighlightLine- "user_id": "123", # $HighlightLine- },-)--# List running sandboxes that has `userId` key with value `123` and `env` key with value `dev`.-paginator = Sandbox.list(- query=SandboxListQuery(+ ```js+ import { Sandbox } from '@e2b/code-interpreter'++ // Create sandbox with metadata.+ const sandbox = await Sandbox.create({+ metadata: {+ env: 'dev', // $HighlightLine+ app: 'my-app', // $HighlightLine+ userId: '123', // $HighlightLine+ },+ })++ // List all sandboxes that has `userId` key with value `123` and `env` key with value `dev`.+ const paginator = Sandbox.list({+ query: {+ metadata: { userId: '123', env: 'dev' }, // $HighlightLine+ },+ })++ const sandboxes = await paginator.nextItems() // $HighlightLine+ ```+ ```python+ from e2b_code_interpreter import Sandbox, SandboxListQuery++ # Create sandbox with metadata.+ sandbox = Sandbox.create(metadata={- "userId": "123", # $HighlightLine- "env": "dev", # $HighlightLine- }- ),-)--# Get the first page of sandboxes (running and paused)-sandboxes = paginator.next_items() # $HighlightLine-```+ "env": "dev", # $HighlightLine+ "app": "my-app", # $HighlightLine+ "user_id": "123", # $HighlightLine+ },+ )++ # List running sandboxes that has `userId` key with value `123` and `env` key with value `dev`.+ paginator = Sandbox.list(+ query=SandboxListQuery(+ metadata={+ "userId": "123", # $HighlightLine+ "env": "dev", # $HighlightLine+ }+ ),+ )++ # Get the first page of sandboxes (running and paused)+ sandboxes = paginator.next_items()+ ```</CodeGroup>### Advanced pagination-For more granular pagination, you can set custom per-page item limit (default and maximum is **1000**) and specify an offset parameter (`nextToken` or `next_token`) to start paginating from.+For more granular pagination, you can set custom per-page item limit (default and maximum is **100**) and specify an offset parameter (`nextToken` or `next_token`) to start paginating from.<CodeGroup>-```js-import { Sandbox } from '@e2b/code-interpreter'--const paginator = Sandbox.list({- limit: 1000, // $HighlightLine- nextToken: '<base64-encoded-token>', // $HighlightLine-})--// Additional paginator properties-// Whether there is a next page-paginator.hasNext--// Next page token-paginator.nextToken--// Fetch the next page-await paginator.nextItems()-```-```python-from e2b_code_interpreter import Sandbox, SandboxListQuery--paginator = Sandbox.list(- limit=1000, # $HighlightLine- next_token='<base64-encoded-token>', # $HighlightLine-)--# Additional paginator properties-# Whether there is a next page-paginator.has_next--# Next page token-paginator.next_token--# Fetch the next page-paginator.next_items()-```+ ```js+ import { Sandbox } from '@e2b/code-interpreter'++ const paginator = Sandbox.list({+ limit: 100, // $HighlightLine+ nextToken: '<base64-encoded-token>', // $HighlightLine+ })++ // Additional paginator properties+ // Whether there is a next page+ paginator.hasNext++ // Next page token+ paginator.nextToken++ // Fetch the next page+ await paginator.nextItems() // $HighlightLine+ ```+ ```python+ from e2b_code_interpreter import Sandbox, SandboxListQuery++ # List running sandboxes that has `userId` key with value `123` and `env` key with value `dev`.+ paginator = Sandbox.list(+ limit=100, # $HighlightLine+ next_token="<base64-encoded-token>", # $HighlightLine+ )++ paginator.has_next # Whether there is a next page+ paginator.next_token # Next page token++ # Fetch the next page+ paginator.next_items() # $HighlightLine+ ```</CodeGroup>You can fetch all pages by looping through the paginator while checking if there is a next page (using `hasNext` or `has_next` property) and fetching until there are no more pages left to fetch:<CodeGroup>-```js-import { Sandbox } from '@e2b/code-interpreter'--const paginator = Sandbox.list()--// Loop through all pages-const sandboxes: SandboxInfo[] = []-while (paginator.hasNext) { // $HighlightLine- const items = await paginator.nextItems()- sandboxes.push(...items)-}-```-```python-from e2b_code_interpreter import Sandbox, SandboxListQuery--paginator = Sandbox.list()--# Loop through all pages-sandboxes: list[SandboxInfo] = []-while paginator.has_next: # $HighlightLine- items = paginator.next_items()- sandboxes.extend(items)-```+ ```js+ import { Sandbox } from '@e2b/code-interpreter'++ const paginator = Sandbox.list()++ // Loop through all pages+ const sandboxes: SandboxInfo[] = []+ while (paginator.hasNext) { // $HighlightLine+ const items = await paginator.nextItems()+ sandboxes.push(...items)+ }+ ```+ ```python+ from e2b_code_interpreter import Sandbox, SandboxListQuery++ paginator = Sandbox.list()++ # Loop through all pages+ sandboxes: list[SandboxInfo] = []+ while paginator.has_next: # $HighlightLine+ items = paginator.next_items()+ sandboxes.extend(items)+ ```+</CodeGroup>++## Old SDK (v1.x.y)++<Note>+ If you're using SDK with version lower than `2.0.0`, the `Sandbox.list()` method behaves differently.+</Note>+++<CodeGroup>+ ```js+ import { Sandbox } from '@e2b/code-interpreter'++ // Create a sandbox.+ const sandbox = await Sandbox.create({+ metadata: {+ name: 'My Sandbox',+ },+ })++ // List all running sandboxes.+ const runningSandboxes = await Sandbox.list() // $HighlightLine+ const runningSandbox = runningSandboxes[0]++ console.log('Running sandbox metadata:', runningSandbox.metadata)+ console.log('Running sandbox id:', runningSandbox.sandboxId)+ console.log('Running sandbox started at:', runningSandbox.startedAt)+ console.log('Running sandbox template id:', runningSandbox.templateId)+ ```+ ```python+ from e2b_code_interpreter import Sandbox++ # Create a sandbox.+ sandbox = Sandbox.create(+ metadata: {+ name: 'My Sandbox',+ },+ )++ # List all running sandboxes.+ running_sandboxes = Sandbox.list() # $HighlightLine+ running_sandbox = running_sandboxes[0]++ print('Running sandbox metadata:', running_sandbox.metadata)+ print('Running sandbox id:', running_sandbox.sandbox_id)+ print('Running sandbox started at:', running_sandbox.started_at)+ print('Running sandbox template id:', running_sandbox.template_id)+ ```+</CodeGroup>++## Filtering sandboxes++You can filter sandboxes by specifying <Link href="/docs/sandbox/metadata">Metadata</Link> key value pairs.+Specifying multiple key value pairs will return sandboxes that match all of them.++This can be useful when you have a large number of sandboxes and want to find only specific ones. The filtering is performed on the server.++<CodeGroup>+ ```js+ import { Sandbox } from '@e2b/code-interpreter'++ // Create sandbox with metadata.+ const sandbox = await Sandbox.create({+ metadata: {+ env: 'dev', // $HighlightLine+ app: 'my-app', // $HighlightLine+ userId: '123', // $HighlightLine+ },+ })++ // List running sandboxes that has `userId` key with value `123` and `env` key with value `dev`.+ const runningSandboxes = await Sandbox.list({+ query: {+ metadata: { userId: '123', env: 'dev' }, // $HighlightLine+ },+ })+ ```+ ```python+ from e2b_code_interpreter import Sandbox+ from e2b.sandbox.sandbox_api import SandboxQuery++ # Create sandbox with metadata.+ sandbox = Sandbox.create(+ metadata={+ "env": "dev", # $HighlightLine+ "app": "my-app", # $HighlightLine+ "user_id": "123", # $HighlightLine+ },+ )++ # List running sandboxes that has `userId` key with value `123` and `env` key with value `dev`.+ running_sandboxes = Sandbox.list(+ query=SandboxQuery(+ metadata={+ "userId": "123", # $HighlightLine+ "env": "dev", # $HighlightLine+ }+ ),+ )+ ```</CodeGroup>diff --git a/apps/web/src/app/(docs)/docs/sandbox/metadata/page.mdx b/apps/web/src/app/(docs)/docs/sandbox/metadata/page.mdxindex f1ea15983..7638b66fc 100644--- a/apps/web/src/app/(docs)/docs/sandbox/metadata/page.mdx+++ b/apps/web/src/app/(docs)/docs/sandbox/metadata/page.mdx@@ -38,7 +38,7 @@ console.log(runningSandboxes[0].metadata)from e2b_code_interpreter import Sandbox# Create sandbox with metadata.-sandbox = Sandbox(+sandbox = Sandbox.create(metadata={'userId': '123', # $HighlightLine},diff --git a/apps/web/src/app/(docs)/docs/sandbox/metrics/page.mdx b/apps/web/src/app/(docs)/docs/sandbox/metrics/page.mdxindex f1ac71785..779a96933 100644--- a/apps/web/src/app/(docs)/docs/sandbox/metrics/page.mdx+++ b/apps/web/src/app/(docs)/docs/sandbox/metrics/page.mdx@@ -51,7 +51,7 @@ console.log('Sandbox metrics:', metrics)from time import sleepfrom e2b_code_interpreter import Sandbox-sbx = Sandbox()+sbx = Sandbox.create()print('Sandbox created', sbx.sandbox_id)# Wait for a few seconds to collect some metricsdiff --git a/apps/web/src/app/(docs)/docs/sandbox/page.mdx b/apps/web/src/app/(docs)/docs/sandbox/page.mdxindex 6d0130bfd..e7188bfdd 100644--- a/apps/web/src/app/(docs)/docs/sandbox/page.mdx+++ b/apps/web/src/app/(docs)/docs/sandbox/page.mdx@@ -17,7 +17,7 @@ from e2b_code_interpreter import Sandbox# Create sandbox with and keep it running for 60 seconds.# 🚨 Note: The units are seconds.-sandbox = Sandbox(+sandbox = Sandbox.create(timeout=60, # $HighlightLine)```@@ -48,7 +48,7 @@ await sandbox.setTimeout(30_000)from e2b_code_interpreter import Sandbox# Create sandbox with and keep it running for 60 seconds.-sandbox = Sandbox(timeout=60)+sandbox = Sandbox.create(timeout=60)# Change the sandbox timeout to 30 seconds.# 🚨 The new timeout will be 30 seconds from now.@@ -86,7 +86,7 @@ console.log(info)from e2b_code_interpreter import Sandbox# Create sandbox with and keep it running for 60 seconds.-sandbox = Sandbox(timeout=60)+sandbox = Sandbox.create(timeout=60)# Retrieve sandbox information.info = sandbox.get_info()@@ -121,7 +121,7 @@ await sandbox.kill()from e2b_code_interpreter import Sandbox# Create sandbox with and keep it running for 60 seconds.-sandbox = Sandbox(timeout=60)+sandbox = Sandbox.create(timeout=60)# Shutdown the sandbox immediately.sandbox.kill()diff --git a/apps/web/src/app/(docs)/docs/sandbox/persistence/page.mdx b/apps/web/src/app/(docs)/docs/sandbox/persistence/page.mdxindex 738f26ff6..b0e547d40 100644--- a/apps/web/src/app/(docs)/docs/sandbox/persistence/page.mdx+++ b/apps/web/src/app/(docs)/docs/sandbox/persistence/page.mdx@@ -1,10 +1,7 @@-# Sandbox persistence-<Note>Sandbox persistence is currently in public beta:-1. You'll need to install the [beta version of the SDKs](/docs/sandbox/installing-beta-sdks).-2. Consider [some limitations](#limitations-while-in-beta).-3. The persistence is free for all users during the beta.+1. Consider [some limitations](#limitations-while-in-beta).+2. The persistence is free for all users during the beta.</Note>The sandbox persistence allows you to pause your sandbox and resume it later from the same state it was in when you paused it.@@ -17,11 +14,6 @@ When you pause a sandbox, both the sandbox's filesystem and memory state will be<CodeGroup>```jsimport { Sandbox } from '@e2b/code-interpreter'-// or use Core: https://github.com/e2b-dev/e2b-// import { Sandbox } from 'e2b'-//-// or use Desktop: https://github.com/e2b-dev/desktop-// import { Sandbox } from '@e2b/desktop'const sbx = await Sandbox.create()console.log('Sandbox created', sbx.sandboxId)@@ -29,24 +21,19 @@ console.log('Sandbox created', sbx.sandboxId)// Pause the sandbox// You can save the sandbox ID in your database// to resume the sandbox later-const sandboxId = await sbx.pause() // $HighlightLine+const sandboxId = await sbx.betaPause() // $HighlightLineconsole.log('Sandbox paused', sandboxId) // $HighlightLine``````pythonfrom e2b_code_interpreter import Sandbox-# or use Core: https://github.com/e2b-dev/e2b-# from e2b import Sandbox-#-# or use Desktop: https://github.com/e2b-dev/desktop-# from e2b_desktop import Sandbox-sbx = Sandbox()+sbx = Sandbox.create()print('Sandbox created', sbx.sandbox_id)# Pause the sandbox# You can save the sandbox ID in your database# to resume the sandbox later-sandbox_id = sbx.pause() # $HighlightLine+sandbox_id = sbx.beta_pause() # $HighlightLineprint('Sandbox paused', sandbox_id) # $HighlightLine```</CodeGroup>@@ -59,11 +46,6 @@ This means that all the files in the sandbox's filesystem will be restored and a<CodeGroup>```jsimport { Sandbox } from '@e2b/code-interpreter'-// or use Core: https://github.com/e2b-dev/e2b-// import { Sandbox } from 'e2b'-//-// or use Desktop: https://github.com/e2b-dev/desktop-// import { Sandbox } from '@e2b/desktop'const sbx = await Sandbox.create()console.log('Sandbox created', sbx.sandboxId)@@ -71,33 +53,28 @@ console.log('Sandbox created', sbx.sandboxId)// Pause the sandbox// You can save the sandbox ID in your database// to resume the sandbox later-const sandboxId = await sbx.pause()+const sandboxId = await sbx.betaPause()console.log('Sandbox paused', sandboxId)-// Resume the sandbox from the same state-const sameSbx = await Sandbox.resume(sandboxId) // $HighlightLine-console.log('Sandbox resumed', sameSbx.sandboxId) // $HighlightLine+// Connect to the sandbox (it will automatically resume the sandbox, if paused)+const sameSbx = await sbx.connect() // $HighlightLine+console.log('Connected to the sandbox', sameSbx.sandboxId) // $HighlightLine``````python-from e2b import Sandbox-# or use Core: https://github.com/e2b-dev/e2b-# from e2b import Sandbox-#-# or use Desktop: https://github.com/e2b-dev/desktop-# from e2b_desktop import Sandbox+from e2b_code_interpreter import Sandbox-sbx = Sandbox()+sbx = Sandbox.create()print('Sandbox created', sbx.sandbox_id)# Pause the sandbox# You can save the sandbox ID in your database# to resume the sandbox later-sandbox_id = sbx.pause()+sandbox_id = sbx.beta_pause()print('Sandbox paused', sandbox_id)-# Resume the sandbox from the same state-same_sbx = Sandbox.resume(sandbox_id) # $HighlightLine-print('Sandbox resumed', same_sbx.sandbox_id) # $HighlightLine+# Connect to the sandbox (it will automatically resume the sandbox, if paused)+same_sbx = sbx.connect() # $HighlightLine+print('Connected to the sandbox', same_sbx.sandbox_id) # $HighlightLine```</CodeGroup>@@ -108,11 +85,6 @@ More information about using the method can be found in [List Sandboxes](/docs/s<CodeGroup>```jsimport { Sandbox, SandboxInfo } from '@e2b/code-interpreter'-// or use Core: https://github.com/e2b-dev/e2b-// import { Sandbox, SandboxInfo } from 'e2b'-//-// or use Desktop: https://github.com/e2b-dev/desktop-// import { Sandbox, SandboxInfo } from '@e2b/desktop'// List all paused sandboxesconst paginator = Sandbox.list({ query: { state: ['paused'] } }) // $HighlightLine@@ -121,28 +93,21 @@ const paginator = Sandbox.list({ query: { state: ['paused'] } }) // $HighlightLiconst sandboxes = await paginator.nextItems() // $HighlightLine// Get all paused sandboxes-const sandboxes: SandboxInfo[] = []while (paginator.hasNext) {const items = await paginator.nextItems()sandboxes.push(...items)}``````python-from e2b_code_interpreter import Sandbox, SandboxListQuery-# or use Core: https://github.com/e2b-dev/e2b-# from e2b import Sandbox, SandboxListQuery-#-# or use Desktop: https://github.com/e2b-dev/desktop-# from e2b_desktop import Sandbox, SandboxInfo, SandboxListQuery-# List all paused sandboxes-paginator = Sandbox.list(SandboxListQuery(state=['paused'])) # $HighlightLine+from e2b_code_interpreter import Sandbox, SandboxQuery, SandboxState++paginator = Sandbox.list(SandboxQuery(state=[SandboxState.PAUSED])) # $HighlightLine# Get the first page of paused sandboxessandboxes = paginator.next_items() # $HighlightLine# Get all paused sandboxes-sandboxes: list[SandboxInfo] = []while paginator.has_next:items = paginator.next_items()sandboxes.extend(items)@@ -156,11 +121,6 @@ You can remove paused sandboxes by calling the `kill` method on the Sandbox inst<CodeGroup>```jsimport { Sandbox } from '@e2b/code-interpreter'-// or use Core: https://github.com/e2b-dev/e2b-// import { Sandbox } from 'e2b'-//-// or use Desktop: https://github.com/e2b-dev/desktop-// import { Sandbox } from '@e2b/desktop'const sbx = await Sandbox.create()console.log('Sandbox created', sbx.sandboxId)@@ -168,7 +128,7 @@ console.log('Sandbox created', sbx.sandboxId)// Pause the sandbox// You can save the sandbox ID in your database// to resume the sandbox later-const sandboxId = await sbx.pause()+const sandboxId = await sbx.betaPause()// Remove the sandboxawait sbx.kill() // $HighlightLine@@ -178,16 +138,11 @@ await Sandbox.kill(sandboxId) // $HighlightLine``````pythonfrom e2b import Sandbox-# or use Core: https://github.com/e2b-dev/e2b-# from e2b import Sandbox-#-# or use Desktop: https://github.com/e2b-dev/desktop-# from e2b_desktop import Sandbox-sbx = Sandbox()+sbx = Sandbox.create()# Pause the sandbox-sandbox_id = sbx.pause()+sandbox_id = sbx.beta_pause()# Remove the sandboxsbx.kill() # $HighlightLine@@ -198,31 +153,20 @@ Sandbox.kill(sandbox_id) # $HighlightLine</CodeGroup>## Sandbox's timeout-When you resume a sandbox, the sandbox's timeout is reset to the default timeout of an E2B sandbox - 5 minutes.-+When you connect to a sandbox, the sandbox's timeout is reset to the default timeout of an E2B sandbox - 5 minutes.-You can pass a custom timeout to the `Sandbox.resume()` method like this:+You can pass a custom timeout to the `Sandbox.connect()`/`Sandbox.connect()` method like this:<CodeGroup>```jsimport { Sandbox } from '@e2b/code-interpreter'-// or use Core: https://github.com/e2b-dev/e2b-// import { Sandbox } from 'e2b'-//-// or use Desktop: https://github.com/e2b-dev/desktop-// import { Sandbox } from '@e2b/desktop'-const sbx = await Sandbox.resume(sandboxId, { timeoutMs: 60 * 1000 }) // 60 seconds+const sbx = await Sandbox.connect(sandboxId, { timeoutMs: 60 * 1000 }) // 60 seconds``````pythonfrom e2b_code_interpreter import Sandbox-# or use Core: https://github.com/e2b-dev/e2b-# from e2b import Sandbox-#-# or use Desktop: https://github.com/e2b-dev/desktop-# from e2b_desktop import Sandbox-sbx = Sandbox.resume(sandbox_id, timeout=60) # 60 seconds+sbx = Sandbox.connect(sandbox_id, timeout=60) # 60 seconds```</CodeGroup>diff --git a/apps/web/src/app/(docs)/docs/sandbox/rate-limits/page.mdx b/apps/web/src/app/(docs)/docs/sandbox/rate-limits/page.mdxindex 7c067e687..5a079dfa3 100644--- a/apps/web/src/app/(docs)/docs/sandbox/rate-limits/page.mdx+++ b/apps/web/src/app/(docs)/docs/sandbox/rate-limits/page.mdx@@ -117,7 +117,7 @@ When you reach the limits of your plan, subsequent requests/function calls will- `RateLimitException` in the Python SDKFor example, if you're on the Pro tier (without any concurrency addons) you can create up to 100 sandboxes running concurrently.-If the 100 sandboxes are still running, requests for creating new sandboxes from the SDKs (`Sandbox.create()` in JS/TS or `Sandbox()` in Python) will fail and return `RateLimitError` or `RateLimitException` respectively.+If the 100 sandboxes are still running, requests for creating new sandboxes from the SDKs (`Sandbox.create()` in JS/TS or `Sandbox.create()` in Python) will fail and return `RateLimitError` or `RateLimitException` respectively.After the number of running sandboxes drops below 100 or you purchase the concurrency addon, you'll be able to create new sandboxes again.## Increasing and avoiding rate limitsdiff --git a/apps/web/src/code/js/basics/metadata.js b/apps/web/src/code/js/basics/metadata.jsindex afd3befb6..8d63495b9 100644--- a/apps/web/src/code/js/basics/metadata.js+++ b/apps/web/src/code/js/basics/metadata.js@@ -10,7 +10,8 @@ await sandbox.keepAlive(60_000)// Later, can be even from another process// List all running sandboxes-const runningSandboxes = await Sandbox.list()+const paginator = Sandbox.list({ query: {state: ['running']}})+const runningSandboxes = await paginator.nextItems()// Find the sandbox by metadataconst found = runningSandboxes.find(s => s.metadata?.userID === 'uniqueID')if (found) {diff --git a/apps/web/src/code/python/basics/fs_watch.py b/apps/web/src/code/python/basics/fs_watch.pyindex 099b87f95..9f8205d44 100644--- a/apps/web/src/code/python/basics/fs_watch.py+++ b/apps/web/src/code/python/basics/fs_watch.py@@ -2,7 +2,7 @@ import timefrom e2b import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()watcher = sandbox.files.watch_dir("/home") # $HighlightLinediff --git a/apps/web/src/code/python/basics/init.py b/apps/web/src/code/python/basics/init.pyindex 729870fff..0efcdc5d1 100644--- a/apps/web/src/code/python/basics/init.py+++ b/apps/web/src/code/python/basics/init.py@@ -1,4 +1,4 @@from e2b import Sandbox-sandbox = Sandbox()+sandbox = Sandbox.create()sandbox.close()diff --git a/apps/web/src/code/python/basics/metadata.py b/apps/web/src/code/python/basics/metadata.pyindex e6a74f31b..aedf716bc 100644--- a/apps/web/src/code/python/basics/metadata.py+++ b/apps/web/src/code/python/basics/metadata.py@@ -1,22 +1,24 @@-from e2b import Sandbox+from e2b import Sandbox, SandboxState+from e2b.sandbox.sandbox_api import SandboxQuerysandbox = Sandbox(- template='base',+ template="base",metadata={"user_id": "uniqueID"}, # $HighlightLine)# Keep the sandbox alive for 60 seconds-sandbox.keep_alive(60)+sandbox.set_timeout(60)# You can even close the script# Later, can be even from another process# List all running sandboxes-running_sandboxes = Sandbox.list()+paginator = Sandbox.list(query=SandboxQuery(state=[SandboxState.RUNNING]))+running_sandboxes = paginator.next_items()# Find the sandbox by metadatafor running_sandbox in running_sandboxes:- if running_sandbox.metadata.get("user_id", "") == 'uniqueID':- sandbox = Sandbox.reconnect(running_sandbox.sandbox_id)+ if running_sandbox.metadata.get("user_id", "") == "uniqueID":+ sandbox = Sandbox.connect(running_sandbox.sandbox_id)breakelse:# Sandbox not founddiff --git a/apps/web/src/components/Navigation/routes.tsx b/apps/web/src/components/Navigation/routes.tsxindex 3d537b5e8..8b34a9db8 100644--- a/apps/web/src/components/Navigation/routes.tsx+++ b/apps/web/src/components/Navigation/routes.tsx@@ -322,10 +322,6 @@ export const docRoutes: NavGroup[] = [title: 'Rate limits',href: '/docs/sandbox/rate-limits',},- {- title: 'Installing beta SDKs',- href: '/docs/sandbox/installing-beta-sdks',- },// {// title: '* Request timeouts',// href: '/docs/sandbox/request-timeouts',diff --git a/packages/cli/src/commands/sandbox/kill.ts b/packages/cli/src/commands/sandbox/kill.tsindex 4f1104132..5b475782c 100644--- a/packages/cli/src/commands/sandbox/kill.ts+++ b/packages/cli/src/commands/sandbox/kill.ts@@ -3,7 +3,7 @@ import * as commander from 'commander'import { ensureAPIKey } from 'src/api'import { asBold } from 'src/utils/format'import * as e2b from 'e2b'-import { listSandboxes } from './list'+import { Sandbox } from 'e2b'async function killSandbox(sandboxID: string, apiKey: string) {const killed = await e2b.Sandbox.kill(sandboxID, { apiKey })@@ -45,17 +45,30 @@ export const killCommand = new commander.Command('kill')}if (all) {- const sandboxes = await listSandboxes({- state: ['running'],+ let total = 0+ const iterator = Sandbox.list({+ apiKey,+ query: {+ state: ['running'],+ },})- if (sandboxes.length === 0) {++ while (iterator.hasNext) {+ const sandboxes = await iterator.nextItems()+ total += sandboxes.length++ await Promise.all(+ sandboxes.map((sandbox) => killSandbox(sandbox.sandboxId, apiKey))+ )+ }++ if (total === 0) {console.log('No running sandboxes')- process.exit(0)+ } else {+ console.log(`Killed ${total} running sandboxes`)}- await Promise.all(- sandboxes.map((sandbox) => killSandbox(sandbox.sandboxID, apiKey))- )+ process.exit(0)} else {await killSandbox(sandboxID, apiKey)}diff --git a/packages/cli/src/commands/sandbox/list.ts b/packages/cli/src/commands/sandbox/list.tsindex e1d929080..8371a3ead 100644--- a/packages/cli/src/commands/sandbox/list.ts+++ b/packages/cli/src/commands/sandbox/list.ts@@ -1,16 +1,15 @@import * as tablePrinter from 'console-table-printer'import * as commander from 'commander'-import { components } from 'e2b'+import { components, Sandbox, SandboxInfo } from 'e2b'-import { client, connectionConfig, ensureAPIKey } from 'src/api'-import { handleE2BRequestError } from '../../utils/errors'+import { ensureAPIKey } from 'src/api'export const listCommand = new commander.Command('list')- .description('list all running sandboxes')+ .description('list all sandboxes, by default it list only running ones').alias('ls').option('-s, --state <state>',- 'filter by state, eg. running, stopped',+ 'filter by state, eg. running, paused. Defaults to running',(value) => value.split(',')).option(@@ -25,10 +24,11 @@ export const listCommand = new commander.Command('list')).action(async (options) => {try {+ const state = options.state || ['running']const sandboxes = await listSandboxes({limit: options.limit,- state: options.state,- metadata: options.metadata,+ state,+ metadataRaw: options.metadata,})if (!sandboxes?.length) {@@ -56,7 +56,7 @@ export const listCommand = new commander.Command('list')rows: sandboxes.map((sandbox) => ({...sandbox,- sandboxID: sandbox.sandboxID,+ sandboxID: sandbox.sandboxId,startedAt: new Date(sandbox.startedAt).toLocaleString(),endAt: new Date(sandbox.endAt).toLocaleString(),state:@@ -106,46 +106,48 @@ export const listCommand = new commander.Command('list')type ListSandboxesOptions = {limit?: numberstate?: components['schemas']['SandboxState'][]- metadata?: string+ metadataRaw?: string}export async function listSandboxes({limit,state,- metadata,-}: ListSandboxesOptions = {}): Promise<- components['schemas']['ListedSandbox'][]-> {- ensureAPIKey()+ metadataRaw,+}: ListSandboxesOptions = {}): Promise<SandboxInfo[]> {+ const apiKey = ensureAPIKey()- const signal = connectionConfig.getSignal()+ let metadata: Record<string, string> | undefined = undefined+ if (metadataRaw && metadataRaw.length > 0) {+ const parsedMetadata: Record<string, string> = {}+ metadataRaw.split(',').map((pair: string) => {+ const [key, value] = pair.split('=')+ if (key && value) {+ parsedMetadata[key.trim()] = value.trim()+ }+ })- let hasNext = true- let nextToken: string | undefined- let remainingLimit: number | undefined = limit+ metadata = parsedMetadata+ }- const sandboxes: components['schemas']['ListedSandbox'][] = []+ let pageLimit = limit+ if (!limit || limit > 100) {+ pageLimit = 100+ }- while (hasNext && (!limit || (remainingLimit && remainingLimit > 0))) {- const res = await client.api.GET('/v2/sandboxes', {- params: {- query: {- state,- metadata,- nextToken,- limit: remainingLimit,- },- },- signal,- })+ let remainingLimit = limit+ const sandboxes: SandboxInfo[] = []+ const iterator = Sandbox.list({+ apiKey: apiKey,+ limit: pageLimit,+ query: { state, metadata },+ })- handleE2BRequestError(res, 'Error getting running sandboxes')+ while (iterator.hasNext && (!remainingLimit || remainingLimit > 0)) {+ const batch = await iterator.nextItems()+ sandboxes.push(...batch)- nextToken = res.response.headers.get('x-next-token') || undefined- hasNext = !!nextToken- sandboxes.push(...res.data)if (limit && remainingLimit) {- remainingLimit -= res.data.length+ remainingLimit -= batch.length}}diff --git a/packages/cli/src/commands/sandbox/logs.ts b/packages/cli/src/commands/sandbox/logs.tsindex 8d83c851d..85b74ef15 100644--- a/packages/cli/src/commands/sandbox/logs.ts+++ b/packages/cli/src/commands/sandbox/logs.ts@@ -5,10 +5,9 @@ import * as chalk from 'chalk'import { client, connectionConfig } from 'src/api'import { asBold, asTimestamp, withUnderline } from 'src/utils/format'-import { listSandboxes } from './list'import { wait } from 'src/utils/wait'import { handleE2BRequestError } from '../../utils/errors'-import { waitForSandboxEnd, formatEnum, Format, getShortID } from './utils'+import { waitForSandboxEnd, formatEnum, Format, isRunning } from './utils'enum LogLevel {DEBUG = 'DEBUG',@@ -104,9 +103,7 @@ export const logsCommand = new commander.Command('logs')console.log(`\nLogs for sandbox ${asBold(sandboxID)}:`)}- const isRunningPromise = listSandboxes({ state: ['running'] })- .then((r) => r.find((s) => s.sandboxID === getShortID(sandboxID)))- .then((s) => !!s)+ const isRunningPromise = isRunning(sandboxID)do {const logs = await listSandboxLogs({ sandboxID, start })diff --git a/packages/cli/src/commands/sandbox/metrics.ts b/packages/cli/src/commands/sandbox/metrics.tsindex 827451d94..1bdc659da 100644--- a/packages/cli/src/commands/sandbox/metrics.ts+++ b/packages/cli/src/commands/sandbox/metrics.ts@@ -3,8 +3,7 @@ import * as commander from 'commander'import { asBold, asTimestamp, withUnderline } from 'src/utils/format'import { wait } from 'src/utils/wait'-import { listSandboxes } from './list'-import { formatEnum, getShortID, Format } from './utils'+import { formatEnum, Format, isRunning } from './utils'import { Sandbox } from 'e2b'import { ensureAPIKey } from '../../api'@@ -44,9 +43,7 @@ export const metricsCommand = new commander.Command('metrics')}const apiKey = ensureAPIKey()- const isRunningPromise = listSandboxes()- .then((r) => r.find((s) => s.sandboxID === getShortID(sandboxID)))- .then((s) => !!s)+ const isRunningPromise = isRunning(sandboxID)do {const metrics = await Sandbox.getMetrics(sandboxID, { start, apiKey })diff --git a/packages/cli/src/commands/sandbox/utils.ts b/packages/cli/src/commands/sandbox/utils.tsindex 1f2fc6ab1..8a26f20a8 100644--- a/packages/cli/src/commands/sandbox/utils.ts+++ b/packages/cli/src/commands/sandbox/utils.ts@@ -1,7 +1,6 @@-import { listSandboxes } from './list'import { wait } from '../../utils/wait'-import {asBold} from '../../utils/format'-+import { asBold } from '../../utils/format'+import { Sandbox } from 'e2b'export function formatEnum(e: { [key: string]: string }) {return Object.values(e)@@ -14,11 +13,10 @@ export enum Format {PRETTY = 'pretty',}-const maxRuntime = 24 * 60 * 60 * 1000 // 24 hours in millisecondsexport function waitForSandboxEnd(sandboxID: string) {- let isRunning = true+ let running = trueasync function monitor() {const startTime = new Date().getTime()@@ -33,14 +31,11 @@ export function waitForSandboxEnd(sandboxID: string) {break}- const response = await listSandboxes()- const sandbox = response.find(- (s) => s.sandboxID === getShortID(sandboxID)- )- if (!sandbox) {- isRunning = false+ running = await isRunning(sandboxID)+ if (!running) {break}+await wait(5000)}}@@ -53,3 +48,12 @@ export function waitForSandboxEnd(sandboxID: string) {export function getShortID(sandboxID: string) {return sandboxID.split('-')[0]}++export async function isRunning(sandboxID: string) {+ try {+ const info = await Sandbox.getInfo(getShortID(sandboxID))+ return info.state === 'running'+ } catch {+ return false+ }+}diff --git a/packages/js-sdk/example.mts b/packages/js-sdk/example.mtsnew file mode 100644index 000000000..4faac361d--- /dev/null+++ b/packages/js-sdk/example.mts@@ -0,0 +1,11 @@+import { Sandbox } from './dist'+import { configDotenv } from 'dotenv'++configDotenv()++const sandbox = await Sandbox.create()++console.log('Sandbox created:', sandbox.sandboxId)++await sandbox.kill()+console.log('Sandbox killed')diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.tsindex bc3fcc121..2d585b596 100644--- a/packages/js-sdk/src/api/index.ts+++ b/packages/js-sdk/src/api/index.ts@@ -14,7 +14,13 @@ export function handleApiError(}if (response.response.status === 429) {- return new RateLimitError('Rate limit exceeded, please try again later.')+ const message = 'Rate limit exceeded, please try again later'+ const content = response.error?.message ?? response.error++ if (content) {+ return new RateLimitError(`${message} - ${content}`)+ }+ return new RateLimitError(message)}const message = response.error?.message ?? response.errordiff --git a/packages/js-sdk/src/api/schema.gen.ts b/packages/js-sdk/src/api/schema.gen.tsindex 16c349521..966492759 100644--- a/packages/js-sdk/src/api/schema.gen.ts+++ b/packages/js-sdk/src/api/schema.gen.ts@@ -195,7 +195,7 @@ export interface paths {parameters: {query?: {end?: number;- /** @description Starting timestamp of the metrics that should be returned in milliseconds */+ /** @description Unix timestamp for the start of the interval, in seconds, for which the metrics */start?: number;};header?: never;@@ -489,6 +489,52 @@ export interface paths {patch?: never;trace?: never;};+ "/teams/{teamID}/metrics": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ /** @description Get metrics for the team */+ get: {+ parameters: {+ query?: {+ end?: number;+ /** @description Unix timestamp for the start of the interval, in seconds, for which the metrics */+ start?: number;+ };+ header?: never;+ path: {+ teamID: components["parameters"]["teamID"];+ };+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Successfully returned the team metrics */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["TeamMetric"][];+ };+ };+ 400: components["responses"]["400"];+ 401: components["responses"]["401"];+ 403: components["responses"]["403"];+ 500: components["responses"]["500"];+ };+ };+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/templates": {parameters: {query?: never;@@ -925,6 +971,12 @@ export interface components {*/timestamp: string;};+ BuildStatusReason: {+ /** @description Message with the status reason, currently reporting only for error status */+ message: string;+ /** @description Step that failed */+ step?: string;+ };/*** Format: int32* @description CPU cores for the sandbox@@ -970,6 +1022,24 @@ export interface components {/** @description Name of the API key */name: string;};+ DiskMetrics: {+ /** @description Device name */+ device: string;+ /** @description Filesystem type (e.g., ext4, xfs) */+ filesystemType: string;+ /** @description Mount point of the disk */+ mountPoint: string;+ /**+ * Format: uint64+ * @description Total space in bytes+ */+ totalBytes: number;+ /**+ * Format: uint64+ * @description Used space in bytes+ */+ usedBytes: number;+ };/*** Format: int32* @description Disk size for the sandbox in MiB@@ -1068,18 +1138,8 @@ export interface components {name: string;};Node: {- /**- * Format: int32- * @description Number of allocated CPU cores- */- allocatedCPU: number;- /**- * Format: int32- * @description Amount of allocated memory in MiB- */- allocatedMemoryMiB: number;/** @description Identifier of the cluster */- clusterID?: string | null;+ clusterID: string;/** @description Commit of the orchestrator */commit: string;/**@@ -1092,10 +1152,11 @@ export interface components {* @description Number of sandbox create successes*/createSuccesses: number;+ metrics: components["schemas"]["NodeMetrics"];/** @description Identifier of the node */nodeID: string;/**- * Format: int32+ * Format: uint32* @description Number of sandboxes running on the node*/sandboxCount: number;@@ -1112,7 +1173,7 @@ export interface components {/** @description List of cached builds id on the node */cachedBuilds: string[];/** @description Identifier of the cluster */- clusterID?: string | null;+ clusterID: string;/** @description Commit of the orchestrator */commit: string;/**@@ -1125,6 +1186,7 @@ export interface components {* @description Number of sandbox create successes*/createSuccesses: number;+ metrics: components["schemas"]["NodeMetrics"];/** @description Identifier of the node */nodeID: string;/** @description List of sandboxes running on the node */@@ -1133,6 +1195,41 @@ export interface components {/** @description Version of the orchestrator */version: string;};+ /** @description Node metrics */+ NodeMetrics: {+ /**+ * Format: uint32+ * @description Number of allocated CPU cores+ */+ allocatedCPU: number;+ /**+ * Format: uint64+ * @description Amount of allocated memory in bytes+ */+ allocatedMemoryBytes: number;+ /**+ * Format: uint32+ * @description Total number of CPU cores on the node+ */+ cpuCount: number;+ /**+ * Format: uint32+ * @description Node CPU usage percentage+ */+ cpuPercent: number;+ /** @description Detailed metrics for each disk/mount point */+ disks: components["schemas"]["DiskMetrics"][];+ /**+ * Format: uint64+ * @description Total node memory in bytes+ */+ memoryTotalBytes: number;+ /**+ * Format: uint64+ * @description Node memory used in bytes+ */+ memoryUsedBytes: number;+ };/*** @description Status of the node* @enum {string}@@ -1143,6 +1240,7 @@ export interface components {};ResumedSandbox: {/**+ * @deprecated* @description Automatically pauses the sandbox after the timeout* @default false*/@@ -1316,6 +1414,24 @@ export interface components {/** @description Name of the API key */name: string;};+ /** @description Team metric with timestamp */+ TeamMetric: {+ /**+ * Format: int32+ * @description The number of concurrent sandboxes for the team+ */+ concurrentSandboxes: number;+ /**+ * Format: float+ * @description Number of sandboxes started per second+ */+ sandboxStartRate: number;+ /**+ * Format: date-time+ * @description Timestamp of the metric entry+ */+ timestamp: string;+ };TeamUser: {/** @description Email of the user */email: string;@@ -1378,8 +1494,7 @@ export interface components {* @default []*/logs: string[];- /** @description Message with the status reason, currently reporting only for error status */- reason?: string;+ reason?: components["schemas"]["BuildStatusReason"];/*** @description Status of the template* @enum {string}@@ -1481,6 +1596,15 @@ export interface components {"application/json": components["schemas"]["Error"];};};+ /** @description Forbidden */+ 403: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["Error"];+ };+ };/** @description Not found */404: {headers: {@@ -1515,6 +1639,7 @@ export interface components {buildID: string;nodeID: string;sandboxID: string;+ teamID: string;templateID: string;};requestBodies: never;diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.tsindex c6bf85109..abf51aeb7 100644--- a/packages/js-sdk/src/sandbox/sandboxApi.ts+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts@@ -51,7 +51,7 @@ export interface SandboxOpts extends ConnectionOpts {/*** Secure all traffic coming to the sandbox controller with auth token*- * @default false+ * @default true*/secure?: boolean@@ -98,7 +98,7 @@ export interface SandboxListOpts extends SandboxApiOpts {/*** Number of sandboxes to return per page.*- * @default 1000+ * @default 100*/limit?: number@@ -455,7 +455,7 @@ export class SandboxApi {metadata: opts?.metadata,envVars: opts?.envs,timeout: timeoutToSeconds(timeoutMs),- secure: opts?.secure,+ secure: opts?.secure ?? true,allow_internet_access: opts?.allowInternetAccess ?? true,},signal: config.getSignal(opts?.requestTimeoutMs),diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.pyindex c211fcb44..e011179f1 100644--- a/packages/python-sdk/e2b/api/__init__.py+++ b/packages/python-sdk/e2b/api/__init__.py@@ -33,9 +33,11 @@ def handle_api_exception(e: Response):body = {}if e.status_code == 429:- return RateLimitException(- f"{e.status_code}: Rate limit exceeded, please try again later."- )+ message = f"{e.status_code}: Rate limit exceeded, please try again later"+ if body.get("message"):+ message += f" - {body['message']}"++ return RateLimitException(message)if "message" in body:return SandboxException(f"{e.status_code}: {body['message']}")diff --git a/packages/python-sdk/e2b/api/client/api/sandboxes/get_sandboxes_sandbox_id_metrics.py b/packages/python-sdk/e2b/api/client/api/sandboxes/get_sandboxes_sandbox_id_metrics.pyindex c3f4c0037..48302c562 100644--- a/packages/python-sdk/e2b/api/client/api/sandboxes/get_sandboxes_sandbox_id_metrics.py+++ b/packages/python-sdk/e2b/api/client/api/sandboxes/get_sandboxes_sandbox_id_metrics.py@@ -90,8 +90,8 @@ def sync_detailed(Args:sandbox_id (str):start (Union[Unset, int]):- end (Union[Unset, int]): Ending timestamp of the metrics that should be returned in- milliseconds+ end (Union[Unset, int]): Unix timestamp for the end of the interval, in seconds, for which+ the metricsRaises:errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.@@ -126,8 +126,8 @@ def sync(Args:sandbox_id (str):start (Union[Unset, int]):- end (Union[Unset, int]): Ending timestamp of the metrics that should be returned in- milliseconds+ end (Union[Unset, int]): Unix timestamp for the end of the interval, in seconds, for which+ the metricsRaises:errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.@@ -157,8 +157,8 @@ async def asyncio_detailed(Args:sandbox_id (str):start (Union[Unset, int]):- end (Union[Unset, int]): Ending timestamp of the metrics that should be returned in- milliseconds+ end (Union[Unset, int]): Unix timestamp for the end of the interval, in seconds, for which+ the metricsRaises:errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.@@ -191,8 +191,8 @@ async def asyncio(Args:sandbox_id (str):start (Union[Unset, int]):- end (Union[Unset, int]): Ending timestamp of the metrics that should be returned in- milliseconds+ end (Union[Unset, int]): Unix timestamp for the end of the interval, in seconds, for which+ the metricsRaises:errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.diff --git a/packages/python-sdk/e2b/api/client/api/sandboxes/get_v2_sandboxes.py b/packages/python-sdk/e2b/api/client/api/sandboxes/get_v2_sandboxes.pyindex 704ace730..4955f815c 100644--- a/packages/python-sdk/e2b/api/client/api/sandboxes/get_v2_sandboxes.py+++ b/packages/python-sdk/e2b/api/client/api/sandboxes/get_v2_sandboxes.py@@ -16,7 +16,7 @@ def _get_kwargs(metadata: Union[Unset, str] = UNSET,state: Union[Unset, list[SandboxState]] = UNSET,next_token: Union[Unset, str] = UNSET,- limit: Union[Unset, int] = 1000,+ limit: Union[Unset, int] = 100,) -> dict[str, Any]:params: dict[str, Any] = {}@@ -94,7 +94,7 @@ def sync_detailed(metadata: Union[Unset, str] = UNSET,state: Union[Unset, list[SandboxState]] = UNSET,next_token: Union[Unset, str] = UNSET,- limit: Union[Unset, int] = 1000,+ limit: Union[Unset, int] = 100,) -> Response[Union[Error, list["ListedSandbox"]]]:"""List all sandboxes@@ -102,7 +102,7 @@ def sync_detailed(metadata (Union[Unset, str]):state (Union[Unset, list[SandboxState]]):next_token (Union[Unset, str]):- limit (Union[Unset, int]): Default: 1000.+ limit (Union[Unset, int]): Default: 100.Raises:errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.@@ -132,7 +132,7 @@ def sync(metadata: Union[Unset, str] = UNSET,state: Union[Unset, list[SandboxState]] = UNSET,next_token: Union[Unset, str] = UNSET,- limit: Union[Unset, int] = 1000,+ limit: Union[Unset, int] = 100,) -> Optional[Union[Error, list["ListedSandbox"]]]:"""List all sandboxes@@ -140,7 +140,7 @@ def sync(metadata (Union[Unset, str]):state (Union[Unset, list[SandboxState]]):next_token (Union[Unset, str]):- limit (Union[Unset, int]): Default: 1000.+ limit (Union[Unset, int]): Default: 100.Raises:errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.@@ -165,7 +165,7 @@ async def asyncio_detailed(metadata: Union[Unset, str] = UNSET,state: Union[Unset, list[SandboxState]] = UNSET,next_token: Union[Unset, str] = UNSET,- limit: Union[Unset, int] = 1000,+ limit: Union[Unset, int] = 100,) -> Response[Union[Error, list["ListedSandbox"]]]:"""List all sandboxes@@ -173,7 +173,7 @@ async def asyncio_detailed(metadata (Union[Unset, str]):state (Union[Unset, list[SandboxState]]):next_token (Union[Unset, str]):- limit (Union[Unset, int]): Default: 1000.+ limit (Union[Unset, int]): Default: 100.Raises:errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.@@ -201,7 +201,7 @@ async def asyncio(metadata: Union[Unset, str] = UNSET,state: Union[Unset, list[SandboxState]] = UNSET,next_token: Union[Unset, str] = UNSET,- limit: Union[Unset, int] = 1000,+ limit: Union[Unset, int] = 100,) -> Optional[Union[Error, list["ListedSandbox"]]]:"""List all sandboxes@@ -209,7 +209,7 @@ async def asyncio(metadata (Union[Unset, str]):state (Union[Unset, list[SandboxState]]):next_token (Union[Unset, str]):- limit (Union[Unset, int]): Default: 1000.+ limit (Union[Unset, int]): Default: 100.Raises:errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.diff --git a/packages/python-sdk/e2b/api/client/models/__init__.py b/packages/python-sdk/e2b/api/client/models/__init__.pyindex 9c05651f3..f0183ee15 100644--- a/packages/python-sdk/e2b/api/client/models/__init__.py+++ b/packages/python-sdk/e2b/api/client/models/__init__.py@@ -1,8 +1,10 @@"""Contains all the data models used in inputs/outputs"""from .build_log_entry import BuildLogEntry+from .build_status_reason import BuildStatusReasonfrom .created_access_token import CreatedAccessTokenfrom .created_team_api_key import CreatedTeamAPIKey+from .disk_metrics import DiskMetricsfrom .error import Errorfrom .identifier_masking_details import IdentifierMaskingDetailsfrom .listed_sandbox import ListedSandbox@@ -12,6 +14,7 @@ from .new_sandbox import NewSandboxfrom .new_team_api_key import NewTeamAPIKeyfrom .node import Nodefrom .node_detail import NodeDetail+from .node_metrics import NodeMetricsfrom .node_status import NodeStatusfrom .node_status_change import NodeStatusChangefrom .post_sandboxes_sandbox_id_refreshes_body import (@@ -30,6 +33,7 @@ from .sandbox_state import SandboxStatefrom .sandboxes_with_metrics import SandboxesWithMetricsfrom .team import Teamfrom .team_api_key import TeamAPIKey+from .team_metric import TeamMetricfrom .team_user import TeamUserfrom .template import Templatefrom .template_build import TemplateBuild@@ -44,8 +48,10 @@ from .update_team_api_key import UpdateTeamAPIKey__all__ = ("BuildLogEntry",+ "BuildStatusReason","CreatedAccessToken","CreatedTeamAPIKey",+ "DiskMetrics","Error","IdentifierMaskingDetails","ListedSandbox",@@ -55,6 +61,7 @@ __all__ = ("NewTeamAPIKey","Node","NodeDetail",+ "NodeMetrics","NodeStatus","NodeStatusChange","PostSandboxesSandboxIDRefreshesBody",@@ -71,6 +78,7 @@ __all__ = ("SandboxState","Team","TeamAPIKey",+ "TeamMetric","TeamUser","Template","TemplateBuild",diff --git a/packages/python-sdk/e2b/api/client/models/build_status_reason.py b/packages/python-sdk/e2b/api/client/models/build_status_reason.pynew file mode 100644index 000000000..387d95976--- /dev/null+++ b/packages/python-sdk/e2b/api/client/models/build_status_reason.py@@ -0,0 +1,70 @@+from collections.abc import Mapping+from typing import Any, TypeVar, Union++from attrs import define as _attrs_define+from attrs import field as _attrs_field++from ..types import UNSET, Unset++T = TypeVar("T", bound="BuildStatusReason")+++@_attrs_define+class BuildStatusReason:+ """+ Attributes:+ message (str): Message with the status reason, currently reporting only for error status+ step (Union[Unset, str]): Step that failed+ """++ message: str+ step: Union[Unset, str] = UNSET+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ message = self.message++ step = self.step++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "message": message,+ }+ )+ if step is not UNSET:+ field_dict["step"] = step++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ message = d.pop("message")++ step = d.pop("step", UNSET)++ build_status_reason = cls(+ message=message,+ step=step,+ )++ build_status_reason.additional_properties = d+ return build_status_reason++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/packages/python-sdk/e2b/api/client/models/disk_metrics.py b/packages/python-sdk/e2b/api/client/models/disk_metrics.pynew file mode 100644index 000000000..6d2b75c8f--- /dev/null+++ b/packages/python-sdk/e2b/api/client/models/disk_metrics.py@@ -0,0 +1,91 @@+from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++T = TypeVar("T", bound="DiskMetrics")+++@_attrs_define+class DiskMetrics:+ """+ Attributes:+ device (str): Device name+ filesystem_type (str): Filesystem type (e.g., ext4, xfs)+ mount_point (str): Mount point of the disk+ total_bytes (int): Total space in bytes+ used_bytes (int): Used space in bytes+ """++ device: str+ filesystem_type: str+ mount_point: str+ total_bytes: int+ used_bytes: int+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ device = self.device++ filesystem_type = self.filesystem_type++ mount_point = self.mount_point++ total_bytes = self.total_bytes++ used_bytes = self.used_bytes++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "device": device,+ "filesystemType": filesystem_type,+ "mountPoint": mount_point,+ "totalBytes": total_bytes,+ "usedBytes": used_bytes,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ device = d.pop("device")++ filesystem_type = d.pop("filesystemType")++ mount_point = d.pop("mountPoint")++ total_bytes = d.pop("totalBytes")++ used_bytes = d.pop("usedBytes")++ disk_metrics = cls(+ device=device,+ filesystem_type=filesystem_type,+ mount_point=mount_point,+ total_bytes=total_bytes,+ used_bytes=used_bytes,+ )++ disk_metrics.additional_properties = d+ return disk_metrics++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/packages/python-sdk/e2b/api/client/models/node.py b/packages/python-sdk/e2b/api/client/models/node.pyindex 592348ec4..8974fb283 100644--- a/packages/python-sdk/e2b/api/client/models/node.py+++ b/packages/python-sdk/e2b/api/client/models/node.py@@ -1,11 +1,14 @@from collections.abc import Mapping-from typing import Any, TypeVar, Union, cast+from typing import TYPE_CHECKING, Any, TypeVarfrom attrs import define as _attrs_definefrom attrs import field as _attrs_fieldfrom ..models.node_status import NodeStatus-from ..types import UNSET, Unset++if TYPE_CHECKING:+ from ..models.node_metrics import NodeMetrics+T = TypeVar("T", bound="Node")@@ -14,36 +17,32 @@ T = TypeVar("T", bound="Node")class Node:"""Attributes:- allocated_cpu (int): Number of allocated CPU cores- allocated_memory_mi_b (int): Amount of allocated memory in MiB+ cluster_id (str): Identifier of the clustercommit (str): Commit of the orchestratorcreate_fails (int): Number of sandbox create failscreate_successes (int): Number of sandbox create successes+ metrics (NodeMetrics): Node metricsnode_id (str): Identifier of the nodesandbox_count (int): Number of sandboxes running on the nodesandbox_starting_count (int): Number of starting Sandboxesstatus (NodeStatus): Status of the nodeversion (str): Version of the orchestrator- cluster_id (Union[None, Unset, str]): Identifier of the cluster"""- allocated_cpu: int- allocated_memory_mi_b: int+ cluster_id: strcommit: strcreate_fails: intcreate_successes: int+ metrics: "NodeMetrics"node_id: strsandbox_count: intsandbox_starting_count: intstatus: NodeStatusversion: str- cluster_id: Union[None, Unset, str] = UNSETadditional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)def to_dict(self) -> dict[str, Any]:- allocated_cpu = self.allocated_cpu-- allocated_memory_mi_b = self.allocated_memory_mi_b+ cluster_id = self.cluster_idcommit = self.commit@@ -51,6 +50,8 @@ class Node:create_successes = self.create_successes+ metrics = self.metrics.to_dict()+node_id = self.node_idsandbox_count = self.sandbox_count@@ -61,21 +62,15 @@ class Node:version = self.version- cluster_id: Union[None, Unset, str]- if isinstance(self.cluster_id, Unset):- cluster_id = UNSET- else:- cluster_id = self.cluster_id-field_dict: dict[str, Any] = {}field_dict.update(self.additional_properties)field_dict.update({- "allocatedCPU": allocated_cpu,- "allocatedMemoryMiB": allocated_memory_mi_b,+ "clusterID": cluster_id,"commit": commit,"createFails": create_fails,"createSuccesses": create_successes,+ "metrics": metrics,"nodeID": node_id,"sandboxCount": sandbox_count,"sandboxStartingCount": sandbox_starting_count,@@ -83,17 +78,15 @@ class Node:"version": version,})- if cluster_id is not UNSET:- field_dict["clusterID"] = cluster_idreturn field_dict@classmethoddef from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:- d = dict(src_dict)- allocated_cpu = d.pop("allocatedCPU")+ from ..models.node_metrics import NodeMetrics- allocated_memory_mi_b = d.pop("allocatedMemoryMiB")+ d = dict(src_dict)+ cluster_id = d.pop("clusterID")commit = d.pop("commit")@@ -101,6 +94,8 @@ class Node:create_successes = d.pop("createSuccesses")+ metrics = NodeMetrics.from_dict(d.pop("metrics"))+node_id = d.pop("nodeID")sandbox_count = d.pop("sandboxCount")@@ -111,27 +106,17 @@ class Node:version = d.pop("version")- def _parse_cluster_id(data: object) -> Union[None, Unset, str]:- if data is None:- return data- if isinstance(data, Unset):- return data- return cast(Union[None, Unset, str], data)-- cluster_id = _parse_cluster_id(d.pop("clusterID", UNSET))-node = cls(- allocated_cpu=allocated_cpu,- allocated_memory_mi_b=allocated_memory_mi_b,+ cluster_id=cluster_id,commit=commit,create_fails=create_fails,create_successes=create_successes,+ metrics=metrics,node_id=node_id,sandbox_count=sandbox_count,sandbox_starting_count=sandbox_starting_count,status=status,version=version,- cluster_id=cluster_id,)node.additional_properties = ddiff --git a/packages/python-sdk/e2b/api/client/models/node_detail.py b/packages/python-sdk/e2b/api/client/models/node_detail.pyindex ea60fd31b..36b7a6a62 100644--- a/packages/python-sdk/e2b/api/client/models/node_detail.py+++ b/packages/python-sdk/e2b/api/client/models/node_detail.py@@ -1,14 +1,14 @@from collections.abc import Mapping-from typing import TYPE_CHECKING, Any, TypeVar, Union, cast+from typing import TYPE_CHECKING, Any, TypeVar, castfrom attrs import define as _attrs_definefrom attrs import field as _attrs_fieldfrom ..models.node_status import NodeStatus-from ..types import UNSET, Unsetif TYPE_CHECKING:from ..models.listed_sandbox import ListedSandbox+ from ..models.node_metrics import NodeMetricsT = TypeVar("T", bound="NodeDetail")@@ -19,36 +19,42 @@ class NodeDetail:"""Attributes:cached_builds (list[str]): List of cached builds id on the node+ cluster_id (str): Identifier of the clustercommit (str): Commit of the orchestratorcreate_fails (int): Number of sandbox create failscreate_successes (int): Number of sandbox create successes+ metrics (NodeMetrics): Node metricsnode_id (str): Identifier of the nodesandboxes (list['ListedSandbox']): List of sandboxes running on the nodestatus (NodeStatus): Status of the nodeversion (str): Version of the orchestrator- cluster_id (Union[None, Unset, str]): Identifier of the cluster"""cached_builds: list[str]+ cluster_id: strcommit: strcreate_fails: intcreate_successes: int+ metrics: "NodeMetrics"node_id: strsandboxes: list["ListedSandbox"]status: NodeStatusversion: str- cluster_id: Union[None, Unset, str] = UNSETadditional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)def to_dict(self) -> dict[str, Any]:cached_builds = self.cached_builds+ cluster_id = self.cluster_id+commit = self.commitcreate_fails = self.create_failscreate_successes = self.create_successes+ metrics = self.metrics.to_dict()+node_id = self.node_idsandboxes = []@@ -60,44 +66,43 @@ class NodeDetail:version = self.version- cluster_id: Union[None, Unset, str]- if isinstance(self.cluster_id, Unset):- cluster_id = UNSET- else:- cluster_id = self.cluster_id-field_dict: dict[str, Any] = {}field_dict.update(self.additional_properties)field_dict.update({"cachedBuilds": cached_builds,+ "clusterID": cluster_id,"commit": commit,"createFails": create_fails,"createSuccesses": create_successes,+ "metrics": metrics,"nodeID": node_id,"sandboxes": sandboxes,"status": status,"version": version,})- if cluster_id is not UNSET:- field_dict["clusterID"] = cluster_idreturn field_dict@classmethoddef from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:from ..models.listed_sandbox import ListedSandbox+ from ..models.node_metrics import NodeMetricsd = dict(src_dict)cached_builds = cast(list[str], d.pop("cachedBuilds"))+ cluster_id = d.pop("clusterID")+commit = d.pop("commit")create_fails = d.pop("createFails")create_successes = d.pop("createSuccesses")+ metrics = NodeMetrics.from_dict(d.pop("metrics"))+node_id = d.pop("nodeID")sandboxes = []@@ -111,25 +116,17 @@ class NodeDetail:version = d.pop("version")- def _parse_cluster_id(data: object) -> Union[None, Unset, str]:- if data is None:- return data- if isinstance(data, Unset):- return data- return cast(Union[None, Unset, str], data)-- cluster_id = _parse_cluster_id(d.pop("clusterID", UNSET))-node_detail = cls(cached_builds=cached_builds,+ cluster_id=cluster_id,commit=commit,create_fails=create_fails,create_successes=create_successes,+ metrics=metrics,node_id=node_id,sandboxes=sandboxes,status=status,version=version,- cluster_id=cluster_id,)node_detail.additional_properties = ddiff --git a/packages/python-sdk/e2b/api/client/models/node_metrics.py b/packages/python-sdk/e2b/api/client/models/node_metrics.pynew file mode 100644index 000000000..129d74fc4--- /dev/null+++ b/packages/python-sdk/e2b/api/client/models/node_metrics.py@@ -0,0 +1,122 @@+from collections.abc import Mapping+from typing import TYPE_CHECKING, Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field++if TYPE_CHECKING:+ from ..models.disk_metrics import DiskMetrics+++T = TypeVar("T", bound="NodeMetrics")+++@_attrs_define+class NodeMetrics:+ """Node metrics++ Attributes:+ allocated_cpu (int): Number of allocated CPU cores+ allocated_memory_bytes (int): Amount of allocated memory in bytes+ cpu_count (int): Total number of CPU cores on the node+ cpu_percent (int): Node CPU usage percentage+ disks (list['DiskMetrics']): Detailed metrics for each disk/mount point+ memory_total_bytes (int): Total node memory in bytes+ memory_used_bytes (int): Node memory used in bytes+ """++ allocated_cpu: int+ allocated_memory_bytes: int+ cpu_count: int+ cpu_percent: int+ disks: list["DiskMetrics"]+ memory_total_bytes: int+ memory_used_bytes: int+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ allocated_cpu = self.allocated_cpu++ allocated_memory_bytes = self.allocated_memory_bytes++ cpu_count = self.cpu_count++ cpu_percent = self.cpu_percent++ disks = []+ for disks_item_data in self.disks:+ disks_item = disks_item_data.to_dict()+ disks.append(disks_item)++ memory_total_bytes = self.memory_total_bytes++ memory_used_bytes = self.memory_used_bytes++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "allocatedCPU": allocated_cpu,+ "allocatedMemoryBytes": allocated_memory_bytes,+ "cpuCount": cpu_count,+ "cpuPercent": cpu_percent,+ "disks": disks,+ "memoryTotalBytes": memory_total_bytes,+ "memoryUsedBytes": memory_used_bytes,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ from ..models.disk_metrics import DiskMetrics++ d = dict(src_dict)+ allocated_cpu = d.pop("allocatedCPU")++ allocated_memory_bytes = d.pop("allocatedMemoryBytes")++ cpu_count = d.pop("cpuCount")++ cpu_percent = d.pop("cpuPercent")++ disks = []+ _disks = d.pop("disks")+ for disks_item_data in _disks:+ disks_item = DiskMetrics.from_dict(disks_item_data)++ disks.append(disks_item)++ memory_total_bytes = d.pop("memoryTotalBytes")++ memory_used_bytes = d.pop("memoryUsedBytes")++ node_metrics = cls(+ allocated_cpu=allocated_cpu,+ allocated_memory_bytes=allocated_memory_bytes,+ cpu_count=cpu_count,+ cpu_percent=cpu_percent,+ disks=disks,+ memory_total_bytes=memory_total_bytes,+ memory_used_bytes=memory_used_bytes,+ )++ node_metrics.additional_properties = d+ return node_metrics++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/packages/python-sdk/e2b/api/client/models/team_metric.py b/packages/python-sdk/e2b/api/client/models/team_metric.pynew file mode 100644index 000000000..bba00ff72--- /dev/null+++ b/packages/python-sdk/e2b/api/client/models/team_metric.py@@ -0,0 +1,78 @@+import datetime+from collections.abc import Mapping+from typing import Any, TypeVar++from attrs import define as _attrs_define+from attrs import field as _attrs_field+from dateutil.parser import isoparse++T = TypeVar("T", bound="TeamMetric")+++@_attrs_define+class TeamMetric:+ """Team metric with timestamp++ Attributes:+ concurrent_sandboxes (int): The number of concurrent sandboxes for the team+ sandbox_start_rate (float): Number of sandboxes started per second+ timestamp (datetime.datetime): Timestamp of the metric entry+ """++ concurrent_sandboxes: int+ sandbox_start_rate: float+ timestamp: datetime.datetime+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)++ def to_dict(self) -> dict[str, Any]:+ concurrent_sandboxes = self.concurrent_sandboxes++ sandbox_start_rate = self.sandbox_start_rate++ timestamp = self.timestamp.isoformat()++ field_dict: dict[str, Any] = {}+ field_dict.update(self.additional_properties)+ field_dict.update(+ {+ "concurrentSandboxes": concurrent_sandboxes,+ "sandboxStartRate": sandbox_start_rate,+ "timestamp": timestamp,+ }+ )++ return field_dict++ @classmethod+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:+ d = dict(src_dict)+ concurrent_sandboxes = d.pop("concurrentSandboxes")++ sandbox_start_rate = d.pop("sandboxStartRate")++ timestamp = isoparse(d.pop("timestamp"))++ team_metric = cls(+ concurrent_sandboxes=concurrent_sandboxes,+ sandbox_start_rate=sandbox_start_rate,+ timestamp=timestamp,+ )++ team_metric.additional_properties = d+ return team_metric++ @property+ def additional_keys(self) -> list[str]:+ return list(self.additional_properties.keys())++ def __getitem__(self, key: str) -> Any:+ return self.additional_properties[key]++ def __setitem__(self, key: str, value: Any) -> None:+ self.additional_properties[key] = value++ def __delitem__(self, key: str) -> None:+ del self.additional_properties[key]++ def __contains__(self, key: str) -> bool:+ return key in self.additional_propertiesdiff --git a/packages/python-sdk/e2b/api/client/models/template_build.py b/packages/python-sdk/e2b/api/client/models/template_build.pyindex a6247eccf..7c49554e1 100644--- a/packages/python-sdk/e2b/api/client/models/template_build.py+++ b/packages/python-sdk/e2b/api/client/models/template_build.py@@ -9,6 +9,7 @@ from ..types import UNSET, Unsetif TYPE_CHECKING:from ..models.build_log_entry import BuildLogEntry+ from ..models.build_status_reason import BuildStatusReasonT = TypeVar("T", bound="TemplateBuild")@@ -23,7 +24,7 @@ class TemplateBuild:logs (list[str]): Build logsstatus (TemplateBuildStatus): Status of the templatetemplate_id (str): Identifier of the template- reason (Union[Unset, str]): Message with the status reason, currently reporting only for error status+ reason (Union[Unset, BuildStatusReason]):"""build_id: str@@ -31,7 +32,7 @@ class TemplateBuild:logs: list[str]status: TemplateBuildStatustemplate_id: str- reason: Union[Unset, str] = UNSET+ reason: Union[Unset, "BuildStatusReason"] = UNSETadditional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)def to_dict(self) -> dict[str, Any]:@@ -48,7 +49,9 @@ class TemplateBuild:template_id = self.template_id- reason = self.reason+ reason: Union[Unset, dict[str, Any]] = UNSET+ if not isinstance(self.reason, Unset):+ reason = self.reason.to_dict()field_dict: dict[str, Any] = {}field_dict.update(self.additional_properties)@@ -69,6 +72,7 @@ class TemplateBuild:@classmethoddef from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:from ..models.build_log_entry import BuildLogEntry+ from ..models.build_status_reason import BuildStatusReasond = dict(src_dict)build_id = d.pop("buildID")@@ -86,7 +90,12 @@ class TemplateBuild:template_id = d.pop("templateID")- reason = d.pop("reason", UNSET)+ _reason = d.pop("reason", UNSET)+ reason: Union[Unset, BuildStatusReason]+ if isinstance(_reason, Unset):+ reason = UNSET+ else:+ reason = BuildStatusReason.from_dict(_reason)template_build = cls(build_id=build_id,diff --git a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.pyindex a144c8e2a..ff6c23574 100644--- a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py+++ b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py@@ -1,7 +1,7 @@from dataclasses import dataclassfrom datetime import datetimefrom enum import Enum-from typing import IO, Optional, Union+from typing import IO, Optional, Union, TypedDictfrom e2b.envd.filesystem import filesystem_pb2@@ -85,8 +85,7 @@ class EntryInfo(WriteInfo):"""-@dataclass-class WriteEntry:+class WriteEntry(TypedDict):"""Contains path and data of the file to be written to the filesystem."""diff --git a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.pyindex 43f7bb182..7399d2ff2 100644--- a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py+++ b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py@@ -138,7 +138,6 @@ class Filesystem:elif format == "stream":return r.aiter_bytes()- @overloadasync def write(self,path: str,@@ -148,11 +147,8 @@ class Filesystem:) -> WriteInfo:"""Write content to a file on the path.-Writing to a file that doesn't exist creates the file.-Writing to a file that already exists overwrites the file.-Writing to a file at path that doesn't exist creates the necessary directories.:param path: Path to the file@@ -162,77 +158,55 @@ class Filesystem::return: Information about the written file"""+ result = await self.write_files(+ [WriteEntry(path=path, data=data)], user, request_timeout+ )- @overload- async def write(+ if len(result) != 1:+ raise SandboxException("Received unexpected response from write operation")++ return result[0]++ async def write_files(self,files: List[WriteEntry],- user: Optional[Username] = "user",+ user: Username = "user",request_timeout: Optional[float] = None,) -> List[WriteInfo]:"""Writes multiple files.- :param files: list of files to write- :param user: Run the operation as this user- :param request_timeout: Timeout for the request- :return: Information about the written files- """-- async def write(- self,- path_or_files: Union[str, List[WriteEntry]],- data_or_user: Union[str, bytes, IO, Username] = "user",- user_or_request_timeout: Optional[Union[float, Username]] = None,- request_timeout_or_none: Optional[float] = None,- ) -> Union[WriteInfo, List[WriteInfo]]:- """- Writes content to a file on the path.+ Writes a list of files to the filesystem.When writing to a file that doesn't exist, the file will get created.When writing to a file that already exists, the file will get overwritten.When writing to a file that's in a directory that doesn't exist, you'll get an error.++ :param files: list of files to write as `WriteEntry` objects, each containing `path` and `data`+ :param user: Run the operation as this user+ :param request_timeout: Timeout for the request+ :return: Information about the written files"""- path, write_files, user, request_timeout = None, [], "user", None- if isinstance(path_or_files, str):- if isinstance(data_or_user, list):- raise Exception(- "Cannot specify both path and array of files. You have to specify either path and data for a single file or an array for multiple files."- )- path, write_files, user, request_timeout = (- path_or_files,- [{"path": path_or_files, "data": data_or_user}],- user_or_request_timeout or "user",- request_timeout_or_none,- )- else:- if path_or_files is None:- raise Exception("Path or files are required")- path, write_files, user, request_timeout = (- None,- path_or_files,- data_or_user,- user_or_request_timeout,- )+ params = {"username": user}+ if len(files) == 1:+ params["path"] = files[0]["path"]# Prepare the files for the multipart/form-data requesthttpx_files = []- for file in write_files:+ for file in files:file_path, file_data = file["path"], file["data"]if isinstance(file_data, str) or isinstance(file_data, bytes):httpx_files.append(("file", (file_path, file_data)))elif isinstance(file_data, IOBase):httpx_files.append(("file", (file_path, file_data.read())))else:- raise ValueError(f"Unsupported data type for file {file_path}")+ raise InvalidArgumentException(+ f"Unsupported data type for file {file_path}"+ )# Allow passing empty list of filesif len(httpx_files) == 0:return []- params = {"username": user}- if path is not None:- params["path"] = path-r = await self._envd_api.post(ENVD_API_FILES_ROUTE,files=httpx_files,@@ -247,13 +221,9 @@ class Filesystem:write_files = r.json()if not isinstance(write_files, list) or len(write_files) == 0:- raise Exception("Expected to receive information about written file")+ raise SandboxException("Expected to receive information about written file")- if len(write_files) == 1 and path:- file = write_files[0]- return WriteInfo(**file)- else:- return [WriteInfo(**file) for file in write_files]+ return [WriteInfo(**file) for file in write_files]async def list(self,diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.pyindex 8bae8e2cb..e7893f342 100644--- a/packages/python-sdk/e2b/sandbox_async/main.py+++ b/packages/python-sdk/e2b/sandbox_async/main.py@@ -157,7 +157,7 @@ class AsyncSandbox(SandboxApi):timeout: Optional[int] = None,metadata: Optional[Dict[str, str]] = None,envs: Optional[Dict[str, str]] = None,- secure: Optional[bool] = None,+ secure: Optional[bool] = True,allow_internet_access: bool = True,**opts: Unpack[ApiParams],) -> Self:@@ -170,7 +170,7 @@ class AsyncSandbox(SandboxApi)::param timeout: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.:param metadata: Custom metadata for the sandbox:param envs: Custom environment variables for the sandbox- :param secure: Envd is secured with access token and cannot be used without it+ :param secure: Envd is secured with access token and cannot be used without it, defaults to `True`.:param allow_internet_access: Allow sandbox to access the internet, defaults to `True`.:return: A Sandbox instance for the new sandbox@@ -184,6 +184,7 @@ class AsyncSandbox(SandboxApi):envs=envs,secure=secure,allow_internet_access=allow_internet_access,+ auto_pause=False,**opts,)@@ -498,7 +499,7 @@ class AsyncSandbox(SandboxApi):auto_pause: bool = False,metadata: Optional[Dict[str, str]] = None,envs: Optional[Dict[str, str]] = None,- secure: Optional[bool] = None,+ secure: bool = True,allow_internet_access: bool = True,**opts: Unpack[ApiParams],) -> Self:@@ -514,7 +515,7 @@ class AsyncSandbox(SandboxApi)::param auto_pause: Automatically pause the sandbox after the timeout expires. Defaults to `False`.:param metadata: Custom metadata for the sandbox:param envs: Custom environment variables for the sandbox- :param secure: Envd is secured with access token and cannot be used without it+ :param secure: Envd is secured with access token and cannot be used without it, defaults to `True`.:param allow_internet_access: Allow sandbox to access the internet, defaults to `True`.:return: A Sandbox instance for the new sandbox@@ -618,13 +619,13 @@ class AsyncSandbox(SandboxApi):@classmethodasync def _create(cls,- template: Optional[str] = None,- timeout: Optional[int] = None,- auto_pause: bool = False,- allow_internet_access: bool = True,- metadata: Optional[Dict[str, str]] = None,- envs: Optional[Dict[str, str]] = None,- secure: Optional[bool] = None,+ template: Optional[str],+ timeout: Optional[int],+ auto_pause: bool,+ allow_internet_access: bool,+ metadata: Optional[Dict[str, str]],+ envs: Optional[Dict[str, str]],+ secure: bool,**opts: Unpack[ApiParams],) -> Self:extra_sandbox_headers = {}diff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.pyindex f11f2642f..8b40fd476 100644--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py@@ -149,9 +149,9 @@ class SandboxApi(SandboxBase):timeout: int,auto_pause: bool,allow_internet_access: bool,- metadata: Optional[Dict[str, str]] = None,- env_vars: Optional[Dict[str, str]] = None,- secure: Optional[bool] = None,+ metadata: Optional[Dict[str, str]],+ env_vars: Optional[Dict[str, str]],+ secure: bool,**opts: Unpack[ApiParams],) -> SandboxCreateResponse:config = ConnectionConfig(**opts)@@ -167,7 +167,7 @@ class SandboxApi(SandboxBase):metadata=metadata or {},timeout=timeout,env_vars=env_vars or {},- secure=secure or False,+ secure=secure,allow_internet_access=allow_internet_access,),client=api_client,diff --git a/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.pyindex 1add5b16f..4a9573548 100644--- a/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py+++ b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py@@ -1,5 +1,6 @@from io import IOBasefrom typing import IO, Iterator, List, Literal, Optional, overload, Union+from e2b.sandbox.filesystem.filesystem import WriteEntryimport e2b_connect@@ -8,7 +9,7 @@ import httpxfrom packaging.version import Versionfrom e2b.envd.versions import ENVD_VERSION_RECURSIVE_WATCH-from e2b.exceptions import TemplateException, InvalidArgumentException+from e2b.exceptions import SandboxException, TemplateException, InvalidArgumentExceptionfrom e2b.connection_config import (ConnectionConfig,Username,@@ -138,7 +139,6 @@ class Filesystem:elif format == "stream":return r.iter_bytes()- @overloaddef write(self,path: str,@@ -148,11 +148,8 @@ class Filesystem:) -> WriteInfo:"""Write content to a file on the path.-Writing to a file that doesn't exist creates the file.-Writing to a file that already exists overwrites the file.-Writing to a file at path that doesn't exist creates the necessary directories.:param path: Path to the file@@ -162,12 +159,21 @@ class Filesystem::return: Information about the written file"""+ result = self.write_files(+ [WriteEntry(path=path, data=data)],+ user=user,+ request_timeout=request_timeout,+ )- @overload- def write(+ if len(result) != 1:+ raise SandboxException("Received unexpected response from write operation")++ return result[0]++ def write_files(self,files: List[WriteEntry],- user: Optional[Username] = "user",+ user: Username = "user",request_timeout: Optional[float] = None,) -> List[WriteInfo]:"""@@ -176,60 +182,32 @@ class Filesystem:When writing to a file that already exists, the file will get overwritten.When writing to a file that's in a directory that doesn't exist, you'll get an error.- :param files: list of files to write+ :param files: list of files to write as `WriteEntry` objects, each containing `path` and `data`:param user: Run the operation as this user:param request_timeout: Timeout for the request:return: Information about the written files"""-- def write(- self,- path_or_files: Union[str, List[WriteEntry]],- data_or_user: Union[str, bytes, IO, Username] = "user",- user_or_request_timeout: Optional[Union[float, Username]] = None,- request_timeout_or_none: Optional[float] = None,- ) -> Union[WriteInfo, List[WriteInfo]]:- path, write_files, user, request_timeout = None, [], "user", None- if isinstance(path_or_files, str):- if isinstance(data_or_user, list):- raise Exception(- "Cannot specify both path and array of files. You have to specify either path and data for a single file or an array for multiple files."- )- path, write_files, user, request_timeout = (- path_or_files,- [{"path": path_or_files, "data": data_or_user}],- user_or_request_timeout or "user",- request_timeout_or_none,- )- else:- if path_or_files is None:- raise Exception("Path or files are required")- path, write_files, user, request_timeout = (- None,- path_or_files,- data_or_user,- user_or_request_timeout,- )+ params = {"username": user}+ if len(files) == 1:+ params["path"] = files[0]["path"]# Prepare the files for the multipart/form-data requesthttpx_files = []- for file in write_files:+ for file in files:file_path, file_data = file["path"], file["data"]if isinstance(file_data, str) or isinstance(file_data, bytes):httpx_files.append(("file", (file_path, file_data)))elif isinstance(file_data, IOBase):httpx_files.append(("file", (file_path, file_data.read())))else:- raise ValueError(f"Unsupported data type for file {file_path}")+ raise InvalidArgumentException(+ f"Unsupported data type for file {file_path}"+ )# Allow passing empty list of filesif len(httpx_files) == 0:return []- params = {"username": user}- if path is not None:- params["path"] = path-r = self._envd_api.post(ENVD_API_FILES_ROUTE,files=httpx_files,@@ -244,13 +222,9 @@ class Filesystem:write_files = r.json()if not isinstance(write_files, list) or len(write_files) == 0:- raise Exception("Expected to receive information about written file")+ raise SandboxException("Expected to receive information about written file")- if len(write_files) == 1 and path:- file = write_files[0]- return WriteInfo(**file)- else:- return [WriteInfo(**file) for file in write_files]+ return [WriteInfo(**file) for file in write_files]def list(self,diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.pyindex 4b3bb2b3e..90bbd1bac 100644--- a/packages/python-sdk/e2b/sandbox_sync/main.py+++ b/packages/python-sdk/e2b/sandbox_sync/main.py@@ -160,7 +160,7 @@ class Sandbox(SandboxApi):timeout: Optional[int] = None,metadata: Optional[Dict[str, str]] = None,envs: Optional[Dict[str, str]] = None,- secure: Optional[bool] = None,+ secure: bool = True,allow_internet_access: bool = True,**opts: Unpack[ApiParams],) -> Self:@@ -173,7 +173,7 @@ class Sandbox(SandboxApi)::param timeout: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.:param metadata: Custom metadata for the sandbox:param envs: Custom environment variables for the sandbox- :param secure: Envd is secured with access token and cannot be used without it+ :param secure: Envd is secured with access token and cannot be used without it, defaults to `True`.:param allow_internet_access: Allow sandbox to access the internet, defaults to `True`.:return: A Sandbox instance for the new sandbox@@ -187,6 +187,7 @@ class Sandbox(SandboxApi):envs=envs,secure=secure,allow_internet_access=allow_internet_access,+ auto_pause=False,**opts,)@@ -504,10 +505,10 @@ class Sandbox(SandboxApi):auto_pause: bool = False,metadata: Optional[Dict[str, str]] = None,envs: Optional[Dict[str, str]] = None,- secure: Optional[bool] = None,+ secure: bool = True,allow_internet_access: bool = True,**opts: Unpack[ApiParams],- ):+ ) -> Self:"""[BETA] This feature is in beta and may change in the future.@@ -520,7 +521,7 @@ class Sandbox(SandboxApi)::param auto_pause: Automatically pause the sandbox after the timeout expires. Defaults to `False`.:param metadata: Custom metadata for the sandbox:param envs: Custom environment variables for the sandbox- :param secure: Envd is secured with access token and cannot be used without it+ :param secure: Envd is secured with access token and cannot be used without it, defaults to `True`.:param allow_internet_access: Allow sandbox to access the internet, defaults to `True`.:return: A Sandbox instance for the new sandbox@@ -616,13 +617,13 @@ class Sandbox(SandboxApi):@classmethoddef _create(cls,- template: Optional[str] = None,- timeout: Optional[int] = None,- auto_pause: bool = False,- metadata: Optional[Dict[str, str]] = None,- envs: Optional[Dict[str, str]] = None,- secure: Optional[bool] = None,- allow_internet_access: bool = True,+ template: Optional[str],+ timeout: Optional[int],+ auto_pause: bool,+ metadata: Optional[Dict[str, str]],+ envs: Optional[Dict[str, str]],+ secure: bool,+ allow_internet_access: bool,**opts: Unpack[ApiParams],) -> Self:extra_sandbox_headers = {}diff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.pyindex f2a264cc6..c7b643f1f 100644--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py@@ -148,9 +148,9 @@ class SandboxApi(SandboxBase):timeout: int,auto_pause: bool,allow_internet_access: bool,- metadata: Optional[Dict[str, str]] = None,- env_vars: Optional[Dict[str, str]] = None,- secure: Optional[bool] = None,+ metadata: Optional[Dict[str, str]],+ env_vars: Optional[Dict[str, str]],+ secure: bool,**opts: Unpack[ApiParams],) -> SandboxCreateResponse:config = ConnectionConfig(**opts)@@ -163,7 +163,7 @@ class SandboxApi(SandboxBase):metadata=metadata or {},timeout=timeout,env_vars=env_vars or {},- secure=secure or False,+ secure=secure,allow_internet_access=allow_internet_access,),client=api_client,diff --git a/packages/python-sdk/example.py b/packages/python-sdk/example.pyindex 1da1ffda3..6f8daa6bf 100644--- a/packages/python-sdk/example.py+++ b/packages/python-sdk/example.py@@ -10,7 +10,7 @@ logging.basicConfig(level=logging.ERROR)async def main():- sbx = await AsyncSandbox.create(timeout=10, debug=True)+ sbx = await AsyncSandbox.create(timeout=10)await sbx.set_timeout(20)diff --git a/packages/python-sdk/tests/async/sandbox_async/files/test_write.py b/packages/python-sdk/tests/async/sandbox_async/files/test_write.pyindex bf7b57da9..24fe73c62 100644--- a/packages/python-sdk/tests/async/sandbox_async/files/test_write.py+++ b/packages/python-sdk/tests/async/sandbox_async/files/test_write.py@@ -2,6 +2,7 @@ import ioimport uuidfrom e2b import AsyncSandbox+from e2b.sandbox.filesystem.filesystem import WriteEntryfrom e2b.sandbox_async.filesystem.filesystem import WriteInfo@@ -9,12 +10,6 @@ async def test_write_text_file(async_sandbox: AsyncSandbox):filename = "test_write.txt"content = "This is a test file."- # Attempt to write without path- try:- await async_sandbox.files.write(None, content)- except Exception as e:- assert "Path or files are required" in str(e)-info = await async_sandbox.files.write(filename, content)assert info.path == f"/home/user/{filename}"@@ -43,31 +38,13 @@ async def test_write_binary_file(async_sandbox: AsyncSandbox):async def test_write_multiple_files(async_sandbox: AsyncSandbox):# Attempt to write with empty files array- empty_info = await async_sandbox.files.write([])+ empty_info = await async_sandbox.files.write_files([])assert isinstance(empty_info, list)assert len(empty_info) == 0- # Attempt to write with None path and empty files array- try:- await async_sandbox.files.write(None, [])- except Exception as e:- assert "Path or files are required" in str(e)-- # Attempt to write with path and file array- try:- await async_sandbox.files.write(- "/path/to/file",- [{"path": "one_test_file.txt", "data": "This is a test file."}],- )- except Exception as e:- assert (- "Cannot specify both path and array of files. You have to specify either path and data for a single file or an array for multiple files."- in str(e)- )-# Attempt to write with one file in array- info = await async_sandbox.files.write(- [{"path": "one_test_file.txt", "data": "This is a test file."}]+ info = await async_sandbox.files.write_files(+ [WriteEntry(path="one_test_file.txt", data="This is a test file.")])assert isinstance(info, list)assert len(info) == 1@@ -85,9 +62,9 @@ async def test_write_multiple_files(async_sandbox: AsyncSandbox):for i in range(10):path = f"test_write_{i}.txt"content = f"This is a test file {i}."- files.append({"path": path, "data": content})+ files.append(WriteEntry(path=path, data=content))- infos = await async_sandbox.files.write(files)+ infos = await async_sandbox.files.write_files(files)assert isinstance(infos, list)assert len(infos) == len(files)for i, info in enumerate(infos):diff --git a/packages/python-sdk/tests/sync/sandbox_sync/files/test_write.py b/packages/python-sdk/tests/sync/sandbox_sync/files/test_write.pyindex 8db95c868..c6018abaf 100644--- a/packages/python-sdk/tests/sync/sandbox_sync/files/test_write.py+++ b/packages/python-sdk/tests/sync/sandbox_sync/files/test_write.py@@ -1,7 +1,7 @@import ioimport uuid-from e2b.sandbox.filesystem.filesystem import WriteInfo+from e2b.sandbox.filesystem.filesystem import WriteInfo, WriteEntryfrom e2b.sandbox_sync.main import Sandbox@@ -9,12 +9,6 @@ def test_write_text_file(sandbox):filename = "test_write.txt"content = "This is a test file."- # Attempt to write without path- try:- sandbox.files.write(None, content)- except Exception as e:- assert "Path or files are required" in str(e)-info = sandbox.files.write(filename, content)assert info.path == f"/home/user/{filename}"@@ -43,31 +37,16 @@ def test_write_binary_file(sandbox):def test_write_multiple_files(sandbox):# Attempt to write with empty files array- empty_info = sandbox.files.write([])+ empty_info = sandbox.files.write_files([])assert isinstance(empty_info, list)assert len(empty_info) == 0- # Attempt to write with None path and empty files array- try:- sandbox.files.write(None, [])- except Exception as e:- assert "Path or files are required" in str(e)-- # Attempt to write with path and file array- try:- sandbox.files.write(- "/path/to/file",- [{"path": "one_test_file.txt", "data": "This is a test file."}],- )- except Exception as e:- assert (- "Cannot specify both path and array of files. You have to specify either path and data for a single file or an array for multiple files."- in str(e)- )+ # Attempt to write with no files+ assert sandbox.files.write_files([]) == []# Attempt to write with one file in array- info = sandbox.files.write(- [{"path": "one_test_file.txt", "data": "This is a test file."}]+ info = sandbox.files.write_files(+ [WriteEntry(path="one_test_file.txt", data="This is a test file.")])assert isinstance(info, list)assert len(info) == 1@@ -85,9 +64,9 @@ def test_write_multiple_files(sandbox):for i in range(10):path = f"test_write_{i}.txt"content = f"This is a test file {i}."- files.append({"path": path, "data": content})+ files.append(WriteEntry(path=path, data=content))- infos = sandbox.files.write(files)+ infos = sandbox.files.write_files(files)assert isinstance(infos, list)assert len(infos) == len(files)for i, info in enumerate(infos):diff --git a/spec/openapi.yml b/spec/openapi.ymlindex 7fbb09ece..e8b0d72d7 100644--- a/spec/openapi.yml+++ b/spec/openapi.yml@@ -51,6 +51,12 @@ components:required: trueschema:type: string+ teamID:+ name: teamID+ in: path+ required: true+ schema:+ type: stringnodeID:name: nodeIDin: path@@ -83,6 +89,12 @@ components:application/json:schema:$ref: "#/components/schemas/Error"+ "403":+ description: Forbidden+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/Error""404":description: Not foundcontent:@@ -449,9 +461,30 @@ components:description: Time to live for the sandbox in seconds.autoPause:type: boolean+ deprecated: truedefault: falsedescription: Automatically pauses the sandbox after the timeout+ TeamMetric:+ description: Team metric with timestamp+ required:+ - timestamp+ - concurrentSandboxes+ - sandboxStartRate+ properties:+ timestamp:+ type: string+ format: date-time+ description: Timestamp of the metric entry+ concurrentSandboxes:+ type: integer+ format: int32+ description: The number of concurrent sandboxes for the team+ sandboxStartRate:+ type: number+ format: float+ description: Number of sandboxes started per second+Template:required:- templateID@@ -638,6 +671,17 @@ components:level:$ref: "#/components/schemas/LogLevel"+ BuildStatusReason:+ required:+ - message+ properties:+ message:+ type: string+ description: Message with the status reason, currently reporting only for error status+ step:+ type: string+ description: Step that failed+TemplateBuild:required:- templateID@@ -673,8 +717,7 @@ components:- ready- errorreason:- type: string- description: Message with the status reason, currently reporting only for error status+ $ref: "#/components/schemas/BuildStatusReason"NodeStatus:type: string@@ -697,13 +740,80 @@ components:status:$ref: "#/components/schemas/NodeStatus"+ DiskMetrics:+ required:+ - mountPoint+ - device+ - filesystemType+ - usedBytes+ - totalBytes+ properties:+ mountPoint:+ type: string+ description: Mount point of the disk+ device:+ type: string+ description: Device name+ filesystemType:+ type: string+ description: Filesystem type (e.g., ext4, xfs)+ usedBytes:+ type: integer+ format: uint64+ description: Used space in bytes+ totalBytes:+ type: integer+ format: uint64+ description: Total space in bytes++ NodeMetrics:+ description: Node metrics+ required:+ - allocatedCPU+ - allocatedMemoryBytes+ - cpuPercent+ - memoryUsedBytes+ - cpuCount+ - memoryTotalBytes+ - disks+ properties:+ allocatedCPU:+ type: integer+ format: uint32+ description: Number of allocated CPU cores+ cpuPercent:+ type: integer+ format: uint32+ description: Node CPU usage percentage+ cpuCount:+ type: integer+ format: uint32+ description: Total number of CPU cores on the node+ allocatedMemoryBytes:+ type: integer+ format: uint64+ description: Amount of allocated memory in bytes+ memoryUsedBytes:+ type: integer+ format: uint64+ description: Node memory used in bytes+ memoryTotalBytes:+ type: integer+ format: uint64+ description: Total node memory in bytes+ disks:+ type: array+ description: Detailed metrics for each disk/mount point+ items:+ $ref: "#/components/schemas/DiskMetrics"+Node:required:- nodeID+ - clusterID- status- sandboxCount- - allocatedCPU- - allocatedMemoryMiB+ - metrics- createSuccesses- createFails- sandboxStartingCount@@ -721,22 +831,15 @@ components:description: Identifier of the nodeclusterID:type: string- nullable: truedescription: Identifier of the clusterstatus:$ref: "#/components/schemas/NodeStatus"sandboxCount:type: integer- format: int32+ format: uint32description: Number of sandboxes running on the node- allocatedCPU:- type: integer- format: int32- description: Number of allocated CPU cores- allocatedMemoryMiB:- type: integer- format: int32- description: Amount of allocated memory in MiB+ metrics:+ $ref: "#/components/schemas/NodeMetrics"createSuccesses:type: integerformat: uint64@@ -753,6 +856,7 @@ components:NodeDetail:required:- nodeID+ - clusterID- status- sandboxes- cachedBuilds@@ -760,10 +864,10 @@ components:- createFails- version- commit+ - metricsproperties:clusterID:type: string- nullable: truedescription: Identifier of the clusterversion:type: string@@ -781,6 +885,8 @@ components:description: List of sandboxes running on the nodeitems:$ref: "#/components/schemas/ListedSandbox"+ metrics:+ $ref: "#/components/schemas/NodeMetrics"cachedBuilds:type: arraydescription: List of cached builds id on the node@@ -980,6 +1086,48 @@ paths:"500":$ref: "#/components/responses/500"+ /teams/{teamID}/metrics:+ get:+ description: Get metrics for the team+ tags: [auth]+ security:+ - ApiKeyAuth: []+ - Supabase1TokenAuth: []+ Supabase2TeamAuth: []+ parameters:+ - $ref: "#/components/parameters/teamID"+ - in: query+ name: start+ schema:+ type: integer+ format: int64+ minimum: 0+ description: Unix timestamp for the start of the interval, in seconds, for which the metrics+ - in: query+ name: end+ schema:+ type: integer+ format: int64+ minimum: 0+ description: Unix timestamp for the end of the interval, in seconds, for which the metrics+ responses:+ "200":+ description: Successfully returned the team metrics+ content:+ application/json:+ schema:+ type: array+ items:+ $ref: "#/components/schemas/TeamMetric"+ "400":+ $ref: "#/components/responses/400"+ "401":+ $ref: "#/components/responses/401"+ "403":+ $ref: "#/components/responses/403"+ "500":+ $ref: "#/components/responses/500"+/sandboxes:get:description: List all running sandboxes@@ -1077,8 +1225,7 @@ paths:type: integerformat: int32minimum: 1- default: 1000- maximum: 1000+ default: 100responses:"200":description: Successfully returned all running sandboxes@@ -1228,14 +1375,14 @@ paths:type: integerformat: int64minimum: 0- description: Starting timestamp of the metrics that should be returned in milliseconds+ description: Unix timestamp for the start of the interval, in seconds, for which the metrics- in: queryname: endschema:type: integerformat: int64minimum: 0- description: Ending timestamp of the metrics that should be returned in milliseconds+ description: Unix timestamp for the end of the interval, in seconds, for which the metricsresponses:"200":@@ -1519,6 +1666,7 @@ paths:description: Delete a templatetags: [templates]security:+ - ApiKeyAuth: []- AccessTokenAuth: []- Supabase1TokenAuth: []parameters: